@codeyam/codeyam-cli 0.1.0-staging.596f0eb → 0.1.0-staging.76566f9

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 (354) 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 +2 -1
  4. package/analyzer-template/packages/ai/src/lib/analyzeScope.ts +2 -0
  5. package/analyzer-template/packages/ai/src/lib/astScopes/astScopeAnalyzer.ts +22 -0
  6. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.ts +23 -1
  7. package/analyzer-template/packages/ai/src/lib/astScopes/processExpression.ts +401 -106
  8. package/analyzer-template/packages/ai/src/lib/astScopes/types.ts +60 -0
  9. package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +734 -45
  10. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.ts +2 -1
  11. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.ts +715 -0
  12. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.ts +233 -75
  13. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.ts +19 -1
  14. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.ts +34 -1
  15. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.ts +23 -0
  16. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.ts +98 -0
  17. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.ts +34 -1
  18. package/analyzer-template/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.ts +236 -24
  19. package/analyzer-template/packages/ai/src/lib/generateChangesEntityKeyAttributes.ts +18 -1
  20. package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarioData.ts +41 -0
  21. package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarios.ts +37 -4
  22. package/analyzer-template/packages/ai/src/lib/generateEntityDataStructure.ts +5 -0
  23. package/analyzer-template/packages/ai/src/lib/generateEntityKeyAttributes.ts +213 -12
  24. package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +36 -25
  25. package/analyzer-template/packages/ai/src/lib/generateEntityScenarios.ts +114 -11
  26. package/analyzer-template/packages/ai/src/lib/getConditionalUsagesFromCode.ts +143 -31
  27. package/analyzer-template/packages/ai/src/lib/guessScenarioDataFromDescription.ts +8 -2
  28. package/analyzer-template/packages/ai/src/lib/promptGenerators/gatherAttributesMap.ts +7 -0
  29. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.ts +42 -2
  30. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.ts +38 -2
  31. package/analyzer-template/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.ts +28 -2
  32. package/analyzer-template/packages/ai/src/lib/worker/SerializableDataStructure.ts +5 -0
  33. package/analyzer-template/packages/ai/src/lib/worker/analyzeScopeWorker.ts +8 -1
  34. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.ts +127 -43
  35. package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.ts +158 -0
  36. package/analyzer-template/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.ts +405 -45
  37. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.ts +1 -1
  38. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +260 -133
  39. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.ts +10 -5
  40. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarioData.ts +77 -83
  41. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarios.ts +2 -5
  42. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +196 -86
  43. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.d.ts +15 -0
  44. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.d.ts.map +1 -0
  45. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.js +31 -0
  46. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.js.map +1 -0
  47. package/analyzer-template/packages/aws/package.json +1 -1
  48. package/analyzer-template/packages/aws/s3/index.ts +1 -0
  49. package/analyzer-template/packages/aws/src/lib/s3/checkS3ObjectExists.ts +47 -0
  50. package/analyzer-template/packages/database/src/lib/kysely/db.ts +4 -4
  51. package/analyzer-template/packages/database/src/lib/kysely/tableRelations.ts +2 -2
  52. package/analyzer-template/packages/database/src/lib/kysely/tables/debugReportsTable.ts +20 -9
  53. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.ts +9 -4
  54. package/analyzer-template/packages/generate/src/lib/deepMerge.ts +26 -1
  55. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts +2 -2
  56. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js +2 -2
  57. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tableRelations.d.ts +2 -2
  58. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts +8 -1
  59. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts.map +1 -1
  60. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts +14 -7
  61. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts.map +1 -1
  62. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.js +9 -3
  63. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.js.map +1 -1
  64. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts +1 -1
  65. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts.map +1 -1
  66. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.d.ts.map +1 -1
  67. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +8 -4
  68. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
  69. package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.d.ts.map +1 -1
  70. package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.js +27 -1
  71. package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.js.map +1 -1
  72. package/analyzer-template/packages/github/dist/types/index.d.ts +4 -3
  73. package/analyzer-template/packages/github/dist/types/index.d.ts.map +1 -1
  74. package/analyzer-template/packages/github/dist/types/index.js +1 -0
  75. package/analyzer-template/packages/github/dist/types/index.js.map +1 -1
  76. package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts +31 -1
  77. package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts.map +1 -1
  78. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts +51 -1
  79. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts.map +1 -1
  80. package/analyzer-template/packages/github/dist/types/src/types/Scenario.js +21 -1
  81. package/analyzer-template/packages/github/dist/types/src/types/Scenario.js.map +1 -1
  82. package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts +48 -0
  83. package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
  84. package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.d.ts.map +1 -1
  85. package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.js +25 -0
  86. package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
  87. package/analyzer-template/packages/types/index.ts +8 -0
  88. package/analyzer-template/packages/types/src/types/Analysis.ts +32 -1
  89. package/analyzer-template/packages/types/src/types/Scenario.ts +75 -6
  90. package/analyzer-template/packages/types/src/types/ScenariosDataStructure.ts +49 -0
  91. package/analyzer-template/packages/ui-components/src/components/ScenarioDetailInteractiveView.tsx +23 -7
  92. package/analyzer-template/packages/utils/dist/types/index.d.ts +4 -3
  93. package/analyzer-template/packages/utils/dist/types/index.d.ts.map +1 -1
  94. package/analyzer-template/packages/utils/dist/types/index.js +1 -0
  95. package/analyzer-template/packages/utils/dist/types/index.js.map +1 -1
  96. package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts +31 -1
  97. package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts.map +1 -1
  98. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts +51 -1
  99. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts.map +1 -1
  100. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.js +21 -1
  101. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.js.map +1 -1
  102. package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts +48 -0
  103. package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
  104. package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.d.ts.map +1 -1
  105. package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.js +25 -0
  106. package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
  107. package/analyzer-template/packages/utils/src/lib/lightweightEntityExtractor.ts +27 -0
  108. package/analyzer-template/playwright/takeElementScreenshot.ts +26 -11
  109. package/analyzer-template/playwright/takeScreenshot.ts +9 -7
  110. package/analyzer-template/project/constructMockCode.ts +286 -84
  111. package/analyzer-template/project/orchestrateCapture/SequentialCaptureTaskRunner.ts +77 -37
  112. package/analyzer-template/project/reconcileMockDataKeys.ts +5 -2
  113. package/analyzer-template/project/runMultiScenarioServer.ts +11 -10
  114. package/analyzer-template/project/serverOnlyModules.ts +71 -23
  115. package/analyzer-template/project/start.ts +10 -0
  116. package/analyzer-template/project/startScenarioCapture.ts +73 -41
  117. package/analyzer-template/project/writeMockDataTsx.ts +115 -54
  118. package/analyzer-template/project/writeScenarioComponents.ts +571 -162
  119. package/analyzer-template/project/writeSimpleRoot.ts +11 -13
  120. package/background/src/lib/virtualized/project/constructMockCode.js +265 -75
  121. package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
  122. package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js +67 -32
  123. package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js.map +1 -1
  124. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js +5 -2
  125. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js.map +1 -1
  126. package/background/src/lib/virtualized/project/runMultiScenarioServer.js +11 -9
  127. package/background/src/lib/virtualized/project/runMultiScenarioServer.js.map +1 -1
  128. package/background/src/lib/virtualized/project/serverOnlyModules.js +62 -25
  129. package/background/src/lib/virtualized/project/serverOnlyModules.js.map +1 -1
  130. package/background/src/lib/virtualized/project/start.js +6 -0
  131. package/background/src/lib/virtualized/project/start.js.map +1 -1
  132. package/background/src/lib/virtualized/project/startScenarioCapture.js +54 -31
  133. package/background/src/lib/virtualized/project/startScenarioCapture.js.map +1 -1
  134. package/background/src/lib/virtualized/project/writeMockDataTsx.js +106 -46
  135. package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
  136. package/background/src/lib/virtualized/project/writeScenarioComponents.js +399 -106
  137. package/background/src/lib/virtualized/project/writeScenarioComponents.js.map +1 -1
  138. package/background/src/lib/virtualized/project/writeSimpleRoot.js +11 -11
  139. package/background/src/lib/virtualized/project/writeSimpleRoot.js.map +1 -1
  140. package/codeyam-cli/src/cli.js +2 -0
  141. package/codeyam-cli/src/cli.js.map +1 -1
  142. package/codeyam-cli/src/commands/debug.js +14 -2
  143. package/codeyam-cli/src/commands/debug.js.map +1 -1
  144. package/codeyam-cli/src/commands/recapture.js +215 -0
  145. package/codeyam-cli/src/commands/recapture.js.map +1 -0
  146. package/codeyam-cli/src/commands/report.js +26 -23
  147. package/codeyam-cli/src/commands/report.js.map +1 -1
  148. package/codeyam-cli/src/utils/backgroundServer.js +2 -2
  149. package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
  150. package/codeyam-cli/src/utils/generateReport.js +252 -106
  151. package/codeyam-cli/src/utils/generateReport.js.map +1 -1
  152. package/codeyam-cli/src/utils/install-skills.js +2 -2
  153. package/codeyam-cli/src/utils/install-skills.js.map +1 -1
  154. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js +38 -0
  155. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js.map +1 -1
  156. package/codeyam-cli/src/utils/queue/job.js +140 -16
  157. package/codeyam-cli/src/utils/queue/job.js.map +1 -1
  158. package/codeyam-cli/src/utils/queue/manager.js +19 -7
  159. package/codeyam-cli/src/utils/queue/manager.js.map +1 -1
  160. package/codeyam-cli/src/utils/queue/persistence.js.map +1 -1
  161. package/codeyam-cli/src/webserver/app/lib/database.js +47 -0
  162. package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
  163. package/codeyam-cli/src/webserver/app/lib/dbNotifier.js.map +1 -1
  164. package/codeyam-cli/src/webserver/backgroundServer.js +5 -10
  165. package/codeyam-cli/src/webserver/backgroundServer.js.map +1 -1
  166. package/codeyam-cli/src/webserver/bootstrap.js +9 -0
  167. package/codeyam-cli/src/webserver/bootstrap.js.map +1 -0
  168. package/codeyam-cli/src/webserver/build/client/assets/EntityItem-wXL1Z2Aq.js +1 -0
  169. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeBadge-efWKDYMr.js → EntityTypeBadge-CzGX-miz.js} +1 -1
  170. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-CXFKsCOD.js +41 -0
  171. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-D-9pXIaY.js +25 -0
  172. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-CBQPrpT0.js +3 -0
  173. package/codeyam-cli/src/webserver/build/client/assets/LoadingDots-D1CdlbrV.js +6 -0
  174. package/codeyam-cli/src/webserver/build/client/assets/LogViewer-wDPcZNKx.js +3 -0
  175. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-4lcOlid-.js +11 -0
  176. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-BfmDgXxG.js +1 -0
  177. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-CUxUNEEC.js +15 -0
  178. package/codeyam-cli/src/webserver/build/client/assets/{TruncatedFilePath-COPstp9J.js → TruncatedFilePath-6J7zDUD5.js} +1 -1
  179. package/codeyam-cli/src/webserver/build/client/assets/_index-DHImXdXq.js +11 -0
  180. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-CVP_WGQ3.js +32 -0
  181. package/codeyam-cli/src/webserver/build/client/assets/api.link-scenario-value-l0sNRNKZ.js +1 -0
  182. package/codeyam-cli/src/webserver/build/client/assets/api.update-key-attributes-l0sNRNKZ.js +1 -0
  183. package/codeyam-cli/src/webserver/build/client/assets/api.update-valid-values-l0sNRNKZ.js +1 -0
  184. package/codeyam-cli/src/webserver/build/client/assets/chevron-down-BYimnrHg.js +6 -0
  185. package/codeyam-cli/src/webserver/build/client/assets/chunk-JMJ3UQ3L-BambyYE_.js +51 -0
  186. package/codeyam-cli/src/webserver/build/client/assets/circle-check-CaVsIRxt.js +6 -0
  187. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-CgUsG7ib.js +21 -0
  188. package/codeyam-cli/src/webserver/build/client/assets/cy-logo-cli-CKnwPCDr.js +1 -0
  189. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-DW_hdGUc.js +1 -0
  190. package/codeyam-cli/src/webserver/build/client/assets/entity._sha._-Dt-SjPsw.js +23 -0
  191. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-DyB90fWk.js +1 -0
  192. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-D_3ero5o.js +1 -0
  193. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-CfLCUi9S.js +5 -0
  194. package/codeyam-cli/src/webserver/build/client/assets/entry.client-DKJyZfAY.js +29 -0
  195. package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-DAtOlaWE.js +1 -0
  196. package/codeyam-cli/src/webserver/build/client/assets/files-ClR0d32A.js +1 -0
  197. package/codeyam-cli/src/webserver/build/client/assets/git-D62Lxxmv.js +15 -0
  198. package/codeyam-cli/src/webserver/build/client/assets/globals-C9s7Lhdl.css +1 -0
  199. package/codeyam-cli/src/webserver/build/client/assets/html2canvas-pro.esm-fmIEn3Bc.js +9 -0
  200. package/codeyam-cli/src/webserver/build/client/assets/index-BosqDOlH.js +3 -0
  201. package/codeyam-cli/src/webserver/build/client/assets/index-CzNNiTkw.js +9 -0
  202. package/codeyam-cli/src/webserver/build/client/assets/keyAttributeCoverage-CTlFMihX.js +1 -0
  203. package/codeyam-cli/src/webserver/build/client/assets/loader-circle-CNp9QFCX.js +6 -0
  204. package/codeyam-cli/src/webserver/build/client/assets/manifest-0d27da29.js +1 -0
  205. package/codeyam-cli/src/webserver/build/client/assets/preload-helper-ckwbz45p.js +1 -0
  206. package/codeyam-cli/src/webserver/build/client/assets/root-B_wIKCIf.js +56 -0
  207. package/codeyam-cli/src/webserver/build/client/assets/scenarioStatus-B_8jpV3e.js +1 -0
  208. package/codeyam-cli/src/webserver/build/client/assets/search-DDGjYAMJ.js +6 -0
  209. package/codeyam-cli/src/webserver/build/client/assets/settings-DgTyB-Wg.js +1 -0
  210. package/codeyam-cli/src/webserver/build/client/assets/simulations-CoNWGt0K.js +1 -0
  211. package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-CBc5dE1s.js +6 -0
  212. package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-BMIGFP-m.js +1 -0
  213. package/codeyam-cli/src/webserver/build/client/assets/useInteractiveMode-Dk_FQqWJ.js +1 -0
  214. package/codeyam-cli/src/webserver/build/client/assets/{useLastLogLine-3pmpUQB-.js → useLastLogLine-BqPPNjAl.js} +1 -1
  215. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-DsJbgMY9.js +1 -0
  216. package/codeyam-cli/src/webserver/build/client/assets/{useToast-DEyawJ8r.js → useToast-DWHcCcl1.js} +1 -1
  217. package/codeyam-cli/src/webserver/build/server/assets/index-CU58-Ttc.js +1 -0
  218. package/codeyam-cli/src/webserver/build/server/assets/server-build-D35o2uae.js +175 -0
  219. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  220. package/codeyam-cli/src/webserver/build-info.json +5 -5
  221. package/codeyam-cli/src/webserver/devServer.js +1 -3
  222. package/codeyam-cli/src/webserver/devServer.js.map +1 -1
  223. package/codeyam-cli/templates/codeyam-setup-skill.md +138 -3
  224. package/codeyam-cli/templates/debug-codeyam.md +625 -0
  225. package/package.json +14 -14
  226. package/packages/ai/src/lib/analyzeScope.js +2 -0
  227. package/packages/ai/src/lib/analyzeScope.js.map +1 -1
  228. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js +16 -0
  229. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js.map +1 -1
  230. package/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.js +16 -0
  231. package/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.js.map +1 -1
  232. package/packages/ai/src/lib/astScopes/processExpression.js +305 -88
  233. package/packages/ai/src/lib/astScopes/processExpression.js.map +1 -1
  234. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +582 -41
  235. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
  236. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js +2 -1
  237. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js.map +1 -1
  238. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js +454 -0
  239. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js.map +1 -0
  240. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js +173 -55
  241. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js.map +1 -1
  242. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js +16 -1
  243. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js.map +1 -1
  244. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js +30 -1
  245. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js.map +1 -1
  246. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js +20 -0
  247. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js.map +1 -1
  248. package/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.js +86 -0
  249. package/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.js.map +1 -0
  250. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js +28 -2
  251. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js.map +1 -1
  252. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js +179 -17
  253. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js.map +1 -1
  254. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js +6 -0
  255. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js.map +1 -1
  256. package/packages/ai/src/lib/generateChangesEntityScenarioData.js +41 -0
  257. package/packages/ai/src/lib/generateChangesEntityScenarioData.js.map +1 -1
  258. package/packages/ai/src/lib/generateChangesEntityScenarios.js +37 -4
  259. package/packages/ai/src/lib/generateChangesEntityScenarios.js.map +1 -1
  260. package/packages/ai/src/lib/generateEntityDataStructure.js +4 -0
  261. package/packages/ai/src/lib/generateEntityDataStructure.js.map +1 -1
  262. package/packages/ai/src/lib/generateEntityKeyAttributes.js +176 -9
  263. package/packages/ai/src/lib/generateEntityKeyAttributes.js.map +1 -1
  264. package/packages/ai/src/lib/generateEntityScenarioData.js +29 -25
  265. package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
  266. package/packages/ai/src/lib/generateEntityScenarios.js +105 -9
  267. package/packages/ai/src/lib/generateEntityScenarios.js.map +1 -1
  268. package/packages/ai/src/lib/getConditionalUsagesFromCode.js +84 -14
  269. package/packages/ai/src/lib/getConditionalUsagesFromCode.js.map +1 -1
  270. package/packages/ai/src/lib/guessScenarioDataFromDescription.js +2 -1
  271. package/packages/ai/src/lib/guessScenarioDataFromDescription.js.map +1 -1
  272. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js +6 -0
  273. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js.map +1 -1
  274. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js +38 -2
  275. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js.map +1 -1
  276. package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js +38 -2
  277. package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js.map +1 -1
  278. package/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.js +16 -3
  279. package/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.js.map +1 -1
  280. package/packages/ai/src/lib/worker/SerializableDataStructure.js.map +1 -1
  281. package/packages/ai/src/lib/worker/analyzeScopeWorker.js +4 -0
  282. package/packages/ai/src/lib/worker/analyzeScopeWorker.js.map +1 -1
  283. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +100 -23
  284. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
  285. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js +125 -0
  286. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js.map +1 -0
  287. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js +298 -45
  288. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js.map +1 -1
  289. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.js +1 -1
  290. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.js.map +1 -1
  291. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +201 -80
  292. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
  293. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js +10 -5
  294. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js.map +1 -1
  295. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js +55 -69
  296. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js.map +1 -1
  297. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js +2 -5
  298. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js.map +1 -1
  299. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +171 -81
  300. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
  301. package/packages/database/src/lib/kysely/db.js +2 -2
  302. package/packages/database/src/lib/kysely/tables/debugReportsTable.js +9 -3
  303. package/packages/database/src/lib/kysely/tables/debugReportsTable.js.map +1 -1
  304. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +8 -4
  305. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
  306. package/packages/generate/src/lib/deepMerge.js +27 -1
  307. package/packages/generate/src/lib/deepMerge.js.map +1 -1
  308. package/packages/types/index.js +1 -0
  309. package/packages/types/index.js.map +1 -1
  310. package/packages/types/src/types/Scenario.js +21 -1
  311. package/packages/types/src/types/Scenario.js.map +1 -1
  312. package/packages/utils/src/lib/lightweightEntityExtractor.js +25 -0
  313. package/packages/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
  314. package/scripts/finalize-analyzer.cjs +3 -1
  315. package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js +0 -238
  316. package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js.map +0 -1
  317. package/codeyam-cli/src/webserver/build/client/assets/EntityItem-CVbSvOjo.js +0 -1
  318. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-DcwcHyl5.js +0 -1
  319. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-WgwC1GfJ.js +0 -26
  320. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-IEKom9O2.js +0 -3
  321. package/codeyam-cli/src/webserver/build/client/assets/LogViewer-BYnfxbUG.js +0 -3
  322. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-_lBPJCzG.js +0 -1
  323. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-lHVhvsu_.js +0 -1
  324. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-d_TBk4GQ.js +0 -5
  325. package/codeyam-cli/src/webserver/build/client/assets/_index-kGT7VUqj.js +0 -1
  326. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-DDGmhu7P.js +0 -7
  327. package/codeyam-cli/src/webserver/build/client/assets/chevron-down-n_HPRfM_.js +0 -1
  328. package/codeyam-cli/src/webserver/build/client/assets/chunk-WWGJGFF6-CbVoyx1U.js +0 -26
  329. package/codeyam-cli/src/webserver/build/client/assets/circle-check-D1VOYveA.js +0 -1
  330. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-YR8jjAlu.js +0 -1
  331. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-B8vP3V_s.js +0 -1
  332. package/codeyam-cli/src/webserver/build/client/assets/entity._sha._-CN6aLCT1.js +0 -16
  333. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-DA5Jeu2P.js +0 -1
  334. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-BTeitalf.js +0 -5
  335. package/codeyam-cli/src/webserver/build/client/assets/entry.client-du6UEYD-.js +0 -13
  336. package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-BpjkhMoi.js +0 -1
  337. package/codeyam-cli/src/webserver/build/client/assets/files-BQGvk4lJ.js +0 -1
  338. package/codeyam-cli/src/webserver/build/client/assets/git-DVdYRT-I.js +0 -12
  339. package/codeyam-cli/src/webserver/build/client/assets/globals-CO-U8Bpo.css +0 -1
  340. package/codeyam-cli/src/webserver/build/client/assets/html2canvas-pro.esm-XQCGvadH.js +0 -5
  341. package/codeyam-cli/src/webserver/build/client/assets/index-DCG-vks0.js +0 -1
  342. package/codeyam-cli/src/webserver/build/client/assets/loader-circle-GazdNeLl.js +0 -1
  343. package/codeyam-cli/src/webserver/build/client/assets/manifest-0b694d28.js +0 -1
  344. package/codeyam-cli/src/webserver/build/client/assets/root-D3tQP7hx.js +0 -16
  345. package/codeyam-cli/src/webserver/build/client/assets/search-CIY6XmtE.js +0 -1
  346. package/codeyam-cli/src/webserver/build/client/assets/server-build-CMKNK2uU.css +0 -1
  347. package/codeyam-cli/src/webserver/build/client/assets/settings-CoMDgElu.js +0 -1
  348. package/codeyam-cli/src/webserver/build/client/assets/simulations-agkniXp2.js +0 -1
  349. package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-B2VUcygF.js +0 -1
  350. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-EvdK-zXP.js +0 -1
  351. package/codeyam-cli/src/webserver/build/server/assets/index-DGVHQEXD.js +0 -1
  352. package/codeyam-cli/src/webserver/build/server/assets/server-build-CghkTkIL.js +0 -166
  353. package/codeyam-cli/templates/debug-command.md +0 -303
  354. /package/codeyam-cli/src/webserver/build/client/assets/{InteractivePreview-CMKNK2uU.css → styles-CMKNK2uU.css} +0 -0
@@ -0,0 +1,175 @@
1
+ var qs=Object.defineProperty;var Gr=e=>{throw TypeError(e)};var Ks=(e,t,r)=>t in e?qs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var tn=(e,t,r)=>Ks(e,typeof t!="symbol"?t+"":t,r),Qs=(e,t,r)=>t.has(e)||Gr("Cannot "+r);var qr=(e,t,r)=>(Qs(e,t,"read from private field"),r?r.call(e):t.get(e)),Kr=(e,t,r)=>t.has(e)?Gr("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r);import{jsx as n,jsxs as c,Fragment as ue}from"react/jsx-runtime";import{PassThrough as Xs}from"node:stream";import{createReadableStreamFromReadable as Zs}from"@react-router/node";import{ServerRouter as eo,useFetcher as _e,useLocation as sr,useNavigate as It,Link as ce,UNSAFE_withComponentProps as We,Meta as to,Links as no,ScrollRestoration as ro,Scripts as ao,useLoaderData as Ge,useRevalidator as lt,Outlet as so,data as Y,useSearchParams as Vt,useParams as ja,useActionData as oo}from"react-router";import{isbot as io}from"isbot";import{renderToPipeableStream as lo}from"react-dom/server";import{useState as j,useEffect as re,useCallback as ae,createContext as or,useContext as An,useRef as Ee,useMemo as oe}from"react";import{Settings as Qr,CheckCircle2 as ir,Bug as $a,AlertTriangle as Kn,Loader2 as nt,HomeIcon as co,GitCommitIcon as Xr,File as uo,RefreshCw as ho,SettingsIcon as mo,PanelsTopLeftIcon as po,ComponentIcon as fo,FileText as Zr,Code as ea,Box as go,List as yo,BarChart3 as xo,Tag as bo,Image as kt,Code2 as Ra,Activity as On,ChevronDown as pn,CircleEqual as vo,PauseCircle as Da,ListTodo as wo,FileCode as Co,GripVertical as No,Ban as So,CheckCircle as Ao,Check as Eo,Copy as _o,Search as La,FolderOpen as Po,CodeXml as ko,Zap as Mo}from"lucide-react";import"fetch-retry";import To from"better-sqlite3";import{Pool as Io}from"pg";import*as q from"fs";import xt,{existsSync as jo}from"fs";import*as X from"path";import be from"path";import{OperationNodeTransformer as $o,Kysely as Oa,ParseJSONResultsPlugin as Ro,SqliteDialect as Do,PostgresDialect as Lo,sql as Je}from"kysely";import*as Oo from"kysely/helpers/sqlite";import*as Fo from"kysely/helpers/postgres";import Ae from"typescript";import*as Ie from"fs/promises";import Te,{writeFile as Yo,readFile as zo}from"fs/promises";import*as Bo from"os";import Qn from"os";import Uo from"prompts";import fn from"chalk";import lr,{randomUUID as jt}from"crypto";import{spawn as cr,exec as dr,execSync as Me}from"child_process";import{promisify as ur}from"util";import Wo from"dotenv";import Ho,{EventEmitter as Vo}from"events";import{v4 as Jo}from"uuid";import{fileURLToPath as Fa}from"url";import Go from"openai";import qo from"p-queue";import ta from"p-retry";import{DynamoDBClient as En,PutItemCommand as Ko}from"@aws-sdk/client-dynamodb";import{LRUCache as hr}from"lru-cache";import"pluralize";import"piscina";import Qo from"json5";import{marshall as Xo}from"@aws-sdk/util-dynamodb";import{Prism as Zo}from"react-syntax-highlighter";import{vscDarkPlus as ei}from"react-syntax-highlighter/dist/cjs/styles/prism/index.js";import{randomUUID as ti}from"node:crypto";import ni from"v8";import ri from"react-diff-viewer-continued";const Ya=5e3;function ai(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"),u=d&&io(d)||a.isSpaMode?"onAllReady":"onShellReady",h=setTimeout(()=>p(),Ya+1e3);const{pipe:m,abort:p}=lo(n(eo,{context:a,url:e.url}),{[u](){l=!0;const f=new Xs({final(y){clearTimeout(h),h=void 0,y()}}),g=Zs(f);r.set("Content-Type","text/html"),m(f),o(new Response(g,{headers:r,status:t}))},onShellError(f){i(f)},onError(f){t=500,l&&console.error(f)}})})}const si=Object.freeze(Object.defineProperty({__proto__:null,default:ai,streamTimeout:Ya},Symbol.toStringTag,{value:"Module"}));function oi({id:e,selected:t,onClick:r,icon:a,name:s}){const[o,i]=j(!1);re(()=>{i(!0)},[]);const l=ae(()=>{r==null||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 za="/assets/cy-logo-cli-C1gnJVOL.svg";function ii(e){return e.scenarioId?`Scenario: ${e.scenarioId.slice(0,8)}...`:e.entitySha?`Entity: ${e.entitySha.slice(0,8)}...`:"General feedback"}function Ba({isOpen:e,onClose:t,context:r,defaultEmail:a="",screenshotDataUrl:s}){const[o,i]=j(""),[l,d]=j(a),[u,h]=j(!1),[m,p]=j(!1),[f,g]=j(null),[y,w]=j(null),x=_e(),v=x.state!=="idle";if(x.data&&!m&&!y){const S=x.data;S.success&&S.reportId?(p(!0),g(S.reportId)):S.error&&w(S.error)}const b=async()=>{w(null);const S=new FormData;if(S.append("issueType","other"),S.append("description",o),S.append("email",l),S.append("source",r.source),S.append("entitySha",r.entitySha||""),S.append("scenarioId",r.scenarioId||""),S.append("analysisId",r.analysisId||""),S.append("currentUrl",r.currentUrl),s)try{const P=await(await fetch(s)).blob();S.append("screenshot",P,"screenshot.jpg")}catch(A){console.error("Failed to convert screenshot:",A)}x.submit(S,{method:"post",action:"/api/generate-report",encType:"multipart/form-data"})},N=()=>{i(""),h(!1),p(!1),g(null),w(null),t()},T=S=>{S.key==="Escape"&&N()};return e?n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",onKeyDown:T,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:[v?n("div",{className:"animate-spin",children:n(Qr,{size:24,style:{strokeWidth:1.5}})}):m?n(ir,{size:24,style:{color:"#10B981",strokeWidth:1.5}}):n($a,{size:24,style:{color:"#005C75",strokeWidth:1.5}}),n("h2",{className:"text-xl font-semibold text-gray-900",children:m?"Report Submitted":"Report Issue"})]}),n("button",{onClick:N,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),m?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:N,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] transition-colors cursor-pointer",children:"Done"})})]}):c("div",{children:[c("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[c("div",{className:"flex items-center justify-between",children:[n("div",{className:"text-sm font-medium text-gray-900",title:`${r.source}${r.entitySha?` • Entity: ${r.entitySha}`:""}${r.scenarioId?` • Scenario: ${r.scenarioId}`:""}${r.analysisId?` • Analysis: ${r.analysisId}`:""}`,children:ii(r)}),n("button",{type:"button",onClick:()=>h(!u),className:"text-xs text-gray-500 hover:text-gray-700 underline cursor-pointer",children:u?"Hide":"Details"})]}),u&&c("div",{className:"mt-2 pt-2 border-t border-gray-200 text-xs text-gray-600 space-y-1",children:[c("div",{children:[n("span",{className:"text-gray-400",children:"Source:"})," ",r.source]}),c("div",{children:[n("span",{className:"text-gray-400",children:"URL:"})," ",r.currentUrl]}),r.entitySha&&c("div",{children:[n("span",{className:"text-gray-400",children:"Entity:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.entitySha})]}),r.scenarioId&&c("div",{children:[n("span",{className:"text-gray-400",children:"Scenario:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.scenarioId})]}),r.analysisId&&c("div",{children:[n("span",{className:"text-gray-400",children:"Analysis:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.analysisId})]})]})]}),s&&c("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-xs text-gray-500 mb-2",children:"Screenshot (will be included in report)"}),n("img",{src:s,alt:"Page screenshot",className:"w-full max-h-[150px] object-contain rounded border border-gray-300"})]}),c("div",{className:"mb-4",children:[n("label",{htmlFor:"description",className:"block text-sm font-medium text-gray-700 mb-2",children:"What happened?"}),n("textarea",{id:"description",value:o,onChange:S=>i(S.target.value),placeholder:"Describe what you expected vs what happened...",rows:4,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"}),n("input",{id:"email",type:"email",value:l,onChange:S=>d(S.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(Kn,{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."})]})]}),v&&n("div",{className:"mb-4 text-center",children:n("p",{className:"text-sm text-gray-600",children:x.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(Kn,{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:N,disabled:v,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-300 transition-colors disabled:opacity-50 cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>void b(),disabled:v,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed flex items-center gap-2 cursor-pointer",children:v?c(ue,{children:[n("div",{className:"animate-spin",children:n(Qr,{size:16,style:{strokeWidth:1.5}})}),"Submitting..."]}):y?"Try Again":"Submit Report"})]})]})]})}):null}const na={source:"navbar"},mr=or(void 0);function li({children:e}){const[t,r]=j(na),a=ae(o=>{r(o)},[]),s=ae(()=>{r(na)},[]);return n(mr.Provider,{value:{contextData:t,setContextData:a,resetContextData:s},children:e})}function Nt(e){const t=An(mr),r=Ee(t);re(()=>{if(r.current)return r.current.setContextData(e),()=>{var a;(a=r.current)==null||a.resetContextData()}},[e.source,e.entitySha,e.scenarioId,e.analysisId])}function ci(){const e=An(mr),t=sr();return e?{source:e.contextData.source,entitySha:e.contextData.entitySha,scenarioId:e.contextData.scenarioId,analysisId:e.contextData.analysisId,currentUrl:t.pathname}:{source:"navbar",currentUrl:t.pathname}}function di(){var v;const e=sr(),t=It(),[r,a]=j(),[s,o]=j(!1),[i,l]=j(!1),[d,u]=j(null),h=_e();re(()=>{h.state==="idle"&&!h.data&&h.load("/api/generate-report")},[h]);const m=((v=h.data)==null?void 0:v.defaultEmail)||"",p={width:"24px",height:"24px",strokeWidth:1.5},f=[{id:"dashboard",icon:n(co,{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(Xr,{style:p}),link:"/git",name:"Git"},{id:"files",icon:n(uo,{style:p}),link:"/files",name:"Files"},{id:"activity",icon:n(ho,{style:p}),link:"/activity",name:"Activity"},{id:"settings",icon:n(mo,{style:p}),link:"/settings",name:"Settings"},{id:"commits",icon:n(Xr,{style:p}),link:"/commits",name:"Commits",hidden:!0},{id:"pages",icon:n(po,{style:p}),link:"/pages",name:"Pages",hidden:!0},{id:"components",icon:n(fo,{style:p}),link:"/components",name:"Components",hidden:!0}],g=ae(b=>{const N=f.find(T=>T.id===b);N!=null&&N.link&&t(N.link),a(T=>T===b?void 0:b)},[f,t]);re(()=>{const b={dashboard:["/","/home"],git:["git"],commits:["commits"],simulations:["simulations"],activity:["activity"],files:["files"],settings:["settings"],pages:["pages"],components:["components"]};for(const[N,T]of Object.entries(b))if(T.some(S=>S==="/"?e.pathname==="/":e.pathname.includes(S))){a(N);return}a(void 0)},[e]);const y=async()=>{l(!0);try{const{default:b}=await import("html2canvas-pro"),T=(await b(document.body)).toDataURL("image/jpeg",.8);u(T),o(!0)}catch(b){console.error("Screenshot capture failed:",b),o(!0)}finally{l(!1)}},w=()=>{o(!1),u(null)},x=ci();return c(ue,{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(ce,{to:"/",className:"flex items-center justify-center h-20 cursor-pointer",children:n("img",{src:za,alt:"CodeYam",className:"h-8"})})}),f.filter(b=>!b.hidden).map(b=>n(oi,{id:b.id,selected:b.id===r,onClick:g,icon:b.icon,name:b.name},`sidebar-button-${b.id}`))]}),n("div",{className:"w-full flex flex-col items-center pb-2",children:c("button",{onClick:()=>void 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 cursor-pointer disabled:opacity-50 disabled:cursor-wait",title:"Report an issue",children:[i?n(nt,{style:p,className:"animate-spin"}):n($a,{style:p}),n("span",{className:"text-[10px] font-medium",children:i?"Capturing...":"Report Issue"})]})})]}),s&&n(Ba,{isOpen:!0,onClose:w,context:x,defaultEmail:m,screenshotDataUrl:d??void 0})]})}const Ua=or(void 0);function ui({children:e}){const[t,r]=j([]),a=ae((o,i="info",l=5e3)=>{const u={id:`toast-${Date.now()}-${Math.random()}`,message:o,type:i,duration:l};r(h=>[...h,u])},[]),s=ae(o=>{r(i=>i.filter(l=>l.id!==o))},[]);return n(Ua.Provider,{value:{toasts:t,showToast:a,closeToast:s},children:e})}function pr(){const e=An(Ua);if(!e)throw new Error("useToast must be used within a ToastProvider");return e}function hi({toast:e,onClose:t}){re(()=>{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 mi({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(hi,{toast:r,onClose:t},r.id))]})}function ct(e,t){const[r,a]=j(""),[s,o]=j(!1),[i,l]=j(null),[d,u]=j(!1);re(()=>{t&&(u(!1),o(!1),l(null))},[t]),re(()=>{if(!e||!t){t||a("");return}const m=async()=>{try{const f=await fetch(`/api/logs/${e}`);if(f.ok){const y=(await f.text()).trim().split(`
17
+ `).filter(v=>v.length>0);if(y.length<3){o(!1),u(!1),l(null),a("");return}const w=y.filter(v=>v.includes("CodeYam Log Level 1"));if(w.length>0){const v=w[w.length-1];a(v.replace(/.*CodeYam Log Level 1: /,""))}const x=y.find(v=>v.includes("$$INTERACTIVE_SERVER_URL$$:"));if(x){const v=x.split("$$INTERACTIVE_SERVER_URL$$:")[1].trim();l(v),u(!0)}y.some(v=>v.includes("CodeYam: Exiting start.js"))&&o(!0)}}catch{}};m().catch(()=>{});const p=setInterval(()=>{m().catch(()=>{})},2e3);return()=>clearInterval(p)},[e,t]);const h=ae(()=>{a(""),o(!1),l(null),u(!1)},[]);return{lastLine:r,interactiveUrl:i,isCompleted:s,resetLogs:h}}function $t({projectSlug:e,onClose:t}){const[r,a]=j("Loading logs..."),[s,o]=j(!0),[i,l]=j(!0),[d,u]=j("all"),h=Ee(null);return re(()=>{const m=async()=>{try{const p=await fetch(`/api/logs/${e}`);if(p.ok){const f=await p.text();if(d==="all")a(f);else{const g=f.trim().split(`
18
+ `).filter(y=>{if(y.length===0)return!1;const w=y.match(/^.*CodeYam Log Level (\d+):/);return!!w&&Number(w[1])<=d});a(g.map(y=>y.replace(/^.*CodeYam Log Level \d+:\s*/,"")).join(`
19
+ `))}i&&h.current&&setTimeout(()=>{var g;(g=h.current)==null||g.scrollTo({top:h.current.scrollHeight,behavior:"smooth"})},100)}else a(`Error: ${p.status} - ${await p.text()}`)}catch(p){a(`Error fetching logs: ${p.message}`)}};if(m().catch(()=>{}),s){const p=setInterval(()=>{m().catch(()=>{})},2e3);return()=>clearInterval(p)}},[e,s,i,d]),re(()=>{const m=p=>{p.key==="Escape"&&t()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[t]),n("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-9999 p-5",onClick:t,children:c("div",{className:"bg-[#1e1e1e] rounded-lg shadow-2xl flex flex-col max-w-[1200px] w-full max-h-[90vh] overflow-hidden",onClick:m=>m.stopPropagation(),children:[c("div",{className:"flex justify-between items-center px-5 py-4 border-b border-[#333] bg-[#252525]",children:[c("h3",{className:"m-0 text-lg font-semibold text-white",children:["Analysis Logs - ",e]}),c("div",{className:"flex items-center gap-4",children:[c("label",{className:"flex items-center gap-2 text-sm text-[#ccc] select-none",children:[n("span",{children:"Log Level:"}),c("select",{value:d,onChange:m=>u(m.target.value==="all"?"all":Number(m.target.value)),className:"bg-[#333] text-white border border-[#555] rounded px-2 py-1 text-sm cursor-pointer outline-none transition-all hover:border-[#777] hover:bg-[#3a3a3a] focus:border-blue-600",children:[n("option",{value:"1",children:"1"}),n("option",{value:"2",children:"2"}),n("option",{value:"3",children:"3"}),n("option",{value:"4",children:"4"}),n("option",{value:"all",children:"All"})]})]}),c("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:s,onChange:m=>o(m.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-refresh"})]}),c("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:i,onChange:m=>l(m.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-scroll"})]}),n("button",{onClick:t,className:"bg-transparent border-none text-[#999] text-2xl cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-all hover:bg-[#333] hover:text-white",title:"Close (Esc)",children:"✕"})]})]}),n("pre",{className:"flex-1 m-0 px-5 py-4 overflow-auto font-mono text-[13px] leading-relaxed text-[#d4d4d4] bg-[#1e1e1e] whitespace-pre-wrap wrap-break-word scrollbar-thin scrollbar-thumb-[#424242] scrollbar-track-[#1e1e1e] hover:scrollbar-thumb-[#4f4f4f]",ref:h,children:r})]})})}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(Ra,{size:14,color:r.iconColor});case"visual":return n(kt,{size:14,color:r.iconColor});case"type":return n(bo,{size:14,color:r.iconColor});case"data":return n(xo,{size:14,color:r.iconColor});case"index":return n(yo,{size:14,color:r.iconColor});case"functionCall":return n(ea,{size:14,color:r.iconColor});case"class":return n(go,{size:14,color:r.iconColor});case"method":return n(ea,{size:14,color:r.iconColor});case"other":return n(Zr,{size:14,color:r.iconColor});default:return n(Zr,{size:14,color:r.iconColor})}};return n("span",{className:`flex items-center justify-center rounded ${r.bgColor}`,style:{width:"18px",height:"18px"},children:a()})}function Wa({filePath:e,maxLength:t=60,className:r,style:a}){const o=((l,d)=>{if(l.length<=d)return l;const u="...",h=d-u.length,m=Math.ceil(h*.4),p=Math.floor(h*.6),f=l.slice(0,m),g=l.slice(-p),y=f.lastIndexOf("/"),w=g.indexOf("/"),x=y>m*.5?f.slice(0,y+1):f,v=w!==-1&&w<p*.5?g.slice(w):g;return`${x}${u}${v}`})(e,t),i=o!==e;return n("span",{className:r||"font-normal text-gray-900 text-[14px] select-text cursor-text",style:{...a,display:"inline-block",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:i?e:void 0,children:o})}function Fn({entity:e,nameSize:t="11px",pathSize:r="10px",pathMaxLength:a=50,showScenarioCount:s=!1,scenarioCount:o=0,additionalContent:i}){return c("div",{className:"flex flex-col gap-1",children:[c("div",{className:"flex items-center gap-1",children:[n(Be,{type:e.entityType||"other"}),c(ce,{to:`/entity/${e.sha}`,className:"hover:underline shrink-0 cursor-pointer",style:{fontSize:t,fontWeight:500,color:"#000",whiteSpace:"nowrap"},children:[e.name,s&&o>0&&` (${o})`]}),n(Wa,{filePath:e.filePath,maxLength:a,style:{fontSize:r,color:"#8E8E8E"}})]}),i]})}const ra={fontSize:"9px",color:"#005C75",fontStyle:"italic"};function pi({currentRun:e,projectSlug:t,currentEntities:r=[],isAnalysisStarting:a=!1,queuedJobCount:s=0,queueJobs:o=[],currentlyExecuting:i=null,historicalRuns:l=[]}){var E,C,_;const[d,u]=j(!1),[h,m]=j(!1),[p,f]=j(null),[g,y]=j(new Set),[w,x]=j(new Set),v=!!i||o.length>0,b=!!i,N=(i==null?void 0:i.entities)||r;e!=null&&e.analysisCompletedAt,e==null||e.readyToBeCaptured,e==null||e.capturesCompleted;const T=(e==null?void 0:e.currentEntityShas)&&e.currentEntityShas.length>0,S=v,{lastLine:A}=ct(t,S),P=b,I=new Set(((E=i==null?void 0:i.entities)==null?void 0:E.map($=>$.sha))||[]),M=l.filter($=>!($.currentEntityShas||[]).some(z=>I.has(z))),R=(()=>{const D=Date.now()-1440*60*1e3;if(e!=null&&e.createdAt&&T){const z=e.analysisCompletedAt||e.createdAt;if(new Date(z).getTime()>D)return!0}if(M.length>0){const z=M[0],W=z.analysisCompletedAt||z.archivedAt||z.createdAt;if(W&&new Date(W).getTime()>D)return!0}return!1})();return re(()=>{const $=(i==null?void 0:i.id)||null;v&&!h&&$!==p&&m(!0),!v&&p!==null&&f(null)},[v,i==null?void 0:i.id,h,p]),c(ue,{children:[c("div",{className:`fixed bottom-4 right-4 z-9998 bg-white rounded shadow-lg border-2 border-primary-100 transition-all duration-200 ${h?"min-w-[350px] max-w-[500px]":"w-auto"}`,children:[!h&&c("div",{onClick:()=>{m(!0),f(null)},className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-gray-50 transition-colors",title:"Click to expand",children:[P?n(nt,{size:16,className:"animate-spin",style:{color:"#005C75"}}):n("div",{className:"flex items-center justify-center rounded",style:{backgroundColor:"#E0E9EC",width:"20px",height:"20px"},children:n(On,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:P?"Analyzing...":"Activity: No Activity Yet"}),P&&n("button",{onClick:$=>{$.stopPropagation(),u(!0)},className:"ml-auto px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),h&&c("div",{children:[c("div",{className:"flex items-center justify-between px-3 py-2",children:[c("div",{className:"flex items-center gap-2",children:[P?n(nt,{size:16,className:"animate-spin",style:{color:"#005C75"}}):n("div",{className:"flex items-center justify-center rounded",style:{backgroundColor:"#E0E9EC",width:"20px",height:"20px"},children:n(On,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:P?"Analyzing...":"Activity"})]}),c("div",{className:"flex items-center gap-2",children:[n("button",{onClick:()=>u(!0),className:"px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"}),n("button",{onClick:()=>{m(!1),f((i==null?void 0:i.id)||null)},className:"p-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC"},title:"Collapse","aria-label":"Collapse",children:n(pn,{size:16,style:{color:"#646464"}})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),c("div",{className:"px-3 pt-2 pb-3 space-y-3",children:[P&&i&&c("div",{children:[c("div",{className:"flex items-center gap-1.5 mb-2",children:[n(On,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Current Activity"})]}),n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:N.length>0?c("div",{className:"space-y-1.5",children:[N.map($=>n(Fn,{entity:$,nameSize:"11px",pathSize:"10px",pathMaxLength:150},$.sha)),A&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:A})]}):c("div",{children:[i.entityNames&&i.entityNames.length>0?c("div",{className:"space-y-0.5",children:[i.entityNames.slice(0,5).map(($,D)=>n("div",{style:{fontSize:"11px",color:"#343434"},children:$},D)),i.entityNames.length>5&&c("div",{className:"italic",style:{fontSize:"10px",color:"#666"},children:["+",i.entityNames.length-5," ","more"]})]}):c("div",{style:{fontSize:"11px",color:"#343434"},children:["Analyzing"," ",((C=i.entityShas)==null?void 0:C.length)||0," ",((_=i.entityShas)==null?void 0:_.length)===1?"entity":"entities","..."]}),A&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:A})]})})]}),o.length>0&&c("div",{children:[c("div",{className:"flex items-center gap-1.5 mb-2",children:[n(vo,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Queued Activity"})]}),n("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:o.map($=>{var W,K;const D=g.has($.id),z=D?$.entities:$.entities.slice(0,3);return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:$.entities.length>0?c("div",{className:"space-y-1.5",children:[z.map(Q=>n(Fn,{entity:Q,nameSize:"10px",pathSize:"9px",pathMaxLength:120},Q.sha)),$.entities.length>3&&n("button",{onClick:()=>{y(Q=>{const te=new Set(Q);return te.has($.id)?te.delete($.id):te.add($.id),te})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:ra,"aria-label":D?"Show fewer entities":`Show ${$.entities.length-3} more entities`,children:D?"Show less":`+${$.entities.length-3} more`})]}):c("div",{style:{fontSize:"10px",color:"#343434"},children:[$.type==="analysis"&&n(ue,{children:$.entityNames&&$.entityNames.length>0?c("div",{className:"space-y-0.5",children:[$.entityNames.slice(0,5).map((Q,te)=>n("div",{children:Q},te)),$.entityNames.length>5&&c("div",{className:"italic",children:["+",$.entityNames.length-5," more"]})]}):`Analyzing ${((W=$.entityShas)==null?void 0:W.length)||0} ${((K=$.entityShas)==null?void 0:K.length)===1?"entity":"entities"}`}),$.type==="recapture"&&"Recapturing scenario",$.type==="debug-setup"&&"Setting up debug environment"]})},$.id)})})]}),R&&M.length>0&&c("div",{children:[c("div",{className:"flex items-center gap-1.5 mb-2",children:[n(ir,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Recently Completed"})]}),n("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:M.slice(0,3).map(($,D)=>{const z=$.entities||[],W=$.analysisCompletedAt||$.archivedAt||$.createdAt||"",K=(()=>{if(!W)return"";const H=Date.now()-new Date(W).getTime(),k=Math.floor(H/6e4),B=Math.floor(H/36e5);return B>0?`${B}h ago`:k>0?`${k}m ago`:"just now"})(),Q=w.has(D),F=(Q?z:z.slice(0,3)).map(H=>{var k,B,ne;return{...H,scenarioCount:((ne=(B=(k=H.analyses)==null?void 0:k[0])==null?void 0:B.scenarios)==null?void 0:ne.length)||0}});return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:z.length>0&&c("div",{className:"space-y-1.5",children:[F.map((H,k)=>c("div",{className:"flex items-start justify-between gap-2",children:[n("div",{className:"flex-1 min-w-0",children:n(Fn,{entity:H,nameSize:"10px",pathSize:"9px",pathMaxLength:100,showScenarioCount:!0,scenarioCount:H.scenarioCount})}),k===0&&K&&n("div",{style:{fontSize:"9px",color:"#8E8E8E",whiteSpace:"nowrap",paddingTop:"2px"},children:K})]},H.sha)),z.length>3&&n("button",{onClick:()=>{x(H=>{const k=new Set(H);return k.has(D)?k.delete(D):k.add(D),k})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:ra,"aria-label":Q?"Show fewer entities":`Show ${z.length-3} more entities`,children:Q?"Show less":`+${z.length-3} more`})]})},D)})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),n("div",{className:"px-3 pb-2",children:n(ce,{to:"/activity",className:"text-xs font-medium hover:underline cursor-pointer",style:{color:"#005C75"},children:"View All Activity →"})})]})]}),d&&t&&n($t,{projectSlug:t,onClose:()=>u(!1)})]})}function He(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r===null?void 0:r]))}function Jt(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:u,updated_at:h,...m}=e,p=(i??[]).map(y=>y.branch_id),f=l?l.map(Xe):void 0,g=d?St(d):void 0;return He({...m,fileId:t,projectId:r,commitId:a,filePath:s,entityType:o,commit:g,analyses:f,branchIds:p,createdAt:u,updatedAt:h})}function fr(e){return He({id:e.id,projectId:e.project_id,name:e.name,path:e.path,deleted:!!e.deleted,metadata:e.metadata??void 0,createdAt:e.created_at,updatedAt:e.updated_at??void 0})}function gr(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:u,...h}=e;return He({...h,branches:t?t.map(Tt):void 0,files:r?r.map(fr):void 0,analyzedAt:a,contentChangedAt:s,createdAt:o,updatedAt:i})}function fi(e){const{id:t,project_id:r,user_id:a,scenario_id:s,thumbs_up:o,user:i}=e,l=i?{username:i.github_username,avatarUrl:i.github_user.avatar_url}:void 0;return He({id:t,projectId:r,userId:a,scenarioId:s,thumbsUp:!!o,user:l})}function gi(e){const{id:t,project_id:r,user_id:a,scenario_id:s,text:o,created_at:i,updated_at:l,user:d}=e,u=d?{username:d.github_username,avatarUrl:d.github_user.avatar_url}:void 0;return He({id:t,projectId:r,userId:a,scenarioId:s,text:o,createdAt:i,updatedAt:l,user:u})}function Ha(e){const{project_id:t,analysis_id:r,previous_version_id:a,analysis:s,user_scenarios:o,scenario_comments:i,approved:l,...d}=e,u=s?Xe(s):void 0,h=o?o.map(fi):void 0,m=i?i.map(gi):void 0;return He({...d,projectId:t,analysisId:r,previousVersionId:a,analysis:u,userScenarios:h,comments:m})}function yi(e){return He({id:e.id,analysisId:e.analysis_id,entitySha:e.entity_sha,branchId:e.branch_id,active:!!e.active,analysis:e.analysis?Xe(e.analysis):void 0,entity:e.entity?Jt(e.entity):void 0,branch:e.branch?Tt(e.branch):void 0,createdAt:e.created_at})}function Xe(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:u,entity:h,commit:m,project:p,scenarios:f,analysis_branches:g,dependency_analyzed_tree_sha:y,analyzed_tree_sha:w,branch_commit_sha:x,committed_at:v,completed_at:b,created_at:N,updated_at:T,indirect:S,...A}=e,P=h?Jt(h):void 0,I=u?fr(u):void 0,M=p?gr(p):void 0,R=m?St(m):void 0,E=f?f.map(Ha):void 0,C=g?g.map(yi):void 0,_=C?C.map($=>$.branch):void 0;return He({...A,projectId:t,commitId:r,fileId:a,filePath:s,entitySha:o,entityType:i,entityName:l,previousAnalysisId:d,entity:P,file:I,commit:R,project:M,scenarios:E,analysisBranches:C,branches:_,dependencyAnalyzedTreeSha:y,analyzedTreeSha:w,branchCommitSha:x,committedAt:v,completedAt:b,createdAt:N,updatedAt:T,indirect:!!S})}function yr(e){return He({id:e.id,commitId:e.commit_id,branchId:e.branch_id,active:!!e.active,commit:e.commit?St(e.commit):void 0,branch:e.branch?Tt(e.branch):void 0})}function xi(e){const{project_id:t,commit_id:r,created_at:a,updated_at:s,success:o,...i}=e;return He({...i,projectId:t,commitId:r,createdAt:a,updatedAt:s,success:!!o})}function St(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:u,analyses:h,entities:m,commit_branches:p,committed_at:f,analyzed_at:g,...y}=e,w=a?Tt(a):void 0,x=i?Tt(i):void 0,v=(s==null?void 0:s.length)>0?xi(s[s.length-1]):void 0,b=(h??[]).map(Xe),N=(m??[]).map(Jt),T=(p==null?void 0:p.length)>0?p.map(yr):void 0;return u&&(u.username=u.preferredUsername??u.username),He({...y,projectId:t,branchId:r,branch:w,backgroundJob:v,mergedBranchId:o,mergedBranch:x,aiMessage:l,htmlUrl:d,author:u,analyses:b,entities:N,commitBranches:T,committedAt:f,analyzedAt:g})}function Tt(e){const{project_id:t,content_changed_at:r,commits:a,analysis_branches:s,active_at:o,created_at:i,updated_at:l,primary:d,...u}=e,h=a?a.map(St):void 0,m=s?s.flatMap(p=>Xe(p.analysis)):void 0;return He({...u,projectId:t,contentChangedAt:r,commits:h,analyses:m,activeAt:o,createdAt:i,updatedAt:l,primary:!!d})}var Sn;class bi{constructor(){Kr(this,Sn,new vi)}transformQuery(t){return qr(this,Sn).transformNode(t.node)}transformResult(t){return Promise.resolve(t.result)}}Sn=new WeakMap;class vi extends $o{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 J=()=>null,wi={analyzed_at:J(),configuration:J(),content_changed_at:J(),created_at:J(),description:J(),github_token:J(),id:J(),metadata:J(),name:J(),path:J(),slug:J(),team_id:J(),updated_at:J()},Ci=Object.keys(wi),Ni={active:J(),analysis_id:J(),branch_id:J(),created_at:J(),entity_sha:J(),id:J()},Si=Object.keys(Ni),Ai={active_at:J(),content_changed_at:J(),created_at:J(),id:J(),metadata:J(),name:J(),primary:J(),project_id:J(),ref:J(),sha:J(),updated_at:J()},Va=Object.keys(Ai),Ei={ai_message:J(),analyzed_at:J(),author_github_username:J(),branch_id:J(),committed_at:J(),created_at:J(),files:J(),html_url:J(),id:J(),merged_branch_id:J(),message:J(),metadata:J(),project_id:J(),sha:J(),title:J(),url:J()},_i=Object.keys(Ei),Pi={commit_id:J(),created_at:J(),description:J(),documentation:J(),entity_type:J(),file_id:J(),file_path:J(),metadata:J(),name:J(),project_id:J(),quality:J(),sha:J(),updated_at:J()},Ja=Object.keys(Pi),ki={active:J(),branch_id:J(),entity_sha:J()},Mi=Object.keys(ki),Ti={created_at:J(),deleted:J(),id:J(),metadata:J(),name:J(),path:J(),project_id:J(),updated_at:J()},Ii=Object.keys(Ti),ji={analysis_id:J(),approved:J(),created_at:J(),description:J(),id:J(),metadata:J(),name:J(),previous_version_id:J(),project_id:J()},xr=Object.keys(ji),$i=!!bt("ENABLE_QUERY_LOGGING"),Ri=!!bt("ENABLE_QUERY_ERROR_LOGGING");bt("USE_LOCAL_POSTGRESQL_FOR_TESTING");let nn;function ve(){if(!nn){const e=qa();if(e==="sqlite")nn=Di();else if(e==="postgresql")nn=Li();else throw new Error(`Unknown database type: ${e}`)}return nn}function Di(e){if(e||(e=bt("SQLITE_PATH")),e===":memory:"||e==="memory")throw new Error("In-memory SQLite not supported in getDatabase(). Use getDatabaseForTesting() instead.");const t=q.existsSync(e),r=X.dirname(e);if(!q.existsSync(r))q.mkdirSync(r,{recursive:!0,mode:493});else try{q.chmodSync(r,493)}catch(s){console.warn(`Warning: Could not set permissions on database directory: ${s.message}`)}const a=new To(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 Oa({dialect:new Do({database:a}),plugins:[new Ro,new bi],log:Ga})}function Li(){const e=Fi();console.log(`CodeYam: Using PostgreSQL database at: ${e}`);const t=new Io({connectionString:e});return t.on("error",(r,a)=>{console.error("CodeYam: Unexpected error on idle PostgreSQL client",r)}),new Oa({dialect:new Lo({pool:t}),log:Ga})}let Yn=null;function At(){return Yn||(Yn=Oi(qa())),Yn}function Ga(e){e.level==="error"?Ri&&console.error("Query failed : ",{durationMs:e.queryDurationMillis,error:e.error,sql:e.query.sql,params:e.query.parameters}):$i&&console.log("Query executed : ",{durationMs:e.queryDurationMillis,sql:e.query.sql,params:e.query.parameters})}function Oi(e){if(e==="sqlite")return Oo;if(e==="postgresql")return Fo;throw new Error(`Unknown database type: ${e}`)}function qa(){if(bt("SQLITE_PATH"))return"sqlite";if(bt("POSTGRESQL_URL"))return"postgresql";throw new Error("No database configuration found. Set SQLITE_PATH for SQLite or POSTGRESQL_URL for PostgreSQL")}function Fi(){const e=bt("POSTGRESQL_URL");if(!e)throw new Error("No PostgreSQL connection string found. Set POSTGRESQL_URL environment variable.");return e}function bt(e){var t;return typeof window<"u"?(t=window.env)==null?void 0:t[e]:process.env[e]}var Gt=(e=>(e.Remix="Remix",e.CodeYam="CodeYam",e.CRA="CRA",e.Next="Next",e.NextPages="NextPages",e.Unknown="Unknown",e))(Gt||{});function Yi(e){return typeof e=="object"&&"localVariable"in e&&"instruction"in e&&("valueOptionRef"in e||"errorOptionRef"in e)}function zi(e){var r;const t=(r=e.metadata)==null?void 0:r.keyAttributeInstructions;return!t||Object.keys(t).length===0?!1:Object.values(t).some(a=>typeof a=="object"&&("valueOptionRef"in a||"errorOptionRef"in a))}const _n="Default Scenario";let Bi="<main>";function Ui(){return Bi}function pe(...e){const t=Ui(),r=e.map(s=>{if(s)return typeof s=="string"?s:s instanceof Error?`${s.name}: ${s.message}
20
+ ${s.stack}`:typeof s=="object"?Wi(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 Wi(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 gn(e,t){try{let r=function(o){var i,l;if(Ae.isFunctionDeclaration(o)&&Ft(o)){const d=((i=o.name)==null?void 0:i.text)||"default",u=o.getText(a),h=zn(o);s.push({name:d,code:u,sha:mt(t,d,u),entityType:"function",isDefault:h})}else if(Ae.isClassDeclaration(o)&&Ft(o)){const d=((l=o.name)==null?void 0:l.text)||"default",u=o.getText(a),h=zn(o),m=u.includes("React.")||u.includes("jsx")||u.includes("tsx");s.push({name:d,code:u,sha:mt(t,d,u),entityType:m?"component":"class",isDefault:h})}else if(Ae.isInterfaceDeclaration(o)&&Ft(o)){const d=o.name.text,u=o.getText(a);s.push({name:d,code:u,sha:mt(t,d,u),entityType:"interface",isDefault:!1})}else if(Ae.isTypeAliasDeclaration(o)&&Ft(o)){const d=o.name.text,u=o.getText(a);s.push({name:d,code:u,sha:mt(t,d,u),entityType:"type",isDefault:!1})}else if(Ae.isVariableStatement(o)&&Ft(o)){const d=zn(o);o.declarationList.declarations.forEach(u=>{var h;if(Ae.isIdentifier(u.name)){const m=u.name.text,p=o.getText(a),f=((h=u.initializer)==null?void 0:h.getText(a))||"",g=(t.endsWith(".tsx")||t.endsWith(".jsx"))&&f.includes("=>")&&(f.includes("<")||f.includes("React."));s.push({name:m,code:p,sha:mt(t,m,p),entityType:g?"component":"variable",isDefault:d})}})}else if(Ae.isExportAssignment(o)){const d=o.getText(a);s.push({name:"default",code:d,sha:mt(t,"default",d),entityType:"unknown",isDefault:!0})}else if(Ae.isExportDeclaration(o)&&o.exportClause&&Ae.isNamedExports(o.exportClause)){const d=o.getText(a);for(const u of o.exportClause.elements){const h=u.name.text;s.push({name:h,code:d,sha:mt(t,h,d),entityType:"unknown",isDefault:!1})}}Ae.forEachChild(o,r)};const a=Ae.createSourceFile(t,e,Ae.ScriptTarget.Latest,!0),s=[];return r(a),s}catch(r){return console.error(`Failed to extract entities from ${t}:`,r),[]}}function Ft(e){if(!Ae.canHaveModifiers(e))return!1;const t=Ae.getModifiers(e);return t?t.some(r=>r.kind===Ae.SyntaxKind.ExportKeyword):!1}function zn(e){if(!Ae.canHaveModifiers(e))return!1;const t=Ae.getModifiers(e);return t?t.some(r=>r.kind===Ae.SyntaxKind.DefaultKeyword):!1}function mt(e,t,r){const a=lr.createHash("sha256");return a.update(`${e}:${t}:${r}`),a.digest("hex").substring(0,40)}function Hi(e){var u;const{webapp:t,port:r,environmentVariables:a,packageManager:s}=e,o=t==null?void 0:t.startCommand;if(!o)return`${s} ${s==="npm"?"run ":""}dev`;const i=((u=o.args)==null?void 0:u.map(h=>h.replace(/\$PORT/g,String(r))))??[],l=[];for(const h of a)if(h.key&&h.value!==void 0){const m=String(h.value).replace(/'/g,"'\\''");l.push(`${h.key}='${m}'`)}if(o.env)for(const[h,m]of Object.entries(o.env)){const f=String(m).replace(/\$PORT/g,String(r)).replace(/'/g,"'\\''");l.push(`${h}='${f}'`)}const d=l.length>0?l.join(" ")+" ":"";return o.command==="sh"&&i[0]==="-c"&&i[1]?`${d}sh -c "${i[1]}"`:`${d}${o.command} ${i.join(" ")}`}function Vi(e,t){if(!t||t.length===0)return;if(t.length===1)return t[0];const r=X.normalize(e),a=[...t].sort((s,o)=>{var i,l;return(((i=o.path)==null?void 0:i.length)??0)-(((l=s.path)==null?void 0:l.length)??0)});for(const s of a){const o=X.normalize(s.path??".");if(o==="."||r.startsWith(o+X.sep)||r===o)return s}return t[0]}function Ji(e){const{filePath:t,webapps:r,environmentVariables:a,port:s,packageManager:o}=e;if(!r||r.length===0)throw new Error("No webapps configured. Please run CodeYam init again.");const i=Vi(t,r);if(!i)throw new Error("Could not find webapp for file path: "+t);const l=Hi({webapp:i,port:s,environmentVariables:a,packageManager:o});return{webapp:i,webappPath:i.path??".",framework:i.framework,packageManager:i.packageManager??o,startCommand:l,url:`http://localhost:${s}/static/codeyam-sample`}}function qt(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 Gi(e){const{jsonObjectFrom:t}=At();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 qi({ids:e,analysisId:t}){const r=ve();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 pe("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 pe("CodeYam Error: Database error deleting scenarios",a,{ids:e,analysisId:t}),a}}function Xn(...e){try{const t=lr.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 aa(e,t){return t.map(r=>Ki(e,r))}function Ki(e,t){return Je` ${Je.ref(e)}.${Je.ref(t)}`.as(t)}function Qi(e,t,r){return t.map(a=>Xi(e,a,r))}function Xi(e,t,r){return Je` ${Je.ref(e)}.${Je.ref(t)}`.as(`_cy_${r}:${t}`)}function Zi(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 el=50;function tl(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 sa({projectId:e,ids:t,fileIds:r,entityName:a,entityShas:s,commitIds:o,branchCommitSha:i,limit:l}){const d=ve(),{jsonObjectFrom:u,jsonArrayFrom:h}=At();let m=d.selectFrom("analyses").selectAll("analyses");if(e&&(m=m.where("project_id","=",e)),t){if(t.length===0)return null;m=m.where("id","in",t)}if(r){if(r.length===0)return null;m=m.where("file_id","in",r)}if(o){if(o.length===0)return null;m=m.where("commit_id","in",o)}return a&&(m=m.where("entity_name","=",a)),s&&(m=m.where("entity_sha","in",s)),i&&(m=m.where("branch_commit_sha","=",i)),l&&(m=m.limit(l)),d.with("filtered_analyses",()=>m).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(p=>[u(p.selectFrom("entities").select(aa("entities",Ja)).whereRef("entities.sha","=","filtered_analyses.entity_sha").limit(1)).as("entity"),h(p.selectFrom("scenarios").select(aa("scenarios",xr)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),h(p.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")])}async function vt(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:u}])=>(u==null?void 0:u.length)>0);let l=[];if(i){const[d,{arr:u,key:h}]=i,m=tl(u,el),p=[];for(let f=0;f<m.length;f++){const g=m[f],w=await sa({...e,[h]:g}).execute();w&&p.push(...w)}l=p}else{const u=await sa(e).execute();if(!u||u.length===0)return pe("CodeYam: No analyses found",null,e),null;l=u}return l.length===0?null:l.map(Xe)}catch(o){return pe("CodeYam Error: Database error in loadAnalyses",o,e),null}}function nl(e,t){const{jsonArrayFrom:r,jsonObjectFrom:a}=At();let s=e.selectFrom("analysis_branches").select(Si).select(o=>a(o.selectFrom("branches").select(Va).whereRef("id","=","analysis_branches.branch_id")).as("branch"));return t&&(s=t(s)),r(s)}async function rt({id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:s,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:d,includeProject:u,includeCommitAndBranch:h,includeScenarios:m,includeBranches:p}){const f=ve();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:w}=At();g=g.select(v=>{const b=[];return b.push(y(v.selectFrom("entities").select(Ja).whereRef("entities.sha","=","analyses.entity_sha")).as("entity")),d&&b.push(y(v.selectFrom("files").select(Ii).whereRef("files.id","=","analyses.file_id")).as("file")),u&&b.push(y(v.selectFrom("projects").select(Ci).whereRef("projects.id","=","analyses.project_id")).as("project")),m&&b.push(w(v.selectFrom("scenarios").select(xr).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")),p&&b.push(nl(v,N=>N.whereRef("analysis_branches.analysis_id","=","analyses.id")).as("analysis_branches")),h&&b.push(y(v.selectFrom("commits").select(_i).select(N=>Gi(N).as("author")).whereRef("commits.id","=","analyses.commit_id")).as("commit")),b});const x=await g.executeTakeFirst();return x?Xe(x):(pe("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:u,includeCommitAndBranch:h,includeScenarios:m,includeBranches:p}),null)}catch(g){return pe("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:u,includeCommitAndBranch:h,includeScenarios:m,includeBranches:p}),null}}async function Ka({projectId:e,ids:t,names:r,includeInactive:a}){const s=ve();try{let o=s.selectFrom("branches").selectAll("branches").where("project_id","=",e);if(t){if(t.length===0)return[];o=o.where("id","in",t)}if(r){if(r.length===0)return[];o=o.where("name","in",r)}return a||(o=o.where("active_at","is not",null)),(await o.execute()).map(Tt)}catch(o){return pe("CodeYam Error: Database error loading branches",o,{projectId:e,ids:t,names:r,includeInactive:a}),[]}}async function rl({projectId:e,commitId:t,branchId:r,active:a,includeBranches:s}){const o=ve();try{let i=o.selectFrom("commit_branches").selectAll("commit_branches").innerJoin("branches","commit_branches.branch_id","branches.id").$if(s,u=>u.select(Qi("branches",Va,"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(u=>Zi(u,"branch")).map(yr)}catch(i){return pe("CodeYam Error: Error loading commit branches",i,{projectId:e,commitId:t,branchId:r,active:a,includeBranches:s}),null}}async function al(e){if(e.length===0)return new Map;const t=ve();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 pe("CodeYam Error: Loading branches for commits",r,{commitIds:e}),new Map}}async function sl(e){if(e.length===0)return new Map;const t=ve(),{jsonObjectFrom:r,jsonArrayFrom:a}=At();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(xr).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 pe("CodeYam Error: Loading analyses for commits",s,{commitIds:e}),new Map}}async function ol(e){if(e.length===0)return new Map;const t=ve();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 pe("CodeYam Error: Loading entities for commits",r,{commitIds:e}),new Map}}async function yn({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=ve(),{jsonObjectFrom:l}=At();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=Je.join(s.map(w=>Je`${w}`),Je`, `);d=d.where(Je`
23
+ EXISTS (
24
+ SELECT 1
25
+ FROM json_each(${Je.ref("commits.files")}) AS f
26
+ WHERE json_extract(f.value, '$.fileName') IN (${y})
27
+ )
28
+ `)}t&&(d=d.where("branch_id","=",t));const u=await d.orderBy("committed_at","desc").limit(o).execute();if(!u||u.length===0)return[];const h=u.map(y=>y.id),[m,p,f]=await Promise.all([al(h),sl(h),ol(h)]);return u.map(y=>{const w=y.branch_id?m.get(y.branch_id):void 0,x=y.merged_branch_id?m.get(y.merged_branch_id):void 0,v=p.get(y.id)||[],b=f.get(y.id)||[];return{...y,branch:w,mergedBranch:x,analyses:v,entities:b}}).map(St)}catch(d){return pe("CodeYam Error: Database error loading commits",d,{projectId:e,branchId:t,ids:r,shas:a,limit:o}),[]}}async function wt({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 u=o.slice(d,d+50),h=await wt({projectId:e,branchId:t,fileIds:r,filePaths:a,names:s,shas:u});h&&l.push(...h)}return l}const i=ve();try{const d=await i.selectFrom("entities").selectAll("entities").$if(!!t,u=>u.innerJoin("entity_branches","entity_branches.entity_sha","entities.sha").where("entity_branches.branch_id","=",t)).$if(!!e,u=>u.where("entities.project_id","=",e)).$if(!!o,u=>u.where("entities.sha","in",o)).$if(!!a,u=>u.where("entities.file_path","in",a)).$if(!!s,u=>u.where("entities.name","in",s)).$if(!!r,u=>u.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(Jt)}catch(l){return console.log("Load Entities: Error occurred",l,{projectId:e,fileIds:r,filePaths:a,shas:o}),null}}function il(e,t){const{jsonArrayFrom:r}=At();let a=e.selectFrom("entity_branches").select(Mi);return t&&(a=t(a)),r(a)}async function Qa({projectId:e,sha:t}){const r=ve();try{const a=await r.selectFrom("entities").innerJoin("files","entities.file_id","files.id").selectAll("entities").select(s=>il(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?Jt(a):(process.env.CODEYAM_E2E_BASELINE_MODE!=="true"&&pe("CodeYam Error: Load Entity: Entity not found",null,{projectId:e,sha:t}),null)}catch(a){return pe("CodeYam Error: Load Entity: Database error",a,{projectId:e,sha:t}),null}}const Bn=1e3;async function Xa({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 u=t.slice(d,d+50),h=await Xa({projectId:e,filePaths:u,fileIds:r,fileNames:a});h&&l.push(...h)}return l}const s=ve(),o=[];let i=0;try{for(;;){let l=s.selectFrom("files").selectAll().where("project_id","=",e).limit(Bn).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<Bn))break;i+=Bn}return o==null?void 0:o.map(fr)}catch(l){return console.log("CodeYam Error: Error loading project files in loadFiles",l),null}}async function ll({id:e,slug:t,withBranches:r,withFiles:a,silent:s}){try{let i=ve().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=gr(l);return a&&(d.files=await Xa({projectId:d.id})),r&&(d.branches=await Ka({projectId:d.id,includeInactive:!1})),d}catch(o){return s||console.log("CodeYam Error: Error loading project",o),null}}function xn(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]=xn(o,s):s!==void 0&&(r[a]=s)}return r}async function Mt({commitId:e,commitSha:t,metadataUpdate:r,runStatusUpdate:a,archiveCurrentRun:s,updateCallback:o}){try{return await ve().transaction().execute(async i=>{var h,m;const l=await i.selectFrom("commits").selectAll().$if(!!e,p=>p.where("id","=",e)).$if(!!t,p=>p.where("sha","=",t)).executeTakeFirst();if(!l)return pe(`CodeYam Error: updateCommitMetadata(): Commit ${e} not found`),null;const d=l.metadata||{};if(a)a.lastUpdatedAt??(a.lastUpdatedAt=new Date().toISOString()),a.currentEntityShas!==void 0&&(console.log("[updateCommitMetadata] Updating currentRun.currentEntityShas"),console.log(`[updateCommitMetadata] Commit SHA: ${t}`),console.log("[updateCommitMetadata] Previous entity SHAs:",(h=d.currentRun)==null?void 0:h.currentEntityShas),console.log("[updateCommitMetadata] New entity SHAs:",a.currentEntityShas),console.log("[updateCommitMetadata] Archive flag:",s)),r=xn(r??{},{currentRun:a});else if(!r&&!o)return d;const u=r?xn(d,r):d;if(s&&u.currentRun){console.log("[updateCommitMetadata] ========================================"),console.log("[updateCommitMetadata] ARCHIVING CURRENT RUN"),console.log(`[updateCommitMetadata] Commit SHA: ${t}`),console.log("[updateCommitMetadata] Current run entity SHAs:",u.currentRun.currentEntityShas),console.log(`[updateCommitMetadata] Current run PIDs: analyzer=${u.currentRun.analyzerPid}, capture=${u.currentRun.capturePid}`),console.log(`[updateCommitMetadata] Current run completed: analyses=${u.currentRun.analysesCompleted}, captures=${u.currentRun.capturesCompleted}`),console.log(`[updateCommitMetadata] Historical runs before archiving: ${((m=u.historicalRuns)==null?void 0:m.length)||0}`);const p={...u.currentRun,archivedAt:new Date().toISOString()};console.log("[updateCommitMetadata] Run to archive:",JSON.stringify(p,null,2)),u.historicalRuns=[...u.historicalRuns||[],p],console.log(`[updateCommitMetadata] Historical runs after archiving: ${u.historicalRuns.length}`),console.log("[updateCommitMetadata] All historical runs:",JSON.stringify(u.historicalRuns.map(f=>({entityShas:f.currentEntityShas,archivedAt:f.archivedAt,completed:{analyses:f.analysesCompleted,captures:f.capturesCompleted}})),null,2)),console.log("[updateCommitMetadata] ========================================")}o&&await o(u,St(l));try{return await i.updateTable("commits").set({metadata:JSON.stringify(u)}).where("id","=",l.id).returningAll().executeTakeFirst()?u:(pe(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`),d)}catch(p){return pe(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`,p),d}})}catch(i){return pe(`CodeYam Error: updateCommitMetadata(): Transaction failed for commit ${e}`,i),null}}async function Za(e,t,r="analysis"){try{return await ve().transaction().execute(async a=>{const s=await a.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!s)return pe(`CodeYam Error: updateFreshAnalysisMetadata(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const o=Xe(s);return t(o.metadata,o),await a.updateTable("analyses").set({metadata:JSON.stringify(o.metadata)}).where("id","=",e).returningAll().executeTakeFirst()?o.metadata:(pe(`CodeYam Error: updateFreshAnalysisMetadata(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(a){return pe(`CodeYam Error: updateFreshAnalysisMetadata(): Transaction failed for analysis ${e} (source: ${r})`,a,{analysisId:e,source:r}),null}}async function Rt(e,t,r="capture"){try{return await ve().transaction().execute(async a=>{const s=await a.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!s)return pe(`CodeYam Error: updateFreshAnalysisStatus(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const o=Xe(s);return t(o.status,o),await a.updateTable("analyses").set({status:JSON.stringify(o.status)}).where("id","=",e).returningAll().executeTakeFirst()?o.status:(pe(`CodeYam Error: updateFreshAnalysisStatus(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(a){return pe(`CodeYam Error: updateFreshAnalysisStatus(): Transaction failed for analysis ${e} (source: ${r})`,a,{analysisId:e,source:r}),null}}async function cl({projectId:e,projectSlug:t,metadataUpdate:r,updateCallback:a}){if(!e&&!t)throw new Error("Either projectId or projectSlug must be provided");try{return await ve().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 pe(`CodeYam Error: updateProjectMetadata(): Project ${e} not found`),null;const i=o.metadata||{};if(!r&&!a)return i;const l=r?xn(i,r):i;a&&await a(l,gr(o));try{return await s.updateTable("projects").set({metadata:JSON.stringify(l)}).where("id","=",o.id).returningAll().executeTakeFirst()?l:(pe(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`),null)}catch(d){return pe(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`,d),null}})}catch(s){return pe(`CodeYam Error: updateProjectMetadata(): Transaction failed for project ${e}`,s),null}}function dl(e){const{id:t,projectId:r,commitId:a,fileId:s,filePath:o,entitySha:i,entityType:l,entityName:d,previousAnalysisId:u,entity:h,dependencyAnalyzedTreeSha:m,analyzedTreeSha:p,branchCommitSha:f,committedAt:g,completedAt:y,createdAt:w,updatedAt:x,metadata:v,status:b,commit:N,file:T,project:S,scenarios:A,analysisBranches:P,branches:I,...M}=e;return{...M,id:t??jt(),metadata:v?JSON.stringify(v):void 0,status:b?JSON.stringify(b):void 0,project_id:r,commit_id:a,file_id:s,file_path:o,entity_sha:i,entity_type:l,entity_name:d,previous_analysis_id:u,dependency_analyzed_tree_sha:m,analyzed_tree_sha:p,branch_commit_sha:f,committed_at:g,completed_at:y,created_at:w,updated_at:x}}async function es(e){if(!e||e.length===0)return[];const t=ve(),r=e.map(a=>{const s={...a,status:{...a.status,sha:Xn(JSON.stringify(a.status??{}))},metadata:{...a.metadata,sha:Xn(JSON.stringify(a.metadata??{}))}},o=dl(s);return delete o.created_at,o.updated_at||delete o.updated_at,o});try{return(await t.insertInto("analyses").values(r).onConflict(qt(r[0],"id",["created_at"])).returningAll().execute()).map(Xe)}catch(a){return pe("CodeYam Error: Database error upserting analyses",a,{analysisCount:e.length,analysisDetails:r.map(s=>({id:s.id,filePath:s.file_path,entityName:s.entity_name,dependencyAnalyzedTreeSha:s.dependency_analyzed_tree_sha,analyzedTreeSha:s.analyzed_tree_sha}))}),[]}}function ul(e){const{id:t,projectId:r,analysisId:a,previousVersionId:s,analysis:o,metadata:i,data:l,...d}=e;return delete d.userScenarios,delete d.comments,"created_at"in d&&delete d.created_at,{...d,id:t??jt(),metadata:i?JSON.stringify(i):null,project_id:r,analysis_id:a,previous_version_id:s}}async function ts(e){if(e.length===0)return[];const t=ve(),r=e.map(ul);try{return(await t.insertInto("scenarios").values(r).onConflict(qt(r[0],"id",["created_at"])).returningAll().execute()).map(Ha)}catch(a){return pe("CodeYam Error: Database error upserting scenarios",a,{scenarioCount:e.length}),null}}function hl(e){const{id:t,commitId:r,branchId:a,...s}=e;return delete s.commit,delete s.branch,{...s,id:t??jt(),commit_id:r,branch_id:a}}async function oa(e){if(e.length===0)return[];const t=ve(),r=e.map(hl);try{return(await t.insertInto("commit_branches").values(r).onConflict(qt(r[0],"id",["created_at"])).returningAll().execute()).map(yr)}catch(a){return pe("CodeYam Error: Database error upserting commit branches",a,{commitBranchCount:e.length,commitBranchIds:e.map(s=>s.id)}),[]}}async function ml(e,t){const r=ve(),a={username:e,avatar_url:t};try{return await r.insertInto("github_users").values(a).onConflict(qt(a,"username",[])).returningAll().executeTakeFirst()||null}catch(s){return pe("CodeYam Error: Error upserting github user",s,{username:e,avatarUrl:t}),null}}function pl(e,t){const{id:r,projectId:a,branchId:s,mergedBranchId:o,aiMessage:i,htmlUrl:l,analyzedAt:d,committedAt:u,author:h,metadata:m,files:p,...f}=e;return delete f.branch,delete f.mergedBranch,delete f.backgroundJob,delete f.analyses,delete f.parents,delete f.entities,delete f.commitBranches,{...f,id:r??jt(),project_id:a??String(t),metadata:m?JSON.stringify(m):void 0,files:p?JSON.stringify(p):void 0,branch_id:s,merged_branch_id:o,author_github_username:h==null?void 0:h.username,html_url:l,ai_message:i,analyzed_at:d,committed_at:u}}async function fl({projectId:e,commits:t}){const r=ve();try{const a=t.reduce((i,l)=>{const{author:d}=l;return d!=null&&d.username&&(d!=null&&d.avatarUrl)&&(i[d.username]=d.avatarUrl),i},{});for(const i in a)await ml(i,a[i]);const s=t.map(i=>pl(i,e));return(await r.insertInto("commits").values(s).onConflict(qt(s[0],"id",["created_at"])).returningAll().execute()).map(St)}catch(a){return pe("CodeYam Error: Error saving commits",a,{projectId:e,commitCount:t.length,commitIds:t.map(s=>s.id).filter(Boolean)}),[]}}const bn=X.join(Bo.homedir(),".codeyam","secrets.json"),vn=X.join(process.cwd(),".codeyam","secrets.json");async function Et(){let e={};try{if(q.existsSync(vn)){const o=await Ie.readFile(vn,"utf8");e=JSON.parse(o)}}catch{console.warn(fn.yellow("⚠ Could not read project secrets file, trying home directory"))}if(!e.OPENAI_API_KEY&&!e.ANTHROPIC_API_KEY)try{if(q.existsSync(bn)){const o=await Ie.readFile(bn,"utf8");e={...JSON.parse(o),...e}}}catch{console.warn(fn.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 gl(e,t=!0){const r=t?bn:vn,a=X.dirname(r);await Ie.mkdir(a,{recursive:!0}),await Ie.writeFile(r,JSON.stringify(e,null,2)),await Ie.chmod(r,384)}function yl(e=!0){return e?bn:vn}async function ia(){const e=await Et(),t=[];for(const r of t)e[r];return{isValid:!0,missing:[],secrets:e}}async function xl(e){console.log(),console.log(fn.blue("ℹ Configuration needed")),console.log();const t={};for(const r of e)switch(r){case"OPENAI_API_KEY":const a=await Uo({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 bl(e=!0){const t=await ia();if(t.isValid)return t.secrets;const r=await xl(t.missing),s={...await Et(),...r};await gl(s,e);const o=yl(e);return console.log(fn.green(`✓ Configuration saved to ${o}`)),(await ia()).secrets}function ns(e=process.cwd()){let t=X.resolve(e);const r=X.parse(t).root;for(;t!==r;){const s=X.join(t,".codeyam","config.json");if(q.existsSync(s))return t;t=X.dirname(t)}const a=X.join(r,".codeyam","config.json");return q.existsSync(a)?r:null}let rs=ns();function ye(){return rs}function vl(e){rs=e}function as(e){const t={...e};for(const r in e)if(r.includes(".")){const a=r.replace(/\./g,"");t[a]=e[r]}return t}const wl={"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>`};as(wl);const Cl={"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>`};as(Cl);function Yt(e,t,r=new WeakSet){if(!t)return e;if(!e)return t;try{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference detected during deep merge");r.add(t)}if(Array.isArray(t)){const s=Array.isArray(e)?e:[],o=[];for(let i=0;i<t.length;i++){const l=t[i];l&&typeof l=="object"&&!Array.isArray(l)||Array.isArray(l)?o[i]=Yt(s[i],l,r):o[i]=l}return o}const a={...e};for(const s in t)if(t[s]===null)a[s]=null;else if(Array.isArray(t[s])){const o=Array.isArray(e[s])?e[s]:[];a[s]=[];for(let i=0;i<t[s].length;i++){const l=t[s][i];typeof l=="object"&&l!==null?a[s][i]=Yt(o[i],l,r):a[s][i]=l}}else typeof t[s]=="object"&&t[s]!==null?a[s]=Yt(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 Nl({projectId:e,commit:t,branch:r}){var l,d,u,h,m,p,f;let a;const s={commitId:t.id,branchId:r.id,active:!0},o=await rl({projectId:e,commitId:t.id,includeBranches:!0});if(o&&o.length>0){a=(l=o.sort((y,w)=>{var x,v,b,N;return(((v=(x=y.branch.metadata)==null?void 0:x.permanent)==null?void 0:v.order)??999)-(((N=(b=w.branch.metadata)==null?void 0:b.permanent)==null?void 0:N.order)??999)})[0])==null?void 0:l.branch,a&&((u=(d=r.metadata)==null?void 0:d.permanent)==null?void 0:u.order)!==void 0&&(((m=(h=r.metadata)==null?void 0:h.permanent)==null?void 0:m.order)<=((f=(p=a.metadata)==null?void 0:p.permanent)==null?void 0:f.order)?a=r:s.active=!1);const g=o.filter(y=>y.active&&y.branch.id!==a.id||!y.active&&y.branch.id===a.id);g.length>0&&await oa(g.map(y=>({...y,active:y.branchId===a.id})))}(o==null?void 0:o.find(g=>g.branchId===s.branchId))||await oa([s])}function _t(){if(process.env.SQLITE_PATH)return process.env.SQLITE_PATH;const e=ye();if(!e)throw new Error("Could not find project root. Please run this command inside a CodeYam project.");return be.join(e,".codeyam","db.sqlite3")}async function Oe(){const e=await bl();process.env.SQLITE_PATH=_t(),e.OPENAI_API_KEY&&(process.env.OPENAI_API_KEY=e.OPENAI_API_KEY)}async function Ue(e){await Oe();const t=await ll({slug:e});if(!t)throw new Error(`Project with slug "${e}" not found in database`);const r=await Ka({projectId:t.id,names:["_local"]}),a=r==null?void 0:r[0];if(!a)throw new Error(`Local development branch not found for project "${e}". Please run "codeyam init" to set up local analysis.`);return{project:t,branch:a}}async function Sl(e,t,r){await Oe();const a=Xn(`${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 fl({projectId:e.id,commits:[s]});if(!o||o.length===0)throw new Error("Failed to create fake commit");return await Nl({projectId:e.id,commit:o[0],branch:t}),o[0]}async function Kt(){await Oe();const e=await wt({});if(!e||e.length===0)return e;const t=e.filter(l=>{var d;return!((d=l.metadata)!=null&&d.isSuperseded)}),r=t.map(l=>l.sha),a=t.map(l=>{var d;return(d=l.metadata)==null?void 0:d.previousVersionWithAnalyses}).filter(l=>!!l),s=[...new Set([...r,...a])],o=await vt({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=>{var h;const d=i.get(l.sha)||[];if(d.length>0)return{...l,analyses:d};const u=(h=l.metadata)==null?void 0:h.previousVersionWithAnalyses;if(u){const m=i.get(u)||[];return{...l,analyses:m}}return{...l,analyses:[]}})}async function Pn(e,t){await Oe();const r=await vt({entityShas:[e],limit:1});if(r&&r.length>0&&t){const a=await Qa({projectId:r[0].projectId,sha:e});if(a)for(const s of r)s.entity=a}return r||[]}async function br(e){await Oe();const t=await vt({entityShas:[e.sha],limit:1});if(t&&t.length>0)return t[0];if(e.name&&e.projectId){const r=await vt({projectId:e.projectId,entityName:e.name,limit:10});if(r&&r.length>0){const a=r.filter(o=>{const i=o.scenarios&&o.scenarios.length>0,l=!e.filePath||o.filePath===e.filePath;return i&&l});if(a.length>0)return a[0];const s=r.find(o=>o.scenarios&&o.scenarios.length>0);if(s)return s}}return null}async function Ct(e){await Oe();const t=await Fe();if(!t)return null;const{project:r}=await Ue(t);return await Qa({projectId:r.id,sha:e})}async function ss(e){var a,s,o,i,l,d,u,h;await Oe();const t=[],r=[];if((a=e.metadata)!=null&&a.importedExports&&e.metadata.importedExports.length>0){const m=e.metadata.importedExports;for(const p of m){if(!p.filePath||!p.name)continue;const f=await wt({projectId:e.projectId,filePaths:[p.filePath],names:[p.name]});if(f&&f.length>0){const g=f[0],y=await vt({entityShas:[g.sha],limit:1});let w,x,v;if(y&&y.length>0&&y[0].scenarios){const b=y[0],N=b.scenarios||[],T=N.length,S=N.find(P=>{var I,M;return(M=(I=P.metadata)==null?void 0:I.screenshotPaths)==null?void 0:M[0]});S&&(w=(o=(s=S.metadata)==null?void 0:s.screenshotPaths)==null?void 0:o[0],x=S.name),v={status:((i=g.metadata)==null?void 0:i.previousVersionWithAnalyses)||b.entitySha!==g.sha?"out_of_date":"up_to_date",scenarioCount:T,timestamp:b.createdAt?new Date(b.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else v={status:"not_analyzed"};t.push({...g,screenshotPath:w,scenarioName:x,analysisStatus:v})}}}if((l=e.metadata)!=null&&l.importedBy){const m=[];for(const p in e.metadata.importedBy)for(const f in e.metadata.importedBy[p]){const g=e.metadata.importedBy[p][f];g.shas&&m.push(...g.shas)}if(m.length>0){const p=await wt({projectId:e.projectId,shas:m});if(p)for(const f of p){const g=await vt({entityShas:[f.sha],limit:1});let y,w,x;if(g&&g.length>0&&g[0].scenarios){const v=g[0],b=v.scenarios||[],N=b.length,T=b.find(A=>{var P,I;return(I=(P=A.metadata)==null?void 0:P.screenshotPaths)==null?void 0:I[0]});T&&(y=(u=(d=T.metadata)==null?void 0:d.screenshotPaths)==null?void 0:u[0],w=T.name),x={status:((h=f.metadata)==null?void 0:h.previousVersionWithAnalyses)||v.entitySha!==f.sha?"out_of_date":"up_to_date",scenarioCount:N,timestamp:v.createdAt?new Date(v.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else x={status:"not_analyzed"};r.push({...f,screenshotPath:y,scenarioName:w,analysisStatus:x})}}}return{importedEntities:t,importingEntities:r}}async function Fe(){try{const e=ye();if(!e)return null;const t=be.join(e,".codeyam","config.json");return JSON.parse(await Te.readFile(t,"utf8")).projectSlug||null}catch(e){return console.error("[getProjectSlug] Error:",e),null}}async function Pt(){await Oe();try{const e=await Fe();if(!e)return null;const{project:t,branch:r}=await Ue(e),a=await yn({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 vr(){try{const e=ye();if(!e)return null;const t=be.join(e,".codeyam","config.json");return JSON.parse(await Te.readFile(t,"utf8"))}catch(e){return console.error("[getProjectConfig] Error:",e),null}}async function os(e){try{const t=ye();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=be.join(t,e.filePath);return await Te.readFile(r,"utf8")}catch(t){return console.error("[getEntityCodeFromFilesystem] Error reading file:",t),null}}async function is(e){if(await Oe(),!e.filePath||!e.name||!e.projectId)return console.error("[getEntityHistory] Entity missing required fields (filePath, name, or projectId)"),[];const t=await wt({projectId:e.projectId,filePaths:[e.filePath],names:[e.name]});if(!t||t.length===0)return[];const r=t.map(i=>i.sha),a=await vt({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,u)=>{const h=new Date(d.createdAt||0).getTime();return new Date(u.createdAt||0).getTime()-h});const o=t.map(i=>({...i,analyses:s.get(i.sha)||[]}));return o.sort((i,l)=>{var h,m;const d=((h=i.analyses[0])==null?void 0:h.createdAt)||i.createdAt||"",u=((m=l.analyses[0])==null?void 0:m.createdAt)||l.createdAt||"";return new Date(u).getTime()-new Date(d).getTime()}),o}async function ls(e){try{const t=ye();if(!t)return console.error("[updateProjectConfig] No project root found"),!1;const r=be.join(t,".codeyam","config.json"),a=await Te.readFile(r,"utf8"),s=JSON.parse(a),o={...s,...e},i=JSON.stringify(o,null,2);if(await Te.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 cl({projectSlug:s.projectSlug,metadataUpdate:l})}return!0}catch(t){return console.error("[updateProjectConfig] Error:",t),!1}}const Al=Object.freeze(Object.defineProperty({__proto__:null,getAllEntities:Kt,getAnalysesForEntity:Pn,getCurrentCommit:Pt,getEntityBySha:Ct,getEntityCodeFromFilesystem:os,getEntityHistory:is,getLatestAnalysisForEntity:br,getProjectConfig:vr,getProjectSlug:Fe,getRelatedEntities:ss,updateProjectConfig:ls},Symbol.toStringTag,{value:"Module"})),cs="secrets.json";function ds(e){return be.join(e,".codeyam",cs)}function us(){return be.join(Qn.homedir(),".codeyam",cs)}async function kn(e){let t={};try{const r=us(),a=await Te.readFile(r,"utf-8");t=JSON.parse(a)}catch{}try{const r=ds(e),a=await Te.readFile(r,"utf-8"),s=JSON.parse(a);t={...t,...s}}catch{}return t}async function El(e,t,r=!0){const a=r?us():ds(e),s=be.dirname(a);await Te.mkdir(s,{recursive:!0}),await Te.writeFile(a,JSON.stringify(t,null,2)+`
29
+ `,"utf-8")}async function _l(e){const t=await kn(e);return!!(t.ANTHROPIC_API_KEY&&t.ANTHROPIC_API_KEY.length>0)||!!(t.OPENAI_API_KEY&&t.OPENAI_API_KEY.length>0)||!!(t.GROQ_API_KEY&&t.GROQ_API_KEY.length>0)||!!(t.OPENROUTER_API_KEY&&t.OPENROUTER_API_KEY.length>0)}const Pl="/assets/globals-C9s7Lhdl.css";function kl({text:e,subtext:t,linkText:r,linkTo:a}){const[s,o]=j(!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(ce,{to:a,className:"shrink-0 px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded hover:bg-blue-700 transition-colors",children:r})]}),n("button",{type:"button",onClick:()=>o(!0),className:"shrink-0 ml-4 p-1 rounded text-blue-600 hover:text-blue-800 hover:bg-blue-100 transition-colors cursor-pointer","aria-label":"Dismiss banner",children:n("svg",{className:"w-5 h-5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M6 18L18 6M6 6l12 12"})})})]})})}function wn(e){return X.join(e,".codeyam","queue.json")}function zt(e){const t=wn(e);if(!q.existsSync(t))return{paused:!1,jobs:[]};try{const r=q.readFileSync(t,"utf8");return JSON.parse(r)}catch(r){return console.error("Failed to load queue state:",r),{paused:!1,jobs:[]}}}function Ml(e,t){const r=wn(e),a=X.dirname(r);q.existsSync(a)||q.mkdirSync(a,{recursive:!0});try{q.writeFileSync(r,JSON.stringify(t,null,2),"utf8")}catch(s){throw console.error("Failed to save queue state:",s),s}}async function Tl({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}/`,u=t.endsWith("/")?t:`${t}/`,h=["-a"];a||h.push("--delete","--force"),h.push(...o);for(const f of r)h.push(`--exclude=${f}`);h.push(d,u);const m=Date.now(),p=cr("rsync",h);p.on("exit",f=>{if(f===0){if(!s){const g=((Date.now()-m)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${g}s]`)}i()}else l(new Error(`rsync failed with exit code ${f}`))}),p.on("error",f=>{s||console.log("Error occurred:",f),l(f)})})}const Il=ur(dr);async function jl(e){return new Promise(t=>setTimeout(t,e))}function $l(e){try{return process.kill(e,0),!0}catch{return!1}}async function hs(e){try{const{stdout:t}=await Il(`ps -A -o pid=,ppid= | awk '$2 == ${e} { print $1 }'`),r=t.trim().split(`
30
+ `).filter(s=>s.trim()).map(s=>parseInt(s.trim(),10)).filter(s=>!isNaN(s)),a=[...r];for(const s of r){const o=await hs(s);a.push(...o)}return a}catch{return[]}}function la(e,t,r){try{process.kill(e,t)}catch(a){r==null||r(`Error sending ${t} to process ${e}: ${a}`)}}async function Rl(e,t,r){const a=await hs(e);for(const s of a.reverse())await la(s,t,r);await la(e,t,r)}async function Cn(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 Rl(e,o,t);for(let l=0;l<i;l++)if(await jl(1e3),a+=1e3,!await $l(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 Dl(e){const t=new Date().toISOString();e.currentRun&&(e.currentRun.archivedAt=t,e.historicalRuns??(e.historicalRuns=[]),e.historicalRuns.push(e.currentRun)),e.currentRun={id:ti(),createdAt:t}}Wo.config({quiet:!0});var ms=(e=>(e.Server="server",e.Analyzer="analyzer",e.Capture="capture",e.Controller="controller",e.Worker="worker",e.Project="project",e.Other="other",e))(ms||{});class Ll extends Ho{constructor(){super(...arguments),this.processes=new Map}register(t){const r=Jo(),{process:a,type:s,name:o,metadata:i,parentId:l}=t,d={id:r,type:s,name:o,pid:a.pid,state:"running",startedAt:Date.now(),metadata:i,parentId:l,children:[]};if(this.processes.set(r,{info:d,process:a}),l){const m=this.processes.get(l);m&&(m.info.children=m.info.children||[],m.info.children.push(r))}const u=(m,p)=>{this.handleProcessExit(r,m,p)},h=m=>{this.handleProcessError(r,m)};return a.on("exit",u),a.on("error",h),a.__cleanup=()=>{a.removeListener("exit",u),a.removeListener("error",h)},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 Cn(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 Un=null;function Ol(){return Un||(Un=new Ll),Un}const Fl={stdoutToConsole:!0,stdoutToFile:!0,stderrToConsole:!0,stderrToFile:!0};function Yl({command:e,args:t,workingDir:r,outputOptions:a=Fl,processName:s,env:o}){const i={...process.env,...o||{},CODEYAM_PROCESS_NAME:`codeyam-${s}`},l=cr(e,t,{cwd:r,env:i});return Ol().register({process:l,type:ms.Other,name:s,metadata:{command:e,args:t,workingDir:r}}),{promise:new Promise(h=>{const m=f=>{const g=be.join(r,"log.txt");q.appendFile(g,f,y=>{y&&console.log("Error writing to log file:",y)})},p=(f,g="")=>{const y=new Date().toLocaleString();return f.split(`
31
+ `).map(x=>x.trim()?`[${y}]${g} ${x}`:x).join(`
32
+ `)};l.stdout.on("data",function(f){const g=(f==null?void 0:f.toString())??"",y=p(g);a.stdoutToConsole&&console.log(y),a.stdoutToFile&&m(y+`
33
+ `),a.stdoutCallback&&a.stdoutCallback(g)}),l.stderr.on("data",function(f){const g=(f==null?void 0:f.toString())??"",y=p(g,"<STDERR>");a.stderrToConsole&&console.error(y),a.stderrToFile&&m(y+`
34
+ `),a.stderrCallback&&a.stderrCallback(g)}),l.on("exit",function(f){h(f)})}),process:l}}function zl(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 Bl({absoluteCodeyamRootPath:e,startEnv:t,startArgs:r,outputOptions:a}){const s=Object.entries(t).map(([i,l])=>`${i}=${l}`).join(`
35
+ `);q.writeFileSync(`${e}/.env`,s);const o=zl(r);return Yl({command:"node",args:["--enable-source-maps","./dist/project/start.js",...o],workingDir:e,outputOptions:a,processName:"analyzer",env:t})}const Ul="/tmp/codeyam/local-dev";function ps(e){return X.join(Ul,e)}function fs(e){return X.join(ps(e),"codeyam")}function dt(e){return X.join(ps(e),"project")}function Mn(e){return X.join(fs(e),"log.txt")}const Wl=[".sync-metadata.json","__codeyamMocks__"];async function Hl(e,t={}){const{port:r,silent:a=!0}=t,s=dt(e);if(r)try{Me(`lsof -ti:${r} | xargs kill -9 2>/dev/null || true`,{stdio:a?"ignore":"inherit"})}catch{}try{Me(`lsof +D "${s}" 2>/dev/null | grep node | awk '{print $2}' | xargs kill -9 2>/dev/null || true`,{stdio:a?"ignore":"inherit"})}catch{}await new Promise(o=>setTimeout(o,500))}async function Vl(e,t={}){const{killProcesses:r=!0,port:a,silent:s=!0}=t,o=dt(e),i=[],l=[];if(!q.existsSync(o))return{removed:i,errors:l};r&&await Hl(e,{port:a,silent:s});for(const d of Wl){const u=X.join(o,d);if(q.existsSync(u))try{(await Ie.stat(u)).isDirectory()?await Ie.rm(u,{recursive:!0,force:!0}):await Ie.unlink(u),i.push(d)}catch(h){l.push(`${d}: ${h instanceof Error?h.message:String(h)}`)}}return{removed:i,errors:l}}const Jl=X.dirname(Fa(import.meta.url));function Gl(e){let t=e;for(;t!==X.dirname(t);){const r=X.join(t,"package.json");if(q.existsSync(r))try{if(JSON.parse(q.readFileSync(r,"utf8")).name==="@codeyam/codeyam-cli")return t}catch{}t=X.dirname(t)}throw new Error("Could not find @codeyam/codeyam-cli package root")}function wr(){const e=Gl(Jl);return X.join(e,"analyzer-template")}function Dt(e){return fs(e)}async function ca(e){const t=wr(),r=Dt(e);if(!q.existsSync(t))throw new Error(`Analyzer template not found at ${t}. Did the build process complete successfully?`);await Ie.mkdir(X.dirname(r),{recursive:!0}),await Tl({sourcePath:t,destinationPath:r,silent:!0})}function Qt(e,t,r,a){const s=Dt(e);if(!q.existsSync(s))throw new Error(`Analyzer not found at ${s}. The analyzer template may not be initialized. Try running 'codeyam init' or contact support if the issue persists.`);const o=void 0;return Bl({absoluteCodeyamRootPath:s,startEnv:t,startArgs:r,outputOptions:{stdoutToConsole:!1,stdoutToFile:!0,stdoutCallback:o,stderrToConsole:!1,stderrToFile:!0,stderrCallback:o}})}function ql(e){const t=wr(),r=Dt(e),a=X.join(t,".build-info.json"),s=X.join(r,".build-info.json");if(!q.existsSync(a))return{isFresh:!1,reason:"Template build marker missing - template may be corrupted"};if(!q.existsSync(r))return{isFresh:!1,reason:"Cached analyzer does not exist"};if(!q.existsSync(s))return{isFresh:!1,reason:"Cached analyzer build marker missing - was created with old version"};try{const o=JSON.parse(q.readFileSync(a,"utf8")),i=JSON.parse(q.readFileSync(s,"utf8"));return o.buildTime>i.buildTime?{isFresh:!1,reason:`Template is newer (${o.buildTimestamp}) than cached version (${i.buildTimestamp})`}:{isFresh:!0}}catch(o){return{isFresh:!1,reason:`Error reading build markers: ${o.message}`}}}async function Tn(e,t){const r=Dt(e);if(!q.existsSync(r)){t.update("Creating analyzer..."),await ca(e);return}const a=ql(e);a.isFresh||(t.update(`Updating analyzer (${a.reason})...`),await ca(e))}async function gs(e){await Vl(e,{killProcesses:!1})}const Kl=X.dirname(Fa(import.meta.url));function ys(){let e=Kl;for(;e!==X.dirname(e);){const t=X.join(e,"package.json");if(q.existsSync(t))try{if(JSON.parse(q.readFileSync(t,"utf8")).name==="@codeyam/codeyam-cli")return e}catch{}e=X.dirname(e)}return null}function Ql(){const e=ys();return e?X.join(e,"package.json"):null}function dn(e){if(!q.existsSync(e))return null;try{return JSON.parse(q.readFileSync(e,"utf8"))}catch{return null}}function xs(e){let t="unknown";const r=ys(),a=Ql();if(a)try{t=JSON.parse(q.readFileSync(a,"utf8")).version||"unknown"}catch{}let s=null;if(r){const h=[X.join(r,"src/webserver/build-info.json"),X.join(r,"codeyam-cli/src/webserver/build-info.json")];for(const m of h)if(s=dn(m),s)break}const o=wr(),i=X.join(o,".build-info.json"),l=dn(i);let d=null;if(e){const h=Dt(e),m=X.join(h,".build-info.json");d=dn(m)}let u=!1;return l&&d?u=l.buildTime>d.buildTime:l&&!d&&e&&(u=!0),{cliVersion:t,webserverVersion:s,templateVersion:l,cachedAnalyzerVersion:d,isCacheStale:u}}function Cr(e){const t=Dt(e),r=X.join(t,".build-info.json"),a=dn(r);return(a==null?void 0:a.version)??null}async function Xl(e,t,r){console.log(`[Queue] Executing job ${e.id} (${e.type})`);try{if(e.type==="analysis")await Zl(e,t,r);else if(e.type==="recapture")await ec(e,t,r);else if(e.type==="capture-only")await tc(e,t,r);else if(e.type==="debug-setup")await nc(e,t,r);else if(e.type==="interactive-start")await rc(e,t,r);else if(e.type==="interactive-stop")await ac(e,t,r);else throw new Error(`Unknown job type: ${e.type}`);console.log(`[Queue] Job ${e.id} completed successfully`)}catch(a){throw console.error(`[Queue] Job ${e.id} failed:`,a),a}}async function Zl(e,t,r){var y,w,x,v;const{projectSlug:a,commitSha:s,entityShas:o}=e;if(!s)throw new Error("Analysis job missing commitSha");const i=o||[],{project:l}=await Ue(a);await gs(a),await Tn(a,{update:b=>console.log(`[Queue] ${b}`)});const d=Cr(a),u={...await Et(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:s,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:_t(),...i.length>0?{ENTITY_SHAS:i.join(",")}:{},...e.onlyDataStructure?{ONLY_DATA_STRUCTURE:"true"}:{},...d?{ANALYZER_VERSION:d}:{}},h=(w=(y=l.metadata)==null?void 0:y.webapps)==null?void 0:w[0];if(!h)throw new Error("No webapps found in project metadata");const m=e.onlyDataStructure,p={packageManager:((x=l.metadata)==null?void 0:x.packageManager)||"npm",absoluteProjectRootPath:dt(a),port:0,noServer:!0,framework:h.framework,...m?{}:{orchestrateCapture:"local-sequential"}},f=Qt(a,u,p),g=b=>{try{return process.kill(b,0),!0}catch{return!1}};await Mt({commitSha:s,runStatusUpdate:{currentEntityShas:i,entityCount:i.length||((v=e.filePaths)==null?void 0:v.length)||0,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString(),analyzerPid:f.process.pid}}),r==null||r.notifyChange("commit");try{try{const b=new Promise((N,T)=>setTimeout(()=>T(new Error("Analysis timed out after 60 minutes")),36e5));await Promise.race([f.promise,b]),await Mt({commitSha:s,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),await Mt({commitSha:s,runStatusUpdate:{currentEntityShas:[]}}),r==null||r.notifyChange("commit"),await new Promise(N=>setTimeout(N,2e3))}finally{if(f.process.pid)try{g(f.process.pid)&&await Cn(f.process.pid,()=>{})}catch{}}}catch(b){if(console.error(`[Queue] Analysis job ${e.id} failed:`,b),f.process.pid&&g(f.process.pid))try{await Cn(f.process.pid,()=>{})}catch{}try{await Mt({commitSha:s,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:b instanceof Error?b.message:String(b)}}),r==null||r.notifyChange("commit")}catch(N){console.error("[Queue] Failed to update commit metadata after job failure:",N)}throw b}}async function ec(e,t,r){var f,g,y,w;const{projectSlug:a,analysisId:s,scenarioId:o,defaultWidth:i}=e;if(!s)throw new Error("Recapture job missing analysisId");const l=await rt({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!l||!l.commit)throw new Error(`Analysis ${s} not found`);if(i){const{getDatabase:x}=await import("./index-CU58-Ttc.js"),v=x(),b=await v.selectFrom("entities").select(["metadata"]).where("sha","=",l.entitySha).executeTakeFirst();let N={};b!=null&&b.metadata&&(typeof b.metadata=="string"?N=JSON.parse(b.metadata):N=b.metadata),N.defaultWidth=i,await v.updateTable("entities").set({metadata:JSON.stringify(N)}).where("sha","=",l.entitySha).execute()}await Rt(s,x=>{if(x.readyToBeCaptured=!0,x.scenarios)for(const v of x.scenarios)(!o||v.name===o)&&(delete v.finishedAt,delete v.startedAt,delete v.screenshotStartedAt,delete v.screenshotFinishedAt,delete v.interactiveStartedAt,delete v.interactiveFinishedAt,delete v.error,delete v.errorStack);delete x.finishedAt});const{project:d}=await Ue(a);await Tn(a,{update:x=>console.log(`[Queue] ${x}`)});const u=Cr(a),h={...await Et(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:l.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:_t(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:s,...o?{SCENARIO_IDS:o}:{},...u?{ANALYZER_VERSION:u}:{}},m={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:dt(a),port:void 0,noServer:!0,framework:((w=(y=(g=d.metadata)==null?void 0:g.webapps)==null?void 0:y[0])==null?void 0:w.framework)??Gt.Next,orchestrateCapture:"local-sequential"},p=Qt(a,h,m);try{await p.promise}finally{try{p.process.kill("SIGTERM")}catch{}}}async function tc(e,t,r){var f,g,y,w;const{projectSlug:a,analysisId:s,scenarioId:o,defaultWidth:i}=e;if(!s)throw new Error("Capture-only job missing analysisId");const l=await rt({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!l||!l.commit)throw new Error(`Analysis ${s} not found`);if(i){const{getDatabase:x}=await import("./index-CU58-Ttc.js"),v=x(),b=await v.selectFrom("entities").select(["metadata"]).where("sha","=",l.entitySha).executeTakeFirst();let N={};b!=null&&b.metadata&&(typeof b.metadata=="string"?N=JSON.parse(b.metadata):N=b.metadata),N.defaultWidth=i,await v.updateTable("entities").set({metadata:JSON.stringify(N)}).where("sha","=",l.entitySha).execute()}await Rt(s,x=>{if(x.readyToBeCaptured=!0,x.scenarios)for(const v of x.scenarios)(!o||v.name===o)&&(delete v.finishedAt,delete v.startedAt,delete v.screenshotStartedAt,delete v.screenshotFinishedAt,delete v.interactiveStartedAt,delete v.interactiveFinishedAt,delete v.error,delete v.errorStack);delete x.finishedAt});const{project:d}=await Ue(a);await Tn(a,{update:x=>console.log(`[Queue] ${x}`)});const u=Cr(a),h={...await Et(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:l.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:_t(),READY_TO_BE_CAPTURED:"true",CAPTURE_ONLY:"true",ANALYSIS_IDS:s,...o?{SCENARIO_IDS:o}:{},...u?{ANALYZER_VERSION:u}:{}},m={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:dt(a),port:void 0,noServer:!0,fast:!0,framework:((w=(y=(g=d.metadata)==null?void 0:g.webapps)==null?void 0:y[0])==null?void 0:w.framework)??Gt.Next,orchestrateCapture:"local-sequential"},p=Qt(a,h,m);try{await p.promise}finally{try{p.process.kill("SIGTERM")}catch{}}}async function nc(e,t,r){var p,f,g,y;const{projectSlug:a,analysisId:s,scenarioId:o}=e;if(!s)throw new Error("Debug setup job missing analysisId");const i=await rt({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${s} not found`);const{project:l}=await Ue(a);await gs(a),await Tn(a,{update:w=>console.log(`[Queue] ${w}`)});const d={...await Et(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:_t(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:s,PREP_ONLY:"true"};o&&(d.SCENARIO_IDS=o);const u={packageManager:((p=l.metadata)==null?void 0:p.packageManager)||"npm",absoluteProjectRootPath:dt(a),port:void 0,noServer:!1,framework:((y=(g=(f=l.metadata)==null?void 0:f.webapps)==null?void 0:g[0])==null?void 0:y.framework)||Gt.Next},m=await Qt(a,d,u).promise;if(m!==0)throw new Error(`Prep process exited with code ${m}`)}async function rc(e,t,r){var m,p,f,g;const{projectSlug:a,analysisId:s,scenarioId:o}=e;if(!s)throw new Error("Interactive start job missing analysisId");const i=await rt({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${s} not found`);const{project:l}=await Ue(a),d={...await Et(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:_t(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:s,INTERACTIVE_MODE:"true"};o&&(d.SCENARIO_IDS=o);const u={packageManager:((m=l.metadata)==null?void 0:m.packageManager)||"npm",absoluteProjectRootPath:dt(a),port:void 0,noServer:!1,framework:((g=(f=(p=l.metadata)==null?void 0:p.webapps)==null?void 0:f[0])==null?void 0:g.framework)||Gt.Next};await Rt(s,y=>{y.readyToBeCaptured=!0});const h=Qt(a,d,u);await Za(s,y=>{y.interactiveMode={pid:h.process.pid,startedAt:new Date().toISOString(),jobId:e.id}}),console.log(`[Queue] Interactive mode started for analysis ${s}, PID: ${h.process.pid}`)}async function ac(e,t,r){var d;const{projectSlug:a,analysisId:s}=e;if(!s)throw new Error("Interactive stop job missing analysisId");const o=await rt({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!o)throw new Error(`Analysis ${s} not found`);const i=(d=o.metadata)==null?void 0:d.interactiveMode;if(!(i!=null&&i.pid)){console.log(`[Queue] No interactive mode process found for analysis ${s}`);return}const l=i.pid;console.log(`[Queue] Stopping interactive mode for analysis ${s}, killing PID: ${l}`);try{try{process.kill(l,0)}catch{console.log(`[Queue] Process ${l} already exited`);return}await Cn(l,()=>{}),console.log(`[Queue] Successfully killed interactive mode process ${l}`)}catch(u){throw console.error(`[Queue] Failed to kill process ${l}:`,u),u}finally{await Za(s,u=>{u.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:[]},r&&(typeof r=="function"?this.notifier={notifyChange:()=>r()}:this.notifier=r)}start(){this.state=zt(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||jt(),a={...t,id:r,queuedAt:new Date().toISOString()};this.state.jobs.push(a),this.save(),console.log(`[Queue] Enqueued job ${r} (${a.type})`);const s=new Promise((o,i)=>{this.completionCallbacks.set(r,l=>{l?i(l):o()})});return this.state.paused||this.processNext().catch(o=>{console.error("[Queue] ERROR in processNext():",o)}),{jobId:r,completion:s}}resume(){console.log("[Queue] Resuming queue"),this.state.paused=!1,this.save(),this.processNext()}pause(){console.log("[Queue] Pausing queue"),this.state.paused=!0,this.save()}getState(){return{...this.state}}getJobResult(t){return this.completedJobs.get(t)}removeJob(t){const r=this.state.jobs.length;this.state.jobs=this.state.jobs.filter(s=>s.id!==t);const a=this.state.jobs.length<r;if(a){console.log(`[Queue] Removed job ${t}`),this.save();const s=this.completionCallbacks.get(t);s&&(setImmediate(()=>s(new Error("Job cancelled by user"))),this.completionCallbacks.delete(t))}else console.log(`[Queue] Job ${t} not found in queue`);return a}clearQueue(){const t=this.state.jobs.length;return t===0?0:(this.state.jobs.forEach(r=>{const a=this.completionCallbacks.get(r.id);a&&(setImmediate(()=>a(new Error("Job cancelled by user"))),this.completionCallbacks.delete(r.id))}),this.state.jobs=[],console.log(`[Queue] Cleared ${t} jobs`),this.save(),t)}reorderJob(t,r){const a=this.state.jobs.findIndex(i=>i.id===t);if(a===-1)return console.log(`[Queue] Job ${t} not found in queue`),!1;const s=r==="up"?a-1:a+1;if(s<0||s>=this.state.jobs.length)return console.log(`[Queue] Cannot move job ${t} ${r}: at boundary`),!1;const o=this.state.jobs[a];return this.state.jobs[a]=this.state.jobs[s],this.state.jobs[s]=o,console.log(`[Queue] Moved job ${t} ${r} (position ${a} -> ${s})`),this.save(),!0}async processNext(){if(this.state.paused||this.processing)return;if(this.state.jobs.length===0){console.log("[Queue] No jobs to process");return}this.processing=!0;const t=this.state.jobs[0];console.log(`[Queue] Starting job ${t.id} (${t.type})`);try{this.state.currentlyExecuting=this.state.jobs.shift(),this.save(),await Xl(t,this.projectRoot,this.notifier),this.state.currentlyExecuting=void 0,this.save(),this.completedJobs.set(t.id,{id:t.id,status:"success",completedAt:new Date().toISOString()});const r=this.completionCallbacks.get(t.id);r&&(r(),this.completionCallbacks.delete(t.id)),console.log(`[Queue] Job ${t.id} completed successfully`)}catch(r){console.error(`[Queue] Job ${t.id} failed:`,r),this.state.currentlyExecuting=void 0,this.save(),this.completedJobs.set(t.id,{id:t.id,status:"error",error:(r==null?void 0:r.message)||"Unknown error",completedAt:new Date().toISOString()});const a=this.completionCallbacks.get(t.id);a&&(a(r),this.completionCallbacks.delete(t.id))}finally{this.processing=!1,!this.state.paused&&this.state.jobs.length>0&&setImmediate(()=>void this.processNext())}}save(){Ml(this.projectRoot,this.state),this.notifier&&this.notifier.notifyChange("queue")}}class oc{constructor(t,r,a=100){this.watcher=null,this.debounceTimer=null,this.projectRoot=t,this.onChange=r,this.debounceMs=a}start(){const t=wn(this.projectRoot);if(!q.existsSync(t)){console.log("[QueueFileWatcher] Queue file does not exist yet, will start watching when created"),this.watchDirectory();return}this.watchFile(t)}watchDirectory(){const t=wn(this.projectRoot),r=t.substring(0,t.lastIndexOf("/"));try{this.watcher=q.watch(r,(a,s)=>{s==="queue.json"&&(this.stop(),this.watchFile(t),this.notifyChange())}),console.log("[QueueFileWatcher] Watching .codeyam directory for queue.json creation")}catch(a){console.error("[QueueFileWatcher] Failed to watch directory:",a)}}watchFile(t){try{this.watcher=q.watch(t,r=>{r==="change"&&this.notifyChange()}),console.log("[QueueFileWatcher] Watching queue.json for changes")}catch(r){console.error("[QueueFileWatcher] Failed to watch queue file:",r)}}notifyChange(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.onChange(),this.debounceTimer=null},this.debounceMs)}stop(){this.watcher&&(this.watcher.close(),this.watcher=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}}class ic{constructor(t,r,a){this.fileWatcher=null,this.serverInfo=t,this.projectRoot=r,this.onStateChange=a,this.cachedState=zt(r)}start(){this.cachedState=zt(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 oc(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=zt(this.projectRoot),{...this.cachedState}}refreshState(){this.cachedState=zt(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 lc(e){const t=X.join(e,".codeyam","server.json");if(!q.existsSync(t))return null;try{const r=q.readFileSync(t,"utf8");return JSON.parse(r)}catch{return null}}function cc(e){try{return process.kill(e,0),!0}catch{return!1}}async function dc(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 uc(e){const t=lc(e);return!t||!cc(t.pid)||!await dc(t.url)?null:{url:t.url,port:t.port,pid:t.pid}}class hc extends Vo{constructor(){super();tn(this,"watcher",null);tn(this,"dbPath",null);tn(this,"isWatching",!1);this.setMaxListeners(20)}async start(){if(!this.isWatching)try{this.dbPath=_t();const{default:r}=await import("chokidar"),a=[this.dbPath,`${this.dbPath}-wal`,`${this.dbPath}-shm`];this.watcher=r.watch(a,{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:1e3}),this.watcher.on("change",s=>{const o=Date.now(),i=new Date(o).toISOString();console.log("[dbNotifier] ========================================"),console.log(`[dbNotifier] Database file changed: ${s}`),console.log(`[dbNotifier] Timestamp: ${i} (${o})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:"unknown",timestamp:o})}).on("error",s=>{console.error("Database watcher error:",s),this.emit("error",s)}),this.isWatching=!0}catch(r){console.error("Failed to start database watcher:",r),this.emit("error",r)}}notifyChange(r="unknown"){const a=Date.now(),s=new Date(a).toISOString();console.log("[dbNotifier] ========================================"),console.log("[dbNotifier] Manual notification triggered"),console.log(`[dbNotifier] Change type: ${r}`),console.log(`[dbNotifier] Timestamp: ${s} (${a})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:r,timestamp:a})}stop(){this.watcher&&(this.watcher.close(),this.watcher=null,this.isWatching=!1,console.log("Database watcher stopped"))}}const Zn=new hc;let gt=null,Bt=null;async function mc(){if(!gt){if(Bt){await Bt;return}Bt=(async()=>{try{const e=process.env.CODEYAM_ROOT_PATH||ns()||process.cwd();vl(e),console.log(`[GlobalQueue] Project root: ${e}`);const t=await uc(e);if(t){console.log(`[GlobalQueue] Detected background server at ${t.url} (PID: ${t.pid})`),console.log("[GlobalQueue] Using proxy queue");const r=new ic(t,e,()=>{Zn.notifyChange("unknown")});await r.start(),gt=r}else{console.log("[GlobalQueue] No background server detected, using local queue");const r=new sc(e,Zn);await r.start(),gt=r}console.log("[GlobalQueue] Queue initialized")}catch(e){throw console.error("[GlobalQueue] Failed to initialize queue:",e),e}})(),await Bt}}async function at(){return gt||await mc(),gt}function pc(){return gt||(Bt&&console.warn("[GlobalQueue] Queue still initializing, loader may see empty state"),null)}const fc=()=>[{rel:"stylesheet",href:Pl},{rel:"icon",type:"image/x-icon",href:"/favicon.ico"}];async function gc({request:e,context:t}){var r,a,s,o,i,l,d;try{const u=ye()||process.cwd(),[h,m,p]=await Promise.all([Pt(),Fe(),kn(u)]);if(!m)throw new Error("Project slug not found");const f=t.analysisQueue||pc(),g=f==null?void 0:f.getState(),y=async _=>{if(!_||_.length===0)return[];const $=Math.min(Math.max(_.length*2e3,1e4),6e4),D=new Promise(W=>setTimeout(()=>{console.warn(`[Loader] Entity fetch timeout after ${$}ms for ${_.length} entities`),W([])},$)),z=Promise.all(_.map(W=>Ct(W))).then(W=>W.filter(K=>K!==null));return Promise.race([z,D])},w=await Promise.all(((g==null?void 0:g.jobs)||[]).map(async _=>{var D;const $=await y(_.entityShas||[]);return $.length===0&&((D=_.entityShas)!=null&&D.length)&&console.warn("[Loader] Entity fetch timeout/failed for job",_.id),{..._,entities:$}}));let x=null;if(g!=null&&g.currentlyExecuting){const _=g.currentlyExecuting,$=await y(_.entityShas||[]);$.length===0&&((r=_.entityShas)!=null&&r.length)&&console.warn("[Loader] Entity fetch timeout/failed for currentlyExecuting",_.id),x={..._,entities:$}}const v=x?w.filter(_=>_.id!==x.id):w;let b=((s=(a=h==null?void 0:h.metadata)==null?void 0:a.currentRun)==null?void 0:s.currentEntityShas)||[];if(b.length===0){const _=((o=h==null?void 0:h.metadata)==null?void 0:o.historicalRuns)||[];if(_.length>0){const D=[..._].sort((z,W)=>{const K=z.archivedAt||z.createdAt||"";return(W.archivedAt||W.createdAt||"").localeCompare(K)})[0];if(D){const z=D.analysisCompletedAt||D.createdAt;if(z){const W=new Date(z).getTime(),Q=Date.now()-1440*60*1e3;W>Q&&(b=D.currentEntityShas||[])}}}}const N=await y(b),T=[];p.ANTHROPIC_API_KEY&&T.push("ANTHROPIC_API_KEY"),p.GROQ_API_KEY&&T.push("GROQ_API_KEY"),p.OPENAI_API_KEY&&T.push("OPENAI_API_KEY"),p.OPENROUTER_API_KEY&&T.push("OPENROUTER_API_KEY");const{project:S,branch:A}=await Ue(m),P=await yn({projectId:S.id,branchId:A.id,limit:20}),I=[];for(const _ of P){const $=((i=_.metadata)==null?void 0:i.historicalRuns)||[];for(const D of $){const z=D.currentEntityShas||[];if(z.length>0){const W=await y(z);I.push({...D,entities:W})}else I.push(D)}}const M=I.sort((_,$)=>{const D=_.archivedAt||_.analysisCompletedAt||_.createdAt||"";return($.archivedAt||$.analysisCompletedAt||$.createdAt||"").localeCompare(D)}),R=new Set(((l=x==null?void 0:x.entities)==null?void 0:l.map(_=>_.sha))||[]),E=M.filter(_=>!(_.currentEntityShas||[]).some(D=>R.has(D))),C={currentRun:(d=h==null?void 0:h.metadata)==null?void 0:d.currentRun,projectSlug:m,currentEntities:N,availableAPIKeys:T,queuedJobCount:v.length,queueJobs:v,currentlyExecuting:x,historicalRuns:E};return Y(C)}catch(u){return console.error("Failed to load root data:",u),Y({currentRun:void 0,projectSlug:null,currentEntities:[],availableAPIKeys:[],queuedJobCount:0,queueJobs:[],currentlyExecuting:null,historicalRuns:[]})}}function yc(){const{currentRun:e,projectSlug:t,currentEntities:r,availableAPIKeys:a,queuedJobCount:s,queueJobs:o,currentlyExecuting:i,historicalRuns:l}=Ge(),{toasts:d,closeToast:u}=pr(),h=lt(),m=Ee(h),p=sr();re(()=>{m.current=h},[h]);const f=p.pathname.startsWith("/entity/")&&p.pathname.includes("/edit/")||p.pathname.startsWith("/dev/"),g=p.pathname.includes("/fullscreen");return re(()=>{const y=new EventSource("/api/events");let w=null,x=0;const v=2e3;return y.addEventListener("message",b=>{const N=JSON.parse(b.data);if(N.type==="queue")m.current.revalidate(),x=Date.now();else if(N.type==="db-change"||N.type==="unknown"){const T=Date.now(),S=T-x;S<v?(w&&clearTimeout(w),w=setTimeout(()=>{m.current.revalidate(),x=Date.now(),w=null},v-S)):(m.current.revalidate(),x=T)}}),y.addEventListener("error",b=>{console.error("SSE connection error:",b)}),()=>{w&&clearTimeout(w),y.close()}},[]),c(ue,{children:[c("div",{className:`min-h-screen ${f?"":"grid"} bg-cygray-10`,style:f?void 0:{gridTemplateColumns:"96px minmax(900px, 1fr)"},children:[!f&&n(di,{}),c("div",{className:"max-h-screen overflow-auto bg-white",children:[a.length===0&&n(kl,{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(so,{})]})]}),n(mi,{toasts:d,onClose:u}),!g&&n(pi,{currentRun:e,projectSlug:t,currentEntities:r,isAnalysisStarting:!1,queuedJobCount:s,queueJobs:o,currentlyExecuting:i,historicalRuns:l})]})}const xc=We(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(to,{}),n(no,{})]}),c("body",{children:[n(ui,{children:n(li,{children:n(yc,{})})}),n(ro,{}),n(ao,{})]})]})}),bc=Object.freeze(Object.defineProperty({__proto__:null,default:xc,links:fc,loader:gc},Symbol.toStringTag,{value:"Module"}));function da(e){const t=e.replace(/[^a-zA-Z0-9_]+/g,"_");return t.slice(0,1).toUpperCase()+t.slice(1)}function Xt({analysisId:e,scenarioId:t,scenarioName:r,projectSlug:a,enabled:s=!0,refreshTrigger:o=0}){const i=_e(),[l,d]=j(null),[u,h]=j(!1),[m,p]=j(!1),[f,g]=j(!1),y=Ee(!1),w=Ee(null),x=Ee(null),[v,b]=j(0),[N,T]=j(0),S=Ee(null),A=Ee(!1),{interactiveUrl:P,resetLogs:I}=ct(a,s),M=Ee(t),R=Ee(o);re(()=>{R.current!==o&&(R.current=o,l&&(console.log("[useInteractiveMode] Manual refresh triggered"),p(!0),g(!1),b(0),T(C=>C+1),A.current=!1,S.current&&(clearTimeout(S.current),S.current=null)))},[o,l]),re(()=>{if(M.current!==t&&(M.current=t,w.current&&x.current&&r)){const C=da(x.current),_=da(r),$=w.current.replace(C,_);d($),p(!0),g(!1),b(0),T(D=>D+1),A.current=!1,S.current&&(clearTimeout(S.current),S.current=null);return}},[t,r]),re(()=>{if(P){const C=P+"?width=600px";w.current=C,r&&(x.current=r),d(C),h(!1),p(!0)}},[P]),re(()=>{const C=_=>{_.data.type==="codeyam-resize"&&(A.current||(A.current=!0,S.current&&(clearTimeout(S.current),S.current=null),b(0),g(!0),requestAnimationFrame(()=>{requestAnimationFrame(()=>{p(!1)})})))};return window.addEventListener("message",C),()=>window.removeEventListener("message",C)},[]);const E=()=>{A.current=!1,S.current&&clearTimeout(S.current);const C=500*Math.pow(2,v);S.current=setTimeout(()=>{A.current||(v<2?(b(_=>_+1),T(_=>_+1),p(!0)):(console.error("[useInteractiveMode] Interactive mode failed to load after 3 attempts - showing iframe anyway"),g(!0),p(!1)))},C)};return re(()=>{s&&!y.current&&t&&e&&(y.current=!0,h(!0),g(!1),d(null),(async()=>{if(a)try{await fetch(`/api/logs/${a}`,{method:"DELETE"})}catch(_){console.error("[useInteractiveMode] Failed to clear log file:",_)}I(),i.submit({action:"start",analysisId:e,scenarioId:t},{method:"post",action:"/api/interactive-mode"})})())},[s,t,e,I,a]),re(()=>{const C=e,_=()=>{if(y.current&&C){const D=new URLSearchParams({action:"stop",analysisId:C});console.log("[useInteractiveMode] Sending stop request via sendBeacon");const z=navigator.sendBeacon("/api/interactive-mode",D);console.log("[useInteractiveMode] sendBeacon result:",z),z||(console.log("[useInteractiveMode] sendBeacon failed, using fetch fallback"),fetch("/api/interactive-mode",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:D,keepalive:!0}).catch(W=>console.error("Failed to stop interactive mode:",W)))}},$=()=>{_()};return window.addEventListener("beforeunload",$),()=>{window.removeEventListener("beforeunload",$),console.log("[useInteractiveMode] Cleanup running:",{hasStarted:y.current,analysisId:C}),_()}},[e]),{interactiveServerUrl:l,isStarting:u,isLoading:m,showIframe:f,iframeKey:N,onIframeLoad:E}}const rn=10,vc=1024;function bs({currentViewportWidth:e,currentPresetName:t,onDevicePresetClick:r,devicePresets:a,onHoverChange:s,hideLabel:o=!1}){const[i,l]=j(null),d=Ee(null),u=oe(()=>[...a].sort((x,v)=>x.width-v.width),[a]),{fittingPresets:h,overflowPresets:m}=oe(()=>{const x=[],v=[];for(const b of u)b.width<=vc?x.push(b):v.push(b);return v.sort((b,N)=>N.width-b.width),{fittingPresets:x,overflowPresets:v}},[u]),p=ae(x=>{if(!d.current)return null;const v=d.current.getBoundingClientRect(),b=x-v.left,N=v.width,T=N/2,A=(h.length>0?h[h.length-1].width:0)/2,P=T-A,I=T+A,M=m.length>0?(m.length-1)*rn:0;if(m.length>0){if(b<P){if(b<=M){const E=Math.min(Math.floor(b/rn),m.length-1);return m[E]}return m[m.length-1]}if(b>I){const E=N-b;if(E<=M){const C=Math.min(Math.floor(E/rn),m.length-1);return m[C]}return m[m.length-1]}}const R=Math.abs(b-T);for(let E=h.length-1;E>=0;E--){const C=h[E],_=h[E-1],$=C.width/2,D=_?_.width/2:0;if(R<=$&&R>=D)return C}return h[0]||m[m.length-1]||null},[h,m]),f=ae(x=>{const v=p(x.clientX);l(v),s==null||s(v)},[p,s]),g=ae(()=>{l(null),s==null||s(null)},[s]),y=ae(x=>{const v=p(x.clientX);v&&r(v)},[p,r]),w=i||{name:t,width:e};return c("div",{ref:d,className:"relative h-6 shrink-0 overflow-hidden cursor-pointer",onMouseMove:f,onMouseLeave:g,onClick:y,children:[i&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:n("div",{className:"h-full transition-all duration-100 bg-[#005C75]",style:{width:`${i.width}px`}})}),n("div",{className:"absolute inset-0 pointer-events-none",children:h.map(x=>{const v=x.width===e,b=(i==null?void 0:i.name)===x.name,N=x.width/2;return c("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% - ${N}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${v||b?"bg-white":"bg-[rgba(255,255,255,0.3)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% + ${N}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${v||b?"bg-white":"bg-[rgba(255,255,255,0.3)]"}`})})]},x.name)})}),n("div",{className:"absolute inset-0 pointer-events-none",children:m.map((x,v)=>{const b=v*rn,N=x.width===e,T=(i==null?void 0:i.name)===x.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 ${N||T?"bg-white":"bg-[rgba(255,255,255,0.3)]"}`})}),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 ${N||T?"bg-white":"bg-[rgba(255,255,255,0.3)]"}`})})]},x.name)})}),!o&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:c("div",{className:`text-[10px] px-2 py-0.5 rounded shadow-sm whitespace-nowrap transition-colors ${i?"bg-[#005c75] text-white":"bg-white/90 text-[#005c75] border border-[rgba(0,92,117,0.25)]"}`,children:[w.name," - ",w.width,"px"]})})]})}function vs({width:e,height:t,onSave:r,onCancel:a}){const[s,o]=j(""),[i,l]=j(""),d=()=>{const h=s.trim();if(!h){l("Please enter a name for this custom size");return}r(h)};return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:c("div",{className:"bg-white rounded-lg max-w-md w-full p-6 shadow-xl",children:[c("div",{className:"flex items-center justify-between mb-6",children:[n("h2",{className:"text-xl font-semibold text-gray-900",children:"Save Custom Size"}),n("button",{onClick:a,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),c("div",{className:"mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-sm text-gray-500 mb-1",children:"Dimensions"}),c("div",{className:"text-lg font-medium text-gray-900",children:[e,"px × ",t,"px"]})]}),c("div",{className:"mb-6",children:[n("label",{htmlFor:"custom-size-name",className:"block text-sm font-medium text-gray-700 mb-2",children:"Name"}),n("input",{id:"custom-size-name",type:"text",value:s,onChange:h=>{o(h.target.value),l("")},onKeyDown:h=>{h.key==="Enter"&&s.trim()&&d(),h.key==="Escape"&&a()},placeholder:"e.g., iPhone 15 Pro",className:`w-full px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] ${i?"border-red-300":"border-gray-300"}`,autoFocus:!0}),i&&n("p",{className:"mt-1 text-sm text-red-600",children:i})]}),c("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:a,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-300 transition-colors cursor-pointer",children:"Cancel"}),n("button",{onClick:d,disabled:!s.trim(),className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors cursor-pointer disabled:bg-gray-300 disabled:cursor-not-allowed",children:"Save"})]})]})})}function ws(e){const[t,r]=j([]),a=e?`codeyam-custom-sizes-${e}`:null;re(()=>{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=ae(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=ae((l,d,u)=>{r(h=>{const m=h.findIndex(g=>g.name===l),p={name:l,width:d,height:u};let f;return m>=0?(f=[...h],f[m]=p):f=[...h,p],s(f),f})},[s]),i=ae(l=>{r(d=>{const u=d.filter(h=>h.name!==l);return s(u),u})},[s]);return{customSizes:t,addCustomSize:o,removeCustomSize:i}}async function wc({params:e}){var l;const{sha:t,scenarioId:r}=e;if(!t||!r)throw Y("Invalid parameters",{status:400});const a=await Ct(t);if(!a)throw Y("Entity not found",{status:404});const s=await br(a),o=((l=s==null?void 0:s.scenarios)==null?void 0:l.find(d=>d.id===r))||null;if(!o)throw Y("Scenario not found",{status:404});const i=await Fe();return Y({entity:a,scenario:o,analysis:s,projectSlug:i})}const Wn=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],Cc=We(function(){const{entity:t,scenario:r,analysis:a,projectSlug:s}=Ge(),o=It(),[i]=Vt(),[l,d]=j(null),[u,h]=j(1440),[m,p]=j({name:"Desktop",width:1440,height:900}),[f,g]=j(!1),[y,w]=j(null),{customSizes:x,addCustomSize:v}=ws(s),b=oe(()=>[...Wn,...x],[x]),{interactiveServerUrl:N,isStarting:T,isLoading:S,showIframe:A,iframeKey:P,onIframeLoad:I}=Xt({analysisId:a==null?void 0:a.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:s,enabled:!0}),{lastLine:M}=ct(s,T||S),R=()=>{o(`/entity/${t.sha}`)},E=(k,B)=>{h(k);const ne=b.find(L=>L.width===k&&L.height===B);d(ne||null),p({name:(ne==null?void 0:ne.name)||"Custom",width:k,height:B})},C=k=>{d(k),h(k.width),p({name:k.name,width:k.width,height:k.height})},_=k=>{v(k,m.width,m.height??900),g(!1),p(B=>({...B,name:k}))},$=(a==null?void 0:a.scenarios)||[],D=$.findIndex(k=>k.id===(r==null?void 0:r.id)),z=D+1,W=$.length,K=D>0,Q=D<$.length-1,te=()=>{if(K){const k=$[D-1],B=encodeURIComponent(`/entity/${t.sha}/scenarios/${k.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${k.id}/fullscreen?from=${B}`)}},F=()=>{if(Q){const k=$[D+1],B=encodeURIComponent(`/entity/${t.sha}/scenarios/${k.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${k.id}/fullscreen?from=${B}`)}},H=T||S||!A;return c("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[c("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:[c("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n("img",{src:za,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),c("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:te,disabled:!K,className:`${K?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),c("span",{className:"text-gray-400 text-sm",children:[z,"/",W]}),n("button",{onClick:F,disabled:!Q,className:`${Q?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Next scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M7.5 15L12.5 10L7.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),c("div",{className:"flex items-center gap-2 ml-2 min-w-0",children:[n("span",{className:"text-white font-semibold text-xs whitespace-nowrap shrink-0",children:r==null?void 0:r.name}),(r==null?void 0:r.description)&&c("div",{className:"relative group min-w-0",children:[n("span",{className:"text-gray-400 text-xs truncate block",children:r.description}),n("div",{className:"absolute left-0 top-full mt-1 hidden group-hover:block z-50 bg-black text-white text-xs px-3 py-2 rounded shadow-lg max-w-md",children:r.description})]})]})]}),n("button",{onClick:R,className:"text-white hover:text-gray-300 transition-colors ml-4","aria-label":"Close fullscreen",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M15 5L5 15M5 5L15 15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),c("div",{className:"bg-[#034456] border-b border-[rgba(0,92,117,0.25)] shrink-0 z-10 h-6 flex items-center justify-center relative",children:[n("div",{className:"absolute inset-0 flex justify-center",children:n("div",{style:{maxWidth:`${Wn[Wn.length-1].width}px`,width:"100%"},children:n(bs,{currentViewportWidth:u,currentPresetName:m.name,onDevicePresetClick:C,devicePresets:b,hideLabel:!0,onHoverChange:w})})}),c("div",{className:"relative z-10 flex items-center gap-2",children:[c("div",{className:"relative w-28 h-5",children:[c("div",{className:"absolute inset-0 bg-[#007392] text-white text-xs px-2 rounded flex items-center justify-between pointer-events-none",children:[n("span",{className:"leading-none",children:(y==null?void 0:y.name)||m.name}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),c("select",{value:m.name,onChange:k=>{const B=b.find(ne=>ne.name===k.target.value);B&&C(B)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[b.map(k=>n("option",{value:k.name,children:k.name},k.name)),m.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:m.width,onChange:k=>{const B=parseInt(k.target.value,10);!isNaN(B)&&B>0&&E(B,m.height??900)},className:"bg-white text-gray-900 text-xs px-1 rounded border border-gray-300 outline-none w-16 text-center h-5 leading-none",min:"200",max:"3840"}),n("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"×"}),n("span",{className:"bg-gray-100 text-gray-600 text-xs px-1 rounded w-14 text-center h-5 flex items-center justify-center leading-none",children:m.height??900}),m.name==="Custom"&&n("button",{onClick:()=>g(!0),className:"bg-[#007392] text-white text-xs px-2 rounded h-5 flex items-center leading-none hover:bg-[#005c75] transition-colors",children:"Save"})]})]}),n("div",{className:"flex-1 flex items-center justify-center overflow-auto p-8",children:N?c("div",{className:"relative bg-white shadow-2xl w-full h-full",style:{maxWidth:`${m.width}px`,maxHeight:`${m.height}px`},children:[H&&n("div",{className:"absolute inset-0 flex items-center justify-center bg-white 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"})})}),n("p",{className:"text-base font-semibold text-[#005c75]",children:T&&!N?"Starting interactive mode...":"Loading interactive preview..."})]})}),n("iframe",{src:N,className:"w-full h-full border-none",title:`Interactive preview: ${r==null?void 0:r.name}`,onLoad:I,style:{opacity:A?1:0}},P)]}):c("div",{className:"flex flex-col items-center gap-6 max-w-2xl",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"})})}),n("h2",{className:"text-2xl font-semibold text-white leading-[30px] m-0 font-['IBM_Plex_Sans']",children:S?"Interactive mode ready: launching...":"Starting Interactive Mode..."}),M&&n("p",{className:"text-xs font-mono text-gray-400 text-center leading-5 m-0 max-w-xl font-['IBM_Plex_Mono']",children:M}),n("p",{className:"text-xs text-gray-500 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..."})]})}),f&&n(vs,{width:m.width,height:m.height??900,onSave:_,onCancel:()=>g(!1)})]})}),Nc=Object.freeze(Object.defineProperty({__proto__:null,default:Cc,loader:wc},Symbol.toStringTag,{value:"Module"})),Cs=or({dimensions:{height:720,width:1200},updateDimensions:()=>{},iframeRef:{current:null},scale:1,updateScale:()=>{},maxWidth:1200,updateMaxWidth:()=>{}}),Nr=()=>{const e=An(Cs);if(!e)throw new Error("useWebContainer must be used within a WebContainerProvider");return e},In=({children:e})=>{const[t,r]=j({height:720,width:1200}),[a,s]=j(1),[o,i]=j(1200),l=Ee(null),d=ae(({height:m,width:p})=>{r(f=>({height:m??f.height,width:p??f.width}))},[]),u=ae(m=>{s(m)},[]),h=ae(m=>{i(m)},[]);return n(Cs.Provider,{value:{dimensions:t,updateDimensions:d,iframeRef:l,scale:a,updateScale:u,maxWidth:o,updateMaxWidth:h},children:e})},Sc=typeof window<"u";function Ac(){const[e,t]=j(null);return re(()=>{import("react-resizable").then(r=>{t(()=>r.ResizableBox)}),Promise.resolve({ })},[]),e}const Ec=1200,_c=720,ua=30,Pc=({id:e,scenarioName:t,iframeUrl:r,defaultWidth:a=1440,defaultHeight:s=900,onDataOverride:o,onIframeLoad:i,onScaleChange:l,onDimensionChange:d})=>{const u=Ac(),[h,m]=j(!1),[p,f]=j(!1),[g,y]=j(Ec),[w,x]=j(_c),[v,b]=j(null),[N,T]=j(null),{dimensions:S,updateDimensions:A,iframeRef:P,updateScale:I,updateMaxWidth:M}=Nr(),R=oe(()=>Math.min(1,g/S.width),[g,S.width]),E=N!==null?N:R;re(()=>{h||(I(E),l==null||l(E))},[E,I,l,h]),re(()=>{M(g)},[g,M]);const C=ae(()=>{m(!0),T(R)},[R]),_=ae(()=>{m(!1),T(null)},[]),$=ae((Q,te)=>{const F=N!==null?N:1,H=Math.round(te.size.width/F);A({width:H}),d==null||d(H,S.height)},[A,N,d,S.height]),D=ae(()=>{setTimeout(()=>{f(!0)},100),i&&i()},[i]);re(()=>{const Q=te=>{if(te.data.type==="codeyam-resize"){if(t&&te.data.name!==t||S.height===te.data.height||te.data.height===0)return;A({height:te.data.height})}};return window.addEventListener("message",Q),()=>{window.removeEventListener("message",Q)}},[P,t,a,S,A]),re(()=>{p&&o&&o(P.current)},[p,o,P]),re(()=>{if(!t)return;const Q=setInterval(()=>{var te,F;(F=(te=P==null?void 0:P.current)==null?void 0:te.contentWindow)==null||F.postMessage({type:"codeyam-respond",name:t},"*")},1e3);return()=>clearInterval(Q)},[t,P]),re(()=>{const Q=()=>{const te=document.getElementById("scenario-container");if(!te)return;const F=te.getBoundingClientRect(),H=te.clientWidth-ua*2,k=window.innerHeight-F.top-ua*2,B=Math.max(k,400),ne=window.innerHeight-F.top;y(H),x(B),b(ne)};return Q(),window.addEventListener("resize",Q),()=>window.removeEventListener("resize",Q)},[]),re(()=>{A({width:a,height:s})},[a,s,A]);const z=oe(()=>S.width*E,[S.width,E]),W=oe(()=>{const Q=S.height,te=Q*E;return Q&&Q!==720&&Q!==900&&te<w?te:w},[S.height,w,E]),K=ae(()=>{window.history.back()},[]);return!Sc||!u?n("div",{className:"relative bg-gray-100 w-full h-full flex items-center justify-center",children:n("p",{className:"text-gray-500",children:"Loading interactive view..."})}):c("div",{id:"scenario-container",className:"relative bg-gray-100 w-full flex items-center justify-center",style:v?{height:`${v}px`}:{},children:[h&&n("div",{className:"fixed inset-0 z-50 bg-transparent"}),n("style",{children:`
36
+ .react-resizable-handle-e {
37
+ display: flex !important;
38
+ align-items: center !important;
39
+ justify-content: center !important;
40
+ width: 6px !important;
41
+ height: 48px !important;
42
+ right: -8px !important;
43
+ top: 50% !important;
44
+ transform: translateY(-50%) !important;
45
+ cursor: ew-resize !important;
46
+ background: #d1d5db !important;
47
+ border-radius: 3px !important;
48
+ opacity: 0 !important;
49
+ transition: all 0.2s ease !important;
50
+ }
51
+ .react-resizable-handle-e:hover {
52
+ opacity: 0.8 !important;
53
+ background: #9ca3af !important;
54
+ }
55
+ .react-resizable:hover .react-resizable-handle-e {
56
+ opacity: 0.4 !important;
57
+ }
58
+ `}),n(u,{width:z,height:W,minConstraints:[300,200],maxConstraints:[g,w],className:"relative bg-white rounded-lg shadow-md",resizeHandles:["e"],onResizeStart:C,onResizeStop:_,onResize:$,children:n("div",{className:"overflow-auto",style:{width:`${z}px`,height:`${W}px`},children:n("div",{style:{width:`${S.width}px`,height:`${S.height}px`,transform:`scale(${E})`,transformOrigin:"top left"},children:r?n("iframe",{ref:P,className:"w-full h-full rounded-lg",src:r,onLoad:D,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:K,children:"Go back"})]})})})},`resizable-box-${e}`)]})};function kc({presets:e,customSizes:t,currentWidth:r,currentHeight:a,scale:s,onSizeChange:o,onSaveCustomSize:i,onRemoveCustomSize:l,className:d=""}){const[u,h]=j(!1),[m,p]=j(String(r)),[f,g]=j(String(a)),[y,w]=j(!1),[x,v]=j(!1),b=Ee(null);re(()=>{y||p(String(r))},[r,y]),re(()=>{x||g(String(a))},[a,x]),re(()=>{const E=C=>{b.current&&!b.current.contains(C.target)&&h(!1)};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[]);const N=oe(()=>{const E=e.find(_=>_.width===r&&_.height===a);if(E)return E.name;const C=t.find(_=>_.width===r&&_.height===a);return C?C.name:"Custom"},[e,t,r,a]),T=N==="Custom",S=E=>{o(E.width,E.height),h(!1)},A=E=>{const C=E.target.value;p(C);const _=parseInt(C,10);!isNaN(_)&&_>0&&o(_,a)},P=E=>{const C=E.target.value;g(C);const _=parseInt(C,10);!isNaN(_)&&_>0&&o(r,_)},I=()=>{w(!1);const E=parseInt(m,10);(isNaN(E)||E<=0)&&p(String(r))},M=()=>{v(!1);const E=parseInt(f,10);(isNaN(E)||E<=0)&&g(String(a))},R=E=>{(E.key==="Enter"||E.key==="Escape")&&E.target.blur()};return c("div",{className:`flex items-center gap-3 ${d}`,children:[c("div",{className:"relative",ref:b,children:[c("button",{onClick:()=>h(!u),className:"flex items-center gap-2 px-3 py-1.5 bg-white border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 min-w-[120px] justify-between",children:[n("span",{children:N}),n("svg",{className:`w-4 h-4 transition-transform ${u?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),u&&n("div",{className:"absolute top-full left-0 mt-1 min-w-full bg-white border border-gray-200 rounded-md shadow-lg z-50",children:c("div",{className:"py-1",children:[e.length>0&&c(ue,{children:[n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Presets"}),e.map(E=>c("button",{onClick:()=>S(E),className:`w-full text-left px-3 py-2 text-sm hover:bg-gray-100 flex justify-between items-center gap-4 whitespace-nowrap ${N===E.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[n("span",{children:E.name}),c("span",{className:"text-xs text-gray-500",children:[E.width," x ",E.height]})]},E.name))]}),t.length>0&&c(ue,{children:[n("div",{className:"border-t border-gray-100 my-1"}),n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Custom"}),[...t].sort((E,C)=>E.width-C.width).map(E=>c("div",{className:`flex items-center gap-1 hover:bg-gray-100 ${N===E.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[c("button",{onClick:()=>S(E),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:E.name}),c("span",{className:"text-xs text-gray-500",children:[E.width," x ",E.height]})]}),l&&n("button",{onClick:C=>{C.stopPropagation(),N===E.name&&e.length>0&&o(e[0].width,e[0].height),l(E.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"})})})]},E.name))]})]})})]}),c("div",{className:"flex items-center gap-1 text-sm",children:[c("div",{className:"flex items-center",children:[n("input",{type:"text",value:m,onChange:A,onFocus:()=>w(!0),onBlur:I,onKeyDown:R,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),n("span",{className:"text-gray-400 mx-1",children:"×"}),c("div",{className:"flex items-center",children:[n("input",{type:"text",value:f,onChange:P,onFocus:()=>v(!0),onBlur:M,onKeyDown:R,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),s!==void 0&&s<1&&c("span",{className:"text-xs text-gray-500 ml-1",children:["(",Math.round(s*100),"%)"]})]}),T&&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 Hn(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 er(e){return e&&(typeof e=="object"||Array.isArray(e))}function Mc(e){return Array.isArray(e)?e.length:void 0}function Tc(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=er(t[s]),l=er(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 Ic({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 jc({path:e,namedPath:t,isArray:r,count:a,onClick:s}){const o=ae(()=>{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 Ns=(e=>(e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.UNION="union",e.OBJECT="object",e.ARRAY="array",e))(Ns||{});const $c=({name:e,value:t,options:r,onChange:a})=>{const s=ae(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))})},Rc=({name:e,value:t,onChange:r})=>{const a=ae(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
59
+ bg-gray-300 checked:bg-blue-600
60
+ after:content-[''] after:absolute after:top-1 after:left-1 after:w-4 after:h-4
61
+ after:bg-white after:rounded-full after:transition-transform
62
+ checked:after:translate-x-4`})})};function Dc({dataType:e,path:t,value:r,onChange:a}){const s=oe(()=>t[t.length-1],[t]),o=oe(()=>t.join("-"),[t]),i=ae(d=>{a(t,d.target.value)},[a,t]),l=ae(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($c,{name:o,value:r,options:e.split("|"),onChange:i}):e===Ns.BOOLEAN?n(Rc,{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 Lc({analysis:e,scenarioName:t,dataItem:r,onResult:a,onGenerateData:s}){const[o,i]=j(!1),[l,d]=j(""),u=ae(async()=>{if(!s){console.error("onGenerateData prop is required for AI data generation");return}i(!0);try{const m=e.scenarios.find(w=>w.name===t);if(!m)throw new Error("Scenario not found");const p=e.scenarios.find(w=>w.name===_n),f=await s(l,r);if(!f){console.error("Error getting AI guess for scenario data"),i(!1);return}const g=(w,x)=>{const v=Object.assign({},w);return y(w)&&y(x)&&Object.keys(x).forEach(b=>{y(x[b])?b in w?v[b]=g(w[b],x[b]):Object.assign(v,{[b]:x[b]}):Object.assign(v,{[b]:x[b]})}),v},y=w=>w&&typeof w=="object"&&!Array.isArray(w);m.metadata.data=g(g((p==null?void 0:p.metadata.data)||{},m.metadata.data),f.data||{}),a(m),i(!1),d("")}catch(m){console.error("Error generating AI data:",m),i(!1)}},[e,l,r,t,a,s]),h=ae(m=>{d(m.target.value)},[]);return c("div",{className:"w-full p-3 flex flex-col gap-2 rounded-lg border-2 border-blue-200 text-sm bg-blue-50",children:[n("div",{className:"font-medium text-gray-700",children:"Describe the data changes to the AI"}),n("textarea",{className:"peer w-full h-16 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"Type your message here.",onChange:h,value:l}),n("button",{type:"button",disabled:o,className:`w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-400 disabled:cursor-not-allowed font-medium ${l.length>0?"flex":"hidden peer-focus-within:flex"} items-center justify-center gap-2`,onClick:()=>void u(),children:o?c(ue,{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 Oc({namedPath:e,path:t,last:r,onClick:a}){const s=ae(()=>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 Fc({dataItem:e,onClick:t}){const r=ae(()=>t([]),[t]),a=oe(()=>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(Oc,{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 ha({analysis:e,scenarioName:t,dataItem:r,onClick:a,onChange:s,onAIResult:o,onGenerateData:i,saveFeedback:l}){const d=oe(()=>r.data,[r]),u=oe(()=>Tc(r),[r]);return c("div",{className:"w-full flex flex-col gap-6 px-3 mt-3",children:[r.path.length>0&&n(Fc,{dataItem:r,onClick:a}),c("div",{className:"flex flex-col gap-3",children:[n(Lc,{analysis:e,scenarioName:t,dataItem:r,onResult:o,onGenerateData:i}),u==null?void 0:u.map((h,m)=>{var f;if(er(d[h])){let g=h;isNaN(Number(h))||(g=d[h].name??d[h].title??d[h].id??`${r.path[r.path.length-1].replace(/s$/,"")} ${parseInt(h)+1}`);const y=[...r.path,h],w=[...r.namedPath,g];return n(jc,{path:y,namedPath:w,isArray:Array.isArray(d),count:Mc(d[h]),onClick:a},`data-${h}-${m}`)}if(h==="id")return null;const p=[...r.path,h];return n(Dc,{dataType:((f=r.structure)==null?void 0:f[h])??"string",path:p,value:d[h],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 h=document.getElementById("recapture-input");h&&(h.value="false")},disabled:l==null?void 0:l.isSaving,className:"flex-1 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:l!=null&&l.isSaving?"Saving...":"Save Changes"}),n("button",{type:"submit",onClick:()=>{const h=document.getElementById("recapture-input");h&&(h.value="true")},disabled:l==null?void 0:l.isSaving,className:"flex-1 px-4 py-2 bg-gray-100 text-gray-700 border border-gray-300 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Save & Recapture"})]}),(l==null?void 0:l.message)&&!(l!=null&&l.isSaving)&&n("div",{className:`mt-3 p-3 rounded-md text-sm font-medium ${l.isError?"bg-red-50 text-red-700 border border-red-200":"bg-green-50 text-green-700 border border-green-200"}`,children:l.message})]})}function ma({title:e,children:t,defaultOpen:r=!1,borderT:a=!1,borderB:s=!1}){const[o,i]=j(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 Yc=({currentScenario:e,defaultScenario:t,dataStructure:r,analysis:a,shouldCreateNewScenario:s,onSave:o,onNavigate:i,iframeRef:l,onGenerateData:d,saveFeedback:u})=>{const h=ae((A,P)=>{const I=Object.assign({},A),M=R=>R&&typeof R=="object"&&!Array.isArray(R);return M(A)&&M(P)&&Object.keys(P).forEach(R=>{M(P[R])?R in A?I[R]=h(A[R],P[R]):Object.assign(I,{[R]:P[R]}):Object.assign(I,{[R]:P[R]})}),I},[]),[m,p]=j({name:e.name,description:e.description,data:h(t.metadata.data,e.metadata.data)}),[f,g]=j(null),y=oe(()=>({...m.data}),[m]),w=oe(()=>({...y.mockData?{"Retrieved Data":y.mockData}:{},...y.argumentsData?{"Function Arguments":y.argumentsData}:{}}),[y]),x=oe(()=>{const A={...r.arguments?{"Function Arguments":r.arguments}:{},...r.dataForMocks?{"Retrieved Data":r.dataForMocks}:{}};return Object.keys(A).reduce((P,I)=>{if(I.includes(".")){const[M,R]=I.split(".");P[M]||(P[M]={}),P[M][R]=A[I]}else P[I]=A[I];return P},{})},[r]),v=ae(async A=>{A.preventDefault();const P=A.target.querySelector('input[name="recapture"]'),I=(P==null?void 0:P.value)==="true",M={mockData:m.data.mockData??{},argumentsData:m.data.argumentsData??[]};console.log("[ScenarioEditor] Saving scenario data:",{scenarioName:m.name,shouldRecapture:I,dataToSave:M,rawFormData:m.data,iframePayload:{arguments:y.argumentsData??[],...y.mockData??{}}}),console.log("[ScenarioEditor] Full dataToSave JSON:",JSON.stringify(M,null,2).substring(0,1e3));const R=a==null?void 0:a.scenarios.map(E=>!s&&E.name===e.name?{...E,name:m.name,description:m.description,metadata:{...E.metadata,data:M}}:E);s&&R.push({name:m.name,description:m.description,metadata:{data:M,interactiveExamplePath:a==null?void 0:a.scenarios[0].metadata.interactiveExamplePath}}),console.log("[ScenarioEditor] Updated scenarios to save:",R),o&&await o(R,{recapture:I}),i&&i(m.name)},[a,e.name,m,y,s,o,i]),b=ae(A=>{p(P=>({...P,[A.target.name]:A.target.value}))},[]),N=ae(A=>{g(P=>{if(!P)return null;for(const I of[{arguments:A.metadata.data.argumentsData},A.metadata.data.mockData]){let M=I;for(const R of P.path)if(M=Hn(M,R),!M)break;M&&(P.data=M)}return{...P}}),p({name:A.name,description:A.description,data:A.metadata.data})},[]),T=ae((A,P)=>{p(I=>{for(const M of[{"Function Arguments":I.data.argumentsData},{"Retrieved Data":I.data.mockData}]){let R=M;for(const E of A.slice(0,-1))if(R=Hn(R,E),!R)break;if(R){const E=R[A[A.length-1]];g(C=>C?(C.namedPath[C.namedPath.length-1]===E&&(C.namedPath[C.namedPath.length-1]=P.toString()),C.data[A[A.length-1]]=P,{...C}):null),R[A[A.length-1]]=P}}return{...I}})},[]),S=ae(A=>{var R,E,C;if(A.length===0){g(null);return}let P=w;const I=[];let M=x;for(const _ of A){if(I.push(isNaN(parseInt(_))?_:((R=P[_])==null?void 0:R.name)??((E=P[_])==null?void 0:E.title)??((C=P[_])==null?void 0:C.id)??_),P=Hn(P,_),!P){console.log("Data not found",P,_),g(null);return}Array.isArray(M)?M=M[0]:M=M[_]}g({path:A,namedPath:I,data:P,structure:M})},[w,x]);return re(()=>{const A=P=>{var I;P.data.type==="codeyam-log"&&((I=P.data.data)!=null&&I.includes("Error"))&&console.error("[ScenarioEditor] Error from iframe:",P.data.data)};return window.addEventListener("message",A),()=>window.removeEventListener("message",A)},[]),re(()=>{var A;if((A=l==null?void 0:l.current)!=null&&A.contentWindow){const P={arguments:y.argumentsData??[],...y.mockData??{}},I={type:"codeyam-override-data",name:e.name,data:JSON.stringify(P)};console.log("[ScenarioEditor] → SENDING codeyam-override-data:",{type:I.type,name:I.name,dataPreview:JSON.stringify(P).substring(0,200)+"...",fullData:P}),l.current.contentWindow.postMessage(I,"*")}},[y,e,l]),n("form",{method:"post",onSubmit:A=>void v(A),children:f?n(ha,{analysis:a,scenarioName:m.name,dataItem:f,onClick:S,onChange:T,onAIResult:N,onGenerateData:d,saveFeedback:u}):c(ue,{children:[n(ma,{title:"Edit Name and Description",borderT:!0,children:n(Ic,{scenarioFormData:m,handleInputChange:b})}),e.metadata.data&&n(ma,{title:"Edit Scenario Data",defaultOpen:!0,borderT:!0,borderB:!0,children:n(ha,{analysis:a,scenarioName:m.name,dataItem:{path:[],namedPath:[],data:w,structure:x},onClick:S,onChange:T,onAIResult:N,onGenerateData:d,saveFeedback:u})})]})})};function jn({scenarioId:e,scenarioName:t,iframeUrl:r,isStarting:a,isLoading:s,showIframe:o,iframeKey:i,onIframeLoad:l,onScaleChange:d,onDimensionChange:u,projectSlug:h,defaultWidth:m=1440,defaultHeight:p=900,retryCount:f=0}){const{lastLine:g}=ct(h??null,a||s);return r?c("div",{className:"flex-1 min-h-0 relative",children:[n("div",{style:{opacity:o?1:0},children:n(Pc,{id:e,scenarioName:t,iframeUrl:r,defaultWidth:m,defaultHeight:p,onIframeLoad:l,onScaleChange:d,onDimensionChange:u},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 zc=({data:e})=>[{title:e!=null&&e.scenario?`Edit ${e.scenario.name} - CodeYam`:"Edit Scenario - CodeYam"},{name:"description",content:"Edit scenario data"}];async function Bc({params:e}){var d,u;const{sha:t,scenarioId:r}=e;if(!t)throw new Response("Entity SHA is required",{status:400});if(!r)throw new Response("Scenario ID is required",{status:400});const a=await Pn(t,!0),s=a&&a.length>0?a[0]:null;if(!s)throw new Response("Analysis not found",{status:404});const o=(d=s.scenarios)==null?void 0:d.find(h=>h.id===r);if(!o)throw new Response("Scenario not found",{status:404});const i=(u=s.scenarios)==null?void 0:u.find(h=>h.name===_n),l=await Fe();return Y({analysis:s,scenario:o,defaultScenario:i||o,entitySha:t,projectSlug:l})}function Uc(){var _,$,D;const e=Ge(),t=e.analysis,r=e.scenario,a=e.defaultScenario,s=e.entitySha,o=e.projectSlug,i=It(),{iframeRef:l}=Nr(),[d,u]=j(!1),[h,m]=j(null),[p,f]=j(null),[g,y]=j(!1),[w,x]=j(!1),[v,b]=j(null),{interactiveServerUrl:N,isStarting:T,isLoading:S,showIframe:A,iframeKey:P,onIframeLoad:I}=Xt({analysisId:t==null?void 0:t.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:o,enabled:!0}),M=ae(async(z,W)=>{u(!0),m(null),f(null),console.log("[EditScenario] Starting save with options:",W),console.log("[EditScenario] Scenarios to save:",z);try{const K={analysis:t,scenarios:z};console.log("[EditScenario] Sending to /api/save-scenarios:",{analysisId:t.id,scenarioCount:z.length,scenarioNames:z.map(F=>F.name)});const Q=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(K)}),te=await Q.json();if(console.log("[EditScenario] API response:",te),!Q.ok||!te.success)throw new Error(te.error||"Failed to save scenarios");if(console.log("[EditScenario] Scenarios saved successfully"),W!=null&&W.recapture&&r.id&&N){console.log("[EditScenario] ========== DIRECT CAPTURE START =========="),console.log("[EditScenario] Taking screenshot from running server",{scenarioId:r.id,projectId:t.projectId,serverUrl:N}),m("Changes saved. Capturing screenshot...");const F={serverUrl:N,scenarioId:r.id,projectId:t.projectId,viewportWidth:1440};console.log("[EditScenario] Capture request body:",F);const H=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(F)});console.log("[EditScenario] Capture response status:",H.status);const k=await H.json();if(console.log("[EditScenario] Capture response body:",k),!H.ok||!k.success)throw console.error("[EditScenario] Capture failed:",k),new Error(k.error||"Failed to capture screenshot");console.log("[EditScenario] Screenshot captured successfully:",k),console.log("[EditScenario] ========== DIRECT CAPTURE COMPLETE =========="),m("Recapture successful")}else if(W!=null&&W.recapture&&!N){console.log("[EditScenario] No running server, using queued recapture");const F=new FormData;F.append("analysisId",t.id||""),F.append("scenarioId",r.id||"");const H=await fetch("/api/recapture-scenario",{method:"POST",body:F}),k=await H.json();if(!H.ok||!k.success)throw new Error(k.error||"Failed to trigger recapture");console.log("Recapture queued:",k),f(k.jobId),m("Changes saved. Screenshot recapture queued.")}else m("Changes saved successfully.")}catch(K){console.error("Error saving scenarios:",K),m(`Error: ${K instanceof Error?K.message:String(K)}`)}finally{u(!1)}},[t,r.id,N]),R=ae(z=>{},[]),E=ae(async(z,W)=>{var te;const K=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:z,existingScenarios:t.scenarios,scenariosDataStructure:(te=t.metadata)==null?void 0:te.scenariosDataStructure,editingMockName:r.name,editingMockData:W==null?void 0:W.data})}),Q=await K.json();if(!K.ok||!Q.success)throw new Error(Q.error||"Failed to generate scenario data");return Q.data},[t,r.name]),C=ae(async()=>{var z;if(!r.id){b("Cannot delete scenario without ID");return}y(!0),b(null);try{const W=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:r.id,screenshotPaths:((z=r.metadata)==null?void 0:z.screenshotPaths)||[]})}),K=await W.json();if(!W.ok||!K.success)throw new Error(K.error||"Failed to delete scenario");i(`/entity/${s}`)}catch(W){console.error("[EditScenario] Error deleting scenario:",W),b(W instanceof Error?W.message:"Failed to delete scenario"),x(!1)}finally{y(!1)}},[r.id,(_=r.metadata)==null?void 0:_.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(ce,{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)==null?void 0:$.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(Yc,{currentScenario:r,defaultScenario:a,dataStructure:((D=t.metadata)==null?void 0:D.scenariosDataStructure)||{},analysis:t,shouldCreateNewScenario:!1,onSave:M,onNavigate:R,iframeRef:l,onGenerateData:E,saveFeedback:{isSaving:d,message:h,isError:(h==null?void 0:h.startsWith("Error"))??!1}}),h==="Recapture successful"&&n("div",{className:"px-4 pb-4",children:n(ce,{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."}),w?c("div",{className:"space-y-3",children:[c("div",{className:"text-sm text-red-600 font-medium",children:['Are you sure you want to delete "',r.name,'"?']}),c("div",{className:"flex gap-2",children:[n("button",{onClick:()=>void C(),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:()=>x(!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:()=>x(!0),className:"w-full px-4 py-2 bg-red-50 text-red-600 border border-red-200 rounded-md text-sm font-medium hover:bg-red-100 transition-colors",children:"Delete Scenario"}),v&&n("div",{className:"mt-3 text-sm text-red-600 bg-red-50 px-3 py-2 rounded-md",children:v})]})]}),n("main",{className:"flex-1 bg-gray-100 overflow-auto flex flex-col min-w-0",children:n(jn,{scenarioId:r.id||r.name,scenarioName:r.name,iframeUrl:N,isStarting:T,isLoading:S,showIframe:A,iframeKey:P,onIframeLoad:I,projectSlug:o,defaultWidth:1440,defaultHeight:900})})]})]})}const Wc=We(function(){return n(In,{children:n(Uc,{})})}),Hc=Object.freeze(Object.defineProperty({__proto__:null,default:Wc,loader:Bc,meta:zc},Symbol.toStringTag,{value:"Module"}));function Vc(e,t=50){if(e===null)return"null";if(e===void 0)return"undefined";let r;if(typeof e=="object")try{r=JSON.stringify(e)}catch{r="[complex object]"}else r=String(e);return r.length>t?r.slice(0,t)+"...":r}function Jc({keyAttributes:e,selections:t,onChange:r,disabled:a=!1}){const[s,o]=j({}),i=ae(m=>t.some(p=>p.path===m),[t]),l=ae(m=>t.find(p=>p.path===m),[t]),d=ae(m=>{if(i(m.path))r(t.filter(p=>p.path!==m.path));else{const f=m.validValues.find(g=>g.usedInScenarios.length===0)||m.validValues[0];r(f?[...t,{path:m.path,value:f.value,valueOptionIndex:f.index,isCustom:!1}]:[...t,{path:m.path,value:"",isCustom:!0}])}},[t,r,i]),u=ae((m,p)=>{const f=e.find(y=>y.path===m);if(!f)return;const g=t.map(y=>{if(y.path!==m)return y;if(p==="custom")return{...y,value:s[m]||"",valueOptionIndex:void 0,isCustom:!0};const w=parseInt(p,10),x=f.validValues[w];return x?{...y,value:x.value,valueOptionIndex:w,isCustom:!1}:y});r(g)},[t,r,e,s]),h=ae((m,p)=>{o(g=>({...g,[m]:p}));const f=t.map(g=>g.path!==m||!g.isCustom?g:{...g,value:p});r(f)},[t,r]);return e.length===0?n("div",{className:"text-sm text-gray-500 py-2",children:"No key attributes found."}):n("div",{className:"space-y-3",children:e.map(m=>{const p=i(m.path),f=l(m.path),g=m.validValues.filter(y=>y.usedInScenarios.length===0).length;return c("div",{className:"border-b border-gray-100 pb-3 last:border-0 last:pb-0",children:[c("label",{className:"flex items-start gap-2 cursor-pointer",children:[n("input",{type:"checkbox",checked:p,onChange:()=>d(m),disabled:a,className:"mt-0.5 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-mono text-sm font-medium text-gray-900",children:m.localVariable}),g>0&&c("span",{className:"text-xs px-1.5 py-0.5 bg-amber-100 text-amber-700 rounded",children:[g," uncovered"]})]}),m.description&&n("p",{className:"text-xs text-gray-500 mt-0.5 m-0",children:m.description})]})]}),p&&c("div",{className:"ml-6 mt-2",children:[c("select",{value:f!=null&&f.isCustom?"custom":String((f==null?void 0:f.valueOptionIndex)??0),onChange:y=>u(m.path,y.target.value),disabled:a,className:"w-full text-sm border border-gray-300 rounded px-2 py-1.5 focus:border-blue-400 focus:outline-none focus:ring-1 focus:ring-blue-400",children:[m.validValues.map((y,w)=>{const x=y.usedInScenarios.length>0;return c("option",{value:w,children:[Vc(y.value),!x&&" (uncovered)"]},w)}),n("option",{value:"custom",children:"Custom value..."})]}),(f==null?void 0:f.isCustom)&&n("input",{type:"text",placeholder:"Enter custom value",value:s[m.path]||(f==null?void 0:f.value)||"",onChange:y=>h(m.path,y.target.value),disabled:a,className:"w-full mt-2 text-sm border border-gray-300 rounded px-2 py-1.5 focus:border-blue-400 focus:outline-none focus:ring-1 focus:ring-blue-400"}),m.dependencies&&m.dependencies.length>0&&c("div",{className:"mt-2 p-2 bg-amber-50 rounded text-xs",children:[n("span",{className:"text-amber-700 font-medium",children:"Requires:"}),n("ul",{className:"m-0 mt-1 pl-4 space-y-0.5",children:m.dependencies.map((y,w)=>c("li",{className:"text-amber-600",children:[n("code",{className:"bg-amber-100 px-1 rounded",children:y.path})," = ",n("code",{className:"bg-amber-100 px-1 rounded",children:String(y.requiredValue)})]},w))})]})]})]},m.path)})})}function Ss(e,t){const r=(e||[]).map(u=>({path:u.dataStructurePath||u.externalPath||u.internalPath,localVariable:u.internalPath,description:u.description,valueType:u.valueType,validValues:(u.validValueOptions||[]).map((h,m)=>({index:m,value:h,usedInScenarios:[]})),errorValues:(u.errorValueOptions||[]).map((h,m)=>({index:m,value:h,usedInScenarios:[]})),sourceLocations:u.sourceLocations,dependencies:u.dependencies})),a=new Map;r.forEach(u=>{a.set(u.path,u)});const s=[],o=[];t.forEach(u=>{var h;if(zi(u)){const m=[],p=((h=u.metadata)==null?void 0:h.keyAttributeInstructions)||{};Object.entries(p).forEach(([f,g])=>{if(Yi(g)){const y=a.get(f);if(!y)return;if(g.valueOptionRef){const w=g.valueOptionRef,x=y.validValues[w.index];x&&(x.usedInScenarios.push({id:u.id||"",name:u.name,refType:w.refType}),m.push({path:f,valueIndex:w.index,value:x.value,isError:!1,refType:w.refType}))}if(g.errorOptionRef){const w=g.errorOptionRef,x=y.errorValues[w.index];x&&(x.usedInScenarios.push({id:u.id||"",name:u.name,refType:w.refType}),m.push({path:f,valueIndex:w.index,value:x.value,isError:!0,refType:w.refType}))}}}),s.push({scenario:u,usedAttributes:m})}else o.push(u)});let i=0,l=0;r.forEach(u=>{i+=u.validValues.length,l+=u.validValues.filter(h=>h.usedInScenarios.length>0).length});const d=i>0?l/i*100:0;return{keyAttributes:r,scenariosWithStructuredRefs:s,scenariosWithoutStructuredRefs:o,totalValidValues:i,usedValidValues:l,coveragePercentage:d}}function Gc(e){const t=[];return e.keyAttributes.forEach(r=>{r.validValues.forEach(a=>{a.usedInScenarios.length===0&&t.push({path:r.path,index:a.index,value:a.value})})}),t}const qc=({data:e})=>[{title:e!=null&&e.entity?`Create Scenario - ${e.entity.name} - CodeYam`:"Create Scenario - CodeYam"},{name:"description",content:"Create a new scenario"}];async function Kc({params:e}){var i;const{sha:t}=e;if(!t)throw new Response("Entity SHA is required",{status:400});const r=await Pn(t,!0),a=r&&r.length>0?r[0]:null;if(!a)throw new Response("Analysis not found",{status:404});const s=(i=a.scenarios)==null?void 0:i.find(l=>l.name===_n);if(!s)throw new Response("Default scenario not found",{status:404});const o=await Fe();return Y({analysis:a,defaultScenario:s,entity:a.entity,entitySha:t,projectSlug:o})}function Qc(){const{analysis:e,defaultScenario:t,entity:r,entitySha:a,projectSlug:s}=Ge(),o=It(),{iframeRef:i}=Nr(),[l,d]=j(""),[u,h]=j(!1),[m,p]=j(!1),[f,g]=j(null),[y,w]=j(null),[x,v]=j([]),b=oe(()=>{var C;return!((C=e==null?void 0:e.metadata)!=null&&C.keyAttributes)||!(e!=null&&e.scenarios)?[]:Ss(e.metadata.keyAttributes,e.scenarios).keyAttributes},[e]),{interactiveServerUrl:N,isStarting:T,isLoading:S,showIframe:A,iframeKey:P,onIframeLoad:I}=Xt({analysisId:e==null?void 0:e.id,scenarioId:t==null?void 0:t.id,scenarioName:t==null?void 0:t.name,projectSlug:s,enabled:!0}),M=ae(async()=>{var E,C,_,$;if(!l.trim()&&x.length===0){g("Please describe how you want to change the scenario or select key attributes");return}h(!0),g(null),w("Generating scenario with AI...");try{const D=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:l,existingScenarios:e.scenarios,scenariosDataStructure:(E=e.metadata)==null?void 0:E.scenariosDataStructure,keyAttributeSelections:x.length>0?x:void 0})}),z=await D.json();if(!D.ok||!z.success)throw new Error(z.error||"Failed to generate scenario data");console.log("[CreateScenario] AI generated scenario:",z.data);const W=z.data;if(!W.name||!W.data)throw new Error("AI response missing required fields (name or data)");w("Saving new scenario..."),p(!0);const K={name:W.name,description:W.description||l,metadata:{data:W.data,interactiveExamplePath:(C=t.metadata)==null?void 0:C.interactiveExamplePath}},Q=[...e.scenarios||[],K],te=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:e,scenarios:Q})}),F=await te.json();if(!te.ok||!F.success)throw new Error(F.error||"Failed to save scenario");console.log("[CreateScenario] Scenario saved:",F);const H=($=(_=F.analysis)==null?void 0:_.scenarios)==null?void 0:$.find(k=>k.name===W.name);if(!(H!=null&&H.id)){console.warn("[CreateScenario] Could not find saved scenario ID, navigating to entity page"),w("Scenario created! Redirecting..."),setTimeout(()=>void o(`/entity/${a}`),1e3);return}if(N){w("Capturing screenshot...");const k=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:N,scenarioId:H.id,projectId:e.projectId,viewportWidth:1440})}),B=await k.json();!k.ok||!B.success?(console.error("[CreateScenario] Capture failed:",B),w("Scenario created! (Screenshot capture failed)")):w("Scenario created and captured!")}else w("Scenario created!");setTimeout(()=>{o(`/entity/${a}/scenarios/${H.id}`)},1e3)}catch(D){console.error("[CreateScenario] Error:",D),g(D instanceof Error?D.message:String(D)),w(null)}finally{h(!1),p(!1)}},[l,x,e,t,a,N,o]),R=u||m;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(ce,{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==null?void 0: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. Select key attributes and/or describe how you'd like to change it."})]}),b.length>0&&c("details",{className:"mb-4 border border-gray-200 rounded-lg",children:[c("summary",{className:"px-3 py-2 text-sm font-medium text-gray-700 cursor-pointer hover:bg-gray-50 rounded-lg",children:["Select Key Attributes"," ",x.length>0&&c("span",{className:"text-blue-600",children:["(",x.length," selected)"]})]}),n("div",{className:"px-3 pb-3 pt-1 border-t border-gray-100",children:n(Jc,{keyAttributes:b,selections:x,onChange:v,disabled:R})})]}),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:E=>d(E.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:R})]}),c("div",{className:"mt-6 space-y-3",children:[n("button",{onClick:()=>void M(),disabled:R||!l.trim()&&x.length===0,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:R?"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(jn,{scenarioId:t.id||t.name,scenarioName:t.name,iframeUrl:N,isStarting:T,isLoading:S,showIframe:A,iframeKey:P,onIframeLoad:I,projectSlug:s,defaultWidth:1440,defaultHeight:900})})]})]})}const Xc=We(function(){return n(In,{children:n(Qc,{})})}),Zc=Object.freeze(Object.defineProperty({__proto__:null,default:Xc,loader:Kc,meta:qc},Symbol.toStringTag,{value:"Module"}));var se;(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={}))})(se||(se={}));function As(e,t){return e?Object.values(se.Model).includes(e)?e:(console.warn(`Invalid model in environment variable: ${e}. Falling back to ${t}`),t):t}const Es=As(process.env.DEFAULT_SMALLER_MODEL,se.Model.OPENAI_GPT4_1_MINI),ed=As(process.env.DEFAULT_LARGER_MODEL,se.Model.OPENAI_GPT4_1),Qe={name:"OpenAI",baseURL:"https://api.openai.com/v1",apiKeyEnvVar:"OPENAI_API_KEY"},Vn={name:"OpenRouter",baseURL:"https://openrouter.ai/api/v1",apiKeyEnvVar:"OPENROUTER_API_KEY"},td={name:"Groq",baseURL:"https://api.groq.com/openai/v1",apiKeyEnvVar:"GROQ_API_KEY"},Jn={name:"Anthropic",baseURL:"https://api.anthropic.com/v1/",apiKeyEnvVar:"ANTHROPIC_API_KEY"},it={name:"DeepInfra",baseURL:"https://api.deepinfra.com/v1/",apiKeyEnvVar:"DEEPINFRA_API_KEY"},nd={[se.Model.OPENAI_GPT5_1]:{id:se.Model.OPENAI_GPT5_1,provider:Qe,apiModelName:"gpt-5.1",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"none"},[se.Model.OPENAI_GPT5]:{id:se.Model.OPENAI_GPT5,provider:Qe,apiModelName:"gpt-5",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"minimal"},[se.Model.OPENAI_GPT5_MINI]:{id:se.Model.OPENAI_GPT5_MINI,provider:Qe,apiModelName:"gpt-5-mini",maxCompletionTokens:128e3,pricing:{input:.25,output:2},reasoningEffort:"minimal"},[se.Model.OPENAI_GPT5_NANO]:{id:se.Model.OPENAI_GPT5_NANO,provider:Qe,apiModelName:"gpt-5-nano",maxCompletionTokens:128e3,pricing:{input:.05,output:.4},reasoningEffort:"minimal"},[se.Model.OPENAI_GPT4_1]:{id:se.Model.OPENAI_GPT4_1,provider:Qe,apiModelName:"gpt-4.1",maxCompletionTokens:32768,pricing:{input:2,output:8}},[se.Model.OPENAI_GPT4_1_MINI]:{id:se.Model.OPENAI_GPT4_1_MINI,provider:Qe,apiModelName:"gpt-4.1-mini",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[se.Model.OPENAI_GPT4_O]:{id:se.Model.OPENAI_GPT4_O,provider:Qe,apiModelName:"gpt-4o",maxCompletionTokens:16384,pricing:{input:2.5,output:10}},[se.Model.OPENAI_GPT4_O_MINI]:{id:se.Model.OPENAI_GPT4_O_MINI,provider:Qe,apiModelName:"gpt-4o-mini",maxCompletionTokens:16384,pricing:{input:.15,output:.6}},[se.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER]:{id:se.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER,provider:Vn,apiModelName:"google/gemini-2.5-flash-lite",maxCompletionTokens:1048576,pricing:{input:.1,output:.4},reasoningEffort:"minimal"},[se.Model.META_LLAMA_4_MAVERICK_OPENROUTER]:{id:se.Model.META_LLAMA_4_MAVERICK_OPENROUTER,provider:Vn,apiModelName:"meta-llama/llama-4-maverick",maxCompletionTokens:1048576,pricing:{input:.15,output:.6},reasoningEffort:"minimal"},[se.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER]:{id:se.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER,provider:Vn,apiModelName:"deepseek/deepseek-v3.1-terminus",maxCompletionTokens:163840,pricing:{input:.23,output:.9},reasoningEffort:"minimal"},[se.Model.OPENAI_GPT_OSS_120B_GROQ]:{id:se.Model.OPENAI_GPT_OSS_120B_GROQ,provider:td,apiModelName:"openai/gpt-oss-120b",maxCompletionTokens:131072,pricing:{input:.15,output:.75},reasoningEffort:"low"},[se.Model.OPENAI_GPT_OSS_120B_DEEPINFRA]:{id:se.Model.OPENAI_GPT_OSS_120B_DEEPINFRA,provider:it,apiModelName:"openai/gpt-oss-120b-Turbo",maxCompletionTokens:32768,pricing:{input:.15,output:.6},reasoningEffort:"low"},[se.Model.QWEN3_235B_INSTRUCT_DEEPINFRA]:{id:se.Model.QWEN3_235B_INSTRUCT_DEEPINFRA,provider:it,apiModelName:"Qwen/Qwen3-235B-A22B-Instruct-2507",maxCompletionTokens:32768,pricing:{input:.09,output:.57}},[se.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA]:{id:se.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA,provider:it,apiModelName:"Qwen/Qwen3-Coder-480B-A35B-Instruct",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[se.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA]:{id:se.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA,provider:it,apiModelName:"google/gemini-2.5-pro",maxCompletionTokens:1048576,pricing:{input:1.25,output:10},reasoningEffort:"low"},[se.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA]:{id:se.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA,provider:it,apiModelName:"google/gemini-2.5-flash",maxCompletionTokens:1048576,pricing:{input:.3,output:2.5},reasoningEffort:"low"},[se.Model.ANTHROPIC_CLAUDE_4_5_HAIKU]:{id:se.Model.ANTHROPIC_CLAUDE_4_5_HAIKU,provider:Jn,apiModelName:"claude-haiku-4-5",maxCompletionTokens:2e5,pricing:{input:1,output:5}},[se.Model.ANTHROPIC_CLAUDE_4_5_SONNET]:{id:se.Model.ANTHROPIC_CLAUDE_4_5_SONNET,provider:Jn,apiModelName:"claude-sonnet-4-5",maxCompletionTokens:2e5,pricing:{input:3,output:15}},[se.Model.ANTHROPIC_CLAUDE_4_5_OPUS]:{id:se.Model.ANTHROPIC_CLAUDE_4_5_OPUS,provider:Jn,apiModelName:"claude-opus-4-5",maxCompletionTokens:2e5,pricing:{input:5,output:25}},[se.Model.PHIND_CODELLAMA]:{id:se.Model.PHIND_CODELLAMA,provider:Qe,apiModelName:"phind-codellama",maxCompletionTokens:16384,pricing:{input:0,output:0}},[se.Model.GOOGLE_GEMINI_PRO]:{id:se.Model.GOOGLE_GEMINI_PRO,provider:it,apiModelName:"google/gemini-pro",maxCompletionTokens:32768,pricing:{input:0,output:0}},[se.Model.GOOGLE_PALM_2_CODE_CHAT_32K]:{id:se.Model.GOOGLE_PALM_2_CODE_CHAT_32K,provider:it,apiModelName:"google/palm-2-code-chat-32k",maxCompletionTokens:32768,pricing:{input:0,output:0}},[se.Model.META_CODELLAMA_34B_INSTRUCT]:{id:se.Model.META_CODELLAMA_34B_INSTRUCT,provider:it,apiModelName:"meta-llama/codellama-34b-instruct",maxCompletionTokens:16384,pricing:{input:0,output:0}},[se.Model.OPENAI_GPT4_PREVIEW]:{id:se.Model.OPENAI_GPT4_PREVIEW,provider:Qe,apiModelName:"gpt-4-preview",maxCompletionTokens:128e3,pricing:{input:0,output:0}}};function $n(e){const t=nd[e];if(!t)throw new Error(`Unknown model: ${e}`);return t}function rd(e){return $n(e).maxCompletionTokens}function ad(e){return $n(e).pricing}const pa=1e6;function sd({model:e,usage:t}){const r=ad(e);return r?t.prompt_tokens*(r.input/pa)+t.completion_tokens*(r.output/pa):null}function od({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=sd({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 id({messages:{system:e,prompt:t},model:r,responseType:a,jsonSchema:s}){const o=r??Es,i=$n(o);rd(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}}}ur(dr);const an=new qo({concurrency:100,timeout:1200*1e3,throwOnTimeout:!0,autoStart:!0}),fa={retries:4,factor:2,minTimeout:1e3,maxTimeout:6e4,randomize:!0},sn={};async function tr({type:e,systemMessage:t,prompt:r,jsonResponse:a=!0,jsonSchema:s,model:o=Es,attempts:i=0}){var S,A,P,I,M,R,E;if(process.env.CODEYAM_LLM_FIXTURES_DIR)return await ld(e,process.env.CODEYAM_LLM_FIXTURES_DIR);console.log(`CodeYam Debug: LLM Pool [queued=${an.size}, running=${an.pending}]`);const l=Date.now();let d,u=0;const h=$n(o),m=process.env[h.provider.apiKeyEnvVar];if(!m)throw new Error(`API key not found for provider ${h.provider.name}. Please set ${h.provider.apiKeyEnvVar} environment variable.`);console.log(`Using ${h.provider.name} for AI request`);const p=new Go({apiKey:m,baseURL:h.provider.baseURL}),f={type:e,messages:{system:t,prompt:r},model:o,responseType:s?"json_schema":a?"json_object":"text",jsonSchema:s},g=id(f),y=await an.add(()=>(d=Date.now(),ta(()=>p.chat.completions.create(g,{timeout:300*1e3}),{...fa,onFailedAttempt:C=>{u++,console.log(`CodeYam Error: Completion call failed [model=${o}]`,{error:C,prompt:r,systemMessage:t,attempts:i,retryCount:u})}})),{throwOnTimeout:!0}),w=Date.now(),x=od({chatRequest:f,chatCompletion:y,model:o});if(!x)throw new Error("Failed to get LLM call stats");x.retries=u,x.wait_ms=d-l,x.duration_ms=w-l;const v=(S=y.choices)==null?void 0:S[0];let b=null;if(v){if(!v.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");b=(A=v.message)==null?void 0:A.content}let N=b;b&&(N=b.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const T=a?N&&(((P=N.match(/\{[\s\S]*\}/))==null?void 0:P[0])??N):N;if(!T){if(console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({completion:T,rawCompletion:b,chatCompletion:y,chatRequest:f},null,2)),i<3)return console.log("CodeYam Error: Retrying completion",{prompt:r,systemMessage:t,attempts:i}),await tr({type:e,systemMessage:t,prompt:r,jsonResponse:a,model:o,attempts:i+1});throw new Error("completionCall(): empty completion from LLM")}if(T.replace(/\s/g,"")==="")throw console.log("CodeYam Error: Empty Completion",{rawCompletion:b,prompt:r,systemMessage:t}),new Error("Empty completion");if(a)try{JSON.parse(T)}catch(C){if(console.log("CodeYam Error: Invalid JSON in completion",{error:C.message,model:o,completion:T.substring(0,500),rawCompletion:b==null?void 0:b.substring(0,500)}),i<3){console.log("CodeYam Error: Retrying with correction prompt",{attempts:i,parseError:C.message});const _=`Your previous response contained invalid JSON with the following error:
63
+
64
+ ${C.message}
65
+
66
+ Here was your previous response:
67
+ \`\`\`
68
+ ${T}
69
+ \`\`\`
70
+
71
+ Please provide a corrected version with valid JSON only. Do not include any explanatory text, just the valid JSON object.`,$=await an.add(()=>ta(()=>p.chat.completions.create({...g,messages:[{role:"system",content:t},{role:"user",content:r},{role:"assistant",content:T},{role:"user",content:_}]},{timeout:300*1e3}),{...fa,onFailedAttempt:K=>{console.log("CodeYam Error: Correction call failed",{error:K,attempts:i})}}),{throwOnTimeout:!0}),D=(R=(M=(I=$.choices)==null?void 0:I[0])==null?void 0:M.message)==null?void 0:R.content;let z=D;D&&(z=D.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const W=z&&(((E=z.match(/\{[\s\S]*\}/))==null?void 0:E[0])??z);if(!W)throw new Error("Correction attempt returned empty completion");try{JSON.parse(W),console.log("CodeYam: JSON correction successful");const K=Date.now();return x.duration_ms=K-l,{finishReason:$.choices[0].finish_reason,completion:W,stats:x}}catch(K){return console.log("CodeYam Error: Corrected JSON still invalid",{error:K.message,correctedCompletion:W.substring(0,500)}),await tr({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:T,stats:x}}async function ld(e,t){var s,o,i;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 l=r.readdirSync(t).filter(g=>g.endsWith(".json"));if(l.length===0)throw new Error(`No LLM fixture files found in ${t}`);const d={};for(const g of l)try{const y=r.readFileSync(a.join(t,g),"utf-8"),w=JSON.parse(y);d[w.prompt_type]||(d[w.prompt_type]=[]),d[w.prompt_type].push(w)}catch(y){console.warn(`Failed to parse LLM fixture file ${g}:`,y)}const u=d[e];if(!u||u.length===0){const g=Object.keys(d).join(", ");throw new Error(`No captured LLM call found for type '${e}'. Available types: ${g}`)}const h=`${t}::${e}`;sn[h]||(sn[h]=0);const m=sn[h];sn[h]=(m+1)%u.length;const p=u[m];console.log(`CodeYam Test: Replaying LLM response for '${e}' [${m+1}/${u.length}]`);let f;try{f=((i=(o=(s=JSON.parse(p.response).choices)==null?void 0:s[0])==null?void 0:o.message)==null?void 0:i.content)||p.response}catch{f=p.response}return{finishReason:"stop",completion:f,stats:{model:p.model??"fixture",prompt_type:e,system_message:p.system_message??"",prompt_text:p.prompt_text??"",response:p.response??"",input_tokens:p.input_tokens??0,output_tokens:p.output_tokens??0,cost:p.cost??0,retries:0,wait_ms:0,duration_ms:1}}}catch(l){throw console.error("CodeYam Test Error: Failed to replay LLM call:",l),l}}function ga(){return process.env.DYNAMODB_PREFIX?`${process.env.DYNAMODB_PREFIX}-llm-calls`:null}async function cd(e){const{propsJson:t,...r}=e,a=JSON.stringify(t,null,2),s=jt(),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=X.join(process.env.DYNAMODB_PATH,d):process.env.CODEYAM_LOCAL_PROJECT_PATH&&(l=X.join(process.env.CODEYAM_LOCAL_PROJECT_PATH,".codeyam","llm-calls",d)),l)try{const h=X.dirname(l);return await Ie.mkdir(h,{recursive:!0}),await Ie.writeFile(l,JSON.stringify(i,null,2)),console.log(`CodeYam: Saved LLM call to local file: ${l}`),{id:s}}catch(h){return console.log("CodeYam Error: Failed to save LLM call to local file",h),{id:"-1"}}const u=ga();if(!u)return console.log("[CodeYam] No DynamoDB table name for LLM calls, skipping save"),{id:"-1"};for(const[h,m]of Object.entries(i))typeof m>"u"&&console.log(`CodeYam Warning: LLM call ${s} property ${h} with explicit value 'undefined'`);try{return await new En().send(new Ko({TableName:ga(),Item:Xo(i,{removeUndefinedValues:!0})})),{id:s}}catch(h){return console.log(`CodeYam Error: Failed to save LLM call to DynamoDB table ${u}`,h),{id:"-1"}}}new En({});new En({});new En({});const dd=3,ud=2,Sr=()=>({max:1e4,maxSize:10*1e3*1e3,sizeCalculation:(e,t)=>16+dd*String(t).length*(1+ud)});new hr(Sr());new hr(Sr());new hr(Sr());class hd{constructor(){this.byMethodName=new Map,this.byClassAndMethod=new Map}register(t,r,a){this.byMethodName.has(t)||this.byMethodName.set(t,[]),this.byMethodName.get(t).push(r),a&&(this.byClassAndMethod.has(a)||this.byClassAndMethod.set(a,new Map),this.byClassAndMethod.get(a).set(t,r))}getByMethodName(t){return this.byMethodName.get(t)}getByClassAndMethod(t,r){var a;return(a=this.byClassAndMethod.get(t))==null?void 0:a.get(r)}}class md{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 pd{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 fd{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 gd{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 yd{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.withReturnValues();a.addType(s,"array")}isComplete(){return!0}}class xd{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 bd{getReturnType(){return"number"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0)for(let o=0;o<s.args.length;o++)a.addEquivalence(r.withElement("*"),t.withParameter(o))}isComplete(){return!0}}class vd{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 wd{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 Cd{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 Nd{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array"),a.addEquivalence(t.withReturnValues(),r.withElement("*"))}isComplete(){return!0}}class Sd{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 Ad{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 Ed{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 _d{getReturnType(){return"unknown"}addEquivalences(t,r,a){t.getLastFunctionCallSegment()}isComplete(){return!0}}class Pd{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 kd(){const e=new hd;return e.register("filter",new md,"Array"),e.register("map",new wd,"Array"),e.register("flatMap",new Cd,"Array"),e.register("join",new vd,"Array"),e.register("find",new pd,"Array"),e.register("findLast",new Sd,"Array"),e.register("at",new Nd,"Array"),e.register("reduce",new fd,"Array"),e.register("concat",new gd,"Array"),e.register("slice",new yd,"Array"),e.register("splice",new xd,"Array"),e.register("push",new bd,"Array"),e.register("fromEntries",new Ad,"Object"),e.register("then",new Ed,"Promise"),e.register("useState",new Pd,"React"),e.register("useMemo",new _d,"React"),e}kd();class Md{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 Md({enabled:!1});const Td=new Set(["filter","sort","slice","splice","unshift","push","reverse","entries"]),Id=new Set(["find","findLast","at","pop","shift"]),jd=new Set(["map","reduce","flatMap","concat","join","some","every","findIndex","findLastIndex","indexOf","lastIndexOf","includes"]),$d=new Set([...Td,...Id,...jd]),Rd=new Set(["trim","concat","replace","replaceAll","toLowerCase","toUpperCase","trimStart","trimEnd","padStart","padEnd","normalize","slice","substring","substr","toString()","toLocaleLowerCase","toLocaleUpperCase"]),Dd=new Set(["split","match","endsWith","startsWith","includes","indexOf","lastIndexOf","charAt","charCodeAt","codePointAt","repeat","search","valueOf","localeCompare","length"]),Ld=new Set([...Rd,...Dd]);[...$d,...Ld];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 _s(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 Qo.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),_s(e)}return null}}function Od({description:e,existingScenarios:t,scenariosDataStructure:r,keyAttributeSelections:a}){let s="";return a&&a.length>0&&(s=`
72
+ User-selected Key Attributes and Values:
73
+ The user has specifically requested these key attributes and values be used in the scenario:
74
+ ${a.map(o=>` - ${o.path}: ${o.value}${o.isCustom?" (custom value)":""}`).join(`
75
+ `)}
76
+
77
+ IMPORTANT: The mockData MUST include these specific values for the specified paths. Generate a scenario name and description that reflects these choices.
78
+ `),`Mock Scenario Data Structure:
79
+ \`\`\`
80
+ ${JSON.stringify(r,null,2)}
81
+ \`\`\`
82
+ Existing Mock Scenario Data:
83
+ \`\`\`
84
+ ${JSON.stringify(t,null,2)}
85
+ \`\`\`
86
+ ${s}
87
+ New Scenario user-created prompt: "${e||"(No additional description - generate based on selected key attributes)"}"
88
+ `}function Fd({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s}){const o=a.find(i=>i.name===_n);return`Mock Scenario Data Structure:
89
+ \`\`\`
90
+ ${JSON.stringify({props:s.arguments,dataVariables:s.dataForMocks},null,2)}
91
+ \`\`\`
92
+
93
+ Existing Mock Scenario Data:
94
+ \`\`\`
95
+ ${JSON.stringify(a.map(i=>({name:i.name,data:Yt(o.metadata.data,i.metadata.data)})),null,2)}
96
+ \`\`\`
97
+
98
+ Mock Scenario that should be edited: "${t}"
99
+ ${r?`The portion of the data that should be edited:
100
+ \`\`\`
101
+ ${JSON.stringify(r,null,2)}
102
+ \`\`\``:""}
103
+
104
+ How this data should be changed: "${e}"
105
+ `}async function Yd({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s,keyAttributeSelections:o,model:i}){const l=t?Fd({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s}):Od({description:e,existingScenarios:a,scenariosDataStructure:s,keyAttributeSelections:o}),d=await tr({type:"guessScenarioDataFromDescription",systemMessage:t?Bd(r):zd,prompt:l,model:i??ed});await cd({object_type:"guessScenarioDataFromDescription",object_id:"new",propsJson:{description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s,model:i},...d.stats});const{completion:u}=d;return u?_s(u):(console.log("CodeYam: guessing scenario data failed: No response from AI"),null)}const zd=`
106
+ 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.
107
+
108
+ 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.
109
+
110
+ 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.
111
+
112
+ You must respond with valid JSON following this format of this TS type definition:
113
+ \`\`\`
114
+ export type ScenarioData = {
115
+ name: string;
116
+ description: string;
117
+ data: {
118
+ mockData: { [key: string]: unknown };
119
+ argumentsData: { [key: string]: unknown };
120
+ };
121
+ };
122
+
123
+ \`\`\`
124
+ `,Bd=e=>`
125
+ 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.
126
+
127
+ Your goal is to edit one of the scenarios, named as the "Mock Scenario that should be edited".
128
+ ${e?`
129
+ 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.`:""}
130
+
131
+ 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.
132
+
133
+ You must respond with valid JSON following this type definition:
134
+ \`\`\`
135
+ {
136
+ data: {
137
+ mockData: { [key: string]: unknown };
138
+ argumentsData: { [key: string]: unknown };
139
+ }
140
+ }
141
+ \`\`\`
142
+ `;async function Ud({request:e}){if(e.method!=="POST")return Y({error:"Method not allowed"},{status:405});try{const t=await e.json(),{description:r,existingScenarios:a,scenariosDataStructure:s,editingMockName:o,editingMockData:i,keyAttributeSelections:l}=t;if(!r&&(!l||l.length===0))return Y({error:"Missing required field: description or keyAttributeSelections"},{status:400});const d=await Yd({description:r||"",existingScenarios:a??[],scenariosDataStructure:s,editingMockName:o,editingMockData:i,keyAttributeSelections:l}),u=(d==null?void 0:d.data)||d;return Y({success:!0,data:u})}catch(t){return console.error("[Generate Scenario Data API] Error:",t),Y({error:"Failed to generate scenario data",details:t instanceof Error?t.message:String(t)},{status:500})}}const Wd=Object.freeze(Object.defineProperty({__proto__:null,action:Ud},Symbol.toStringTag,{value:"Module"}));async function Hd({request:e}){var t;if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const r=await e.json(),{action:a,analysisId:s,analysis:o,keyAttribute:i,keyAttributeIndex:l}=r;if(!s||!o)return Response.json({error:"Missing required fields: analysisId and analysis"},{status:400});const u=[...((t=o.metadata)==null?void 0:t.keyAttributes)||[]];switch(a){case"add":if(!i)return Response.json({error:"Missing keyAttribute for add action"},{status:400});const p=u.map(g=>g.dataStructurePath||g.externalPath||g.internalPath),f=i.dataStructurePath||i.externalPath||i.internalPath;if(p.includes(f))return Response.json({error:`Key attribute with path "${f}" already exists`},{status:400});u.push(i);break;case"update":if(l===void 0||!i)return Response.json({error:"Missing keyAttributeIndex or keyAttribute for update action"},{status:400});if(l<0||l>=u.length)return Response.json({error:"Invalid keyAttributeIndex"},{status:400});u[l]=i;break;case"remove":if(l===void 0)return Response.json({error:"Missing keyAttributeIndex for remove action"},{status:400});if(l<0||l>=u.length)return Response.json({error:"Invalid keyAttributeIndex"},{status:400});u.splice(l,1);break;default:return Response.json({error:`Invalid action: ${a}`},{status:400})}const h={...o,metadata:{...o.metadata,keyAttributes:u}},m=await es([h]);if(!m||m.length===0)throw new Error("Failed to save analysis to database");return Response.json({success:!0,analysis:m[0]})}catch(r){return console.error("[API] Error updating key attributes:",r),Response.json({error:"Failed to update key attributes",details:r instanceof Error?r.message:String(r)},{status:500})}}const Vd=Object.freeze(Object.defineProperty({__proto__:null,action:Hd},Symbol.toStringTag,{value:"Module"}));async function Jd(e,t){const r=ye();if(!r)return{entityCalls:[],analysisCalls:[]};const a=X.join(r,".codeyam","llm-calls");try{await Ie.access(a)}catch{return{entityCalls:[],analysisCalls:[]}}const s=[],o=[];try{const l=(await Ie.readdir(a)).filter(x=>x.endsWith(".json")),d=`${e}_`,u=t?`${t}_`:null,h=[],m=[];for(const x of l)x.startsWith(d)||u&&x.startsWith(u)?h.push(x):m.push(x);const p=h.map(async x=>{try{const v=X.join(a,x),b=await Ie.readFile(v,"utf-8");return JSON.parse(b)}catch{return null}}),f=m.map(async x=>{try{const v=X.join(a,x),b=await Ie.readFile(v,"utf-8"),N=JSON.parse(b);return N.object_id===e||t&&N.object_id===t?N:null}catch{return null}}),[g,y]=await Promise.all([Promise.all(p),Promise.all(f)]),w=[...g,...y].filter(x=>x!==null);for(const x of w)x.object_id===e?s.push(x):t&&x.object_id===t&&o.push(x);s.sort((x,v)=>v.created_at-x.created_at),o.sort((x,v)=>v.created_at-x.created_at)}catch(i){console.error("Error loading LLM calls:",i)}return{entityCalls:s,analysisCalls:o}}async function Gd({params:e,request:t}){const{entitySha:r}=e;if(!r)return Y({error:"Entity SHA is required"},{status:400});const s=new URL(t.url).searchParams.get("analysisId")||void 0,o=await Jd(r,s);return Y(o)}const qd=Object.freeze(Object.defineProperty({__proto__:null,loader:Gd},Symbol.toStringTag,{value:"Module"}));async function Kd({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{action:r,scenario:a,keyAttributePath:s,valueOptionRef:o,isErrorValue:i}=t;if(!a||!a.id)return Response.json({error:"Missing required field: scenario with id"},{status:400});if(!s)return Response.json({error:"Missing required field: keyAttributePath"},{status:400});const l={...a.metadata},d={...l.keyAttributeInstructions||{}};switch(r){case"link":if(!o)return Response.json({error:"Missing valueOptionRef for link action"},{status:400});const m=d[s];let p=s.split(".").pop()||s;typeof m=="object"&&"localVariable"in m&&(p=m.localVariable),d[s]={localVariable:p,instruction:`Using value at index ${o.index}`,...i?{errorOptionRef:o}:{valueOptionRef:o}};break;case"unlink":delete d[s];break;default:return Response.json({error:`Invalid action: ${r}`},{status:400})}const u={...a,metadata:{...l,keyAttributeInstructions:d}},h=await ts([u]);if(!h||h.length===0)throw new Error("Failed to save scenario to database");return Response.json({success:!0,scenario:h[0]})}catch(t){return console.error("[API] Error linking scenario value:",t),Response.json({error:"Failed to link scenario value",details:t instanceof Error?t.message:String(t)},{status:500})}}const Qd=Object.freeze(Object.defineProperty({__proto__:null,action:Kd},Symbol.toStringTag,{value:"Module"}));async function Xd({request:e}){var t;if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const r=await e.json(),{action:a,analysisId:s,analysis:o,keyAttributeIndex:i,valueType:l,value:d,valueIndex:u}=r;if(!s||!o)return Response.json({error:"Missing required fields: analysisId and analysis"},{status:400});if(i===void 0)return Response.json({error:"Missing required field: keyAttributeIndex"},{status:400});const h=((t=o.metadata)==null?void 0:t.keyAttributes)||[];if(i<0||i>=h.length)return Response.json({error:"Invalid keyAttributeIndex"},{status:400});const m=[...h],p={...m[i]};m[i]=p;const f=l==="validValueOptions"?[...p.validValueOptions||[]]:[...p.errorValueOptions||[]];switch(a){case"add":if(!d||d.trim()==="")return Response.json({error:"Value cannot be empty"},{status:400});if(f.includes(d))return Response.json({error:`Value "${d}" already exists`},{status:400});f.push(d);break;case"remove":if(u===void 0)return Response.json({error:"Missing valueIndex for remove action"},{status:400});if(u<0||u>=f.length)return Response.json({error:"Invalid valueIndex"},{status:400});f.splice(u,1);break;default:return Response.json({error:`Invalid action: ${a}`},{status:400})}l==="validValueOptions"?p.validValueOptions=f:p.errorValueOptions=f;const g={...o,metadata:{...o.metadata,keyAttributes:m}},y=await es([g]);if(!y||y.length===0)throw new Error("Failed to save analysis to database");return Response.json({success:!0,analysis:y[0]})}catch(r){return console.error("[API] Error updating valid values:",r),Response.json({error:"Failed to update valid values",details:r instanceof Error?r.message:String(r)},{status:500})}}const Zd=Object.freeze(Object.defineProperty({__proto__:null,action:Xd},Symbol.toStringTag,{value:"Module"}));function eu(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const r=Me("git status --porcelain",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]});return tu(r)}catch(r){return console.error("Failed to get git status:",r),[]}}function tu(e){const t=e.trim().split(`
143
+ `).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,u;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 h=i.indexOf(" -> ");h!==-1&&(u=i.slice(0,h).trim(),i=i.slice(h+4).trim())}else o==="?"?(l="untracked",d=!1):(l="modified",d=s!==" "&&s!=="?");if(i.endsWith("/")){const h=process.env.CODEYAM_ROOT_PATH||process.cwd(),m=be.join(h,i);try{const p=(g,y)=>{const w=xt.readdirSync(g,{withFileTypes:!0}),x=[];for(const v of w){const b=be.join(g,v.name),N=be.relative(h,b);v.isDirectory()?x.push(...p(b,y)):v.isFile()&&x.push(N)}return x},f=p(m,h);for(const g of f)r.push({path:g,status:l,staged:d,...u&&{oldPath:u}})}catch(p){console.error(`Failed to expand directory ${i}:`,p)}}else r.push({path:i,status:l,staged:d,...u&&{oldPath:u}})}return r}function nu(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Me("git branch --show-current",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()||null}catch(r){return console.error("Failed to get current branch:",r),null}}function ru(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const a=Me('git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null || echo ""',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().match(/refs\/remotes\/origin\/(.+)/);if(a)return a[1];try{return Me("git show-ref --verify --quiet refs/heads/main",{cwd:t,stdio:["pipe","pipe","ignore"]}),"main"}catch{try{return Me("git show-ref --verify --quiet refs/heads/master",{cwd:t,stdio:["pipe","pipe","ignore"]}),"master"}catch{return"main"}}}catch(r){return console.error("Failed to get default branch:",r),"main"}}function au(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Me('git branch --format="%(refname:short)"',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
144
+ `).filter(a=>a.length>0)}catch(r){return console.error("Failed to get branches:",r),[]}}function Ps(){const e=ye();return e?eu(e):[]}function su(){const e=ye();return e?nu(e):null}function ou(){const e=ye();return e?ru(e):"main"}function iu(){const e=ye();return e?au(e):[]}function ks(e,t){const r=ye();return r?lu(e,t,r):[]}function lu(e,t,r){const a=r||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Me(`git diff --name-status ${e}...${t}`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
145
+ `).filter(i=>i.length>0).map(i=>{const l=i.split(" "),d=l[0];let u=l[1],h,m;return d==="A"?m="added":d==="M"?m="modified":d==="D"?m="deleted":d.startsWith("R")?(m="renamed",h=l[1],u=l[2]):m="modified",{path:u,status:m,...h&&{oldPath:h}}})}catch(s){return console.error("Failed to get branch diff:",s),[]}}function cu(e,t){const r=t||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let a="";try{a=Me(`git show HEAD:"${e}"`,{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{a=""}let s="";try{s=xt.readFileSync(be.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 du(e){const t=ye();return t?cu(e,t):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function uu(e,t,r,a){const s=a||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let o="";try{o=Me(`git show ${t}:"${e}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{o=""}let i="";try{i=Me(`git show ${r}:"${e}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{i=""}return{oldContent:o,newContent:i,fileName:e}}catch(o){return console.error(`Failed to get branch diff for ${e}:`,o),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function un(e,t,r){const a=ye();return a?uu(e,t,r,a):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function ya(e,t){var r,a;try{return((a=(r=Me(`git rev-parse ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}))==null?void 0:r.toString())==null?void 0:a.trim())??null}catch(s){return console.error(`Failed to get commit SHA for ${e}:`,s),""}}function hu(e,t,r,a){const s=lr.createHash("sha256");return s.update(`${e}:${t}:${r}:${a}`),s.digest("hex").substring(0,16)}function Ms(){const e=ye();if(!e)throw new Error("No project root found");const t=be.join(e,".codeyam","cache","branch-entity-diff");return xt.existsSync(t)||xt.mkdirSync(t,{recursive:!0}),t}function mu(e){try{const t=Ms(),r=be.join(t,`${e}.json`);if(!xt.existsSync(r))return null;const a=xt.readFileSync(r,"utf8");return JSON.parse(a)}catch(t){return console.error("Failed to read cache:",t),null}}function pu(e,t){try{const r=Ms(),a=be.join(r,`${e}.json`);xt.writeFileSync(a,JSON.stringify(t,null,2))}catch(r){console.error("Failed to write cache:",r)}}function fu(e,t,r){const a=gn(t,e),s=gn(r,e),o=new Map(a.map(h=>[h.name,h])),i=new Map(s.map(h=>[h.name,h])),l=[],d=[],u=[];for(const[h,m]of i){const p=o.get(h);p?p.sha!==m.sha&&d.push({name:h,baseSha:p.sha,compareSha:m.sha,entityType:m.entityType}):l.push(m)}for(const[h,m]of o)i.has(h)||u.push(m);return{filePath:e,newEntities:l,modifiedEntities:d,deletedEntities:u}}function gu(e,t){const r=ye();if(!r)throw new Error("No project root found");const a=ya(e,r),s=ya(t,r);if(!a||!s)throw new Error(`Failed to get commit SHAs for branches: ${e}, ${t}`);const o=hu(e,t,a,s),i=mu(o);if(i)return console.log(`Using cached branch entity diff: ${o}`),i;const l=ks(e,t),d=[];for(const h of l)if(h.path.match(/\.(tsx?|jsx?)$/))if(h.status==="deleted"){const m=un(h.path,e,t),p=gn(m.oldContent,h.path);d.push({filePath:h.path,newEntities:[],modifiedEntities:[],deletedEntities:p})}else if(h.status==="added"){const m=un(h.path,e,t),p=gn(m.newContent,h.path);d.push({filePath:h.path,newEntities:p,modifiedEntities:[],deletedEntities:[]})}else{const m=un(h.path,e,t),p=fu(h.path,m.oldContent,m.newContent);(p.newEntities.length>0||p.modifiedEntities.length>0||p.deletedEntities.length>0)&&d.push(p)}const u={baseBranch:e,compareBranch:t,baseCommitSha:a,compareCommitSha:s,fileComparisons:d,cacheKey:o,computedAt:new Date().toISOString()};return pu(o,u),u}function yu({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("base"),a=t.searchParams.get("compare");if(!r||!a)return Y({error:"Missing required parameters: base and compare"},{status:400});const s=gu(r,a);return Y(s)}catch(t){return console.error("Failed to compute branch entity diff:",t),Y({error:"Failed to compute branch entity diff",details:t instanceof Error?t.message:String(t)},{status:500})}}const xu=Object.freeze(Object.defineProperty({__proto__:null,loader:yu},Symbol.toStringTag,{value:"Module"}));async function bu({request:e}){if(e.method!=="POST")return Y({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 Y({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=ye();if(!i)return Y({error:"Project root not found"},{status:500});const l=X.join(i,"background","src","lib","virtualized","playwright","captureFromUrl.ts"),d=JSON.stringify({url:r,scenarioId:a,projectId:s,projectRoot:i,viewportWidth:o}),u=await new Promise(p=>{const f=X.join(i,".codeyam","db.sqlite3"),g=cr("npx",["tsx",l,d],{cwd:i,env:{...process.env,SQLITE_PATH:f}});let y="",w="";g.stdout.on("data",x=>{const v=x.toString();y+=v;const b=v.trim().split(`
146
+ `);for(const N of b)N.includes("[Capture]")&&console.log(N)}),g.stderr.on("data",x=>{const v=x.toString();w+=v,console.error("[Capture:Error]",v.trim())}),g.on("close",x=>{p(x===0?{success:!0,output:y}:{success:!1,output:y,error:w||`Process exited with code ${x}`})}),g.on("error",x=>{console.error("[Capture] Failed to spawn child process:",x),p({success:!1,output:"",error:x.message})})});if(!u.success)return Y({error:"Failed to capture screenshot",details:u.error},{status:500});const h=u.output.match(/\[Capture\] RESULT:(.+)/);if(!h)return Y({error:"Failed to parse capture result"},{status:500});const m=JSON.parse(h[1]);return Y(m)}catch(t){return console.error("[Capture] Error:",t),Y({error:"Failed to capture screenshot",details:t instanceof Error?t.message:String(t)},{status:500})}}const vu=Object.freeze(Object.defineProperty({__proto__:null,action:bu},Symbol.toStringTag,{value:"Module"}));async function wu(e,t,r){var f;console.log(`[recapture] Starting recapture for analysis ${e} with width ${t}`),await Oe();const a=await rt({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);const s=ve(),o=a.entitySha,i=await s.selectFrom("entities").select(["metadata"]).where("sha","=",o).executeTakeFirst();let l={};if(i!=null&&i.metadata&&(typeof i.metadata=="string"?l=JSON.parse(i.metadata):l=i.metadata),l.defaultWidth=t,await s.updateTable("entities").set({metadata:JSON.stringify(l)}).where("sha","=",o).execute(),console.log(`[recapture] Updated defaultWidth for entity ${o} to ${t}`),!a.commit)throw new Error(`Commit not found for analysis ${e}`);console.log(`[recapture] Loaded analysis with ${((f=a.scenarios)==null?void 0:f.length)||0} scenarios`),await Rt(e,g=>{if(g){if(g.readyToBeCaptured=!0,g.scenarios)for(const y of g.scenarios)delete y.finishedAt,delete y.startedAt,delete y.screenshotStartedAt,delete y.screenshotFinishedAt,delete y.interactiveStartedAt,delete y.interactiveFinishedAt,delete y.error,delete y.errorStack;delete g.finishedAt}}),console.log(`[recapture] Marked analysis ${e} as ready to be captured`);const d=ye();if(!d)throw new Error("Project root not found");const u=X.join(d,".codeyam","config.json"),h=JSON.parse(q.readFileSync(u,"utf8")),{projectSlug:m}=h;if(!m)throw new Error("Project slug not found in config");const{jobId:p}=r.enqueue({type:"recapture",commitSha:a.commit.sha,projectSlug:m,analysisId:e,defaultWidth:t});return console.log(`[recapture] Recapture job queued with ID: ${p}`),{jobId:p}}async function Cu(e,t,r){var h;console.log(`[recapture] Starting scenario recapture for analysis ${e}, scenario ${t}`),await Oe();const a=await rt({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=(h=a.scenarios)==null?void 0:h.find(m=>m.id===t);if(!s)throw console.log(`[recapture] Scenario ${t} not found in analysis ${e}`),new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[recapture] Found scenario: ${s.name}`),await Rt(e,m=>{if(m&&(m.readyToBeCaptured=!0,delete m.finishedAt,m.scenarios)){const p=m.scenarios.find(f=>f.name===s.name);p&&(delete p.finishedAt,delete p.startedAt,delete p.error,delete p.errorStack,delete p.screenshotStartedAt,delete p.screenshotFinishedAt,delete p.interactiveStartedAt,delete p.interactiveFinishedAt)}}),console.log(`[recapture] Cleared errors and marked scenario ${s.name} for recapture`);const o=ye();if(!o)throw new Error("Project root not found");const i=X.join(o,".codeyam","config.json"),l=JSON.parse(q.readFileSync(i,"utf8")),{projectSlug:d}=l;if(!d)throw new Error("Project slug not found in config");const{jobId:u}=r.enqueue({type:"recapture",commitSha:a.commit.sha,projectSlug:d,analysisId:e,scenarioId:t});return console.log(`[recapture] Scenario recapture job queued with ID: ${u}`),{jobId:u}}async function Nu({request:e,context:t}){if(e.method!=="POST")return Y({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await at()),!r)return Y({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("analysisId"),o=a.get("scenarioId");if(!s||!o)return Y({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Starting scenario recapture for analysis ${s}, scenario ${o}`);const i=await Cu(s,o,r);return console.log("[API] Scenario recapture queued",i),Y({success:!0,message:"Scenario recapture queued",...i})}catch(a){return console.log("[API] Error during scenario recapture:",a),Y({error:"Failed to recapture scenario",details:a instanceof Error?a.message:String(a)},{status:500})}}const Su=Object.freeze(Object.defineProperty({__proto__:null,action:Nu},Symbol.toStringTag,{value:"Module"}));async function Au({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=Mn(r);try{return await Yo(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 Eu({params:e}){const{projectSlug:t}=e;if(!t)return new Response("Project slug is required",{status:400});const r=Mn(t);try{if(!jo(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 zo(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 _u=Object.freeze(Object.defineProperty({__proto__:null,action:Au,loader:Eu},Symbol.toStringTag,{value:"Module"}));async function Pu(e,t){var o,i,l,d,u,h;console.log(`[executeLibraryFunction] Starting execution for analysis ${e}, scenario ${t}`),await Oe();const r=await rt({id:e,includeScenarios:!0,includeFile:!0});if(!r)throw new Error(`Analysis ${e} not found`);const a=(o=r.scenarios)==null?void 0:o.find(m=>m.id===t);if(!a)throw new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[executeLibraryFunction] Executing ${r.entityName} with scenario ${a.name}`);const s={returnValue:{status:"success",data:((d=(l=(i=a.metadata)==null?void 0:i.data)==null?void 0:l.argumentsData)==null?void 0:d[0])||{},timestamp:new Date().toISOString()},error:null,sideEffects:{consoleOutput:[{level:"log",args:[`Executing ${r.entityName}...`]},{level:"log",args:["Processing input:",JSON.stringify((h=(u=a.metadata)==null?void 0:u.data)==null?void 0:h.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 ku({request:e}){if(e.method!=="POST")return Y({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("analysisId"),a=t.get("scenarioId");if(!r||!a)return Y({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Executing library function for analysis ${r}, scenario ${a}`);const s=await Pu(r,a);return console.log("[API] Function execution completed successfully"),Y({success:!0,result:s})}catch(t){return console.log("[API] Error during function execution:",t),Y({success:!1,error:"Failed to execute function",details:t instanceof Error?t.message:String(t)},{status:500})}}const Mu=Object.freeze(Object.defineProperty({__proto__:null,action:ku},Symbol.toStringTag,{value:"Module"}));function Tu({request:e}){return Y({status:"ok"})}async function Iu({request:e,context:t}){if(e.method!=="POST")return Y({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await at()),!r)return console.error("[Interactive Mode API] Queue not initialized"),Y({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 Y({error:"Missing required fields: action and analysisId"},{status:400});if(s!=="start"&&s!=="stop")return Y({error:'Invalid action. Must be "start" or "stop"'},{status:400});const l=await Fe();if(console.log("[Interactive Mode API] projectSlug:",l),!l)return Y({error:"Project not initialized"},{status:500});if(s==="start"){const d=await r.enqueue({type:"interactive-start",analysisId:o,scenarioId:i,projectSlug:l});return Y({success:!0,action:"start",message:"Interactive mode starting...",jobId:d})}else{const d=await r.enqueue({type:"interactive-stop",analysisId:o,projectSlug:l});return Y({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),Y({error:"Failed to control interactive mode",details:s},{status:500})}}const ju=Object.freeze(Object.defineProperty({__proto__:null,action:Iu,loader:Tu},Symbol.toStringTag,{value:"Module"}));async function $u({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=ye();if(s)for(const o of a){const i=be.join(s,".codeyam","captures","screenshots",o);try{await Te.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 qi({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 Ru=Object.freeze(Object.defineProperty({__proto__:null,action:$u},Symbol.toStringTag,{value:"Module"})),Wt="/tmp/codeyam",nr=process.env.CODEYAM_API_BASE||"https://dev.codeyam.com",Ts=500,Du=Ts*1024*1024;function ft(e,t){try{return Me(`git ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return null}}function hn(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Lu(e){return ft("config user.email",e)}function Ou(e){const t=X.join(e,".codeyam","debug-report.md");if(!q.existsSync(t))return null;try{return q.readFileSync(t,"utf8")}catch{return null}}function Fu(e,t=20){const r=X.join(Wt,"local-dev",e,"codeyam","log.txt");if(!q.existsSync(r))return[];try{return q.readFileSync(r,"utf8").split(`
147
+ `).filter(i=>i.includes("CodeYam Log Level 1")).slice(-t)}catch{return[]}}async function Yu(e){try{const t=await fetch(`${nr}/api/reports/check-base`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({baseSha:e})});if(!t.ok)return!1;const{hasBase:r}=await t.json();return r}catch{return!1}}function zu(e,t){try{Me(`git archive HEAD | gzip > "${t}"`,{cwd:e,stdio:"pipe",shell:"/bin/bash"})}catch(r){throw new Error(`Failed to create base archive: ${r.message}`)}}function Bu(e){const{projectRoot:t,projectSlug:r,outputPath:a,metadata:s,screenshot:o,onProgress:i}=e,l=i||(()=>{}),d=Date.now(),u=X.join(Wt,`delta-staging-${d}`),h=X.join(u,"delta");q.mkdirSync(h,{recursive:!0});try{const m=ft("diff --binary HEAD",t)||"";q.writeFileSync(X.join(h,"tracked.patch"),m);const p=ft("ls-files --others --exclude-standard",t);if(p){const w=X.join(h,"untracked");q.mkdirSync(w,{recursive:!0});for(const x of p.split(`
148
+ `).filter(Boolean)){const v=X.join(t,x),b=X.join(w,x);if(q.existsSync(v)){const N=X.dirname(b);q.mkdirSync(N,{recursive:!0}),q.statSync(v).isFile()&&q.copyFileSync(v,b)}}}const f=X.join(t,".codeyam");if(q.existsSync(f)){const w=X.join(h,"codeyam");q.cpSync(f,w,{recursive:!0})}q.writeFileSync(X.join(h,"meta.json"),JSON.stringify(s,null,2));const g=X.join(Wt,"local-dev",r,"codeyam","log.txt");q.existsSync(g)?q.copyFileSync(g,X.join(h,"codeyam-log.txt")):q.writeFileSync(X.join(h,"codeyam-log.txt"),`# Log file not found
149
+ `);const y=X.join(t,".codeyam","debug-report.md");q.existsSync(y)&&(q.copyFileSync(y,X.join(h,"debug-report.md")),l("Debug report included")),o&&o.length>0&&(q.writeFileSync(X.join(h,"screenshot.jpg"),o),l(`Screenshot included (${hn(o.length)})`));try{Me(`tar -czf "${a}" -C "${u}" delta`,{stdio:"pipe"})}catch(w){throw new Error(`tar failed: ${w.message}`)}}finally{q.rmSync(u,{recursive:!0,force:!0})}}async function Uu(e){const{projectRoot:t,projectSlug:r,feedback:a,screenshot:s,onProgress:o}=e,i=o||(()=>{});i("Gathering metadata...");const l=ft("rev-parse HEAD",t);if(!l)throw new Error("At least one commit is required to generate a bundle. Please commit your changes first.");const d=ft("rev-parse --abbrev-ref HEAD",t)||"unknown",u=ft("status --porcelain",t),h=ft("remote get-url origin",t),m=u!==null&&u.length>0,p=xs(r),f=Ou(t);let g=a;f&&(g={...a||{issueType:"other",source:"cli"},debugReport:f},i("Found debug report from /debug-codeyam workflow"));const y={timestamp:new Date().toISOString(),projectSlug:r,git:{sha:l,branch:d,isDirty:m,remoteUrl:h},versions:{cli:p.cliVersion,webserver:p.webserverVersion,node:process.version},system:{platform:process.platform,arch:process.arch},feedback:g},w=Date.now(),x=X.join(Wt,`base-${l}-${w}.tar.gz`),v=X.join(Wt,`delta-${r}-${w}.tar.gz`);i("Checking for existing base...");const b=await Yu(l);let N=null;b?i("Server already has base, skipping..."):(i("Generating base archive..."),zu(t,x),N=q.statSync(x).size,i(`Base archive: ${hn(N)}`)),i("Generating delta archive..."),Bu({projectRoot:t,projectSlug:r,outputPath:v,metadata:y,screenshot:s,onProgress:o});const S=q.statSync(v).size;i(`Delta archive: ${hn(S)}`);const A=(N||0)+S;if(A>Du)throw q.existsSync(x)&&q.unlinkSync(x),q.unlinkSync(v),new Error(`Bundle too large: ${hn(A)} (max: ${Ts} MB). Try removing large files from the project or adding them to .gitignore`);return{basePath:b?null:x,deltaPath:v,metadata:y,baseSha:l,baseSize:N,deltaSize:S}}async function Wu(e){const{basePath:t,deltaPath:r,projectSlug:a,metadata:s,baseSha:o,deltaSize:i,onProgress:l}=e,d=l||(()=>{}),u=q.statSync(r),h=t?q.statSync(t):null,m=u.size+((h==null?void 0:h.size)||0);d("Requesting upload URLs...");const p=await fetch(`${nr}/api/reports/request-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectSlug:a,fileSizeBytes:m,baseSha:o,needsBaseUpload:t!==null,deltaSizeBytes:i,metadata:{timestamp:s.timestamp,git:s.git,versions:s.versions,system:s.system,feedback:s.feedback}})});if(!p.ok){const b=await p.json();throw new Error(b.error||`Server returned ${p.status}`)}const{reportId:f,deltaUploadUrl:g,baseUploadUrl:y}=await p.json(),w=[];if(t&&y){d("Uploading base...");const b=q.readFileSync(t);w.push(fetch(y,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:b}).then(N=>{if(!N.ok)throw new Error(`Base upload failed: ${N.status}`)}))}d("Uploading delta...");const x=q.readFileSync(r);w.push(fetch(g,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:x}).then(b=>{if(!b.ok)throw new Error(`Delta upload failed: ${b.status}`)})),await Promise.all(w),d("Confirming upload...");const v=await fetch(`${nr}/api/reports/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reportId:f})});if(!v.ok){const b=await v.json();throw new Error(b.error||`Confirm failed: ${v.status}`)}return t&&q.existsSync(t)&&q.unlinkSync(t),q.unlinkSync(r),{bundleId:f}}async function Hu({request:e}){if(e.method!=="POST")return Y({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"),u=t.get("currentUrl"),h=t.get("screenshot");let m;if(h&&h.size>0){const v=await h.arrayBuffer();m=Buffer.from(v),console.log(`[Bundle] Screenshot received: ${h.size} bytes`)}const p=ye();if(!p)return Y({error:"Project root not found"},{status:500});const f=await Fe();if(!f)return Y({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:u||void 0,recentActivity:Fu(f,20)};console.log(`[Bundle] Generating bundle for ${f}...`),console.log(`[Bundle] Context: ${g.source}, issue: ${g.issueType}`);const y=await Uu({projectRoot:p,projectSlug:f,feedback:g,screenshot:m,onProgress:v=>{console.log(`[Bundle] ${v}`)}}),w=(y.baseSize||0)+y.deltaSize;console.log(`[Bundle] Archives created: delta=${y.deltaSize} bytes${y.basePath?`, base=${y.baseSize} bytes`:" (base reused)"}`);const x=await Wu({basePath:y.basePath,deltaPath:y.deltaPath,projectSlug:f,metadata:y.metadata,baseSha:y.baseSha,deltaSize:y.deltaSize,onProgress:v=>{console.log(`[Bundle] ${v}`)}});return console.log(`[Bundle] Upload complete: ${x.bundleId}`),Y({success:!0,reportId:x.bundleId,size:w})}catch(t){return console.error("[Bundle] Error:",t),Y({error:t.message||"Failed to generate bundle"},{status:500})}}function Vu(){const e=ye(),t=e?Lu(e):null;return Y({defaultEmail:t})}const Ju=Object.freeze(Object.defineProperty({__proto__:null,action:Hu,loader:Vu},Symbol.toStringTag,{value:"Module"})),xa=ur(dr);async function Gu({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=qu(o),l=i?await Ku(o):null;return{pid:o,isRunning:i,processName:l}}));return Response.json({processes:s})}function qu(e){try{return process.kill(e,0),!0}catch{return!1}}async function Ku(e){try{const{stdout:t}=await xa(`ps -p ${e} -o comm=`);return t.trim()||null}catch{try{const{stdout:r}=await xa(`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 Qu=Object.freeze(Object.defineProperty({__proto__:null,loader:Gu},Symbol.toStringTag,{value:"Module"}));async function Xu({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{analysis:r,scenarios:a}=t;if(!r||!a)return Response.json({error:"Missing required fields: analysis and scenarios"},{status:400});console.log(`[API] Saving scenarios for analysis ${r.id}`),console.log(`[API] Received ${a.length} scenarios to save`),a.forEach((l,d)=>{var m,p,f,g,y;const u=(p=(m=l.metadata)==null?void 0:m.data)==null?void 0:p.argumentsData,h=Array.isArray(u)&&u.length>0?JSON.stringify(u[0]).substring(0,200):"empty-or-not-array";console.log(`[API] Scenario ${d}: ${l.name}`,{id:l.id,projectId:l.projectId,analysisId:l.analysisId,hasMetadata:!!l.metadata,hasData:!!((f=l.metadata)!=null&&f.data),mockDataKeys:(y=(g=l.metadata)==null?void 0:g.data)!=null&&y.mockData?Object.keys(l.metadata.data.mockData):[],argumentsDataLength:Array.isArray(u)?u.length:"not-array",argumentsDataPreview:h})});const s=a.map(l=>({...l,projectId:l.projectId||r.projectId,analysisId:l.analysisId||r.id})),o=await ts(s);if(!o||o.length===0)throw new Error("Failed to save scenarios to database");console.log(`[API] Scenarios saved successfully for analysis ${r.id}`),console.log(`[API] Saved ${o.length} scenarios to database`),o.forEach((l,d)=>{var h,m;const u=(m=(h=l.metadata)==null?void 0:h.data)==null?void 0:m.argumentsData;console.log(`[API] Saved scenario ${d}: ${l.name}`,{id:l.id,argumentsDataLength:Array.isArray(u)?u.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 Zu=Object.freeze(Object.defineProperty({__proto__:null,action:Xu},Symbol.toStringTag,{value:"Module"}));async function eh({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(!ba(r))return Response.json({error:"Process not running",pid:r},{status:404});try{process.kill(r,a)}catch(h){return Response.json({error:"Failed to kill process",pid:r,details:h instanceof Error?h.message:String(h)},{status:500})}const i=3e4,l=500,d=Date.now();let u=!0;for(;u&&Date.now()-d<i;)await new Promise(h=>setTimeout(h,l)),u=ba(r);if(u){console.warn(`Process ${r} didn't die after SIGTERM, sending SIGKILL`);try{process.kill(r,"SIGKILL"),await new Promise(h=>setTimeout(h,2e3))}catch(h){console.error(`Failed to SIGKILL process ${r}:`,h)}}if(s)try{await Mt({commitSha:s,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:`Process ${r} killed by user`}})}catch(h){console.error("Failed to update database after killing process:",h)}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 ba(e){try{return process.kill(e,0),!0}catch{return!1}}const th=Object.freeze(Object.defineProperty({__proto__:null,action:eh},Symbol.toStringTag,{value:"Module"}));async function nh({params:e}){const t=e["*"];if(!t)return new Response("Screenshot path is required",{status:400});const r=ye();if(!r)return console.error("[screenshot api] Project root not found"),new Response("Project root not found",{status:500});const a=be.join(r,".codeyam","captures","screenshots",t);try{await Te.access(a);const s=await Te.readFile(a),o=be.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 rh=Object.freeze(Object.defineProperty({__proto__:null,loader:nh},Symbol.toStringTag,{value:"Module"})),va={visual:{label:"VISUAL",bgColor:"#f9f9f9",textColor:"#9040f5"},library:{label:"LIBRARY",bgColor:"#f9f9f9",textColor:"#06b6d5"},type:{label:"TYPE",bgColor:"#ffe1e1",textColor:"#db2627"},other:{label:"OTHER",bgColor:"#f9f9f9",textColor:"#646464"}};function Ar({type:e,className:t=""}){const r=va[e]||va.other;return n("div",{className:`inline-flex items-center justify-center px-[4px] rounded-[4px] ${t}`,style:{backgroundColor:r.bgColor,color:r.textColor,height:"15px"},children:n("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-semibold leading-[15px] uppercase",children:r.label})})}const ah={analyzer:{bgColor:"#e1e1e1",textColor:"#3e3e3e",borderColor:"#e1e1e1"},capture:{bgColor:"#e1e1e1",textColor:"#3e3e3e",borderColor:"#e1e1e1"},running:{bgColor:"#e8ffe6",textColor:"#00925d",borderColor:"#c3f3bf"},error:{bgColor:"#fee2e2",textColor:"#991b1b",borderColor:"#fecaca"}};function on({variant:e,pid:t,label:r,className:a=""}){const s=ah[e],o=r||(e==="analyzer"&&t?`Analyzer: ${t}`:e==="capture"&&t?`Capture: ${t}`:e==="running"?"Running":e==="error"?"Error":"");return n("div",{className:`inline-flex items-center justify-center px-[8px] rounded-[4px] ${a}`,style:{backgroundColor:s.bgColor,borderWidth:"1px",borderStyle:"solid",borderColor:s.borderColor,height:"20px"},children:n("span",{className:"font-['IBM_Plex_Sans']",style:{fontSize:"10px",fontWeight:400,lineHeight:"15px",color:s.textColor},children:o})})}function Le({screenshotPath:e,cacheBuster:t,alt:r,className:a="",title:s}){const[o,i]=j("loading"),[l,d]=j(!1),u=Ee(null),h=t?`/api/screenshot/${e}?cb=${t}`:`/api/screenshot/${e}`,m=()=>{i("success"),d(!0)},p=()=>{i("error"),d(!1)};return re(()=>{i("loading"),d(!1);const f=u.current;f!=null&&f.complete&&(f.naturalHeight!==0?(i("success"),d(!0)):(i("error"),d(!1)))},[h]),e?c("div",{className:"relative w-full h-full flex items-center justify-center",title:s,children:[n("img",{ref:u,src:h,alt:r,onLoad:m,onError:p,className:a||"max-w-full max-h-full object-contain",style:{visibility:l?"visible":"hidden",position:l?"relative":"absolute"}}),o==="loading"&&n("div",{className:"absolute inset-0 bg-gray-100 animate-pulse rounded flex items-center justify-center",children:n("svg",{className:"w-8 h-8 text-gray-300",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),o==="error"&&c("div",{className:"absolute inset-0 border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",children:[n("span",{className:"text-2xl text-gray-400",children:"📷"}),n("span",{className:"text-gray-400 whitespace-nowrap",children:"No Screenshot"})]})]}):n("div",{className:"w-full h-full border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",title:s,children:n("span",{className:"text-2xl text-gray-400",children:"📷"})})}let wa=!1;function sh(){if(wa)return;const e=document.createElement("style");e.textContent=`
150
+ @keyframes strongPulse {
151
+ 0%, 100% { opacity: 0.2; }
152
+ 50% { opacity: 1; }
153
+ }
154
+ `,document.head.appendChild(e),wa=!0}function Er({size:e="medium",className:t=""}){typeof document<"u"&&sh();const r={small:{sideDotSize:3,centerDotSize:4,gap:2},medium:{sideDotSize:4,centerDotSize:6,gap:2},large:{sideDotSize:6,centerDotSize:8,gap:3}},{sideDotSize:a,centerDotSize:s,gap:o}=r[e];return c("div",{className:`flex items-center justify-center ${t}`,style:{gap:`${o}px`},role:"status","aria-label":"Loading",children:[n("div",{className:"rounded-full",style:{width:`${a}px`,height:`${a}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0s"}}),n("div",{className:"rounded-full",style:{width:`${s}px`,height:`${s}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.3s"}}),n("div",{className:"rounded-full",style:{width:`${a}px`,height:`${a}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.6s"}})]})}async function oh({request:e,context:t,params:r}){var K,Q,te,F,H,k,B,ne;let a=t.analysisQueue;a||(a=await at());const s=new URL(e.url),o=parseInt(s.searchParams.get("page")||"1",10),i=20,l=r.tab||"current";if(!a)return Y({error:"Queue not initialized",state:{paused:!1,jobs:[]},currentRun:void 0,historicalRuns:[],totalHistoricalRuns:0,currentPage:o,totalPages:0,projectSlug:null,commitSha:void 0,queueJobs:[],currentlyExecuting:null,currentEntities:[],tab:l,hasCurrentActivity:!1,queuedCount:0,recentCompletedEntities:[],hasMoreCompletedRuns:!1,currentEntityScenarios:[],currentEntityForScenarios:null,currentAnalysisStatus:null},{status:500});const d=a.getState(),u=await Fe();let h=null;if(u&&((K=d==null?void 0:d.currentlyExecuting)!=null&&K.commitSha)){const{project:V,branch:L}=await Ue(u),U=await yn({projectId:V.id,branchId:L.id,shas:[d.currentlyExecuting.commitSha]});h=U&&U.length>0?U[0]:null}else h=await Pt();const m=async V=>{const L=await Ct(V);if(!L)return null;const{getAnalysesForEntity:U}=await Promise.resolve().then(()=>Al),G=await U(V,!1);return{...L,analyses:G||[]}},p=await Promise.all(((d==null?void 0:d.jobs)||[]).map(async V=>{const L=[];if(V.entityShas&&V.entityShas.length>0){const U=V.entityShas.map(O=>m(O)),G=await Promise.all(U);L.push(...G.filter(O=>O!==null))}return{...V,entities:L}}));let f=null;if(d!=null&&d.currentlyExecuting){const V=d.currentlyExecuting,L=[];if(V.entityShas&&V.entityShas.length>0){const U=V.entityShas.map(O=>m(O)),G=await Promise.all(U);L.push(...G.filter(O=>O!==null))}f={...V,entities:L}}const g=f?p.filter(V=>V.id!==f.id):p,y=((te=(Q=h==null?void 0:h.metadata)==null?void 0:Q.currentRun)==null?void 0:te.currentEntityShas)||[],x=(await Promise.all(y.map(V=>m(V)))).filter(V=>V!==null),v=[];if(u)try{const{project:V,branch:L}=await Ue(u),U=await yn({projectId:V.id,branchId:L.id,limit:100});for(const G of U){const O=((F=G.metadata)==null?void 0:F.historicalRuns)||[];v.push(...O)}}catch(V){console.error("[activity.tsx] Failed to load historical runs from commits:",V)}const b=[...v].sort((V,L)=>{const U=V.archivedAt||V.createdAt||"";return(L.archivedAt||L.createdAt||"").localeCompare(U)}),N=(o-1)*i,T=N+i,S=b.slice(N,T),A=Math.ceil(b.length/i),P=await Promise.all(S.map(async V=>{const L=V.currentEntityShas||[];if(L.length===0)return{...V,entities:[]};const U=await Promise.all(L.map(G=>m(G)));return{...V,entities:U.filter(G=>G!==null)}})),I=!!f,M=p.length,R=b.filter(V=>{const L=!!V.failedAt,U=V.readyToBeCaptured,G=V.capturesCompleted??0,O=U===void 0?!0:U===0||G>=U;return!L&&!!V.analysisCompletedAt&&O}),E=new Set(((H=f==null?void 0:f.entities)==null?void 0:H.map(V=>V.sha))||[]),C=R.filter(V=>!(V.currentEntityShas||[]).some(U=>E.has(U))),$=(await Promise.all(C.slice(0,3).map(async V=>{const L=V.currentEntityShas||[];if(L.length===0)return{run:V,entities:[]};const U=await Promise.all(L.map(G=>m(G)));return{run:V,entities:U.filter(G=>G!==null)}}))).flatMap(({run:V,entities:L})=>L.map(U=>({...U,runId:V.id,completedAt:V.analysisCompletedAt||V.archivedAt||V.createdAt})));let D=[],z=null,W=null;if((B=(k=h==null?void 0:h.metadata)==null?void 0:k.currentRun)!=null&&B.analysisCompletedAt&&x.length>0){const V=x[0].sha;z=x[0];const L=await Pn(V);L&&L.length>0&&L[0].scenarios&&(D=L[0].scenarios,W=L[0].status)}return Y({state:{...d,jobs:g,currentlyExecuting:f},currentRun:(ne=h==null?void 0:h.metadata)==null?void 0:ne.currentRun,historicalRuns:P,totalHistoricalRuns:b.length,currentPage:o,totalPages:A,projectSlug:u,commitSha:h==null?void 0:h.sha,queueJobs:g,currentlyExecuting:f,currentEntities:x,tab:l,hasCurrentActivity:I,queuedCount:M,recentCompletedEntities:$,hasMoreCompletedRuns:C.length>3,currentEntityScenarios:D,currentEntityForScenarios:z,currentAnalysisStatus:W})}function ih({activeTab:e,hasCurrentActivity:t,queuedCount:r,historicCount:a}){const s=[{id:"current",label:"Current Activity",hasContent:t,count:t?1:null},{id:"queued",label:"Queued Activity",hasContent:r>0,count:r},{id:"historic",label:"Historic Activity",hasContent:a>0,count:a}];return n("div",{className:"border-b border-gray-200 mb-6",children:n("nav",{className:"flex gap-8",children:s.map(o=>{const i=e===o.id;return n(ce,{to:o.id==="current"?"/activity":`/activity/${o.id}`,className:`
155
+ relative pb-4 px-2 text-sm font-medium transition-colors cursor-pointer
156
+ ${i?"border-b-2":"text-gray-500 hover:text-gray-700"}
157
+ `,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:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${i?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:o.count}),o.count===null&&o.hasContent&&n("span",{className:`
158
+ inline-block w-2 h-2 rounded-full
159
+ ${i?"":"bg-gray-400"}
160
+ `,style:i?{backgroundColor:"#005C75"}:{}})]})},o.id)})})})}function lh({currentlyExecuting:e,currentRun:t,state:r,projectSlug:a,commitSha:s,onShowLogs:o,recentCompletedEntities:i,hasMoreCompletedRuns:l,currentEntityScenarios:d,currentEntityForScenarios:u,currentAnalysisStatus:h}){var I,M,R,E;const[m,p]=j({}),[f,g]=j({isKilling:!1,current:0,total:0}),y=lt(),w=!!e,x=(e==null?void 0:e.entities)||[],v=!!(t!=null&&t.analysisCompletedAt),b=v&&!!(t!=null&&t.capturePid),N=!v,T=w,S=d||[],{lastLine:A}=ct(a,T);re(()=>{if(!t)return;const C=[t.analyzerPid,t.capturePid].filter(z=>!!z);if(C.length===0)return;let _=!0;const $=async()=>{try{const W=await(await fetch(`/api/process-status?pids=${C.join(",")}`)).json();if(W.processes&&_){const K={};W.processes.forEach(Q=>{K[Q.pid]={isRunning:Q.isRunning,processName:Q.processName}}),p(K)}}catch(z){_&&console.error("Failed to fetch process statuses:",z)}};$();const D=setInterval(()=>void $(),5e3);return()=>{_=!1,clearInterval(D)}},[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid]);const P=x==null?void 0:x[0];return c("div",{className:"flex flex-col gap-[45px]",children:[T?c("div",{className:"rounded-[10px] p-[15px]",style:{backgroundColor:"#f6f9fc",border:"2px solid #e0e9ec"},children:[c("div",{className:"flex items-center gap-2 mb-[15px]",children:[n(nt,{size:14,strokeWidth:2.5,className:"animate-spin",style:{color:"#005c75"}}),n("span",{className:"font-medium",style:{fontSize:"14px",lineHeight:"18px",color:"#005c75"},children:b?"Capturing...":"Analyzing..."})]}),P&&c("div",{className:"bg-white border border-[#e1e1e1] rounded-[4px] mb-[15px]",style:{height:"60px",padding:"0 15px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[c("div",{className:"inline-grid place-items-start relative",style:{gridTemplateColumns:"max-content",gridTemplateRows:"max-content",lineHeight:0},children:[n("div",{className:"relative",style:{gridArea:"1 / 1",marginLeft:"10px",marginTop:"8.97px"},children:n("div",{style:{transform:"scale(1.33)"},children:n(Be,{type:P.entityType||"other"})})}),c("div",{className:"flex flex-col gap-[1px] relative",style:{gridArea:"1 / 1",marginLeft:"49px",marginTop:"0"},children:[c("div",{className:"flex items-center gap-[14px]",children:[n(ce,{to:`/entity/${P.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:P.name}),P.entityType&&n(Ar,{type:P.entityType})]}),n("div",{className:"truncate",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",width:"422px"},title:P.filePath,children:P.filePath})]})]}),n("button",{onClick:o,className:"px-[10px] rounded-[4px] transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},children:"View Logs"})]}),b&&S&&S.length>0&&u&&n("div",{className:"flex gap-[10px] overflow-x-auto mb-[15px]",children:S.map(C=>{var Q,te,F,H;if(!C.id)return null;const _=(te=(Q=C.metadata)==null?void 0:Q.screenshotPaths)==null?void 0:te[0],$=(F=C.metadata)==null?void 0:F.noScreenshotSaved,D=_&&!$,z=(H=h==null?void 0:h.scenarios)==null?void 0:H.find(k=>k.name===C.name),K=z&&z.screenshotStartedAt&&!z.screenshotFinishedAt||!D&&!$;return n(ce,{to:`/entity/${u.sha}/scenarios/${C.id}`,className:"border border-solid rounded-[6px] overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"160px",height:"90px",backgroundColor:K?"#f9f9f9":void 0,borderColor:K?"#efefef":"#ccc"},children:D?n(Le,{screenshotPath:_,alt:C.name,className:"w-full h-full object-contain bg-gray-100"}):K?n("div",{className:"w-full h-full flex items-center justify-center",children:n(Er,{size:"medium"})}):n("div",{className:"w-full h-full bg-gray-100 flex items-center justify-center text-xs text-gray-400",children:"No preview"})},C.id)})}),A&&n("div",{className:"mb-[15px] font-['IBM_Plex_Mono']",style:{fontSize:"12px",lineHeight:"20px",fontWeight:500,color:"#005c75"},children:A}),n("div",{className:"mb-[15px]",style:{height:"1px",backgroundColor:"#e0e9ec"}}),c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center gap-2",children:[c("span",{style:{fontSize:"12px",lineHeight:"15px",fontWeight:400,color:"#000"},children:["Running Processes:"," "]}),(t==null?void 0:t.analyzerPid)&&n(on,{variant:"analyzer",pid:t.analyzerPid}),(t==null?void 0:t.analyzerPid)&&(N||((I=m[t.analyzerPid])==null?void 0:I.isRunning))&&n(on,{variant:"running"}),(t==null?void 0:t.capturePid)&&n(on,{variant:"capture",pid:t.capturePid}),(t==null?void 0:t.capturePid)&&(b||((M=m[t.capturePid])==null?void 0:M.isRunning))&&n(on,{variant:"running"})]}),(((R=m[t==null?void 0:t.analyzerPid])==null?void 0:R.isRunning)||((E=m[t==null?void 0:t.capturePid])==null?void 0:E.isRunning))&&n("button",{onClick:()=>{const C=[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid].filter(D=>{var z;return!!D&&((z=m[D])==null?void 0:z.isRunning)});if(C.length===0)return;const _=C.join(", ");if(!confirm(`Are you sure you want to kill all running processes (${_})?`))return;g({isKilling:!0,current:1,total:C.length}),(async()=>{for(let D=0;D<C.length;D++){const z=C[D];try{await fetch("/api/kill-process",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:z,commitSha:s||""})})}catch(W){console.error(`Failed to kill process ${z}:`,W)}D<C.length-1&&g({isKilling:!0,current:D+2,total:C.length})}g({isKilling:!1,current:0,total:0}),y.revalidate()})()},disabled:f.isKilling,className:"px-[8px] rounded-[4px] transition-colors whitespace-nowrap cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",style:{backgroundColor:"#991b1b",color:"white",fontSize:"12px",lineHeight:"15px",fontWeight:500,height:"27px",width:"114px"},children:f.isKilling?"Killing...":"Kill All Processes"})]})]}):c("div",{className:"bg-[#efefef] rounded-xl p-8 text-center",children:[n("div",{className:"flex justify-center mb-4",children:n("div",{className:"p-[10px] bg-gray-200 rounded",children:n(Da,{size:24,className:"text-gray-600"})})}),n("h3",{className:"font-semibold text-gray-700 mb-2",style:{fontSize:"16px",lineHeight:"24px"},children:"No Current Activity"}),c("p",{className:"text-gray-500",style:{fontSize:"14px",lineHeight:"18px"},children:["There are no analyses currently running. Trigger an analysis from the"," ",n(ce,{to:"/git",className:"text-[#005C75] underline hover:text-[#004a5e] font-medium cursor-pointer",children:"Git"})," ","or"," ",n(ce,{to:"/files",className:"text-[#005C75] underline hover:text-[#004a5e] font-medium cursor-pointer",children:"Files"})," ","page."]})]}),i&&i.length>0&&c("div",{children:[n("h3",{className:"font-semibold",style:{fontSize:"16px",lineHeight:"24px",color:"#343434",marginBottom:"16px"},children:"Recently Completed Analyses"}),n("div",{className:"flex flex-col gap-4",children:i.map(C=>{var D;const _=(D=C.analyses)==null?void 0:D[0],$=(_==null?void 0:_.scenarios)||[];return _==null||_.status,n("div",{className:"rounded-[8px] p-[15px]",style:{backgroundColor:"#f2fcf9",border:"2px solid #aff1a9"},children:c("div",{className:"flex flex-col gap-[15px]",children:[c("div",{className:"flex items-center",children:[n("div",{className:"flex-shrink-0",style:{transform:"scale(1.33)",marginLeft:"10px"},children:n(Be,{type:C.entityType||"other"})}),c("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[c("div",{className:"flex items-center gap-[5px]",children:[n(ce,{to:`/entity/${C.sha}`,className:"hover:underline cursor-pointer",title:C.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:C.name}),n("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:"#e8ffe6",color:"#00925d",fontSize:"12px",lineHeight:"16px",fontWeight:400},children:C.isUncommitted?"Modified":"Up to date"})]}),n("div",{style:{fontSize:"13px",lineHeight:"18px",color:"#646464",fontWeight:400,width:"422px"},className:"truncate",title:C.filePath,children:C.filePath})]}),n("div",{className:"flex-1"}),n("div",{className:"flex-shrink-0",children:n("button",{onClick:o,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:z=>{z.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:z=>{z.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})})]}),$.length>0?n("div",{className:"flex gap-[10px] overflow-x-auto",children:$.map(z=>{var te,F,H;if(!z.id)return null;const W=(F=(te=z.metadata)==null?void 0:te.screenshotPaths)==null?void 0:F[0],K=(H=z.metadata)==null?void 0:H.noScreenshotSaved,Q=W&&!K;return n(ce,{to:`/entity/${C.sha}/scenarios/${z.id}`,className:"border border-[#ccc] border-solid rounded-[6px] overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"144px",height:"96px"},children:Q?n(Le,{screenshotPath:W,alt:z.name,className:"w-full h-full object-contain bg-gray-100"}):n("div",{className:"w-full h-full bg-gray-100 flex items-center justify-center text-xs text-gray-400",children:"No preview"})},z.id)})}):n("div",{className:"italic",style:{fontSize:"12px",color:"#646464"},children:"No scenarios available"})]})},C.sha)})})]})]})}function ch({queueJobs:e,state:t,currentRun:r}){if(!e||e.length===0)return c("div",{className:"rounded-xl p-12 text-center",style:{backgroundColor:"#f3f3f3"},children:[n("div",{className:"flex justify-center mb-4",children:n("div",{className:"p-[10px] rounded",style:{backgroundColor:"#e5e5e5"},children:n(wo,{size:24,style:{color:"#646464"}})})}),n("h3",{className:"font-semibold mb-2",style:{fontSize:"16px",lineHeight:"24px",color:"#343434"},children:"No Queued Jobs"}),n("p",{style:{fontSize:"14px",lineHeight:"18px",color:"#646464"},children:"Analysis jobs will appear here when they are queued but not yet started."})]});const[a,s]=j(null),[o,i]=j(null),[l,d]=j(null),[u,h]=j(!1),m=lt(),p=v=>{s(v)},f=(v,b)=>{v.preventDefault(),i(b)},g=async(v,b)=>{if(v.preventDefault(),!a){i(null);return}const N=e.findIndex(A=>A.id===a);if(N===-1){s(null),i(null);return}if(N===b){s(null),i(null);return}const T=N<b?"down":"up",S=Math.abs(b-N);h(!0);try{for(let A=0;A<S;A++)await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"reorder",jobId:a,direction:T})});m.revalidate()}catch(A){console.error("Failed to reorder job:",A)}finally{h(!1),s(null),i(null)}},y=()=>{u||(s(null),i(null))},w=async v=>{if(confirm("Are you sure you want to cancel this job?"))try{await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"remove",jobId:v})}),window.location.reload()}catch(b){console.error("Failed to cancel job:",b)}},x=async()=>{if(confirm(`Are you sure you want to cancel all ${e.length} queued jobs?`))try{await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clear"})}),window.location.reload()}catch(v){console.error("Failed to cancel jobs:",v)}};return c("div",{children:[c("div",{className:"flex items-center justify-between mb-4",children:[c("h3",{className:"font-semibold",style:{fontSize:"16px",lineHeight:"24px",color:"#343434"},children:[e.length," Queued Job",e.length!==1?"s":""]}),e.length>0&&n("button",{onClick:()=>void x(),className:"px-[10px] py-0 rounded transition-colors cursor-pointer hover:bg-red-300",style:{backgroundColor:"#ffdcd9",color:"#ef4444",fontSize:"12px",fontWeight:500,height:"29px"},children:"Cancel All"})]}),n("div",{className:"flex flex-col gap-3",children:e.map((v,b)=>{var P,I,M;const N=(P=v.entities)==null?void 0:P[0],T=l===b,S=a===v.id;return c("div",{className:"rounded-lg p-4 relative",style:{backgroundColor:"#f6f9fc",border:"2px solid #005C75",opacity:S||u?.5:1,transform:o===b&&a!==null&&!S?"translateY(-2px)":"translateY(0)",transition:"transform 0.2s ease, opacity 0.2s ease",cursor:u?"not-allowed":S?"grabbing":"grab"},onMouseEnter:()=>d(b),onMouseLeave:()=>d(null),draggable:!u,onDragStart:R=>{p(v.id),R.dataTransfer.effectAllowed="move"},onDragOver:R=>f(R,b),onDrop:R=>void g(R,b),onDragEnd:y,children:[c("div",{className:"absolute left-4 top-4 flex items-center gap-1.5 flex-shrink-0",children:[n(Da,{size:16,style:{color:"#005C75"}}),c("span",{style:{fontSize:"14px",fontWeight:500,lineHeight:"18px",color:"#005C75"},children:["Job ",b+1]})]}),n("div",{className:"bg-white rounded mt-8",style:{border:"1px solid #e1e1e1",height:"60px"},children:c("div",{className:"flex items-center justify-between h-full px-[15px]",children:[N?c("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{style:{transform:"scale(1.0)"},children:n(Be,{type:N.entityType||"other"})}),c("div",{className:"flex-1",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(ce,{to:`/entity/${N.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:N.name}),N.entityType&&n(Ar,{type:N.entityType})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:N.filePath})]})]}):c("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{style:{transform:"scale(1.0)"},children:n(Co,{size:18,style:{color:"#8e8e8e"}})}),c("div",{className:"flex-1",children:[n("div",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:((I=v.entityNames)==null?void 0:I[0])||(v.type==="analysis"?"Analysis Job":v.type==="recapture"?"Recapture Job":v.type==="debug-setup"?"Debug Setup":v.type.charAt(0).toUpperCase()+v.type.slice(1))}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:((M=v.filePaths)==null?void 0:M[0])||(v.filePaths&&v.filePaths.length>1?`${v.filePaths.length} files`:v.entityShas&&v.entityShas.length>0?`${v.entityShas.length} ${v.entityShas.length===1?"entity":"entities"}`:"Queued for processing")})]})]}),T&&n("div",{className:"mr-2 cursor-grab active:cursor-grabbing",style:{color:"#8e8e8e"},title:"Drag to reorder",children:n(No,{size:20})}),n("button",{onClick:()=>void w(v.id),className:"transition-colors cursor-pointer hover:bg-red-100 rounded flex items-center justify-center",style:{fontSize:"10px",fontWeight:600,lineHeight:"22px",color:"#ef4444",backgroundColor:"#fef6f6",padding:"0 10px",height:"22px"},children:"Cancel"})]})})]},v.id)})})]})}function dh({historicalRuns:e,totalHistoricalRuns:t,currentPage:r,totalPages:a,tab:s,onShowLogs:o}){if(t===0)return c("div",{className:"rounded-xl p-12 text-center",style:{backgroundColor:"#EFEFEF"},children:[n("div",{className:"flex justify-center mb-4",children:n(So,{size:24,style:{color:"#646464"}})}),n("h3",{className:"font-semibold mb-2",style:{fontSize:"16px",lineHeight:"24px",color:"#343434"},children:"No Historic Activity"}),n("p",{style:{fontSize:"14px",lineHeight:"18px",color:"#646464"},children:"Completed analyses will appear here for historical reference."})]});const i=[];return e.forEach(l=>{l.entities&&l.entities.length>0&&l.entities.forEach(d=>{i.push({...d,runCreatedAt:l.createdAt})})}),n("div",{className:"flex flex-col gap-4",children:i.slice(0,20).map(l=>{var m;const d=(m=l.analyses)==null?void 0:m[0],u=(d==null?void 0:d.scenarios)||[],h=!l.isUncommitted;return c("div",{className:"rounded-lg p-4",style:{backgroundColor:h?"#f2fcf9":"#fef9e7",border:"2px solid",borderColor:h?"#aff1a9":"#f9d689"},children:[c("div",{className:"flex items-start justify-between mb-3",children:[c("div",{className:"flex items-start gap-3 flex-1",children:[n("div",{style:{transform:"scale(1.0)",marginTop:"2px"},children:n(Be,{type:l.entityType||"other"})}),c("div",{className:"flex-1",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(ce,{to:`/entity/${l.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#343434"},children:l.name}),n("div",{className:"px-2 py-0.5 rounded",style:{backgroundColor:h?"#e8ffe6":"#fef3cd",color:h?"#00925d":"#a16207",fontSize:"12px",fontWeight:400},children:h?"Up to date":"Out of date"})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#646464"},children:l.filePath})]})]}),n("button",{onClick:o,className:"px-3 py-1 rounded transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),u.length>0&&c("div",{className:"flex gap-2 overflow-x-auto",children:[u.slice(0,8).map(p=>{var w,x,v;if(!p.id)return null;const f=(x=(w=p.metadata)==null?void 0:w.screenshotPaths)==null?void 0:x[0],g=(v=p.metadata)==null?void 0:v.noScreenshotSaved,y=f&&!g;return n(ce,{to:`/entity/${l.sha}/scenarios/${p.id}`,className:"border border-gray-300 rounded overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"120px",height:"80px"},children:y?n(Le,{screenshotPath:f,alt:p.name,className:"w-full h-full object-cover bg-gray-100"}):n("div",{className:"w-full h-full bg-gray-100 flex items-center justify-center text-xs text-gray-400",children:"No preview"})},p.id)}),u.length>8&&c("div",{className:"flex items-center justify-center flex-shrink-0",style:{width:"120px",height:"80px",fontSize:"12px",color:"#646464"},children:["+",u.length-8," more"]})]})]},`${l.sha}-${l.runCreatedAt}`)})})}const uh=We(function(){const t=Ge(),r=ja(),[a,s]=j(!1);Nt({source:"activity-page"});const o=r.tab||"current";return t?c("div",{className:"px-20 py-12",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-3xl font-semibold text-gray-900 mb-2",children:"Activity"}),n("p",{className:"text-gray-600",children:"View queued, current, and historical analysis activity."})]}),n(ih,{activeTab:o,hasCurrentActivity:t.hasCurrentActivity,queuedCount:t.queuedCount,historicCount:t.totalHistoricalRuns}),o==="current"&&n(lh,{currentlyExecuting:t.currentlyExecuting,currentRun:t.currentRun,state:t.state,projectSlug:t.projectSlug,commitSha:t.commitSha,onShowLogs:()=>s(!0),recentCompletedEntities:t.recentCompletedEntities||[],hasMoreCompletedRuns:t.hasMoreCompletedRuns||!1,currentEntityScenarios:t.currentEntityScenarios||[],currentEntityForScenarios:t.currentEntityForScenarios,currentAnalysisStatus:t.currentAnalysisStatus}),o==="queued"&&n(ch,{queueJobs:t.queueJobs,state:t.state,currentRun:t.currentRun}),o==="historic"&&n(dh,{historicalRuns:t.historicalRuns,totalHistoricalRuns:t.totalHistoricalRuns,currentPage:t.currentPage,totalPages:t.totalPages,tab:o,onShowLogs:()=>s(!0)}),a&&t.projectSlug&&n($t,{projectSlug:t.projectSlug,onClose:()=>s(!1)})]}):n("div",{className:"px-20 py-12",children:n("div",{className:"text-center",children:n("p",{className:"text-gray-600",children:"Loading..."})})})}),hh=Object.freeze(Object.defineProperty({__proto__:null,default:uh,loader:oh},Symbol.toStringTag,{value:"Module"}));async function Is(e,t,r){var N,T;await Oe();const a=await rt({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=ye();if(!s)throw new Error("Project root not found");const o=X.join(s,".codeyam","config.json"),i=JSON.parse(q.readFileSync(o,"utf8")),{projectSlug:l}=i;if(!l)throw new Error("Project slug not found in config");const d=Mn(l);try{q.writeFileSync(d,"","utf8")}catch{}const{project:u}=await Ue(l),h=((N=u.metadata)==null?void 0:N.packageManager)||"npm",m=3112,p=dt(l),f=((T=u.metadata)==null?void 0:T.webapps)||[];if(f.length===0)throw new Error(`No webapps found in project metadata for project ${l}`);const g=i.environmentVariables||[],y=Ji({filePath:a.filePath,webapps:f,environmentVariables:g,port:m,packageManager:h});await Rt(e,S=>{if(S&&(S.readyToBeCaptured=!0,S.scenarios))for(const A of S.scenarios)(!t||A.name===t)&&(delete A.screenshotStartedAt,delete A.screenshotFinishedAt,delete A.interactiveStartedAt,delete A.interactiveFinishedAt,delete A.error,delete A.errorStack)});const{jobId:w}=r.enqueue({type:"debug-setup",commitSha:a.commit.sha,projectSlug:l,analysisId:e,scenarioId:t,prepOnly:!0}),x=y.startCommand,v={title:"Debug Setup In Progress",sections:[{heading:"Status",items:[{content:"Setting up debug environment... This may take a minute."},{label:"Project Path",content:p}]},{heading:"What's Happening",items:[{content:"1. Preparing analyzer and dependencies"},{content:"2. Syncing project files"},{content:"3. Setting up mock environment"}]},{heading:"Next Steps (Once Complete)",items:[{label:"1. Open the project directory",content:`code ${p}`,isCode:!0},{label:"2. Start the development server (copy & paste this exact command)",content:x,isCode:!0},{label:"3. View the scenario in your browser",content:`http://localhost:${m}/static/codeyam-sample`,isLink:!0}]}]};return{success:!0,jobId:w,analysisId:e,scenarioId:t,projectPath:p,projectSlug:l,port:m,packageManager:h,framework:y.framework,instructions:v}}async function mh({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 Y({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 at()),!o)return Y({error:"Queue not initialized"},{status:500});console.log("[Debug Setup API] GET request for:",{analysisId:a,scenarioId:s});try{const i=await Is(a,s,o);return Y({...i,success:!0,message:"Debug setup queued"})}catch(i){return console.error("[Debug Setup API] GET Error:",i),Y({error:"Failed to setup debug environment",details:i.message},{status:500})}}async function ph({request:e,context:t}){if(e.method!=="POST")return Y({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await at()),!r)return Y({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("analysisId"),o=a.get("scenarioId");if(!s)return Y({error:"Missing required field: analysisId"},{status:400});const i=await Is(s,o,r);return Y({...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),Y({error:"Failed to setup debug environment",details:s},{status:500})}}const fh=Object.freeze(Object.defineProperty({__proto__:null,action:ph,loader:mh},Symbol.toStringTag,{value:"Module"}));async function gh({request:e,context:t}){if(e.method!=="POST")return Y({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await at()),!r)return Y({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("analysisId"),o=a.get("defaultWidth");if(!s||!o)return Y({error:"Missing required fields: analysisId and defaultWidth"},{status:400});const i=parseInt(o,10);if(isNaN(i)||i<320||i>3840)return Y({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 wu(s,i,r);return console.log("[API] Recapture queued",l),Y({success:!0,message:"Recapture queued",...l})}catch(a){return console.log("[API] Error during recapture:",a),Y({error:"Failed to recapture screenshots",details:a instanceof Error?a.message:String(a)},{status:500})}}const yh=Object.freeze(Object.defineProperty({__proto__:null,action:gh},Symbol.toStringTag,{value:"Module"}));function xh(e,t){var i,l,d,u,h;const r=((i=e.metadata)==null?void 0:i.isUncommitted)===!0,a=e.analyses&&e.analyses.length>0&&e.analyses.some(m=>m.scenarios&&m.scenarios.length>0);if(!r){const m=!!((l=e.metadata)!=null&&l.previousVersionWithAnalyses),p=a&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha!==e.sha;return m||p?a?{state:"committed_no_simulations",hasSimulations:!0,hasOutdatedSimulations:!0,canGenerateSimulations:!0,badge:{label:"Committed - Simulations Outdated",color:"text-orange-700",bgColor:"bg-orange-50",borderColor:"border-orange-300",icon:"⚠"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not Yet Analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}:a?{state:"committed_with_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up to date",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"✓"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}}const s=!!((d=e.metadata)!=null&&d.previousCommittedSha);if(!!((u=e.metadata)!=null&&u.previousVersionWithAnalyses)||s){const m=a&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha===((h=e.metadata)==null?void 0:h.previousVersionWithAnalyses);return a&&!m?{state:"uncommitted_with_new_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up-to-date Simulations",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"●"}}:a?{state:"uncommitted_outdated_simulations",hasSimulations:!0,hasOutdatedSimulations:!0,canGenerateSimulations:!0,badge:{label:"Edited - Simulations Outdated",color:"text-amber-700",bgColor:"bg-amber-50",borderColor:"border-amber-300",icon:"⚠"}}:{state:"uncommitted_outdated_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not Analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}}else return a?{state:"uncommitted_with_new_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up-to-date Simulations",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"●"}}:{state:"uncommitted_no_previous_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"New",color:"text-purple-700",bgColor:"bg-purple-50",borderColor:"border-purple-200",icon:"+"}}}function bh(e){return xh(e).hasOutdatedSimulations}function _r(e,t,r,a,s){var z,W,K,Q,te,F,H,k;const o=(z=t==null?void 0:t.scenarios)==null?void 0:z.find(B=>B.name===e.name),i=!!(o!=null&&o.startedAt),l=!!(o!=null&&o.screenshotStartedAt),d=!!(o!=null&&o.screenshotFinishedAt),u=!!(o!=null&&o.finishedAt),h=1800*1e3,m=l&&!d&&(o==null?void 0:o.screenshotStartedAt)&&Date.now()-new Date(o.screenshotStartedAt).getTime()>h,p=!!((K=(W=e.metadata)==null?void 0:W.screenshotPaths)!=null&&K[0])||!!((Q=e.metadata)!=null&&Q.executionResult),f=l&&!d,g=o==null?void 0:o.error,y=(F=(te=e.metadata)==null?void 0:te.executionResult)==null?void 0:F.error,w=[];if(t!=null&&t.errors&&t.errors.length>0)for(const B of t.errors)w.push({source:`${B.phase} phase`,message:B.message});if(t!=null&&t.steps)for(const B of t.steps)B.error&&w.push({source:B.name,message:B.error});const x=!p&&!g&&!y&&w.length>0,v=!!(g||y||m||x),b=m?"Capture timed out after 30 minutes":(typeof g=="string"?g:null)||(y==null?void 0:y.message)||(x?`Analysis error: ${w[0].message}`:null),N=m?"The capture process has been running for more than 30 minutes and likely got stuck. Consider re-running the analysis.":(o==null?void 0:o.errorStack)||(y==null?void 0:y.stack)||null,S=(a&&s?s.jobs.some(B=>{var ne;return((ne=B.entityShas)==null?void 0:ne.includes(a))||B.type==="analysis"&&B.entityShas&&B.entityShas.length===0})||((k=(H=s.currentlyExecuting)==null?void 0:H.entityShas)==null?void 0:k.includes(a)):!1)&&!i&&!v||!!(o!=null&&o.analyzing)&&!i&&!v,A=i&&!l&&!u&&!v,P=(S||A||f)&&!v,I=(S||A)&&r===!1&&!p;let M;I?M="crashed":v?M="error":p||u?M="completed":f?M="capturing":A?M="starting":S?M="queued":M="pending";let R="📷",E="pending",C=!1,_=`Not captured: ${e.name}`;const $="border-gray-300",D=v||I?"bg-red-50":"bg-white";return v||I?(R="⚠️",E="error",_=`Error: ${I?"Analysis process crashed":b||"Unknown error"}`):S?(R="⋯",E="queued",_=`Queued: ${e.name}`):A?(R="⋯",E="starting",C=!0,_=`Starting server for ${e.name}...`):f&&!v?(R="⋯",E="capturing",C=!0,_=`Capturing ${e.name}...`):p&&(R="✓",E="completed",_=e.name),{hasError:v||I,errorMessage:I?"Analysis process crashed":b,errorStack:I?"Process terminated unexpectedly before completing analysis":N,isCapturing:f,isCaptured:p,hasCrashed:I,isAnalyzing:P,isQueued:S,isServerStarting:A,status:M,icon:R,iconType:E,shouldSpin:C,title:_,borderColor:$,bgColor:D}}function js({scenario:e,entitySha:t,size:r="medium",showBorder:a=!0,isOutdated:s=!1}){var N,T,S,A,P,I;const o=_r(e,void 0,void 0,t,void 0),i=(N=e.metadata)==null?void 0:N.executionResult,l=!!i,u=(((S=(T=e.metadata)==null?void 0:T.data)==null?void 0:S.argumentsData)||[]).length,h=(i==null?void 0:i.returnValue)!==void 0&&(i==null?void 0:i.returnValue)!==null,m=((P=(A=i==null?void 0:i.sideEffects)==null?void 0:A.consoleOutput)==null?void 0:P.length)||0,p=((I=i==null?void 0:i.timing)==null?void 0:I.duration)||0;let f=0;u>0&&f++,u>2&&f++,h&&f++,m>0&&f++,f=Math.min(3,f);const g=r==="small"?{width:"w-[50px]",height:"h-[38px]",iconSize:"text-base",textSize:"text-[8px]"}:{width:"w-20",height:"h-15",iconSize:"text-xl",textSize:"text-[10px]"},w=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"},x=a?`border-2 ${w.border}`:"",v=Array.from({length:3},(M,R)=>n("div",{className:`w-1 h-1 rounded-full ${R<f?w.icon.replace("text-","bg-"):"bg-gray-300"}`},R)),b=o.hasError?`Error: ${o.errorMessage||"Unknown error"}`:l?`${e.name}
161
+ ${u} args → ${h?"value":"void"}${m>0?` (${m} logs)`:""}
162
+ ${p}ms`:`Not executed: ${e.name}`;return c(ce,{to:`/entity/${t}/scenarios/${e.id}`,className:`relative ${g.width} ${g.height} ${x} rounded ${w.bg} flex flex-col items-center justify-center gap-0.5 cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:b,onClick:M=>M.stopPropagation(),children:[n("div",{className:`${w.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} ${w.badge} px-1 rounded`,children:[n("span",{children:u}),n("span",{children:"→"}),n("span",{children:h?"✓":"∅"})]}),l&&!o.hasError&&r==="medium"&&n("div",{className:"flex gap-0.5 mt-0.5",children:v}),l&&!o.hasError&&p>100&&r==="medium"&&n("div",{className:`absolute top-0.5 right-0.5 ${g.textSize} ${w.badge} px-1 rounded`,children:p>1e3?`${Math.round(p/1e3)}s`:`${p}ms`}),l&&!o.hasError&&m>0&&r==="medium"&&c("div",{className:"absolute bottom-0.5 left-0.5 text-[8px] text-gray-500",children:["📝",m]})]})}function rr({size:e=24,className:t=""}){return c("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":"true",children:[n("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z",fill:"#ef4444",stroke:"none"}),n("line",{x1:"12",y1:"9",x2:"12",y2:"13",stroke:"#FFFFFF",strokeWidth:"2",strokeLinecap:"round"}),n("circle",{cx:"12",cy:"17",r:"1",fill:"#FFFFFF"})]})}function vh({scenario:e,entity:t,analysisStatus:r,queueState:a,processIsRunning:s,size:o="medium",cacheBuster:i,className:l="",viewMode:d}){var y,w;if(t.entityType==="library")return n(js,{scenario:e,entitySha:t.sha,size:o==="small"?"small":"medium"});const h=_r(e,r,s,t.sha,a),m=o==="small"?{containerClass:"w-16 h-12",iconSize:"text-xl"}:o==="large"?{containerClass:"w-full h-[67px]",iconSize:"text-2xl"}:{containerClass:"w-20 h-15",iconSize:"text-2xl"},p=`relative ${m.containerClass} ${l}`,f=()=>{const x=`/entity/${t.sha}/scenarios/${e.id}`;return d?`${x}/${d}`:x};if(h.isCaptured){const x=(w=(y=e.metadata)==null?void 0:y.screenshotPaths)==null?void 0:w[0];return n(ce,{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(Le,{screenshotPath:x,cacheBuster:i,alt:e.name,title:e.name,className:"max-w-full max-h-full object-contain object-center"})})}const g=()=>{const x={size:o==="small"?16:o==="large"?24:20,strokeWidth:2},v=n(Er,{size:o});if(h.shouldSpin||h.iconType==="queued"||h.iconType==="pending")return v;switch(h.iconType){case"starting":case"capturing":return v;case"error":return c("div",{className:"flex flex-col items-center justify-center gap-1",children:[n(rr,{size:24}),n("span",{className:"text-[10px] text-[#ef4444] font-medium",children:"Capture Error"})]});case"completed":return n(Ao,{...x});default:return v}};return n(ce,{to:f(),className:`${p} ${h.bgColor} flex flex-col items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:h.title,children:n("div",{className:m.iconSize,children:g()})})}const ln=70;function wh({scenarios:e,analysis:t,selectedScenario:r,entitySha:a,cacheBuster:s,activeTab:o,entityType:i,entity:l,queueState:d,processIsRunning:u,isEntityAnalyzing:h,viewMode:m,setViewMode:p,onDebugSetup:f,debugFetcher:g,isBreakdownView:y}){const w=Ee(null),[x,v]=j(new Set);re(()=>{w.current&&o==="scenarios"&&w.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[r==null?void 0:r.id,o]);const b=S=>`/entity/${a}/scenarios/${S}`,N=S=>{v(A=>{const P=new Set(A);return P.has(S)?P.delete(S):P.add(S),P})},T=(S,A=2)=>{const I=S.split(`
163
+ `).slice(0,A).join(" ").trim();return I.length>ln?I.substring(0,ln-3):(S.split(`
164
+ `).length>A||S.length>I.length,I)};return c("aside",{className:"w-[220px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-3",children:[p&&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 cursor-pointer ${m==="screenshot"?"bg-white text-[#3e3e3e] border-[#c7c7c7]":"bg-[#e1e1e1] text-[#626262] border-[rgba(0,92,117,0.05)] hover:bg-[#d4d4d4]"}`,onClick:()=>p("screenshot"),"aria-label":"Screenshot view","aria-pressed":m==="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 cursor-pointer ${m==="interactive"?"bg-white text-[#3e3e3e] border-[#c7c7c7]":"bg-[#e1e1e1] text-[#626262] border-[rgba(0,92,117,0.05)] hover:bg-[#d4d4d4]"}`,onClick:()=>p("interactive"),"aria-label":"Interactive view","aria-pressed":m==="interactive",children:"🎮 Interactive"})]})]}),r&&c("div",{className:"grid grid-cols-2 gap-1",children:[n(ce,{to:`/entity/${a}/scenarios/${r.id}/edit`,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:f,disabled:(g==null?void 0:g.state)!=="idle",title:"Setup Debug Environment",children:(g==null?void 0:g.state)==="idle"?"Debug Scenario":"Setting up..."})]}),l&&l.filePath&&n("div",{children:n(ce,{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"})}),t&&n("div",{children:c(ce,{to:`/entity/${a}/scenarios/breakdown`,className:`w-full px-[10px] py-[6px] border rounded text-[10px] font-normal cursor-pointer transition-colors no-underline flex flex-col items-start bg-white text-[#005c75] ${y?"border-[#005c75]":"border-[#e1e1e1] hover:border-[#005c75]"}`,children:[n("span",{className:"font-semibold",children:"Scenarios Breakdown"}),n("span",{className:"text-[9px] text-[#808080]",children:"View all key attributes and possible scenarios"})]})}),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:h?c(ue,{children:[c("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#FFF4FC",color:"#FF2AB5",height:"23px"},children:[c("svg",{width:"9",height:"9",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}),n("p",{className:"text-[#8e8e8e] text-xs font-normal m-0 mt-2 text-left leading-5",children:"Scenarios will appear here once analysis completes"})]}):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((S,A)=>{const P=!y&&(r==null?void 0:r.id)===S.id,I=x.has(S.id||"");return S.id?c(ce,{to:b(S.id),ref:P?w:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${P?"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(vh,{scenario:S,entity:{sha:a,entityType:i},analysisStatus:t==null?void 0:t.status,queueState:d,processIsRunning:u,size:"large",cacheBuster:s,viewMode:m})}),c("div",{className:"px-[7px] py-[6.444px]",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${I?"":"line-clamp-1"}`,children:S.name}),S.description&&n("div",{className:"mt-[4px]",children:c("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[I?S.description:T(S.description),!I&&S.description.length>ln&&c(ue,{children:["...",n("button",{onClick:M=>{M.preventDefault(),M.stopPropagation(),N(S.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),I&&S.description.length>ln&&n("button",{onClick:M=>{M.preventDefault(),M.stopPropagation(),N(S.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},A):null})})})]})}function Ch({scenario:e,entitySha:t,onApply:r,onSave:a,onEditMockData:s,onDelete:o,isApplying:i=!1,isSaving:l=!1,saveMessage:d=null,showDeleteConfirm:u=!1,onShowDeleteConfirm:h,isDeleting:m=!1,deleteError:p=null}){const[f,g]=j(""),y=async()=>{await r(f)},w=async x=>{await a(f,x),x||g("")};return c("aside",{className:"w-[220px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-3 h-full",children:[c("div",{className:"border-b border-[#e1e1e1] pb-3",children:[c("div",{className:"flex items-start justify-between mb-2",children:[n("div",{className:"text-[10px] text-[#626262] font-medium",children:"Edit Scenario"}),n(ce,{to:`/entity/${t}`,className:"text-[#626262] hover:text-[#3e3e3e] transition-colors text-sm leading-none no-underline cursor-pointer",title:"Close",children:"×"})]}),n("div",{className:"text-xs font-semibold text-[#626262]",children:e.name})]}),c("div",{className:"flex-1 overflow-y-auto flex flex-col gap-2",children:[c("div",{className:"pt-1",children:[n("label",{htmlFor:"ai-description",className:"block text-xs text-[#343434] font-semibold mb-[6px]",children:"Describe changes to the AI"}),n("textarea",{id:"ai-description",value:f,onChange:x=>g(x.target.value),placeholder:"e.g. change amount of data to zero",className:"w-full px-[7px] py-[6px] border border-[#c7c7c7] rounded-[4px] text-xs focus:outline-none focus:ring-1 focus:ring-[#005c75] focus:border-[#005c75] resize-none",rows:4}),c("button",{onClick:()=>void y(),disabled:i||!f.trim(),className:"w-full mt-1 h-[22px] bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center gap-1",children:[i&&c("svg",{className:"animate-spin h-3 w-3",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),i?"Applying...":"Apply"]})]}),n("div",{className:"border-t border-[#e1e1e1] my-1"}),c("div",{className:"pt-1",children:[n("div",{className:"text-xs text-[#343434] font-semibold mb-[6px]",children:"Change file"}),n("p",{className:"text-[10px] text-[#808080] mb-2",children:"You can edit the data used for this scenario directly."}),n("button",{onClick:s,className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa]",children:"Edit Mock Data"})]}),d&&n("div",{className:`text-[10px] px-[7px] py-[6px] rounded-[4px] ${d.startsWith("Error")?"bg-red-50 text-red-600":"bg-green-50 text-green-600"}`,children:d}),d==="Recapture successful"&&n("div",{children:n(ce,{to:`/entity/${t}`,className:"text-[#005c75] hover:text-[#004a5e] hover:underline text-[10px] cursor-pointer",children:"View updated screenshot on entity page →"})})]}),c("div",{className:"border-t border-[#e1e1e1] pt-2 bg-white flex flex-col gap-1",children:[n("button",{onClick:()=>void w(!1),disabled:l||!f.trim(),className:"w-full h-[22px] bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center",children:l?"Saving...":"Save Scenario Data"}),n("button",{onClick:()=>void w(!0),disabled:l||!f.trim(),className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa] disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center",children:"Save As New"}),o&&c(ue,{children:[u?c("div",{className:"flex flex-col gap-1",children:[c("div",{className:"text-[10px] text-red-600 font-medium",children:['Are you sure you want to delete "',e.name,'"?']}),c("div",{className:"flex gap-1",children:[n("button",{onClick:()=>void o(),disabled:m,className:"flex-1 h-[22px] bg-red-600 text-white rounded text-[10px] font-normal hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors flex items-center justify-center cursor-pointer",children:m?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>h==null?void 0:h(!1),disabled:m,className:"flex-1 h-[22px] bg-gray-100 text-gray-700 border border-gray-300 rounded text-[10px] font-normal hover:bg-gray-200 disabled:opacity-50 transition-colors flex items-center justify-center cursor-pointer",children:"Cancel"})]})]}):n("button",{onClick:()=>h==null?void 0:h(!0),className:"w-full h-[22px] bg-red-50 text-red-600 border border-red-200 rounded text-[10px] font-normal hover:bg-red-100 transition-colors flex items-center justify-center cursor-pointer",children:"Delete Scenario"}),p&&n("div",{className:"text-[10px] text-red-600 bg-red-50 px-[7px] py-[6px] rounded-[4px]",children:p})]})]})]})}function Nh({scenario:e,analysis:t,entity:r}){var i,l,d;const a=((i=e.metadata)==null?void 0:i.executionResult)||null,s=((d=(l=e.metadata)==null?void 0:l.data)==null?void 0:d.argumentsData)||[],o=u=>{var g,y,w;if(!u)return"No execution results available yet. Run the function to capture side effects including console output, file operations, and API calls.";const h=[],m=((g=u.sideEffects)==null?void 0:g.consoleOutput)||[];m.length>0&&(h.push(`Console Output: ${m.length} log ${m.length===1?"entry":"entries"} captured`),m.forEach(x=>{h.push(` [${x.level.toUpperCase()}] ${x.args.join(" ")}`)}));const p=((y=u.sideEffects)==null?void 0:y.fileWrites)||[];p.length>0&&(h.push(`
165
+ File System Operations: ${p.length} ${p.length===1?"operation":"operations"} detected`),p.forEach(x=>{h.push(` ${x.operation}: ${x.path}${x.size?` (${x.size} bytes)`:""}`)}));const f=((w=u.sideEffects)==null?void 0:w.apiCalls)||[];return f.length>0&&(h.push(`
166
+ API Calls: ${f.length} ${f.length===1?"call":"calls"} made`),f.forEach(x=>{h.push(` ${x.method} ${x.url}${x.status?` → ${x.status}`:""}${x.duration?` (${x.duration}ms)`:""}`)})),u.error&&h.push(`
167
+ Error: ${u.error.name||"Error"}: ${u.error.message}`),h.length===0?"No side effects detected. The function executed without console output, file operations, or API calls.":h.join(`
168
+ `)};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 pt={commandBoxBg:"#f6f9fc",commandBoxBorder:"#e1e1e1",commandBoxText:"#005c75",heading:"#000",subtext:"#646464",link:"#005c75"};function Ut({scenarioId:e,analysisId:t}){const[r,a]=j(!1),[s,o]=j(!1),[i,l]=j(null),[d,u]=j(!1),h=e||t;if(!h)return null;const m=`/debug-codeyam ${h}`,p=async()=>{o(!0);try{const{default:g}=await import("html2canvas-pro"),w=(await g(document.body,{scale:.5})).toDataURL("image/jpeg",.8);l(w),a(!0)}catch(g){console.error("Screenshot capture failed:",g),a(!0)}finally{o(!1)}},f=()=>{a(!1),l(null)};return c(ue,{children:[c("div",{className:"text-center p-6 bg-cywhite-100 rounded-lg border-cygray-30 border",children:[n("h3",{className:"font-semibold font-['IBM_Plex_Sans']",style:{fontSize:"18px",lineHeight:"26px",color:pt.heading},children:"Claude can help debug this error."}),n("p",{className:"m-0 mb-4 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"18px",color:pt.subtext},children:"Simply run this command in Claude Code:"}),c("div",{className:"flex items-center justify-between rounded mx-auto mb-3 border",style:{backgroundColor:pt.commandBoxBg,borderColor:pt.commandBoxBorder,maxWidth:"505px",height:"35px",paddingLeft:"13px",paddingRight:"13px",paddingTop:"6px",paddingBottom:"6px"},children:[n("code",{className:"font-mono font-['IBM_Plex_Mono'] flex-1 text-left",style:{fontSize:"12px",lineHeight:"20px",color:pt.commandBoxText},children:m}),n("button",{onClick:g=>{g.stopPropagation(),navigator.clipboard.writeText(m),u(!0),setTimeout(()=>u(!1),2e3)},className:"ml-3 cursor-pointer p-0 bg-transparent border-none hover:opacity-80 transition-opacity",style:{width:"14px",height:"14px",color:d?"#22c55e":pt.commandBoxText},title:d?"Copied!":"Copy command","aria-label":"Copy command to clipboard",children:d?n(Eo,{size:14}):n(_o,{size:14})})]}),c("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:"#005c75"},children:["If Claude is unable to address this issue or suggests reporting it,"," ",n("button",{onClick:()=>void p(),disabled:s,className:"underline cursor-pointer bg-transparent border-none p-0 font-normal hover:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:pt.link},children:s?"capturing...":"please do so here"}),"."]})]}),n(Ba,{isOpen:r,onClose:f,context:{source:e?"scenario-page":"entity-page",entitySha:void 0,scenarioId:e,analysisId:t,currentUrl:typeof window<"u"?window.location.pathname:"/"},screenshotDataUrl:i??void 0})]})}const Ca=1440,cn=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],tt={background:"#ffdcd9",border:"#fda4a4",text:"#ef4444",link:"#991b1b"};function $s({selectedScenario:e,analysis:t,entity:r,viewMode:a,cacheBuster:s,hasScenarios:o,isAnalyzing:i=!1,projectSlug:l,hasAnApiKey:d=!0}){var L,U,G,O,Z,le,he,fe,we,Pe,ke;const u=_e(),[h,m]=j(!1),[p,f]=j(!1),[g,y]=j({name:"Desktop",width:Ca,height:900}),[w,x]=j(Ca),[v,b]=j(1),{customSizes:N,addCustomSize:T,removeCustomSize:S}=ws(l),A=oe(()=>[...cn,...N],[N]),P=(de,Ce)=>{x(de);const je=A.find(Ne=>Ne.width===de&&Ne.height===Ce);y({name:(je==null?void 0:je.name)||"Custom",width:de,height:Ce})},I=de=>{x(de.width),y({name:de.name,width:de.width,height:de.height})},M=de=>{T(de,g.width,g.height??900),f(!1),y(Ce=>({...Ce,name:de}))},R=(de,Ce)=>{x(de);const je=A.find(Ne=>Ne.width===de&&Ne.height===Ce);y(Ne=>({name:(je==null?void 0:je.name)||"Custom",width:de,height:Ne.height}))},E=(U=(L=e==null?void 0:e.metadata)==null?void 0:L.screenshotPaths)==null?void 0:U[0],C=oe(()=>e?_r(e,t==null?void 0:t.status,void 0,r==null?void 0:r.sha,void 0):null,[e,t==null?void 0:t.status,r==null?void 0:r.sha]),_=oe(()=>{var Ce,je;const de=[];if((Ce=t==null?void 0:t.status)!=null&&Ce.errors&&t.status.errors.length>0)for(const Ne of t.status.errors)de.push({source:`${Ne.phase} phase`,message:Ne.message,stack:Ne.stack});if((je=t==null?void 0:t.status)!=null&&je.steps)for(const Ne of t.status.steps)Ne.error&&de.push({source:Ne.name,message:Ne.error,stack:Ne.errorStack});return de},[(G=t==null?void 0:t.status)==null?void 0:G.errors,(O=t==null?void 0:t.status)==null?void 0:O.steps]),$=(C==null?void 0:C.errorMessage)||null,D=(C==null?void 0:C.errorStack)||null,{interactiveServerUrl:z,isStarting:W,isLoading:K,showIframe:Q,iframeKey:te,onIframeLoad:F}=Xt({analysisId:t==null?void 0:t.id,scenarioId:e==null?void 0:e.id,scenarioName:e==null?void 0:e.name,projectSlug:l,enabled:a==="interactive"}),H=oe(()=>z||null,[z]),k=!i&&o&&e&&!((le=(Z=e.metadata)==null?void 0:Z.screenshotPaths)!=null&&le[0])&&((fe=(he=t==null?void 0:t.status)==null?void 0:he.scenarios)==null?void 0:fe.some(de=>de.name===e.name&&de.screenshotStartedAt&&!de.screenshotFinishedAt)),{lastLine:B}=ct(l,i||a==="interactive"||k||!1);if(!e){if(i&&r)return n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center bg-[#f6f9fc]",children:c("div",{className:"flex flex-col items-center gap-6 max-w-2xl",children:[n("div",{className:"w-12 h-12 mb-2",children:n("svg",{className:"animate-spin",viewBox:"0 0 50 50",children:n("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"#005c75",strokeWidth:"4",strokeDasharray:"31.4 31.4",strokeLinecap:"round"})})}),n("h2",{className:"text-2xl font-semibold text-[#005c75] leading-[30px] m-0 font-['IBM_Plex_Sans']",children:k?"Capturing screenshots...":"Analyzing..."}),n("p",{className:"text-xs text-[#8e8e8e] text-center leading-5 m-0 font-['IBM_Plex_Mono']",children:"This may take a few minutes."}),B&&n("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl",children:B}),l&&n("button",{onClick:()=>m(!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"})]})});if(!o&&r&&!i){if(_.length>0){const de=_.length===1?((we=_[0])==null?void 0:we.message)||"An error occurred during analysis.":`${_.length} errors occurred during analysis.`;return n("div",{className:"flex-1 flex flex-col justify-center items-center px-5",style:{minHeight:"75vh"},children:c("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded",style:{backgroundColor:tt.background,border:`2px solid ${tt.border}`},role:"alert",children:c("div",{className:"flex items-center gap-3",children:[n(rr,{size:24,className:"shrink-0"}),n("div",{className:"flex-1 min-w-0",children:c("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:tt.text},children:[n("span",{className:"font-semibold",children:"Analysis Error."})," ",de," ",n("button",{onClick:()=>m(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:tt.link},children:"See logs"})," ","for details."]})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(Ut,{analysisId:t==null?void 0:t.id})})]})})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-[#f6f9fc]",children:c("div",{className:"max-w-[600px]",children:[n("h2",{className:"text-[28px] font-semibold text-[#343434] mb-4 m-0 leading-10",children:"No simulations yet"}),n("p",{className:"text-base font-normal text-[#3e3e3e] mb-8 leading-6 m-0",children:"Analyze the code to create simulations and create test scenarios automatically."}),r.filePath&&n("button",{onClick:()=>{u.submit({entitySha:r.sha,filePath:r.filePath},{method:"post",action:"/api/analyze"})},disabled:u.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:u.state!=="idle"?"Analyzing...":"Analyze"})]})})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center",children:n("p",{className:"text-base text-gray-500 m-0",children:"Select a scenario to view its screenshot"})})}return c(ue,{children:[n("main",{className:"flex-1 bg-[#f9f9f9] overflow-auto flex flex-col min-w-0",children:(i||k)&&!E&&!$&&a==="screenshot"?n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-linear-to-br from-blue-50 to-indigo-50",children:c("div",{className:"max-w-2xl w-full bg-white rounded-t-2xl shadow-xl p-8",children:[c("div",{className:"mb-8",children:[n("div",{className:"inline-flex items-center justify-center w-24 h-24 bg-blue-100 rounded-full mb-6",children:n("span",{className:"text-5xl animate-spin",children:"⚙️"})}),n("h2",{className:"text-3xl font-bold text-gray-900 mb-4 m-0",children:k?`Capturing ${r==null?void 0:r.name}`:`Analyzing ${r==null?void 0:r.name}`}),n("p",{className:"text-base text-gray-600 leading-relaxed m-0 mb-2",children:k?`Taking screenshots for ${((Pe=t==null?void 0:t.scenarios)==null?void 0:Pe.length)||0} scenario${((ke=t==null?void 0:t.scenarios)==null?void 0:ke.length)!==1?"s":""}...`:`Generating simulations and scenarios for this ${r==null?void 0:r.entityType} entity...`}),e&&c("p",{className:"text-sm text-blue-600 font-semibold m-0",children:["Currently processing: ",e.name]})]}),B&&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:B,children:B})]})]})}),l&&n("button",{onClick:()=>m(!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"&&(E||$)||a==="interactive"&&(H||W)||a==="data"?c(ue,{children:[$&&!E&&n("div",{className:"flex-1 flex flex-col justify-center items-center p-6",children:c("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded overflow-auto",style:{backgroundColor:tt.background,border:`2px solid ${tt.border}`,maxHeight:"50vh"},role:"alert",children:c("div",{className:"flex flex-col gap-3",children:[c("div",{className:"flex items-center justify-center gap-2 font-bold",style:{color:tt.text},children:[n(rr,{size:24,className:"shrink-0"}),n("div",{children:"Capture Error"})]}),c("div",{className:"text-center",children:[n("button",{onClick:()=>m(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:tt.link},children:"See logs"})," ","for details."]}),n("div",{className:"flex-1 min-w-0",children:n("div",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:tt.text},children:$})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(Ut,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})}),a==="interactive"?c("div",{className:"flex-1 flex flex-col min-h-0",children:[H&&c("div",{className:"bg-gray-50 border-b border-gray-200 px-6 py-3 shrink-0 flex justify-center items-center gap-4",children:[n(kc,{presets:[...cn],customSizes:N,currentWidth:g.width,currentHeight:g.height??900,scale:v,onSizeChange:P,onSaveCustomSize:()=>f(!0),onRemoveCustomSize:S}),e&&r&&c(ce,{to:`/entity/${r.sha}/scenarios/${e.id}/fullscreen?from=${encodeURIComponent(`/entity/${r.sha}/scenarios/${e.id}/interactive`)}`,className:"flex items-center gap-2 px-4 py-2 bg-[#005c75] text-white rounded hover:bg-[#004a5c] transition-colors text-sm font-medium no-underline",title:"Open in fullscreen",children:[n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:n("path",{d:"M2 5V2H5M11 2H14V5M14 11V14H11M5 14H2V11",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),"Fullscreen"]})]}),H&&n("div",{className:"bg-[#f6f9fc] border-b border-[rgba(0,92,117,0.25)] flex justify-center",children:n("div",{style:{maxWidth:`${cn[cn.length-1].width}px`,width:"100%"},children:n(bs,{currentViewportWidth:w,currentPresetName:g.name,onDevicePresetClick:I,devicePresets:A})})}),n(jn,{scenarioId:e.id,scenarioName:e.name,iframeUrl:H,isStarting:W,isLoading:K,showIframe:Q,iframeKey:te,onIframeLoad:F,onScaleChange:b,onDimensionChange:R,projectSlug:l,defaultWidth:g.width,defaultHeight:g.height})]}):a==="data"?n("div",{className:"flex-1 min-h-0",children:n(Nh,{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:`${w}px`},children:(E||!$)&&n(Le,{screenshotPath:E,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&&!E?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."]}),B&&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:B})]}),l&&n("button",{onClick:()=>m(!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"})]})]})})}):$?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(ce,{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:$})})]}),D&&c("details",{className:"mt-4",children:[n("summary",{className:"text-sm text-red-700 cursor-pointer hover:text-red-900 font-semibold",children:"📋 View full stack trace"}),n("div",{className:"mt-3 bg-white border border-red-200 rounded p-4 overflow-auto",children:n("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:D})})]}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(Ut,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0: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(AnalysisErrorDisplay,{errors:_,title:"Analysis Error",description:_.length===1?"An error occurred during analysis. Screenshot capture was not completed.":`${_.length} errors occurred during analysis. Screenshot capture was not completed.`}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(Ut,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})}):c("div",{className:"flex flex-col items-center gap-4 text-center",children:[n("span",{className:"text-6xl text-gray-300",children:"📷"}),n("p",{className:"text-lg text-gray-500 m-0",children:"No screenshot available for this scenario"}),n("p",{className:"text-sm text-gray-400 m-0",children:"Try recapturing or debugging this scenario"})]})})})}),h&&l&&n($t,{projectSlug:l,onClose:()=>m(!1)}),p&&n(vs,{width:g.width,height:g.height??900,onSave:M,onCancel:()=>f(!1)})]})}function mn(e){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="object")try{return JSON.stringify(e)}catch{return"[complex object]"}return String(e)}function Na(e,t=15){const r=mn(e);return r.length>t?r.slice(0,t)+"...":r}function Sh({analysis:e,entitySha:t}){const r=lt(),[a,s]=j(e);re(()=>{s(e)},[e]);const[o,i]=j(!1),[l,d]=j(null),[u,h]=j({}),[m,p]=j(null),f=oe(()=>{var b;return!((b=a==null?void 0:a.metadata)!=null&&b.keyAttributes)||!(a!=null&&a.scenarios)?null:Ss(a.metadata.keyAttributes,a.scenarios)},[a]),g=oe(()=>f?Gc(f):[],[f]),y=oe(()=>a!=null&&a.scenarios?a.scenarios:[],[a]),w=ae(b=>{if(!f)return[];const N=f.scenariosWithStructuredRefs.find(T=>T.scenario.id===b.id);return(N==null?void 0:N.usedAttributes)||[]},[f]),x=ae(async(b,N)=>{var A;if(!a)return;const T=`${b}-${N}`,S=(A=u[T])==null?void 0:A.trim();if(S){i(!0),d(null);try{const P=await fetch("/api/update-valid-values",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"add",analysisId:a.id,analysis:a,keyAttributeIndex:b,valueType:N,value:S})}),I=await P.json();if(!P.ok||!I.success)throw new Error(I.error||"Failed to add value");s(I.analysis),h(M=>({...M,[T]:""})),r.revalidate()}catch(P){d(P instanceof Error?P.message:String(P))}finally{i(!1)}}},[a,u,r]),v=ae(async(b,N,T)=>{if(a){i(!0),d(null);try{const S=await fetch("/api/update-valid-values",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"remove",analysisId:a.id,analysis:a,keyAttributeIndex:b,valueType:N,value:"",valueIndex:T})}),A=await S.json();if(!S.ok||!A.success)throw new Error(A.error||"Failed to remove value");s(A.analysis),r.revalidate()}catch(S){d(S instanceof Error?S.message:String(S))}finally{i(!1)}}},[a,r]);return a?!f||f.keyAttributes.length===0?n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#fafafa]",children:c("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Key Attributes"}),n("p",{className:"text-sm",children:"Re-analyze this entity to generate key attributes."})]})}):n("div",{className:"flex-1 overflow-auto bg-[#fafafa]",children:c("div",{className:"p-6 space-y-6",children:[c("div",{className:"bg-white border border-gray-200 rounded-lg p-4",children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0 mb-3",children:"Scenarios Breakdown"}),c("div",{className:"grid grid-cols-4 gap-4 text-center",children:[c("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:y.length}),n("div",{className:"text-xs text-gray-500",children:"Scenarios"})]}),c("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:f.keyAttributes.length}),n("div",{className:"text-xs text-gray-500",children:"Key Attributes"})]}),c("div",{className:"bg-gray-50 rounded-lg p-3",children:[c("div",{className:"text-2xl font-bold text-gray-900",children:[f.usedValidValues,"/",f.totalValidValues]}),n("div",{className:"text-xs text-gray-500",children:"Values Used"})]}),c("div",{className:"bg-gray-50 rounded-lg p-3",children:[c("div",{className:`text-2xl font-bold ${f.coveragePercentage===100?"text-green-600":f.coveragePercentage>=50?"text-amber-600":"text-red-600"}`,children:[f.coveragePercentage.toFixed(0),"%"]}),n("div",{className:"text-xs text-gray-500",children:"Coverage"})]})]})]}),l&&c("div",{className:"p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700",children:[l,n("button",{onClick:()=>d(null),className:"ml-2 text-red-500 hover:underline",children:"Dismiss"})]}),c("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:c("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Scenarios (",y.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:y.length===0?c("div",{className:"p-4 text-center text-gray-500 text-sm",children:["No scenarios yet."," ",n(ce,{to:`/entity/${t}/create-scenario`,className:"text-blue-600 hover:underline",children:"Create one"})]}):y.map(b=>{var S,A,P;const N=(A=(S=b.metadata)==null?void 0:S.screenshotPaths)==null?void 0:A[0],T=w(b);return c("div",{className:"p-4 flex gap-4",children:[n("div",{className:"w-72 h-40 shrink-0 bg-gray-100 rounded overflow-hidden flex items-start justify-center",children:n(Le,{screenshotPath:N,alt:b.name||"Scenario screenshot",className:"max-w-full max-h-full object-contain object-top"})}),c("div",{className:"flex-1 min-w-0",children:[n("div",{className:"flex items-start justify-between gap-2",children:c("div",{children:[n(ce,{to:`/entity/${t}/scenarios/${b.id}`,className:"font-medium text-gray-900 hover:text-blue-600 no-underline text-sm",children:b.name}),((P=b.metadata)==null?void 0:P.error)&&n("span",{className:"ml-2 text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"Error"})]})}),n("p",{className:"text-xs text-gray-500 mt-1 line-clamp-2",children:b.description}),T.length>0&&n("div",{className:"flex flex-wrap gap-1 mt-2",children:T.map((I,M)=>c("span",{className:`text-xs px-1.5 py-0.5 rounded ${I.isError?"bg-red-50 text-red-700":"bg-blue-50 text-blue-700"}`,children:[String(I.path).split(".").pop(),"=",Na(I.value)]},M))})]})]},b.id)})}),n("div",{className:"px-4 py-3 border-t border-gray-100 bg-gray-50",children:c(ce,{to:`/entity/${t}/create-scenario`,className:"w-full px-4 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 flex items-center justify-center gap-2 no-underline",children:[n("span",{className:"text-lg leading-none",children:"+"}),"Add Scenario"]})})]}),g.length>0&&c("div",{className:"p-3 bg-amber-50 border border-amber-200 rounded-lg",children:[c("p",{className:"text-sm text-amber-800 font-medium mb-2",children:[g.length," unused value",g.length>1?"s":""," — consider adding scenarios to cover these"]}),c("div",{className:"flex flex-wrap gap-1",children:[g.slice(0,10).map((b,N)=>c("span",{className:"text-xs px-2 py-0.5 bg-amber-100 text-amber-700 rounded",children:[String(b.path).split(".").pop(),"=",Na(b.value,20)]},N)),g.length>10&&c("span",{className:"text-xs text-amber-600",children:["+",g.length-10," more"]})]})]}),c("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:c("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Key Attributes (",f.keyAttributes.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:f.keyAttributes.map((b,N)=>{var P;const T=m===b.path,S=b.validValues.filter(I=>I.usedInScenarios.length>0).length,A=b.validValues.length;return c("div",{children:[n("button",{onClick:()=>p(T?null:b.path),className:"w-full px-4 py-3 flex items-start justify-between text-left bg-transparent border-none cursor-pointer hover:bg-gray-50",children:c("div",{className:"flex items-start gap-3 flex-1",children:[n("span",{className:"text-gray-400 text-sm mt-0.5 shrink-0",children:T?"▼":"▶"}),c("div",{className:"flex-1",children:[c("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-mono text-sm font-medium text-gray-900",children:String(b.localVariable)}),c("span",{className:`text-xs px-2 py-0.5 rounded ${S===A?"bg-green-100 text-green-700":S>0?"bg-amber-100 text-amber-700":"bg-gray-100 text-gray-600"}`,children:[S,"/",A," covered"]})]}),b.description&&n("p",{className:"text-sm text-gray-600 mt-1 m-0",children:String(b.description)})]})]})}),T&&c("div",{className:"border-t border-gray-100 px-4 py-3 bg-gray-50/50",children:[c("div",{className:"space-y-2",children:[b.validValues.map(I=>{const M=I.usedInScenarios.length>0;return c("div",{className:"flex items-start gap-3 py-1",children:[n("div",{className:`w-4 h-4 mt-0.5 rounded border flex items-center justify-center shrink-0 ${M?"bg-green-500 border-green-500":"bg-white border-gray-300"}`,children:M&&n("svg",{className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2",children:[n("span",{className:"font-mono text-sm text-gray-800",children:mn(I.value)}),!M&&n("button",{onClick:()=>{v(N,"validValueOptions",I.index)},disabled:o,className:"text-gray-400 hover:text-red-500 text-xs disabled:opacity-50",title:"Remove value",children:"✕"})]}),M&&n("div",{className:"flex flex-wrap gap-1 mt-1",children:I.usedInScenarios.map((R,E)=>n("span",{className:"text-xs px-1.5 py-0.5 bg-gray-100 text-gray-600 rounded",children:String(R.name)},E))})]})]},I.index)}),c("div",{className:"flex items-center gap-2 pt-2 border-t border-gray-200 mt-2",children:[n("input",{type:"text",value:u[`${N}-validValueOptions`]||"",onChange:I=>h(M=>({...M,[`${N}-validValueOptions`]:I.target.value})),placeholder:"Add value...",className:"flex-1 text-sm px-2 py-1 border border-gray-200 rounded focus:border-blue-400 focus:outline-none",disabled:o,onKeyDown:I=>{I.key==="Enter"&&x(N,"validValueOptions")}}),n("button",{onClick:()=>{x(N,"validValueOptions")},disabled:o||!((P=u[`${N}-validValueOptions`])!=null&&P.trim()),className:"text-xs px-2 py-1 bg-gray-100 text-gray-700 rounded hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed",children:"Add"})]})]}),b.errorValues.length>0&&c("div",{className:"mt-4 pt-3 border-t border-gray-200",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Error Values"}),n("div",{className:"space-y-2",children:b.errorValues.map(I=>{const M=I.usedInScenarios.length>0;return c("div",{className:"flex items-start gap-3 py-1",children:[n("div",{className:`w-4 h-4 mt-0.5 rounded border flex items-center justify-center shrink-0 ${M?"bg-red-500 border-red-500":"bg-white border-gray-300"}`,children:M&&n("svg",{className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})}),c("div",{className:"flex-1",children:[n("span",{className:"font-mono text-sm text-gray-800",children:mn(I.value)}),M&&n("div",{className:"flex flex-wrap gap-1 mt-1",children:I.usedInScenarios.map((R,E)=>n("span",{className:"text-xs px-1.5 py-0.5 bg-red-50 text-red-600 rounded",children:String(R.name)},E))})]})]},I.index)})})]}),b.dependencies&&b.dependencies.length>0&&c("div",{className:"mt-4 pt-3 border-t border-gray-200",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Required for this attribute to have effect:"}),n("div",{className:"space-y-1.5",children:b.dependencies.map((I,M)=>c("div",{className:"flex items-start gap-2 text-xs",children:[n("span",{className:"text-amber-500 mt-0.5",children:"⚠"}),c("div",{children:[n("code",{className:"font-mono text-gray-800 bg-gray-100 px-1 py-0.5 rounded",children:String(I.path)}),n("span",{className:"text-gray-500 mx-1",children:"="}),n("code",{className:"font-mono text-blue-700 bg-blue-50 px-1 py-0.5 rounded",children:mn(I.requiredValue)}),I.description&&n("span",{className:"text-gray-500 ml-2",children:String(I.description)})]})]},M))})]}),b.sourceLocations&&b.sourceLocations.length>0&&c("div",{className:"mt-4 pt-3 border-t border-gray-200",children:[c("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:["Source Locations (",b.sourceLocations.length,")"]}),n("div",{className:"space-y-2",children:b.sourceLocations.map((I,M)=>c("div",{className:"bg-white rounded-lg p-2 border border-gray-200",children:[c("div",{className:"flex items-center gap-2 text-xs text-gray-600 mb-1",children:[n("span",{className:"font-medium",children:String(I.entityName)}),n("span",{className:"text-gray-400",children:"|"}),c("span",{children:["Line ",I.lineNumber]}),n("span",{className:"text-gray-400",children:"|"}),n("span",{className:"capitalize px-1.5 py-0.5 bg-blue-50 text-blue-700 rounded",children:I.usageType})]}),n("pre",{className:"text-xs bg-gray-900 text-gray-100 p-2 rounded overflow-x-auto font-mono whitespace-pre-wrap",children:n("code",{children:String(I.codeSnippet)})}),I.description&&n("p",{className:"text-xs text-gray-500 mt-1 italic m-0",children:String(I.description)})]},M))})]})]})]},b.path)})})]}),f.scenariosWithoutStructuredRefs.length>0&&c("div",{className:"text-xs text-gray-500 p-3 bg-gray-50 rounded-lg",children:[n("strong",{children:"Note:"})," ",f.scenariosWithoutStructuredRefs.length," scenario(s) don't have structured value references. Re-analyze to update coverage tracking."]})]})}):n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#fafafa]",children:c("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Analysis Found"}),n("p",{className:"text-sm",children:"Analyze this entity to see the scenarios breakdown."})]})})}function Sa({hasIndirectBadge:e,onAnalyze:t}){return c(ue,{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 Ah({entity:e,history:t}){const[r,a]=j("entity"),[s,o]=j(new Set),i=t.filter(h=>h.analyses.length>0).length,l=oe(()=>{const h=new Map;return t.forEach(m=>{m.analyses.forEach(p=>{var f;(f=p.scenarios)==null||f.forEach(g=>{h.has(g.name)||h.set(g.name,[]),h.get(g.name).push({version:m,analysis:p,scenario:g})})})}),Array.from(h.entries()).map(([m,p])=>{var f;return{name:m,description:((f=p[0])==null?void 0:f.scenario.description)||"",versions:p.sort((g,y)=>{const w=new Date(g.analysis.createdAt||0).getTime();return new Date(y.analysis.createdAt||0).getTime()-w})}})},[t]),d=l.length,u=h=>{o(m=>{const p=new Set(m);return p.has(h)?p.delete(h):p.add(h),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((h,m)=>c("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[19px] w-[11.5px] h-[11.5px] rounded-full bg-[#00925d]"}),c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-3 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center gap-3",children:[h.sha===(e==null?void 0:e.sha)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),c("span",{className:"text-xs font-mono text-[#646464] leading-5",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e]",children:h.sha.substring(0,8)})]})]}),n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-[22px]",children:h.createdAt&&new Date(h.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})})]})}),h.analyses.length>0?n("div",{children:h.analyses.map((p,f)=>{var g;return n("div",{children:!p.scenarios||p.scenarios.length===0?n(Sa,{hasIndirectBadge:p.indirect,onAnalyze:()=>{console.log("Analyze version:",h.sha)}}):c(ue,{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":""]})]})}),((g=p.metadata)==null?void 0:g.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((y,w)=>{var b,N;const x=(N=(b=y.metadata)==null?void 0:b.screenshotPaths)==null?void 0:N[0],v=`${y.name}-${w}`;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:x?n(Le,{screenshotPath:x,alt:y.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:y.name})})]},v)})})})]})},p.id||f)})}):n(Sa,{onAnalyze:()=>{console.log("Analyze version:",h.sha)}})]})]},h.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((h,m)=>{const p=s.has(h.name),f=p?h.versions:h.versions.slice(0,1),g=h.versions.length-1,y=h.versions[0];return y==null||y.version.sha,e==null||e.sha,c("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[42px] w-[13.26px] h-[13.26px] rounded-full bg-[#00925d]"}),c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[c("div",{className:"px-5 py-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:[n("h3",{className:"text-base font-semibold text-[#232323] m-0 mb-1 leading-6",children:h.name}),h.description&&n("p",{className:"text-sm font-normal text-[#626262] m-0 leading-[22px]",children:h.description})]}),c("div",{className:"p-5 bg-white",children:[f.map((w,x)=>{var A,P;const{version:v,analysis:b,scenario:N}=w,T=(P=(A=N.metadata)==null?void 0:A.screenshotPaths)==null?void 0:P[0],S=x===0;return c("div",{className:`flex gap-5 items-start ${S?"":"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:T?n(Le,{screenshotPath:T,alt:N.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:[v.sha===(e==null?void 0:e.sha)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),S&&h.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:[h.versions.length," versions"]})]}),c("p",{className:"text-xs font-mono text-[#646464] m-0 leading-5",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e]",children:v.sha.substring(0,8)})]}),b.createdAt&&c("p",{className:"text-xs font-medium text-[#8e8e8e] m-0 leading-[22px]",children:["Captured:"," ",new Date(b.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})]}),b.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5 self-start",children:"Indirect"})]})]},`${v.sha}-${x}`)}),g>0&&c("button",{onClick:()=>u(h.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":""}`]})]})]})]},h.name)})})]})})}function Aa({entity:e,analysisInfo:t,from:r}){const a=_e(),s=a.state!=="idle",o=e.entityType==="visual"||e.entityType==="library",i=l=>{l.preventDefault(),l.stopPropagation(),o&&a.submit({entitySha:e.sha,filePath:e.filePath},{method:"post",action:"/api/analyze"})};return n(ce,{to:`/entity/${e.sha}${r?`?from=${r}`:""}`,className:"block group cursor-pointer",children:c("div",{className:"flex gap-0 border border-gray-200 rounded-lg overflow-hidden transition-all hover:border-[#005c75] hover:shadow-md bg-white h-[100px]",children:[e.screenshotPath?n("div",{className:"w-[125px] h-full bg-gray-50 flex items-center justify-center shrink-0 rounded-bl-[8px] rounded-tl-[8px] border-r border-gray-200",children:n(Le,{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(ue,{children:[c("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f9f9f9] border border-[#e1e1e1] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#c7c7c7]"}),n("span",{className:"text-[10px] font-semibold text-[#646464]",children:"Not analyzed"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${s?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:s,children:s?"Analyzing...":"Analyze"})]}):t.status==="up_to_date"?c("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f2fcf9] border border-[#c8f2e3] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#00925d]"}),n("span",{className:"text-[10px] font-semibold text-[#00925d]",children:"Up to date"})]}):c(ue,{children:[c("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#e0e9ec] border border-[#e0e9ec] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#005c75]"}),n("span",{className:"text-[10px] font-semibold text-[#005c75]",children:"Out of date"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${s?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:s,children:s?"Analyzing...":"Analyze"})]})})]})]})},e.sha)}const Ea=e=>{var s,o,i;const t=((s=e.analysisStatus)==null?void 0:s.status)||"not_analyzed",r=((o=e.analysisStatus)==null?void 0:o.scenarioCount)||0,a=(i=e.analysisStatus)==null?void 0:i.timestamp;return t==="not_analyzed"?{status:"not_analyzed",label:"Not analyzed",color:"gray"}:t==="up_to_date"?{status:"up_to_date",label:"Up to date",color:"green",hasScenarios:r>0,scenarioCount:r,timestamp:a}:{status:"out_of_date",label:"Out of date",color:"teal",hasScenarios:r>0,scenarioCount:r,timestamp:a}};function Eh({importedEntities:e,importingEntities:t}){const[r]=Vt(),a=r.get("from"),s=_e(),o=s.state!=="idle",i=e.length>0,l=t.length>0,d=p=>p.filter(f=>f.entityType==="visual"||f.entityType==="library"),u=p=>{const f=d(p);f.length!==0&&s.submit({entityShas:f.map(g=>g.sha).join(",")},{method:"post",action:"/api/analyze"})},h=d(e).length>0,m=d(t).length>0;return n("div",{className:"max-w-[1400px] mx-auto",children:c("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[c("div",{className:"px-6 py-4 flex items-start justify-between",children:[c("div",{children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imports"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#deeafc] text-[#2f80ed] rounded-[9.095px] text-xs font-semibold leading-5",children:e.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities imported by this component."})]}),h&&n("button",{onClick:()=>u(e),disabled:o,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:o?"Analyzing...":"Analyze All"})]}),i?n("div",{className:"p-6 space-y-4",children:e.map(p=>n(Aa,{entity:p,analysisInfo:Ea(p),from:a},p.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"No imports."})})]}),c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[c("div",{className:"px-6 py-4 flex items-start justify-between",children:[c("div",{children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imported By"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#f3eefe] text-[#9b51e0] rounded-[9.095px] text-xs font-semibold leading-5",children:t.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities that import this component."})]}),m&&n("button",{onClick:()=>u(t),disabled:o,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:o?"Analyzing...":"Analyze All"})]}),l?n("div",{className:"p-6 space-y-4",children:t.map(p=>n(Aa,{entity:p,analysisInfo:Ea(p),from:a},p.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px] text-center",children:"Not imported by any entity."})})]})]})})}function _h({relatedEntities:e}){return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:n(Eh,{importedEntities:e.importedEntities,importingEntities:e.importingEntities})})}function Ph({data:e,defaultExpanded:t=!1,maxDepth:r=3}){return n("div",{className:"font-mono text-sm",children:n(Ht,{data:e,depth:0,defaultExpanded:t,maxDepth:r})})}function Ht({data:e,depth:t,defaultExpanded:r,maxDepth:a,objectKey:s,showInlineToggle:o=!1}){const[i,l]=j(r||t<2);if(re(()=>{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(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:e.map((u,h)=>n("div",{className:"py-0.5",children:n(Ht,{data:u,depth:t+1,defaultExpanded:r,maxDepth:a})},h))}),n("div",{className:"text-gray-600",children:"]"})]}):null]});if(d==="object"){const u=Object.keys(e);if(u.length===0)return n("span",{className:"text-gray-600",children:"{}"});const h=p=>p!==null&&typeof p=="object"&&!Array.isArray(p)&&Object.keys(p).length>0,m=p=>Array.isArray(p)&&p.length>0;return c("span",{children:[c("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>l(!i),children:[c("span",{children:[i?"▼":"▶"," ","{"]}),!i&&c("span",{children:[u.length,"}"]})]}),i?c(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:u.map(p=>{const f=e[p],g=h(f),y=m(f);return n("div",{className:"py-0.5",children:g?n(Pr,{propertyKey:p,value:f,depth:t,defaultExpanded:r,maxDepth:a}):y?n(kr,{propertyKey:p,value:f,depth:t,defaultExpanded:r,maxDepth:a}):c(ue,{children:[c("span",{className:"text-orange-600",children:[p,": "]}),n(Ht,{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 Pr({propertyKey:e,value:t,depth:r,defaultExpanded:a,maxDepth:s}){const[o,i]=j(a||r<2),l=Object.keys(t);return re(()=>{i(a||r<2)},[a,r]),c(ue,{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(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:l.map(d=>{const u=t[d],h=u!==null&&typeof u=="object"&&!Array.isArray(u)&&Object.keys(u).length>0,m=Array.isArray(u)&&u.length>0;return n("div",{className:"py-0.5",children:h?n(Pr,{propertyKey:d,value:u,depth:r+1,defaultExpanded:a,maxDepth:s}):m?n(kr,{propertyKey:d,value:u,depth:r+1,defaultExpanded:a,maxDepth:s}):c(ue,{children:[c("span",{className:"text-orange-600",children:[d,": "]}),n(Ht,{data:u,depth:r+2,defaultExpanded:a,maxDepth:s})]})},d)})}),n("div",{className:"text-gray-600",children:"}"})]})]})}function kr({propertyKey:e,value:t,depth:r,defaultExpanded:a,maxDepth:s}){const[o,i]=j(a||r<2);return re(()=>{i(a||r<2)},[a,r]),c(ue,{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(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:t.map((l,d)=>{const u=l!==null&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,h=Array.isArray(l)&&l.length>0;return n("div",{className:"py-0.5",children:u?n(Pr,{propertyKey:d.toString(),value:l,depth:r+1,defaultExpanded:a,maxDepth:s}):h?n(kr,{propertyKey:d.toString(),value:l,depth:r+1,defaultExpanded:a,maxDepth:s}):n(Ht,{data:l,depth:r+2,defaultExpanded:a,maxDepth:s})},d)})}),n("div",{className:"text-gray-600",children:"]"})]})]})}function Gn({label:e,count:t,isActive:r,onClick:a,badgeColorActive:s,badgeTextActive:o}){return c("button",{onClick:a,className:`px-6 py-3 text-sm font-medium relative transition-colors cursor-pointer ${r?"text-[#005c75]":"text-[#3e3e3e] hover:text-gray-900 hover:bg-gray-50"}`,children:[e,t!==void 0&&n("span",{className:`ml-2 px-2 py-0.5 rounded-full text-xs font-semibold ${r?`${s} ${o}`:"bg-gray-200 text-gray-700"}`,children:t}),r&&n("div",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-[#005c75]"})]})}function _a({label:e,isActive:t,onClick:r,disabled:a=!1}){return n("button",{onClick:r,className:`w-full text-left px-3 py-2.5 rounded-md transition-all text-sm cursor-pointer ${t?"bg-[#f6f9fc] text-[#005c75] font-medium border-l-2 border-[#005c75] pl-[10px]":"text-[#3e3e3e] hover:bg-gray-50"}`,disabled:a,children:e})}function Pa({call:e,scenarioName:t}){const[r,a]=j(!1),[s,o]=j("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(" / ")},u=oe(()=>{var p,f,g,y,w;try{const x=JSON.parse(e.response);return(g=(f=(p=x.choices)==null?void 0:p[0])==null?void 0:f.message)!=null&&g.content?x.choices[0].message.content:(w=(y=x.content)==null?void 0:y[0])!=null&&w.text?x.content[0].text:e.response}catch{return e.response}},[e.response]),h=oe(()=>{try{return JSON.stringify(JSON.parse(e.props),null,2)}catch{return e.props}},[e.props]),m=oe(()=>{var p;if(t)return t;try{const f=JSON.parse(e.props);return((p=f==null?void 0:f.scenario)==null?void 0:p.name)||null}catch{return null}},[e.props,t]);return c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-4 bg-[#f6f9fc] border-b border-[#e1e1e1] cursor-pointer hover:bg-[#edf2f7] transition-colors",onClick:()=>a(!r),children:c("div",{className:"flex items-start justify-between gap-4",children:[c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#005c75] text-white rounded text-[11px] font-medium",children:e.prompt_type}),n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-[11px] font-medium",children:e.model}),m&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-[11px] font-medium",children:m}),e.error&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-[11px] font-medium",children:"Error"})]}),c("div",{className:"flex items-center gap-4 text-xs text-[#626262]",children:[n("span",{children:i(e.created_at)}),d(e.input_tokens,e.output_tokens)&&n("span",{children:d(e.input_tokens,e.output_tokens)}),l(e.cost)&&n("span",{className:"text-[#005c75] font-medium",children:l(e.cost)})]}),c("div",{className:"text-[11px] text-[#8a8a8a] font-mono mt-1",children:[".codeyam/llm-calls/",e.object_id,"_",e.id,".json"]})]}),n("svg",{width:"20",height:"20",viewBox:"0 0 16 16",fill:"none",className:`transition-transform shrink-0 ${r?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"#626262",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})}),r&&c("div",{className:"border-t border-[#e1e1e1]",children:[c("div",{className:"flex border-b border-[#e1e1e1] bg-[#fafafa]",children:[n("button",{onClick:()=>o("system"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${s==="system"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"System"}),n("button",{onClick:()=>o("prompt"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${s==="prompt"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Prompt"}),n("button",{onClick:()=>o("response"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${s==="response"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Response"}),n("button",{onClick:()=>o("props"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${s==="props"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Context"})]}),s&&c("div",{className:"p-4 bg-white max-h-[400px] overflow-auto",children:[s==="system"&&n("div",{children:e.system_message?n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.system_message}):n("p",{className:"text-xs text-[#626262] italic m-0",children:"No system message"})}),s==="prompt"&&n("div",{children:n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.prompt_text})}),s==="response"&&c("div",{children:[e.error&&c("div",{className:"mb-4 p-3 bg-[#fef2f2] border border-[#fecaca] rounded",children:[n("h4",{className:"text-xs font-semibold text-[#dc2626] uppercase mb-1",children:"Error"}),n("p",{className:"text-xs text-[#dc2626] m-0",children:e.error})]}),n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:u})]}),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:h})]}),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 ka=["generateEntityScenarios","analyzeEntity","generateDataStructure","generateEntityDescription"];function kh({entity:e,analysis:t,scenarios:r,onAnalyze:a,llmCalls:s}){var b,N,T,S,A,P,I,M,R;const[o,i]=j("entity"),[l,d]=j("isolatedDataStructure"),[u,h]=j(r.length>0?{scenarioId:r[0].id||r[0].name}:null),[m,p]=j("entity"),{entityLlmCalls:f,scenarioLlmCalls:g,totalLlmCalls:y}=oe(()=>{if(!s)return{entityLlmCalls:[],scenarioLlmCalls:[],totalLlmCalls:0};const E=[...s.entityCalls,...s.analysisCalls],C=E.filter($=>$.object_type==="entity"||ka.includes($.prompt_type)),_=E.filter($=>$.object_type!=="entity"&&!ka.includes($.prompt_type));return C.sort(($,D)=>D.created_at-$.created_at),_.sort(($,D)=>D.created_at-$.created_at),{entityLlmCalls:C,scenarioLlmCalls:_,totalLlmCalls:E.length}},[s]),w=[{id:"analysis",title:"Analysis",data:t?{id:t.id,status:t.status}:void 0,description:"Analysis metadata including ID and processing status"},{id:"isolatedDataStructure",title:"Isolated Data Structure",data:(b=e==null?void 0:e.metadata)==null?void 0:b.isolatedDataStructure,description:"Entity's own data structure without dependencies"},{id:"mergedDataStructure",title:"Merged Data Structure",data:(N=t==null?void 0:t.metadata)==null?void 0:N.mergedDataStructure,description:"Combined data structure including dependencies"},{id:"conditionalUsages",title:"Conditional Usages",data:(S=(T=e==null?void 0:e.metadata)==null?void 0:T.isolatedDataStructure)==null?void 0:S.conditionalUsages,description:"Attributes used in conditionals (if, ternary, switch, &&) - candidates for key attributes"},{id:"keyAttributes",title:"Key Attributes",data:(A=t==null?void 0:t.metadata)==null?void 0:A.keyAttributes,description:"Important attributes identified during analysis"},{id:"importedExports",title:"Imported Dependencies",data:{"Internal Dependencies":(P=e==null?void 0:e.metadata)==null?void 0:P.importedExports,"External Dependencies":(I=e==null?void 0:e.metadata)==null?void 0:I.nodeModuleImports},description:"Internal and external dependencies used by this entity"},{id:"scenariosDataStructure",title:"Scenarios Data Structure",data:(M=t==null?void 0:t.metadata)==null?void 0:M.scenariosDataStructure,description:"Structure template used across all scenarios"}],x=w.filter(E=>E.data!==void 0&&E.data!==null).length;let v=null;if(o==="entity"){const E=w.find(C=>C.id===l);E&&E.data!==void 0&&E.data!==null&&(v={title:E.title,description:E.description,data:E.data})}else if(o==="scenarios"&&u){const E=r.find(C=>(C.id||C.name)===u.scenarioId);E&&(v={title:E.name,description:E.description||"Scenario data and configuration",data:E.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(Gn,{label:"Entity",isActive:o==="entity",onClick:()=>i("entity"),badgeColorActive:"bg-[#e0e9ec]",badgeTextActive:"text-[#005c75]"}),n(Gn,{label:"Scenarios",count:r.length,isActive:o==="scenarios",onClick:()=>i("scenarios"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),n(Gn,{label:"LLM Calls",count:y,isActive:o==="llm-calls",onClick:()=>i("llm-calls"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),((R=t==null?void 0:t.metadata)==null?void 0:R.analyzerVersion)&&c("div",{className:"ml-auto flex items-center text-xs text-gray-500",children:[n("span",{className:"font-medium",children:"Analyzer:"}),n("span",{className:"ml-1 font-mono",children:t.metadata.analyzerVersion})]})]})}),o==="llm-calls"?c("div",{className:"flex-1 min-h-0",children:[c("div",{className:"flex gap-4 mb-4",children:[c("button",{onClick:()=>p("entity"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${m==="entity"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Entity Calls (",f.length,")"]}),c("button",{onClick:()=>p("scenario"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${m==="scenario"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Scenario Calls (",g.length,")"]})]}),n("div",{className:"space-y-4 overflow-y-auto",style:{maxHeight:"calc(100vh - 350px)"},children:m==="entity"?f.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:n("p",{className:"text-gray-500 text-sm m-0",children:"No entity-level LLM calls found"})}):f.map(E=>n(Pa,{call:E},E.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(E=>n(Pa,{call:E},E.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(ue,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"ENTITY SECTIONS"}),x===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No entity data available."}):n("nav",{className:"space-y-1",children:w.map(E=>{const C=E.data!==void 0&&E.data!==null;return n(_a,{label:E.title,isActive:l===E.id,onClick:()=>d(E.id),disabled:!C},E.id)})})]}):c(ue,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"SCENARIOS"}),r.length===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No scenarios available."}):n("nav",{className:"space-y-1",children:r.map(E=>{const C=E.id||E.name,_=(u==null?void 0:u.scenarioId)===C;return n(_a,{label:E.name,isActive:_,onClick:()=>h({scenarioId:C})},C)})})]})}),n("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:v?n(Mh,{title:v.title,description:v.description,data:v.data}):o==="scenarios"&&r.length===0?n(Ma,{title:"No Simulations Yet",description:"Analyze the code to create simulations and create test scenarios automatically.",onAnalyze:a}):o==="entity"?n(Ma,{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 Ma({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 Mh({title:e,description:t,data:r}){const[a,s]=j(!0),[o,i]=j("Copy JSON");return c(ue,{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(Ph,{data:r,defaultExpanded:a,maxDepth:99})}):n("div",{className:"text-center py-12 text-gray-500",children:"No data available for this section"})})})]})}function Th({entity:e,analysis:t,scenarios:r,onAnalyze:a}){const s=_e();return re(()=>{if(e!=null&&e.sha&&s.state==="idle"&&!s.data){const o=t!=null&&t.id?`/api/llm-calls/${e.sha}?analysisId=${t.id}`:`/api/llm-calls/${e.sha}`;s.load(o)}},[e==null?void 0:e.sha,t==null?void 0:t.id,s.state,s.data]),n("div",{className:"flex-1 min-h-0 bg-[#f9f9f9] overflow-auto p-8",children:n(kh,{entity:e,analysis:t,scenarios:r,onAnalyze:a,llmCalls:s.data})})}function ar({content:e,label:t="Copy",copiedLabel:r="✓ Copied!",className:a="",duration:s=2e3,ariaLabel:o}){const[i,l]=j(!1),d=ae(()=>{navigator.clipboard.writeText(e).then(()=>{l(!0),setTimeout(()=>l(!1),s)}).catch(u=>{console.error("Failed to copy:",u)})},[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})}const Ih={margin:0,padding:"24px",backgroundColor:"#101827",fontSize:"14px",lineHeight:"1.5"},jh={minWidth:"3em",paddingRight:"1em",color:"#6b7280",userSelect:"none"},$h=2e3,Rh=e=>{var r;if(!e)return"typescript";switch((r=e.split(".").pop())==null?void 0:r.toLowerCase()){case"ts":case"tsx":return"typescript";case"js":case"jsx":return"javascript";case"json":return"json";case"css":return"css";default:return"typescript"}};function Dh({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==null?void 0:e.filePath})]}),t&&n(ar,{content:t,label:"Copy Code",duration:$h,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(Zo,{language:Rh(e==null?void 0:e.filePath),style:ei,showLineNumbers:!0,customStyle:Ih,lineNumberStyle:jh,children:t})}):n("div",{className:"p-12 text-center text-gray-500",children:"No code available"})})]})})}const Lh=({data:e})=>[{title:e!=null&&e.entity?`${e.entity.name} - CodeYam`:"Entity - CodeYam"},{name:"description",content:"View entity scenarios and screenshots"}];function Oh({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 Fh({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",u=l[1]||null,h=l[2]||null,m=r.analysisQueue,p=m?m.getState():{paused:!1,jobs:[]},[f,g,y,w]=await Promise.all([Ct(a),Fe(),Pt(),_l(ye()||process.cwd())]),x=f?await br(f):null;let v={importedEntities:[],importingEntities:[]},b=null,N=[];return f&&(v=await ss(f),b=await os(f),N=await is(f)),Y({entity:f??void 0,analysis:x??void 0,projectSlug:g,from:o,relatedEntities:v,entityCode:b??void 0,history:N,tab:d,scenarioId:u,viewModeFromUrl:h,currentCommit:y,hasAnApiKey:w,queueState:p})}const Yh=We(function(){var Or,Fr,Yr,zr,Br,Ur,Wr,Hr,Vr,Jr;const t=Ge(),s=(ja()["*"]||"").split("/").filter(Boolean),o=s[0]||"scenarios",i=s[1]||null,l=s[2]||null,d=t.entity,u=t.analysis,h=t.projectSlug;t.from;const m=t.relatedEntities,p=t.entityCode,f=t.history,g=t.currentCommit,y=t.hasAnApiKey,w=t.queueState,x=(u==null?void 0:u.scenarios)||[],v=It(),b=Ee(null);re(()=>{b.current===null&&(b.current=window.history.length)},[]);const N=()=>{if(typeof window>"u")return;const ee=window.history.state;if(ee===null||(ee==null?void 0:ee.idx)===void 0||(ee==null?void 0:ee.idx)===0)v("/");else{const me=window.history.length,xe=b.current;if(xe!==null&&me>xe){const ge=me-xe+1;v(-ge)}else v(-1)}},T=!!w.currentlyExecuting,S=o,A=(Or=g==null?void 0:g.metadata)==null?void 0:Or.currentRun,P=!!(A!=null&&A.createdAt)&&!(A!=null&&A.analysisCompletedAt),I=!!(d!=null&&d.sha&&((Fr=A==null?void 0:A.currentEntityShas)!=null&&Fr.includes(d.sha))),M=!!(d!=null&&d.sha&&((zr=(Yr=w.currentlyExecuting)==null?void 0:Yr.entityShas)!=null&&zr.includes(d.sha))),R=!!(d!=null&&d.sha&&((Br=w.jobs)!=null&&Br.some(ee=>{var me;return(me=ee.entityShas)==null?void 0:me.includes(d.sha)}))),E=I||M||R,C=oe(()=>{if(S!=="scenarios")return null;if(i){const ee=x.find(me=>me.id===i);if(ee)return ee}return x.length>0&&!E?x[0]:null},[S,i,x,E]);Nt({source:C?"scenario-page":"entity-page",entitySha:d==null?void 0:d.sha,scenarioId:C==null?void 0:C.id,analysisId:u==null?void 0:u.id});const[_,$]=j(()=>l&&l!=="edit"?l:(d==null?void 0:d.entityType)==="library"?"data":"screenshot");re(()=>{l&&l!==_&&l!=="edit"&&$(l)},[l]);const D=l==="edit",[z,W]=j(!1),[K,Q]=j(!1),[te,F]=j(null),[H,k]=j(!1),[B,ne]=j(!1),[V,L]=j(null),[U,G]=j(null),[O,Z]=j(0),{interactiveServerUrl:le,isStarting:he,isLoading:fe,showIframe:we,iframeKey:Pe,onIframeLoad:ke}=Xt({analysisId:u==null?void 0:u.id,scenarioId:C==null?void 0:C.id,scenarioName:C==null?void 0:C.name,projectSlug:h,enabled:D&&!!C,refreshTrigger:O}),[de,Ce]=j(!1),[je,Ne]=j(""),[ut,st]=j(!1),[Lt,ie]=j(Date.now()),[$e,Ye]=j(null),[Zt,en]=j(!1),[Fs,Rn]=j(!1),Ze=_e(),ze=_e(),ht=_e(),et=_e(),Re=lt(),Ys=w.jobs.some(ee=>{var me;return(d==null?void 0:d.sha)&&((me=ee.entityShas)==null?void 0:me.includes(d.sha))||ee.type==="analysis"&&ee.commitSha===(g==null?void 0:g.sha)&&ee.entityShas&&ee.entityShas.length===0}),Dn=E;(Ur=d==null?void 0:d.metadata)!=null&&Ur.defaultWidth||(Wr=u==null?void 0:u.metadata)!=null&&Wr.defaultWidth,Ze.state==="submitting"||Ze.state,oe(()=>{var ee;return!!((ee=C==null?void 0:C.metadata)!=null&&ee.interactiveExamplePath)},[C]);const{isCompleted:$r}=ct(h,ut);re(()=>{Ze.state==="idle"&&Ze.data&&(Ze.data.success?setTimeout(()=>{ie(Date.now()),Re.revalidate(),st(!1)},1500):Ze.data.error&&(st(!1),alert(`Recapture failed: ${Ze.data.error}`)))},[Ze.state,Ze.data,Re]),re(()=>{ut&&$r&&setTimeout(()=>{ie(Date.now()),Re.revalidate(),st(!1)},1500)},[ut,$r,Re]),re(()=>{if(ze.state==="idle"&&ze.data)if(ze.data.success){Ye(ze.data),en(!0);const ee=ze.data.jobId;if(ee){const me=async()=>{try{const ge=await fetch("/api/queue?queryType=job&jobId="+encodeURIComponent(ee));if(!ge.ok){const Ke=await ge.text();console.error("[Debug Setup] Poll failed with status",ge.status,":",Ke);return}(await ge.json()).status==="completed"&&(clearInterval(xe),Ye(Ke=>{var ot,De;return Ke?{...Ke,complete:!0,instructions:{title:"Debug Environment Ready ✓",sections:((De=(ot=Ke.instructions)==null?void 0:ot.sections)==null?void 0:De.map(Se=>Se.heading==="Status"?{heading:"Status",items:[{content:"Setup complete! Your debug environment is ready."},...Se.items.slice(1)]}:Se.heading==="What's Happening"?null:Se.heading==="Next Steps (Once Complete)"?{...Se,heading:"Next Steps"}:Se).filter(Boolean))||[]}}:null}))}catch(ge){console.error("[Debug Setup] Error polling queue:",ge)}},xe=setInterval(()=>{me().catch(()=>{})},2e3);return()=>{clearInterval(xe)}}else console.warn("[Debug Setup] No job ID returned from debug setup!")}else ze.data.error&&(console.error("[Debug Setup] Error:",ze.data.error),alert(`Debug setup failed: ${ze.data.error}`))},[ze.state,ze.data]),re(()=>{ht.state==="idle"&&ht.data&&(ht.data.success?setTimeout(()=>{ie(Date.now()),Re.revalidate(),st(!1)},1500):ht.data.error&&(st(!1),alert(`Recapture failed: ${ht.data.error}`)))},[ht.state,ht.data,Re]);const Rr=()=>{d&&et.submit({entitySha:d.sha,filePath:d.filePath||""},{method:"post",action:"/api/analyze"})};re(()=>{et.state==="idle"&&et.data&&(et.data.success?Re.revalidate():et.data.error&&alert(`Analysis failed: ${et.data.error}`))},[et.state,et.data,d==null?void 0:d.sha,Re]),re(()=>{const ee=setTimeout(()=>{Re.revalidate()},500);return()=>clearTimeout(ee)},[]),re(()=>{if(P||Dn){const ee=setInterval(()=>{Re.revalidate()},3e3);return()=>clearInterval(ee)}else{const ee=setInterval(()=>{Re.revalidate()},5e3),me=setTimeout(()=>{clearInterval(ee)},3e4);return()=>{clearInterval(ee),clearTimeout(me)}}},[P,Dn,Re]);const zs=(ee,me)=>ee==="scenarios"?`/entity/${d==null?void 0:d.sha}/scenarios`:`/entity/${d==null?void 0:d.sha}/${ee}`,Bs=(ee,me)=>`/entity/${d==null?void 0:d.sha}/scenarios/${ee}/${me}`,Us=ee=>{$(ee),C!=null&&C.id&&(ee==="interactive"?v(`/entity/${d==null?void 0:d.sha}/scenarios/${C.id}/fullscreen`,{replace:!0}):v(Bs(C.id,ee),{replace:!0}))},Ws=async ee=>{var me,xe;if(console.log("[EntityDetail] ===== APPLY CHANGES CALLED =====",{description:ee,hasSelectedScenario:!!C,hasAnalysis:!!u}),!C||!u){const ge="Error: No scenario or analysis available";console.error("[EntityDetail]",ge),F(ge);return}W(!0),F(null),console.log("[EntityDetail] Applying changes (preview mode)",{description:ee,scenarioId:C.id,scenarioName:C.name,currentData:C.data});try{const ge=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:ee,existingScenarios:u.scenarios,scenariosDataStructure:(me=u.metadata)==null?void 0:me.scenariosDataStructure,editingMockName:C.name,editingMockData:U||((xe=C.metadata)==null?void 0:xe.data)})}),qe=await ge.json();if(!ge.ok||!qe.success)throw new Error(qe.error||"Failed to generate scenario data");console.log("[EntityDetail] Generated data:",qe.data),G(qe.data);const Ke=(u.scenarios||[]).map(Se=>Se.id===C.id?{...Se,metadata:{...Se.metadata,data:qe.data}}:Se),ot=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:u,scenarios:Ke})}),De=await ot.json();if(!ot.ok||!De.success)throw console.error("[EntityDetail] Temp save failed:",De),new Error(De.error||"Failed to apply preview");if(F("Generating preview. Capturing screenshot..."),le){console.log("[EntityDetail] Using direct capture from running server",{serverUrl:le});const Se=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:le,scenarioId:C.id,projectId:u.projectId,viewportWidth:1440})}),Ot=await Se.json();!Se.ok||!Ot.success?(console.error("[EntityDetail] Direct capture failed:",Ot),F("Preview applied. Screenshot capture failed.")):(console.log("[EntityDetail] Direct capture successful"),F('Preview applied. Click "Save Scenario Data" to persist.'))}else{console.log("[EntityDetail] No server running, using queued recapture");const Se=new FormData;Se.append("analysisId",u.id||""),Se.append("scenarioId",C.id||"");const Ot=await fetch("/api/recapture-scenario",{method:"POST",body:Se}),Ln=await Ot.json();!Ot.ok||!Ln.success?(console.warn("[EntityDetail] Recapture failed:",Ln.error),F("Preview applied. Screenshot recapture failed.")):(console.log("[EntityDetail] Recapture queued:",Ln.jobId),F('Preview applied. Screenshot will update shortly. Click "Save Scenario Data" to persist.'))}Z(Se=>Se+1),Re.revalidate()}catch(ge){console.error("Error applying changes:",ge),F(`Error: ${ge instanceof Error?ge.message:String(ge)}`)}finally{W(!1)}},Hs=async(ee,me)=>{var xe;if(!C||!u){F("Error: No scenario or analysis available");return}Q(!0),F(null),console.log("[EntityDetail] Saving scenario to database",{description:ee,saveAsNew:me});try{const ge=U||((xe=C.metadata)==null?void 0:xe.data);let qe;if(me){const De={...C,id:`${C.name}-${Date.now()}`,name:`${C.name} (Copy)`,metadata:{...C.metadata,data:ge},description:ee||C.description};qe=[...u.scenarios||[],De]}else qe=(u.scenarios||[]).map(De=>De.id===C.id?{...De,metadata:{...De.metadata,data:ge},description:ee||De.description}:De);const Ke=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:u,scenarios:qe})}),ot=await Ke.json();if(!Ke.ok||!ot.success)throw new Error(ot.error||"Failed to save scenarios");console.log("[EntityDetail] Scenarios saved successfully"),F(me?"New scenario created successfully":"Scenario saved successfully"),G(null),Re.revalidate()}catch(ge){console.error("Error saving scenario:",ge),F(`Error: ${ge instanceof Error?ge.message:String(ge)}`)}finally{Q(!1)}},Vs=()=>{console.log("[EntityDetail] Edit mock data clicked"),F("Mock data editor coming soon")},Js=async()=>{var ee;if(!(C!=null&&C.id)){L("Cannot delete scenario without ID");return}k(!0),L(null);try{const me=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:C.id,screenshotPaths:((ee=C.metadata)==null?void 0:ee.screenshotPaths)||[]})}),xe=await me.json();if(!me.ok||!xe.success)throw new Error(xe.error||"Failed to delete scenario");v(`/entity/${d==null?void 0:d.sha}/scenarios`)}catch(me){console.error("[EntityDetail] Error deleting scenario:",me),L(me instanceof Error?me.message:"Failed to delete scenario"),ne(!1)}finally{k(!1)}},Gs=u&&d&&u.entitySha!==d.sha,Dr=(d?bh(d):!1)||Gs,Lr=u!==null;return n(In,{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-1.5 min-w-0",children:[n("button",{onClick:N,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-sm font-semibold text-black m-0 leading-[20px] shrink-0",children:d==null?void 0:d.name}),E?c("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#FFF4FC",color:"#FF2AB5",height:"23px"},children:[c("svg",{width:"9",height:"9",viewBox:"0 0 9 9",fill:"none",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):Ys?n("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#f3e5f5",color:"#6a1b9a",height:"23px"},children:"Queued"}):Lr?Dr?n("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"23px"},children:"Out of date"}):n("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"23px"},children:"Up to date"}):n("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#f9f9f9",color:"#646464",height:"23px"},children:"Not analyzed"}),n("span",{className:"text-[#e1e1e1] mx-1.5 shrink-0",children:"|"}),n("span",{className:"text-sm text-[#626262] font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:d==null?void 0:d.filePath,children:d==null?void 0:d.filePath})]}),n("div",{className:"flex items-center gap-3 shrink-0",children:(!Lr||Dr)&&n("button",{onClick:Rr,disabled:et.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"})})]})}),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:x.length},{id:"related",label:"Related Entities",count:m.importedEntities.length+m.importingEntities.length},{id:"data",label:"Data Structure"},{id:"code",label:"Code"},{id:"history",label:"History"}].map(ee=>c(ce,{to:zs(ee.id),className:`flex items-center justify-center gap-3 shrink-0 text-sm rounded-md transition-colors no-underline ${S===ee.id?"bg-[#343434] text-[#efefef] font-medium h-8 px-6":"text-[#3e3e3e] font-normal hover:bg-gray-100 py-1 px-[15px]"}`,children:[ee.label,ee.count!==void 0&&n("span",{className:`w-[25px] h-5 rounded-md text-xs font-normal flex items-center justify-center ${S===ee.id?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:ee.count})]},ee.id))})}),c("div",{className:"flex grow items-stretch justify-center gap-0 min-h-0",children:[S==="scenarios"&&c(ue,{children:[D&&C?n(Ch,{scenario:C,entitySha:(d==null?void 0:d.sha)||"",onApply:Ws,onSave:Hs,onEditMockData:Vs,onDelete:Js,isApplying:z,isSaving:K,saveMessage:te,showDeleteConfirm:B,onShowDeleteConfirm:ne,isDeleting:H,deleteError:V}):n(wh,{scenarios:x,analysis:u,selectedScenario:C,entitySha:(d==null?void 0:d.sha)||"",cacheBuster:Lt,activeTab:S,entityType:d==null?void 0:d.entityType,entity:d,queueState:w,processIsRunning:T,isEntityAnalyzing:E,viewMode:_,setViewMode:Us,onDebugSetup:()=>{!(C!=null&&C.id)||!(u!=null&&u.id)||ze.submit({analysisId:u.id,scenarioId:C.id},{method:"post",action:"/api/debug-setup"})},debugFetcher:ze,isBreakdownView:i==="breakdown"}),i==="breakdown"?n(Sh,{analysis:u??null,entitySha:(d==null?void 0:d.sha)||""}):D&&C?n(jn,{scenarioId:C.id||C.name,scenarioName:C.name,iframeUrl:le,isStarting:he,isLoading:fe,showIframe:we,iframeKey:Pe,onIframeLoad:ke,projectSlug:h,defaultWidth:1440,defaultHeight:900}):n($s,{selectedScenario:C,analysis:u,entity:d,viewMode:_,cacheBuster:Lt,hasScenarios:x.length>0,isAnalyzing:Dn,projectSlug:h,hasAnApiKey:y})]}),S==="related"&&n(_h,{relatedEntities:m}),S==="data"&&n(Th,{entity:d,analysis:u,scenarios:x,onAnalyze:Rr}),S==="code"&&n(Dh,{entity:d,entityCode:p}),S==="history"&&n(Ah,{entity:d,history:f})]}),Fs&&h&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>Rn(!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:ee=>ee.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:()=>Rn(!1),children:"×"})]}),n("div",{className:"flex-1 overflow-hidden",children:n($t,{projectSlug:h,onClose:()=>Rn(!1)})})]})}),Zt&&$e&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>en(!1),children:c("div",{className:"bg-white rounded-xl max-w-200 w-full max-h-[90vh] flex flex-col shadow-[0_20px_60px_rgba(0,0,0,0.3)]",onClick:ee=>ee.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:((Hr=$e.instructions)==null?void 0:Hr.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:()=>en(!1),children:"×"})]}),n("div",{className:"px-6",children:n(Ut,{scenarioId:C==null?void 0:C.id,analysisId:u==null?void 0:u.id})}),n("div",{className:"px-6 py-6 overflow-y-auto flex-1",children:n("div",{className:"p-0",children:(Jr=(Vr=$e.instructions)==null?void 0:Vr.sections)==null?void 0:Jr.map((ee,me)=>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:[ee.heading==="Status"&&!$e.complete&&n("div",{className:"w-6 h-6 border-3 border-purple-600 border-t-transparent rounded-full animate-spin",style:{borderWidth:"3px"}}),ee.heading]}),ee.items.map((xe,ge)=>c("div",{className:"mb-3 pl-0 last:mb-0",children:[xe.label&&n("div",{className:"font-semibold text-gray-700 mb-1 text-sm",children:xe.label}),xe.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:xe.content}),n(ar,{content:xe.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"})]}):xe.isLink?c("div",{className:"flex items-center gap-2 mt-1",children:[n("a",{href:xe.content,target:"_blank",rel:"noopener noreferrer",className:"text-purple-600 hover:text-purple-800 underline text-sm font-medium",children:xe.content}),n(ar,{content:xe.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:xe.content})]},ge))]},me))})}),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:()=>en(!1),children:"Close"})})]})})]})})}),zh=Object.freeze(Object.defineProperty({__proto__:null,default:Yh,loader:Fh,meta:Lh,shouldRevalidate:Oh},Symbol.toStringTag,{value:"Module"}));async function Bh(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 Oe();const i=ye();if(!i)throw new Error("Project root not found");console.log(`[analyzeEntities] Project root: ${i}`);const l=be.join(i,".codeyam","config.json"),d=JSON.parse(await Te.readFile(l,"utf8")),{projectSlug:u,branchId:h}=d;if(!u||!h)throw new Error("Invalid project configuration - missing projectSlug or branchId");console.log(`[analyzeEntities] Project: ${u}, Branch: ${h}`);const m=Mn(u);try{await Te.writeFile(m,"","utf8"),console.log("[analyzeEntities] Cleared log file")}catch{}const{project:p,branch:f}=await Ue(u);console.log("[analyzeEntities] Loading entities to determine file paths and names...");const g=await wt({shas:t});if(!g||g.length===0)throw new Error(`No entities found for SHAs: ${t.join(", ")}`);let y=r;if((!y||y.length===0)&&(y=[...new Set(g.map(v=>v.filePath).filter(v=>!!v))],console.log(`[analyzeEntities] Found ${y.length} unique files`)),!y||y.length===0)throw new Error("No file paths available for analysis");console.log(`[analyzeEntities] Creating fake commit for ${y.length} files...`);const w=await Sl(p,f,y);console.log(`[analyzeEntities] Created commit ${w.sha.substring(0,8)}`),console.log("[analyzeEntities] Initializing progress tracking..."),await Mt({commitSha:w.sha,runStatusUpdate:{queuedAt:new Date().toISOString(),entityCount:t.length,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString()},updateCallback:(v,b)=>{if(!v)return;const N=v.currentRun;if(N&&N.id&&N.archivedAt)return;N&&(N.analysesCompleted&&N.analysesCompleted>0||N.capturesCompleted&&N.capturesCompleted>0)&&Dl(v)}}),console.log("[analyzeEntities] Enqueueing analysis job...");const{jobId:x}=o.enqueue({type:"analysis",commitSha:w.sha,projectSlug:u,filePaths:y,entityShas:t,entityNames:g.map(v=>v.name),...a?{context:a}:{},...s?{scenarioCount:s}:{}});return console.log(`[analyzeEntities] Job queued with ID: ${x} for ${t.length} entities`),{jobId:x}}catch(i){throw console.error("[analyzeEntities] Failed:",i),i}}async function Uh({request:e,context:t}){if(e.method!=="POST")return Y({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await at()),!r)return Y({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 u;if(o)u=o.split(",").filter(Boolean);else if(s)u=[s];else return Y({error:"Missing required field: entitySha or entityShas"},{status:400});if(u.length===0)return Y({error:"No entities to analyze"},{status:400});console.log(`[API] Starting analysis for ${u.length} entity(ies)`);const h=await wt({shas:u}),p=[...new Set(h.map(g=>g.filePath).filter(g=>!!g))].length,{jobId:f}=await Bh({entityShas:u,filePaths:i?[i]:void 0,context:l||void 0,scenarioCount:d?parseInt(d,10):void 0,queue:r});return console.log(`[API] Analysis queued with job ID: ${f}`),Y({success:!0,message:`Analysis queued for ${u.length} entity(ies)`,entityCount:u.length,fileCount:p,jobId:f})}catch(a){return console.error("[API] Error starting analysis:",a),Y({error:"Failed to start analysis",details:a.message},{status:500})}}const Wh=Object.freeze(Object.defineProperty({__proto__:null,action:Uh},Symbol.toStringTag,{value:"Module"}));function Hh(e){switch(e){case"queued":return{text:"Queued",bgColor:"#cbf3fa",textColor:"#3098b4",icon:c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]})};case"analyzing":return{text:"Analyzing...",bgColor:"#ffdbf6",textColor:"#ff2ab5",icon:c("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]})};case"up-to-date":return{text:"Up to date",bgColor:"#e8ffe6",textColor:"#00925d",icon:null};case"incomplete":return{text:"Incomplete",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"out-of-date":return{text:"Out of date",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"not-analyzed":return{text:"Not analyzed",bgColor:"#f9f9f9",textColor:"#646464",icon:null}}}function Rs(e){if(!e)return"Never";const t=new Date(e),r=new Date;if(t.getDate()===r.getDate()&&t.getMonth()===r.getMonth()&&t.getFullYear()===r.getFullYear()){const s=t.getHours(),o=t.getMinutes(),i=s>=12?"pm":"am",l=s%12||12,d=o.toString().padStart(2,"0");return`Today, ${l}:${d} ${i}`}return t.toLocaleString("en-US",{month:"numeric",day:"numeric",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!0})}function Ve(e,t=[],r=!1){var h,m;if(t.some(p=>{var f,g;return!!((f=p.entityShas)!=null&&f.includes(e.sha)||(g=p.entities)!=null&&g.some(y=>y.sha===e.sha))}))return r?"analyzing":"queued";if(!e.analyses||e.analyses.length===0)return"not-analyzed";const s=e.analyses[0];if(!(((h=s.status)==null?void 0:h.scenarios)&&s.status.scenarios.length>0&&s.status.scenarios.some(p=>p.screenshotFinishedAt||p.finishedAt))||s.entitySha!==e.sha)return"not-analyzed";const i=s.createdAt?new Date(s.createdAt).getTime():0,l=(m=e.metadata)!=null&&m.editedAt?new Date(e.metadata.editedAt).getTime():0,d=s.scenarios||[],u=d.some(p=>{var f,g,y;return((g=(f=p.metadata)==null?void 0:f.screenshotPaths)==null?void 0:g[0])||((y=p.metadata)==null?void 0:y.executionResult)});return i>=l?d.length>0&&u?d.every(f=>{var g,y,w;return((y=(g=f.metadata)==null?void 0:g.screenshotPaths)==null?void 0:y[0])||((w=f.metadata)==null?void 0:w.executionResult)})?"up-to-date":"incomplete":d.length>0?"incomplete":"not-analyzed":"out-of-date"}const Vh=()=>[{title:"Simulations - CodeYam"},{name:"description",content:"A visual gallery of your recently captured component screenshots"}];async function Jh({request:e,context:t}){try{const r=t.analysisQueue,a=r?r.getState():{paused:!1,jobs:[]},s=await Kt();return Y({entities:s||[],queueState:a})}catch(r){return console.error("Failed to load simulations:",r),Y({entities:[],queueState:{paused:!1,jobs:[]},error:"Failed to load simulations"})}}const Gh=We(function(){const t=Ge(),r=t.entities,a=t.queueState;Nt({source:"simulations-page"});const[s,o]=j(""),[i,l]=j("visual"),d=oe(()=>{const y=[];return r.forEach(w=>{var v;const x=(v=w.analyses)==null?void 0:v[0];if(x!=null&&x.scenarios){const b=x.scenarios.map(N=>{var R,E,C,_,$;const T=(E=(R=N.metadata)==null?void 0:R.screenshotPaths)==null?void 0:E[0],S=(C=N.metadata)==null?void 0:C.noScreenshotSaved,A=T&&!S,P=($=(_=x.status)==null?void 0:_.scenarios)==null?void 0:$.find(D=>D.name===N.name),I=P&&P.screenshotStartedAt&&!P.screenshotFinishedAt;let M;return A?M="completed":I?M="capturing":M="error",{scenarioName:N.name,scenarioDescription:N.description||"",screenshotPath:T||"",scenarioId:N.id,state:M}}).filter(N=>N.state==="completed"||N.state==="capturing");b.length>0&&y.push({entity:w,screenshots:b,createdAt:x.createdAt||""})}}),y.sort((w,x)=>new Date(x.createdAt).getTime()-new Date(w.createdAt).getTime()),y},[r]),u=oe(()=>r.filter(y=>{var v,b;const w=(v=y.analyses)==null?void 0:v[0];return!((b=w==null?void 0:w.scenarios)==null?void 0:b.some(N=>{var T,S;return(S=(T=N.metadata)==null?void 0:T.screenshotPaths)==null?void 0:S[0]}))}),[r]),h=oe(()=>d.filter(({entity:y})=>{const w=!s||y.name.toLowerCase().includes(s.toLowerCase()),x=i==="all"||y.entityType===i;return w&&x}),[d,s,i]),m=oe(()=>u.filter(y=>{const w=!s||y.name.toLowerCase().includes(s.toLowerCase()),x=i==="all"||y.entityType===i;return w&&x}),[u,s,i]),p=ae(y=>{o(y.target.value)},[]),f=ae(y=>{l(y.target.value)},[]),g=d.length>0;return n("div",{className:"bg-[#f9f9f9] min-h-screen overflow-y-auto",children:c("div",{className:"px-20 py-12",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-3xl font-semibold text-gray-900 mb-2",children:"Simulations"}),n("p",{className:"text-gray-600",children:"A visual gallery of your recently captured simulations."})]}),!g&&n("div",{className:"bg-[#D1F3F9] border border-[#A5E8F0] rounded-lg p-4 mb-6",children:c("p",{className:"text-sm text-gray-700 m-0",children:["This page will display a visual gallery of your recently captured component simulations."," ",n("strong",{children:"Start by analyzing your first component below."})]})}),c("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),c("div",{className:"flex gap-3",children:[c("div",{className:"relative",children:[c("select",{className:"appearance-none bg-gray-50 border border-gray-200 rounded px-3 pr-8 text-[13px] h-[39px] cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",value:i,onChange:f,children:[n("option",{value:"all",children:"All Types"}),n("option",{value:"visual",children:"Visual"}),n("option",{value:"library",children:"Library"})]}),n(pn,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),c("div",{className:"flex-1 relative",children:[n(La,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-3 text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors",value:s,onChange:p})]})]})]}),g&&h.length>0&&n("div",{className:"bg-[#efefef] rounded-lg mb-2 text-[11px] font-normal leading-[16px] text-[#3e3e3e] uppercase",children:c("div",{className:"flex items-center gap-1.5 px-3 py-2",children:[n("span",{children:"ENTITY"}),n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"text-[#3e3e3e]",children:n("path",{d:"M3 5L6 8L9 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})}),c("div",{className:"flex flex-col gap-[3px]",children:[g&&(h.length===0?n("div",{className:"bg-white border border-gray-200 rounded-lg p-8 text-center text-gray-500",children:"No simulations match your filters."}):n(ue,{children:h.map(({entity:y,screenshots:w})=>n(qh,{entity:y,screenshots:w,queueJobs:(a==null?void 0:a.jobs)||[]},y.sha))})),!g&&(m.length===0?n("div",{className:"bg-white border border-gray-200 rounded-b-lg p-8 text-center text-gray-500",children:"No components found matching your filters."}):m.map(y=>n(Kh,{entity:y},y.sha)))]})]})})});function qh({entity:e,screenshots:t,queueJobs:r}){var d,u,h;const a=It(),s=t.length||(((h=(u=(d=e.analyses)==null?void 0:d[0])==null?void 0:u.scenarios)==null?void 0:h.length)??0),o=m=>{a(`/entity/${e.sha}/scenarios/${m}?from=simulations`)},i=Ve(e,r),l=Hh(i);return n("div",{className:"bg-white rounded hover:bg-gray-50 transition-colors border-b border-[#e1e1e1]",children:c("div",{className:"px-5 pb-[15px]",children:[c("div",{className:"flex items-center justify-between py-[10px]",children:[c(ce,{to:`/entity/${e.sha}`,className:"flex items-center gap-2 no-underline",children:[n(Be,{type:e.entityType}),c("span",{className:"font-['IBM_Plex_Sans'] font-medium text-[12px] leading-[15px] text-[#343434]",children:[e.name," (",s,")"]})]}),c("div",{className:"flex items-center gap-2.5",children:[c("span",{className:"px-2 rounded inline-flex items-center gap-1.5 max-w-full whitespace-nowrap overflow-hidden",style:{backgroundColor:l.bgColor,color:l.textColor,height:"23px",fontSize:"10px",lineHeight:"15px"},children:[l.icon,l.text]}),n("button",{onClick:()=>void a(`/entity/${e.sha}/logs`),className:"bg-[#e0e9ec] text-[#005c75] rounded font-['IBM_Plex_Sans'] font-semibold hover:bg-[#d0dfe5] transition-colors px-[10px] py-0 cursor-pointer border-none",style:{fontSize:"10px",lineHeight:"22px"},children:"View Logs"})]})]}),n("div",{className:"flex gap-2.5 overflow-x-auto pb-1",children:t.length>0?t.map(m=>n("button",{onClick:()=>o(m.scenarioId||""),className:"shrink-0 block cursor-pointer bg-transparent border-none p-0",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{"--hover-border":"#005C75",backgroundColor:m.state==="capturing"?"#f9f9f9":"#f3f4f6",borderColor:m.state==="capturing"?"#efefef":"#d1d5db"},onMouseEnter:p=>{m.state==="completed"&&(p.currentTarget.style.borderColor="#005C75",p.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:p=>{p.currentTarget.style.borderColor=m.state==="capturing"?"#efefef":"#d1d5db",p.currentTarget.style.boxShadow="none"},children:m.state==="completed"?n(Le,{screenshotPath:m.screenshotPath,alt:m.scenarioName,className:"max-w-full max-h-full object-contain"}):m.state==="capturing"?n(Er,{size:"medium"}):null})},m.scenarioId)):n("div",{className:"text-xs text-gray-400 py-4",children:"No screenshots available"})})]})})}function Kh({entity:e}){const t=_e(),[r,a]=j(!1),s=()=>{a(!0),t.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};return re(()=>{t.state==="idle"&&r&&a(!1)},[t.state,r]),n("div",{className:"bg-white rounded hover:bg-gray-100 transition-colors cursor-pointer border-b border-[#e1e1e1]",onClick:s,children:c("div",{className:"px-5 py-4 flex items-center",children:[c("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n(Be,{type:e.entityType}),c("div",{className:"min-w-0",children:[c("div",{className:"flex items-center gap-3 mb-0.5",children:[n(ce,{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:Rs(e.createdAt||null)}),n("div",{className:"w-24 flex justify-end",children:r||t.state!=="idle"?c("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(nt,{size:14,className:"animate-spin"}),"Analyzing..."]}):n("button",{onClick:s,className:"bg-[#e0e9ec] text-[#005c75] px-4 py-1.5 rounded text-xs font-medium hover:bg-[#d0dde1] transition-colors cursor-pointer",children:"Analyze"})})]})})}const Qh=Object.freeze(Object.defineProperty({__proto__:null,default:Gh,loader:Jh,meta:Vh},Symbol.toStringTag,{value:"Module"}));function Xh({request:e,context:t}){const r=t.dbNotifier||Zn;if(!r)return console.error("[SSE] ERROR: dbNotifier not found in context or global!"),new Response("Server configuration error",{status:500});r.start().catch(()=>{});const a=new ReadableStream({start(s){const o=new TextEncoder;s.enqueue(o.encode(`data: ${JSON.stringify({type:"connected"})}
169
+
170
+ `)),Math.random().toString(36).substring(7);let i=!1;const l=()=>{if(!i){i=!0,r.off("change",d),clearInterval(u);try{s.close()}catch{}}},d=h=>{try{s.enqueue(o.encode(`data: ${JSON.stringify({type:"db-change",changeType:h.type,timestamp:h.timestamp})}
171
+
172
+ `))}catch{l()}};r.on("change",d);const u=setInterval(()=>{try{s.enqueue(o.encode(`data: ${JSON.stringify({type:"keepalive"})}
173
+
174
+ `))}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 Zh=Object.freeze(Object.defineProperty({__proto__:null,loader:Xh},Symbol.toStringTag,{value:"Module"}));function yt(){const e=process.memoryUsage(),t=ni.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(Qn.totalmem()/1024/1024),freeMemory:Math.round(Qn.freemem()/1024/1024)}}}function em(){const e=yt();console.log(`
175
+ [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 tm(){if(global.gc){console.log("[Memory Profiler] Running garbage collection...");const e=yt();global.gc();const t=yt(),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 nm(){const e=yt(),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 rm({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=tm(),s=yt();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=em();return Response.json({success:!0,stats:a})}case"leaks":{const a=nm(),s=yt();return Response.json({success:!0,leakCheck:a,stats:s})}default:{const a=yt();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 am=Object.freeze(Object.defineProperty({__proto__:null,loader:rm},Symbol.toStringTag,{value:"Module"}));async function sm({request:e,context:t}){var o;let r=t.analysisQueue;if(r||(r=await at()),!r)return Y({error:"Queue not initialized"},{status:500});const a=new URL(e.url),s=a.searchParams.get("queryType");if(!s)return Y({error:"Missing queryType parameter for GET request"},{status:400});if(s==="job"){const i=a.searchParams.get("jobId");if(!i)return Y({error:"Missing jobId parameter for job query"},{status:400});const l=r.getState();if(((o=l.currentlyExecuting)==null?void 0:o.id)===i)return Y({jobId:i,status:"running",job:l.currentlyExecuting});const d=l.jobs.find(h=>h.id===i);if(d){const h=l.jobs.indexOf(d);return Y({jobId:i,status:"queued",position:h,job:d})}const u=r.getJobResult(i);return u?Y({jobId:i,status:u.status==="error"?"failed":"completed",error:u.error}):Y({jobId:i,status:"completed"})}if(s==="full"){const i=r.getState(),l=await Promise.all(i.jobs.map(async u=>{const h=[];if(u.entityShas&&u.entityShas.length>0){const m=u.entityShas.map(f=>Ct(f)),p=await Promise.all(m);h.push(...p.filter(f=>f!==null))}return{id:u.id,type:u.type,commitSha:u.commitSha,projectSlug:u.projectSlug,queuedAt:u.queuedAt,entities:h,filePaths:u.filePaths}}));let d;if(i.currentlyExecuting){const u=i.currentlyExecuting,h=[];if(u.entityShas&&u.entityShas.length>0){const m=u.entityShas.map(f=>Ct(f)),p=await Promise.all(m);h.push(...p.filter(f=>f!==null))}d={id:u.id,type:u.type,commitSha:u.commitSha,projectSlug:u.projectSlug,queuedAt:u.queuedAt,entities:h,filePaths:u.filePaths}}return Y({state:{...i,jobsWithEntities:l,currentlyExecutingWithEntities:d}})}return Y({error:"Unknown queryType"},{status:400})}async function om({request:e,context:t}){console.log("[Queue API] Received request"),console.log("[Queue API] Context keys:",Object.keys(t||{})),console.log("[Queue API] analysisQueue exists:",!!(t!=null&&t.analysisQueue));let r=t.analysisQueue;if(r||(r=await at(),console.log("[Queue API] Using global queue")),!r)return console.error("[Queue API] ERROR: Queue not initialized in context"),Y({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)}),Y({jobId:i,status:"queued"})}if(s==="resume")return r.resume(),Y({status:"resumed"});if(s==="pause")return r.pause(),Y({status:"paused"});if(s==="remove"){const{jobId:i}=o;return i?r.removeJob(i)?Y({status:"removed",jobId:i}):Y({error:"Job not found in queue"},{status:404}):Y({error:"Missing jobId parameter"},{status:400})}if(s==="clear"){const i=r.clearQueue();return Y({status:"cleared",count:i})}if(s==="reorder"){const{jobId:i,direction:l}=o;return!i||!l?Y({error:"Missing jobId or direction parameter"},{status:400}):l!=="up"&&l!=="down"?Y({error:'Invalid direction: must be "up" or "down"'},{status:400}):r.reorderJob(i,l)?Y({status:"reordered",jobId:i,direction:l}):Y({error:"Could not reorder job (not found or at boundary)"},{status:400})}return Y({error:"Unknown action"},{status:400})}const im=Object.freeze(Object.defineProperty({__proto__:null,action:om,loader:sm},Symbol.toStringTag,{value:"Module"})),lm=()=>[{title:"Empty State - CodeYam"},{name:"description",content:"Simulations empty state development view"}],cm=We(function(){return _e(),n(In,{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($s,{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})]})]})})}),dm=Object.freeze(Object.defineProperty({__proto__:null,default:cm,meta:lm},Symbol.toStringTag,{value:"Module"})),um=()=>[{title:"CodeYam - Settings"},{name:"description",content:"Configure project settings"}];async function hm({request:e}){try{const t=await vr();if(!t)return Y({config:null,secrets:null,versionInfo:null,error:"Project configuration not found"});const r=ye()||process.cwd(),a=await kn(r),s=xs(t.projectSlug);return Y({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),Y({config:null,secrets:null,versionInfo:null,error:"Failed to load configuration"})}}function mm(e){if(!e||!e.trim())return;const t=e.trim().split(/\s+/);if(t.length===0)return;const r=t[0],a=t.length>1?t.slice(1):void 0;return{command:r,args:a}}async function pm({request:e}){try{const t=await e.formData(),r=t.get("universalMocks"),a=t.get("startCommands"),s=t.get("groqApiKey"),o=t.get("anthropicApiKey"),i=t.get("openAiApiKey"),l=t.get("pathsToIgnore");let d;if(r)try{d=JSON.parse(r)}catch{return Y({success:!1,error:"Invalid universalMocks JSON format",requiresRestart:!1},{status:400})}let u;if(a)try{u=JSON.parse(a)}catch{return Y({success:!1,error:"Invalid startCommands JSON format",requiresRestart:!1},{status:400})}let h;l&&(h=l.split(",").map(g=>g.trim()).map(g=>g.startsWith('"')&&g.endsWith('"')||g.startsWith("'")&&g.endsWith("'")?g.slice(1,-1):g).filter(g=>g.length>0));let m;if(u){const g=await vr();g!=null&&g.webapps&&(m=g.webapps.map((y,w)=>{if(u[w]!==void 0){const x=mm(u[w]);return{...y,startCommand:x}}return y}))}if(!await ls({universalMocks:d,pathsToIgnore:h,webapps:m}))return Y({success:!1,error:"Failed to update configuration",requiresRestart:!1},{status:500});let f=!1;if(s!==void 0||o!==void 0||i!==void 0){const g=ye()||process.cwd(),y=await kn(g);f=s!==void 0&&s!==(y.GROQ_API_KEY||"")||o!==void 0&&o!==(y.ANTHROPIC_API_KEY||"")||i!==void 0&&i!==(y.OPENAI_API_KEY||""),await El(g,{...y,GROQ_API_KEY:s||void 0,ANTHROPIC_API_KEY:o||void 0,OPENAI_API_KEY:i||void 0},!0)}return Y({success:!0,error:null,requiresRestart:f})}catch(t){return console.log("[Settings Action] Failed to save config:",t),Y({success:!1,error:"Failed to save configuration",requiresRestart:!1},{status:500})}}function Ta(e){if(!e)return"";const t=[e.command];return e.args&&e.args.length>0&&t.push(...e.args),t.join(" ")}function Ia({mock:e,onSave:t,onCancel:r}){const[a,s]=j(e.entityName),[o,i]=j(e.filePath),[l,d]=j(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:h=>s(h.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., determineDatabaseType"})]}),c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path"}),n("input",{type:"text",value:o,onChange:h=>i(h.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., packages/database/src/lib/kysely/db.ts"})]}),c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:l,onChange:h=>d(h.target.value),rows:6,className:"w-full px-3 py-2 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., function determineDatabaseType() { return 'postgresql' }"})]}),c("div",{className:"flex gap-2 justify-end",children:[n("button",{type:"button",onClick:r,className:"px-4 py-2 bg-gray-200 text-gray-800 border-none rounded text-sm cursor-pointer hover:bg-gray-300",children:"Cancel"}),n("button",{type:"button",onClick:()=>{if(!a.trim()||!o.trim()||!l.trim()){alert("All fields are required");return}t({entityName:a,filePath:o,content:l})},className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Save"})]})]})}function fm(e){try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}const gm=We(function(){var U,G;const{config:t,secrets:r,versionInfo:a,error:s}=Ge(),o=oo(),i=_e(),l=lt(),[d,u]=j("project-metadata");Nt({source:"settings-page"});const[h,m]=j((t==null?void 0:t.universalMocks)||[]),[p,f]=j(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[g,y]=j(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[w,x]=j((r==null?void 0:r.GROQ_API_KEY)||""),[v,b]=j((r==null?void 0:r.ANTHROPIC_API_KEY)||""),[N,T]=j((r==null?void 0:r.OPENAI_API_KEY)||""),[S,A]=j(!1),[P,I]=j(!1),[M,R]=j(!1),[E,C]=j(!1),[_,$]=j(!1),[D,z]=j(!1),[W,K]=j(null),[Q,te]=j(!1),[F,H]=j({});re(()=>{var O;if(t){m(t.universalMocks||[]);const Z=(t.pathsToIgnore||[]).join(", ");f(Z),y(Z);const le={};(O=t.webapps)==null||O.forEach((he,fe)=>{he.startCommand&&(le[fe]=Ta(he.startCommand))}),H(le)}r&&(x(r.GROQ_API_KEY||""),b(r.ANTHROPIC_API_KEY||""),T(r.OPENAI_API_KEY||""))},[t,r]),re(()=>{if(o!=null&&o.success){C(!0);const O=setTimeout(()=>C(!1),3e3);return()=>clearTimeout(O)}},[o]),re(()=>{if(i.state==="idle"&&i.data&&!D){console.log("[Settings] Fetcher data:",i.data);const O=i.data;if(O.success){console.log("[Settings] Save successful, revalidating..."),C(!0),z(!0),(p!==g||O.requiresRestart)&&$(!0),l.revalidate();const Z=setTimeout(()=>{C(!1),z(!1)},3e3);return()=>clearTimeout(Z)}}},[i.state,i.data,D,l,p,g]);const k=O=>{O.preventDefault();const Z=new FormData(O.currentTarget);Z.set("universalMocks",JSON.stringify(h)),Z.set("startCommands",JSON.stringify(F)),console.log("[Settings] Submitting form data:",{universalMocks:Z.get("universalMocks"),startCommands:Z.get("startCommands"),openAiApiKey:Z.get("openAiApiKey")?"***":"(empty)"}),i.submit(Z,{method:"post"})},B=O=>{m([...h,O]),te(!1)},ne=(O,Z)=>{const le=[...h];le[O]=Z,m(le),K(null)},V=O=>{m(h.filter((Z,le)=>le!==O))};if(s)return c("div",{className:"max-w-6xl mx-auto p-8 font-sans",children:[n("header",{className:"mb-6 pb-4 border-b border-gray-200",children:n("div",{className:"flex justify-between items-center",children:n("h1",{className:"text-4xl font-bold text-gray-900",children:"Settings"})})}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4",children:n("p",{className:"text-red-700",children:s})})]});const L=[{id:"project-metadata",label:"Project Metadata"},{id:"ai-provider",label:"AI Provider Configuration"},{id:"commands",label:"Commands"},{id:"paths-to-ignore",label:"Paths To Ignore"},{id:"universal-mocks",label:"Universal Mocks"},{id:"current-configuration",label:"Current Configuration"}];return n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-20 py-12 font-sans",children:[c("div",{className:"mb-8 flex justify-between items-start",children:[c("div",{children:[n("h1",{className:"text-3xl font-semibold text-gray-900 mb-2",children:"Settings"}),n("p",{className:"text-gray-600",children:"Project Configuration"})]}),n("button",{type:"submit",form:"settings-form",disabled:i.state==="submitting",className:"px-6 py-2 bg-[#005C75] text-white border-none rounded text-sm font-medium cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 hover:bg-[#004a5d] whitespace-nowrap",children:i.state==="submitting"?"Saving...":"Save Settings"})]}),c("div",{className:"flex gap-8 items-start",children:[n("nav",{className:"w-64 flex-shrink-0",children:n("ul",{className:"space-y-1",children:L.map(O=>n("li",{children:n("button",{type:"button",onClick:()=>u(O.id),className:`w-full text-left px-0 py-2.5 text-sm transition-colors cursor-pointer ${d===O.id?"text-[#005C75] font-medium":"text-gray-600 hover:text-gray-900"}`,children:O.label})},O.id))})}),n("div",{className:"flex-1 min-w-0 -mt-2",children:c("form",{id:"settings-form",onSubmit:k,className:"space-y-6",children:[d==="project-metadata"&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Project Metadata"}),c("div",{className:"mb-6",children:[n("label",{className:"block mb-2 font-medium text-gray-700",children:"Web Applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-3",children:t.webapps.map((O,Z)=>{var le;return n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:c("div",{className:"space-y-2 text-sm",children:[c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:O.path==="."?"Root":O.path})]}),O.appDirectory&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:O.appDirectory})]}),c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:O.framework})]}),O.startCommand&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",c("span",{className:"text-gray-900 font-mono text-xs",children:[O.startCommand.command," ",(le=O.startCommand.args)==null?void 0:le.join(" ")]})]})]})},Z)})}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"}),n("p",{className:"mt-2 text-sm text-gray-600",children:"Web applications are detected during initialization. To modify, edit `.codeyam/config.json` or re-run `codeyam init`."})]})]}),d==="ai-provider"&&c("div",{children:[n("h3",{className:"text-lg font-semibold text-gray-800 mb-4",children:"AI Provider API Keys"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure API keys for AI-powered analysis. Choose the provider that best fits your needs."}),c("div",{className:"space-y-6",children:[c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:c("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Groq"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Lightning-fast inference with industry-leading speed. Groq's LPU architecture delivers exceptional performance for real-time AI applications with competitive pricing."}),c("div",{className:"flex gap-3 text-xs",children:[c("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$0.10/1M tokens"]}),c("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 850 tokens/s"]}),c("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Less reliable, but capable of producing reasonable results"]})]})]})}),c("div",{className:"mt-4",children:[n("label",{htmlFor:"groqApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),c("div",{className:"relative",children:[n("input",{type:S?"text":"password",id:"groqApiKey",name:"groqApiKey",value:w,onChange:O=>x(O.target.value),placeholder:"gsk_...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>A(!S),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:S?"Hide":"Show"})]})]})]}),c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:c("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Anthropic Claude"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Advanced reasoning and coding capabilities with superior context understanding. Claude excels at complex analysis tasks and provides highly accurate results with detailed explanations."}),c("div",{className:"flex gap-3 text-xs",children:[c("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$3.00/1M tokens"]}),c("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 120 tokens/s"]}),c("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),c("div",{className:"mt-4",children:[n("label",{htmlFor:"anthropicApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),c("div",{className:"relative",children:[n("input",{type:P?"text":"password",id:"anthropicApiKey",name:"anthropicApiKey",value:v,onChange:O=>b(O.target.value),placeholder:"sk-ant-...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>I(!P),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:P?"Hide":"Show"})]})]})]}),c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:c("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"OpenAI GPT"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Industry-standard AI with broad capabilities and extensive ecosystem. GPT models offer reliable performance across diverse tasks with good balance of speed and quality."}),c("div",{className:"flex gap-3 text-xs",children:[c("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$2.50/1M tokens"]}),c("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 150 tokens/s"]}),c("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),c("div",{className:"mt-4",children:[n("label",{htmlFor:"openAiApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),c("div",{className:"relative",children:[n("input",{type:M?"text":"password",id:"openAiApiKey",name:"openAiApiKey",value:N,onChange:O=>T(O.target.value),placeholder:"sk-...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>R(!M),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:M?"Hide":"Show"})]})]})]})]})]}),d==="commands"&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Commands"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure start commands for your web applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-4",children:t.webapps.map((O,Z)=>c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[c("div",{className:"mb-4",children:[n("div",{className:"text-base font-semibold text-gray-900 mb-1",children:O.path==="."?"Root":O.path}),n("div",{className:"text-sm text-gray-600",children:O.framework})]}),c("div",{children:[n("label",{htmlFor:`startCommand-${Z}`,className:"block text-sm font-medium text-gray-700 mb-2",children:"Start Command"}),n("input",{type:"text",id:`startCommand-${Z}`,name:`startCommand-${Z}`,value:F[Z]||"",onChange:le=>H({...F,[Z]:le.target.value}),placeholder:"e.g., pnpm dev --port $PORT",className:"w-full px-3 py-2 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("p",{className:"mt-2 text-xs text-gray-500",children:"Use $PORT as a placeholder for the dynamic port number"})]})]},Z))}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"})]}),d==="paths-to-ignore"&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Paths To Ignore"}),n("input",{type:"text",id:"pathsToIgnore",name:"pathsToIgnore",value:p,onChange:O=>f(O.target.value),placeholder:"e.g., __tests__, \\.test\\.ts$, ^background (no quotes needed)",className:"w-full px-3 py-3 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-2 focus:ring-[#005C75]/10"}),c("p",{className:"mt-2 text-sm text-gray-600",children:["Comma-separated list of regex patterns for paths to ignore during file watching. Examples:"," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"__tests__"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"\\.test\\.tsx?$"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"^background"}),n("br",{}),n("span",{className:"text-xs text-gray-500 mt-1 inline-block",children:"Note: Files matching patterns in .gitignore are also automatically ignored"})]})]}),d==="universal-mocks"&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Universal Mocks"}),n("p",{className:"mb-3 text-sm text-gray-600",children:"Mock functions that will be applied across all entity simulations"}),h.length===0?c("div",{className:"mb-4",children:[n("div",{className:"text-sm text-gray-500 mb-3",children:"No universal mocks configured"}),n("button",{type:"button",onClick:()=>te(!0),className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}):n("div",{className:"space-y-3",children:h.map((O,Z)=>n("div",{className:"p-4 bg-gray-50 rounded border border-gray-200",children:W===Z?n(Ia,{mock:O,onSave:le=>ne(Z,le),onCancel:()=>K(null)}):n(ue,{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:O.entityName}),n("div",{className:"text-sm text-gray-600 mb-2",children:O.filePath}),n("pre",{className:"text-xs bg-white p-2 rounded border border-gray-200 overflow-x-auto",children:O.content})]}),c("div",{className:"flex gap-2 ml-3",children:[n("button",{type:"button",onClick:()=>K(Z),className:"px-3 py-1 bg-teal-600 text-white border-none rounded text-sm cursor-pointer hover:bg-teal-700",children:"Edit"}),n("button",{type:"button",onClick:()=>V(Z),className:"px-3 py-1 bg-red-600 text-white border-none rounded text-sm cursor-pointer hover:bg-red-700",children:"Delete"})]})]})})},Z))}),h.length>0&&n("button",{type:"button",onClick:()=>te(!0),className:"mt-4 px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}),d==="current-configuration"&&c("div",{className:"space-y-6",children:[t&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Current Configuration"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded mb-6",children:c("div",{className:"space-y-2 text-sm",children:[t.projectSlug&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Project Slug:"})," ",n("span",{className:"text-gray-900",children:t.projectSlug})]}),t.packageManager&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Package Manager:"})," ",n("span",{className:"text-gray-900",children:t.packageManager})]})]})}),t.webapps&&t.webapps.length>0&&c("div",{children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Web Applications"}),n("div",{className:"space-y-3",children:t.webapps.map((O,Z)=>n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:c("div",{className:"space-y-2 text-sm",children:[c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:O.path==="."?"Root":O.path})]}),O.appDirectory&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:O.appDirectory})]}),c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:O.framework})]}),O.startCommand&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",n("span",{className:"text-gray-900 font-mono text-xs",children:Ta(O.startCommand)})]})]})},Z))})]})]}),a&&c("div",{className:"mt-6",children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Version Information"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:c("div",{className:"space-y-2 text-sm",children:[a.webserverVersion&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Webserver:"})," ",n("span",{className:"text-gray-900 font-mono",children:a.webserverVersion.version||"unknown"})]}),a.templateVersion&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Analyzer Template:"})," ",n("span",{className:"font-mono text-gray-900",children:a.templateVersion.version||((U=a.templateVersion.gitCommit)==null?void 0:U.slice(0,7))||"unknown"}),a.templateVersion.buildTimestamp&&c("span",{className:"text-gray-500 ml-2",children:["(built"," ",fm(a.templateVersion.buildTimestamp),")"]})]}),a.cachedAnalyzerVersion&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"font-mono text-gray-900",children:a.cachedAnalyzerVersion.version||((G=a.cachedAnalyzerVersion.gitCommit)==null?void 0:G.slice(0,7))||"unknown"}),a.isCacheStale?n("span",{className:"ml-2 px-2 py-0.5 bg-amber-100 text-amber-800 rounded text-xs",children:"Stale - will update on next analysis"}):n("span",{className:"ml-2 px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:"Up to date"})]}),!a.cachedAnalyzerVersion&&(t==null?void 0:t.projectSlug)&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"text-gray-500 italic",children:"Not initialized - will be created on first analysis"})]})]})})]})]})]})})]}),(E||_||(o==null?void 0:o.error)||i.data&&typeof i.data=="object"&&"error"in i.data)&&c("div",{className:"mt-6 max-w-5xl mx-auto space-y-3",children:[E&&n("div",{className:"text-emerald-600 text-sm font-medium bg-emerald-50 border border-emerald-200 rounded px-4 py-2",children:"Settings saved successfully!"}),_&&c("div",{className:"text-amber-700 text-sm font-medium bg-amber-50 border border-amber-200 rounded px-4 py-2",children:[n("div",{children:"⚠️ Settings changed. Please restart CodeYam for changes to take effect:"}),n("code",{className:"ml-2 bg-amber-100 px-2 py-1 rounded text-xs",children:"codeyam stop && codeyam"})]}),(o==null?void 0:o.error)&&n("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:o.error}),(()=>{if(i.data&&typeof i.data=="object"&&"error"in i.data){const O=i.data;return typeof O.error=="string"?n("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:O.error}):null}return null})()]}),Q&&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(Ia,{mock:{entityName:"",filePath:"",content:""},onSave:B,onCancel:()=>te(!1)})]})})]})})}),ym=Object.freeze(Object.defineProperty({__proto__:null,action:pm,default:gm,loader:hm,meta:um},Symbol.toStringTag,{value:"Module"}));async function xm({params:e}){const t=e["*"];if(!t)return new Response("Static path is required",{status:400});const r=ye();if(!r)return new Response("Project root not found",{status:500});const s=be.extname(t)!==""?t:`${t}.html`,o=be.join(r,".codeyam","captures","static",s);try{await Te.access(o);let i=await Te.readFile(o);const l=be.extname(o).toLowerCase();let d="application/octet-stream";if(l===".html"){d="text/html";let u=i.toString("utf-8");const h=u.match(/<script>(window\.__remixContext\s*=\s*\{[\s\S]*?\});?<\/script>/i);if(h)try{const p=h[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>`;u=u.replace(h[0],g)}}catch(m){console.error("[Static] Failed to parse Remix context:",m)}i=Buffer.from(u,"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 bm=Object.freeze(Object.defineProperty({__proto__:null,loader:xm},Symbol.toStringTag,{value:"Module"}));function vm(e,t,r=10){var d;const a=new Map,s=u=>u.entityType==="visual"||u.entityType==="library";for(const u of e)s(u)&&a.set(u.sha,{entity:u,depth:0});const o=new Map;for(const u of t){const h=(d=u.metadata)==null?void 0:d.importedBy;if(h)for(const m of Object.keys(h))for(const p of Object.keys(h[m])){const{shas:f}=h[m][p];for(const g of f)o.has(u.sha)||o.set(u.sha,new Set),o.get(u.sha).add(g)}}const i=[],l=new Set;for(const u of e)i.push({sha:u.sha,depth:0}),l.add(u.sha);for(;i.length>0;){const{sha:u,depth:h}=i.shift();if(h>=r)continue;const m=o.get(u);if(m)for(const p of m){if(l.has(p))continue;l.add(p);const f=t.find(g=>g.sha===p);if(f){if(s(f)){const g=h+1,y=a.get(p);(!y||g<y.depth)&&a.set(p,{entity:f,depth:g})}i.push({sha:p,depth:h+1})}}}return Array.from(a.values()).sort((u,h)=>u.depth!==h.depth?u.depth-h.depth:u.entity.name.localeCompare(h.entity.name))}function Nn(e){const t=new Map;for(const a of e)t.has(a.name)||t.set(a.name,[]),t.get(a.name).push(a);const r=[];for(const a of t.values())if(a.length===1)r.push(a[0]);else{const s=a.sort((o,i)=>{var u,h;const l=((u=o.metadata)==null?void 0:u.editedAt)||o.createdAt||"";return(((h=i.metadata)==null?void 0:h.editedAt)||i.createdAt||"").localeCompare(l)});r.push(s[0])}return r}function Ds(e,t){const r=new Map,a=new Set(e.map(s=>s.path));for(const s of e)s.status==="renamed"&&s.oldPath&&a.add(s.oldPath);for(const s of e){const o=t.filter(d=>d.filePath===s.path||s.status==="renamed"&&s.oldPath&&d.filePath===s.oldPath),i=o.filter(d=>{var u,h;return a.has(d.filePath)&&((u=d.metadata)==null?void 0:u.isUncommitted)&&!((h=d.metadata)!=null&&h.isSuperseded)}),l=Nn(i);r.set(s.path,{status:s,entities:o,editedEntities:l})}return r}function wm(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=Nn(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(u=>(u.filePath===o.path||o.status==="renamed"&&o.oldPath&&u.filePath===o.oldPath)&&i.has(u.name)):[],d=Nn(l);a.set(o.path,{status:o,entities:d})}}return a}function Cm(e,t){const r=new Map,a=Ls(e,t);for(const s of a){const i=vm([s],t).filter(({depth:l})=>l>0);r.set(s.sha,i)}return r}function Ls(e,t){const r=new Set(e.map(s=>s.path));for(const s of e)s.status==="renamed"&&s.oldPath&&r.add(s.oldPath);const a=t.filter(s=>{var o,i;return r.has(s.filePath)&&((o=s.metadata)==null?void 0:o.isUncommitted)&&!((i=s.metadata)!=null&&i.isSuperseded)});return Nn(a)}const Nm="/assets/codeyam-name-logo-CvKwUgHo.svg",Sm=()=>[{title:"Dashboard - CodeYam"},{name:"description",content:"CodeYam project dashboard"}];async function Am({request:e,context:t}){var r,a;try{const s=t.analysisQueue,o=s?s.getState():{paused:!1,jobs:[]},[i,l,d]=await Promise.all([Kt(),Fe(),Pt()]),u=Ps(),h=i?Ds(u,i):new Map,m=Array.from(h.entries()).sort((M,R)=>M[0].localeCompare(R[0])),p=(i==null?void 0:i.length)||0,f=(i==null?void 0:i.filter(M=>M.entityType==="visual").length)||0,g=(i==null?void 0:i.filter(M=>M.entityType==="library").length)||0,y=i?Ls(u,i):[],w=y.length,x=(i==null?void 0:i.filter(M=>(M.analyses??[]).filter(R=>R.scenarios&&R.scenarios.length>0).length>0).length)||0,v=(i==null?void 0:i.reduce((M,R)=>{var C,_,$;const E=(($=(_=(C=R.analyses)==null?void 0:C[0])==null?void 0:_.scenarios)==null?void 0:$.length)||0;return M+E},0))||0,b=(i==null?void 0:i.reduce((M,R)=>{var _,$;const C=((($=(_=R.analyses)==null?void 0:_[0])==null?void 0:$.scenarios)||[]).filter(D=>{var z,W;return(W=(z=D.metadata)==null?void 0:z.screenshotPaths)==null?void 0:W[0]}).length;return M+C},0))||0,N=[];i==null||i.forEach(M=>{var E;const R=(E=M.analyses)==null?void 0:E[0];R!=null&&R.scenarios&&R.scenarios.forEach(C=>{var $,D;const _=(D=($=C.metadata)==null?void 0:$.screenshotPaths)==null?void 0:D[0];_&&N.push({entitySha:M.sha,entityName:M.name,scenarioId:C.id,scenarioName:C.name,screenshotPath:_,createdAt:R.createdAt||""})})}),N.sort((M,R)=>new Date(R.createdAt).getTime()-new Date(M.createdAt).getTime());const T=N.slice(0,16),S=(i==null?void 0:i.filter(M=>M.entityType==="visual").filter(M=>{var C,_;const R=(C=M.analyses)==null?void 0:C[0];return!((_=R==null?void 0:R.scenarios)==null?void 0:_.some($=>{var D,z;return(z=(D=$.metadata)==null?void 0:D.screenshotPaths)==null?void 0:z[0]}))}).slice(0,8))||[],A=(r=d==null?void 0:d.metadata)==null?void 0:r.currentRun,P=((a=A==null?void 0:A.currentEntityShas)==null?void 0:a.length)||0,I=o.jobs.length||0;return Y({stats:{totalEntities:p,visualEntities:f,libraryEntities:g,uncommittedEntities:w,entitiesWithAnalyses:x,totalScenarios:v,capturedScreenshots:b,currentlyAnalyzing:P,filesOnQueue:I},uncommittedFiles:m,uncommittedEntitiesList:y,recentSimulations:T,visualEntitiesForSimulation:S,projectSlug:l,queueState:o,currentCommit:d})}catch(s){return console.error("Failed to load dashboard data:",s),Y({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 Em=We(function(){var F,H;const{stats:t,uncommittedFiles:r,uncommittedEntitiesList:a,recentSimulations:s,visualEntitiesForSimulation:o,projectSlug:i,queueState:l,currentCommit:d}=Ge(),u=_e(),h=lt(),{showToast:m}=pr();Nt({source:"dashboard"});const[p,f]=j(new Set),[g,y]=j(null),[w,x]=j(!1),[v,b]=j(!1),{lastLine:N,isCompleted:T,resetLogs:S}=ct(i,!!g),{simulatingEntity:A,scenarios:P,scenarioStatuses:I,allScenariosCaptured:M}=oe(()=>{var O,Z;const k={simulatingEntity:null,scenarios:[],scenarioStatuses:[],allScenariosCaptured:!1};if(!g)return k;const B=o==null?void 0:o.find(le=>le.sha===g);if(!B)return k;const ne=(O=B.analyses)==null?void 0:O[0],V=(ne==null?void 0:ne.scenarios)||[],L=((Z=ne==null?void 0:ne.status)==null?void 0:Z.scenarios)||[],U=L.filter(le=>le.screenshotFinishedAt).length,G=V.length>0&&U===V.length;return{simulatingEntity:B,scenarios:V,scenarioStatuses:L,allScenariosCaptured:G}},[g,o]);re(()=>{(T||M)&&y(null)},[T,M]);const R=(F=d==null?void 0:d.metadata)==null?void 0:F.currentRun,E=new Set((R==null?void 0:R.currentEntityShas)||[]),C=new Set(l.jobs.flatMap(k=>k.entityShas||[])),_=new Set(((H=l.currentlyExecuting)==null?void 0:H.entityShas)||[]),$=a.filter(k=>k.entityType==="visual"||k.entityType==="library"),D=$.filter(k=>!E.has(k.sha)&&!C.has(k.sha)&&!_.has(k.sha)),z=()=>{if(D.length===0){m("All entities are already queued or analyzing","info",3e3);return}const k=D.map(B=>B.sha);b(!0),m(`Starting analysis for ${D.length} entities...`,"info",3e3),u.submit({entityShas:k.join(",")},{method:"post",action:"/api/analyze"})};re(()=>{if(u.state==="idle"&&u.data){const k=u.data;k.success?(console.log("[Analyze All] Success:",k.message),m(`Analysis started for ${k.entityCount} entities in ${k.fileCount} files. Watch the logs for progress.`,"success",6e3),b(!1)):k.error&&(console.error("[Analyze All] Error:",k.error),m(`Error: ${k.error}`,"error",8e3),b(!1))}},[u.state,u.data,m]);const W=(k,B)=>{console.log("Simulating entity:",k);const ne=o==null?void 0:o.find(V=>V.sha===k);y(k),S(),m(`Starting analysis for ${(ne==null?void 0:ne.name)||"entity"}...`,"info",3e3),u.submit({entitySha:k,filePath:B},{method:"post",action:"/api/analyze"})},K=k=>{f(B=>{const ne=new Set(B);return ne.has(k)?ne.delete(k):ne.add(k),ne})},Q=oe(()=>{const k=new Map;return s.forEach(B=>{const ne=B.entitySha;k.has(ne)||k.set(ne,[]),k.get(ne).push(B)}),Array.from(k.entries()).map(([B,ne])=>({entitySha:B,entityName:ne[0].entityName,scenarios:ne}))},[s]),te=[{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:"px-20 py-12",children:[c("header",{className:"mb-8 flex justify-between items-center",children:[c("div",{className:"flex items-center gap-2",children:[n("img",{src:Nm,alt:"CodeYam",className:"h-3.5"}),n("span",{className:"text-gray-400 text-sm",children:"|"}),c("h1",{className:"text-sm font-normal text-gray-600 m-0",children:["Overview of"," ",n("span",{className:"font-semibold",children:i?i.replace(/-/g," ").replace(/\b\w/g,k=>k.toUpperCase()):"Project"})]})]}),h.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:te.map((k,B)=>n(ce,{to:k.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 cursor-pointer",style:{borderLeft:`4px solid ${k.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:k.label}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 sm:hidden md:flex",style:{color:k.color},children:"View All →"})]}),c("div",{className:"flex flex-col gap-2",children:[c("div",{className:"flex items-center gap-3",children:[c("div",{className:"rounded-lg p-2 leading-none shrink-0",style:{backgroundColor:`${k.color}15`},children:[k.iconType==="folder"&&n(Po,{size:20,style:{color:k.color}}),k.iconType==="check"&&n(ir,{size:20,style:{color:k.color}}),k.iconType==="image"&&n(kt,{size:20,style:{color:k.color}}),k.iconType==="code-xml"&&n(ko,{size:20,style:{color:k.color}})]}),n("div",{className:"text-2xl font-bold text-gray-900 leading-none",children:k.value})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 md:hidden",style:{color:k.color},children:"View All →"})]})]})},B))}),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"})]}),$.length>0&&n("button",{onClick:z,disabled:u.state!=="idle"||v||D.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:k=>k.currentTarget.style.backgroundColor="#004560",onMouseLeave:k=>k.currentTarget.style.backgroundColor="#005C75",children:u.state!=="idle"||v?"Starting analysis...":D.length===0?"All Queued":"Analyze All"})]}),r.length>0?n("div",{className:"flex flex-col gap-3",children:r.map(([k,B])=>{const ne=p.has(k),V=B.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:()=>K(k),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:ne?"▼":"▶"}),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:k}),c("span",{className:"text-xs text-gray-500",children:[V.length," entit",V.length!==1?"ies":"y"]})]})]})}),ne&&n("div",{className:"border-t border-gray-200 bg-gray-50 p-3 flex flex-col gap-2",children:V.length>0?V.map(L=>{const U=E.has(L.sha),G=C.has(L.sha)||_.has(L.sha);return c(ce,{to:`/entity/${L.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:O=>O.currentTarget.style.borderColor="#005C75",onMouseLeave:O=>O.currentTarget.style.borderColor="inherit",children:[c("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center",style:{backgroundColor:L.entityType==="visual"?"#8B5CF615":L.entityType==="library"?"#6366F1":"#EC4899"},children:[L.entityType==="visual"&&n(kt,{size:16,style:{color:"#8B5CF6"}}),L.entityType==="library"&&n(Ra,{size:16,className:"text-white"}),L.entityType==="other"&&n(Mo,{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:L.name}),L.entityType==="visual"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#8B5CF60D",color:"#8B5CF6"},children:"Visual"}),L.entityType==="library"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#0DBFE90D",color:"#0DBFE9"},children:"Library"}),L.entityType==="other"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#EC48990D",color:"#EC4899"},children:"Other"})]}),L.description&&n("div",{className:"text-sm text-gray-500 mt-1 overflow-hidden text-ellipsis whitespace-nowrap",children:L.description})]}),c("div",{className:"flex items-center gap-2 shrink-0",children:[U&&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(nt,{size:14,className:"animate-spin"}),"Analyzing..."]}),!U&&G&&n("div",{className:"px-2 py-1 bg-purple-50 border border-purple-300 rounded text-xs text-purple-700 font-semibold",children:"⏳ Queued"}),!U&&!G&&n("button",{onClick:O=>{O.preventDefault(),O.stopPropagation(),m(`Starting analysis for ${L.name}...`,"info",3e3),u.submit({entityShas:L.sha},{method:"post",action:"/api/analyze"})},disabled:u.state!=="idle",className:"px-3 py-1.5 text-white border-none rounded text-xs font-medium cursor-pointer transition-all disabled:bg-gray-400 disabled:cursor-not-allowed",style:{backgroundColor:"#005C75"},onMouseEnter:O=>O.currentTarget.style.backgroundColor="#004560",onMouseLeave:O=>O.currentTarget.style.backgroundColor="#005C75",children:"Analyze"})]})]},L.sha)}):n("div",{className:"text-sm text-gray-500 italic p-2",children:"No entity changes detected in this file"})})]},k)})}):c("div",{className:"py-12 px-6 text-center flex flex-col items-center bg-gray-50 rounded-lg min-h-50 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(ue,{children:[n("div",{className:"space-y-6 mb-5",children:Q.map(k=>c("div",{children:[c("div",{className:"mb-3 flex items-center gap-2",children:[n("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center bg-purple-100",children:n(kt,{size:16,style:{color:"#8B5CF6"}})}),n(ce,{to:`/entity/${k.entitySha}`,className:"text-sm font-semibold text-gray-900 no-underline hover:text-gray-700 transition-colors",children:k.entityName})]}),n("div",{className:"grid grid-cols-4 gap-3",children:k.scenarios.map((B,ne)=>n(ce,{to:B.scenarioId?`/entity/${B.entitySha}/scenarios/${B.scenarioId}`:`/entity/${B.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:V=>{V.currentTarget.style.borderColor="#005C75",V.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.2)"},onMouseLeave:V=>{V.currentTarget.style.borderColor="#E5E7EB",V.currentTarget.style.boxShadow="none"},title:`${B.scenarioName}`,children:n(Le,{screenshotPath:B.screenshotPath,alt:B.scenarioName,className:"max-w-full max-h-full object-contain object-center"})},ne))})]},k.entitySha))}),n(ce,{to:"/simulations",className:"block text-center p-3 rounded-lg no-underline font-semibold text-sm transition-all",style:{color:"#005C75",backgroundColor:"#F6F9FC"},onMouseEnter:k=>k.currentTarget.style.backgroundColor="#EEF4F8",onMouseLeave:k=>k.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:[A&&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 ",A.name]}),n("div",{className:"text-[13px] text-gray-500 font-mono overflow-hidden text-ellipsis whitespace-nowrap",children:A.filePath})]})]})}),M?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 (",P.length," scenario",P.length!==1?"s":"",")"]})]}):N?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(nt,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-mono text-xs",title:N,children:N}),i&&n("button",{onClick:()=>x(!0),className:"px-2 py-1.5 bg-gray-500 text-white border-none rounded-md text-[13px] font-medium cursor-pointer transition-all whitespace-nowrap self-start hover:bg-gray-600 hover:-translate-y-px",title:"View analysis logs",children:"📋 Logs"})]}):u.state!=="idle"?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(nt,{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(nt,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Starting analysis..."})]}),P.length>0&&n("div",{className:"flex gap-2 flex-wrap p-4 bg-white border-t border-gray-200",children:P.slice(0,8).map((k,B)=>{var G,O;const ne=(O=(G=k.metadata)==null?void 0:G.screenshotPaths)==null?void 0:O[0],V=I.find(Z=>Z.name===k.name),L=(V==null?void 0:V.screenshotStartedAt)&&!(V!=null&&V.screenshotFinishedAt);return ne?n(ce,{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(Le,{screenshotPath:ne,alt:k.name,title:k.name,className:"max-w-full max-h-full object-contain object-center"})},B):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 ${k.name}...`,children:n("span",{className:L?"animate-pulse":"text-gray-400",children:L?"⋯":"⏹️"})},B)})})]}):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-50",children:[n("div",{className:"mb-4 bg-[#efefef] rounded-lg p-3",children:n(kt,{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==null?void 0:o.length)??0)>0?n(ue,{children:n("div",{className:"flex flex-col gap-3 mt-6 w-full",children:(g&&A?[A]:o||[]).map(k=>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:B=>{B.currentTarget.style.backgroundColor="#F9FAFB"},onMouseLeave:B=>{B.currentTarget.style.backgroundColor="white"},children:[c(ce,{to:`/entity/${k.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(kt,{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:k.name}),n("div",{className:"text-xs text-gray-500 font-mono overflow-hidden text-ellipsis whitespace-nowrap",children:k.filePath})]})]}),n("button",{onClick:()=>W(k.sha,k.filePath||""),disabled:u.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:B=>B.currentTarget.style.backgroundColor="#004560",onMouseLeave:B=>B.currentTarget.style.backgroundColor="#005C75",title:g?"Please wait for current analysis to complete":"Analyze this entity",children:"Analyze"})]})},k.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"})]})]})]}),w&&i&&n($t,{projectSlug:i,onClose:()=>x(!1)})]})})}),_m=Object.freeze(Object.defineProperty({__proto__:null,default:Em,loader:Am,meta:Sm},Symbol.toStringTag,{value:"Module"}));function qn(e){return`${e.filePath||""}::${e.name}`}function Os(e,t){const r=_e(),{showToast:a}=pr(),[s,o]=j(new Map);re(()=>{if(r.state==="idle"&&r.data){const p=r.data;p!=null&&p.error&&a(`Error: ${p.error}`,"error",6e3)}},[r.state,r.data,a]),re(()=>{var f;if(s.size===0)return;const p=new Set;(f=t==null?void 0:t.jobs)==null||f.forEach(g=>{var y;(y=g.entityShas)==null||y.forEach(w=>{s.forEach((x,v)=>{x===w&&p.add(v)})})}),e==null||e.forEach(g=>{s.forEach((y,w)=>{y===g&&p.add(w)})}),p.size>0&&o(g=>{const y=new Map(g);return p.forEach(w=>y.delete(w)),y})},[t,e,s]);const i=ae(p=>{console.log("Generate analysis clicked for entity:",p.sha,p.name);const f=qn(p);o(y=>new Map(y).set(f,p.sha));const g=new FormData;g.append("entitySha",p.sha),g.append("filePath",p.filePath||""),r.submit(g,{method:"post",action:"/api/analyze"})},[r]),l=ae(p=>{const f=p.filter(w=>w.entityType==="visual"||w.entityType==="library");console.log("Generate analysis for all entities:",f.length),o(w=>{const x=new Map(w);return f.forEach(v=>x.set(qn(v),v.sha)),x});const g=f.map(w=>w.sha).join(","),y=new FormData;y.append("entityShas",g),r.submit(y,{method:"post",action:"/api/analyze"})},[r]),d=ae(p=>(e==null?void 0:e.includes(p))??!1,[e]),u=ae(p=>{const f=qn(p);return s.has(f)},[s]),h=ae(p=>{var f;return((f=t==null?void 0:t.jobs)==null?void 0:f.some(g=>{var y;return(y=g.entityShas)==null?void 0:y.includes(p)}))??!1},[t]),m=oe(()=>Array.from(s.keys()),[s]);return{isAnalyzing:r.state!=="idle",handleGenerateSimulation:i,handleGenerateAllSimulations:l,isEntityBeingAnalyzed:d,isEntityPending:u,isEntityInQueue:h,pendingEntityKeys:m}}function Mr({showActions:e=!1,sortOrder:t="desc",onSortChange:r,onAnalyzeAll:a,analyzeAllDisabled:s=!1,analyzeAllText:o="Analyze All"}){return n("div",{className:"bg-[#efefef] rounded-lg mb-2 text-[11px] font-normal leading-[16px] text-[#3e3e3e] uppercase",children:c("div",{className:"flex justify-between items-center px-3 py-2",children:[c("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4"}),n("span",{children:"FILE"})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:n("span",{children:"UNCOMMITTED"})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:n("span",{children:"SIMULATIONS"})}),c("div",{className:"flex gap-4 items-center",children:[n("span",{className:"text-center",style:{width:"70px"},children:"ENTITIES"}),c("div",{className:"flex items-center justify-center gap-1 cursor-pointer hover:text-[#232323] transition-colors",style:{width:"116px"},onClick:r,role:"button",tabIndex:0,onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),r==null||r())},children:[n("span",{children:"MODIFIED"}),n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{transform:t==="asc"?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease"},children:n("path",{d:"M3 5L6 8L9 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),e&&n("div",{className:"text-center",style:{width:"127px"},children:a&&n("button",{onClick:a,disabled:s,className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-medium hover:bg-[#004a5e] transition-colors cursor-pointer disabled:bg-gray-400 disabled:cursor-not-allowed whitespace-nowrap px-3 py-1.5 normal-case",title:s?o:"Analyze all entities",children:o})})]})]})]})})}function Pm({status:e,variant:t="compact"}){const r={modified:{label:"M",bgColor:"bg-[#f59e0c]"},added:{label:"A",bgColor:"bg-emerald-500"},deleted:{label:"D",bgColor:"bg-red-500",showWarning:!0},renamed:{label:"R",bgColor:"bg-indigo-500"},untracked:{label:"U",bgColor:"bg-purple-500"}},a={modified:{label:"MODIFIED",textColor:"#BB6BD9"},added:{label:"ADDED",textColor:"#F2994A"},deleted:{label:"DELETED",textColor:"#EF4444"},renamed:{label:"RENAMED",textColor:"#3B82F6"},untracked:{label:"UNTRACKED",textColor:"#6B7280"}};if(t==="full"){const o=a[e]||{label:"UNKNOWN",textColor:"#6B7280"};return n("div",{className:"bg-[#f9f9f9] inline-flex items-center justify-center px-[5px] py-0 rounded",style:{height:"22px"},children:n("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-medium leading-[22px]",style:{color:o.textColor},children:o.label})})}const s=r[e]||{label:"?",bgColor:"bg-gray-500"};return c("div",{className:"inline-flex items-center gap-1",children:[n("span",{className:`inline-flex items-center justify-center w-5 h-5 text-[11px] font-bold text-white rounded ${s.bgColor}`,title:e,children:s.label}),s.showWarning&&n("span",{className:"inline-flex items-center justify-center w-3 h-3 text-[10px] text-amber-600",title:"Warning: File will be deleted",children:"⚠"})]})}function Tr({filePath:e,isExpanded:t,onToggle:r,fileStatus:a,simulationPreviews:s,entityCount:o,state:i,lastModified:l,actionButton:d,uncommittedCount:u,children:h,isNotAnalyzable:m=!1,isUncommitted:p=!1}){return c("div",{className:"bg-white overflow-hidden",style:t?{border:"1px solid #e1e1e1",borderLeft:"4px solid #306AFF",borderRadius:"8px"}:{borderBottom:"1px solid #e1e1e1"},children:[c("div",{className:`flex justify-between items-center p-3 cursor-pointer select-none transition-colors ${m?"opacity-50":"hover:bg-gray-200"}`,style:{outlineColor:"#005C75"},onClick:r,role:"button",tabIndex:0,onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),r())},children:[c("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:t?"rotate(90deg)":"none"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:t?"#3e3e3e":"#c7c7c7"})})}),n("img",{src:"/icons/file-icon.svg",alt:"file",className:"w-4 h-5 shrink-0"}),n(Wa,{filePath:e}),a&&n(Pm,{status:typeof a=="string"?a:a.status,variant:"full"})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:(p||i==="out-of-date")&&c("div",{className:"flex gap-1.5 items-center",children:[p&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fff3cd",color:"#856404",height:"22px"},children:"Uncommitted"}),i==="out-of-date"&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:s}),c("div",{className:"flex gap-4 items-center",children:[n("div",{className:"flex items-center justify-center",style:{width:"70px"},children:n("div",{className:"bg-[#f9f9f9] flex items-center justify-center px-2 rounded whitespace-nowrap",style:{height:"26px"},children:c("span",{className:"text-[13px] text-[#3e3e3e]",children:[o," ",o===1?"entity":"entities"]})})}),n("div",{className:"text-[12px] text-gray-600 text-center",style:{width:"116px"},children:Rs(l)}),n("div",{style:{width:"127px"},className:"flex justify-center",children:d})]})]})]}),t&&h&&n("div",{className:"bg-gray-50 py-2 rounded-bl-[4px] rounded-br-[4px] flex flex-col gap-1",children:h})]})}function Ir({entities:e,maxPreviews:t=3}){var a,s,o,i,l;const r=[];for(const d of e){if(r.length>=t)break;const u=((s=(a=d.analyses)==null?void 0:a[0])==null?void 0:s.scenarios)||[];if(d.entityType==="library"){const h=u.find(m=>{var p,f;return((p=m.metadata)==null?void 0:p.executionResult)||((f=m.metadata)==null?void 0:f.error)});h&&r.push({type:"library",scenario:h,entitySha:d.sha})}else if(d.entityType==="visual"){const h=u.find(m=>{var p,f;return(f=(p=m.metadata)==null?void 0:p.screenshotPaths)==null?void 0:f[0]});if(h){const m=(i=(o=h.metadata)==null?void 0:o.screenshotPaths)==null?void 0:i[0],p=!!((l=h.metadata)!=null&&l.error);m&&r.push({type:"screenshot",screenshot:m,hasError:p,scenario:h,entitySha:d.sha})}}}return r.length===0?n("span",{className:"text-gray-400 font-light text-[14px]",children:"—"}):n(ue,{children:r.map((d,u)=>{if(d.type==="screenshot"&&d.screenshot){const h=d.hasError?"border-red-400":"border-gray-200";return c(ce,{to:d.scenario?`/entity/${d.entitySha}/scenarios/${d.scenario.id}`:`/entity/${d.entitySha}`,className:`relative w-[50px] h-[38px] border ${h} rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,onClick:m=>m.stopPropagation(),children:[n(Le,{screenshotPath:d.screenshot,alt:`Preview ${u+1}`,className:"max-w-full max-h-full object-contain object-center"}),d.hasError&&n("div",{className:"absolute top-0 right-0 w-4 h-4 bg-red-500 text-white flex items-center justify-center text-[10px] rounded-bl",title:"Error during capture",children:n(Kn,{size:12,color:"white"})})]},`screenshot-${u}`)}return d.type==="library"&&d.scenario&&d.entitySha?n(js,{scenario:d.scenario,entitySha:d.entitySha,size:"small",showBorder:!0},`library-${u}`):null})})}function jr({entity:e,isActivelyAnalyzing:t,isQueued:r,onGenerateSimulation:a}){var h,m;const s=t||r?[{entityShas:[e.sha]}]:[],o=Ve(e,s,t),i=e.entityType==="visual"||e.entityType==="library",l=i&&(o==="not-analyzed"||o==="out-of-date")&&!t&&!r,u=(((m=(h=e.analyses)==null?void 0:h[0])==null?void 0:m.scenarios)||[]).filter(p=>{var f,g;return(g=(f=p.metadata)==null?void 0:f.screenshotPaths)==null?void 0:g[0]});return c("div",{className:"bg-white rounded-lg",children:[c(ce,{to:`/entity/${e.sha}`,className:"flex items-center justify-between p-3 transition-colors hover:bg-gray-100 cursor-pointer",children:[c("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 shrink-0"}),e.entityType==="type"?n("div",{className:"bg-[#ffe1e1] inline-flex items-center justify-center px-[4px] rounded-[4px]",style:{height:"18px",width:"18px"},children:n("div",{className:"w-[10px] h-[10px] flex items-center justify-center",children:n(Be,{type:"type"})})}):n(Be,{type:e.entityType||"other"}),n("span",{className:`font-['IBM_Plex_Sans'] text-[14px] leading-[18px] text-black ${i?"font-medium":"font-normal"}`,children:e.name}),n(Ar,{type:e.entityType||"other"})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{style:{width:"160px"}}),c("div",{className:"flex gap-4 items-center",children:[n("div",{style:{width:"70px"}}),n("div",{style:{width:"116px"}}),n("div",{style:{width:"127px"},className:"flex justify-center items-center",children:i?o==="queued"?c("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#cbf3fa",color:"#3098b4",height:"26px"},children:[c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]}),"Queued"]}):o==="analyzing"?c("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[c("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):o==="up-to-date"?n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):o==="out-of-date"?n("button",{onClick:p=>{p.preventDefault(),p.stopPropagation(),a(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-medium hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):l&&n("button",{onClick:p=>{p.preventDefault(),p.stopPropagation(),a(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-medium hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Analyze"}):n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"})})]})]})]}),u.length>0&&n("div",{className:"px-3 pb-3 pt-0 flex items-center gap-2 pl-[52px]",children:u.map((p,f)=>{var y,w;const g=(w=(y=p.metadata)==null?void 0:y.screenshotPaths)==null?void 0:w[0];return g?n(ce,{to:`/entity/${e.sha}?scenario=${p.id}`,className:"relative w-[120px] h-[90px] border border-gray-200 rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center hover:border-gray-400 transition-colors",onClick:x=>x.stopPropagation(),children:n(Le,{screenshotPath:g,alt:p.name,className:"max-w-full max-h-full object-contain object-center"})},p.id):null})})]})}function km({entities:e,page:t,itemsPerPage:r=50,currentRun:a,filter:s,entityType:o,queueState:i,isEntityPending:l,pendingEntityKeys:d,onGenerateSimulation:u,onGenerateAllSimulations:h,totalFilesCount:m,totalEntitiesCount:p,uncommittedFilesCount:f,showOnlyUncommitted:g,onToggleUncommitted:y}){const[w,x]=Vt(),[v,b]=j(new Set),[N,T]=j(""),[S,A]=j(!1),[P,I]=j("all"),[M,R]=j("desc"),E=o||"all",C=oe(()=>{let F=e;return E!=="all"&&(F=F.filter(H=>H.entityType===E)),s==="analyzed"&&(F=F.filter(H=>H.analyses&&H.analyses.length>0)),F},[e,E,s]),_=oe(()=>{const F=new Map,H=new Map,k=new Map;C.forEach(L=>{var O,Z;const U=`${L.filePath}::${L.name}`,G=H.get(U);if(!G)H.set(U,L),k.set(U,[]);else{const le=((O=G.metadata)==null?void 0:O.editedAt)||G.createdAt||"",he=((Z=L.metadata)==null?void 0:Z.editedAt)||L.createdAt||"";let fe=!1;if(he>le)fe=!0;else if(he===le){const we=G.createdAt||"";fe=(L.createdAt||"")>we}fe?(k.get(U).push(G),H.set(U,L)):k.get(U).push(L)}}),H.forEach((L,U)=>{var O;if(!(L.analyses&&L.analyses.length>0)&&((O=L.metadata)!=null&&O.previousVersionWithAnalyses)){const le=(k.get(U)||[]).find(he=>{var fe;return he.sha===((fe=L.metadata)==null?void 0:fe.previousVersionWithAnalyses)});le&&le.analyses&&le.analyses.length>0&&(L.analyses=le.analyses)}}),Array.from(H.values()).sort((L,U)=>{var Z,le,he,fe;const G=!((Z=L.metadata)!=null&&Z.notExported)&&!((le=L.metadata)!=null&&le.namedExport),O=!((he=U.metadata)!=null&&he.notExported)&&!((fe=U.metadata)!=null&&fe.namedExport);return G&&!O?-1:!G&&O?1:0}).forEach(L=>{var le,he,fe,we,Pe;const U=L.filePath??"No File Path";F.has(U)||F.set(U,{filePath:U,entities:[],totalCount:0,uncommittedCount:0,lastUpdated:null,previewScreenshots:[],previewScreenshotErrors:[],previewLibraryScenarios:[],state:"up-to-date",simulationCount:0});const G=F.get(U);G.entities.push(L),G.totalCount++,(le=L.metadata)!=null&&le.isUncommitted&&G.uncommittedCount++;const O=((we=(fe=(he=L.analyses)==null?void 0:he[0])==null?void 0:fe.scenarios)==null?void 0:we.length)||0;G.simulationCount+=O;const Z=((Pe=L.metadata)==null?void 0:Pe.editedAt)||L.updatedAt;Z&&(!G.lastUpdated||new Date(Z)>new Date(G.lastUpdated))&&(G.lastUpdated=Z)});const B=(i==null?void 0:i.jobs)||[],ne=L=>{const U=`${L.filePath||""}::${L.name}`;return(d==null?void 0:d.includes(U))||!1};F.forEach(L=>{const U=L.entities.map(G=>ne(G)?"queued":Ve(G,B));U.includes("analyzing")||U.includes("queued")?L.state="analyzing":U.includes("incomplete")?L.state="incomplete":U.includes("out-of-date")?L.state="out-of-date":U.includes("not-analyzed")?L.state="not-analyzed":L.state="up-to-date"}),F.forEach(L=>{var U,G,O,Z,le;for(const he of L.entities){if(L.previewScreenshots.length+L.previewLibraryScenarios.length>=3)break;const we=((G=(U=he.analyses)==null?void 0:U[0])==null?void 0:G.scenarios)||[];if(he.entityType==="library"){const Pe=we.find(ke=>{var de,Ce;return((de=ke.metadata)==null?void 0:de.executionResult)||((Ce=ke.metadata)==null?void 0:Ce.error)});Pe&&L.previewLibraryScenarios.push({scenario:Pe,entitySha:he.sha})}else{const Pe=we.find(ke=>{var de,Ce;return(Ce=(de=ke.metadata)==null?void 0:de.screenshotPaths)==null?void 0:Ce[0]});if(Pe){const ke=(Z=(O=Pe.metadata)==null?void 0:O.screenshotPaths)==null?void 0:Z[0],de=!!((le=Pe.metadata)!=null&&le.error);ke&&!L.previewScreenshots.includes(ke)&&(L.previewScreenshots.push(ke),L.previewScreenshotErrors.push(de))}}}});const V=Array.from(F.values());return V.sort((L,U)=>{if(s==="analyzed"){const Z=Math.max(...L.entities.filter(he=>{var fe,we;return(we=(fe=he.analyses)==null?void 0:fe[0])==null?void 0:we.createdAt}).map(he=>new Date(he.analyses[0].createdAt).getTime()),0),le=Math.max(...U.entities.filter(he=>{var fe,we;return(we=(fe=he.analyses)==null?void 0:fe[0])==null?void 0:we.createdAt}).map(he=>new Date(he.analyses[0].createdAt).getTime()),0);return M==="desc"?le-Z:Z-le}if(L.uncommittedCount>0&&U.uncommittedCount===0)return-1;if(L.uncommittedCount===0&&U.uncommittedCount>0)return 1;const G=L.lastUpdated?new Date(L.lastUpdated).getTime():0,O=U.lastUpdated?new Date(U.lastUpdated).getTime():0;return M==="desc"?O-G:G-O}),V},[C,s,M,i,d]),$=oe(()=>{let F=_;if(P!=="all"&&(F=F.filter(H=>H.state===P)),N.trim()){const H=N.toLowerCase();F=F.filter(k=>k.filePath.toLowerCase().includes(H))}return F},[_,N,P]),D=(t-1)*r,z=D+r,W=$.slice(D,z),K=Math.ceil($.length/r),Q=F=>{b(H=>{const k=new Set(H);return k.has(F)?k.delete(F):k.add(F),k})},te=()=>{R(F=>F==="desc"?"asc":"desc")};return c("div",{children:[c("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),c("div",{className:"flex gap-3",children:[c("div",{className:"relative w-[130px]",children:[c("select",{value:E,onChange:F=>{const H=F.target.value,k=new URLSearchParams(w);H==="all"?k.delete("entityType"):k.set("entityType",H),k.set("page","1"),x(k)},className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:[n("option",{value:"all",children:"All Types"}),n("option",{value:"visual",children:"Visual"}),n("option",{value:"library",children:"Library"})]}),n(pn,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),c("div",{className:"relative w-[130px]",children:[c("select",{value:P,onChange:F=>I(F.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:[n("option",{value:"all",children:"All States"}),n("option",{value:"analyzing",children:"Analyzing..."}),n("option",{value:"up-to-date",children:"Up to date"}),n("option",{value:"incomplete",children:"Incomplete"}),n("option",{value:"out-of-date",children:"Out of date"}),n("option",{value:"not-analyzed",children:"Not analyzed"})]}),n(pn,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),c("div",{className:"flex-1 relative",children:[n(La,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",placeholder:"Search component",value:N,onChange:F=>T(F.target.value),className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})]})]}),m!==void 0&&p!==void 0&&f!==void 0&&n("div",{className:"mb-3",children:c("div",{className:"flex items-center justify-between text-[13px]",children:[c("div",{className:"flex items-center gap-3",children:[c("span",{className:"text-gray-900",children:[$.length," ",$.length===1?"file":"files"]}),n("span",{className:"text-gray-300",children:"|"}),c("div",{className:"flex items-center gap-1 group relative",children:[c("span",{className:"text-gray-900",children:[$.reduce((F,H)=>F+H.totalCount,0)," ",$.reduce((F,H)=>F+H.totalCount,0)===1?"entity":"entities"]}),c("svg",{className:"w-3.5 h-3.5 text-[#001f3f]",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[n("circle",{cx:"12",cy:"12",r:"10",strokeWidth:"2"}),n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 16v-4m0-4h.01"})]}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:c("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"text-gray-300",children:"|"}),g?c("button",{onClick:y,className:"flex items-center gap-2 font-medium text-[#005c75] underline hover:text-[#004a5e] transition-colors",children:[$.filter(F=>F.uncommittedCount>0).length," ","uncommitted"," ",$.filter(F=>F.uncommittedCount>0).length===1?"file":"files",n("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M6 18L18 6M6 6l12 12"})})]}):c("button",{onClick:y,className:"font-medium text-[#005c75] underline hover:text-[#004a5e] transition-colors",children:[f," uncommitted"," ",f===1?"file":"files"]})]}),W.length>0&&c("div",{className:"flex gap-6",children:[n("button",{onClick:()=>{b(new Set(W.map(F=>F.filePath))),A(!0)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-medium transition-all cursor-pointer px-3 py-1 rounded",children:"Expand All"}),n("button",{onClick:()=>{b(new Set),A(!1)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-medium transition-all cursor-pointer px-3 py-1 rounded",children:"Collapse All"})]})]})}),n(Mr,{showActions:!0,sortOrder:M,onSortChange:te}),n("div",{className:"flex flex-col gap-[3px]",children:W.map(F=>{const H=v.has(F.filePath),B=F.entities.filter(U=>(U.entityType==="visual"||U.entityType==="library")&&(Ve(U,(i==null?void 0:i.jobs)||[])==="not-analyzed"||Ve(U,(i==null?void 0:i.jobs)||[])==="out-of-date"||Ve(U,(i==null?void 0:i.jobs)||[])==="incomplete")).length>0,ne=U=>{var G;return((G=a==null?void 0:a.currentEntityShas)==null?void 0:G.includes(U))||!1},V=U=>{var G;return l!=null&&l(U)?!0:((G=i==null?void 0:i.jobs)==null?void 0:G.some(O=>{var Z;return(Z=O.entityShas)==null?void 0:Z.includes(U.sha)}))||!1},L=U=>{u==null||u(U)};return n(Tr,{filePath:F.filePath,isExpanded:H,onToggle:()=>Q(F.filePath),simulationPreviews:n(Ir,{entities:F.entities,maxPreviews:1}),entityCount:F.totalCount,state:F.state,lastModified:F.lastUpdated,uncommittedCount:F.uncommittedCount,isUncommitted:F.uncommittedCount>0,actionButton:B?n("button",{onClick:U=>{U.stopPropagation();const G=F.entities.filter(O=>(O.entityType==="visual"||O.entityType==="library")&&(Ve(O,(i==null?void 0:i.jobs)||[])==="not-analyzed"||Ve(O,(i==null?void 0:i.jobs)||[])==="out-of-date"||Ve(O,(i==null?void 0:i.jobs)||[])==="incomplete"));h==null||h(G)},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-medium hover:bg-[#004a5e] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Analyze"}):void 0,children:F.entities.sort((U,G)=>{const O=U.entityType==="visual"||U.entityType==="library",Z=G.entityType==="visual"||G.entityType==="library";return O&&!Z?-1:!O&&Z?1:0}).map(U=>n(jr,{entity:U,isActivelyAnalyzing:ne(U.sha),isQueued:V(U),onGenerateSimulation:L},U.sha))},F.filePath)})}),K>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(w),page:String(t-1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"← Previous"}),c("span",{children:["Page ",t," of ",K]}),t<K&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(w),page:String(t+1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"Next →"})]})]})}const Mm=()=>[{title:"CodeYam - Files & Entities"},{name:"description",content:"Browse your codebase files and entities"}];async function Tm({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,u]=await Promise.all([Kt(),Pt()]);return Y({entities:d,currentCommit:u,page:a,filter:s,entityType:o,queueState:l})}catch(r){return console.error("Failed to load entities:",r),Y({entities:[],currentCommit:null,page:1,filter:null,entityType:null,queueState:{paused:!1,jobs:[]},error:"Failed to load entities"})}}const Im=We(function(){var v,b,N;const{entities:t,currentCommit:r,page:a,filter:s,entityType:o,queueState:i}=Ge();lt();const[l,d]=Vt(),[u,h]=j(!1);Nt({source:"files-page"});const{handleGenerateSimulation:m,handleGenerateAllSimulations:p,isEntityPending:f,pendingEntityKeys:g}=Os((b=(v=r==null?void 0:r.metadata)==null?void 0:v.currentRun)==null?void 0:b.currentEntityShas,i),y=oe(()=>{if(!t)return[];const T=new Set([]);for(const S of t)T.add(S.filePath??"No File Path");return Array.from(T)},[t]),w=oe(()=>{if(!t)return[];let T=t;return u&&(T=T.filter(S=>{var A;return(A=S.metadata)==null?void 0:A.isUncommitted})),T.sort((S,A)=>{var P,I,M,R,E,C;return(P=S.metadata)!=null&&P.isUncommitted&&!((I=A.metadata)!=null&&I.isUncommitted)?-1:!((M=S.metadata)!=null&&M.isUncommitted)&&((R=A.metadata)!=null&&R.isUncommitted)?1:new Date(((E=A.metadata)==null?void 0:E.editedAt)||0).getTime()-new Date(((C=S.metadata)==null?void 0:C.editedAt)||0).getTime()})},[t,u]),x=oe(()=>{var S;if(!t)return[];const T=new Set([]);for(const A of t)(S=A.metadata)!=null&&S.isUncommitted&&T.add(A.filePath??"No File Path");return Array.from(T)},[t]);return t?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-20 py-12 font-sans",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-3xl font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-gray-600",children:"This is a list of all the files in your app."})]}),n(km,{entities:w,page:a,itemsPerPage:50,currentRun:(N=r==null?void 0:r.metadata)==null?void 0:N.currentRun,filter:s,entityType:o,queueState:i,isEntityPending:f,pendingEntityKeys:g,onGenerateSimulation:m,onGenerateAllSimulations:p,totalFilesCount:y.length,totalEntitiesCount:t.length,uncommittedFilesCount:x.length,showOnlyUncommitted:u,onToggleUncommitted:()=>h(!u)})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-3xl font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:"Unable to retrieve entities"})]})})}),jm=Object.freeze(Object.defineProperty({__proto__:null,default:Im,loader:Tm,meta:Mm},Symbol.toStringTag,{value:"Module"}));function $m(e,t,r){const[a,s]=j(()=>new Set),[o,i]=j(()=>new Set),l=Ee([]),d=Ee([]);return re(()=>{(t.length!==l.current.length||t.some((y,w)=>y!==l.current[w]))&&(l.current=t,s(y=>{const w=new Set;return t.forEach(x=>{y.has(x)&&w.add(x)}),w}))},[t]),re(()=>{(r.length!==d.current.length||r.some((y,w)=>y!==d.current[w]))&&(d.current=r,i(y=>{const w=new Set;return r.forEach(x=>{y.has(x)&&w.add(x)}),w}))},[r]),{expandedUncommitted:a,expandedBranch:o,setExpandedUncommitted:s,setExpandedBranch:i,toggleFile:(g,y,w)=>{w(x=>{const v=new Set(x);return v.has(g)?v.delete(g):v.add(g),v})},expandAllUncommitted:()=>{s(new Set(t))},collapseAllUncommitted:()=>{s(new Set)},expandAllBranch:()=>{i(new Set(r))},collapseAllBranch:()=>{i(new Set)}}}function Rm(e,t,r){const[a,s]=j(null),[o,i]=j(null),l=_e();re(()=>{var m,p;((m=l.data)==null?void 0:m.oldContent)!==void 0&&((p=l.data)==null?void 0:p.newContent)!==void 0&&i({oldContent:l.data.oldContent,newContent:l.data.newContent,fileName:l.data.fileName})},[l.data]);const d=m=>{s({type:"file",path:m}),i(null);const p=new FormData;p.append("actionType","getDiff"),p.append("filePath",m),p.append("diffType","branch"),p.append("baseBranch",e),p.append("currentBranch",t||""),l.submit(p,{method:"post"})},u=(m,p)=>{s({type:"entity",path:m,entitySha:p}),i(null);const f=new FormData;f.append("actionType","getDiff"),f.append("filePath",m),f.append("diffType","branch"),f.append("baseBranch",e),f.append("currentBranch",t||""),f.append("entitySha",p),l.submit(f,{method:"post"})},h=()=>{s(null),i(null)};return{diffView:a,diffContent:o,isLoading:l.state==="loading"||l.state==="submitting",handleShowFileDiff:d,handleShowEntityDiff:u,handleCloseDiff:h}}function Dm({diffView:e,diffContent:t,isLoading:r,entities:a,onClose:s}){var u;const[o,i]=j(!1),[l,d]=j(!1);return re(()=>{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:"," ",((u=a.find(h=>h.sha===e.entitySha))==null?void 0:u.name)||e.entitySha]})]}),c("div",{className:"flex items-center gap-3",children:[n("button",{onClick:()=>i(!o),className:"px-3 py-1.5 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] text-sm font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",title:o?"Show changes only":"Show full file",children:o?"Show Changes Only":"Show Full File"}),n("button",{onClick:s,className:"text-[#8e8e8e] hover:text-[#626262] transition-colors cursor-pointer",children:n("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]}),n("div",{className:"flex-1 overflow-auto",children:r?n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"Loading diff..."})}):t?n("div",{className:"diff-viewer-wrapper",children:l&&n(ri,{oldValue:t.oldContent,newValue:t.newContent,splitView:!0,useDarkTheme:!1,showDiffOnly:!o,extraLinesSurroundingDiff:4,styles:{variables:{light:{diffViewerBackground:"#fff",diffViewerColor:"#212529",addedBackground:"#e6ffed",addedColor:"#24292e",removedBackground:"#ffeef0",removedColor:"#24292e",wordAddedBackground:"#acf2bd",wordRemovedBackground:"#fdb8c0",addedGutterBackground:"#cdffd8",removedGutterBackground:"#ffdce0",gutterBackground:"#f6f8fa",gutterBackgroundDark:"#f3f4f6",highlightBackground:"#fffbdd",highlightGutterBackground:"#fff5b1"}},contentText:{fontSize:"12px",lineHeight:"1.5"},line:{padding:"2px 10px",fontSize:"12px","&:hover":{background:"#f8f9fa"}},splitView:{display:"flex",width:"100%"},diffContainer:{width:"50%",overflowX:"auto"}}})}):n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"No diff available"})})}),n("div",{className:"p-6 border-t border-[#e1e1e1] flex justify-end gap-3",children:n("button",{onClick:s,className:"px-4 py-2 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",children:"Close"})})]})})}function Lm({files:e,currentBranch:t,defaultBranch:r,baseBranch:a,allBranches:s,expandedFiles:o,isEntityBeingAnalyzed:i,isEntityQueued:l,sortOrder:d,onToggleFile:u,onBranchChange:h,onGenerateSimulation:m,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}){const w=e.flatMap(([b,{entities:N}])=>{const T=N.filter(S=>i(S.sha)||l(S)).map(S=>S.sha);return T.length>0?[{entityShas:T}]:[]}),x=b=>{const N=b.map(T=>Ve(T,w));return N.includes("analyzing")||N.includes("queued")?"analyzing":N.includes("out-of-date")?"out-of-date":N.includes("not-analyzed")?"not-analyzed":"up-to-date"},v=oe(()=>[...e].sort((b,N)=>{const T=b[1].entities.reduce((I,M)=>{var E;const R=((E=M.metadata)==null?void 0:E.editedAt)||M.updatedAt;return R?I?new Date(R)>new Date(I)?R:I:R:I},null),S=N[1].entities.reduce((I,M)=>{var E;const R=((E=M.metadata)==null?void 0:E.editedAt)||M.updatedAt;return R?I?new Date(R)>new Date(I)?R:I:R:I},null);if(!T&&!S)return 0;if(!T)return 1;if(!S)return-1;const A=new Date(T).getTime(),P=new Date(S).getTime();return d==="desc"?P-A:A-P}),[e,d]);return n("div",{children:e.length>0?c("div",{children:[n(Mr,{showActions:!0,sortOrder:d,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}),n("div",{className:"flex flex-col gap-[3px]",children:v.map(([b,{status:N,entities:T,isUncommitted:S}])=>{const A=o.has(b),P=x(T),I=T.reduce((C,_)=>{var D;const $=((D=_.metadata)==null?void 0:D.editedAt)||_.updatedAt;return $?C?new Date($)>new Date(C)?$:C:$:C},null),R=T.filter(C=>C.entityType==="visual"||C.entityType==="library").length===0;let E;return R?E=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):P==="analyzing"?E=c("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[c("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):P==="up-to-date"?E=n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):P==="out-of-date"?E=n("button",{onClick:C=>{C.stopPropagation(),T.filter(_=>(_.entityType==="visual"||_.entityType==="library")&&!i(_.sha)&&!l(_)).forEach(_=>m(_))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-medium hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):P==="not-analyzed"&&(E=n("button",{onClick:C=>{C.stopPropagation(),T.filter(_=>(_.entityType==="visual"||_.entityType==="library")&&!i(_.sha)&&!l(_)).forEach(_=>m(_))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-medium hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(Tr,{filePath:b,isExpanded:A,onToggle:()=>u(b),fileStatus:N,isUncommitted:S,simulationPreviews:n(Ir,{entities:T,maxPreviews:1}),entityCount:T.length,state:P,lastModified:I,isNotAnalyzable:R,actionButton:E,children:T.sort((C,_)=>{const $=C.entityType==="visual"||C.entityType==="library",D=_.entityType==="visual"||_.entityType==="library";return $&&!D?-1:!$&&D?1:0}).map(C=>n(jr,{entity:C,isActivelyAnalyzing:i(C.sha),isQueued:l(C),onGenerateSimulation:m},C.sha))},b)})})]}):c("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"No files have been modified in this branch."})]})})}function Om({files:e,entityImpactMap:t,expandedFiles:r,isEntityBeingAnalyzed:a,isEntityQueued:s,projectSlug:o,baseBranch:i,currentBranch:l,sortOrder:d,onToggleFile:u,onShowFileDiff:h,onGenerateSimulation:m,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}){const w=oe(()=>{const b=[];return e.forEach(([N,{editedEntities:T}])=>{const S=T.filter(A=>a(A.sha)||s(A)).map(A=>A.sha);S.length>0&&b.push({entityShas:S})}),b},[e,a,s]),x=oe(()=>{const b=new Map;return e.forEach(([N,{editedEntities:T}])=>{const S=T.map(M=>Ve(M,w));let A;S.includes("analyzing")||S.includes("queued")?A="analyzing":S.includes("out-of-date")?A="out-of-date":S.includes("not-analyzed")?A="not-analyzed":A="up-to-date";const P=T.reduce((M,R)=>{var C;const E=((C=R.metadata)==null?void 0:C.editedAt)||R.updatedAt;return E&&(!M||new Date(E)>new Date(M))?E:M},null),I=T.filter(M=>M.entityType==="visual"||M.entityType==="library").length;b.set(N,{state:A,lastModified:P,analyzableCount:I})}),b},[e,w]),v=oe(()=>[...e].sort((b,N)=>{const T=x.get(b[0]),S=x.get(N[0]),A=T==null?void 0:T.lastModified,P=S==null?void 0:S.lastModified;if(!A&&!P)return 0;if(!A)return 1;if(!P)return-1;const I=new Date(A).getTime(),M=new Date(P).getTime();return d==="desc"?M-I:I-M}),[e,x,d]);return e.length===0?c("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Uncommitted Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"If you edit a file in your project, it will show up here."})]}):c("div",{children:[n(Mr,{showActions:!0,sortOrder:d,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}),n("div",{className:"flex flex-col gap-[3px]",children:v.map(([b,{status:N,editedEntities:T}])=>{const S=r.has(b),A=x.get(b),{state:P,lastModified:I,analyzableCount:M}=A,R=M===0;let E;return R?E=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):P==="analyzing"?E=c("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[c("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):P==="up-to-date"?E=n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):P==="out-of-date"?E=n("button",{onClick:C=>{C.stopPropagation(),T.filter(_=>(_.entityType==="visual"||_.entityType==="library")&&!a(_.sha)&&!s(_)).forEach(_=>m(_))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-medium hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):P==="not-analyzed"&&(E=n("button",{onClick:C=>{C.stopPropagation(),T.filter(_=>(_.entityType==="visual"||_.entityType==="library")&&!a(_.sha)&&!s(_)).forEach(_=>m(_))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-medium hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(Tr,{filePath:b,isExpanded:S,onToggle:()=>u(b),fileStatus:N,simulationPreviews:n(Ir,{entities:T,maxPreviews:1}),entityCount:T.length,state:P,lastModified:I,isNotAnalyzable:R,isUncommitted:!0,actionButton:E,children:T.sort((C,_)=>{const $=C.entityType==="visual"||C.entityType==="library",D=_.entityType==="visual"||_.entityType==="library";return $&&!D?-1:!$&&D?1:0}).map(C=>n(jr,{entity:C,isActivelyAnalyzing:a(C.sha),isQueued:s(C),onGenerateSimulation:m},C.sha))},b)})})]})}function Fm({activeTab:e,onTabChange:t,uncommittedCount:r,branchCount:a}){return n("div",{className:"border-b border-gray-200",children:c("nav",{className:"flex gap-8 items-center",children:[c("button",{onClick:()=>t("branch"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="branch"?"text-[#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-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:a})]}),e==="branch"&&n("span",{className:"absolute bottom-[-1px] left-0 right-0 h-[2px] bg-[#005C75]"})]}),c("button",{onClick:()=>t("uncommitted"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="uncommitted"?"text-[#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-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:r})]}),e==="uncommitted"&&n("span",{className:"absolute bottom-[-1px] left-0 right-0 h-[2px] bg-[#005C75]"})]})]})})}const Ym=()=>[{title:"Git - CodeYam"},{name:"description",content:"Git status and impact analysis"}];async function zm({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=un(a,o,i):d=du(a),Y({...d,entitySha:l})}return Y({error:"Unknown action"},{status:400})}async function Bm({request:e,context:t}){try{const r=new URL(e.url),a=r.searchParams.get("compare"),s=r.searchParams.get("viewBranch"),o=t.analysisQueue,i=o?o.getState():{paused:!1,jobs:[]},[l,d,u]=await Promise.all([Kt(),Pt(),Fe()]),h=Ps(),m=su(),p=ou(),f=iu(),g=s||m,y=a||p;let w=[];return g&&g!==y&&(w=ks(y,g)),Y({entities:l||[],gitStatus:h,currentBranch:g,actualCurrentBranch:m,defaultBranch:p,allBranches:f,baseBranch:y,branchDiff:w,currentCommit:d,projectSlug:u,queueState:i})}catch(r){return console.error("Failed to load git data:",r),Y({entities:[],gitStatus:[],currentBranch:null,actualCurrentBranch:null,defaultBranch:"main",allBranches:[],baseBranch:"main",branchDiff:[],currentCommit:null,projectSlug:null,queueState:{paused:!1,jobs:[]},error:"Failed to load git data"})}}const Um=We(function(){var st,Lt;const{entities:t,gitStatus:r,currentBranch:a,actualCurrentBranch:s,defaultBranch:o,allBranches:i,baseBranch:l,branchDiff:d,currentCommit:u,projectSlug:h,queueState:m}=Ge();Nt({source:"git-page"});const[p,f]=Vt(),[g,y]=j(null),[w,x]=j("desc"),[v,b]=j("branch"),N=p.get("expanded")==="true",T=()=>{x(ie=>ie==="desc"?"asc":"desc")},S=_e(),A=S.data;re(()=>{a&&l&&a!==l&&S.state==="idle"&&!A&&S.load(`/api/branch-entity-diff?base=${encodeURIComponent(l)}&compare=${encodeURIComponent(a)}`)},[a,l,S,A]);const P=oe(()=>{const ie=Ds(r,t);return Array.from(ie.entries()).sort(($e,Ye)=>$e[0].localeCompare(Ye[0]))},[r,t]),I=oe(()=>{const ie=wm(d,t,A);return Array.from(ie.entries()).sort(($e,Ye)=>$e[0].localeCompare(Ye[0]))},[d,t,A]),M=oe(()=>Cm(r,t),[r,t]),R=oe(()=>v==="uncommitted"?P:I,[v,P,I]),E=oe(()=>R.map(([ie])=>ie),[R]),{expandedUncommitted:C,setExpandedUncommitted:_,toggleFile:$,expandAllUncommitted:D,collapseAllUncommitted:z}=$m(N,E,[]),{diffView:W,diffContent:K,isLoading:Q,handleShowFileDiff:te,handleCloseDiff:F}=Rm(l,a),H=(st=u==null?void 0:u.metadata)==null?void 0:st.currentRun,k=new Set((H==null?void 0:H.currentEntityShas)||[]),B=new Set(m.jobs.flatMap(ie=>ie.entityShas||[])),ne=new Set(((Lt=m.currentlyExecuting)==null?void 0:Lt.entityShas)||[]),{isAnalyzing:V,handleGenerateSimulation:L,handleGenerateAllSimulations:U,isEntityBeingAnalyzed:G,isEntityPending:O}=Os(H==null?void 0:H.currentEntityShas,m),Z=ie=>O(ie)||B.has(ie.sha)||ne.has(ie.sha),le=ie=>{ie===(s||a)?p.delete("viewBranch"):p.set("viewBranch",ie),f(p)},he=ie=>{ie===o?p.delete("compare"):p.set("compare",ie),f(p)},fe=()=>{const $e=R.flatMap(([Ye,Zt])=>Zt.editedEntities||Zt.entities||[]).filter(Ye=>!k.has(Ye.sha)&&!B.has(Ye.sha)&&!ne.has(Ye.sha)&&!O(Ye));U($e)},we=P.length,Pe=I.length,ke=R.flatMap(([ie,$e])=>$e.editedEntities||$e.entities||[]),de=ke.filter(ie=>ie.entityType==="visual"||ie.entityType==="library"),Ce=de.length>0&&de.every(ie=>k.has(ie.sha)),je=de.length>0&&!Ce&&de.every(ie=>B.has(ie.sha)||ne.has(ie.sha)),Ne=V||Ce||je,ut=Ce?"Analyzing...":je?"Queued...":V?"Analyzing...":"Analyze All";return n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-20 py-12",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-3xl font-semibold text-gray-900 mb-2",children:"Git Changes"}),c("p",{className:"text-gray-600",children:["This is a list of all the files that are affected by your local changes. ",n("strong",{children:"Analyze a file to get simulations."})]})]}),n("div",{className:"mb-6",children:n(Fm,{activeTab:v,onTabChange:b,uncommittedCount:we,branchCount:Pe})}),a&&v==="branch"&&n("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:c("div",{className:"flex gap-6 items-center",children:[c("div",{className:"flex-shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Changes in Branch:"}),i.length>0?c("div",{className:"relative w-[200px]",children:[n("select",{value:a,onChange:ie=>le(ie.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:i.map(ie=>n("option",{value:ie,children:ie},ie))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}):n("span",{className:"text-gray-900 font-medium text-[12px]",children:a})]}),c("div",{className:"flex-shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Compared To:"}),c("div",{className:"relative w-[200px]",children:[n("select",{value:l,onChange:ie=>he(ie.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:i.filter(ie=>ie!==a).map(ie=>n("option",{value:ie,children:ie},ie))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]})]}),n("div",{className:"flex-1 mt-6",children:c("div",{className:"relative flex items-center",children:[n("svg",{className:"absolute left-3 w-4 h-4 text-gray-400 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})})]})}),n("div",{className:"mb-3",children:c("div",{className:"flex items-center justify-between text-[13px]",children:[c("div",{className:"flex items-center gap-3",children:[c("span",{className:"text-gray-900",children:[R.length," modified"," ",R.length===1?"file":"files"]}),n("span",{className:"text-gray-300",children:"|"}),c("div",{className:"flex items-center gap-1 group relative",children:[c("span",{className:"text-gray-900",children:[ke.length," ",ke.length===1?"entity":"entities"]}),c("svg",{className:"w-3.5 h-3.5 text-[#001f3f]",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[n("circle",{cx:"12",cy:"12",r:"10",strokeWidth:"2"}),n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 16v-4m0-4h.01"})]}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:c("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]})]}),R.length>0&&c("div",{className:"flex gap-6",children:[n("button",{onClick:D,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-medium transition-all cursor-pointer px-3 py-1 rounded",children:"Expand All"}),n("button",{onClick:z,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-medium transition-all cursor-pointer px-3 py-1 rounded",children:"Collapse All"})]})]})}),c("div",{className:"overflow-hidden",children:[v==="branch"&&a&&n(Lm,{files:I,currentBranch:a,defaultBranch:o,baseBranch:l,allBranches:i,expandedFiles:C,isEntityBeingAnalyzed:G,isEntityQueued:Z,sortOrder:w,onToggleFile:ie=>$(ie,C,_),onBranchChange:he,onGenerateSimulation:L,onSortChange:T,onAnalyzeAll:fe,analyzeAllDisabled:Ne,analyzeAllText:ut}),v==="uncommitted"&&n(Om,{files:P,entityImpactMap:M,expandedFiles:C,isEntityBeingAnalyzed:G,isEntityQueued:Z,projectSlug:h,baseBranch:l,currentBranch:a,sortOrder:w,onToggleFile:ie=>$(ie,C,_),onShowFileDiff:te,onGenerateSimulation:L,onSortChange:T,onAnalyzeAll:fe,analyzeAllDisabled:Ne,analyzeAllText:ut})]}),W&&n(Dm,{diffView:W,diffContent:K,isLoading:Q,entities:t,onClose:F}),g&&h&&n($t,{projectSlug:h,onClose:()=>y(null)})]})})}),Wm=Object.freeze(Object.defineProperty({__proto__:null,action:zm,default:Um,loader:Bm,meta:Ym},Symbol.toStringTag,{value:"Module"})),Ip={entry:{module:"/assets/entry.client-DKJyZfAY.js",imports:["/assets/chunk-JMJ3UQ3L-BambyYE_.js","/assets/index-CzNNiTkw.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-B_wIKCIf.js",imports:["/assets/chunk-JMJ3UQ3L-BambyYE_.js","/assets/index-CzNNiTkw.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-CKnwPCDr.js","/assets/ReportIssueModal-4lcOlid-.js","/assets/useReportContext-DsJbgMY9.js","/assets/loader-circle-CNp9QFCX.js","/assets/createLucideIcon-CgUsG7ib.js","/assets/useToast-DWHcCcl1.js","/assets/useLastLogLine-BqPPNjAl.js","/assets/LogViewer-wDPcZNKx.js","/assets/EntityTypeIcon-CXFKsCOD.js","/assets/TruncatedFilePath-6J7zDUD5.js","/assets/chevron-down-BYimnrHg.js","/assets/circle-check-CaVsIRxt.js","/assets/triangle-alert-CBc5dE1s.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.scenarios.$scenarioId.fullscreen":{id:"routes/entity.$sha.scenarios.$scenarioId.fullscreen",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/fullscreen",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha.scenarios._scenarioId.fullscreen-DyB90fWk.js",imports:["/assets/chunk-JMJ3UQ3L-BambyYE_.js","/assets/useInteractiveMode-Dk_FQqWJ.js","/assets/useLastLogLine-BqPPNjAl.js","/assets/useCustomSizes-BMIGFP-m.js","/assets/cy-logo-cli-CKnwPCDr.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-CfLCUi9S.js",imports:["/assets/chunk-JMJ3UQ3L-BambyYE_.js","/assets/InteractivePreview-D-9pXIaY.js","/assets/useInteractiveMode-Dk_FQqWJ.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-BqPPNjAl.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha_.create-scenario":{id:"routes/entity.$sha_.create-scenario",parentId:"root",path:"entity/:sha/create-scenario",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha_.create-scenario-D_3ero5o.js",imports:["/assets/chunk-JMJ3UQ3L-BambyYE_.js","/assets/InteractivePreview-D-9pXIaY.js","/assets/useInteractiveMode-Dk_FQqWJ.js","/assets/keyAttributeCoverage-CTlFMihX.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-BqPPNjAl.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-scenario-data":{id:"routes/api.generate-scenario-data",parentId:"root",path:"api/generate-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.generate-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.update-key-attributes":{id:"routes/api.update-key-attributes",parentId:"root",path:"api/update-key-attributes",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.update-key-attributes-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.link-scenario-value":{id:"routes/api.link-scenario-value",parentId:"root",path:"api/link-scenario-value",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.link-scenario-value-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.update-valid-values":{id:"routes/api.update-valid-values",parentId:"root",path:"api/update-valid-values",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.update-valid-values-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)-CVP_WGQ3.js",imports:["/assets/chunk-JMJ3UQ3L-BambyYE_.js","/assets/LogViewer-wDPcZNKx.js","/assets/useLastLogLine-BqPPNjAl.js","/assets/useReportContext-DsJbgMY9.js","/assets/EntityTypeIcon-CXFKsCOD.js","/assets/EntityTypeBadge-CzGX-miz.js","/assets/SafeScreenshot-BfmDgXxG.js","/assets/LoadingDots-D1CdlbrV.js","/assets/loader-circle-CNp9QFCX.js","/assets/createLucideIcon-CgUsG7ib.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._-Dt-SjPsw.js",imports:["/assets/chunk-JMJ3UQ3L-BambyYE_.js","/assets/useLastLogLine-BqPPNjAl.js","/assets/useInteractiveMode-Dk_FQqWJ.js","/assets/InteractivePreview-D-9pXIaY.js","/assets/SafeScreenshot-BfmDgXxG.js","/assets/LibraryFunctionPreview-CBQPrpT0.js","/assets/LoadingDots-D1CdlbrV.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/ScenarioViewer-CUxUNEEC.js","/assets/createLucideIcon-CgUsG7ib.js","/assets/keyAttributeCoverage-CTlFMihX.js","/assets/EntityTypeIcon-CXFKsCOD.js","/assets/LogViewer-wDPcZNKx.js","/assets/useReportContext-DsJbgMY9.js","/assets/preload-helper-ckwbz45p.js","/assets/useCustomSizes-BMIGFP-m.js","/assets/ReportIssueModal-4lcOlid-.js","/assets/circle-check-CaVsIRxt.js","/assets/triangle-alert-CBc5dE1s.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.analyze-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/simulations-CoNWGt0K.js",imports:["/assets/chunk-JMJ3UQ3L-BambyYE_.js","/assets/useReportContext-DsJbgMY9.js","/assets/SafeScreenshot-BfmDgXxG.js","/assets/LoadingDots-D1CdlbrV.js","/assets/EntityTypeIcon-CXFKsCOD.js","/assets/fileTableUtils-DAtOlaWE.js","/assets/chevron-down-BYimnrHg.js","/assets/search-DDGjYAMJ.js","/assets/loader-circle-CNp9QFCX.js","/assets/createLucideIcon-CgUsG7ib.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-DW_hdGUc.js",imports:["/assets/chunk-JMJ3UQ3L-BambyYE_.js","/assets/ScenarioViewer-CUxUNEEC.js","/assets/InteractivePreview-D-9pXIaY.js","/assets/useCustomSizes-BMIGFP-m.js","/assets/LogViewer-wDPcZNKx.js","/assets/SafeScreenshot-BfmDgXxG.js","/assets/useLastLogLine-BqPPNjAl.js","/assets/useInteractiveMode-Dk_FQqWJ.js","/assets/preload-helper-ckwbz45p.js","/assets/ReportIssueModal-4lcOlid-.js","/assets/createLucideIcon-CgUsG7ib.js","/assets/circle-check-CaVsIRxt.js","/assets/triangle-alert-CBc5dE1s.js","/assets/scenarioStatus-B_8jpV3e.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/settings-DgTyB-Wg.js",imports:["/assets/chunk-JMJ3UQ3L-BambyYE_.js","/assets/useReportContext-DsJbgMY9.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-DHImXdXq.js",imports:["/assets/chunk-JMJ3UQ3L-BambyYE_.js","/assets/useLastLogLine-BqPPNjAl.js","/assets/useToast-DWHcCcl1.js","/assets/useReportContext-DsJbgMY9.js","/assets/LogViewer-wDPcZNKx.js","/assets/EntityTypeIcon-CXFKsCOD.js","/assets/SafeScreenshot-BfmDgXxG.js","/assets/createLucideIcon-CgUsG7ib.js","/assets/circle-check-CaVsIRxt.js","/assets/loader-circle-CNp9QFCX.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-ClR0d32A.js",imports:["/assets/chunk-JMJ3UQ3L-BambyYE_.js","/assets/useReportContext-DsJbgMY9.js","/assets/EntityItem-wXL1Z2Aq.js","/assets/fileTableUtils-DAtOlaWE.js","/assets/chevron-down-BYimnrHg.js","/assets/search-DDGjYAMJ.js","/assets/useToast-DWHcCcl1.js","/assets/TruncatedFilePath-6J7zDUD5.js","/assets/SafeScreenshot-BfmDgXxG.js","/assets/LibraryFunctionPreview-CBQPrpT0.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-CBc5dE1s.js","/assets/createLucideIcon-CgUsG7ib.js","/assets/EntityTypeIcon-CXFKsCOD.js","/assets/EntityTypeBadge-CzGX-miz.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-D62Lxxmv.js",imports:["/assets/chunk-JMJ3UQ3L-BambyYE_.js","/assets/useReportContext-DsJbgMY9.js","/assets/EntityItem-wXL1Z2Aq.js","/assets/LogViewer-wDPcZNKx.js","/assets/fileTableUtils-DAtOlaWE.js","/assets/useToast-DWHcCcl1.js","/assets/TruncatedFilePath-6J7zDUD5.js","/assets/SafeScreenshot-BfmDgXxG.js","/assets/LibraryFunctionPreview-CBQPrpT0.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-CBc5dE1s.js","/assets/createLucideIcon-CgUsG7ib.js","/assets/EntityTypeIcon-CXFKsCOD.js","/assets/EntityTypeBadge-CzGX-miz.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0}},url:"/assets/manifest-0d27da29.js",version:"0d27da29",sri:void 0},jp="build/client",$p="/",Rp={unstable_optimizeDeps:!1,unstable_subResourceIntegrity:!1,v8_middleware:!1,v8_splitRouteModules:!1,v8_viteEnvironmentApi:!1},Dp=!0,Lp=!1,Op=[],Fp={mode:"lazy",manifestPath:"/__manifest"},Yp="/",zp={module:si},Bp={root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,module:bc},"routes/entity.$sha.scenarios.$scenarioId.fullscreen":{id:"routes/entity.$sha.scenarios.$scenarioId.fullscreen",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/fullscreen",index:void 0,caseSensitive:void 0,module:Nc},"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:Hc},"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:Zc},"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:Wd},"routes/api.update-key-attributes":{id:"routes/api.update-key-attributes",parentId:"root",path:"api/update-key-attributes",index:void 0,caseSensitive:void 0,module:Vd},"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:qd},"routes/api.link-scenario-value":{id:"routes/api.link-scenario-value",parentId:"root",path:"api/link-scenario-value",index:void 0,caseSensitive:void 0,module:Qd},"routes/api.update-valid-values":{id:"routes/api.update-valid-values",parentId:"root",path:"api/update-valid-values",index:void 0,caseSensitive:void 0,module:Zd},"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:xu},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,module:vu},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,module:Su},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,module:_u},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,module:Mu},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,module:ju},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,module:Ru},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,module:Ju},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,module:Qu},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,module:Zu},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,module:th},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,module:rh},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,module:hh},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,module:fh},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,module:yh},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,module:zh},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,module:Wh},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,module:Qh},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,module:Zh},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,module:am},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,module:im},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,module:dm},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,module:ym},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,module:bm},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,module:_m},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,module:jm},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,module:Wm}};export{fl as A,ml as B,ts as C,ve as D,Di as E,Li as F,At as G,Si as H,Va as I,_i as J,Ja as K,Mi as L,Ii as M,jp as N,$p as O,Ci as P,Rp as Q,Dp as R,xr as S,Lp as T,Op as U,Fp as V,Yp as W,zp as X,Bp as Y,Ip as Z,yi as a,Tt as b,St as c,Xe as d,Jt as e,fr as f,gr as g,Ha as h,fi as i,qi as j,Xn as k,vt as l,rt as m,Ka as n,rl as o,yn as p,wt as q,Qa as r,Xa as s,ll as t,Mt as u,Za as v,Rt as w,cl as x,es as y,oa as z};