@codeyam/codeyam-cli 0.1.7 → 0.1.8

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 (382) 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 +6 -6
  4. package/analyzer-template/packages/ai/package.json +1 -1
  5. package/analyzer-template/packages/ai/src/lib/astScopes/astScopeAnalyzer.ts +34 -3
  6. package/analyzer-template/packages/ai/src/lib/completionCall.ts +14 -2
  7. package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +27 -0
  8. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/coercePrimitivesToArraysBySchema.ts +62 -0
  9. package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +78 -2
  10. package/analyzer-template/packages/analyze/src/lib/ProjectAnalyzer.ts +6 -0
  11. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +9 -1
  12. package/analyzer-template/packages/analyze/src/lib/files/analyze/dependencyResolver.ts +0 -6
  13. package/analyzer-template/packages/analyze/src/lib/files/analyze/findOrCreateEntity.ts +12 -0
  14. package/analyzer-template/packages/analyze/src/lib/files/scenarios/TransformationTracer.ts +65 -28
  15. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +83 -0
  16. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +23 -4
  17. package/analyzer-template/packages/aws/package.json +1 -1
  18. package/analyzer-template/packages/database/index.ts +1 -0
  19. package/analyzer-template/packages/database/package.json +3 -3
  20. package/analyzer-template/packages/database/src/lib/kysely/db.ts +8 -0
  21. package/analyzer-template/packages/database/src/lib/kysely/tables/editorScenariosTable.ts +62 -0
  22. package/analyzer-template/packages/database/src/lib/loadCommits.ts +31 -20
  23. package/analyzer-template/packages/database/src/lib/loadReadyToBeCapturedAnalyses.ts +0 -5
  24. package/analyzer-template/packages/database/src/lib/updateCommitMetadata.ts +151 -135
  25. package/analyzer-template/packages/database/src/lib/updateFreshAnalysisStatus.ts +58 -42
  26. package/analyzer-template/packages/database/src/lib/updateFreshAnalysisStatusWithScenarios.ts +81 -65
  27. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.ts +29 -1
  28. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.ts +33 -5
  29. package/analyzer-template/packages/github/dist/database/index.d.ts +1 -0
  30. package/analyzer-template/packages/github/dist/database/index.d.ts.map +1 -1
  31. package/analyzer-template/packages/github/dist/database/index.js +1 -0
  32. package/analyzer-template/packages/github/dist/database/index.js.map +1 -1
  33. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts +2 -0
  34. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts.map +1 -1
  35. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js +5 -0
  36. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js.map +1 -1
  37. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.d.ts +20 -0
  38. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.d.ts.map +1 -0
  39. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.js +45 -0
  40. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.js.map +1 -0
  41. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts +5 -0
  42. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts.map +1 -1
  43. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.d.ts.map +1 -1
  44. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js +23 -13
  45. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js.map +1 -1
  46. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.d.ts.map +1 -1
  47. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js +1 -4
  48. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
  49. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts.map +1 -1
  50. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js +100 -89
  51. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js.map +1 -1
  52. package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatus.d.ts.map +1 -1
  53. package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatus.js +41 -30
  54. package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatus.js.map +1 -1
  55. package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatusWithScenarios.d.ts.map +1 -1
  56. package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatusWithScenarios.js +68 -57
  57. package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatusWithScenarios.js.map +1 -1
  58. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.d.ts.map +1 -1
  59. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +29 -1
  60. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -1
  61. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.d.ts.map +1 -1
  62. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +33 -5
  63. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
  64. package/analyzer-template/packages/github/dist/types/src/types/ProjectMetadata.d.ts +1 -0
  65. package/analyzer-template/packages/github/dist/types/src/types/ProjectMetadata.d.ts.map +1 -1
  66. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts +10 -0
  67. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts.map +1 -1
  68. package/analyzer-template/packages/github/package.json +1 -1
  69. package/analyzer-template/packages/types/src/types/ProjectMetadata.ts +1 -0
  70. package/analyzer-template/packages/types/src/types/Scenario.ts +10 -0
  71. package/analyzer-template/packages/utils/dist/types/src/types/ProjectMetadata.d.ts +1 -0
  72. package/analyzer-template/packages/utils/dist/types/src/types/ProjectMetadata.d.ts.map +1 -1
  73. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts +10 -0
  74. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts.map +1 -1
  75. package/analyzer-template/playwright/captureFromUrl.ts +89 -82
  76. package/analyzer-template/project/constructMockCode.ts +136 -43
  77. package/analyzer-template/project/reconcileMockDataKeys.ts +19 -14
  78. package/analyzer-template/project/start.ts +3 -0
  79. package/analyzer-template/project/startScenarioCapture.ts +9 -0
  80. package/analyzer-template/project/writeClientLogRoute.ts +125 -0
  81. package/analyzer-template/project/writeMockDataTsx.ts +17 -0
  82. package/analyzer-template/project/writeScenarioComponents.ts +36 -7
  83. package/analyzer-template/tsconfig.json +13 -1
  84. package/background/src/lib/virtualized/project/constructMockCode.js +115 -34
  85. package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
  86. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js +17 -11
  87. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js.map +1 -1
  88. package/background/src/lib/virtualized/project/start.js +2 -0
  89. package/background/src/lib/virtualized/project/start.js.map +1 -1
  90. package/background/src/lib/virtualized/project/startScenarioCapture.js +5 -0
  91. package/background/src/lib/virtualized/project/startScenarioCapture.js.map +1 -1
  92. package/background/src/lib/virtualized/project/writeClientLogRoute.js +110 -0
  93. package/background/src/lib/virtualized/project/writeClientLogRoute.js.map +1 -0
  94. package/background/src/lib/virtualized/project/writeMockDataTsx.js +12 -0
  95. package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
  96. package/background/src/lib/virtualized/project/writeScenarioComponents.js +29 -7
  97. package/background/src/lib/virtualized/project/writeScenarioComponents.js.map +1 -1
  98. package/codeyam-cli/scripts/apply-setup.js +208 -11
  99. package/codeyam-cli/scripts/apply-setup.js.map +1 -1
  100. package/codeyam-cli/src/cli.js +2 -0
  101. package/codeyam-cli/src/cli.js.map +1 -1
  102. package/codeyam-cli/src/commands/analyze.js +17 -7
  103. package/codeyam-cli/src/commands/analyze.js.map +1 -1
  104. package/codeyam-cli/src/commands/default.js +58 -3
  105. package/codeyam-cli/src/commands/default.js.map +1 -1
  106. package/codeyam-cli/src/commands/editor.js +1839 -0
  107. package/codeyam-cli/src/commands/editor.js.map +1 -0
  108. package/codeyam-cli/src/commands/init.js +40 -11
  109. package/codeyam-cli/src/commands/init.js.map +1 -1
  110. package/codeyam-cli/src/utils/__tests__/editorAudit.test.js +246 -0
  111. package/codeyam-cli/src/utils/__tests__/editorAudit.test.js.map +1 -0
  112. package/codeyam-cli/src/utils/__tests__/editorDevServer.test.js +126 -0
  113. package/codeyam-cli/src/utils/__tests__/editorDevServer.test.js.map +1 -0
  114. package/codeyam-cli/src/utils/__tests__/editorJournal.test.js +295 -0
  115. package/codeyam-cli/src/utils/__tests__/editorJournal.test.js.map +1 -0
  116. package/codeyam-cli/src/utils/__tests__/editorMockState.test.js +270 -0
  117. package/codeyam-cli/src/utils/__tests__/editorMockState.test.js.map +1 -0
  118. package/codeyam-cli/src/utils/__tests__/editorPreloadHelpers.test.js +100 -0
  119. package/codeyam-cli/src/utils/__tests__/editorPreloadHelpers.test.js.map +1 -0
  120. package/codeyam-cli/src/utils/__tests__/editorPreview.test.js +147 -0
  121. package/codeyam-cli/src/utils/__tests__/editorPreview.test.js.map +1 -0
  122. package/codeyam-cli/src/utils/__tests__/editorScenarios.test.js +76 -0
  123. package/codeyam-cli/src/utils/__tests__/editorScenarios.test.js.map +1 -0
  124. package/codeyam-cli/src/utils/__tests__/git.editor.test.js +134 -0
  125. package/codeyam-cli/src/utils/__tests__/git.editor.test.js.map +1 -0
  126. package/codeyam-cli/src/utils/__tests__/pathIgnoring.test.js +9 -0
  127. package/codeyam-cli/src/utils/__tests__/pathIgnoring.test.js.map +1 -1
  128. package/codeyam-cli/src/utils/__tests__/project.test.js +65 -0
  129. package/codeyam-cli/src/utils/__tests__/project.test.js.map +1 -0
  130. package/codeyam-cli/src/utils/__tests__/scenarioMarkers.test.js +121 -0
  131. package/codeyam-cli/src/utils/__tests__/scenarioMarkers.test.js.map +1 -0
  132. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js +26 -0
  133. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js.map +1 -1
  134. package/codeyam-cli/src/utils/backgroundServer.js +19 -3
  135. package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
  136. package/codeyam-cli/src/utils/buildFlags.js +4 -0
  137. package/codeyam-cli/src/utils/buildFlags.js.map +1 -0
  138. package/codeyam-cli/src/utils/devModeEvents.js +40 -0
  139. package/codeyam-cli/src/utils/devModeEvents.js.map +1 -0
  140. package/codeyam-cli/src/utils/editorAudit.js +82 -0
  141. package/codeyam-cli/src/utils/editorAudit.js.map +1 -0
  142. package/codeyam-cli/src/utils/editorDevServer.js +98 -0
  143. package/codeyam-cli/src/utils/editorDevServer.js.map +1 -0
  144. package/codeyam-cli/src/utils/editorJournal.js +137 -0
  145. package/codeyam-cli/src/utils/editorJournal.js.map +1 -0
  146. package/codeyam-cli/src/utils/editorMockState.js +248 -0
  147. package/codeyam-cli/src/utils/editorMockState.js.map +1 -0
  148. package/codeyam-cli/src/utils/editorPreloadHelpers.js +64 -0
  149. package/codeyam-cli/src/utils/editorPreloadHelpers.js.map +1 -0
  150. package/codeyam-cli/src/utils/editorPreview.js +66 -0
  151. package/codeyam-cli/src/utils/editorPreview.js.map +1 -0
  152. package/codeyam-cli/src/utils/editorScenarios.js +56 -0
  153. package/codeyam-cli/src/utils/editorScenarios.js.map +1 -0
  154. package/codeyam-cli/src/utils/fileMetadata.js +5 -0
  155. package/codeyam-cli/src/utils/fileMetadata.js.map +1 -1
  156. package/codeyam-cli/src/utils/fileWatcher.js +25 -9
  157. package/codeyam-cli/src/utils/fileWatcher.js.map +1 -1
  158. package/codeyam-cli/src/utils/git.js +103 -0
  159. package/codeyam-cli/src/utils/git.js.map +1 -1
  160. package/codeyam-cli/src/utils/install-skills.js +55 -13
  161. package/codeyam-cli/src/utils/install-skills.js.map +1 -1
  162. package/codeyam-cli/src/utils/interactiveSyncWatcher.js +126 -0
  163. package/codeyam-cli/src/utils/interactiveSyncWatcher.js.map +1 -0
  164. package/codeyam-cli/src/utils/pathIgnoring.js +19 -7
  165. package/codeyam-cli/src/utils/pathIgnoring.js.map +1 -1
  166. package/codeyam-cli/src/utils/project.js +15 -5
  167. package/codeyam-cli/src/utils/project.js.map +1 -1
  168. package/codeyam-cli/src/utils/queue/__tests__/heartbeat.test.js +11 -11
  169. package/codeyam-cli/src/utils/queue/__tests__/heartbeat.test.js.map +1 -1
  170. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js +22 -0
  171. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js.map +1 -1
  172. package/codeyam-cli/src/utils/queue/heartbeat.js +13 -5
  173. package/codeyam-cli/src/utils/queue/heartbeat.js.map +1 -1
  174. package/codeyam-cli/src/utils/queue/job.js +70 -1
  175. package/codeyam-cli/src/utils/queue/job.js.map +1 -1
  176. package/codeyam-cli/src/utils/queue/manager.js +7 -6
  177. package/codeyam-cli/src/utils/queue/manager.js.map +1 -1
  178. package/codeyam-cli/src/utils/scenarioMarkers.js +134 -0
  179. package/codeyam-cli/src/utils/scenarioMarkers.js.map +1 -0
  180. package/codeyam-cli/src/utils/serverState.js +27 -2
  181. package/codeyam-cli/src/utils/serverState.js.map +1 -1
  182. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +45 -4
  183. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
  184. package/codeyam-cli/src/utils/testRunner.js +158 -0
  185. package/codeyam-cli/src/utils/testRunner.js.map +1 -0
  186. package/codeyam-cli/src/utils/webappDetection.js +14 -2
  187. package/codeyam-cli/src/utils/webappDetection.js.map +1 -1
  188. package/codeyam-cli/src/webserver/app/lib/database.js +41 -27
  189. package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
  190. package/codeyam-cli/src/webserver/app/lib/dbNotifier.js.map +1 -1
  191. package/codeyam-cli/src/webserver/backgroundServer.js +108 -18
  192. package/codeyam-cli/src/webserver/backgroundServer.js.map +1 -1
  193. package/codeyam-cli/src/webserver/build/client/assets/{CopyButton-CtmbP4Gl.js → CopyButton-DmJveP3T.js} +1 -1
  194. package/codeyam-cli/src/webserver/build/client/assets/{EntityItem-DlMph_Hm.js → EntityItem-C76mRRiF.js} +1 -1
  195. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeBadge-B-0PjGOU.js → EntityTypeBadge-g3saevPb.js} +1 -1
  196. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeIcon-DN9eiJAO.js → EntityTypeIcon-CobE682z.js} +1 -1
  197. package/codeyam-cli/src/webserver/build/client/assets/InlineSpinner-Bu6c6aDe.js +1 -0
  198. package/codeyam-cli/src/webserver/build/client/assets/{InteractivePreview-rE_fI2h2.js → InteractivePreview-DYFW3lDD.js} +3 -3
  199. package/codeyam-cli/src/webserver/build/client/assets/{LibraryFunctionPreview-CnatsCw2.js → LibraryFunctionPreview-DLeucoVX.js} +1 -1
  200. package/codeyam-cli/src/webserver/build/client/assets/{LoadingDots-CSP6DZrh.js → LoadingDots-BU_OAEMP.js} +1 -1
  201. package/codeyam-cli/src/webserver/build/client/assets/{LogViewer-CMK8Q7yk.js → LogViewer-ceAyBX-H.js} +1 -1
  202. package/codeyam-cli/src/webserver/build/client/assets/{ReportIssueModal-TCV_HBjy.js → ReportIssueModal-djPLI-WV.js} +1 -1
  203. package/codeyam-cli/src/webserver/build/client/assets/{SafeScreenshot-CG2uh31y.js → SafeScreenshot-BED4B6sP.js} +1 -1
  204. package/codeyam-cli/src/webserver/build/client/assets/{ScenarioViewer-CU_TDYd8.js → ScenarioViewer-B76aig_2.js} +1 -1
  205. package/codeyam-cli/src/webserver/build/client/assets/Spinner-Bb5uFQ5V.js +34 -0
  206. package/codeyam-cli/src/webserver/build/client/assets/Terminal-Dnj5CY9R.js +41 -0
  207. package/codeyam-cli/src/webserver/build/client/assets/{TruncatedFilePath-D7IoaWUW.js → TruncatedFilePath-C8OKAR5x.js} +1 -1
  208. package/codeyam-cli/src/webserver/build/client/assets/{_index-B8z7mjR-.js → _index-C96V0n15.js} +1 -1
  209. package/codeyam-cli/src/webserver/build/client/assets/{activity.(_tab)-DZu78RI1.js → activity.(_tab)-BpKzcsJz.js} +1 -1
  210. package/codeyam-cli/src/webserver/build/client/assets/addon-fit-CUXOrorO.js +1 -0
  211. package/codeyam-cli/src/webserver/build/client/assets/addon-web-links-Duc5hnl7.js +1 -0
  212. package/codeyam-cli/src/webserver/build/client/assets/{agent-transcripts-Dm5RS9il.js → agent-transcripts-D9hemwl6.js} +1 -1
  213. package/codeyam-cli/src/webserver/build/client/assets/api.dev-mode-events-l0sNRNKZ.js +1 -0
  214. package/codeyam-cli/src/webserver/build/client/assets/api.editor-audit-l0sNRNKZ.js +1 -0
  215. package/codeyam-cli/src/webserver/build/client/assets/api.editor-capture-scenario-l0sNRNKZ.js +1 -0
  216. package/codeyam-cli/src/webserver/build/client/assets/api.editor-client-errors-l0sNRNKZ.js +1 -0
  217. package/codeyam-cli/src/webserver/build/client/assets/api.editor-commit-l0sNRNKZ.js +1 -0
  218. package/codeyam-cli/src/webserver/build/client/assets/api.editor-dev-server-l0sNRNKZ.js +1 -0
  219. package/codeyam-cli/src/webserver/build/client/assets/api.editor-entity-status-l0sNRNKZ.js +1 -0
  220. package/codeyam-cli/src/webserver/build/client/assets/api.editor-journal-entry-l0sNRNKZ.js +1 -0
  221. package/codeyam-cli/src/webserver/build/client/assets/api.editor-journal-image._-l0sNRNKZ.js +1 -0
  222. package/codeyam-cli/src/webserver/build/client/assets/api.editor-journal-l0sNRNKZ.js +1 -0
  223. package/codeyam-cli/src/webserver/build/client/assets/api.editor-journal-screenshot-l0sNRNKZ.js +1 -0
  224. package/codeyam-cli/src/webserver/build/client/assets/api.editor-journal-update-l0sNRNKZ.js +1 -0
  225. package/codeyam-cli/src/webserver/build/client/assets/api.editor-load-commit-l0sNRNKZ.js +1 -0
  226. package/codeyam-cli/src/webserver/build/client/assets/api.editor-refresh-l0sNRNKZ.js +1 -0
  227. package/codeyam-cli/src/webserver/build/client/assets/api.editor-register-scenario-l0sNRNKZ.js +1 -0
  228. package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenario-data-l0sNRNKZ.js +1 -0
  229. package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenario-image._-l0sNRNKZ.js +1 -0
  230. package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenarios-l0sNRNKZ.js +1 -0
  231. package/codeyam-cli/src/webserver/build/client/assets/api.editor-switch-scenario-l0sNRNKZ.js +1 -0
  232. package/codeyam-cli/src/webserver/build/client/assets/api.editor-test-results-l0sNRNKZ.js +1 -0
  233. package/codeyam-cli/src/webserver/build/client/assets/{book-open-Bp5FLkd4.js → book-open-D_nMCFmP.js} +1 -1
  234. package/codeyam-cli/src/webserver/build/client/assets/{chevron-down-DQJA9f4o.js → chevron-down-BH2h1Ea2.js} +1 -1
  235. package/codeyam-cli/src/webserver/build/client/assets/{chunk-JZWAC4HX-7VptmeIr.js → chunk-JZWAC4HX-C4pqxYJB.js} +1 -1
  236. package/codeyam-cli/src/webserver/build/client/assets/{circle-check-B6C4LY9o.js → circle-check-DyIKORY6.js} +1 -1
  237. package/codeyam-cli/src/webserver/build/client/assets/{copy-6nzYCu0G.js → copy-NDbZjXao.js} +1 -1
  238. package/codeyam-cli/src/webserver/build/client/assets/{createLucideIcon-D-QUFOwe.js → createLucideIcon-CMT1jU2q.js} +1 -1
  239. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-BiM6z3Do.js +1 -0
  240. package/codeyam-cli/src/webserver/build/client/assets/editor-D1DAKXtT.js +8 -0
  241. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-C6PQhwY5.js → entity._sha._-CrjR3zZW.js} +8 -8
  242. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.dev-DkzqFzFj.js +6 -0
  243. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-C28BiQzt.js +6 -0
  244. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-p9hhkjJM.js +6 -0
  245. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha_.edit._scenarioId-C7ysA4Jq.js → entity._sha_.edit._scenarioId-BMvVHNXU.js} +2 -2
  246. package/codeyam-cli/src/webserver/build/client/assets/{entry.client-CU6EUArK.js → entry.client-DTvKq3TY.js} +1 -1
  247. package/codeyam-cli/src/webserver/build/client/assets/{fileTableUtils-EWpfFU4X.js → fileTableUtils-cPo8LiG3.js} +1 -1
  248. package/codeyam-cli/src/webserver/build/client/assets/{files-CrxAoWIL.js → files-DO4CZ16O.js} +1 -1
  249. package/codeyam-cli/src/webserver/build/client/assets/{git-BldHtKeW.js → git-CFCTYk9I.js} +1 -1
  250. package/codeyam-cli/src/webserver/build/client/assets/globals-B17TBSS6.css +1 -0
  251. package/codeyam-cli/src/webserver/build/client/assets/{index-7-1FmlHo.js → index-10oVnAAH.js} +1 -1
  252. package/codeyam-cli/src/webserver/build/client/assets/{index-DuYcwYp_.js → index-BcvgDzbZ.js} +1 -1
  253. package/codeyam-cli/src/webserver/build/client/assets/{labs-CPPVOSWB.js → labs-Zk7ryIM1.js} +1 -1
  254. package/codeyam-cli/src/webserver/build/client/assets/{loader-circle-BnDcD54R.js → loader-circle-BAXYRVEO.js} +1 -1
  255. package/codeyam-cli/src/webserver/build/client/assets/manifest-a632de18.js +1 -0
  256. package/codeyam-cli/src/webserver/build/client/assets/{memory-0wMU4KXe.js → memory-Dg0mvYrI.js} +5 -2
  257. package/codeyam-cli/src/webserver/build/client/assets/{pause-DhQX2g22.js → pause-DTAcYxBt.js} +1 -1
  258. package/codeyam-cli/src/webserver/build/client/assets/root-DUKqhFlb.js +67 -0
  259. package/codeyam-cli/src/webserver/build/client/assets/{search-DborVoKD.js → search-fKo7v0Zo.js} +1 -1
  260. package/codeyam-cli/src/webserver/build/client/assets/{settings-BWunYSXt.js → settings-DfuTtcJP.js} +1 -1
  261. package/codeyam-cli/src/webserver/build/client/assets/{simulations-BtrtCYJg.js → simulations-B3aOzpCZ.js} +1 -1
  262. package/codeyam-cli/src/webserver/build/client/assets/{terminal-Bs4NC-VZ.js → terminal-BG4heKCG.js} +1 -1
  263. package/codeyam-cli/src/webserver/build/client/assets/{triangle-alert-DTf3Jojp.js → triangle-alert-DtSmdtM4.js} +1 -1
  264. package/codeyam-cli/src/webserver/build/client/assets/{useCustomSizes-D_bDZyDU.js → useCustomSizes-ByhSyh0W.js} +1 -1
  265. package/codeyam-cli/src/webserver/build/client/assets/useLastLogLine-C14nCb1q.js +2 -0
  266. package/codeyam-cli/src/webserver/build/client/assets/{useReportContext-BsQb6rFd.js → useReportContext-O-jkvSPx.js} +1 -1
  267. package/codeyam-cli/src/webserver/build/client/assets/{useToast-BOur3mUv.js → useToast-9FIWuYfK.js} +1 -1
  268. package/codeyam-cli/src/webserver/build/client/assets/xterm-BqvuqXEL.js +27 -0
  269. package/codeyam-cli/src/webserver/build/server/assets/index-HfLydfDq.js +1 -0
  270. package/codeyam-cli/src/webserver/build/server/assets/server-build-CUu_F-oo.js +366 -0
  271. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  272. package/codeyam-cli/src/webserver/build-info.json +5 -5
  273. package/codeyam-cli/src/webserver/devServer.js +39 -5
  274. package/codeyam-cli/src/webserver/devServer.js.map +1 -1
  275. package/codeyam-cli/src/webserver/editorProxy.js +440 -0
  276. package/codeyam-cli/src/webserver/editorProxy.js.map +1 -0
  277. package/codeyam-cli/src/webserver/scripts/codeyam-preload.mjs +175 -0
  278. package/codeyam-cli/src/webserver/scripts/journalCapture.ts +140 -0
  279. package/codeyam-cli/src/webserver/server.js +226 -1
  280. package/codeyam-cli/src/webserver/server.js.map +1 -1
  281. package/codeyam-cli/src/webserver/terminalServer.js +698 -0
  282. package/codeyam-cli/src/webserver/terminalServer.js.map +1 -0
  283. package/codeyam-cli/templates/codeyam-editor-claude.md +68 -0
  284. package/codeyam-cli/templates/editor-step-hook.py +147 -0
  285. package/codeyam-cli/templates/isolation-route/next-app.tsx.template +80 -0
  286. package/codeyam-cli/templates/isolation-route/next-pages.tsx.template +79 -0
  287. package/codeyam-cli/templates/isolation-route/vite-react.tsx.template +78 -0
  288. package/codeyam-cli/templates/msw/browser-setup.ts.template +47 -0
  289. package/codeyam-cli/templates/msw/handler-router.ts.template +47 -0
  290. package/codeyam-cli/templates/msw/server-setup.ts.template +52 -0
  291. package/codeyam-cli/templates/nextjs-prisma-sqlite/PRISMA_SETUP.md +84 -0
  292. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/api/todos/route.ts +17 -0
  293. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/globals.css +26 -0
  294. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/layout.tsx +34 -0
  295. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/lib/prisma.ts +19 -0
  296. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/page.tsx +10 -0
  297. package/codeyam-cli/templates/nextjs-prisma-sqlite/eslint.config.mjs +11 -0
  298. package/codeyam-cli/templates/nextjs-prisma-sqlite/gitignore +43 -0
  299. package/codeyam-cli/templates/nextjs-prisma-sqlite/next.config.ts +14 -0
  300. package/codeyam-cli/templates/nextjs-prisma-sqlite/package.json +35 -0
  301. package/codeyam-cli/templates/nextjs-prisma-sqlite/postcss.config.mjs +7 -0
  302. package/codeyam-cli/templates/nextjs-prisma-sqlite/prisma/schema.prisma +27 -0
  303. package/codeyam-cli/templates/nextjs-prisma-sqlite/prisma/seed.ts +37 -0
  304. package/codeyam-cli/templates/nextjs-prisma-sqlite/prisma.config.ts +12 -0
  305. package/codeyam-cli/templates/nextjs-prisma-sqlite/tsconfig.json +34 -0
  306. package/codeyam-cli/templates/skills/codeyam-dev-mode/SKILL.md +237 -0
  307. package/codeyam-cli/templates/skills/codeyam-editor/SKILL.md +69 -0
  308. package/codeyam-cli/templates/{codeyam-memory.md → skills/codeyam-memory/SKILL.md} +215 -0
  309. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/deprecated-prompt.md +100 -0
  310. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/detect-deprecated-patterns.sh +108 -0
  311. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/find-exports.sh +69 -0
  312. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/misleading-api-prompt.md +117 -0
  313. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/analyze-prompt.md +46 -0
  314. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/cleanup.sh +12 -0
  315. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/filter.jq +45 -0
  316. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/preprocess.sh +139 -0
  317. package/package.json +4 -2
  318. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js +22 -4
  319. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js.map +1 -1
  320. package/packages/ai/src/lib/completionCall.js +10 -2
  321. package/packages/ai/src/lib/completionCall.js.map +1 -1
  322. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +21 -0
  323. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
  324. package/packages/ai/src/lib/dataStructure/helpers/coercePrimitivesToArraysBySchema.js +54 -0
  325. package/packages/ai/src/lib/dataStructure/helpers/coercePrimitivesToArraysBySchema.js.map +1 -0
  326. package/packages/ai/src/lib/dataStructure/helpers/stripNullableMarkers.js +34 -0
  327. package/packages/ai/src/lib/dataStructure/helpers/stripNullableMarkers.js.map +1 -0
  328. package/packages/ai/src/lib/generateEntityScenarioData.js +57 -2
  329. package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
  330. package/packages/analyze/src/lib/ProjectAnalyzer.js +3 -0
  331. package/packages/analyze/src/lib/ProjectAnalyzer.js.map +1 -1
  332. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +8 -1
  333. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
  334. package/packages/analyze/src/lib/files/analyze/dependencyResolver.js +0 -5
  335. package/packages/analyze/src/lib/files/analyze/dependencyResolver.js.map +1 -1
  336. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js +9 -0
  337. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js.map +1 -1
  338. package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js +54 -27
  339. package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js.map +1 -1
  340. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +65 -0
  341. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
  342. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +18 -4
  343. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
  344. package/packages/database/index.js +1 -0
  345. package/packages/database/index.js.map +1 -1
  346. package/packages/database/src/lib/kysely/db.js +5 -0
  347. package/packages/database/src/lib/kysely/db.js.map +1 -1
  348. package/packages/database/src/lib/kysely/tables/editorScenariosTable.js +45 -0
  349. package/packages/database/src/lib/kysely/tables/editorScenariosTable.js.map +1 -0
  350. package/packages/database/src/lib/loadCommits.js +23 -13
  351. package/packages/database/src/lib/loadCommits.js.map +1 -1
  352. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js +1 -4
  353. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
  354. package/packages/database/src/lib/updateCommitMetadata.js +100 -89
  355. package/packages/database/src/lib/updateCommitMetadata.js.map +1 -1
  356. package/packages/database/src/lib/updateFreshAnalysisStatus.js +41 -30
  357. package/packages/database/src/lib/updateFreshAnalysisStatus.js.map +1 -1
  358. package/packages/database/src/lib/updateFreshAnalysisStatusWithScenarios.js +68 -57
  359. package/packages/database/src/lib/updateFreshAnalysisStatusWithScenarios.js.map +1 -1
  360. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +29 -1
  361. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -1
  362. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +33 -5
  363. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
  364. package/scripts/npm-post-install.cjs +34 -0
  365. package/codeyam-cli/src/webserver/build/client/assets/InlineSpinner-C1rIyZdV.js +0 -34
  366. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-DmzSmblj.js +0 -1
  367. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-DVTcUnur.js +0 -6
  368. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-BVgNO76F.js +0 -6
  369. package/codeyam-cli/src/webserver/build/client/assets/globals-CLmFdUae.css +0 -1
  370. package/codeyam-cli/src/webserver/build/client/assets/manifest-717e346a.js +0 -1
  371. package/codeyam-cli/src/webserver/build/client/assets/root-DqfSDjyQ.js +0 -62
  372. package/codeyam-cli/src/webserver/build/client/assets/useLastLogLine-DZp6rrQD.js +0 -2
  373. package/codeyam-cli/src/webserver/build/server/assets/index-B8jmgmn2.js +0 -1
  374. package/codeyam-cli/src/webserver/build/server/assets/server-build-9OU4lmvL.js +0 -285
  375. package/scripts/finalize-analyzer.cjs +0 -13
  376. /package/codeyam-cli/templates/{codeyam-diagnose.md → commands/codeyam-diagnose.md} +0 -0
  377. /package/codeyam-cli/templates/{codeyam-debug.md → skills/codeyam-debug/SKILL.md} +0 -0
  378. /package/codeyam-cli/templates/{codeyam-new-rule.md → skills/codeyam-new-rule/SKILL.md} +0 -0
  379. /package/codeyam-cli/templates/{codeyam-setup.md → skills/codeyam-setup/SKILL.md} +0 -0
  380. /package/codeyam-cli/templates/{codeyam-sim.md → skills/codeyam-sim/SKILL.md} +0 -0
  381. /package/codeyam-cli/templates/{codeyam-test.md → skills/codeyam-test/SKILL.md} +0 -0
  382. /package/codeyam-cli/templates/{codeyam-verify.md → skills/codeyam-verify/SKILL.md} +0 -0
@@ -1,285 +0,0 @@
1
- var Pi=Object.defineProperty;var es=e=>{throw TypeError(e)};var Mi=(e,t,r)=>t in e?Pi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var vn=(e,t,r)=>Mi(e,typeof t!="symbol"?t+"":t,r),Ti=(e,t,r)=>t.has(e)||es("Cannot "+r);var ts=(e,t,r)=>(Ti(e,t,"read from private field"),r?r.call(e):t.get(e)),ns=(e,t,r)=>t.has(e)?es("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r);import{jsx as n,jsxs as l,Fragment as le}from"react/jsx-runtime";import{PassThrough as ji}from"node:stream";import{createReadableStreamFromReadable as Ii}from"@react-router/node";import{ServerRouter as $i,useFetcher as Ee,useLocation as er,useNavigate as It,Link as se,UNSAFE_withComponentProps as De,Meta as Ri,Links as Di,ScrollRestoration as Li,Scripts as Fi,useLoaderData as Be,useRevalidator as it,Outlet as Oi,data as W,useSearchParams as cn,useRouteLoaderData as zi,useParams as qs,useActionData as Yi,redirect as Bi}from"react-router";import{isbot as Ui}from"isbot";import{renderToPipeableStream as Wi}from"react-dom/server";import{useState as _,useEffect as ee,useCallback as ie,createContext as aa,useContext as tr,useRef as Ne,useMemo as ae}from"react";import{Settings as rs,CheckCircle2 as sa,Bug as Ks,AlertTriangle as Dn,Check as et,Copy as st,Loader2 as Xe,HomeIcon as Hi,GitCommitIcon as as,File as Vi,RefreshCw as Ji,BookOpen as Ln,FlaskConical as Gi,SettingsIcon as qi,PanelsTopLeftIcon as Ki,ComponentIcon as Qi,FileText as ss,Code as os,Box as Zi,List as Xi,BarChart3 as el,Tag as tl,Image as an,Code2 as Qs,Activity as Er,ChevronDown as Qe,CircleEqual as nl,ArrowLeft as rl,Terminal as Fn,Search as dn,ChevronLeft as al,ChevronRight as xt,Save as sl,MessageSquare as ol,Pause as Zs,ListTodo as il,PauseCircle as ll,FileCode as On,GripVertical as cl,Ban as dl,CheckCircle as ul,FolderOpen as ml,CodeXml as hl,Zap as pl,Pencil as fl,Trash2 as gl,X as un,Folder as Xs,Info as Vr,Plus as oa,Eye as yl,FolderTree as xl,ChevronsUpDown as eo,ChevronsDownUp as to}from"lucide-react";import"fetch-retry";import bl from"better-sqlite3";import{Pool as vl}from"pg";import*as K from"fs";import Mt,{existsSync as pt,readdirSync as wl,rmSync as Ar}from"fs";import*as Z from"path";import oe,{join as is}from"path";import{OperationNodeTransformer as Cl,Kysely as no,ParseJSONResultsPlugin as Nl,SqliteDialect as Sl,PostgresDialect as kl,sql as Ke}from"kysely";import*as El from"kysely/helpers/sqlite";import*as Al from"kysely/helpers/postgres";import je from"typescript";import*as Re from"fs/promises";import he,{writeFile as Xt,readFile as Jr,mkdir as _l}from"fs/promises";import*as Pl from"os";import Gr from"os";import Ml from"prompts";import zn from"chalk";import*as Tl from"crypto";import nr,{randomUUID as ro,createHmac as jl}from"crypto";import{execSync as Me,spawn as rr,exec as ia}from"child_process";import{fileURLToPath as ar}from"url";import{promisify as la}from"util";import Il from"dotenv";import $l,{EventEmitter as Rl}from"events";import{v4 as Dl}from"uuid";import Ll from"openai";import Fl from"p-queue";import ls from"p-retry";import{DynamoDBClient as sr,PutItemCommand as Ol}from"@aws-sdk/client-dynamodb";import{LRUCache as ca}from"lru-cache";import"pluralize";import"piscina";import zl from"json5";import{marshall as Yl}from"@aws-sdk/util-dynamodb";import Bl from"v8";import{Prism as Ul}from"react-syntax-highlighter";import{vscDarkPlus as Wl}from"react-syntax-highlighter/dist/cjs/styles/prism/index.js";import{randomUUID as Hl}from"node:crypto";import{minimatch as qr}from"minimatch";import Vl from"react-markdown";import Jl from"remark-gfm";import Gl from"react-diff-viewer-continued";const ao=5e3;function ql(e,t,r,a,s){return e.method.toUpperCase()==="HEAD"?new Response(null,{status:t,headers:r}):new Promise((o,i)=>{let c=!1,d=e.headers.get("user-agent"),m=d&&Ui(d)||a.isSpaMode?"onAllReady":"onShellReady",u=setTimeout(()=>p(),ao+1e3);const{pipe:h,abort:p}=Wi(n($i,{context:a,url:e.url}),{[m](){c=!0;const f=new ji({final(y){clearTimeout(u),u=void 0,y()}}),g=Ii(f);r.set("Content-Type","text/html"),h(f),o(new Response(g,{headers:r,status:t}))},onShellError(f){i(f)},onError(f){t=500,c&&console.error(f)}})})}const Kl=Object.freeze(Object.defineProperty({__proto__:null,default:ql,streamTimeout:ao},Symbol.toStringTag,{value:"Module"}));function Ql({id:e,selected:t,onClick:r,icon:a,name:s}){const[o,i]=_(!1);ee(()=>{i(!0)},[]);const c=ie(()=>{r==null||r(e)},[r,e]);return l("button",{className:`
2
- w-full px-1.5 py-2 cursor-pointer focus:outline-none
3
- flex flex-col items-center justify-center gap-1 transition-colors
4
- ${t?"text-[#CBF3FA]":"text-[#568B94] hover:text-[#CBF3FA]"}
5
- `,onClick:c,children:[n("div",{className:`${t?"bg-[#CBF3FA] text-[#022A35]":""} w-9 h-9 rounded-lg flex items-center justify-center transition-colors`,children:o&&a}),n("span",{className:`text-[10px] font-normal text-center leading-tight ${t?"text-[#CBF3FA]":""}`,style:t?{color:"#CBF3FA !important"}:void 0,children:s})]})}const so="/assets/cy-logo-cli-CCKUIm0S.svg";function Zl(e){return e.scenarioName&&e.entityName?`${e.entityName} → "${e.scenarioName}"`:e.entityName?e.entityName:e.scenarioId?`Scenario: ${e.scenarioId.slice(0,8)}...`:e.entitySha?`Entity: ${e.entitySha.slice(0,8)}...`:"General feedback"}function Xl({content:e,className:t=""}){const[r,a]=_(!1),s=ie(()=>{navigator.clipboard.writeText(e).then(()=>{a(!0),setTimeout(()=>a(!1),2e3)}).catch(o=>{console.error("Failed to copy:",o)})},[e]);return n("button",{onClick:s,className:`cursor-pointer flex items-center gap-1 ${t}`,disabled:r,"aria-label":r?"Copied to clipboard":"Copy to clipboard",children:r?l(le,{children:[n(et,{size:14}),"Copied"]}):l(le,{children:[n(st,{size:14}),"Copy"]})})}function oo({isOpen:e,onClose:t,context:r,defaultEmail:a="",screenshotDataUrl:s}){const[o,i]=_(""),[c,d]=_(a),[m,u]=_(!1),[h,p]=_(!1),[f,g]=_(null),[y,x]=_(null),v=Ee(),b=v.state!=="idle",w=!!(r.scenarioId||r.analysisId),C=r.analysisId||r.scenarioId||"",k=()=>{const M=`/codeyam-diagnose ${C}`;return o.trim()?`${M} ${o.trim()}`:M};if(v.data&&!h&&!y){const M=v.data;M.success&&M.reportId?(p(!0),g(M.reportId)):M.error&&x(M.error)}const N=async()=>{x(null);const M=new FormData;if(M.append("issueType","other"),M.append("description",o),M.append("email",c),M.append("source",r.source),M.append("entitySha",r.entitySha||""),M.append("scenarioId",r.scenarioId||""),M.append("analysisId",r.analysisId||""),M.append("currentUrl",r.currentUrl),M.append("entityName",r.entityName||""),M.append("entityType",r.entityType||""),M.append("scenarioName",r.scenarioName||""),M.append("errorMessage",r.errorMessage||""),s)try{const L=await(await fetch(s)).blob();M.append("screenshot",L,"screenshot.jpg")}catch(F){console.error("Failed to convert screenshot:",F)}v.submit(M,{method:"post",action:"/api/generate-report",encType:"multipart/form-data"})},E=()=>{i(""),u(!1),p(!1),g(null),x(null),t()},S=M=>{M.key==="Escape"&&E()};return e?n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",onKeyDown:S,children:l("div",{className:"bg-white rounded-lg max-w-lg w-full p-6 shadow-xl max-h-[90vh] overflow-y-auto",children:[l("div",{className:"flex items-center justify-between mb-6",children:[l("div",{className:"flex items-center gap-3",children:[b?n("div",{className:"animate-spin",children:n(rs,{size:24,style:{strokeWidth:1.5}})}):h?n(sa,{size:24,style:{color:"#10B981",strokeWidth:1.5}}):n(Ks,{size:24,style:{color:"#005C75",strokeWidth:1.5}}),n("h2",{className:"text-xl font-semibold text-gray-900",children:h?"Report Submitted":"Report Issue"})]}),n("button",{onClick:E,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),h?l("div",{children:[l("div",{className:"mb-6 p-4 bg-green-50 rounded-lg border border-green-200",children:[n("p",{className:"text-sm text-green-800 font-medium mb-1",children:"Thank you for your feedback!"}),l("p",{className:"text-xs text-green-700",children:["Report ID:"," ",n("code",{className:"bg-green-100 px-1 rounded",children:f})]})]}),n("p",{className:"text-sm text-gray-600 mb-6",children:"The CodeYam team will investigate and may reach out if you provided an email address."}),n("div",{className:"flex justify-end",children:n("button",{onClick:E,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] transition-colors cursor-pointer",children:"Done"})})]}):l("div",{children:[l("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[l("div",{className:"flex items-center justify-between",children:[n("div",{className:"text-sm font-medium text-gray-900",title:`${r.source}${r.entitySha?` • Entity: ${r.entitySha}`:""}${r.scenarioId?` • Scenario: ${r.scenarioId}`:""}${r.analysisId?` • Analysis: ${r.analysisId}`:""}`,children:Zl(r)}),n("button",{type:"button",onClick:()=>u(!m),className:"text-xs text-gray-500 hover:text-gray-700 underline cursor-pointer",children:m?"Hide":"Details"})]}),m&&l("div",{className:"mt-2 pt-2 border-t border-gray-200 text-xs text-gray-600 space-y-1 break-all",children:[l("div",{children:[n("span",{className:"text-gray-400",children:"Source:"})," ",r.source]}),l("div",{children:[n("span",{className:"text-gray-400",children:"URL:"})," ",r.currentUrl]}),r.entitySha&&l("div",{children:[n("span",{className:"text-gray-400",children:"Entity:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.entitySha})]}),r.scenarioId&&l("div",{children:[n("span",{className:"text-gray-400",children:"Scenario:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.scenarioId})]}),r.analysisId&&l("div",{children:[n("span",{className:"text-gray-400",children:"Analysis:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.analysisId})]})]})]}),s&&l("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-xs text-gray-500 mb-2",children:"Screenshot (will be included in report)"}),n("img",{src:s,alt:"Page screenshot",className:"w-full max-h-[150px] object-contain rounded border border-gray-300"})]}),l("div",{className:"mb-4",children:[n("label",{htmlFor:"description",className:"block text-sm font-medium text-gray-700 mb-2",children:"What happened?"}),n("textarea",{id:"description",value:o,onChange:M=>i(M.target.value),placeholder:"Optional: Describe what you expected vs what happened...",rows:3,className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] resize-none"})]}),w&&l(le,{children:[l("div",{className:"mb-4 p-4 bg-purple-50 rounded-lg border border-purple-200",children:[l("div",{className:"flex items-center gap-2 mb-2",children:[n("span",{className:"text-lg",children:"🔧"}),n("h3",{className:"text-sm font-semibold text-purple-900",children:"Diagnose & Fix (Recommended)"})]}),n("p",{className:"text-xs text-purple-700 mb-3",children:"Run this command in Claude Code to investigate the issue locally and potentially fix it. A detailed report will also be uploaded."}),l("div",{className:"relative",children:[n("div",{className:"bg-gray-800 text-gray-50 px-3 py-2.5 pr-20 rounded-md text-xs font-mono overflow-x-auto whitespace-nowrap",children:k()}),n(Xl,{content:k(),className:"absolute top-1.5 right-2 px-2 py-1 bg-purple-600 text-white border-none rounded text-[11px] font-medium hover:bg-purple-700 transition-colors"})]})]}),l("div",{className:"relative my-5",children:[n("div",{className:"absolute inset-0 flex items-center",children:n("div",{className:"w-full border-t border-gray-300"})}),n("div",{className:"relative flex justify-center",children:n("span",{className:"bg-white px-3 text-xs text-gray-500 uppercase",children:"or"})})]})]}),l("div",{className:w?"opacity-75":"",children:[w&&l("div",{className:"flex items-center gap-2 mb-3",children:[n("span",{className:"text-lg",children:"📤"}),n("h3",{className:"text-sm font-semibold text-gray-700",children:"Quick Report"}),n("span",{className:"text-xs text-gray-500",children:"(won't investigate locally)"})]}),l("div",{className:"mb-4",children:[n("label",{htmlFor:"email",className:"block text-sm font-medium text-gray-700 mb-2",children:"Your email"}),n("input",{id:"email",type:"email",value:c,onChange:M=>d(M.target.value),placeholder:"you@example.com",className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"})]}),l("div",{className:"mb-4 p-3 bg-amber-50 rounded-lg border border-amber-200 flex gap-2",children:[n(Dn,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#D97706"}}),l("div",{className:"text-xs text-amber-800",children:[n("p",{className:"font-medium mb-1",children:"Source code will be uploaded"}),n("p",{children:"This report includes your project source code, git history, and CodeYam logs. Only submit if you're comfortable sharing this with the CodeYam team."})]})]}),b&&n("div",{className:"mb-4 text-center",children:n("p",{className:"text-sm text-gray-600",children:v.formData?"Uploading report...":"Creating archive..."})}),y&&l("div",{className:"mb-4 p-3 bg-red-50 rounded-lg border border-red-200 flex gap-2",children:[n(Dn,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#DC2626"}}),l("div",{className:"text-xs text-red-800",children:[n("p",{className:"font-medium mb-1",children:"Upload failed"}),n("p",{children:y})]})]}),l("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:E,disabled:b,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-300 transition-colors disabled:opacity-50 cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>void N(),disabled:b,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed flex items-center gap-2 cursor-pointer",children:b?l(le,{children:[n("div",{className:"animate-spin",children:n(rs,{size:16,style:{strokeWidth:1.5}})}),"Submitting..."]}):y?"Try Again":"Submit Report"})]})]})]})]})}):null}const cs={source:"navbar"},da=aa(void 0);function ec({children:e}){const[t,r]=_(cs),a=ie(o=>{r(o)},[]),s=ie(()=>{r(cs)},[]);return n(da.Provider,{value:{contextData:t,setContextData:a,resetContextData:s},children:e})}function tt(e){const t=tr(da),r=Ne(t);ee(()=>{if(r.current)return r.current.setContextData(e),()=>{var a;(a=r.current)==null||a.resetContextData()}},[e.source,e.entitySha,e.scenarioId,e.analysisId,e.entityName,e.entityType,e.scenarioName,e.errorMessage])}function tc(){const e=tr(da),t=er();return e?{source:e.contextData.source,entitySha:e.contextData.entitySha,scenarioId:e.contextData.scenarioId,analysisId:e.contextData.analysisId,currentUrl:t.pathname,entityName:e.contextData.entityName,entityType:e.contextData.entityType,scenarioName:e.contextData.scenarioName,errorMessage:e.contextData.errorMessage}:{source:"navbar",currentUrl:t.pathname}}function nc({labs:e,isAdmin:t}){var k;const r=er(),a=It(),[s,o]=_(),[i,c]=_(!1),[d,m]=_(!1),[u,h]=_(null),p=Ee();ee(()=>{p.state==="idle"&&!p.data&&p.load("/api/generate-report")},[p]);const f=((k=p.data)==null?void 0:k.defaultEmail)||"",g={width:"20px",height:"20px",strokeWidth:1.5},y=(e==null?void 0:e.simulations)??!1,x=[{id:"dashboard",icon:n(Hi,{style:g}),link:"/",name:"Dashboard",hidden:!y},{id:"simulations",icon:l("svg",{width:"20",height:"20",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:g,children:[n("path",{d:"M9 12.75V15.75",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6 15.75H12",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6.75 12.7498L11.325 8.17483C11.6067 7.89873 11.9858 7.7447 12.3803 7.7461C12.7747 7.74751 13.1528 7.90423 13.4325 8.18233L16.5 11.2498",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6 8.25C6.82843 8.25 7.5 7.57843 7.5 6.75C7.5 5.92157 6.82843 5.25 6 5.25C5.17157 5.25 4.5 5.92157 4.5 6.75C4.5 7.57843 5.17157 8.25 6 8.25Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M15 2.25H3C2.17157 2.25 1.5 2.92157 1.5 3.75V11.25C1.5 12.0784 2.17157 12.75 3 12.75H15C15.8284 12.75 16.5 12.0784 16.5 11.25V3.75C16.5 2.92157 15.8284 2.25 15 2.25Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]}),link:"/simulations",name:"Simulations",hidden:!y},{id:"git",icon:n(as,{style:g}),link:"/git",name:"Git",hidden:!y},{id:"files",icon:n(Vi,{style:g}),link:"/files",name:"Files",hidden:!y},{id:"activity",icon:n(Ji,{style:g}),link:"/activity",name:"Activity",hidden:!y},{id:"memory",icon:n(Ln,{style:g}),link:"/memory",name:"Memory"},{id:"labs",icon:n(Gi,{style:g}),link:"/labs",name:"Labs"},{id:"settings",icon:n(qi,{style:g}),link:"/settings",name:"Settings"},{id:"commits",icon:n(as,{style:g}),link:"/commits",name:"Commits",hidden:!0},{id:"pages",icon:n(Ki,{style:g}),link:"/pages",name:"Pages",hidden:!0},{id:"components",icon:n(Qi,{style:g}),link:"/components",name:"Components",hidden:!0}],v=ie(N=>{const E=x.find(S=>S.id===N);E!=null&&E.link&&a(E.link),o(S=>S===N?void 0:N)},[x,a]);ee(()=>{const N={dashboard:["/","/home"],git:["git"],commits:["commits"],simulations:["simulations"],activity:["activity"],memory:["memory","agent-transcripts"],files:["files"],labs:["labs"],settings:["settings"],pages:["pages"],components:["components"]};for(const[E,S]of Object.entries(N))if(S.some(M=>M==="/"?r.pathname==="/":r.pathname.includes(M))){o(E);return}o(void 0)},[r]);const b=async()=>{m(!0);try{const{default:N}=await import("html2canvas-pro"),S=(await N(document.body)).toDataURL("image/jpeg",.8);h(S),c(!0)}catch(N){console.error("Screenshot capture failed:",N),c(!0)}finally{m(!1)}},w=()=>{c(!1),h(null)},C=tc();return l(le,{children:[l("div",{id:"sidebar",className:"sticky top-0 w-full h-screen bg-[#051C22] flex flex-col justify-between py-3",children:[l("div",{className:"w-full flex flex-col items-center",children:[n("div",{className:"py-3 mt-2 mb-4",children:n(se,{to:"/",className:"flex items-center justify-center cursor-pointer",children:n("img",{src:so,alt:"CodeYam",className:"h-6"})})}),x.filter(N=>!N.hidden).map(N=>n(Ql,{id:N.id,selected:N.id===s,onClick:v,icon:N.icon,name:N.name},`sidebar-button-${N.id}`))]}),t&&n("div",{className:"w-full flex flex-col items-center pb-2",children:l("button",{onClick:()=>void b(),disabled:d,className:"w-full px-1.5 py-2 flex flex-col items-center justify-center gap-1 text-[#568B94] hover:text-[#CBF3FA] transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-wait",children:[n("div",{className:"w-9 h-9 rounded-lg flex items-center justify-center",children:d?n(Xe,{style:{width:"20px",height:"20px",strokeWidth:1.5},className:"animate-spin"}):n(Ks,{style:{width:"20px",height:"20px",strokeWidth:1.5}})}),n("span",{className:"text-[9px] font-normal text-center leading-tight whitespace-pre-line",children:d?"Capturing...":`Report
6
- Bug`})]})})]}),i&&n(oo,{isOpen:!0,onClose:w,context:C,defaultEmail:f,screenshotDataUrl:u??void 0})]})}const io=aa(void 0);function rc({children:e}){const[t,r]=_([]),a=ie((o,i="info",c=5e3)=>{const m={id:`toast-${Date.now()}-${Math.random()}`,message:o,type:i,duration:c};r(u=>[...u,m])},[]),s=ie(o=>{r(i=>i.filter(c=>c.id!==o))},[]);return n(io.Provider,{value:{toasts:t,showToast:a,closeToast:s},children:e})}function ua(){const e=tr(io);if(!e)throw new Error("useToast must be used within a ToastProvider");return e}function ac({toast:e,onClose:t}){ee(()=>{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 l("div",{className:`flex items-center gap-3 px-4 py-3 rounded-lg border-2 shadow-lg min-w-[320px] max-w-[500px] animate-[slideIn_0.3s_ease-out] ${{success:"bg-emerald-50 border-emerald-200 text-emerald-900",error:"bg-red-50 border-red-200 text-red-900",info:"bg-blue-50 border-blue-200 text-blue-900",warning:"bg-amber-50 border-amber-200 text-amber-900"}[e.type]}`,children:[n("span",{className:"text-2xl",children:r[e.type]}),n("p",{className:"flex-1 text-sm font-medium m-0",children:e.message}),n("button",{onClick:()=>t(e.id),className:"text-gray-500 hover:text-gray-700 text-xl leading-none bg-transparent border-none cursor-pointer p-0 w-6 h-6 flex items-center justify-center rounded transition-colors hover:bg-black/10",children:"×"})]})}function sc({toasts:e,onClose:t}){return e.length===0?null:l("div",{className:"fixed top-4 right-4 z-10000 flex flex-col gap-2",children:[n("style",{children:`
7
- @keyframes slideIn {
8
- from {
9
- transform: translateX(400px);
10
- opacity: 0;
11
- }
12
- to {
13
- transform: translateX(0);
14
- opacity: 1;
15
- }
16
- }
17
- `}),e.map(r=>n(ac,{toast:r,onClose:t},r.id))]})}function bt(e,t){const[r,a]=_(""),[s,o]=_(!1),[i,c]=_(null),[d,m]=_(!1);ee(()=>{t&&(m(!1),o(!1),c(null))},[t]),ee(()=>{if(!e||!t){t||a("");return}const h=async()=>{try{const f=await fetch(`/api/logs/${e}`);if(f.ok){const y=(await f.text()).trim().split(`
18
- `).filter(b=>b.length>0);if(y.length<3){o(!1),m(!1),c(null),a("");return}const x=y.filter(b=>b.includes("CodeYam Log Level 1"));if(x.length>0){const b=x[x.length-1];a(b.replace(/.*CodeYam Log Level 1: /,""))}const v=y.find(b=>b.includes("$$INTERACTIVE_SERVER_URL$$:"));if(v){const b=v.split("$$INTERACTIVE_SERVER_URL$$:")[1].trim();c(b),m(!0)}y.some(b=>b.includes("CodeYam: Exiting start.js"))&&o(!0)}}catch{}};h().catch(()=>{});const p=setInterval(()=>{h().catch(()=>{})},2e3);return()=>clearInterval(p)},[e,t]);const u=ie(()=>{a(""),o(!1),c(null),m(!1)},[]);return{lastLine:r,interactiveUrl:i,isCompleted:s,resetLogs:u}}function gt({projectSlug:e,onClose:t}){const[r,a]=_("Loading logs..."),[s,o]=_(!0),[i,c]=_(!0),[d,m]=_("all"),u=Ne(null);return ee(()=>{const h=async()=>{try{const p=await fetch(`/api/logs/${e}`);if(p.ok){const f=await p.text();if(d==="all")a(f);else{const g=f.trim().split(`
19
- `).filter(y=>{if(y.length===0)return!1;const x=y.match(/^.*CodeYam Log Level (\d+):/);return!!x&&Number(x[1])<=d});a(g.map(y=>y.replace(/^.*CodeYam Log Level \d+:\s*/,"")).join(`
20
- `))}i&&u.current&&setTimeout(()=>{var g;(g=u.current)==null||g.scrollTo({top:u.current.scrollHeight,behavior:"smooth"})},100)}else a(`Error: ${p.status} - ${await p.text()}`)}catch(p){a(`Error fetching logs: ${p.message}`)}};if(h().catch(()=>{}),s){const p=setInterval(()=>{h().catch(()=>{})},2e3);return()=>clearInterval(p)}},[e,s,i,d]),ee(()=>{const h=p=>{p.key==="Escape"&&t()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[t]),n("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-9999 p-5",onClick:t,children:l("div",{className:"bg-[#1e1e1e] rounded-lg shadow-2xl flex flex-col max-w-[1200px] w-full max-h-[90vh] overflow-hidden",onClick:h=>h.stopPropagation(),children:[l("div",{className:"flex justify-between items-center px-5 py-4 border-b border-[#333] bg-[#252525]",children:[l("h3",{className:"m-0 text-lg font-semibold text-white",children:["Analysis Logs - ",e]}),l("div",{className:"flex items-center gap-4",children:[l("label",{className:"flex items-center gap-2 text-sm text-[#ccc] select-none",children:[n("span",{children:"Log Level:"}),l("select",{value:d,onChange:h=>m(h.target.value==="all"?"all":Number(h.target.value)),className:"bg-[#333] text-white border border-[#555] rounded px-2 py-1 text-sm cursor-pointer outline-none transition-all hover:border-[#777] hover:bg-[#3a3a3a] focus:border-blue-600",children:[n("option",{value:"1",children:"1"}),n("option",{value:"2",children:"2"}),n("option",{value:"3",children:"3"}),n("option",{value:"4",children:"4"}),n("option",{value:"all",children:"All"})]})]}),l("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:s,onChange:h=>o(h.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-refresh"})]}),l("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:i,onChange:h=>c(h.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-scroll"})]}),n("button",{onClick:t,className:"bg-transparent border-none text-[#999] text-2xl cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-all hover:bg-[#333] hover:text-white",title:"Close (Esc)",children:"✕"})]})]}),n("pre",{className:"flex-1 m-0 px-5 py-4 overflow-auto font-mono text-[13px] leading-relaxed text-[#d4d4d4] bg-[#1e1e1e] whitespace-pre-wrap wrap-break-word scrollbar-thin scrollbar-thumb-[#424242] scrollbar-track-[#1e1e1e] hover:scrollbar-thumb-[#4f4f4f]",ref:u,children:r})]})})}function Ve({type:e,size:t="default"}){const r={visual:{iconColor:"#7c3aed",bgColor:"bg-purple-100",bgHex:"#f3e8ff"},library:{iconColor:"#06b6d5",bgColor:"bg-[#e6fbff]",bgHex:"#e6fbff"},type:{iconColor:"#db2627",bgColor:"bg-[#ffe1e1]",bgHex:"#ffe1e1"},data:{iconColor:"#2563eb",bgColor:"bg-blue-100",bgHex:"#dbeafe"},index:{iconColor:"#ea580c",bgColor:"bg-orange-100",bgHex:"#ffedd5"},functionCall:{iconColor:"#7c3aed",bgColor:"bg-purple-100",bgHex:"#f3e8ff"},class:{iconColor:"#059669",bgColor:"bg-emerald-100",bgHex:"#d1fae5"},method:{iconColor:"#0891b2",bgColor:"bg-cyan-100",bgHex:"#cffafe"},other:{iconColor:"#6b7280",bgColor:"bg-gray-100",bgHex:"#f3f4f6"}},a=r[e]||r.other,s=t==="large"?18:14,o=t==="large"?32:18,i=()=>{switch(e){case"library":return n(Qs,{size:s,color:a.iconColor});case"visual":return n(an,{size:s,color:a.iconColor});case"type":return n(tl,{size:s,color:a.iconColor});case"data":return n(el,{size:s,color:a.iconColor});case"index":return n(Xi,{size:s,color:a.iconColor});case"functionCall":return n(os,{size:s,color:a.iconColor});case"class":return n(Zi,{size:s,color:a.iconColor});case"method":return n(os,{size:s,color:a.iconColor});case"other":return n(ss,{size:s,color:a.iconColor});default:return n(ss,{size:s,color:a.iconColor})}};return n("span",{className:`flex items-center justify-center rounded ${a.bgColor}`,style:{width:`${o}px`,height:`${o}px`},children:i()})}function lo({filePath:e,maxLength:t=60,className:r,style:a}){const o=((c,d)=>{if(c.length<=d)return c;const m="...",u=d-m.length,h=Math.ceil(u*.4),p=Math.floor(u*.6),f=c.slice(0,h),g=c.slice(-p),y=f.lastIndexOf("/"),x=g.indexOf("/"),v=y>h*.5?f.slice(0,y+1):f,b=x!==-1&&x<p*.5?g.slice(x):g;return`${v}${m}${b}`})(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 _r({entity:e,nameSize:t="11px",pathSize:r="10px",pathMaxLength:a=50,showScenarioCount:s=!1,scenarioCount:o=0,additionalContent:i}){return l("div",{className:"flex flex-col gap-1",children:[l("div",{className:"flex items-center gap-1",children:[n(Ve,{type:e.entityType||"other"}),l(se,{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(lo,{filePath:e.filePath,maxLength:a,style:{fontSize:r,color:"#8E8E8E"}})]}),i]})}const Pr={fontSize:"9px",color:"#005C75",fontStyle:"italic"};function oc({currentRun:e,projectSlug:t,currentEntities:r=[],isAnalysisStarting:a=!1,queuedJobCount:s=0,queueJobs:o=[],currentlyExecuting:i=null,historicalRuns:c=[]}){var V,U,z;const[d,m]=_(!1),[u,h]=_(!1),[p,f]=_(null),[g,y]=_(new Set),[x,v]=_(new Set),[b,w]=_(!1),C=!!i||o.length>0,k=!!i,N=(i==null?void 0:i.entities)||r,E=!!(e!=null&&e.analysisCompletedAt),S=(e==null?void 0:e.readyToBeCaptured)??0,M=(e==null?void 0:e.capturesCompleted)??0;e!=null&&e.captureCompletedAt||E&&(S===0||M>=S);const F=(e==null?void 0:e.currentEntityShas)&&e.currentEntityShas.length>0,L=C,{lastLine:P}=bt(t,L),T=k||o.length>0,$=new Set(((V=i==null?void 0:i.entities)==null?void 0:V.map(Y=>Y.sha))||[]),I=c.filter(Y=>!(Y.currentEntityShas||[]).some(A=>$.has(A))),J=(()=>{const R=Date.now()-1440*60*1e3;if(e!=null&&e.createdAt&&F){const A=e.analysisCompletedAt||e.createdAt;if(new Date(A).getTime()>R)return!0}if(I.length>0){const A=I[0],G=A.analysisCompletedAt||A.archivedAt||A.createdAt;if(G&&new Date(G).getTime()>R)return!0}return!1})();return ee(()=>{const Y=(i==null?void 0:i.id)||null;C&&!u&&Y!==p&&h(!0),!C&&p!==null&&f(null)},[C,i==null?void 0:i.id,u,p]),l(le,{children:[l("div",{className:`fixed bottom-4 right-4 z-9998 bg-white rounded shadow-lg border-2 border-primary-100 transition-all duration-200 ${u?"min-w-[350px] max-w-[500px]":"w-auto"}`,children:[!u&&l("div",{onClick:()=>{h(!0),f(null)},className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-gray-50 transition-colors",title:"Click to expand",children:[T?n(Xe,{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(Er,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:T?"Analyzing...":"Activity: No Activity Yet"}),T&&n("button",{onClick:Y=>{Y.stopPropagation(),m(!0)},className:"ml-auto px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),u&&l("div",{children:[l("div",{className:"flex items-center justify-between px-3 py-2",children:[l("div",{className:"flex items-center gap-2",children:[T?n(Xe,{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(Er,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:T?"Analyzing...":"Activity"})]}),l("div",{className:"flex items-center gap-2",children:[n("button",{onClick:()=>m(!0),className:"px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"}),n("button",{onClick:()=>{h(!1),f((i==null?void 0:i.id)||null)},className:"p-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC"},title:"Collapse","aria-label":"Collapse",children:n(Qe,{size:16,style:{color:"#646464"}})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),l("div",{className:"px-3 pt-2 pb-3 space-y-3",children:[T&&i&&l("div",{children:[l("div",{className:"flex items-center gap-1.5 mb-2",children:[n(Er,{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?l("div",{className:"space-y-1.5",children:[(b?N:N.slice(0,3)).map(Y=>n(_r,{entity:Y,nameSize:"11px",pathSize:"10px",pathMaxLength:150},Y.sha)),N.length>3&&n("button",{onClick:()=>w(Y=>!Y),className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:Pr,"aria-label":b?"Show fewer entities":`Show ${N.length-3} more entities`,children:b?"Show less":`+${N.length-3} more`}),P&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:P})]}):l("div",{children:[i.entityNames&&i.entityNames.length>0?l("div",{className:"space-y-0.5",children:[i.entityNames.slice(0,5).map((Y,R)=>n("div",{style:{fontSize:"11px",color:"#343434"},children:Y},R)),i.entityNames.length>5&&l("div",{className:"italic",style:{fontSize:"10px",color:"#666"},children:["+",i.entityNames.length-5," ","more"]})]}):l("div",{style:{fontSize:"11px",color:"#343434"},children:["Analyzing"," ",((U=i.entityShas)==null?void 0:U.length)||0," ",((z=i.entityShas)==null?void 0:z.length)===1?"entity":"entities","..."]}),P&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:P})]})})]}),o.length>0&&l("div",{children:[l("div",{className:"flex items-center gap-1.5 mb-2",children:[n(nl,{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(Y=>{var G,B;const R=g.has(Y.id),A=R?Y.entities:Y.entities.slice(0,3);return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:Y.entities.length>0?l("div",{className:"space-y-1.5",children:[A.map(H=>n(_r,{entity:H,nameSize:"10px",pathSize:"9px",pathMaxLength:120},H.sha)),Y.entities.length>3&&n("button",{onClick:()=>{y(H=>{const re=new Set(H);return re.has(Y.id)?re.delete(Y.id):re.add(Y.id),re})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:Pr,"aria-label":R?"Show fewer entities":`Show ${Y.entities.length-3} more entities`,children:R?"Show less":`+${Y.entities.length-3} more`})]}):l("div",{style:{fontSize:"10px",color:"#343434"},children:[Y.type==="analysis"&&n(le,{children:Y.entityNames&&Y.entityNames.length>0?l("div",{className:"space-y-0.5",children:[Y.entityNames.slice(0,5).map((H,re)=>n("div",{children:H},re)),Y.entityNames.length>5&&l("div",{className:"italic",children:["+",Y.entityNames.length-5," more"]})]}):`Analyzing ${((G=Y.entityShas)==null?void 0:G.length)||0} ${((B=Y.entityShas)==null?void 0:B.length)===1?"entity":"entities"}`}),Y.type==="recapture"&&"Recapturing scenario",Y.type==="debug-setup"&&"Setting up debug environment"]})},Y.id)})})]}),J&&I.length>0&&l("div",{children:[l("div",{className:"flex items-center gap-1.5 mb-2",children:[n(sa,{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:I.slice(0,3).map((Y,R)=>{const A=Y.entities||[],G=Y.analysisCompletedAt||Y.archivedAt||Y.createdAt||"",B=(()=>{if(!G)return"";const j=Date.now()-new Date(G).getTime(),D=Math.floor(j/6e4),q=Math.floor(j/36e5);return q>0?`${q}h ago`:D>0?`${D}m ago`:"just now"})(),H=x.has(R),O=(H?A:A.slice(0,3)).map(j=>{var D,q,te;return{...j,scenarioCount:((te=(q=(D=j.analyses)==null?void 0:D[0])==null?void 0:q.scenarios)==null?void 0:te.length)||0}});return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:A.length>0&&l("div",{className:"space-y-1.5",children:[O.map((j,D)=>l("div",{className:"flex items-start justify-between gap-2",children:[n("div",{className:"flex-1 min-w-0",children:n(_r,{entity:j,nameSize:"10px",pathSize:"9px",pathMaxLength:100,showScenarioCount:!0,scenarioCount:j.scenarioCount})}),D===0&&B&&n("div",{style:{fontSize:"9px",color:"#8E8E8E",whiteSpace:"nowrap",paddingTop:"2px"},children:B})]},j.sha)),A.length>3&&n("button",{onClick:()=>{v(j=>{const D=new Set(j);return D.has(R)?D.delete(R):D.add(R),D})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:Pr,"aria-label":H?"Show fewer entities":`Show ${A.length-3} more entities`,children:H?"Show less":`+${A.length-3} more`})]})},R)})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),n("div",{className:"px-3 pb-2",children:n(se,{to:"/activity",className:"text-xs font-medium hover:underline cursor-pointer",style:{color:"#005C75"},children:"View All Activity →"})})]})]}),d&&t&&n(gt,{projectSlug:t,onClose:()=>m(!1)})]})}function Je(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r===null?void 0:r]))}function mn(e){const{file_id:t,project_id:r,commit_id:a,file_path:s,entity_type:o,entity_branches:i,analyses:c,commit:d,created_at:m,updated_at:u,...h}=e,p=(i??[]).map(y=>y.branch_id),f=c?c.map(lt):void 0,g=d?Tt(d):void 0;return Je({...h,fileId:t,projectId:r,commitId:a,filePath:s,entityType:o,commit:g,analyses:f,branchIds:p,createdAt:m,updatedAt:u})}function ma(e){return Je({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 ha(e){const{branches:t,files:r,analyzed_at:a,content_changed_at:s,created_at:o,updated_at:i,github_token:c,configuration:d,team_id:m,...u}=e;return Je({...u,branches:t?t.map(Ot):void 0,files:r?r.map(ma):void 0,analyzedAt:a,contentChangedAt:s,createdAt:o,updatedAt:i})}function ic(e){const{id:t,project_id:r,user_id:a,scenario_id:s,thumbs_up:o,user:i}=e,c=i?{username:i.github_username,avatarUrl:i.github_user.avatar_url}:void 0;return Je({id:t,projectId:r,userId:a,scenarioId:s,thumbsUp:!!o,user:c})}function lc(e){const{id:t,project_id:r,user_id:a,scenario_id:s,text:o,created_at:i,updated_at:c,user:d}=e,m=d?{username:d.github_username,avatarUrl:d.github_user.avatar_url}:void 0;return Je({id:t,projectId:r,userId:a,scenarioId:s,text:o,createdAt:i,updatedAt:c,user:m})}function co(e){const{project_id:t,analysis_id:r,previous_version_id:a,analysis:s,user_scenarios:o,scenario_comments:i,approved:c,...d}=e,m=s?lt(s):void 0,u=o?o.map(ic):void 0,h=i?i.map(lc):void 0;return Je({...d,projectId:t,analysisId:r,previousVersionId:a,analysis:m,userScenarios:u,comments:h})}function cc(e){return Je({id:e.id,analysisId:e.analysis_id,entitySha:e.entity_sha,branchId:e.branch_id,active:!!e.active,analysis:e.analysis?lt(e.analysis):void 0,entity:e.entity?mn(e.entity):void 0,branch:e.branch?Ot(e.branch):void 0,createdAt:e.created_at})}function lt(e){const{project_id:t,commit_id:r,file_id:a,file_path:s,entity_sha:o,entity_type:i,entity_name:c,previous_analysis_id:d,file:m,entity:u,commit:h,project:p,scenarios:f,analysis_branches:g,dependency_analyzed_tree_sha:y,analyzed_tree_sha:x,branch_commit_sha:v,committed_at:b,completed_at:w,created_at:C,updated_at:k,indirect:N,...E}=e,S=u?mn(u):void 0,M=m?ma(m):void 0,F=p?ha(p):void 0,L=h?Tt(h):void 0,P=f?f.map(co):void 0,T=g?g.map(cc):void 0,$=T?T.map(I=>I.branch):void 0;return Je({...E,projectId:t,commitId:r,fileId:a,filePath:s,entitySha:o,entityType:i,entityName:c,previousAnalysisId:d,entity:S,file:M,commit:L,project:F,scenarios:P,analysisBranches:T,branches:$,dependencyAnalyzedTreeSha:y,analyzedTreeSha:x,branchCommitSha:v,committedAt:b,completedAt:w,createdAt:C,updatedAt:k,indirect:!!N})}function pa(e){return Je({id:e.id,commitId:e.commit_id,branchId:e.branch_id,active:!!e.active,commit:e.commit?Tt(e.commit):void 0,branch:e.branch?Ot(e.branch):void 0})}function dc(e){const{project_id:t,commit_id:r,created_at:a,updated_at:s,success:o,...i}=e;return Je({...i,projectId:t,commitId:r,createdAt:a,updatedAt:s,success:!!o})}function Tt(e){const{project_id:t,branch_id:r,branch:a,background_jobs:s,merged_branch_id:o,mergedBranch:i,ai_message:c,html_url:d,author:m,analyses:u,entities:h,commit_branches:p,committed_at:f,analyzed_at:g,...y}=e,x=a?Ot(a):void 0,v=i?Ot(i):void 0,b=(s==null?void 0:s.length)>0?dc(s[s.length-1]):void 0,w=(u??[]).map(lt),C=(h??[]).map(mn),k=(p==null?void 0:p.length)>0?p.map(pa):void 0;return m&&(m.username=m.preferredUsername??m.username),Je({...y,projectId:t,branchId:r,branch:x,backgroundJob:b,mergedBranchId:o,mergedBranch:v,aiMessage:c,htmlUrl:d,author:m,analyses:w,entities:C,commitBranches:k,committedAt:f,analyzedAt:g})}function Ot(e){const{project_id:t,content_changed_at:r,commits:a,analysis_branches:s,active_at:o,created_at:i,updated_at:c,primary:d,...m}=e,u=a?a.map(Tt):void 0,h=s?s.flatMap(p=>lt(p.analysis)):void 0;return Je({...m,projectId:t,contentChangedAt:r,commits:u,analyses:h,activeAt:o,createdAt:i,updatedAt:c,primary:!!d})}var Xn;class uc{constructor(){ns(this,Xn,new mc)}transformQuery(t){return ts(this,Xn).transformNode(t.node)}transformResult(t){return Promise.resolve(t.result)}}Xn=new WeakMap;class mc extends Cl{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 X=()=>null,hc={analyzed_at:X(),configuration:X(),content_changed_at:X(),created_at:X(),description:X(),github_token:X(),id:X(),metadata:X(),name:X(),path:X(),slug:X(),team_id:X(),updated_at:X()},pc=Object.keys(hc),fc={active:X(),analysis_id:X(),branch_id:X(),created_at:X(),entity_sha:X(),id:X()},gc=Object.keys(fc),yc={active_at:X(),content_changed_at:X(),created_at:X(),id:X(),metadata:X(),name:X(),primary:X(),project_id:X(),ref:X(),sha:X(),updated_at:X()},uo=Object.keys(yc),xc={ai_message:X(),analyzed_at:X(),author_github_username:X(),branch_id:X(),committed_at:X(),created_at:X(),files:X(),html_url:X(),id:X(),merged_branch_id:X(),message:X(),metadata:X(),project_id:X(),sha:X(),title:X(),url:X()},mo=Object.keys(xc);mo.filter(e=>e!=="files");const bc={commit_id:X(),created_at:X(),description:X(),documentation:X(),entity_type:X(),file_id:X(),file_path:X(),metadata:X(),name:X(),project_id:X(),quality:X(),sha:X(),updated_at:X()},ho=Object.keys(bc),vc={active:X(),branch_id:X(),entity_sha:X()},wc=Object.keys(vc),Cc={created_at:X(),deleted:X(),id:X(),metadata:X(),name:X(),path:X(),project_id:X(),updated_at:X()},Nc=Object.keys(Cc),Sc={analysis_id:X(),approved:X(),created_at:X(),description:X(),id:X(),metadata:X(),name:X(),previous_version_id:X(),project_id:X()},Yn=Object.keys(Sc),kc=!!jt("ENABLE_QUERY_LOGGING"),Ec=!!jt("ENABLE_QUERY_ERROR_LOGGING");jt("USE_LOCAL_POSTGRESQL_FOR_TESTING");let wn;function Ae(){if(!wn){const e=fo();if(e==="sqlite")wn=Ac();else if(e==="postgresql")wn=_c();else throw new Error(`Unknown database type: ${e}`)}return wn}function Ac(e){if(e||(e=jt("SQLITE_PATH")),e===":memory:"||e==="memory")throw new Error("In-memory SQLite not supported in getDatabase(). Use getDatabaseForTesting() instead.");const t=K.existsSync(e),r=Z.dirname(e);if(!K.existsSync(r))K.mkdirSync(r,{recursive:!0,mode:493});else try{K.chmodSync(r,493)}catch(s){console.warn(`Warning: Could not set permissions on database directory: ${s.message}`)}const a=new bl(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 no({dialect:new Sl({database:a}),plugins:[new Nl,new uc],log:po})}function _c(){const e=Mc();console.log(`CodeYam: Using PostgreSQL database at: ${e}`);const t=new vl({connectionString:e,max:3,idleTimeoutMillis:1e4});return t.on("error",(r,a)=>{console.error("CodeYam: Unexpected error on idle PostgreSQL client",r)}),new no({dialect:new kl({pool:t}),log:po})}let Mr=null;function $t(){return Mr||(Mr=Pc(fo())),Mr}function po(e){e.level==="error"?Ec&&console.error("Query failed : ",{durationMs:e.queryDurationMillis,error:e.error,sql:e.query.sql,params:e.query.parameters}):kc&&console.log("Query executed : ",{durationMs:e.queryDurationMillis,sql:e.query.sql,params:e.query.parameters})}function Pc(e){if(e==="sqlite")return El;if(e==="postgresql")return Al;throw new Error(`Unknown database type: ${e}`)}function fo(){if(jt("SQLITE_PATH"))return"sqlite";if(jt("POSTGRESQL_URL"))return"postgresql";throw new Error("No database configuration found. Set SQLITE_PATH for SQLite or POSTGRESQL_URL for PostgreSQL")}function Mc(){const e=jt("POSTGRESQL_URL");if(!e)throw new Error("No PostgreSQL connection string found. Set POSTGRESQL_URL environment variable.");return e}function jt(e){var t;return typeof window<"u"?(t=window.env)==null?void 0:t[e]:process.env[e]}var hn=(e=>(e.Remix="Remix",e.CodeYam="CodeYam",e.CRA="CRA",e.Next="Next",e.NextPages="NextPages",e.Unknown="Unknown",e))(hn||{});const or="Default Scenario";let Tc="<main>";function jc(){return Tc}function ds(e,...t){we(`CodeYam Log Level ${e}: ${t[0]}`,...t.slice(1))}function we(...e){const t=jc(),r=e.map(s=>{if(s)return typeof s=="string"?s:s instanceof Error?`${s.name}: ${s.message}
21
- ${s.stack}`:typeof s=="object"?Ic(s):String(s)}).filter(Boolean).join(`
22
- `),a=`${t} ${r}`;if(!process.env.CODEYAM_ECS_TASK_ARN){console.log(a+`
23
- `);return}console.log(a.replace(/\n/g,"\r"))}function Ic(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(c=>{const d=r(c,s);return typeof c=="string"?`"${d}"`:d}).join(",")}]`:`{${Object.entries(a).map(([i,c])=>{let d;return typeof c>"u"?null:(typeof c=="function"?d=`"(function: ${c.name||"anonymous"})"`:c instanceof Date?d=`"${c.toISOString()}"`:typeof c=="object"&&c!==null?d=r(c,s):typeof c=="string"?d=`"${c.replace(/"/g,'\\"')}"`:d=JSON.stringify(c),`"${i.replace(/"/g,'\\"')}":${d}`)}).filter(Boolean).join(",")}}`)}try{return JSON.stringify(e,null,t)}catch(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 Bn(e,t){try{let r=function(o){var i,c;if(je.isFunctionDeclaration(o)&&Kt(o)){const d=((i=o.name)==null?void 0:i.text)||"default",m=o.getText(a),u=Tr(o);s.push({name:d,code:m,sha:St(t,d,m),entityType:"function",isDefault:u})}else if(je.isClassDeclaration(o)&&Kt(o)){const d=((c=o.name)==null?void 0:c.text)||"default",m=o.getText(a),u=Tr(o),h=m.includes("React.")||m.includes("jsx")||m.includes("tsx");s.push({name:d,code:m,sha:St(t,d,m),entityType:h?"component":"class",isDefault:u})}else if(je.isInterfaceDeclaration(o)&&Kt(o)){const d=o.name.text,m=o.getText(a);s.push({name:d,code:m,sha:St(t,d,m),entityType:"interface",isDefault:!1})}else if(je.isTypeAliasDeclaration(o)&&Kt(o)){const d=o.name.text,m=o.getText(a);s.push({name:d,code:m,sha:St(t,d,m),entityType:"type",isDefault:!1})}else if(je.isVariableStatement(o)&&Kt(o)){const d=Tr(o);o.declarationList.declarations.forEach(m=>{var u;if(je.isIdentifier(m.name)){const h=m.name.text,p=o.getText(a),f=((u=m.initializer)==null?void 0:u.getText(a))||"",g=(t.endsWith(".tsx")||t.endsWith(".jsx"))&&f.includes("=>")&&(f.includes("<")||f.includes("React."));s.push({name:h,code:p,sha:St(t,h,p),entityType:g?"component":"variable",isDefault:d})}})}else if(je.isExportAssignment(o)){const d=o.getText(a);s.push({name:"default",code:d,sha:St(t,"default",d),entityType:"unknown",isDefault:!0})}else if(je.isExportDeclaration(o)&&o.exportClause&&je.isNamedExports(o.exportClause)){const d=o.getText(a);for(const m of o.exportClause.elements){const u=m.name.text;s.push({name:u,code:d,sha:St(t,u,d),entityType:"unknown",isDefault:!1})}}je.forEachChild(o,r)};const a=je.createSourceFile(t,e,je.ScriptTarget.Latest,!0),s=[];return r(a),s}catch(r){return console.error(`Failed to extract entities from ${t}:`,r),[]}}function Kt(e){if(!je.canHaveModifiers(e))return!1;const t=je.getModifiers(e);return t?t.some(r=>r.kind===je.SyntaxKind.ExportKeyword):!1}function Tr(e){if(!je.canHaveModifiers(e))return!1;const t=je.getModifiers(e);return t?t.some(r=>r.kind===je.SyntaxKind.DefaultKeyword):!1}function St(e,t,r){const a=nr.createHash("sha256");return a.update(`${e}:${t}:${r}`),a.digest("hex").substring(0,40)}function $c(e){var m;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=((m=o.args)==null?void 0:m.map(u=>u.replace(/\$PORT/g,String(r))))??[],c=[];for(const u of a)if(u.key&&u.value!==void 0){const h=String(u.value).replace(/'/g,"'\\''");c.push(`${u.key}='${h}'`)}if(o.env)for(const[u,h]of Object.entries(o.env)){const f=String(h).replace(/\$PORT/g,String(r)).replace(/'/g,"'\\''");c.push(`${u}='${f}'`)}const d=c.length>0?c.join(" ")+" ":"";return o.command==="sh"&&i[0]==="-c"&&i[1]?`${d}sh -c "${i[1]}"`:`${d}${o.command} ${i.join(" ")}`}function Rc(e,t){if(!t||t.length===0)return;if(t.length===1)return t[0];const r=Z.normalize(e),a=[...t].sort((s,o)=>{var i,c;return(((i=o.path)==null?void 0:i.length)??0)-(((c=s.path)==null?void 0:c.length)??0)});for(const s of a){const o=Z.normalize(s.path??".");if(o==="."||r.startsWith(o+Z.sep)||r===o)return s}return t[0]}function Dc(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=Rc(t,r);if(!i)throw new Error("Could not find webapp for file path: "+t);const c=$c({webapp:i,port:s,environmentVariables:a,packageManager:o});return{webapp:i,webappPath:i.path??".",framework:i.framework,packageManager:i.packageManager??o,startCommand:c,url:`http://localhost:${s}/static/codeyam-sample`}}function ir(e,t,r=[]){const a=Array.isArray(t)?t:[t];return s=>s.columns(a).doUpdateSet(o=>{const i=Object.keys(e).filter(c=>c!==t&&!r.includes(c));return Object.fromEntries(i.map(c=>[c,o.ref(`excluded.${c}`)]))})}function Lc(e){const{jsonObjectFrom:t}=$t();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 Fc({ids:e,analysisId:t}){const r=Ae();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 we("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 we("CodeYam Error: Database error deleting scenarios",a,{ids:e,analysisId:t}),a}}function Oc(...e){try{const t=nr.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 jr(e,t){return t.map(r=>zc(e,r))}function zc(e,t){return Ke` ${Ke.ref(e)}.${Ke.ref(t)}`.as(t)}function Yc(e,t,r){return t.map(a=>Bc(e,a,r))}function Bc(e,t,r){return Ke` ${Ke.ref(e)}.${Ke.ref(t)}`.as(`_cy_${r}:${t}`)}function Uc(e,...t){const r={};for(const[a,s]of Object.entries(e)){const o=a.match(/^_cy_(.+?):(.+)$/);if(o){const[,i,c]=o;if(t.includes(i)){r[i]||(r[i]={}),r[i][c]=s;continue}console.warn(`CodeYam Warning: Unrecognized prefix in key '${a}'`);continue}r[a]=s}return r}const Wc=50;function Hc(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 us({projectId:e,ids:t,fileIds:r,entityName:a,entityShas:s,commitIds:o,branchCommitSha:i,limit:c,excludeMetadata:d}){const m=Ae(),{jsonObjectFrom:u,jsonArrayFrom:h}=$t();let p=d?m.selectFrom("analyses").select(["analyses.id","analyses.project_id","analyses.file_id","analyses.commit_id","analyses.entity_sha","analyses.entity_name","analyses.entity_type","analyses.file_path","analyses.status","analyses.created_at","analyses.updated_at","analyses.tree_sha","analyses.analyzed_tree_sha","analyses.dependency_analyzed_tree_sha","analyses.previous_analysis_id","analyses.branch_commit_sha","analyses.indirect","analyses.committed_at","analyses.completed_at"]):m.selectFrom("analyses").selectAll("analyses");if(e&&(p=p.where("project_id","=",e)),t){if(t.length===0)return null;p=p.where("id","in",t)}if(r){if(r.length===0)return null;p=p.where("file_id","in",r)}if(o){if(o.length===0)return null;p=p.where("commit_id","in",o)}return a&&(p=p.where("entity_name","=",a)),s&&(p=p.where("entity_sha","in",s)),i&&(p=p.where("branch_commit_sha","=",i)),c&&(p=p.limit(c)),d?m.with("filtered_analyses",()=>p).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[h(f.selectFrom("scenarios").select(jr("scenarios",Yn)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),h(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")]):m.with("filtered_analyses",()=>p).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[u(f.selectFrom("entities").select(jr("entities",ho)).whereRef("entities.sha","=","filtered_analyses.entity_sha").limit(1)).as("entity"),h(f.selectFrom("scenarios").select(jr("scenarios",Yn)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),h(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")])}async function yt(e){const{ids:t,fileIds:r,entityShas:a,commitIds:s}=e;try{const i=Object.entries({id:{arr:t,key:"ids"},file_id:{arr:r,key:"fileIds"},entity_sha:{arr:a,key:"entityShas"},commit_id:{arr:s,key:"commitIds"}}).find(([d,{arr:m}])=>(m==null?void 0:m.length)>0);let c=[];if(i){const[d,{arr:m,key:u}]=i,h=Hc(m,Wc),p=[];for(let f=0;f<h.length;f++){const g=h[f],x=await us({...e,[u]:g}).execute();x&&p.push(...x)}c=p}else{const m=await us(e).execute();if(!m||m.length===0)return we("CodeYam: No analyses found",null,e),null;c=m}return c.length===0?null:c.map(lt)}catch(o){return we("CodeYam Error: Database error in loadAnalyses",o,e),null}}function Vc(e,t){const{jsonArrayFrom:r,jsonObjectFrom:a}=$t();let s=e.selectFrom("analysis_branches").select(gc).select(o=>a(o.selectFrom("branches").select(uo).whereRef("id","=","analysis_branches.branch_id")).as("branch"));return t&&(s=t(s)),r(s)}async function ct({id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:s,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:c,includeFile:d,includeProject:m,includeCommitAndBranch:u,includeScenarios:h,includeBranches:p}){const f=Ae(),g=Date.now();try{let y=f.selectFrom("analyses").selectAll("analyses");e&&(y=y.where("id","=",e)),r&&(y=y.where("project_id","=",r)),i?y=y.where("dependency_analyzed_tree_sha","=",i):c?y=y.where("analyzed_tree_sha","=",c):a&&(y=y.where("file_id","=",a)),o&&(y=y.where("entity_name","=",o)),s?y=y.where("commit_id","=",s):y=y.orderBy("created_at","desc").limit(1),t&&(y=y.innerJoin("analysis_branches","analyses.id","analysis_branches.analysis_id").where("analysis_branches.id","=",t));const{jsonObjectFrom:x,jsonArrayFrom:v}=$t();y=y.select(C=>{const k=[];return k.push(x(C.selectFrom("entities").select(ho).whereRef("entities.sha","=","analyses.entity_sha")).as("entity")),d&&k.push(x(C.selectFrom("files").select(Nc).whereRef("files.id","=","analyses.file_id")).as("file")),m&&k.push(x(C.selectFrom("projects").select(pc).whereRef("projects.id","=","analyses.project_id")).as("project")),h&&k.push(v(C.selectFrom("scenarios").select(Yn).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")),p&&k.push(Vc(C,N=>N.whereRef("analysis_branches.analysis_id","=","analyses.id")).as("analysis_branches")),u&&k.push(x(C.selectFrom("commits").select(mo).select(N=>Lc(N).as("author")).whereRef("commits.id","=","analyses.commit_id")).as("commit")),k});const b=await y.executeTakeFirst(),w=Date.now()-g;if(!b)return we("CodeYam Error: Analysis not found",null,{id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:s,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:c,includeFile:d,includeProject:m,includeCommitAndBranch:u,includeScenarios:h,includeBranches:p}),null;if(w>100&&u){const C=b.commit,k=C!=null&&C.files?JSON.stringify(C.files).length:0;console.log(`CodeYam DEBUG: [CommitFilesTiming] loadAnalysis took ${w}ms (files: ${Math.round(k/1024)}KB)`,{id:b.id,entityName:b.entity_name})}return lt(b)}catch(y){return we("CodeYam Error: Database error loading analysis",y,{id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:s,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:c,includeFile:d,includeProject:m,includeCommitAndBranch:u,includeScenarios:h,includeBranches:p}),null}}async function go({projectId:e,ids:t,names:r,includeInactive:a}){const s=Ae();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(Ot)}catch(o){return we("CodeYam Error: Database error loading branches",o,{projectId:e,ids:t,names:r,includeInactive:a}),[]}}async function Jc({projectId:e,commitId:t,branchId:r,active:a,includeBranches:s}){const o=Ae();try{let i=o.selectFrom("commit_branches").selectAll("commit_branches").innerJoin("branches","commit_branches.branch_id","branches.id").$if(s,m=>m.select(Yc("branches",uo,"branch"))).where("branches.project_id","=",e);t&&(i=i.where("commit_branches.commit_id","=",t)),r&&(i=i.where("commit_branches.branch_id","=",r)),a!==void 0&&(i=i.where("commit_branches.active","=",a));const c=await i.execute();return!c||c.length===0?null:c.map(m=>Uc(m,"branch")).map(pa)}catch(i){return we("CodeYam Error: Error loading commit branches",i,{projectId:e,commitId:t,branchId:r,active:a,includeBranches:s}),null}}async function Gc(e){if(e.length===0)return new Map;const t=Ae();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 we("CodeYam Error: Loading branches for commits",r,{commitIds:e}),new Map}}async function qc(e){if(e.length===0)return new Map;const t=Ae(),{jsonObjectFrom:r,jsonArrayFrom:a}=$t();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(Yn).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")]).where("commit_id","in",e).execute(),o=new Map;return s.forEach(i=>{const c=o.get(i.commit_id)||[];c.push(i),o.set(i.commit_id,c)}),o}catch(s){return we("CodeYam Error: Loading analyses for commits",s,{commitIds:e}),new Map}}async function Kc(e){if(e.length===0)return new Map;const t=Ae();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 we("CodeYam Error: Loading entities for commits",r,{commitIds:e}),new Map}}async function Un({projectId:e,branchId:t,ids:r,shas:a,fileNames:s,limit:o=10,skipRelations:i=!1}){if(!e&&!r)throw new Error("Must provide projectId or ids");const c=Ae(),{jsonObjectFrom:d}=$t(),m=Date.now();try{let u=c.selectFrom("commits").selectAll("commits").select(b=>[d(b.selectFrom("github_users").select(["username","preferred_username as preferredUsername","avatar_url as avatarUrl"]).where("github_users.username","=",b.ref("commits.author_github_username"))).as("author")]);if(e&&(u=u.where("project_id","=",e)),r){if(r.length===0)return[];u=u.where("id","in",r)}if(a){if(a.length===0)return[];u=u.where("sha","in",a)}if(s&&s.length>0){const b=Ke.join(s.map(w=>Ke`${w}`),Ke`, `);u=u.where(Ke`
24
- EXISTS (
25
- SELECT 1
26
- FROM json_each(${Ke.ref("commits.files")}) AS f
27
- WHERE json_extract(f.value, '$.fileName') IN (${b})
28
- )
29
- `)}t&&(u=u.where("branch_id","=",t));const h=await u.orderBy("committed_at","desc").limit(o).execute(),p=Date.now()-m;if(!h||h.length===0)return[];if(p>100){const b=h.reduce((w,C)=>w+(C.files?JSON.stringify(C.files).length:0),0);console.log(`CodeYam DEBUG: [CommitFilesTiming] loadCommits took ${p}ms (${h.length} commits, totalFiles: ${Math.round(b/1024)}KB)`)}if(i)return h.map(w=>({...w,branch:void 0,mergedBranch:void 0,analyses:[],entities:[]})).map(Tt);const f=h.map(b=>b.id),[g,y,x]=await Promise.all([Gc(f),qc(f),Kc(f)]);return h.map(b=>{const w=b.branch_id?g.get(b.branch_id):void 0,C=b.merged_branch_id?g.get(b.merged_branch_id):void 0,k=y.get(b.id)||[],N=x.get(b.id)||[];return{...b,branch:w,mergedBranch:C,analyses:k,entities:N}}).map(Tt)}catch(u){return we("CodeYam Error: Database error loading commits",u,{projectId:e,branchId:t,ids:r,shas:a,limit:o}),[]}}async function ot({projectId:e,branchId:t,fileIds:r,filePaths:a,names:s,shas:o,excludeMetadata:i}){if(r&&r.length==0||a&&a.length==0||s&&s.length==0||o&&o.length==0)return[];if(o&&o.length>50){const d=[];for(let m=0;m<o.length;m+=50){const u=o.slice(m,m+50),h=await ot({projectId:e,branchId:t,fileIds:r,filePaths:a,names:s,shas:u,excludeMetadata:i});h&&d.push(...h)}return d}const c=Ae();try{const u=await(i?c.selectFrom("entities").select(["entities.project_id","entities.file_id","entities.commit_id","entities.name","entities.sha","entities.entity_type","entities.file_path","entities.description","entities.documentation","entities.quality","entities.created_at","entities.updated_at"]):c.selectFrom("entities").selectAll("entities")).$if(!!t,h=>h.innerJoin("entity_branches","entity_branches.entity_sha","entities.sha").where("entity_branches.branch_id","=",t)).$if(!!e,h=>h.where("entities.project_id","=",e)).$if(!!o,h=>h.where("entities.sha","in",o)).$if(!!a,h=>h.where("entities.file_path","in",a)).$if(!!s,h=>h.where("entities.name","in",s)).$if(!!r,h=>h.where("entities.file_id","in",r)).execute();return!u||u.length===0?(console.log("Load Entities: No entities found",{projectId:e,fileIds:r,filePaths:a,shas:o}),null):u.map(mn)}catch(d){return console.log("Load Entities: Error occurred",d,{projectId:e,fileIds:r,filePaths:a,shas:o}),null}}function Qc(e,t){const{jsonArrayFrom:r}=$t();let a=e.selectFrom("entity_branches").select(wc);return t&&(a=t(a)),r(a)}async function yo({projectId:e,sha:t}){const r=Ae();try{const a=await r.selectFrom("entities").innerJoin("files","entities.file_id","files.id").selectAll("entities").select(s=>Qc(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?mn(a):(process.env.CODEYAM_E2E_BASELINE_MODE!=="true"&&we("CodeYam Error: Load Entity: Entity not found",null,{projectId:e,sha:t}),null)}catch(a){return we("CodeYam Error: Load Entity: Database error",a,{projectId:e,sha:t}),null}}const Ir=1e3;async function xo({projectId:e,filePaths:t,fileIds:r,fileNames:a}){if(t&&t.length>50){const c=[];for(let d=0;d<t.length;d+=50){const m=t.slice(d,d+50),u=await xo({projectId:e,filePaths:m,fileIds:r,fileNames:a});u&&c.push(...u)}return c}const s=Ae(),o=[];let i=0;try{for(;;){let c=s.selectFrom("files").selectAll().where("project_id","=",e).limit(Ir).offset(i);if(t){if(t.length===0)return[];c=c.where("path","in",t)}if(r){if(r.length===0)return[];c=c.where("id","in",r)}if(a){if(a.length===0)return[];c=c.where("name","in",a)}const d=await c.execute();if(!d||d.length===0||(o.push(...d),d.length<Ir))break;i+=Ir}return o==null?void 0:o.map(ma)}catch(c){return console.log("CodeYam Error: Error loading project files in loadFiles",c),null}}async function Zc({id:e,slug:t,withBranches:r,withFiles:a,silent:s}){try{let i=Ae().selectFrom("projects").selectAll();if(e)i=i.where("id","=",e);else if(t)i=i.where("slug","=",t);else throw new Error("Either id or slug must be provided");const c=await i.executeTakeFirst();if(!c)return s||console.log("CodeYam Error: Error loading project",{id:e,slug:t,withBranches:r,withFiles:a}),null;const d=ha(c);return a&&(d.files=await xo({projectId:d.id})),r&&(d.branches=await go({projectId:d.id,includeInactive:!1})),d}catch(o){return s||console.log("CodeYam Error: Error loading project",o),null}}function Wn(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]=Wn(o,s):s!==void 0&&(r[a]=s)}return r}async function ft({commitId:e,commitSha:t,metadataUpdate:r,runStatusUpdate:a,archiveCurrentRun:s,updateCallback:o}){try{return await Ae().transaction().execute(async i=>{var u,h;const c=await i.selectFrom("commits").select(["id","metadata"]).$if(!!e,p=>p.where("id","=",e)).$if(!!t,p=>p.where("sha","=",t)).executeTakeFirst();if(!c)return we(`CodeYam Error: updateCommitMetadata(): Commit ${e} not found`),null;const d=c.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:",(u=d.currentRun)==null?void 0:u.currentEntityShas),console.log("[updateCommitMetadata] New entity SHAs:",a.currentEntityShas),console.log("[updateCommitMetadata] Archive flag:",s)),r=Wn(r??{},{currentRun:a});else if(!r&&!o)return d;const m=r?Wn(d,r):d;if(s&&m.currentRun){console.log("[updateCommitMetadata] ========================================"),console.log("[updateCommitMetadata] ARCHIVING CURRENT RUN"),console.log(`[updateCommitMetadata] Commit SHA: ${t}`),console.log("[updateCommitMetadata] Current run entity SHAs:",m.currentRun.currentEntityShas),console.log(`[updateCommitMetadata] Current run PIDs: analyzer=${m.currentRun.analyzerPid}, capture=${m.currentRun.capturePid}`),console.log(`[updateCommitMetadata] Current run completed: analyses=${m.currentRun.analysesCompleted}, captures=${m.currentRun.capturesCompleted}`),console.log(`[updateCommitMetadata] Historical runs before archiving: ${((h=m.historicalRuns)==null?void 0:h.length)||0}`);const p={...m.currentRun,archivedAt:new Date().toISOString()};console.log("[updateCommitMetadata] Run to archive:",JSON.stringify(p,null,2)),m.historicalRuns=[...m.historicalRuns||[],p],console.log(`[updateCommitMetadata] Historical runs after archiving: ${m.historicalRuns.length}`),console.log("[updateCommitMetadata] All historical runs:",JSON.stringify(m.historicalRuns.map(f=>({entityShas:f.currentEntityShas,archivedAt:f.archivedAt,completed:{analyses:f.analysesCompleted,captures:f.capturesCompleted}})),null,2)),console.log("[updateCommitMetadata] ========================================")}o&&await o(m);try{return await i.updateTable("commits").set({metadata:JSON.stringify(m)}).where("id","=",c.id).returning(["id"]).executeTakeFirst()?m:(we(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`),d)}catch(p){return we(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`,p),d}})}catch(i){return we(`CodeYam Error: updateCommitMetadata(): Transaction failed for commit ${e}`,i),null}}async function bo(e,t,r="analysis"){try{return await Ae().transaction().execute(async a=>{const s=await a.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!s)return we(`CodeYam Error: updateFreshAnalysisMetadata(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const o=lt(s);return t(o.metadata,o),await a.updateTable("analyses").set({metadata:JSON.stringify(o.metadata)}).where("id","=",e).returningAll().executeTakeFirst()?o.metadata:(we(`CodeYam Error: updateFreshAnalysisMetadata(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(a){return we(`CodeYam Error: updateFreshAnalysisMetadata(): Transaction failed for analysis ${e} (source: ${r})`,a,{analysisId:e,source:r}),null}}async function Yt(e,t,r="capture"){try{return await Ae().transaction().execute(async a=>{const s=await a.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!s)return we(`CodeYam Error: updateFreshAnalysisStatus(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const o=lt(s);return t(o.status,o),await a.updateTable("analyses").set({status:JSON.stringify(o.status)}).where("id","=",e).returningAll().executeTakeFirst()?o.status:(we(`CodeYam Error: updateFreshAnalysisStatus(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(a){return we(`CodeYam Error: updateFreshAnalysisStatus(): Transaction failed for analysis ${e} (source: ${r})`,a,{analysisId:e,source:r}),null}}async function Hn({projectId:e,projectSlug:t,metadataUpdate:r,updateCallback:a}){if(!e&&!t)throw new Error("Either projectId or projectSlug must be provided");try{return await Ae().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 we(`CodeYam Error: updateProjectMetadata(): Project ${e} not found`),null;const i=o.metadata||{};if(!r&&!a)return i;const c=r?Wn(i,r):i;a&&await a(c,ha(o));try{return await s.updateTable("projects").set({metadata:JSON.stringify(c)}).where("id","=",o.id).returningAll().executeTakeFirst()?c:(we(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`),null)}catch(d){return we(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`,d),null}})}catch(s){return we(`CodeYam Error: updateProjectMetadata(): Transaction failed for project ${e}`,s),null}}const Xc=()=>crypto.randomUUID();function ed(e){const{id:t,projectId:r,analysisId:a,previousVersionId:s,analysis:o,metadata:i,data:c,...d}=e;return delete d.userScenarios,delete d.comments,"created_at"in d&&delete d.created_at,{...d,id:t??Xc(),metadata:i?JSON.stringify(i):null,project_id:r,analysis_id:a,previous_version_id:s}}async function td(e){if(e.length===0)return[];const t=Ae(),r=e.map(ed);try{return(await t.insertInto("scenarios").values(r).onConflict(ir(r[0],"id",["created_at"])).returningAll().execute()).map(co)}catch(a){return we("CodeYam Error: Database error upserting scenarios",a,{scenarioCount:e.length}),null}}const nd=()=>crypto.randomUUID();function rd(e){const{id:t,commitId:r,branchId:a,...s}=e;return delete s.commit,delete s.branch,{...s,id:t??nd(),commit_id:r,branch_id:a}}async function ms(e){if(e.length===0)return[];const t=Ae(),r=e.map(rd);try{return(await t.insertInto("commit_branches").values(r).onConflict(ir(r[0],"id",["created_at"])).returningAll().execute()).map(pa)}catch(a){return we("CodeYam Error: Database error upserting commit branches",a,{commitBranchCount:e.length,commitBranchIds:e.map(s=>s.id)}),[]}}async function ad(e,t){const r=Ae(),a={username:e,avatar_url:t};try{return await r.insertInto("github_users").values(a).onConflict(ir(a,"username",[])).returningAll().executeTakeFirst()||null}catch(s){return we("CodeYam Error: Error upserting github user",s,{username:e,avatarUrl:t}),null}}const sd=()=>crypto.randomUUID();function od(e,t){const{id:r,projectId:a,branchId:s,mergedBranchId:o,aiMessage:i,htmlUrl:c,analyzedAt:d,committedAt:m,author:u,metadata:h,files:p,...f}=e;return delete f.branch,delete f.mergedBranch,delete f.backgroundJob,delete f.analyses,delete f.parents,delete f.entities,delete f.commitBranches,{...f,id:r??sd(),project_id:a??String(t),metadata:h?JSON.stringify(h):void 0,files:p?JSON.stringify(p):void 0,branch_id:s,merged_branch_id:o,author_github_username:u==null?void 0:u.username,html_url:c,ai_message:i,analyzed_at:d,committed_at:m}}async function id({projectId:e,commits:t}){const r=Ae();try{const a=t.reduce((i,c)=>{const{author:d}=c;return d!=null&&d.username&&(d!=null&&d.avatarUrl)&&(i[d.username]=d.avatarUrl),i},{});for(const i in a)await ad(i,a[i]);const s=t.map(i=>od(i,e));return(await r.insertInto("commits").values(s).onConflict(ir(s[0],"id",["created_at"])).returningAll().execute()).map(Tt)}catch(a){return we("CodeYam Error: Error saving commits",a,{projectId:e,commitCount:t.length,commitIds:t.map(s=>s.id).filter(Boolean)}),[]}}const Vn=Z.join(Pl.homedir(),".codeyam","secrets.json"),Jn=Z.join(process.cwd(),".codeyam","secrets.json");async function vt(){let e={};try{if(K.existsSync(Jn)){const o=await Re.readFile(Jn,"utf8");e=JSON.parse(o)}}catch{console.warn(zn.yellow("⚠ Could not read project secrets file, trying home directory"))}if(!e.OPENAI_API_KEY&&!e.ANTHROPIC_API_KEY)try{if(K.existsSync(Vn)){const o=await Re.readFile(Vn,"utf8");e={...JSON.parse(o),...e}}}catch{console.warn(zn.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 ld(e,t=!0){const r=t?Vn:Jn,a=Z.dirname(r);await Re.mkdir(a,{recursive:!0}),await Re.writeFile(r,JSON.stringify(e,null,2)),await Re.chmod(r,384)}function cd(e=!0){return e?Vn:Jn}async function hs(){const e=await vt(),t=[];for(const r of t)e[r];return{isValid:!0,missing:[],secrets:e}}async function dd(e){console.log(),console.log(zn.blue("ℹ Configuration needed")),console.log();const t={};for(const r of e)switch(r){case"OPENAI_API_KEY":const a=await Ml({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 ud(e=!0){const t=await hs();if(t.isValid)return t.secrets;const r=await dd(t.missing),s={...await vt(),...r};await ld(s,e);const o=cd(e);return console.log(zn.green(`✓ Configuration saved to ${o}`)),(await hs()).secrets}function vo(e=process.cwd()){let t=Z.resolve(e);const r=Z.parse(t).root;for(;t!==r;){const s=Z.join(t,".codeyam","config.json");if(K.existsSync(s))return t;t=Z.dirname(t)}const a=Z.join(r,".codeyam","config.json");return K.existsSync(a)?r:null}let wo=vo();function fe(){return wo}function md(e){wo=e}function Co(e){const t={...e};for(const r in e)if(r.includes(".")){const a=r.replace(/\./g,"");t[a]=e[r]}return t}const hd={"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>`};Co(hd);const pd={"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>`};Co(pd);function en(e,t,r=new WeakSet){if(!t)return e;if(!e)return t;try{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference detected during deep merge");r.add(t)}if(Array.isArray(t)){const s=Array.isArray(e)?e:[],o=[];for(let i=0;i<t.length;i++){const c=t[i];c&&typeof c=="object"&&!Array.isArray(c)||Array.isArray(c)?o[i]=en(s[i],c,r):o[i]=c}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 c=t[s][i];typeof c=="object"&&c!==null?a[s][i]=en(o[i],c,r):a[s][i]=c}}else typeof t[s]=="object"&&t[s]!==null?a[s]=en(a[s]??{},t[s],r):a[s]=t[s];return a}catch(a){throw console.log("CodeYam: Error merging data",e,t),a}}async function fd({projectId:e,commit:t,branch:r}){var c,d,m,u,h,p,f;let a;const s={commitId:t.id,branchId:r.id,active:!0},o=await Jc({projectId:e,commitId:t.id,includeBranches:!0});if(o&&o.length>0){a=(c=o.sort((y,x)=>{var v,b,w,C;return(((b=(v=y.branch.metadata)==null?void 0:v.permanent)==null?void 0:b.order)??999)-(((C=(w=x.branch.metadata)==null?void 0:w.permanent)==null?void 0:C.order)??999)})[0])==null?void 0:c.branch,a&&((m=(d=r.metadata)==null?void 0:d.permanent)==null?void 0:m.order)!==void 0&&(((h=(u=r.metadata)==null?void 0:u.permanent)==null?void 0:h.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 ms(g.map(y=>({...y,active:y.branchId===a.id})))}(o==null?void 0:o.find(g=>g.branchId===s.branchId))||await ms([s])}function wt(){if(process.env.SQLITE_PATH)return process.env.SQLITE_PATH;const e=fe();if(!e)throw new Error("Could not find project root. Please run this command inside a CodeYam project.");return oe.join(e,".codeyam","db.sqlite3")}async function Le(){const e=await ud();process.env.SQLITE_PATH=wt(),e.OPENAI_API_KEY&&(process.env.OPENAI_API_KEY=e.OPENAI_API_KEY)}async function Ie(e){await Le();const t=await Zc({slug:e});if(!t)throw new Error(`Project with slug "${e}" not found in database`);const r=await go({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 gd(e,t,r){await Le();const a=fe(),s=Oc(`${e.slug}-local-${Date.now()}-${Math.random()}`),o=r.map(d=>{let m="";if(a)try{if(m=Me(`git diff HEAD -- "${d}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10}),!m)try{const u=Me(`cat "${d}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"]});if(u){const h=u.split(`
30
- `);m=`@@ -0,0 +1,${h.length} @@
31
- ${h.map(p=>`+${p}`).join(`
32
- `)}`}}catch{}}catch{}return{fileName:d,status:"modified",patch:m}}),i={sha:s,projectId:e.id,branchId:t.id,message:`Local analysis: ${r.join(", ")} at ${new Date().toISOString()}`,url:`local://codeyam/${e.slug}/${s}`,htmlUrl:`local://codeyam/${e.slug}/${s}`,author:{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"},committedAt:new Date().toISOString(),parents:[],files:o,metadata:{baseline:!1,receivedAt:new Date().toISOString()}},c=await id({projectId:e.id,commits:[i]});if(!c||c.length===0)throw new Error("Failed to create fake commit");return await fd({projectId:e.id,commit:c[0],branch:t}),c[0]}async function pn(){await Le();const e=await ot({excludeMetadata:!0});if(!e||e.length===0)return[];const t=e.filter(d=>{var m;return!((m=d.metadata)!=null&&m.isSuperseded)}),r=t.map(d=>d.sha),a=t.map(d=>{var m;return(m=d.metadata)==null?void 0:m.previousVersionWithAnalyses}).filter(d=>!!d),s=[...new Set([...r,...a])],o=await yt({entityShas:s,excludeMetadata:!0}),i=new Map;if(o)for(const d of o)i.has(d.entitySha)||i.set(d.entitySha,[]),i.get(d.entitySha).push(d);return t.map(d=>{var h;const m=i.get(d.sha)||[];if(m.length>0)return{...d,analyses:m};const u=(h=d.metadata)==null?void 0:h.previousVersionWithAnalyses;if(u){const p=i.get(u)||[];return{...d,analyses:p}}return{...d,analyses:[]}})}async function lr(e,t){await Le();const r=await yt({entityShas:[e],limit:1});if(r&&r.length>0&&t){const a=await yo({projectId:r[0].projectId,sha:e});if(a)for(const s of r)s.entity=a}return r||[]}async function fa(e){if(await Le(),e.name&&e.projectId){const r=await yt({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,c=!e.filePath||o.filePath===e.filePath;return i&&c});if(a.length>0)return a.sort((o,i)=>{const c=new Date(o.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-c}),a[0];const s=r.filter(o=>o.scenarios&&o.scenarios.length>0);if(s.length>0)return s.sort((o,i)=>{const c=new Date(o.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-c}),s[0]}}const t=await yt({entityShas:[e.sha],limit:1});return t&&t.length>0?t[0]:null}async function No(e){await Le();const t=await yt({entityShas:[e],limit:1});return(t==null?void 0:t[0])??null}async function zt(e){await Le();const t=await $e();if(!t)return null;const{project:r}=await Ie(t);return await yo({projectId:r.id,sha:e})}async function So(e){var a,s,o,i,c,d,m,u;await Le();const t=[],r=[];if((a=e.metadata)!=null&&a.importedExports&&e.metadata.importedExports.length>0){const h=e.metadata.importedExports;for(const p of h){if(!p.filePath||!p.name)continue;const f=p.resolvedFilePath??p.filePath,g=p.resolvedName??p.name;let y=await ot({projectId:e.projectId,filePaths:[f],names:[g]});if((!y||y.length===0)&&p.resolvedIsDefault&&(y=await ot({projectId:e.projectId,filePaths:[f],names:["default"]})),y&&y.length>0){const x=y[0],v=await yt({entityShas:[x.sha],limit:1});let b,w,C;if(v&&v.length>0&&v[0].scenarios){const k=v[0],N=k.scenarios||[],E=N.length,S=N.find(F=>{var L,P;return(P=(L=F.metadata)==null?void 0:L.screenshotPaths)==null?void 0:P[0]});S&&(b=(o=(s=S.metadata)==null?void 0:s.screenshotPaths)==null?void 0:o[0],w=S.name),C={status:((i=x.metadata)==null?void 0:i.previousVersionWithAnalyses)||k.entitySha!==x.sha?"out_of_date":"up_to_date",scenarioCount:E,timestamp:k.createdAt?new Date(k.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else C={status:"not_analyzed"};t.push({...x,screenshotPath:b,scenarioName:w,analysisStatus:C})}}}if((c=e.metadata)!=null&&c.importedBy){const h=[];for(const p in e.metadata.importedBy)for(const f in e.metadata.importedBy[p]){const g=e.metadata.importedBy[p][f];g.shas&&h.push(...g.shas)}if(h.length>0){const p=await ot({projectId:e.projectId,shas:h});if(p)for(const f of p){const g=await yt({entityShas:[f.sha],limit:1});let y,x,v;if(g&&g.length>0&&g[0].scenarios){const b=g[0],w=b.scenarios||[],C=w.length,k=w.find(E=>{var S,M;return(M=(S=E.metadata)==null?void 0:S.screenshotPaths)==null?void 0:M[0]});k&&(y=(m=(d=k.metadata)==null?void 0:d.screenshotPaths)==null?void 0:m[0],x=k.name),v={status:((u=f.metadata)==null?void 0:u.previousVersionWithAnalyses)||b.entitySha!==f.sha?"out_of_date":"up_to_date",scenarioCount:C,timestamp:b.createdAt?new Date(b.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else v={status:"not_analyzed"};r.push({...f,screenshotPath:y,scenarioName:x,analysisStatus:v})}}}return{importedEntities:t,importingEntities:r}}async function $e(){try{const e=fe();if(!e)return null;const t=oe.join(e,".codeyam","config.json");return JSON.parse(await he.readFile(t,"utf8")).projectSlug||null}catch(e){return console.error("[getProjectSlug] Error:",e),null}}async function Bt(){await Le();try{const e=await $e();if(!e)return null;const{project:t,branch:r}=await Ie(e),a=await Un({projectId:t.id,branchId:r.id,limit:1,skipRelations:!0});return a&&a.length>0?a[0]:null}catch(e){return console.error("[getCurrentCommit] Error:",e),null}}async function cr(){try{const e=fe();if(!e)return null;const t=oe.join(e,".codeyam","config.json");return JSON.parse(await he.readFile(t,"utf8"))}catch(e){return console.error("[getProjectConfig] Error:",e),null}}async function ko(e){try{const t=fe();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=oe.join(t,e.filePath);return await he.readFile(r,"utf8")}catch(t){return console.error("[getEntityCodeFromFilesystem] Error reading file:",t),null}}async function Eo(e){try{const t=fe();if(!t||!e.filePath)return!1;const r=oe.join(t,e.filePath),s=(await he.stat(r)).mtime.getTime(),o=e.updatedAt||e.createdAt;if(!o)return!1;const i=new Date(o).getTime();return s>i+1e3}catch{return!1}}async function Ao(e){if(await Le(),!e.filePath||!e.name||!e.projectId)return console.error("[getEntityHistory] Entity missing required fields (filePath, name, or projectId)"),[];const t=await ot({projectId:e.projectId,filePaths:[e.filePath],names:[e.name]});if(!t||t.length===0)return[];const r=t.map(i=>i.sha),a=await yt({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,c]of s.entries())c.sort((d,m)=>{const u=new Date(d.createdAt||0).getTime();return new Date(m.createdAt||0).getTime()-u});const o=t.map(i=>({...i,analyses:s.get(i.sha)||[]}));return o.sort((i,c)=>{var u,h;const d=((u=i.analyses[0])==null?void 0:u.createdAt)||i.createdAt||"",m=((h=c.analyses[0])==null?void 0:h.createdAt)||c.createdAt||"";return new Date(m).getTime()-new Date(d).getTime()}),o}async function _o(e){try{const t=fe();if(!t)return console.error("[updateProjectConfig] No project root found"),!1;const r=oe.join(t,".codeyam","config.json"),a=await he.readFile(r,"utf8"),s=JSON.parse(a),o={...s,...e},i=JSON.stringify(o,null,2);if(await he.writeFile(r,i,"utf8"),s.projectSlug){const c={};e.universalMocks!==void 0&&(c.universalMocks=e.universalMocks),e.pathsToIgnore!==void 0&&(c.pathsToIgnore=e.pathsToIgnore),e.webapps!==void 0&&(c.webapps=e.webapps),await Hn({projectSlug:s.projectSlug,metadataUpdate:c})}return!0}catch(t){return console.error("[updateProjectConfig] Error:",t),!1}}const yd=Object.freeze(Object.defineProperty({__proto__:null,getAllEntities:pn,getAnalysesForEntity:lr,getAnalysisForExactEntitySha:No,getCurrentCommit:Bt,getEntityBySha:zt,getEntityCodeFromFilesystem:ko,getEntityHistory:Ao,getLatestAnalysisForEntity:fa,getProjectConfig:cr,getProjectSlug:$e,getRelatedEntities:So,hasFileBeenModifiedSinceEntity:Eo,requireBranchAndProject:Ie,updateProjectConfig:_o},Symbol.toStringTag,{value:"Module"})),Po="secrets.json";function Mo(e){return oe.join(e,".codeyam",Po)}function To(){return oe.join(Gr.homedir(),".codeyam",Po)}async function dr(e){let t={};try{const r=To(),a=await he.readFile(r,"utf-8");t=JSON.parse(a)}catch{}try{const r=Mo(e),a=await he.readFile(r,"utf-8"),s=JSON.parse(a);t={...t,...s}}catch{}return t}async function xd(e,t,r=!0){const a=r?To():Mo(e),s=oe.dirname(a);await he.mkdir(s,{recursive:!0}),await he.writeFile(a,JSON.stringify(t,null,2)+`
33
- `,"utf-8")}async function bd(e){const t=await dr(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 vd=3;let Qt=0;async function Cn(e){if(!e||e.length===0)return[];if(Qt>=vd)return console.warn(`[Loader] Circuit breaker open (${Qt} consecutive timeouts), skipping entity fetch for ${e.length} entities`),[];const t=Math.min(Math.max(e.length*2e3,1e4),6e4);return new Promise(r=>{let a=!1;const s=setTimeout(()=>{a||(a=!0,Qt++,console.warn(`[Loader] Entity fetch timeout after ${t}ms for ${e.length} entities`),r([]))},t);ot({shas:e,excludeMetadata:!0}).then(o=>{a||(a=!0,clearTimeout(s),Qt=0,r(o||[]))}).catch(()=>{a||(a=!0,clearTimeout(s),Qt++,r([]))})})}function wd({sourcePath:e,destinationPath:t,excludes:r,silent:a}){if(process.platform!=="darwin")return!1;if(pt(t))try{if(wl(t).length>0)return!1;Ar(t,{recursive:!0})}catch{return!1}try{Me(`cp -c -R "${e}" "${t}"`,{stdio:"pipe",timeout:3e5});for(const s of r)if(s.includes("*"))try{Me(`rm -rf "${is(t,s)}"`,{stdio:"pipe",shell:"/bin/sh"})}catch{}else{const o=is(t,s);pt(o)&&Ar(o,{recursive:!0,force:!0})}return a||console.log(`Directory cloned (APFS CoW) from ${e} to ${t}`),!0}catch{if(pt(t))try{Ar(t,{recursive:!0})}catch{}return!1}}async function Cd({sourcePath:e,destinationPath:t,excludes:r=[],keepExisting:a=!1,silent:s=!1,extraArgs:o=[]}){const i=Date.now();if(!a&&o.length===0&&wd({sourcePath:e,destinationPath:t,excludes:r,silent:s})){if(!s){const d=((Date.now()-i)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${d}s]`)}return}return new Promise((c,d)=>{const m=e.endsWith("/")?e:`${e}/`,u=t.endsWith("/")?t:`${t}/`,h=["-a","--no-specials"];a||h.push("--delete","--force"),h.push(...o);for(const f of r)h.push(`--exclude=${f}`);h.push(m,u);const p=rr("rsync",h);p.on("exit",f=>{if(f===0){if(!s){const g=((Date.now()-i)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${g}s]`)}c()}else console.error(`CodeYam Error: rsync failed with code: ${f}`,JSON.stringify({rsyncArgs:h},null,2)),d(new Error(`rsync failed with exit code ${f}`))}),p.on("error",f=>{s||console.log("Error occurred:",f),d(f)})})}const Nd=la(ia);async function Sd(e){return new Promise(t=>setTimeout(t,e))}function kd(e){try{return process.kill(e,0),!0}catch{return!1}}async function jo(e){try{const{stdout:t}=await Nd(`ps -A -o pid=,ppid= | awk '$2 == ${e} { print $1 }'`),r=t.trim().split(`
34
- `).filter(s=>s.trim()).map(s=>parseInt(s.trim(),10)).filter(s=>!isNaN(s)),a=[...r];for(const s of r){const o=await jo(s);a.push(...o)}return a}catch{return[]}}function ps(e,t,r){try{process.kill(e,t)}catch(a){r==null||r(`Error sending ${t} to process ${e}: ${a}`)}}async function Ed(e,t,r){const a=await jo(e);for(const s of a.reverse())await ps(s,t,r);await ps(e,t,r)}async function sn(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 Ed(e,o,t);for(let c=0;c<i;c++)if(await Sd(1e3),a+=1e3,!await kd(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 Ad(e){const t=new Date().toISOString();e.currentRun&&(e.currentRun.archivedAt=t,e.historicalRuns??(e.historicalRuns=[]),e.historicalRuns.push(e.currentRun)),e.currentRun={id:Hl(),createdAt:t}}Il.config({quiet:!0});var Io=(e=>(e.Server="server",e.Analyzer="analyzer",e.Capture="capture",e.Controller="controller",e.Worker="worker",e.Project="project",e.Other="other",e))(Io||{});class _d extends $l{constructor(){super(...arguments),this.processes=new Map}register(t){const r=Dl(),{process:a,type:s,name:o,metadata:i,parentId:c}=t,d={id:r,type:s,name:o,pid:a.pid,state:"running",startedAt:Date.now(),metadata:i,parentId:c,children:[]};if(this.processes.set(r,{info:d,process:a}),c){const h=this.processes.get(c);h&&(h.info.children=h.info.children||[],h.info.children.push(r))}const m=(h,p)=>{this.handleProcessExit(r,h,p)},u=h=>{this.handleProcessError(r,h)};return a.on("exit",m),a.on("error",u),a.__cleanup=()=>{a.removeListener("exit",m),a.removeListener("error",u)},this.emit("processStarted",d),r}unregister(t){const r=this.processes.get(t);return r?(r.process.__cleanup&&r.process.__cleanup(),this.processes.delete(t),!0):!1}getInfo(t){const r=this.processes.get(t);return r?{...r.info}:null}listAll(){return Array.from(this.processes.values()).map(t=>({...t.info}))}listByType(t){return this.listAll().filter(r=>r.type===t)}listByState(t){return this.listAll().filter(r=>r.state===t)}findByName(t){return this.listAll().filter(r=>r.name===t)}async shutdown(t,r={}){const a=this.processes.get(t);if(!a)throw new Error(`Process not found: ${t}`);const{info:s,process:o}=a;if(s.state==="completed"||s.state==="failed"||s.state==="killed")return;if(r.shutdownChildren&&s.children&&s.children.length>0&&await Promise.all(s.children.map(c=>this.shutdown(c,r))),o.pid)try{await sn(o.pid,c=>console.log(`[Process ${t}] ${c}`))}catch(c){console.warn(`Error killing process ${t}:`,c)}await new Promise(c=>setTimeout(c,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 c=o.process.__cleanup;c&&c(),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 $r=null;function Pd(){return $r||($r=new _d),$r}const Md={stdoutToConsole:!0,stdoutToFile:!0,stderrToConsole:!0,stderrToFile:!0};function Td({command:e,args:t,workingDir:r,outputOptions:a=Md,processName:s,env:o}){const i={...process.env,...o||{},CODEYAM_PROCESS_NAME:`codeyam-${s}`},c=rr(e,t,{cwd:r,env:i});return Pd().register({process:c,type:Io.Other,name:s,metadata:{command:e,args:t,workingDir:r}}),{promise:new Promise(u=>{const h=f=>{const g=oe.join(r,"log.txt");K.appendFile(g,f,y=>{y&&console.log("Error writing to log file:",y)})},p=(f,g="")=>{const y=new Date().toLocaleString();return f.split(`
35
- `).map(v=>v.trim()?`[${y}]${g} ${v}`:v).join(`
36
- `)};c.stdout.on("data",function(f){const g=(f==null?void 0:f.toString())??"",y=p(g);a.stdoutToConsole&&console.log(y),a.stdoutToFile&&h(y+`
37
- `),a.stdoutCallback&&a.stdoutCallback(g)}),c.stderr.on("data",function(f){const g=(f==null?void 0:f.toString())??"",y=p(g,"<STDERR>");a.stderrToConsole&&console.error(y),a.stderrToFile&&h(y+`
38
- `),a.stderrCallback&&a.stderrCallback(g)}),c.on("exit",function(f){u(f)})}),process:c}}function jd(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 Id({absoluteCodeyamRootPath:e,startEnv:t,startArgs:r,outputOptions:a}){const s=Object.entries(t).map(([i,c])=>`${i}=${c}`).join(`
39
- `);K.writeFileSync(`${e}/.env`,s);const o=jd(r);return Td({command:"node",args:["--enable-source-maps","./dist/project/start.js",...o],workingDir:e,outputOptions:a,processName:"analyzer",env:t})}const $d="/tmp/codeyam/local-dev";function $o(e){return Z.join($d,e)}function Ro(e){return Z.join($o(e),"codeyam")}function dt(e){return Z.join($o(e),"project")}function ur(e){return Z.join(Ro(e),"log.txt")}const Rd=[".sync-metadata.json","__codeyamMocks__"];async function Dd(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 Ld(e,t={}){const{killProcesses:r=!0,port:a,silent:s=!0}=t,o=dt(e),i=[],c=[];if(!K.existsSync(o))return{removed:i,errors:c};r&&await Dd(e,{port:a,silent:s});for(const d of Rd){const m=Z.join(o,d);if(K.existsSync(m))try{(await Re.stat(m)).isDirectory()?await Re.rm(m,{recursive:!0,force:!0}):await Re.unlink(m),i.push(d)}catch(u){c.push(`${d}: ${u instanceof Error?u.message:String(u)}`)}}return{removed:i,errors:c}}const Fd=Z.dirname(ar(import.meta.url));function Od(e){let t=e;for(;t!==Z.dirname(t);){const r=Z.join(t,"package.json");if(K.existsSync(r))try{if(JSON.parse(K.readFileSync(r,"utf8")).name==="@codeyam/codeyam-cli")return t}catch{}t=Z.dirname(t)}throw new Error("Could not find @codeyam/codeyam-cli package root")}function mr(){const e=Od(Fd);return Z.join(e,"analyzer-template")}function Ut(e){return Ro(e)}function zd(){const e=mr();return K.existsSync(Z.join(e,".finalized"))}async function fs(e){const t=mr(),r=Ut(e);if(!K.existsSync(t))throw new Error(`Analyzer template not found at ${t}. Did the build process complete successfully?`);await Re.mkdir(Z.dirname(r),{recursive:!0}),await Cd({sourcePath:t,destinationPath:r,silent:!0})}function Wt(e,t,r,a){const s=Ut(e);if(!K.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 Id({absoluteCodeyamRootPath:s,startEnv:t,startArgs:r,outputOptions:{stdoutToConsole:!1,stdoutToFile:!0,stdoutCallback:o,stderrToConsole:!1,stderrToFile:!0,stderrCallback:o}})}function Yd(e){const t=mr(),r=Ut(e),a=Z.join(t,".build-info.json"),s=Z.join(r,".build-info.json");if(!K.existsSync(a))return{isFresh:!1,reason:"Template build marker missing - template may be corrupted"};if(!K.existsSync(r))return{isFresh:!1,reason:"Cached analyzer does not exist"};if(!K.existsSync(s))return{isFresh:!1,reason:"Cached analyzer build marker missing - was created with old version"};try{const o=JSON.parse(K.readFileSync(a,"utf8")),i=JSON.parse(K.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 fn(e,t){const r=Ut(e);if(!K.existsSync(r)){t.update("Creating analyzer..."),await fs(e);return}const a=Yd(e);a.isFresh||(t.update(`Updating analyzer (${a.reason})...`),await fs(e))}async function ga(e){await Ld(e,{killProcesses:!1})}const Bd=Z.dirname(ar(import.meta.url));function hr(){let e=Bd;for(;e!==Z.dirname(e);){const t=Z.join(e,"package.json");if(K.existsSync(t))try{if(JSON.parse(K.readFileSync(t,"utf8")).name==="@codeyam/codeyam-cli")return e}catch{}e=Z.dirname(e)}return null}function Ft(e){if(!K.existsSync(e))return null;try{return JSON.parse(K.readFileSync(e,"utf8"))}catch{return null}}function Ud(){const e=hr();if(e){const t=[Z.join(e,"src/webserver/build-info.json"),Z.join(e,"codeyam-cli/src/webserver/build-info.json")];for(const r of t){const a=Ft(r);if(a!=null&&a.semanticVersion)return a.semanticVersion}}return"unknown"}function Wd(){const e=hr();if(e){const t=Z.join(e,"package.json");try{const r=JSON.parse(K.readFileSync(t,"utf8"));if(r.version)return r.version}catch{}}return"unknown"}const ya=Ud(),Rr=Wd();function xa(){if(Rr!=="unknown"&&Rr!=="0.1.0")return Rr;const e=hr();if(e)for(const t of[Z.join(e,"src/webserver/build-info.json"),Z.join(e,"codeyam-cli/src/webserver/build-info.json")]){const r=Ft(t);if(r!=null&&r.buildNumber)return`dev (build ${r.buildNumber})`}return"dev"}function Do(e){const t=hr();let r=null;if(t){const d=[Z.join(t,"src/webserver/build-info.json"),Z.join(t,"codeyam-cli/src/webserver/build-info.json")];for(const m of d)if(r=Ft(m),r)break}const a=mr(),s=Z.join(a,".build-info.json"),o=Ft(s);let i=null;if(e){const d=Ut(e),m=Z.join(d,".build-info.json");i=Ft(m)}let c=!1;return o&&i?c=o.buildTime>i.buildTime:o&&!i&&e&&(c=!0),{cliVersion:ya,webserverVersion:r,templateVersion:o,cachedAnalyzerVersion:i,isCacheStale:c}}function pr(e){const t=Ut(e),r=Z.join(t,".build-info.json"),a=Ft(r);return(a==null?void 0:a.version)??null}function Lo(){const e=fe();return e?Z.join(e,".codeyam","server.json"):null}function Fo(){const e=Lo();if(!e||!K.existsSync(e))return null;try{const t=K.readFileSync(e,"utf8");return JSON.parse(t)}catch{return null}}function Hd(){const e=Lo();if(e)try{K.unlinkSync(e)}catch{}}const Vd="/assets/globals-CLmFdUae.css";function gs({text:e,subtext:t,linkText:r,linkTo:a}){const[s,o]=_(!1);return s?null:n("div",{className:"bg-blue-100 border rounded border-blue-800 shadow-sm mx-6 mt-6",children:l("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[l("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-yellow-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),l("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-blue-900",children:e}),n("p",{className:"text-xs text-blue-700 mt-0.5",children:t})]}),n(se,{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 Jd({version:e}){return n("div",{className:"px-6 sm:px-12 pb-8 mt-auto pt-8",children:l("div",{className:"border-t border-cygray-30 pt-6 flex flex-wrap justify-between items-center gap-4",children:[l("div",{className:"flex items-center gap-3",children:[n("span",{className:"font-mono text-sm font-semibold tracking-widest text-cyblack-100",children:"CODEYAM"}),e&&n("span",{className:"font-mono text-xs text-gray-400",children:e})]}),l("div",{className:"flex items-center gap-4 font-mono text-xs uppercase tracking-widest",children:[n("a",{href:"https://blog.codeyam.com/",target:"_blank",rel:"noopener noreferrer",className:"text-cyblack-100 underline underline-offset-4 hover:text-primary-100",children:"Read the Blog"}),n("span",{className:"text-cygray-30",children:"|"}),n("a",{href:"https://discord.gg/x4uAgaRdwF",target:"_blank",rel:"noopener noreferrer",className:"text-cyblack-100 underline underline-offset-4 hover:text-primary-100",children:"Join Discord"})]})]})})}function Gd({serverVersion:e}){const[t,r]=_("stale"),[a,s]=_(null),o=async()=>{r("restarting"),s(null);try{if(!(await fetch("/api/restart-server",{method:"POST"})).ok)throw new Error("Failed to restart server");r("reconnecting");let c=0;const d=30,m=1e3,u=async()=>{try{if((await fetch("/api/health")).ok){window.location.reload();return}}catch{}c++,c<d?setTimeout(()=>void u(),m):(s("Server took too long to restart. Please refresh manually."),r("stale"))};setTimeout(()=>void u(),500)}catch(i){s(i instanceof Error?i.message:"Failed to restart server"),r("stale")}};return n("div",{className:"bg-amber-100 border rounded border-amber-700 shadow-sm mx-6 mt-6",children:n("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:l("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-amber-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}),l("div",{className:"flex-1",children:[t==="stale"&&l(le,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Dashboard server is out of date"}),l("p",{className:"text-xs text-amber-700 mt-0.5",children:["Server version: ",e,". A newer version of CodeYam CLI is installed. Restart the server to get the latest features."]}),a&&n("p",{className:"text-xs text-red-600 mt-1",children:a})]}),t==="restarting"&&l(le,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Restarting server..."}),n("p",{className:"text-xs text-amber-700 mt-0.5",children:"Please wait while the server restarts."})]}),t==="reconnecting"&&l(le,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Reconnecting..."}),n("p",{className:"text-xs text-amber-700 mt-0.5",children:"Waiting for the server to come back online."})]})]}),t==="stale"&&n("button",{type:"button",onClick:()=>void o(),className:"shrink-0 px-4 py-2 bg-amber-600 text-white text-sm font-medium rounded hover:bg-amber-700 transition-colors cursor-pointer",children:"Restart Server"}),(t==="restarting"||t==="reconnecting")&&l("div",{className:"shrink-0 flex items-center gap-2 px-4 py-2 text-amber-700 text-sm",children:[l("svg",{className:"w-4 h-4 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),t==="restarting"?"Stopping...":"Reconnecting..."]})]})})})}function Ht({content:e,label:t="Copy",copiedLabel:r="✓ Copied!",className:a="",duration:s=2e3,ariaLabel:o,icon:i=!1,iconSize:c=14}){const[d,m]=_(!1),u=ie(()=>{navigator.clipboard.writeText(e).then(()=>{m(!0),setTimeout(()=>m(!1),s)}).catch(h=>{console.error("Failed to copy:",h)})},[e,s]);return n("button",{onClick:u,className:`cursor-pointer ${a}`,disabled:d,"aria-label":o||(d?"Copied to clipboard":"Copy to clipboard"),"aria-live":"polite",children:i?d?n(et,{size:c,className:"text-green-500"}):n(st,{size:c}):d?r:t})}function qd({currentVersion:e,latestVersion:t}){const[r,a]=_(!1);if(r)return null;const s="npm install -g @codeyam/codeyam-cli@latest && codeyam stop && codeyam";return n("div",{className:"bg-emerald-100 border rounded border-emerald-700 shadow-sm mx-6 mt-6",children:l("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[l("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-emerald-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M7 11l5-5m0 0l5 5m-5-5v12"})})}),l("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-emerald-900",children:"A new version of CodeYam CLI is available"}),l("p",{className:"text-xs text-emerald-700 mt-0.5",children:["Current: ",e," → Latest: ",t]})]}),l("div",{className:"shrink-0 flex items-center gap-2",children:[n("code",{className:"text-xs bg-emerald-200 text-emerald-900 px-2 py-1.5 rounded font-mono",children:s}),n(Ht,{content:s,label:"Copy",copiedLabel:"Copied!",className:"px-3 py-1.5 bg-emerald-600 text-white text-xs font-medium rounded hover:bg-emerald-700 transition-colors"})]})]}),n("button",{type:"button",onClick:()=>a(!0),className:"shrink-0 ml-4 p-1 rounded text-emerald-600 hover:text-emerald-800 hover:bg-emerald-200 transition-colors cursor-pointer","aria-label":"Dismiss banner",children:n("svg",{className:"w-5 h-5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M6 18L18 6M6 6l12 12"})})})]})})}let Zt=null,Nn=0;const Kd=3600*1e3;function Qd(e,t){const r=e.split(".").map(Number),a=t.split(".").map(Number);for(let s=0;s<Math.max(r.length,a.length);s++){const o=r[s]??0,i=a[s]??0;if(isNaN(o)||isNaN(i))return!1;if(o>i)return!0;if(o<i)return!1}return!1}async function Zd(){const e=xa();if(Zt&&Date.now()-Nn<Kd)return Zt;try{const t=new AbortController,r=setTimeout(()=>t.abort(),5e3),a=await fetch("https://registry.npmjs.org/@codeyam/codeyam-cli/latest",{signal:t.signal});if(clearTimeout(r),!a.ok){const c={updateAvailable:!1,latestVersion:null,currentVersion:e};return Zt=c,Nn=Date.now(),c}const o=(await a.json()).version;if(!o){const c={updateAvailable:!1,latestVersion:null,currentVersion:e};return Zt=c,Nn=Date.now(),c}const i={updateAvailable:Qd(o,e),latestVersion:o,currentVersion:e};return Zt=i,Nn=Date.now(),i}catch{return{updateAvailable:!1,latestVersion:null,currentVersion:e}}}function Gn(e){return Z.join(e,".codeyam","queue.json")}function tn(e){const t=Gn(e);if(!K.existsSync(t))return{paused:!1,jobs:[]};try{const r=K.readFileSync(t,"utf8");return JSON.parse(r)}catch(r){return console.error("Failed to load queue state:",r),{paused:!1,jobs:[]}}}function Xd(e,t){const r=Gn(e),a=Z.dirname(r);K.existsSync(a)||K.mkdirSync(a,{recursive:!0});try{K.writeFileSync(r,JSON.stringify(t,null,2),"utf8")}catch(s){throw console.error("Failed to save queue state:",s),s}}async function eu(e,t,r){console.log(`[Queue] Executing job ${e.id} (${e.type})`);try{if(e.type==="analysis")await tu(e,t,r);else if(e.type==="baseline")await nu(e,t,r);else if(e.type==="recapture")await ru(e,t,r);else if(e.type==="capture-only")await au(e,t,r);else if(e.type==="debug-setup")await su(e,t,r);else if(e.type==="interactive-start")await ou(e,t,r);else if(e.type==="interactive-stop")await iu(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 tu(e,t,r){var y,x,v,b;const{projectSlug:a,commitSha:s,entityShas:o}=e;if(!s)throw new Error("Analysis job missing commitSha");const i=o||[],{project:c}=await Ie(a);await ga(a),await fn(a,{update:w=>console.log(`[Queue] ${w}`)});const d=pr(a),m={...await vt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:s,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:wt(),...i.length>0?{ENTITY_SHAS:i.join(",")}:{},...e.onlyDataStructure?{ONLY_DATA_STRUCTURE:"true"}:{},...d?{ANALYZER_VERSION:d}:{},...process.env.CODEYAM_TRACE_TRANSFORMS?{CODEYAM_TRACE_TRANSFORMS:process.env.CODEYAM_TRACE_TRANSFORMS}:{}},u=(x=(y=c.metadata)==null?void 0:y.webapps)==null?void 0:x[0];if(!u)throw new Error("No webapps found in project metadata");const h=e.onlyDataStructure,p={packageManager:((v=c.metadata)==null?void 0:v.packageManager)||"npm",absoluteProjectRootPath:dt(a),port:0,noServer:!0,framework:u.framework,...h?{}:{orchestrateCapture:"local-sequential"}},f=Wt(a,m,p),g=w=>{try{return process.kill(w,0),!0}catch{return!1}};await ft({commitSha:s,runStatusUpdate:{currentEntityShas:i,entityCount:i.length||((b=e.filePaths)==null?void 0:b.length)||0,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString(),analyzerPid:f.process.pid}}),r==null||r.notifyChange("commit");try{try{const w=new Promise((C,k)=>setTimeout(()=>k(new Error("Analysis timed out after 60 minutes")),36e5));await Promise.race([f.promise,w]),await ft({commitSha:s,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),await ft({commitSha:s,runStatusUpdate:{currentEntityShas:[]}}),r==null||r.notifyChange("commit"),await new Promise(C=>setTimeout(C,2e3))}finally{if(f.process.pid)try{g(f.process.pid)&&await sn(f.process.pid,()=>{})}catch{}}}catch(w){if(console.error(`[Queue] Analysis job ${e.id} failed:`,w),f.process.pid&&g(f.process.pid))try{await sn(f.process.pid,()=>{})}catch{}try{await ft({commitSha:s,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:w instanceof Error?w.message:String(w)}}),r==null||r.notifyChange("commit")}catch(C){console.error("[Queue] Failed to update commit metadata after job failure:",C)}throw w}}async function nu(e,t,r){var p,f,g;const{projectSlug:a,commitSha:s}=e;if(!s)throw new Error("Baseline job missing commitSha");console.log(`[Queue] Starting baseline analysis for ${a}`);const{project:o}=await Ie(a);await ga(a),await fn(a,{update:y=>console.log(`[Queue] ${y}`)});const i=pr(a),c={...await vt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",BRANCH_COMMIT_SHA:s,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:wt(),...i?{ANALYZER_VERSION:i}:{}},d=(f=(p=o.metadata)==null?void 0:p.webapps)==null?void 0:f[0];if(!d)throw new Error("No webapps found in project metadata");const m={packageManager:((g=o.metadata)==null?void 0:g.packageManager)||"npm",absoluteProjectRootPath:dt(a),port:0,noServer:!0,framework:d.framework,orchestrateCapture:"local-sequential"},u=Wt(a,c,m),h=y=>{try{return process.kill(y,0),!0}catch{return!1}};await ft({commitSha:s,runStatusUpdate:{createdAt:new Date().toISOString(),analyzerPid:u.process.pid}}),r==null||r.notifyChange("commit");try{const y=new Promise((x,v)=>setTimeout(()=>v(new Error("Baseline timed out after 4 hours")),144e5));await Promise.race([u.promise,y]),await ft({commitSha:s,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),console.log(`[Queue] Baseline completed for ${a}`),await new Promise(x=>setTimeout(x,2e3))}finally{if(u.process.pid)try{h(u.process.pid)&&await sn(u.process.pid,()=>{})}catch{}}}async function ru(e,t,r){var f,g,y,x;const{projectSlug:a,analysisId:s,scenarioId:o,defaultWidth:i}=e;if(!s)throw new Error("Recapture job missing analysisId");const c=await ct({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!c||!c.commit)throw new Error(`Analysis ${s} not found`);if(i){const{getDatabase:v}=await import("./index-B8jmgmn2.js"),b=v(),w=await b.selectFrom("entities").select(["metadata"]).where("sha","=",c.entitySha).executeTakeFirst();let C={};w!=null&&w.metadata&&(typeof w.metadata=="string"?C=JSON.parse(w.metadata):C=w.metadata),C.defaultWidth=i,await b.updateTable("entities").set({metadata:JSON.stringify(C)}).where("sha","=",c.entitySha).execute()}await Yt(s,v=>{if(v.readyToBeCaptured=!0,v.scenarios)for(const b of v.scenarios)(!o||b.name===o)&&(delete b.finishedAt,delete b.startedAt,delete b.screenshotStartedAt,delete b.screenshotFinishedAt,delete b.interactiveStartedAt,delete b.interactiveFinishedAt,delete b.error,delete b.errorStack);delete v.finishedAt});const{project:d}=await Ie(a);await fn(a,{update:v=>console.log(`[Queue] ${v}`)});const m=pr(a),u={...await vt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:c.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:wt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:s,...o?{SCENARIO_IDS:o}:{},...m?{ANALYZER_VERSION:m}:{}},h={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:dt(a),port:void 0,noServer:!0,framework:((x=(y=(g=d.metadata)==null?void 0:g.webapps)==null?void 0:y[0])==null?void 0:x.framework)??hn.Next,orchestrateCapture:"local-sequential"},p=Wt(a,u,h);try{await p.promise}finally{try{p.process.kill("SIGTERM")}catch{}}}async function au(e,t,r){var f,g,y,x;const{projectSlug:a,analysisId:s,scenarioId:o,defaultWidth:i}=e;if(!s)throw new Error("Capture-only job missing analysisId");const c=await ct({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!c||!c.commit)throw new Error(`Analysis ${s} not found`);if(i){const{getDatabase:v}=await import("./index-B8jmgmn2.js"),b=v(),w=await b.selectFrom("entities").select(["metadata"]).where("sha","=",c.entitySha).executeTakeFirst();let C={};w!=null&&w.metadata&&(typeof w.metadata=="string"?C=JSON.parse(w.metadata):C=w.metadata),C.defaultWidth=i,await b.updateTable("entities").set({metadata:JSON.stringify(C)}).where("sha","=",c.entitySha).execute()}await Yt(s,v=>{if(v.readyToBeCaptured=!0,v.scenarios)for(const b of v.scenarios)(!o||b.name===o)&&(delete b.finishedAt,delete b.startedAt,delete b.screenshotStartedAt,delete b.screenshotFinishedAt,delete b.interactiveStartedAt,delete b.interactiveFinishedAt,delete b.error,delete b.errorStack);delete v.finishedAt});const{project:d}=await Ie(a);await fn(a,{update:v=>console.log(`[Queue] ${v}`)});const m=pr(a);console.log("[Queue] executeCaptureOnlyJob: Setting CAPTURE_ONLY=true for capture without file regeneration");const u={...await vt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:c.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:wt(),READY_TO_BE_CAPTURED:"true",CAPTURE_ONLY:"true",ANALYSIS_IDS:s,...o?{SCENARIO_IDS:o}:{},...m?{ANALYZER_VERSION:m}:{}},h={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:dt(a),port:void 0,noServer:!0,fast:!0,framework:((x=(y=(g=d.metadata)==null?void 0:g.webapps)==null?void 0:y[0])==null?void 0:x.framework)??hn.Next,orchestrateCapture:"local-sequential"},p=Wt(a,u,h);try{await p.promise}finally{try{p.process.kill("SIGTERM")}catch{}}}async function su(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 ct({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${s} not found`);const{project:c}=await Ie(a);await ga(a),await fn(a,{update:x=>console.log(`[Queue] ${x}`)});const d={...await vt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:wt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:s,PREP_ONLY:"true"};o&&(d.SCENARIO_IDS=o);const m={packageManager:((p=c.metadata)==null?void 0:p.packageManager)||"npm",absoluteProjectRootPath:dt(a),port:void 0,noServer:!1,framework:((y=(g=(f=c.metadata)==null?void 0:f.webapps)==null?void 0:g[0])==null?void 0:y.framework)||hn.Next},h=await Wt(a,d,m).promise;if(h!==0)throw new Error(`Prep process exited with code ${h}`)}async function ou(e,t,r){var h,p,f,g;const{projectSlug:a,analysisId:s,scenarioId:o}=e;if(!s)throw new Error("Interactive start job missing analysisId");const i=await ct({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${s} not found`);const{project:c}=await Ie(a),d={...await vt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:wt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:s,INTERACTIVE_MODE:"true"};o&&(d.SCENARIO_IDS=o);const m={packageManager:((h=c.metadata)==null?void 0:h.packageManager)||"npm",absoluteProjectRootPath:dt(a),port:void 0,noServer:!1,framework:((g=(f=(p=c.metadata)==null?void 0:p.webapps)==null?void 0:f[0])==null?void 0:g.framework)||hn.Next};await Yt(s,y=>{y.readyToBeCaptured=!0});const u=Wt(a,d,m);await bo(s,y=>{y.interactiveMode={pid:u.process.pid,startedAt:new Date().toISOString(),jobId:e.id}}),console.log(`[Queue] Interactive mode started for analysis ${s}, PID: ${u.process.pid}`)}async function iu(e,t,r){var d;const{projectSlug:a,analysisId:s}=e;if(!s)throw new Error("Interactive stop job missing analysisId");const o=await ct({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 c=i.pid;console.log(`[Queue] Stopping interactive mode for analysis ${s}, killing PID: ${c}`);try{try{process.kill(c,0)}catch{console.log(`[Queue] Process ${c} already exited`);return}await sn(c,()=>{}),console.log(`[Queue] Successfully killed interactive mode process ${c}`)}catch(m){throw console.error(`[Queue] Failed to kill process ${c}:`,m),m}finally{await bo(s,m=>{m.interactiveMode=null})}}class lu{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=tn(this.projectRoot),this.state.jobs.length>0?(this.state.currentlyExecuting&&(console.log(`[Queue] Clearing stale currentlyExecuting job from previous session: ${this.state.currentlyExecuting.id}`),this.state.currentlyExecuting=void 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||ro(),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,c=>{c?i(c):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 eu(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(){Xd(this.projectRoot,this.state),this.notifier&&this.notifier.notifyChange("queue")}}class cu{constructor(t,r,a=100){this.watcher=null,this.debounceTimer=null,this.projectRoot=t,this.onChange=r,this.debounceMs=a}start(){const t=Gn(this.projectRoot);if(!K.existsSync(t)){console.log("[QueueFileWatcher] Queue file does not exist yet, will start watching when created"),this.watchDirectory();return}this.watchFile(t)}watchDirectory(){const t=Gn(this.projectRoot),r=t.substring(0,t.lastIndexOf("/"));try{this.watcher=K.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=K.watch(t,r=>{r==="change"&&this.notifyChange()}),console.log("[QueueFileWatcher] Watching queue.json for changes")}catch(r){console.error("[QueueFileWatcher] Failed to watch queue file:",r)}}notifyChange(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.onChange(),this.debounceTimer=null},this.debounceMs)}stop(){this.watcher&&(this.watcher.close(),this.watcher=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}}class du{constructor(t,r,a){this.fileWatcher=null,this.serverInfo=t,this.projectRoot=r,this.onStateChange=a,this.cachedState=tn(r)}start(){this.cachedState=tn(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 cu(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,c)=>{r=i,a=c}),o=`proxy-${Date.now()}-${Math.random().toString(36).slice(2)}`;return this.enqueueRemote(t).then(i=>{console.log(`[ProxyQueue] Job enqueued on background server: ${i.jobId}`),this.refreshState(),r()}).catch(i=>{console.error("[ProxyQueue] Failed to enqueue job:",i),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=tn(this.projectRoot),{...this.cachedState}}refreshState(){this.cachedState=tn(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 uu(e){const t=Z.join(e,".codeyam","server.json");if(!K.existsSync(t))return null;try{const r=K.readFileSync(t,"utf8");return JSON.parse(r)}catch{return null}}function mu(e){try{return process.kill(e,0),!0}catch{return!1}}async function hu(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 pu(e){const t=uu(e);return!t||!mu(t.pid)||!await hu(t.url)?null:{url:t.url,port:t.port,pid:t.pid}}class fu extends Rl{constructor(){super();vn(this,"watcher",null);vn(this,"dbPath",null);vn(this,"isWatching",!1);this.setMaxListeners(20)}async start(){if(!this.isWatching)try{this.dbPath=wt();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 Kr=new fu;let _t=null,nn=null;async function gu(){if(!_t){if(nn){await nn;return}nn=(async()=>{try{const e=process.env.CODEYAM_ROOT_PATH||vo()||process.cwd();md(e),console.log(`[GlobalQueue] Project root: ${e}`);const t=await pu(e);if(t){console.log(`[GlobalQueue] Detected background server at ${t.url} (PID: ${t.pid})`),console.log("[GlobalQueue] Using proxy queue");const r=new du(t,e,()=>{Kr.notifyChange("unknown")});await r.start(),_t=r}else{console.log("[GlobalQueue] No background server detected, using local queue");const r=new lu(e,Kr);await r.start(),_t=r}console.log("[GlobalQueue] Queue initialized")}catch(e){throw console.error("[GlobalQueue] Failed to initialize queue:",e),e}})(),await nn}}async function ut(){return _t||await gu(),_t}function yu(){return _t||(nn&&console.warn("[GlobalQueue] Queue still initializing, loader may see empty state"),null)}const xu=()=>[{rel:"stylesheet",href:Vd},{rel:"icon",type:"image/x-icon",href:"/favicon.ico"}],bu={currentRun:void 0,projectSlug:null,currentEntities:[],availableAPIKeys:[],queuedJobCount:0,queueJobs:[],currentlyExecuting:null,historicalRuns:[],isServerOutOfDate:!1,serverVersion:"unknown",npmUpdate:null,labs:null,simulationsEnabled:!1,isSimulationsReady:!1,isAdmin:!1,displayVersion:xa()};async function vu({request:e,context:t}){var r,a,s,o,i,c,d,m,u,h;try{const p=e.signal,f=()=>{if(p.aborted)throw new Response(null,{status:499})};f();const g=fe()||process.cwd(),[y,x,v]=await Promise.all([$e(),dr(g),Zd().catch(()=>null)]);if(!y)throw new Error("Project slug not found");const{project:b,branch:w}=await Ie(y);f();const C=await Un({projectId:b.id,branchId:w.id,limit:20,skipRelations:!0});f();const k=C.length>0?C[0]:null,N=t.analysisQueue||yu(),E=N==null?void 0:N.getState();f();const S=await Promise.all(((E==null?void 0:E.jobs)||[]).map(async j=>{var q;const D=await Cn(j.entityShas||[]);return D.length===0&&((q=j.entityShas)!=null&&q.length)&&console.warn("[Loader] Entity fetch timeout/failed for job",j.id),{...j,entities:D}}));let M=null;if(E!=null&&E.currentlyExecuting){const j=E.currentlyExecuting,D=await Cn(j.entityShas||[]);D.length===0&&((r=j.entityShas)!=null&&r.length)&&console.warn("[Loader] Entity fetch timeout/failed for currentlyExecuting",j.id),M={...j,entities:D}}const F=M?S.filter(j=>j.id!==M.id):S;let L=((s=(a=k==null?void 0:k.metadata)==null?void 0:a.currentRun)==null?void 0:s.currentEntityShas)||[];if(L.length===0){const j=((o=k==null?void 0:k.metadata)==null?void 0:o.historicalRuns)||[];if(j.length>0){const q=[...j].sort((te,de)=>{const ge=te.archivedAt||te.createdAt||"";return(de.archivedAt||de.createdAt||"").localeCompare(ge)})[0];if(q){const te=q.analysisCompletedAt||q.createdAt;if(te){const de=new Date(te).getTime(),pe=Date.now()-1440*60*1e3;de>pe&&(L=q.currentEntityShas||[])}}}}const P=await Cn(L),T=[];x.ANTHROPIC_API_KEY&&T.push("ANTHROPIC_API_KEY"),x.GROQ_API_KEY&&T.push("GROQ_API_KEY"),x.OPENAI_API_KEY&&T.push("OPENAI_API_KEY"),x.OPENROUTER_API_KEY&&T.push("OPENROUTER_API_KEY"),f();const $=[];for(const j of C){const D=((i=j.metadata)==null?void 0:i.historicalRuns)||[];for(const q of D)$.push(q)}$.sort((j,D)=>{const q=j.archivedAt||j.analysisCompletedAt||j.createdAt||"";return(D.archivedAt||D.analysisCompletedAt||D.createdAt||"").localeCompare(q)});const I=new Set(((c=M==null?void 0:M.entities)==null?void 0:c.map(j=>j.sha))||[]),V=$.filter(j=>!(j.currentEntityShas||[]).some(q=>I.has(q))).slice(0,3),U=new Set;for(const j of V)for(const D of j.currentEntityShas||[])U.add(D);const z=await Cn(Array.from(U)),Y=new Map;for(const j of z)Y.set(j.sha,j);const R=V.map(j=>({...j,entities:(j.currentEntityShas||[]).map(D=>Y.get(D)).filter(D=>D!=null)})),A=Fo(),G=(A==null?void 0:A.cliVersion)??"unknown",B=G!=="unknown"&&G!==ya,H=((m=(d=b.metadata)==null?void 0:d.labs)==null?void 0:m.simulations)??!1,re=H?zd():!1,O={currentRun:(u=k==null?void 0:k.metadata)==null?void 0:u.currentRun,projectSlug:y,currentEntities:P,availableAPIKeys:T,queuedJobCount:F.length,queueJobs:F,currentlyExecuting:M,historicalRuns:R,isServerOutOfDate:B,serverVersion:G,npmUpdate:v!=null&&v.updateAvailable&&v.latestVersion?{latestVersion:v.latestVersion,currentVersion:v.currentVersion}:null,labs:((h=b.metadata)==null?void 0:h.labs)??null,simulationsEnabled:H,isSimulationsReady:re,isAdmin:!!process.env.CODEYAM_ADMIN,displayVersion:xa()};return W(O)}catch(p){return p instanceof Response&&p.status===499||console.error("Failed to load root data:",p),W(bu)}}function wu(){const{currentRun:e,projectSlug:t,currentEntities:r,availableAPIKeys:a,queuedJobCount:s,queueJobs:o,currentlyExecuting:i,historicalRuns:c,isServerOutOfDate:d,serverVersion:m,npmUpdate:u,labs:h,simulationsEnabled:p,isSimulationsReady:f,isAdmin:g,displayVersion:y}=Be(),{toasts:x,closeToast:v}=ua(),b=it(),w=Ne(b),C=er();ee(()=>{w.current=b},[b]);const k=C.pathname.startsWith("/entity/")&&C.pathname.includes("/edit/")||C.pathname.startsWith("/dev/"),N=C.pathname.includes("/fullscreen");return ee(()=>{const E=new EventSource("/api/events");let S=null,M=0;const F=2e3;return E.addEventListener("message",L=>{const P=JSON.parse(L.data);if(P.type==="queue")w.current.revalidate(),M=Date.now();else if(P.type==="db-change"||P.type==="unknown"){const T=Date.now(),$=T-M;$<F?(S&&clearTimeout(S),S=setTimeout(()=>{w.current.revalidate(),M=Date.now(),S=null},F-$)):(w.current.revalidate(),M=T)}}),E.addEventListener("error",L=>{console.error("SSE connection error:",L)}),()=>{S&&clearTimeout(S),E.close()}},[]),l(le,{children:[l("div",{className:`min-h-screen ${k?"":"grid"} bg-cygray-10`,style:k?void 0:{gridTemplateColumns:"65px minmax(0, 1fr)"},children:[!k&&n(nc,{labs:h,isAdmin:g}),l("div",{className:"bg-cygray-10 flex flex-col min-h-screen",children:[d&&n(Gd,{serverVersion:m}),u&&u.currentVersion&&n(qd,{currentVersion:u.currentVersion,latestVersion:u.latestVersion}),p&&a.length===0&&n(gs,{text:"No AI API keys configured. Please provide an AI API key at your earliest convenience.",subtext:"An API key is required for stable, frequent use of CodeYam",linkText:"Configure API Keys",linkTo:"/settings"}),p&&!f&&n(gs,{text:"Simulations enabled but not yet configured",subtext:"Run /codeyam-setup in Claude Code to install the analyzer and configure your dev server",linkText:"View Labs",linkTo:"/labs"}),n("div",{className:"flex-1",children:n(Oi,{})}),n(Jd,{version:y})]})]}),n(sc,{toasts:x,onClose:v}),!N&&p&&n(oc,{currentRun:e,projectSlug:t,currentEntities:r,isAnalysisStarting:!1,queuedJobCount:s,queueJobs:o,currentlyExecuting:i,historicalRuns:c})]})}const Cu=De(function(){return l("html",{lang:"en",children:[l("head",{children:[n("meta",{charSet:"utf-8"}),n("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),n(Ri,{}),n(Di,{})]}),l("body",{children:[n(rc,{children:n(ec,{children:n(wu,{})})}),n(Li,{}),n(Fi,{})]})]})}),Nu=Object.freeze(Object.defineProperty({__proto__:null,default:Cu,links:xu,loader:vu},Symbol.toStringTag,{value:"Module"}));function ys(e){const t=e.replace(/[^a-zA-Z0-9_]+/g,"_");return t.slice(0,1).toUpperCase()+t.slice(1)}function gn({analysisId:e,scenarioId:t,scenarioName:r,projectSlug:a,enabled:s=!0,refreshTrigger:o=0}){const i=Ee(),[c,d]=_(null),[m,u]=_(!1),[h,p]=_(!1),[f,g]=_(!1),y=Ne(!1),x=Ne(null),v=Ne(null),[b,w]=_(0),[C,k]=_(0),N=Ne(null),E=Ne(!1),{interactiveUrl:S,resetLogs:M}=bt(a,s),F=Ne(t),L=Ne(o);ee(()=>{L.current!==o&&(L.current=o,c&&(console.log("[useInteractiveMode] Manual refresh triggered"),p(!0),g(!1),w(0),k(T=>T+1),E.current=!1,N.current&&(clearTimeout(N.current),N.current=null)))},[o,c]),ee(()=>{if(F.current!==t&&(F.current=t,x.current&&v.current&&r)){const T=ys(v.current),$=ys(r),I=x.current.replace(T,$);d(I),p(!0),g(!1),w(0),k(J=>J+1),E.current=!1,N.current&&(clearTimeout(N.current),N.current=null);return}},[t,r]),ee(()=>{if(S){const T=S+"?width=600px";x.current=T,r&&(v.current=r),d(T),u(!1),p(!0)}},[S]),ee(()=>{const T=$=>{$.data.type==="codeyam-resize"&&(E.current||(E.current=!0,N.current&&(clearTimeout(N.current),N.current=null),w(0),g(!0),requestAnimationFrame(()=>{requestAnimationFrame(()=>{p(!1)})})))};return window.addEventListener("message",T),()=>window.removeEventListener("message",T)},[]);const P=()=>{E.current=!1,N.current&&clearTimeout(N.current);const T=500*Math.pow(2,b);N.current=setTimeout(()=>{E.current||(b<2?(w($=>$+1),k($=>$+1),p(!0)):(console.error("[useInteractiveMode] Interactive mode failed to load after 3 attempts - showing iframe anyway"),g(!0),p(!1)))},T)};return ee(()=>{s&&!y.current&&t&&e&&(y.current=!0,u(!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:",$)}M(),i.submit({action:"start",analysisId:e,scenarioId:t},{method:"post",action:"/api/interactive-mode"})})())},[s,t,e,M,a]),ee(()=>{const T=e,$=()=>{if(y.current&&T){const J=new URLSearchParams({action:"stop",analysisId:T});console.log("[useInteractiveMode] Sending stop request via sendBeacon");const V=navigator.sendBeacon("/api/interactive-mode",J);console.log("[useInteractiveMode] sendBeacon result:",V),V||(console.log("[useInteractiveMode] sendBeacon failed, using fetch fallback"),fetch("/api/interactive-mode",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:J,keepalive:!0}).catch(U=>console.error("Failed to stop interactive mode:",U)))}},I=()=>{$()};return window.addEventListener("beforeunload",I),()=>{window.removeEventListener("beforeunload",I),console.log("[useInteractiveMode] Cleanup running:",{hasStarted:y.current,analysisId:T}),$()}},[e]),{interactiveServerUrl:c,isStarting:m,isLoading:h,showIframe:f,iframeKey:C,onIframeLoad:P}}const Sn=10,Su=1024;function Oo({currentViewportWidth:e,currentPresetName:t,onDevicePresetClick:r,devicePresets:a,onHoverChange:s,hideLabel:o=!1,lightMode:i=!1}){const[c,d]=_(null),m=Ne(null),u=ae(()=>[...a].sort((b,w)=>b.width-w.width),[a]),{fittingPresets:h,overflowPresets:p}=ae(()=>{const b=[],w=[];for(const C of u)C.width<=Su?b.push(C):w.push(C);return w.sort((C,k)=>k.width-C.width),{fittingPresets:b,overflowPresets:w}},[u]),f=ie(b=>{if(!m.current)return null;const w=m.current.getBoundingClientRect(),C=b-w.left,k=w.width,N=k/2,S=(h.length>0?h[h.length-1].width:0)/2,M=N-S,F=N+S,L=p.length>0?(p.length-1)*Sn:0;if(p.length>0){if(C<M){if(C<=L){const T=Math.min(Math.floor(C/Sn),p.length-1);return p[T]}return p[p.length-1]}if(C>F){const T=k-C;if(T<=L){const $=Math.min(Math.floor(T/Sn),p.length-1);return p[$]}return p[p.length-1]}}const P=Math.abs(C-N);for(let T=h.length-1;T>=0;T--){const $=h[T],I=h[T-1],J=$.width/2,V=I?I.width/2:0;if(P<=J&&P>=V)return $}return h[0]||p[p.length-1]||null},[h,p]),g=ie(b=>{const w=f(b.clientX);d(w),s==null||s(w)},[f,s]),y=ie(()=>{d(null),s==null||s(null)},[s]),x=ie(b=>{const w=f(b.clientX);w&&r(w)},[f,r]),v=c||{name:t,width:e};return l("div",{ref:m,className:"relative h-6 shrink-0 overflow-hidden cursor-pointer",onMouseMove:g,onMouseLeave:y,onClick:x,children:[c&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:n("div",{className:"h-full transition-all duration-100 bg-[#005C75]",style:{width:`${c.width}px`}})}),n("div",{className:"absolute inset-0 pointer-events-none",children:h.map(b=>{const w=b.width===e,C=(c==null?void 0:c.name)===b.name,k=b.width/2;return l("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% - ${k}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${w||C?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% + ${k}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${w||C?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},b.name)})}),n("div",{className:"absolute inset-0 pointer-events-none",children:p.map((b,w)=>{const C=w*Sn,k=b.width===e,N=(c==null?void 0:c.name)===b.name;return l("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`${C}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${k||N?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{right:`${C}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${k||N?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},b.name)})}),!o&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:l("div",{className:`text-[10px] px-2 py-0.5 rounded shadow-sm whitespace-nowrap transition-colors ${c?"bg-[#005c75] text-white":"bg-white/90 text-[#005c75] border border-[rgba(0,92,117,0.25)]"}`,children:[v.name," - ",v.width,"px"]})})]})}function zo({width:e,height:t,onSave:r,onCancel:a}){const[s,o]=_(""),[i,c]=_(""),d=()=>{const u=s.trim();if(!u){c("Please enter a name for this custom size");return}r(u)};return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:l("div",{className:"bg-white rounded-lg max-w-md w-full p-6 shadow-xl",children:[l("div",{className:"flex items-center justify-between mb-6",children:[n("h2",{className:"text-xl font-semibold text-gray-900",children:"Save Custom Size"}),n("button",{onClick: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"})})})]}),l("div",{className:"mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-sm text-gray-500 mb-1",children:"Dimensions"}),l("div",{className:"text-lg font-medium text-gray-900",children:[e,"px × ",t,"px"]})]}),l("div",{className:"mb-6",children:[n("label",{htmlFor:"custom-size-name",className:"block text-sm font-medium text-gray-700 mb-2",children:"Name"}),n("input",{id:"custom-size-name",type:"text",value:s,onChange:u=>{o(u.target.value),c("")},onKeyDown:u=>{u.key==="Enter"&&s.trim()&&d(),u.key==="Escape"&&a()},placeholder:"e.g., iPhone 15 Pro",className:`w-full px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] ${i?"border-red-300":"border-gray-300"}`,autoFocus:!0}),i&&n("p",{className:"mt-1 text-sm text-red-600",children:i})]}),l("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 Yo(e){const[t,r]=_([]),a=e?`codeyam-custom-sizes-${e}`:null;ee(()=>{if(!a||typeof window>"u"){r([]);return}try{const c=localStorage.getItem(a);if(c){const d=JSON.parse(c);Array.isArray(d)&&r(d)}}catch(c){console.error("[useCustomSizes] Failed to load custom sizes:",c),r([])}},[a]);const s=ie(c=>{if(!(!a||typeof window>"u"))try{localStorage.setItem(a,JSON.stringify(c))}catch(d){console.error("[useCustomSizes] Failed to save custom sizes:",d)}},[a]),o=ie((c,d,m)=>{r(u=>{const h=u.findIndex(g=>g.name===c),p={name:c,width:d,height:m};let f;return h>=0?(f=[...u],f[h]=p):f=[...u,p],s(f),f})},[s]),i=ie(c=>{r(d=>{const m=d.filter(u=>u.name!==c);return s(m),m})},[s]);return{customSizes:t,addCustomSize:o,removeCustomSize:i}}function qn(){return l("div",{className:"spinner-container",children:[n("span",{className:"loader"}),n("style",{children:`
40
- .loader {
41
- width: 48px;
42
- height: 48px;
43
- border: 3px solid rgba(0, 92, 117, 0.2);
44
- border-radius: 50%;
45
- display: inline-block;
46
- position: relative;
47
- box-sizing: border-box;
48
- animation: rotation 1s linear infinite;
49
- }
50
- .loader::after {
51
- content: '';
52
- box-sizing: border-box;
53
- position: absolute;
54
- left: 50%;
55
- top: 50%;
56
- transform: translate(-50%, -50%);
57
- width: 56px;
58
- height: 56px;
59
- border-radius: 50%;
60
- border: 3px solid;
61
- border-color: #005c75 transparent;
62
- }
63
-
64
- @keyframes rotation {
65
- 0% {
66
- transform: rotate(0deg);
67
- }
68
- 100% {
69
- transform: rotate(360deg);
70
- }
71
- }
72
- `})]})}const xs=["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"],ku=80;function Kn(){const[e,t]=_(0);return ee(()=>{const r=setInterval(()=>{t(a=>(a+1)%xs.length)},ku);return()=>clearInterval(r)},[]),n("span",{className:"inline-block mr-2",children:xs[e]})}async function Eu({params:e}){var c;const{sha:t,scenarioId:r}=e;if(!t||!r)throw W("Invalid parameters",{status:400});const a=await zt(t);if(!a)throw W("Entity not found",{status:404});const s=await fa(a),o=((c=s==null?void 0:s.scenarios)==null?void 0:c.find(d=>d.id===r))||null;if(!o)throw W("Scenario not found",{status:404});const i=await $e();return W({entity:a,scenario:o,analysis:s,projectSlug:i})}const Dr=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],Au=De(function(){const{entity:t,scenario:r,analysis:a,projectSlug:s}=Be(),o=It(),[i]=cn(),[c,d]=_(null),[m,u]=_(1440),[h,p]=_({name:"Desktop",width:1440,height:900}),[f,g]=_(!1),[y,x]=_(null),{customSizes:v,addCustomSize:b}=Yo(s),w=ae(()=>[...Dr,...v],[v]),{interactiveServerUrl:C,isStarting:k,isLoading:N,showIframe:E,iframeKey:S,onIframeLoad:M}=gn({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:F}=bt(s,k||N),L=()=>{o(`/entity/${t.sha}`)},P=(B,H)=>{u(B);const re=w.find(j=>j.width===B&&j.height===H);d(re||null),p({name:(re==null?void 0:re.name)||"Custom",width:B,height:H})},T=B=>{d(B),u(B.width),p({name:B.name,width:B.width,height:B.height})},$=B=>{b(B,h.width,h.height??900),g(!1),p(H=>({...H,name:B}))},I=((a==null?void 0:a.scenarios)||[]).filter(B=>{var H;return!((H=B.metadata)!=null&&H.sameAsDefault)}),J=I.findIndex(B=>B.id===(r==null?void 0:r.id)),V=J+1,U=I.length,z=J>0,Y=J<I.length-1,R=()=>{if(z){const B=I[J-1],H=encodeURIComponent(`/entity/${t.sha}/scenarios/${B.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${B.id}/fullscreen?from=${H}`)}},A=()=>{if(Y){const B=I[J+1],H=encodeURIComponent(`/entity/${t.sha}/scenarios/${B.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${B.id}/fullscreen?from=${H}`)}},G=k||N||!E;return l("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[l("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:[l("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n("img",{src:so,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),l("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:R,disabled:!z,className:`${z?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),l("span",{className:"text-gray-400 text-sm",children:[V,"/",U]}),n("button",{onClick:A,disabled:!Y,className:`${Y?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Next scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M7.5 15L12.5 10L7.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),l("div",{className:"flex items-center gap-2 ml-2 min-w-0",children:[n("span",{className:"text-white font-semibold text-xs whitespace-nowrap shrink-0",children:r==null?void 0:r.name}),(r==null?void 0:r.description)&&l("div",{className:"relative group min-w-0",children:[n("span",{className:"text-gray-400 text-xs truncate block",children:r.description}),n("div",{className:"absolute left-0 top-full mt-1 hidden group-hover:block z-50 bg-black text-white text-xs px-3 py-2 rounded shadow-lg max-w-md",children:r.description})]})]})]}),n("button",{onClick:L,className:"text-white hover:text-gray-300 transition-colors ml-4","aria-label":"Close fullscreen",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M15 5L5 15M5 5L15 15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),l("div",{className:"bg-[#e5e7eb] border-b border-[rgba(0,0,0,0.1)] shrink-0 z-10 h-6 flex items-center justify-center relative",children:[n("div",{className:"absolute inset-0 flex justify-center",children:n("div",{style:{maxWidth:`${Dr[Dr.length-1].width}px`,width:"100%"},children:n(Oo,{currentViewportWidth:m,currentPresetName:h.name,onDevicePresetClick:T,devicePresets:w,hideLabel:!0,onHoverChange:x,lightMode:!0})})}),l("div",{className:"relative z-10 flex items-center gap-2",children:[l("div",{className:"relative w-28 h-5",children:[l("div",{className:"absolute inset-0 bg-white text-gray-900 text-xs px-2 rounded flex items-center justify-between pointer-events-none border border-gray-300",children:[n("span",{className:"leading-none",children:(y==null?void 0:y.name)||h.name}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),l("select",{value:h.name,onChange:B=>{const H=w.find(re=>re.name===B.target.value);H&&T(H)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[w.map(B=>n("option",{value:B.name,children:B.name},B.name)),h.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:h.width,onChange:B=>{const H=parseInt(B.target.value,10);!isNaN(H)&&H>0&&P(H,h.height??900)},className:"bg-white text-gray-900 text-xs px-1 rounded border border-gray-300 outline-none w-16 text-center h-5 leading-none",min:"200",max:"3840"}),n("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"×"}),n("span",{className:"bg-gray-100 text-gray-600 text-xs px-1 rounded w-14 text-center h-5 flex items-center justify-center leading-none",children:h.height??900}),h.name==="Custom"&&n("button",{onClick:()=>g(!0),className:"bg-white text-gray-900 text-xs px-2 rounded h-5 flex items-center leading-none border border-gray-300 hover:bg-gray-50 transition-colors",children:"Save"})]})]}),n("div",{className:"flex-1 flex items-center justify-center overflow-auto p-8",style:{backgroundImage:`
73
- linear-gradient(45deg, #ebebeb 25%, transparent 25%),
74
- linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
75
- linear-gradient(45deg, transparent 75%, #ebebeb 75%),
76
- linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
77
- `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:C?l("div",{className:"relative bg-white w-full h-full",style:{maxWidth:`${h.width}px`,maxHeight:`${h.height}px`},children:[G&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:l("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(qn,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),F&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Kn,{}),F]})]})]})}),n("iframe",{src:C,className:"w-full h-full border-none",title:`Interactive preview: ${r==null?void 0:r.name}`,onLoad:M,style:{opacity:E?1:0}},S)]}):l("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(qn,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),F&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Kn,{}),F]})]})]})}),f&&n(zo,{width:h.width,height:h.height??900,onSave:$,onCancel:()=>g(!1)})]})}),_u=Object.freeze(Object.defineProperty({__proto__:null,default:Au,loader:Eu},Symbol.toStringTag,{value:"Module"})),Bo=aa({dimensions:{height:720,width:1200},updateDimensions:()=>{},iframeRef:{current:null},scale:1,updateScale:()=>{},maxWidth:1200,updateMaxWidth:()=>{}}),ba=()=>{const e=tr(Bo);if(!e)throw new Error("useWebContainer must be used within a WebContainerProvider");return e},fr=({children:e})=>{const[t,r]=_({height:720,width:1200}),[a,s]=_(1),[o,i]=_(1200),c=Ne(null),d=ie(({height:h,width:p})=>{r(f=>({height:h??f.height,width:p??f.width}))},[]),m=ie(h=>{s(h)},[]),u=ie(h=>{i(h)},[]);return n(Bo.Provider,{value:{dimensions:t,updateDimensions:d,iframeRef:c,scale:a,updateScale:m,maxWidth:o,updateMaxWidth:u},children:e})},Pu=typeof window<"u";function Mu(){const[e,t]=_(null);return ee(()=>{import("react-resizable").then(r=>{t(()=>r.ResizableBox)}),Promise.resolve({ })},[]),e}const Tu=1200,ju=720,bs=30,Iu=({id:e,scenarioName:t,iframeUrl:r,defaultWidth:a=1440,defaultHeight:s=900,onDataOverride:o,onIframeLoad:i,onScaleChange:c,onDimensionChange:d})=>{const m=Mu(),[u,h]=_(!1),[p,f]=_(!1),[g,y]=_(Tu),[x,v]=_(ju),[b,w]=_(null),[C,k]=_(null),{dimensions:N,updateDimensions:E,iframeRef:S,updateScale:M,updateMaxWidth:F}=ba(),L=ae(()=>Math.min(1,g/N.width),[g,N.width]),P=C!==null?C:L;ee(()=>{u||(M(P),c==null||c(P))},[P,M,c,u]),ee(()=>{F(g)},[g,F]);const T=ie(()=>{h(!0),k(L)},[L]),$=ie(()=>{h(!1),k(null)},[]),I=ie((Y,R)=>{const A=C!==null?C:1,G=Math.round(R.size.width/A);E({width:G}),d==null||d(G,N.height)},[E,C,d,N.height]),J=ie(()=>{setTimeout(()=>{f(!0)},100),i&&i()},[i]);ee(()=>{const Y=R=>{if(R.data.type==="codeyam-resize"){if(t&&R.data.name!==t||N.height===R.data.height||R.data.height===0)return;E({height:R.data.height})}};return window.addEventListener("message",Y),()=>{window.removeEventListener("message",Y)}},[S,t,a,N,E]),ee(()=>{p&&o&&o(S.current)},[p,o,S]),ee(()=>{if(!t)return;const Y=setInterval(()=>{var R,A;(A=(R=S==null?void 0:S.current)==null?void 0:R.contentWindow)==null||A.postMessage({type:"codeyam-respond",name:t},"*")},1e3);return()=>clearInterval(Y)},[t,S]),ee(()=>{const Y=()=>{const R=document.getElementById("scenario-container");if(!R)return;const A=R.getBoundingClientRect(),G=R.clientWidth-bs*2,B=window.innerHeight-A.top-bs*2,H=Math.max(B,400),re=window.innerHeight-A.top;y(G),v(H),w(re)};return Y(),window.addEventListener("resize",Y),()=>window.removeEventListener("resize",Y)},[]),ee(()=>{E({width:a,height:s})},[a,s,E]);const V=ae(()=>N.width*P,[N.width,P]),U=ae(()=>{const Y=N.height,R=Y*P;return Y&&Y!==720&&Y!==900&&R<x?R:x},[N.height,x,P]),z=ie(()=>{window.history.back()},[]);return!Pu||!m?n("div",{className:"relative bg-gray-100 w-full h-full flex items-center justify-center",children:n("p",{className:"text-gray-500",children:"Loading interactive view..."})}):l("div",{id:"scenario-container",className:"relative bg-gray-100 w-full flex items-center justify-center",style:b?{height:`${b}px`}:{},children:[u&&n("div",{className:"fixed inset-0 z-50 bg-transparent"}),n("style",{children:`
78
- .react-resizable-handle-e {
79
- display: flex !important;
80
- align-items: center !important;
81
- justify-content: center !important;
82
- width: 6px !important;
83
- height: 48px !important;
84
- right: -8px !important;
85
- top: 50% !important;
86
- transform: translateY(-50%) !important;
87
- cursor: ew-resize !important;
88
- background: #d1d5db !important;
89
- border-radius: 3px !important;
90
- opacity: 0 !important;
91
- transition: all 0.2s ease !important;
92
- }
93
- .react-resizable-handle-e:hover {
94
- opacity: 0.8 !important;
95
- background: #9ca3af !important;
96
- }
97
- .react-resizable:hover .react-resizable-handle-e {
98
- opacity: 0.4 !important;
99
- }
100
- `}),n(m,{width:V,height:U,minConstraints:[300,200],maxConstraints:[g,x],className:"relative bg-white rounded-lg shadow-md",resizeHandles:["e"],onResizeStart:T,onResizeStop:$,onResize:I,children:n("div",{className:"overflow-auto",style:{width:`${V}px`,height:`${U}px`},children:n("div",{style:{width:`${N.width}px`,height:`${N.height}px`,transform:`scale(${P})`,transformOrigin:"top left"},children:r?n("iframe",{ref:S,className:"w-full h-full rounded-lg",src:r,onLoad:J,sandbox:"allow-scripts allow-same-origin"}):l("p",{className:"w-full h-full flex flex-col gap-3 items-center justify-center",children:[n("span",{className:"text-xl font-light",children:"Oops! Looks like this scenario is not available yet. Please check back later."}),n("span",{className:"text-blue-600 cursor-pointer",onClick:z,children:"Go back"})]})})})},`resizable-box-${e}`)]})};function $u({presets:e,customSizes:t,currentWidth:r,currentHeight:a,scale:s,onSizeChange:o,onSaveCustomSize:i,onRemoveCustomSize:c,className:d=""}){const[m,u]=_(!1),[h,p]=_(String(r)),[f,g]=_(String(a)),[y,x]=_(!1),[v,b]=_(!1),w=Ne(null);ee(()=>{y||p(String(r))},[r,y]),ee(()=>{v||g(String(a))},[a,v]),ee(()=>{const P=T=>{w.current&&!w.current.contains(T.target)&&u(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[]);const C=ae(()=>{const P=e.find($=>$.width===r&&$.height===a);if(P)return P.name;const T=t.find($=>$.width===r&&$.height===a);return T?T.name:"Custom"},[e,t,r,a]),k=C==="Custom",N=P=>{o(P.width,P.height),u(!1)},E=P=>{const T=P.target.value;p(T);const $=parseInt(T,10);!isNaN($)&&$>0&&o($,a)},S=P=>{const T=P.target.value;g(T);const $=parseInt(T,10);!isNaN($)&&$>0&&o(r,$)},M=()=>{x(!1);const P=parseInt(h,10);(isNaN(P)||P<=0)&&p(String(r))},F=()=>{b(!1);const P=parseInt(f,10);(isNaN(P)||P<=0)&&g(String(a))},L=P=>{(P.key==="Enter"||P.key==="Escape")&&P.target.blur()};return l("div",{className:`flex items-center gap-3 ${d}`,children:[l("div",{className:"relative",ref:w,children:[l("button",{onClick:()=>u(!m),className:"flex items-center gap-2 px-3 py-1.5 bg-white border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 min-w-[120px] justify-between",children:[n("span",{children:C}),n("svg",{className:`w-4 h-4 transition-transform ${m?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),m&&n("div",{className:"absolute top-full left-0 mt-1 min-w-full bg-white border border-gray-200 rounded-md shadow-lg z-50",children:l("div",{className:"py-1",children:[e.length>0&&l(le,{children:[n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Presets"}),e.map(P=>l("button",{onClick:()=>N(P),className:`w-full text-left px-3 py-2 text-sm hover:bg-gray-100 flex justify-between items-center gap-4 whitespace-nowrap ${C===P.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[n("span",{children:P.name}),l("span",{className:"text-xs text-gray-500",children:[P.width," x ",P.height]})]},P.name))]}),t.length>0&&l(le,{children:[n("div",{className:"border-t border-gray-100 my-1"}),n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Custom"}),[...t].sort((P,T)=>P.width-T.width).map(P=>l("div",{className:`flex items-center gap-1 hover:bg-gray-100 ${C===P.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[l("button",{onClick:()=>N(P),className:"flex-1 text-left px-3 py-2 text-sm flex justify-between items-center gap-4 whitespace-nowrap cursor-pointer",children:[n("span",{children:P.name}),l("span",{className:"text-xs text-gray-500",children:[P.width," x ",P.height]})]}),c&&n("button",{onClick:T=>{T.stopPropagation(),C===P.name&&e.length>0&&o(e[0].width,e[0].height),c(P.name)},className:"p-1.5 mr-1 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded cursor-pointer transition-colors",title:"Remove custom size",children:n("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]},P.name))]})]})})]}),l("div",{className:"flex items-center gap-1 text-sm",children:[l("div",{className:"flex items-center",children:[n("input",{type:"text",value:h,onChange:E,onFocus:()=>x(!0),onBlur:M,onKeyDown:L,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),n("span",{className:"text-gray-400 mx-1",children:"×"}),l("div",{className:"flex items-center",children:[n("input",{type:"text",value:f,onChange:S,onFocus:()=>b(!0),onBlur:F,onKeyDown:L,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&&l("span",{className:"text-xs text-gray-500 ml-1",children:["(",Math.round(s*100),"%)"]})]}),k&&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 Lr(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 Qr(e){return e&&(typeof e=="object"||Array.isArray(e))}function Ru(e){return Array.isArray(e)?e.length:void 0}function Du(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=Qr(t[s]),c=Qr(t[o]);return i&&!c?1:!i&&c?-1:s.localeCompare(o)});if(typeof t=="object")return Object.keys(t).sort((s,o)=>s.localeCompare(o))}}function Lu({scenarioFormData:e,handleInputChange:t}){return l("div",{className:"p-3 flex flex-col gap-3",children:[l("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:"name",className:"text-sm font-medium text-gray-700",children:"Name"}),n("input",{type:"text",id:"name",placeholder:"Name",name:"name",value:e.name,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),l("div",{className:"grid w-full gap-1.5 pt-2",children:[n("label",{htmlFor:"description",className:"text-sm font-medium text-gray-700",children:"Description"}),n("textarea",{placeholder:"Type your message here.",id:"description",name:"description",value:e.description,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 min-h-[100px]"})]}),n("button",{type:"submit",className:"mt-3 w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium",children:"Save Name & Description"})]})}function Fu({path:e,namedPath:t,isArray:r,count:a,onClick:s}){const o=ie(()=>{s&&s(e)},[s,e]);return l("div",{className:"bg-blue-50 p-3 rounded-lg flex items-center justify-between cursor-pointer group hover:bg-blue-100 transition-colors border border-blue-200",onClick:o,children:[l("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-4 h-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})}),l("div",{className:"capitalize font-medium text-gray-900",children:[t[t.length-1],a!==void 0&&` (${a})`]})]}),l("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-5 h-5 text-red-500 opacity-0 group-hover:opacity-100 transition-opacity",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),n("svg",{className:"w-4 h-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]})}var Uo=(e=>(e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.UNION="union",e.OBJECT="object",e.ARRAY="array",e))(Uo||{});const Ou=({name:e,value:t,options:r,onChange:a})=>{const s=ie(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))})},zu=({name:e,value:t,onChange:r})=>{const a=ie(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
101
- bg-gray-300 checked:bg-blue-600
102
- after:content-[''] after:absolute after:top-1 after:left-1 after:w-4 after:h-4
103
- after:bg-white after:rounded-full after:transition-transform
104
- checked:after:translate-x-4`})})};function Yu({dataType:e,path:t,value:r,onChange:a}){const s=ae(()=>t[t.length-1],[t]),o=ae(()=>t.join("-"),[t]),i=ie(d=>{a(t,d.target.value)},[a,t]),c=ie(d=>{a(t,d.target.value)},[a,t]);return l("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:o,className:"capitalize text-sm font-medium text-gray-700",children:s==="~~codeyam-code~~"?"Dynamic Field":s}),e.includes("|")?n(Ou,{name:o,value:r,options:e.split("|"),onChange:i}):e===Uo.BOOLEAN?n(zu,{name:o,value:r??!1,onChange:c}):n("input",{id:o,name:o,type:"text",value:JSON.stringify(r??"").replace(/"/g,""),onChange:i,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"},`Input-${o}`)]})}function Bu({analysis:e,scenarioName:t,dataItem:r,onResult:a,onGenerateData:s}){const[o,i]=_(!1),[c,d]=_(""),m=ie(async()=>{if(!s){console.error("onGenerateData prop is required for AI data generation");return}i(!0);try{const h=e.scenarios.find(x=>x.name===t);if(!h)throw new Error("Scenario not found");const p=e.scenarios.find(x=>x.name===or),f=await s(c,r);if(!f){console.error("Error getting AI guess for scenario data"),i(!1);return}const g=(x,v)=>{const b=Object.assign({},x);return y(x)&&y(v)&&Object.keys(v).forEach(w=>{y(v[w])?w in x?b[w]=g(x[w],v[w]):Object.assign(b,{[w]:v[w]}):Object.assign(b,{[w]:v[w]})}),b},y=x=>x&&typeof x=="object"&&!Array.isArray(x);h.metadata.data=g(g((p==null?void 0:p.metadata.data)||{},h.metadata.data),f.data||{}),a(h),i(!1),d("")}catch(h){console.error("Error generating AI data:",h),i(!1)}},[e,c,r,t,a,s]),u=ie(h=>{d(h.target.value)},[]);return l("div",{className:"w-full p-3 flex flex-col gap-2 rounded-lg border-2 border-blue-200 text-sm bg-blue-50",children:[n("div",{className:"font-medium text-gray-700",children:"Describe the data changes to the AI"}),n("textarea",{className:"peer w-full h-16 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"Type your message here.",onChange:u,value:c}),n("button",{type:"button",disabled:o,className:`w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-400 disabled:cursor-not-allowed font-medium ${c.length>0?"flex":"hidden peer-focus-within:flex"} items-center justify-center gap-2`,onClick:()=>void m(),children:o?l(le,{children:[l("svg",{className:"animate-spin h-4 w-4 text-white",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Please wait"]}):"Generate Data"})]})}function Uu({namedPath:e,path:t,last:r,onClick:a}){const s=ie(()=>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 Wu({dataItem:e,onClick:t}){const r=ie(()=>t([]),[t]),a=ae(()=>e.namedPath.length>=2?e.namedPath.length-2:0,[e]);return l("div",{className:"text-sm flex items-center gap-2 py-3 px-2 border-b border-t border-gray-300 bg-gray-50",children:[n("svg",{className:"w-4 h-4 cursor-pointer hover:text-blue-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",onClick:r,children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),e.namedPath.length>2&&l("div",{className:"flex items-center gap-1",children:[n("div",{children:"..."}),n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),e.namedPath.slice(a).map((s,o)=>l("div",{className:"flex items-center gap-1",children:[n(Uu,{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 vs({analysis:e,scenarioName:t,dataItem:r,onClick:a,onChange:s,onAIResult:o,onGenerateData:i,saveFeedback:c}){const d=ae(()=>r.data,[r]),m=ae(()=>Du(r),[r]);return l("div",{className:"w-full flex flex-col gap-6 px-3 mt-3",children:[r.path.length>0&&n(Wu,{dataItem:r,onClick:a}),l("div",{className:"flex flex-col gap-3",children:[n(Bu,{analysis:e,scenarioName:t,dataItem:r,onResult:o,onGenerateData:i}),m==null?void 0:m.map((u,h)=>{var f;if(Qr(d[u])){let g=u;isNaN(Number(u))||(g=d[u].name??d[u].title??d[u].id??`${r.path[r.path.length-1].replace(/s$/,"")} ${parseInt(u)+1}`);const y=[...r.path,u],x=[...r.namedPath,g];return n(Fu,{path:y,namedPath:x,isArray:Array.isArray(d),count:Ru(d[u]),onClick:a},`data-${u}-${h}`)}if(u==="id")return null;const p=[...r.path,u];return n(Yu,{dataType:((f=r.structure)==null?void 0:f[u])??"string",path:p,value:d[u],onChange:s},`InputField-${p.join("-")}`)})]}),n("input",{type:"hidden",name:"recapture",id:"recapture-input",value:"false"}),l("div",{className:"flex gap-2",children:[n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="false")},disabled:c==null?void 0:c.isSaving,className:"flex-1 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:c!=null&&c.isSaving?"Saving...":"Save Changes"}),n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="true")},disabled:c==null?void 0:c.isSaving,className:"flex-1 px-4 py-2 bg-gray-100 text-gray-700 border border-gray-300 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Save & Recapture"})]}),(c==null?void 0:c.message)&&!(c!=null&&c.isSaving)&&n("div",{className:`mt-3 p-3 rounded-md text-sm font-medium ${c.isError?"bg-red-50 text-red-700 border border-red-200":"bg-green-50 text-green-700 border border-green-200"}`,children:c.message})]})}function ws({title:e,children:t,defaultOpen:r=!1,borderT:a=!1,borderB:s=!1}){const[o,i]=_(r),c=[];return a&&c.push("border-t"),s&&c.push("border-b"),l("div",{className:`${c.join(" ")} border-gray-300`,children:[l("button",{type:"button",onClick:()=>i(!o),className:"w-full px-4 py-3 flex items-center justify-between bg-gray-50 hover:bg-gray-100 transition-colors text-left font-semibold text-gray-900",children:[n("span",{children:e}),n("svg",{className:`transition-transform ${o?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",style:{width:"20px",height:"20px",minWidth:"20px",minHeight:"20px",maxWidth:"20px",maxHeight:"20px",flexShrink:0},children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),o&&n("div",{className:"px-4 py-3",children:t})]})}const Hu=({currentScenario:e,defaultScenario:t,dataStructure:r,analysis:a,shouldCreateNewScenario:s,onSave:o,onNavigate:i,iframeRef:c,onGenerateData:d,saveFeedback:m})=>{const u=ie((E,S)=>{const M=Object.assign({},E),F=L=>L&&typeof L=="object"&&!Array.isArray(L);return F(E)&&F(S)&&Object.keys(S).forEach(L=>{F(S[L])?L in E?M[L]=u(E[L],S[L]):Object.assign(M,{[L]:S[L]}):Object.assign(M,{[L]:S[L]})}),M},[]),[h,p]=_({name:e.name,description:e.description,data:u(t.metadata.data,e.metadata.data)}),[f,g]=_(null),y=ae(()=>({...h.data}),[h]),x=ae(()=>({...y.mockData?{"Retrieved Data":y.mockData}:{},...y.argumentsData?{"Function Arguments":y.argumentsData}:{}}),[y]),v=ae(()=>{const E={...r.arguments?{"Function Arguments":r.arguments}:{},...r.dataForMocks?{"Retrieved Data":r.dataForMocks}:{}};return Object.keys(E).reduce((S,M)=>{if(M.includes(".")){const[F,L]=M.split(".");S[F]||(S[F]={}),S[F][L]=E[M]}else S[M]=E[M];return S},{})},[r]),b=ie(async E=>{E.preventDefault();const S=E.target.querySelector('input[name="recapture"]'),M=(S==null?void 0:S.value)==="true",F={mockData:h.data.mockData??{},argumentsData:h.data.argumentsData??[]};console.log("[ScenarioEditor] Saving scenario data:",{scenarioName:h.name,shouldRecapture:M,dataToSave:F,rawFormData:h.data,iframePayload:{arguments:y.argumentsData??[],...y.mockData??{}}}),console.log("[ScenarioEditor] Full dataToSave JSON:",JSON.stringify(F,null,2).substring(0,1e3));const L=a==null?void 0:a.scenarios.map(P=>!s&&P.name===e.name?{...P,name:h.name,description:h.description,metadata:{...P.metadata,data:F}}:P);s&&L.push({name:h.name,description:h.description,metadata:{data:F,interactiveExamplePath:a==null?void 0:a.scenarios[0].metadata.interactiveExamplePath}}),console.log("[ScenarioEditor] Updated scenarios to save:",L),o&&await o(L,{recapture:M}),i&&i(h.name)},[a,e.name,h,y,s,o,i]),w=ie(E=>{p(S=>({...S,[E.target.name]:E.target.value}))},[]),C=ie(E=>{g(S=>{if(!S)return null;for(const M of[{arguments:E.metadata.data.argumentsData},E.metadata.data.mockData]){let F=M;for(const L of S.path)if(F=Lr(F,L),!F)break;F&&(S.data=F)}return{...S}}),p({name:E.name,description:E.description,data:E.metadata.data})},[]),k=ie((E,S)=>{p(M=>{for(const F of[{"Function Arguments":M.data.argumentsData},{"Retrieved Data":M.data.mockData}]){let L=F;for(const P of E.slice(0,-1))if(L=Lr(L,P),!L)break;if(L){const P=L[E[E.length-1]];g(T=>T?(T.namedPath[T.namedPath.length-1]===P&&(T.namedPath[T.namedPath.length-1]=S.toString()),T.data[E[E.length-1]]=S,{...T}):null),L[E[E.length-1]]=S}}return{...M}})},[]),N=ie(E=>{var L,P,T;if(E.length===0){g(null);return}let S=x;const M=[];let F=v;for(const $ of E){if(M.push(isNaN(parseInt($))?$:((L=S[$])==null?void 0:L.name)??((P=S[$])==null?void 0:P.title)??((T=S[$])==null?void 0:T.id)??$),S=Lr(S,$),!S){console.log("Data not found",S,$),g(null);return}Array.isArray(F)?F=F[0]:F=F[$]}g({path:E,namedPath:M,data:S,structure:F})},[x,v]);return ee(()=>{const E=S=>{var M;S.data.type==="codeyam-log"&&((M=S.data.data)!=null&&M.includes("Error"))&&console.error("[ScenarioEditor] Error from iframe:",S.data.data)};return window.addEventListener("message",E),()=>window.removeEventListener("message",E)},[]),ee(()=>{var E;if((E=c==null?void 0:c.current)!=null&&E.contentWindow){const S={arguments:y.argumentsData??[],...y.mockData??{}},M={type:"codeyam-override-data",name:e.name,data:JSON.stringify(S)};console.log("[ScenarioEditor] → SENDING codeyam-override-data:",{type:M.type,name:M.name,dataPreview:JSON.stringify(S).substring(0,200)+"...",fullData:S}),c.current.contentWindow.postMessage(M,"*")}},[y,e,c]),n("form",{method:"post",onSubmit:E=>void b(E),children:f?n(vs,{analysis:a,scenarioName:h.name,dataItem:f,onClick:N,onChange:k,onAIResult:C,onGenerateData:d,saveFeedback:m}):l(le,{children:[n(ws,{title:"Edit Name and Description",borderT:!0,children:n(Lu,{scenarioFormData:h,handleInputChange:w})}),e.metadata.data&&n(ws,{title:"Edit Scenario Data",defaultOpen:!0,borderT:!0,borderB:!0,children:n(vs,{analysis:a,scenarioName:h.name,dataItem:{path:[],namedPath:[],data:x,structure:v},onClick:N,onChange:k,onAIResult:C,onGenerateData:d,saveFeedback:m})})]})})};function gr({scenarioId:e,scenarioName:t,iframeUrl:r,isStarting:a,isLoading:s,showIframe:o,iframeKey:i,onIframeLoad:c,onScaleChange:d,onDimensionChange:m,projectSlug:u,defaultWidth:h=1440,defaultHeight:p=900,retryCount:f=0}){const{lastLine:g}=bt(u??null,a||s);return r?l("div",{className:"flex-1 min-h-0 relative",style:{background:"transparent"},children:[n("div",{style:{opacity:o?1:0,background:"transparent"},children:n(Iu,{id:e,scenarioName:t,iframeUrl:r,defaultWidth:h,defaultHeight:p,onIframeLoad:c,onScaleChange:d,onDimensionChange:m},i)}),!o&&(a||s)&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:l("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(qn,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),g&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Kn,{}),g]})]})]})})]}):n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center",children:l("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(qn,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),g&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(Kn,{}),g]})]})]})})}const Vu=({data:e})=>[{title:e!=null&&e.scenario?`Edit ${e.scenario.name} - CodeYam`:"Edit Scenario - CodeYam"},{name:"description",content:"Edit scenario data"}];async function Ju({params:e}){var d,m;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 lr(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(u=>u.id===r);if(!o)throw new Response("Scenario not found",{status:404});const i=(m=s.scenarios)==null?void 0:m.find(u=>u.name===or),c=await $e();return W({analysis:s,scenario:o,defaultScenario:i||o,entitySha:t,projectSlug:c})}function Gu(){var $,I,J;const e=Be(),t=e.analysis,r=e.scenario,a=e.defaultScenario,s=e.entitySha,o=e.projectSlug,i=It(),{iframeRef:c}=ba(),[d,m]=_(!1),[u,h]=_(null),[p,f]=_(null),[g,y]=_(!1),[x,v]=_(!1),[b,w]=_(null),{interactiveServerUrl:C,isStarting:k,isLoading:N,showIframe:E,iframeKey:S,onIframeLoad:M}=gn({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}),F=ie(async(V,U)=>{m(!0),h(null),f(null),console.log("[EditScenario] Starting save with options:",U),console.log("[EditScenario] Scenarios to save:",V);try{const z={analysis:t,scenarios:V};console.log("[EditScenario] Sending to /api/save-scenarios:",{analysisId:t.id,scenarioCount:V.length,scenarioNames:V.map(A=>A.name)});const Y=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(z)}),R=await Y.json();if(console.log("[EditScenario] API response:",R),!Y.ok||!R.success)throw new Error(R.error||"Failed to save scenarios");if(console.log("[EditScenario] Scenarios saved successfully"),U!=null&&U.recapture&&r.id&&C){console.log("[EditScenario] ========== DIRECT CAPTURE START =========="),console.log("[EditScenario] Taking screenshot from running server",{scenarioId:r.id,projectId:t.projectId,serverUrl:C}),h("Changes saved. Capturing screenshot...");const A={serverUrl:C,scenarioId:r.id,projectId:t.projectId,viewportWidth:1440};console.log("[EditScenario] Capture request body:",A);const G=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A)});console.log("[EditScenario] Capture response status:",G.status);const B=await G.json();if(console.log("[EditScenario] Capture response body:",B),!G.ok||!B.success)throw console.error("[EditScenario] Capture failed:",B),new Error(B.error||"Failed to capture screenshot");console.log("[EditScenario] Screenshot captured successfully:",B),console.log("[EditScenario] ========== DIRECT CAPTURE COMPLETE =========="),h("Recapture successful")}else if(U!=null&&U.recapture&&!C){console.log("[EditScenario] No running server, using queued recapture");const A=new FormData;A.append("analysisId",t.id||""),A.append("scenarioId",r.id||"");const G=await fetch("/api/recapture-scenario",{method:"POST",body:A}),B=await G.json();if(!G.ok||!B.success)throw new Error(B.error||"Failed to trigger recapture");console.log("Recapture queued:",B),f(B.jobId),h("Changes saved. Screenshot recapture queued.")}else h("Changes saved successfully.")}catch(z){console.error("Error saving scenarios:",z),h(`Error: ${z instanceof Error?z.message:String(z)}`)}finally{m(!1)}},[t,r.id,C]),L=ie(V=>{},[]),P=ie(async(V,U)=>{var R;const z=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:V,existingScenarios:t.scenarios,scenariosDataStructure:(R=t.metadata)==null?void 0:R.scenariosDataStructure,editingMockName:r.name,editingMockData:U==null?void 0:U.data})}),Y=await z.json();if(!z.ok||!Y.success)throw new Error(Y.error||"Failed to generate scenario data");return Y.data},[t,r.name]),T=ie(async()=>{var V;if(!r.id){w("Cannot delete scenario without ID");return}y(!0),w(null);try{const U=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:r.id,screenshotPaths:((V=r.metadata)==null?void 0:V.screenshotPaths)||[]})}),z=await U.json();if(!U.ok||!z.success)throw new Error(z.error||"Failed to delete scenario");i(`/entity/${s}`)}catch(U){console.error("[EditScenario] Error deleting scenario:",U),w(U instanceof Error?U.message:"Failed to delete scenario"),v(!1)}finally{y(!1)}},[r.id,($=r.metadata)==null?void 0:$.screenshotPaths,s,i]);return l("div",{className:"h-screen bg-gray-50 flex flex-col",children:[l("header",{className:"bg-white border-b border-gray-200 px-8 py-6 shrink-0",children:[n("div",{className:"mb-4",children:l(se,{to:`/entity/${s}`,className:"text-blue-600 no-underline text-sm font-medium transition-colors hover:text-blue-700 hover:underline",children:["← Back to ",(I=t.entity)==null?void 0:I.name]})}),l("h1",{className:"text-[32px] font-bold text-gray-900 m-0 mb-3",children:["Edit Scenario: ",r.name]}),r.description&&n("p",{className:"text-gray-600 text-[15px] leading-relaxed m-0",children:r.description})]}),l("div",{className:"flex flex-1 gap-0 min-h-0",children:[l("aside",{className:"w-[400px] bg-white border-r border-gray-200 overflow-y-auto shrink-0",children:[n(Hu,{currentScenario:r,defaultScenario:a,dataStructure:((J=t.metadata)==null?void 0:J.scenariosDataStructure)||{},analysis:t,shouldCreateNewScenario:!1,onSave:F,onNavigate:L,iframeRef:c,onGenerateData:P,saveFeedback:{isSaving:d,message:u,isError:(u==null?void 0:u.startsWith("Error"))??!1}}),u==="Recapture successful"&&n("div",{className:"px-4 pb-4",children:n(se,{to:`/entity/${s}`,className:"text-blue-600 hover:text-blue-700 hover:underline text-sm",children:"View updated screenshot on entity page →"})}),l("div",{className:"border-t border-gray-200 p-4 mt-4",children:[n("div",{className:"text-sm text-gray-600 mb-3",children:"Permanently remove this scenario and its screenshots."}),x?l("div",{className:"space-y-3",children:[l("div",{className:"text-sm text-red-600 font-medium",children:['Are you sure you want to delete "',r.name,'"?']}),l("div",{className:"flex gap-2",children:[n("button",{onClick:()=>void T(),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:()=>v(!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:()=>v(!0),className:"w-full px-4 py-2 bg-red-50 text-red-600 border border-red-200 rounded-md text-sm font-medium hover:bg-red-100 transition-colors",children:"Delete Scenario"}),b&&n("div",{className:"mt-3 text-sm text-red-600 bg-red-50 px-3 py-2 rounded-md",children:b})]})]}),n("main",{className:"flex-1 bg-gray-100 overflow-auto flex flex-col min-w-0",children:n(gr,{scenarioId:r.id||r.name,scenarioName:r.name,iframeUrl:C,isStarting:k,isLoading:N,showIframe:E,iframeKey:S,onIframeLoad:M,projectSlug:o,defaultWidth:1440,defaultHeight:900})})]})]})}const qu=De(function(){return n(fr,{children:n(Gu,{})})}),Ku=Object.freeze(Object.defineProperty({__proto__:null,default:qu,loader:Ju,meta:Vu},Symbol.toStringTag,{value:"Module"}));function Qu({executionFlows:e,selections:t,onChange:r,disabled:a=!1}){const s=ie(i=>t.some(c=>c.flowId===i),[t]),o=ie(i=>{s(i.id)?r(t.filter(c=>c.flowId!==i.id)):r([...t,{flowId:i.id,flowName:i.name}])},[t,r,s]);return e.length===0?n("div",{className:"text-sm text-gray-500 py-2",children:"No execution flows found."}):n("div",{className:"space-y-3",children:e.map(i=>{const c=s(i.id),d=i.usedInScenarios.length>0;return l("div",{className:"border-b border-gray-100 pb-3 last:border-0 last:pb-0",children:[l("label",{className:"flex items-start gap-2 cursor-pointer",children:[n("input",{type:"checkbox",checked:c,onChange:()=>o(i),disabled:a,className:"mt-0.5 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-mono text-sm font-medium text-gray-900",children:i.name}),!d&&n("span",{className:"text-xs px-1.5 py-0.5 bg-amber-100 text-amber-700 rounded",children:"uncovered"}),i.blocksOtherFlows&&n("span",{className:"text-xs px-1.5 py-0.5 bg-purple-100 text-purple-700 rounded",children:"blocking"}),i.impact==="high"&&n("span",{className:"text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"high impact"})]}),i.description&&n("p",{className:"text-xs text-gray-500 mt-0.5 m-0",children:i.description})]})]}),c&&i.requiredValues.length>0&&l("div",{className:"ml-6 mt-2 p-2 bg-gray-50 rounded text-xs",children:[n("span",{className:"text-gray-700 font-medium",children:"Required values:"}),n("ul",{className:"m-0 mt-1 pl-4 space-y-0.5",children:i.requiredValues.map((m,u)=>l("li",{className:"text-gray-600",children:[n("code",{className:"bg-gray-100 px-1 rounded",children:m.attributePath})," ",n("span",{className:"text-gray-400",children:m.comparison})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:m.value})]},u))})]})]},i.id)})})}function va(e,t){const r=(e||[]).map(d=>({...d,usedInScenarios:[]})),a=new Map;r.forEach(d=>{a.set(d.id,d)});const s=[];t.forEach(d=>{var u;const m=((u=d.metadata)==null?void 0:u.coveredFlows)||[];m.forEach(h=>{const p=a.get(h);p&&p.usedInScenarios.push({id:d.id||"",name:d.name})}),s.push({scenario:d,coveredFlowIds:m})});const o=r.length,i=r.filter(d=>d.usedInScenarios.length>0).length,c=o>0?i/o*100:0;return{executionFlows:r,totalFlows:o,coveredFlows:i,coveragePercentage:c,scenariosWithFlows:s}}function Zu(e){return e.executionFlows.filter(t=>t.usedInScenarios.length===0)}const Xu=({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 em({params:e}){var i;const{sha:t}=e;if(!t)throw new Response("Entity SHA is required",{status:400});const r=await lr(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(c=>c.name===or);if(!s)throw new Response("Default scenario not found",{status:404});const o=await $e();return W({analysis:a,defaultScenario:s,entity:a.entity,entitySha:t,projectSlug:o})}function tm(){var z;const{analysis:e,defaultScenario:t,entity:r,entitySha:a,projectSlug:s}=Be(),o=It(),{iframeRef:i}=ba(),[c,d]=_(""),[m,u]=_(400),[h,p]=_(!1),[f,g]=_(!1),[y,x]=_(!1),[v,b]=_(null),[w,C]=_(null),[k,N]=_([]),E=ae(()=>{var R;return!((R=e==null?void 0:e.metadata)!=null&&R.executionFlows)||!(e!=null&&e.scenarios)?[]:va(e.metadata.executionFlows,e.scenarios).executionFlows},[e]),{interactiveServerUrl:S,isStarting:M,isLoading:F,showIframe:L,iframeKey:P,onIframeLoad:T}=gn({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}),$=ie(async()=>{var Y,R,A,G;if(!c.trim()&&k.length===0){b("Please describe how you want to change the scenario or select execution flows");return}g(!0),b(null),C("Generating scenario with AI...");try{const B=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:c,existingScenarios:e.scenarios,scenariosDataStructure:(Y=e.metadata)==null?void 0:Y.scenariosDataStructure,flowSelections:k.length>0?k:void 0})}),H=await B.json();if(!B.ok||!H.success)throw new Error(H.error||"Failed to generate scenario data");console.log("[CreateScenario] AI generated scenario:",H.data);const re=H.data;if(!re.name||!re.data)throw new Error("AI response missing required fields (name or data)");C("Saving new scenario..."),x(!0);const O={name:re.name,description:re.description||c,metadata:{data:re.data,interactiveExamplePath:(R=t.metadata)==null?void 0:R.interactiveExamplePath}},j=[...e.scenarios||[],O],D=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:e,scenarios:j})}),q=await D.json();if(!D.ok||!q.success)throw new Error(q.error||"Failed to save scenario");console.log("[CreateScenario] Scenario saved:",q);const te=(G=(A=q.analysis)==null?void 0:A.scenarios)==null?void 0:G.find(de=>de.name===re.name);if(!(te!=null&&te.id)){console.warn("[CreateScenario] Could not find saved scenario ID, navigating to entity page"),C("Scenario created! Redirecting..."),setTimeout(()=>void o(`/entity/${a}`),1e3);return}if(S){C("Capturing screenshot...");const de=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:S,scenarioId:te.id,projectId:e.projectId,viewportWidth:1440})}),ge=await de.json();!de.ok||!ge.success?(console.error("[CreateScenario] Capture failed:",ge),C("Scenario created! (Screenshot capture failed)")):C("Scenario created and captured!")}else C("Scenario created!");setTimeout(()=>{o(`/entity/${a}/scenarios/${te.id}`)},1e3)}catch(B){console.error("[CreateScenario] Error:",B),b(B instanceof Error?B.message:String(B)),C(null)}finally{g(!1),x(!1)}},[c,k,e,t,a,S,o]),I=f||y,J=ie(()=>{p(!0)},[]),V=ie(Y=>{if(!h)return;const R=Y.clientX;R>=250&&R<=600&&u(R)},[h]),U=ie(()=>{p(!1)},[]);return ee(()=>(h?(document.addEventListener("mousemove",V),document.addEventListener("mouseup",U)):(document.removeEventListener("mousemove",V),document.removeEventListener("mouseup",U)),()=>{document.removeEventListener("mousemove",V),document.removeEventListener("mouseup",U)}),[h,V,U]),l("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:l("div",{className:"flex items-end h-full px-6 gap-6",children:[l("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[n("button",{onClick:()=>void o(`/entity/${a}`),className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:r==null?void 0:r.name}),n("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:r==null?void 0:r.filePath,children:r==null?void 0:r.filePath})]}),l("div",{className:"flex items-end gap-8 shrink-0",children:[n(se,{to:`/entity/${a}/scenarios`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-medium border-b-2",style:{color:"#005C75",borderColor:"#005C75"},children:l("span",{className:"flex items-center gap-2",children:["Scenarios",n("span",{className:"inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full bg-[#cbf3fa] text-[#005c75]",children:((z=e==null?void 0:e.scenarios)==null?void 0:z.length)||0})]})}),n(se,{to:`/entity/${a}/related`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Related Entities"}),n(se,{to:`/entity/${a}/code`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Code"}),n(se,{to:`/entity/${a}/data`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Data Structure"}),n(se,{to:`/entity/${a}/history`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"History"})]})]})}),l("div",{className:"flex flex-1 gap-0 min-h-0 relative",children:[l("aside",{className:"bg-white border-r border-gray-200 overflow-y-auto shrink-0 p-6 flex flex-col",style:{width:`${m}px`},children:[l("div",{className:"mb-6",children:[n("h2",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Default Scenario Preview"}),n("p",{className:"text-sm text-gray-600 leading-relaxed",children:"The preview on the right shows the Default Scenario. Select execution flows and/or describe how you'd like to change it."})]}),E.length>0&&l("details",{className:"mb-4 border border-gray-200 rounded-lg",children:[l("summary",{className:"px-3 py-2 text-sm font-medium text-gray-700 cursor-pointer hover:bg-gray-50 rounded-lg",children:["Select Execution Flows"," ",k.length>0&&l("span",{className:"text-blue-600",children:["(",k.length," selected)"]})]}),n("div",{className:"px-3 pb-3 pt-1 border-t border-gray-100",children:n(Qu,{executionFlows:E,selections:k,onChange:N,disabled:I})})]}),l("div",{className:"mb-4",children:[n("label",{htmlFor:"prompt",className:"block text-sm font-medium text-gray-700 mb-2",children:"Describe your scenario"}),n("textarea",{id:"prompt",value:c,onChange:Y=>d(Y.target.value),placeholder:"e.g., Show an empty state with no items...",className:"w-full h-32 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-sm resize-none",disabled:I})]}),l("div",{className:"space-y-2",children:[n("button",{onClick:()=>void $(),disabled:I||!c.trim()&&k.length===0,className:"w-full px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium cursor-pointer transition-colors hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed",children:I?"Creating...":"Create Scenario"}),w&&n("div",{className:"text-xs text-blue-600 bg-blue-50 px-2 py-1.5 rounded",children:w}),v&&n("div",{className:"text-xs text-red-600 bg-red-50 px-2 py-1.5 rounded",children:v})]})]}),l("div",{onMouseDown:J,style:{width:"20px",position:"absolute",top:0,left:`${m-10}px`,bottom:0,cursor:"col-resize",touchAction:"none",userSelect:"none",zIndex:100,pointerEvents:"auto"},children:[n("div",{style:{position:"absolute",left:"10px",top:0,bottom:0,width:"1px",background:h?"#005c75":"rgba(0,0,0,0.1)",transition:"background 0.15s ease"}}),n("div",{style:{position:"absolute",top:"50%",left:"10px",transform:"translate(-50%, -50%)",width:"8px",height:"40px",background:"#fff",border:"1px solid rgba(0,0,0,0.15)",borderRadius:"4px",cursor:"col-resize"}})]}),n("main",{className:"flex-1 overflow-auto flex items-center justify-center min-w-0",style:{backgroundImage:`
105
- linear-gradient(45deg, #ebebeb 25%, transparent 25%),
106
- linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
107
- linear-gradient(45deg, transparent 75%, #ebebeb 75%),
108
- linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
109
- `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:n(gr,{scenarioId:t.id||t.name,scenarioName:t.name,iframeUrl:S,isStarting:M,isLoading:F,showIframe:L,iframeKey:P,onIframeLoad:T,projectSlug:s,defaultWidth:1440,defaultHeight:900})})]})]})}const nm=De(function(){return n(fr,{children:n(tm,{})})}),rm=Object.freeze(Object.defineProperty({__proto__:null,default:nm,loader:em,meta:Xu},Symbol.toStringTag,{value:"Module"}));var ce;(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={}))})(ce||(ce={}));function Wo(e,t){return e?Object.values(ce.Model).includes(e)?e:(console.warn(`Invalid model in environment variable: ${e}. Falling back to ${t}`),t):t}const Ho=Wo(process.env.DEFAULT_SMALLER_MODEL,ce.Model.OPENAI_GPT4_1_MINI),am=Wo(process.env.DEFAULT_LARGER_MODEL,ce.Model.OPENAI_GPT4_1),Ze={name:"OpenAI",baseURL:"https://api.openai.com/v1",apiKeyEnvVar:"OPENAI_API_KEY"},Fr={name:"OpenRouter",baseURL:"https://openrouter.ai/api/v1",apiKeyEnvVar:"OPENROUTER_API_KEY"},sm={name:"Groq",baseURL:"https://api.groq.com/openai/v1",apiKeyEnvVar:"GROQ_API_KEY"},Or={name:"Anthropic",baseURL:"https://api.anthropic.com/v1/",apiKeyEnvVar:"ANTHROPIC_API_KEY"},mt={name:"DeepInfra",baseURL:"https://api.deepinfra.com/v1/",apiKeyEnvVar:"DEEPINFRA_API_KEY"},om={[ce.Model.OPENAI_GPT5_1]:{id:ce.Model.OPENAI_GPT5_1,provider:Ze,apiModelName:"gpt-5.1",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"none"},[ce.Model.OPENAI_GPT5]:{id:ce.Model.OPENAI_GPT5,provider:Ze,apiModelName:"gpt-5",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"minimal"},[ce.Model.OPENAI_GPT5_MINI]:{id:ce.Model.OPENAI_GPT5_MINI,provider:Ze,apiModelName:"gpt-5-mini",maxCompletionTokens:128e3,pricing:{input:.25,output:2},reasoningEffort:"minimal"},[ce.Model.OPENAI_GPT5_NANO]:{id:ce.Model.OPENAI_GPT5_NANO,provider:Ze,apiModelName:"gpt-5-nano",maxCompletionTokens:128e3,pricing:{input:.05,output:.4},reasoningEffort:"minimal"},[ce.Model.OPENAI_GPT4_1]:{id:ce.Model.OPENAI_GPT4_1,provider:Ze,apiModelName:"gpt-4.1",maxCompletionTokens:32768,pricing:{input:2,output:8}},[ce.Model.OPENAI_GPT4_1_MINI]:{id:ce.Model.OPENAI_GPT4_1_MINI,provider:Ze,apiModelName:"gpt-4.1-mini",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[ce.Model.OPENAI_GPT4_O]:{id:ce.Model.OPENAI_GPT4_O,provider:Ze,apiModelName:"gpt-4o",maxCompletionTokens:16384,pricing:{input:2.5,output:10}},[ce.Model.OPENAI_GPT4_O_MINI]:{id:ce.Model.OPENAI_GPT4_O_MINI,provider:Ze,apiModelName:"gpt-4o-mini",maxCompletionTokens:16384,pricing:{input:.15,output:.6}},[ce.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER]:{id:ce.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER,provider:Fr,apiModelName:"google/gemini-2.5-flash-lite",maxCompletionTokens:1048576,pricing:{input:.1,output:.4},reasoningEffort:"minimal"},[ce.Model.META_LLAMA_4_MAVERICK_OPENROUTER]:{id:ce.Model.META_LLAMA_4_MAVERICK_OPENROUTER,provider:Fr,apiModelName:"meta-llama/llama-4-maverick",maxCompletionTokens:1048576,pricing:{input:.15,output:.6},reasoningEffort:"minimal"},[ce.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER]:{id:ce.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER,provider:Fr,apiModelName:"deepseek/deepseek-v3.1-terminus",maxCompletionTokens:163840,pricing:{input:.23,output:.9},reasoningEffort:"minimal"},[ce.Model.OPENAI_GPT_OSS_120B_GROQ]:{id:ce.Model.OPENAI_GPT_OSS_120B_GROQ,provider:sm,apiModelName:"openai/gpt-oss-120b",maxCompletionTokens:131072,pricing:{input:.15,output:.75},reasoningEffort:"low"},[ce.Model.OPENAI_GPT_OSS_120B_DEEPINFRA]:{id:ce.Model.OPENAI_GPT_OSS_120B_DEEPINFRA,provider:mt,apiModelName:"openai/gpt-oss-120b-Turbo",maxCompletionTokens:32768,pricing:{input:.15,output:.6},reasoningEffort:"low"},[ce.Model.QWEN3_235B_INSTRUCT_DEEPINFRA]:{id:ce.Model.QWEN3_235B_INSTRUCT_DEEPINFRA,provider:mt,apiModelName:"Qwen/Qwen3-235B-A22B-Instruct-2507",maxCompletionTokens:32768,pricing:{input:.09,output:.57}},[ce.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA]:{id:ce.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA,provider:mt,apiModelName:"Qwen/Qwen3-Coder-480B-A35B-Instruct",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[ce.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA]:{id:ce.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA,provider:mt,apiModelName:"google/gemini-2.5-pro",maxCompletionTokens:1048576,pricing:{input:1.25,output:10},reasoningEffort:"low"},[ce.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA]:{id:ce.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA,provider:mt,apiModelName:"google/gemini-2.5-flash",maxCompletionTokens:1048576,pricing:{input:.3,output:2.5},reasoningEffort:"low"},[ce.Model.ANTHROPIC_CLAUDE_4_5_HAIKU]:{id:ce.Model.ANTHROPIC_CLAUDE_4_5_HAIKU,provider:Or,apiModelName:"claude-haiku-4-5",maxCompletionTokens:2e5,pricing:{input:1,output:5}},[ce.Model.ANTHROPIC_CLAUDE_4_5_SONNET]:{id:ce.Model.ANTHROPIC_CLAUDE_4_5_SONNET,provider:Or,apiModelName:"claude-sonnet-4-5",maxCompletionTokens:2e5,pricing:{input:3,output:15}},[ce.Model.ANTHROPIC_CLAUDE_4_5_OPUS]:{id:ce.Model.ANTHROPIC_CLAUDE_4_5_OPUS,provider:Or,apiModelName:"claude-opus-4-5",maxCompletionTokens:2e5,pricing:{input:5,output:25}},[ce.Model.PHIND_CODELLAMA]:{id:ce.Model.PHIND_CODELLAMA,provider:Ze,apiModelName:"phind-codellama",maxCompletionTokens:16384,pricing:{input:0,output:0}},[ce.Model.GOOGLE_GEMINI_PRO]:{id:ce.Model.GOOGLE_GEMINI_PRO,provider:mt,apiModelName:"google/gemini-pro",maxCompletionTokens:32768,pricing:{input:0,output:0}},[ce.Model.GOOGLE_PALM_2_CODE_CHAT_32K]:{id:ce.Model.GOOGLE_PALM_2_CODE_CHAT_32K,provider:mt,apiModelName:"google/palm-2-code-chat-32k",maxCompletionTokens:32768,pricing:{input:0,output:0}},[ce.Model.META_CODELLAMA_34B_INSTRUCT]:{id:ce.Model.META_CODELLAMA_34B_INSTRUCT,provider:mt,apiModelName:"meta-llama/codellama-34b-instruct",maxCompletionTokens:16384,pricing:{input:0,output:0}},[ce.Model.OPENAI_GPT4_PREVIEW]:{id:ce.Model.OPENAI_GPT4_PREVIEW,provider:Ze,apiModelName:"gpt-4-preview",maxCompletionTokens:128e3,pricing:{input:0,output:0}}};function yr(e){const t=om[e];if(!t)throw new Error(`Unknown model: ${e}`);return t}function im(e){return yr(e).maxCompletionTokens}function lm(e){return yr(e).pricing}const Cs=1e6;function cm({model:e,usage:t}){const r=lm(e);return r?t.prompt_tokens*(r.input/Cs)+t.completion_tokens*(r.output/Cs):null}function dm({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=cm({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 um({messages:{system:e,prompt:t},model:r,responseType:a,jsonSchema:s}){const o=r??Ho,i=yr(o);im(o);const c=[];return e&&c.push({role:"system",content:e}),c.push({role:"user",content:[{type:"text",text:t}]}),{messages:c,model:i.apiModelName,response_format: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}}}const Zr="/tmp/codeyam-e2e-tracking";let zr,Yr;function mm(){return zr===void 0&&(zr=process.env.CODEYAM_E2E_TRACK_DATA==="true"),zr}function hm(){return Yr===void 0&&(Yr=!process.env.CODEYAM_LLM_FIXTURES_DIR),Yr}function pm(){K.existsSync(Zr)||K.mkdirSync(Zr,{recursive:!0})}function fm(e){const t=JSON.stringify(e,null,0);return Tl.createHash("md5").update(t).digest("hex")}function gm(e,t,r){return[e].join("_")+".json"}function Vo(e,t,r,a){if(!mm())return;pm();const s=gm(e),o=Z.join(Zr,s),i=fm(t);if(hm()){const c={timestamp:Date.now(),checkpoint:e,entityName:r,scenarioName:a,dataHash:i,data:t};K.writeFileSync(o,JSON.stringify(c,null,2)),console.log(`[E2E Tracking] First run - saved snapshot: ${e} hash=${i.substring(0,8)}`)}else if(K.existsSync(o)){const c=JSON.parse(K.readFileSync(o,"utf-8")),d={matches:i===c.dataHash,firstRunHash:c.dataHash};if(d.matches)console.log(`[E2E Tracking] Match at ${e} hash=${i.substring(0,8)}`);else{d.differences=Xr(c.data,t),console.log(`[E2E Tracking] MISMATCH at ${e}`),console.log(` First run hash: ${c.dataHash}`),console.log(` Second run hash: ${i}`);const m=o.replace(".json","_DIFF.json");K.writeFileSync(m,JSON.stringify({checkpoint:e,entityName:r,scenarioName:a,firstRun:c.data,secondRun:t,differences:d.differences},null,2)),console.log(` Diff saved to: ${m}`)}}else console.log(`[E2E Tracking] No first-run snapshot found for: ${e}`)}function Xr(e,t,r=""){const a=[];if(typeof e!=typeof t)return a.push(`${r||"root"}: type mismatch (${typeof e} vs ${typeof t})`),a;if(e===null||t===null)return e!==t&&a.push(`${r||"root"}: ${JSON.stringify(e)} vs ${JSON.stringify(t)}`),a;if(Array.isArray(e)&&Array.isArray(t)){e.length!==t.length&&a.push(`${r||"root"}: array length ${e.length} vs ${t.length}`);const s=Math.max(e.length,t.length);for(let o=0;o<s;o++)a.push(...Xr(e[o],t[o],`${r}[${o}]`));return a}if(typeof e=="object"&&typeof t=="object"){const s=Object.keys(e),o=Object.keys(t),i=Array.from(new Set([...s,...o]));for(const c of i){const d=e[c],m=t[c];c in e?c in t?a.push(...Xr(d,m,`${r?r+".":""}${c}`)):a.push(`${r?r+".":""}${c}: missing in second run`):a.push(`${r?r+".":""}${c}: missing in first run`)}return a}if(e!==t){const s=JSON.stringify(e),o=JSON.stringify(t);s.length<100&&o.length<100?a.push(`${r||"root"}: ${s} vs ${o}`):a.push(`${r||"root"}: values differ (${s.length} chars vs ${o.length} chars)`)}return a}la(ia);const kn=new Fl({concurrency:100,timeout:1200*1e3,autoStart:!0}),Ns={retries:4,factor:2,minTimeout:1e3,maxTimeout:6e4,randomize:!0},ht={};async function ea({type:e,systemMessage:t,prompt:r,jsonResponse:a=!0,jsonSchema:s,model:o=Ho,attempts:i=0}){var N,E,S,M,F,L,P;if(process.env.CODEYAM_LLM_FIXTURES_DIR)return await ym(e,process.env.CODEYAM_LLM_FIXTURES_DIR,t);console.log(`CodeYam Debug: LLM Pool [queued=${kn.size}, running=${kn.pending}]`);const c=Date.now();let d,m=0;const u=yr(o),h=process.env[u.provider.apiKeyEnvVar];if(!h)throw new Error(`API key not found for provider ${u.provider.name}. Please set ${u.provider.apiKeyEnvVar} environment variable.`);console.log(`Using ${u.provider.name} for AI request`);const p=new Ll({apiKey:h,baseURL:u.provider.baseURL}),f={type:e,messages:{system:t,prompt:r},model:o,responseType:s?"json_schema":a?"json_object":"text",jsonSchema:s},g=um(f),y=await kn.add(()=>(d=Date.now(),ls(async()=>{const T=Date.now(),$=["Waiting for LLM response","Still waiting for LLM response","LLM call in progress","Processing LLM request","Awaiting LLM completion"],I=setInterval(()=>{const J=Math.floor((Date.now()-T)/1e3),V=Math.floor(J/10)%$.length;ds(1,`${$[V]} [type=${e}, model=${o}, elapsed=${J}s]`)},1e4);try{return await p.chat.completions.create(g,{timeout:300*1e3})}finally{clearInterval(I)}},{...Ns,onFailedAttempt:T=>{m++,console.log(`CodeYam Error: Completion call failed [model=${o}]`,{error:T,prompt:r,systemMessage:t,attempts:i,retryCount:m})}}))),x=Date.now(),v=dm({chatRequest:f,chatCompletion:y,model:o});if(!v)throw new Error("Failed to get LLM call stats");v.retries=m,v.wait_ms=d-c,v.duration_ms=x-c;const b=(N=y.choices)==null?void 0:N[0];let w=null;if(b){if(!b.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");w=(E=b.message)==null?void 0:E.content}let C=w;w&&(C=w.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const k=a?C&&(((S=C.match(/\{[\s\S]*\}/))==null?void 0:S[0])??C):C;if(!k){if(console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({completion:k,rawCompletion:w,chatCompletion:y,chatRequest:f},null,2)),i<3)return console.log("CodeYam Error: Retrying completion",{prompt:r,systemMessage:t,attempts:i}),await ea({type:e,systemMessage:t,prompt:r,jsonResponse:a,model:o,attempts:i+1});throw new Error("completionCall(): empty completion from LLM")}if(k.replace(/\s/g,"")==="")throw console.log("CodeYam Error: Empty Completion",{rawCompletion:w,prompt:r,systemMessage:t}),new Error("Empty completion");if(a)try{JSON.parse(k)}catch(T){if(console.log("CodeYam Error: Invalid JSON in completion",{error:T.message,model:o,completion:k.substring(0,500),rawCompletion:w==null?void 0:w.substring(0,500)}),i<3){console.log("CodeYam Error: Retrying with correction prompt",{attempts:i,parseError:T.message});const $=`Your previous response contained invalid JSON with the following error:
110
-
111
- ${T.message}
112
-
113
- Here was your previous response:
114
- \`\`\`
115
- ${k}
116
- \`\`\`
117
-
118
- Please provide a corrected version with valid JSON only. Do not include any explanatory text, just the valid JSON object.`,I=await kn.add(()=>ls(async()=>{const z=Date.now(),Y=["Waiting for LLM correction response","Still waiting for LLM correction","LLM correction in progress","Processing LLM correction request","Awaiting LLM correction completion"],R=setInterval(()=>{const A=Math.floor((Date.now()-z)/1e3),G=Math.floor(A/10)%Y.length;ds(1,`${Y[G]} [type=${e}, model=${o}, elapsed=${A}s]`)},1e4);try{return await p.chat.completions.create({...g,messages:[{role:"system",content:t},{role:"user",content:r},{role:"assistant",content:k},{role:"user",content:$}]},{timeout:300*1e3})}finally{clearInterval(R)}},{...Ns,onFailedAttempt:z=>{console.log("CodeYam Error: Correction call failed",{error:z,attempts:i})}})),J=(L=(F=(M=I.choices)==null?void 0:M[0])==null?void 0:F.message)==null?void 0:L.content;let V=J;J&&(V=J.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const U=V&&(((P=V.match(/\{[\s\S]*\}/))==null?void 0:P[0])??V);if(!U)throw new Error("Correction attempt returned empty completion");try{JSON.parse(U),console.log("CodeYam: JSON correction successful");const z=Date.now();return v.duration_ms=z-c,{finishReason:I.choices[0].finish_reason,completion:U,stats:v}}catch(z){return console.log("CodeYam Error: Corrected JSON still invalid",{error:z.message,correctedCompletion:U.substring(0,500)}),await ea({type:e,systemMessage:t,prompt:r,jsonResponse:a,model:o,attempts:i+1})}}throw new Error(`Invalid JSON after ${i} attempts: ${T.message}`)}return Vo(`completionCall_${e}`,{completion:k,finishReason:y.choices[0].finish_reason}),{finishReason:y.choices[0].finish_reason,completion:k,stats:v}}async function ym(e,t,r){var o,i,c,d,m;const a=await import("fs"),s=await import("path");console.log(`CodeYam Test: Replaying LLM call for type '${e}' from ${t}`);try{if(!a.existsSync(t))throw console.log(`CodeYam Test: Fixtures directory does not exist yet: ${t}`),new Error(`No LLM fixture files found - directory does not exist: ${t}`);const u=a.readdirSync(t).filter(b=>b.endsWith(".json"));if(u.length===0)throw new Error(`No LLM fixture files found in ${t}`);const h={};for(const b of u)try{const w=a.readFileSync(s.join(t,b),"utf-8"),C=JSON.parse(w);h[C.prompt_type]||(h[C.prompt_type]=[]),h[C.prompt_type].push(C)}catch(w){console.warn(`Failed to parse LLM fixture file ${b}:`,w)}for(const b of Object.keys(h))h[b].sort((w,C)=>{const k=w.created_at??0,N=C.created_at??0;return k-N});const p=h[e];if(!p||p.length===0){const b=Object.keys(h).join(", ");return console.warn(`CodeYam Test: No captured LLM call found for type '${e}'. Available types: ${b}`),{finishReason:"stop",completion:"{}",stats:{model:"fixture-fallback",prompt_type:e,system_message:"",prompt_text:"",response:"{}",input_tokens:0,output_tokens:0,cost:0}}}let f;if(["generateEntityScenarioData","generateChunkMockData","generateMissingMockData"].includes(e)&&r){const b=r.match(/Scenario name must match exactly: "([^"]+)"/),w=b==null?void 0:b[1];if(w){const C={};for(const N of p)try{const S=((o=JSON.parse(N.props||"{}").scenario)==null?void 0:o.name)||"__NO_SCENARIO__";C[S]||(C[S]=[]),C[S].push(N)}catch{}const k=C[w];if(k&&k.length>0){const N=`${t}::${e}::${w}`;ht[N]===void 0&&(ht[N]=0);const E=ht[N];ht[N]=(E+1)%k.length,f=k[E],console.log(`CodeYam Test: ✅ Matched fixture for scenario '${w}' [${E+1}/${k.length}]`)}else{const N=Object.keys(C).join(", ");console.warn(`CodeYam Test: ⚠️ No fixture found for scenario '${w}'. Available: [${N}]`)}}else console.warn(`CodeYam Test: ⚠️ Could not extract scenario name from system message for type '${e}'`)}if(!f){const b=`${t}::${e}`;ht[b]===void 0&&(ht[b]=0);const w=ht[b];ht[b]=(w+1)%p.length,f=p[w],console.log(`CodeYam Test: Replaying LLM response for '${e}' [${w+1}/${p.length}]`)}let y;try{y=((d=(c=(i=JSON.parse(f.response).choices)==null?void 0:i[0])==null?void 0:c.message)==null?void 0:d.content)||f.response}catch{y=f.response}let x=y;y&&(x=y.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const v=x&&(((m=x.match(/\{[\s\S]*\}/))==null?void 0:m[0])??x);return Vo(`completionCall_${e}`,{completion:v||"",finishReason:"stop"}),{finishReason:"stop",completion:v||"",stats:{model:f.model??"fixture",prompt_type:e,system_message:f.system_message??"",prompt_text:f.prompt_text??"",response:f.response??"",input_tokens:f.input_tokens??0,output_tokens:f.output_tokens??0,cost:f.cost??0,retries:0,wait_ms:0,duration_ms:1}}}catch(u){throw console.error("CodeYam Test Error: Failed to replay LLM call:",u),u}}function Ss(){return process.env.DYNAMODB_PREFIX?`${process.env.DYNAMODB_PREFIX}-llm-calls`:null}async function xm(e){const{propsJson:t,...r}=e,a=JSON.stringify(t,null,2),s=ro(),o=Date.now(),i={...r,id:s,created_at:o,props:a};let c;const d=`${i.object_id}_${s}.json`;if(process.env.DYNAMODB_PATH?c=Z.join(process.env.DYNAMODB_PATH,d):process.env.CODEYAM_LOCAL_PROJECT_PATH&&(c=Z.join(process.env.CODEYAM_LOCAL_PROJECT_PATH,".codeyam","llm-calls",d)),c)try{const u=Z.dirname(c);return await Re.mkdir(u,{recursive:!0}),await Re.writeFile(c,JSON.stringify(i,null,2)),console.log(`CodeYam: Saved LLM call to local file: ${c}`),{id:s}}catch(u){return console.log("CodeYam Error: Failed to save LLM call to local file",u),{id:"-1"}}const m=Ss();if(!m)return console.log("[CodeYam] No DynamoDB table name for LLM calls, skipping save"),{id:"-1"};for(const[u,h]of Object.entries(i))typeof h>"u"&&console.log(`CodeYam Warning: LLM call ${s} property ${u} with explicit value 'undefined'`);try{return await new sr().send(new Ol({TableName:Ss(),Item:Yl(i,{removeUndefinedValues:!0})})),{id:s}}catch(u){return console.log(`CodeYam Error: Failed to save LLM call to DynamoDB table ${m}`,u),{id:"-1"}}}new sr({});new sr({});new sr({});const bm=3,vm=2,wa=()=>({max:1e4,maxSize:10*1e3*1e3,sizeCalculation:(e,t)=>16+bm*String(t).length*(1+vm)});new ca(wa());new ca(wa());new ca(wa());class wm{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 Cm{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 Nm{getReturnType(){return"boolean"}addEquivalences(t,r,a){a.addType(r,"array"),a.addType(t,"boolean");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 Sm{getReturnType(){return"boolean"}addEquivalences(t,r,a){a.addType(r,"array"),a.addType(t,"boolean");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 km{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 Em{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 Am{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"unknown");const s=t.getLastFunctionCallSegment();s&&s.args.forEach(o=>{a.addEquivalence(t,o)}),a.addEquivalence(t,r.withElement("*"))}isComplete(){return!0}}class _m{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"unknown");const s=t.withReturnValues();a.addType(s,"unknown")}isComplete(){return!0}}class Pm{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 Mm{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 Tm{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 jm{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 Im{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 $m{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"unknown"),a.addEquivalence(t.withReturnValues(),r.withElement("*"))}isComplete(){return!0}}class Rm{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 Dm{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 Lm{getReturnType(){return"string[]"}addEquivalences(t,r,a){a.addType(r,"string"),a.addType(t,"string[]"),a.addEquivalence(t.withReturnValues().withElement("*"),r)}isComplete(){return!0}}class Fm{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 Om{getReturnType(){return"unknown"}addEquivalences(t,r,a){t.getLastFunctionCallSegment()}isComplete(){return!0}}class zm{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 Ym(){const e=new wm;return e.register("filter",new Cm,"Array"),e.register("map",new jm,"Array"),e.register("flatMap",new Im,"Array"),e.register("join",new Tm,"Array"),e.register("find",new km,"Array"),e.register("findLast",new Rm,"Array"),e.register("at",new $m,"Array"),e.register("reduce",new Em,"Array"),e.register("concat",new Am,"Array"),e.register("slice",new _m,"Array"),e.register("splice",new Pm,"Array"),e.register("push",new Mm,"Array"),e.register("some",new Nm,"Array"),e.register("every",new Sm,"Array"),e.register("fromEntries",new Dm,"Object"),e.register("split",new Lm,"String"),e.register("then",new Fm,"Promise"),e.register("useState",new zm,"React"),e.register("useMemo",new Om,"React"),e}Ym();new Set(Object.getOwnPropertyNames(Array.prototype).filter(e=>typeof Array.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(String.prototype).filter(e=>typeof String.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Number.prototype).filter(e=>typeof Number.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Boolean.prototype).filter(e=>typeof Boolean.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Date.prototype).filter(e=>typeof Date.prototype[e]=="function"));const Bm=new Set(["filter","sort","slice","splice","unshift","push","reverse","entries"]),Um=new Set(["find","findLast","at","pop","shift"]),Wm=new Set(["map","reduce","flatMap","concat","join","some","every","findIndex","findLastIndex","indexOf","lastIndexOf","includes"]),Hm=new Set([...Bm,...Um,...Wm]),Vm=new Set(["trim","concat","replace","replaceAll","toLowerCase","toUpperCase","trimStart","trimEnd","padStart","padEnd","normalize","slice","substring","substr","toString()","toLocaleLowerCase","toLocaleUpperCase"]),Jm=new Set(["split","match","endsWith","startsWith","includes","indexOf","lastIndexOf","charAt","charCodeAt","codePointAt","repeat","search","valueOf","localeCompare","length"]),Gm=new Set([...Vm,...Jm]);[...Hm,...Gm];class qm{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 qm({enabled:!1});function kt(e,t){const r={added:{},removed:{},changed:{}},a=new Set(Object.keys(e??{})),s=new Set(Object.keys(t??{}));for(const o of s)a.has(o)||(r.added[o]=t[o]);for(const o of a)s.has(o)||(r.removed[o]=e[o]);for(const o of a)s.has(o)&&e[o]!==t[o]&&(r.changed[o]={from:e[o],to:t[o]});return r}function Km(e){return Object.keys(e.added).length>0||Object.keys(e.removed).length>0||Object.keys(e.changed).length>0}function En(e){return Object.keys(e.added).length+Object.keys(e.removed).length+Object.keys(e.changed).length}let Qm=0;class Ca{constructor(t){this.traces=new Map,this.currentEntity=null,this.currentStage=null,this.tracerId=++Qm,this.enabled=(t==null?void 0:t.enabled)??!1,this.outputPath=(t==null?void 0:t.outputPath)??"/tmp/codeyam/transform-trace.json",this.enabled&&console.log(`[Tracer] Initialized (id=${this.tracerId}, output=${this.outputPath})`)}log(t){this.isEnabled()&&console.log(`[Tracer] ${t}`)}isEnabled(){const t=process.env.CODEYAM_TRACE_TRANSFORMS;return t==="1"||t==="true"?!0:this.enabled}enable(){this.enabled=!0}disable(){this.enabled=!1}setOutputPath(t){this.outputPath=t}setProjectSlug(t){this.projectSlug=t}startEntity(t){if(!this.isEnabled())return;this.currentEntity=t.name;const r=this.traces.get(t.name);if(r){this.log(`startEntity: ${t.name} already exists, preserving ${r.stages.length} stages`);return}this.log(`startEntity: ${t.name}`),this.traces.set(t.name,{entityName:t.name,entityType:t.entityType,filePath:t.filePath,stages:[],operations:[]})}snapshot(t,r,a){var d,m,u,h;if(!this.isEnabled())return;const s=this.traces.get(t);if(!s)return this.log(`snapshot: no trace for ${t}, creating one`),this.startEntity({name:t,entityType:"unknown",filePath:"unknown"}),this.snapshot(t,r,a);this.log(`snapshot: ${t} → ${r}`),this.currentStage=r;const o=JSON.parse(JSON.stringify(a)),i={stage:r,timestamp:Date.now(),data:o},c=s.stages[s.stages.length-1];if(c&&(i.diffFromPrevious={signatureSchema:kt(c.data.signatureSchema,o.signatureSchema),returnValueSchema:kt(c.data.returnValueSchema,o.returnValueSchema)},o.dependencySchemas||c.data.dependencySchemas)){i.diffFromPrevious.dependencySchemas={};const p=new Set([...Object.keys(o.dependencySchemas??{}),...Object.keys(c.data.dependencySchemas??{})]);for(const f of p){const g=(d=c.data.dependencySchemas)==null?void 0:d[f],y=(m=o.dependencySchemas)==null?void 0:m[f];for(const x of new Set([...Object.keys(g??{}),...Object.keys(y??{})])){const v=`${f}::${x}`,b=(u=g==null?void 0:g[x])==null?void 0:u.returnValueSchema,w=(h=y==null?void 0:y[x])==null?void 0:h.returnValueSchema,C=kt(b,w);Km(C)&&(i.diffFromPrevious.dependencySchemas[v]=C)}}}s.stages.push(i)}operation(t,r){if(!this.isEnabled())return;const a=this.traces.get(t);a&&a.operations.push({...r,stage:r.stage??this.currentStage??void 0,timestamp:Date.now()})}flush(){var d;if(!this.isEnabled())return;if(this.traces.size===0){this.log("flush: no traces to write");return}const t=Array.from(this.traces.keys()),r=t.map(m=>`${m}(${this.traces.get(m).stages.length})`).join(", ");this.log(`flush: writing ${t.length} entities: ${r}`);const a={},s=new Map;for(const[m,u]of this.traces){let h=0;for(const p of u.stages){if(!p.diffFromPrevious)continue;const g=`${((d=u.stages[u.stages.indexOf(p)-1])==null?void 0:d.stage)??"start"}→${p.stage}`;if(a[g]||(a[g]={added:0,removed:0,changed:0}),p.diffFromPrevious.signatureSchema){const y=p.diffFromPrevious.signatureSchema;a[g].added+=Object.keys(y.added).length,a[g].removed+=Object.keys(y.removed).length,a[g].changed+=Object.keys(y.changed).length,h+=En(y)}if(p.diffFromPrevious.returnValueSchema){const y=p.diffFromPrevious.returnValueSchema;a[g].added+=Object.keys(y.added).length,a[g].removed+=Object.keys(y.removed).length,a[g].changed+=Object.keys(y.changed).length,h+=En(y)}}s.set(m,h)}const o=[...s.entries()].sort((m,u)=>u[1]-m[1]).slice(0,10).map(([m])=>m),i={meta:{timestamp:new Date().toISOString(),projectSlug:this.projectSlug,entityCount:this.traces.size},summary:{stageChangeCounts:a,entitiesWithMostChanges:o},entities:Object.fromEntries(this.traces)},c=Z.dirname(this.outputPath);K.existsSync(c)||K.mkdirSync(c,{recursive:!0}),K.writeFileSync(this.outputPath,JSON.stringify(i,null,2)),this.log(`flush: wrote trace to ${this.outputPath}`)}clear(){this.traces.clear(),this.currentEntity=null,this.currentStage=null}static loadTrace(t){const r=K.readFileSync(t,"utf-8"),a=JSON.parse(r),s=new Ca({enabled:!1});s.projectSlug=a.meta.projectSlug;for(const[o,i]of Object.entries(a.entities))s.traces.set(o,i);return s}getSummary(){var s,o,i;const t={},r=new Map;for(const[c,d]of this.traces){let m=0;for(let u=1;u<d.stages.length;u++){const h=d.stages[u],f=`${((s=d.stages[u-1])==null?void 0:s.stage)??"start"}→${h.stage}`;if(t[f]||(t[f]={added:0,removed:0,changed:0}),(o=h.diffFromPrevious)!=null&&o.signatureSchema){const g=h.diffFromPrevious.signatureSchema;t[f].added+=Object.keys(g.added).length,t[f].removed+=Object.keys(g.removed).length,t[f].changed+=Object.keys(g.changed).length,m+=En(g)}if((i=h.diffFromPrevious)!=null&&i.returnValueSchema){const g=h.diffFromPrevious.returnValueSchema;t[f].added+=Object.keys(g.added).length,t[f].removed+=Object.keys(g.removed).length,t[f].changed+=Object.keys(g.changed).length,m+=En(g)}}r.set(c,m)}const a=[...r.entries()].sort((c,d)=>d[1]-c[1]).slice(0,10).map(([c,d])=>({name:c,totalChanges:d}));return{entityCount:this.traces.size,stageChangeCounts:t,entitiesWithMostChanges:a}}getEntitySummary(t){const r=this.traces.get(t);return r?{entityName:t,stages:r.stages.map(a=>({stage:a.stage,diffFromPrevious:a.diffFromPrevious?{signatureSchema:a.diffFromPrevious.signatureSchema,returnValueSchema:a.diffFromPrevious.returnValueSchema}:void 0}))}:null}getOperations(t,r){const a=this.traces.get(t);return a?r?a.operations.filter(s=>s.path&&r.test(s.path)):a.operations:[]}tracePath(t,r){var o,i;const a=this.traces.get(t),s=[];if(!a)return{entityName:t,path:r,history:s};for(const c of a.stages){const d=(o=c.data.signatureSchema)==null?void 0:o[r],m=(i=c.data.returnValueSchema)==null?void 0:i[r],u=d??m;u!==void 0&&s.push({stage:c.stage,value:u})}for(const c of a.operations)c.path===r&&s.push({operation:c.operation,stage:c.stage,value:c.after??c.before,context:c.context});return{entityName:t,path:r,history:s}}getEntityTrace(t){return this.traces.get(t)}getEntityNames(){return[...this.traces.keys()]}findProperty(t,r){const a=this.traces.get(t);if(!a)return[];const s=[],o=new RegExp(`(^|\\.)${r}(\\.|\\[|$)`);for(const i of a.stages){for(const[c,d]of Object.entries(i.data.signatureSchema??{}))o.test(c)&&s.push({stage:i.stage,path:c,type:d,schemaType:"signature"});for(const[c,d]of Object.entries(i.data.returnValueSchema??{}))o.test(c)&&s.push({stage:i.stage,path:c,type:d,schemaType:"returnValue"});for(const[c,d]of Object.entries(i.data.dependencySchemas??{}))for(const[m,u]of Object.entries(d))for(const[h,p]of Object.entries(u.returnValueSchema??{}))o.test(h)&&s.push({stage:i.stage,path:`${c}/${m}::${h}`,type:p,schemaType:"dependency"})}return s}findTypeInconsistencies(t){const r=this.traces.get(t);if(!r)return[];let a=r.stages[r.stages.length-1];for(let d=r.stages.length-1;d>=0;d--)if(Object.keys(r.stages[d].data.dependencySchemas??{}).length>0){a=r.stages[d];break}if(!a)return[];const s=new Set(["length","toString","valueOf","constructor"]),o=new Map,i=(d,m)=>{const u=d.match(/\.([a-zA-Z_][a-zA-Z0-9_]*)(\[\])?$/);if(!u)return;const h=u[1],p=u[2]==="[]";if(s.has(h))return;const f=h+(p?"[]":"");o.has(f)||o.set(f,[]),o.get(f).push({path:d,type:m})};for(const[,d]of Object.entries(a.data.dependencySchemas??{}))for(const[,m]of Object.entries(d))for(const[u,h]of Object.entries(m.returnValueSchema??{}))i(u,h);const c=[];for(const[d,m]of o)new Set(m.map(h=>h.type.replace(/ \| undefined/g,"").replace(/ \| null/g,""))).size>1&&c.push({propertyName:d,paths:m.map(h=>({...h,stage:a.stage}))});return c.sort((d,m)=>{const u=new Set(d.paths.map(p=>p.type)).size;return new Set(m.paths.map(p=>p.type)).size-u}),c}getStageDiffSummary(t,r,a){const s=this.traces.get(t);if(!s)return null;const o=s.stages.find(p=>p.stage===r),i=s.stages.find(p=>p.stage===a);if(!o||!i)return null;const c={added:[],removed:[],typeChanged:[]},d=o.data.returnValueSchema??{},m=i.data.returnValueSchema??{},u=new Set(Object.keys(d)),h=new Set(Object.keys(m));for(const p of h)u.has(p)?d[p]!==m[p]&&c.typeChanged.push({path:p,from:d[p],to:m[p]}):c.added.push(`${p}: ${m[p]}`);for(const p of u)h.has(p)||c.removed.push(`${p}: ${d[p]}`);return c}traceSchemaTransform(t,r,a,s,o){if(!this.enabled)return s(a),a;const i={...a};s(a);const c=kt(i,a);for(const[d,m]of Object.entries(c.added))this.operation(t,{operation:r,path:d,before:void 0,after:m,context:{...o,changeType:"added"}});for(const[d,m]of Object.entries(c.removed))this.operation(t,{operation:r,path:d,before:m,after:void 0,context:{...o,changeType:"removed"}});for(const[d,{from:m,to:u}]of Object.entries(c.changed))this.operation(t,{operation:r,path:d,before:m,after:u,context:{...o,changeType:"changed"}});return a}traceSchemaTransformResult(t,r,a,s,o){if(!this.enabled)return;const i=kt(a,s);for(const[c,d]of Object.entries(i.added))this.operation(t,{operation:r,path:c,before:void 0,after:d,context:{...o,changeType:"added"}});for(const[c,d]of Object.entries(i.removed))this.operation(t,{operation:r,path:c,before:d,after:void 0,context:{...o,changeType:"removed"}});for(const[c,{from:d,to:m}]of Object.entries(i.changed))this.operation(t,{operation:r,path:c,before:d,after:m,context:{...o,changeType:"changed"}})}traceDependencySchemaTransform(t,r,a,s,o="both"){if(!this.enabled){for(const i in a)for(const c in a[i]){const d=a[i][c];(o==="signature"||o==="both")&&d.signatureSchema&&s(d.signatureSchema),(o==="returnValue"||o==="both")&&d.returnValueSchema&&s(d.returnValueSchema)}return}for(const i in a)for(const c in a[i]){const d=a[i][c],m={filePath:i,dependencyName:c};(o==="signature"||o==="both")&&d.signatureSchema&&this.traceSchemaTransform(t,r,d.signatureSchema,s,{...m,schemaType:"signature"}),(o==="returnValue"||o==="both")&&d.returnValueSchema&&this.traceSchemaTransform(t,r,d.returnValueSchema,s,{...m,schemaType:"returnValue"})}}traceDependencySchemaChanges(t,r,a,s){var i;if(!this.enabled){s();return}const o={};for(const c in a){o[c]={};for(const d in a[c]){const m=a[c][d];o[c][d]={sig:{...m.signatureSchema||{}},rv:{...m.returnValueSchema||{}}}}}s();for(const c in a)for(const d in a[c]){const m=a[c][d],u=(i=o[c])==null?void 0:i[d],h={filePath:c,dependencyName:d};if(m.signatureSchema){const p=(u==null?void 0:u.sig)||{},f=kt(p,m.signatureSchema);for(const[g,y]of Object.entries(f.added))this.operation(t,{operation:r,path:g,before:void 0,after:y,context:{...h,schemaType:"signature",changeType:"added"}});for(const[g,{from:y,to:x}]of Object.entries(f.changed))this.operation(t,{operation:r,path:g,before:y,after:x,context:{...h,schemaType:"signature",changeType:"changed"}})}if(m.returnValueSchema){const p=(u==null?void 0:u.rv)||{},f=kt(p,m.returnValueSchema);for(const[g,y]of Object.entries(f.added))this.operation(t,{operation:r,path:g,before:void 0,after:y,context:{...h,schemaType:"returnValue",changeType:"added"}});for(const[g,{from:y,to:x}]of Object.entries(f.changed))this.operation(t,{operation:r,path:g,before:y,after:x,context:{...h,schemaType:"returnValue",changeType:"changed"}})}}}}function Zm(){const e=process.env.CODEYAM_TRACE_TRANSFORMS;return e==="1"||e==="true"}const ks=new Ca({enabled:Zm(),outputPath:"/tmp/codeyam/transform-trace.json"});process.on("beforeExit",()=>{ks.isEnabled()&&ks.flush()});function Jo(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 zl.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),Jo(e)}return null}}function Xm({description:e,existingScenarios:t,scenariosDataStructure:r,flowSelections:a}){let s="";return a&&a.length>0&&(s=`
119
- User-selected Execution Flow Values:
120
- The user has specifically requested these values be used in the scenario:
121
- ${a.map(o=>` - ${o.path}: ${o.value}${o.isCustom?" (custom value)":""}`).join(`
122
- `)}
123
-
124
- IMPORTANT: The mockData MUST include these specific values for the specified paths. Generate a scenario name and description that reflects these choices.
125
- `),`Mock Scenario Data Structure:
126
- \`\`\`
127
- ${JSON.stringify(r,null,2)}
128
- \`\`\`
129
- Existing Mock Scenario Data:
130
- \`\`\`
131
- ${JSON.stringify(t,null,2)}
132
- \`\`\`
133
- ${s}
134
- New Scenario user-created prompt: "${e||"(No additional description - generate based on selected execution flow values)"}"
135
- `}function eh({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s}){const o=a.find(i=>i.name===or);return`Mock Scenario Data Structure:
136
- \`\`\`
137
- ${JSON.stringify({props:s.arguments,dataVariables:s.dataForMocks},null,2)}
138
- \`\`\`
139
-
140
- Existing Mock Scenario Data:
141
- \`\`\`
142
- ${JSON.stringify(a.map(i=>({name:i.name,data:en(o.metadata.data,i.metadata.data)})),null,2)}
143
- \`\`\`
144
-
145
- Mock Scenario that should be edited: "${t}"
146
- ${r?`The portion of the data that should be edited:
147
- \`\`\`
148
- ${JSON.stringify(r,null,2)}
149
- \`\`\``:""}
150
-
151
- How this data should be changed: "${e}"
152
- `}async function th({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s,flowSelections:o,model:i}){const c=t?eh({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s}):Xm({description:e,existingScenarios:a,scenariosDataStructure:s,flowSelections:o}),d=await ea({type:"guessScenarioDataFromDescription",systemMessage:t?rh(r):nh,prompt:c,model:i??am});await xm({object_type:"guessScenarioDataFromDescription",object_id:"new",propsJson:{description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s,model:i},...d.stats});const{completion:m}=d;return m?Jo(m):(console.log("CodeYam: guessing scenario data failed: No response from AI"),null)}const nh=`
153
- 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.
154
-
155
- 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.
156
-
157
- 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.
158
-
159
- You must respond with valid JSON following this format of this TS type definition:
160
- \`\`\`
161
- export type ScenarioData = {
162
- name: string;
163
- description: string;
164
- data: {
165
- mockData: { [key: string]: unknown };
166
- argumentsData: { [key: string]: unknown };
167
- };
168
- };
169
-
170
- \`\`\`
171
- `,rh=e=>`
172
- 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.
173
-
174
- Your goal is to edit one of the scenarios, named as the "Mock Scenario that should be edited".
175
- ${e?`
176
- 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.`:""}
177
-
178
- 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.
179
-
180
- You must respond with valid JSON following this type definition:
181
- \`\`\`
182
- {
183
- data: {
184
- mockData: { [key: string]: unknown };
185
- argumentsData: { [key: string]: unknown };
186
- }
187
- }
188
- \`\`\`
189
- `;async function ah({request:e}){if(e.method!=="POST")return W({error:"Method not allowed"},{status:405});try{const t=await e.json(),{description:r,existingScenarios:a,scenariosDataStructure:s,editingMockName:o,editingMockData:i,flowSelections:c}=t;if(!r&&(!c||c.length===0))return W({error:"Missing required field: description or flowSelections"},{status:400});const d=await th({description:r||"",existingScenarios:a??[],scenariosDataStructure:s,editingMockName:o,editingMockData:i,flowSelections:c}),m=(d==null?void 0:d.data)||d;return W({success:!0,data:m})}catch(t){return console.error("[Generate Scenario Data API] Error:",t),W({error:"Failed to generate scenario data",details:t instanceof Error?t.message:String(t)},{status:500})}}const sh=Object.freeze(Object.defineProperty({__proto__:null,action:ah},Symbol.toStringTag,{value:"Module"}));async function oh(e,t){const r=fe();if(!r)return{entityCalls:[],analysisCalls:[]};const a=Z.join(r,".codeyam","llm-calls");try{await Re.access(a)}catch{return{entityCalls:[],analysisCalls:[]}}const s=[],o=[];try{const c=(await Re.readdir(a)).filter(v=>v.endsWith(".json")),d=`${e}_`,m=t?`${t}_`:null,u=[],h=[];for(const v of c)v.startsWith(d)||m&&v.startsWith(m)?u.push(v):h.push(v);const p=u.map(async v=>{try{const b=Z.join(a,v),w=await Re.readFile(b,"utf-8");return JSON.parse(w)}catch{return null}}),f=h.map(async v=>{try{const b=Z.join(a,v),w=await Re.readFile(b,"utf-8"),C=JSON.parse(w);return C.object_id===e||t&&C.object_id===t?C:null}catch{return null}}),[g,y]=await Promise.all([Promise.all(p),Promise.all(f)]),x=[...g,...y].filter(v=>v!==null);for(const v of x)v.object_id===e?s.push(v):t&&v.object_id===t&&o.push(v);s.sort((v,b)=>b.created_at-v.created_at),o.sort((v,b)=>b.created_at-v.created_at)}catch(i){console.error("Error loading LLM calls:",i)}return{entityCalls:s,analysisCalls:o}}async function ih({params:e,request:t}){const{entitySha:r}=e;if(!r)return W({error:"Entity SHA is required"},{status:400});const s=new URL(t.url).searchParams.get("analysisId")||void 0,o=await oh(r,s);return W(o)}const lh=Object.freeze(Object.defineProperty({__proto__:null,loader:ih},Symbol.toStringTag,{value:"Module"}));function ch(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 dh(r)}catch(r){return console.error("Failed to get git status:",r),[]}}function dh(e){const t=e.trim().split(`
190
- `).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]+/,""),c,d=!1,m;if(s==="A"||o==="A")c="added",d=s==="A";else if(s==="M"||o==="M")c="modified",d=s==="M";else if(s==="D"||o==="D")c="deleted",d=s==="D";else if(s==="R"||o==="R"){c="renamed",d=s==="R";const u=i.indexOf(" -> ");u!==-1&&(m=i.slice(0,u).trim(),i=i.slice(u+4).trim())}else o==="?"?(c="untracked",d=!1):(c="modified",d=s!==" "&&s!=="?");if(i.endsWith("/")){const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),h=oe.join(u,i);try{const p=(g,y)=>{const x=Mt.readdirSync(g,{withFileTypes:!0}),v=[];for(const b of x){const w=oe.join(g,b.name),C=oe.relative(u,w);b.isDirectory()?v.push(...p(w,y)):b.isFile()&&v.push(C)}return v},f=p(h,u);for(const g of f)r.push({path:g,status:c,staged:d,...m&&{oldPath:m}})}catch(p){console.error(`Failed to expand directory ${i}:`,p)}}else r.push({path:i,status:c,staged:d,...m&&{oldPath:m}})}return r}function uh(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 mh(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 hh(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(`
191
- `).filter(a=>a.length>0)}catch(r){return console.error("Failed to get branches:",r),[]}}function Go(){const e=fe();return e?ch(e):[]}function ph(){const e=fe();return e?uh(e):null}function fh(){const e=fe();return e?mh(e):"main"}function gh(){const e=fe();return e?hh(e):[]}function qo(e,t){const r=fe();return r?yh(e,t,r):[]}function yh(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(`
192
- `).filter(i=>i.length>0).map(i=>{const c=i.split(" "),d=c[0];let m=c[1],u,h;return d==="A"?h="added":d==="M"?h="modified":d==="D"?h="deleted":d.startsWith("R")?(h="renamed",u=c[1],m=c[2]):h="modified",{path:m,status:h,...u&&{oldPath:u}}})}catch(s){return console.error("Failed to get branch diff:",s),[]}}function xh(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=Mt.readFileSync(oe.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 bh(e){const t=fe();return t?xh(e,t):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function vh(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 jn(e,t,r){const a=fe();return a?vh(e,t,r,a):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function Es(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 wh(e,t,r,a){const s=nr.createHash("sha256");return s.update(`${e}:${t}:${r}:${a}`),s.digest("hex").substring(0,16)}function Ko(){const e=fe();if(!e)throw new Error("No project root found");const t=oe.join(e,".codeyam","cache","branch-entity-diff");return Mt.existsSync(t)||Mt.mkdirSync(t,{recursive:!0}),t}function Ch(e){try{const t=Ko(),r=oe.join(t,`${e}.json`);if(!Mt.existsSync(r))return null;const a=Mt.readFileSync(r,"utf8");return JSON.parse(a)}catch(t){return console.error("Failed to read cache:",t),null}}function Nh(e,t){try{const r=Ko(),a=oe.join(r,`${e}.json`);Mt.writeFileSync(a,JSON.stringify(t,null,2))}catch(r){console.error("Failed to write cache:",r)}}function Sh(e,t,r){const a=Bn(t,e),s=Bn(r,e),o=new Map(a.map(u=>[u.name,u])),i=new Map(s.map(u=>[u.name,u])),c=[],d=[],m=[];for(const[u,h]of i){const p=o.get(u);p?p.sha!==h.sha&&d.push({name:u,baseSha:p.sha,compareSha:h.sha,entityType:h.entityType}):c.push(h)}for(const[u,h]of o)i.has(u)||m.push(h);return{filePath:e,newEntities:c,modifiedEntities:d,deletedEntities:m}}function kh(e,t){const r=fe();if(!r)throw new Error("No project root found");const a=Es(e,r),s=Es(t,r);if(!a||!s)throw new Error(`Failed to get commit SHAs for branches: ${e}, ${t}`);const o=wh(e,t,a,s),i=Ch(o);if(i)return console.log(`Using cached branch entity diff: ${o}`),i;const c=qo(e,t),d=[];for(const u of c)if(u.path.match(/\.(tsx?|jsx?)$/))if(u.status==="deleted"){const h=jn(u.path,e,t),p=Bn(h.oldContent,u.path);d.push({filePath:u.path,newEntities:[],modifiedEntities:[],deletedEntities:p})}else if(u.status==="added"){const h=jn(u.path,e,t),p=Bn(h.newContent,u.path);d.push({filePath:u.path,newEntities:p,modifiedEntities:[],deletedEntities:[]})}else{const h=jn(u.path,e,t),p=Sh(u.path,h.oldContent,h.newContent);(p.newEntities.length>0||p.modifiedEntities.length>0||p.deletedEntities.length>0)&&d.push(p)}const m={baseBranch:e,compareBranch:t,baseCommitSha:a,compareCommitSha:s,fileComparisons:d,cacheKey:o,computedAt:new Date().toISOString()};return Nh(o,m),m}function Eh({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("base"),a=t.searchParams.get("compare");if(!r||!a)return W({error:"Missing required parameters: base and compare"},{status:400});const s=kh(r,a);return W(s)}catch(t){return console.error("Failed to compute branch entity diff:",t),W({error:"Failed to compute branch entity diff",details:t instanceof Error?t.message:String(t)},{status:500})}}const Ah=Object.freeze(Object.defineProperty({__proto__:null,loader:Eh},Symbol.toStringTag,{value:"Module"}));async function _h({request:e}){if(e.method!=="POST")return W({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 W({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=fe();if(!i)return W({error:"Project root not found"},{status:500});const c=Z.join(i,"background","src","lib","virtualized","playwright","captureFromUrl.ts"),d=JSON.stringify({url:r,scenarioId:a,projectId:s,projectRoot:i,viewportWidth:o}),m=await new Promise(p=>{const f=Z.join(i,".codeyam","db.sqlite3"),g=rr("npx",["tsx",c,d],{cwd:i,env:{...process.env,SQLITE_PATH:f}});let y="",x="";g.stdout.on("data",v=>{const b=v.toString();y+=b;const w=b.trim().split(`
193
- `);for(const C of w)C.includes("[Capture]")&&console.log(C)}),g.stderr.on("data",v=>{const b=v.toString();x+=b,console.error("[Capture:Error]",b.trim())}),g.on("close",v=>{p(v===0?{success:!0,output:y}:{success:!1,output:y,error:x||`Process exited with code ${v}`})}),g.on("error",v=>{console.error("[Capture] Failed to spawn child process:",v),p({success:!1,output:"",error:v.message})})});if(!m.success)return W({error:"Failed to capture screenshot",details:m.error},{status:500});const u=m.output.match(/\[Capture\] RESULT:(.+)/);if(!u)return W({error:"Failed to parse capture result"},{status:500});const h=JSON.parse(u[1]);return W(h)}catch(t){return console.error("[Capture] Error:",t),W({error:"Failed to capture screenshot",details:t instanceof Error?t.message:String(t)},{status:500})}}const Ph=Object.freeze(Object.defineProperty({__proto__:null,action:_h},Symbol.toStringTag,{value:"Module"}));async function Mh(e,t,r){var f;console.log(`[recapture] Starting recapture for analysis ${e} with width ${t}`),await Le();const a=await ct({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);const s=Ae(),o=a.entitySha,i=await s.selectFrom("entities").select(["metadata"]).where("sha","=",o).executeTakeFirst();let c={};if(i!=null&&i.metadata&&(typeof i.metadata=="string"?c=JSON.parse(i.metadata):c=i.metadata),c.defaultWidth=t,await s.updateTable("entities").set({metadata:JSON.stringify(c)}).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 Yt(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=fe();if(!d)throw new Error("Project root not found");const m=Z.join(d,".codeyam","config.json"),u=JSON.parse(K.readFileSync(m,"utf8")),{projectSlug:h}=u;if(!h)throw new Error("Project slug not found in config");const{jobId:p}=r.enqueue({type:"recapture",commitSha:a.commit.sha,projectSlug:h,analysisId:e,defaultWidth:t});return console.log(`[recapture] Recapture job queued with ID: ${p}`),{jobId:p}}async function Th(e,t,r){var u;console.log(`[recapture] Starting scenario recapture for analysis ${e}, scenario ${t}`),await Le();const a=await ct({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=(u=a.scenarios)==null?void 0:u.find(h=>h.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 Yt(e,h=>{if(h&&(h.readyToBeCaptured=!0,delete h.finishedAt,h.scenarios)){const p=h.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=fe();if(!o)throw new Error("Project root not found");const i=Z.join(o,".codeyam","config.json"),c=JSON.parse(K.readFileSync(i,"utf8")),{projectSlug:d}=c;if(!d)throw new Error("Project slug not found in config");const{jobId:m}=r.enqueue({type:"recapture",commitSha:a.commit.sha,projectSlug:d,analysisId:e,scenarioId:t});return console.log(`[recapture] Scenario recapture job queued with ID: ${m}`),{jobId:m}}async function jh({request:e,context:t}){if(e.method!=="POST")return W({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await ut()),!r)return W({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("analysisId"),o=a.get("scenarioId");if(!s||!o)return W({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Starting scenario recapture for analysis ${s}, scenario ${o}`);const i=await Th(s,o,r);return console.log("[API] Scenario recapture queued",i),W({success:!0,message:"Scenario recapture queued",...i})}catch(a){return console.log("[API] Error during scenario recapture:",a),W({error:"Failed to recapture scenario",details:a instanceof Error?a.message:String(a)},{status:500})}}const Ih=Object.freeze(Object.defineProperty({__proto__:null,action:jh},Symbol.toStringTag,{value:"Module"}));async function ta(e){try{return await he.stat(e),!0}catch{return!1}}async function Qo(){try{const e=fe();if(!e)return null;const t=oe.join(e,".codeyam","config.json");return JSON.parse(await he.readFile(t,"utf-8")).projectSlug||null}catch{return null}}function $h(){return`/private/tmp/claude-501/-${(fe()||process.cwd()).replace(/^\//,"").replace(/\//g,"-")}/tasks`}const In="/tmp/claude-rule-markers",Rh=/<system-reminder>[\s\S]*?<\/system-reminder>/g,As=2e3;function Dh(e,t){if(e==="Read"||e==="Write"||e==="Edit")return String(t.file_path||"");if(e==="Glob")return String(t.pattern||"");if(e==="Grep"){const r=String(t.pattern||""),a=String(t.path||"");return a?`"${r}" in ${a}`:`"${r}"`}if(e==="Bash"){const r=String(t.command||"");return r.length>100?r.slice(0,100)+"...":r}if(e==="Task")return String(t.description||String(t.prompt||"").slice(0,80));for(const r of Object.values(t))if(typeof r=="string"&&r)return r.slice(0,80);return""}const Lh=["no,","no ","that's not","thats not","that is not","wrong","incorrect","actually,","actually ","i meant","i mean","not what i","stop","wait","don't do","dont do","shouldn't","should not","try again","let me clarify","to clarify","that broke","that failed","error","bug"];function Fh(e){const t=[],r=new Set;for(const a of e)if(!(a.type!=="tool_call"||!a.name||!a.input)){if(a.name==="Write"||a.name==="Edit"){const s=String(a.input.file_path||"");if(s.includes(".claude/rules/")){const o=s.replace(/^.*?(\.claude\/rules\/)/,"$1"),i=`${a.name}:${o}`;r.has(i)||(r.add(i),a.name==="Write"?t.push({action:"created",filePath:o,content:String(a.input.content||"")}):t.push({action:"modified",filePath:o,oldString:String(a.input.old_string||""),newString:String(a.input.new_string||"")}))}}else if(a.name==="Bash"){const s=String(a.input.command||"");if(s.includes("codeyam memory touch")){const o=`touch:${s}`;r.has(o)||(r.add(o),t.push({action:"touched",filePath:s}))}}}return t}function Oh(e){if(!e)return;const t="### Session transcript",r=e.indexOf(t);if(r===-1)return;let a=e.slice(r+t.length).trim();const s=a.indexOf(`
194
- ###`);return s!==-1&&(a=a.slice(0,s).trim()),a||void 0}function zh(e){for(const t of e){if(t.type!=="user_prompt")continue;const r=(t.text||"").toLowerCase();for(const a of Lh)if(r.includes(a))return!0}return!1}function Yh(e){for(const t of e){const r=t.trim();if(r)try{const a=JSON.parse(r);if(a.type==="assistant"){const s=(a.message||{}).model;if(typeof s=="string"&&s)return s}}catch{continue}}}function Bh(e){for(const t of e){const r=t.trim();if(r)try{const a=JSON.parse(r);if(a.type!=="result")continue;const s={subtype:String(a.subtype||"unknown"),is_error:!!a.is_error};if(typeof a.duration_ms=="number"&&(s.duration_ms=a.duration_ms),typeof a.duration_api_ms=="number"&&(s.duration_api_ms=a.duration_api_ms),typeof a.num_turns=="number"&&(s.num_turns=a.num_turns),typeof a.total_cost_usd=="number"&&(s.total_cost_usd=a.total_cost_usd),a.usage&&typeof a.usage=="object"){s.usage={};for(const o of["input_tokens","output_tokens","cache_read_input_tokens","cache_creation_input_tokens"])typeof a.usage[o]=="number"&&(s.usage[o]=a.usage[o])}return Array.isArray(a.errors)&&a.errors.length>0&&(s.errors=a.errors.map(String)),s}catch{continue}}}function Uh(e){const t=[],r={};for(const a of e){const s=a.trim();if(!s)continue;let o;try{o=JSON.parse(s)}catch{continue}const i=o.type;if(i==="progress"||i==="system"||i==="result")continue;const d=(o.message||{}).content,m=o.timestamp||"";if(i==="user"){if(typeof d=="string")t.push({type:"user_prompt",text:d,timestamp:m,agent_id:String(o.agentId||o.session_id||"unknown"),slug:String(o.slug||"")});else if(Array.isArray(d)){for(const u of d)if(typeof u=="object"&&u!==null&&u.type==="tool_result"){const h=u,p=String(h.tool_use_id||"");let f=h.content;const g=!!h.is_error;typeof f=="string"&&(f=f.replace(Rh,"").trim()),t.push({type:"tool_result",tool_use_id:p,tool_name:r[p]||"unknown",content:typeof f=="string"?f:JSON.stringify(f),is_error:g,timestamp:m})}}}else if(i==="assistant"&&Array.isArray(d))for(const u of d){if(typeof u!="object"||u===null)continue;const h=u;if(h.type==="text"){const p=String(h.text||"").trim();p&&t.push({type:"assistant_text",text:p,timestamp:m})}else if(h.type==="tool_use"){const p=String(h.id||""),f=String(h.name||"unknown"),g=h.input||{};r[p]=f,t.push({type:"tool_call",tool_use_id:p,name:f,input:g,timestamp:m})}}}return t}function Wh(e,t){return e.type==="user_prompt"||e.type==="assistant_text"?(e.text||"").toLowerCase().includes(t):e.type==="tool_call"?(e.name||"").toLowerCase().includes(t)?!0:JSON.stringify(e.input||{}).toLowerCase().includes(t):e.type==="tool_result"?(e.content||"").toLowerCase().includes(t):!1}const Rt=20;async function _s(e){const r=(await he.readFile(e.filePath,"utf-8")).split(`
195
- `),a=Uh(r);if(a.length===0)return null;const s=a.find(w=>w.type==="user_prompt"),o=e.stem,i=Yh(r);let c=(s==null?void 0:s.slug)||"",d=(s==null?void 0:s.timestamp)||"";d||(d=new Date(e.mtime).toISOString());let m;if(e.filePath.endsWith(".log")){e.stem.endsWith("-stale")?c=c||"rule-reflection/stale":e.stem.endsWith("-conversation")?c=c||"rule-reflection/conversation":e.stem.endsWith("-interruption")?c=c||"rule-reflection/interruption":c=c||"rule-reflection";const w=e.filePath.replace(/\.log$/,".context");if(await ta(w))try{m=await he.readFile(w,"utf-8")}catch{}}const u=a.filter(w=>w.type==="tool_call").length,h=a.filter(w=>w.type==="assistant_text").length,p=a.filter(w=>w.type==="tool_result"&&w.is_error&&w.content!=="Sibling tool call errored"),f=p.length,g=p.map(w=>{const C=w.content||"Unknown error";return C.length>150?C.slice(0,150)+"...":C});for(const w of a)w.type==="tool_call"&&w.name&&w.input&&(w.summary=Dh(w.name,w.input));for(const w of a)w.type==="tool_result"&&w.content&&w.content.length>As&&(w.truncated=!0,w.fullLength=w.content.length,w.content=w.content.slice(0,As));const y=Fh(a),x=zh(a),v=Oh(m),b=Bh(r);return{id:o,slug:c,timestamp:d,model:i,sourceFile:e.filePath,stats:{toolCalls:u,textBlocks:h,errors:f,errorMessages:g},entries:a,context:m,conversationSnippet:v,ruleChanges:y,hasConfusion:x,sessionResult:b}}async function Hh(){const e=$h(),t=In,r=[];if(await ta(e)){const i=await he.readdir(e);for(const c of i)if(c.endsWith(".output")){const d=oe.join(e,c),m=await he.stat(d);r.push({filePath:d,stem:c.replace(".output",""),mtime:m.mtimeMs})}}const a=new Set,s=await Qo(),o=[];s&&o.push(oe.join(t,s)),o.push(t);for(const i of o){if(!await ta(i))continue;const c=await he.readdir(i);for(const d of c){if(!d.endsWith(".log")||a.has(d))continue;a.add(d);const m=oe.join(i,d),u=await he.stat(m);r.push({filePath:m,stem:d.replace(".log",""),mtime:u.mtimeMs})}}return r.sort((i,c)=>c.mtime-i.mtime),r}async function Vh({request:e}){var t;try{const r=new URL(e.url),a=((t=r.searchParams.get("search"))==null?void 0:t.toLowerCase())||"",s=Math.max(1,parseInt(r.searchParams.get("page")||"1",10)),o=await Hh();if(!a){const u=o.length,h=(s-1)*Rt,p=o.slice(h,h+Rt),f=[];for(const g of p){const y=await _s(g);y&&f.push(y)}return Response.json({agents:f,total:u,page:s,pageSize:Rt})}const i=[];for(const u of o){const h=await _s(u);if(!h)continue;(h.id.toLowerCase().includes(a)||h.slug.toLowerCase().includes(a)||h.entries.some(f=>Wh(f,a)))&&i.push(h)}const c=i.length,d=(s-1)*Rt,m=i.slice(d,d+Rt);return Response.json({agents:m,total:c,page:s,pageSize:Rt})}catch(r){return console.error("[api.agent-transcripts] Error:",r),Response.json({error:"Failed to load agent transcripts",details:r instanceof Error?r.message:String(r)},{status:500})}}const Jh=Object.freeze(Object.defineProperty({__proto__:null,loader:Vh},Symbol.toStringTag,{value:"Module"}));async function Gh({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=ur(r);try{return await Xt(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 qh({params:e}){const{projectSlug:t}=e;if(!t)return new Response("Project slug is required",{status:400});const r=ur(t);try{if(!pt(r))return new Response("No logs available yet. Analysis may not have started.",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});const a=await Jr(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 Kh=Object.freeze(Object.defineProperty({__proto__:null,action:Gh,loader:qh},Symbol.toStringTag,{value:"Module"}));async function Qh(e,t){var o,i,c,d,m,u;console.log(`[executeLibraryFunction] Starting execution for analysis ${e}, scenario ${t}`),await Le();const r=await ct({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(h=>h.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=(c=(i=a.metadata)==null?void 0:i.data)==null?void 0:c.argumentsData)==null?void 0:d[0])||{},timestamp:new Date().toISOString()},error:null,sideEffects:{consoleOutput:[{level:"log",args:[`Executing ${r.entityName}...`]},{level:"log",args:["Processing input:",JSON.stringify((u=(m=a.metadata)==null?void 0:m.data)==null?void 0:u.argumentsData)]},{level:"log",args:["Execution completed successfully"]}],fileWrites:[],apiCalls:[]},timing:{duration:Math.floor(Math.random()*100)+10,timestamp:new Date().toISOString()}};return console.log(`[executeLibraryFunction] Execution completed for ${r.entityName}`),s}async function Zh({request:e}){if(e.method!=="POST")return W({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("analysisId"),a=t.get("scenarioId");if(!r||!a)return W({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Executing library function for analysis ${r}, scenario ${a}`);const s=await Qh(r,a);return console.log("[API] Function execution completed successfully"),W({success:!0,result:s})}catch(t){return console.log("[API] Error during function execution:",t),W({success:!1,error:"Failed to execute function",details:t instanceof Error?t.message:String(t)},{status:500})}}const Xh=Object.freeze(Object.defineProperty({__proto__:null,action:Zh},Symbol.toStringTag,{value:"Module"}));function ep({request:e}){return W({status:"ok"})}async function tp({request:e,context:t}){if(e.method!=="POST")return W({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await ut()),!r)return console.error("[Interactive Mode API] Queue not initialized"),W({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 W({error:"Missing required fields: action and analysisId"},{status:400});if(s!=="start"&&s!=="stop")return W({error:'Invalid action. Must be "start" or "stop"'},{status:400});const c=await $e();if(console.log("[Interactive Mode API] projectSlug:",c),!c)return W({error:"Project not initialized"},{status:500});if(s==="start"){const d=await r.enqueue({type:"interactive-start",analysisId:o,scenarioId:i,projectSlug:c});return W({success:!0,action:"start",message:"Interactive mode starting...",jobId:d})}else{const d=await r.enqueue({type:"interactive-stop",analysisId:o,projectSlug:c});return W({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),W({error:"Failed to control interactive mode",details:s},{status:500})}}const np=Object.freeze(Object.defineProperty({__proto__:null,action:tp,loader:ep},Symbol.toStringTag,{value:"Module"}));async function rp({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=fe();if(s)for(const o of a){const i=oe.join(s,".codeyam","captures","screenshots",o);try{await he.unlink(i),console.log(`[API] Deleted screenshot: ${i}`)}catch(c){console.log(`[API] Could not delete screenshot ${i}:`,c instanceof Error?c.message:c)}}}return await Fc({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 ap=Object.freeze(Object.defineProperty({__proto__:null,action:rp},Symbol.toStringTag,{value:"Module"})),on="/tmp/codeyam",na=process.env.CODEYAM_API_BASE||"https://dev.codeyam.com",Zo=500,sp=Zo*1024*1024;function At(e,t){try{return Me(`git ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return null}}function $n(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Xo(e){return At("config user.email",e)}function op(e){const t=Z.join(e,".codeyam","debug-report.md");if(!K.existsSync(t))return null;try{return K.readFileSync(t,"utf8")}catch{return null}}function ip(e,t=20){const r=Z.join(on,"local-dev",e,"codeyam","log.txt");if(!K.existsSync(r))return[];try{return K.readFileSync(r,"utf8").split(`
196
- `).filter(i=>i.includes("CodeYam Log Level 1")).slice(-t)}catch{return[]}}async function lp(e){try{const t=await fetch(`${na}/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 cp(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 dp(e){const{projectRoot:t,projectSlug:r,outputPath:a,metadata:s,screenshot:o,onProgress:i}=e,c=i||(()=>{}),d=Date.now(),m=Z.join(on,`delta-staging-${d}`),u=Z.join(m,"delta");K.mkdirSync(u,{recursive:!0});try{const h=At("diff --binary HEAD",t)||"";K.writeFileSync(Z.join(u,"tracked.patch"),h?h+`
197
- `:"");const p=At("ls-files --others --exclude-standard",t);if(p){const x=Z.join(u,"untracked");K.mkdirSync(x,{recursive:!0});for(const v of p.split(`
198
- `).filter(Boolean)){const b=Z.join(t,v),w=Z.join(x,v);if(K.existsSync(b)){const C=Z.dirname(w);K.mkdirSync(C,{recursive:!0}),K.statSync(b).isFile()&&K.copyFileSync(b,w)}}}const f=Z.join(t,".codeyam");if(K.existsSync(f)){const x=Z.join(u,"codeyam");K.cpSync(f,x,{recursive:!0})}K.writeFileSync(Z.join(u,"meta.json"),JSON.stringify(s,null,2));const g=Z.join(on,"local-dev",r,"codeyam","log.txt");K.existsSync(g)?K.copyFileSync(g,Z.join(u,"codeyam-log.txt")):K.writeFileSync(Z.join(u,"codeyam-log.txt"),`# Log file not found
199
- `);const y=Z.join(t,".codeyam","debug-report.md");K.existsSync(y)&&(K.copyFileSync(y,Z.join(u,"debug-report.md")),c("Debug report included")),o&&o.length>0&&(K.writeFileSync(Z.join(u,"screenshot.jpg"),o),c(`Screenshot included (${$n(o.length)})`));try{Me(`tar -czf "${a}" -C "${m}" delta`,{stdio:"pipe"})}catch(x){throw new Error(`tar failed: ${x.message}`)}}finally{K.rmSync(m,{recursive:!0,force:!0})}}async function up(e){const{projectRoot:t,projectSlug:r,feedback:a,screenshot:s,onProgress:o}=e,i=o||(()=>{});i("Gathering metadata...");const c=At("rev-parse HEAD",t);if(!c)throw new Error("At least one commit is required to generate a bundle. Please commit your changes first.");const d=At("rev-parse --abbrev-ref HEAD",t)||"unknown",m=At("status --porcelain",t),u=At("remote get-url origin",t),h=m!==null&&m.length>0,p=Do(r),f=op(t);let g=a;f&&(g={...a||{issueType:"other",source:"cli"},debugReport:f},i("Found debug report from /codeyam-diagnose workflow"));const y={timestamp:new Date().toISOString(),projectSlug:r,git:{sha:c,branch:d,isDirty:h,remoteUrl:u},versions:{cli:p.cliVersion,webserver:p.webserverVersion,node:process.version},system:{platform:process.platform,arch:process.arch},feedback:g},x=Date.now(),v=Z.join(on,`base-${c}-${x}.tar.gz`),b=Z.join(on,`delta-${r}-${x}.tar.gz`);i("Checking for existing base...");const w=await lp(c);let C=null;w?i("Server already has base, skipping..."):(i("Generating base archive..."),cp(t,v),C=K.statSync(v).size,i(`Base archive: ${$n(C)}`)),i("Generating delta archive..."),dp({projectRoot:t,projectSlug:r,outputPath:b,metadata:y,screenshot:s,onProgress:o});const N=K.statSync(b).size;i(`Delta archive: ${$n(N)}`);const E=(C||0)+N;if(E>sp)throw K.existsSync(v)&&K.unlinkSync(v),K.unlinkSync(b),new Error(`Bundle too large: ${$n(E)} (max: ${Zo} MB). Try removing large files from the project or adding them to .gitignore`);return{basePath:w?null:v,deltaPath:b,metadata:y,baseSha:c,baseSize:C,deltaSize:N}}async function mp(e){const{basePath:t,deltaPath:r,projectSlug:a,metadata:s,baseSha:o,deltaSize:i,onProgress:c}=e,d=c||(()=>{}),m=K.statSync(r),u=t?K.statSync(t):null,h=m.size+((u==null?void 0:u.size)||0);d("Requesting upload URLs...");const p=await fetch(`${na}/api/reports/request-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectSlug:a,fileSizeBytes:h,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 w=await p.json();throw new Error(w.error||`Server returned ${p.status}`)}const{reportId:f,deltaUploadUrl:g,baseUploadUrl:y}=await p.json(),x=[];if(t&&y){d("Uploading base...");const w=K.readFileSync(t);x.push(fetch(y,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:w}).then(C=>{if(!C.ok)throw new Error(`Base upload failed: ${C.status}`)}))}d("Uploading delta...");const v=K.readFileSync(r);x.push(fetch(g,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:v}).then(w=>{if(!w.ok)throw new Error(`Delta upload failed: ${w.status}`)})),await Promise.all(x),d("Confirming upload...");const b=await fetch(`${na}/api/reports/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reportId:f})});if(!b.ok){const w=await b.json();throw new Error(w.error||`Confirm failed: ${b.status}`)}return t&&K.existsSync(t)&&K.unlinkSync(t),K.unlinkSync(r),{bundleId:f}}async function hp({request:e}){if(e.method!=="POST")return W({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"),c=t.get("scenarioId"),d=t.get("analysisId"),m=t.get("currentUrl"),u=t.get("entityName"),h=t.get("entityType"),p=t.get("scenarioName"),f=t.get("errorMessage"),g=t.get("screenshot");let y=a||void 0;!y&&u&&(p?y=`Issue on ${u} scenario "${p}"`:y=`Issue on ${u}`);let x;if(g&&g.size>0){const E=await g.arrayBuffer();x=Buffer.from(E),console.log(`[Bundle] Screenshot received: ${g.size} bytes`)}const v=fe();if(!v)return W({error:"Project root not found"},{status:500});const b=await $e();if(!b)return W({error:"Project slug not found"},{status:500});const w={issueType:r||"other",description:y,email:s||void 0,source:o||"navbar",entitySha:i||void 0,scenarioId:c||void 0,analysisId:d||void 0,currentUrl:m||void 0,recentActivity:ip(b,20),entityName:u||void 0,entityType:h||void 0,scenarioName:p||void 0,errorMessage:f||void 0};console.log(`[Bundle] Generating bundle for ${b}...`),console.log(`[Bundle] Context: ${w.source}, issue: ${w.issueType}`);const C=await up({projectRoot:v,projectSlug:b,feedback:w,screenshot:x,onProgress:E=>{console.log(`[Bundle] ${E}`)}}),k=(C.baseSize||0)+C.deltaSize;console.log(`[Bundle] Archives created: delta=${C.deltaSize} bytes${C.basePath?`, base=${C.baseSize} bytes`:" (base reused)"}`);const N=await mp({basePath:C.basePath,deltaPath:C.deltaPath,projectSlug:b,metadata:C.metadata,baseSha:C.baseSha,deltaSize:C.deltaSize,onProgress:E=>{console.log(`[Bundle] ${E}`)}});return console.log(`[Bundle] Upload complete: ${N.bundleId}`),W({success:!0,reportId:N.bundleId,size:k})}catch(t){return console.error("[Bundle] Error:",t),W({error:t.message||"Failed to generate bundle"},{status:500})}}function pp(){const e=fe(),t=e?Xo(e):null;return W({defaultEmail:t})}const fp=Object.freeze(Object.defineProperty({__proto__:null,action:hp,loader:pp},Symbol.toStringTag,{value:"Module"}));function Pt(){const e=process.memoryUsage(),t=Bl.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(Gr.totalmem()/1024/1024),freeMemory:Math.round(Gr.freemem()/1024/1024)}}}function gp(){const e=Pt();console.log(`
200
- [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 yp(){if(global.gc){console.log("[Memory Profiler] Running garbage collection...");const e=Pt();global.gc();const t=Pt(),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 xp(){const e=Pt(),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 bp({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=yp(),s=Pt();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=gp();return Response.json({success:!0,stats:a})}case"leaks":{const a=xp(),s=Pt();return Response.json({success:!0,leakCheck:a,stats:s})}default:{const a=Pt();return Response.json({success:!0,stats:a,actions:{gc:"/api/memory-profile?action=gc - Force garbage collection (requires --expose-gc)",detailed:"/api/memory-profile?action=detailed - Log detailed stats to console",leaks:"/api/memory-profile?action=leaks - Check for memory leak indicators"}})}}}catch(a){return console.error("[Memory API] Error:",a),Response.json({success:!1,error:a.message},{status:500})}}const vp=Object.freeze(Object.defineProperty({__proto__:null,loader:bp},Symbol.toStringTag,{value:"Module"})),An=la(ia);async function wp({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=Cp(o),c=i?await Np(o):null;return{pid:o,isRunning:i,processName:c}}));return Response.json({processes:s})}function Cp(e){try{return process.kill(e,0),!0}catch{return!1}}async function Np(e){if(process.platform==="win32")try{const{stdout:r}=await An(`tasklist /FI "PID eq ${e}" /FO CSV /NH`),a=r.match(/"([^"]+)"/);if(!a)return null;const s=a[1];if(s.toLowerCase()==="node.exe")try{const{stdout:o}=await An(`wmic process where "ProcessId=${e}" get CommandLine /FORMAT:LIST`),i=o.match(/codeyam-(\w+)/);if(i)return`codeyam-${i[1]}`}catch{}return s}catch{return null}try{const{stdout:r}=await An(`ps -p ${e} -o comm=`);return r.trim()||null}catch{try{const{stdout:a}=await An(`ps -p ${e} -o args=`),s=a.trim(),o=s.match(/codeyam-(\w+)/);return o?`codeyam-${o[1]}`:s.split(" ")[0]||null}catch{return null}}}const Sp=Object.freeze(Object.defineProperty({__proto__:null,loader:wp},Symbol.toStringTag,{value:"Module"})),kp=ar(import.meta.url),Ep=Z.dirname(kp);function Ap({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=Fo(),r=fe()||(t==null?void 0:t.projectRoot);if(!r)throw new Error("Could not determine project root");const a=(t==null?void 0:t.port)||3111,s=Z.join(Ep,"..","..","..","..","webserver","bootstrap.js"),o=Z.join(r,".codeyam","logs");K.existsSync(o)||K.mkdirSync(o,{recursive:!0});const i=K.openSync(Z.join(o,"background-server.log"),"a"),c=K.openSync(Z.join(o,"background-server-error.log"),"a"),d=new Date().toISOString();K.appendFileSync(Z.join(o,"background-server.log"),`
201
- [${d}] Server restart requested via dashboard
202
- `),Hd();const m=rr("node",[s],{detached:!0,stdio:["ignore",i,c],env:{...process.env,CODEYAM_PORT:a.toString(),CODEYAM_ROOT_PATH:r,CODEYAM_PROCESS_NAME:"codeyam-server",CODEYAM_WAIT_FOR_PORT:"true"}});m.unref(),console.log(`[api.restart-server] Spawned new server process (pid: ${m.pid})`);const u=new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json"}});return setTimeout(()=>{console.log("[api.restart-server] Exiting old server process"),process.exit(0)},100),u}catch(t){return console.error("[api.restart-server] Error restarting server:",t),new Response(JSON.stringify({success:!1,error:t instanceof Error?t.message:"Unknown error"}),{status:500,headers:{"Content-Type":"application/json"}})}}const _p=Object.freeze(Object.defineProperty({__proto__:null,action:Ap},Symbol.toStringTag,{value:"Module"}));async function Pp({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((c,d)=>{var h,p,f,g,y;const m=(p=(h=c.metadata)==null?void 0:h.data)==null?void 0:p.argumentsData,u=Array.isArray(m)&&m.length>0?JSON.stringify(m[0]).substring(0,200):"empty-or-not-array";console.log(`[API] Scenario ${d}: ${c.name}`,{id:c.id,projectId:c.projectId,analysisId:c.analysisId,hasMetadata:!!c.metadata,hasData:!!((f=c.metadata)!=null&&f.data),mockDataKeys:(y=(g=c.metadata)==null?void 0:g.data)!=null&&y.mockData?Object.keys(c.metadata.data.mockData):[],argumentsDataLength:Array.isArray(m)?m.length:"not-array",argumentsDataPreview:u})});const s=a.map(c=>({...c,projectId:c.projectId||r.projectId,analysisId:c.analysisId||r.id})),o=await td(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((c,d)=>{var u,h;const m=(h=(u=c.metadata)==null?void 0:u.data)==null?void 0:h.argumentsData;console.log(`[API] Saved scenario ${d}: ${c.name}`,{id:c.id,argumentsDataLength:Array.isArray(m)?m.length:"not-array"})});const i={...r,scenarios:o};return Response.json({success:!0,analysis:i})}catch(t){return console.error("[API] Error saving scenarios:",t),Response.json({error:"Failed to save scenarios",details:t instanceof Error?t.message:String(t)},{status:500})}}const Mp=Object.freeze(Object.defineProperty({__proto__:null,action:Pp},Symbol.toStringTag,{value:"Module"})),Tp=()=>[{title:"Agent Transcripts - CodeYam"},{name:"description",content:"View background agent transcripts and tool call history"}];async function jp({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("search")||"",a=t.searchParams.get("page")||"1",s=new URLSearchParams;r&&s.set("search",r),a!=="1"&&s.set("page",a);const o=s.toString(),i=new URL(`/api/agent-transcripts${o?`?${o}`:""}`,e.url),d=await(await fetch(i.toString())).json();if(d.error)return W({agents:[],error:d.error,search:r,page:1,totalPages:1});const m=d.total??(d.agents||[]).length,u=d.pageSize??20;return W({agents:d.agents||[],error:null,search:r,page:d.page??parseInt(a,10),totalPages:Math.max(1,Math.ceil(m/u))})}catch(t){return console.error("Failed to load agent transcripts:",t),W({agents:[],error:"Failed to load agent transcripts",search:"",page:1,totalPages:1})}}function Ip(e){if(!e)return"";try{return new Date(e).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}catch{return e}}function $p(e){if(!e)return"";try{return new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1})}catch{return e}}function Rp(e){return e.includes("opus")?"Opus":e.includes("sonnet")?"Sonnet":e.includes("haiku")?"Haiku":e}function Rn({type:e,toolName:t}){const r={user_prompt:"bg-[#00b4d8] text-black",assistant_text:"bg-[#a8dadc] text-black",tool_call:"bg-[#f4a261] text-black",tool_result:"bg-[#2a9d8f] text-black",context:"bg-[#7c3aed] text-white"},a={user_prompt:"USER",assistant_text:"ASSISTANT",tool_call:t||"TOOL",tool_result:"RESULT",context:"CONTEXT"};return n("span",{className:`inline-block px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wide ${r[e]||"bg-gray-300 text-black"}`,children:a[e]||e})}function Dp({input:e}){return n("div",{className:"text-xs font-mono space-y-1",children:Object.entries(e).map(([t,r])=>{let a=typeof r=="string"?r:JSON.stringify(r);return a.length>500&&(a=a.slice(0,500)+"..."),l("div",{children:[l("span",{className:"text-[#f4a261] font-bold",children:[t,":"]})," ",n("span",{className:"text-gray-700",children:a})]},t)})})}function Lp({content:e,truncated:t,fullLength:r}){const[a,s]=_(!1);return l("div",{children:[l("pre",{className:"whitespace-pre-wrap break-words text-xs max-h-96 overflow-y-auto text-gray-700",children:[e,t&&!a&&"..."]}),t&&n("button",{onClick:()=>s(!a),className:"text-[11px] text-gray-500 hover:text-gray-700 mt-1 font-mono cursor-pointer",children:a?"Show less":`Show more (${(r||0)-e.length} more chars)`})]})}function Fp({entry:e,pairedResult:t}){const[r,a]=_(!1),s=Ip(e.timestamp||"");return e.type==="user_prompt"?l("div",{className:"my-2",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(Rn,{type:"user_prompt"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:s})]}),n("pre",{className:"bg-white border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-xs font-mono border-l-[3px] border-l-[#00b4d8] max-h-72 overflow-y-auto text-gray-800",children:e.text})]}):e.type==="assistant_text"?l("div",{className:"my-2",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(Rn,{type:"assistant_text"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:s})]}),n("div",{className:"bg-white border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-sm border-l-[3px] border-l-[#a8dadc] text-gray-800",children:e.text})]}):e.type==="tool_call"?l("div",{className:"my-2",children:[l("button",{onClick:()=>a(!r),className:"flex items-center gap-2 w-full text-left bg-white border border-gray-200 rounded-md px-3 py-2 hover:bg-gray-50 cursor-pointer",children:[r?n(Qe,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}):n(xt,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}),n(Rn,{type:"tool_call",toolName:e.name}),n("span",{className:"text-xs text-gray-500 font-mono truncate flex-1",children:e.summary||""}),n("span",{className:"text-[11px] text-gray-400 font-mono flex-shrink-0",children:s})]}),r&&l("div",{className:"bg-white border border-t-0 border-gray-200 rounded-b-md px-3 py-2 border-l-[3px] border-l-[#f4a261]",children:[n(Dp,{input:e.input||{}}),t&&l("div",{className:"mt-3 pt-3 border-t border-gray-200",children:[l("div",{className:"text-[11px] font-bold uppercase tracking-wide text-[#2a9d8f] mb-1",children:["Result",t.is_error?" (Error)":"",":"]}),n(Lp,{content:t.content||"",truncated:t.truncated,fullLength:t.fullLength})]})]})]}):(e.type==="tool_result",null)}function Op({context:e}){const[t,r]=_(!1);return l("div",{className:"my-2",children:[l("button",{onClick:()=>r(!t),className:"flex items-center gap-2 mb-1 cursor-pointer hover:opacity-80",children:[t?n(Qe,{className:"w-3 h-3 text-gray-400"}):n(xt,{className:"w-3 h-3 text-gray-400"}),n(Rn,{type:"context"}),n("span",{className:"text-xs text-gray-500",children:"Full prompt context"})]}),t&&n("pre",{className:"bg-gray-50 border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-xs font-mono border-l-[3px] border-l-[#7c3aed] max-h-96 overflow-y-auto text-gray-700",children:e})]})}function zp({snippet:e}){const[t,r]=_(!1),a=e.split(`
203
- `).filter(c=>c.trim()),s=a.slice(0,4),o=a.length>4,i=t?a:s;return l("div",{className:"my-2 bg-blue-50 border border-blue-200 rounded-md p-3",children:[l("div",{className:"flex items-center gap-2 mb-2",children:[n(ol,{className:"w-3.5 h-3.5 text-blue-600"}),n("span",{className:"text-xs font-bold text-blue-800",children:"Source Conversation"}),l("span",{className:"text-[10px] text-blue-500",children:[a.length," message",a.length!==1?"s":""]})]}),n("div",{className:"space-y-1",children:i.map((c,d)=>{const m=c.match(/^\[(\w+)\]:\s*(.*)/);if(!m)return null;const[,u,h]=m,p=u==="user";return l("div",{className:"text-xs",children:[l("span",{className:`font-bold ${p?"text-blue-700":"text-gray-500"}`,children:[p?"User":"Assistant",":"]})," ",n("span",{className:"text-gray-700",children:h.length>200?h.slice(0,200)+"...":h})]},d)})}),o&&n("button",{onClick:()=>r(!t),className:"text-[11px] text-blue-600 hover:text-blue-800 mt-2 font-mono cursor-pointer",children:t?"Show less":`Show all ${a.length} messages`})]})}function Yp({change:e}){const[t,r]=_(!1),a=e.action==="created"?!!e.content:e.action==="modified"?!!(e.oldString||e.newString):!1;return l("li",{children:[n("button",{onClick:()=>a&&r(!t),className:`text-left w-full ${a?"hover:text-green-900 cursor-pointer":""}`,children:l("span",{className:"inline-flex items-center gap-1",children:[a&&(t?n(Qe,{className:"w-3 h-3 inline flex-shrink-0"}):n(xt,{className:"w-3 h-3 inline flex-shrink-0"})),e.action==="created"?"Created":"Modified"," ",e.filePath]})}),t&&e.action==="created"&&e.content&&n("pre",{className:"mt-1 mb-2 ml-4 p-2 bg-white border border-green-200 rounded text-[11px] text-gray-700 whitespace-pre-wrap break-words max-h-64 overflow-y-auto",children:e.content}),t&&e.action==="modified"&&l("div",{className:"mt-1 mb-2 ml-4 space-y-1",children:[e.oldString&&l("pre",{className:"p-2 bg-red-50 border border-red-200 rounded text-[11px] text-red-800 whitespace-pre-wrap break-words max-h-32 overflow-y-auto",children:["- ",e.oldString]}),e.newString&&l("pre",{className:"p-2 bg-green-50 border border-green-300 rounded text-[11px] text-green-800 whitespace-pre-wrap break-words max-h-32 overflow-y-auto",children:["+ ",e.newString]})]})]})}function Bp({changes:e}){const t=e.filter(i=>i.action==="touched"),r=e.filter(i=>i.action!=="touched"),a=r.some(i=>i.action==="created"),s=r.some(i=>i.action==="modified");return l("div",{className:`my-2 border rounded-md p-3 ${a?"bg-green-50 border-green-200 text-green-800 [&_ul]:text-green-700":s?"bg-amber-50 border-amber-200 text-amber-800 [&_ul]:text-amber-700":"bg-gray-50 border-gray-200 text-gray-600 [&_ul]:text-gray-500"}`,children:[n("div",{className:"text-xs font-bold mb-1",children:"Rule Changes:"}),l("ul",{className:"text-xs space-y-0.5 font-mono",children:[r.map((i,c)=>n(Yp,{change:i},c)),t.length>0&&l("li",{children:["Touched timestamps on ",t.length," rule",t.length!==1?"s":""]})]})]})}function Up({result:e}){const t=e.is_error,r=t?"bg-red-50 border-red-200":"bg-green-50 border-green-200",a=t?"text-red-800":"text-green-800",s=t?"text-red-700":"text-green-700",o=e.subtype.replace(/^error_/,"").replace(/_/g," "),i=d=>d>=6e4?`${(d/6e4).toFixed(1)}m`:`${(d/1e3).toFixed(1)}s`,c=d=>d>=1e3?`${(d/1e3).toFixed(1)}k`:String(d);return l("div",{className:`my-2 border rounded-md p-3 ${r}`,children:[l("div",{className:`text-xs font-bold mb-1 ${a}`,children:["Session Result: ",o]}),l("div",{className:`text-xs ${s} font-mono space-y-0.5`,children:[l("div",{className:"flex flex-wrap gap-x-4 gap-y-0.5",children:[e.duration_ms!=null&&l("span",{children:["Duration: ",i(e.duration_ms)]}),e.duration_api_ms!=null&&l("span",{children:["API time: ",i(e.duration_api_ms)]}),e.num_turns!=null&&l("span",{children:["Turns: ",e.num_turns]}),e.total_cost_usd!=null&&l("span",{children:["Cost: $",e.total_cost_usd.toFixed(4)]})]}),e.usage&&l("div",{className:"flex flex-wrap gap-x-4 gap-y-0.5 mt-1",children:[e.usage.input_tokens!=null&&l("span",{children:["Input: ",c(e.usage.input_tokens)]}),e.usage.output_tokens!=null&&l("span",{children:["Output: ",c(e.usage.output_tokens)]}),e.usage.cache_read_input_tokens!=null&&l("span",{children:["Cache read: ",c(e.usage.cache_read_input_tokens)]}),e.usage.cache_creation_input_tokens!=null&&l("span",{children:["Cache write:"," ",c(e.usage.cache_creation_input_tokens)]})]}),e.errors&&e.errors.length>0&&n("div",{className:"mt-1",children:e.errors.map((d,m)=>n("div",{className:"text-red-700 break-words",children:d},m))})]})]})}function Wp({agent:e,defaultOpen:t,isAdmin:r}){var k,N,E;const[a,s]=_(t),[o,i]=_(!1),[c,d]=_(null),[m,u]=_(!1),h=ae(()=>{const S={};for(const M of e.entries)M.type==="tool_result"&&M.tool_use_id&&(S[M.tool_use_id]=M);return S},[e.entries]),p=ae(()=>{const S=new Set;for(const M of e.entries)M.type==="tool_call"&&M.tool_use_id&&h[M.tool_use_id]&&S.add(M.tool_use_id);return S},[e.entries,h]),f=S=>{S.stopPropagation(),i(!0),d(null),fetch("/api/save-fixture",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:e.id})}).then(M=>M.json()).then(M=>{M.success?d(`Saved to ${M.fixturePath}`):d(`Error: ${M.error}`)}).catch(M=>{d(`Error: ${M instanceof Error?M.message:String(M)}`)}).finally(()=>{i(!1)})},g=(e.ruleChanges||[]).filter(S=>S.action!=="touched"),y=g.filter(S=>S.action==="created"),x=g.filter(S=>S.action==="modified"),v=(e.ruleChanges||[]).filter(S=>S.action==="touched"),b=g.length>0,w=v.length>0,C=b||w;return l("div",{className:`bg-white border rounded-lg overflow-hidden mb-4 ${e.stats.errors>0?"border-red-300":y.length>0?"border-green-300":x.length>0?"border-amber-300":"border-gray-200"}`,children:[l("button",{onClick:()=>s(!a),className:"w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-gray-50 cursor-pointer",children:[a?n(Qe,{className:"w-4 h-4 text-gray-400 flex-shrink-0"}):n(xt,{className:"w-4 h-4 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm font-bold text-[#005C75] font-mono",children:e.id.slice(0,8)}),e.slug&&n("span",{className:"text-xs text-gray-500",children:e.slug}),e.model&&n("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-bold bg-purple-100 text-purple-700",title:e.model,children:Rp(e.model)}),y.length>0&&l("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-green-100 text-green-800",children:[n(Ln,{className:"w-3 h-3"}),y.length," rule",y.length!==1?"s":""," ","created"]}),x.length>0&&l("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-amber-100 text-amber-800",children:[n(Ln,{className:"w-3 h-3"}),x.length," rule",x.length!==1?"s":""," ","modified"]}),!b&&w&&l("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-gray-100 text-gray-500",children:[v.length," timestamp",v.length!==1?"s":""," ","touched"]}),e.stats.errors>0&&l("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-red-100 text-red-800",children:[n(Dn,{className:"w-3 h-3 flex-shrink-0"}),e.stats.errors," ",e.stats.errors===1?"Error":"Errors"]}),l("span",{className:"text-[11px] text-gray-400 font-mono",children:[e.stats.toolCalls," tool calls, ",e.stats.textBlocks," text blocks",((k=e.sessionResult)==null?void 0:k.duration_ms)!=null&&l(le,{children:[" · ",e.sessionResult.duration_ms>=6e4?`${(e.sessionResult.duration_ms/6e4).toFixed(1)}m`:`${(e.sessionResult.duration_ms/1e3).toFixed(1)}s`]}),((N=e.sessionResult)==null?void 0:N.total_cost_usd)!=null&&l(le,{children:[" · ","$",e.sessionResult.total_cost_usd.toFixed(2)]})]}),l("span",{className:"text-[11px] text-gray-400 font-mono ml-auto flex items-center gap-2",children:[$p(e.timestamp),r&&b&&l("button",{onClick:f,disabled:o,className:"inline-flex items-center gap-1 px-2 py-1 rounded text-[10px] font-bold bg-gray-100 text-gray-600 hover:bg-gray-200 disabled:opacity-50 cursor-pointer",title:"Save as test fixture",children:[n(sl,{className:"w-3 h-3"}),o?"Saving...":"Save Fixture"]})]})]}),c&&n("div",{className:`px-4 py-2 text-xs font-mono ${c.startsWith("Error")?"bg-red-50 text-red-700":"bg-green-50 text-green-700"}`,children:c}),a&&l("div",{className:"px-4 pb-4 border-t border-gray-100",children:[e.sourceFile&&l("div",{className:"flex items-center gap-2 py-2 text-xs text-gray-500 font-mono",children:[n("span",{className:"text-gray-400",children:"FILE:"}),n("span",{className:"truncate",children:e.sourceFile}),n("button",{onClick:S=>{S.stopPropagation(),navigator.clipboard.writeText(e.sourceFile),u(!0),setTimeout(()=>u(!1),2e3)},className:"p-0.5 rounded text-gray-400 hover:text-gray-600 cursor-pointer transition-colors flex-shrink-0",title:"Copy file path",children:m?n(et,{className:"w-3.5 h-3.5 text-green-500"}):n(st,{className:"w-3.5 h-3.5"})})]}),e.sessionResult&&n(Up,{result:e.sessionResult}),e.stats.errors>0&&((E=e.stats.errorMessages)==null?void 0:E.length)>0&&l("div",{className:"my-2 bg-red-50 border border-red-200 rounded-md p-3",children:[l("div",{className:"text-xs font-bold text-red-800 mb-1",children:[e.stats.errors," Error",e.stats.errors!==1?"s":"",":"]}),n("ul",{className:"text-xs text-red-700 space-y-1 font-mono",children:e.stats.errorMessages.map((S,M)=>n("li",{className:"break-words",children:S},M))})]}),e.conversationSnippet&&n(zp,{snippet:e.conversationSnippet}),C&&n(Bp,{changes:e.ruleChanges}),e.context&&n(Op,{context:e.context}),e.entries.map((S,M)=>{if(S.type==="tool_result"&&S.tool_use_id&&p.has(S.tool_use_id))return null;const F=S.type==="tool_call"&&S.tool_use_id?h[S.tool_use_id]:void 0;return n(Fp,{entry:S,pairedResult:F},`${e.id}-${M}`)})]})]})}function Br(e,t){const r=new URLSearchParams;t&&r.set("search",t),e>1&&r.set("page",String(e));const a=r.toString();return`/agent-transcripts${a?`?${a}`:""}`}const Hp=De(function(){const{agents:t,error:r,search:a,page:s,totalPages:o}=Be(),i=It(),c=zi("root"),d=(c==null?void 0:c.isAdmin)??!1,[m,u]=_(a),[h,p]=_(!1),[f,g]=_(0);tt({source:"agent-transcripts-page"});const y=v=>{v.preventDefault(),window.location.href=Br(1,m)},x=()=>{p(!h),g(v=>v+1)};return r?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:r})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-20 py-12 font-sans",children:[l("div",{className:"mb-8",children:[l("div",{className:"flex items-center gap-3 mb-1",children:[n("button",{onClick:()=>{i("/memory")},className:"text-gray-600 hover:text-[#005C75] transition-colors cursor-pointer",title:"Back to Memory","aria-label":"Back to Memory",children:n(rl,{className:"w-5 h-5"})}),n(Fn,{className:"w-6 h-6 text-[#232323]"}),n("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Agent Transcripts"})]}),n("p",{className:"text-[15px] text-gray-500 ml-14",children:"View background agent transcripts and tool call history"})]}),l("div",{className:"flex items-center gap-4 mb-6",children:[l("form",{onSubmit:y,className:"relative flex-1 max-w-md",children:[n(dn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:m,onChange:v=>u(v.target.value),placeholder:"Search transcripts...",className:"w-full pl-10 pr-4 py-2 border border-gray-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent text-sm"})]}),n("button",{onClick:x,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:h?"Collapse All":"Expand All"})]}),l("div",{className:"text-sm text-gray-500 mb-4",children:["Page ",s," of ",o,a&&l("span",{children:[" ","matching “",a,"”",n(se,{to:"/agent-transcripts",className:"text-[#005C75] hover:underline ml-2",children:"Clear"})]})]}),t.length===0?l("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(Fn,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),n("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Agent Transcripts Found"}),n("p",{className:"text-gray-500",children:"Background agent output files will appear here when available."})]}):n("div",{children:t.map(v=>n(Wp,{agent:v,defaultOpen:h,isAdmin:d},v.id))},f),o>1&&l("div",{className:"flex items-center justify-center gap-3 mt-8",children:[l("a",{href:s>1?Br(s-1,a):void 0,className:`inline-flex items-center gap-1 px-3 py-1.5 rounded-md text-sm font-medium ${s>1?"bg-white border border-gray-200 text-gray-700 hover:bg-gray-50 cursor-pointer":"bg-gray-100 text-gray-400 pointer-events-none"}`,children:[n(al,{className:"w-4 h-4"}),"Prev"]}),l("span",{className:"text-sm text-gray-500 font-mono",children:[s," / ",o]}),l("a",{href:s<o?Br(s+1,a):void 0,className:`inline-flex items-center gap-1 px-3 py-1.5 rounded-md text-sm font-medium ${s<o?"bg-white border border-gray-200 text-gray-700 hover:bg-gray-50 cursor-pointer":"bg-gray-100 text-gray-400 pointer-events-none"}`,children:["Next",n(xt,{className:"w-4 h-4"})]})]})]})})}),Vp=Object.freeze(Object.defineProperty({__proto__:null,default:Hp,loader:jp,meta:Tp},Symbol.toStringTag,{value:"Module"}));async function Jp({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(!Ps(r))return Response.json({error:"Process not running",pid:r},{status:404});try{process.kill(r,a)}catch(u){return Response.json({error:"Failed to kill process",pid:r,details:u instanceof Error?u.message:String(u)},{status:500})}const i=3e4,c=500,d=Date.now();let m=!0;for(;m&&Date.now()-d<i;)await new Promise(u=>setTimeout(u,c)),m=Ps(r);if(m){console.warn(`Process ${r} didn't die after SIGTERM, sending SIGKILL`);try{process.kill(r,"SIGKILL"),await new Promise(u=>setTimeout(u,2e3))}catch(u){console.error(`Failed to SIGKILL process ${r}:`,u)}}if(s)try{await ft({commitSha:s,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:`Process ${r} killed by user`}})}catch(u){console.error("Failed to update database after killing process:",u)}return Response.json({success:!0,pid:r,signal:a,message:`Process ${r} killed successfully`,waitedMs:Date.now()-d})}catch(t){return console.error("Error in kill-process API:",t),Response.json({error:"Internal server error",details:t instanceof Error?t.message:String(t)},{status:500})}}function Ps(e){try{return process.kill(e,0),!0}catch{return!1}}const Gp=Object.freeze(Object.defineProperty({__proto__:null,action:Jp},Symbol.toStringTag,{value:"Module"})),qp=ar(import.meta.url),Kp=oe.dirname(qp),Qp=oe.resolve(Kp,"../../../../src/utils/ruleReflection/__tests__/fixtures/captured");function Zp(e){const t=[],r=new Set;for(const a of e.split(`
204
- `)){const s=a.trim();if(!s)continue;let o;try{o=JSON.parse(s)}catch{continue}if(o.type!=="assistant")continue;const i=o.message;if(!(!i||!Array.isArray(i.content)))for(const c of i.content){if(typeof c!="object"||c===null)continue;const d=c;if(d.type!=="tool_use")continue;const m=String(d.name||""),u=d.input||{};if(m==="Write"||m==="Edit"){const h=String(u.file_path||"");if(h.includes(".claude/rules/")){const p=h.replace(/^.*?(\.claude\/rules\/)/,"$1"),f=`${m}:${p}`;r.has(f)||(r.add(f),t.push({action:m==="Write"?"created":"modified",filePath:p}))}}else if(m==="Bash"){const h=String(u.command||"");if(h.includes("codeyam memory touch")){const p=`touch:${h}`;r.has(p)||(r.add(p),t.push({action:"touched",filePath:h}))}}}}return t}async function Xp({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{sessionId:r}=t;if(!r)return Response.json({error:"Missing required field: sessionId"},{status:400});const a=await Qo(),s=a?oe.join(In,a):null;let o=s?oe.join(s,`${r}.log`):"";if((!o||!pt(o))&&(o=oe.join(In,`${r}.log`)),!pt(o))return Response.json({error:`Log file not found: ${r}.log`},{status:404});const i=await Jr(o,"utf-8");let c=s?oe.join(s,`${r}.context`):"";(!c||!pt(c))&&(c=oe.join(In,`${r}.context`));let d=null;if(pt(c))try{d=await Jr(c,"utf-8")}catch{}const m=Zp(i),h=d?["no,","no ","that's not","wrong","incorrect","actually,","actually ","i meant","i mean","not what i","stop","wait","don't do","shouldn't","try again","that broke","that failed","error","bug"].some(x=>d.toLowerCase().includes(x)):!1,p=r.endsWith("-stale")?"-stale":r.endsWith("-conversation")?"-conv":r.endsWith("-interruption")?"-int":"",f=r.slice(0,8)+p,g=oe.join(Qp,f);await _l(g,{recursive:!0}),await Xt(oe.join(g,"agent-log.jsonl"),i),d&&await Xt(oe.join(g,"context.md"),d),await Xt(oe.join(g,"rule-changes.json"),JSON.stringify(m,null,2)),await Xt(oe.join(g,"metadata.json"),JSON.stringify({sessionId:r,capturedAt:new Date().toISOString(),hasConfusion:h,ruleChangeCount:m.length},null,2));const y=oe.relative(process.cwd(),g);return console.log(`[api.save-fixture] Saved fixture to ${y}`),Response.json({success:!0,fixturePath:y})}catch(t){return console.error("[api.save-fixture] Error:",t),Response.json({error:"Failed to save fixture",details:t instanceof Error?t.message:String(t)},{status:500})}}const ef=Object.freeze(Object.defineProperty({__proto__:null,action:Xp},Symbol.toStringTag,{value:"Module"}));async function tf({params:e}){const t=e["*"];if(!t)return new Response("Screenshot path is required",{status:400});const r=fe();if(!r)return console.error("[screenshot api] Project root not found"),new Response("Project root not found",{status:500});const a=oe.join(r,".codeyam","captures","screenshots",t);try{await he.access(a);const s=await he.readFile(a),o=oe.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 nf=Object.freeze(Object.defineProperty({__proto__:null,loader:tf},Symbol.toStringTag,{value:"Module"})),Ms={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 Na({type:e,className:t=""}){const r=Ms[e]||Ms.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 rf={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 _n({variant:e,pid:t,label:r,className:a=""}){const s=rf[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 Ye({screenshotPath:e,cacheBuster:t,alt:r,className:a="",title:s}){const[o,i]=_("loading"),[c,d]=_(!1),m=Ne(null),u=t?`/api/screenshot/${e}?cb=${t}`:`/api/screenshot/${e}`,h=()=>{i("success"),d(!0)},p=()=>{i("error"),d(!1)};return ee(()=>{i("loading"),d(!1);const f=m.current;f!=null&&f.complete&&(f.naturalHeight!==0?(i("success"),d(!0)):(i("error"),d(!1)))},[u]),e?l("div",{className:"relative w-full h-full flex items-center justify-center",title:s,children:[n("img",{ref:m,src:u,alt:r,onLoad:h,onError:p,className:a||"max-w-full max-h-full object-contain",style:{visibility:c?"visible":"hidden",position:c?"relative":"absolute"}}),o==="loading"&&n("div",{className:"absolute inset-0 bg-gray-100 animate-pulse rounded flex items-center justify-center",children:n("svg",{className:"w-8 h-8 text-gray-300",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),o==="error"&&l("div",{className:"absolute inset-0 border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",children:[n("span",{className:"text-2xl text-gray-400",children:"📷"}),n("span",{className:"text-gray-400 whitespace-nowrap",children:"No Screenshot"})]})]}):n("div",{className:"w-full h-full border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",title:s,children:n("span",{className:"text-2xl text-gray-400",children:"📷"})})}let Ts=!1;function af(){if(Ts)return;const e=document.createElement("style");e.textContent=`
205
- @keyframes strongPulse {
206
- 0%, 100% { opacity: 0.2; }
207
- 50% { opacity: 1; }
208
- }
209
- `,document.head.appendChild(e),Ts=!0}function Sa({size:e="medium",className:t=""}){typeof document<"u"&&af();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 l("div",{className:`flex items-center justify-center ${t}`,style:{gap:`${o}px`},role:"status","aria-label":"Loading",children:[n("div",{className:"rounded-full",style:{width:`${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"}})]})}const sf=()=>[{title:"Activity - CodeYam"},{name:"description",content:"View analysis activity and queue status"}];async function of({request:e,context:t,params:r}){var z,Y,R,A,G,B,H,re;let a=t.analysisQueue;a||(a=await ut());const s=new URL(e.url),o=parseInt(s.searchParams.get("page")||"1",10),i=20,c=r.tab||"current";if(!a)return W({error:"Queue not initialized",state:{paused:!1,jobs:[]},currentRun:void 0,historicalRuns:[],totalHistoricalRuns:0,currentPage:o,totalPages:0,projectSlug:null,commitSha:void 0,queueJobs:[],currentlyExecuting:null,currentEntities:[],tab:c,hasCurrentActivity:!1,queuedCount:0,recentCompletedEntities:[],hasMoreCompletedRuns:!1,currentEntityScenarios:[],currentEntityForScenarios:null,currentAnalysisStatus:null},{status:500});const d=a.getState(),m=await $e();let u=null;if(m&&((z=d==null?void 0:d.currentlyExecuting)!=null&&z.commitSha)){const{project:O,branch:j}=await Ie(m),D=await Un({projectId:O.id,branchId:j.id,shas:[d.currentlyExecuting.commitSha]});u=D&&D.length>0?D[0]:null}else u=await Bt();const h=async O=>{const j=await zt(O);if(!j)return null;const{getAnalysesForEntity:D}=await Promise.resolve().then(()=>yd),q=await D(O,!1);return{...j,analyses:q||[]}},p=await Promise.all(((d==null?void 0:d.jobs)||[]).map(async O=>{const j=[];if(O.entityShas&&O.entityShas.length>0){const D=O.entityShas.map(te=>h(te)),q=await Promise.all(D);j.push(...q.filter(te=>te!==null))}return{...O,entities:j}}));let f=null;if(d!=null&&d.currentlyExecuting){const O=d.currentlyExecuting,j=[];if(O.entityShas&&O.entityShas.length>0){const D=O.entityShas.map(te=>h(te)),q=await Promise.all(D);j.push(...q.filter(te=>te!==null))}f={...O,entities:j}}const g=f?p.filter(O=>O.id!==f.id):p,y=((R=(Y=u==null?void 0:u.metadata)==null?void 0:Y.currentRun)==null?void 0:R.currentEntityShas)||[],v=(await Promise.all(y.map(O=>h(O)))).filter(O=>O!==null),b=[];if(m)try{const{project:O,branch:j}=await Ie(m),D=await Un({projectId:O.id,branchId:j.id,limit:100});for(const q of D){const te=((A=q.metadata)==null?void 0:A.historicalRuns)||[];b.push(...te)}}catch(O){console.error("[activity.tsx] Failed to load historical runs from commits:",O)}const w=[...b].sort((O,j)=>{const D=O.lastCaptureAt||O.analysisCompletedAt||O.archivedAt||O.createdAt||"";return(j.lastCaptureAt||j.analysisCompletedAt||j.archivedAt||j.createdAt||"").localeCompare(D)}),C=(o-1)*i,k=C+i,N=w.slice(C,k),E=Math.ceil(w.length/i),S=await Promise.all(N.map(async O=>{const j=O.currentEntityShas||[];if(j.length===0)return{...O,entities:[]};const D=await Promise.all(j.map(q=>h(q)));return{...O,entities:D.filter(q=>q!==null)}})),M=!!f,F=g.length,L=w.filter(O=>{const j=!!O.failedAt,D=O.readyToBeCaptured,q=O.capturesCompleted??0,te=D===void 0?!0:D===0||q>=D;return!j&&!!O.analysisCompletedAt&&te}),P=new Set(((G=f==null?void 0:f.entities)==null?void 0:G.map(O=>O.sha))||[]),T=L.filter(O=>!(O.currentEntityShas||[]).some(D=>P.has(D))),I=(await Promise.all(T.slice(0,3).map(async O=>{const j=O.currentEntityShas||[];if(j.length===0)return{run:O,entities:[]};const D=await Promise.all(j.map(q=>h(q)));return{run:O,entities:D.filter(q=>q!==null)}}))).flatMap(({run:O,entities:j})=>j.map(D=>({...D,runId:O.id,completedAt:O.lastCaptureAt||O.analysisCompletedAt||O.archivedAt||O.createdAt})));let J=[],V=null,U=null;if((H=(B=u==null?void 0:u.metadata)==null?void 0:B.currentRun)!=null&&H.analysisCompletedAt&&v.length>0){const O=v[0].sha;V=v[0];const j=await lr(O);j&&j.length>0&&j[0].scenarios&&(J=j[0].scenarios,U=j[0].status)}return W({state:{...d,jobs:g,currentlyExecuting:f},currentRun:(re=u==null?void 0:u.metadata)==null?void 0:re.currentRun,historicalRuns:S,totalHistoricalRuns:w.length,currentPage:o,totalPages:E,projectSlug:m,commitSha:u==null?void 0:u.sha,queueJobs:g,currentlyExecuting:f,currentEntities:v,tab:c,hasCurrentActivity:M,queuedCount:F,recentCompletedEntities:I,hasMoreCompletedRuns:T.length>3,currentEntityScenarios:J,currentEntityForScenarios:V,currentAnalysisStatus:U})}function lf({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(se,{to:o.id==="current"?"/activity":`/activity/${o.id}`,className:`
210
- relative pb-4 px-2 text-sm transition-colors cursor-pointer
211
- ${i?"font-medium border-b-2":"font-normal hover:text-gray-700"}
212
- `,style:i?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:l("span",{className:"flex items-center gap-2",children:[o.label,o.count!==null&&o.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${i?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:o.count}),o.count===null&&o.hasContent&&n("span",{className:`
213
- inline-block w-2 h-2 rounded-full
214
- ${i?"":"bg-gray-400"}
215
- `,style:i?{backgroundColor:"#005C75"}:{}})]})},o.id)})})})}function cf({currentlyExecuting:e,currentRun:t,state:r,projectSlug:a,commitSha:s,onShowLogs:o,recentCompletedEntities:i,hasMoreCompletedRuns:c,currentEntityScenarios:d,currentEntityForScenarios:m,currentAnalysisStatus:u}){var $,I,J,V;const[h,p]=_({}),[f,g]=_({isKilling:!1,current:0,total:0}),y=it(),x=!!e,v=(e==null?void 0:e.entities)||[],b=!!(t!=null&&t.analysisCompletedAt),w=b&&!!(t!=null&&t.capturePid),C=!b,k=x,N=d||[],{lastLine:E}=bt(a,k);ee(()=>{if(!t)return;const U=[t.analyzerPid,t.capturePid].filter(A=>!!A);if(U.length===0)return;let z=!0;const Y=async()=>{try{const G=await(await fetch(`/api/process-status?pids=${U.join(",")}`)).json();if(G.processes&&z){const B={};G.processes.forEach(H=>{B[H.pid]={isRunning:H.isRunning,processName:H.processName}}),p(B)}}catch(A){z&&console.error("Failed to fetch process statuses:",A)}};Y();const R=setInterval(()=>void Y(),5e3);return()=>{z=!1,clearInterval(R)}},[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid]);const[S,M]=_(!1),[F,L]=_(!1);ee(()=>{v.length<=3&&S&&M(!1)},[v.length,S]),ee(()=>{i.length<=3&&F&&L(!1)},[i.length,F]);const P=S?v:v.slice(0,3),T=v.length>3;return l("div",{className:"flex flex-col gap-[45px]",children:[k?l("div",{className:"rounded-[10px] p-[15px]",style:{backgroundColor:"#f6f9fc",border:"1px solid #e0e9ec"},children:[l("div",{className:"flex items-center gap-2 mb-[15px]",children:[n(Xe,{size:14,strokeWidth:2.5,className:"animate-spin",style:{color:"#005c75"}}),n("span",{className:"font-medium",style:{fontSize:"14px",lineHeight:"18px",color:"#005c75"},children:w?"Capturing...":"Analyzing..."})]}),P.map(U=>l("div",{className:"bg-white border border-[#e1e1e1] rounded-[4px] mb-[15px]",style:{height:"60px",padding:"0 15px",display:"flex",alignItems:"center",justifyContent:"space-between",boxShadow:"0 1px 3px 0 rgb(0 0 0 / 0.1)"},children:[l("div",{className:"flex items-center gap-3",children:[n("div",{children:n(Ve,{type:U.entityType||"other",size:"large"})}),l("div",{className:"flex flex-col gap-[1px]",children:[l("div",{className:"flex items-center gap-[14px]",children:[n(se,{to:`/entity/${U.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:U.name}),U.entityType&&n(Na,{type:U.entityType})]}),n("div",{className:"truncate font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",width:"422px"},title:U.filePath,children:U.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"})]},U.sha)),T&&!S&&l("button",{onClick:()=>M(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] mb-[15px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",v.length-3," more"," ",v.length-3===1?"entity":"entities"]}),S&&T&&n("button",{onClick:()=>M(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] mb-[15px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"}),w&&N&&N.length>0&&m&&n("div",{className:"flex gap-[10px] overflow-x-auto mb-[15px]",children:N.map(U=>{var H,re,O,j;if(!U.id)return null;const z=(re=(H=U.metadata)==null?void 0:H.screenshotPaths)==null?void 0:re[0],Y=(O=U.metadata)==null?void 0:O.noScreenshotSaved,R=z&&!Y,A=(j=u==null?void 0:u.scenarios)==null?void 0:j.find(D=>D.name===U.name),B=A&&A.screenshotStartedAt&&!A.screenshotFinishedAt||!R&&!Y;return n(se,{to:`/entity/${m.sha}/scenarios/${U.id}`,className:"border border-solid rounded-[6px] overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"160px",height:"90px",backgroundColor:B?"#f9f9f9":void 0,borderColor:B?"#efefef":"#ccc"},children:R?n(Ye,{screenshotPath:z,alt:U.name,className:"w-full h-full object-contain bg-gray-100"}):B?n("div",{className:"w-full h-full flex items-center justify-center",children:n(Sa,{size:"medium"})}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundColor:"#FAFAFA",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})},U.id)})}),E&&n("div",{className:"mb-[15px] font-['IBM_Plex_Mono']",style:{fontSize:"12px",lineHeight:"20px",fontWeight:500,color:"#005c75"},children:E}),n("div",{className:"mb-[15px]",style:{height:"1px",backgroundColor:"#e0e9ec"}}),((t==null?void 0:t.analyzerPid)||(t==null?void 0:t.capturePid))&&l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center gap-2",children:[l("span",{style:{fontSize:"12px",lineHeight:"15px",fontWeight:400,color:"#000"},children:["Running Processes:"," "]}),(t==null?void 0:t.analyzerPid)&&n(_n,{variant:"analyzer",pid:t.analyzerPid}),(t==null?void 0:t.analyzerPid)&&(C||(($=h[t.analyzerPid])==null?void 0:$.isRunning))&&n(_n,{variant:"running"}),(t==null?void 0:t.capturePid)&&n(_n,{variant:"capture",pid:t.capturePid}),(t==null?void 0:t.capturePid)&&(w||((I=h[t.capturePid])==null?void 0:I.isRunning))&&n(_n,{variant:"running"})]}),(((J=h[t==null?void 0:t.analyzerPid])==null?void 0:J.isRunning)||((V=h[t==null?void 0:t.capturePid])==null?void 0:V.isRunning))&&n("button",{onClick:()=>{const U=[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid].filter(R=>{var A;return!!R&&((A=h[R])==null?void 0:A.isRunning)});if(U.length===0)return;const z=U.join(", ");if(!confirm(`Are you sure you want to kill all running processes (${z})?`))return;g({isKilling:!0,current:1,total:U.length}),(async()=>{for(let R=0;R<U.length;R++){const A=U[R];try{await fetch("/api/kill-process",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:A,commitSha:s||""})})}catch(G){console.error(`Failed to kill process ${A}:`,G)}R<U.length-1&&g({isKilling:!0,current:R+2,total:U.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"})]})]}):l("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[l("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(Zs,{size:24,style:{color:"#005C75"}})}),l("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Current Activity"}),l("p",{className:"text-sm",style:{color:"#8e8e8e"},children:["There are no analyses running. Trigger one from"," ",n(se,{to:"/git",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Git"})," ","or"," ",n(se,{to:"/files",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Files"}),"."]})]})]}),l(se,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]}),i&&i.length>0&&l("div",{children:[n("h3",{className:"font-mono uppercase",style:{fontSize:"12px",lineHeight:"18px",color:"#8e8e8e",marginBottom:"16px",fontWeight:500,letterSpacing:"0.05em"},children:"Recently Completed Analyses"}),l("div",{className:"flex flex-col gap-4",children:[(F?i:i.slice(0,3)).map(U=>{var R;const z=(R=U.analyses)==null?void 0:R[0],Y=(z==null?void 0:z.scenarios)||[];return z==null||z.status,n("div",{className:"rounded-[8px] p-[15px]",style:{backgroundColor:"#ffffff",border:"1px solid #aff1a9"},children:l("div",{className:"flex flex-col gap-[15px]",children:[l("div",{className:"flex items-center",children:[n("div",{className:"flex-shrink-0",children:n(Ve,{type:U.entityType||"other",size:"large"})}),l("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[l("div",{className:"flex items-center gap-[5px]",children:[n(se,{to:`/entity/${U.sha}`,className:"hover:underline cursor-pointer",title:U.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:U.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:U.isUncommitted?"Modified":"Up to date"})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",fontWeight:400},className:"font-mono",title:U.filePath,children:U.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:A=>{A.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:A=>{A.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})})]}),n("div",{className:"border-t border-gray-200 mx-[-15px]"}),Y.length>0?n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:Y.map(A=>{var re,O,j;if(!A.id)return null;const G=(O=(re=A.metadata)==null?void 0:re.screenshotPaths)==null?void 0:O[0],B=(j=A.metadata)==null?void 0:j.noScreenshotSaved,H=G&&!B;return l("div",{className:"shrink-0 flex flex-col gap-2",children:[n(se,{to:`/entity/${U.sha}/scenarios/${A.id}`,className:"block cursor-pointer",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{backgroundColor:H?"#f3f4f6":"#FAFAFA",borderColor:H?"#d1d5db":"#BCCDD3",borderStyle:H?"solid":"dashed"},onMouseEnter:D=>{H&&(D.currentTarget.style.borderColor="#005C75",D.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:D=>{D.currentTarget.style.borderColor=H?"#d1d5db":"#BCCDD3",D.currentTarget.style.boxShadow="none"},children:H?n(Ye,{screenshotPath:G,alt:A.name,className:"max-w-full max-h-full object-contain"}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})})}),n("div",{className:"text-left text-xs text-gray-600 cursor-default",style:{fontSize:"11px",lineHeight:"14px",maxWidth:"144px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:A.name})]},A.id)})}):n("div",{className:"italic",style:{fontSize:"12px",color:"#646464",marginLeft:"49px"},children:"No scenarios available"})]})},U.sha)}),i.length>3&&!F&&l("button",{onClick:()=>L(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",i.length-3," more"," ",i.length-3===1?"entity":"entities"]}),F&&i.length>3&&n("button",{onClick:()=>L(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})]})]})}function df({queueJobs:e,state:t,currentRun:r}){if(!e||e.length===0)return l("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[l("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(il,{size:24,style:{color:"#005C75"}})}),l("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Queued Jobs"}),n("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Analysis jobs will appear here when they are queued but not yet started."})]})]}),l(se,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]});const[a,s]=_(null),[o,i]=_(null),[c,d]=_(null),[m,u]=_(!1),[h,p]=_(!1),[f,g]=_(new Set),y=it();ee(()=>{e.length<=3&&h&&p(!1)},[e.length,h]);const x=N=>{s(N)},v=(N,E)=>{N.preventDefault(),i(E)},b=async(N,E)=>{if(N.preventDefault(),!a){i(null);return}const S=e.findIndex(L=>L.id===a);if(S===-1){s(null),i(null);return}if(S===E){s(null),i(null);return}const M=S<E?"down":"up",F=Math.abs(E-S);u(!0);try{for(let L=0;L<F;L++)await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"reorder",jobId:a,direction:M})});y.revalidate()}catch(L){console.error("Failed to reorder job:",L)}finally{u(!1),s(null),i(null)}},w=()=>{m||(s(null),i(null))},C=async N=>{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:N})}),window.location.reload()}catch(E){console.error("Failed to cancel job:",E)}},k=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(N){console.error("Failed to cancel jobs:",N)}};return l("div",{children:[l("div",{className:"flex items-center justify-between mb-4",children:[l("h3",{className:"font-semibold",style:{fontSize:"16px",lineHeight:"24px",color:"#343434"},children:[e.length," Queued Job",e.length!==1?"s":""]}),e.length>0&&n("button",{onClick:()=>void k(),className:"px-[10px] py-0 rounded transition-colors cursor-pointer hover:bg-red-300",style:{backgroundColor:"#ffdcd9",color:"#ef4444",fontSize:"12px",fontWeight:500,height:"29px"},children:"Cancel All"})]}),l("div",{className:"flex flex-col gap-3",children:[(h?e:e.slice(0,3)).map(N=>{var T,$,I,J;const E=e.findIndex(V=>V.id===N.id),S=c===E,M=a===N.id,F=o===E,L=f.has(N.id),P=((T=N.entities)==null?void 0:T.length)>0?L?N.entities:N.entities.slice(0,3):[];return l("div",{className:"rounded-lg p-4 relative",style:{backgroundColor:"#f6f9fc",border:"1px solid #005C75",opacity:M||m?.5:1,transform:F&&a!==null&&!M?"translateY(-2px)":"translateY(0)",transition:"transform 0.2s ease, opacity 0.2s ease",cursor:m?"not-allowed":M?"grabbing":"grab"},onMouseEnter:()=>d(E),onMouseLeave:()=>d(null),draggable:!m,onDragStart:V=>{x(N.id),V.dataTransfer.effectAllowed="move"},onDragOver:V=>v(V,E),onDrop:V=>void b(V,E),onDragEnd:w,children:[l("div",{className:"absolute left-4 top-4 flex items-center gap-1.5 flex-shrink-0",children:[n(ll,{size:16,style:{color:"#005C75"}}),l("span",{style:{fontSize:"14px",fontWeight:500,lineHeight:"18px",color:"#005C75"},children:["Job ",E+1]})]}),l("div",{className:"flex flex-col gap-2 mt-8",children:[P.length>0?l(le,{children:[P.map(V=>n("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:n("div",{className:"flex items-center justify-between h-full px-[15px]",children:l("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{children:n(Ve,{type:V.entityType||"other",size:"large"})}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(se,{to:`/entity/${V.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:V.name}),V.entityType&&n(Na,{type:V.entityType})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:V.filePath})]})]})})},V.sha)),(($=N.entities)==null?void 0:$.length)>3&&n("button",{onClick:()=>{g(V=>{const U=new Set(V);return U.has(N.id)?U.delete(N.id):U.add(N.id),U})},className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"40px",fontSize:"12px",color:"#646464",fontWeight:500},children:L?"Show less":`+${N.entities.length-3} more ${N.entities.length-3===1?"entity":"entities"}`})]}):n("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:n("div",{className:"flex items-center justify-between h-full px-[15px]",children:l("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{style:{transform:"scale(1.0)"},children:n(On,{size:18,style:{color:"#8e8e8e"}})}),l("div",{className:"flex-1",children:[n("div",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:((I=N.entityNames)==null?void 0:I[0])||(N.type==="analysis"?"Analysis Job":N.type==="recapture"?"Recapture Job":N.type==="debug-setup"?"Debug Setup":N.type.charAt(0).toUpperCase()+N.type.slice(1))}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:((J=N.filePaths)==null?void 0:J[0])||(N.filePaths&&N.filePaths.length>1?`${N.filePaths.length} files`:N.entityShas&&N.entityShas.length>0?`${N.entityShas.length} ${N.entityShas.length===1?"entity":"entities"}`:"Queued for processing")})]})]})})}),l("div",{className:"flex items-center justify-end gap-2 mt-1",children:[S&&n("div",{className:"cursor-grab active:cursor-grabbing",style:{color:"#8e8e8e"},title:"Drag to reorder",children:n(cl,{size:20})}),n("button",{onClick:()=>void C(N.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"})]})]})]},N.id)}),e.length>3&&!h&&l("button",{onClick:()=>p(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",e.length-3," more"," ",e.length-3===1?"job":"jobs"]}),h&&e.length>3&&n("button",{onClick:()=>p(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})]})}function uf({historicalRuns:e,totalHistoricalRuns:t,currentPage:r,totalPages:a,tab:s,onShowLogs:o}){if(t===0)return l("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[l("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(dl,{size:24,style:{color:"#005C75"}})}),l("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Historic Activity"}),n("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Completed analyses will appear here for historical reference."})]})]}),l(se,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]});const[i,c]=_(!1),d=[];e.forEach(u=>{u.entities&&u.entities.length>0&&u.entities.forEach(h=>{d.push({...h,runCreatedAt:u.createdAt})})});const m=i?d:d.slice(0,3);return l("div",{className:"flex flex-col gap-4",children:[m.map(u=>{var g;const h=(g=u.analyses)==null?void 0:g[0],p=(h==null?void 0:h.scenarios)||[],f=!u.isUncommitted;return l("div",{className:"rounded-lg p-4",style:{backgroundColor:f?"#ffffff":"#fef9e7",border:"1px solid",borderColor:f?"#aff1a9":"#f9d689"},children:[l("div",{className:"flex items-start justify-between mb-3",children:[l("div",{className:"flex items-start gap-3 flex-1",children:[n("div",{children:n(Ve,{type:u.entityType||"other",size:"large"})}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(se,{to:`/entity/${u.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#343434"},children:u.name}),n("div",{className:"px-2 py-0.5 rounded",style:{backgroundColor:f?"#e8ffe6":"#fef3cd",color:f?"#00925d":"#a16207",fontSize:"12px",fontWeight:400},children:f?"Up to date":"Out of date"})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},title:u.filePath,children:u.filePath})]})]}),n("button",{onClick:o,className:"px-3 py-1 rounded transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),p.length>0&&l("div",{className:"flex gap-2 overflow-x-auto",style:{marginLeft:"44px"},children:[p.slice(0,8).map(y=>{var w,C,k;if(!y.id)return null;const x=(C=(w=y.metadata)==null?void 0:w.screenshotPaths)==null?void 0:C[0],v=(k=y.metadata)==null?void 0:k.noScreenshotSaved,b=x&&!v;return n(se,{to:`/entity/${u.sha}/scenarios/${y.id}`,className:"border rounded overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"120px",height:"80px",borderColor:b?"#ccc":"#BCCDD3",borderStyle:b?"solid":"dashed"},children:b?n(Ye,{screenshotPath:x,alt:y.name,className:"w-full h-full object-cover bg-gray-100"}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundColor:"#FAFAFA",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})},y.id)}),p.length>8&&l("div",{className:"flex items-center justify-center flex-shrink-0",style:{width:"120px",height:"80px",fontSize:"12px",color:"#646464"},children:["+",p.length-8," more"]})]})]},`${u.sha}-${u.runCreatedAt}`)}),d.length>3&&!i&&l("button",{onClick:()=>c(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",d.length-3," more"," ",d.length-3===1?"entity":"entities"]}),i&&d.length>3&&n("button",{onClick:()=>c(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})}const mf=De(function(){const t=Be(),r=qs(),[a,s]=_(!1);tt({source:"activity-page"});const o=r.tab||"current";return t?l("div",{className:"px-20 py-12",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Activity"}),n("p",{className:"text-[15px] text-gray-500",children:"View queued, current, and historical analysis activity."})]}),n(lf,{activeTab:o,hasCurrentActivity:t.hasCurrentActivity,queuedCount:t.queuedCount,historicCount:t.totalHistoricalRuns}),o==="current"&&n(cf,{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(df,{queueJobs:t.queueJobs,state:t.state,currentRun:t.currentRun}),o==="historic"&&n(uf,{historicalRuns:t.historicalRuns,totalHistoricalRuns:t.totalHistoricalRuns,currentPage:t.currentPage,totalPages:t.totalPages,tab:o,onShowLogs:()=>s(!0)}),a&&t.projectSlug&&n(gt,{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..."})})})}),hf=Object.freeze(Object.defineProperty({__proto__:null,default:mf,loader:of,meta:sf},Symbol.toStringTag,{value:"Module"}));async function ei(e,t,r){var C,k;await Le();const a=await ct({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=fe();if(!s)throw new Error("Project root not found");const o=Z.join(s,".codeyam","config.json"),i=JSON.parse(K.readFileSync(o,"utf8")),{projectSlug:c}=i;if(!c)throw new Error("Project slug not found in config");const d=ur(c);try{K.writeFileSync(d,"","utf8")}catch{}const{project:m}=await Ie(c),u=((C=m.metadata)==null?void 0:C.packageManager)||"npm",h=3112,p=dt(c),f=((k=m.metadata)==null?void 0:k.webapps)||[];if(f.length===0)throw new Error(`No webapps found in project metadata for project ${c}`);const g=i.environmentVariables||[],y=Dc({filePath:a.filePath,webapps:f,environmentVariables:g,port:h,packageManager:u});await Yt(e,N=>{if(N&&(N.readyToBeCaptured=!0,N.scenarios))for(const E of N.scenarios)(!t||E.name===t)&&(delete E.screenshotStartedAt,delete E.screenshotFinishedAt,delete E.interactiveStartedAt,delete E.interactiveFinishedAt,delete E.error,delete E.errorStack)});const{jobId:x}=r.enqueue({type:"debug-setup",commitSha:a.commit.sha,projectSlug:c,analysisId:e,scenarioId:t,prepOnly:!0}),v=y.startCommand,b={title:"Debug Setup In Progress",sections:[{heading:"Status",items:[{content:"Setting up debug environment... This may take a minute."},{label:"Project Path",content:p}]},{heading:"What's Happening",items:[{content:"1. Preparing analyzer and dependencies"},{content:"2. Syncing project files"},{content:"3. Setting up mock environment"}]},{heading:"Next Steps (Once Complete)",items:[{label:"1. Open the project directory",content:`code ${p}`,isCode:!0},{label:"2. Start the development server (copy & paste this exact command)",content:v,isCode:!0},{label:"3. View the scenario in your browser",content:`http://localhost:${h}/static/codeyam-sample`,isLink:!0}]}]};return{success:!0,jobId:x,analysisId:e,scenarioId:t,projectPath:p,projectSlug:c,port:h,packageManager:u,framework:y.framework,instructions:b}}async function pf({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 W({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 ut()),!o)return W({error:"Queue not initialized"},{status:500});console.log("[Debug Setup API] GET request for:",{analysisId:a,scenarioId:s});try{const i=await ei(a,s,o);return W({...i,success:!0,message:"Debug setup queued"})}catch(i){return console.error("[Debug Setup API] GET Error:",i),W({error:"Failed to setup debug environment",details:i.message},{status:500})}}async function ff({request:e,context:t}){if(e.method!=="POST")return W({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await ut()),!r)return W({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("analysisId"),o=a.get("scenarioId");if(!s)return W({error:"Missing required field: analysisId"},{status:400});const i=await ei(s,o,r);return W({...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),W({error:"Failed to setup debug environment",details:s},{status:500})}}const gf=Object.freeze(Object.defineProperty({__proto__:null,action:ff,loader:pf},Symbol.toStringTag,{value:"Module"})),yf=process.env.LABS_UNLOCK_SALT||"codeyam-labs-default-salt";function ti(e){const t=jl("sha256",yf);return t.update(e),`CY-${t.digest("hex").slice(0,16)}`}function xf(e,t){return t===ti(e)}async function bf({request:e}){if(e.method!=="POST")return W({error:"Method not allowed"},{status:405});try{const r=(await e.formData()).get("unlockCode");if(!r)return W({success:!1,error:"Unlock code is required"},{status:400});const a=await $e();return a?xf(a,r)?(await Hn({projectSlug:a,metadataUpdate:{labs:{accessGranted:!0,simulations:!0}}}),W({success:!0})):W({success:!1,error:"Invalid unlock code"},{status:400}):W({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("[Labs Unlock] Error:",t),W({success:!1,error:"Failed to validate unlock code. Please try again."},{status:500})}}const vf=Object.freeze(Object.defineProperty({__proto__:null,action:bf},Symbol.toStringTag,{value:"Module"}));async function wf({request:e,context:t}){if(e.method!=="POST")return W({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await ut()),!r)return W({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("analysisId"),o=a.get("defaultWidth");if(!s||!o)return W({error:"Missing required fields: analysisId and defaultWidth"},{status:400});const i=parseInt(o,10);if(isNaN(i)||i<320||i>3840)return W({error:"Invalid defaultWidth: must be between 320 and 3840"},{status:400});console.log(`[API] Starting recapture for analysis ${s} with width ${i}`);const c=await Mh(s,i,r);return console.log("[API] Recapture queued",c),W({success:!0,message:"Recapture queued",...c})}catch(a){return console.log("[API] Error during recapture:",a),W({error:"Failed to recapture screenshots",details:a instanceof Error?a.message:String(a)},{status:500})}}const Cf=Object.freeze(Object.defineProperty({__proto__:null,action:wf},Symbol.toStringTag,{value:"Module"}));function Nf(e){if(e.length===0)throw new Error("paths array must not be empty");return e.map(Sf).map(s=>s===""?[]:s.split("/")).reduce((s,o)=>{const i=[];for(let c=0;c<Math.min(s.length,o.length)&&s[c]===o[c];c++)i.push(s[c]);return i}).join("/")}function Sf(e){const r=e.replace(/\/+$/,"").split("/");for(;r.length>0;){const a=r[r.length-1];if(kf(a))r.pop();else break}return r.join("/")}function kf(e){return!!(e.includes("*")||/\.\w+$/.test(e))}function Ef({request:e}){const r=new URL(e.url).searchParams.getAll("paths");if(r.length===0)return Response.json({error:"Missing required query parameter: paths"},{status:400});const a=Nf(r),s=a?`.claude/rules/${a}/`:".claude/rules/";return Response.json({result:s})}const Af=Object.freeze(Object.defineProperty({__proto__:null,loader:Ef},Symbol.toStringTag,{value:"Module"}));function _f(e,t){var i,c,d,m,u;const r=((i=e.metadata)==null?void 0:i.isUncommitted)===!0,a=e.analyses&&e.analyses.length>0&&e.analyses.some(h=>h.scenarios&&h.scenarios.length>0);if(!r){const h=!!((c=e.metadata)!=null&&c.previousVersionWithAnalyses),p=a&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha!==e.sha;return h||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(!!((m=e.metadata)!=null&&m.previousVersionWithAnalyses)||s){const h=a&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha===((u=e.metadata)==null?void 0:u.previousVersionWithAnalyses);return a&&!h?{state:"uncommitted_with_new_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up-to-date Simulations",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"●"}}: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 Pf(e){return _f(e).hasOutdatedSimulations}function xr(e,t,r,a,s){var V,U,z,Y,R,A,G,B;const o=(V=t==null?void 0:t.scenarios)==null?void 0:V.find(H=>H.name===e.name),i=!!(o!=null&&o.startedAt),c=!!(o!=null&&o.screenshotStartedAt),d=!!(o!=null&&o.screenshotFinishedAt),m=!!(o!=null&&o.finishedAt),u=1800*1e3,h=c&&!d&&(o==null?void 0:o.screenshotStartedAt)&&Date.now()-new Date(o.screenshotStartedAt).getTime()>u,p=!!((z=(U=e.metadata)==null?void 0:U.screenshotPaths)!=null&&z[0])||!!((Y=e.metadata)!=null&&Y.executionResult),f=c&&!d,g=o==null?void 0:o.error,y=(A=(R=e.metadata)==null?void 0:R.executionResult)==null?void 0:A.error,x=[];if(t!=null&&t.errors&&t.errors.length>0)for(const H of t.errors)x.push({source:`${H.phase} phase`,message:H.message});if(t!=null&&t.steps)for(const H of t.steps)H.error&&x.push({source:H.name,message:H.error});const v=!p&&!g&&!y&&x.length>0,b=!!(g||y||h||v),w=h?"Capture timed out after 30 minutes":(typeof g=="string"?g:null)||(y==null?void 0:y.message)||(v?`Analysis error: ${x[0].message}`:null),C=h?"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,N=(a&&s?s.jobs.some(H=>{var re;return((re=H.entityShas)==null?void 0:re.includes(a))||H.type==="analysis"&&H.entityShas&&H.entityShas.length===0})||((B=(G=s.currentlyExecuting)==null?void 0:G.entityShas)==null?void 0:B.includes(a)):!1)&&!i&&!b||!!(o!=null&&o.analyzing)&&!i&&!b,E=i&&!c&&!m&&!b,S=(N||E||f)&&!b,M=(N||E)&&r===!1&&!p;let F;M?F="crashed":b?F="error":p||m?F="completed":f?F="capturing":E?F="starting":N?F="queued":F="pending";let L="📷",P="pending",T=!1,$=`Not captured: ${e.name}`;const I="border-gray-300",J=b||M?"bg-red-50":"bg-white";return b||M?(L="⚠️",P="error",$=`Error: ${M?"Analysis process crashed":w||"Unknown error"}`):N?(L="⋯",P="queued",$=`Queued: ${e.name}`):E?(L="⋯",P="starting",T=!0,$=`Starting server for ${e.name}...`):f&&!b?(L="⋯",P="capturing",T=!0,$=`Capturing ${e.name}...`):p&&(L="✓",P="completed",$=e.name),{hasError:b||M,errorMessage:M?"Analysis process crashed":w,errorStack:M?"Process terminated unexpectedly before completing analysis":C,isCapturing:f,isCaptured:p,hasCrashed:M,isAnalyzing:S,isQueued:N,isServerStarting:E,status:F,icon:L,iconType:P,shouldSpin:T,title:$,borderColor:I,bgColor:J}}function ni({scenario:e,entitySha:t,size:r="medium",showBorder:a=!0,isOutdated:s=!1}){var C,k,N,E,S,M;const o=xr(e,void 0,void 0,t,void 0),i=(C=e.metadata)==null?void 0:C.executionResult,c=!!i,m=(((N=(k=e.metadata)==null?void 0:k.data)==null?void 0:N.argumentsData)||[]).length,u=(i==null?void 0:i.returnValue)!==void 0&&(i==null?void 0:i.returnValue)!==null,h=((S=(E=i==null?void 0:i.sideEffects)==null?void 0:E.consoleOutput)==null?void 0:S.length)||0,p=((M=i==null?void 0:i.timing)==null?void 0:M.duration)||0;let f=0;m>0&&f++,m>2&&f++,u&&f++,h>0&&f++,f=Math.min(3,f);const g=r==="small"?{width:"w-[50px]",height:"h-[38px]",iconSize:"text-base",textSize:"text-[8px]"}:{width:"w-20",height:"h-15",iconSize:"text-xl",textSize:"text-[10px]"},x=o.hasError?{border:"border-red-400",bg:"bg-red-50",icon:"text-red-600",badge:"bg-red-100 text-red-700"}:c?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"},v=a?`border-2 ${x.border}`:"",b=Array.from({length:3},(F,L)=>n("div",{className:`w-1 h-1 rounded-full ${L<f?x.icon.replace("text-","bg-"):"bg-gray-300"}`},L)),w=o.hasError?`Error: ${o.errorMessage||"Unknown error"}`:c?`${e.name}
216
- ${m} args → ${u?"value":"void"}${h>0?` (${h} logs)`:""}
217
- ${p}ms`:`Not executed: ${e.name}`;return l(se,{to:`/entity/${t}/scenarios/${e.id}`,className:`relative ${g.width} ${g.height} ${v} rounded ${x.bg} flex flex-col items-center justify-center gap-0.5 cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:w,onClick:F=>F.stopPropagation(),children:[n("div",{className:`${x.icon} ${g.iconSize} font-mono font-bold`,children:o.hasError?"⚠":c?"ƒ":"○"}),c&&!o.hasError&&l("div",{className:`flex items-center gap-0.5 ${g.textSize} ${x.badge} px-1 rounded`,children:[n("span",{children:m}),n("span",{children:"→"}),n("span",{children:u?"✓":"∅"})]}),c&&!o.hasError&&r==="medium"&&n("div",{className:"flex gap-0.5 mt-0.5",children:b}),c&&!o.hasError&&p>100&&r==="medium"&&n("div",{className:`absolute top-0.5 right-0.5 ${g.textSize} ${x.badge} px-1 rounded`,children:p>1e3?`${Math.round(p/1e3)}s`:`${p}ms`}),c&&!o.hasError&&h>0&&r==="medium"&&l("div",{className:"absolute bottom-0.5 left-0.5 text-[8px] text-gray-500",children:["📝",h]})]})}function ra({size:e=24,className:t=""}){return l("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":"true",children:[n("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z",fill:"#ef4444",stroke:"none"}),n("line",{x1:"12",y1:"9",x2:"12",y2:"13",stroke:"#FFFFFF",strokeWidth:"2",strokeLinecap:"round"}),n("circle",{cx:"12",cy:"17",r:"1",fill:"#FFFFFF"})]})}function js({scenario:e,entity:t,analysisStatus:r,queueState:a,processIsRunning:s,size:o="medium",cacheBuster:i,className:c="",viewMode:d}){var y,x;if(t.entityType==="library")return n(ni,{scenario:e,entitySha:t.sha,size:o==="small"?"small":"medium"});const u=xr(e,r,s,t.sha,a),h=o==="small"?{containerClass:"w-16 h-12",iconSize:"text-xl"}:o==="large"?{containerClass:"w-full h-[67px]",iconSize:"text-2xl"}:{containerClass:"w-20 h-15",iconSize:"text-2xl"},p=`relative ${h.containerClass} ${c}`,f=()=>{const v=`/entity/${t.sha}/scenarios/${e.id}`;return d?`${v}/${d}`:v};if(u.isCaptured){const v=(x=(y=e.metadata)==null?void 0:y.screenshotPaths)==null?void 0:x[0];return n(se,{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(Ye,{screenshotPath:v,cacheBuster:i,alt:e.name,title:e.name,className:"max-w-full max-h-full object-contain object-center"})})}const g=()=>{const v={size:o==="small"?16:o==="large"?24:20,strokeWidth:2},b=n(Sa,{size:o});if(u.shouldSpin||u.iconType==="queued"||u.iconType==="pending")return b;switch(u.iconType){case"starting":case"capturing":return b;case"error":return l("div",{className:"flex flex-col items-center justify-center gap-1",children:[n(ra,{size:24}),n("span",{className:"text-[10px] text-[#ef4444] font-medium",children:"Capture Error"})]});case"completed":return n(ul,{...v});default:return b}};return n(se,{to:f(),className:`${p} ${u.bgColor} flex flex-col items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:u.title,children:n("div",{className:h.iconSize,children:g()})})}const Dt=70;function Mf({scenarios:e,hiddenScenarios:t=[],analysis:r,selectedScenario:a,entitySha:s,cacheBuster:o,activeTab:i,entityType:c,entity:d,queueState:m,processIsRunning:u,isEntityAnalyzing:h,areScenariosStale:p,viewMode:f,setViewMode:g,isBreakdownView:y}){var T,$,I,J,V,U;const x=Ne(null),[v,b]=_(new Set),[w,C]=_(!1);ee(()=>{x.current&&i==="scenarios"&&x.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[a==null?void 0:a.id,i]);const k=z=>`/entity/${s}/scenarios/${z}`,N=z=>{b(Y=>{const R=new Set(Y);return R.has(z)?R.delete(z):R.add(z),R})},E=(z,Y=2)=>{const A=z.split(`
218
- `).slice(0,Y).join(" ").trim();return A.length>Dt?A.substring(0,Dt-3):(z.split(`
219
- `).length>Y||z.length>A.length,A)},S=ae(()=>{var Y;if(!((Y=r==null?void 0:r.metadata)!=null&&Y.executionFlows)||!(r!=null&&r.scenarios))return null;const z=r.scenarios.filter(R=>{var A;return!((A=R.metadata)!=null&&A.sameAsDefault)});return va(r.metadata.executionFlows,z)},[r]),M=(S==null?void 0:S.totalFlows)||0,F=(S==null?void 0:S.coveredFlows)||0,L=(S==null?void 0:S.coveragePercentage)||0;(T=d==null?void 0:d.metadata)!=null&&T.defaultWidth||($=r==null?void 0:r.metadata)!=null&&$.defaultWidth;const P=(I=r==null?void 0:r.status)!=null&&I.finishedAt?new Date(r.status.finishedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):null;return l("aside",{className:"w-[250px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-4",children:[r&&e.length>0&&l("div",{className:"flex flex-col gap-2",children:[n("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:"SCENARIOS"}),l("div",{className:"grid grid-cols-2 gap-2",children:[l(se,{to:y?`/entity/${s}/scenarios/${(a==null?void 0:a.id)||((J=e[0])==null?void 0:J.id)}`:`/entity/${s}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[l("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[Math.round(L),"%"]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1",children:"COVERAGE"})]}),l(se,{to:y?`/entity/${s}/scenarios/${(a==null?void 0:a.id)||((V=e[0])==null?void 0:V.id)}`:`/entity/${s}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[l("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[F,"/",M]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1 whitespace-nowrap",children:"FLOWS COVERED"})]})]}),l(se,{to:y?`/entity/${s}/scenarios/${(a==null?void 0:a.id)||((U=e[0])==null?void 0:U.id)}`:`/entity/${s}/scenarios/breakdown`,className:`border rounded px-3 py-2 no-underline hover:shadow-sm transition-shadow flex items-center justify-between ${y?"bg-[#CBF3FA] border-[#CBF3FA]":"bg-[#F6F9FC] border-[#E0E9EC]"}`,children:[n("div",{className:"text-[11px] text-[#005c75] font-normal uppercase font-mono underline",children:"EXECUTION FLOWS"}),y?n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M3 3L9 9M9 3L3 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}):n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]}),d&&d.filePath&&n("div",{children:n(se,{to:`/entity/${s}/create-scenario`,className:"w-full px-3 py-2 bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[11px] font-medium font-mono cursor-pointer transition-colors hover:bg-[#004a5e] no-underline flex items-center justify-center gap-1",children:"+ Create New Scenario"})}),e.length>0&&l("div",{className:"py-3 flex items-center justify-between",children:[l("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:[e.length," AUTO-GENERATED"]}),P&&n("div",{className:"text-[10px] text-[#9e9e9e] font-normal font-mono",children:P})]}),h&&(p||e.length===0)?l("div",{className:"",children:[l("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#FFF4FC",color:"#FF2AB5",height:"23px"},children:[l("svg",{width:"9",height:"9",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}),n("p",{className:"text-[#8e8e8e] text-xs font-normal m-0 mt-2 text-left leading-5",children:"Scenarios will appear here once analysis completes"})]}):e.length===0?n("div",{className:"",children:n("p",{className:"text-[#8e8e8e] text-xs font-medium m-0 text-left leading-5",children:"No Scenarios"})}):n("div",{className:"overflow-y-auto flex-1",children:n("div",{className:"flex flex-col gap-[11.6px]",children:e.map((z,Y)=>{const R=!y&&(a==null?void 0:a.id)===z.id,A=v.has(z.id||"");return z.id?l(se,{to:k(z.id),ref:R?x:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${R?"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(js,{scenario:z,entity:{sha:s,entityType:c},analysisStatus:r==null?void 0:r.status,queueState:m,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),l("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${A?"":"line-clamp-1"}`,children:z.name}),z.description&&n("div",{className:"mt-2",children:l("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[A?z.description:E(z.description),!A&&z.description.length>Dt&&l(le,{children:["...",n("button",{onClick:G=>{G.preventDefault(),G.stopPropagation(),N(z.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),A&&z.description.length>Dt&&n("button",{onClick:G=>{G.preventDefault(),G.stopPropagation(),N(z.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},Y):null})})}),t.length>0&&!(h&&p)&&l("div",{className:"border-t border-[#e1e1e1] pt-3",children:[l("button",{onClick:()=>C(!w),className:"flex items-center gap-1 text-[10px] text-[#626262] font-medium cursor-pointer bg-transparent border-none p-0 hover:text-[#005c75] transition-colors w-full",children:[n("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",className:`transition-transform ${w?"rotate-90":""}`,children:n("path",{d:"M3.5 2L6.5 5L3.5 8",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),"Hidden Scenarios (",t.length,")"]}),w&&l("div",{className:"mt-2",children:[n("p",{className:"text-[10px] text-[#8e8e8e] leading-[14px] mb-3",children:"These scenarios were hidden because the screenshots did not differ from the Default Scenario."}),n("div",{className:"flex flex-col gap-[11.6px]",children:t.map((z,Y)=>{const R=!y&&(a==null?void 0:a.id)===z.id,A=v.has(z.id||"");return z.id?l(se,{to:`/entity/${s}/scenarios/${z.id}`,ref:R?x:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${R?"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(js,{scenario:z,entity:{sha:s,entityType:c},analysisStatus:r==null?void 0:r.status,queueState:m,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),l("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${A?"":"line-clamp-1"}`,children:z.name}),z.description&&n("div",{className:"mt-2",children:l("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[A?z.description:E(z.description),!A&&z.description.length>Dt&&l(le,{children:["...",n("button",{onClick:G=>{G.preventDefault(),G.stopPropagation(),N(z.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),A&&z.description.length>Dt&&n("button",{onClick:G=>{G.preventDefault(),G.stopPropagation(),N(z.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},Y):null})})]})]})]})}function Tf({scenario:e,entitySha:t,onApply:r,onSave:a,onEditMockData:s,onDelete:o,isApplying:i=!1,isSaving:c=!1,saveMessage:d=null,showDeleteConfirm:m=!1,onShowDeleteConfirm:u,isDeleting:h=!1,deleteError:p=null}){const[f,g]=_(""),y=async()=>{await r(f)},x=async v=>{await a(f,v),v||g("")};return l("aside",{className:"w-[220px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-3 h-full",children:[l("div",{className:"border-b border-[#e1e1e1] pb-3",children:[l("div",{className:"flex items-start justify-between mb-2",children:[n("div",{className:"text-[10px] text-[#626262] font-medium",children:"Edit Scenario"}),n(se,{to:`/entity/${t}`,className:"text-[#626262] hover:text-[#3e3e3e] transition-colors text-sm leading-none no-underline cursor-pointer",title:"Close",children:"×"})]}),n("div",{className:"text-xs font-semibold text-[#626262]",children:e.name})]}),l("div",{className:"flex-1 overflow-y-auto flex flex-col gap-2",children:[l("div",{className:"pt-1",children:[n("label",{htmlFor:"ai-description",className:"block text-xs text-[#343434] font-semibold mb-[6px]",children:"Describe changes to the AI"}),n("textarea",{id:"ai-description",value:f,onChange:v=>g(v.target.value),placeholder:"e.g. change amount of data to zero",className:"w-full px-[7px] py-[6px] border border-[#c7c7c7] rounded-[4px] text-xs focus:outline-none focus:ring-1 focus:ring-[#005c75] focus:border-[#005c75] resize-none",rows:4}),l("button",{onClick:()=>void 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&&l("svg",{className:"animate-spin h-3 w-3",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),i?"Applying...":"Apply"]})]}),n("div",{className:"border-t border-[#e1e1e1] my-1"}),l("div",{className:"pt-1",children:[n("div",{className:"text-xs text-[#343434] font-semibold mb-[6px]",children:"Change file"}),n("p",{className:"text-[10px] text-[#808080] mb-2",children:"You can edit the data used for this scenario directly."}),n("button",{onClick: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(se,{to:`/entity/${t}`,className:"text-[#005c75] hover:text-[#004a5e] hover:underline text-[10px] cursor-pointer",children:"View updated screenshot on entity page →"})})]}),l("div",{className:"border-t border-[#e1e1e1] pt-2 bg-white flex flex-col gap-1",children:[n("button",{onClick:()=>void x(!1),disabled:c||!f.trim(),className:"w-full h-[22px] bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center",children:c?"Saving...":"Save Scenario Data"}),n("button",{onClick:()=>void x(!0),disabled:c||!f.trim(),className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa] disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center",children:"Save As New"}),o&&l(le,{children:[m?l("div",{className:"flex flex-col gap-1",children:[l("div",{className:"text-[10px] text-red-600 font-medium",children:['Are you sure you want to delete "',e.name,'"?']}),l("div",{className:"flex gap-1",children:[n("button",{onClick:()=>void o(),disabled:h,className:"flex-1 h-[22px] bg-red-600 text-white rounded text-[10px] font-normal hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors flex items-center justify-center cursor-pointer",children:h?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>u==null?void 0:u(!1),disabled:h,className:"flex-1 h-[22px] bg-gray-100 text-gray-700 border border-gray-300 rounded text-[10px] font-normal hover:bg-gray-200 disabled:opacity-50 transition-colors flex items-center justify-center cursor-pointer",children:"Cancel"})]})]}):n("button",{onClick:()=>u==null?void 0:u(!0),className:"w-full h-[22px] bg-red-50 text-red-600 border border-red-200 rounded text-[10px] font-normal hover:bg-red-100 transition-colors flex items-center justify-center cursor-pointer",children:"Delete Scenario"}),p&&n("div",{className:"text-[10px] text-red-600 bg-red-50 px-[7px] py-[6px] rounded-[4px]",children:p})]})]})]})}function jf({scenario:e,analysis:t,entity:r}){var i,c,d;const a=((i=e.metadata)==null?void 0:i.executionResult)||null,s=((d=(c=e.metadata)==null?void 0:c.data)==null?void 0:d.argumentsData)||[],o=m=>{var g,y,x;if(!m)return"No execution results available yet. Run the function to capture side effects including console output, file operations, and API calls.";const u=[],h=((g=m.sideEffects)==null?void 0:g.consoleOutput)||[];h.length>0&&(u.push(`Console Output: ${h.length} log ${h.length===1?"entry":"entries"} captured`),h.forEach(v=>{u.push(` [${v.level.toUpperCase()}] ${v.args.join(" ")}`)}));const p=((y=m.sideEffects)==null?void 0:y.fileWrites)||[];p.length>0&&(u.push(`
220
- File System Operations: ${p.length} ${p.length===1?"operation":"operations"} detected`),p.forEach(v=>{u.push(` ${v.operation}: ${v.path}${v.size?` (${v.size} bytes)`:""}`)}));const f=((x=m.sideEffects)==null?void 0:x.apiCalls)||[];return f.length>0&&(u.push(`
221
- API Calls: ${f.length} ${f.length===1?"call":"calls"} made`),f.forEach(v=>{u.push(` ${v.method} ${v.url}${v.status?` → ${v.status}`:""}${v.duration?` (${v.duration}ms)`:""}`)})),m.error&&u.push(`
222
- Error: ${m.error.name||"Error"}: ${m.error.message}`),u.length===0?"No side effects detected. The function executed without console output, file operations, or API calls.":u.join(`
223
- `)};return l("div",{className:"flex w-full h-full gap-0",children:[l("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Input Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:JSON.stringify(s,null,2)})})]}),l("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Returned Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children: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"})})]}),l("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Side Effects"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-4",children:n("p",{className:"text-sm text-gray-700 leading-[22px] m-0 whitespace-pre-wrap",children:o(a)})})]})]})}const Et={commandBoxBg:"#f6f9fc",commandBoxBorder:"#e1e1e1",commandBoxText:"#005c75",heading:"#000",subtext:"#646464",link:"#005c75"};function Pn({scenarioId:e,analysisId:t}){const[r,a]=_(!1),[s,o]=_(!1),[i,c]=_(null),[d,m]=_(!1),u=e||t;if(!u)return null;const h=`/codeyam-diagnose ${u}`,p=async()=>{o(!0);try{const{default:g}=await import("html2canvas-pro"),x=(await g(document.body,{scale:.5})).toDataURL("image/jpeg",.8);c(x),a(!0)}catch(g){console.error("Screenshot capture failed:",g),a(!0)}finally{o(!1)}},f=()=>{a(!1),c(null)};return l(le,{children:[l("div",{className:"text-center p-6 bg-cywhite-100 rounded-lg border-cygray-30 border",children:[n("h3",{className:"font-semibold font-['IBM_Plex_Sans']",style:{fontSize:"18px",lineHeight:"26px",color:Et.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:Et.subtext},children:"Simply run this command in Claude Code:"}),l("div",{className:"flex items-center justify-between rounded mx-auto mb-3 border",style:{backgroundColor:Et.commandBoxBg,borderColor:Et.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:Et.commandBoxText},children:h}),n("button",{onClick:g=>{g.stopPropagation(),navigator.clipboard.writeText(h),m(!0),setTimeout(()=>m(!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":Et.commandBoxText},title:d?"Copied!":"Copy command","aria-label":"Copy command to clipboard",children:d?n(et,{size:14}):n(st,{size:14})})]}),l("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:"#005c75"},children:["If Claude is unable to address this issue or suggests reporting it,"," ",n("button",{onClick:()=>void p(),disabled: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:Et.link},children:s?"capturing...":"please do so here"}),"."]})]}),n(oo,{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 Is=1440,Mn=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],at={background:"#ffdcd9",border:"#fda4a4",text:"#ef4444",link:"#991b1b"};function ri({selectedScenario:e,analysis:t,entity:r,viewMode:a,cacheBuster:s,hasScenarios:o,isAnalyzing:i=!1,projectSlug:c,hasAnApiKey:d=!0,processIsRunning:m,queueState:u}){var q,te,de,ge,pe,be,Ce,ke,Se,_e,Te;const h=Ee(),[p,f]=_(!1),[g,y]=_(!1),[x,v]=_({name:"Desktop",width:Is,height:900}),[b,w]=_(Is),[C,k]=_(1),{customSizes:N,addCustomSize:E,removeCustomSize:S}=Yo(c),M=ae(()=>[...Mn,...N],[N]),F=(ve,Q)=>{w(ve);const me=M.find(ye=>ye.width===ve&&ye.height===Q);v({name:(me==null?void 0:me.name)||"Custom",width:ve,height:Q})},L=ve=>{w(ve.width),v({name:ve.name,width:ve.width,height:ve.height})},P=ve=>{E(ve,x.width,x.height??900),y(!1),v(Q=>({...Q,name:ve}))},T=(ve,Q)=>{w(ve);const me=M.find(ye=>ye.width===ve&&ye.height===Q);v(ye=>({name:(me==null?void 0:me.name)||"Custom",width:ve,height:ye.height}))},$=(te=(q=e==null?void 0:e.metadata)==null?void 0:q.screenshotPaths)==null?void 0:te[0],I=ae(()=>e?xr(e,t==null?void 0:t.status,m,r==null?void 0:r.sha,u):null,[e,t==null?void 0:t.status,m,r==null?void 0:r.sha,u]),J=ae(()=>{var Q,me;const ve=[];if((Q=t==null?void 0:t.status)!=null&&Q.errors&&t.status.errors.length>0)for(const ye of t.status.errors)ve.push({source:`${ye.phase} phase`,message:ye.message,stack:ye.stack});if((me=t==null?void 0:t.status)!=null&&me.steps)for(const ye of t.status.steps)ye.error&&ve.push({source:ye.name,message:ye.error,stack:ye.errorStack});return ve},[(de=t==null?void 0:t.status)==null?void 0:de.errors,(ge=t==null?void 0:t.status)==null?void 0:ge.steps]),V=(I==null?void 0:I.errorMessage)||null,U=(I==null?void 0:I.errorStack)||null,{interactiveServerUrl:z,isStarting:Y,isLoading:R,showIframe:A,iframeKey:G,onIframeLoad:B}=gn({analysisId:t==null?void 0:t.id,scenarioId:e==null?void 0:e.id,scenarioName:e==null?void 0:e.name,projectSlug:c,enabled:a==="interactive"}),H=ae(()=>z||null,[z]),re=!i&&o&&e&&!((be=(pe=e.metadata)==null?void 0:pe.screenshotPaths)!=null&&be[0])&&((ke=(Ce=t==null?void 0:t.status)==null?void 0:Ce.scenarios)==null?void 0:ke.some(ve=>ve.name===e.name&&ve.screenshotStartedAt&&!ve.screenshotFinishedAt)),{lastLine:O}=bt(c,i||a==="interactive"||re||!1);if(!e){if(i&&r)return l(le,{children:[n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center bg-[#f6f9fc]",children:l("div",{className:"flex flex-col items-center gap-6 max-w-2xl",children:[n("div",{className:"w-12 h-12 mb-2",children:n("svg",{className:"animate-spin",viewBox:"0 0 50 50",children:n("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"#005c75",strokeWidth:"4",strokeDasharray:"31.4 31.4",strokeLinecap:"round"})})}),n("h2",{className:"text-2xl font-semibold text-[#005c75] leading-[30px] m-0 font-['IBM_Plex_Sans']",children:re?"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."}),O&&n("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl",children:O}),c&&n("button",{onClick:()=>f(!0),className:"w-[148px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-sm text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c] font-['IBM_Plex_Sans']",children:"View full logs"})]})}),p&&c&&n(gt,{projectSlug:c,onClose:()=>f(!1)})]});if(!o&&r&&!i){if(J.length>0){const ve=J.length===1?((Se=J[0])==null?void 0:Se.message)||"An error occurred during analysis.":`${J.length} errors occurred during analysis.`;return l(le,{children:[n("div",{className:"flex-1 flex flex-col justify-center items-center px-5",style:{minHeight:"75vh"},children:l("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded",style:{backgroundColor:at.background,border:`2px solid ${at.border}`},role:"alert",children:l("div",{className:"flex items-center gap-3",children:[n(ra,{size:24,className:"shrink-0"}),n("div",{className:"flex-1 min-w-0",children:l("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:at.text},children:[n("span",{className:"font-semibold",children:"Analysis Error."})," ",ve," ",n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:at.link},children:"See logs"})," ","for details."]})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(Pn,{analysisId:t==null?void 0:t.id})})]})}),p&&c&&n(gt,{projectSlug:c,onClose:()=>f(!1)})]})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-[#f6f9fc]",children:l("div",{className:"max-w-[600px]",children:[n("h2",{className:"text-[28px] font-semibold text-[#343434] mb-4 m-0 leading-10",children:"No simulations yet"}),n("p",{className:"text-base font-normal text-[#3e3e3e] mb-8 leading-6 m-0",children:"Analyze the code to create simulations and create test scenarios automatically."}),r.filePath&&n("button",{onClick:()=>{h.submit({entitySha:r.sha,filePath:r.filePath},{method:"post",action:"/api/analyze"})},disabled:h.state!=="idle",className:"h-[54px] w-[183px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-lg text-base font-medium cursor-pointer transition-all hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed",children:h.state!=="idle"?"Analyzing...":"Analyze"})]})})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center",children:n("p",{className:"text-base text-gray-500 m-0",children:"Select a scenario to view its screenshot"})})}return l(le,{children:[n("main",{className:"flex-1 overflow-auto flex flex-col min-w-0",style:{backgroundImage:`
224
- linear-gradient(45deg, #ebebeb 25%, transparent 25%),
225
- linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
226
- linear-gradient(45deg, transparent 75%, #ebebeb 75%),
227
- linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
228
- `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:(i||re&&!$)&&!V&&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:l("div",{className:"max-w-2xl w-full bg-white rounded-t-2xl shadow-xl p-8",children:[l("div",{className:"mb-8",children:[n("div",{className:"inline-flex items-center justify-center w-24 h-24 bg-blue-100 rounded-full mb-6",children:n("span",{className:"text-5xl animate-spin",children:"⚙️"})}),n("h2",{className:"text-3xl font-bold text-gray-900 mb-4 m-0",children:re?`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:re?`Taking screenshots for ${((_e=t==null?void 0:t.scenarios)==null?void 0:_e.length)||0} scenario${((Te=t==null?void 0:t.scenarios)==null?void 0:Te.length)!==1?"s":""}...`:`Generating simulations and scenarios for this ${r==null?void 0:r.entityType} entity...`}),e&&l("p",{className:"text-sm text-blue-600 font-semibold m-0",children:["Currently processing: ",e.name]})]}),O&&n("div",{className:"bg-[#f6f9fc] border-2 border-[#e1e1e1] rounded-lg p-6 mb-6",children:l("div",{className:"flex items-start gap-3",children:[n("span",{className:"text-xl shrink-0",children:"📝"}),l("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2 m-0",children:"Current Progress"}),n("p",{className:"text-sm text-gray-900 font-mono wrap-break-word m-0",title:O,children:O})]})]})}),c&&n("button",{onClick:()=>f(!0),className:"px-6 py-3 bg-[#005c75] text-white border-none rounded-lg text-base font-semibold cursor-pointer transition-all hover:bg-[#004a5e] hover:shadow-lg",children:"📋 View Full Logs"}),n("p",{className:"text-xs text-gray-500 mt-8 m-0",children:"Screenshots will appear here as they are captured. This may take a few minutes."})]})}):a==="screenshot"&&($||V)||a==="interactive"&&(H||Y)||a==="data"?l(le,{children:[V&&!$&&n("div",{className:"flex-1 flex flex-col justify-center items-center p-6",children:l("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded overflow-auto",style:{backgroundColor:at.background,border:`2px solid ${at.border}`,maxHeight:"50vh"},role:"alert",children:l("div",{className:"flex flex-col gap-3",children:[l("div",{className:"flex items-center justify-center gap-2 font-bold",style:{color:at.text},children:[n(ra,{size:24,className:"shrink-0"}),n("div",{children:"Capture Error"})]}),l("div",{className:"text-center",children:[n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:at.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:at.text},children:V})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(Pn,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})}),a==="interactive"?l("div",{className:"flex-1 flex flex-col min-h-0",children:[H&&l("div",{className:"bg-gray-50 border-b border-gray-200 px-6 py-3 shrink-0 flex justify-center items-center gap-4",children:[n($u,{presets:[...Mn],customSizes:N,currentWidth:x.width,currentHeight:x.height??900,scale:C,onSizeChange:F,onSaveCustomSize:()=>y(!0),onRemoveCustomSize:S}),e&&r&&l(se,{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-[#005c75] border-b border-[rgba(0,0,0,0.2)] flex justify-center",children:n("div",{style:{maxWidth:`${Mn[Mn.length-1].width}px`,width:"100%"},children:n(Oo,{currentViewportWidth:b,currentPresetName:x.name,onDevicePresetClick:L,devicePresets:M})})}),n(gr,{scenarioId:e.id,scenarioName:e.name,iframeUrl:H,isStarting:Y,isLoading:R,showIframe:A,iframeKey:G,onIframeLoad:B,onScaleChange:k,onDimensionChange:T,projectSlug:c,defaultWidth:x.width,defaultHeight:x.height})]}):a==="data"?n("div",{className:"flex-1 min-h-0",children:n(jf,{scenario:e,analysis:t,entity:r})}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 p-6 flex items-center justify-center",children:n("div",{className:"transition-all duration-300",style:{maxWidth:`${b}px`},children:($||!V)&&n(Ye,{screenshotPath:$,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&&!$?n("div",{className:"w-full h-full flex items-center justify-center",children:n("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-8",children:l("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"animate-spin text-4xl shrink-0",children:"⚙️"}),l("div",{className:"flex-1",children:[n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Capturing Screenshot"}),l("p",{className:"text-sm text-blue-800 m-0 mb-4",children:["Analysis is in progress for"," ",n("strong",{children:e.name}),". The screenshot will appear here once capture is complete."]}),O&&l("div",{className:"bg-white border border-blue-200 rounded p-4 mt-4",children:[n("h4",{className:"text-xs font-semibold text-blue-800 m-0 mb-2 uppercase tracking-wide",children:"Current Progress"}),n("p",{className:"text-sm text-blue-900 m-0 font-mono wrap-break-word",children:O})]}),c&&n("button",{onClick:()=>f(!0),className:"mt-4 px-4 py-2 bg-[#005c75] text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-[#004a5e]",children:"📋 View Full Logs"})]})]})})}):V?l("div",{className:"w-full h-full flex flex-col items-center justify-center overflow-auto gap-6",children:[!d&&n("div",{className:"bg-blue-50 border-2 border-blue-300 rounded-lg p-8",children:l("div",{className:"flex-1 flex flex-col gap-4 items-center justify-center",children:[l("div",{className:"flex items-start gap-4",children:[n("span",{className:"text-blue-600 text-2xl shrink-0",children:"🔑"}),n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Improve Analysis Quality with an API Key"})]}),l("div",{className:"bg-white border border-blue-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-blue-900 m-0 mb-2 uppercase tracking-wide",children:"CodeYam requires an AI API key for reliable analysis."}),l("ul",{className:"text-sm text-blue-800 m-0 space-y-1 pl-5 list-disc",children:[n("li",{children:"You can use API keys for a variety of models"}),n("li",{children:"Faster analysis processing"}),n("li",{children:"Better handling of complex code structures"}),n("li",{children:"Improved scenario generation quality"})]})]}),n(se,{to:"/settings",className:"inline-block px-4 py-2 bg-blue-600 text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-blue-700",children:"🔐 Configure API Keys"})]})}),n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:l("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),l("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xl font-semibold text-red-800 m-0 mb-3",children:"Capture Failed"}),n("p",{className:"text-sm text-red-700 m-0 mb-4",children:"An error occurred while capturing this scenario. No screenshot is available."}),l("div",{className:"bg-white border border-red-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-red-800 m-0 mb-2 uppercase tracking-wide",children:"Error Message"}),n("div",{className:"max-h-[300px] overflow-auto",children:n("p",{className:"text-sm text-red-900 m-0 font-mono whitespace-pre-wrap wrap-break-word",children:V})})]}),U&&l("details",{className:"mt-4",children:[n("summary",{className:"text-sm text-red-700 cursor-pointer hover:text-red-900 font-semibold",children:"📋 View full stack trace"}),n("div",{className:"mt-3 bg-white border border-red-200 rounded p-4 overflow-auto",children:n("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:U})})]}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(Pn,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})]}):J.length>0?n("div",{className:"w-full h-full flex items-center justify-center overflow-auto",children:n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:l("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),l("div",{className:"flex-1 min-w-0",children:[n(AnalysisErrorDisplay,{errors:J,title:"Analysis Error",description:J.length===1?"An error occurred during analysis. Screenshot capture was not completed.":`${J.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(Pn,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})}):l("div",{className:"flex flex-col items-center gap-4 text-center",children:[n("span",{className:"text-6xl text-gray-300",children:"📷"}),n("p",{className:"text-lg text-gray-500 m-0",children:"No screenshot available for this scenario"}),n("p",{className:"text-sm text-gray-400 m-0",children:"Try recapturing or debugging this scenario"})]})})})}),p&&c&&n(gt,{projectSlug:c,onClose:()=>f(!1)}),g&&n(zo,{width:x.width,height:x.height??900,onSave:P,onCancel:()=>y(!1)})]})}function If({analysis:e,entitySha:t}){it();const[r,a]=_(e);ee(()=>{a(e)},[e]);const[s,o]=_(null),i=ae(()=>{var h;if(!((h=r==null?void 0:r.metadata)!=null&&h.executionFlows)||!(r!=null&&r.scenarios))return null;const u=r.scenarios.filter(p=>{var f;return!((f=p.metadata)!=null&&f.sameAsDefault)});return va(r.metadata.executionFlows,u)},[r]),c=ae(()=>i?Zu(i):[],[i]),d=ae(()=>r!=null&&r.scenarios?r.scenarios.filter(u=>{var h;return!((h=u.metadata)!=null&&h.sameAsDefault)}):[],[r]),m=u=>{var p;const h=((p=u.metadata)==null?void 0:p.coveredFlows)||[];return i?i.executionFlows.filter(f=>h.includes(f.id)):[]};return r?!i||i.executionFlows.length===0?n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:l("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Execution Flows"}),n("p",{className:"text-sm",children:"Re-analyze this entity to generate execution flows."})]})}):n("div",{className:"flex-1 overflow-auto bg-[#fafafa]",children:l("div",{className:"p-6 space-y-6",children:[l("div",{className:"bg-white border border-gray-200 rounded-lg p-4",children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0 mb-3",children:"Scenarios Breakdown"}),l("div",{className:"grid grid-cols-4 gap-4 text-center",children:[l("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:d.length}),n("div",{className:"text-xs text-gray-500",children:"Scenarios"})]}),l("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:i.executionFlows.length}),n("div",{className:"text-xs text-gray-500",children:"Execution Flows"})]}),l("div",{className:"bg-gray-50 rounded-lg p-3",children:[l("div",{className:"text-2xl font-bold text-gray-900",children:[i.coveredFlows,"/",i.totalFlows]}),n("div",{className:"text-xs text-gray-500",children:"Flows Covered"})]}),l("div",{className:"bg-gray-50 rounded-lg p-3",children:[l("div",{className:`text-2xl font-bold ${i.coveragePercentage===100?"text-green-600":i.coveragePercentage>=50?"text-amber-600":"text-red-600"}`,children:[i.coveragePercentage.toFixed(0),"%"]}),n("div",{className:"text-xs text-gray-500",children:"Coverage"})]})]})]}),l("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:l("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Scenarios (",d.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:d.length===0?l("div",{className:"p-4 text-center text-gray-500 text-sm",children:["No scenarios yet."," ",n(se,{to:`/entity/${t}/create-scenario`,className:"text-blue-600 hover:underline",children:"Create one"})]}):d.map(u=>{var f,g,y;const h=(g=(f=u.metadata)==null?void 0:f.screenshotPaths)==null?void 0:g[0],p=m(u);return l("div",{className:"p-4 flex gap-4",children:[n("div",{className:"w-72 h-40 shrink-0 bg-gray-100 rounded overflow-hidden flex items-start justify-center",children:n(Ye,{screenshotPath:h,alt:u.name||"Scenario screenshot",className:"max-w-full max-h-full object-contain object-top"})}),l("div",{className:"flex-1 min-w-0",children:[n("div",{className:"flex items-start justify-between gap-2",children:l("div",{children:[n(se,{to:`/entity/${t}/scenarios/${u.id}`,className:"font-medium text-gray-900 hover:text-blue-600 no-underline text-sm",children:u.name}),((y=u.metadata)==null?void 0:y.error)&&n("span",{className:"ml-2 text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"Error"})]})}),n("p",{className:"text-xs text-gray-500 mt-1 line-clamp-2",children:u.description}),p.length>0&&n("div",{className:"flex flex-wrap gap-1 mt-2",children:p.map(x=>n("span",{className:`text-xs px-1.5 py-0.5 rounded ${x.isError?"bg-red-50 text-red-700":x.blocksOtherFlows?"bg-purple-50 text-purple-700":"bg-blue-50 text-blue-700"}`,children:x.name},x.id))})]})]},u.id)})}),n("div",{className:"px-4 py-3 border-t border-gray-100 bg-gray-50",children:l(se,{to:`/entity/${t}/create-scenario`,className:"w-full px-4 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 flex items-center justify-center gap-2 no-underline",children:[n("span",{className:"text-lg leading-none",children:"+"}),"Add Scenario"]})})]}),c.length>0&&l("div",{className:"p-3 bg-amber-50 border border-amber-200 rounded-lg",children:[l("p",{className:"text-sm text-amber-800 font-medium mb-2",children:[c.length," uncovered execution flow",c.length>1?"s":""," — consider adding scenarios to cover these"]}),l("div",{className:"flex flex-wrap gap-1",children:[c.slice(0,10).map(u=>l("span",{className:`text-xs px-2 py-0.5 rounded ${u.impact==="high"?"bg-red-100 text-red-700":"bg-amber-100 text-amber-700"}`,children:[u.name,u.impact==="high"&&" (high impact)"]},u.id)),c.length>10&&l("span",{className:"text-xs text-amber-600",children:["+",c.length-10," more"]})]})]}),l("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:l("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Execution Flows (",i.executionFlows.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:i.executionFlows.map(u=>{const h=s===u.id,p=u.usedInScenarios.length>0;return l("div",{children:[n("button",{onClick:()=>o(h?null:u.id),className:"w-full px-4 py-3 flex items-start justify-between text-left bg-transparent border-none cursor-pointer hover:bg-gray-50",children:l("div",{className:"flex items-start gap-3 flex-1",children:[n("span",{className:"text-gray-400 text-sm mt-0.5 shrink-0",children:h?"▼":"▶"}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-medium text-sm text-gray-900",children:u.name}),p?n("span",{className:"text-xs px-2 py-0.5 rounded bg-green-100 text-green-700",children:"Covered"}):n("span",{className:"text-xs px-2 py-0.5 rounded bg-amber-100 text-amber-700",children:"Uncovered"}),u.blocksOtherFlows&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-purple-100 text-purple-700",children:"Blocking"}),u.impact==="high"&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"High Impact"}),u.isError&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"Error"})]}),u.description&&n("p",{className:"text-sm text-gray-600 mt-1 m-0",children:u.description})]})]})}),h&&l("div",{className:"border-t border-gray-100 px-4 py-3 bg-gray-50/50",children:[u.requiredValues.length>0&&l("div",{className:"mb-4",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Required Values"}),n("div",{className:"space-y-1",children:u.requiredValues.map((f,g)=>l("div",{className:"flex items-center gap-2 text-xs",children:[n("code",{className:"font-mono text-gray-800 bg-gray-100 px-1 py-0.5 rounded",children:f.attributePath}),n("span",{className:"text-gray-400",children:f.comparison}),n("code",{className:"font-mono text-blue-700 bg-blue-50 px-1 py-0.5 rounded",children:f.value})]},g))})]}),p&&l("div",{children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Covered by Scenarios"}),n("div",{className:"flex flex-wrap gap-1",children:u.usedInScenarios.map(f=>n("span",{className:"text-xs px-1.5 py-0.5 bg-green-50 text-green-700 rounded",children:f.name},f.id))})]}),u.codeSnippet&&l("div",{className:"mt-4 pt-3 border-t border-gray-200",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Code Location"}),n("pre",{className:"text-xs bg-gray-900 text-gray-100 p-2 rounded overflow-x-auto font-mono whitespace-pre-wrap",children:n("code",{children:u.codeSnippet})})]})]})]},u.id)})})]})]})}):n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:l("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Analysis Found"}),n("p",{className:"text-sm",children:"Analyze this entity to see the scenarios breakdown."})]})})}function $s({hasIndirectBadge:e,onAnalyze:t}){return l(le,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:l("div",{className:"flex items-center justify-end gap-2",children:[e&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:"0 scenarios"})]})}),l("div",{className:"px-5 py-5 bg-white rounded-bl-lg rounded-br-lg flex items-center justify-between",children:[n("p",{className:"text-sm font-normal text-[#8e8e8e] m-0 leading-[22px]",children:"No analyses available for this version."}),n("button",{className:"px-[15px] py-0 h-[23px] bg-[#005c75] text-white rounded text-xs font-medium leading-5 border-none cursor-pointer hover:bg-[#004a5e] transition-colors flex items-center justify-center",onClick:t,children:"Analyze"})]})]})}function $f({entity:e,history:t}){const[r,a]=_("entity"),[s,o]=_(new Set),i=t.filter(u=>u.analyses.length>0).length,c=ae(()=>{const u=new Map;return t.forEach(h=>{h.analyses.forEach(p=>{(p.scenarios??[]).filter(g=>{var y;return!((y=g.metadata)!=null&&y.sameAsDefault)}).forEach(g=>{u.has(g.name)||u.set(g.name,[]),u.get(g.name).push({version:h,analysis:p,scenario:g})})})}),Array.from(u.entries()).map(([h,p])=>{var f;return{name:h,description:((f=p[0])==null?void 0:f.scenario.description)||"",versions:p.sort((g,y)=>{const x=new Date(g.analysis.createdAt||0).getTime();return new Date(y.analysis.createdAt||0).getTime()-x})}})},[t]),d=c.length,m=u=>{o(h=>{const p=new Set(h);return p.has(u)?p.delete(u):p.add(u),p})};return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto",children:l("div",{className:"max-w-[1400px] mx-auto px-8 py-8",children:[n("div",{className:"mb-8",children:l("div",{className:"flex items-center gap-6 border-b-2 border-[#e1e1e1]",children:[l("button",{onClick:()=>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})]}),l("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"?l("div",{className:"relative pl-12",children:[t.length>1&&n("div",{className:"absolute left-[17.5px] top-10 bottom-10 w-px bg-[#c7c7c7]"}),t.map((u,h)=>l("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[19px] w-[11.5px] h-[11.5px] rounded-full bg-[#00925d]"}),l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-3 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center gap-3",children:[u.sha===(e==null?void 0:e.sha)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),l(se,{to:`/entity/${u.sha}/scenarios`,className:"text-xs font-mono text-[#646464] leading-5 hover:text-[#005c75] transition-colors",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:u.sha.substring(0,8)})]})]}),n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-[22px]",children:u.createdAt&&new Date(u.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})})]})}),u.analyses.length>0?n("div",{children:u.analyses.map((p,f)=>{var y;const g=(p.scenarios??[]).filter(x=>{var v;return!((v=x.metadata)!=null&&v.sameAsDefault)});return n("div",{children:g.length===0?n($s,{hasIndirectBadge:p.indirect,onAnalyze:()=>{console.log("Analyze version:",u.sha)}}):l(le,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:l("div",{className:"flex items-center justify-end gap-2",children:[p.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),l("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:[g.length," scenario",g.length!==1?"s":""]})]})}),((y=p.metadata)==null?void 0:y.scenarioChangesOverview)&&n("div",{className:"p-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:l("p",{className:"text-sm text-[#005c75] m-0 leading-[22px]",children:[l("span",{className:"font-medium",children:["What Changed:"," "]}),p.metadata.scenarioChangesOverview]})}),g.length>0&&n("div",{className:"p-5 bg-white",children:n("div",{className:"flex gap-4 flex-wrap",children:g.map((x,v)=>{var C,k;const b=(k=(C=x.metadata)==null?void 0:C.screenshotPaths)==null?void 0:k[0],w=`${x.name}-${v}`;return l(se,{to:`/entity/${u.sha}/scenarios/${x.id}`,className:"w-[187px] border border-[#e1e1e1] rounded bg-white overflow-hidden hover:border-[#005c75] hover:shadow-sm transition-all",children:[n("div",{className:"h-[110px] border-b border-[#e1e1e1] bg-gray-50 flex items-center justify-center p-[5.6px]",children:b?n(Ye,{screenshotPath:b,alt:x.name,className:"max-w-full max-h-full object-contain rounded-sm"}):l("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No Screenshot"})]})}),n("div",{className:"p-[5.6px]",children:n("p",{className:"text-[10.2px] font-medium text-[#343434] m-0 leading-[13px] line-clamp-3",children:x.name})})]},w)})})})]})},p.id||f)})}):n($s,{onAnalyze:()=>{console.log("Analyze version:",u.sha)}})]})]},u.sha))]}):n("div",{className:"relative pl-12",children:c.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No scenarios found"})}):c.map((u,h)=>{const p=s.has(u.name),f=p?u.versions:u.versions.slice(0,1),g=u.versions.length-1,y=u.versions[0];return y==null||y.version.sha,e==null||e.sha,l("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[42px] w-[13.26px] h-[13.26px] rounded-full bg-[#00925d]"}),l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[l("div",{className:"px-5 py-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:[n("h3",{className:"text-base font-semibold text-[#232323] m-0 mb-1 leading-6",children:u.name}),u.description&&n("p",{className:"text-sm font-normal text-[#626262] m-0 leading-[22px]",children:u.description})]}),l("div",{className:"p-5 bg-white",children:[f.map((x,v)=>{var E,S;const{version:b,analysis:w,scenario:C}=x,k=(S=(E=C.metadata)==null?void 0:E.screenshotPaths)==null?void 0:S[0],N=v===0;return l("div",{className:`flex gap-5 items-start ${N?"":"mt-5 pt-5 border-t border-[#e1e1e1]"}`,children:[n(se,{to:`/entity/${b.sha}/scenarios/${C.id}`,className:"w-[175px] h-[110px] border border-[#e1e1e1] rounded bg-gray-50 flex items-center justify-center shrink-0 hover:border-[#005c75] hover:shadow-sm transition-all",children:k?n(Ye,{screenshotPath:k,alt:C.name,className:"max-w-full max-h-full object-contain rounded-sm"}):l("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No screenshot"})]})}),l("div",{className:"flex-1 flex flex-col gap-2",children:[l("div",{className:"flex items-center gap-2 flex-wrap",children:[b.sha===(e==null?void 0:e.sha)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),N&&u.versions.length>1&&l("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#e0e9ec] text-[#005c75] rounded text-xs font-medium leading-5",children:[u.versions.length," versions"]})]}),l(se,{to:`/entity/${b.sha}/scenarios`,className:"text-xs font-mono text-[#646464] m-0 leading-5 hover:text-[#005c75] transition-colors w-fit",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:b.sha.substring(0,8)})]}),w.createdAt&&l("p",{className:"text-xs font-medium text-[#8e8e8e] m-0 leading-[22px]",children:["Captured:"," ",new Date(w.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})]}),w.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5 self-start",children:"Indirect"})]})]},`${b.sha}-${v}`)}),g>0&&l("button",{onClick:()=>m(u.name),className:"mt-5 flex items-center gap-2 text-sm text-[#005c75] bg-transparent border-none cursor-pointer p-0 hover:underline",children:[n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",className:`transition-transform ${p?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),p?"Hide":`${g} previous version${g!==1?"s":""}`]})]})]})]},u.name)})})]})})}function Rs({entity:e,analysisInfo:t,from:r}){const a=Ee(),s=a.state!=="idle",o=e.entityType==="visual"||e.entityType==="library",i=c=>{c.preventDefault(),c.stopPropagation(),o&&a.submit({entitySha:e.sha,filePath:e.filePath},{method:"post",action:"/api/analyze"})};return n(se,{to:`/entity/${e.sha}${r?`?from=${r}`:""}`,className:"block group cursor-pointer",children:l("div",{className:"flex gap-0 border border-gray-200 rounded-lg overflow-hidden transition-all hover:border-[#005c75] hover:shadow-md bg-white h-[100px]",children:[e.screenshotPath?n("div",{className:"w-[125px] h-full bg-gray-50 flex items-center justify-center shrink-0 rounded-bl-[8px] rounded-tl-[8px] border-r border-gray-200",children:n(Ye,{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(Ve,{type:e.entityType})})}),l("div",{className:"flex-1 flex items-center justify-between px-4 min-w-0",children:[l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n(Ve,{type:e.entityType}),n("div",{className:"text-base font-medium text-black truncate group-hover:text-[#005c75] transition-colors",children:e.name})]}),n("div",{className:"text-[10px] text-[#8e8e8e] truncate mb-1 font-mono",title:e.filePath,children:e.filePath}),t.hasScenarios&&l("div",{className:"flex items-center gap-2 mt-2",children:[l("span",{className:"px-[5px] py-0 bg-[#efefef] text-[#3e3e3e] rounded text-[10px] font-medium",children:[t.scenarioCount," scenarios"]}),n("span",{className:"text-xs text-[#8e8e8e]",children:t.timestamp})]})]}),n("div",{className:"shrink-0 ml-4",children:t.status==="not_analyzed"?l(le,{children:[l("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f9f9f9] border border-[#e1e1e1] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#c7c7c7]"}),n("span",{className:"text-[10px] font-semibold text-[#646464]",children:"Not analyzed"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${s?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:s,children:s?"Analyzing...":"Analyze"})]}):t.status==="up_to_date"?l("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f2fcf9] border border-[#c8f2e3] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#00925d]"}),n("span",{className:"text-[10px] font-semibold text-[#00925d]",children:"Up to date"})]}):l(le,{children:[l("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#e0e9ec] border border-[#e0e9ec] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#005c75]"}),n("span",{className:"text-[10px] font-semibold text-[#005c75]",children:"Out of date"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${s?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:s,children:s?"Analyzing...":"Analyze"})]})})]})]})},e.sha)}const Ds=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 Rf({importedEntities:e,importingEntities:t}){const[r]=cn(),a=r.get("from"),s=Ee(),o=s.state!=="idle",i=e.length>0,c=t.length>0,d=p=>p.filter(f=>f.entityType==="visual"||f.entityType==="library"),m=p=>{const f=d(p);f.length!==0&&s.submit({entityShas:f.map(g=>g.sha).join(",")},{method:"post",action:"/api/analyze"})},u=d(e).length>0,h=d(t).length>0;return n("div",{className:"max-w-[1400px] mx-auto",children:l("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[l("div",{className:"px-6 py-4 flex items-start justify-between",children:[l("div",{children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imports"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#deeafc] text-[#2f80ed] rounded-[9.095px] text-xs font-semibold leading-5",children:e.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities imported by this component."})]}),u&&n("button",{onClick:()=>m(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(Rs,{entity:p,analysisInfo:Ds(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."})})]}),l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[l("div",{className:"px-6 py-4 flex items-start justify-between",children:[l("div",{children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imported By"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#f3eefe] text-[#9b51e0] rounded-[9.095px] text-xs font-semibold leading-5",children:t.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities that import this component."})]}),h&&n("button",{onClick:()=>m(t),disabled:o,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:o?"Analyzing...":"Analyze All"})]}),c?n("div",{className:"p-6 space-y-4",children:t.map(p=>n(Rs,{entity:p,analysisInfo:Ds(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 Df({relatedEntities:e}){return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:n(Rf,{importedEntities:e.importedEntities,importingEntities:e.importingEntities})})}function Lf({data:e,defaultExpanded:t=!1,maxDepth:r=3}){return n("div",{className:"font-mono text-sm",children:n(ln,{data:e,depth:0,defaultExpanded:t,maxDepth:r})})}function ln({data:e,depth:t,defaultExpanded:r,maxDepth:a,objectKey:s,showInlineToggle:o=!1}){const[i,c]=_(r||t<2);if(ee(()=>{c(r||t<2)},[r,t]),e===null)return n("span",{className:"text-gray-500",children:"null"});if(e===void 0)return n("span",{className:"text-gray-500",children:"undefined"});const d=typeof e;if(d==="string")return l("span",{className:"text-green-600",children:['"',e,'"']});if(d==="number")return n("span",{className:"text-blue-600",children:e});if(d==="boolean")return n("span",{className:"text-purple-600",children:e.toString()});if(Array.isArray(e))return e.length===0?n("span",{className:"text-gray-600",children:"[]"}):l("span",{children:[l("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>c(!i),children:[l("span",{children:[i?"▼":"▶"," ","["]}),!i&&l("span",{children:[e.length,"]"]})]}),i?l(le,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:e.map((m,u)=>n("div",{className:"py-0.5",children:n(ln,{data:m,depth:t+1,defaultExpanded:r,maxDepth:a})},u))}),n("div",{className:"text-gray-600",children:"]"})]}):null]});if(d==="object"){const m=Object.keys(e);if(m.length===0)return n("span",{className:"text-gray-600",children:"{}"});const u=p=>p!==null&&typeof p=="object"&&!Array.isArray(p)&&Object.keys(p).length>0,h=p=>Array.isArray(p)&&p.length>0;return l("span",{children:[l("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>c(!i),children:[l("span",{children:[i?"▼":"▶"," ","{"]}),!i&&l("span",{children:[m.length,"}"]})]}),i?l(le,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:m.map(p=>{const f=e[p],g=u(f),y=h(f);return n("div",{className:"py-0.5",children:g?n(ka,{propertyKey:p,value:f,depth:t,defaultExpanded:r,maxDepth:a}):y?n(Ea,{propertyKey:p,value:f,depth:t,defaultExpanded:r,maxDepth:a}):l(le,{children:[l("span",{className:"text-orange-600",children:[p,": "]}),n(ln,{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 ka({propertyKey:e,value:t,depth:r,defaultExpanded:a,maxDepth:s}){const[o,i]=_(a||r<2),c=Object.keys(t);return ee(()=>{i(a||r<2)},[a,r]),l(le,{children:[l("button",{className:"cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded inline-flex items-baseline",style:{marginLeft:"-14px"},onClick:()=>i(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),l("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"{"}),!o&&l("span",{className:"text-gray-600",children:[c.length,"}"]})]}),o&&l(le,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:c.map(d=>{const m=t[d],u=m!==null&&typeof m=="object"&&!Array.isArray(m)&&Object.keys(m).length>0,h=Array.isArray(m)&&m.length>0;return n("div",{className:"py-0.5",children:u?n(ka,{propertyKey:d,value:m,depth:r+1,defaultExpanded:a,maxDepth:s}):h?n(Ea,{propertyKey:d,value:m,depth:r+1,defaultExpanded:a,maxDepth:s}):l(le,{children:[l("span",{className:"text-orange-600",children:[d,": "]}),n(ln,{data:m,depth:r+2,defaultExpanded:a,maxDepth:s})]})},d)})}),n("div",{className:"text-gray-600",children:"}"})]})]})}function Ea({propertyKey:e,value:t,depth:r,defaultExpanded:a,maxDepth:s}){const[o,i]=_(a||r<2);return ee(()=>{i(a||r<2)},[a,r]),l(le,{children:[l("button",{className:"cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded inline-flex items-baseline",style:{marginLeft:"-14px"},onClick:()=>i(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),l("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"["}),!o&&l("span",{className:"text-gray-600",children:[t.length,"]"]})]}),o&&l(le,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:t.map((c,d)=>{const m=c!==null&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,u=Array.isArray(c)&&c.length>0;return n("div",{className:"py-0.5",children:m?n(ka,{propertyKey:d.toString(),value:c,depth:r+1,defaultExpanded:a,maxDepth:s}):u?n(Ea,{propertyKey:d.toString(),value:c,depth:r+1,defaultExpanded:a,maxDepth:s}):n(ln,{data:c,depth:r+2,defaultExpanded:a,maxDepth:s})},d)})}),n("div",{className:"text-gray-600",children:"]"})]})]})}function Ur({label:e,count:t,isActive:r,onClick:a,badgeColorActive:s,badgeTextActive:o}){return l("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 Ls({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 Fs({call:e,scenarioName:t}){const[r,a]=_(!1),[s,o]=_("system"),i=p=>new Date(p).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),c=p=>p?`$${p.toFixed(4)}`:null,d=(p,f)=>{if(!p&&!f)return null;const g=[];return p&&g.push(`${p.toLocaleString()} in`),f&&g.push(`${f.toLocaleString()} out`),g.join(" / ")},m=ae(()=>{var p,f,g,y,x;try{const v=JSON.parse(e.response);return(g=(f=(p=v.choices)==null?void 0:p[0])==null?void 0:f.message)!=null&&g.content?v.choices[0].message.content:(x=(y=v.content)==null?void 0:y[0])!=null&&x.text?v.content[0].text:e.response}catch{return e.response}},[e.response]),u=ae(()=>{try{return JSON.stringify(JSON.parse(e.props),null,2)}catch{return e.props}},[e.props]),h=ae(()=>{var p;if(t)return t;try{const f=JSON.parse(e.props);return((p=f==null?void 0:f.scenario)==null?void 0:p.name)||null}catch{return null}},[e.props,t]);return l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-4 bg-[#f6f9fc] border-b border-[#e1e1e1] cursor-pointer hover:bg-[#edf2f7] transition-colors",onClick:()=>a(!r),children:l("div",{className:"flex items-start justify-between gap-4",children:[l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#005c75] text-white rounded text-[11px] font-medium",children:e.prompt_type}),n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-[11px] font-medium",children:e.model}),h&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-[11px] font-medium",children:h}),e.error&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-[11px] font-medium",children:"Error"})]}),l("div",{className:"flex items-center gap-4 text-xs text-[#626262]",children:[n("span",{children:i(e.created_at)}),d(e.input_tokens,e.output_tokens)&&n("span",{children:d(e.input_tokens,e.output_tokens)}),c(e.cost)&&n("span",{className:"text-[#005c75] font-medium",children:c(e.cost)})]}),l("div",{className:"text-[11px] text-[#8a8a8a] font-mono mt-1",children:[".codeyam/llm-calls/",e.object_id,"_",e.id,".json"]})]}),n("svg",{width:"20",height:"20",viewBox:"0 0 16 16",fill:"none",className:`transition-transform shrink-0 ${r?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"#626262",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})}),r&&l("div",{className:"border-t border-[#e1e1e1]",children:[l("div",{className:"flex border-b border-[#e1e1e1] bg-[#fafafa]",children:[n("button",{onClick:()=>o("system"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${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&&l("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"&&l("div",{children:[e.error&&l("div",{className:"mb-4 p-3 bg-[#fef2f2] border border-[#fecaca] rounded",children:[n("h4",{className:"text-xs font-semibold text-[#dc2626] uppercase mb-1",children:"Error"}),n("p",{className:"text-xs text-[#dc2626] m-0",children:e.error})]}),n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:m})]}),s==="props"&&n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:u})]}),e.error&&!s&&n("div",{className:"p-4 bg-[#fef2f2] border-t border-[#fecaca]",children:l("p",{className:"text-xs text-[#dc2626] m-0",children:[n("span",{className:"font-semibold",children:"Error: "}),e.error]})})]})]})}const Os=["generateEntityScenarios","analyzeEntity","generateDataStructure","generateEntityDescription"];function Ff({entity:e,analysis:t,scenarios:r,onAnalyze:a,llmCalls:s}){var w,C,k,N,E,S,M,F,L;const[o,i]=_("entity"),[c,d]=_("analysis"),[m,u]=_(r.length>0?{scenarioId:r[0].id||r[0].name}:null),[h,p]=_("entity"),{entityLlmCalls:f,scenarioLlmCalls:g,totalLlmCalls:y}=ae(()=>{if(!s)return{entityLlmCalls:[],scenarioLlmCalls:[],totalLlmCalls:0};const P=[...s.entityCalls,...s.analysisCalls],T=P.filter(I=>I.object_type==="entity"||Os.includes(I.prompt_type)),$=P.filter(I=>I.object_type!=="entity"&&!Os.includes(I.prompt_type));return T.sort((I,J)=>J.created_at-I.created_at),$.sort((I,J)=>J.created_at-I.created_at),{entityLlmCalls:T,scenarioLlmCalls:$,totalLlmCalls:P.length}},[s]),x=[{id:"analysis",title:"Analysis",data:t?{id:t.id,status:t.status}:void 0,description:"Analysis metadata including ID and processing status"},{id:"isolatedDataStructure",title:"Isolated Data Structure",data:(w=e==null?void 0:e.metadata)==null?void 0:w.isolatedDataStructure,description:"Entity's own data structure without dependencies"},{id:"mergedDataStructure",title:"Merged Data Structure",data:(C=t==null?void 0:t.metadata)==null?void 0:C.mergedDataStructure,description:"Combined data structure including dependencies"},{id:"conditionalUsages",title:"Conditional Usages",data:(N=(k=e==null?void 0:e.metadata)==null?void 0:k.isolatedDataStructure)==null?void 0:N.conditionalUsages,description:"Attributes used in conditionals (if, ternary, switch, &&) - candidates for key attributes"},{id:"executionFlows",title:"Execution Flows",data:(E=t==null?void 0:t.metadata)==null?void 0:E.executionFlows,description:"Distinct outcomes/behaviors this component can produce"},{id:"importedExports",title:"Imported Dependencies",data:{"Internal Dependencies":(S=e==null?void 0:e.metadata)==null?void 0:S.importedExports,"External Dependencies":(M=e==null?void 0:e.metadata)==null?void 0:M.nodeModuleImports},description:"Internal and external dependencies used by this entity"},{id:"scenariosDataStructure",title:"Scenarios Data Structure",data:(F=t==null?void 0:t.metadata)==null?void 0:F.scenariosDataStructure,description:"Structure template used across all scenarios"}],v=x.filter(P=>P.data!==void 0&&P.data!==null).length;let b=null;if(o==="entity"){const P=x.find(T=>T.id===c);P&&P.data!==void 0&&P.data!==null&&(b={title:P.title,description:P.description,data:P.data})}else if(o==="scenarios"&&m){const P=r.find(T=>(T.id||T.name)===m.scenarioId);P&&(b={title:P.name,description:P.description||"Scenario data and configuration",data:P.metadata})}return l("div",{className:"max-w-[1800px] mx-auto h-full flex flex-col",children:[n("div",{className:"mb-6 shrink-0",children:l("div",{className:"flex border-b border-gray-200 relative",children:[n(Ur,{label:"Entity",isActive:o==="entity",onClick:()=>i("entity"),badgeColorActive:"bg-[#e0e9ec]",badgeTextActive:"text-[#005c75]"}),n(Ur,{label:"Scenarios",count:r.length,isActive:o==="scenarios",onClick:()=>i("scenarios"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),n(Ur,{label:"LLM Calls",count:y,isActive:o==="llm-calls",onClick:()=>i("llm-calls"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),((L=t==null?void 0:t.metadata)==null?void 0:L.analyzerVersion)&&l("div",{className:"ml-auto flex items-center text-xs text-gray-500",children:[n("span",{className:"font-medium",children:"Analyzer:"}),n("span",{className:"ml-1 font-mono",children:t.metadata.analyzerVersion})]})]})}),o==="llm-calls"?l("div",{className:"flex-1 min-h-0",children:[l("div",{className:"flex gap-4 mb-4",children:[l("button",{onClick:()=>p("entity"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${h==="entity"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Entity Calls (",f.length,")"]}),l("button",{onClick:()=>p("scenario"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${h==="scenario"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Scenario Calls (",g.length,")"]})]}),n("div",{className:"space-y-4 overflow-y-auto",style:{maxHeight:"calc(100vh - 350px)"},children:h==="entity"?f.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:n("p",{className:"text-gray-500 text-sm m-0",children:"No entity-level LLM calls found"})}):f.map(P=>n(Fs,{call:P},P.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(P=>n(Fs,{call:P},P.id))})]}):l("div",{className:"grid grid-cols-[340px_1fr] gap-6 flex-1 min-h-0",children:[n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 overflow-y-auto",children:o==="entity"?l(le,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"ENTITY SECTIONS"}),v===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No entity data available."}):n("nav",{className:"space-y-1",children:x.map(P=>{const T=P.data!==void 0&&P.data!==null;return n(Ls,{label:P.title,isActive:c===P.id,onClick:()=>d(P.id),disabled:!T},P.id)})})]}):l(le,{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(P=>{const T=P.id||P.name,$=(m==null?void 0:m.scenarioId)===T;return n(Ls,{label:P.name,isActive:$,onClick:()=>u({scenarioId:T})},T)})})]})}),n("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:b?n(Of,{title:b.title,description:b.description,data:b.data}):o==="scenarios"&&r.length===0?n(zs,{title:"No Simulations Yet",description:"Analyze the code to create simulations and create test scenarios automatically.",onAnalyze:a}):o==="entity"?n(zs,{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 zs({title:e,description:t,onAnalyze:r}){return l("div",{className:"flex flex-col items-center justify-center h-full bg-[#f6f9fc]",children:[n("h2",{className:"text-[28px] font-semibold text-[#646464] leading-[40px] mb-2 text-center",children:e}),n("p",{className:"text-base text-[#646464] leading-6 mb-6 text-center max-w-[600px]",children:t}),r&&n("button",{onClick:r,className:"h-[54px] w-[183px] bg-[#005c75] text-white text-base font-medium rounded-lg border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]})}function Of({title:e,description:t,data:r}){const[a,s]=_(!0);return l(le,{children:[l("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50",children:[n("h3",{className:"text-base font-semibold text-black m-0",children:e}),n("p",{className:"text-sm text-[#646464] mt-1 m-0",children:t})]}),l("div",{className:"px-6 py-4 bg-white flex justify-between items-center",children:[l("div",{className:"flex gap-2",children:[n("button",{onClick:()=>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(Ht,{content:JSON.stringify(r,null,2),label:"Copy JSON",copiedLabel:"Copied!",className:"px-4 h-8 bg-[#343434] hover:bg-[#232323] text-white text-sm font-medium rounded border-none transition-colors whitespace-nowrap"})]}),n("div",{className:"overflow-y-auto flex-1",children:n("div",{className:"p-6",children:r?n("div",{className:"bg-gray-50 rounded-lg p-3 overflow-x-auto",children:n(Lf,{data:r,defaultExpanded:a,maxDepth:99})}):n("div",{className:"text-center py-12 text-gray-500",children:"No data available for this section"})})})]})}function zf({entity:e,analysis:t,scenarios:r,onAnalyze:a}){const s=Ee();return ee(()=>{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(Ff,{entity:e,analysis:t,scenarios:r,onAnalyze:a,llmCalls:s.data})})}const Yf={margin:0,padding:"24px",backgroundColor:"#101827",fontSize:"14px",lineHeight:"1.5"},Bf={minWidth:"3em",paddingRight:"1em",color:"#6b7280",userSelect:"none"},Uf=2e3,Wf=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 Hf({entity:e,entityCode:t}){const r=er(),a=Ne(null);return ee(()=>{const s=r.hash;if(!s||!a.current)return;const o=s.match(/^#L(\d+)$/);if(!o)return;const i=parseInt(o[1],10);setTimeout(()=>{if(!a.current)return;const c=a.current.querySelector(`[data-line-number="${i}"]`);if(c&&c instanceof HTMLElement){c.scrollIntoView({behavior:"smooth",block:"center"});const d=c.style.backgroundColor;c.style.backgroundColor="rgba(255, 255, 0, 0.2)",setTimeout(()=>{c.style.backgroundColor=d},2e3)}},300)},[r.hash,t]),n("div",{ref:a,className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:l("div",{className:"bg-white rounded-tl-lg rounded-tr-lg border border-gray-200 overflow-hidden",children:[l("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50 flex justify-between items-center",children:[l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0",children:"Source Code"}),n("p",{className:"text-xs text-[#646464] font-mono mt-1 m-0",children:e==null?void 0:e.filePath})]}),t&&n(Ht,{content:t,label:"Copy Code",duration:Uf,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(Ul,{language:Wf(e==null?void 0:e.filePath),style:Wl,showLineNumbers:!0,customStyle:Yf,lineNumberStyle:Bf,wrapLines:!0,lineProps:s=>({"data-line-number":s,style:{display:"block"}}),children:t})}):n("div",{className:"p-12 text-center text-gray-500",children:"No code available"})})]})})}const Vf=({data:e})=>[{title:e!=null&&e.entity?`${e.entity.name} - CodeYam`:"Entity - CodeYam"},{name:"description",content:"View entity scenarios and screenshots"}];function Jf({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 Gf({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"),c=(e["*"]||"").split("/").filter(Boolean),d=c[0]||"scenarios",m=c[1]||null,u=c[2]||null,h=r.analysisQueue,p=h?h.getState():{paused:!1,jobs:[]},[f,g,y,x]=await Promise.all([zt(a),$e(),Bt(),bd(fe()||process.cwd())]),v=f?await fa(f):null,b=f?await No(f.sha):null;let w={importedEntities:[],importingEntities:[]},C=null,k=[];f&&(w=await So(f),C=await ko(f),k=await Ao(f));const N=!!(f&&k.length>0&&k[0].sha!==f.sha),E=k.length>0?k[0].sha:null,S=!!(k.length>0&&k[0].analyses&&k[0].analyses.length>0),M=f?await Eo(f):!1;return W({entity:f??void 0,analysis:v??void 0,currentEntityAnalysis:b??void 0,projectSlug:g,from:o,relatedEntities:w,entityCode:C??void 0,hasNewerVersion:N,newestEntitySha:E,newestVersionHasAnalysis:S,fileModifiedSinceEntity:M,history:k,tab:d,scenarioId:m,viewModeFromUrl:u,currentCommit:y,hasAnApiKey:x,queueState:p})}const qf=De(function(){var Oa,za,Ya,Ba,Ua,Wa,Ha,Va,Ja,Ga,qa,Ka,Qa,Za,Xa;const t=Be(),s=(qs()["*"]||"").split("/").filter(Boolean),o=s[0]||"scenarios",i=s[1]||null,c=s[2]||null,d=t.entity,m=t.analysis,u=t.currentEntityAnalysis,h=u||m,p=t.projectSlug;t.from;const f=t.relatedEntities,g=t.entityCode,y=t.hasNewerVersion,x=t.newestEntitySha,v=t.newestVersionHasAnalysis,b=t.fileModifiedSinceEntity,w=t.history,C=t.currentCommit,k=t.hasAnApiKey,N=t.queueState;(Oa=h==null?void 0:h.status)==null||Oa.errors;const E=(h==null?void 0:h.scenarios)||[],S=E.filter(ne=>{var xe;return!((xe=ne.metadata)!=null&&xe.sameAsDefault)}),M=E.filter(ne=>{var xe;return(xe=ne.metadata)==null?void 0:xe.sameAsDefault}),F=It(),L=Ne(null);ee(()=>{L.current===null&&(L.current=window.history.length)},[]);const P=()=>{if(typeof window>"u")return;const ne=window.history.state;if(ne===null||(ne==null?void 0:ne.idx)===void 0||(ne==null?void 0:ne.idx)===0)F("/");else{const xe=window.history.length,He=L.current;if(He!==null&&xe>He){const Pe=xe-He+1;F(-Pe)}else F(-1)}},T=!!N.currentlyExecuting,$=o,I=(za=C==null?void 0:C.metadata)==null?void 0:za.currentRun,J=!!(I!=null&&I.createdAt)&&!(I!=null&&I.analysisCompletedAt),V=!!(d!=null&&d.sha&&((Ya=I==null?void 0:I.currentEntityShas)!=null&&Ya.includes(d.sha))),U=!!(d!=null&&d.sha&&((Ua=(Ba=N.currentlyExecuting)==null?void 0:Ba.entityShas)!=null&&Ua.includes(d.sha))),z=!!(d!=null&&d.sha&&((Wa=N.jobs)!=null&&Wa.some(ne=>{var xe;return(xe=ne.entityShas)==null?void 0:xe.includes(d.sha)}))),Y=V||U||z,R=Y&&((Ha=h==null?void 0:h.status)==null?void 0:Ha.finishedAt)!=null&&S.length>0&&h.entitySha!==(d==null?void 0:d.sha),A=ae(()=>{if($!=="scenarios")return null;if(i){const ne=S.find(xe=>xe.id===i);if(ne)return ne}return S.length>0&&!Y?S[0]:null},[$,i,S,Y]),G=((Ga=(Ja=(Va=A==null?void 0:A.metadata)==null?void 0:Va.executionResult)==null?void 0:Ja.error)==null?void 0:Ga.message)||((Qa=(Ka=(qa=h==null?void 0:h.status)==null?void 0:qa.errors)==null?void 0:Ka[0])==null?void 0:Qa.message);tt({source:A?"scenario-page":"entity-page",entitySha:d==null?void 0:d.sha,scenarioId:A==null?void 0:A.id,analysisId:h==null?void 0:h.id,entityName:d==null?void 0:d.name,entityType:d==null?void 0:d.entityType,scenarioName:A==null?void 0:A.name,errorMessage:G});const[B,H]=_(()=>c&&c!=="edit"?c:(d==null?void 0:d.entityType)==="library"?"data":"screenshot");ee(()=>{c&&c!==B&&c!=="edit"&&H(c)},[c]);const re=c==="edit",[O,j]=_(!1),[D,q]=_(!1),[te,de]=_(null),[ge,pe]=_(!1),[be,Ce]=_(!1),[ke,Se]=_(null),[_e,Te]=_(null),[ve,Q]=_(0),{interactiveServerUrl:me,isStarting:ye,isLoading:Ct,showIframe:ue,iframeKey:Fe,onIframeLoad:Oe}=gn({analysisId:h==null?void 0:h.id,scenarioId:A==null?void 0:A.id,scenarioName:A==null?void 0:A.name,projectSlug:p,enabled:re&&!!A,refreshTrigger:ve}),[Vt,U0]=_(!1),[W0,H0]=_(""),[xn,Jt]=_(!1),[Ra,wr]=_(Date.now()),[xi,Cr]=_(!1),nt=Ee(),Nt=Ee(),We=Ee(),ze=it(),bi=N.jobs.some(ne=>{var xe;return(d==null?void 0:d.sha)&&((xe=ne.entityShas)==null?void 0:xe.includes(d.sha))||ne.type==="analysis"&&ne.commitSha===(C==null?void 0:C.sha)&&ne.entityShas&&ne.entityShas.length===0}),Nr=Y,Da=((Za=d==null?void 0:d.metadata)==null?void 0:Za.defaultWidth)||((Xa=h==null?void 0:h.metadata)==null?void 0:Xa.defaultWidth)||1440,vi=Math.round(Da*(900/1440));nt.state==="submitting"||nt.state,ae(()=>{var ne;return!!((ne=A==null?void 0:A.metadata)!=null&&ne.interactiveExamplePath)},[A]);const{isCompleted:La}=bt(p,xn);ee(()=>{nt.state==="idle"&&nt.data&&(nt.data.success?setTimeout(()=>{wr(Date.now()),ze.revalidate(),Jt(!1)},1500):nt.data.error&&(Jt(!1),alert(`Recapture failed: ${nt.data.error}`)))},[nt.state,nt.data,ze]),ee(()=>{xn&&La&&setTimeout(()=>{wr(Date.now()),ze.revalidate(),Jt(!1)},1500)},[xn,La,ze]),ee(()=>{Nt.state==="idle"&&Nt.data&&(Nt.data.success?setTimeout(()=>{wr(Date.now()),ze.revalidate(),Jt(!1)},1500):Nt.data.error&&(Jt(!1),alert(`Recapture failed: ${Nt.data.error}`)))},[Nt.state,Nt.data,ze]);const Fa=()=>{d&&(y&&x&&x!==d.sha?(F(`/entity/${x}/scenarios`),setTimeout(()=>{We.submit({entitySha:x,filePath:d.filePath||""},{method:"post",action:"/api/analyze"})},100)):We.submit({entitySha:d.sha,filePath:d.filePath||""},{method:"post",action:"/api/analyze"}))};ee(()=>{We.state==="idle"&&We.data&&(We.data.success?ze.revalidate():We.data.error&&alert(`Analysis failed: ${We.data.error}`))},[We.state,We.data,d==null?void 0:d.sha,ze]),ee(()=>{const ne=setTimeout(()=>{ze.revalidate()},500);return()=>clearTimeout(ne)},[]),ee(()=>{if(J||Nr){const ne=setInterval(()=>{ze.revalidate()},3e3);return()=>clearInterval(ne)}else{const ne=setInterval(()=>{ze.revalidate()},5e3),xe=setTimeout(()=>{clearInterval(ne)},3e4);return()=>{clearInterval(ne),clearTimeout(xe)}}},[J,Nr,ze]);const wi=(ne,xe)=>ne==="scenarios"?`/entity/${d==null?void 0:d.sha}/scenarios`:`/entity/${d==null?void 0:d.sha}/${ne}`,Ci=(ne,xe)=>`/entity/${d==null?void 0:d.sha}/scenarios/${ne}/${xe}`,Ni=ne=>{H(ne),A!=null&&A.id&&(ne==="interactive"?F(`/entity/${d==null?void 0:d.sha}/scenarios/${A.id}/fullscreen`,{replace:!0}):F(Ci(A.id,ne),{replace:!0}))},Si=async ne=>{var xe,He;if(console.log("[EntityDetail] ===== APPLY CHANGES CALLED =====",{description:ne,hasSelectedScenario:!!A,hasAnalysis:!!h}),!A||!h){const Pe="Error: No scenario or analysis available";console.error("[EntityDetail]",Pe),de(Pe);return}j(!0),de(null),console.log("[EntityDetail] Applying changes (preview mode)",{description:ne,scenarioId:A.id,scenarioName:A.name,currentData:A.data});try{const Pe=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:ne,existingScenarios:h.scenarios,scenariosDataStructure:(xe=h.metadata)==null?void 0:xe.scenariosDataStructure,editingMockName:A.name,editingMockData:_e||((He=A.metadata)==null?void 0:He.data)})}),rt=await Pe.json();if(!Pe.ok||!rt.success)throw new Error(rt.error||"Failed to generate scenario data");console.log("[EntityDetail] Generated data:",rt.data),Te(rt.data);const bn=(h.scenarios||[]).map(Ue=>Ue.id===A.id?{...Ue,metadata:{...Ue.metadata,data:rt.data}}:Ue),Gt=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:h,scenarios:bn})}),Ge=await Gt.json();if(!Gt.ok||!Ge.success)throw console.error("[EntityDetail] Temp save failed:",Ge),new Error(Ge.error||"Failed to apply preview");if(de("Generating preview. Capturing screenshot..."),me){console.log("[EntityDetail] Using direct capture from running server",{serverUrl:me});const Ue=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:me,scenarioId:A.id,projectId:h.projectId,viewportWidth:1440})}),qt=await Ue.json();!Ue.ok||!qt.success?(console.error("[EntityDetail] Direct capture failed:",qt),de("Preview applied. Screenshot capture failed.")):(console.log("[EntityDetail] Direct capture successful"),de('Preview applied. Click "Save Scenario Data" to persist.'))}else{console.log("[EntityDetail] No server running, using queued recapture");const Ue=new FormData;Ue.append("analysisId",h.id||""),Ue.append("scenarioId",A.id||"");const qt=await fetch("/api/recapture-scenario",{method:"POST",body:Ue}),kr=await qt.json();!qt.ok||!kr.success?(console.warn("[EntityDetail] Recapture failed:",kr.error),de("Preview applied. Screenshot recapture failed.")):(console.log("[EntityDetail] Recapture queued:",kr.jobId),de('Preview applied. Screenshot will update shortly. Click "Save Scenario Data" to persist.'))}Q(Ue=>Ue+1),ze.revalidate()}catch(Pe){console.error("Error applying changes:",Pe),de(`Error: ${Pe instanceof Error?Pe.message:String(Pe)}`)}finally{j(!1)}},ki=async(ne,xe)=>{var He;if(!A||!h){de("Error: No scenario or analysis available");return}q(!0),de(null),console.log("[EntityDetail] Saving scenario to database",{description:ne,saveAsNew:xe});try{const Pe=_e||((He=A.metadata)==null?void 0:He.data);let rt;if(xe){const Ge={...A,id:`${A.name}-${Date.now()}`,name:`${A.name} (Copy)`,metadata:{...A.metadata,data:Pe},description:ne||A.description};rt=[...h.scenarios||[],Ge]}else rt=(h.scenarios||[]).map(Ge=>Ge.id===A.id?{...Ge,metadata:{...Ge.metadata,data:Pe},description:ne||Ge.description}:Ge);const bn=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:h,scenarios:rt})}),Gt=await bn.json();if(!bn.ok||!Gt.success)throw new Error(Gt.error||"Failed to save scenarios");console.log("[EntityDetail] Scenarios saved successfully"),de(xe?"New scenario created successfully":"Scenario saved successfully"),Te(null),ze.revalidate()}catch(Pe){console.error("Error saving scenario:",Pe),de(`Error: ${Pe instanceof Error?Pe.message:String(Pe)}`)}finally{q(!1)}},Ei=()=>{console.log("[EntityDetail] Edit mock data clicked"),de("Mock data editor coming soon")},Ai=async()=>{var ne;if(!(A!=null&&A.id)){Se("Cannot delete scenario without ID");return}pe(!0),Se(null);try{const xe=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:A.id,screenshotPaths:((ne=A.metadata)==null?void 0:ne.screenshotPaths)||[]})}),He=await xe.json();if(!xe.ok||!He.success)throw new Error(He.error||"Failed to delete scenario");F(`/entity/${d==null?void 0:d.sha}/scenarios`)}catch(xe){console.error("[EntityDetail] Error deleting scenario:",xe),Se(xe instanceof Error?xe.message:"Failed to delete scenario"),Ce(!1)}finally{pe(!1)}},Sr=h&&d&&h.entitySha!==d.sha,_i=d?Pf(d):!1;return n(fr,{children:l("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:l("div",{className:"flex items-end h-full px-6 gap-6",children:[l("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[n("button",{onClick:P,className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:d==null?void 0:d.name}),n("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:d==null?void 0:d.filePath,children:d==null?void 0:d.filePath})]}),n("div",{className:"flex items-end gap-8 shrink-0",children:[{id:"scenarios",label:"Scenarios",count:S.length},{id:"related",label:"Related Entities",count:f.importedEntities.length+f.importingEntities.length},{id:"code",label:"Code"},{id:"data",label:"Data Structure"},{id:"history",label:"History"}].map(ne=>n(se,{to:wi(ne.id),className:`relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline ${$===ne.id?"font-medium border-b-2":"font-normal hover:text-gray-700"}`,style:$===ne.id?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:l("span",{className:"flex items-center gap-2",children:[ne.label,ne.count!==void 0&&ne.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${$===ne.id?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:ne.count})]})},ne.id))})]})}),(y||Sr&&!u||b&&_i)&&!Y&&!bi&&n("div",{className:"border-b border-[#FEE585] px-6 py-3 flex items-center justify-center shrink-0",style:{backgroundColor:"#FEE585"},children:l("div",{className:"flex items-center gap-3",children:[n("svg",{className:"w-4 h-4",style:{color:"#714A25"},fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),n("span",{className:"text-sm font-semibold",style:{color:"#714A25"},children:Sr&&!y?"This entity version has not been analyzed yet.":"This entity has been recently changed."}),n("span",{className:"text-sm",style:{color:"#714A25"},children:y?"You are viewing an older version. A newer version is available.":Sr?"Showing scenarios from a previous version.":"The file on disk has been modified since this entity was analyzed."}),y&&x&&v?n(se,{to:`/entity/${x}/scenarios`,className:"px-3 py-1.5 text-white rounded text-[11px] font-medium font-mono cursor-pointer transition-colors no-underline",style:{backgroundColor:"#C69538"},onMouseEnter:ne=>{ne.currentTarget.style.backgroundColor="#B58530"},onMouseLeave:ne=>{ne.currentTarget.style.backgroundColor="#C69538"},children:"View Latest Version"}):n("button",{onClick:Fa,disabled:We.state!=="idle",className:"px-3 py-1.5 text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer transition-colors disabled:bg-gray-400 disabled:cursor-not-allowed",style:{backgroundColor:"#C69538"},onMouseEnter:ne=>{We.state==="idle"&&(ne.currentTarget.style.backgroundColor="#B58530")},onMouseLeave:ne=>{We.state==="idle"&&(ne.currentTarget.style.backgroundColor="#C69538")},children:"Re-analyze"})]})}),l("div",{className:"flex grow items-stretch justify-center gap-0 min-h-0",children:[$==="scenarios"&&l(le,{children:[re&&A?n(Tf,{scenario:A,entitySha:(d==null?void 0:d.sha)||"",onApply:Si,onSave:ki,onEditMockData:Ei,onDelete:Ai,isApplying:O,isSaving:D,saveMessage:te,showDeleteConfirm:be,onShowDeleteConfirm:Ce,isDeleting:ge,deleteError:ke}):n(Mf,{scenarios:S,hiddenScenarios:M,analysis:h,selectedScenario:A,entitySha:(d==null?void 0:d.sha)||"",cacheBuster:Ra,activeTab:$,entityType:d==null?void 0:d.entityType,entity:d,queueState:N,processIsRunning:T,isEntityAnalyzing:Y,areScenariosStale:R,viewMode:B,setViewMode:Ni,isBreakdownView:i==="breakdown"}),i==="breakdown"?n(If,{analysis:h??null,entitySha:(d==null?void 0:d.sha)||""}):re&&A?n(gr,{scenarioId:A.id||A.name,scenarioName:A.name,iframeUrl:me,isStarting:ye,isLoading:Ct,showIframe:ue,iframeKey:Fe,onIframeLoad:Oe,projectSlug:p,defaultWidth:1440,defaultHeight:900}):l("div",{className:"flex flex-col flex-1 min-h-0",children:[A&&l("div",{className:"bg-[#f5f5f5] border-b border-gray-200 px-4 py-2 flex items-center justify-between shrink-0",children:[l("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-xs font-semibold text-[#343434]",children:A.name}),l("span",{className:"text-xs text-[#9e9e9e] font-normal",children:[Da," × ",vi]})]}),l("div",{className:"flex items-center gap-2",children:[n(se,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${A.id}/edit`,className:"px-3 py-1.5 bg-white text-[#343434] rounded text-[11px] font-medium font-mono border border-gray-300 cursor-pointer hover:bg-gray-50 transition-colors no-underline flex items-center",title:"Edit Scenario Data",children:"Edit Scenario"}),l("button",{className:"px-3 py-1.5 bg-[#022A35] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#011a21] transition-colors flex items-center gap-1.5",onClick:()=>{alert("Download functionality coming soon")},title:"Download",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:n("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"})}),"Download"]}),l(se,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${A.id}/fullscreen`,className:"px-3 py-1.5 bg-[#005c75] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#004a5e] transition-colors no-underline flex items-center gap-1.5",title:"Interactive Mode",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:n("path",{d:"M8 5v14l11-7z"})}),"Interactive Mode"]})]})]}),n(ri,{selectedScenario:A,analysis:h,entity:d,viewMode:B,cacheBuster:Ra,hasScenarios:S.length>0,isAnalyzing:Nr,projectSlug:p,hasAnApiKey:k,processIsRunning:T,queueState:N})]})]}),$==="related"&&n(Df,{relatedEntities:f}),$==="data"&&n(zf,{entity:d,analysis:h,scenarios:S,onAnalyze:Fa}),$==="code"&&n(Hf,{entity:d,entityCode:g}),$==="history"&&n($f,{entity:d,history:w})]}),xi&&p&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>Cr(!1),children:l("div",{className:"bg-white rounded-xl max-w-[1200px] w-full max-h-[90vh] flex flex-col shadow-[0_20px_60px_rgba(0,0,0,0.3)]",onClick:ne=>ne.stopPropagation(),children:[l("div",{className:"px-6 py-6 border-b border-gray-200 flex justify-between items-center",children:[n("h2",{className:"m-0 text-xl font-semibold text-gray-900",children:"Analysis Logs"}),n("button",{className:"bg-transparent border-none text-[28px] text-gray-500 cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-colors hover:bg-gray-100",onClick:()=>Cr(!1),children:"×"})]}),n("div",{className:"flex-1 overflow-hidden",children:n(gt,{projectSlug:p,onClose:()=>Cr(!1)})})]})})]})})}),Kf=Object.freeze(Object.defineProperty({__proto__:null,default:qf,loader:Gf,meta:Vf,shouldRevalidate:Jf},Symbol.toStringTag,{value:"Module"}));async function Qf(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 Le();const i=fe();if(!i)throw new Error("Project root not found");console.log(`[analyzeEntities] Project root: ${i}`);const c=oe.join(i,".codeyam","config.json"),d=JSON.parse(await he.readFile(c,"utf8")),{projectSlug:m,branchId:u}=d;if(!m||!u)throw new Error("Invalid project configuration - missing projectSlug or branchId");console.log(`[analyzeEntities] Project: ${m}, Branch: ${u}`);const h=ur(m);try{await he.writeFile(h,"","utf8"),console.log("[analyzeEntities] Cleared log file")}catch{}const{project:p,branch:f}=await Ie(m);console.log("[analyzeEntities] Loading entities to determine file paths and names...");const g=await ot({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(b=>b.filePath).filter(b=>!!b))],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 x=await gd(p,f,y);console.log(`[analyzeEntities] Created commit ${x.sha.substring(0,8)}`),console.log("[analyzeEntities] Initializing progress tracking..."),await ft({commitSha:x.sha,runStatusUpdate:{queuedAt:new Date().toISOString(),entityCount:t.length,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString()},updateCallback:b=>{if(!b)return;const w=b.currentRun;if(w&&w.id&&w.archivedAt)return;w&&(w.analysesCompleted&&w.analysesCompleted>0||w.capturesCompleted&&w.capturesCompleted>0)&&Ad(b)}}),console.log("[analyzeEntities] Enqueueing analysis job...");const{jobId:v}=o.enqueue({type:"analysis",commitSha:x.sha,projectSlug:m,filePaths:y,entityShas:t,entityNames:g.map(b=>b.name),...a?{context:a}:{},...s?{scenarioCount:s}:{}});return console.log(`[analyzeEntities] Job queued with ID: ${v} for ${t.length} entities`),{jobId:v}}catch(i){throw console.error("[analyzeEntities] Failed:",i),i}}async function Zf({request:e,context:t}){if(e.method!=="POST")return W({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await ut()),!r)return W({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("entitySha"),o=a.get("entityShas"),i=a.get("filePath"),c=a.get("context"),d=a.get("scenarioCount");let m;if(o)m=o.split(",").filter(Boolean);else if(s)m=[s];else return W({error:"Missing required field: entitySha or entityShas"},{status:400});if(m.length===0)return W({error:"No entities to analyze"},{status:400});console.log(`[API] Starting analysis for ${m.length} entity(ies)`);const u=await ot({shas:m}),p=[...new Set(u.map(g=>g.filePath).filter(g=>!!g))].length,{jobId:f}=await Qf({entityShas:m,filePaths:i?[i]:void 0,context:c||void 0,scenarioCount:d?parseInt(d,10):void 0,queue:r});return console.log(`[API] Analysis queued with job ID: ${f}`),W({success:!0,message:`Analysis queued for ${m.length} entity(ies)`,entityCount:m.length,fileCount:p,jobId:f})}catch(a){return console.error("[API] Error starting analysis:",a),W({error:"Failed to start analysis",details:a.message},{status:500})}}const Xf=Object.freeze(Object.defineProperty({__proto__:null,action:Zf},Symbol.toStringTag,{value:"Module"}));function eg(e){switch(e){case"queued":return{text:"Queued",bgColor:"#cbf3fa",textColor:"#3098b4",icon:l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]})};case"analyzing":return{text:"Analyzing...",bgColor:"#ffdbf6",textColor:"#ff2ab5",icon:l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]})};case"up-to-date":return{text:"Up to date",bgColor:"#e8ffe6",textColor:"#00925d",icon:null};case"incomplete":return{text:"Incomplete",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"out-of-date":return{text:"Out of date",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"not-analyzed":return{text:"Not analyzed",bgColor:"#f9f9f9",textColor:"#646464",icon:null}}}function ai(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",c=s%12||12,d=o.toString().padStart(2,"0");return`Today, ${c}:${d} ${i}`}return t.toLocaleString("en-US",{month:"numeric",day:"numeric",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!0})}function qe(e,t=[],r=!1){var u,h;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(!(((u=s.status)==null?void 0:u.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,c=(h=e.metadata)!=null&&h.editedAt?new Date(e.metadata.editedAt).getTime():0,d=s.scenarios||[],m=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>=c?d.length>0&&m?d.every(f=>{var g,y,x;return((y=(g=f.metadata)==null?void 0:g.screenshotPaths)==null?void 0:y[0])||((x=f.metadata)==null?void 0:x.executionResult)})?"up-to-date":"incomplete":d.length>0?"incomplete":"not-analyzed":"out-of-date"}const tg=()=>[{title:"Simulations - CodeYam"},{name:"description",content:"A visual gallery of your recently captured component screenshots"}];async function ng({request:e,context:t}){try{const r=t.analysisQueue,a=r?r.getState():{paused:!1,jobs:[]},s=await pn();return W({entities:s||[],queueState:a})}catch(r){return console.error("Failed to load simulations:",r),W({entities:[],queueState:{paused:!1,jobs:[]},error:"Failed to load simulations"})}}const rg=De(function(){const t=Be(),r=t.entities,a=t.queueState;tt({source:"simulations-page"});const[s,o]=_(""),[i,c]=_("visual"),d=ae(()=>{const y=[];return r.forEach(x=>{var b;const v=(b=x.analyses)==null?void 0:b[0];if(v!=null&&v.scenarios){const w=v.scenarios.filter(C=>{var k;return!((k=C.metadata)!=null&&k.sameAsDefault)}).map(C=>{var L,P,T,$,I;const k=(P=(L=C.metadata)==null?void 0:L.screenshotPaths)==null?void 0:P[0],N=(T=C.metadata)==null?void 0:T.noScreenshotSaved,E=k&&!N,S=(I=($=v.status)==null?void 0:$.scenarios)==null?void 0:I.find(J=>J.name===C.name),M=S&&S.screenshotStartedAt&&!S.screenshotFinishedAt;let F;return E?F="completed":M?F="capturing":F="error",{scenarioName:C.name,scenarioDescription:C.description||"",screenshotPath:k||"",scenarioId:C.id,state:F}}).filter(C=>C.state==="completed"||C.state==="capturing");w.length>0&&y.push({entity:x,screenshots:w,createdAt:v.createdAt||""})}}),y.sort((x,v)=>new Date(v.createdAt).getTime()-new Date(x.createdAt).getTime()),y},[r]),m=ae(()=>r.filter(y=>{var b,w;const x=(b=y.analyses)==null?void 0:b[0];return!((w=x==null?void 0:x.scenarios)==null?void 0:w.some(C=>{var k,N;return(N=(k=C.metadata)==null?void 0:k.screenshotPaths)==null?void 0:N[0]}))}),[r]),u=ae(()=>d.filter(({entity:y})=>{const x=!s||y.name.toLowerCase().includes(s.toLowerCase()),v=i==="all"||y.entityType===i;return x&&v}),[d,s,i]),h=ae(()=>m.filter(y=>{const x=!s||y.name.toLowerCase().includes(s.toLowerCase()),v=i==="all"||y.entityType===i;return x&&v}),[m,s,i]),p=ie(y=>{o(y.target.value)},[]),f=ie(y=>{c(y.target.value)},[]),g=d.length>0;return n("div",{className:"bg-[#F8F7F6] min-h-screen overflow-y-auto",children:l("div",{className:"px-20 py-12",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Simulations"}),n("p",{className:"text-[15px] text-gray-500",children:"A visual gallery of your recently captured simulations."})]}),!g&&n("div",{className:"bg-[#D1F3F9] border border-[#A5E8F0] rounded-lg p-4 mb-6",children:l("p",{className:"text-sm text-gray-700 m-0",children:["This page will display a visual gallery of your recently captured component simulations."," ",n("strong",{children:"Start by analyzing your first component below."})]})}),l("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),l("div",{className:"flex gap-3",children:[l("div",{className:"relative",children:[l("select",{className:"appearance-none bg-gray-50 border border-gray-200 rounded px-3 pr-8 text-[13px] h-[39px] cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",value:i,onChange:f,children:[n("option",{value:"all",children:"All Types"}),n("option",{value:"visual",children:"Visual"}),n("option",{value:"library",children:"Library"})]}),n(Qe,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),l("div",{className:"flex-1 relative",children:[n(dn,{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&&u.length>0&&n("div",{className:"mb-2",children:l("div",{className:"flex items-center py-3",children:[l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:u.length})," ",u.length===1?"entity":"entities"]}),l("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:u.reduce((y,{screenshots:x})=>y+x.length,0)})," ","scenarios"]})]})}),l("div",{className:"flex flex-col gap-3",children:[g&&(u.length===0?n("div",{className:"bg-white border border-gray-200 rounded-lg p-8 text-center text-gray-500",children:"No simulations match your filters."}):n(le,{children:u.map(({entity:y,screenshots:x})=>n(ag,{entity:y,screenshots:x,queueJobs:(a==null?void 0:a.jobs)||[]},y.sha))})),!g&&(h.length===0?n("div",{className:"bg-white border border-gray-200 rounded-b-lg p-8 text-center text-gray-500",children:"No components found matching your filters."}):h.map(y=>n(sg,{entity:y},y.sha)))]})]})})});function ag({entity:e,screenshots:t,queueJobs:r}){var f,g,y;const a=It(),s=Ee(),[o,i]=_(!1),c=t.length||(((y=(g=(f=e.analyses)==null?void 0:f[0])==null?void 0:g.scenarios)==null?void 0:y.length)??0),d=x=>{a(`/entity/${e.sha}/scenarios/${x}?from=simulations`)},m=()=>{i(!0),s.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};ee(()=>{s.state==="idle"&&o&&i(!1)},[s.state,o]);const u=qe(e,r),h=eg(u),p=u==="out-of-date";return n("div",{className:"rounded-[8px]",style:{backgroundColor:"#ffffff",border:"1px solid #e1e1e1"},children:l("div",{className:"flex flex-col",children:[l("div",{className:"flex items-center px-[15px] py-[15px]",children:[n("div",{className:"flex-shrink-0",children:n(Ve,{type:e.entityType||"other",size:"large"})}),l("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[l("div",{className:"flex items-center gap-[5px]",children:[l(se,{to:`/entity/${e.sha}`,className:"hover:underline cursor-pointer",title:e.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:[e.name," (",c,")"]}),n("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:h.bgColor,color:h.textColor,fontSize:"12px",lineHeight:"16px",fontWeight:400},children:h.text})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#b0b0b0",fontWeight:400},className:"font-mono",title:e.filePath,children:e.filePath})]}),n("div",{className:"flex-1"}),l("div",{className:"flex-shrink-0 flex items-center gap-2",children:[p&&n(le,{children:o||s.state!=="idle"?l("div",{className:"px-2 py-1 bg-pink-100 rounded flex items-center gap-1.5",children:[n(Xe,{size:14,className:"animate-spin",style:{color:"#be185d"}}),n("span",{style:{color:"#be185d",fontSize:"10px",lineHeight:"20px",fontWeight:600},children:"Analyzing..."})]}):n("button",{onClick:m,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#005c75",color:"#ffffff",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#004d5e"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#005c75"},children:"Re-analyze"})}),n("button",{onClick:()=>void a(`/entity/${e.sha}/logs`),className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})]})]}),n("div",{className:"border-t border-gray-200"}),n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:t.length>0?t.map(x=>l("div",{className:"shrink-0 flex flex-col gap-2",children:[n("button",{onClick:()=>d(x.scenarioId||""),className:"block cursor-pointer bg-transparent border-none p-0",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{"--hover-border":"#005C75",backgroundColor:x.state==="capturing"?"#f9f9f9":"#f3f4f6",borderColor:x.state==="capturing"?"#efefef":"#d1d5db"},onMouseEnter:v=>{x.state==="completed"&&(v.currentTarget.style.borderColor="#005C75",v.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:v=>{v.currentTarget.style.borderColor=x.state==="capturing"?"#efefef":"#d1d5db",v.currentTarget.style.boxShadow="none"},children:x.state==="completed"?n(Ye,{screenshotPath:x.screenshotPath,alt:x.scenarioName,className:"max-w-full max-h-full object-contain"}):x.state==="capturing"?n(Sa,{size:"medium"}):null})}),l("div",{className:"relative group",children:[n("div",{className:"text-left text-xs text-gray-600 cursor-default",style:{fontSize:"11px",lineHeight:"14px",maxWidth:"144px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:x.scenarioName}),n("div",{className:"fixed hidden group-hover:block pointer-events-none",style:{zIndex:1e4,transform:"translateY(8px)"},children:l("div",{className:"bg-gray-100 text-gray-800 text-xs rounded-lg px-3 py-2 shadow-lg max-w-xs border border-gray-200",children:[x.scenarioName,x.scenarioDescription&&l(le,{children:[": ",x.scenarioDescription]}),n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-100 border-l border-t border-gray-200 transform rotate-45"})]})})]})]},x.scenarioId)):n("div",{className:"text-xs text-gray-400 py-4",children:"No screenshots available"})})]})})}function sg({entity:e}){const t=Ee(),[r,a]=_(!1),s=()=>{a(!0),t.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};return ee(()=>{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:l("div",{className:"px-5 py-4 flex items-center",children:[l("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n(Ve,{type:e.entityType}),l("div",{className:"min-w-0",children:[l("div",{className:"flex items-center gap-3 mb-0.5",children:[n(se,{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:ai(e.createdAt||null)}),n("div",{className:"w-24 flex justify-end",children:r||t.state!=="idle"?l("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(Xe,{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 og=Object.freeze(Object.defineProperty({__proto__:null,default:rg,loader:ng,meta:tg},Symbol.toStringTag,{value:"Module"}));function ig({request:e,context:t}){const r=t.dbNotifier||Kr;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"})}
229
-
230
- `)),Math.random().toString(36).substring(7);let i=!1;const c=()=>{if(!i){i=!0,r.off("change",d),clearInterval(m);try{s.close()}catch{}}},d=u=>{try{s.enqueue(o.encode(`data: ${JSON.stringify({type:"db-change",changeType:u.type,timestamp:u.timestamp})}
231
-
232
- `))}catch{c()}};r.on("change",d);const m=setInterval(()=>{try{s.enqueue(o.encode(`data: ${JSON.stringify({type:"keepalive"})}
233
-
234
- `))}catch{c()}},3e4);e.signal.addEventListener("abort",c)}});return new Response(a,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}const lg=Object.freeze(Object.defineProperty({__proto__:null,loader:ig},Symbol.toStringTag,{value:"Module"}));function cg(){return new Response(JSON.stringify({status:"ok",version:ya,message:"CodeYam Remix server is running"}),{status:200,headers:{"Content-Type":"application/json"}})}const dg=Object.freeze(Object.defineProperty({__proto__:null,loader:cg},Symbol.toStringTag,{value:"Module"}));function Aa(e){const t=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,r=e.match(t);if(!r)return{frontmatter:{},body:e};const a=r[1],s=r[2],o={},i=a.match(/paths:\s*\n((?:\s+-\s+[^\n]+\n?)*)/),c=a.match(/paths:\s*\[([^\]]*)\]/);i&&i[1].trim()?o.paths=i[1].split(`
235
- `).filter(m=>m.trim().startsWith("-")).map(m=>m.replace(/^\s*-\s*/,"").replace(/['"]/g,"").trim()).filter(Boolean):c&&(o.paths=c[1].split(",").map(m=>m.replace(/['"]/g,"").trim()).filter(Boolean));const d=a.match(/^category:\s*(.+)$/m);return d&&(o.category=d[1].replace(/['"]/g,"").trim()),{frontmatter:o,body:s}}async function br(e,t=""){const r=[];try{const a=await he.readdir(e,{withFileTypes:!0});for(const s of a){const o=t?`${t}/${s.name}`:s.name;if(s.isDirectory()){const i=await br(oe.join(e,s.name),o);r.push(...i)}else s.isFile()&&s.name.endsWith(".md")&&r.push(o)}}catch{}return r}async function yn(e){const t=await br(e),r=[];for(const a of t){const s=oe.join(e,a);try{const o=await he.readFile(s,"utf-8"),{frontmatter:i,body:c}=Aa(o);r.push({filePath:a,absolutePath:s,frontmatter:i,body:c})}catch{}}return r}function si(e){const t=oe.posix.dirname(e.filePath);return!t||t==="."?null:`${t}/**`}function oi(e,t){if(t.frontmatter.paths&&t.frontmatter.paths.length>0)return t.frontmatter.paths.some(a=>qr(e,a,{matchBase:!0}));const r=si(t);return r?qr(e,r,{matchBase:!0}):!1}function ug(e,t){return(!e.frontmatter.paths||e.frontmatter.paths.length===0)&&!si(e)?[]:t.filter(r=>oi(r,e))}const mg=new Set(["node_modules",".git","dist",".codeyam",".claude","build","coverage"]);async function _a(e){const t=[];async function r(a,s){try{const o=await Re.readdir(a,{withFileTypes:!0});for(const i of o){const c=Z.join(a,i.name),d=s?`${s}/${i.name}`:i.name;i.isDirectory()&&mg.has(i.name)||(i.isDirectory()?await r(c,d):i.isFile()&&t.push(d))}}catch{}}return await r(e,""),t}const hg="codeyam-rule-state.json",Wr=1;function ii(e){const t=e.replace(/^category:\s*.+$\n?/m,"");return nr.createHash("sha256").update(t).digest("hex")}function li(e){return oe.join(e,".claude",hg)}async function ci(e){const t=li(e);try{const r=await he.readFile(t,"utf-8"),a=JSON.parse(r);return a.version!==Wr?(console.warn(`[ruleState] Unknown version ${a.version}, using empty state`),{version:Wr,rules:{}}):a}catch{return{version:Wr,rules:{}}}}async function di(e,t){const r=li(e),a=oe.dirname(r);await he.mkdir(a,{recursive:!0}),await he.writeFile(r,JSON.stringify(t,null,2)+`
236
- `,"utf-8")}async function Pa(e,t){const r=await ci(e),a=new Set(t.map(s=>s.filePath));for(const s of Object.keys(r.rules))a.has(s)||delete r.rules[s];for(const s of t){const o=await he.readFile(s.absolutePath,"utf-8"),i=ii(o),c=r.rules[s.filePath];c?c.contentHash!==i&&(r.rules[s.filePath]={...c,contentHash:i,reviewed:!1}):r.rules[s.filePath]={contentHash:i,reviewed:!1}}return await di(e,r),r}async function Ys(e,t,r,a){const s=await ci(e);if(r){const o=oe.join(e,".claude","rules"),i=oe.join(o,t),c=await he.readFile(i,"utf-8"),d=ii(c);s.rules[t]?(s.rules[t].reviewed=!0,s.rules[t].contentHash=d):s.rules[t]={contentHash:d,reviewed:!0}}else s.rules[t]&&(s.rules[t].reviewed=!1);await di(e,s)}function Ma(e,t){var r;return((r=e.rules[t])==null?void 0:r.reviewed)??!1}async function ui(e,t=""){const r=[],a=await he.readdir(e,{withFileTypes:!0});for(const s of a){const o=t?`${t}/${s.name}`:s.name;s.isDirectory()?r.push(...await ui(oe.join(e,s.name),o)):s.name.endsWith(".md")&&r.push(o)}return r}function Qn(e){if(!e||e==="(diff not available)")return!1;const t=e.split(`
237
- `).filter(a=>!(!a.startsWith("+")&&!a.startsWith("-")||a.startsWith("+++")||a.startsWith("---"))).map(a=>a.substring(1).trim());if(t.length===0)return!1;const r=/^(category:\s*\w+)$/;return t.every(a=>r.test(a))}async function pg({request:e}){const t=fe();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=new URL(e.url),a=r.searchParams.get("action"),s=oe.join(t,".claude","rules");if(a==="recent-changes")return gg(t,s);if(a==="reviewed-status")return xg(t,s);if(a==="audit")return bg(t,s);if(a==="source-files")return vg(t);if(a==="rule-coverage")return wg(t,s);if(a==="rule-diff"){const o=r.searchParams.get("filePath");return o?yg(t,o):Response.json({error:"Missing required parameter: filePath"},{status:400})}if(a==="rules-for-path"){const o=r.searchParams.get("path");return o?Cg(s,o):Response.json({error:"Missing required parameter: path"},{status:400})}try{const o=await br(s),i=[];for(const u of o){const h=oe.join(s,u);try{const p=await he.readFile(h,"utf-8"),f=await he.stat(h),{frontmatter:g,body:y}=Aa(p);i.push({filePath:u,content:p,frontmatter:g,body:y,lastModified:f.mtime.toISOString()})}catch{}}i.sort((u,h)=>new Date(h.lastModified).getTime()-new Date(u.lastModified).getTime());let c=i.length>0;if(!c)try{await he.access(oe.join(t,".claude","codeyam-rule-state.json")),c=!0}catch{}const d=await yn(s),m={};if(d.length>0){const u=await Pa(t,d);for(const h of d)m[h.filePath]=Ma(u,h.filePath)}return Response.json({memories:i,memoryInitialized:c,reviewedStatus:m})}catch(o){return console.error("[API] Error loading memories:",o),Response.json({error:"Failed to load memories",details:o instanceof Error?o.message:String(o),memoryInitialized:!1},{status:500})}}async function fg(e,t){const r=[];try{const a=t("git status --porcelain -- .claude/rules/ 2>/dev/null || true",{cwd:e,encoding:"utf-8"});for(const s of a.split(`
238
- `).filter(Boolean)){const o=s.substring(0,2);let i=s.substring(3);if(i.includes(" -> ")&&(i=i.split(" -> ")[1]),!i.startsWith(".claude/rules/"))continue;const c=o[0],d=o[1];let m=[i];if(i.endsWith("/")&&c==="?"){const u=oe.join(e,i);try{m=(await ui(u)).map(p=>i+p)}catch{continue}}for(const u of m){if(u.endsWith("/"))continue;const h=u.replace(".claude/rules/","");let p="modified";c==="A"||c==="?"?p="added":c==="D"||d==="D"?p="deleted":(c==="M"||d==="M")&&(p="modified");let f="";try{if(p==="deleted")f=t(`git diff HEAD -- "${u}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});else if(p==="added"&&c==="?"){const g=`${e}/${u}`;try{const y=await he.readFile(g,"utf-8");f=`diff --git a/${u} b/${u}
239
- new file mode 100644
240
- --- /dev/null
241
- +++ b/${u}
242
- @@ -0,0 +1,${y.split(`
243
- `).length} @@
244
- ${y.split(`
245
- `).map(x=>"+"+x).join(`
246
- `)}`}catch{f="(content not available)"}}else f=t(`git diff HEAD -- "${u}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});f.length>5e3&&(f=f.substring(0,5e3)+`
247
- ... (truncated)`)}catch{f="(diff not available)"}p==="modified"&&Qn(f)||r.push({filePath:h,changeType:p,diff:f})}}}catch{}return r}async function gg(e,t){try{const{execSync:r}=await import("child_process"),a=[],s=await yn(t),o={};if(s.length>0){const u=await Pa(e,s);for(const h of s)o[h.filePath]=Ma(u,h.filePath)}const c=(await fg(e,r)).filter(u=>!o[u.filePath]);c.length>0&&a.push({commitHash:"uncommitted",date:new Date().toISOString(),message:"Uncommitted changes",files:c});const m=r('git log --format="%H|%aI|%s" --since="60 days ago" -- .claude/rules/ 2>/dev/null || true',{cwd:e,encoding:"utf-8",maxBuffer:10*1024*1024}).split(`
248
- `).filter(Boolean).slice(0,20);for(const u of m){const[h,p,...f]=u.split("|"),g=f.join("|");if(!h||!p)continue;const y=r(`git diff-tree --no-commit-id --name-status -r ${h} -- .claude/rules/ 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}),x=[];for(const v of y.split(`
249
- `).filter(Boolean)){const[b,w]=v.split(" ");if(!w||!w.startsWith(".claude/rules/"))continue;const C=w.replace(".claude/rules/","");let k="modified";if(b==="A"?k="added":b==="D"&&(k="deleted"),o[C])continue;let N="";try{N=r(`git show ${h} --format="" -- "${w}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024}),N.length>5e3&&(N=N.substring(0,5e3)+`
250
- ... (truncated)`)}catch{N="(diff not available)"}k==="modified"&&Qn(N)||x.push({filePath:C,changeType:k,diff:N})}x.length>0&&a.push({commitHash:h.substring(0,8),date:p,message:g,files:x})}return Response.json({changes:a,reviewedStatus:o})}catch(r){return console.error("[API] Error getting recent changes:",r),Response.json({changes:[],reviewedStatus:{}})}}async function yg(e,t){try{const{execSync:r}=await import("child_process"),a=`.claude/rules/${t}`,s=r(`git rev-list --count HEAD -- "${a}" 2>/dev/null || echo 0`,{cwd:e,encoding:"utf-8"}),o=parseInt(s.trim(),10)||0,i=r(`git diff HEAD -- "${a}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});if(i.trim()){if(Qn(i))return Response.json({diff:null});const y=i.length>5e3?i.substring(0,5e3)+`
251
- ... (truncated)`:i;return Response.json({diff:{diff:y,commitMessage:"Uncommitted changes",date:new Date().toISOString(),isUncommitted:!0,commitCount:o}})}if(r(`git status --porcelain -- "${a}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}).trim().startsWith("?")){const y=oe.join(e,a);try{const x=await he.readFile(y,"utf-8"),v=`diff --git a/${a} b/${a}
252
- new file mode 100644
253
- --- /dev/null
254
- +++ b/${a}
255
- @@ -0,0 +1,${x.split(`
256
- `).length} @@
257
- ${x.split(`
258
- `).map(b=>"+"+b).join(`
259
- `)}`;return Response.json({diff:{diff:v.length>5e3?v.substring(0,5e3)+`
260
- ... (truncated)`:v,commitMessage:"New file (untracked)",date:new Date().toISOString(),isUncommitted:!0,commitCount:0}})}catch{}}const m=r(`git log -1 --format="%H|%aI|%s" -- "${a}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}).trim();if(!m)return Response.json({diff:null});const[u,h,...p]=m.split("|"),f=p.join("|");if(!u||!h)return Response.json({diff:null});let g=r(`git show ${u} --format="" -- "${a}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});return g.trim()?Qn(g)?Response.json({diff:null}):(g.length>5e3&&(g=g.substring(0,5e3)+`
261
- ... (truncated)`),Response.json({diff:{diff:g,commitMessage:f,date:h,isUncommitted:!1,commitCount:o}})):Response.json({diff:null})}catch(r){return console.error("[API] Error getting rule diff:",r),Response.json({diff:null})}}async function xg(e,t){try{const r=await yn(t),a={};if(r.length>0){const s=await Pa(e,r);for(const o of r)a[o.filePath]=Ma(s,o.filePath)}return Response.json({reviewedStatus:a})}catch(r){return console.error("[API] Error getting reviewed status:",r),Response.json({reviewedStatus:{}})}}async function bg(e,t){try{const r=await yn(t),a=await _a(e),s=[];for(const o of a){const i=r.filter(c=>oi(o,c));if(i.length>0){const c=i.reduce((d,m)=>d+m.body.length,0);s.push({filePath:o,matchingRules:i.map(d=>({filePath:d.filePath,patterns:d.frontmatter.paths||[],bodyLength:d.body.length})),totalTextLength:c})}}return s.sort((o,i)=>i.totalTextLength-o.totalTextLength),Response.json({topPaths:s,totalFilesWithCoverage:s.length,allSourceFiles:a})}catch(r){return console.error("[API] Error getting audit data:",r),Response.json({error:"Failed to get audit data",details:r instanceof Error?r.message:String(r)},{status:500})}}async function vg(e){try{const t=await _a(e);return Response.json({files:t})}catch(t){return console.error("[API] Error getting source files:",t),Response.json({error:"Failed to get source files",details:t instanceof Error?t.message:String(t)},{status:500})}}async function wg(e,t){try{const[r,a]=await Promise.all([yn(t),_a(e)]),s={};for(const o of r)s[o.filePath]=ug(o,a).length;return Response.json({coverage:s})}catch(r){return console.error("[API] Error getting rule coverage:",r),Response.json({error:"Failed to get rule coverage",details:r instanceof Error?r.message:String(r)},{status:500})}}async function Cg(e,t){try{const r=await br(e),a=[];for(const o of r){const i=oe.join(e,o);try{const c=await he.readFile(i,"utf-8"),d=await he.stat(i),{frontmatter:m,body:u}=Aa(c);m.paths&&m.paths.some(h=>qr(t,h,{matchBase:!0}))&&a.push({filePath:o,content:c,frontmatter:m,body:u,lastModified:d.mtime.toISOString()})}catch{}}const s=a.reduce((o,i)=>o+i.body.length,0);return Response.json({rules:a,totalTextLength:s})}catch(r){return console.error("[API] Error getting rules for path:",r),Response.json({error:"Failed to get rules for path",details:r instanceof Error?r.message:String(r)},{status:500})}}async function Ng({request:e}){const t=fe();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=oe.join(t,".claude","rules");try{const a=await e.json(),{action:s,filePath:o,content:i,lastModified:c}=a;if(!o)return Response.json({error:"Missing required field: filePath"},{status:400});if(s==="mark-reviewed")return await Ys(t,o,!0),console.log(`[API] Rule marked as reviewed: ${o}`),Response.json({success:!0,message:"Rule marked as reviewed",filePath:o});if(s==="mark-unreviewed")return await Ys(t,o,!1),console.log(`[API] Rule marked as unreviewed: ${o}`),Response.json({success:!0,message:"Rule marked as unreviewed",filePath:o});const d=oe.normalize(o);if(d.includes("..")||oe.isAbsolute(d))return Response.json({error:"Invalid file path"},{status:400});const m=oe.join(r,d);switch(s){case"create":case"update":return i?(await he.mkdir(oe.dirname(m),{recursive:!0}),await he.writeFile(m,i,"utf-8"),console.log(`[API] Memory ${s}d: ${o}`),Response.json({success:!0,message:`Memory ${s}d successfully`,filePath:o})):Response.json({error:"Missing required field: content"},{status:400});case"delete":try{await he.unlink(m),console.log(`[API] Memory deleted: ${o}`);const u=oe.dirname(m);try{(await he.readdir(u)).length===0&&u!==r&&await he.rmdir(u)}catch{}return Response.json({success:!0,message:"Memory deleted successfully"})}catch(u){if(u.code==="ENOENT")return Response.json({error:"Memory not found"},{status:404});throw u}default:return Response.json({error:"Invalid action. Must be create, update, or delete"},{status:400})}}catch(a){return console.error("[API] Error managing memory:",a),Response.json({error:"Failed to manage memory",details:a instanceof Error?a.message:String(a)},{status:500})}}const Sg=Object.freeze(Object.defineProperty({__proto__:null,action:Ng,loader:pg},Symbol.toStringTag,{value:"Module"}));async function kg({request:e,context:t}){var o;let r=t.analysisQueue;if(r||(r=await ut()),!r)return W({error:"Queue not initialized"},{status:500});const a=new URL(e.url),s=a.searchParams.get("queryType");if(!s)return W({error:"Missing queryType parameter for GET request"},{status:400});if(s==="job"){const i=a.searchParams.get("jobId");if(!i)return W({error:"Missing jobId parameter for job query"},{status:400});const c=r.getState();if(((o=c.currentlyExecuting)==null?void 0:o.id)===i)return W({jobId:i,status:"running",job:c.currentlyExecuting});const d=c.jobs.find(u=>u.id===i);if(d){const u=c.jobs.indexOf(d);return W({jobId:i,status:"queued",position:u,job:d})}const m=r.getJobResult(i);return m?W({jobId:i,status:m.status==="error"?"failed":"completed",error:m.error}):W({jobId:i,status:"completed"})}if(s==="full"){const i=r.getState(),c=await Promise.all(i.jobs.map(async m=>{const u=[];if(m.entityShas&&m.entityShas.length>0){const h=m.entityShas.map(f=>zt(f)),p=await Promise.all(h);u.push(...p.filter(f=>f!==null))}return{id:m.id,type:m.type,commitSha:m.commitSha,projectSlug:m.projectSlug,queuedAt:m.queuedAt,entities:u,filePaths:m.filePaths}}));let d;if(i.currentlyExecuting){const m=i.currentlyExecuting,u=[];if(m.entityShas&&m.entityShas.length>0){const h=m.entityShas.map(f=>zt(f)),p=await Promise.all(h);u.push(...p.filter(f=>f!==null))}d={id:m.id,type:m.type,commitSha:m.commitSha,projectSlug:m.projectSlug,queuedAt:m.queuedAt,entities:u,filePaths:m.filePaths}}return W({state:{...i,jobsWithEntities:c,currentlyExecutingWithEntities:d}})}return W({error:"Unknown queryType"},{status:400})}async function Eg({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 ut(),console.log("[Queue API] Using global queue")),!r)return console.error("[Queue API] ERROR: Queue not initialized in context"),W({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:c}=r.enqueue(o);return c.catch(d=>{console.error(`[Queue API] Job ${i} failed:`,d)}),W({jobId:i,status:"queued"})}if(s==="resume")return r.resume(),W({status:"resumed"});if(s==="pause")return r.pause(),W({status:"paused"});if(s==="remove"){const{jobId:i}=o;return i?r.removeJob(i)?W({status:"removed",jobId:i}):W({error:"Job not found in queue"},{status:404}):W({error:"Missing jobId parameter"},{status:400})}if(s==="clear"){const i=r.clearQueue();return W({status:"cleared",count:i})}if(s==="reorder"){const{jobId:i,direction:c}=o;return!i||!c?W({error:"Missing jobId or direction parameter"},{status:400}):c!=="up"&&c!=="down"?W({error:'Invalid direction: must be "up" or "down"'},{status:400}):r.reorderJob(i,c)?W({status:"reordered",jobId:i,direction:c}):W({error:"Could not reorder job (not found or at boundary)"},{status:400})}return W({error:"Unknown action"},{status:400})}const Ag=Object.freeze(Object.defineProperty({__proto__:null,action:Eg,loader:kg},Symbol.toStringTag,{value:"Module"})),_g=()=>[{title:"Empty State - CodeYam"},{name:"description",content:"Simulations empty state development view"}],Pg=De(function(){return Ee(),n(fr,{children:l("div",{className:"h-screen bg-[#F8F7F6] flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:l("div",{className:"flex items-center h-full px-6 gap-6",children:[l("div",{className:"flex items-center gap-3 min-w-0",children:[n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),n("h1",{className:"text-lg font-semibold text-black m-0 leading-[26px] shrink-0",children:"Dashboard"}),n("span",{className:"text-xs text-[#626262] font-mono whitespace-nowrap overflow-hidden text-ellipsis min-w-0",children:"codeyam-cli/src/webserver/app/routes/_index.tsx"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[l("div",{className:"flex items-center gap-2 px-[15px] py-0 h-[26px] bg-[#efefef] border border-[#e1e1e1] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#626262]"}),n("span",{className:"text-xs font-semibold text-[#626262]",children:"Not analyzed"})]}),n("button",{className:"px-[15px] py-0 h-[26px] bg-[#005c75] text-white rounded text-xs font-semibold border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]}),l("div",{className:"flex items-center gap-1 text-[10px] text-[#626262] ml-auto",children:[n("span",{className:"leading-[22px]",children:"Next Entity"}),n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M4 8.5H13M13 8.5L8.5 4M13 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})}),n("div",{className:"bg-[#efefef] border-b border-[#efefef] shrink-0",children:l("div",{className:"flex items-center gap-3 h-11 px-[15px]",children:[l("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded bg-[#343434] text-[#efefef] font-semibold h-8",children:["Scenarios",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#cbf3fa] text-[#005c75] min-w-[25px] text-center",children:"0"})]}),l("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded-[9px] text-[#3e3e3e] font-normal",children:["Related Entities",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#e1e1e1] text-[#3e3e3e] min-w-[25px] text-center",children:"5"})]}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Code"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Data Structure"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"History"})]})}),l("div",{className:"flex flex-1 gap-0 min-h-0",children:[n("div",{className:"w-[165px] bg-[#e1e1e1] border-r border-[#c7c7c7] flex items-center justify-center shrink-0",children:n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-5",children:"No Scenarios"})}),n(ri,{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})]})]})})}),Mg=Object.freeze(Object.defineProperty({__proto__:null,default:Pg,meta:_g},Symbol.toStringTag,{value:"Module"})),Tg=()=>[{title:"Settings - CodeYam"},{name:"description",content:"Configure project settings"}];async function jg({request:e}){var t,r;try{const a=await cr();if(!a)return W({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Project configuration not found"});let s=!1;try{const d=await $e();if(d){const{project:m}=await Ie(d);s=((r=(t=m.metadata)==null?void 0:t.labs)==null?void 0:r.simulations)===!0}}catch{}const o=fe()||process.cwd(),i=await dr(o),c=Do(a.projectSlug);return W({config:a,secrets:{GROQ_API_KEY:i.GROQ_API_KEY||"",ANTHROPIC_API_KEY:i.ANTHROPIC_API_KEY||"",OPENAI_API_KEY:i.OPENAI_API_KEY||""},versionInfo:c,simulationsEnabled:s,error:null})}catch(a){return console.error("Failed to load config:",a),W({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Failed to load configuration"})}}function Ig(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 $g({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"),c=t.get("pathsToIgnore"),d=t.get("memorySettings");let m;if(r)try{m=JSON.parse(r)}catch{return W({success:!1,error:"Invalid universalMocks JSON format",requiresRestart:!1},{status:400})}let u;if(a)try{u=JSON.parse(a)}catch{return W({success:!1,error:"Invalid startCommands JSON format",requiresRestart:!1},{status:400})}let h;c&&(h=c.split(",").map(x=>x.trim()).map(x=>x.startsWith('"')&&x.endsWith('"')||x.startsWith("'")&&x.endsWith("'")?x.slice(1,-1):x).filter(x=>x.length>0));let p;if(d)try{p=JSON.parse(d)}catch{return W({success:!1,error:"Invalid memorySettings JSON format",requiresRestart:!1},{status:400})}let f;if(u){const x=await cr();x!=null&&x.webapps&&(f=x.webapps.map((v,b)=>{if(u[b]!==void 0){const w=Ig(u[b]);return{...v,startCommand:w}}return v}))}if(!await _o({universalMocks:m,pathsToIgnore:h,webapps:f,memory:p}))return W({success:!1,error:"Failed to update configuration",requiresRestart:!1},{status:500});let y=!1;if(s!==void 0||o!==void 0||i!==void 0){const x=fe()||process.cwd(),v=await dr(x);y=s!==void 0&&s!==(v.GROQ_API_KEY||"")||o!==void 0&&o!==(v.ANTHROPIC_API_KEY||"")||i!==void 0&&i!==(v.OPENAI_API_KEY||""),await xd(x,{...v,GROQ_API_KEY:s||void 0,ANTHROPIC_API_KEY:o||void 0,OPENAI_API_KEY:i||void 0},!0)}return W({success:!0,error:null,requiresRestart:y})}catch(t){return console.log("[Settings Action] Failed to save config:",t),W({success:!1,error:"Failed to save configuration",requiresRestart:!1},{status:500})}}function Bs(e){if(!e)return"";const t=[e.command];return e.args&&e.args.length>0&&t.push(...e.args),t.join(" ")}function Us({mock:e,onSave:t,onCancel:r}){const[a,s]=_(e.entityName),[o,i]=_(e.filePath),[c,d]=_(e.content);return l("div",{className:"space-y-3",children:[l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Entity Name"}),n("input",{type:"text",value:a,onChange:u=>s(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., determineDatabaseType"})]}),l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path"}),n("input",{type:"text",value:o,onChange:u=>i(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., packages/database/src/lib/kysely/db.ts"})]}),l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:c,onChange:u=>d(u.target.value),rows:6,className:"w-full px-3 py-2 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., function determineDatabaseType() { return 'postgresql' }"})]}),l("div",{className:"flex gap-2 justify-end",children:[n("button",{type:"button",onClick:r,className:"px-4 py-2 bg-gray-200 text-gray-800 border-none rounded text-sm cursor-pointer hover:bg-gray-300",children:"Cancel"}),n("button",{type:"button",onClick:()=>{if(!a.trim()||!o.trim()||!c.trim()){alert("All fields are required");return}t({entityName:a,filePath:o,content:c})},className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Save"})]})]})}function Rg(e){try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}const Dg=De(function(){var ke,Se,_e,Te,ve;const{config:t,secrets:r,versionInfo:a,simulationsEnabled:s,error:o}=Be(),i=Yi(),c=Ee(),d=it(),[m,u]=_(s?"project-metadata":"memory");tt({source:"settings-page"});const[h,p]=_((t==null?void 0:t.universalMocks)||[]),[f,g]=_(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[y,x]=_(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[v,b]=_((r==null?void 0:r.GROQ_API_KEY)||""),[w,C]=_((r==null?void 0:r.ANTHROPIC_API_KEY)||""),[k,N]=_((r==null?void 0:r.OPENAI_API_KEY)||""),[E,S]=_(!1),[M,F]=_(!1),[L,P]=_(!1),[T,$]=_(!1),[I,J]=_(!1),[V,U]=_(!1),[z,Y]=_(null),[R,A]=_(!1),[G,B]=_({}),[H,re]=_(((ke=t==null?void 0:t.memory)==null?void 0:ke.conversationReflection)??!0),[O,j]=_(((Se=t==null?void 0:t.memory)==null?void 0:Se.ruleMaintenance)??!0),[D,q]=_(((_e=t==null?void 0:t.memory)==null?void 0:_e.promptModel)??"haiku");ee(()=>{var Q,me,ye,Ct;if(t){p(t.universalMocks||[]);const ue=(t.pathsToIgnore||[]).join(", ");g(ue),x(ue);const Fe={};(Q=t.webapps)==null||Q.forEach((Oe,Vt)=>{Oe.startCommand&&(Fe[Vt]=Bs(Oe.startCommand))}),B(Fe),re(((me=t.memory)==null?void 0:me.conversationReflection)??!0),j(((ye=t.memory)==null?void 0:ye.ruleMaintenance)??!0),q(((Ct=t.memory)==null?void 0:Ct.promptModel)??"haiku")}r&&(b(r.GROQ_API_KEY||""),C(r.ANTHROPIC_API_KEY||""),N(r.OPENAI_API_KEY||""))},[t,r]),ee(()=>{if(i!=null&&i.success){$(!0);const Q=setTimeout(()=>$(!1),3e3);return()=>clearTimeout(Q)}},[i]),ee(()=>{if(c.state==="idle"&&c.data&&!V){console.log("[Settings] Fetcher data:",c.data);const Q=c.data;if(Q.success){console.log("[Settings] Save successful, revalidating..."),$(!0),U(!0),(f!==y||Q.requiresRestart)&&J(!0),d.revalidate();const me=setTimeout(()=>{$(!1),U(!1)},3e3);return()=>clearTimeout(me)}}},[c.state,c.data,V,d,f,y]);const te=Q=>{Q.preventDefault();const me=new FormData(Q.currentTarget);me.set("universalMocks",JSON.stringify(h)),me.set("startCommands",JSON.stringify(G)),me.set("memorySettings",JSON.stringify({conversationReflection:H,ruleMaintenance:O,promptModel:D})),console.log("[Settings] Submitting form data:",{universalMocks:me.get("universalMocks"),startCommands:me.get("startCommands"),openAiApiKey:me.get("openAiApiKey")?"***":"(empty)"}),c.submit(me,{method:"post"})},de=Q=>{p([...h,Q]),A(!1)},ge=(Q,me)=>{const ye=[...h];ye[Q]=me,p(ye),Y(null)},pe=Q=>{p(h.filter((me,ye)=>ye!==Q))};if(o)return l("div",{className:"max-w-6xl mx-auto p-8 font-sans",children:[n("header",{className:"mb-6 pb-4 border-b border-gray-200",children:n("div",{className:"flex justify-between items-center",children:n("h1",{className:"text-4xl font-bold text-gray-900",children:"Settings"})})}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4",children:n("p",{className:"text-red-700",children:o})})]});const be=[{id:"project-metadata",label:"Project Metadata"},{id:"ai-provider",label:"AI Provider Configuration"},{id:"commands",label:"Commands"},{id:"paths-to-ignore",label:"Paths To Ignore"},{id:"universal-mocks",label:"Universal Mocks"},{id:"memory",label:"Memory"},{id:"current-configuration",label:"Current Configuration"}],Ce=s?be:be.filter(Q=>Q.id==="memory");return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-6 sm:px-12 lg:px-20 pt-8 pb-12 font-sans",children:[l("div",{className:"mb-8 flex justify-between items-start",children:[l("div",{children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Settings"}),n("p",{className:"text-[15px] text-gray-500",children:"Project Configuration"})]}),n("button",{type:"submit",form:"settings-form",disabled:c.state==="submitting",className:"px-6 py-2 bg-[#005C75] text-white border-none rounded text-sm font-medium cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 hover:bg-[#004a5d] whitespace-nowrap",children:c.state==="submitting"?"Saving...":"Save Settings"})]}),(T||I||(i==null?void 0:i.error)||c.data&&typeof c.data=="object"&&"error"in c.data)&&l("div",{className:"mb-4 space-y-3",children:[T&&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!"}),I&&l("div",{className:"text-amber-700 text-sm font-medium bg-amber-50 border border-amber-200 rounded px-4 py-2",children:[n("div",{children:"Settings changed. Please restart CodeYam for changes to take effect:"}),l("div",{className:"flex items-center gap-2 mt-1",children:[n("code",{className:"bg-amber-100 px-2 py-1 rounded text-xs",children:"codeyam stop && codeyam"}),n(Ht,{content:"codeyam stop && codeyam",className:"px-2 py-1 text-xs bg-amber-200 hover:bg-amber-300 text-amber-800 rounded border-none transition-colors"})]})]}),(i==null?void 0:i.error)&&n("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:i.error}),(()=>{if(c.data&&typeof c.data=="object"&&"error"in c.data){const Q=c.data;return typeof Q.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:Q.error}):null}return null})()]}),l("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8 items-start",children:[n("nav",{className:"w-full lg:w-64 flex-shrink-0",children:n("ul",{className:"flex lg:flex-col overflow-x-auto gap-1",children:Ce.map(Q=>n("li",{children:n("button",{type:"button",onClick:()=>u(Q.id),className:`w-full text-left px-3 lg:px-0 py-2.5 text-sm transition-colors cursor-pointer whitespace-nowrap ${m===Q.id?"text-[#005C75] font-medium":"text-gray-600 hover:text-gray-900"}`,children:Q.label})},Q.id))})}),n("div",{className:"flex-1 min-w-0 -mt-2",children:l("form",{id:"settings-form",onSubmit:te,className:"space-y-6",children:[m==="project-metadata"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Project Metadata"}),l("div",{className:"mb-6",children:[n("label",{className:"block mb-2 font-medium text-gray-700",children:"Web Applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-3",children:t.webapps.map((Q,me)=>{var ye;return n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:l("div",{className:"space-y-2 text-sm",children:[l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:Q.path==="."?"Root":Q.path})]}),Q.appDirectory&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:Q.appDirectory})]}),l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:Q.framework})]}),Q.startCommand&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",l("span",{className:"text-gray-900 font-mono text-xs",children:[Q.startCommand.command," ",(ye=Q.startCommand.args)==null?void 0:ye.join(" ")]})]})]})},me)})}):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`."})]})]}),m==="ai-provider"&&l("div",{children:[n("h3",{className:"text-lg font-semibold text-gray-800 mb-4",children:"AI Provider API Keys"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure API keys for AI-powered analysis. Choose the provider that best fits your needs."}),l("div",{className:"space-y-6",children:[l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:l("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Groq"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Lightning-fast inference with industry-leading speed. Groq's LPU architecture delivers exceptional performance for real-time AI applications with competitive pricing."}),l("div",{className:"flex flex-wrap gap-2 text-xs",children:[l("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$0.10/1M tokens"]}),l("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 850 tokens/s"]}),l("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Less reliable, but capable of producing reasonable results"]})]})]})}),l("div",{className:"mt-4",children:[n("label",{htmlFor:"groqApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),l("div",{className:"relative",children:[n("input",{type:E?"text":"password",id:"groqApiKey",name:"groqApiKey",value:v,onChange:Q=>b(Q.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:()=>S(!E),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:E?"Hide":"Show"})]})]})]}),l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:l("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Anthropic Claude"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Advanced reasoning and coding capabilities with superior context understanding. Claude excels at complex analysis tasks and provides highly accurate results with detailed explanations."}),l("div",{className:"flex flex-wrap gap-2 text-xs",children:[l("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$3.00/1M tokens"]}),l("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 120 tokens/s"]}),l("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),l("div",{className:"mt-4",children:[n("label",{htmlFor:"anthropicApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),l("div",{className:"relative",children:[n("input",{type:M?"text":"password",id:"anthropicApiKey",name:"anthropicApiKey",value:w,onChange:Q=>C(Q.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:()=>F(!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"})]})]})]}),l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:l("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"OpenAI GPT"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Industry-standard AI with broad capabilities and extensive ecosystem. GPT models offer reliable performance across diverse tasks with good balance of speed and quality."}),l("div",{className:"flex flex-wrap gap-2 text-xs",children:[l("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$2.50/1M tokens"]}),l("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 150 tokens/s"]}),l("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),l("div",{className:"mt-4",children:[n("label",{htmlFor:"openAiApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),l("div",{className:"relative",children:[n("input",{type:L?"text":"password",id:"openAiApiKey",name:"openAiApiKey",value:k,onChange:Q=>N(Q.target.value),placeholder:"sk-...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>P(!L),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:L?"Hide":"Show"})]})]})]})]})]}),m==="commands"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Commands"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure start commands for your web applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-4",children:t.webapps.map((Q,me)=>l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[l("div",{className:"mb-4",children:[n("div",{className:"text-base font-semibold text-gray-900 mb-1",children:Q.path==="."?"Root":Q.path}),n("div",{className:"text-sm text-gray-600",children:Q.framework})]}),l("div",{children:[n("label",{htmlFor:`startCommand-${me}`,className:"block text-sm font-medium text-gray-700 mb-2",children:"Start Command"}),n("input",{type:"text",id:`startCommand-${me}`,name:`startCommand-${me}`,value:G[me]||"",onChange:ye=>B({...G,[me]:ye.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"})]})]},me))}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"})]}),m==="paths-to-ignore"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Paths To Ignore"}),n("input",{type:"text",id:"pathsToIgnore",name:"pathsToIgnore",value:f,onChange:Q=>g(Q.target.value),placeholder:"e.g., __tests__, \\.test\\.ts$, ^background (no quotes needed)",className:"w-full px-3 py-3 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-2 focus:ring-[#005C75]/10"}),l("p",{className:"mt-2 text-sm text-gray-600",children:["Comma-separated list of regex patterns for paths to ignore during file watching. Examples:"," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"__tests__"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"\\.test\\.tsx?$"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"^background"}),n("br",{}),n("span",{className:"text-xs text-gray-500 mt-1 inline-block",children:"Note: Files matching patterns in .gitignore are also automatically ignored"})]})]}),m==="universal-mocks"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Universal Mocks"}),n("p",{className:"mb-3 text-sm text-gray-600",children:"Mock functions that will be applied across all entity simulations"}),h.length===0?l("div",{className:"mb-4",children:[n("div",{className:"text-sm text-gray-500 mb-3",children:"No universal mocks configured"}),n("button",{type:"button",onClick:()=>A(!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((Q,me)=>n("div",{className:"p-4 bg-gray-50 rounded border border-gray-200",children:z===me?n(Us,{mock:Q,onSave:ye=>ge(me,ye),onCancel:()=>Y(null)}):n(le,{children:l("div",{className:"flex justify-between items-start mb-2",children:[l("div",{className:"flex-1",children:[n("div",{className:"font-medium text-gray-800 mb-1",children:Q.entityName}),n("div",{className:"text-sm text-gray-600 mb-2",children:Q.filePath}),n("pre",{className:"text-xs bg-white p-2 rounded border border-gray-200 overflow-x-auto",children:Q.content})]}),l("div",{className:"flex gap-2 ml-3",children:[n("button",{type:"button",onClick:()=>Y(me),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:()=>pe(me),className:"px-3 py-1 bg-red-600 text-white border-none rounded text-sm cursor-pointer hover:bg-red-700",children:"Delete"})]})]})})},me))}),h.length>0&&n("button",{type:"button",onClick:()=>A(!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"})]}),m==="memory"&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Memory"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure how CodeYam reflects on conversations and maintains rules between sessions."}),l("div",{className:"space-y-6",children:[n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"flex-1 mr-4",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Conversation Reflection"}),n("p",{className:"text-sm text-gray-600",children:"After each conversation, an agent reviews the session for architectural decisions, tribal knowledge, confusion, or corrections that future sessions would benefit from knowing. It creates or updates Claude Rules based on what it learns."})]}),n("button",{type:"button",role:"switch","aria-checked":H,onClick:()=>re(!H),className:`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${H?"bg-[#005C75]":"bg-gray-200"}`,children:n("span",{className:`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${H?"translate-x-5":"translate-x-0"}`})})]})}),n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"flex-1 mr-4",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Rule Maintenance"}),n("p",{className:"text-sm text-gray-600",children:"After each conversation, an agent checks if any existing Claude Rules have become stale based on recent code changes. It reviews the rule content against file diffs and updates rules that are out of date."})]}),n("button",{type:"button",role:"switch","aria-checked":O,onClick:()=>j(!O),className:`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${O?"bg-[#005C75]":"bg-gray-200"}`,children:n("span",{className:`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${O?"translate-x-5":"translate-x-0"}`})})]})}),l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Memory Prompt Model"}),n("p",{className:"text-sm text-gray-600 mb-4",children:"Choose the Claude model used for conversation reflection and rule maintenance tasks."}),n("div",{className:"space-y-3",children:[{value:"haiku",label:"Haiku",badge:"Default, Recommended",description:"Fastest and cheapest. Good for routine reflection tasks."},{value:"sonnet",label:"Sonnet",badge:null,description:"Balanced speed and quality. Better at nuanced rule writing."},{value:"opus",label:"Opus",badge:null,description:"Highest quality. Best for complex architectural decisions. Costs significantly more."}].map(Q=>l("label",{className:`flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${D===Q.value?"border-[#005C75] bg-[#005C75]/5":"border-gray-200 hover:border-gray-300"}`,children:[n("input",{type:"radio",name:"promptModel",value:Q.value,checked:D===Q.value,onChange:()=>q(Q.value),className:"mt-1 accent-[#005C75]"}),l("div",{children:[l("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-gray-900",children:Q.label}),Q.badge&&n("span",{className:"px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:Q.badge})]}),n("p",{className:"text-sm text-gray-600 mt-0.5",children:Q.description})]})]},Q.value))})]})]})]}),m==="current-configuration"&&l("div",{className:"space-y-6",children:[t&&l("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Current Configuration"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded mb-6",children:l("div",{className:"space-y-2 text-sm",children:[t.projectSlug&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Project Slug:"})," ",n("span",{className:"text-gray-900",children:t.projectSlug})]}),t.packageManager&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Package Manager:"})," ",n("span",{className:"text-gray-900",children:t.packageManager})]})]})}),t.webapps&&t.webapps.length>0&&l("div",{children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Web Applications"}),n("div",{className:"space-y-3",children:t.webapps.map((Q,me)=>n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:l("div",{className:"space-y-2 text-sm",children:[l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:Q.path==="."?"Root":Q.path})]}),Q.appDirectory&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:Q.appDirectory})]}),l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:Q.framework})]}),Q.startCommand&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",n("span",{className:"text-gray-900 font-mono text-xs",children:Bs(Q.startCommand)})]})]})},me))})]})]}),a&&l("div",{className:"mt-6",children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Version Information"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:l("div",{className:"space-y-2 text-sm",children:[a.webserverVersion&&l("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&&l("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||((Te=a.templateVersion.gitCommit)==null?void 0:Te.slice(0,7))||"unknown"}),a.templateVersion.buildTimestamp&&l("span",{className:"text-gray-500 ml-2",children:["(built"," ",Rg(a.templateVersion.buildTimestamp),")"]})]}),a.cachedAnalyzerVersion&&l("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||((ve=a.cachedAnalyzerVersion.gitCommit)==null?void 0:ve.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)&&l("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"text-gray-500 italic",children:"Not initialized - will be created on first analysis"})]})]})})]})]})]})})]}),R&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:l("div",{className:"bg-white rounded-lg max-w-2xl w-full p-6",children:[n("h2",{className:"text-2xl font-bold mb-4 text-gray-900",children:"Add Universal Mock"}),n(Us,{mock:{entityName:"",filePath:"",content:""},onSave:de,onCancel:()=>A(!1)})]})})]})})}),Lg=Object.freeze(Object.defineProperty({__proto__:null,action:$g,default:Dg,loader:jg,meta:Tg},Symbol.toStringTag,{value:"Module"}));async function Fg({params:e}){const t=e["*"];if(!t)return new Response("Static path is required",{status:400});const r=fe();if(!r)return new Response("Project root not found",{status:500});const s=oe.extname(t)!==""?t:`${t}.html`,o=oe.join(r,".codeyam","captures","static",s);try{await he.access(o);let i=await he.readFile(o);const c=oe.extname(o).toLowerCase();let d="application/octet-stream";if(c===".html"){d="text/html";let m=i.toString("utf-8");const u=m.match(/<script>(window\.__remixContext\s*=\s*\{[\s\S]*?\});?<\/script>/i);if(u)try{const p=u[1].match(/=\s*(\{[\s\S]*\})/);if(p){const f=JSON.parse(p[1]);f.isSpaMode=!0,f.future&&(f.future.v3_lazyRouteDiscovery=!1);const g=`<script>window.__remixContext = ${JSON.stringify(f)};<\/script>`;m=m.replace(u[0],g)}}catch(h){console.error("[Static] Failed to parse Remix context:",h)}i=Buffer.from(m,"utf-8")}else c===".js"||c===".mjs"?d="application/javascript":c===".css"?d="text/css":c===".json"?d="application/json":c===".png"?d="image/png":c===".jpg"||c===".jpeg"?d="image/jpeg":c===".svg"?d="image/svg+xml":c===".woff"?d="font/woff":c===".woff2"?d="font/woff2":c===".ttf"&&(d="font/ttf");return new Response(i,{status:200,headers:{"Content-Type":d,"Cache-Control":"public, max-age=3600","X-Frame-Options":"SAMEORIGIN"}})}catch{return new Response("Static file not found",{status:404})}}const Og=Object.freeze(Object.defineProperty({__proto__:null,loader:Fg},Symbol.toStringTag,{value:"Module"}));function zg(e,t,r=10){var d;const a=new Map,s=m=>m.entityType==="visual"||m.entityType==="library";for(const m of e)s(m)&&a.set(m.sha,{entity:m,depth:0});const o=new Map;for(const m of t){const u=(d=m.metadata)==null?void 0:d.importedBy;if(u)for(const h of Object.keys(u))for(const p of Object.keys(u[h])){const{shas:f}=u[h][p];for(const g of f)o.has(m.sha)||o.set(m.sha,new Set),o.get(m.sha).add(g)}}const i=[],c=new Set;for(const m of e)i.push({sha:m.sha,depth:0}),c.add(m.sha);for(;i.length>0;){const{sha:m,depth:u}=i.shift();if(u>=r)continue;const h=o.get(m);if(h)for(const p of h){if(c.has(p))continue;c.add(p);const f=t.find(g=>g.sha===p);if(f){if(s(f)){const g=u+1,y=a.get(p);(!y||g<y.depth)&&a.set(p,{entity:f,depth:g})}i.push({sha:p,depth:u+1})}}}return Array.from(a.values()).sort((m,u)=>m.depth!==u.depth?m.depth-u.depth:m.entity.name.localeCompare(u.entity.name))}function Zn(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 m,u;const c=((m=o.metadata)==null?void 0:m.editedAt)||o.createdAt||"";return(((u=i.metadata)==null?void 0:u.editedAt)||i.createdAt||"").localeCompare(c)});r.push(s[0])}return r}function mi(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 m,u;return a.has(d.filePath)&&((m=d.metadata)==null?void 0:m.isUncommitted)&&!((u=d.metadata)!=null&&u.isSuperseded)}),c=Zn(i);r.set(s.path,{status:s,entities:o,editedEntities:c})}return r}function Yg(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),c=Zn(i);a.set(o.path,{status:o,entities:c})}return a}const s=new Map;for(const o of r.fileComparisons){const i=new Set;for(const c of o.newEntities)i.add(c.name);for(const c of o.modifiedEntities)i.add(c.name);for(const c of o.deletedEntities)i.add(c.name);i.size>0&&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 c=i?t.filter(m=>(m.filePath===o.path||o.status==="renamed"&&o.oldPath&&m.filePath===o.oldPath)&&i.has(m.name)):[],d=Zn(c);a.set(o.path,{status:o,entities:d})}}return a}function Bg(e,t){const r=new Map,a=hi(e,t);for(const s of a){const i=zg([s],t).filter(({depth:c})=>c>0);r.set(s.sha,i)}return r}function hi(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 Zn(a)}function Ug({recentSimulations:e}){const t=ae(()=>{const r=new Map;return e.forEach(a=>{const s=a.entitySha,o=r.get(s);o?o.push(a):r.set(s,[a])}),Array.from(r.entries()).map(([a,s])=>({entitySha:a,entityName:s[0].entityName,scenarios:s}))},[e]);return l("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:l("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:e.length>0?`Latest ${e.length} captured screenshot${e.length!==1?"s":""}`:"No simulations captured yet"})]})}),e.length>0?l(le,{children:[n("div",{className:"space-y-6 mb-5",children:t.map(r=>l("div",{children:[l("div",{className:"mb-3 flex items-center gap-2",children:[n("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center bg-purple-100",children:n(an,{size:16,style:{color:"#8B5CF6"}})}),n(se,{to:`/entity/${r.entitySha}`,className:"text-sm font-semibold text-gray-900 no-underline hover:text-gray-700 transition-colors",children:r.entityName})]}),n("div",{className:"grid grid-cols-4 gap-3",children:r.scenarios.map((a,s)=>n(se,{to:a.scenarioId?`/entity/${a.entitySha}/scenarios/${a.scenarioId}`:`/entity/${a.entitySha}`,className:"aspect-4/3 border border-gray-200 rounded-lg overflow-hidden bg-gray-50 transition-all flex items-center justify-center hover:scale-105",onMouseEnter:o=>{o.currentTarget.style.borderColor="#005C75",o.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.2)"},onMouseLeave:o=>{o.currentTarget.style.borderColor="#E5E7EB",o.currentTarget.style.boxShadow="none"},title:a.scenarioName,children:n(Ye,{screenshotPath:a.screenshotPath,alt:a.scenarioName,className:"max-w-full max-h-full object-contain object-center"})},a.scenarioId||`${a.entitySha}-${s}`))})]},r.entitySha))}),n(se,{to:"/simulations",className:"block text-center p-3 rounded-lg no-underline font-semibold text-sm transition-all",style:{color:"#005C75",backgroundColor:"#F6F9FC"},onMouseEnter:r=>r.currentTarget.style.backgroundColor="#EEF4F8",onMouseLeave:r=>r.currentTarget.style.backgroundColor="#F6F9FC",children:"View All Recent Simulations →"})]}):l("div",{className:"py-12 px-6 text-center rounded-lg w-full flex flex-col items-center justify-center min-h-50 border border-dashed",style:{backgroundColor:"#F2F7F8",borderColor:"#BBCCD3"},children:[n("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:n(an,{size:24,style:{color:"#7A9BA5"},strokeWidth:1.5})}),n("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No simulations captured yet."}),l("p",{className:"text-xs m-0 mt-2",style:{color:"#7A9BA5"},children:["Trigger an analysis from the"," ",n(se,{to:"/git",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Git"})," ","or"," ",n(se,{to:"/files",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Files"})," ","page."]})]})]})}const Wg="/assets/codeyam-name-logo-CvKwUgHo.svg",Hg=()=>[{title:"Dashboard - CodeYam"},{name:"description",content:"CodeYam project dashboard"}];async function Vg({request:e,context:t}){var r,a,s,o;try{const i=await $e();if(i){const{project:P}=await Ie(i);if(!(((a=(r=P.metadata)==null?void 0:r.labs)==null?void 0:a.simulations)??!1))return Bi("/memory")}const c=t.analysisQueue,d=c?c.getState():{paused:!1,jobs:[]},[m,u]=await Promise.all([pn(),Bt()]),h=Go(),p=m?mi(h,m):new Map,f=Array.from(p.entries()).sort((P,T)=>P[0].localeCompare(T[0])),g=(m==null?void 0:m.length)||0,y=(m==null?void 0:m.filter(P=>P.entityType==="visual").length)||0,x=(m==null?void 0:m.filter(P=>P.entityType==="library").length)||0,v=m?hi(h,m):[],b=v.length,w=(m==null?void 0:m.filter(P=>(P.analyses??[]).filter(T=>T.scenarios&&T.scenarios.length>0).length>0).length)||0,C=(m==null?void 0:m.reduce((P,T)=>{var I,J,V;const $=((V=(J=(I=T.analyses)==null?void 0:I[0])==null?void 0:J.scenarios)==null?void 0:V.length)||0;return P+$},0))||0,k=(m==null?void 0:m.reduce((P,T)=>{var J,V;const I=(((V=(J=T.analyses)==null?void 0:J[0])==null?void 0:V.scenarios)||[]).filter(U=>{var z,Y;return(Y=(z=U.metadata)==null?void 0:z.screenshotPaths)==null?void 0:Y[0]}).length;return P+I},0))||0,N=[];m==null||m.forEach(P=>{var $;const T=($=P.analyses)==null?void 0:$[0];T!=null&&T.scenarios&&T.scenarios.filter(J=>{var V;return!((V=J.metadata)!=null&&V.sameAsDefault)}).forEach(J=>{var U,z;const V=(z=(U=J.metadata)==null?void 0:U.screenshotPaths)==null?void 0:z[0];V&&N.push({entitySha:P.sha,entityName:P.name,scenarioId:J.id,scenarioName:J.name,screenshotPath:V,createdAt:T.createdAt||""})})}),N.sort((P,T)=>new Date(T.createdAt).getTime()-new Date(P.createdAt).getTime());const E=N.slice(0,16),S=(m==null?void 0:m.filter(P=>P.entityType==="visual").filter(P=>{var I,J;const T=(I=P.analyses)==null?void 0:I[0];return!((J=T==null?void 0:T.scenarios)==null?void 0:J.some(V=>{var U,z;return(z=(U=V.metadata)==null?void 0:U.screenshotPaths)==null?void 0:z[0]}))}).slice(0,8))||[],M=(s=u==null?void 0:u.metadata)==null?void 0:s.currentRun,F=((o=M==null?void 0:M.currentEntityShas)==null?void 0:o.length)||0,L=d.jobs.length||0;return W({stats:{totalEntities:g,visualEntities:y,libraryEntities:x,uncommittedEntities:b,entitiesWithAnalyses:w,totalScenarios:C,capturedScreenshots:k,currentlyAnalyzing:F,filesOnQueue:L},uncommittedFiles:f,uncommittedEntitiesList:v,recentSimulations:E,visualEntitiesForSimulation:S,projectSlug:i,queueState:d,currentCommit:u})}catch(i){return console.error("Failed to load dashboard data:",i),W({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 Jg=De(function(){var z,Y;const{stats:t,uncommittedFiles:r,uncommittedEntitiesList:a,recentSimulations:s,visualEntitiesForSimulation:o,projectSlug:i,queueState:c,currentCommit:d}=Be(),m=Ee(),u=it(),{showToast:h}=ua();tt({source:"dashboard"});const[p,f]=_(new Set),[g,y]=_(null),[x,v]=_(!1),[b,w]=_(!1),{lastLine:C,isCompleted:k}=bt(i,!!g),{simulatingEntity:N,scenarios:E,scenarioStatuses:S,allScenariosCaptured:M}=ae(()=>{var j,D;const R={simulatingEntity:null,scenarios:[],scenarioStatuses:[],allScenariosCaptured:!1};if(!g)return R;const A=o==null?void 0:o.find(q=>q.sha===g);if(!A)return R;const G=(j=A.analyses)==null?void 0:j[0],B=(G==null?void 0:G.scenarios)||[],H=((D=G==null?void 0:G.status)==null?void 0:D.scenarios)||[],re=H.filter(q=>q.screenshotFinishedAt).length,O=B.length>0&&re===B.length;return{simulatingEntity:A,scenarios:B,scenarioStatuses:H,allScenariosCaptured:O}},[g,o]);ee(()=>{(k||M)&&y(null)},[k,M]);const F=(z=d==null?void 0:d.metadata)==null?void 0:z.currentRun,L=new Set((F==null?void 0:F.currentEntityShas)||[]),P=new Set(c.jobs.flatMap(R=>R.entityShas||[])),T=new Set(((Y=c.currentlyExecuting)==null?void 0:Y.entityShas)||[]),$=a.filter(R=>R.entityType==="visual"||R.entityType==="library"),I=$.filter(R=>!L.has(R.sha)&&!P.has(R.sha)&&!T.has(R.sha)),J=()=>{if(I.length===0){h("All entities are already queued or analyzing","info",3e3);return}const R=I.map(A=>A.sha);w(!0),h(`Starting analysis for ${I.length} entities...`,"info",3e3),m.submit({entityShas:R.join(",")},{method:"post",action:"/api/analyze"})};ee(()=>{if(m.state==="idle"&&m.data){const R=m.data;R.success?(console.log("[Analyze All] Success:",R.message),h(`Analysis started for ${R.entityCount} entities in ${R.fileCount} files. Watch the logs for progress.`,"success",6e3),w(!1)):R.error&&(console.error("[Analyze All] Error:",R.error),h(`Error: ${R.error}`,"error",8e3),w(!1))}},[m.state,m.data,h]);const V=R=>{f(A=>{const G=new Set(A);return G.has(R)?G.delete(R):G.add(R),G})},U=[{label:"Total Entities",value:t.totalEntities,iconType:"folder",link:"/files",color:"#005C75",tooltip:"In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested."},{label:"Analyzed Entities",value:t.entitiesWithAnalyses,iconType:"check",link:"/simulations",color:"#10B981",tooltip:"Entities that have been analyzed by CodeYam and have generated scenarios."},{label:"Visual Components",value:t.visualEntities,iconType:"image",link:"/files?entityType=visual",color:"#8B5CF6",tooltip:"React components and visual elements that can be rendered and captured as screenshots."},{label:"Library Functions",value:t.libraryEntities,iconType:"code-xml",link:"/files?entityType=library",color:"#0DBFE9",tooltip:"Reusable functions and utilities that can be independently tested."}];return n("div",{className:"bg-cygray-10 min-h-screen",children:l("div",{className:"px-20 pt-8 pb-12",children:[l("header",{className:"mb-8 flex justify-between items-center",children:[l("div",{className:"flex items-center gap-4",children:[n("img",{src:Wg,alt:"CodeYam",className:"h-3.5"}),n("span",{className:"text-gray-400 text-sm",children:"|"}),n("h1",{className:"text-sm font-mono font-normal text-gray-400 m-0",children:i?i.replace(/-/g," ").replace(/\b\w/g,R=>R.toUpperCase()):"Project"})]}),u.state==="loading"&&n("div",{className:"text-blue-600 text-sm font-medium animate-pulse",children:"🔄 Updating..."})]}),n("div",{className:"flex items-center justify-between gap-3",children:U.map((R,A)=>n(se,{to:R.link,className:"flex-1 bg-white rounded-xl border border-gray-200 overflow-hidden flex transition-all hover:shadow-lg no-underline cursor-pointer",style:{borderLeft:`4px solid ${R.color}`},children:l("div",{className:"px-6 py-6 flex flex-col gap-3 flex-1",children:[l("div",{className:"flex md:justify-between md:items-start md:flex-row flex-col",children:[l("div",{className:"flex items-center gap-1.5 group relative",children:[n("span",{className:"text-xs text-gray-700 font-medium font-mono uppercase",children:R.label}),l("svg",{className:"w-3 h-3 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[n("circle",{cx:"12",cy:"12",r:"10",strokeWidth:"2"}),n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 16v-4m0-4h.01"})]}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:[R.tooltip,n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 sm:hidden md:flex",style:{color:R.color},children:"View All →"})]}),l("div",{className:"flex flex-col gap-2",children:[l("div",{className:"flex items-center gap-3",children:[l("div",{className:"rounded-lg p-2 leading-none shrink-0",style:{backgroundColor:`${R.color}15`},children:[R.iconType==="folder"&&n(ml,{size:20,style:{color:R.color}}),R.iconType==="check"&&n(sa,{size:20,style:{color:R.color}}),R.iconType==="image"&&n(an,{size:20,style:{color:R.color}}),R.iconType==="code-xml"&&n(hl,{size:20,style:{color:R.color}})]}),n("div",{className:"text-3xl font-semibold font-mono text-gray-900 leading-none",children:R.value.toLocaleString("en-US")})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 md:hidden",style:{color:R.color},children:"View All →"})]})]})},A))}),l("div",{className:"mt-12 grid gap-8 items-start",style:{gridTemplateColumns:"repeat(auto-fit, minmax(500px, 1fr))"},children:[l("section",{id:"uncommitted",className:"bg-white border border-gray-200 rounded-xl p-6",children:[l("div",{className:"flex justify-between items-start mb-5",children:[l("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Uncommitted Changes"}),n("p",{className:"text-sm text-gray-500 m-0",children:r.length>0?`${r.length} file${r.length!==1?"s":""} with ${a.length} uncommitted entit${a.length!==1?"ies":"y"}`:"No uncommitted changes detected"})]}),$.length>0&&n("button",{onClick:J,disabled:m.state!=="idle"||b||I.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:R=>R.currentTarget.style.backgroundColor="#004560",onMouseLeave:R=>R.currentTarget.style.backgroundColor="#005C75",children:m.state!=="idle"||b?"Starting analysis...":I.length===0?"All Queued":"Analyze All"})]}),r.length>0?n("div",{className:"flex flex-col gap-3",children:r.map(([R,A])=>{const G=p.has(R),B=A.editedEntities||[];return l("div",{className:"bg-white border border-gray-200 border-l-4 rounded-lg overflow-hidden",style:{borderLeftColor:"#005C75"},children:[n("div",{className:"p-4 cursor-pointer select-none transition-colors hover:bg-gray-50",onClick:()=>V(R),role:"button",tabIndex:0,children:l("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-gray-500 text-xs w-4 shrink-0",children:G?"▼":"▶"}),l("svg",{width:"16",height:"20",viewBox:"0 0 12 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"shrink-0",children:[l("g",{clipPath:"url(#clip0_784_10666)",children:[n("path",{d:"M0 2.55857C0 1.14551 1.14551 0 2.55857 0H8.73194L12 3.3616V13.4414C12 14.8545 10.8545 16 9.44143 16H2.55857C1.14551 16 0 14.8545 0 13.4414V2.55857Z",fill:"#DDDDFE"}),n("path",{d:"M8.72656 3.3307H11.9906L8.72656 0V3.3307Z",fill:"#306AFF"}),n("line",{x1:"1.8125",y1:"5.94825",x2:"10.0235",y2:"5.94825",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"8.82715",x2:"6.01207",y2:"8.82715",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"11.7061",x2:"10.0235",y2:"11.7061",stroke:"#306AFF",strokeWidth:"1.27929"})]}),n("defs",{children:n("clipPath",{id:"clip0_784_10666",children:n("rect",{width:"12",height:"16",fill:"white"})})})]}),l("div",{className:"flex-1 min-w-0",children:[n("span",{className:"font-normal text-gray-900 text-sm block truncate",children:R}),l("span",{className:"text-xs text-gray-500",children:[B.length," entit",B.length!==1?"ies":"y"]})]})]})}),G&&n("div",{className:"border-t border-gray-200 bg-gray-50 p-3 flex flex-col gap-2",children:B.length>0?B.map(H=>{const re=L.has(H.sha),O=P.has(H.sha)||T.has(H.sha);return l(se,{to:`/entity/${H.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:j=>j.currentTarget.style.borderColor="#005C75",onMouseLeave:j=>j.currentTarget.style.borderColor="inherit",children:[l("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center",style:{backgroundColor:H.entityType==="visual"?"#8B5CF615":H.entityType==="library"?"#6366F1":"#EC4899"},children:[H.entityType==="visual"&&n(an,{size:16,style:{color:"#8B5CF6"}}),H.entityType==="library"&&n(Qs,{size:16,className:"text-white"}),H.entityType==="other"&&n(pl,{size:16,className:"text-white"})]}),l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2 mb-0.5",children:[n("div",{className:"font-semibold text-gray-900 text-sm",children:H.name}),H.entityType==="visual"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#8B5CF60D",color:"#8B5CF6"},children:"Visual"}),H.entityType==="library"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#0DBFE90D",color:"#0DBFE9"},children:"Library"}),H.entityType==="other"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#EC48990D",color:"#EC4899"},children:"Other"})]}),H.description&&n("div",{className:"text-sm text-gray-500 mt-1 overflow-hidden text-ellipsis whitespace-nowrap",children:H.description})]}),l("div",{className:"flex items-center gap-2 shrink-0",children:[re&&l("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(Xe,{size:14,className:"animate-spin"}),"Analyzing..."]}),!re&&O&&n("div",{className:"px-2 py-1 bg-purple-50 border border-purple-300 rounded text-xs text-purple-700 font-semibold",children:"⏳ Queued"}),!re&&!O&&n("button",{onClick:j=>{j.preventDefault(),j.stopPropagation(),h(`Starting analysis for ${H.name}...`,"info",3e3),m.submit({entityShas:H.sha},{method:"post",action:"/api/analyze"})},disabled:m.state!=="idle",className:"px-3 py-1.5 text-white border-none rounded text-xs font-medium cursor-pointer transition-all disabled:bg-gray-400 disabled:cursor-not-allowed",style:{backgroundColor:"#005C75"},onMouseEnter:j=>j.currentTarget.style.backgroundColor="#004560",onMouseLeave:j=>j.currentTarget.style.backgroundColor="#005C75",children:"Analyze"})]})]},H.sha)}):n("div",{className:"text-sm text-gray-500 italic p-2",children:"No entity changes detected in this file"})})]},R)})}):l("div",{className:"py-12 px-6 text-center flex flex-col items-center rounded-lg min-h-50 justify-center border border-dashed",style:{backgroundColor:"#F2F7F8",borderColor:"#BBCCD3"},children:[n("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:l("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#7A9BA5",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n("polyline",{points:"14 2 14 8 20 8"}),n("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),n("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}),n("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No Uncommitted Changes."})]})]}),!g&&n(Ug,{recentSimulations:s}),g&&l("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:l("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:s.length>0?`Latest ${s.length} captured screenshot${s.length!==1?"s":""}`:"No simulations captured yet"})]})}),g&&l("div",{className:"p-0 bg-white rounded-lg flex flex-col gap-0",children:[N&&n("div",{className:"p-4 rounded-t-lg",style:{backgroundColor:"#F0F5F8",borderBottom:"2px solid #005C75"},children:l("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-[32px] leading-none",children:n(Ve,{type:"visual"})}),l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"text-base font-bold mb-1",style:{color:"#005C75"},children:["Generating Simulations for ",N.name]}),n("div",{className:"text-[13px] text-gray-500 font-mono overflow-hidden text-ellipsis whitespace-nowrap",children:N.filePath})]})]})}),M?l("div",{className:"flex items-center gap-2 text-sm text-emerald-600 font-medium p-4 bg-emerald-50",children:[n("span",{className:"text-lg",children:"✅"}),l("span",{children:["Complete (",E.length," scenario",E.length!==1?"s":"",")"]})]}):C?l("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(Xe,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-mono text-xs",title:C,children:C}),i&&n("button",{onClick:()=>v(!0),className:"px-2 py-1.5 bg-gray-500 text-white border-none rounded-md text-[13px] font-medium cursor-pointer transition-all whitespace-nowrap self-start hover:bg-gray-600 hover:-translate-y-px",title:"View analysis logs",children:"📋 Logs"})]}):m.state!=="idle"?l("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(Xe,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Initializing analysis..."})]}):l("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(Xe,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Starting analysis..."})]}),E.length>0&&n("div",{className:"flex gap-2 flex-wrap p-4 bg-white border-t border-gray-200",children:E.slice(0,8).map((R,A)=>{var D,q,te;const G=(D=N==null?void 0:N.analyses)==null?void 0:D[0],B=xr(R,G==null?void 0:G.status,void 0,g||void 0,void 0),H=(te=(q=R.metadata)==null?void 0:q.screenshotPaths)==null?void 0:te[0],re=B.isCaptured,O=B.status==="capturing"||B.status==="starting",j=B.hasError;return re?n(se,{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(Ye,{screenshotPath:H,alt:R.name,title:R.name,className:"max-w-full max-h-full object-contain object-center"})},A):j?n("div",{className:"w-20 h-15 border-2 border-solid border-red-300 rounded bg-red-50 flex flex-col items-center justify-center text-lg",title:B.errorMessage||"Capture error",children:n("span",{className:"text-red-500",children:"⚠️"})},A):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:`${O?"Capturing":"Pending"} ${R.name}...`,children:n("span",{className:O?"animate-pulse":"text-gray-400",children:O?"⋯":"⏹️"})},A)})})]})]})]}),x&&i&&n(gt,{projectSlug:i,onClose:()=>v(!1)})]})})}),Gg=Object.freeze(Object.defineProperty({__proto__:null,default:Jg,loader:Vg,meta:Hg},Symbol.toStringTag,{value:"Module"}));function pi({content:e,className:t}){const r=e.trim().replace(/^#+ .+$/m,"").trim();return n(Vl,{remarkPlugins:[Jl],components:{h1:({children:a})=>n("h1",{className:"text-lg font-bold text-gray-900 mb-3 mt-6 first:mt-0 pb-1 border-b border-gray-200",children:a}),h2:({children:a})=>n("h2",{className:"text-base font-semibold text-gray-900 mb-2 mt-5 first:mt-0",children:a}),h3:({children:a})=>n("h3",{className:"text-sm font-semibold text-gray-800 mb-2 mt-4 first:mt-0",children:a}),p:({children:a})=>n("p",{className:"text-sm text-gray-700 mb-3 leading-relaxed",children:a}),ul:({children:a})=>n("ul",{className:"list-disc ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:a}),ol:({children:a})=>n("ol",{className:"list-decimal ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:a}),li:({children:a})=>n("li",{className:"leading-relaxed",children:a}),code:({children:a,className:s})=>(s==null?void 0:s.includes("language-"))?n("pre",{className:"bg-gray-100 rounded p-3 text-xs font-mono overflow-x-auto mb-3",children:n("code",{children:a})}):n("code",{className:"bg-gray-100 px-1.5 py-0.5 rounded text-xs font-mono text-gray-800",children:a}),pre:({children:a})=>n(le,{children:a}),strong:({children:a})=>n("strong",{className:"font-semibold text-gray-900",children:a}),blockquote:({children:a})=>n("blockquote",{className:"border-l-4 border-gray-300 pl-4 italic text-gray-600 mb-3",children:a}),table:({children:a})=>n("div",{className:"overflow-x-auto mb-3",children:n("table",{className:"min-w-full text-sm border-collapse border border-gray-200",children:a})}),thead:({children:a})=>n("thead",{className:"bg-gray-50",children:a}),th:({children:a})=>n("th",{className:"border border-gray-200 px-3 py-2 text-left font-semibold text-gray-900",children:a}),td:({children:a})=>n("td",{className:"border border-gray-200 px-3 py-2 text-gray-700",children:a}),a:({children:a,href:s})=>n("a",{href:s,className:"text-[#005C75] hover:underline",target:"_blank",rel:"noopener noreferrer",children:a})},children:r})}function fi(e){const t={name:"root",path:"",memories:[],children:new Map};for(const r of e){const a=r.filePath.split("/");a.pop();let s=t,o="";for(const i of a)o=o?`${o}/${i}`:i,s.children.has(i)||s.children.set(i,{name:i,path:o,memories:[],children:new Map}),s=s.children.get(i);a.length===0?t.memories.push(r):s.memories.push(r)}return t}function gi(e){let t=e.memories.length;for(const r of e.children.values())t+=gi(r);return t}function vr(e,t){var a;const r=e.match(/^#+ (.+)$/m);return r?r[1]:((a=t.split("/").pop())==null?void 0:a.replace(".md",""))||t}function rn(e){return Math.round(e/3.5)}function Lt(e){const t=new Date(e),r=new Date;if(t.toDateString()===r.toDateString()){const d=r.getTime()-t.getTime(),m=Math.floor(d/(1e3*60)),u=Math.floor(d/(1e3*60*60));return m<3?"Just now":m<60?`${m}min ago`:u===1?"1h ago":`${u}h ago`}const s=t.toLocaleDateString("en-US",{month:"short"}),o=t.getDate(),i=t.getFullYear(),c=r.getFullYear();return i===c?`${s} ${o}`:`${s} ${o}, ${i}`}function qg({rule:e,onEdit:t,onDelete:r,onView:a,isReviewed:s,onToggleReviewed:o,changeType:i,isUncommitted:c,changeDate:d,diff:m,isFadingOut:u,showLeftBorder:h}){const[p,f]=_(!1),[g,y]=_(!1),x=ae(()=>vr(e.body,e.filePath),[e.body,e.filePath]),v=rn(e.body.length),b=p?"#3e3e3e":c?"#d97706":"#c7c7c7",w=`rounded-lg border overflow-hidden transition-all ease-in-out ${c?"bg-amber-50 border-amber-300":"bg-white border-gray-200"}`,C={...u&&{opacity:0,maxHeight:0,paddingTop:0,paddingBottom:0,marginBottom:0,borderWidth:0,transitionDuration:"600ms"}};return l("div",{className:w,style:C,children:[n("div",{className:`p-4 cursor-pointer ${c?"hover:bg-amber-100":"hover:bg-gray-50"}`,onClick:()=>a?a(e):f(!p),children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"flex items-center gap-3",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:p?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:b})})}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:c?"#78350f":"#000"},children:x}),i&&n("span",{className:`px-2 py-0.5 rounded uppercase font-medium tracking-wider ${i==="deleted"?"bg-red-100 text-red-700":""}`,style:{fontSize:"10px",...i==="added"&&{backgroundColor:"#CBF3FA",color:"#005C75"},...i==="modified"&&{backgroundColor:"#FFE8C1",color:"#C67E06"}},children:i}),c&&n("span",{className:"px-2 py-0.5 bg-amber-200 text-amber-800 rounded font-medium uppercase tracking-wider",style:{fontSize:"10px"},children:"Uncommitted"}),l("span",{className:"text-xs text-gray-400",children:["~",v.toLocaleString()," tokens"]})]}),n("div",{className:"flex items-center gap-2 text-xs text-gray-500 flex-wrap",children:e.frontmatter.paths&&e.frontmatter.paths.length>0&&l(le,{children:[e.frontmatter.paths.slice(0,2).map((k,N)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-500 rounded font-mono",children:k},N)),e.frontmatter.paths.length>2&&l("span",{className:"text-gray-400 whitespace-nowrap",children:["+",e.frontmatter.paths.length-2," more"]})]})})]})]}),l("div",{className:"flex items-center gap-3 flex-shrink-0",children:[d&&n("span",{className:"text-xs text-gray-400",children:Lt(d)}),o&&n("button",{onClick:k=>{k.stopPropagation(),o(e.filePath,e.lastModified,s??!1)},className:`w-5 h-5 rounded-full border-2 flex items-center justify-center cursor-pointer transition-colors ${s?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,title:s?"Mark as unreviewed":"Mark as reviewed",children:s&&n("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})}),p&&l("div",{className:`border-t ${c?"border-amber-200":"border-gray-100"}`,children:[l("div",{className:`px-4 py-3 flex items-center justify-between ${c?"bg-amber-50":"bg-white"}`,children:[n("div",{className:"flex items-center gap-2",children:i==="modified"&&m&&l("button",{onClick:k=>{k.stopPropagation(),y(!g)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${g?c?"bg-amber-200 text-amber-900":"bg-gray-200 text-gray-900":c?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[n(Fn,{className:"w-3 h-3"}),g?"Hide Diff":"Show Diff"]})}),i!=="deleted"&&l("div",{className:"flex items-center gap-2",children:[l("button",{onClick:k=>{k.stopPropagation(),t(e)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${c?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[n(fl,{className:"w-3 h-3"}),"Edit"]}),l("button",{onClick:k=>{k.stopPropagation(),r(e)},className:"flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer text-red-600 hover:text-red-800 hover:bg-red-100",children:[n(gl,{className:"w-3 h-3"}),"Delete"]})]})]}),g&&m&&n("pre",{className:"mx-4 mb-4 p-4 text-xs font-mono overflow-x-auto bg-gray-900 text-gray-100 max-h-64 overflow-y-auto rounded-md",children:m.split(`
262
- `).map((k,N)=>{let E="";return k.startsWith("+")&&!k.startsWith("+++")?E="text-green-400":k.startsWith("-")&&!k.startsWith("---")?E="text-red-400":k.startsWith("@@")&&(E="text-cyan-400"),n("div",{className:E,children:k},N)})}),l("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Edit with Claude:"}),l("div",{className:"flex items-center gap-2",children:[l("span",{className:"px-2 py-1 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:["Claude, can you help me edit this rule: `",e.filePath,"`"]}),n(Ht,{content:`Claude, can you help me edit this rule: \`${e.filePath}\``,icon:!0,iconSize:14,className:"p-1 text-gray-400 hover:text-gray-600 rounded transition-colors"})]})]}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&l("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Applies to paths:"}),n("div",{className:"flex flex-wrap gap-1.5",children:e.frontmatter.paths.map((k,N)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:k},N))})]}),!g&&n("div",{className:"mx-4 mb-4 p-4 rounded border max-h-[500px] overflow-auto bg-white border-gray-200",children:n(pi,{content:e.body})})]})]})}function Kg(){return new Date().toISOString().split(".")[0]+"",`---
263
- paths:
264
- - '**/*.ts'
265
- ---
266
-
267
- ## Title
268
-
269
- Description here.
270
- `}function Qg({rule:e,onSave:t,onCancel:r}){const[a,s]=_(e?`.claude/rules/${e.filePath}`:""),[o,i]=_((e==null?void 0:e.content)||Kg()),[c,d]=_(!!e),[m,u]=_(!1),h=!e;return l("div",{className:"p-6",children:[l("div",{className:"flex items-center justify-between mb-4",children:[n("h3",{className:"text-lg font-semibold",style:{fontFamily:"Sora"},children:e?"Edit Rule":"Create New Rule"}),n("button",{onClick:r,className:"text-gray-400 hover:text-gray-600 cursor-pointer",children:n(un,{className:"w-5 h-5"})})]}),h&&l("div",{className:"mb-6",children:[n("div",{className:"bg-[#f0f9ff] border border-[#bae6fd] rounded-lg p-4 mb-4",children:l("div",{className:"flex items-start gap-3",children:[n(Fn,{className:"w-5 h-5 text-[#0284c7] mt-0.5 flex-shrink-0"}),l("div",{children:[n("h4",{className:"font-medium text-[#0c4a6e] mb-1",children:"Recommended: Use Claude Code"}),n("p",{className:"text-sm text-[#0369a1] mb-2",children:"Run this command in Claude Code to create a properly formatted rule with the right file location and paths:"}),l("div",{className:"relative",children:[n("code",{className:"block bg-white px-3 py-2 pr-9 rounded border border-[#bae6fd] font-mono text-sm text-[#0c4a6e]",children:"/codeyam-new-rule"}),n("button",{onClick:()=>{navigator.clipboard.writeText("/codeyam-new-rule"),u(!0),setTimeout(()=>u(!1),2e3)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-[#0284c7] hover:text-[#0c4a6e] cursor-pointer transition-colors",title:"Copy command",children:m?n(et,{className:"w-4 h-4 text-green-500"}):n(st,{className:"w-4 h-4"})})]})]})]})}),l("button",{onClick:()=>d(!c),className:"flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 cursor-pointer",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:c?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:c?"#3e3e3e":"#c7c7c7"})})}),"Or create manually"]})]}),(c||!h)&&l("div",{className:"space-y-4",children:[l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path (relative to .claude/rules/)"}),l("div",{className:"relative",children:[n("input",{type:"text",value:a,onChange:p=>s(p.target.value),placeholder:"e.g., src/webserver/architecture.md",className:"w-full px-3 py-2 pr-10 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-sm",disabled:!!e}),n("button",{onClick:()=>{navigator.clipboard.writeText(a)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 cursor-pointer",title:"Copy path",children:n(st,{className:"w-4 h-4"})})]})]}),e&&l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Ask Claude for help editing:"}),l("div",{className:"relative",children:[n("input",{type:"text",value:`Claude, can you help me edit the rule: \`${a}\``,readOnly:!0,className:"w-full px-3 py-2 pr-10 border border-gray-300 rounded-md bg-gray-50 font-mono text-sm text-gray-600"}),n("button",{onClick:()=>{navigator.clipboard.writeText(`Claude, can you help me edit the rule: \`${a}\``)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 cursor-pointer",title:"Copy prompt",children:n(st,{className:"w-4 h-4"})})]})]}),l("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:o,onChange:p=>i(p.target.value),rows:20,className:"w-full px-3 py-2 border border-gray-700 rounded-md focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-sm bg-gray-900 text-gray-100 [&::-webkit-scrollbar]:w-2 [&::-webkit-scrollbar-track]:bg-gray-800 [&::-webkit-scrollbar-thumb]:bg-gray-600 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:hover:bg-gray-500 [&::-webkit-resizer]:bg-gray-700"})]}),l("div",{className:"flex justify-end gap-2",children:[n("button",{onClick:r,className:"px-4 py-2 text-[#001f3f] hover:text-[#001530] rounded-md cursor-pointer font-mono uppercase text-xs font-semibold",children:"Cancel"}),n("button",{onClick:()=>t(a.replace(/^\.claude\/rules\//,""),o),disabled:!a.trim()||!o.trim(),className:"px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer font-mono uppercase text-xs font-semibold",children:"Save"})]})]})]})}function Zg({memories:e,selectedPath:t,onSelectPath:r,expandedFolders:a,onToggleFolder:s}){const o=ae(()=>fi(e),[e]),i=(m,u,h)=>{if(m.target.closest(".chevron-toggle")){h&&s(u||"root");return}const f=u||null;r(t===f?null:f),h&&!a.has(u||"root")&&s(u||"root")},c=m=>{r(t===m?null:m)},d=(m,u=0)=>{const h=a.has(m.path||"root"),p=gi(m),f=m.children.size>0,g=m.name==="root"?"(root)":m.name,y=m.memories.length>0||f,x=m.path||"",v=t===x||t===null&&x==="";return l("div",{children:[l("div",{className:`flex items-center gap-2 py-2.5 cursor-pointer rounded px-2 relative ${v?"bg-[#E0E9EC]":"hover:bg-gray-100"}`,style:{paddingLeft:`${u*12+8}px`},onClick:b=>i(b,m.path,y),children:[y&&n("span",{className:"chevron-toggle p-0.5 -m-0.5 hover:bg-gray-200 rounded",onClick:b=>{b.stopPropagation(),s(m.path||"root")},children:n(xt,{className:`w-3 h-3 text-gray-500 transition-transform ${h?"rotate-90":""}`})}),!y&&n("div",{className:"w-3"}),n(Xs,{className:"w-3.5 h-3.5 text-[#005C75]"}),n("span",{className:`text-xs font-mono font-semibold ${v?"text-[#005C75]":""}`,style:{color:"#005C75"},children:g}),l("span",{className:"text-xs ml-auto",style:{color:"#005C75"},children:[p," rules"]})]}),h&&l("div",{className:"relative",children:[(m.memories.length>0||f)&&n("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:`${u*12+8+6}px`}}),m.memories.length>0&&n("div",{style:{paddingLeft:`${(u+1)*12+8}px`},children:m.memories.map(b=>{var C;const w=t===b.filePath;return n("div",{className:`flex items-center gap-2 py-1 px-2 text-sm rounded cursor-pointer relative ${w?"bg-[#E0E9EC] text-[#005C75]":"text-gray-600 hover:bg-gray-50"}`,onClick:()=>c(b.filePath),children:n("span",{className:"text-xs",children:(C=b.filePath.split("/").pop())==null?void 0:C.replace(".md","")})},b.filePath)})}),f&&n("div",{children:Array.from(m.children.values()).sort((b,w)=>b.name.localeCompare(w.name)).map(b=>d(b,u+1))})]})]},m.path||"root")};return n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 mb-8",children:d(o)})}function Xg({memories:e,onEdit:t,onDelete:r,expandedFolders:a,onToggleFolder:s,reviewedStatus:o,onMarkReviewed:i,onMarkUnreviewed:c,onViewRule:d}){const[m,u]=_({});ee(()=>{u({})},[o]);const h=ae(()=>({...o,...m}),[o,m]),p=ae(()=>fi(e),[e]),f=(y,x,v)=>{u(b=>({...b,[y]:!v})),v?c(y):i(y,x)},g=(y,x=0)=>{const v=a.has(y.path||"root"),b=y.children.size>0,w=y.name==="root"?"root":y.name,C=y.memories.length>0||b;return l("div",{children:[l("div",{className:"flex items-center gap-2 py-2 cursor-pointer hover:bg-gray-50 rounded px-2 mb-2",style:{backgroundColor:"rgba(224, 233, 236, 0.5)"},onClick:()=>C&&s(y.path||"root"),children:[C&&n(xt,{className:`w-4 h-4 text-gray-500 transition-transform ${v?"rotate-90":""}`}),!C&&n("div",{className:"w-4"}),n(Xs,{className:"w-4 h-4 text-[#005C75]"}),n("span",{className:"text-sm font-mono font-semibold",style:{color:"#001f3f"},children:w})]}),v&&l("div",{className:"ml-10 space-y-4 relative",children:[(y.memories.length>0||b)&&n("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:"-24px"}}),y.memories.length>0&&n("div",{className:"space-y-2",children:y.memories.map(k=>n(qg,{rule:k,onEdit:t,onDelete:r,onView:d,isReviewed:h[k.filePath]??!1,onToggleReviewed:f},k.filePath))}),b&&n("div",{className:"space-y-4",children:Array.from(y.children.values()).sort((k,N)=>k.name.localeCompare(N.name)).map(k=>g(k,x+1))})]})]},y.path||"root")};return n("div",{children:g(p)})}function e0({memories:e,reviewedStatus:t,onViewRule:r,refreshKey:a}){const[s,o]=_("unreviewed"),[i,c]=_("by-date"),[d,m]=_(null),[u,h]=_(!0),[p,f]=_(new Map),g=Ne(t),y=Ne([]);ee(()=>()=>{y.current.forEach(clearTimeout)},[]),ee(()=>{(async()=>{h(!0);try{const N=await(await fetch("/api/memory?action=rule-coverage")).json();m(N.coverage??null)}catch{m(null)}finally{h(!1)}})()},[a]),ee(()=>{const C=g.current,k=[];for(const[N,E]of Object.entries(t))E&&!C[N]&&k.push(N);g.current=t,k.length!==0&&(f(N=>{const E=new Map(N);return k.forEach(S=>E.set(S,"approved")),E}),y.current.push(setTimeout(()=>{f(N=>{const E=new Map(N);return k.forEach(S=>E.set(S,"fading")),E})},1500)),y.current.push(setTimeout(()=>{f(N=>{const E=new Map(N);return k.forEach(S=>E.delete(S)),E})},2500)))},[t]);const x=ae(()=>{const C=[...e];return i==="by-impact"&&d!==null?C.sort((k,N)=>{const E=d[k.filePath]??0,S=d[N.filePath]??0;return S!==E?S-E:new Date(N.lastModified).getTime()-new Date(k.lastModified).getTime()}):C.sort((k,N)=>new Date(N.lastModified).getTime()-new Date(k.lastModified).getTime()),C},[e,i,d]),v=ae(()=>x.filter(C=>!t[C.filePath]).length,[x,t]),b=ae(()=>s==="unreviewed"?x.filter(C=>!t[C.filePath]||p.has(C.filePath)):x,[x,s,t,p]),w=!u&&d!==null;return l("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:[l("div",{className:"flex items-center gap-4 border-b border-[#e1e1e1] px-5",children:[n("button",{className:"py-3 border-b-2 border-[#232323] text-[#232323] bg-transparent cursor-pointer",children:n("span",{className:"text-[14px] leading-6",style:{fontFamily:"Sora",fontWeight:600},children:"Recently Changed Rules"})}),n("div",{className:"flex-1"}),l("button",{onClick:()=>o("unreviewed"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:s==="unreviewed"?"#005C75":"#d1d5db"}}),l("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:s==="unreviewed"?600:400,color:s==="unreviewed"?"#005C75":"#626262"},children:["Unreviewed Rules (",v,")"]})]}),l("button",{onClick:()=>o("all"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:s==="all"?"#005C75":"#d1d5db"}}),l("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:s==="all"?600:400,color:s==="all"?"#005C75":"#626262"},children:["All (",x.length,")"]})]})]}),l("div",{className:"grid grid-cols-[1fr_90px_80px_100px] px-5 py-2 border-b border-gray-100",children:[n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium",children:"Rule"}),l("button",{onClick:()=>w&&c("by-impact"),className:`text-[11px] uppercase tracking-wider font-medium text-center flex items-center justify-center gap-0.5 whitespace-nowrap bg-transparent border-none p-0 ${w?"cursor-pointer hover:text-gray-600":"cursor-default"} ${i==="by-impact"?"text-[#005C75]":"text-gray-400"}`,children:["Src Files",i==="by-impact"&&n(Qe,{className:"w-3 h-3"})]}),l("button",{onClick:()=>c("by-date"),className:`text-[11px] uppercase tracking-wider font-medium text-center flex items-center justify-center gap-0.5 whitespace-nowrap bg-transparent border-none cursor-pointer p-0 hover:text-gray-600 ${i==="by-date"?"text-[#005C75]":"text-gray-400"}`,children:["Changed At",i==="by-date"&&n(Qe,{className:"w-3 h-3"})]}),l("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium text-center flex items-center justify-center gap-1 whitespace-nowrap",children:["✓ Reviewed",l("span",{className:"relative group",children:[n(Vr,{className:"w-3 h-3 text-gray-300 cursor-help"}),n("span",{className:"absolute top-full right-0 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-52 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Showing which rules have been reviewed and approved. Click a rule to view it and approve it"})]})]})]}),n("div",{className:"flex-1 overflow-y-auto max-h-[400px]",children:b.map(C=>{const k=t[C.filePath]??!1,N=p.get(C.filePath),E=vr(C.body,C.filePath),S=(d==null?void 0:d[C.filePath])??0;return n("div",{className:`border-b border-gray-50 transition-all ${N==="fading"?"duration-1000":"duration-300"}`,style:{opacity:N==="fading"?0:1},children:l("div",{className:`grid grid-cols-[1fr_90px_80px_100px] px-5 py-2.5 items-center cursor-pointer transition-colors duration-300 ${N==="approved"?"bg-[#f0fdf4]":"hover:bg-gray-50"}`,onClick:()=>r(C),children:[n("div",{className:"flex items-center gap-2 min-w-0",children:n("span",{className:"text-sm text-gray-900 truncate",children:E})}),n("span",{className:"text-xs text-center",children:u?n("span",{className:"inline-block w-6 h-3 bg-gray-100 rounded animate-pulse"}):d!==null?n("span",{className:S>0?"text-gray-700 font-medium":"text-gray-300",children:S}):n("span",{className:"text-gray-300",children:"—"})}),n("span",{className:"text-xs text-gray-500 text-center",children:Lt(C.lastModified)}),n("div",{className:"flex justify-center",children:n("div",{className:`w-5 h-5 rounded-full border-2 flex items-center justify-center transition-colors duration-300 ${k?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:k&&n("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})})]})},C.filePath)})}),b.length===0&&s==="unreviewed"&&n("div",{className:"px-5 py-8 text-center text-sm text-gray-500",children:"All rules have been reviewed"})]})}function t0(e,t){const r=t.map(a=>`- \`${a}\``).join(`
271
- `);return`Please audit the following Claude Rules that apply to the file \`${e}\`:
272
-
273
- ${r}
274
-
275
- Please review these rules in conjunction with one another as they all apply to this file.
276
-
277
- Review each rule with the other rules in mind:
278
- - Efficiency: Are the rules concise and well-structured?
279
- - Effectiveness: Does the rules provide clear, actionable guidance?
280
- - Context window impact: Can the rules be shortened without losing important information?
281
- - Overlap: Is there any redundant information across the rules that can be consolidated?
282
- - Duplication: Are there any rules that are nearly identical that can be merged or removed?
283
-
284
- Note: Each rule may apply to multiple files, not just the file listed above. Consider this when suggesting changes — modifications should not negatively impact the rule's usefulness for other files it covers.`}function n0({filePath:e,rulePaths:t,onClose:r}){const[a,s]=_(!1),o=t0(e,t);return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:r,children:l("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative",onClick:c=>c.stopPropagation(),children:[n("button",{onClick:r,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(un,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-1",children:"Audit Rules For File"}),n("p",{className:"font-mono text-sm text-gray-500 mb-4 truncate",title:e,children:e}),n("p",{className:"text-gray-600 text-sm mb-4",children:"Claude can audit these rules to try and make them as efficient and effective as possible, reducing the impact on the context window."}),n("textarea",{readOnly:!0,value:o,className:"w-full h-48 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-4",children:n("button",{onClick:()=>{navigator.clipboard.writeText(o),s(!0),setTimeout(()=>s(!1),2e3)},className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:a?l(le,{children:[n(et,{className:"w-4 h-4"}),"Copied!"]}):l(le,{children:[n(st,{className:"w-4 h-4"}),"Copy Prompt"]})})})]})})}function r0({refreshKey:e,reviewedStatus:t,memories:r,onViewRule:a}){const[s,o]=_("unreviewed"),[i,c]=_(null),[d,m]=_(""),[u,h]=_(0),[p,f]=_(!1),[g,y]=_(null),[x,v]=_(null),b=Ne(null),w=Ne(null),[C,k]=_({topPaths:[],totalFilesWithCoverage:0,allSourceFiles:[]}),[N,E]=_(!0);ee(()=>{(async()=>{E(!0);try{const V=await(await fetch("/api/memory?action=audit")).json();k({topPaths:V.topPaths||[],totalFilesWithCoverage:V.totalFilesWithCoverage||0,allSourceFiles:V.allSourceFiles||[]})}catch(J){console.error("Failed to load audit data:",J)}finally{E(!1)}})()},[e]);const S=ae(()=>s==="all"?C.topPaths:C.topPaths.filter(I=>I.matchingRules.some(J=>!t[J.filePath])),[C.topPaths,s,t]);ae(()=>C.topPaths.filter(I=>I.matchingRules.some(J=>!t[J.filePath])).length,[C.topPaths,t]);const M=I=>I.split("/").pop()||I,F=ae(()=>{const I=new Map;for(const J of C.topPaths)I.set(J.filePath,J);return I},[C.topPaths]),L=ae(()=>{if(!d.trim())return[];const I=d.toLowerCase(),J=[],V=[];for(const U of C.allSourceFiles){const z=U.toLowerCase();if(!z.includes(I))continue;const Y=F.get(U)||{filePath:U,matchingRules:[],totalTextLength:0};z.startsWith(I)?J.push(Y):V.push(Y)}return J.sort((U,z)=>U.filePath.localeCompare(z.filePath)),V.sort((U,z)=>U.filePath.localeCompare(z.filePath)),[...J,...V].slice(0,8)},[d,C.allSourceFiles,F]),P=ie(I=>{var J;y(I),c(I.filePath),m(I.filePath),f(!1),(J=b.current)==null||J.blur()},[]),T=ie(()=>{var I;m(""),y(null),c(null),(I=b.current)==null||I.focus()},[]),$=ie(I=>{var J;!p||L.length===0||(I.key==="ArrowDown"?(I.preventDefault(),h(V=>Math.min(V+1,L.length-1))):I.key==="ArrowUp"?(I.preventDefault(),h(V=>Math.max(V-1,0))):I.key==="Enter"?(I.preventDefault(),P(L[u])):I.key==="Escape"&&(f(!1),(J=b.current)==null||J.blur()))},[p,L,u,P]);return ee(()=>{h(0)},[L]),l("div",{className:"bg-white rounded-lg border border-gray-200 flex flex-col",children:[l("div",{className:"flex items-center gap-4 border-b border-[#e1e1e1] px-5",children:[n("button",{className:"py-3 border-b-2 border-[#232323] text-[#232323] bg-transparent cursor-pointer",children:n("span",{className:"text-[14px] leading-6",style:{fontFamily:"Sora",fontWeight:600},children:"Rule Audit"})}),l("div",{className:"relative flex-1 max-w-[300px]",children:[n(dn,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),n("input",{ref:b,type:"text",value:d,onChange:I=>{m(I.target.value),f(!0)},onFocus:()=>{d.trim()&&f(!0)},onBlur:()=>{setTimeout(()=>f(!1),200)},onKeyDown:$,placeholder:"Search files...",className:`w-full pl-8 ${d?"pr-7":"pr-3"} py-1 text-xs border border-gray-200 rounded-md focus:outline-none focus:ring-1 focus:ring-[#005C75] focus:border-[#005C75] bg-gray-50`}),d&&n("button",{type:"button",onMouseDown:I=>{I.preventDefault(),T()},className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center text-gray-400 hover:text-gray-600 cursor-pointer",children:n("svg",{viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"w-3 h-3",children:n("path",{d:"M1 1l12 12M13 1L1 13"})})}),p&&L.length>0&&n("div",{ref:w,className:"absolute left-0 top-full mt-0.5 bg-white border border-gray-200 rounded-md shadow-lg z-10 max-h-75 overflow-y-auto min-w-75 max-w-120",children:L.map((I,J)=>l("div",{onMouseDown:V=>{V.preventDefault(),P(I)},onMouseEnter:()=>h(J),className:`flex items-center gap-2 px-3 py-2 cursor-pointer text-sm ${J===u?"bg-[#f0f9ff]":"hover:bg-gray-50"}`,children:[n(On,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-gray-700 truncate",title:I.filePath,children:(()=>{const V=I.filePath.toLowerCase().indexOf(d.toLowerCase());if(V===-1)return I.filePath;const U=I.filePath.slice(0,V),z=I.filePath.slice(V,V+d.length),Y=I.filePath.slice(V+d.length);return l(le,{children:[U,n("span",{className:"font-semibold text-[#005C75]",children:z}),Y]})})()}),l("span",{className:"text-xs text-gray-400 ml-auto flex-shrink-0",children:[I.matchingRules.length," rule",I.matchingRules.length!==1?"s":""]})]},I.filePath))})]}),n("div",{className:"flex-1"}),l("button",{onClick:()=>o("unreviewed"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:s==="unreviewed"?"#005C75":"#d1d5db"}}),n("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:s==="unreviewed"?600:400,color:s==="unreviewed"?"#005C75":"#626262"},children:"Unreviewed Rules"})]}),l("button",{onClick:()=>o("all"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:s==="all"?"#005C75":"#d1d5db"}}),n("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:s==="all"?600:400,color:s==="all"?"#005C75":"#626262"},children:"All"})]})]}),l("div",{className:"grid grid-cols-[1fr_140px_150px] px-5 py-2 border-b border-gray-100",children:[n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium",children:"Source file"}),l("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Rules",l("span",{className:"relative group",children:[n(Vr,{className:"w-3 h-3 text-gray-300 flex-shrink-0 cursor-help"}),n("span",{className:"absolute top-full left-1/2 -translate-x-1/2 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-48 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Number of rules not yet reviewed for this file / Total number of rules that apply to this file"})]})]}),l("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Tokens",l("span",{className:"relative group",children:[n(Vr,{className:"w-3 h-3 text-gray-300 flex-shrink-0 cursor-help"}),n("span",{className:"absolute top-full right-0 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-52 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Estimated tokens from unreviewed rules / Total number of tokens from all rules that apply to this file"})]})]})]}),N&&n("div",{className:"px-5 py-6",children:l("div",{className:"animate-pulse space-y-3",children:[n("div",{className:"h-4 bg-gray-200 rounded w-3/4"}),n("div",{className:"h-3 bg-gray-100 rounded w-1/2"}),n("div",{className:"h-4 bg-gray-200 rounded w-2/3 mt-4"})]})}),!N&&(S.length>0||g)&&n("div",{className:"max-h-[400px] overflow-y-auto",children:(g?[g,...S.filter(J=>J.filePath!==g.filePath)].slice(0,8):S.slice(0,8)).map((I,J)=>{const V=I.matchingRules.length,U=I.matchingRules.filter(B=>!t[B.filePath]),z=U.length,Y=U.reduce((B,H)=>B+H.bodyLength,0),R=z>0,A=i===I.filePath,G=(g==null?void 0:g.filePath)===I.filePath;return l("div",{children:[l("div",{onClick:()=>c(A?null:I.filePath),className:`grid grid-cols-[1fr_140px_150px] px-5 py-2.5 items-center border-b border-gray-50 cursor-pointer ${G?"bg-[#f0f9ff] hover:bg-[#e0f2fe]":"hover:bg-gray-50"}`,children:[l("div",{className:"flex items-center gap-2 min-w-0",children:[A?n(Qe,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}):n(xt,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n(On,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm text-gray-900 truncate",title:I.filePath,children:G?I.filePath:M(I.filePath)})]}),l("span",{className:"text-sm text-center",children:[n("span",{className:R?"font-semibold text-[#1A5276]":"text-gray-400",children:z}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:V})]}),l("span",{className:"text-sm text-center",children:[n("span",{className:R?"font-semibold text-[#1A5276]":"text-gray-400",children:rn(Y).toLocaleString()}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:rn(I.totalTextLength).toLocaleString()})]})]}),A&&l("div",{className:"bg-gray-50 border-b border-gray-100",children:[I.matchingRules.map(B=>{const H=r.find(O=>O.filePath===B.filePath),re=t[B.filePath]??!1;return l("div",{onClick:O=>{O.stopPropagation(),H&&a(H)},className:"flex items-center gap-2 px-5 pl-12 py-2 hover:bg-gray-100 cursor-pointer",children:[n(Ln,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm text-gray-700 truncate flex-1",children:H?vr(H.body,H.filePath):B.filePath}),l("span",{className:"text-xs text-gray-400 flex-shrink-0",children:[rn(B.bodyLength).toLocaleString()," ","tokens"]}),n("div",{className:`w-4 h-4 rounded-full border-2 flex items-center justify-center flex-shrink-0 ${re?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:re&&n("svg",{width:"8",height:"6",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]},B.filePath)}),l("div",{className:"flex items-center justify-center gap-3 px-5 py-2 border-t border-gray-200",children:[n("span",{className:"text-xs text-gray-400",children:"Have Claude audit these rules"}),n("button",{onClick:B=>{B.stopPropagation(),v({filePath:I.filePath,rulePaths:I.matchingRules.map(H=>H.filePath)})},className:"px-3 py-1 text-xs font-medium text-[#005C75] border border-[#005C75] rounded hover:bg-[#f0f9ff] cursor-pointer",children:"Prompt"})]})]})]},I.filePath)})}),!N&&S.length===0&&n("div",{className:"px-5 py-8 text-center text-sm text-gray-500",children:s==="unreviewed"?"No files have unreviewed rules":"No files have rule coverage yet"}),x&&n(n0,{filePath:x.filePath,rulePaths:x.rulePaths,onClose:()=>v(null)})]})}function a0({rule:e,changeInfo:t,isReviewed:r,onApprove:a,onEdit:s,onDelete:o,onClose:i}){const c=vr(e.body,e.filePath),d=rn(e.body.length),m=e.frontmatter.category,u=`.claude/rules/${e.filePath}`,[h,p]=_(null),f=(t==null?void 0:t.changeType)==="added"||h!=null&&h.commitCount!=null&&h.commitCount<=1&&!(h.commitCount===1&&h.isUncommitted);return ee(()=>{p(null),fetch(`/api/memory?action=rule-diff&filePath=${encodeURIComponent(e.filePath)}`).then(g=>g.json()).then(g=>{g.diff&&p(g.diff)}).catch(()=>{})},[e.filePath]),ee(()=>{const g=y=>{y.key==="Escape"&&i()};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[i]),n("div",{className:"fixed inset-0 flex items-center justify-center z-[9999] p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.8)"},onClick:i,children:l("div",{className:"rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",style:{backgroundColor:"#F8F7F6"},onClick:g=>g.stopPropagation(),children:[n("div",{className:"px-6 pt-5 pb-4",children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"min-w-0 flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1.5 flex-wrap",children:[n("h2",{className:"text-[16px] font-bold text-gray-900",children:c}),t&&l(le,{children:[n("span",{className:"text-xs text-gray-400 flex-shrink-0",children:Lt(t.date)}),n("span",{className:`flex-shrink-0 text-[11px] uppercase font-semibold tracking-wider ${t.changeType==="added"?"text-green-600":t.changeType==="modified"?"text-orange-600":"text-red-600"}`,children:t.changeType})]})]}),m&&l("div",{className:"flex items-center gap-2 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"TYPE:"}),n("span",{className:"px-2 py-0.5 rounded text-[10px] uppercase font-semibold tracking-wider bg-[#E0F2F1] text-[#00796B]",children:m})]}),l("div",{className:"flex items-center gap-1.5 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"FILE:"}),n("code",{className:"text-[11px] text-gray-600 font-mono",children:u}),n(Ht,{content:u,icon:!0,iconSize:12,className:"p-0.5 rounded text-gray-400 hover:text-gray-600 transition-colors",ariaLabel:"Copy file path"})]}),l("div",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:["TOKENS: ~",d.toLocaleString()]})]}),l("div",{className:"flex items-center gap-2 flex-shrink-0 ml-4",children:[l("button",{onClick:a,className:`flex items-center gap-1.5 px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer transition-colors ${r?"bg-green-600 text-white":"border border-green-600 text-green-700 hover:bg-green-50"}`,children:[n(et,{className:"w-3.5 h-3.5"}),r?"Approved":"Approve"]}),n("button",{onClick:s,className:"px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer border border-gray-300 text-gray-600 hover:bg-gray-50 transition-colors",children:"Edit"}),n("button",{onClick:o,className:"px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer border border-red-300 text-red-600 hover:bg-red-50 transition-colors",children:"Delete"}),n("button",{onClick:i,className:"p-1.5 rounded text-gray-400 hover:text-gray-600 hover:bg-gray-200 cursor-pointer transition-colors ml-1",children:n(un,{className:"w-5 h-5"})})]})]})}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&l("div",{className:"px-6 pb-4",children:[n("div",{className:"text-[13px] text-gray-700 font-semibold mb-2",children:"Applies to paths:"}),n("div",{className:"bg-white rounded-lg p-4 space-y-2.5",style:{border:"1px solid #E6E6E6"},children:e.frontmatter.paths.map((g,y)=>{const x=g.split("/"),v=x.pop()||g,b=x.length>0?x.join("/")+"/":"";return l("div",{className:"flex items-center gap-2 text-[13px] font-mono",children:[n(On,{className:"w-4 h-4 text-[#005C75] flex-shrink-0"}),l("span",{children:[b&&n("span",{className:"text-gray-500",children:b}),n("span",{className:"font-bold text-gray-900",children:v})]})]},y)})})]}),f?n("div",{className:"px-6 pb-4",children:l("div",{className:"text-[13px] text-gray-500",children:["Created"," ",t!=null&&t.date?Lt(t.date):h!=null&&h.date?Lt(h.date):"recently"]})}):h&&n("div",{className:"px-6 pb-4",children:l("details",{children:[l("summary",{className:"text-[13px] text-gray-700 font-semibold cursor-pointer",children:["Recent change: ",h.commitMessage," —"," ",Lt(h.date)]}),n("pre",{className:"mt-2 p-4 text-xs font-mono overflow-x-auto bg-gray-900 text-gray-100 max-h-64 overflow-y-auto rounded-md",children:h.diff.split(`
285
- `).map((g,y)=>{let x="";return g.startsWith("+")&&!g.startsWith("+++")?x="text-green-400":g.startsWith("-")&&!g.startsWith("---")?x="text-red-400":g.startsWith("@@")&&(x="text-cyan-400"),n("div",{className:x,children:g},y)})})]})}),l("div",{className:"px-6 pb-6",children:[n("div",{className:"text-[13px] text-gray-700 font-semibold mb-2",children:"Rule Text:"}),n("div",{className:"bg-white rounded-lg p-6",style:{border:"1px solid #E6E6E6"},children:n(pi,{content:e.body})})]})]})})}function s0(){return l("svg",{width:"24",height:"24",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#232323"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#232323"}),n("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#232323"}),n("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#232323"}),n("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#232323"}),n("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#232323"}),n("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#232323"}),n("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#232323"}),n("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#232323"}),n("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#232323"}),n("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#232323"}),n("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#232323"}),n("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#232323"}),n("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#232323"}),n("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#232323"}),n("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#232323"}),n("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#232323"}),n("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#232323"}),n("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#232323"}),n("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#232323"}),n("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#232323"}),n("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#232323"}),n("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#232323"}),n("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#232323"}),n("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#232323"}),n("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#232323"}),n("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#232323"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#232323"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#232323"})]})}function o0(){return l("svg",{width:"20",height:"20",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#005C75"}),n("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#005C75"}),n("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#005C75"}),n("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#005C75"}),n("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#005C75"}),n("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#005C75"}),n("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#005C75"}),n("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#005C75"}),n("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#005C75"}),n("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#005C75"}),n("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#005C75"}),n("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#005C75"}),n("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#005C75"}),n("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#005C75"}),n("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#005C75"}),n("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#005C75"}),n("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#005C75"}),n("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#005C75"}),n("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#005C75"}),n("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#005C75"}),n("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#005C75"}),n("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#005C75"}),n("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#005C75"})]})}function i0(){return n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans max-w-3xl mx-auto",children:[l("div",{className:"text-center mb-10",children:[n("h1",{className:"text-[22px] font-semibold mb-4",style:{fontFamily:"Sora",color:"#232323"},children:"Get Started with CodeYam Memory"}),n("p",{className:"text-[15px] text-gray-500 leading-relaxed max-w-2xl mx-auto",children:"CodeYam Memory generates path-scoped Claude Rules that load automatically when Claude works on matching files. These rules capture any confusion, architectural decisions, and tribal knowledge from your as you work with Claude, ensuring sessions become more efficient and aligned with your codebase over time."})]}),l("div",{className:"rounded-lg p-8 mb-6",style:{backgroundColor:"#EDF8FA",border:"1px solid #C8E6EC"},children:[n("h2",{className:"text-[18px] font-semibold mb-6",style:{fontFamily:"Sora",color:"#232323"},children:"Setup Steps"}),l("ol",{className:"space-y-5",children:[l("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"1"}),n("p",{className:"text-[14px] font-medium text-gray-900 pt-0.5",children:"Open Claude Code in your project terminal"})]}),l("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"2"}),l("div",{children:[l("div",{className:"flex items-center gap-2 pt-0.5",children:[n("span",{className:"text-[14px] font-medium text-gray-900",children:"Run"}),n(Ws,{value:"/codeyam-memory"}),n("span",{className:"text-[14px] font-medium text-gray-900",children:"in the Claude Code session"})]}),n("p",{className:"text-[13px] text-gray-600 mt-1",children:"This kicks off analysis of your git history to find confusion patterns."})]})]}),l("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"3"}),l("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900 pt-0.5",children:"Return to this dashboard page to review the new rules"}),n("p",{className:"text-[13px] text-gray-600 mt-1",children:"You can review, edit, and approve the rules Claude creates."})]})]})]})]}),l("div",{className:"rounded-lg p-8 mb-6",style:{backgroundColor:"#EDF8FA",border:"1px solid #C8E6EC"},children:[n("h2",{className:"text-[18px] font-semibold mb-6",style:{fontFamily:"Sora",color:"#232323"},children:"What Gets Created"}),l("div",{className:"relative",children:[n("div",{className:"absolute left-[15px] top-8 bottom-4",style:{borderLeft:"2px dotted #B0BEC5"}}),l("div",{className:"space-y-6",children:[l("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),l("div",{children:[l("p",{className:"text-[14px] font-medium text-gray-900",children:[n("code",{className:"bg-gray-200/60 px-1.5 py-0.5 rounded text-[13px]",children:".claude/rules/*.md"}),n("span",{className:"text-gray-400 mx-1.5",children:"—"}),"path-scoped guidance files"]}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"Markdown files with frontmatter specifying which file paths they apply to."})]})]}),l("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),l("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900",children:"Rules load automatically when Claude works on matching files"}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"No manual steps needed — Claude picks up relevant rules based on the files it touches."})]})]}),l("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),l("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900",children:"Pre-commit hook to keep rules fresh and capture new patterns"}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"A git hook runs automatically to update rules when related code changes and looks for any new patterns of confusion in work sessions."})]})]})]})]})]}),l("div",{className:"rounded-lg px-8 py-5 flex items-center justify-center gap-3",style:{backgroundColor:"#1A2332"},children:[n("span",{className:"text-white text-[15px] font-medium",children:"Run"}),n(Ws,{value:"/codeyam-memory"}),n("span",{className:"text-white text-[15px] font-medium",children:"in Claude Code to get started"})]})]})})}function Ws({value:e}){const[t,r]=_(!1);return l("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded text-[13px] font-mono cursor-pointer border-0",style:{backgroundColor:"#2C3E50",color:"#E0E0E0"},title:"Copy to clipboard",children:[e,t?n(et,{className:"w-3.5 h-3.5 text-green-400"}):l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-gray-400",children:[n("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),n("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})]})}function Tn({label:e,count:t,icon:r,bgColor:a,iconBgColor:s,textColor:o}){return n("div",{className:"rounded-lg p-4",style:{backgroundColor:a,border:"1px solid #EFEFEF"},children:l("div",{className:"flex items-start gap-3",children:[n("div",{className:"w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0",style:{backgroundColor:s},children:r}),l("div",{className:"flex-1",children:[n("div",{className:"text-[32px] font-semibold leading-none mb-1",style:{color:o},children:t}),n("div",{className:"text-[11px] uppercase tracking-wider font-medium",style:{color:o},children:e})]})]})})}function l0({searchFilter:e,onSearchChange:t,onCreateNew:r,onLearnMore:a,reviewCounts:s}){return l("div",{className:"mb-8",children:[l("div",{className:"flex flex-wrap items-center justify-between gap-4 mb-6",children:[l("div",{children:[l("div",{className:"flex items-center gap-3 mb-2",children:[n(s0,{}),n("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Memory"})]}),l("p",{className:"text-[15px] text-gray-500",children:["Rules help Claude understand your codebase patterns and conventions."," ",n("button",{onClick:a,className:"text-[#005C75] underline cursor-pointer",children:"Learn more about rules."})]})]}),l("div",{className:"flex items-center gap-3",children:[l("div",{className:"relative",children:[n(dn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:e,onChange:o=>t(o.target.value),placeholder:"Search rules...",className:"w-64 pl-10 pr-4 py-2 border border-gray-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent text-sm"})]}),l("button",{onClick:r,className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:[n(oa,{className:"w-4 h-4"}),"New Rule"]})]})]}),l("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[n(Tn,{label:"Total Rules",count:s.total,icon:n(o0,{}),bgColor:"#EDF1F3",iconBgColor:"#E0E9EC",textColor:"#005C75"}),n(Tn,{label:"Unreviewed",count:s.unreviewed,icon:n(yl,{className:"w-5 h-5 text-[#1A5276]"}),bgColor:"#E9F0FB",iconBgColor:"#DBE9FF",textColor:"#1A5276"}),n(Tn,{label:"Reviewed",count:s.reviewed,icon:n(et,{className:"w-5 h-5 text-[#1B7A4A]"}),bgColor:"#EAFBEF",iconBgColor:"#D4EDDB",textColor:"#1B7A4A"}),n(Tn,{label:"Stale",count:s.stale,icon:n(Zs,{className:"w-5 h-5 text-[#5B21B6]"}),bgColor:"#EDE9FB",iconBgColor:"#DDD6FE",textColor:"#5B21B6"})]})]})}function c0({onClose:e,onCreateNew:t}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:l("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative",onClick:r=>r.stopPropagation(),children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(un,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-4",children:"What are Claude Rules?"}),n("h3",{className:"mb-4 font-semibold",children:"And how does CodeYam Memory work with Claude Rules?"}),l("div",{className:"text-gray-600 text-[15px] space-y-3 mb-6",children:[l("p",{children:["Claude Rules are a component of"," ",n("a",{href:"https://code.claude.com/docs/en/memory#modular-rules-with-claude%2Frules%2F",target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 underline",children:"Memory Management in Claude Code"}),'. The text of each rule is passed into the context window when working on the specific files described in the "paths" frontmatter field of the rule.']}),n("p",{children:"This allows you to provide context that is surgically specific to certain files in your codebase. They are a powerful tool but are harder to write and maintain than CLAUDE.md files."}),n("p",{children:"CodeYam Memory helps write and maintain Claude Rules. Hooks ensure that rules are reviewed and added during Claude Code working sessions. The CodeYam CLI Dashboard provides a page dedicated to Memory where you can view, edit, create, delete, and review Claude Rules."})]}),n("div",{className:"flex justify-center",children:l("button",{onClick:t,className:"flex items-center gap-2 px-5 py-2.5 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:[n(oa,{className:"w-4 h-4"}),"New Rule"]})})]})})}function d0({rule:e,onConfirm:t,onCancel:r}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:l("div",{className:"bg-white rounded-lg p-6 max-w-md w-full mx-4",children:[n("h3",{className:"text-lg font-semibold mb-2",children:"Delete Memory?"}),l("p",{className:"text-gray-600 mb-4",children:["Are you sure you want to delete"," ",n("span",{className:"font-mono text-sm",children:e.filePath}),"? This cannot be undone."]}),l("div",{className:"flex justify-end gap-2",children:[n("button",{onClick:r,className:"px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-md cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>t(e),className:"px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 cursor-pointer",children:"Delete"})]})]})})}const Hs="Can you help me perform an interactive rules audit? Please look at all of the rules in `.claude/rules`. Are they organized properly? Ideally they should be in a folder that is the best representation of the files they impact (e.g. if the rule impacts `folder1/folder2/file1` and `folder1/folder2/folder3/file2` then the rule should be in `.claude/rules/folder1/folder2`). Do they make sense? Are they oriented toward avoiding future confusion (vs documenting bug fixes or temporary workarounds, etc)? Please literally read each one to ensure you understand what it is saying and learn something useful from it. Are they concise and efficient in their communication? We want to be respectful of the context window so any information in a rule that does not make sense, is not particularly helpful, or is repetitive should be removed. All other information should be presented as directly as possible. Bullets and tables can help with this as opposed to paragraphs. Take into consideration how rules interact as any one file may have multiple rules applied to it. Please look at the impacted files as well to ensure that it is an appropriate rule for them and to ensure the rules is not just repeating information that can be ascertained from the code. We don't want Claude to have to read a large number of files (or a single very large file) to figure out how everything works, so architectural guidance can be quite valuable, but information that is specific to one file and can be ascertained by the code and comments in that file is unnecessary. If you have any questions please ask!",Vs="Can you mark all of these rules as reviewed in `.claude/codeyam-rule-state.json`?";function Js({text:e}){const[t,r]=_(!1);return n("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:t?l(le,{children:[n(et,{className:"w-4 h-4"}),"Copied!"]}):l(le,{children:[n(st,{className:"w-4 h-4"}),"Copy Prompt"]})})}function u0({onClose:e}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:l("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative max-h-[90vh] overflow-y-auto",onClick:t=>t.stopPropagation(),children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(un,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-2",children:"Audit All Rules"}),n("p",{className:"text-gray-600 text-sm mb-4",children:"Claude can review all rules to look for information that is inconsistent, inappropriate, duplicative, inefficient, etc."}),n("textarea",{readOnly:!0,value:Hs,className:"w-full h-48 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-3",children:n(Js,{text:Hs})}),l("div",{className:"border-t border-gray-200 mt-6 pt-5",children:[n("p",{className:"text-gray-500 text-sm mb-3",children:"If you would like to avoid reviewing all of the changes Claude makes you can ask Claude to mark all rules as reviewed."}),n("textarea",{readOnly:!0,value:Vs,className:"w-full h-16 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-3",children:n(Js,{text:Vs})})]})]})})}function m0(){const[e,t]=_(!1);return l(le,{children:[l("div",{className:"border border-gray-200 rounded-lg px-5 py-4 mb-8 flex items-center gap-3",children:[n("h3",{className:"text-[14px] leading-6 text-[#232323] flex-shrink-0",style:{fontFamily:"Sora",fontWeight:600},children:"Audit All Rules"}),n("p",{className:"text-sm text-gray-500",children:"Ask Claude to review, audit, and improve all rules."}),n("button",{onClick:()=>t(!0),className:"px-4 py-2 text-xs font-medium text-[#005C75] border border-[#005C75] rounded hover:bg-[#f0f9ff] cursor-pointer flex-shrink-0",children:"Get Prompt"})]}),e&&n(u0,{onClose:()=>t(!1)})]})}const h0=()=>[{title:"Memory - CodeYam"},{name:"description",content:"Manage Claude Memory documentation"}];async function p0({request:e}){try{const r=await(await fetch(new URL("/api/memory",e.url).toString())).json();return r.error?W({memories:[],reviewedStatus:{},memoryInitialized:r.memoryInitialized??!1,error:r.error}):r.memoryInitialized??!1?W({memories:r.memories||[],reviewedStatus:r.reviewedStatus||{},memoryInitialized:!0,error:null}):W({memories:[],reviewedStatus:{},memoryInitialized:!1,error:null})}catch(t){return console.error("Failed to load memories:",t),W({memories:[],reviewedStatus:{},memoryInitialized:!1,error:"Failed to load memories"})}}const f0=De(function(){const{memories:t,reviewedStatus:r,memoryInitialized:a,error:s}=Be(),o=Ee(),i=it(),[c,d]=_(""),[m,u]=_(null),[h,p]=_(new Set(["root"])),[f,g]=_(null),[y,x]=_(!1),[v,b]=_(null),[w,C]=_(0),[k,N]=_(!1),[E,S]=_(null),[M,F]=_(null),[L,P]=_({}),T=O=>{p(j=>{const D=new Set(j);return D.has(O)?D.delete(O):D.add(O),D})};tt({source:"memory-page"});const $=ae(()=>({...r,...L}),[r,L]),I=Ne(o.state);ee(()=>{const O=I.current==="loading"||I.current==="submitting",j=o.state==="idle";O&&j&&o.data&&(i.revalidate(),g(null),x(!1),C(D=>D+1)),I.current=o.state},[o.state,o.data,i]),ee(()=>{P(O=>{const j={};for(const[D,q]of Object.entries(O))r[D]!==q&&(j[D]=q);return Object.keys(j).length===Object.keys(O).length?O:j})},[r]);const J=(O,j)=>{P(D=>({...D,[O]:!0})),o.submit({action:"mark-reviewed",filePath:O,lastModified:j},{method:"POST",action:"/api/memory",encType:"application/json"})},V=O=>{P(j=>({...j,[O]:!1})),o.submit({action:"mark-unreviewed",filePath:O},{method:"POST",action:"/api/memory",encType:"application/json"})},U=(O,j)=>{S(O),F(j??null)},z=ae(()=>{let O=t;if(c.trim()){const j=c.toLowerCase();O=O.filter(D=>{var te;return(((te=D.filePath.split("/").pop())==null?void 0:te.replace(".md",""))||"").toLowerCase().includes(j)||D.body.toLowerCase().includes(j)})}return O},[t,c]),Y=ae(()=>m?z.some(j=>j.filePath===m)?z.filter(j=>j.filePath===m):z.filter(j=>j.filePath.startsWith(m+"/")||j.filePath===m):z,[z,m]),R=(O,j)=>{const D=f?"update":"create";o.submit({action:D,filePath:O,content:j},{method:"POST",action:"/api/memory",encType:"application/json"})},A=O=>{o.submit({action:"delete",filePath:O.filePath},{method:"POST",action:"/api/memory",encType:"application/json"}),b(null)},G=ae(()=>{const O=t.filter(j=>$[j.filePath]).length;return{total:t.length,reviewed:O,unreviewed:t.length-O,stale:0}},[t,$]),B=ae(()=>{const O=new Set(["root"]);for(const j of z){const D=j.filePath.split("/");D.pop();let q="";for(const te of D)q=q?`${q}/${te}`:te,O.add(q)}return O},[z]),H=B.size===h.size&&[...B].every(O=>h.has(O)),re=()=>{p(H?new Set(["root"]):new Set(B))};return s?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:s})]})}):a?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans",children:[n(l0,{searchFilter:c,onSearchChange:d,onCreateNew:()=>x(!0),onLearnMore:()=>N(!0),reviewCounts:G}),(y||f)&&n("div",{className:"fixed inset-0 flex items-center justify-center z-[9999] p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.8)"},onClick:()=>{x(!1),g(null)},children:n("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",onClick:O=>O.stopPropagation(),children:n(Qg,{rule:f,onSave:R,onCancel:()=>{x(!1),g(null)}})})}),l("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 lg:gap-8 mb-8",children:[n(e0,{memories:z,reviewedStatus:$,onViewRule:U,refreshKey:w}),n(r0,{onEditRule:g,onDeleteRule:b,refreshKey:w,reviewedStatus:$,onMarkReviewed:J,onMarkUnreviewed:V,memories:t,onViewRule:U})]}),n(m0,{}),l("div",{className:"flex items-center justify-between mb-4",children:[n("h2",{className:"text-xl leading-6 text-[#232323]",style:{fontFamily:"Sora",fontWeight:600},children:"All Rules"}),n("div",{className:"flex items-center gap-4",children:B.size>1&&n("button",{onClick:re,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:H?"Collapse All":"Expand All"})})]}),l("div",{className:"flex gap-6",children:[n("div",{className:"hidden lg:block w-80 flex-shrink-0",children:n(Zg,{memories:z,selectedPath:m,onSelectPath:u,expandedFolders:h,onToggleFolder:T})}),n("div",{className:"flex-1 min-w-0",children:t.length===0?l("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(xl,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),n("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Rules Yet"}),l("p",{className:"text-gray-500 mb-4",children:["Run"," ",n("code",{className:"bg-gray-100 px-2 py-1 rounded",children:"/codeyam-memory"})," ","to generate initial memories for your codebase."]}),l("button",{onClick:()=>x(!0),className:"inline-flex items-center gap-2 px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] cursor-pointer",children:[n(oa,{className:"w-4 h-4"}),"Create Your First Memory"]})]}):l("div",{children:[m&&l("div",{className:"flex items-center gap-2 text-sm text-gray-600 mb-4",children:["Showing rules in"," ",n("span",{className:"font-mono bg-gray-100 px-1.5 py-0.5 rounded",children:m||"(root)"}),n("button",{onClick:()=>u(null),className:"text-[#005C75] hover:underline cursor-pointer",children:"Clear filter"})]}),n(Xg,{memories:Y,onEdit:g,onDelete:b,expandedFolders:h,onToggleFolder:T,reviewedStatus:$,onMarkReviewed:J,onMarkUnreviewed:V,onViewRule:U})]})})]}),n("div",{className:"mt-8 mb-8",children:n(se,{to:"/agent-transcripts",className:"block bg-white border border-gray-200 rounded-lg p-5 hover:border-[#005C75] hover:shadow-sm transition-all group",children:l("div",{className:"flex items-center gap-3",children:[n("div",{className:"w-10 h-10 rounded-lg bg-[#EDF1F3] flex items-center justify-center",children:l("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#005C75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("polyline",{points:"4 17 10 11 4 5"}),n("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}),l("div",{children:[n("h3",{className:"text-sm font-semibold text-[#232323] group-hover:text-[#005C75]",style:{fontFamily:"Sora"},children:"Agent Transcripts"}),n("p",{className:"text-xs text-gray-500",children:"View background agent transcripts and tool call history"})]})]})})}),E&&!f&&(()=>{const O=t.find(j=>j.filePath===E.filePath)??E;return n(a0,{rule:O,changeInfo:M??void 0,isReviewed:$[O.filePath]??!1,onApprove:()=>{$[O.filePath]??!1?V(O.filePath):J(O.filePath,O.lastModified),S(null)},onEdit:()=>{g(O)},onDelete:()=>{b(O),S(null)},onClose:()=>S(null)})})(),k&&n(c0,{onClose:()=>N(!1),onCreateNew:()=>{N(!1),x(!0)}}),v&&n(d0,{rule:v,onConfirm:A,onCancel:()=>b(null)})]})}):n(i0,{})}),g0=Object.freeze(Object.defineProperty({__proto__:null,default:f0,loader:p0,meta:h0},Symbol.toStringTag,{value:"Module"}));function Hr(e){return`${e.filePath||""}::${e.name}`}function yi(e,t){const r=Ee(),{showToast:a}=ua(),[s,o]=_(new Map);ee(()=>{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]),ee(()=>{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(x=>{s.forEach((v,b)=>{v===x&&p.add(b)})})}),e==null||e.forEach(g=>{s.forEach((y,x)=>{y===g&&p.add(x)})}),p.size>0&&o(g=>{const y=new Map(g);return p.forEach(x=>y.delete(x)),y})},[t,e,s]);const i=ie(p=>{console.log("Generate analysis clicked for entity:",p.sha,p.name);const f=Hr(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]),c=ie(p=>{const f=p.filter(x=>x.entityType==="visual"||x.entityType==="library");console.log("Generate analysis for all entities:",f.length),o(x=>{const v=new Map(x);return f.forEach(b=>v.set(Hr(b),b.sha)),v});const g=f.map(x=>x.sha).join(","),y=new FormData;y.append("entityShas",g),r.submit(y,{method:"post",action:"/api/analyze"})},[r]),d=ie(p=>(e==null?void 0:e.includes(p))??!1,[e]),m=ie(p=>{const f=Hr(p);return s.has(f)},[s]),u=ie(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]),h=ae(()=>Array.from(s.keys()),[s]);return{isAnalyzing:r.state!=="idle",handleGenerateSimulation:i,handleGenerateAllSimulations:c,isEntityBeingAnalyzed:d,isEntityPending:m,isEntityInQueue:u,pendingEntityKeys:h}}function Ta({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:l("div",{className:"flex justify-between items-center px-3 py-2",children:[l("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4"}),n("span",{children:"FILE"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:n("span",{children:"STATE"})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:n("span",{children:"SIMULATIONS"})}),l("div",{className:"flex gap-4 items-center",children:[n("span",{className:"text-center",style:{width:"70px"},children:"ENTITIES"}),l("div",{className:"flex items-center justify-center gap-1 cursor-pointer hover:text-[#232323] transition-colors",style:{width:"116px"},onClick:r,role:"button",tabIndex:0,onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),r==null||r())},children:[n("span",{children:"MODIFIED"}),n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{transform:t==="asc"?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease"},children:n("path",{d:"M3 5L6 8L9 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),e&&n("div",{className:"text-center",style:{width:"127px"},children:a&&n("button",{onClick:a,disabled:s,className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors cursor-pointer disabled:bg-gray-400 disabled:cursor-not-allowed whitespace-nowrap px-3 py-1.5 normal-case",title:s?o:"Analyze all entities",children:o})})]})]})]})})}function y0({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 l("div",{className:"inline-flex items-center gap-1",children:[n("span",{className:`inline-flex items-center justify-center w-5 h-5 text-[11px] font-bold text-white rounded ${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 ja({filePath:e,isExpanded:t,onToggle:r,fileStatus:a,simulationPreviews:s,entityCount:o,state:i,lastModified:c,actionButton:d,uncommittedCount:m,children:u,isNotAnalyzable:h=!1,isUncommitted:p=!1}){return l("div",{className:"bg-white overflow-hidden",style:t?{border:"1px solid #e1e1e1",borderLeft:"4px solid #005C75",borderRadius:"8px"}:{borderBottom:"1px solid #e1e1e1"},children:[l("div",{className:`flex justify-between items-center p-3 cursor-pointer select-none transition-colors ${h?"opacity-50":"hover:bg-gray-200"}`,style:{outlineColor:"#005C75"},onClick:r,role:"button",tabIndex:0,onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),r())},children:[l("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:t?"rotate(90deg)":"none"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:t?"#3e3e3e":"#c7c7c7"})})}),n("img",{src:"/icons/file-icon.svg",alt:"file",className:"w-4 h-5 shrink-0"}),n(lo,{filePath:e}),a&&n(y0,{status:typeof a=="string"?a:a.status,variant:"full"}),p&&i==="out-of-date"&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:(p||i==="out-of-date")&&l("div",{className:"flex gap-1.5 items-center",children:[p&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fff3cd",color:"#856404",height:"22px"},children:"Uncommitted"}),i==="out-of-date"&&!p&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:s}),l("div",{className:"flex gap-4 items-center",children:[n("div",{className:"flex items-center justify-center",style:{width:"70px"},children:n("div",{className:"bg-[#f9f9f9] flex items-center justify-center px-2 rounded whitespace-nowrap",style:{height:"26px"},children:l("span",{className:"text-[13px] text-[#3e3e3e]",children:[o," ",o===1?"entity":"entities"]})})}),n("div",{className:"text-[12px] text-gray-600 text-center",style:{width:"116px"},children:ai(c)}),n("div",{style:{width:"127px"},className:"flex justify-center",children:d})]})]})]}),t&&u&&n("div",{className:"bg-gray-50 py-2 rounded-bl-[4px] rounded-br-[4px] flex flex-col gap-1",children:u})]})}function Ia({entities:e,maxPreviews:t=3}){var a,s,o,i,c;const r=[];for(const d of e){if(r.length>=t)break;const m=((s=(a=d.analyses)==null?void 0:a[0])==null?void 0:s.scenarios)||[];if(d.entityType==="library"){const u=m.find(h=>{var p,f;return((p=h.metadata)==null?void 0:p.executionResult)||((f=h.metadata)==null?void 0:f.error)});u&&r.push({type:"library",scenario:u,entitySha:d.sha})}else if(d.entityType==="visual"){const u=m.find(h=>{var p,f;return(f=(p=h.metadata)==null?void 0:p.screenshotPaths)==null?void 0:f[0]});if(u){const h=(i=(o=u.metadata)==null?void 0:o.screenshotPaths)==null?void 0:i[0],p=!!((c=u.metadata)!=null&&c.error);h&&r.push({type:"screenshot",screenshot:h,hasError:p,scenario:u,entitySha:d.sha})}}}return r.length===0?n("span",{className:"text-gray-400 font-light text-[14px]",children:"—"}):n(le,{children:r.map((d,m)=>{if(d.type==="screenshot"&&d.screenshot){const u=d.hasError?"border-red-400":"border-gray-200";return l(se,{to:d.scenario?`/entity/${d.entitySha}/scenarios/${d.scenario.id}`:`/entity/${d.entitySha}`,className:`relative w-[50px] h-[38px] border ${u} rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,onClick:h=>h.stopPropagation(),children:[n(Ye,{screenshotPath:d.screenshot,alt:`Preview ${m+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(Dn,{size:12,color:"white"})})]},`screenshot-${m}`)}return d.type==="library"&&d.scenario&&d.entitySha?n(ni,{scenario:d.scenario,entitySha:d.entitySha,size:"small",showBorder:!0},`library-${m}`):null})})}function $a({entity:e,isActivelyAnalyzing:t,isQueued:r,onGenerateSimulation:a}){var u,h;const s=t||r?[{entityShas:[e.sha]}]:[],o=qe(e,s,t),i=e.entityType==="visual"||e.entityType==="library",c=i&&(o==="not-analyzed"||o==="out-of-date")&&!t&&!r,m=(((h=(u=e.analyses)==null?void 0:u[0])==null?void 0:h.scenarios)||[]).filter(p=>{var f,g;return(g=(f=p.metadata)==null?void 0:f.screenshotPaths)==null?void 0:g[0]});return l("div",{className:"bg-white rounded-lg",children:[l(se,{to:`/entity/${e.sha}`,className:"flex items-center justify-between p-3 transition-colors hover:bg-gray-100 cursor-pointer",children:[l("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 shrink-0"}),e.entityType==="type"?n("div",{className:"bg-[#ffe1e1] inline-flex items-center justify-center px-[4px] rounded-[4px]",style:{height:"18px",width:"18px"},children:n("div",{className:"w-[10px] h-[10px] flex items-center justify-center",children:n(Ve,{type:"type"})})}):n(Ve,{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(Na,{type:e.entityType||"other"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{style:{width:"160px"}}),l("div",{className:"flex gap-4 items-center",children:[n("div",{style:{width:"70px"}}),n("div",{style:{width:"116px"}}),n("div",{style:{width:"127px"},className:"flex justify-center items-center",children:i?o==="queued"?l("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#cbf3fa",color:"#3098b4",height:"26px"},children:[l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]}),"Queued"]}):o==="analyzing"?l("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):o==="up-to-date"?n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):o==="out-of-date"?n("button",{onClick:p=>{p.preventDefault(),p.stopPropagation(),a(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):c&&n("button",{onClick:p=>{p.preventDefault(),p.stopPropagation(),a(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Analyze"}):n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"})})]})]})]}),m.length>0&&n("div",{className:"px-3 pb-3 pt-0 flex items-center gap-2 pl-[52px]",children:m.map((p,f)=>{var y,x;const g=(x=(y=p.metadata)==null?void 0:y.screenshotPaths)==null?void 0:x[0];return g?n(se,{to:`/entity/${e.sha}?scenario=${p.id}`,className:"relative w-[120px] h-[90px] border border-gray-200 rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center hover:border-gray-400 transition-colors",onClick:v=>v.stopPropagation(),children:n(Ye,{screenshotPath:g,alt:p.name,className:"max-w-full max-h-full object-contain object-center"})},p.id):null})})]})}function x0({entities:e,page:t,itemsPerPage:r=50,currentRun:a,filter:s,entityType:o,queueState:i,isEntityPending:c,pendingEntityKeys:d,onGenerateSimulation:m,onGenerateAllSimulations:u,totalFilesCount:h,totalEntitiesCount:p,uncommittedFilesCount:f,showOnlyUncommitted:g,onToggleUncommitted:y}){const[x,v]=cn(),[b,w]=_(new Set),[C,k]=_(""),[N,E]=_(!1),[S,M]=_("all"),[F,L]=_("desc"),P=o||"all",T=ae(()=>{let A=e;return P!=="all"&&(A=A.filter(G=>G.entityType===P)),s==="analyzed"&&(A=A.filter(G=>G.analyses&&G.analyses.length>0)),A},[e,P,s]),$=ae(()=>{const A=new Map,G=new Map,B=new Map;T.forEach(j=>{var te,de;const D=`${j.filePath}::${j.name}`,q=G.get(D);if(!q)G.set(D,j),B.set(D,[]);else{const ge=((te=q.metadata)==null?void 0:te.editedAt)||q.createdAt||"",pe=((de=j.metadata)==null?void 0:de.editedAt)||j.createdAt||"";let be=!1;if(pe>ge)be=!0;else if(pe===ge){const Ce=q.createdAt||"";be=(j.createdAt||"")>Ce}be?(B.get(D).push(q),G.set(D,j)):B.get(D).push(j)}}),G.forEach((j,D)=>{var te;if(!(j.analyses&&j.analyses.length>0)&&((te=j.metadata)!=null&&te.previousVersionWithAnalyses)){const ge=(B.get(D)||[]).find(pe=>{var be;return pe.sha===((be=j.metadata)==null?void 0:be.previousVersionWithAnalyses)});ge&&ge.analyses&&ge.analyses.length>0&&(j.analyses=ge.analyses)}}),Array.from(G.values()).sort((j,D)=>{var de,ge,pe,be;const q=!((de=j.metadata)!=null&&de.notExported)&&!((ge=j.metadata)!=null&&ge.namedExport),te=!((pe=D.metadata)!=null&&pe.notExported)&&!((be=D.metadata)!=null&&be.namedExport);return q&&!te?-1:!q&&te?1:0}).forEach(j=>{var ge,pe,be,Ce,ke;const D=j.filePath??"No File Path";A.has(D)||A.set(D,{filePath:D,entities:[],totalCount:0,uncommittedCount:0,lastUpdated:null,previewScreenshots:[],previewScreenshotErrors:[],previewLibraryScenarios:[],state:"up-to-date",simulationCount:0});const q=A.get(D);q.entities.push(j),q.totalCount++,(ge=j.metadata)!=null&&ge.isUncommitted&&q.uncommittedCount++;const te=((Ce=(be=(pe=j.analyses)==null?void 0:pe[0])==null?void 0:be.scenarios)==null?void 0:Ce.length)||0;q.simulationCount+=te;const de=((ke=j.metadata)==null?void 0:ke.editedAt)||j.updatedAt;de&&(!q.lastUpdated||new Date(de)>new Date(q.lastUpdated))&&(q.lastUpdated=de)});const H=(i==null?void 0:i.jobs)||[],re=j=>{const D=`${j.filePath||""}::${j.name}`;return(d==null?void 0:d.includes(D))||!1};A.forEach(j=>{const D=j.entities.map(q=>re(q)?"queued":qe(q,H));D.includes("analyzing")||D.includes("queued")?j.state="analyzing":D.includes("incomplete")?j.state="incomplete":D.includes("out-of-date")?j.state="out-of-date":D.includes("not-analyzed")?j.state="not-analyzed":j.state="up-to-date"}),A.forEach(j=>{var D,q,te,de,ge;for(const pe of j.entities){if(j.previewScreenshots.length+j.previewLibraryScenarios.length>=3)break;const Ce=((q=(D=pe.analyses)==null?void 0:D[0])==null?void 0:q.scenarios)||[];if(pe.entityType==="library"){const ke=Ce.find(Se=>{var _e,Te;return((_e=Se.metadata)==null?void 0:_e.executionResult)||((Te=Se.metadata)==null?void 0:Te.error)});ke&&j.previewLibraryScenarios.push({scenario:ke,entitySha:pe.sha})}else{const ke=Ce.find(Se=>{var _e,Te;return(Te=(_e=Se.metadata)==null?void 0:_e.screenshotPaths)==null?void 0:Te[0]});if(ke){const Se=(de=(te=ke.metadata)==null?void 0:te.screenshotPaths)==null?void 0:de[0],_e=!!((ge=ke.metadata)!=null&&ge.error);Se&&!j.previewScreenshots.includes(Se)&&(j.previewScreenshots.push(Se),j.previewScreenshotErrors.push(_e))}}}});const O=Array.from(A.values());return O.sort((j,D)=>{if(s==="analyzed"){const de=Math.max(...j.entities.filter(pe=>{var be,Ce;return(Ce=(be=pe.analyses)==null?void 0:be[0])==null?void 0:Ce.createdAt}).map(pe=>new Date(pe.analyses[0].createdAt).getTime()),0),ge=Math.max(...D.entities.filter(pe=>{var be,Ce;return(Ce=(be=pe.analyses)==null?void 0:be[0])==null?void 0:Ce.createdAt}).map(pe=>new Date(pe.analyses[0].createdAt).getTime()),0);return F==="desc"?ge-de:de-ge}if(j.uncommittedCount>0&&D.uncommittedCount===0)return-1;if(j.uncommittedCount===0&&D.uncommittedCount>0)return 1;const q=j.lastUpdated?new Date(j.lastUpdated).getTime():0,te=D.lastUpdated?new Date(D.lastUpdated).getTime():0;return F==="desc"?te-q:q-te}),O},[T,s,F,i,d]),I=ae(()=>{let A=$;if(S!=="all"&&(A=A.filter(G=>G.state===S)),C.trim()){const G=C.toLowerCase();A=A.filter(B=>B.filePath.toLowerCase().includes(G))}return A},[$,C,S]),J=(t-1)*r,V=J+r,U=I.slice(J,V),z=Math.ceil(I.length/r),Y=A=>{w(G=>{const B=new Set(G);return B.has(A)?B.delete(A):B.add(A),B})},R=()=>{L(A=>A==="desc"?"asc":"desc")};return l("div",{children:[l("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),l("div",{className:"flex gap-3",children:[l("div",{className:"relative w-[130px]",children:[l("select",{value:P,onChange:A=>{const G=A.target.value,B=new URLSearchParams(x);G==="all"?B.delete("entityType"):B.set("entityType",G),B.set("page","1"),v(B)},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(Qe,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),l("div",{className:"relative w-[130px]",children:[l("select",{value:S,onChange:A=>M(A.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(Qe,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),l("div",{className:"flex-1 relative",children:[n(dn,{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:C,onChange:A=>k(A.target.value),className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})]})]}),h!==void 0&&p!==void 0&&f!==void 0&&n("div",{className:"mb-3",children:l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center",children:[l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:I.length})," ",I.length===1?"file":"files"]}),l("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:I.reduce((A,G)=>A+G.totalCount,0)})," ",I.reduce((A,G)=>A+G.totalCount,0)===1?"entity":"entities"]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),g?l("button",{onClick:y,className:"flex items-center gap-2 text-[#005c75] underline hover:text-[#004a5e] transition-colors ml-2 font-mono uppercase cursor-pointer",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[I.filter(A=>A.uncommittedCount>0).length," ","uncommitted"," ",I.filter(A=>A.uncommittedCount>0).length===1?"file":"files",n("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M6 18L18 6M6 6l12 12"})})]}):l("button",{onClick:y,className:"text-[#005c75] underline hover:text-[#004a5e] transition-colors ml-2 font-mono uppercase",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[f," uncommitted"," ",f===1?"file":"files"]})]}),U.length>0&&l("div",{className:"flex gap-6",children:[l("button",{onClick:()=>{w(new Set(U.map(A=>A.filePath))),E(!0)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(eo,{className:"w-3.5 h-3.5"}),"Expand All"]}),l("button",{onClick:()=>{w(new Set),E(!1)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(to,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),n(Ta,{showActions:!0,sortOrder:F,onSortChange:R}),n("div",{className:"flex flex-col gap-[3px]",children:U.map(A=>{const G=b.has(A.filePath),H=A.entities.filter(D=>(D.entityType==="visual"||D.entityType==="library")&&(qe(D,(i==null?void 0:i.jobs)||[])==="not-analyzed"||qe(D,(i==null?void 0:i.jobs)||[])==="out-of-date"||qe(D,(i==null?void 0:i.jobs)||[])==="incomplete")).length>0,re=D=>{var q;return((q=a==null?void 0:a.currentEntityShas)==null?void 0:q.includes(D))||!1},O=D=>{var q;return c!=null&&c(D)?!0:((q=i==null?void 0:i.jobs)==null?void 0:q.some(te=>{var de;return(de=te.entityShas)==null?void 0:de.includes(D.sha)}))||!1},j=D=>{m==null||m(D)};return n(ja,{filePath:A.filePath,isExpanded:G,onToggle:()=>Y(A.filePath),simulationPreviews:n(Ia,{entities:A.entities,maxPreviews:1}),entityCount:A.totalCount,state:A.state,lastModified:A.lastUpdated,uncommittedCount:A.uncommittedCount,isUncommitted:A.uncommittedCount>0,actionButton:H?n("button",{onClick:D=>{D.stopPropagation();const q=A.entities.filter(te=>(te.entityType==="visual"||te.entityType==="library")&&(qe(te,(i==null?void 0:i.jobs)||[])==="not-analyzed"||qe(te,(i==null?void 0:i.jobs)||[])==="out-of-date"||qe(te,(i==null?void 0:i.jobs)||[])==="incomplete"));u==null||u(q)},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:A.state==="out-of-date"?"Re-analyze":"Analyze"}):void 0,children:A.entities.sort((D,q)=>{var be,Ce,ke,Se;const te=!((be=D.metadata)!=null&&be.notExported)&&!((Ce=D.metadata)!=null&&Ce.namedExport),de=!((ke=q.metadata)!=null&&ke.notExported)&&!((Se=q.metadata)!=null&&Se.namedExport);if(te&&!de)return-1;if(!te&&de)return 1;const ge=D.entityType==="visual"||D.entityType==="library",pe=q.entityType==="visual"||q.entityType==="library";return ge&&!pe?-1:!ge&&pe?1:D.name.localeCompare(q.name)}).map(D=>n($a,{entity:D,isActivelyAnalyzing:re(D.sha),isQueued:O(D),onGenerateSimulation:j},D.sha))},A.filePath)})}),z>1&&l("div",{className:"flex justify-center items-center gap-4 mt-6 p-4",children:[t>1&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(x),page:String(t-1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"← Previous"}),l("span",{children:["Page ",t," of ",z]}),t<z&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(x),page:String(t+1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"Next →"})]})]})}const b0=()=>[{title:"Files & Entities - CodeYam"},{name:"description",content:"Browse your codebase files and entities"}];async function v0({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,c=i?i.getState():{paused:!1,jobs:[]},[d,m]=await Promise.all([pn(),Bt()]);return W({entities:d,currentCommit:m,page:a,filter:s,entityType:o,queueState:c})}catch(r){return console.error("Failed to load entities:",r),W({entities:[],currentCommit:null,page:1,filter:null,entityType:null,queueState:{paused:!1,jobs:[]},error:"Failed to load entities"})}}const w0=De(function(){var C,k,N;const{entities:t,currentCommit:r,page:a,filter:s,entityType:o,queueState:i,error:c}=Be();it();const[d,m]=cn(),[u,h]=_(!1);tt({source:"files-page"});const{handleGenerateSimulation:p,handleGenerateAllSimulations:f,isEntityPending:g,pendingEntityKeys:y}=yi((k=(C=r==null?void 0:r.metadata)==null?void 0:C.currentRun)==null?void 0:k.currentEntityShas,i),x=t||[],v=ae(()=>{const E=new Set([]);for(const S of x)E.add(S.filePath??"No File Path");return Array.from(E)},[x]),b=ae(()=>{let E=x;return u&&(E=E.filter(S=>{var M;return(M=S.metadata)==null?void 0:M.isUncommitted})),E.sort((S,M)=>{var F,L,P,T,$,I;return(F=S.metadata)!=null&&F.isUncommitted&&!((L=M.metadata)!=null&&L.isUncommitted)?-1:!((P=S.metadata)!=null&&P.isUncommitted)&&((T=M.metadata)!=null&&T.isUncommitted)?1:new Date((($=M.metadata)==null?void 0:$.editedAt)||0).getTime()-new Date(((I=S.metadata)==null?void 0:I.editedAt)||0).getTime()})},[x,u]),w=ae(()=>{var S;const E=new Set([]);for(const M of x)(S=M.metadata)!=null&&S.isUncommitted&&E.add(M.filePath??"No File Path");return Array.from(E)},[x]);return c?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:c})]})}):x.length===0?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-20 py-12 font-sans",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:l("div",{className:"max-w-md mx-auto",children:[n("h2",{className:"text-xl font-semibold text-gray-900 mb-3",children:"No entities found"}),l("p",{className:"text-[15px] text-gray-600 mb-6",children:["Your project hasn't been analyzed yet. Run"," ",n("code",{className:"px-2 py-1 bg-gray-100 rounded text-sm font-mono",children:"codeyam analyze"})," ","to extract entities from your codebase."]}),n("p",{className:"text-sm text-gray-500",children:"Entities include React components, functions, and other analyzable code elements."})]})})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-20 py-12 font-sans",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),n(x0,{entities:b,page:a,itemsPerPage:50,currentRun:(N=r==null?void 0:r.metadata)==null?void 0:N.currentRun,filter:s,entityType:o,queueState:i,isEntityPending:g,pendingEntityKeys:y,onGenerateSimulation:p,onGenerateAllSimulations:f,totalFilesCount:v.length,totalEntitiesCount:x.length,uncommittedFilesCount:w.length,showOnlyUncommitted:u,onToggleUncommitted:()=>h(!u)})]})})}),C0=Object.freeze(Object.defineProperty({__proto__:null,default:w0,loader:v0,meta:b0},Symbol.toStringTag,{value:"Module"})),N0=()=>[{title:"Labs - CodeYam"},{name:"description",content:"Experimental features"}];async function S0({request:e}){var t;try{const r=await $e();if(!r)return W({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Project not found"});const{project:a}=await Ie(r),s=fe()||process.cwd(),o=Xo(s)||"";let i="";try{const d=await cr();if(d!=null&&d.webapps&&Array.isArray(d.webapps)){const m=d.webapps.map(u=>u.framework).filter(Boolean);m.length>0&&(i=m.join(", "))}}catch{}const c=ti(r);return W({labs:((t=a.metadata)==null?void 0:t.labs)??null,projectSlug:r,defaultEmail:o,detectedTechStack:i,unlockCode:c,error:null})}catch(r){return console.error("Failed to load labs config:",r),W({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Failed to load labs configuration"})}}async function k0({request:e}){try{const t=await e.formData(),r=t.get("feature"),a=t.get("enabled")==="true";if(!r)return W({success:!1,error:"Missing feature name"},{status:400});const s=await $e();return s?(r==="clearAccess"?await Hn({projectSlug:s,metadataUpdate:{labs:{accessGranted:!1,simulations:!1}}}):await Hn({projectSlug:s,metadataUpdate:{labs:{[r]:a}}}),W({success:!0,error:null})):W({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("Failed to update labs config:",t),W({success:!1,error:"Failed to save labs configuration"},{status:500})}}const E0=[{id:"simulations",name:"Simulations",description:"Enable entity analysis, visual simulations, git impact analysis, file browsing, and activity monitoring. When disabled, only Memory, Labs, and Settings are accessible.",defaultEnabled:!0},{id:"enhancedClaudeTesting",name:"Enhanced Claude Testing",description:"Automatically generated mock data that covers the scenarios you actually care about: empty states, error states, auth flows, broken images, missing permissions.",defaultEnabled:!0},{id:"gitIntegration",name:"Git Integration Showing Impacted Files",description:"Lorem Ipsum Automatically generated mock data that covers the scenarios you actually care about: empty states, error states, auth flows, broken images, missing permissions.",defaultEnabled:!1}],Gs="https://docs.google.com/forms/d/e/1FAIpQLSfopqQOQsjY9S4Ns0l3xDLzGl7iYNpKa2Wn2Xzmtxj8CR1sMA/viewform",A0=[{title:"CodeYam Simulations",status:"apply for early access",desc:"CodeYam Simulations are the core of the CodeYam development experience. They leverage static code analysis and AI to generate robust data scenarios that are used to hydrate code. This creates a whole new dimension to the software development experience"},{title:"The Full CodeYam Experience",status:"more to come",desc:"CodeYam is completely rethinking the software development experience in the AI era. Focused on navigating the challenges of iteration speed, complexity, and communication, CodeYam will provide a powerful software development experience."}];function _0({onClose:e}){const t=Ne(null),r=Ne(0);return ee(()=>{const a=t.current;if(!a)return;const s=100,o=2e3,i=500;let c=null,d=!1;const m=()=>{r.current=Date.now(),!c&&!d&&(c=setInterval(()=>{const u=Date.now()-r.current,h=a.scrollTop>s,p=u>o;h&&p&&(a.scrollTo({top:0,behavior:"smooth"}),d=!0,c&&(clearInterval(c),c=null))},i))};return a.addEventListener("scroll",m,{passive:!0}),()=>{a.removeEventListener("scroll",m),c&&clearInterval(c)}},[]),l("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:a=>{a.target===a.currentTarget&&e()},children:[n("div",{className:"absolute inset-0 bg-black/50"}),l("div",{className:"relative bg-white rounded-xl max-w-3xl w-full mx-4 max-h-[90vh] overflow-hidden",children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none cursor-pointer bg-transparent border-none z-10",children:"×"}),l("div",{ref:t,className:"overflow-y-auto max-h-[90vh] p-4 md:p-6",children:[l("div",{className:"mb-4",children:[n("h3",{className:"font-serif italic text-2xl text-primary-200 mb-2",children:"Request Early Access"}),n("p",{className:"text-sm text-gray-500",children:"Complete the form below to join the waitlist for CodeYam Labs."})]}),n("div",{className:"bg-white rounded-lg overflow-hidden",children:n("iframe",{src:`${Gs}?embedded=true`,width:"100%",height:"1400",style:{border:0,minHeight:"1400px"},title:"Labs Waitlist Form",loading:"eager",children:n("div",{className:"flex items-center justify-center p-8 text-gray-600",children:l("div",{className:"text-center",children:[n("div",{className:"mb-4",children:"Loading form..."}),l("div",{className:"text-sm",children:["If this takes too long,"," ",n("a",{href:Gs,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 underline",children:"open the form directly"})]})]})})})})]})]})]})}function P0({onClose:e,unlockCodeInput:t,setUnlockCodeInput:r,unlockFetcher:a}){var i,c;const s=(i=a.data)==null?void 0:i.error,o=(c=a.data)==null?void 0:c.success;return l("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:d=>{d.target===d.currentTarget&&e()},children:[n("div",{className:"absolute inset-0 bg-black/50"}),l("div",{className:"relative bg-white rounded-xl p-8 max-w-md w-full mx-4",children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none cursor-pointer bg-transparent border-none",children:"×"}),n("h3",{className:"font-serif italic text-2xl text-primary-200 mb-2",children:"Have an unlock code?"}),n("p",{className:"text-sm text-cygray-50 mb-6",children:"If you've received an unlock code, paste it below to enable Simulations immediately."}),l(a.Form,{method:"post",action:"/api/labs-unlock",className:"space-y-4",children:[n("input",{type:"text",name:"unlockCode",value:t,onChange:d=>r(d.target.value),placeholder:"CY-...",className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-100 focus:border-transparent"}),n("button",{type:"submit",disabled:!t.trim()||a.state==="submitting",className:"w-full py-3 text-white border-none rounded-lg text-sm font-mono font-semibold uppercase tracking-wider cursor-pointer transition-all bg-primary-200 hover:bg-primary-100 disabled:bg-gray-400 disabled:cursor-not-allowed",children:a.state==="submitting"?"Validating...":"Unlock"}),s&&n("p",{className:"text-red-600 text-sm mt-2",children:s}),o&&n("p",{className:"text-emerald-600 text-sm mt-2",children:"Simulations enabled! Refresh the page to see all tabs."})]})]})]})}const M0=De(function(){const{labs:t,unlockCode:r,error:a}=Be(),s=Ee(),o=Ee(),i=Ee(),[c,d]=_(""),[m,u]=_(!1),[h,p]=_(!1);tt({source:"labs-page"});const f=(t==null?void 0:t.accessGranted)===!0||(t==null?void 0:t.simulations)===!0;return a?n("div",{className:"bg-cygray-10 min-h-screen",children:l("div",{className:"px-20 pt-8 pb-12 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Labs"}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 mt-4",children:n("p",{className:"text-red-700",children:a})})]})}):f?l("div",{className:"bg-cygray-10 min-h-screen font-sans flex flex-col",children:[n("div",{className:"px-6 sm:px-12 pt-8 pb-4",children:n("h1",{className:"font-mono text-lg font-semibold tracking-widest text-cyblack-100 m-0",children:"LABS"})}),l("div",{className:"px-6 sm:px-12 pt-8 pb-10",children:[n("h2",{className:"font-serif italic text-[32px] sm:text-[48px] text-primary-100 mb-3 font-normal leading-tight",children:"Congrats!"}),n("p",{className:"font-serif text-[18px] sm:text-[24px] text-cyblack-100 font-normal leading-snug max-w-2xl",children:"You were granted early access to software simulation and other experimental features."})]}),n("div",{className:"px-6 sm:px-12 space-y-6 flex-1",children:E0.map(g=>{var v;const y=(t==null?void 0:t[g.id])??g.defaultEnabled,x=o.state==="submitting"&&((v=o.formData)==null?void 0:v.get("feature"))===g.id;return n("div",{className:"border border-cygray-30 rounded-xl p-5 sm:p-8 bg-white",children:l("div",{className:"flex items-center justify-between gap-4",children:[l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-3 mb-3",children:[n("h3",{className:"text-lg font-semibold text-cyblack-100 m-0",children:g.name}),n("span",{className:`inline-flex items-center px-2.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ${y?"bg-primary-100/15 text-primary-100":"bg-cygray-20 text-cygray-50"}`,children:y?"Enabled":"Disabled"})]}),n("p",{className:"text-sm text-cygray-50 leading-relaxed m-0",children:g.description})]}),l(o.Form,{method:"post",children:[n("input",{type:"hidden",name:"feature",value:g.id}),n("input",{type:"hidden",name:"enabled",value:String(!y)}),n("button",{type:"submit",disabled:x,className:`relative inline-flex h-8 w-14 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none disabled:opacity-60 disabled:cursor-not-allowed ${y?"bg-primary-100":"bg-gray-300"}`,children:n("span",{className:`pointer-events-none inline-block h-7 w-7 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${y?"translate-x-6":"translate-x-0"}`})})]})]})},g.id)})}),r&&n("div",{className:"px-6 sm:px-12 pt-12",children:l("div",{className:"border border-cygray-30 rounded-xl p-5 sm:p-8 bg-white",children:[n("h3",{className:"text-base font-semibold text-cyblack-100 mb-1",children:"Unlock Code"}),n("p",{className:"text-sm text-cygray-50 mb-3",children:"This code was used to enable Labs access. Clear it to revoke access and return to the landing page."}),l("div",{className:"flex flex-col sm:flex-row sm:items-center gap-3",children:[n("code",{className:"sm:flex-1 px-4 py-2.5 bg-cygray-10 border border-cygray-30 rounded-lg text-sm font-mono text-cyblack-100 overflow-x-auto",children:r}),l(i.Form,{method:"post",children:[n("input",{type:"hidden",name:"feature",value:"clearAccess"}),n("input",{type:"hidden",name:"enabled",value:"false"}),n("button",{type:"submit",disabled:i.state==="submitting",className:"px-4 py-2.5 bg-red-50 border border-red-200 rounded-lg text-sm font-medium text-red-700 cursor-pointer transition-colors hover:bg-red-100 disabled:opacity-60 disabled:cursor-not-allowed",children:i.state==="submitting"?"Clearing...":"Clear"})]})]})]})})]}):l("div",{className:"bg-cygray-10 min-h-screen font-sans",children:[m&&n(_0,{onClose:()=>u(!1)}),h&&n(P0,{onClose:()=>p(!1),unlockCodeInput:c,setUnlockCodeInput:d,unlockFetcher:s}),l("div",{className:"flex flex-wrap justify-between items-center gap-3 px-6 sm:px-12 pt-8 pb-4",children:[n("h1",{className:"font-mono text-lg font-semibold tracking-widest text-cyblack-100 m-0",children:"LABS"}),l("div",{className:"flex flex-wrap items-center gap-3",children:[n("button",{onClick:()=>p(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-4 sm:px-5 py-2.5 rounded border border-cygray-30 bg-transparent text-cygray-50 cursor-pointer transition-colors hover:border-cyblack-100 hover:text-cyblack-100",children:"Have a Code?"}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-4 sm:px-5 py-2.5 rounded border border-cyblack-100 bg-transparent text-cyblack-100 cursor-pointer transition-colors hover:bg-cyblack-100 hover:text-white",children:"Apply for Early Access"})]})]}),l("div",{className:"px-6 sm:px-12 pt-12 pb-8",children:[n("h2",{className:"font-serif text-[24px] sm:text-[32px] leading-snug text-cyblack-100 max-w-xl mb-4 font-normal",children:"Powerful tools for the AI coding era."}),l("p",{className:"text-base sm:text-lg text-cygray-50 leading-relaxed max-w-xl mb-8",children:["We're opening early access to"," ",n("strong",{className:"text-cyblack-100",children:"experimental features"})," to a small group of developers and teams."]}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-6 py-3 rounded bg-primary-200 text-white border-none cursor-pointer transition-colors hover:bg-primary-100",children:"Apply for Early Access"})]}),n("div",{className:"px-6 sm:px-12 py-8",children:n("hr",{className:"border-t border-cygray-30 m-0"})}),l("div",{className:"px-6 sm:px-12 pt-8 pb-4",children:[n("h3",{className:"font-serif text-[22px] sm:text-[28px] text-cyblack-100 mb-10 font-normal text-center",children:"In The Works"}),n("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-5 max-w-4xl mx-auto",children:A0.map(g=>l("div",{className:"border border-cygray-30 bg-white p-5 sm:p-8 rounded-lg",children:[l("h4",{className:"text-base font-semibold text-cyblack-100 mb-1",children:[g.title," ",l("span",{className:"font-normal text-primary-100 font-serif italic",children:["(",g.status,")"]})]}),n("p",{className:"text-sm text-cygray-50 leading-relaxed mt-3 mb-0",children:g.desc})]},g.title))})]}),n("div",{className:"px-6 sm:px-12 py-16",children:l("div",{className:"rounded-lg p-6 sm:p-12 bg-primary-200",children:[n("h3",{className:"font-serif text-[20px] sm:text-[24px] text-white mb-4 font-semibold",children:"Request Early Access"}),n("p",{className:"text-sm text-white/80 leading-relaxed max-w-lg mb-10 font-mono",children:"We're onboarding a limited number of developers and teams. Tell us about how you build and we'll let you know when you can try simulations and other Labs features."}),n("button",{onClick:()=>u(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-6 py-3 rounded border border-white bg-white text-cyblack-100 cursor-pointer transition-colors hover:bg-white/90 mb-4",children:"Apply for Early Access"}),n("p",{className:"text-xs text-white/60 m-0",children:"Takes about 2 minutes. Your answers help us determine eligibility and prioritize access."})]})})]})}),T0=Object.freeze(Object.defineProperty({__proto__:null,action:k0,default:M0,loader:S0,meta:N0},Symbol.toStringTag,{value:"Module"}));function j0(e,t,r){const[a,s]=_(()=>new Set),[o,i]=_(()=>new Set),c=Ne([]),d=Ne([]);return ee(()=>{(t.length!==c.current.length||t.some((y,x)=>y!==c.current[x]))&&(c.current=t,s(y=>{const x=new Set;return t.forEach(v=>{y.has(v)&&x.add(v)}),x}))},[t]),ee(()=>{(r.length!==d.current.length||r.some((y,x)=>y!==d.current[x]))&&(d.current=r,i(y=>{const x=new Set;return r.forEach(v=>{y.has(v)&&x.add(v)}),x}))},[r]),{expandedUncommitted:a,expandedBranch:o,setExpandedUncommitted:s,setExpandedBranch:i,toggleFile:(g,y,x)=>{x(v=>{const b=new Set(v);return b.has(g)?b.delete(g):b.add(g),b})},expandAllUncommitted:()=>{s(new Set(t))},collapseAllUncommitted:()=>{s(new Set)},expandAllBranch:()=>{i(new Set(r))},collapseAllBranch:()=>{i(new Set)}}}function I0(e,t,r){const[a,s]=_(null),[o,i]=_(null),c=Ee();ee(()=>{var h,p;((h=c.data)==null?void 0:h.oldContent)!==void 0&&((p=c.data)==null?void 0:p.newContent)!==void 0&&i({oldContent:c.data.oldContent,newContent:c.data.newContent,fileName:c.data.fileName})},[c.data]);const d=h=>{s({type:"file",path:h}),i(null);const p=new FormData;p.append("actionType","getDiff"),p.append("filePath",h),p.append("diffType","branch"),p.append("baseBranch",e),p.append("currentBranch",t||""),c.submit(p,{method:"post"})},m=(h,p)=>{s({type:"entity",path:h,entitySha:p}),i(null);const f=new FormData;f.append("actionType","getDiff"),f.append("filePath",h),f.append("diffType","branch"),f.append("baseBranch",e),f.append("currentBranch",t||""),f.append("entitySha",p),c.submit(f,{method:"post"})},u=()=>{s(null),i(null)};return{diffView:a,diffContent:o,isLoading:c.state==="loading"||c.state==="submitting",handleShowFileDiff:d,handleShowEntityDiff:m,handleCloseDiff:u}}function $0({diffView:e,diffContent:t,isLoading:r,entities:a,onClose:s}){var m;const[o,i]=_(!1),[c,d]=_(!1);return ee(()=>{d(!0)},[]),n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-8 z-50",children:l("div",{className:"bg-white rounded-xl shadow-2xl max-w-6xl w-full max-h-[90vh] flex flex-col",children:[l("div",{className:"p-6 border-b border-[#e1e1e1] flex items-center justify-between",children:[l("div",{children:[n("h2",{className:"font-['IBM_Plex_Sans'] text-2xl font-semibold text-[#232323]",children:e.type==="file"?"File Diff":"Entity Diff"}),n("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e] mt-1",children:e.path}),e.type==="entity"&&e.entitySha&&l("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e]",children:["Entity:"," ",((m=a.find(u=>u.sha===e.entitySha))==null?void 0:m.name)||e.entitySha]})]}),l("div",{className:"flex items-center gap-3",children:[n("button",{onClick:()=>i(!o),className:"px-3 py-1.5 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] text-sm font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",title:o?"Show changes only":"Show full file",children:o?"Show Changes Only":"Show Full File"}),n("button",{onClick: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:c&&n(Gl,{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 R0({files:e,currentBranch:t,defaultBranch:r,baseBranch:a,allBranches:s,expandedFiles:o,isEntityBeingAnalyzed:i,isEntityQueued:c,sortOrder:d,onToggleFile:m,onBranchChange:u,onGenerateSimulation:h,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}){const x=e.flatMap(([w,{entities:C}])=>{const k=C.filter(N=>i(N.sha)||c(N)).map(N=>N.sha);return k.length>0?[{entityShas:k}]:[]}),v=w=>{const C=w.map(k=>qe(k,x));return C.includes("analyzing")||C.includes("queued")?"analyzing":C.includes("out-of-date")?"out-of-date":C.includes("not-analyzed")?"not-analyzed":"up-to-date"},b=ae(()=>[...e].sort((w,C)=>{const k=w[1].entities.reduce((M,F)=>{var P;const L=((P=F.metadata)==null?void 0:P.editedAt)||F.updatedAt;return L?M?new Date(L)>new Date(M)?L:M:L:M},null),N=C[1].entities.reduce((M,F)=>{var P;const L=((P=F.metadata)==null?void 0:P.editedAt)||F.updatedAt;return L?M?new Date(L)>new Date(M)?L:M:L:M},null);if(!k&&!N)return 0;if(!k)return 1;if(!N)return-1;const E=new Date(k).getTime(),S=new Date(N).getTime();return d==="desc"?S-E:E-S}),[e,d]);return n("div",{children:e.length>0?l("div",{children:[n(Ta,{showActions:!0,sortOrder:d,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}),n("div",{className:"flex flex-col gap-[3px]",children:b.map(([w,{status:C,entities:k,isUncommitted:N}])=>{const E=o.has(w),S=v(k),M=k.reduce((T,$)=>{var J;const I=((J=$.metadata)==null?void 0:J.editedAt)||$.updatedAt;return I?T?new Date(I)>new Date(T)?I:T:I:T},null),L=k.filter(T=>T.entityType==="visual"||T.entityType==="library").length===0;let P;return L?P=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):S==="analyzing"?P=l("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):S==="up-to-date"?P=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"}):S==="out-of-date"?P=n("button",{onClick:T=>{T.stopPropagation(),k.filter($=>($.entityType==="visual"||$.entityType==="library")&&!i($.sha)&&!c($)).forEach($=>h($))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):S==="not-analyzed"&&(P=n("button",{onClick:T=>{T.stopPropagation(),k.filter($=>($.entityType==="visual"||$.entityType==="library")&&!i($.sha)&&!c($)).forEach($=>h($))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(ja,{filePath:w,isExpanded:E,onToggle:()=>m(w),fileStatus:C,isUncommitted:N,simulationPreviews:n(Ia,{entities:k,maxPreviews:1}),entityCount:k.length,state:S,lastModified:M,isNotAnalyzable:L,actionButton:P,children:k.sort((T,$)=>{const I=T.entityType==="visual"||T.entityType==="library",J=$.entityType==="visual"||$.entityType==="library";return I&&!J?-1:!I&&J?1:0}).map(T=>n($a,{entity:T,isActivelyAnalyzing:i(T.sha),isQueued:c(T),onGenerateSimulation:h},T.sha))},w)})})]}):l("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"No files have been modified in this branch."})]})})}function D0({files:e,entityImpactMap:t,expandedFiles:r,isEntityBeingAnalyzed:a,isEntityQueued:s,projectSlug:o,baseBranch:i,currentBranch:c,sortOrder:d,onToggleFile:m,onShowFileDiff:u,onGenerateSimulation:h,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}){const x=ae(()=>{const w=[];return e.forEach(([C,{editedEntities:k}])=>{const N=k.filter(E=>a(E.sha)||s(E)).map(E=>E.sha);N.length>0&&w.push({entityShas:N})}),w},[e,a,s]),v=ae(()=>{const w=new Map;return e.forEach(([C,{editedEntities:k}])=>{const N=k.map(F=>qe(F,x));let E;N.includes("analyzing")||N.includes("queued")?E="analyzing":N.includes("out-of-date")?E="out-of-date":N.includes("not-analyzed")?E="not-analyzed":E="up-to-date";const S=k.reduce((F,L)=>{var T;const P=((T=L.metadata)==null?void 0:T.editedAt)||L.updatedAt;return P&&(!F||new Date(P)>new Date(F))?P:F},null),M=k.filter(F=>F.entityType==="visual"||F.entityType==="library").length;w.set(C,{state:E,lastModified:S,analyzableCount:M})}),w},[e,x]),b=ae(()=>[...e].sort((w,C)=>{const k=v.get(w[0]),N=v.get(C[0]),E=k==null?void 0:k.lastModified,S=N==null?void 0:N.lastModified;if(!E&&!S)return 0;if(!E)return 1;if(!S)return-1;const M=new Date(E).getTime(),F=new Date(S).getTime();return d==="desc"?F-M:M-F}),[e,v,d]);return e.length===0?l("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Uncommitted Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"If you edit a file in your project, it will show up here."})]}):l("div",{children:[n(Ta,{showActions:!0,sortOrder:d,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}),n("div",{className:"flex flex-col gap-[3px]",children:b.map(([w,{status:C,editedEntities:k}])=>{const N=r.has(w),E=v.get(w),{state:S,lastModified:M,analyzableCount:F}=E,L=F===0;let P;return L?P=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):S==="analyzing"?P=l("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):S==="up-to-date"?P=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"}):S==="out-of-date"?P=n("button",{onClick:T=>{T.stopPropagation(),k.filter($=>($.entityType==="visual"||$.entityType==="library")&&!a($.sha)&&!s($)).forEach($=>h($))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):S==="not-analyzed"&&(P=n("button",{onClick:T=>{T.stopPropagation(),k.filter($=>($.entityType==="visual"||$.entityType==="library")&&!a($.sha)&&!s($)).forEach($=>h($))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(ja,{filePath:w,isExpanded:N,onToggle:()=>m(w),fileStatus:C,simulationPreviews:n(Ia,{entities:k,maxPreviews:1}),entityCount:k.length,state:S,lastModified:M,isNotAnalyzable:L,isUncommitted:!0,actionButton:P,children:k.sort((T,$)=>{const I=T.entityType==="visual"||T.entityType==="library",J=$.entityType==="visual"||$.entityType==="library";return I&&!J?-1:!I&&J?1:0}).map(T=>n($a,{entity:T,isActivelyAnalyzing:a(T.sha),isQueued:s(T),onGenerateSimulation:h},T.sha))},w)})})]})}function L0({activeTab:e,onTabChange:t,uncommittedCount:r,branchCount:a}){return n("div",{className:"border-b border-gray-200",children:l("nav",{className:"flex gap-8 items-center",children:[l("button",{onClick:()=>t("branch"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="branch"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[l("span",{className:"flex items-center gap-2",children:["Branch Changes",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-px left-0 right-0 h-0.5 bg-primary-100"})]}),l("button",{onClick:()=>t("uncommitted"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="uncommitted"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[l("span",{className:"flex items-center gap-2",children:["Uncommitted Changes",r>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="uncommitted"?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:r})]}),e==="uncommitted"&&n("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]})]})})}const F0=()=>[{title:"Git - CodeYam"},{name:"description",content:"Git status and impact analysis"}];async function O0({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"),c=t.get("entitySha");let d;return s==="branch"?d=jn(a,o,i):d=bh(a),W({...d,entitySha:c})}return W({error:"Unknown action"},{status:400})}async function z0({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:[]},[c,d,m]=await Promise.all([pn(),Bt(),$e()]),u=Go(),h=ph(),p=fh(),f=gh(),g=s||h,y=a||p;let x=[];return g&&g!==y&&(x=qo(y,g)),W({entities:c||[],gitStatus:u,currentBranch:g,actualCurrentBranch:h,defaultBranch:p,allBranches:f,baseBranch:y,branchDiff:x,currentCommit:d,projectSlug:m,queueState:i})}catch(r){return console.error("Failed to load git data:",r),W({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 Y0=De(function(){var ye,Ct;const{entities:t,gitStatus:r,currentBranch:a,actualCurrentBranch:s,defaultBranch:o,allBranches:i,baseBranch:c,branchDiff:d,currentCommit:m,projectSlug:u,queueState:h}=Be();tt({source:"git-page"});const[p,f]=cn(),[g,y]=_(null),[x,v]=_("desc"),[b,w]=_("branch"),C=p.get("expanded")==="true",k=()=>{v(ue=>ue==="desc"?"asc":"desc")},N=Ee(),E=N.data;ee(()=>{a&&c&&a!==c&&N.state==="idle"&&!E&&N.load(`/api/branch-entity-diff?base=${encodeURIComponent(c)}&compare=${encodeURIComponent(a)}`)},[a,c,N,E]);const S=ae(()=>{const ue=mi(r,t);return Array.from(ue.entries()).sort((Fe,Oe)=>Fe[0].localeCompare(Oe[0]))},[r,t]),M=ae(()=>{const ue=Yg(d,t,E);return Array.from(ue.entries()).sort((Fe,Oe)=>Fe[0].localeCompare(Oe[0]))},[d,t,E]),F=ae(()=>Bg(r,t),[r,t]),L=ae(()=>b==="uncommitted"?S:M,[b,S,M]),P=ae(()=>L.map(([ue])=>ue),[L]),{expandedUncommitted:T,setExpandedUncommitted:$,toggleFile:I,expandAllUncommitted:J,collapseAllUncommitted:V}=j0(C,P,[]),{diffView:U,diffContent:z,isLoading:Y,handleShowFileDiff:R,handleCloseDiff:A}=I0(c,a),G=(ye=m==null?void 0:m.metadata)==null?void 0:ye.currentRun,B=new Set((G==null?void 0:G.currentEntityShas)||[]),H=new Set(h.jobs.flatMap(ue=>ue.entityShas||[])),re=new Set(((Ct=h.currentlyExecuting)==null?void 0:Ct.entityShas)||[]),{isAnalyzing:O,handleGenerateSimulation:j,handleGenerateAllSimulations:D,isEntityBeingAnalyzed:q,isEntityPending:te}=yi(G==null?void 0:G.currentEntityShas,h),de=ue=>te(ue)||H.has(ue.sha)||re.has(ue.sha),ge=ue=>{ue===(s||a)?p.delete("viewBranch"):p.set("viewBranch",ue),f(p)},pe=ue=>{ue===o?p.delete("compare"):p.set("compare",ue),f(p)},be=()=>{const Fe=L.flatMap(([Oe,Vt])=>Vt.editedEntities||Vt.entities||[]).filter(Oe=>!B.has(Oe.sha)&&!H.has(Oe.sha)&&!re.has(Oe.sha)&&!te(Oe));D(Fe)},Ce=S.length,ke=M.length,Se=L.flatMap(([ue,Fe])=>Fe.editedEntities||Fe.entities||[]),_e=Se.filter(ue=>ue.entityType==="visual"||ue.entityType==="library"),Te=_e.length>0&&_e.every(ue=>B.has(ue.sha)),ve=_e.length>0&&!Te&&_e.every(ue=>H.has(ue.sha)||re.has(ue.sha)),Q=O||Te||ve,me=Te?"Analyzing...":ve?"Queued...":O?"Analyzing...":"Analyze All";return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-20 py-12",children:[l("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Git Changes"}),l("p",{className:"text-[15px] text-gray-500",children:["This is a list of all the files that are affected by your local changes. ",n("strong",{children:"Analyze a file to get simulations."})]})]}),n("div",{className:"mb-6",children:n(L0,{activeTab:b,onTabChange:w,uncommittedCount:Ce,branchCount:ke})}),a&&b==="branch"&&n("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:a===o?l("div",{className:"text-gray-700",children:["You are currently on the primary branch,"," ",n("span",{className:"text-cyblack-75",children:o}),"."]}):l("div",{className:"flex gap-6 items-center",children:[l("div",{className:"shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Changes in Branch:"}),i.length>0?l("div",{className:"relative w-50",children:[n("select",{value:a,onChange:ue=>ge(ue.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-2.5 pr-6 text-[13px] h-9.75 w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:i.map(ue=>n("option",{value:ue,children:ue},ue))}),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})]}),l("div",{className:"flex-shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Compared To:"}),l("div",{className:"relative w-[200px]",children:[n("select",{value:c,onChange:ue=>pe(ue.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(ue=>ue!==a).map(ue=>n("option",{value:ue,children:ue},ue))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]})]}),n("div",{className:"flex-1 mt-6",children:l("div",{className:"relative flex items-center",children:[n("svg",{className:"absolute left-3 w-4 h-4 text-gray-400 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})})]})}),n("div",{className:"mb-3",children:l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center",children:[l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:L.length})," ","modified ",L.length===1?"file":"files"]}),l("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:Se.length})," ",Se.length===1?"entity":"entities"]})]}),L.length>0&&l("div",{className:"flex gap-6",children:[l("button",{onClick:J,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(eo,{className:"w-3.5 h-3.5"}),"Expand All"]}),l("button",{onClick:V,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(to,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),l("div",{className:"overflow-hidden",children:[b==="branch"&&a&&n(R0,{files:M,currentBranch:a,defaultBranch:o,baseBranch:c,allBranches:i,expandedFiles:T,isEntityBeingAnalyzed:q,isEntityQueued:de,sortOrder:x,onToggleFile:ue=>I(ue,T,$),onBranchChange:pe,onGenerateSimulation:j,onSortChange:k,onAnalyzeAll:be,analyzeAllDisabled:Q,analyzeAllText:me}),b==="uncommitted"&&n(D0,{files:S,entityImpactMap:F,expandedFiles:T,isEntityBeingAnalyzed:q,isEntityQueued:de,projectSlug:u,baseBranch:c,currentBranch:a,sortOrder:x,onToggleFile:ue=>I(ue,T,$),onShowFileDiff:R,onGenerateSimulation:j,onSortChange:k,onAnalyzeAll:be,analyzeAllDisabled:Q,analyzeAllText:me})]}),U&&n($0,{diffView:U,diffContent:z,isLoading:Y,entities:t,onClose:A}),g&&u&&n(gt,{projectSlug:u,onClose:()=>y(null)})]})})}),B0=Object.freeze(Object.defineProperty({__proto__:null,action:O0,default:Y0,loader:z0,meta:F0},Symbol.toStringTag,{value:"Module"})),Dy={entry:{module:"/assets/entry.client-CU6EUArK.js",imports:["/assets/chunk-JZWAC4HX-7VptmeIr.js","/assets/index-7-1FmlHo.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-DqfSDjyQ.js",imports:["/assets/chunk-JZWAC4HX-7VptmeIr.js","/assets/index-7-1FmlHo.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/ReportIssueModal-TCV_HBjy.js","/assets/useReportContext-BsQb6rFd.js","/assets/loader-circle-BnDcD54R.js","/assets/createLucideIcon-D-QUFOwe.js","/assets/book-open-Bp5FLkd4.js","/assets/useToast-BOur3mUv.js","/assets/useLastLogLine-DZp6rrQD.js","/assets/LogViewer-CMK8Q7yk.js","/assets/EntityTypeIcon-DN9eiJAO.js","/assets/TruncatedFilePath-D7IoaWUW.js","/assets/chevron-down-DQJA9f4o.js","/assets/circle-check-B6C4LY9o.js","/assets/CopyButton-CtmbP4Gl.js","/assets/triangle-alert-DTf3Jojp.js","/assets/copy-6nzYCu0G.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-DVTcUnur.js",imports:["/assets/chunk-JZWAC4HX-7VptmeIr.js","/assets/InlineSpinner-C1rIyZdV.js","/assets/useLastLogLine-DZp6rrQD.js","/assets/useCustomSizes-D_bDZyDU.js","/assets/cy-logo-cli-DcX-ZS3p.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-C7ysA4Jq.js",imports:["/assets/chunk-JZWAC4HX-7VptmeIr.js","/assets/InteractivePreview-rE_fI2h2.js","/assets/InlineSpinner-C1rIyZdV.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-DZp6rrQD.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-BVgNO76F.js",imports:["/assets/chunk-JZWAC4HX-7VptmeIr.js","/assets/InteractivePreview-rE_fI2h2.js","/assets/InlineSpinner-C1rIyZdV.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-DZp6rrQD.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.llm-calls.$entitySha":{id:"routes/api.llm-calls.$entitySha",parentId:"root",path:"api/llm-calls/:entitySha",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.llm-calls._entitySha-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.branch-entity-diff":{id:"routes/api.branch-entity-diff",parentId:"root",path:"api/branch-entity-diff",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.branch-entity-diff-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.capture-screenshot-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.agent-transcripts-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.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.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.memory-profile-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.process-status-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.restart-server-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.save-scenarios-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/agent-transcripts-Dm5RS9il.js",imports:["/assets/chunk-JZWAC4HX-7VptmeIr.js","/assets/useReportContext-BsQb6rFd.js","/assets/createLucideIcon-D-QUFOwe.js","/assets/terminal-Bs4NC-VZ.js","/assets/search-DborVoKD.js","/assets/chevron-down-DQJA9f4o.js","/assets/book-open-Bp5FLkd4.js","/assets/triangle-alert-DTf3Jojp.js","/assets/copy-6nzYCu0G.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.kill-process-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.save-fixture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.screenshot._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/activity.(_tab)-DZu78RI1.js",imports:["/assets/chunk-JZWAC4HX-7VptmeIr.js","/assets/LogViewer-CMK8Q7yk.js","/assets/useLastLogLine-DZp6rrQD.js","/assets/useReportContext-BsQb6rFd.js","/assets/EntityTypeIcon-DN9eiJAO.js","/assets/EntityTypeBadge-B-0PjGOU.js","/assets/SafeScreenshot-CG2uh31y.js","/assets/LoadingDots-CSP6DZrh.js","/assets/loader-circle-BnDcD54R.js","/assets/pause-DhQX2g22.js","/assets/createLucideIcon-D-QUFOwe.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.debug-setup-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.labs-unlock-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.rule-path":{id:"routes/api.rule-path",parentId:"root",path:"api/rule-path",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.rule-path-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha._-C6PQhwY5.js",imports:["/assets/chunk-JZWAC4HX-7VptmeIr.js","/assets/useLastLogLine-DZp6rrQD.js","/assets/InlineSpinner-C1rIyZdV.js","/assets/InteractivePreview-rE_fI2h2.js","/assets/SafeScreenshot-CG2uh31y.js","/assets/LibraryFunctionPreview-CnatsCw2.js","/assets/LoadingDots-CSP6DZrh.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/ScenarioViewer-CU_TDYd8.js","/assets/createLucideIcon-D-QUFOwe.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/EntityTypeIcon-DN9eiJAO.js","/assets/CopyButton-CtmbP4Gl.js","/assets/LogViewer-CMK8Q7yk.js","/assets/useReportContext-BsQb6rFd.js","/assets/preload-helper-ckwbz45p.js","/assets/useCustomSizes-D_bDZyDU.js","/assets/ReportIssueModal-TCV_HBjy.js","/assets/circle-check-B6C4LY9o.js","/assets/triangle-alert-DTf3Jojp.js","/assets/copy-6nzYCu0G.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-BtrtCYJg.js",imports:["/assets/chunk-JZWAC4HX-7VptmeIr.js","/assets/useReportContext-BsQb6rFd.js","/assets/SafeScreenshot-CG2uh31y.js","/assets/LoadingDots-CSP6DZrh.js","/assets/EntityTypeIcon-DN9eiJAO.js","/assets/fileTableUtils-EWpfFU4X.js","/assets/chevron-down-DQJA9f4o.js","/assets/search-DborVoKD.js","/assets/loader-circle-BnDcD54R.js","/assets/createLucideIcon-D-QUFOwe.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.events-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.health-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.memory-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.queue-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/dev.empty-DmzSmblj.js",imports:["/assets/chunk-JZWAC4HX-7VptmeIr.js","/assets/ScenarioViewer-CU_TDYd8.js","/assets/InteractivePreview-rE_fI2h2.js","/assets/useCustomSizes-D_bDZyDU.js","/assets/LogViewer-CMK8Q7yk.js","/assets/SafeScreenshot-CG2uh31y.js","/assets/useLastLogLine-DZp6rrQD.js","/assets/InlineSpinner-C1rIyZdV.js","/assets/preload-helper-ckwbz45p.js","/assets/ReportIssueModal-TCV_HBjy.js","/assets/createLucideIcon-D-QUFOwe.js","/assets/circle-check-B6C4LY9o.js","/assets/triangle-alert-DTf3Jojp.js","/assets/copy-6nzYCu0G.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-BWunYSXt.js",imports:["/assets/chunk-JZWAC4HX-7VptmeIr.js","/assets/useReportContext-BsQb6rFd.js","/assets/CopyButton-CtmbP4Gl.js","/assets/copy-6nzYCu0G.js","/assets/createLucideIcon-D-QUFOwe.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-B8z7mjR-.js",imports:["/assets/chunk-JZWAC4HX-7VptmeIr.js","/assets/useLastLogLine-DZp6rrQD.js","/assets/useToast-BOur3mUv.js","/assets/useReportContext-BsQb6rFd.js","/assets/LogViewer-CMK8Q7yk.js","/assets/EntityTypeIcon-DN9eiJAO.js","/assets/SafeScreenshot-CG2uh31y.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/createLucideIcon-D-QUFOwe.js","/assets/circle-check-B6C4LY9o.js","/assets/loader-circle-BnDcD54R.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/memory-0wMU4KXe.js",imports:["/assets/chunk-JZWAC4HX-7VptmeIr.js","/assets/useReportContext-BsQb6rFd.js","/assets/createLucideIcon-D-QUFOwe.js","/assets/terminal-Bs4NC-VZ.js","/assets/copy-6nzYCu0G.js","/assets/CopyButton-CtmbP4Gl.js","/assets/chevron-down-DQJA9f4o.js","/assets/search-DborVoKD.js","/assets/pause-DhQX2g22.js","/assets/book-open-Bp5FLkd4.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-CrxAoWIL.js",imports:["/assets/chunk-JZWAC4HX-7VptmeIr.js","/assets/useReportContext-BsQb6rFd.js","/assets/EntityItem-DlMph_Hm.js","/assets/fileTableUtils-EWpfFU4X.js","/assets/chevron-down-DQJA9f4o.js","/assets/search-DborVoKD.js","/assets/createLucideIcon-D-QUFOwe.js","/assets/useToast-BOur3mUv.js","/assets/TruncatedFilePath-D7IoaWUW.js","/assets/SafeScreenshot-CG2uh31y.js","/assets/LibraryFunctionPreview-CnatsCw2.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-DTf3Jojp.js","/assets/EntityTypeIcon-DN9eiJAO.js","/assets/EntityTypeBadge-B-0PjGOU.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/labs-CPPVOSWB.js",imports:["/assets/chunk-JZWAC4HX-7VptmeIr.js","/assets/useReportContext-BsQb6rFd.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-BldHtKeW.js",imports:["/assets/chunk-JZWAC4HX-7VptmeIr.js","/assets/useReportContext-BsQb6rFd.js","/assets/EntityItem-DlMph_Hm.js","/assets/LogViewer-CMK8Q7yk.js","/assets/fileTableUtils-EWpfFU4X.js","/assets/createLucideIcon-D-QUFOwe.js","/assets/useToast-BOur3mUv.js","/assets/TruncatedFilePath-D7IoaWUW.js","/assets/SafeScreenshot-CG2uh31y.js","/assets/LibraryFunctionPreview-CnatsCw2.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-DTf3Jojp.js","/assets/EntityTypeIcon-DN9eiJAO.js","/assets/EntityTypeBadge-B-0PjGOU.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0}},url:"/assets/manifest-717e346a.js",version:"717e346a",sri:void 0},Ly="build/client",Fy="/",Oy={unstable_optimizeDeps:!1,unstable_subResourceIntegrity:!1,unstable_trailingSlashAwareDataRequests:!1,v8_middleware:!1,v8_splitRouteModules:!1,v8_viteEnvironmentApi:!1},zy=!0,Yy=!1,By=[],Uy={mode:"lazy",manifestPath:"/__manifest"},Wy="/",Hy={module:Kl},Vy={root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,module:Nu},"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:_u},"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:Ku},"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:rm},"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:sh},"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:lh},"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:Ah},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,module:Ph},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,module:Ih},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,module:Jh},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,module:Kh},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,module:Xh},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,module:np},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,module:ap},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,module:fp},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,module:vp},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,module:Sp},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,module:_p},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,module:Mp},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,module:Vp},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,module:Gp},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,module:ef},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,module:nf},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,module:hf},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,module:gf},"routes/api.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,module:vf},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,module:Cf},"routes/api.rule-path":{id:"routes/api.rule-path",parentId:"root",path:"api/rule-path",index:void 0,caseSensitive:void 0,module:Af},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,module:Kf},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,module:Xf},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,module:og},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,module:lg},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,module:dg},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,module:Sg},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,module:Ag},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,module:Mg},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,module:Lg},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,module:Og},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,module:Gg},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,module:g0},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,module:C0},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,module:T0},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,module:B0}},Jy=!1;export{ad as A,td as B,Ae as C,Ac as D,_c as E,$t as F,gc as G,uo as H,mo as I,ho as J,wc as K,Nc as L,Ly as M,Fy as N,Oy as O,pc as P,zy as Q,Yy as R,Yn as S,By as T,Uy as U,Wy as V,Hy as W,Vy as X,Jy as Y,Dy as Z,cc as a,Ot as b,Tt as c,lt as d,mn as e,ma as f,ha as g,co as h,ic as i,Fc as j,Oc as k,yt as l,ct as m,go as n,Jc as o,Un as p,ot as q,yo as r,xo as s,Zc as t,ft as u,bo as v,Yt as w,Hn as x,ms as y,id as z};