@codeyam/codeyam-cli 0.1.0-staging.b8a55ba → 0.1.0-staging.d0ad4ae

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 (340) hide show
  1. package/analyzer-template/.build-info.json +7 -7
  2. package/analyzer-template/common/execAsync.ts +1 -1
  3. package/analyzer-template/log.txt +3 -3
  4. package/analyzer-template/package.json +7 -4
  5. package/analyzer-template/packages/ai/package.json +1 -1
  6. package/analyzer-template/packages/ai/src/lib/astScopes/processExpression.ts +14 -1
  7. package/analyzer-template/packages/ai/src/lib/checkAllAttributes.ts +29 -10
  8. package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +120 -19
  9. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.ts +2 -1
  10. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.ts +91 -35
  11. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.ts +110 -74
  12. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.ts +11 -0
  13. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.ts +98 -0
  14. package/analyzer-template/packages/ai/src/lib/deepEqual.ts +30 -0
  15. package/analyzer-template/packages/ai/src/lib/findMatchingAttribute.ts +24 -17
  16. package/analyzer-template/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.ts +214 -39
  17. package/analyzer-template/packages/ai/src/lib/generateChangesEntityKeyAttributes.ts +54 -1
  18. package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarioData.ts +72 -6
  19. package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarios.ts +12 -5
  20. package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +39 -23
  21. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.ts +32 -0
  22. package/analyzer-template/packages/analyze/src/lib/FileAnalyzer.ts +14 -0
  23. package/analyzer-template/packages/analyze/src/lib/asts/nodes/index.ts +1 -0
  24. package/analyzer-template/packages/analyze/src/lib/asts/nodes/isAsyncFunction.ts +67 -0
  25. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.ts +73 -69
  26. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +6 -0
  27. package/analyzer-template/packages/analyze/src/lib/files/analyze/findOrCreateEntity.ts +3 -0
  28. package/analyzer-template/packages/analyze/src/lib/files/analyzeChange.ts +22 -6
  29. package/analyzer-template/packages/analyze/src/lib/files/analyzeEntity.ts +9 -5
  30. package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.ts +49 -11
  31. package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.ts +102 -0
  32. package/analyzer-template/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.ts +399 -52
  33. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.ts +128 -2
  34. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +114 -70
  35. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarioData.ts +34 -129
  36. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +155 -79
  37. package/analyzer-template/packages/aws/codebuild/index.ts +1 -0
  38. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.d.ts +11 -1
  39. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.d.ts.map +1 -1
  40. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.js +29 -18
  41. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.js.map +1 -1
  42. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.d.ts +2 -2
  43. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.d.ts.map +1 -1
  44. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.js +2 -2
  45. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.js.map +1 -1
  46. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.d.ts +8 -18
  47. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.d.ts.map +1 -1
  48. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.js +17 -61
  49. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.js.map +1 -1
  50. package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.d.ts.map +1 -1
  51. package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.js +8 -1
  52. package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.js.map +1 -1
  53. package/analyzer-template/packages/aws/package.json +1 -1
  54. package/analyzer-template/packages/aws/src/lib/codebuild/waitForBuild.ts +43 -19
  55. package/analyzer-template/packages/aws/src/lib/ecs/ecsDefineContainer.ts +3 -3
  56. package/analyzer-template/packages/aws/src/lib/ecs/ecsTaskFactory.ts +17 -69
  57. package/analyzer-template/packages/aws/src/lib/s3/uploadFileToS3.ts +8 -1
  58. package/analyzer-template/packages/generate/index.ts +3 -0
  59. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.ts +17 -1
  60. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.ts +193 -0
  61. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.ts +73 -0
  62. package/analyzer-template/packages/generate/src/lib/scenarioComponentForServer.ts +114 -0
  63. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entitiesTable.d.ts +1 -0
  64. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entitiesTable.d.ts.map +1 -1
  65. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts +1 -0
  66. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts.map +1 -1
  67. package/analyzer-template/packages/github/dist/generate/index.d.ts +3 -0
  68. package/analyzer-template/packages/github/dist/generate/index.d.ts.map +1 -1
  69. package/analyzer-template/packages/github/dist/generate/index.js +3 -0
  70. package/analyzer-template/packages/github/dist/generate/index.js.map +1 -1
  71. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.d.ts.map +1 -1
  72. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +16 -1
  73. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
  74. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.d.ts +9 -0
  75. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.d.ts.map +1 -0
  76. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +189 -0
  77. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -0
  78. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.d.ts +20 -0
  79. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.d.ts.map +1 -0
  80. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js +53 -0
  81. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js.map +1 -0
  82. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.d.ts +8 -0
  83. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.d.ts.map +1 -0
  84. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.js +89 -0
  85. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.js.map +1 -0
  86. package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.d.ts.map +1 -1
  87. package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.js +10 -0
  88. package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.js.map +1 -1
  89. package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.d.ts.map +1 -1
  90. package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.js +3 -0
  91. package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.js.map +1 -1
  92. package/analyzer-template/packages/github/dist/types/src/types/Entity.d.ts +2 -0
  93. package/analyzer-template/packages/github/dist/types/src/types/Entity.d.ts.map +1 -1
  94. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts +6 -0
  95. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts.map +1 -1
  96. package/analyzer-template/packages/github/src/lib/loadOrCreateCommit.ts +14 -0
  97. package/analyzer-template/packages/github/src/lib/syncPrimaryBranch.ts +2 -0
  98. package/analyzer-template/packages/process/index.ts +2 -0
  99. package/analyzer-template/packages/process/package.json +12 -0
  100. package/analyzer-template/packages/process/tsconfig.json +8 -0
  101. package/analyzer-template/packages/types/src/types/Entity.ts +2 -0
  102. package/analyzer-template/packages/types/src/types/Scenario.ts +6 -0
  103. package/analyzer-template/packages/utils/dist/types/src/types/Entity.d.ts +2 -0
  104. package/analyzer-template/packages/utils/dist/types/src/types/Entity.d.ts.map +1 -1
  105. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts +6 -0
  106. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts.map +1 -1
  107. package/analyzer-template/playwright/capture.ts +37 -18
  108. package/analyzer-template/playwright/waitForServer.ts +21 -6
  109. package/analyzer-template/project/constructMockCode.ts +781 -140
  110. package/analyzer-template/project/orchestrateCapture/KyselyAnalysisLoader.ts +3 -6
  111. package/analyzer-template/project/orchestrateCapture.ts +10 -3
  112. package/analyzer-template/project/reconcileMockDataKeys.ts +28 -100
  113. package/analyzer-template/project/runAnalysis.ts +5 -0
  114. package/analyzer-template/project/serverOnlyModules.ts +127 -2
  115. package/analyzer-template/project/start.ts +5 -3
  116. package/analyzer-template/project/startScenarioCapture.ts +6 -0
  117. package/analyzer-template/project/writeMockDataTsx.ts +50 -22
  118. package/analyzer-template/project/writeScenarioClientWrapper.ts +21 -0
  119. package/analyzer-template/project/writeScenarioComponents.ts +162 -100
  120. package/analyzer-template/project/writeScenarioFiles.ts +26 -0
  121. package/analyzer-template/project/writeSimpleRoot.ts +11 -35
  122. package/analyzer-template/scripts/comboWorkerLoop.cjs +1 -0
  123. package/analyzer-template/scripts/defaultCmd.sh +9 -0
  124. package/background/src/lib/local/createLocalAnalyzer.js +1 -29
  125. package/background/src/lib/local/createLocalAnalyzer.js.map +1 -1
  126. package/background/src/lib/local/execAsync.js +1 -1
  127. package/background/src/lib/local/execAsync.js.map +1 -1
  128. package/background/src/lib/virtualized/common/execAsync.js +1 -1
  129. package/background/src/lib/virtualized/common/execAsync.js.map +1 -1
  130. package/background/src/lib/virtualized/project/constructMockCode.js +718 -127
  131. package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
  132. package/background/src/lib/virtualized/project/orchestrateCapture/KyselyAnalysisLoader.js +3 -2
  133. package/background/src/lib/virtualized/project/orchestrateCapture/KyselyAnalysisLoader.js.map +1 -1
  134. package/background/src/lib/virtualized/project/orchestrateCapture.js +7 -4
  135. package/background/src/lib/virtualized/project/orchestrateCapture.js.map +1 -1
  136. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js +25 -61
  137. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js.map +1 -1
  138. package/background/src/lib/virtualized/project/runAnalysis.js +4 -0
  139. package/background/src/lib/virtualized/project/runAnalysis.js.map +1 -1
  140. package/background/src/lib/virtualized/project/serverOnlyModules.js +106 -3
  141. package/background/src/lib/virtualized/project/serverOnlyModules.js.map +1 -1
  142. package/background/src/lib/virtualized/project/start.js +5 -3
  143. package/background/src/lib/virtualized/project/start.js.map +1 -1
  144. package/background/src/lib/virtualized/project/startScenarioCapture.js +7 -0
  145. package/background/src/lib/virtualized/project/startScenarioCapture.js.map +1 -1
  146. package/background/src/lib/virtualized/project/writeMockDataTsx.js +52 -23
  147. package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
  148. package/background/src/lib/virtualized/project/writeScenarioClientWrapper.js +15 -0
  149. package/background/src/lib/virtualized/project/writeScenarioClientWrapper.js.map +1 -0
  150. package/background/src/lib/virtualized/project/writeScenarioComponents.js +136 -83
  151. package/background/src/lib/virtualized/project/writeScenarioComponents.js.map +1 -1
  152. package/background/src/lib/virtualized/project/writeScenarioFiles.js +19 -0
  153. package/background/src/lib/virtualized/project/writeScenarioFiles.js.map +1 -1
  154. package/background/src/lib/virtualized/project/writeSimpleRoot.js +11 -34
  155. package/background/src/lib/virtualized/project/writeSimpleRoot.js.map +1 -1
  156. package/codeyam-cli/src/cli.js +5 -1
  157. package/codeyam-cli/src/cli.js.map +1 -1
  158. package/codeyam-cli/src/commands/analyze.js +1 -1
  159. package/codeyam-cli/src/commands/analyze.js.map +1 -1
  160. package/codeyam-cli/src/commands/baseline.js +177 -0
  161. package/codeyam-cli/src/commands/baseline.js.map +1 -0
  162. package/codeyam-cli/src/commands/status.js +23 -1
  163. package/codeyam-cli/src/commands/status.js.map +1 -1
  164. package/codeyam-cli/src/commands/test-startup.js +1 -1
  165. package/codeyam-cli/src/commands/test-startup.js.map +1 -1
  166. package/codeyam-cli/src/commands/wipe.js +108 -0
  167. package/codeyam-cli/src/commands/wipe.js.map +1 -0
  168. package/codeyam-cli/src/utils/database.js +91 -5
  169. package/codeyam-cli/src/utils/database.js.map +1 -1
  170. package/codeyam-cli/src/utils/git.js +79 -0
  171. package/codeyam-cli/src/utils/git.js.map +1 -0
  172. package/codeyam-cli/src/utils/queue/job.js +104 -0
  173. package/codeyam-cli/src/utils/queue/job.js.map +1 -1
  174. package/codeyam-cli/src/utils/queue/persistence.js.map +1 -1
  175. package/codeyam-cli/src/utils/wipe.js +128 -0
  176. package/codeyam-cli/src/utils/wipe.js.map +1 -0
  177. package/codeyam-cli/src/webserver/app/lib/database.js +66 -17
  178. package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
  179. package/codeyam-cli/src/webserver/build/client/assets/{EntityItem-wXL1Z2Aq.js → EntityItem-Cmysw5OP.js} +1 -1
  180. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeBadge-CzGX-miz.js → EntityTypeBadge-DLqD3qNt.js} +1 -1
  181. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeIcon-CXFKsCOD.js → EntityTypeIcon-CAneekK2.js} +1 -1
  182. package/codeyam-cli/src/webserver/build/client/assets/{InteractivePreview-D-9pXIaY.js → InteractivePreview-Cu16OUmx.js} +2 -2
  183. package/codeyam-cli/src/webserver/build/client/assets/{LibraryFunctionPreview-CBQPrpT0.js → LibraryFunctionPreview-CVtiBnY5.js} +1 -1
  184. package/codeyam-cli/src/webserver/build/client/assets/{LoadingDots-D1CdlbrV.js → LoadingDots-B0GLXMsr.js} +1 -1
  185. package/codeyam-cli/src/webserver/build/client/assets/{LogViewer-wDPcZNKx.js → LogViewer-xgeCVgSM.js} +1 -1
  186. package/codeyam-cli/src/webserver/build/client/assets/{ReportIssueModal-4lcOlid-.js → ReportIssueModal-DcAUIpD_.js} +1 -1
  187. package/codeyam-cli/src/webserver/build/client/assets/{SafeScreenshot-BfmDgXxG.js → SafeScreenshot-DuDvi0jm.js} +1 -1
  188. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-BMKg0SAF.js +15 -0
  189. package/codeyam-cli/src/webserver/build/client/assets/{TruncatedFilePath-6J7zDUD5.js → TruncatedFilePath-DyFZkK0l.js} +1 -1
  190. package/codeyam-cli/src/webserver/build/client/assets/_index-DSmTpjmK.js +11 -0
  191. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-BF_aK4y6.js +32 -0
  192. package/codeyam-cli/src/webserver/build/client/assets/{chevron-down-BYimnrHg.js → chevron-down-Cx24_aWc.js} +1 -1
  193. package/codeyam-cli/src/webserver/build/client/assets/chunk-EPOLDU6W-CXRTFQ3F.js +51 -0
  194. package/codeyam-cli/src/webserver/build/client/assets/{circle-check-CaVsIRxt.js → circle-check-BOARzkeR.js} +1 -1
  195. package/codeyam-cli/src/webserver/build/client/assets/{createLucideIcon-CgUsG7ib.js → createLucideIcon-BdhJEx6B.js} +1 -1
  196. package/codeyam-cli/src/webserver/build/client/assets/{dev.empty-DW_hdGUc.js → dev.empty-RJCf3Tvw.js} +1 -1
  197. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-zUEpfPsu.js → entity._sha._-D0-YwkBh.js} +12 -12
  198. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-EylcgScH.js +1 -0
  199. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha_.create-scenario-D_3ero5o.js → entity._sha_.create-scenario-DMe7kvgo.js} +1 -1
  200. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha_.edit._scenarioId-CfLCUi9S.js → entity._sha_.edit._scenarioId-C1H_a_Y3.js} +1 -1
  201. package/codeyam-cli/src/webserver/build/client/assets/{entry.client-DKJyZfAY.js → entry.client-CS2cb_eZ.js} +6 -6
  202. package/codeyam-cli/src/webserver/build/client/assets/{fileTableUtils-DAtOlaWE.js → fileTableUtils-DMJ7zii9.js} +1 -1
  203. package/codeyam-cli/src/webserver/build/client/assets/{files-ClR0d32A.js → files-BW7Cyeyi.js} +1 -1
  204. package/codeyam-cli/src/webserver/build/client/assets/{git-D62Lxxmv.js → git-CZu4fif0.js} +2 -2
  205. package/codeyam-cli/src/webserver/build/client/assets/globals-wHVy_II5.css +1 -0
  206. package/codeyam-cli/src/webserver/build/client/assets/{index-CzNNiTkw.js → index-B1h680n5.js} +1 -1
  207. package/codeyam-cli/src/webserver/build/client/assets/{index-BosqDOlH.js → index-lzqtyFU8.js} +1 -1
  208. package/codeyam-cli/src/webserver/build/client/assets/{loader-circle-CNp9QFCX.js → loader-circle-B7B9V-bu.js} +1 -1
  209. package/codeyam-cli/src/webserver/build/client/assets/{manifest-09d684be.js → manifest-2d191949.js} +1 -1
  210. package/codeyam-cli/src/webserver/build/client/assets/root-FHgpM6gc.js +56 -0
  211. package/codeyam-cli/src/webserver/build/client/assets/{search-DDGjYAMJ.js → search-CxXUmBSd.js} +1 -1
  212. package/codeyam-cli/src/webserver/build/client/assets/{settings-DgTyB-Wg.js → settings-6D8k8Jp5.js} +1 -1
  213. package/codeyam-cli/src/webserver/build/client/assets/simulations-CDJZnWhN.js +1 -0
  214. package/codeyam-cli/src/webserver/build/client/assets/{triangle-alert-CBc5dE1s.js → triangle-alert-B6LgvRJg.js} +1 -1
  215. package/codeyam-cli/src/webserver/build/client/assets/{useCustomSizes-BMIGFP-m.js → useCustomSizes-Dv18q8LD.js} +1 -1
  216. package/codeyam-cli/src/webserver/build/client/assets/{useInteractiveMode-Dk_FQqWJ.js → useInteractiveMode-0ToGk4K3.js} +1 -1
  217. package/codeyam-cli/src/webserver/build/client/assets/{useLastLogLine-BqPPNjAl.js → useLastLogLine-aSv48UbS.js} +1 -1
  218. package/codeyam-cli/src/webserver/build/client/assets/{useReportContext-DsJbgMY9.js → useReportContext-1BX144Eg.js} +1 -1
  219. package/codeyam-cli/src/webserver/build/client/assets/{useToast-DWHcCcl1.js → useToast-mBRpZPiu.js} +1 -1
  220. package/codeyam-cli/src/webserver/build/server/assets/{index-CV6i1S1A.js → index-pU0o5t1o.js} +1 -1
  221. package/codeyam-cli/src/webserver/build/server/assets/server-build-YzfkRwdn.js +178 -0
  222. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  223. package/codeyam-cli/src/webserver/build-info.json +5 -5
  224. package/codeyam-cli/templates/codeyam-setup-skill.md +138 -3
  225. package/codeyam-cli/templates/debug-codeyam.md +7 -2
  226. package/package.json +5 -5
  227. package/packages/ai/src/lib/astScopes/processExpression.js +13 -1
  228. package/packages/ai/src/lib/astScopes/processExpression.js.map +1 -1
  229. package/packages/ai/src/lib/checkAllAttributes.js +24 -9
  230. package/packages/ai/src/lib/checkAllAttributes.js.map +1 -1
  231. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +94 -18
  232. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
  233. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js +2 -1
  234. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js.map +1 -1
  235. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js +51 -23
  236. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js.map +1 -1
  237. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js +70 -54
  238. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js.map +1 -1
  239. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js +11 -0
  240. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js.map +1 -1
  241. package/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.js +86 -0
  242. package/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.js.map +1 -0
  243. package/packages/ai/src/lib/deepEqual.js +32 -0
  244. package/packages/ai/src/lib/deepEqual.js.map +1 -0
  245. package/packages/ai/src/lib/findMatchingAttribute.js +20 -16
  246. package/packages/ai/src/lib/findMatchingAttribute.js.map +1 -1
  247. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js +168 -41
  248. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js.map +1 -1
  249. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js +42 -1
  250. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js.map +1 -1
  251. package/packages/ai/src/lib/generateChangesEntityScenarioData.js +59 -3
  252. package/packages/ai/src/lib/generateChangesEntityScenarioData.js.map +1 -1
  253. package/packages/ai/src/lib/generateChangesEntityScenarios.js +6 -6
  254. package/packages/ai/src/lib/generateChangesEntityScenarios.js.map +1 -1
  255. package/packages/ai/src/lib/generateEntityScenarioData.js +32 -23
  256. package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
  257. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js +20 -1
  258. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js.map +1 -1
  259. package/packages/analyze/src/lib/FileAnalyzer.js +15 -0
  260. package/packages/analyze/src/lib/FileAnalyzer.js.map +1 -1
  261. package/packages/analyze/src/lib/asts/nodes/index.js +1 -0
  262. package/packages/analyze/src/lib/asts/nodes/index.js.map +1 -1
  263. package/packages/analyze/src/lib/asts/nodes/isAsyncFunction.js +52 -0
  264. package/packages/analyze/src/lib/asts/nodes/isAsyncFunction.js.map +1 -0
  265. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +59 -50
  266. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
  267. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +6 -0
  268. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
  269. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js +2 -0
  270. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js.map +1 -1
  271. package/packages/analyze/src/lib/files/analyzeChange.js +14 -4
  272. package/packages/analyze/src/lib/files/analyzeChange.js.map +1 -1
  273. package/packages/analyze/src/lib/files/analyzeEntity.js +7 -6
  274. package/packages/analyze/src/lib/files/analyzeEntity.js.map +1 -1
  275. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js +44 -10
  276. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js.map +1 -1
  277. package/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.js +85 -0
  278. package/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.js.map +1 -0
  279. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js +314 -52
  280. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js.map +1 -1
  281. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.js +97 -2
  282. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.js.map +1 -1
  283. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +88 -52
  284. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
  285. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js +26 -98
  286. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js.map +1 -1
  287. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +141 -75
  288. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
  289. package/packages/aws/src/lib/ecs/ecsDefineContainer.js +2 -2
  290. package/packages/aws/src/lib/ecs/ecsDefineContainer.js.map +1 -1
  291. package/packages/aws/src/lib/ecs/ecsTaskFactory.js +17 -61
  292. package/packages/aws/src/lib/ecs/ecsTaskFactory.js.map +1 -1
  293. package/packages/generate/index.js +3 -0
  294. package/packages/generate/index.js.map +1 -1
  295. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +16 -1
  296. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
  297. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +189 -0
  298. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -0
  299. package/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js +53 -0
  300. package/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js.map +1 -0
  301. package/packages/generate/src/lib/scenarioComponentForServer.js +89 -0
  302. package/packages/generate/src/lib/scenarioComponentForServer.js.map +1 -0
  303. package/packages/github/src/lib/loadOrCreateCommit.js +10 -0
  304. package/packages/github/src/lib/loadOrCreateCommit.js.map +1 -1
  305. package/packages/github/src/lib/syncPrimaryBranch.js +3 -0
  306. package/packages/github/src/lib/syncPrimaryBranch.js.map +1 -1
  307. package/packages/process/index.js +3 -0
  308. package/packages/process/index.js.map +1 -0
  309. package/packages/process/src/GlobalProcessManager.js.map +1 -0
  310. package/{background/src/lib/process → packages/process/src}/ProcessManager.js +1 -1
  311. package/packages/process/src/ProcessManager.js.map +1 -0
  312. package/packages/process/src/index.js.map +1 -0
  313. package/packages/process/src/managedExecAsync.js.map +1 -0
  314. package/analyzer-template/process/INTEGRATION_COMPLETE.md +0 -333
  315. package/analyzer-template/process/INTEGRATION_EXAMPLE.md +0 -525
  316. package/analyzer-template/process/README.md +0 -507
  317. package/background/src/lib/process/GlobalProcessManager.js.map +0 -1
  318. package/background/src/lib/process/ProcessManager.js.map +0 -1
  319. package/background/src/lib/process/index.js.map +0 -1
  320. package/background/src/lib/process/managedExecAsync.js.map +0 -1
  321. package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js +0 -238
  322. package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js.map +0 -1
  323. package/codeyam-cli/scripts/fixtures/formbricks/universal-mocks/apps/web/lib/instance/service.js +0 -7
  324. package/codeyam-cli/scripts/fixtures/formbricks/universal-mocks/apps/web/lib/instance/service.js.map +0 -1
  325. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-CUxUNEEC.js +0 -15
  326. package/codeyam-cli/src/webserver/build/client/assets/_index-DHImXdXq.js +0 -11
  327. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-2mG6mjVb.js +0 -32
  328. package/codeyam-cli/src/webserver/build/client/assets/chunk-JMJ3UQ3L-BambyYE_.js +0 -51
  329. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-DyB90fWk.js +0 -1
  330. package/codeyam-cli/src/webserver/build/client/assets/globals-C6vQASxy.css +0 -1
  331. package/codeyam-cli/src/webserver/build/client/assets/root-BxJUvKau.js +0 -56
  332. package/codeyam-cli/src/webserver/build/client/assets/simulations-CoNWGt0K.js +0 -1
  333. package/codeyam-cli/src/webserver/build/server/assets/server-build-BDlyhfrv.js +0 -175
  334. /package/analyzer-template/{process → packages/process/src}/GlobalProcessManager.ts +0 -0
  335. /package/analyzer-template/{process → packages/process/src}/ProcessManager.ts +0 -0
  336. /package/analyzer-template/{process → packages/process/src}/index.ts +0 -0
  337. /package/analyzer-template/{process → packages/process/src}/managedExecAsync.ts +0 -0
  338. /package/{background/src/lib/process → packages/process/src}/GlobalProcessManager.js +0 -0
  339. /package/{background/src/lib/process → packages/process/src}/index.js +0 -0
  340. /package/{background/src/lib/process → packages/process/src}/managedExecAsync.js +0 -0
@@ -0,0 +1,178 @@
1
+ var lo=Object.defineProperty;var oa=e=>{throw TypeError(e)};var co=(e,t,r)=>t in e?lo(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var ln=(e,t,r)=>co(e,typeof t!="symbol"?t+"":t,r),uo=(e,t,r)=>t.has(e)||oa("Cannot "+r);var ia=(e,t,r)=>(uo(e,t,"read from private field"),r?r.call(e):t.get(e)),la=(e,t,r)=>t.has(e)?oa("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r);import{jsx as n,jsxs as c,Fragment as ue}from"react/jsx-runtime";import{PassThrough as ho}from"node:stream";import{createReadableStreamFromReadable as mo}from"@react-router/node";import{ServerRouter as po,useFetcher as ke,useLocation as hr,useNavigate as It,Link as oe,UNSAFE_withComponentProps as We,Meta as fo,Links as go,ScrollRestoration as yo,Scripts as xo,useLoaderData as Ke,useRevalidator as ht,Outlet as bo,data as z,useSearchParams as qt,useParams as Va,useActionData as vo}from"react-router";import{isbot as wo}from"isbot";import{renderToPipeableStream as Co}from"react-dom/server";import{useState as j,useEffect as ne,useCallback as re,createContext as mr,useContext as kn,useRef as Pe,useMemo as se}from"react";import{Settings as ca,CheckCircle2 as pr,Bug as Ga,AlertTriangle as rr,Loader2 as at,HomeIcon as No,GitCommitIcon as da,File as So,RefreshCw as Ao,SettingsIcon as Eo,PanelsTopLeftIcon as _o,ComponentIcon as Po,FileText as ua,Code as ha,Box as ko,List as Mo,BarChart3 as To,Tag as Io,Image as Ht,Code2 as Ja,Activity as Hn,ChevronDown as bn,CircleEqual as jo,PauseCircle as qa,ListTodo as Ro,FileCode as $o,GripVertical as Do,Ban as Lo,CheckCircle as Oo,Check as Fo,Copy as Yo,Search as Ka,FolderOpen as zo,CodeXml as Bo,Zap as Uo}from"lucide-react";import"fetch-retry";import Wo from"better-sqlite3";import{Pool as Ho}from"pg";import*as K from"fs";import Ct,{existsSync as Vo}from"fs";import*as ee from"path";import be from"path";import{OperationNodeTransformer as Go,Kysely as Qa,ParseJSONResultsPlugin as Jo,SqliteDialect as qo,PostgresDialect as Ko,sql as qe}from"kysely";import*as Qo from"kysely/helpers/sqlite";import*as Zo from"kysely/helpers/postgres";import _e from"typescript";import*as Re from"fs/promises";import Ie,{writeFile as Xo,readFile as ei}from"fs/promises";import*as ti from"os";import ar from"os";import ni from"prompts";import vn from"chalk";import fr,{randomUUID as jt}from"crypto";import{execSync as Me,spawn as gr,exec as yr}from"child_process";import{promisify as xr}from"util";import ri from"dotenv";import ai,{EventEmitter as si}from"events";import{v4 as oi}from"uuid";import{fileURLToPath as Za}from"url";import ii from"openai";import li from"p-queue";import ma from"p-retry";import{DynamoDBClient as Mn,PutItemCommand as ci}from"@aws-sdk/client-dynamodb";import{LRUCache as br}from"lru-cache";import"pluralize";import"piscina";import di from"json5";import{marshall as ui}from"@aws-sdk/util-dynamodb";import{Prism as hi}from"react-syntax-highlighter";import{vscDarkPlus as mi}from"react-syntax-highlighter/dist/cjs/styles/prism/index.js";import{randomUUID as pi}from"node:crypto";import fi from"v8";import gi from"react-diff-viewer-continued";const Xa=5e3;function yi(e,t,r,a,s){return e.method.toUpperCase()==="HEAD"?new Response(null,{status:t,headers:r}):new Promise((o,i)=>{let l=!1,d=e.headers.get("user-agent"),h=d&&wo(d)||a.isSpaMode?"onAllReady":"onShellReady",u=setTimeout(()=>p(),Xa+1e3);const{pipe:m,abort:p}=Co(n(po,{context:a,url:e.url}),{[h](){l=!0;const f=new ho({final(y){clearTimeout(u),u=void 0,y()}}),g=mo(f);r.set("Content-Type","text/html"),m(f),o(new Response(g,{headers:r,status:t}))},onShellError(f){i(f)},onError(f){t=500,l&&console.error(f)}})})}const xi=Object.freeze(Object.defineProperty({__proto__:null,default:yi,streamTimeout:Xa},Symbol.toStringTag,{value:"Module"}));function bi({id:e,selected:t,onClick:r,icon:a,name:s}){const[o,i]=j(!1);ne(()=>{i(!0)},[]);const l=re(()=>{r==null||r(e)},[r,e]);return c("button",{className:`
2
+ w-full aspect-square p-3 cursor-pointer focus:outline-none
3
+ flex flex-col items-center justify-center gap-1 text-[#626262]
4
+ hover:bg-[#d8d8d8] text-xs font-ibmPlexSans uppercase
5
+ `,onClick:l,children:[n("div",{className:`${t?"bg-primary-100 text-cygray-10":""} w-10 h-10 rounded-lg flex items-center justify-center`,children:o&&a}),n("span",{className:`${t?"text-primary-100":""} whitespace-nowrap`,children:s})]})}const es="/assets/cy-logo-cli-C1gnJVOL.svg";function vi(e){return e.scenarioId?`Scenario: ${e.scenarioId.slice(0,8)}...`:e.entitySha?`Entity: ${e.entitySha.slice(0,8)}...`:"General feedback"}function ts({isOpen:e,onClose:t,context:r,defaultEmail:a="",screenshotDataUrl:s}){const[o,i]=j(""),[l,d]=j(a),[h,u]=j(!1),[m,p]=j(!1),[f,g]=j(null),[y,b]=j(null),x=ke(),w=x.state!=="idle";if(x.data&&!m&&!y){const A=x.data;A.success&&A.reportId?(p(!0),g(A.reportId)):A.error&&b(A.error)}const v=async()=>{b(null);const A=new FormData;if(A.append("issueType","other"),A.append("description",o),A.append("email",l),A.append("source",r.source),A.append("entitySha",r.entitySha||""),A.append("scenarioId",r.scenarioId||""),A.append("analysisId",r.analysisId||""),A.append("currentUrl",r.currentUrl),s)try{const M=await(await fetch(s)).blob();A.append("screenshot",M,"screenshot.jpg")}catch(P){console.error("Failed to convert screenshot:",P)}x.submit(A,{method:"post",action:"/api/generate-report",encType:"multipart/form-data"})},C=()=>{i(""),u(!1),p(!1),g(null),b(null),t()},k=A=>{A.key==="Escape"&&C()};return e?n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",onKeyDown:k,children:c("div",{className:"bg-white rounded-lg max-w-lg w-full p-6 shadow-xl",children:[c("div",{className:"flex items-center justify-between mb-6",children:[c("div",{className:"flex items-center gap-3",children:[w?n("div",{className:"animate-spin",children:n(ca,{size:24,style:{strokeWidth:1.5}})}):m?n(pr,{size:24,style:{color:"#10B981",strokeWidth:1.5}}):n(Ga,{size:24,style:{color:"#005C75",strokeWidth:1.5}}),n("h2",{className:"text-xl font-semibold text-gray-900",children:m?"Report Submitted":"Report Issue"})]}),n("button",{onClick:C,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),m?c("div",{children:[c("div",{className:"mb-6 p-4 bg-green-50 rounded-lg border border-green-200",children:[n("p",{className:"text-sm text-green-800 font-medium mb-1",children:"Thank you for your feedback!"}),c("p",{className:"text-xs text-green-700",children:["Report ID:"," ",n("code",{className:"bg-green-100 px-1 rounded",children:f})]})]}),n("p",{className:"text-sm text-gray-600 mb-6",children:"The CodeYam team will investigate and may reach out if you provided an email address."}),n("div",{className:"flex justify-end",children:n("button",{onClick:C,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] transition-colors cursor-pointer",children:"Done"})})]}):c("div",{children:[c("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[c("div",{className:"flex items-center justify-between",children:[n("div",{className:"text-sm font-medium text-gray-900",title:`${r.source}${r.entitySha?` • Entity: ${r.entitySha}`:""}${r.scenarioId?` • Scenario: ${r.scenarioId}`:""}${r.analysisId?` • Analysis: ${r.analysisId}`:""}`,children:vi(r)}),n("button",{type:"button",onClick:()=>u(!h),className:"text-xs text-gray-500 hover:text-gray-700 underline cursor-pointer",children:h?"Hide":"Details"})]}),h&&c("div",{className:"mt-2 pt-2 border-t border-gray-200 text-xs text-gray-600 space-y-1",children:[c("div",{children:[n("span",{className:"text-gray-400",children:"Source:"})," ",r.source]}),c("div",{children:[n("span",{className:"text-gray-400",children:"URL:"})," ",r.currentUrl]}),r.entitySha&&c("div",{children:[n("span",{className:"text-gray-400",children:"Entity:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.entitySha})]}),r.scenarioId&&c("div",{children:[n("span",{className:"text-gray-400",children:"Scenario:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.scenarioId})]}),r.analysisId&&c("div",{children:[n("span",{className:"text-gray-400",children:"Analysis:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.analysisId})]})]})]}),s&&c("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-xs text-gray-500 mb-2",children:"Screenshot (will be included in report)"}),n("img",{src:s,alt:"Page screenshot",className:"w-full max-h-[150px] object-contain rounded border border-gray-300"})]}),c("div",{className:"mb-4",children:[n("label",{htmlFor:"description",className:"block text-sm font-medium text-gray-700 mb-2",children:"What happened?"}),n("textarea",{id:"description",value:o,onChange:A=>i(A.target.value),placeholder:"Describe what you expected vs what happened...",rows:4,className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] resize-none"})]}),c("div",{className:"mb-4",children:[n("label",{htmlFor:"email",className:"block text-sm font-medium text-gray-700 mb-2",children:"Your email"}),n("input",{id:"email",type:"email",value:l,onChange:A=>d(A.target.value),placeholder:"you@example.com",className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"})]}),c("div",{className:"mb-6 p-3 bg-amber-50 rounded-lg border border-amber-200 flex gap-2",children:[n(rr,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#D97706"}}),c("div",{className:"text-xs text-amber-800",children:[n("p",{className:"font-medium mb-1",children:"Source code will be uploaded"}),n("p",{children:"This report includes your project source code, git history, and CodeYam logs. Only submit if you're comfortable sharing this with the CodeYam team."})]})]}),w&&n("div",{className:"mb-4 text-center",children:n("p",{className:"text-sm text-gray-600",children:x.formData?"Uploading report...":"Creating archive..."})}),y&&c("div",{className:"mb-4 p-3 bg-red-50 rounded-lg border border-red-200 flex gap-2",children:[n(rr,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#DC2626"}}),c("div",{className:"text-xs text-red-800",children:[n("p",{className:"font-medium mb-1",children:"Upload failed"}),n("p",{children:y})]})]}),c("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:C,disabled:w,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 v(),disabled:w,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:w?c(ue,{children:[n("div",{className:"animate-spin",children:n(ca,{size:16,style:{strokeWidth:1.5}})}),"Submitting..."]}):y?"Try Again":"Submit Report"})]})]})]})}):null}const pa={source:"navbar"},vr=mr(void 0);function wi({children:e}){const[t,r]=j(pa),a=re(o=>{r(o)},[]),s=re(()=>{r(pa)},[]);return n(vr.Provider,{value:{contextData:t,setContextData:a,resetContextData:s},children:e})}function Et(e){const t=kn(vr),r=Pe(t);ne(()=>{if(r.current)return r.current.setContextData(e),()=>{var a;(a=r.current)==null||a.resetContextData()}},[e.source,e.entitySha,e.scenarioId,e.analysisId])}function Ci(){const e=kn(vr),t=hr();return e?{source:e.contextData.source,entitySha:e.contextData.entitySha,scenarioId:e.contextData.scenarioId,analysisId:e.contextData.analysisId,currentUrl:t.pathname}:{source:"navbar",currentUrl:t.pathname}}function Ni(){var w;const e=hr(),t=It(),[r,a]=j(),[s,o]=j(!1),[i,l]=j(!1),[d,h]=j(null),u=ke();ne(()=>{u.state==="idle"&&!u.data&&u.load("/api/generate-report")},[u]);const m=((w=u.data)==null?void 0:w.defaultEmail)||"",p={width:"24px",height:"24px",strokeWidth:1.5},f=[{id:"dashboard",icon:n(No,{style:p}),link:"/",name:"Dashboard"},{id:"simulations",icon:c("svg",{width:"24",height:"24",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:p,children:[n("path",{d:"M9 12.75V15.75",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6 15.75H12",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6.75 12.7498L11.325 8.17483C11.6067 7.89873 11.9858 7.7447 12.3803 7.7461C12.7747 7.74751 13.1528 7.90423 13.4325 8.18233L16.5 11.2498",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6 8.25C6.82843 8.25 7.5 7.57843 7.5 6.75C7.5 5.92157 6.82843 5.25 6 5.25C5.17157 5.25 4.5 5.92157 4.5 6.75C4.5 7.57843 5.17157 8.25 6 8.25Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M15 2.25H3C2.17157 2.25 1.5 2.92157 1.5 3.75V11.25C1.5 12.0784 2.17157 12.75 3 12.75H15C15.8284 12.75 16.5 12.0784 16.5 11.25V3.75C16.5 2.92157 15.8284 2.25 15 2.25Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]}),link:"/simulations",name:"Simulations"},{id:"git",icon:n(da,{style:p}),link:"/git",name:"Git"},{id:"files",icon:n(So,{style:p}),link:"/files",name:"Files"},{id:"activity",icon:n(Ao,{style:p}),link:"/activity",name:"Activity"},{id:"settings",icon:n(Eo,{style:p}),link:"/settings",name:"Settings"},{id:"commits",icon:n(da,{style:p}),link:"/commits",name:"Commits",hidden:!0},{id:"pages",icon:n(_o,{style:p}),link:"/pages",name:"Pages",hidden:!0},{id:"components",icon:n(Po,{style:p}),link:"/components",name:"Components",hidden:!0}],g=re(v=>{const C=f.find(k=>k.id===v);C!=null&&C.link&&t(C.link),a(k=>k===v?void 0:v)},[f,t]);ne(()=>{const v={dashboard:["/","/home"],git:["git"],commits:["commits"],simulations:["simulations"],activity:["activity"],files:["files"],settings:["settings"],pages:["pages"],components:["components"]};for(const[C,k]of Object.entries(v))if(k.some(A=>A==="/"?e.pathname==="/":e.pathname.includes(A))){a(C);return}a(void 0)},[e]);const y=async()=>{l(!0);try{const{default:v}=await import("html2canvas-pro"),k=(await v(document.body)).toDataURL("image/jpeg",.8);h(k),o(!0)}catch(v){console.error("Screenshot capture failed:",v),o(!0)}finally{l(!1)}},b=()=>{o(!1),h(null)},x=Ci();return c(ue,{children:[c("div",{id:"sidebar",className:"relative w-full h-screen bg-cygray-30 flex flex-col justify-between py-3",children:[c("div",{className:"w-full flex flex-col items-center",children:[n("div",{children:n(oe,{to:"/",className:"flex items-center justify-center h-20 cursor-pointer",children:n("img",{src:es,alt:"CodeYam",className:"h-8"})})}),f.filter(v=>!v.hidden).map(v=>n(bi,{id:v.id,selected:v.id===r,onClick:g,icon:v.icon,name:v.name},`sidebar-button-${v.id}`))]}),n("div",{className:"w-full flex flex-col items-center pb-2",children:c("button",{onClick:()=>void y(),disabled:i,className:"flex flex-col items-center gap-1 p-2 rounded-lg text-gray-600 hover:bg-gray-100 hover:text-gray-900 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-wait",title:"Report an issue",children:[i?n(at,{style:p,className:"animate-spin"}):n(Ga,{style:p}),n("span",{className:"text-[10px] font-medium",children:i?"Capturing...":"Report Issue"})]})})]}),s&&n(ts,{isOpen:!0,onClose:b,context:x,defaultEmail:m,screenshotDataUrl:d??void 0})]})}const ns=mr(void 0);function Si({children:e}){const[t,r]=j([]),a=re((o,i="info",l=5e3)=>{const h={id:`toast-${Date.now()}-${Math.random()}`,message:o,type:i,duration:l};r(u=>[...u,h])},[]),s=re(o=>{r(i=>i.filter(l=>l.id!==o))},[]);return n(ns.Provider,{value:{toasts:t,showToast:a,closeToast:s},children:e})}function wr(){const e=kn(ns);if(!e)throw new Error("useToast must be used within a ToastProvider");return e}function Ai({toast:e,onClose:t}){ne(()=>{const s=e.duration||5e3;if(s>0){const o=setTimeout(()=>{t(e.id)},s);return()=>clearTimeout(o)}},[e.id,e.duration,t]);const r={success:"✅",error:"❌",info:"ℹ️",warning:"⚠️"};return c("div",{className:`flex items-center gap-3 px-4 py-3 rounded-lg border-2 shadow-lg min-w-[320px] max-w-[500px] animate-[slideIn_0.3s_ease-out] ${{success:"bg-emerald-50 border-emerald-200 text-emerald-900",error:"bg-red-50 border-red-200 text-red-900",info:"bg-blue-50 border-blue-200 text-blue-900",warning:"bg-amber-50 border-amber-200 text-amber-900"}[e.type]}`,children:[n("span",{className:"text-2xl",children:r[e.type]}),n("p",{className:"flex-1 text-sm font-medium m-0",children:e.message}),n("button",{onClick:()=>t(e.id),className:"text-gray-500 hover:text-gray-700 text-xl leading-none bg-transparent border-none cursor-pointer p-0 w-6 h-6 flex items-center justify-center rounded transition-colors hover:bg-black/10",children:"×"})]})}function Ei({toasts:e,onClose:t}){return e.length===0?null:c("div",{className:"fixed top-4 right-4 z-10000 flex flex-col gap-2",children:[n("style",{children:`
6
+ @keyframes slideIn {
7
+ from {
8
+ transform: translateX(400px);
9
+ opacity: 0;
10
+ }
11
+ to {
12
+ transform: translateX(0);
13
+ opacity: 1;
14
+ }
15
+ }
16
+ `}),e.map(r=>n(Ai,{toast:r,onClose:t},r.id))]})}function mt(e,t){const[r,a]=j(""),[s,o]=j(!1),[i,l]=j(null),[d,h]=j(!1);ne(()=>{t&&(h(!1),o(!1),l(null))},[t]),ne(()=>{if(!e||!t){t||a("");return}const m=async()=>{try{const f=await fetch(`/api/logs/${e}`);if(f.ok){const y=(await f.text()).trim().split(`
17
+ `).filter(w=>w.length>0);if(y.length<3){o(!1),h(!1),l(null),a("");return}const b=y.filter(w=>w.includes("CodeYam Log Level 1"));if(b.length>0){const w=b[b.length-1];a(w.replace(/.*CodeYam Log Level 1: /,""))}const x=y.find(w=>w.includes("$$INTERACTIVE_SERVER_URL$$:"));if(x){const w=x.split("$$INTERACTIVE_SERVER_URL$$:")[1].trim();l(w),h(!0)}y.some(w=>w.includes("CodeYam: Exiting start.js"))&&o(!0)}}catch{}};m().catch(()=>{});const p=setInterval(()=>{m().catch(()=>{})},2e3);return()=>clearInterval(p)},[e,t]);const u=re(()=>{a(""),o(!1),l(null),h(!1)},[]);return{lastLine:r,interactiveUrl:i,isCompleted:s,resetLogs:u}}function Rt({projectSlug:e,onClose:t}){const[r,a]=j("Loading logs..."),[s,o]=j(!0),[i,l]=j(!0),[d,h]=j("all"),u=Pe(null);return ne(()=>{const m=async()=>{try{const p=await fetch(`/api/logs/${e}`);if(p.ok){const f=await p.text();if(d==="all")a(f);else{const g=f.trim().split(`
18
+ `).filter(y=>{if(y.length===0)return!1;const b=y.match(/^.*CodeYam Log Level (\d+):/);return!!b&&Number(b[1])<=d});a(g.map(y=>y.replace(/^.*CodeYam Log Level \d+:\s*/,"")).join(`
19
+ `))}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(m().catch(()=>{}),s){const p=setInterval(()=>{m().catch(()=>{})},2e3);return()=>clearInterval(p)}},[e,s,i,d]),ne(()=>{const m=p=>{p.key==="Escape"&&t()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[t]),n("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-9999 p-5",onClick:t,children:c("div",{className:"bg-[#1e1e1e] rounded-lg shadow-2xl flex flex-col max-w-[1200px] w-full max-h-[90vh] overflow-hidden",onClick:m=>m.stopPropagation(),children:[c("div",{className:"flex justify-between items-center px-5 py-4 border-b border-[#333] bg-[#252525]",children:[c("h3",{className:"m-0 text-lg font-semibold text-white",children:["Analysis Logs - ",e]}),c("div",{className:"flex items-center gap-4",children:[c("label",{className:"flex items-center gap-2 text-sm text-[#ccc] select-none",children:[n("span",{children:"Log Level:"}),c("select",{value:d,onChange:m=>h(m.target.value==="all"?"all":Number(m.target.value)),className:"bg-[#333] text-white border border-[#555] rounded px-2 py-1 text-sm cursor-pointer outline-none transition-all hover:border-[#777] hover:bg-[#3a3a3a] focus:border-blue-600",children:[n("option",{value:"1",children:"1"}),n("option",{value:"2",children:"2"}),n("option",{value:"3",children:"3"}),n("option",{value:"4",children:"4"}),n("option",{value:"all",children:"All"})]})]}),c("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:s,onChange:m=>o(m.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-refresh"})]}),c("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:i,onChange:m=>l(m.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-scroll"})]}),n("button",{onClick:t,className:"bg-transparent border-none text-[#999] text-2xl cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-all hover:bg-[#333] hover:text-white",title:"Close (Esc)",children:"✕"})]})]}),n("pre",{className:"flex-1 m-0 px-5 py-4 overflow-auto font-mono text-[13px] leading-relaxed text-[#d4d4d4] bg-[#1e1e1e] whitespace-pre-wrap wrap-break-word scrollbar-thin scrollbar-thumb-[#424242] scrollbar-track-[#1e1e1e] hover:scrollbar-thumb-[#4f4f4f]",ref:u,children:r})]})})}function Ue({type:e}){const t={visual:{iconColor:"#7c3aed",bgColor:"bg-purple-100",bgHex:"#f3e8ff"},library:{iconColor:"#06b6d5",bgColor:"bg-[#e6fbff]",bgHex:"#e6fbff"},type:{iconColor:"#db2627",bgColor:"bg-[#ffe1e1]",bgHex:"#ffe1e1"},data:{iconColor:"#2563eb",bgColor:"bg-blue-100",bgHex:"#dbeafe"},index:{iconColor:"#ea580c",bgColor:"bg-orange-100",bgHex:"#ffedd5"},functionCall:{iconColor:"#7c3aed",bgColor:"bg-purple-100",bgHex:"#f3e8ff"},class:{iconColor:"#059669",bgColor:"bg-emerald-100",bgHex:"#d1fae5"},method:{iconColor:"#0891b2",bgColor:"bg-cyan-100",bgHex:"#cffafe"},other:{iconColor:"#6b7280",bgColor:"bg-gray-100",bgHex:"#f3f4f6"}},r=t[e]||t.other,a=()=>{switch(e){case"library":return n(Ja,{size:14,color:r.iconColor});case"visual":return n(Ht,{size:14,color:r.iconColor});case"type":return n(Io,{size:14,color:r.iconColor});case"data":return n(To,{size:14,color:r.iconColor});case"index":return n(Mo,{size:14,color:r.iconColor});case"functionCall":return n(ha,{size:14,color:r.iconColor});case"class":return n(ko,{size:14,color:r.iconColor});case"method":return n(ha,{size:14,color:r.iconColor});case"other":return n(ua,{size:14,color:r.iconColor});default:return n(ua,{size:14,color:r.iconColor})}};return n("span",{className:`flex items-center justify-center rounded ${r.bgColor}`,style:{width:"18px",height:"18px"},children:a()})}function rs({filePath:e,maxLength:t=60,className:r,style:a}){const o=((l,d)=>{if(l.length<=d)return l;const h="...",u=d-h.length,m=Math.ceil(u*.4),p=Math.floor(u*.6),f=l.slice(0,m),g=l.slice(-p),y=f.lastIndexOf("/"),b=g.indexOf("/"),x=y>m*.5?f.slice(0,y+1):f,w=b!==-1&&b<p*.5?g.slice(b):g;return`${x}${h}${w}`})(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 Vn({entity:e,nameSize:t="11px",pathSize:r="10px",pathMaxLength:a=50,showScenarioCount:s=!1,scenarioCount:o=0,additionalContent:i}){return c("div",{className:"flex flex-col gap-1",children:[c("div",{className:"flex items-center gap-1",children:[n(Ue,{type:e.entityType||"other"}),c(oe,{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(rs,{filePath:e.filePath,maxLength:a,style:{fontSize:r,color:"#8E8E8E"}})]}),i]})}const fa={fontSize:"9px",color:"#005C75",fontStyle:"italic"};function _i({currentRun:e,projectSlug:t,currentEntities:r=[],isAnalysisStarting:a=!1,queuedJobCount:s=0,queueJobs:o=[],currentlyExecuting:i=null,historicalRuns:l=[]}){var _,S,E;const[d,h]=j(!1),[u,m]=j(!1),[p,f]=j(null),[g,y]=j(new Set),[b,x]=j(new Set),w=!!i||o.length>0,v=!!i,C=(i==null?void 0:i.entities)||r;e!=null&&e.analysisCompletedAt,e==null||e.readyToBeCaptured,e==null||e.capturesCompleted;const k=(e==null?void 0:e.currentEntityShas)&&e.currentEntityShas.length>0,A=w,{lastLine:P}=mt(t,A),M=v||o.length>0,I=new Set(((_=i==null?void 0:i.entities)==null?void 0:_.map(R=>R.sha))||[]),N=l.filter(R=>!(R.currentEntityShas||[]).some(O=>I.has(O))),$=(()=>{const D=Date.now()-1440*60*1e3;if(e!=null&&e.createdAt&&k){const O=e.analysisCompletedAt||e.createdAt;if(new Date(O).getTime()>D)return!0}if(N.length>0){const O=N[0],H=O.analysisCompletedAt||O.archivedAt||O.createdAt;if(H&&new Date(H).getTime()>D)return!0}return!1})();return ne(()=>{const R=(i==null?void 0:i.id)||null;w&&!u&&R!==p&&m(!0),!w&&p!==null&&f(null)},[w,i==null?void 0:i.id,u,p]),c(ue,{children:[c("div",{className:`fixed bottom-4 right-4 z-9998 bg-white rounded shadow-lg border-2 border-primary-100 transition-all duration-200 ${u?"min-w-[350px] max-w-[500px]":"w-auto"}`,children:[!u&&c("div",{onClick:()=>{m(!0),f(null)},className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-gray-50 transition-colors",title:"Click to expand",children:[M?n(at,{size:16,className:"animate-spin",style:{color:"#005C75"}}):n("div",{className:"flex items-center justify-center rounded",style:{backgroundColor:"#E0E9EC",width:"20px",height:"20px"},children:n(Hn,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:M?"Analyzing...":"Activity: No Activity Yet"}),M&&n("button",{onClick:R=>{R.stopPropagation(),h(!0)},className:"ml-auto px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),u&&c("div",{children:[c("div",{className:"flex items-center justify-between px-3 py-2",children:[c("div",{className:"flex items-center gap-2",children:[M?n(at,{size:16,className:"animate-spin",style:{color:"#005C75"}}):n("div",{className:"flex items-center justify-center rounded",style:{backgroundColor:"#E0E9EC",width:"20px",height:"20px"},children:n(Hn,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:M?"Analyzing...":"Activity"})]}),c("div",{className:"flex items-center gap-2",children:[n("button",{onClick:()=>h(!0),className:"px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"}),n("button",{onClick:()=>{m(!1),f((i==null?void 0:i.id)||null)},className:"p-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC"},title:"Collapse","aria-label":"Collapse",children:n(bn,{size:16,style:{color:"#646464"}})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),c("div",{className:"px-3 pt-2 pb-3 space-y-3",children:[M&&i&&c("div",{children:[c("div",{className:"flex items-center gap-1.5 mb-2",children:[n(Hn,{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:C.length>0?c("div",{className:"space-y-1.5",children:[C.map(R=>n(Vn,{entity:R,nameSize:"11px",pathSize:"10px",pathMaxLength:150},R.sha)),P&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:P})]}):c("div",{children:[i.entityNames&&i.entityNames.length>0?c("div",{className:"space-y-0.5",children:[i.entityNames.slice(0,5).map((R,D)=>n("div",{style:{fontSize:"11px",color:"#343434"},children:R},D)),i.entityNames.length>5&&c("div",{className:"italic",style:{fontSize:"10px",color:"#666"},children:["+",i.entityNames.length-5," ","more"]})]}):c("div",{style:{fontSize:"11px",color:"#343434"},children:["Analyzing"," ",((S=i.entityShas)==null?void 0:S.length)||0," ",((E=i.entityShas)==null?void 0:E.length)===1?"entity":"entities","..."]}),P&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:P})]})})]}),o.length>0&&c("div",{children:[c("div",{className:"flex items-center gap-1.5 mb-2",children:[n(jo,{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(R=>{var H,Q;const D=g.has(R.id),O=D?R.entities:R.entities.slice(0,3);return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:R.entities.length>0?c("div",{className:"space-y-1.5",children:[O.map(q=>n(Vn,{entity:q,nameSize:"10px",pathSize:"9px",pathMaxLength:120},q.sha)),R.entities.length>3&&n("button",{onClick:()=>{y(q=>{const L=new Set(q);return L.has(R.id)?L.delete(R.id):L.add(R.id),L})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:fa,"aria-label":D?"Show fewer entities":`Show ${R.entities.length-3} more entities`,children:D?"Show less":`+${R.entities.length-3} more`})]}):c("div",{style:{fontSize:"10px",color:"#343434"},children:[R.type==="analysis"&&n(ue,{children:R.entityNames&&R.entityNames.length>0?c("div",{className:"space-y-0.5",children:[R.entityNames.slice(0,5).map((q,L)=>n("div",{children:q},L)),R.entityNames.length>5&&c("div",{className:"italic",children:["+",R.entityNames.length-5," more"]})]}):`Analyzing ${((H=R.entityShas)==null?void 0:H.length)||0} ${((Q=R.entityShas)==null?void 0:Q.length)===1?"entity":"entities"}`}),R.type==="recapture"&&"Recapturing scenario",R.type==="debug-setup"&&"Setting up debug environment"]})},R.id)})})]}),$&&N.length>0&&c("div",{children:[c("div",{className:"flex items-center gap-1.5 mb-2",children:[n(pr,{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:N.slice(0,3).map((R,D)=>{const O=R.entities||[],H=R.analysisCompletedAt||R.archivedAt||R.createdAt||"",Q=(()=>{if(!H)return"";const U=Date.now()-new Date(H).getTime(),Y=Math.floor(U/6e4),V=Math.floor(U/36e5);return V>0?`${V}h ago`:Y>0?`${Y}m ago`:"just now"})(),q=b.has(D),T=(q?O:O.slice(0,3)).map(U=>{var Y,V,le;return{...U,scenarioCount:((le=(V=(Y=U.analyses)==null?void 0:Y[0])==null?void 0:V.scenarios)==null?void 0:le.length)||0}});return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:O.length>0&&c("div",{className:"space-y-1.5",children:[T.map((U,Y)=>c("div",{className:"flex items-start justify-between gap-2",children:[n("div",{className:"flex-1 min-w-0",children:n(Vn,{entity:U,nameSize:"10px",pathSize:"9px",pathMaxLength:100,showScenarioCount:!0,scenarioCount:U.scenarioCount})}),Y===0&&Q&&n("div",{style:{fontSize:"9px",color:"#8E8E8E",whiteSpace:"nowrap",paddingTop:"2px"},children:Q})]},U.sha)),O.length>3&&n("button",{onClick:()=>{x(U=>{const Y=new Set(U);return Y.has(D)?Y.delete(D):Y.add(D),Y})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:fa,"aria-label":q?"Show fewer entities":`Show ${O.length-3} more entities`,children:q?"Show less":`+${O.length-3} more`})]})},D)})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),n("div",{className:"px-3 pb-2",children:n(oe,{to:"/activity",className:"text-xs font-medium hover:underline cursor-pointer",style:{color:"#005C75"},children:"View All Activity →"})})]})]}),d&&t&&n(Rt,{projectSlug:t,onClose:()=>h(!1)})]})}function He(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r===null?void 0:r]))}function Kt(e){const{file_id:t,project_id:r,commit_id:a,file_path:s,entity_type:o,entity_branches:i,analyses:l,commit:d,created_at:h,updated_at:u,...m}=e,p=(i??[]).map(y=>y.branch_id),f=l?l.map(tt):void 0,g=d?_t(d):void 0;return He({...m,fileId:t,projectId:r,commitId:a,filePath:s,entityType:o,commit:g,analyses:f,branchIds:p,createdAt:h,updatedAt:u})}function Cr(e){return He({id:e.id,projectId:e.project_id,name:e.name,path:e.path,deleted:!!e.deleted,metadata:e.metadata??void 0,createdAt:e.created_at,updatedAt:e.updated_at??void 0})}function Nr(e){const{branches:t,files:r,analyzed_at:a,content_changed_at:s,created_at:o,updated_at:i,github_token:l,configuration:d,team_id:h,...u}=e;return He({...u,branches:t?t.map(Tt):void 0,files:r?r.map(Cr):void 0,analyzedAt:a,contentChangedAt:s,createdAt:o,updatedAt:i})}function Pi(e){const{id:t,project_id:r,user_id:a,scenario_id:s,thumbs_up:o,user:i}=e,l=i?{username:i.github_username,avatarUrl:i.github_user.avatar_url}:void 0;return He({id:t,projectId:r,userId:a,scenarioId:s,thumbsUp:!!o,user:l})}function ki(e){const{id:t,project_id:r,user_id:a,scenario_id:s,text:o,created_at:i,updated_at:l,user:d}=e,h=d?{username:d.github_username,avatarUrl:d.github_user.avatar_url}:void 0;return He({id:t,projectId:r,userId:a,scenarioId:s,text:o,createdAt:i,updatedAt:l,user:h})}function as(e){const{project_id:t,analysis_id:r,previous_version_id:a,analysis:s,user_scenarios:o,scenario_comments:i,approved:l,...d}=e,h=s?tt(s):void 0,u=o?o.map(Pi):void 0,m=i?i.map(ki):void 0;return He({...d,projectId:t,analysisId:r,previousVersionId:a,analysis:h,userScenarios:u,comments:m})}function Mi(e){return He({id:e.id,analysisId:e.analysis_id,entitySha:e.entity_sha,branchId:e.branch_id,active:!!e.active,analysis:e.analysis?tt(e.analysis):void 0,entity:e.entity?Kt(e.entity):void 0,branch:e.branch?Tt(e.branch):void 0,createdAt:e.created_at})}function tt(e){const{project_id:t,commit_id:r,file_id:a,file_path:s,entity_sha:o,entity_type:i,entity_name:l,previous_analysis_id:d,file:h,entity:u,commit:m,project:p,scenarios:f,analysis_branches:g,dependency_analyzed_tree_sha:y,analyzed_tree_sha:b,branch_commit_sha:x,committed_at:w,completed_at:v,created_at:C,updated_at:k,indirect:A,...P}=e,M=u?Kt(u):void 0,I=h?Cr(h):void 0,N=p?Nr(p):void 0,$=m?_t(m):void 0,_=f?f.map(as):void 0,S=g?g.map(Mi):void 0,E=S?S.map(R=>R.branch):void 0;return He({...P,projectId:t,commitId:r,fileId:a,filePath:s,entitySha:o,entityType:i,entityName:l,previousAnalysisId:d,entity:M,file:I,commit:$,project:N,scenarios:_,analysisBranches:S,branches:E,dependencyAnalyzedTreeSha:y,analyzedTreeSha:b,branchCommitSha:x,committedAt:w,completedAt:v,createdAt:C,updatedAt:k,indirect:!!A})}function Sr(e){return He({id:e.id,commitId:e.commit_id,branchId:e.branch_id,active:!!e.active,commit:e.commit?_t(e.commit):void 0,branch:e.branch?Tt(e.branch):void 0})}function Ti(e){const{project_id:t,commit_id:r,created_at:a,updated_at:s,success:o,...i}=e;return He({...i,projectId:t,commitId:r,createdAt:a,updatedAt:s,success:!!o})}function _t(e){const{project_id:t,branch_id:r,branch:a,background_jobs:s,merged_branch_id:o,mergedBranch:i,ai_message:l,html_url:d,author:h,analyses:u,entities:m,commit_branches:p,committed_at:f,analyzed_at:g,...y}=e,b=a?Tt(a):void 0,x=i?Tt(i):void 0,w=(s==null?void 0:s.length)>0?Ti(s[s.length-1]):void 0,v=(u??[]).map(tt),C=(m??[]).map(Kt),k=(p==null?void 0:p.length)>0?p.map(Sr):void 0;return h&&(h.username=h.preferredUsername??h.username),He({...y,projectId:t,branchId:r,branch:b,backgroundJob:w,mergedBranchId:o,mergedBranch:x,aiMessage:l,htmlUrl:d,author:h,analyses:v,entities:C,commitBranches:k,committedAt:f,analyzedAt:g})}function Tt(e){const{project_id:t,content_changed_at:r,commits:a,analysis_branches:s,active_at:o,created_at:i,updated_at:l,primary:d,...h}=e,u=a?a.map(_t):void 0,m=s?s.flatMap(p=>tt(p.analysis)):void 0;return He({...h,projectId:t,contentChangedAt:r,commits:u,analyses:m,activeAt:o,createdAt:i,updatedAt:l,primary:!!d})}var Pn;class Ii{constructor(){la(this,Pn,new ji)}transformQuery(t){return ia(this,Pn).transformNode(t.node)}transformResult(t){return Promise.resolve(t.result)}}Pn=new WeakMap;class ji extends Go{transformValue(t){return{...super.transformValue(t),value:typeof t.value=="boolean"?t.value?1:0:t.value}}transformPrimitiveValueList(t){return{...t,values:t.values.map(r=>typeof r=="boolean"?r?1:0:r)}}}const J=()=>null,Ri={analyzed_at:J(),configuration:J(),content_changed_at:J(),created_at:J(),description:J(),github_token:J(),id:J(),metadata:J(),name:J(),path:J(),slug:J(),team_id:J(),updated_at:J()},$i=Object.keys(Ri),Di={active:J(),analysis_id:J(),branch_id:J(),created_at:J(),entity_sha:J(),id:J()},Li=Object.keys(Di),Oi={active_at:J(),content_changed_at:J(),created_at:J(),id:J(),metadata:J(),name:J(),primary:J(),project_id:J(),ref:J(),sha:J(),updated_at:J()},ss=Object.keys(Oi),Fi={ai_message:J(),analyzed_at:J(),author_github_username:J(),branch_id:J(),committed_at:J(),created_at:J(),files:J(),html_url:J(),id:J(),merged_branch_id:J(),message:J(),metadata:J(),project_id:J(),sha:J(),title:J(),url:J()},Yi=Object.keys(Fi),zi={commit_id:J(),created_at:J(),description:J(),documentation:J(),entity_type:J(),file_id:J(),file_path:J(),metadata:J(),name:J(),project_id:J(),quality:J(),sha:J(),updated_at:J()},os=Object.keys(zi),Bi={active:J(),branch_id:J(),entity_sha:J()},Ui=Object.keys(Bi),Wi={created_at:J(),deleted:J(),id:J(),metadata:J(),name:J(),path:J(),project_id:J(),updated_at:J()},Hi=Object.keys(Wi),Vi={analysis_id:J(),approved:J(),created_at:J(),description:J(),id:J(),metadata:J(),name:J(),previous_version_id:J(),project_id:J()},Ar=Object.keys(Vi),Gi=!!Nt("ENABLE_QUERY_LOGGING"),Ji=!!Nt("ENABLE_QUERY_ERROR_LOGGING");Nt("USE_LOCAL_POSTGRESQL_FOR_TESTING");let cn;function ve(){if(!cn){const e=ls();if(e==="sqlite")cn=qi();else if(e==="postgresql")cn=Ki();else throw new Error(`Unknown database type: ${e}`)}return cn}function qi(e){if(e||(e=Nt("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=ee.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 Wo(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 Qa({dialect:new qo({database:a}),plugins:[new Jo,new Ii],log:is})}function Ki(){const e=Zi();console.log(`CodeYam: Using PostgreSQL database at: ${e}`);const t=new Ho({connectionString:e});return t.on("error",(r,a)=>{console.error("CodeYam: Unexpected error on idle PostgreSQL client",r)}),new Qa({dialect:new Ko({pool:t}),log:is})}let Gn=null;function Pt(){return Gn||(Gn=Qi(ls())),Gn}function is(e){e.level==="error"?Ji&&console.error("Query failed : ",{durationMs:e.queryDurationMillis,error:e.error,sql:e.query.sql,params:e.query.parameters}):Gi&&console.log("Query executed : ",{durationMs:e.queryDurationMillis,sql:e.query.sql,params:e.query.parameters})}function Qi(e){if(e==="sqlite")return Qo;if(e==="postgresql")return Zo;throw new Error(`Unknown database type: ${e}`)}function ls(){if(Nt("SQLITE_PATH"))return"sqlite";if(Nt("POSTGRESQL_URL"))return"postgresql";throw new Error("No database configuration found. Set SQLITE_PATH for SQLite or POSTGRESQL_URL for PostgreSQL")}function Zi(){const e=Nt("POSTGRESQL_URL");if(!e)throw new Error("No PostgreSQL connection string found. Set POSTGRESQL_URL environment variable.");return e}function Nt(e){var t;return typeof window<"u"?(t=window.env)==null?void 0:t[e]:process.env[e]}var Qt=(e=>(e.Remix="Remix",e.CodeYam="CodeYam",e.CRA="CRA",e.Next="Next",e.NextPages="NextPages",e.Unknown="Unknown",e))(Qt||{});function Xi(e){return typeof e=="object"&&"localVariable"in e&&"instruction"in e&&("valueOptionRef"in e||"errorOptionRef"in e)}function el(e){var r;const t=(r=e.metadata)==null?void 0:r.keyAttributeInstructions;return!t||Object.keys(t).length===0?!1:Object.values(t).some(a=>typeof a=="object"&&("valueOptionRef"in a||"errorOptionRef"in a))}const Tn="Default Scenario";let tl="<main>";function nl(){return tl}function me(...e){const t=nl(),r=e.map(s=>{if(s)return typeof s=="string"?s:s instanceof Error?`${s.name}: ${s.message}
20
+ ${s.stack}`:typeof s=="object"?rl(s):String(s)}).filter(Boolean).join(`
21
+ `),a=`${t} ${r}`;if(!process.env.CODEYAM_ECS_TASK_ARN){console.log(a+`
22
+ `);return}console.log(a.replace(/\n/g,"\r"))}function rl(e,t=2){function r(a,s=new WeakMap){return a===null||typeof a!="object"?a:s.has(a)?`"[Circular: ${a.constructor.name}]"`:(s.set(a,!0),Array.isArray(a)?`[${a.map(l=>{const d=r(l,s);return typeof l=="string"?`"${d}"`:d}).join(",")}]`:`{${Object.entries(a).map(([i,l])=>{let d;return typeof l>"u"?null:(typeof l=="function"?d=`"(function: ${l.name||"anonymous"})"`:l instanceof Date?d=`"${l.toISOString()}"`:typeof l=="object"&&l!==null?d=r(l,s):typeof l=="string"?d=`"${l.replace(/"/g,'\\"')}"`:d=JSON.stringify(l),`"${i.replace(/"/g,'\\"')}":${d}`)}).filter(Boolean).join(",")}}`)}try{return JSON.stringify(e,null,t)}catch(a){const s=r(e);if(!t)return s;try{return JSON.stringify(JSON.parse(r(e)),null,t)}catch(o){return console.log("CodeYam Error: error stringifying object to provide proper spacing",{error:o,pureStringifyError:a,serialized:s}),s}}}function wn(e,t){try{let r=function(o){var i,l;if(_e.isFunctionDeclaration(o)&&Yt(o)){const d=((i=o.name)==null?void 0:i.text)||"default",h=o.getText(a),u=Jn(o);s.push({name:d,code:h,sha:yt(t,d,h),entityType:"function",isDefault:u})}else if(_e.isClassDeclaration(o)&&Yt(o)){const d=((l=o.name)==null?void 0:l.text)||"default",h=o.getText(a),u=Jn(o),m=h.includes("React.")||h.includes("jsx")||h.includes("tsx");s.push({name:d,code:h,sha:yt(t,d,h),entityType:m?"component":"class",isDefault:u})}else if(_e.isInterfaceDeclaration(o)&&Yt(o)){const d=o.name.text,h=o.getText(a);s.push({name:d,code:h,sha:yt(t,d,h),entityType:"interface",isDefault:!1})}else if(_e.isTypeAliasDeclaration(o)&&Yt(o)){const d=o.name.text,h=o.getText(a);s.push({name:d,code:h,sha:yt(t,d,h),entityType:"type",isDefault:!1})}else if(_e.isVariableStatement(o)&&Yt(o)){const d=Jn(o);o.declarationList.declarations.forEach(h=>{var u;if(_e.isIdentifier(h.name)){const m=h.name.text,p=o.getText(a),f=((u=h.initializer)==null?void 0:u.getText(a))||"",g=(t.endsWith(".tsx")||t.endsWith(".jsx"))&&f.includes("=>")&&(f.includes("<")||f.includes("React."));s.push({name:m,code:p,sha:yt(t,m,p),entityType:g?"component":"variable",isDefault:d})}})}else if(_e.isExportAssignment(o)){const d=o.getText(a);s.push({name:"default",code:d,sha:yt(t,"default",d),entityType:"unknown",isDefault:!0})}else if(_e.isExportDeclaration(o)&&o.exportClause&&_e.isNamedExports(o.exportClause)){const d=o.getText(a);for(const h of o.exportClause.elements){const u=h.name.text;s.push({name:u,code:d,sha:yt(t,u,d),entityType:"unknown",isDefault:!1})}}_e.forEachChild(o,r)};const a=_e.createSourceFile(t,e,_e.ScriptTarget.Latest,!0),s=[];return r(a),s}catch(r){return console.error(`Failed to extract entities from ${t}:`,r),[]}}function Yt(e){if(!_e.canHaveModifiers(e))return!1;const t=_e.getModifiers(e);return t?t.some(r=>r.kind===_e.SyntaxKind.ExportKeyword):!1}function Jn(e){if(!_e.canHaveModifiers(e))return!1;const t=_e.getModifiers(e);return t?t.some(r=>r.kind===_e.SyntaxKind.DefaultKeyword):!1}function yt(e,t,r){const a=fr.createHash("sha256");return a.update(`${e}:${t}:${r}`),a.digest("hex").substring(0,40)}function al(e){var h;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=((h=o.args)==null?void 0:h.map(u=>u.replace(/\$PORT/g,String(r))))??[],l=[];for(const u of a)if(u.key&&u.value!==void 0){const m=String(u.value).replace(/'/g,"'\\''");l.push(`${u.key}='${m}'`)}if(o.env)for(const[u,m]of Object.entries(o.env)){const f=String(m).replace(/\$PORT/g,String(r)).replace(/'/g,"'\\''");l.push(`${u}='${f}'`)}const d=l.length>0?l.join(" ")+" ":"";return o.command==="sh"&&i[0]==="-c"&&i[1]?`${d}sh -c "${i[1]}"`:`${d}${o.command} ${i.join(" ")}`}function sl(e,t){if(!t||t.length===0)return;if(t.length===1)return t[0];const r=ee.normalize(e),a=[...t].sort((s,o)=>{var i,l;return(((i=o.path)==null?void 0:i.length)??0)-(((l=s.path)==null?void 0:l.length)??0)});for(const s of a){const o=ee.normalize(s.path??".");if(o==="."||r.startsWith(o+ee.sep)||r===o)return s}return t[0]}function ol(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=sl(t,r);if(!i)throw new Error("Could not find webapp for file path: "+t);const l=al({webapp:i,port:s,environmentVariables:a,packageManager:o});return{webapp:i,webappPath:i.path??".",framework:i.framework,packageManager:i.packageManager??o,startCommand:l,url:`http://localhost:${s}/static/codeyam-sample`}}function Zt(e,t,r=[]){const a=Array.isArray(t)?t:[t];return s=>s.columns(a).doUpdateSet(o=>{const i=Object.keys(e).filter(l=>l!==t&&!r.includes(l));return Object.fromEntries(i.map(l=>[l,o.ref(`excluded.${l}`)]))})}function il(e){const{jsonObjectFrom:t}=Pt();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 ll({ids:e,analysisId:t}){const r=ve();try{let a=r.deleteFrom("scenarios");if(e){if(e.length===0)return;a=a.where("id","in",e)}else if(t)a=a.where("analysis_id","=",t);else throw me("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 me("CodeYam Error: Database error deleting scenarios",a,{ids:e,analysisId:t}),a}}function sr(...e){try{const t=fr.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 ga(e,t){return t.map(r=>cl(e,r))}function cl(e,t){return qe` ${qe.ref(e)}.${qe.ref(t)}`.as(t)}function dl(e,t,r){return t.map(a=>ul(e,a,r))}function ul(e,t,r){return qe` ${qe.ref(e)}.${qe.ref(t)}`.as(`_cy_${r}:${t}`)}function hl(e,...t){const r={};for(const[a,s]of Object.entries(e)){const o=a.match(/^_cy_(.+?):(.+)$/);if(o){const[,i,l]=o;if(t.includes(i)){r[i]||(r[i]={}),r[i][l]=s;continue}console.warn(`CodeYam Warning: Unrecognized prefix in key '${a}'`);continue}r[a]=s}return r}const ml=50;function pl(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 ya({projectId:e,ids:t,fileIds:r,entityName:a,entityShas:s,commitIds:o,branchCommitSha:i,limit:l}){const d=ve(),{jsonObjectFrom:h,jsonArrayFrom:u}=Pt();let m=d.selectFrom("analyses").selectAll("analyses");if(e&&(m=m.where("project_id","=",e)),t){if(t.length===0)return null;m=m.where("id","in",t)}if(r){if(r.length===0)return null;m=m.where("file_id","in",r)}if(o){if(o.length===0)return null;m=m.where("commit_id","in",o)}return a&&(m=m.where("entity_name","=",a)),s&&(m=m.where("entity_sha","in",s)),i&&(m=m.where("branch_commit_sha","=",i)),l&&(m=m.limit(l)),d.with("filtered_analyses",()=>m).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(p=>[h(p.selectFrom("entities").select(ga("entities",os)).whereRef("entities.sha","=","filtered_analyses.entity_sha").limit(1)).as("entity"),u(p.selectFrom("scenarios").select(ga("scenarios",Ar)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),u(p.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")])}async function ut(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:h}])=>(h==null?void 0:h.length)>0);let l=[];if(i){const[d,{arr:h,key:u}]=i,m=pl(h,ml),p=[];for(let f=0;f<m.length;f++){const g=m[f],b=await ya({...e,[u]:g}).execute();b&&p.push(...b)}l=p}else{const h=await ya(e).execute();if(!h||h.length===0)return me("CodeYam: No analyses found",null,e),null;l=h}return l.length===0?null:l.map(tt)}catch(o){return me("CodeYam Error: Database error in loadAnalyses",o,e),null}}function fl(e,t){const{jsonArrayFrom:r,jsonObjectFrom:a}=Pt();let s=e.selectFrom("analysis_branches").select(Li).select(o=>a(o.selectFrom("branches").select(ss).whereRef("id","=","analysis_branches.branch_id")).as("branch"));return t&&(s=t(s)),r(s)}async function st({id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:s,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:d,includeProject:h,includeCommitAndBranch:u,includeScenarios:m,includeBranches:p}){const f=ve();try{let g=f.selectFrom("analyses").selectAll("analyses");e&&(g=g.where("id","=",e)),r&&(g=g.where("project_id","=",r)),i?g=g.where("dependency_analyzed_tree_sha","=",i):l?g=g.where("analyzed_tree_sha","=",l):a&&(g=g.where("file_id","=",a)),o&&(g=g.where("entity_name","=",o)),s?g=g.where("commit_id","=",s):g=g.orderBy("created_at","desc").limit(1),t&&(g=g.innerJoin("analysis_branches","analyses.id","analysis_branches.analysis_id").where("analysis_branches.id","=",t));const{jsonObjectFrom:y,jsonArrayFrom:b}=Pt();g=g.select(w=>{const v=[];return v.push(y(w.selectFrom("entities").select(os).whereRef("entities.sha","=","analyses.entity_sha")).as("entity")),d&&v.push(y(w.selectFrom("files").select(Hi).whereRef("files.id","=","analyses.file_id")).as("file")),h&&v.push(y(w.selectFrom("projects").select($i).whereRef("projects.id","=","analyses.project_id")).as("project")),m&&v.push(b(w.selectFrom("scenarios").select(Ar).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")),p&&v.push(fl(w,C=>C.whereRef("analysis_branches.analysis_id","=","analyses.id")).as("analysis_branches")),u&&v.push(y(w.selectFrom("commits").select(Yi).select(C=>il(C).as("author")).whereRef("commits.id","=","analyses.commit_id")).as("commit")),v});const x=await g.executeTakeFirst();return x?tt(x):(me("CodeYam Error: Analysis not found",null,{id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:s,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:d,includeProject:h,includeCommitAndBranch:u,includeScenarios:m,includeBranches:p}),null)}catch(g){return me("CodeYam Error: Database error loading analysis",g,{id:e,analysisBranchId:t,projectId:r,fileId:a,commitId:s,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:d,includeProject:h,includeCommitAndBranch:u,includeScenarios:m,includeBranches:p}),null}}async function cs({projectId:e,ids:t,names:r,includeInactive:a}){const s=ve();try{let o=s.selectFrom("branches").selectAll("branches").where("project_id","=",e);if(t){if(t.length===0)return[];o=o.where("id","in",t)}if(r){if(r.length===0)return[];o=o.where("name","in",r)}return a||(o=o.where("active_at","is not",null)),(await o.execute()).map(Tt)}catch(o){return me("CodeYam Error: Database error loading branches",o,{projectId:e,ids:t,names:r,includeInactive:a}),[]}}async function gl({projectId:e,commitId:t,branchId:r,active:a,includeBranches:s}){const o=ve();try{let i=o.selectFrom("commit_branches").selectAll("commit_branches").innerJoin("branches","commit_branches.branch_id","branches.id").$if(s,h=>h.select(dl("branches",ss,"branch"))).where("branches.project_id","=",e);t&&(i=i.where("commit_branches.commit_id","=",t)),r&&(i=i.where("commit_branches.branch_id","=",r)),a!==void 0&&(i=i.where("commit_branches.active","=",a));const l=await i.execute();return!l||l.length===0?null:l.map(h=>hl(h,"branch")).map(Sr)}catch(i){return me("CodeYam Error: Error loading commit branches",i,{projectId:e,commitId:t,branchId:r,active:a,includeBranches:s}),null}}async function yl(e){if(e.length===0)return new Map;const t=ve();try{const r=await t.selectFrom("commits").select(["id","branch_id","merged_branch_id"]).where("id","in",e).execute(),a=new Set;if(r.forEach(o=>{o.branch_id&&a.add(o.branch_id),o.merged_branch_id&&a.add(o.merged_branch_id)}),a.size===0)return new Map;const s=await t.selectFrom("branches").selectAll().where("id","in",Array.from(a)).execute();return new Map(s.map(o=>[o.id,o]))}catch(r){return me("CodeYam Error: Loading branches for commits",r,{commitIds:e}),new Map}}async function xl(e){if(e.length===0)return new Map;const t=ve(),{jsonObjectFrom:r,jsonArrayFrom:a}=Pt();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(Ar).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")]).where("commit_id","in",e).execute(),o=new Map;return s.forEach(i=>{const l=o.get(i.commit_id)||[];l.push(i),o.set(i.commit_id,l)}),o}catch(s){return me("CodeYam Error: Loading analyses for commits",s,{commitIds:e}),new Map}}async function bl(e){if(e.length===0)return new Map;const t=ve();try{const r=await t.selectFrom("entities").selectAll().where("commit_id","in",e).execute(),a=new Map;return r.forEach(s=>{const o=a.get(s.commit_id)||[];o.push(s),a.set(s.commit_id,o)}),a}catch(r){return me("CodeYam Error: Loading entities for commits",r,{commitIds:e}),new Map}}async function Cn({projectId:e,branchId:t,ids:r,shas:a,fileNames:s,limit:o=10}){if(!e&&!r)throw new Error("Must provide projectId or ids");const i=ve(),{jsonObjectFrom:l}=Pt();try{let d=i.selectFrom("commits").selectAll("commits").select(y=>[l(y.selectFrom("github_users").select(["username","preferred_username as preferredUsername","avatar_url as avatarUrl"]).where("github_users.username","=",y.ref("commits.author_github_username"))).as("author")]);if(e&&(d=d.where("project_id","=",e)),r){if(r.length===0)return[];d=d.where("id","in",r)}if(a){if(a.length===0)return[];d=d.where("sha","in",a)}if(s&&s.length>0){const y=qe.join(s.map(b=>qe`${b}`),qe`, `);d=d.where(qe`
23
+ EXISTS (
24
+ SELECT 1
25
+ FROM json_each(${qe.ref("commits.files")}) AS f
26
+ WHERE json_extract(f.value, '$.fileName') IN (${y})
27
+ )
28
+ `)}t&&(d=d.where("branch_id","=",t));const h=await d.orderBy("committed_at","desc").limit(o).execute();if(!h||h.length===0)return[];const u=h.map(y=>y.id),[m,p,f]=await Promise.all([yl(u),xl(u),bl(u)]);return h.map(y=>{const b=y.branch_id?m.get(y.branch_id):void 0,x=y.merged_branch_id?m.get(y.merged_branch_id):void 0,w=p.get(y.id)||[],v=f.get(y.id)||[];return{...y,branch:b,mergedBranch:x,analyses:w,entities:v}}).map(_t)}catch(d){return me("CodeYam Error: Database error loading commits",d,{projectId:e,branchId:t,ids:r,shas:a,limit:o}),[]}}async function St({projectId:e,branchId:t,fileIds:r,filePaths:a,names:s,shas:o}){if(r&&r.length==0||a&&a.length==0||s&&s.length==0||o&&o.length==0)return[];if(o&&o.length>50){const l=[];for(let d=0;d<o.length;d+=50){const h=o.slice(d,d+50),u=await St({projectId:e,branchId:t,fileIds:r,filePaths:a,names:s,shas:h});u&&l.push(...u)}return l}const i=ve();try{const d=await i.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!d||d.length===0?(console.log("Load Entities: No entities found",{projectId:e,fileIds:r,filePaths:a,shas:o}),null):d.map(Kt)}catch(l){return console.log("Load Entities: Error occurred",l,{projectId:e,fileIds:r,filePaths:a,shas:o}),null}}function vl(e,t){const{jsonArrayFrom:r}=Pt();let a=e.selectFrom("entity_branches").select(Ui);return t&&(a=t(a)),r(a)}async function ds({projectId:e,sha:t}){const r=ve();try{const a=await r.selectFrom("entities").innerJoin("files","entities.file_id","files.id").selectAll("entities").select(s=>vl(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?Kt(a):(process.env.CODEYAM_E2E_BASELINE_MODE!=="true"&&me("CodeYam Error: Load Entity: Entity not found",null,{projectId:e,sha:t}),null)}catch(a){return me("CodeYam Error: Load Entity: Database error",a,{projectId:e,sha:t}),null}}const qn=1e3;async function us({projectId:e,filePaths:t,fileIds:r,fileNames:a}){if(t&&t.length>50){const l=[];for(let d=0;d<t.length;d+=50){const h=t.slice(d,d+50),u=await us({projectId:e,filePaths:h,fileIds:r,fileNames:a});u&&l.push(...u)}return l}const s=ve(),o=[];let i=0;try{for(;;){let l=s.selectFrom("files").selectAll().where("project_id","=",e).limit(qn).offset(i);if(t){if(t.length===0)return[];l=l.where("path","in",t)}if(r){if(r.length===0)return[];l=l.where("id","in",r)}if(a){if(a.length===0)return[];l=l.where("name","in",a)}const d=await l.execute();if(!d||d.length===0||(o.push(...d),d.length<qn))break;i+=qn}return o==null?void 0:o.map(Cr)}catch(l){return console.log("CodeYam Error: Error loading project files in loadFiles",l),null}}async function wl({id:e,slug:t,withBranches:r,withFiles:a,silent:s}){try{let i=ve().selectFrom("projects").selectAll();if(e)i=i.where("id","=",e);else if(t)i=i.where("slug","=",t);else throw new Error("Either id or slug must be provided");const l=await i.executeTakeFirst();if(!l)return s||console.log("CodeYam Error: Error loading project",{id:e,slug:t,withBranches:r,withFiles:a}),null;const d=Nr(l);return a&&(d.files=await us({projectId:d.id})),r&&(d.branches=await cs({projectId:d.id,includeInactive:!1})),d}catch(o){return s||console.log("CodeYam Error: Error loading project",o),null}}function Nn(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]=Nn(o,s):s!==void 0&&(r[a]=s)}return r}async function dt({commitId:e,commitSha:t,metadataUpdate:r,runStatusUpdate:a,archiveCurrentRun:s,updateCallback:o}){try{return await ve().transaction().execute(async i=>{var u,m;const l=await i.selectFrom("commits").selectAll().$if(!!e,p=>p.where("id","=",e)).$if(!!t,p=>p.where("sha","=",t)).executeTakeFirst();if(!l)return me(`CodeYam Error: updateCommitMetadata(): Commit ${e} not found`),null;const d=l.metadata||{};if(a)a.lastUpdatedAt??(a.lastUpdatedAt=new Date().toISOString()),a.currentEntityShas!==void 0&&(console.log("[updateCommitMetadata] Updating currentRun.currentEntityShas"),console.log(`[updateCommitMetadata] Commit SHA: ${t}`),console.log("[updateCommitMetadata] Previous entity SHAs:",(u=d.currentRun)==null?void 0:u.currentEntityShas),console.log("[updateCommitMetadata] New entity SHAs:",a.currentEntityShas),console.log("[updateCommitMetadata] Archive flag:",s)),r=Nn(r??{},{currentRun:a});else if(!r&&!o)return d;const h=r?Nn(d,r):d;if(s&&h.currentRun){console.log("[updateCommitMetadata] ========================================"),console.log("[updateCommitMetadata] ARCHIVING CURRENT RUN"),console.log(`[updateCommitMetadata] Commit SHA: ${t}`),console.log("[updateCommitMetadata] Current run entity SHAs:",h.currentRun.currentEntityShas),console.log(`[updateCommitMetadata] Current run PIDs: analyzer=${h.currentRun.analyzerPid}, capture=${h.currentRun.capturePid}`),console.log(`[updateCommitMetadata] Current run completed: analyses=${h.currentRun.analysesCompleted}, captures=${h.currentRun.capturesCompleted}`),console.log(`[updateCommitMetadata] Historical runs before archiving: ${((m=h.historicalRuns)==null?void 0:m.length)||0}`);const p={...h.currentRun,archivedAt:new Date().toISOString()};console.log("[updateCommitMetadata] Run to archive:",JSON.stringify(p,null,2)),h.historicalRuns=[...h.historicalRuns||[],p],console.log(`[updateCommitMetadata] Historical runs after archiving: ${h.historicalRuns.length}`),console.log("[updateCommitMetadata] All historical runs:",JSON.stringify(h.historicalRuns.map(f=>({entityShas:f.currentEntityShas,archivedAt:f.archivedAt,completed:{analyses:f.analysesCompleted,captures:f.capturesCompleted}})),null,2)),console.log("[updateCommitMetadata] ========================================")}o&&await o(h,_t(l));try{return await i.updateTable("commits").set({metadata:JSON.stringify(h)}).where("id","=",l.id).returningAll().executeTakeFirst()?h:(me(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`),d)}catch(p){return me(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`,p),d}})}catch(i){return me(`CodeYam Error: updateCommitMetadata(): Transaction failed for commit ${e}`,i),null}}async function hs(e,t,r="analysis"){try{return await ve().transaction().execute(async a=>{const s=await a.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!s)return me(`CodeYam Error: updateFreshAnalysisMetadata(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const o=tt(s);return t(o.metadata,o),await a.updateTable("analyses").set({metadata:JSON.stringify(o.metadata)}).where("id","=",e).returningAll().executeTakeFirst()?o.metadata:(me(`CodeYam Error: updateFreshAnalysisMetadata(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(a){return me(`CodeYam Error: updateFreshAnalysisMetadata(): Transaction failed for analysis ${e} (source: ${r})`,a,{analysisId:e,source:r}),null}}async function $t(e,t,r="capture"){try{return await ve().transaction().execute(async a=>{const s=await a.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!s)return me(`CodeYam Error: updateFreshAnalysisStatus(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const o=tt(s);return t(o.status,o),await a.updateTable("analyses").set({status:JSON.stringify(o.status)}).where("id","=",e).returningAll().executeTakeFirst()?o.status:(me(`CodeYam Error: updateFreshAnalysisStatus(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(a){return me(`CodeYam Error: updateFreshAnalysisStatus(): Transaction failed for analysis ${e} (source: ${r})`,a,{analysisId:e,source:r}),null}}async function Cl({projectId:e,projectSlug:t,metadataUpdate:r,updateCallback:a}){if(!e&&!t)throw new Error("Either projectId or projectSlug must be provided");try{return await ve().transaction().execute(async s=>{const o=await s.selectFrom("projects").selectAll().$if(!!e,d=>d.where("id","=",e)).$if(!!t,d=>d.where("slug","=",t)).executeTakeFirst();if(!o)return me(`CodeYam Error: updateProjectMetadata(): Project ${e} not found`),null;const i=o.metadata||{};if(!r&&!a)return i;const l=r?Nn(i,r):i;a&&await a(l,Nr(o));try{return await s.updateTable("projects").set({metadata:JSON.stringify(l)}).where("id","=",o.id).returningAll().executeTakeFirst()?l:(me(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`),null)}catch(d){return me(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`,d),null}})}catch(s){return me(`CodeYam Error: updateProjectMetadata(): Transaction failed for project ${e}`,s),null}}function Nl(e){const{id:t,projectId:r,commitId:a,fileId:s,filePath:o,entitySha:i,entityType:l,entityName:d,previousAnalysisId:h,entity:u,dependencyAnalyzedTreeSha:m,analyzedTreeSha:p,branchCommitSha:f,committedAt:g,completedAt:y,createdAt:b,updatedAt:x,metadata:w,status:v,commit:C,file:k,project:A,scenarios:P,analysisBranches:M,branches:I,...N}=e;return{...N,id:t??jt(),metadata:w?JSON.stringify(w):void 0,status:v?JSON.stringify(v):void 0,project_id:r,commit_id:a,file_id:s,file_path:o,entity_sha:i,entity_type:l,entity_name:d,previous_analysis_id:h,dependency_analyzed_tree_sha:m,analyzed_tree_sha:p,branch_commit_sha:f,committed_at:g,completed_at:y,created_at:b,updated_at:x}}async function ms(e){if(!e||e.length===0)return[];const t=ve(),r=e.map(a=>{const s={...a,status:{...a.status,sha:sr(JSON.stringify(a.status??{}))},metadata:{...a.metadata,sha:sr(JSON.stringify(a.metadata??{}))}},o=Nl(s);return delete o.created_at,o.updated_at||delete o.updated_at,o});try{return(await t.insertInto("analyses").values(r).onConflict(Zt(r[0],"id",["created_at"])).returningAll().execute()).map(tt)}catch(a){return me("CodeYam Error: Database error upserting analyses",a,{analysisCount:e.length,analysisDetails:r.map(s=>({id:s.id,filePath:s.file_path,entityName:s.entity_name,dependencyAnalyzedTreeSha:s.dependency_analyzed_tree_sha,analyzedTreeSha:s.analyzed_tree_sha}))}),[]}}function Sl(e){const{id:t,projectId:r,analysisId:a,previousVersionId:s,analysis:o,metadata:i,data:l,...d}=e;return delete d.userScenarios,delete d.comments,"created_at"in d&&delete d.created_at,{...d,id:t??jt(),metadata:i?JSON.stringify(i):null,project_id:r,analysis_id:a,previous_version_id:s}}async function ps(e){if(e.length===0)return[];const t=ve(),r=e.map(Sl);try{return(await t.insertInto("scenarios").values(r).onConflict(Zt(r[0],"id",["created_at"])).returningAll().execute()).map(as)}catch(a){return me("CodeYam Error: Database error upserting scenarios",a,{scenarioCount:e.length}),null}}function Al(e){const{id:t,commitId:r,branchId:a,...s}=e;return delete s.commit,delete s.branch,{...s,id:t??jt(),commit_id:r,branch_id:a}}async function xa(e){if(e.length===0)return[];const t=ve(),r=e.map(Al);try{return(await t.insertInto("commit_branches").values(r).onConflict(Zt(r[0],"id",["created_at"])).returningAll().execute()).map(Sr)}catch(a){return me("CodeYam Error: Database error upserting commit branches",a,{commitBranchCount:e.length,commitBranchIds:e.map(s=>s.id)}),[]}}async function El(e,t){const r=ve(),a={username:e,avatar_url:t};try{return await r.insertInto("github_users").values(a).onConflict(Zt(a,"username",[])).returningAll().executeTakeFirst()||null}catch(s){return me("CodeYam Error: Error upserting github user",s,{username:e,avatarUrl:t}),null}}function _l(e,t){const{id:r,projectId:a,branchId:s,mergedBranchId:o,aiMessage:i,htmlUrl:l,analyzedAt:d,committedAt:h,author:u,metadata:m,files:p,...f}=e;return delete f.branch,delete f.mergedBranch,delete f.backgroundJob,delete f.analyses,delete f.parents,delete f.entities,delete f.commitBranches,{...f,id:r??jt(),project_id:a??String(t),metadata:m?JSON.stringify(m):void 0,files:p?JSON.stringify(p):void 0,branch_id:s,merged_branch_id:o,author_github_username:u==null?void 0:u.username,html_url:l,ai_message:i,analyzed_at:d,committed_at:h}}async function Pl({projectId:e,commits:t}){const r=ve();try{const a=t.reduce((i,l)=>{const{author:d}=l;return d!=null&&d.username&&(d!=null&&d.avatarUrl)&&(i[d.username]=d.avatarUrl),i},{});for(const i in a)await El(i,a[i]);const s=t.map(i=>_l(i,e));return(await r.insertInto("commits").values(s).onConflict(Zt(s[0],"id",["created_at"])).returningAll().execute()).map(_t)}catch(a){return me("CodeYam Error: Error saving commits",a,{projectId:e,commitCount:t.length,commitIds:t.map(s=>s.id).filter(Boolean)}),[]}}const Sn=ee.join(ti.homedir(),".codeyam","secrets.json"),An=ee.join(process.cwd(),".codeyam","secrets.json");async function pt(){let e={};try{if(K.existsSync(An)){const o=await Re.readFile(An,"utf8");e=JSON.parse(o)}}catch{console.warn(vn.yellow("⚠ Could not read project secrets file, trying home directory"))}if(!e.OPENAI_API_KEY&&!e.ANTHROPIC_API_KEY)try{if(K.existsSync(Sn)){const o=await Re.readFile(Sn,"utf8");e={...JSON.parse(o),...e}}}catch{console.warn(vn.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 kl(e,t=!0){const r=t?Sn:An,a=ee.dirname(r);await Re.mkdir(a,{recursive:!0}),await Re.writeFile(r,JSON.stringify(e,null,2)),await Re.chmod(r,384)}function Ml(e=!0){return e?Sn:An}async function ba(){const e=await pt(),t=[];for(const r of t)e[r];return{isValid:!0,missing:[],secrets:e}}async function Tl(e){console.log(),console.log(vn.blue("ℹ Configuration needed")),console.log();const t={};for(const r of e)switch(r){case"OPENAI_API_KEY":const a=await ni({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 Il(e=!0){const t=await ba();if(t.isValid)return t.secrets;const r=await Tl(t.missing),s={...await pt(),...r};await kl(s,e);const o=Ml(e);return console.log(vn.green(`✓ Configuration saved to ${o}`)),(await ba()).secrets}function fs(e=process.cwd()){let t=ee.resolve(e);const r=ee.parse(t).root;for(;t!==r;){const s=ee.join(t,".codeyam","config.json");if(K.existsSync(s))return t;t=ee.dirname(t)}const a=ee.join(r,".codeyam","config.json");return K.existsSync(a)?r:null}let gs=fs();function pe(){return gs}function jl(e){gs=e}function ys(e){const t={...e};for(const r in e)if(r.includes(".")){const a=r.replace(/\./g,"");t[a]=e[r]}return t}const Rl={"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>`};ys(Rl);const $l={"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>`};ys($l);function zt(e,t,r=new WeakSet){if(!t)return e;if(!e)return t;try{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference detected during deep merge");r.add(t)}if(Array.isArray(t)){const s=Array.isArray(e)?e:[],o=[];for(let i=0;i<t.length;i++){const l=t[i];l&&typeof l=="object"&&!Array.isArray(l)||Array.isArray(l)?o[i]=zt(s[i],l,r):o[i]=l}return o}const a={...e};for(const s in t)if(t[s]===null)a[s]=null;else if(Array.isArray(t[s])){const o=Array.isArray(e[s])?e[s]:[];a[s]=[];for(let i=0;i<t[s].length;i++){const l=t[s][i];typeof l=="object"&&l!==null?a[s][i]=zt(o[i],l,r):a[s][i]=l}}else typeof t[s]=="object"&&t[s]!==null?a[s]=zt(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 Dl({projectId:e,commit:t,branch:r}){var l,d,h,u,m,p,f;let a;const s={commitId:t.id,branchId:r.id,active:!0},o=await gl({projectId:e,commitId:t.id,includeBranches:!0});if(o&&o.length>0){a=(l=o.sort((y,b)=>{var x,w,v,C;return(((w=(x=y.branch.metadata)==null?void 0:x.permanent)==null?void 0:w.order)??999)-(((C=(v=b.branch.metadata)==null?void 0:v.permanent)==null?void 0:C.order)??999)})[0])==null?void 0:l.branch,a&&((h=(d=r.metadata)==null?void 0:d.permanent)==null?void 0:h.order)!==void 0&&(((m=(u=r.metadata)==null?void 0:u.permanent)==null?void 0:m.order)<=((f=(p=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 xa(g.map(y=>({...y,active:y.branchId===a.id})))}(o==null?void 0:o.find(g=>g.branchId===s.branchId))||await xa([s])}function ft(){if(process.env.SQLITE_PATH)return process.env.SQLITE_PATH;const e=pe();if(!e)throw new Error("Could not find project root. Please run this command inside a CodeYam project.");return be.join(e,".codeyam","db.sqlite3")}async function $e(){const e=await Il();process.env.SQLITE_PATH=ft(),e.OPENAI_API_KEY&&(process.env.OPENAI_API_KEY=e.OPENAI_API_KEY)}async function Ye(e){await $e();const t=await wl({slug:e});if(!t)throw new Error(`Project with slug "${e}" not found in database`);const r=await cs({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 Ll(e,t,r){await $e();const a=pe(),s=sr(`${e.slug}-local-${Date.now()}-${Math.random()}`),o=r.map(d=>{let h="";if(a)try{if(h=Me(`git diff HEAD -- "${d}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10}),!h)try{const u=Me(`cat "${d}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"]});if(u){const m=u.split(`
29
+ `);h=`@@ -0,0 +1,${m.length} @@
30
+ ${m.map(p=>`+${p}`).join(`
31
+ `)}`}}catch{}}catch{}return{fileName:d,status:"modified",patch:h}}),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()}},l=await Pl({projectId:e.id,commits:[i]});if(!l||l.length===0)throw new Error("Failed to create fake commit");return await Dl({projectId:e.id,commit:l[0],branch:t}),l[0]}async function Xt(){await $e();const e=await St({});if(!e||e.length===0)return e;const t=e.filter(l=>{var d;return!((d=l.metadata)!=null&&d.isSuperseded)}),r=t.map(l=>l.sha),a=t.map(l=>{var d;return(d=l.metadata)==null?void 0:d.previousVersionWithAnalyses}).filter(l=>!!l),s=[...new Set([...r,...a])],o=await ut({entityShas:s}),i=new Map;if(o)for(const l of o)i.has(l.entitySha)||i.set(l.entitySha,[]),i.get(l.entitySha).push(l);return t.map(l=>{var u;const d=i.get(l.sha)||[];if(d.length>0)return{...l,analyses:d};const h=(u=l.metadata)==null?void 0:u.previousVersionWithAnalyses;if(h){const m=i.get(h)||[];return{...l,analyses:m}}return{...l,analyses:[]}})}async function In(e,t){await $e();const r=await ut({entityShas:[e],limit:1});if(r&&r.length>0&&t){const a=await ds({projectId:r[0].projectId,sha:e});if(a)for(const s of r)s.entity=a}return r||[]}async function Er(e){if(await $e(),e.name&&e.projectId){const r=await ut({projectId:e.projectId,entityName:e.name,limit:10});if(r&&r.length>0){const a=r.filter(o=>{const i=o.scenarios&&o.scenarios.length>0,l=!e.filePath||o.filePath===e.filePath;return i&&l});if(a.length>0)return a.sort((o,i)=>{const l=new Date(o.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-l}),a[0];const s=r.filter(o=>o.scenarios&&o.scenarios.length>0);if(s.length>0)return s.sort((o,i)=>{const l=new Date(o.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-l}),s[0]}}const t=await ut({entityShas:[e.sha],limit:1});return t&&t.length>0?t[0]:null}async function xs(e){await $e();const t=await ut({entityShas:[e],limit:1});return(t==null?void 0:t[0])??null}async function At(e){await $e();const t=await ze();if(!t)return null;const{project:r}=await Ye(t);return await ds({projectId:r.id,sha:e})}async function bs(e){var a,s,o,i,l,d,h,u;await $e();const t=[],r=[];if((a=e.metadata)!=null&&a.importedExports&&e.metadata.importedExports.length>0){const m=e.metadata.importedExports;for(const p of m){if(!p.filePath||!p.name)continue;const f=await St({projectId:e.projectId,filePaths:[p.filePath],names:[p.name]});if(f&&f.length>0){const g=f[0],y=await ut({entityShas:[g.sha],limit:1});let b,x,w;if(y&&y.length>0&&y[0].scenarios){const v=y[0],C=v.scenarios||[],k=C.length,A=C.find(M=>{var I,N;return(N=(I=M.metadata)==null?void 0:I.screenshotPaths)==null?void 0:N[0]});A&&(b=(o=(s=A.metadata)==null?void 0:s.screenshotPaths)==null?void 0:o[0],x=A.name),w={status:((i=g.metadata)==null?void 0:i.previousVersionWithAnalyses)||v.entitySha!==g.sha?"out_of_date":"up_to_date",scenarioCount:k,timestamp:v.createdAt?new Date(v.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else w={status:"not_analyzed"};t.push({...g,screenshotPath:b,scenarioName:x,analysisStatus:w})}}}if((l=e.metadata)!=null&&l.importedBy){const m=[];for(const p in e.metadata.importedBy)for(const f in e.metadata.importedBy[p]){const g=e.metadata.importedBy[p][f];g.shas&&m.push(...g.shas)}if(m.length>0){const p=await St({projectId:e.projectId,shas:m});if(p)for(const f of p){const g=await ut({entityShas:[f.sha],limit:1});let y,b,x;if(g&&g.length>0&&g[0].scenarios){const w=g[0],v=w.scenarios||[],C=v.length,k=v.find(P=>{var M,I;return(I=(M=P.metadata)==null?void 0:M.screenshotPaths)==null?void 0:I[0]});k&&(y=(h=(d=k.metadata)==null?void 0:d.screenshotPaths)==null?void 0:h[0],b=k.name),x={status:((u=f.metadata)==null?void 0:u.previousVersionWithAnalyses)||w.entitySha!==f.sha?"out_of_date":"up_to_date",scenarioCount:C,timestamp:w.createdAt?new Date(w.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else x={status:"not_analyzed"};r.push({...f,screenshotPath:y,scenarioName:b,analysisStatus:x})}}}return{importedEntities:t,importingEntities:r}}async function ze(){try{const e=pe();if(!e)return null;const t=be.join(e,".codeyam","config.json");return JSON.parse(await Ie.readFile(t,"utf8")).projectSlug||null}catch(e){return console.error("[getProjectSlug] Error:",e),null}}async function kt(){await $e();try{const e=await ze();if(!e)return null;const{project:t,branch:r}=await Ye(e),a=await Cn({projectId:t.id,branchId:r.id,limit:1});return a&&a.length>0?a[0]:null}catch(e){return console.error("[getCurrentCommit] Error:",e),null}}async function _r(){try{const e=pe();if(!e)return null;const t=be.join(e,".codeyam","config.json");return JSON.parse(await Ie.readFile(t,"utf8"))}catch(e){return console.error("[getProjectConfig] Error:",e),null}}async function vs(e){try{const t=pe();if(!t)return console.error("[getEntityCodeFromFilesystem] No project root found"),null;if(!e.filePath)return console.error("[getEntityCodeFromFilesystem] Entity has no filePath"),null;const r=be.join(t,e.filePath);return await Ie.readFile(r,"utf8")}catch(t){return console.error("[getEntityCodeFromFilesystem] Error reading file:",t),null}}async function ws(e){try{const t=pe();if(!t||!e.filePath)return!1;const r=be.join(t,e.filePath),s=(await Ie.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 Cs(e){if(await $e(),!e.filePath||!e.name||!e.projectId)return console.error("[getEntityHistory] Entity missing required fields (filePath, name, or projectId)"),[];const t=await St({projectId:e.projectId,filePaths:[e.filePath],names:[e.name]});if(!t||t.length===0)return[];const r=t.map(i=>i.sha),a=await ut({entityShas:r}),s=new Map;if(a)for(const i of a)s.has(i.entitySha)||s.set(i.entitySha,[]),s.get(i.entitySha).push(i);for(const[i,l]of s.entries())l.sort((d,h)=>{const u=new Date(d.createdAt||0).getTime();return new Date(h.createdAt||0).getTime()-u});const o=t.map(i=>({...i,analyses:s.get(i.sha)||[]}));return o.sort((i,l)=>{var u,m;const d=((u=i.analyses[0])==null?void 0:u.createdAt)||i.createdAt||"",h=((m=l.analyses[0])==null?void 0:m.createdAt)||l.createdAt||"";return new Date(h).getTime()-new Date(d).getTime()}),o}async function Ns(e){try{const t=pe();if(!t)return console.error("[updateProjectConfig] No project root found"),!1;const r=be.join(t,".codeyam","config.json"),a=await Ie.readFile(r,"utf8"),s=JSON.parse(a),o={...s,...e},i=JSON.stringify(o,null,2);if(await Ie.writeFile(r,i,"utf8"),s.projectSlug){const l={};e.universalMocks!==void 0&&(l.universalMocks=e.universalMocks),e.pathsToIgnore!==void 0&&(l.pathsToIgnore=e.pathsToIgnore),e.webapps!==void 0&&(l.webapps=e.webapps),await Cl({projectSlug:s.projectSlug,metadataUpdate:l})}return!0}catch(t){return console.error("[updateProjectConfig] Error:",t),!1}}const Ol=Object.freeze(Object.defineProperty({__proto__:null,getAllEntities:Xt,getAnalysesForEntity:In,getAnalysisForExactEntitySha:xs,getCurrentCommit:kt,getEntityBySha:At,getEntityCodeFromFilesystem:vs,getEntityHistory:Cs,getLatestAnalysisForEntity:Er,getProjectConfig:_r,getProjectSlug:ze,getRelatedEntities:bs,hasFileBeenModifiedSinceEntity:ws,updateProjectConfig:Ns},Symbol.toStringTag,{value:"Module"})),Ss="secrets.json";function As(e){return be.join(e,".codeyam",Ss)}function Es(){return be.join(ar.homedir(),".codeyam",Ss)}async function jn(e){let t={};try{const r=Es(),a=await Ie.readFile(r,"utf-8");t=JSON.parse(a)}catch{}try{const r=As(e),a=await Ie.readFile(r,"utf-8"),s=JSON.parse(a);t={...t,...s}}catch{}return t}async function Fl(e,t,r=!0){const a=r?Es():As(e),s=be.dirname(a);await Ie.mkdir(s,{recursive:!0}),await Ie.writeFile(a,JSON.stringify(t,null,2)+`
32
+ `,"utf-8")}async function Yl(e){const t=await jn(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 zl="/assets/globals-wHVy_II5.css";function Bl({text:e,subtext:t,linkText:r,linkTo:a}){const[s,o]=j(!1);return s?null:n("div",{className:"bg-blue-100 border rounded border-blue-800 shadow-sm mx-6 mt-6",children:c("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[c("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-yellow-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),c("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-blue-900",children:e}),n("p",{className:"text-xs text-blue-700 mt-0.5",children:t})]}),n(oe,{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 En(e){return ee.join(e,".codeyam","queue.json")}function Bt(e){const t=En(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 Ul(e,t){const r=En(e),a=ee.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 Wl({sourcePath:e,destinationPath:t,excludes:r=[],keepExisting:a=!1,silent:s=!1,extraArgs:o=[]}){return new Promise((i,l)=>{const d=e.endsWith("/")?e:`${e}/`,h=t.endsWith("/")?t:`${t}/`,u=["-a"];a||u.push("--delete","--force"),u.push(...o);for(const f of r)u.push(`--exclude=${f}`);u.push(d,h);const m=Date.now(),p=gr("rsync",u);p.on("exit",f=>{if(f===0){if(!s){const g=((Date.now()-m)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${g}s]`)}i()}else l(new Error(`rsync failed with exit code ${f}`))}),p.on("error",f=>{s||console.log("Error occurred:",f),l(f)})})}const Hl=xr(yr);async function Vl(e){return new Promise(t=>setTimeout(t,e))}function Gl(e){try{return process.kill(e,0),!0}catch{return!1}}async function _s(e){try{const{stdout:t}=await Hl(`ps -A -o pid=,ppid= | awk '$2 == ${e} { print $1 }'`),r=t.trim().split(`
33
+ `).filter(s=>s.trim()).map(s=>parseInt(s.trim(),10)).filter(s=>!isNaN(s)),a=[...r];for(const s of r){const o=await _s(s);a.push(...o)}return a}catch{return[]}}function va(e,t,r){try{process.kill(e,t)}catch(a){r==null||r(`Error sending ${t} to process ${e}: ${a}`)}}async function Jl(e,t,r){const a=await _s(e);for(const s of a.reverse())await va(s,t,r);await va(e,t,r)}async function Vt(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 Jl(e,o,t);for(let l=0;l<i;l++)if(await Vl(1e3),a+=1e3,!await Gl(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 ql(e){const t=new Date().toISOString();e.currentRun&&(e.currentRun.archivedAt=t,e.historicalRuns??(e.historicalRuns=[]),e.historicalRuns.push(e.currentRun)),e.currentRun={id:pi(),createdAt:t}}ri.config({quiet:!0});var Ps=(e=>(e.Server="server",e.Analyzer="analyzer",e.Capture="capture",e.Controller="controller",e.Worker="worker",e.Project="project",e.Other="other",e))(Ps||{});class Kl extends ai{constructor(){super(...arguments),this.processes=new Map}register(t){const r=oi(),{process:a,type:s,name:o,metadata:i,parentId:l}=t,d={id:r,type:s,name:o,pid:a.pid,state:"running",startedAt:Date.now(),metadata:i,parentId:l,children:[]};if(this.processes.set(r,{info:d,process:a}),l){const m=this.processes.get(l);m&&(m.info.children=m.info.children||[],m.info.children.push(r))}const h=(m,p)=>{this.handleProcessExit(r,m,p)},u=m=>{this.handleProcessError(r,m)};return a.on("exit",h),a.on("error",u),a.__cleanup=()=>{a.removeListener("exit",h),a.removeListener("error",u)},this.emit("processStarted",d),r}unregister(t){const r=this.processes.get(t);return r?(r.process.__cleanup&&r.process.__cleanup(),this.processes.delete(t),!0):!1}getInfo(t){const r=this.processes.get(t);return r?{...r.info}:null}listAll(){return Array.from(this.processes.values()).map(t=>({...t.info}))}listByType(t){return this.listAll().filter(r=>r.type===t)}listByState(t){return this.listAll().filter(r=>r.state===t)}findByName(t){return this.listAll().filter(r=>r.name===t)}async shutdown(t,r={}){const a=this.processes.get(t);if(!a)throw new Error(`Process not found: ${t}`);const{info:s,process:o}=a;if(s.state==="completed"||s.state==="failed"||s.state==="killed")return;if(r.shutdownChildren&&s.children&&s.children.length>0&&await Promise.all(s.children.map(l=>this.shutdown(l,r))),o.pid)try{await Vt(o.pid,l=>console.log(`[Process ${t}] ${l}`))}catch(l){console.warn(`Error killing process ${t}:`,l)}await new Promise(l=>setTimeout(l,100)),s.state==="running"&&(s.state="killed",s.endedAt=Date.now());const i=o.__cleanup;i&&i()}async shutdownByType(t,r={}){const a=this.listByType(t);await Promise.all(a.map(s=>this.shutdown(s.id,r)))}async shutdownAll(t={}){const r=this.listAll();await Promise.all(r.map(a=>this.shutdown(a.id,t)))}cleanupCompleted(t={}){const{retentionMs:r=6e4}=t,a=Date.now();for(const[s,o]of this.processes.entries()){const{info:i}=o;if((i.state==="completed"||i.state==="failed"||i.state==="killed")&&i.endedAt&&a-i.endedAt>r){const l=o.process.__cleanup;l&&l(),this.processes.delete(s)}}}handleProcessExit(t,r,a){const s=this.processes.get(t);if(!s)return;const{info:o}=s;o.endedAt=Date.now(),o.exitCode=r,o.signal=a,r===0?o.state="completed":a?o.state="killed":o.state="failed",this.emit("processExited",o)}handleProcessError(t,r){const a=this.processes.get(t);if(!a)return;const{info:s}=a;s.endedAt=Date.now(),s.state="failed",s.metadata={...s.metadata,error:r.message},this.emit("processExited",s)}}let Kn=null;function Ql(){return Kn||(Kn=new Kl),Kn}const Zl={stdoutToConsole:!0,stdoutToFile:!0,stderrToConsole:!0,stderrToFile:!0};function Xl({command:e,args:t,workingDir:r,outputOptions:a=Zl,processName:s,env:o}){const i={...process.env,...o||{},CODEYAM_PROCESS_NAME:`codeyam-${s}`},l=gr(e,t,{cwd:r,env:i});return Ql().register({process:l,type:Ps.Other,name:s,metadata:{command:e,args:t,workingDir:r}}),{promise:new Promise(u=>{const m=f=>{const g=be.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(`
34
+ `).map(x=>x.trim()?`[${y}]${g} ${x}`:x).join(`
35
+ `)};l.stdout.on("data",function(f){const g=(f==null?void 0:f.toString())??"",y=p(g);a.stdoutToConsole&&console.log(y),a.stdoutToFile&&m(y+`
36
+ `),a.stdoutCallback&&a.stdoutCallback(g)}),l.stderr.on("data",function(f){const g=(f==null?void 0:f.toString())??"",y=p(g,"<STDERR>");a.stderrToConsole&&console.error(y),a.stderrToFile&&m(y+`
37
+ `),a.stderrCallback&&a.stderrCallback(g)}),l.on("exit",function(f){u(f)})}),process:l}}function ec(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 tc({absoluteCodeyamRootPath:e,startEnv:t,startArgs:r,outputOptions:a}){const s=Object.entries(t).map(([i,l])=>`${i}=${l}`).join(`
38
+ `);K.writeFileSync(`${e}/.env`,s);const o=ec(r);return Xl({command:"node",args:["--enable-source-maps","./dist/project/start.js",...o],workingDir:e,outputOptions:a,processName:"analyzer",env:t})}const nc="/tmp/codeyam/local-dev";function ks(e){return ee.join(nc,e)}function Ms(e){return ee.join(ks(e),"codeyam")}function ot(e){return ee.join(ks(e),"project")}function Rn(e){return ee.join(Ms(e),"log.txt")}const rc=[".sync-metadata.json","__codeyamMocks__"];async function ac(e,t={}){const{port:r,silent:a=!0}=t,s=ot(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 sc(e,t={}){const{killProcesses:r=!0,port:a,silent:s=!0}=t,o=ot(e),i=[],l=[];if(!K.existsSync(o))return{removed:i,errors:l};r&&await ac(e,{port:a,silent:s});for(const d of rc){const h=ee.join(o,d);if(K.existsSync(h))try{(await Re.stat(h)).isDirectory()?await Re.rm(h,{recursive:!0,force:!0}):await Re.unlink(h),i.push(d)}catch(u){l.push(`${d}: ${u instanceof Error?u.message:String(u)}`)}}return{removed:i,errors:l}}const oc=ee.dirname(Za(import.meta.url));function ic(e){let t=e;for(;t!==ee.dirname(t);){const r=ee.join(t,"package.json");if(K.existsSync(r))try{if(JSON.parse(K.readFileSync(r,"utf8")).name==="@codeyam/codeyam-cli")return t}catch{}t=ee.dirname(t)}throw new Error("Could not find @codeyam/codeyam-cli package root")}function Pr(){const e=ic(oc);return ee.join(e,"analyzer-template")}function Dt(e){return Ms(e)}async function wa(e){const t=Pr(),r=Dt(e);if(!K.existsSync(t))throw new Error(`Analyzer template not found at ${t}. Did the build process complete successfully?`);await Re.mkdir(ee.dirname(r),{recursive:!0}),await Wl({sourcePath:t,destinationPath:r,silent:!0})}function Lt(e,t,r,a){const s=Dt(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 tc({absoluteCodeyamRootPath:s,startEnv:t,startArgs:r,outputOptions:{stdoutToConsole:!1,stdoutToFile:!0,stdoutCallback:o,stderrToConsole:!1,stderrToFile:!0,stderrCallback:o}})}function lc(e){const t=Pr(),r=Dt(e),a=ee.join(t,".build-info.json"),s=ee.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 en(e,t){const r=Dt(e);if(!K.existsSync(r)){t.update("Creating analyzer..."),await wa(e);return}const a=lc(e);a.isFresh||(t.update(`Updating analyzer (${a.reason})...`),await wa(e))}async function kr(e){await sc(e,{killProcesses:!1})}const cc=ee.dirname(Za(import.meta.url));function Ts(){let e=cc;for(;e!==ee.dirname(e);){const t=ee.join(e,"package.json");if(K.existsSync(t))try{if(JSON.parse(K.readFileSync(t,"utf8")).name==="@codeyam/codeyam-cli")return e}catch{}e=ee.dirname(e)}return null}function dc(){const e=Ts();return e?ee.join(e,"package.json"):null}function fn(e){if(!K.existsSync(e))return null;try{return JSON.parse(K.readFileSync(e,"utf8"))}catch{return null}}function Is(e){let t="unknown";const r=Ts(),a=dc();if(a)try{t=JSON.parse(K.readFileSync(a,"utf8")).version||"unknown"}catch{}let s=null;if(r){const u=[ee.join(r,"src/webserver/build-info.json"),ee.join(r,"codeyam-cli/src/webserver/build-info.json")];for(const m of u)if(s=fn(m),s)break}const o=Pr(),i=ee.join(o,".build-info.json"),l=fn(i);let d=null;if(e){const u=Dt(e),m=ee.join(u,".build-info.json");d=fn(m)}let h=!1;return l&&d?h=l.buildTime>d.buildTime:l&&!d&&e&&(h=!0),{cliVersion:t,webserverVersion:s,templateVersion:l,cachedAnalyzerVersion:d,isCacheStale:h}}function $n(e){const t=Dt(e),r=ee.join(t,".build-info.json"),a=fn(r);return(a==null?void 0:a.version)??null}async function uc(e,t,r){console.log(`[Queue] Executing job ${e.id} (${e.type})`);try{if(e.type==="analysis")await hc(e,t,r);else if(e.type==="baseline")await mc(e,t,r);else if(e.type==="recapture")await pc(e,t,r);else if(e.type==="capture-only")await fc(e,t,r);else if(e.type==="debug-setup")await gc(e,t,r);else if(e.type==="interactive-start")await yc(e,t,r);else if(e.type==="interactive-stop")await xc(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 hc(e,t,r){var y,b,x,w;const{projectSlug:a,commitSha:s,entityShas:o}=e;if(!s)throw new Error("Analysis job missing commitSha");const i=o||[],{project:l}=await Ye(a);await kr(a),await en(a,{update:v=>console.log(`[Queue] ${v}`)});const d=$n(a),h={...await pt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:s,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:ft(),...i.length>0?{ENTITY_SHAS:i.join(",")}:{},...e.onlyDataStructure?{ONLY_DATA_STRUCTURE:"true"}:{},...d?{ANALYZER_VERSION:d}:{}},u=(b=(y=l.metadata)==null?void 0:y.webapps)==null?void 0:b[0];if(!u)throw new Error("No webapps found in project metadata");const m=e.onlyDataStructure,p={packageManager:((x=l.metadata)==null?void 0:x.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:0,noServer:!0,framework:u.framework,...m?{}:{orchestrateCapture:"local-sequential"}},f=Lt(a,h,p),g=v=>{try{return process.kill(v,0),!0}catch{return!1}};await dt({commitSha:s,runStatusUpdate:{currentEntityShas:i,entityCount:i.length||((w=e.filePaths)==null?void 0:w.length)||0,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString(),analyzerPid:f.process.pid}}),r==null||r.notifyChange("commit");try{try{const v=new Promise((C,k)=>setTimeout(()=>k(new Error("Analysis timed out after 60 minutes")),36e5));await Promise.race([f.promise,v]),await dt({commitSha:s,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),await dt({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 Vt(f.process.pid,()=>{})}catch{}}}catch(v){if(console.error(`[Queue] Analysis job ${e.id} failed:`,v),f.process.pid&&g(f.process.pid))try{await Vt(f.process.pid,()=>{})}catch{}try{await dt({commitSha:s,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:v instanceof Error?v.message:String(v)}}),r==null||r.notifyChange("commit")}catch(C){console.error("[Queue] Failed to update commit metadata after job failure:",C)}throw v}}async function mc(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 Ye(a);await kr(a),await en(a,{update:y=>console.log(`[Queue] ${y}`)});const i=$n(a),l={...await pt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",BRANCH_COMMIT_SHA:s,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:ft(),...i?{ANALYZER_VERSION:i}:{}},d=(f=(p=o.metadata)==null?void 0:p.webapps)==null?void 0:f[0];if(!d)throw new Error("No webapps found in project metadata");const h={packageManager:((g=o.metadata)==null?void 0:g.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:0,noServer:!0,framework:d.framework,orchestrateCapture:"local-sequential"},u=Lt(a,l,h),m=y=>{try{return process.kill(y,0),!0}catch{return!1}};await dt({commitSha:s,runStatusUpdate:{createdAt:new Date().toISOString(),analyzerPid:u.process.pid}}),r==null||r.notifyChange("commit");try{const y=new Promise((b,x)=>setTimeout(()=>x(new Error("Baseline timed out after 4 hours")),144e5));await Promise.race([u.promise,y]),await dt({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(b=>setTimeout(b,2e3))}finally{if(u.process.pid)try{m(u.process.pid)&&await Vt(u.process.pid,()=>{})}catch{}}}async function pc(e,t,r){var f,g,y,b;const{projectSlug:a,analysisId:s,scenarioId:o,defaultWidth:i}=e;if(!s)throw new Error("Recapture job missing analysisId");const l=await st({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!l||!l.commit)throw new Error(`Analysis ${s} not found`);if(i){const{getDatabase:x}=await import("./index-pU0o5t1o.js"),w=x(),v=await w.selectFrom("entities").select(["metadata"]).where("sha","=",l.entitySha).executeTakeFirst();let C={};v!=null&&v.metadata&&(typeof v.metadata=="string"?C=JSON.parse(v.metadata):C=v.metadata),C.defaultWidth=i,await w.updateTable("entities").set({metadata:JSON.stringify(C)}).where("sha","=",l.entitySha).execute()}await $t(s,x=>{if(x.readyToBeCaptured=!0,x.scenarios)for(const w of x.scenarios)(!o||w.name===o)&&(delete w.finishedAt,delete w.startedAt,delete w.screenshotStartedAt,delete w.screenshotFinishedAt,delete w.interactiveStartedAt,delete w.interactiveFinishedAt,delete w.error,delete w.errorStack);delete x.finishedAt});const{project:d}=await Ye(a);await en(a,{update:x=>console.log(`[Queue] ${x}`)});const h=$n(a),u={...await pt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:l.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:ft(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:s,...o?{SCENARIO_IDS:o}:{},...h?{ANALYZER_VERSION:h}:{}},m={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:void 0,noServer:!0,framework:((b=(y=(g=d.metadata)==null?void 0:g.webapps)==null?void 0:y[0])==null?void 0:b.framework)??Qt.Next,orchestrateCapture:"local-sequential"},p=Lt(a,u,m);try{await p.promise}finally{try{p.process.kill("SIGTERM")}catch{}}}async function fc(e,t,r){var f,g,y,b;const{projectSlug:a,analysisId:s,scenarioId:o,defaultWidth:i}=e;if(!s)throw new Error("Capture-only job missing analysisId");const l=await st({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!l||!l.commit)throw new Error(`Analysis ${s} not found`);if(i){const{getDatabase:x}=await import("./index-pU0o5t1o.js"),w=x(),v=await w.selectFrom("entities").select(["metadata"]).where("sha","=",l.entitySha).executeTakeFirst();let C={};v!=null&&v.metadata&&(typeof v.metadata=="string"?C=JSON.parse(v.metadata):C=v.metadata),C.defaultWidth=i,await w.updateTable("entities").set({metadata:JSON.stringify(C)}).where("sha","=",l.entitySha).execute()}await $t(s,x=>{if(x.readyToBeCaptured=!0,x.scenarios)for(const w of x.scenarios)(!o||w.name===o)&&(delete w.finishedAt,delete w.startedAt,delete w.screenshotStartedAt,delete w.screenshotFinishedAt,delete w.interactiveStartedAt,delete w.interactiveFinishedAt,delete w.error,delete w.errorStack);delete x.finishedAt});const{project:d}=await Ye(a);await en(a,{update:x=>console.log(`[Queue] ${x}`)});const h=$n(a),u={...await pt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:l.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:ft(),READY_TO_BE_CAPTURED:"true",CAPTURE_ONLY:"true",ANALYSIS_IDS:s,...o?{SCENARIO_IDS:o}:{},...h?{ANALYZER_VERSION:h}:{}},m={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:void 0,noServer:!0,fast:!0,framework:((b=(y=(g=d.metadata)==null?void 0:g.webapps)==null?void 0:y[0])==null?void 0:b.framework)??Qt.Next,orchestrateCapture:"local-sequential"},p=Lt(a,u,m);try{await p.promise}finally{try{p.process.kill("SIGTERM")}catch{}}}async function gc(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 st({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${s} not found`);const{project:l}=await Ye(a);await kr(a),await en(a,{update:b=>console.log(`[Queue] ${b}`)});const d={...await pt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:ft(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:s,PREP_ONLY:"true"};o&&(d.SCENARIO_IDS=o);const h={packageManager:((p=l.metadata)==null?void 0:p.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:void 0,noServer:!1,framework:((y=(g=(f=l.metadata)==null?void 0:f.webapps)==null?void 0:g[0])==null?void 0:y.framework)||Qt.Next},m=await Lt(a,d,h).promise;if(m!==0)throw new Error(`Prep process exited with code ${m}`)}async function yc(e,t,r){var m,p,f,g;const{projectSlug:a,analysisId:s,scenarioId:o}=e;if(!s)throw new Error("Interactive start job missing analysisId");const i=await st({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${s} not found`);const{project:l}=await Ye(a),d={...await pt(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:ft(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:s,INTERACTIVE_MODE:"true"};o&&(d.SCENARIO_IDS=o);const h={packageManager:((m=l.metadata)==null?void 0:m.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:void 0,noServer:!1,framework:((g=(f=(p=l.metadata)==null?void 0:p.webapps)==null?void 0:f[0])==null?void 0:g.framework)||Qt.Next};await $t(s,y=>{y.readyToBeCaptured=!0});const u=Lt(a,d,h);await hs(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 xc(e,t,r){var d;const{projectSlug:a,analysisId:s}=e;if(!s)throw new Error("Interactive stop job missing analysisId");const o=await st({id:s,includeScenarios:!0,includeCommitAndBranch:!0});if(!o)throw new Error(`Analysis ${s} not found`);const i=(d=o.metadata)==null?void 0:d.interactiveMode;if(!(i!=null&&i.pid)){console.log(`[Queue] No interactive mode process found for analysis ${s}`);return}const l=i.pid;console.log(`[Queue] Stopping interactive mode for analysis ${s}, killing PID: ${l}`);try{try{process.kill(l,0)}catch{console.log(`[Queue] Process ${l} already exited`);return}await Vt(l,()=>{}),console.log(`[Queue] Successfully killed interactive mode process ${l}`)}catch(h){throw console.error(`[Queue] Failed to kill process ${l}:`,h),h}finally{await hs(s,h=>{h.interactiveMode=null})}}class bc{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=Bt(this.projectRoot),this.state.jobs.length>0?(this.state.paused=!0,this.save(),console.log(`[Queue] Found ${this.state.jobs.length} queued jobs from previous session (paused)`)):this.state.paused=!1}enqueue(t){const r=t.commitSha||jt(),a={...t,id:r,queuedAt:new Date().toISOString()};this.state.jobs.push(a),this.save(),console.log(`[Queue] Enqueued job ${r} (${a.type})`);const s=new Promise((o,i)=>{this.completionCallbacks.set(r,l=>{l?i(l):o()})});return this.state.paused||this.processNext().catch(o=>{console.error("[Queue] ERROR in processNext():",o)}),{jobId:r,completion:s}}resume(){console.log("[Queue] Resuming queue"),this.state.paused=!1,this.save(),this.processNext()}pause(){console.log("[Queue] Pausing queue"),this.state.paused=!0,this.save()}getState(){return{...this.state}}getJobResult(t){return this.completedJobs.get(t)}removeJob(t){const r=this.state.jobs.length;this.state.jobs=this.state.jobs.filter(s=>s.id!==t);const a=this.state.jobs.length<r;if(a){console.log(`[Queue] Removed job ${t}`),this.save();const s=this.completionCallbacks.get(t);s&&(setImmediate(()=>s(new Error("Job cancelled by user"))),this.completionCallbacks.delete(t))}else console.log(`[Queue] Job ${t} not found in queue`);return a}clearQueue(){const t=this.state.jobs.length;return t===0?0:(this.state.jobs.forEach(r=>{const a=this.completionCallbacks.get(r.id);a&&(setImmediate(()=>a(new Error("Job cancelled by user"))),this.completionCallbacks.delete(r.id))}),this.state.jobs=[],console.log(`[Queue] Cleared ${t} jobs`),this.save(),t)}reorderJob(t,r){const a=this.state.jobs.findIndex(i=>i.id===t);if(a===-1)return console.log(`[Queue] Job ${t} not found in queue`),!1;const s=r==="up"?a-1:a+1;if(s<0||s>=this.state.jobs.length)return console.log(`[Queue] Cannot move job ${t} ${r}: at boundary`),!1;const o=this.state.jobs[a];return this.state.jobs[a]=this.state.jobs[s],this.state.jobs[s]=o,console.log(`[Queue] Moved job ${t} ${r} (position ${a} -> ${s})`),this.save(),!0}async processNext(){if(this.state.paused||this.processing)return;if(this.state.jobs.length===0){console.log("[Queue] No jobs to process");return}this.processing=!0;const t=this.state.jobs[0];console.log(`[Queue] Starting job ${t.id} (${t.type})`);try{this.state.currentlyExecuting=this.state.jobs.shift(),this.save(),await uc(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(){Ul(this.projectRoot,this.state),this.notifier&&this.notifier.notifyChange("queue")}}class vc{constructor(t,r,a=100){this.watcher=null,this.debounceTimer=null,this.projectRoot=t,this.onChange=r,this.debounceMs=a}start(){const t=En(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=En(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 wc{constructor(t,r,a){this.fileWatcher=null,this.serverInfo=t,this.projectRoot=r,this.onStateChange=a,this.cachedState=Bt(r)}start(){this.cachedState=Bt(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 vc(this.projectRoot,()=>{console.log("[ProxyQueue] Detected queue.json change from background server"),this.refreshState()}),this.fileWatcher.start()}enqueue(t){let r,a;const s=new Promise((i,l)=>{r=i,a=l}),o=`proxy-${Date.now()}-${Math.random().toString(36).slice(2)}`;return this.enqueueRemote(t).then(i=>{console.log(`[ProxyQueue] Job enqueued on background server: ${i.jobId}`),this.refreshState(),r()}).catch(i=>{console.error("[ProxyQueue] Failed to enqueue job:",i),a(i)}),{jobId:o,completion:s}}async enqueueRemote(t){const r=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"enqueue",...t})});if(!r.ok){const a=await r.text();throw new Error(`Failed to enqueue: ${r.status} ${a}`)}return r.json()}resume(){console.log("[ProxyQueue] Sending resume command to background server"),this.sendAction("resume").catch(t=>{console.error("[ProxyQueue] Failed to resume:",t)})}pause(){console.log("[ProxyQueue] Sending pause command to background server"),this.sendAction("pause").catch(t=>{console.error("[ProxyQueue] Failed to pause:",t)})}async sendAction(t){const r=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t})});if(!r.ok){const a=await r.text();throw new Error(`Failed to ${t}: ${r.status} ${a}`)}this.refreshState()}getState(){return this.cachedState=Bt(this.projectRoot),{...this.cachedState}}refreshState(){this.cachedState=Bt(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 Cc(e){const t=ee.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 Nc(e){try{return process.kill(e,0),!0}catch{return!1}}async function Sc(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 Ac(e){const t=Cc(e);return!t||!Nc(t.pid)||!await Sc(t.url)?null:{url:t.url,port:t.port,pid:t.pid}}class Ec extends si{constructor(){super();ln(this,"watcher",null);ln(this,"dbPath",null);ln(this,"isWatching",!1);this.setMaxListeners(20)}async start(){if(!this.isWatching)try{this.dbPath=ft();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 or=new Ec;let vt=null,Ut=null;async function _c(){if(!vt){if(Ut){await Ut;return}Ut=(async()=>{try{const e=process.env.CODEYAM_ROOT_PATH||fs()||process.cwd();jl(e),console.log(`[GlobalQueue] Project root: ${e}`);const t=await Ac(e);if(t){console.log(`[GlobalQueue] Detected background server at ${t.url} (PID: ${t.pid})`),console.log("[GlobalQueue] Using proxy queue");const r=new wc(t,e,()=>{or.notifyChange("unknown")});await r.start(),vt=r}else{console.log("[GlobalQueue] No background server detected, using local queue");const r=new bc(e,or);await r.start(),vt=r}console.log("[GlobalQueue] Queue initialized")}catch(e){throw console.error("[GlobalQueue] Failed to initialize queue:",e),e}})(),await Ut}}async function it(){return vt||await _c(),vt}function Pc(){return vt||(Ut&&console.warn("[GlobalQueue] Queue still initializing, loader may see empty state"),null)}const kc=()=>[{rel:"stylesheet",href:zl},{rel:"icon",type:"image/x-icon",href:"/favicon.ico"}];async function Mc({request:e,context:t}){var r,a,s,o,i,l,d;try{const h=pe()||process.cwd(),[u,m,p]=await Promise.all([kt(),ze(),jn(h)]);if(!m)throw new Error("Project slug not found");const f=t.analysisQueue||Pc(),g=f==null?void 0:f.getState(),y=async E=>{if(!E||E.length===0)return[];const R=Math.min(Math.max(E.length*2e3,1e4),6e4),D=new Promise(H=>setTimeout(()=>{console.warn(`[Loader] Entity fetch timeout after ${R}ms for ${E.length} entities`),H([])},R)),O=Promise.all(E.map(H=>At(H))).then(H=>H.filter(Q=>Q!==null));return Promise.race([O,D])},b=await Promise.all(((g==null?void 0:g.jobs)||[]).map(async E=>{var D;const R=await y(E.entityShas||[]);return R.length===0&&((D=E.entityShas)!=null&&D.length)&&console.warn("[Loader] Entity fetch timeout/failed for job",E.id),{...E,entities:R}}));let x=null;if(g!=null&&g.currentlyExecuting){const E=g.currentlyExecuting,R=await y(E.entityShas||[]);R.length===0&&((r=E.entityShas)!=null&&r.length)&&console.warn("[Loader] Entity fetch timeout/failed for currentlyExecuting",E.id),x={...E,entities:R}}const w=x?b.filter(E=>E.id!==x.id):b;let v=((s=(a=u==null?void 0:u.metadata)==null?void 0:a.currentRun)==null?void 0:s.currentEntityShas)||[];if(v.length===0){const E=((o=u==null?void 0:u.metadata)==null?void 0:o.historicalRuns)||[];if(E.length>0){const D=[...E].sort((O,H)=>{const Q=O.archivedAt||O.createdAt||"";return(H.archivedAt||H.createdAt||"").localeCompare(Q)})[0];if(D){const O=D.analysisCompletedAt||D.createdAt;if(O){const H=new Date(O).getTime(),q=Date.now()-1440*60*1e3;H>q&&(v=D.currentEntityShas||[])}}}}const C=await y(v),k=[];p.ANTHROPIC_API_KEY&&k.push("ANTHROPIC_API_KEY"),p.GROQ_API_KEY&&k.push("GROQ_API_KEY"),p.OPENAI_API_KEY&&k.push("OPENAI_API_KEY"),p.OPENROUTER_API_KEY&&k.push("OPENROUTER_API_KEY");const{project:A,branch:P}=await Ye(m),M=await Cn({projectId:A.id,branchId:P.id,limit:20}),I=[];for(const E of M){const R=((i=E.metadata)==null?void 0:i.historicalRuns)||[];for(const D of R){const O=D.currentEntityShas||[];if(O.length>0){const H=await y(O);I.push({...D,entities:H})}else I.push(D)}}const N=I.sort((E,R)=>{const D=E.archivedAt||E.analysisCompletedAt||E.createdAt||"";return(R.archivedAt||R.analysisCompletedAt||R.createdAt||"").localeCompare(D)}),$=new Set(((l=x==null?void 0:x.entities)==null?void 0:l.map(E=>E.sha))||[]),_=N.filter(E=>!(E.currentEntityShas||[]).some(D=>$.has(D))),S={currentRun:(d=u==null?void 0:u.metadata)==null?void 0:d.currentRun,projectSlug:m,currentEntities:C,availableAPIKeys:k,queuedJobCount:w.length,queueJobs:w,currentlyExecuting:x,historicalRuns:_};return z(S)}catch(h){return console.error("Failed to load root data:",h),z({currentRun:void 0,projectSlug:null,currentEntities:[],availableAPIKeys:[],queuedJobCount:0,queueJobs:[],currentlyExecuting:null,historicalRuns:[]})}}function Tc(){const{currentRun:e,projectSlug:t,currentEntities:r,availableAPIKeys:a,queuedJobCount:s,queueJobs:o,currentlyExecuting:i,historicalRuns:l}=Ke(),{toasts:d,closeToast:h}=wr(),u=ht(),m=Pe(u),p=hr();ne(()=>{m.current=u},[u]);const f=p.pathname.startsWith("/entity/")&&p.pathname.includes("/edit/")||p.pathname.startsWith("/dev/"),g=p.pathname.includes("/fullscreen");return ne(()=>{const y=new EventSource("/api/events");let b=null,x=0;const w=2e3;return y.addEventListener("message",v=>{const C=JSON.parse(v.data);if(C.type==="queue")m.current.revalidate(),x=Date.now();else if(C.type==="db-change"||C.type==="unknown"){const k=Date.now(),A=k-x;A<w?(b&&clearTimeout(b),b=setTimeout(()=>{m.current.revalidate(),x=Date.now(),b=null},w-A)):(m.current.revalidate(),x=k)}}),y.addEventListener("error",v=>{console.error("SSE connection error:",v)}),()=>{b&&clearTimeout(b),y.close()}},[]),c(ue,{children:[c("div",{className:`min-h-screen ${f?"":"grid"} bg-cygray-10`,style:f?void 0:{gridTemplateColumns:"96px minmax(900px, 1fr)"},children:[!f&&n(Ni,{}),c("div",{className:"max-h-screen overflow-auto bg-white",children:[a.length===0&&n(Bl,{text:"No AI API keys configured. Please provide an AI API key at your earliest convenience.",subtext:"An API key is required for stable, frequent use of CodeYam",linkText:"Configure API Keys",linkTo:"/settings"}),n(bo,{})]})]}),n(Ei,{toasts:d,onClose:h}),!g&&n(_i,{currentRun:e,projectSlug:t,currentEntities:r,isAnalysisStarting:!1,queuedJobCount:s,queueJobs:o,currentlyExecuting:i,historicalRuns:l})]})}const Ic=We(function(){return c("html",{lang:"en",children:[c("head",{children:[n("meta",{charSet:"utf-8"}),n("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),n(fo,{}),n(go,{})]}),c("body",{children:[n(Si,{children:n(wi,{children:n(Tc,{})})}),n(yo,{}),n(xo,{})]})]})}),jc=Object.freeze(Object.defineProperty({__proto__:null,default:Ic,links:kc,loader:Mc},Symbol.toStringTag,{value:"Module"}));function Ca(e){const t=e.replace(/[^a-zA-Z0-9_]+/g,"_");return t.slice(0,1).toUpperCase()+t.slice(1)}function tn({analysisId:e,scenarioId:t,scenarioName:r,projectSlug:a,enabled:s=!0,refreshTrigger:o=0}){const i=ke(),[l,d]=j(null),[h,u]=j(!1),[m,p]=j(!1),[f,g]=j(!1),y=Pe(!1),b=Pe(null),x=Pe(null),[w,v]=j(0),[C,k]=j(0),A=Pe(null),P=Pe(!1),{interactiveUrl:M,resetLogs:I}=mt(a,s),N=Pe(t),$=Pe(o);ne(()=>{$.current!==o&&($.current=o,l&&(console.log("[useInteractiveMode] Manual refresh triggered"),p(!0),g(!1),v(0),k(S=>S+1),P.current=!1,A.current&&(clearTimeout(A.current),A.current=null)))},[o,l]),ne(()=>{if(N.current!==t&&(N.current=t,b.current&&x.current&&r)){const S=Ca(x.current),E=Ca(r),R=b.current.replace(S,E);d(R),p(!0),g(!1),v(0),k(D=>D+1),P.current=!1,A.current&&(clearTimeout(A.current),A.current=null);return}},[t,r]),ne(()=>{if(M){const S=M+"?width=600px";b.current=S,r&&(x.current=r),d(S),u(!1),p(!0)}},[M]),ne(()=>{const S=E=>{E.data.type==="codeyam-resize"&&(P.current||(P.current=!0,A.current&&(clearTimeout(A.current),A.current=null),v(0),g(!0),requestAnimationFrame(()=>{requestAnimationFrame(()=>{p(!1)})})))};return window.addEventListener("message",S),()=>window.removeEventListener("message",S)},[]);const _=()=>{P.current=!1,A.current&&clearTimeout(A.current);const S=500*Math.pow(2,w);A.current=setTimeout(()=>{P.current||(w<2?(v(E=>E+1),k(E=>E+1),p(!0)):(console.error("[useInteractiveMode] Interactive mode failed to load after 3 attempts - showing iframe anyway"),g(!0),p(!1)))},S)};return ne(()=>{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(E){console.error("[useInteractiveMode] Failed to clear log file:",E)}I(),i.submit({action:"start",analysisId:e,scenarioId:t},{method:"post",action:"/api/interactive-mode"})})())},[s,t,e,I,a]),ne(()=>{const S=e,E=()=>{if(y.current&&S){const D=new URLSearchParams({action:"stop",analysisId:S});console.log("[useInteractiveMode] Sending stop request via sendBeacon");const O=navigator.sendBeacon("/api/interactive-mode",D);console.log("[useInteractiveMode] sendBeacon result:",O),O||(console.log("[useInteractiveMode] sendBeacon failed, using fetch fallback"),fetch("/api/interactive-mode",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:D,keepalive:!0}).catch(H=>console.error("Failed to stop interactive mode:",H)))}},R=()=>{E()};return window.addEventListener("beforeunload",R),()=>{window.removeEventListener("beforeunload",R),console.log("[useInteractiveMode] Cleanup running:",{hasStarted:y.current,analysisId:S}),E()}},[e]),{interactiveServerUrl:l,isStarting:h,isLoading:m,showIframe:f,iframeKey:C,onIframeLoad:_}}const dn=10,Rc=1024;function js({currentViewportWidth:e,currentPresetName:t,onDevicePresetClick:r,devicePresets:a,onHoverChange:s,hideLabel:o=!1}){const[i,l]=j(null),d=Pe(null),h=se(()=>[...a].sort((x,w)=>x.width-w.width),[a]),{fittingPresets:u,overflowPresets:m}=se(()=>{const x=[],w=[];for(const v of h)v.width<=Rc?x.push(v):w.push(v);return w.sort((v,C)=>C.width-v.width),{fittingPresets:x,overflowPresets:w}},[h]),p=re(x=>{if(!d.current)return null;const w=d.current.getBoundingClientRect(),v=x-w.left,C=w.width,k=C/2,P=(u.length>0?u[u.length-1].width:0)/2,M=k-P,I=k+P,N=m.length>0?(m.length-1)*dn:0;if(m.length>0){if(v<M){if(v<=N){const _=Math.min(Math.floor(v/dn),m.length-1);return m[_]}return m[m.length-1]}if(v>I){const _=C-v;if(_<=N){const S=Math.min(Math.floor(_/dn),m.length-1);return m[S]}return m[m.length-1]}}const $=Math.abs(v-k);for(let _=u.length-1;_>=0;_--){const S=u[_],E=u[_-1],R=S.width/2,D=E?E.width/2:0;if($<=R&&$>=D)return S}return u[0]||m[m.length-1]||null},[u,m]),f=re(x=>{const w=p(x.clientX);l(w),s==null||s(w)},[p,s]),g=re(()=>{l(null),s==null||s(null)},[s]),y=re(x=>{const w=p(x.clientX);w&&r(w)},[p,r]),b=i||{name:t,width:e};return c("div",{ref:d,className:"relative h-6 shrink-0 overflow-hidden cursor-pointer",onMouseMove:f,onMouseLeave:g,onClick:y,children:[i&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:n("div",{className:"h-full transition-all duration-100 bg-[#005C75]",style:{width:`${i.width}px`}})}),n("div",{className:"absolute inset-0 pointer-events-none",children:u.map(x=>{const w=x.width===e,v=(i==null?void 0:i.name)===x.name,C=x.width/2;return c("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% - ${C}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${w||v?"bg-white":"bg-[rgba(255,255,255,0.3)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% + ${C}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${w||v?"bg-white":"bg-[rgba(255,255,255,0.3)]"}`})})]},x.name)})}),n("div",{className:"absolute inset-0 pointer-events-none",children:m.map((x,w)=>{const v=w*dn,C=x.width===e,k=(i==null?void 0:i.name)===x.name;return c("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`${v}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${C||k?"bg-white":"bg-[rgba(255,255,255,0.3)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{right:`${v}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${C||k?"bg-white":"bg-[rgba(255,255,255,0.3)]"}`})})]},x.name)})}),!o&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:c("div",{className:`text-[10px] px-2 py-0.5 rounded shadow-sm whitespace-nowrap transition-colors ${i?"bg-[#005c75] text-white":"bg-white/90 text-[#005c75] border border-[rgba(0,92,117,0.25)]"}`,children:[b.name," - ",b.width,"px"]})})]})}function Rs({width:e,height:t,onSave:r,onCancel:a}){const[s,o]=j(""),[i,l]=j(""),d=()=>{const u=s.trim();if(!u){l("Please enter a name for this custom size");return}r(u)};return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:c("div",{className:"bg-white rounded-lg max-w-md w-full p-6 shadow-xl",children:[c("div",{className:"flex items-center justify-between mb-6",children:[n("h2",{className:"text-xl font-semibold text-gray-900",children:"Save Custom Size"}),n("button",{onClick:a,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),c("div",{className:"mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-sm text-gray-500 mb-1",children:"Dimensions"}),c("div",{className:"text-lg font-medium text-gray-900",children:[e,"px × ",t,"px"]})]}),c("div",{className:"mb-6",children:[n("label",{htmlFor:"custom-size-name",className:"block text-sm font-medium text-gray-700 mb-2",children:"Name"}),n("input",{id:"custom-size-name",type:"text",value:s,onChange:u=>{o(u.target.value),l("")},onKeyDown:u=>{u.key==="Enter"&&s.trim()&&d(),u.key==="Escape"&&a()},placeholder:"e.g., iPhone 15 Pro",className:`w-full px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] ${i?"border-red-300":"border-gray-300"}`,autoFocus:!0}),i&&n("p",{className:"mt-1 text-sm text-red-600",children:i})]}),c("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:a,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-300 transition-colors 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 $s(e){const[t,r]=j([]),a=e?`codeyam-custom-sizes-${e}`:null;ne(()=>{if(!a||typeof window>"u"){r([]);return}try{const l=localStorage.getItem(a);if(l){const d=JSON.parse(l);Array.isArray(d)&&r(d)}}catch(l){console.error("[useCustomSizes] Failed to load custom sizes:",l),r([])}},[a]);const s=re(l=>{if(!(!a||typeof window>"u"))try{localStorage.setItem(a,JSON.stringify(l))}catch(d){console.error("[useCustomSizes] Failed to save custom sizes:",d)}},[a]),o=re((l,d,h)=>{r(u=>{const m=u.findIndex(g=>g.name===l),p={name:l,width:d,height:h};let f;return m>=0?(f=[...u],f[m]=p):f=[...u,p],s(f),f})},[s]),i=re(l=>{r(d=>{const h=d.filter(u=>u.name!==l);return s(h),h})},[s]);return{customSizes:t,addCustomSize:o,removeCustomSize:i}}async function $c({params:e}){var l;const{sha:t,scenarioId:r}=e;if(!t||!r)throw z("Invalid parameters",{status:400});const a=await At(t);if(!a)throw z("Entity not found",{status:404});const s=await Er(a),o=((l=s==null?void 0:s.scenarios)==null?void 0:l.find(d=>d.id===r))||null;if(!o)throw z("Scenario not found",{status:404});const i=await ze();return z({entity:a,scenario:o,analysis:s,projectSlug:i})}const Qn=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],Dc=We(function(){const{entity:t,scenario:r,analysis:a,projectSlug:s}=Ke(),o=It(),[i]=qt(),[l,d]=j(null),[h,u]=j(1440),[m,p]=j({name:"Desktop",width:1440,height:900}),[f,g]=j(!1),[y,b]=j(null),{customSizes:x,addCustomSize:w}=$s(s),v=se(()=>[...Qn,...x],[x]),{interactiveServerUrl:C,isStarting:k,isLoading:A,showIframe:P,iframeKey:M,onIframeLoad:I}=tn({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:N}=mt(s,k||A),$=()=>{o(`/entity/${t.sha}`)},_=(Y,V)=>{u(Y);const le=v.find(B=>B.width===Y&&B.height===V);d(le||null),p({name:(le==null?void 0:le.name)||"Custom",width:Y,height:V})},S=Y=>{d(Y),u(Y.width),p({name:Y.name,width:Y.width,height:Y.height})},E=Y=>{w(Y,m.width,m.height??900),g(!1),p(V=>({...V,name:Y}))},R=((a==null?void 0:a.scenarios)||[]).filter(Y=>{var V;return!((V=Y.metadata)!=null&&V.sameAsDefault)}),D=R.findIndex(Y=>Y.id===(r==null?void 0:r.id)),O=D+1,H=R.length,Q=D>0,q=D<R.length-1,L=()=>{if(Q){const Y=R[D-1],V=encodeURIComponent(`/entity/${t.sha}/scenarios/${Y.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${Y.id}/fullscreen?from=${V}`)}},T=()=>{if(q){const Y=R[D+1],V=encodeURIComponent(`/entity/${t.sha}/scenarios/${Y.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${Y.id}/fullscreen?from=${V}`)}},U=k||A||!P;return c("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[c("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:[c("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n("img",{src:es,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),c("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:L,disabled:!Q,className:`${Q?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),c("span",{className:"text-gray-400 text-sm",children:[O,"/",H]}),n("button",{onClick:T,disabled:!q,className:`${q?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Next scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M7.5 15L12.5 10L7.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),c("div",{className:"flex items-center gap-2 ml-2 min-w-0",children:[n("span",{className:"text-white font-semibold text-xs whitespace-nowrap shrink-0",children:r==null?void 0:r.name}),(r==null?void 0:r.description)&&c("div",{className:"relative group min-w-0",children:[n("span",{className:"text-gray-400 text-xs truncate block",children:r.description}),n("div",{className:"absolute left-0 top-full mt-1 hidden group-hover:block z-50 bg-black text-white text-xs px-3 py-2 rounded shadow-lg max-w-md",children:r.description})]})]})]}),n("button",{onClick:$,className:"text-white hover:text-gray-300 transition-colors ml-4","aria-label":"Close fullscreen",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M15 5L5 15M5 5L15 15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),c("div",{className:"bg-[#034456] border-b border-[rgba(0,92,117,0.25)] shrink-0 z-10 h-6 flex items-center justify-center relative",children:[n("div",{className:"absolute inset-0 flex justify-center",children:n("div",{style:{maxWidth:`${Qn[Qn.length-1].width}px`,width:"100%"},children:n(js,{currentViewportWidth:h,currentPresetName:m.name,onDevicePresetClick:S,devicePresets:v,hideLabel:!0,onHoverChange:b})})}),c("div",{className:"relative z-10 flex items-center gap-2",children:[c("div",{className:"relative w-28 h-5",children:[c("div",{className:"absolute inset-0 bg-[#007392] text-white text-xs px-2 rounded flex items-center justify-between pointer-events-none",children:[n("span",{className:"leading-none",children:(y==null?void 0:y.name)||m.name}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),c("select",{value:m.name,onChange:Y=>{const V=v.find(le=>le.name===Y.target.value);V&&S(V)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[v.map(Y=>n("option",{value:Y.name,children:Y.name},Y.name)),m.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:m.width,onChange:Y=>{const V=parseInt(Y.target.value,10);!isNaN(V)&&V>0&&_(V,m.height??900)},className:"bg-white text-gray-900 text-xs px-1 rounded border border-gray-300 outline-none w-16 text-center h-5 leading-none",min:"200",max:"3840"}),n("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"×"}),n("span",{className:"bg-gray-100 text-gray-600 text-xs px-1 rounded w-14 text-center h-5 flex items-center justify-center leading-none",children:m.height??900}),m.name==="Custom"&&n("button",{onClick:()=>g(!0),className:"bg-[#007392] text-white text-xs px-2 rounded h-5 flex items-center leading-none hover:bg-[#005c75] transition-colors",children:"Save"})]})]}),n("div",{className:"flex-1 flex items-center justify-center overflow-auto p-8",children:C?c("div",{className:"relative bg-white shadow-2xl w-full h-full",style:{maxWidth:`${m.width}px`,maxHeight:`${m.height}px`},children:[U&&n("div",{className:"absolute inset-0 flex items-center justify-center bg-white z-10",children:c("div",{className:"flex flex-col items-center gap-3",children:[n("div",{className:"w-12 h-12",children:n("svg",{className:"animate-spin",viewBox:"0 0 50 50",children:n("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"#005c75",strokeWidth:"4",strokeDasharray:"31.4 31.4",strokeLinecap:"round"})})}),n("p",{className:"text-base font-semibold text-[#005c75]",children:k&&!C?"Starting interactive mode...":"Loading interactive preview..."})]})}),n("iframe",{src:C,className:"w-full h-full border-none",title:`Interactive preview: ${r==null?void 0:r.name}`,onLoad:I,style:{opacity:P?1:0}},M)]}):c("div",{className:"flex flex-col items-center gap-6 max-w-2xl",children:[n("div",{className:"w-12 h-12",children:n("svg",{className:"animate-spin",viewBox:"0 0 50 50",children:n("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"#005c75",strokeWidth:"4",strokeDasharray:"31.4 31.4",strokeLinecap:"round"})})}),n("h2",{className:"text-2xl font-semibold text-white leading-[30px] m-0 font-['IBM_Plex_Sans']",children:A?"Interactive mode ready: launching...":"Starting Interactive Mode..."}),N&&n("p",{className:"text-xs font-mono text-gray-400 text-center leading-5 m-0 max-w-xl font-['IBM_Plex_Mono']",children:N}),n("p",{className:"text-xs text-gray-500 text-center leading-5 m-0 font-['IBM_Plex_Mono']",children:A?"Loading the page in the background...":"Setting up the dev server for this scenario..."})]})}),f&&n(Rs,{width:m.width,height:m.height??900,onSave:E,onCancel:()=>g(!1)})]})}),Lc=Object.freeze(Object.defineProperty({__proto__:null,default:Dc,loader:$c},Symbol.toStringTag,{value:"Module"})),Ds=mr({dimensions:{height:720,width:1200},updateDimensions:()=>{},iframeRef:{current:null},scale:1,updateScale:()=>{},maxWidth:1200,updateMaxWidth:()=>{}}),Mr=()=>{const e=kn(Ds);if(!e)throw new Error("useWebContainer must be used within a WebContainerProvider");return e},Dn=({children:e})=>{const[t,r]=j({height:720,width:1200}),[a,s]=j(1),[o,i]=j(1200),l=Pe(null),d=re(({height:m,width:p})=>{r(f=>({height:m??f.height,width:p??f.width}))},[]),h=re(m=>{s(m)},[]),u=re(m=>{i(m)},[]);return n(Ds.Provider,{value:{dimensions:t,updateDimensions:d,iframeRef:l,scale:a,updateScale:h,maxWidth:o,updateMaxWidth:u},children:e})},Oc=typeof window<"u";function Fc(){const[e,t]=j(null);return ne(()=>{import("react-resizable").then(r=>{t(()=>r.ResizableBox)}),Promise.resolve({ })},[]),e}const Yc=1200,zc=720,Na=30,Bc=({id:e,scenarioName:t,iframeUrl:r,defaultWidth:a=1440,defaultHeight:s=900,onDataOverride:o,onIframeLoad:i,onScaleChange:l,onDimensionChange:d})=>{const h=Fc(),[u,m]=j(!1),[p,f]=j(!1),[g,y]=j(Yc),[b,x]=j(zc),[w,v]=j(null),[C,k]=j(null),{dimensions:A,updateDimensions:P,iframeRef:M,updateScale:I,updateMaxWidth:N}=Mr(),$=se(()=>Math.min(1,g/A.width),[g,A.width]),_=C!==null?C:$;ne(()=>{u||(I(_),l==null||l(_))},[_,I,l,u]),ne(()=>{N(g)},[g,N]);const S=re(()=>{m(!0),k($)},[$]),E=re(()=>{m(!1),k(null)},[]),R=re((q,L)=>{const T=C!==null?C:1,U=Math.round(L.size.width/T);P({width:U}),d==null||d(U,A.height)},[P,C,d,A.height]),D=re(()=>{setTimeout(()=>{f(!0)},100),i&&i()},[i]);ne(()=>{const q=L=>{if(L.data.type==="codeyam-resize"){if(t&&L.data.name!==t||A.height===L.data.height||L.data.height===0)return;P({height:L.data.height})}};return window.addEventListener("message",q),()=>{window.removeEventListener("message",q)}},[M,t,a,A,P]),ne(()=>{p&&o&&o(M.current)},[p,o,M]),ne(()=>{if(!t)return;const q=setInterval(()=>{var L,T;(T=(L=M==null?void 0:M.current)==null?void 0:L.contentWindow)==null||T.postMessage({type:"codeyam-respond",name:t},"*")},1e3);return()=>clearInterval(q)},[t,M]),ne(()=>{const q=()=>{const L=document.getElementById("scenario-container");if(!L)return;const T=L.getBoundingClientRect(),U=L.clientWidth-Na*2,Y=window.innerHeight-T.top-Na*2,V=Math.max(Y,400),le=window.innerHeight-T.top;y(U),x(V),v(le)};return q(),window.addEventListener("resize",q),()=>window.removeEventListener("resize",q)},[]),ne(()=>{P({width:a,height:s})},[a,s,P]);const O=se(()=>A.width*_,[A.width,_]),H=se(()=>{const q=A.height,L=q*_;return q&&q!==720&&q!==900&&L<b?L:b},[A.height,b,_]),Q=re(()=>{window.history.back()},[]);return!Oc||!h?n("div",{className:"relative bg-gray-100 w-full h-full flex items-center justify-center",children:n("p",{className:"text-gray-500",children:"Loading interactive view..."})}):c("div",{id:"scenario-container",className:"relative bg-gray-100 w-full flex items-center justify-center",style:w?{height:`${w}px`}:{},children:[u&&n("div",{className:"fixed inset-0 z-50 bg-transparent"}),n("style",{children:`
39
+ .react-resizable-handle-e {
40
+ display: flex !important;
41
+ align-items: center !important;
42
+ justify-content: center !important;
43
+ width: 6px !important;
44
+ height: 48px !important;
45
+ right: -8px !important;
46
+ top: 50% !important;
47
+ transform: translateY(-50%) !important;
48
+ cursor: ew-resize !important;
49
+ background: #d1d5db !important;
50
+ border-radius: 3px !important;
51
+ opacity: 0 !important;
52
+ transition: all 0.2s ease !important;
53
+ }
54
+ .react-resizable-handle-e:hover {
55
+ opacity: 0.8 !important;
56
+ background: #9ca3af !important;
57
+ }
58
+ .react-resizable:hover .react-resizable-handle-e {
59
+ opacity: 0.4 !important;
60
+ }
61
+ `}),n(h,{width:O,height:H,minConstraints:[300,200],maxConstraints:[g,b],className:"relative bg-white rounded-lg shadow-md",resizeHandles:["e"],onResizeStart:S,onResizeStop:E,onResize:R,children:n("div",{className:"overflow-auto",style:{width:`${O}px`,height:`${H}px`},children:n("div",{style:{width:`${A.width}px`,height:`${A.height}px`,transform:`scale(${_})`,transformOrigin:"top left"},children:r?n("iframe",{ref:M,className:"w-full h-full rounded-lg",src:r,onLoad:D,sandbox:"allow-scripts allow-same-origin"}):c("p",{className:"w-full h-full flex flex-col gap-3 items-center justify-center",children:[n("span",{className:"text-xl font-light",children:"Oops! Looks like this scenario is not available yet. Please check back later."}),n("span",{className:"text-blue-600 cursor-pointer",onClick:Q,children:"Go back"})]})})})},`resizable-box-${e}`)]})};function Uc({presets:e,customSizes:t,currentWidth:r,currentHeight:a,scale:s,onSizeChange:o,onSaveCustomSize:i,onRemoveCustomSize:l,className:d=""}){const[h,u]=j(!1),[m,p]=j(String(r)),[f,g]=j(String(a)),[y,b]=j(!1),[x,w]=j(!1),v=Pe(null);ne(()=>{y||p(String(r))},[r,y]),ne(()=>{x||g(String(a))},[a,x]),ne(()=>{const _=S=>{v.current&&!v.current.contains(S.target)&&u(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[]);const C=se(()=>{const _=e.find(E=>E.width===r&&E.height===a);if(_)return _.name;const S=t.find(E=>E.width===r&&E.height===a);return S?S.name:"Custom"},[e,t,r,a]),k=C==="Custom",A=_=>{o(_.width,_.height),u(!1)},P=_=>{const S=_.target.value;p(S);const E=parseInt(S,10);!isNaN(E)&&E>0&&o(E,a)},M=_=>{const S=_.target.value;g(S);const E=parseInt(S,10);!isNaN(E)&&E>0&&o(r,E)},I=()=>{b(!1);const _=parseInt(m,10);(isNaN(_)||_<=0)&&p(String(r))},N=()=>{w(!1);const _=parseInt(f,10);(isNaN(_)||_<=0)&&g(String(a))},$=_=>{(_.key==="Enter"||_.key==="Escape")&&_.target.blur()};return c("div",{className:`flex items-center gap-3 ${d}`,children:[c("div",{className:"relative",ref:v,children:[c("button",{onClick:()=>u(!h),className:"flex items-center gap-2 px-3 py-1.5 bg-white border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 min-w-[120px] justify-between",children:[n("span",{children:C}),n("svg",{className:`w-4 h-4 transition-transform ${h?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),h&&n("div",{className:"absolute top-full left-0 mt-1 min-w-full bg-white border border-gray-200 rounded-md shadow-lg z-50",children:c("div",{className:"py-1",children:[e.length>0&&c(ue,{children:[n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Presets"}),e.map(_=>c("button",{onClick:()=>A(_),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===_.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[n("span",{children:_.name}),c("span",{className:"text-xs text-gray-500",children:[_.width," x ",_.height]})]},_.name))]}),t.length>0&&c(ue,{children:[n("div",{className:"border-t border-gray-100 my-1"}),n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Custom"}),[...t].sort((_,S)=>_.width-S.width).map(_=>c("div",{className:`flex items-center gap-1 hover:bg-gray-100 ${C===_.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[c("button",{onClick:()=>A(_),className:"flex-1 text-left px-3 py-2 text-sm flex justify-between items-center gap-4 whitespace-nowrap cursor-pointer",children:[n("span",{children:_.name}),c("span",{className:"text-xs text-gray-500",children:[_.width," x ",_.height]})]}),l&&n("button",{onClick:S=>{S.stopPropagation(),C===_.name&&e.length>0&&o(e[0].width,e[0].height),l(_.name)},className:"p-1.5 mr-1 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded cursor-pointer transition-colors",title:"Remove custom size",children:n("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]},_.name))]})]})})]}),c("div",{className:"flex items-center gap-1 text-sm",children:[c("div",{className:"flex items-center",children:[n("input",{type:"text",value:m,onChange:P,onFocus:()=>b(!0),onBlur:I,onKeyDown:$,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),n("span",{className:"text-gray-400 mx-1",children:"×"}),c("div",{className:"flex items-center",children:[n("input",{type:"text",value:f,onChange:M,onFocus:()=>w(!0),onBlur:N,onKeyDown:$,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),s!==void 0&&s<1&&c("span",{className:"text-xs text-gray-500 ml-1",children:["(",Math.round(s*100),"%)"]})]}),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 Zn(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 ir(e){return e&&(typeof e=="object"||Array.isArray(e))}function Wc(e){return Array.isArray(e)?e.length:void 0}function Hc(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=ir(t[s]),l=ir(t[o]);return i&&!l?1:!i&&l?-1:s.localeCompare(o)});if(typeof t=="object")return Object.keys(t).sort((s,o)=>s.localeCompare(o))}}function Vc({scenarioFormData:e,handleInputChange:t}){return c("div",{className:"p-3 flex flex-col gap-3",children:[c("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:"name",className:"text-sm font-medium text-gray-700",children:"Name"}),n("input",{type:"text",id:"name",placeholder:"Name",name:"name",value:e.name,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),c("div",{className:"grid w-full gap-1.5 pt-2",children:[n("label",{htmlFor:"description",className:"text-sm font-medium text-gray-700",children:"Description"}),n("textarea",{placeholder:"Type your message here.",id:"description",name:"description",value:e.description,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 min-h-[100px]"})]}),n("button",{type:"submit",className:"mt-3 w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium",children:"Save Name & Description"})]})}function Gc({path:e,namedPath:t,isArray:r,count:a,onClick:s}){const o=re(()=>{s&&s(e)},[s,e]);return c("div",{className:"bg-blue-50 p-3 rounded-lg flex items-center justify-between cursor-pointer group hover:bg-blue-100 transition-colors border border-blue-200",onClick:o,children:[c("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-4 h-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})}),c("div",{className:"capitalize font-medium text-gray-900",children:[t[t.length-1],a!==void 0&&` (${a})`]})]}),c("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-5 h-5 text-red-500 opacity-0 group-hover:opacity-100 transition-opacity",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),n("svg",{className:"w-4 h-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]})}var Ls=(e=>(e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.UNION="union",e.OBJECT="object",e.ARRAY="array",e))(Ls||{});const Jc=({name:e,value:t,options:r,onChange:a})=>{const s=re(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))})},qc=({name:e,value:t,onChange:r})=>{const a=re(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
62
+ bg-gray-300 checked:bg-blue-600
63
+ after:content-[''] after:absolute after:top-1 after:left-1 after:w-4 after:h-4
64
+ after:bg-white after:rounded-full after:transition-transform
65
+ checked:after:translate-x-4`})})};function Kc({dataType:e,path:t,value:r,onChange:a}){const s=se(()=>t[t.length-1],[t]),o=se(()=>t.join("-"),[t]),i=re(d=>{a(t,d.target.value)},[a,t]),l=re(d=>{a(t,d.target.value)},[a,t]);return c("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:o,className:"capitalize text-sm font-medium text-gray-700",children:s==="~~codeyam-code~~"?"Dynamic Field":s}),e.includes("|")?n(Jc,{name:o,value:r,options:e.split("|"),onChange:i}):e===Ls.BOOLEAN?n(qc,{name:o,value:r??!1,onChange:l}):n("input",{id:o,name:o,type:"text",value:JSON.stringify(r??"").replace(/"/g,""),onChange:i,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"},`Input-${o}`)]})}function Qc({analysis:e,scenarioName:t,dataItem:r,onResult:a,onGenerateData:s}){const[o,i]=j(!1),[l,d]=j(""),h=re(async()=>{if(!s){console.error("onGenerateData prop is required for AI data generation");return}i(!0);try{const m=e.scenarios.find(b=>b.name===t);if(!m)throw new Error("Scenario not found");const p=e.scenarios.find(b=>b.name===Tn),f=await s(l,r);if(!f){console.error("Error getting AI guess for scenario data"),i(!1);return}const g=(b,x)=>{const w=Object.assign({},b);return y(b)&&y(x)&&Object.keys(x).forEach(v=>{y(x[v])?v in b?w[v]=g(b[v],x[v]):Object.assign(w,{[v]:x[v]}):Object.assign(w,{[v]:x[v]})}),w},y=b=>b&&typeof b=="object"&&!Array.isArray(b);m.metadata.data=g(g((p==null?void 0:p.metadata.data)||{},m.metadata.data),f.data||{}),a(m),i(!1),d("")}catch(m){console.error("Error generating AI data:",m),i(!1)}},[e,l,r,t,a,s]),u=re(m=>{d(m.target.value)},[]);return c("div",{className:"w-full p-3 flex flex-col gap-2 rounded-lg border-2 border-blue-200 text-sm bg-blue-50",children:[n("div",{className:"font-medium text-gray-700",children:"Describe the data changes to the AI"}),n("textarea",{className:"peer w-full h-16 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"Type your message here.",onChange:u,value:l}),n("button",{type:"button",disabled:o,className:`w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-400 disabled:cursor-not-allowed font-medium ${l.length>0?"flex":"hidden peer-focus-within:flex"} items-center justify-center gap-2`,onClick:()=>void h(),children:o?c(ue,{children:[c("svg",{className:"animate-spin h-4 w-4 text-white",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Please wait"]}):"Generate Data"})]})}function Zc({namedPath:e,path:t,last:r,onClick:a}){const s=re(()=>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 Xc({dataItem:e,onClick:t}){const r=re(()=>t([]),[t]),a=se(()=>e.namedPath.length>=2?e.namedPath.length-2:0,[e]);return c("div",{className:"text-sm flex items-center gap-2 py-3 px-2 border-b border-t border-gray-300 bg-gray-50",children:[n("svg",{className:"w-4 h-4 cursor-pointer hover:text-blue-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",onClick:r,children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),e.namedPath.length>2&&c("div",{className:"flex items-center gap-1",children:[n("div",{children:"..."}),n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),e.namedPath.slice(a).map((s,o)=>c("div",{className:"flex items-center gap-1",children:[n(Zc,{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 Sa({analysis:e,scenarioName:t,dataItem:r,onClick:a,onChange:s,onAIResult:o,onGenerateData:i,saveFeedback:l}){const d=se(()=>r.data,[r]),h=se(()=>Hc(r),[r]);return c("div",{className:"w-full flex flex-col gap-6 px-3 mt-3",children:[r.path.length>0&&n(Xc,{dataItem:r,onClick:a}),c("div",{className:"flex flex-col gap-3",children:[n(Qc,{analysis:e,scenarioName:t,dataItem:r,onResult:o,onGenerateData:i}),h==null?void 0:h.map((u,m)=>{var f;if(ir(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],b=[...r.namedPath,g];return n(Gc,{path:y,namedPath:b,isArray:Array.isArray(d),count:Wc(d[u]),onClick:a},`data-${u}-${m}`)}if(u==="id")return null;const p=[...r.path,u];return n(Kc,{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"}),c("div",{className:"flex gap-2",children:[n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="false")},disabled:l==null?void 0:l.isSaving,className:"flex-1 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:l!=null&&l.isSaving?"Saving...":"Save Changes"}),n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="true")},disabled:l==null?void 0:l.isSaving,className:"flex-1 px-4 py-2 bg-gray-100 text-gray-700 border border-gray-300 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Save & Recapture"})]}),(l==null?void 0:l.message)&&!(l!=null&&l.isSaving)&&n("div",{className:`mt-3 p-3 rounded-md text-sm font-medium ${l.isError?"bg-red-50 text-red-700 border border-red-200":"bg-green-50 text-green-700 border border-green-200"}`,children:l.message})]})}function Aa({title:e,children:t,defaultOpen:r=!1,borderT:a=!1,borderB:s=!1}){const[o,i]=j(r),l=[];return a&&l.push("border-t"),s&&l.push("border-b"),c("div",{className:`${l.join(" ")} border-gray-300`,children:[c("button",{type:"button",onClick:()=>i(!o),className:"w-full px-4 py-3 flex items-center justify-between bg-gray-50 hover:bg-gray-100 transition-colors text-left font-semibold text-gray-900",children:[n("span",{children:e}),n("svg",{className:`transition-transform ${o?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",style:{width:"20px",height:"20px",minWidth:"20px",minHeight:"20px",maxWidth:"20px",maxHeight:"20px",flexShrink:0},children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),o&&n("div",{className:"px-4 py-3",children:t})]})}const ed=({currentScenario:e,defaultScenario:t,dataStructure:r,analysis:a,shouldCreateNewScenario:s,onSave:o,onNavigate:i,iframeRef:l,onGenerateData:d,saveFeedback:h})=>{const u=re((P,M)=>{const I=Object.assign({},P),N=$=>$&&typeof $=="object"&&!Array.isArray($);return N(P)&&N(M)&&Object.keys(M).forEach($=>{N(M[$])?$ in P?I[$]=u(P[$],M[$]):Object.assign(I,{[$]:M[$]}):Object.assign(I,{[$]:M[$]})}),I},[]),[m,p]=j({name:e.name,description:e.description,data:u(t.metadata.data,e.metadata.data)}),[f,g]=j(null),y=se(()=>({...m.data}),[m]),b=se(()=>({...y.mockData?{"Retrieved Data":y.mockData}:{},...y.argumentsData?{"Function Arguments":y.argumentsData}:{}}),[y]),x=se(()=>{const P={...r.arguments?{"Function Arguments":r.arguments}:{},...r.dataForMocks?{"Retrieved Data":r.dataForMocks}:{}};return Object.keys(P).reduce((M,I)=>{if(I.includes(".")){const[N,$]=I.split(".");M[N]||(M[N]={}),M[N][$]=P[I]}else M[I]=P[I];return M},{})},[r]),w=re(async P=>{P.preventDefault();const M=P.target.querySelector('input[name="recapture"]'),I=(M==null?void 0:M.value)==="true",N={mockData:m.data.mockData??{},argumentsData:m.data.argumentsData??[]};console.log("[ScenarioEditor] Saving scenario data:",{scenarioName:m.name,shouldRecapture:I,dataToSave:N,rawFormData:m.data,iframePayload:{arguments:y.argumentsData??[],...y.mockData??{}}}),console.log("[ScenarioEditor] Full dataToSave JSON:",JSON.stringify(N,null,2).substring(0,1e3));const $=a==null?void 0:a.scenarios.map(_=>!s&&_.name===e.name?{..._,name:m.name,description:m.description,metadata:{..._.metadata,data:N}}:_);s&&$.push({name:m.name,description:m.description,metadata:{data:N,interactiveExamplePath:a==null?void 0:a.scenarios[0].metadata.interactiveExamplePath}}),console.log("[ScenarioEditor] Updated scenarios to save:",$),o&&await o($,{recapture:I}),i&&i(m.name)},[a,e.name,m,y,s,o,i]),v=re(P=>{p(M=>({...M,[P.target.name]:P.target.value}))},[]),C=re(P=>{g(M=>{if(!M)return null;for(const I of[{arguments:P.metadata.data.argumentsData},P.metadata.data.mockData]){let N=I;for(const $ of M.path)if(N=Zn(N,$),!N)break;N&&(M.data=N)}return{...M}}),p({name:P.name,description:P.description,data:P.metadata.data})},[]),k=re((P,M)=>{p(I=>{for(const N of[{"Function Arguments":I.data.argumentsData},{"Retrieved Data":I.data.mockData}]){let $=N;for(const _ of P.slice(0,-1))if($=Zn($,_),!$)break;if($){const _=$[P[P.length-1]];g(S=>S?(S.namedPath[S.namedPath.length-1]===_&&(S.namedPath[S.namedPath.length-1]=M.toString()),S.data[P[P.length-1]]=M,{...S}):null),$[P[P.length-1]]=M}}return{...I}})},[]),A=re(P=>{var $,_,S;if(P.length===0){g(null);return}let M=b;const I=[];let N=x;for(const E of P){if(I.push(isNaN(parseInt(E))?E:(($=M[E])==null?void 0:$.name)??((_=M[E])==null?void 0:_.title)??((S=M[E])==null?void 0:S.id)??E),M=Zn(M,E),!M){console.log("Data not found",M,E),g(null);return}Array.isArray(N)?N=N[0]:N=N[E]}g({path:P,namedPath:I,data:M,structure:N})},[b,x]);return ne(()=>{const P=M=>{var I;M.data.type==="codeyam-log"&&((I=M.data.data)!=null&&I.includes("Error"))&&console.error("[ScenarioEditor] Error from iframe:",M.data.data)};return window.addEventListener("message",P),()=>window.removeEventListener("message",P)},[]),ne(()=>{var P;if((P=l==null?void 0:l.current)!=null&&P.contentWindow){const M={arguments:y.argumentsData??[],...y.mockData??{}},I={type:"codeyam-override-data",name:e.name,data:JSON.stringify(M)};console.log("[ScenarioEditor] → SENDING codeyam-override-data:",{type:I.type,name:I.name,dataPreview:JSON.stringify(M).substring(0,200)+"...",fullData:M}),l.current.contentWindow.postMessage(I,"*")}},[y,e,l]),n("form",{method:"post",onSubmit:P=>void w(P),children:f?n(Sa,{analysis:a,scenarioName:m.name,dataItem:f,onClick:A,onChange:k,onAIResult:C,onGenerateData:d,saveFeedback:h}):c(ue,{children:[n(Aa,{title:"Edit Name and Description",borderT:!0,children:n(Vc,{scenarioFormData:m,handleInputChange:v})}),e.metadata.data&&n(Aa,{title:"Edit Scenario Data",defaultOpen:!0,borderT:!0,borderB:!0,children:n(Sa,{analysis:a,scenarioName:m.name,dataItem:{path:[],namedPath:[],data:b,structure:x},onClick:A,onChange:k,onAIResult:C,onGenerateData:d,saveFeedback:h})})]})})};function Ln({scenarioId:e,scenarioName:t,iframeUrl:r,isStarting:a,isLoading:s,showIframe:o,iframeKey:i,onIframeLoad:l,onScaleChange:d,onDimensionChange:h,projectSlug:u,defaultWidth:m=1440,defaultHeight:p=900,retryCount:f=0}){const{lastLine:g}=mt(u??null,a||s);return r?c("div",{className:"flex-1 min-h-0 relative",children:[n("div",{style:{opacity:o?1:0},children:n(Bc,{id:e,scenarioName:t,iframeUrl:r,defaultWidth:m,defaultHeight:p,onIframeLoad:l,onScaleChange:d,onDimensionChange:h},i)}),!o&&(a||s)&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:c("div",{className:"flex flex-col items-center gap-3",children:[n("div",{className:"w-12 h-12",children:n("svg",{className:"animate-spin",viewBox:"0 0 50 50",children:n("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"#005c75",strokeWidth:"4",strokeDasharray:"31.4 31.4",strokeLinecap:"round"})})}),c("div",{className:"text-center",children:[n("p",{className:"text-base font-semibold text-[#005c75] mb-1",children:a&&!r?"Starting interactive mode...":`Checking server stability. Attempt #${f+1}..`}),g&&!r&&n("p",{className:"text-xs font-mono text-[#666] leading-relaxed",children:g}),r&&f>0&&c("p",{className:"text-xs font-mono text-[#666] leading-relaxed",children:["Waiting for application to initialize... (attempt"," ",f+1,")"]})]})]})})]}):n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center bg-[#f6f9fc]",children:c("div",{className:"flex flex-col items-center gap-6 max-w-2xl",children:[n("div",{className:"w-12 h-12 mb-2",children:n("svg",{className:"animate-spin",viewBox:"0 0 50 50",children:n("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"#005c75",strokeWidth:"4",strokeDasharray:"31.4 31.4",strokeLinecap:"round"})})}),n("h2",{className:"text-2xl font-semibold text-[#005c75] leading-[30px] m-0 font-['IBM_Plex_Sans']",children:s?"Interactive mode ready: launching...":"Starting Interactive Mode..."}),g&&n("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl font-['IBM_Plex_Mono']",children:g}),n("p",{className:"text-xs text-[#8e8e8e] text-center leading-5 m-0 font-['IBM_Plex_Mono']",children:s?"Loading the page in the background...":"Setting up the dev server for this scenario..."})]})})}const td=({data:e})=>[{title:e!=null&&e.scenario?`Edit ${e.scenario.name} - CodeYam`:"Edit Scenario - CodeYam"},{name:"description",content:"Edit scenario data"}];async function nd({params:e}){var d,h;const{sha:t,scenarioId:r}=e;if(!t)throw new Response("Entity SHA is required",{status:400});if(!r)throw new Response("Scenario ID is required",{status:400});const a=await In(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=(h=s.scenarios)==null?void 0:h.find(u=>u.name===Tn),l=await ze();return z({analysis:s,scenario:o,defaultScenario:i||o,entitySha:t,projectSlug:l})}function rd(){var E,R,D;const e=Ke(),t=e.analysis,r=e.scenario,a=e.defaultScenario,s=e.entitySha,o=e.projectSlug,i=It(),{iframeRef:l}=Mr(),[d,h]=j(!1),[u,m]=j(null),[p,f]=j(null),[g,y]=j(!1),[b,x]=j(!1),[w,v]=j(null),{interactiveServerUrl:C,isStarting:k,isLoading:A,showIframe:P,iframeKey:M,onIframeLoad:I}=tn({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}),N=re(async(O,H)=>{h(!0),m(null),f(null),console.log("[EditScenario] Starting save with options:",H),console.log("[EditScenario] Scenarios to save:",O);try{const Q={analysis:t,scenarios:O};console.log("[EditScenario] Sending to /api/save-scenarios:",{analysisId:t.id,scenarioCount:O.length,scenarioNames:O.map(T=>T.name)});const q=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Q)}),L=await q.json();if(console.log("[EditScenario] API response:",L),!q.ok||!L.success)throw new Error(L.error||"Failed to save scenarios");if(console.log("[EditScenario] Scenarios saved successfully"),H!=null&&H.recapture&&r.id&&C){console.log("[EditScenario] ========== DIRECT CAPTURE START =========="),console.log("[EditScenario] Taking screenshot from running server",{scenarioId:r.id,projectId:t.projectId,serverUrl:C}),m("Changes saved. Capturing screenshot...");const T={serverUrl:C,scenarioId:r.id,projectId:t.projectId,viewportWidth:1440};console.log("[EditScenario] Capture request body:",T);const U=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(T)});console.log("[EditScenario] Capture response status:",U.status);const Y=await U.json();if(console.log("[EditScenario] Capture response body:",Y),!U.ok||!Y.success)throw console.error("[EditScenario] Capture failed:",Y),new Error(Y.error||"Failed to capture screenshot");console.log("[EditScenario] Screenshot captured successfully:",Y),console.log("[EditScenario] ========== DIRECT CAPTURE COMPLETE =========="),m("Recapture successful")}else if(H!=null&&H.recapture&&!C){console.log("[EditScenario] No running server, using queued recapture");const T=new FormData;T.append("analysisId",t.id||""),T.append("scenarioId",r.id||"");const U=await fetch("/api/recapture-scenario",{method:"POST",body:T}),Y=await U.json();if(!U.ok||!Y.success)throw new Error(Y.error||"Failed to trigger recapture");console.log("Recapture queued:",Y),f(Y.jobId),m("Changes saved. Screenshot recapture queued.")}else m("Changes saved successfully.")}catch(Q){console.error("Error saving scenarios:",Q),m(`Error: ${Q instanceof Error?Q.message:String(Q)}`)}finally{h(!1)}},[t,r.id,C]),$=re(O=>{},[]),_=re(async(O,H)=>{var L;const Q=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:O,existingScenarios:t.scenarios,scenariosDataStructure:(L=t.metadata)==null?void 0:L.scenariosDataStructure,editingMockName:r.name,editingMockData:H==null?void 0:H.data})}),q=await Q.json();if(!Q.ok||!q.success)throw new Error(q.error||"Failed to generate scenario data");return q.data},[t,r.name]),S=re(async()=>{var O;if(!r.id){v("Cannot delete scenario without ID");return}y(!0),v(null);try{const H=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:r.id,screenshotPaths:((O=r.metadata)==null?void 0:O.screenshotPaths)||[]})}),Q=await H.json();if(!H.ok||!Q.success)throw new Error(Q.error||"Failed to delete scenario");i(`/entity/${s}`)}catch(H){console.error("[EditScenario] Error deleting scenario:",H),v(H instanceof Error?H.message:"Failed to delete scenario"),x(!1)}finally{y(!1)}},[r.id,(E=r.metadata)==null?void 0:E.screenshotPaths,s,i]);return c("div",{className:"h-screen bg-gray-50 flex flex-col",children:[c("header",{className:"bg-white border-b border-gray-200 px-8 py-6 shrink-0",children:[n("div",{className:"mb-4",children:c(oe,{to:`/entity/${s}`,className:"text-blue-600 no-underline text-sm font-medium transition-colors hover:text-blue-700 hover:underline",children:["← Back to ",(R=t.entity)==null?void 0:R.name]})}),c("h1",{className:"text-[32px] font-bold text-gray-900 m-0 mb-3",children:["Edit Scenario: ",r.name]}),r.description&&n("p",{className:"text-gray-600 text-[15px] leading-relaxed m-0",children:r.description})]}),c("div",{className:"flex flex-1 gap-0 min-h-0",children:[c("aside",{className:"w-[400px] bg-white border-r border-gray-200 overflow-y-auto shrink-0",children:[n(ed,{currentScenario:r,defaultScenario:a,dataStructure:((D=t.metadata)==null?void 0:D.scenariosDataStructure)||{},analysis:t,shouldCreateNewScenario:!1,onSave:N,onNavigate:$,iframeRef:l,onGenerateData:_,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(oe,{to:`/entity/${s}`,className:"text-blue-600 hover:text-blue-700 hover:underline text-sm",children:"View updated screenshot on entity page →"})}),c("div",{className:"border-t border-gray-200 p-4 mt-4",children:[n("div",{className:"text-sm text-gray-600 mb-3",children:"Permanently remove this scenario and its screenshots."}),b?c("div",{className:"space-y-3",children:[c("div",{className:"text-sm text-red-600 font-medium",children:['Are you sure you want to delete "',r.name,'"?']}),c("div",{className:"flex gap-2",children:[n("button",{onClick:()=>void S(),disabled:g,className:"flex-1 px-4 py-2 bg-red-600 text-white rounded-md text-sm font-medium hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors",children:g?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>x(!1),disabled:g,className:"flex-1 px-4 py-2 bg-gray-100 text-gray-700 border border-gray-300 rounded-md text-sm font-medium hover:bg-gray-200 disabled:opacity-50 transition-colors",children:"Cancel"})]})]}):n("button",{onClick:()=>x(!0),className:"w-full px-4 py-2 bg-red-50 text-red-600 border border-red-200 rounded-md text-sm font-medium hover:bg-red-100 transition-colors",children:"Delete Scenario"}),w&&n("div",{className:"mt-3 text-sm text-red-600 bg-red-50 px-3 py-2 rounded-md",children:w})]})]}),n("main",{className:"flex-1 bg-gray-100 overflow-auto flex flex-col min-w-0",children:n(Ln,{scenarioId:r.id||r.name,scenarioName:r.name,iframeUrl:C,isStarting:k,isLoading:A,showIframe:P,iframeKey:M,onIframeLoad:I,projectSlug:o,defaultWidth:1440,defaultHeight:900})})]})]})}const ad=We(function(){return n(Dn,{children:n(rd,{})})}),sd=Object.freeze(Object.defineProperty({__proto__:null,default:ad,loader:nd,meta:td},Symbol.toStringTag,{value:"Module"}));function od(e,t=50){if(e===null)return"null";if(e===void 0)return"undefined";let r;if(typeof e=="object")try{r=JSON.stringify(e)}catch{r="[complex object]"}else r=String(e);return r.length>t?r.slice(0,t)+"...":r}function id({keyAttributes:e,selections:t,onChange:r,disabled:a=!1}){const[s,o]=j({}),i=re(m=>t.some(p=>p.path===m),[t]),l=re(m=>t.find(p=>p.path===m),[t]),d=re(m=>{if(i(m.path))r(t.filter(p=>p.path!==m.path));else{const f=m.validValues.find(g=>g.usedInScenarios.length===0)||m.validValues[0];r(f?[...t,{path:m.path,value:f.value,valueOptionIndex:f.index,isCustom:!1}]:[...t,{path:m.path,value:"",isCustom:!0}])}},[t,r,i]),h=re((m,p)=>{const f=e.find(y=>y.path===m);if(!f)return;const g=t.map(y=>{if(y.path!==m)return y;if(p==="custom")return{...y,value:s[m]||"",valueOptionIndex:void 0,isCustom:!0};const b=parseInt(p,10),x=f.validValues[b];return x?{...y,value:x.value,valueOptionIndex:b,isCustom:!1}:y});r(g)},[t,r,e,s]),u=re((m,p)=>{o(g=>({...g,[m]:p}));const f=t.map(g=>g.path!==m||!g.isCustom?g:{...g,value:p});r(f)},[t,r]);return e.length===0?n("div",{className:"text-sm text-gray-500 py-2",children:"No key attributes found."}):n("div",{className:"space-y-3",children:e.map(m=>{const p=i(m.path),f=l(m.path),g=m.validValues.filter(y=>y.usedInScenarios.length===0).length;return c("div",{className:"border-b border-gray-100 pb-3 last:border-0 last:pb-0",children:[c("label",{className:"flex items-start gap-2 cursor-pointer",children:[n("input",{type:"checkbox",checked:p,onChange:()=>d(m),disabled:a,className:"mt-0.5 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-mono text-sm font-medium text-gray-900",children:m.localVariable}),g>0&&c("span",{className:"text-xs px-1.5 py-0.5 bg-amber-100 text-amber-700 rounded",children:[g," uncovered"]})]}),m.description&&n("p",{className:"text-xs text-gray-500 mt-0.5 m-0",children:m.description})]})]}),p&&c("div",{className:"ml-6 mt-2",children:[c("select",{value:f!=null&&f.isCustom?"custom":String((f==null?void 0:f.valueOptionIndex)??0),onChange:y=>h(m.path,y.target.value),disabled:a,className:"w-full text-sm border border-gray-300 rounded px-2 py-1.5 focus:border-blue-400 focus:outline-none focus:ring-1 focus:ring-blue-400",children:[m.validValues.map((y,b)=>{const x=y.usedInScenarios.length>0;return c("option",{value:b,children:[od(y.value),!x&&" (uncovered)"]},b)}),n("option",{value:"custom",children:"Custom value..."})]}),(f==null?void 0:f.isCustom)&&n("input",{type:"text",placeholder:"Enter custom value",value:s[m.path]||(f==null?void 0:f.value)||"",onChange:y=>u(m.path,y.target.value),disabled:a,className:"w-full mt-2 text-sm border border-gray-300 rounded px-2 py-1.5 focus:border-blue-400 focus:outline-none focus:ring-1 focus:ring-blue-400"}),m.dependencies&&m.dependencies.length>0&&c("div",{className:"mt-2 p-2 bg-amber-50 rounded text-xs",children:[n("span",{className:"text-amber-700 font-medium",children:"Requires:"}),n("ul",{className:"m-0 mt-1 pl-4 space-y-0.5",children:m.dependencies.map((y,b)=>c("li",{className:"text-amber-600",children:[n("code",{className:"bg-amber-100 px-1 rounded",children:y.path})," = ",n("code",{className:"bg-amber-100 px-1 rounded",children:String(y.requiredValue)})]},b))})]})]})]},m.path)})})}function Os(e,t){const r=(e||[]).map(h=>({path:h.dataStructurePath||h.externalPath||h.internalPath,localVariable:h.internalPath,description:h.description,valueType:h.valueType,validValues:(h.validValueOptions||[]).map((u,m)=>({index:m,value:u,usedInScenarios:[]})),errorValues:(h.errorValueOptions||[]).map((u,m)=>({index:m,value:u,usedInScenarios:[]})),sourceLocations:h.sourceLocations,dependencies:h.dependencies})),a=new Map;r.forEach(h=>{a.set(h.path,h)});const s=[],o=[];t.forEach(h=>{var u;if(el(h)){const m=[],p=((u=h.metadata)==null?void 0:u.keyAttributeInstructions)||{};Object.entries(p).forEach(([f,g])=>{if(Xi(g)){const y=a.get(f);if(!y)return;if(g.valueOptionRef){const b=g.valueOptionRef,x=y.validValues[b.index];x&&(x.usedInScenarios.push({id:h.id||"",name:h.name,refType:b.refType}),m.push({path:f,valueIndex:b.index,value:x.value,isError:!1,refType:b.refType}))}if(g.errorOptionRef){const b=g.errorOptionRef,x=y.errorValues[b.index];x&&(x.usedInScenarios.push({id:h.id||"",name:h.name,refType:b.refType}),m.push({path:f,valueIndex:b.index,value:x.value,isError:!0,refType:b.refType}))}}}),s.push({scenario:h,usedAttributes:m})}else o.push(h)});let i=0,l=0;r.forEach(h=>{i+=h.validValues.length,l+=h.validValues.filter(u=>u.usedInScenarios.length>0).length});const d=i>0?l/i*100:0;return{keyAttributes:r,scenariosWithStructuredRefs:s,scenariosWithoutStructuredRefs:o,totalValidValues:i,usedValidValues:l,coveragePercentage:d}}function ld(e){const t=[];return e.keyAttributes.forEach(r=>{r.validValues.forEach(a=>{a.usedInScenarios.length===0&&t.push({path:r.path,index:a.index,value:a.value})})}),t}const cd=({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 dd({params:e}){var i;const{sha:t}=e;if(!t)throw new Response("Entity SHA is required",{status:400});const r=await In(t,!0),a=r&&r.length>0?r[0]:null;if(!a)throw new Response("Analysis not found",{status:404});const s=(i=a.scenarios)==null?void 0:i.find(l=>l.name===Tn);if(!s)throw new Response("Default scenario not found",{status:404});const o=await ze();return z({analysis:a,defaultScenario:s,entity:a.entity,entitySha:t,projectSlug:o})}function ud(){const{analysis:e,defaultScenario:t,entity:r,entitySha:a,projectSlug:s}=Ke(),o=It(),{iframeRef:i}=Mr(),[l,d]=j(""),[h,u]=j(!1),[m,p]=j(!1),[f,g]=j(null),[y,b]=j(null),[x,w]=j([]),v=se(()=>{var S;return!((S=e==null?void 0:e.metadata)!=null&&S.keyAttributes)||!(e!=null&&e.scenarios)?[]:Os(e.metadata.keyAttributes,e.scenarios).keyAttributes},[e]),{interactiveServerUrl:C,isStarting:k,isLoading:A,showIframe:P,iframeKey:M,onIframeLoad:I}=tn({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}),N=re(async()=>{var _,S,E,R;if(!l.trim()&&x.length===0){g("Please describe how you want to change the scenario or select key attributes");return}u(!0),g(null),b("Generating scenario with AI...");try{const D=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:l,existingScenarios:e.scenarios,scenariosDataStructure:(_=e.metadata)==null?void 0:_.scenariosDataStructure,keyAttributeSelections:x.length>0?x:void 0})}),O=await D.json();if(!D.ok||!O.success)throw new Error(O.error||"Failed to generate scenario data");console.log("[CreateScenario] AI generated scenario:",O.data);const H=O.data;if(!H.name||!H.data)throw new Error("AI response missing required fields (name or data)");b("Saving new scenario..."),p(!0);const Q={name:H.name,description:H.description||l,metadata:{data:H.data,interactiveExamplePath:(S=t.metadata)==null?void 0:S.interactiveExamplePath}},q=[...e.scenarios||[],Q],L=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:e,scenarios:q})}),T=await L.json();if(!L.ok||!T.success)throw new Error(T.error||"Failed to save scenario");console.log("[CreateScenario] Scenario saved:",T);const U=(R=(E=T.analysis)==null?void 0:E.scenarios)==null?void 0:R.find(Y=>Y.name===H.name);if(!(U!=null&&U.id)){console.warn("[CreateScenario] Could not find saved scenario ID, navigating to entity page"),b("Scenario created! Redirecting..."),setTimeout(()=>void o(`/entity/${a}`),1e3);return}if(C){b("Capturing screenshot...");const Y=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:C,scenarioId:U.id,projectId:e.projectId,viewportWidth:1440})}),V=await Y.json();!Y.ok||!V.success?(console.error("[CreateScenario] Capture failed:",V),b("Scenario created! (Screenshot capture failed)")):b("Scenario created and captured!")}else b("Scenario created!");setTimeout(()=>{o(`/entity/${a}/scenarios/${U.id}`)},1e3)}catch(D){console.error("[CreateScenario] Error:",D),g(D instanceof Error?D.message:String(D)),b(null)}finally{u(!1),p(!1)}},[l,x,e,t,a,C,o]),$=h||m;return c("div",{className:"h-screen bg-gray-50 flex flex-col",children:[c("header",{className:"bg-white border-b border-gray-200 px-8 py-6 shrink-0",children:[n("div",{className:"mb-4",children:c(oe,{to:`/entity/${a}`,className:"text-blue-600 no-underline text-sm font-medium transition-colors hover:text-blue-700 hover:underline",children:["← Back to ",r==null?void 0:r.name]})}),n("h1",{className:"text-[32px] font-bold text-gray-900 m-0 mb-3",children:"Create New Scenario"}),n("p",{className:"text-gray-600 text-[15px] leading-relaxed m-0",children:"Create a new scenario based on the Default Scenario"})]}),c("div",{className:"flex flex-1 gap-0 min-h-0",children:[c("aside",{className:"w-[400px] bg-white border-r border-gray-200 overflow-y-auto shrink-0 p-6 flex flex-col",children:[c("div",{className:"mb-6",children:[n("h2",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Default Scenario Preview"}),n("p",{className:"text-sm text-gray-600 leading-relaxed",children:"The preview on the right shows the Default Scenario. Select key attributes and/or describe how you'd like to change it."})]}),v.length>0&&c("details",{className:"mb-4 border border-gray-200 rounded-lg",children:[c("summary",{className:"px-3 py-2 text-sm font-medium text-gray-700 cursor-pointer hover:bg-gray-50 rounded-lg",children:["Select Key Attributes"," ",x.length>0&&c("span",{className:"text-blue-600",children:["(",x.length," selected)"]})]}),n("div",{className:"px-3 pb-3 pt-1 border-t border-gray-100",children:n(id,{keyAttributes:v,selections:x,onChange:w,disabled:$})})]}),c("div",{className:"flex-1",children:[n("label",{htmlFor:"prompt",className:"block text-sm font-medium text-gray-700 mb-2",children:"How would you like to change it for your new scenario?"}),n("textarea",{id:"prompt",value:l,onChange:_=>d(_.target.value),placeholder:"e.g., Show an empty state with no items in the list, or Display an error message when the API fails, or Show a user with admin privileges...",className:"w-full h-40 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 text-sm resize-none",disabled:$})]}),c("div",{className:"mt-6 space-y-3",children:[n("button",{onClick:()=>void N(),disabled:$||!l.trim()&&x.length===0,className:"w-full px-4 py-2 bg-[#005c75] text-white rounded-md text-sm font-medium hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors",children:$?"Creating...":"Create Scenario"}),y&&n("div",{className:"text-sm text-blue-600 bg-blue-50 px-3 py-2 rounded-md",children:y}),f&&n("div",{className:"text-sm text-red-600 bg-red-50 px-3 py-2 rounded-md",children:f})]})]}),n("main",{className:"flex-1 bg-gray-100 overflow-auto flex flex-col min-w-0",children:n(Ln,{scenarioId:t.id||t.name,scenarioName:t.name,iframeUrl:C,isStarting:k,isLoading:A,showIframe:P,iframeKey:M,onIframeLoad:I,projectSlug:s,defaultWidth:1440,defaultHeight:900})})]})]})}const hd=We(function(){return n(Dn,{children:n(ud,{})})}),md=Object.freeze(Object.defineProperty({__proto__:null,default:hd,loader:dd,meta:cd},Symbol.toStringTag,{value:"Module"}));var ae;(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={}))})(ae||(ae={}));function Fs(e,t){return e?Object.values(ae.Model).includes(e)?e:(console.warn(`Invalid model in environment variable: ${e}. Falling back to ${t}`),t):t}const Ys=Fs(process.env.DEFAULT_SMALLER_MODEL,ae.Model.OPENAI_GPT4_1_MINI),pd=Fs(process.env.DEFAULT_LARGER_MODEL,ae.Model.OPENAI_GPT4_1),et={name:"OpenAI",baseURL:"https://api.openai.com/v1",apiKeyEnvVar:"OPENAI_API_KEY"},Xn={name:"OpenRouter",baseURL:"https://openrouter.ai/api/v1",apiKeyEnvVar:"OPENROUTER_API_KEY"},fd={name:"Groq",baseURL:"https://api.groq.com/openai/v1",apiKeyEnvVar:"GROQ_API_KEY"},er={name:"Anthropic",baseURL:"https://api.anthropic.com/v1/",apiKeyEnvVar:"ANTHROPIC_API_KEY"},ct={name:"DeepInfra",baseURL:"https://api.deepinfra.com/v1/",apiKeyEnvVar:"DEEPINFRA_API_KEY"},gd={[ae.Model.OPENAI_GPT5_1]:{id:ae.Model.OPENAI_GPT5_1,provider:et,apiModelName:"gpt-5.1",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"none"},[ae.Model.OPENAI_GPT5]:{id:ae.Model.OPENAI_GPT5,provider:et,apiModelName:"gpt-5",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"minimal"},[ae.Model.OPENAI_GPT5_MINI]:{id:ae.Model.OPENAI_GPT5_MINI,provider:et,apiModelName:"gpt-5-mini",maxCompletionTokens:128e3,pricing:{input:.25,output:2},reasoningEffort:"minimal"},[ae.Model.OPENAI_GPT5_NANO]:{id:ae.Model.OPENAI_GPT5_NANO,provider:et,apiModelName:"gpt-5-nano",maxCompletionTokens:128e3,pricing:{input:.05,output:.4},reasoningEffort:"minimal"},[ae.Model.OPENAI_GPT4_1]:{id:ae.Model.OPENAI_GPT4_1,provider:et,apiModelName:"gpt-4.1",maxCompletionTokens:32768,pricing:{input:2,output:8}},[ae.Model.OPENAI_GPT4_1_MINI]:{id:ae.Model.OPENAI_GPT4_1_MINI,provider:et,apiModelName:"gpt-4.1-mini",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[ae.Model.OPENAI_GPT4_O]:{id:ae.Model.OPENAI_GPT4_O,provider:et,apiModelName:"gpt-4o",maxCompletionTokens:16384,pricing:{input:2.5,output:10}},[ae.Model.OPENAI_GPT4_O_MINI]:{id:ae.Model.OPENAI_GPT4_O_MINI,provider:et,apiModelName:"gpt-4o-mini",maxCompletionTokens:16384,pricing:{input:.15,output:.6}},[ae.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER]:{id:ae.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER,provider:Xn,apiModelName:"google/gemini-2.5-flash-lite",maxCompletionTokens:1048576,pricing:{input:.1,output:.4},reasoningEffort:"minimal"},[ae.Model.META_LLAMA_4_MAVERICK_OPENROUTER]:{id:ae.Model.META_LLAMA_4_MAVERICK_OPENROUTER,provider:Xn,apiModelName:"meta-llama/llama-4-maverick",maxCompletionTokens:1048576,pricing:{input:.15,output:.6},reasoningEffort:"minimal"},[ae.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER]:{id:ae.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER,provider:Xn,apiModelName:"deepseek/deepseek-v3.1-terminus",maxCompletionTokens:163840,pricing:{input:.23,output:.9},reasoningEffort:"minimal"},[ae.Model.OPENAI_GPT_OSS_120B_GROQ]:{id:ae.Model.OPENAI_GPT_OSS_120B_GROQ,provider:fd,apiModelName:"openai/gpt-oss-120b",maxCompletionTokens:131072,pricing:{input:.15,output:.75},reasoningEffort:"low"},[ae.Model.OPENAI_GPT_OSS_120B_DEEPINFRA]:{id:ae.Model.OPENAI_GPT_OSS_120B_DEEPINFRA,provider:ct,apiModelName:"openai/gpt-oss-120b-Turbo",maxCompletionTokens:32768,pricing:{input:.15,output:.6},reasoningEffort:"low"},[ae.Model.QWEN3_235B_INSTRUCT_DEEPINFRA]:{id:ae.Model.QWEN3_235B_INSTRUCT_DEEPINFRA,provider:ct,apiModelName:"Qwen/Qwen3-235B-A22B-Instruct-2507",maxCompletionTokens:32768,pricing:{input:.09,output:.57}},[ae.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA]:{id:ae.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA,provider:ct,apiModelName:"Qwen/Qwen3-Coder-480B-A35B-Instruct",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[ae.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA]:{id:ae.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA,provider:ct,apiModelName:"google/gemini-2.5-pro",maxCompletionTokens:1048576,pricing:{input:1.25,output:10},reasoningEffort:"low"},[ae.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA]:{id:ae.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA,provider:ct,apiModelName:"google/gemini-2.5-flash",maxCompletionTokens:1048576,pricing:{input:.3,output:2.5},reasoningEffort:"low"},[ae.Model.ANTHROPIC_CLAUDE_4_5_HAIKU]:{id:ae.Model.ANTHROPIC_CLAUDE_4_5_HAIKU,provider:er,apiModelName:"claude-haiku-4-5",maxCompletionTokens:2e5,pricing:{input:1,output:5}},[ae.Model.ANTHROPIC_CLAUDE_4_5_SONNET]:{id:ae.Model.ANTHROPIC_CLAUDE_4_5_SONNET,provider:er,apiModelName:"claude-sonnet-4-5",maxCompletionTokens:2e5,pricing:{input:3,output:15}},[ae.Model.ANTHROPIC_CLAUDE_4_5_OPUS]:{id:ae.Model.ANTHROPIC_CLAUDE_4_5_OPUS,provider:er,apiModelName:"claude-opus-4-5",maxCompletionTokens:2e5,pricing:{input:5,output:25}},[ae.Model.PHIND_CODELLAMA]:{id:ae.Model.PHIND_CODELLAMA,provider:et,apiModelName:"phind-codellama",maxCompletionTokens:16384,pricing:{input:0,output:0}},[ae.Model.GOOGLE_GEMINI_PRO]:{id:ae.Model.GOOGLE_GEMINI_PRO,provider:ct,apiModelName:"google/gemini-pro",maxCompletionTokens:32768,pricing:{input:0,output:0}},[ae.Model.GOOGLE_PALM_2_CODE_CHAT_32K]:{id:ae.Model.GOOGLE_PALM_2_CODE_CHAT_32K,provider:ct,apiModelName:"google/palm-2-code-chat-32k",maxCompletionTokens:32768,pricing:{input:0,output:0}},[ae.Model.META_CODELLAMA_34B_INSTRUCT]:{id:ae.Model.META_CODELLAMA_34B_INSTRUCT,provider:ct,apiModelName:"meta-llama/codellama-34b-instruct",maxCompletionTokens:16384,pricing:{input:0,output:0}},[ae.Model.OPENAI_GPT4_PREVIEW]:{id:ae.Model.OPENAI_GPT4_PREVIEW,provider:et,apiModelName:"gpt-4-preview",maxCompletionTokens:128e3,pricing:{input:0,output:0}}};function On(e){const t=gd[e];if(!t)throw new Error(`Unknown model: ${e}`);return t}function yd(e){return On(e).maxCompletionTokens}function xd(e){return On(e).pricing}const Ea=1e6;function bd({model:e,usage:t}){const r=xd(e);return r?t.prompt_tokens*(r.input/Ea)+t.completion_tokens*(r.output/Ea):null}function vd({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=bd({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 wd({messages:{system:e,prompt:t},model:r,responseType:a,jsonSchema:s}){const o=r??Ys,i=On(o);yd(o);const l=[];return e&&l.push({role:"system",content:e}),l.push({role:"user",content:[{type:"text",text:t}]}),{messages:l,model:i.apiModelName,response_format:a==="json_schema"&&s?{type:"json_schema",json_schema:{name:s.name,schema:s.schema,strict:s.strict!==!1}}:{type:a&&a=="text"?"text":"json_object"},...i.reasoningEffort&&{reasoning_effort:i.reasoningEffort}}}xr(yr);const un=new li({concurrency:100,timeout:1200*1e3,throwOnTimeout:!0,autoStart:!0}),_a={retries:4,factor:2,minTimeout:1e3,maxTimeout:6e4,randomize:!0},hn={};async function lr({type:e,systemMessage:t,prompt:r,jsonResponse:a=!0,jsonSchema:s,model:o=Ys,attempts:i=0}){var A,P,M,I,N,$,_;if(process.env.CODEYAM_LLM_FIXTURES_DIR)return await Cd(e,process.env.CODEYAM_LLM_FIXTURES_DIR);console.log(`CodeYam Debug: LLM Pool [queued=${un.size}, running=${un.pending}]`);const l=Date.now();let d,h=0;const u=On(o),m=process.env[u.provider.apiKeyEnvVar];if(!m)throw new Error(`API key not found for provider ${u.provider.name}. Please set ${u.provider.apiKeyEnvVar} environment variable.`);console.log(`Using ${u.provider.name} for AI request`);const p=new ii({apiKey:m,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=wd(f),y=await un.add(()=>(d=Date.now(),ma(()=>p.chat.completions.create(g,{timeout:300*1e3}),{..._a,onFailedAttempt:S=>{h++,console.log(`CodeYam Error: Completion call failed [model=${o}]`,{error:S,prompt:r,systemMessage:t,attempts:i,retryCount:h})}})),{throwOnTimeout:!0}),b=Date.now(),x=vd({chatRequest:f,chatCompletion:y,model:o});if(!x)throw new Error("Failed to get LLM call stats");x.retries=h,x.wait_ms=d-l,x.duration_ms=b-l;const w=(A=y.choices)==null?void 0:A[0];let v=null;if(w){if(!w.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");v=(P=w.message)==null?void 0:P.content}let C=v;v&&(C=v.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const k=a?C&&(((M=C.match(/\{[\s\S]*\}/))==null?void 0:M[0])??C):C;if(!k){if(console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({completion:k,rawCompletion:v,chatCompletion:y,chatRequest:f},null,2)),i<3)return console.log("CodeYam Error: Retrying completion",{prompt:r,systemMessage:t,attempts:i}),await lr({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:v,prompt:r,systemMessage:t}),new Error("Empty completion");if(a)try{JSON.parse(k)}catch(S){if(console.log("CodeYam Error: Invalid JSON in completion",{error:S.message,model:o,completion:k.substring(0,500),rawCompletion:v==null?void 0:v.substring(0,500)}),i<3){console.log("CodeYam Error: Retrying with correction prompt",{attempts:i,parseError:S.message});const E=`Your previous response contained invalid JSON with the following error:
66
+
67
+ ${S.message}
68
+
69
+ Here was your previous response:
70
+ \`\`\`
71
+ ${k}
72
+ \`\`\`
73
+
74
+ Please provide a corrected version with valid JSON only. Do not include any explanatory text, just the valid JSON object.`,R=await un.add(()=>ma(()=>p.chat.completions.create({...g,messages:[{role:"system",content:t},{role:"user",content:r},{role:"assistant",content:k},{role:"user",content:E}]},{timeout:300*1e3}),{..._a,onFailedAttempt:Q=>{console.log("CodeYam Error: Correction call failed",{error:Q,attempts:i})}}),{throwOnTimeout:!0}),D=($=(N=(I=R.choices)==null?void 0:I[0])==null?void 0:N.message)==null?void 0:$.content;let O=D;D&&(O=D.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const H=O&&(((_=O.match(/\{[\s\S]*\}/))==null?void 0:_[0])??O);if(!H)throw new Error("Correction attempt returned empty completion");try{JSON.parse(H),console.log("CodeYam: JSON correction successful");const Q=Date.now();return x.duration_ms=Q-l,{finishReason:R.choices[0].finish_reason,completion:H,stats:x}}catch(Q){return console.log("CodeYam Error: Corrected JSON still invalid",{error:Q.message,correctedCompletion:H.substring(0,500)}),await lr({type:e,systemMessage:t,prompt:r,jsonResponse:a,model:o,attempts:i+1})}}throw new Error(`Invalid JSON after ${i} attempts: ${S.message}`)}return{finishReason:y.choices[0].finish_reason,completion:k,stats:x}}async function Cd(e,t){var s,o,i;const r=await import("fs"),a=await import("path");console.log(`CodeYam Test: Replaying LLM call for type '${e}' from ${t}`);try{if(!r.existsSync(t))throw console.log(`CodeYam Test: Fixtures directory does not exist yet: ${t}`),new Error(`No LLM fixture files found - directory does not exist: ${t}`);const l=r.readdirSync(t).filter(g=>g.endsWith(".json"));if(l.length===0)throw new Error(`No LLM fixture files found in ${t}`);const d={};for(const g of l)try{const y=r.readFileSync(a.join(t,g),"utf-8"),b=JSON.parse(y);d[b.prompt_type]||(d[b.prompt_type]=[]),d[b.prompt_type].push(b)}catch(y){console.warn(`Failed to parse LLM fixture file ${g}:`,y)}const h=d[e];if(!h||h.length===0){const g=Object.keys(d).join(", ");throw new Error(`No captured LLM call found for type '${e}'. Available types: ${g}`)}const u=`${t}::${e}`;hn[u]||(hn[u]=0);const m=hn[u];hn[u]=(m+1)%h.length;const p=h[m];console.log(`CodeYam Test: Replaying LLM response for '${e}' [${m+1}/${h.length}]`);let f;try{f=((i=(o=(s=JSON.parse(p.response).choices)==null?void 0:s[0])==null?void 0:o.message)==null?void 0:i.content)||p.response}catch{f=p.response}return{finishReason:"stop",completion:f,stats:{model:p.model??"fixture",prompt_type:e,system_message:p.system_message??"",prompt_text:p.prompt_text??"",response:p.response??"",input_tokens:p.input_tokens??0,output_tokens:p.output_tokens??0,cost:p.cost??0,retries:0,wait_ms:0,duration_ms:1}}}catch(l){throw console.error("CodeYam Test Error: Failed to replay LLM call:",l),l}}function Pa(){return process.env.DYNAMODB_PREFIX?`${process.env.DYNAMODB_PREFIX}-llm-calls`:null}async function Nd(e){const{propsJson:t,...r}=e,a=JSON.stringify(t,null,2),s=jt(),o=Date.now(),i={...r,id:s,created_at:o,props:a};let l;const d=`${i.object_id}_${s}.json`;if(process.env.DYNAMODB_PATH?l=ee.join(process.env.DYNAMODB_PATH,d):process.env.CODEYAM_LOCAL_PROJECT_PATH&&(l=ee.join(process.env.CODEYAM_LOCAL_PROJECT_PATH,".codeyam","llm-calls",d)),l)try{const u=ee.dirname(l);return await Re.mkdir(u,{recursive:!0}),await Re.writeFile(l,JSON.stringify(i,null,2)),console.log(`CodeYam: Saved LLM call to local file: ${l}`),{id:s}}catch(u){return console.log("CodeYam Error: Failed to save LLM call to local file",u),{id:"-1"}}const h=Pa();if(!h)return console.log("[CodeYam] No DynamoDB table name for LLM calls, skipping save"),{id:"-1"};for(const[u,m]of Object.entries(i))typeof m>"u"&&console.log(`CodeYam Warning: LLM call ${s} property ${u} with explicit value 'undefined'`);try{return await new Mn().send(new ci({TableName:Pa(),Item:ui(i,{removeUndefinedValues:!0})})),{id:s}}catch(u){return console.log(`CodeYam Error: Failed to save LLM call to DynamoDB table ${h}`,u),{id:"-1"}}}new Mn({});new Mn({});new Mn({});const Sd=3,Ad=2,Tr=()=>({max:1e4,maxSize:10*1e3*1e3,sizeCalculation:(e,t)=>16+Sd*String(t).length*(1+Ad)});new br(Tr());new br(Tr());new br(Tr());class Ed{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 _d{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array"),a.addType(t,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Pd{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class kd{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 Md{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();s&&s.args.forEach(o=>{a.addEquivalence(t,o)}),a.addType(t,"array"),a.addEquivalence(t,r.withElement("*"))}isComplete(){return!0}}class Td{getReturnType(){return"array"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.withReturnValues();a.addType(s,"array")}isComplete(){return!0}}class Id{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 jd{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 Rd{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 $d{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 Dd{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 Ld{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array"),a.addEquivalence(t.withReturnValues(),r.withElement("*"))}isComplete(){return!0}}class Od{getReturnType(){return"unknown"}addEquivalences(t,r,a){a.addType(r,"array");const s=t.getLastFunctionCallSegment();if(s&&s.args.length>0){const o=s.args[0];a.addType(o,"function"),a.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Fd{getReturnType(){return"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 Yd{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 zd{getReturnType(){return"unknown"}addEquivalences(t,r,a){t.getLastFunctionCallSegment()}isComplete(){return!0}}class Bd{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 Ud(){const e=new Ed;return e.register("filter",new _d,"Array"),e.register("map",new $d,"Array"),e.register("flatMap",new Dd,"Array"),e.register("join",new Rd,"Array"),e.register("find",new Pd,"Array"),e.register("findLast",new Od,"Array"),e.register("at",new Ld,"Array"),e.register("reduce",new kd,"Array"),e.register("concat",new Md,"Array"),e.register("slice",new Td,"Array"),e.register("splice",new Id,"Array"),e.register("push",new jd,"Array"),e.register("fromEntries",new Fd,"Object"),e.register("then",new Yd,"Promise"),e.register("useState",new Bd,"React"),e.register("useMemo",new zd,"React"),e}Ud();class Wd{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 Wd({enabled:!1});const Hd=new Set(["filter","sort","slice","splice","unshift","push","reverse","entries"]),Vd=new Set(["find","findLast","at","pop","shift"]),Gd=new Set(["map","reduce","flatMap","concat","join","some","every","findIndex","findLastIndex","indexOf","lastIndexOf","includes"]),Jd=new Set([...Hd,...Vd,...Gd]),qd=new Set(["trim","concat","replace","replaceAll","toLowerCase","toUpperCase","trimStart","trimEnd","padStart","padEnd","normalize","slice","substring","substr","toString()","toLocaleLowerCase","toLocaleUpperCase"]),Kd=new Set(["split","match","endsWith","startsWith","includes","indexOf","lastIndexOf","charAt","charCodeAt","codePointAt","repeat","search","valueOf","localeCompare","length"]),Qd=new Set([...qd,...Kd]);[...Jd,...Qd];new Set(Object.getOwnPropertyNames(Array.prototype).filter(e=>typeof Array.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(String.prototype).filter(e=>typeof String.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Number.prototype).filter(e=>typeof Number.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Boolean.prototype).filter(e=>typeof Boolean.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Date.prototype).filter(e=>typeof Date.prototype[e]=="function"));function zs(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 di.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),zs(e)}return null}}function Zd({description:e,existingScenarios:t,scenariosDataStructure:r,keyAttributeSelections:a}){let s="";return a&&a.length>0&&(s=`
75
+ User-selected Key Attributes and Values:
76
+ The user has specifically requested these key attributes and values be used in the scenario:
77
+ ${a.map(o=>` - ${o.path}: ${o.value}${o.isCustom?" (custom value)":""}`).join(`
78
+ `)}
79
+
80
+ IMPORTANT: The mockData MUST include these specific values for the specified paths. Generate a scenario name and description that reflects these choices.
81
+ `),`Mock Scenario Data Structure:
82
+ \`\`\`
83
+ ${JSON.stringify(r,null,2)}
84
+ \`\`\`
85
+ Existing Mock Scenario Data:
86
+ \`\`\`
87
+ ${JSON.stringify(t,null,2)}
88
+ \`\`\`
89
+ ${s}
90
+ New Scenario user-created prompt: "${e||"(No additional description - generate based on selected key attributes)"}"
91
+ `}function Xd({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s}){const o=a.find(i=>i.name===Tn);return`Mock Scenario Data Structure:
92
+ \`\`\`
93
+ ${JSON.stringify({props:s.arguments,dataVariables:s.dataForMocks},null,2)}
94
+ \`\`\`
95
+
96
+ Existing Mock Scenario Data:
97
+ \`\`\`
98
+ ${JSON.stringify(a.map(i=>({name:i.name,data:zt(o.metadata.data,i.metadata.data)})),null,2)}
99
+ \`\`\`
100
+
101
+ Mock Scenario that should be edited: "${t}"
102
+ ${r?`The portion of the data that should be edited:
103
+ \`\`\`
104
+ ${JSON.stringify(r,null,2)}
105
+ \`\`\``:""}
106
+
107
+ How this data should be changed: "${e}"
108
+ `}async function eu({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s,keyAttributeSelections:o,model:i}){const l=t?Xd({description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s}):Zd({description:e,existingScenarios:a,scenariosDataStructure:s,keyAttributeSelections:o}),d=await lr({type:"guessScenarioDataFromDescription",systemMessage:t?nu(r):tu,prompt:l,model:i??pd});await Nd({object_type:"guessScenarioDataFromDescription",object_id:"new",propsJson:{description:e,editingMockName:t,editingMockData:r,existingScenarios:a,scenariosDataStructure:s,model:i},...d.stats});const{completion:h}=d;return h?zs(h):(console.log("CodeYam: guessing scenario data failed: No response from AI"),null)}const tu=`
109
+ 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.
110
+
111
+ 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.
112
+
113
+ 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.
114
+
115
+ You must respond with valid JSON following this format of this TS type definition:
116
+ \`\`\`
117
+ export type ScenarioData = {
118
+ name: string;
119
+ description: string;
120
+ data: {
121
+ mockData: { [key: string]: unknown };
122
+ argumentsData: { [key: string]: unknown };
123
+ };
124
+ };
125
+
126
+ \`\`\`
127
+ `,nu=e=>`
128
+ 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.
129
+
130
+ Your goal is to edit one of the scenarios, named as the "Mock Scenario that should be edited".
131
+ ${e?`
132
+ 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.`:""}
133
+
134
+ 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.
135
+
136
+ You must respond with valid JSON following this type definition:
137
+ \`\`\`
138
+ {
139
+ data: {
140
+ mockData: { [key: string]: unknown };
141
+ argumentsData: { [key: string]: unknown };
142
+ }
143
+ }
144
+ \`\`\`
145
+ `;async function ru({request:e}){if(e.method!=="POST")return z({error:"Method not allowed"},{status:405});try{const t=await e.json(),{description:r,existingScenarios:a,scenariosDataStructure:s,editingMockName:o,editingMockData:i,keyAttributeSelections:l}=t;if(!r&&(!l||l.length===0))return z({error:"Missing required field: description or keyAttributeSelections"},{status:400});const d=await eu({description:r||"",existingScenarios:a??[],scenariosDataStructure:s,editingMockName:o,editingMockData:i,keyAttributeSelections:l}),h=(d==null?void 0:d.data)||d;return z({success:!0,data:h})}catch(t){return console.error("[Generate Scenario Data API] Error:",t),z({error:"Failed to generate scenario data",details:t instanceof Error?t.message:String(t)},{status:500})}}const au=Object.freeze(Object.defineProperty({__proto__:null,action:ru},Symbol.toStringTag,{value:"Module"}));async function su({request:e}){var t;if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const r=await e.json(),{action:a,analysisId:s,analysis:o,keyAttribute:i,keyAttributeIndex:l}=r;if(!s||!o)return Response.json({error:"Missing required fields: analysisId and analysis"},{status:400});const h=[...((t=o.metadata)==null?void 0:t.keyAttributes)||[]];switch(a){case"add":if(!i)return Response.json({error:"Missing keyAttribute for add action"},{status:400});const p=h.map(g=>g.dataStructurePath||g.externalPath||g.internalPath),f=i.dataStructurePath||i.externalPath||i.internalPath;if(p.includes(f))return Response.json({error:`Key attribute with path "${f}" already exists`},{status:400});h.push(i);break;case"update":if(l===void 0||!i)return Response.json({error:"Missing keyAttributeIndex or keyAttribute for update action"},{status:400});if(l<0||l>=h.length)return Response.json({error:"Invalid keyAttributeIndex"},{status:400});h[l]=i;break;case"remove":if(l===void 0)return Response.json({error:"Missing keyAttributeIndex for remove action"},{status:400});if(l<0||l>=h.length)return Response.json({error:"Invalid keyAttributeIndex"},{status:400});h.splice(l,1);break;default:return Response.json({error:`Invalid action: ${a}`},{status:400})}const u={...o,metadata:{...o.metadata,keyAttributes:h}},m=await ms([u]);if(!m||m.length===0)throw new Error("Failed to save analysis to database");return Response.json({success:!0,analysis:m[0]})}catch(r){return console.error("[API] Error updating key attributes:",r),Response.json({error:"Failed to update key attributes",details:r instanceof Error?r.message:String(r)},{status:500})}}const ou=Object.freeze(Object.defineProperty({__proto__:null,action:su},Symbol.toStringTag,{value:"Module"}));async function iu(e,t){const r=pe();if(!r)return{entityCalls:[],analysisCalls:[]};const a=ee.join(r,".codeyam","llm-calls");try{await Re.access(a)}catch{return{entityCalls:[],analysisCalls:[]}}const s=[],o=[];try{const l=(await Re.readdir(a)).filter(x=>x.endsWith(".json")),d=`${e}_`,h=t?`${t}_`:null,u=[],m=[];for(const x of l)x.startsWith(d)||h&&x.startsWith(h)?u.push(x):m.push(x);const p=u.map(async x=>{try{const w=ee.join(a,x),v=await Re.readFile(w,"utf-8");return JSON.parse(v)}catch{return null}}),f=m.map(async x=>{try{const w=ee.join(a,x),v=await Re.readFile(w,"utf-8"),C=JSON.parse(v);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)]),b=[...g,...y].filter(x=>x!==null);for(const x of b)x.object_id===e?s.push(x):t&&x.object_id===t&&o.push(x);s.sort((x,w)=>w.created_at-x.created_at),o.sort((x,w)=>w.created_at-x.created_at)}catch(i){console.error("Error loading LLM calls:",i)}return{entityCalls:s,analysisCalls:o}}async function lu({params:e,request:t}){const{entitySha:r}=e;if(!r)return z({error:"Entity SHA is required"},{status:400});const s=new URL(t.url).searchParams.get("analysisId")||void 0,o=await iu(r,s);return z(o)}const cu=Object.freeze(Object.defineProperty({__proto__:null,loader:lu},Symbol.toStringTag,{value:"Module"}));async function du({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{action:r,scenario:a,keyAttributePath:s,valueOptionRef:o,isErrorValue:i}=t;if(!a||!a.id)return Response.json({error:"Missing required field: scenario with id"},{status:400});if(!s)return Response.json({error:"Missing required field: keyAttributePath"},{status:400});const l={...a.metadata},d={...l.keyAttributeInstructions||{}};switch(r){case"link":if(!o)return Response.json({error:"Missing valueOptionRef for link action"},{status:400});const m=d[s];let p=s.split(".").pop()||s;typeof m=="object"&&"localVariable"in m&&(p=m.localVariable),d[s]={localVariable:p,instruction:`Using value at index ${o.index}`,...i?{errorOptionRef:o}:{valueOptionRef:o}};break;case"unlink":delete d[s];break;default:return Response.json({error:`Invalid action: ${r}`},{status:400})}const h={...a,metadata:{...l,keyAttributeInstructions:d}},u=await ps([h]);if(!u||u.length===0)throw new Error("Failed to save scenario to database");return Response.json({success:!0,scenario:u[0]})}catch(t){return console.error("[API] Error linking scenario value:",t),Response.json({error:"Failed to link scenario value",details:t instanceof Error?t.message:String(t)},{status:500})}}const uu=Object.freeze(Object.defineProperty({__proto__:null,action:du},Symbol.toStringTag,{value:"Module"}));async function hu({request:e}){var t;if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const r=await e.json(),{action:a,analysisId:s,analysis:o,keyAttributeIndex:i,valueType:l,value:d,valueIndex:h}=r;if(!s||!o)return Response.json({error:"Missing required fields: analysisId and analysis"},{status:400});if(i===void 0)return Response.json({error:"Missing required field: keyAttributeIndex"},{status:400});const u=((t=o.metadata)==null?void 0:t.keyAttributes)||[];if(i<0||i>=u.length)return Response.json({error:"Invalid keyAttributeIndex"},{status:400});const m=[...u],p={...m[i]};m[i]=p;const f=l==="validValueOptions"?[...p.validValueOptions||[]]:[...p.errorValueOptions||[]];switch(a){case"add":if(!d||d.trim()==="")return Response.json({error:"Value cannot be empty"},{status:400});if(f.includes(d))return Response.json({error:`Value "${d}" already exists`},{status:400});f.push(d);break;case"remove":if(h===void 0)return Response.json({error:"Missing valueIndex for remove action"},{status:400});if(h<0||h>=f.length)return Response.json({error:"Invalid valueIndex"},{status:400});f.splice(h,1);break;default:return Response.json({error:`Invalid action: ${a}`},{status:400})}l==="validValueOptions"?p.validValueOptions=f:p.errorValueOptions=f;const g={...o,metadata:{...o.metadata,keyAttributes:m}},y=await ms([g]);if(!y||y.length===0)throw new Error("Failed to save analysis to database");return Response.json({success:!0,analysis:y[0]})}catch(r){return console.error("[API] Error updating valid values:",r),Response.json({error:"Failed to update valid values",details:r instanceof Error?r.message:String(r)},{status:500})}}const mu=Object.freeze(Object.defineProperty({__proto__:null,action:hu},Symbol.toStringTag,{value:"Module"}));function pu(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 fu(r)}catch(r){return console.error("Failed to get git status:",r),[]}}function fu(e){const t=e.trim().split(`
146
+ `).filter(a=>a.length>0),r=[];for(const a of t){const s=a[0],o=a[1];let i=a.slice(2).replace(/^[ \t]+/,""),l,d=!1,h;if(s==="A"||o==="A")l="added",d=s==="A";else if(s==="M"||o==="M")l="modified",d=s==="M";else if(s==="D"||o==="D")l="deleted",d=s==="D";else if(s==="R"||o==="R"){l="renamed",d=s==="R";const u=i.indexOf(" -> ");u!==-1&&(h=i.slice(0,u).trim(),i=i.slice(u+4).trim())}else o==="?"?(l="untracked",d=!1):(l="modified",d=s!==" "&&s!=="?");if(i.endsWith("/")){const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),m=be.join(u,i);try{const p=(g,y)=>{const b=Ct.readdirSync(g,{withFileTypes:!0}),x=[];for(const w of b){const v=be.join(g,w.name),C=be.relative(u,v);w.isDirectory()?x.push(...p(v,y)):w.isFile()&&x.push(C)}return x},f=p(m,u);for(const g of f)r.push({path:g,status:l,staged:d,...h&&{oldPath:h}})}catch(p){console.error(`Failed to expand directory ${i}:`,p)}}else r.push({path:i,status:l,staged:d,...h&&{oldPath:h}})}return r}function gu(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 yu(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 xu(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(`
147
+ `).filter(a=>a.length>0)}catch(r){return console.error("Failed to get branches:",r),[]}}function Bs(){const e=pe();return e?pu(e):[]}function bu(){const e=pe();return e?gu(e):null}function vu(){const e=pe();return e?yu(e):"main"}function wu(){const e=pe();return e?xu(e):[]}function Us(e,t){const r=pe();return r?Cu(e,t,r):[]}function Cu(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(`
148
+ `).filter(i=>i.length>0).map(i=>{const l=i.split(" "),d=l[0];let h=l[1],u,m;return d==="A"?m="added":d==="M"?m="modified":d==="D"?m="deleted":d.startsWith("R")?(m="renamed",u=l[1],h=l[2]):m="modified",{path:h,status:m,...u&&{oldPath:u}}})}catch(s){return console.error("Failed to get branch diff:",s),[]}}function Nu(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=Ct.readFileSync(be.join(r,e),"utf8")}catch(o){console.error(`Failed to read current file ${e}:`,o),s=""}return{oldContent:a,newContent:s,fileName:e}}catch(a){return console.error(`Failed to get diff for ${e}:`,a),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function Su(e){const t=pe();return t?Nu(e,t):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function Au(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 gn(e,t,r){const a=pe();return a?Au(e,t,r,a):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function ka(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 Eu(e,t,r,a){const s=fr.createHash("sha256");return s.update(`${e}:${t}:${r}:${a}`),s.digest("hex").substring(0,16)}function Ws(){const e=pe();if(!e)throw new Error("No project root found");const t=be.join(e,".codeyam","cache","branch-entity-diff");return Ct.existsSync(t)||Ct.mkdirSync(t,{recursive:!0}),t}function _u(e){try{const t=Ws(),r=be.join(t,`${e}.json`);if(!Ct.existsSync(r))return null;const a=Ct.readFileSync(r,"utf8");return JSON.parse(a)}catch(t){return console.error("Failed to read cache:",t),null}}function Pu(e,t){try{const r=Ws(),a=be.join(r,`${e}.json`);Ct.writeFileSync(a,JSON.stringify(t,null,2))}catch(r){console.error("Failed to write cache:",r)}}function ku(e,t,r){const a=wn(t,e),s=wn(r,e),o=new Map(a.map(u=>[u.name,u])),i=new Map(s.map(u=>[u.name,u])),l=[],d=[],h=[];for(const[u,m]of i){const p=o.get(u);p?p.sha!==m.sha&&d.push({name:u,baseSha:p.sha,compareSha:m.sha,entityType:m.entityType}):l.push(m)}for(const[u,m]of o)i.has(u)||h.push(m);return{filePath:e,newEntities:l,modifiedEntities:d,deletedEntities:h}}function Mu(e,t){const r=pe();if(!r)throw new Error("No project root found");const a=ka(e,r),s=ka(t,r);if(!a||!s)throw new Error(`Failed to get commit SHAs for branches: ${e}, ${t}`);const o=Eu(e,t,a,s),i=_u(o);if(i)return console.log(`Using cached branch entity diff: ${o}`),i;const l=Us(e,t),d=[];for(const u of l)if(u.path.match(/\.(tsx?|jsx?)$/))if(u.status==="deleted"){const m=gn(u.path,e,t),p=wn(m.oldContent,u.path);d.push({filePath:u.path,newEntities:[],modifiedEntities:[],deletedEntities:p})}else if(u.status==="added"){const m=gn(u.path,e,t),p=wn(m.newContent,u.path);d.push({filePath:u.path,newEntities:p,modifiedEntities:[],deletedEntities:[]})}else{const m=gn(u.path,e,t),p=ku(u.path,m.oldContent,m.newContent);(p.newEntities.length>0||p.modifiedEntities.length>0||p.deletedEntities.length>0)&&d.push(p)}const h={baseBranch:e,compareBranch:t,baseCommitSha:a,compareCommitSha:s,fileComparisons:d,cacheKey:o,computedAt:new Date().toISOString()};return Pu(o,h),h}function Tu({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("base"),a=t.searchParams.get("compare");if(!r||!a)return z({error:"Missing required parameters: base and compare"},{status:400});const s=Mu(r,a);return z(s)}catch(t){return console.error("Failed to compute branch entity diff:",t),z({error:"Failed to compute branch entity diff",details:t instanceof Error?t.message:String(t)},{status:500})}}const Iu=Object.freeze(Object.defineProperty({__proto__:null,loader:Tu},Symbol.toStringTag,{value:"Module"}));async function ju({request:e}){if(e.method!=="POST")return z({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 z({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=pe();if(!i)return z({error:"Project root not found"},{status:500});const l=ee.join(i,"background","src","lib","virtualized","playwright","captureFromUrl.ts"),d=JSON.stringify({url:r,scenarioId:a,projectId:s,projectRoot:i,viewportWidth:o}),h=await new Promise(p=>{const f=ee.join(i,".codeyam","db.sqlite3"),g=gr("npx",["tsx",l,d],{cwd:i,env:{...process.env,SQLITE_PATH:f}});let y="",b="";g.stdout.on("data",x=>{const w=x.toString();y+=w;const v=w.trim().split(`
149
+ `);for(const C of v)C.includes("[Capture]")&&console.log(C)}),g.stderr.on("data",x=>{const w=x.toString();b+=w,console.error("[Capture:Error]",w.trim())}),g.on("close",x=>{p(x===0?{success:!0,output:y}:{success:!1,output:y,error:b||`Process exited with code ${x}`})}),g.on("error",x=>{console.error("[Capture] Failed to spawn child process:",x),p({success:!1,output:"",error:x.message})})});if(!h.success)return z({error:"Failed to capture screenshot",details:h.error},{status:500});const u=h.output.match(/\[Capture\] RESULT:(.+)/);if(!u)return z({error:"Failed to parse capture result"},{status:500});const m=JSON.parse(u[1]);return z(m)}catch(t){return console.error("[Capture] Error:",t),z({error:"Failed to capture screenshot",details:t instanceof Error?t.message:String(t)},{status:500})}}const Ru=Object.freeze(Object.defineProperty({__proto__:null,action:ju},Symbol.toStringTag,{value:"Module"}));async function $u(e,t,r){var f;console.log(`[recapture] Starting recapture for analysis ${e} with width ${t}`),await $e();const a=await st({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);const s=ve(),o=a.entitySha,i=await s.selectFrom("entities").select(["metadata"]).where("sha","=",o).executeTakeFirst();let l={};if(i!=null&&i.metadata&&(typeof i.metadata=="string"?l=JSON.parse(i.metadata):l=i.metadata),l.defaultWidth=t,await s.updateTable("entities").set({metadata:JSON.stringify(l)}).where("sha","=",o).execute(),console.log(`[recapture] Updated defaultWidth for entity ${o} to ${t}`),!a.commit)throw new Error(`Commit not found for analysis ${e}`);console.log(`[recapture] Loaded analysis with ${((f=a.scenarios)==null?void 0:f.length)||0} scenarios`),await $t(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=pe();if(!d)throw new Error("Project root not found");const h=ee.join(d,".codeyam","config.json"),u=JSON.parse(K.readFileSync(h,"utf8")),{projectSlug:m}=u;if(!m)throw new Error("Project slug not found in config");const{jobId:p}=r.enqueue({type:"recapture",commitSha:a.commit.sha,projectSlug:m,analysisId:e,defaultWidth:t});return console.log(`[recapture] Recapture job queued with ID: ${p}`),{jobId:p}}async function Du(e,t,r){var u;console.log(`[recapture] Starting scenario recapture for analysis ${e}, scenario ${t}`),await $e();const a=await st({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(m=>m.id===t);if(!s)throw console.log(`[recapture] Scenario ${t} not found in analysis ${e}`),new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[recapture] Found scenario: ${s.name}`),await $t(e,m=>{if(m&&(m.readyToBeCaptured=!0,delete m.finishedAt,m.scenarios)){const p=m.scenarios.find(f=>f.name===s.name);p&&(delete p.finishedAt,delete p.startedAt,delete p.error,delete p.errorStack,delete p.screenshotStartedAt,delete p.screenshotFinishedAt,delete p.interactiveStartedAt,delete p.interactiveFinishedAt)}}),console.log(`[recapture] Cleared errors and marked scenario ${s.name} for recapture`);const o=pe();if(!o)throw new Error("Project root not found");const i=ee.join(o,".codeyam","config.json"),l=JSON.parse(K.readFileSync(i,"utf8")),{projectSlug:d}=l;if(!d)throw new Error("Project slug not found in config");const{jobId:h}=r.enqueue({type:"recapture",commitSha:a.commit.sha,projectSlug:d,analysisId:e,scenarioId:t});return console.log(`[recapture] Scenario recapture job queued with ID: ${h}`),{jobId:h}}async function Lu({request:e,context:t}){if(e.method!=="POST")return z({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await it()),!r)return z({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("analysisId"),o=a.get("scenarioId");if(!s||!o)return z({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Starting scenario recapture for analysis ${s}, scenario ${o}`);const i=await Du(s,o,r);return console.log("[API] Scenario recapture queued",i),z({success:!0,message:"Scenario recapture queued",...i})}catch(a){return console.log("[API] Error during scenario recapture:",a),z({error:"Failed to recapture scenario",details:a instanceof Error?a.message:String(a)},{status:500})}}const Ou=Object.freeze(Object.defineProperty({__proto__:null,action:Lu},Symbol.toStringTag,{value:"Module"}));async function Fu({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=Rn(r);try{return await Xo(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 Yu({params:e}){const{projectSlug:t}=e;if(!t)return new Response("Project slug is required",{status:400});const r=Rn(t);try{if(!Vo(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 ei(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 zu=Object.freeze(Object.defineProperty({__proto__:null,action:Fu,loader:Yu},Symbol.toStringTag,{value:"Module"}));async function Bu(e,t){var o,i,l,d,h,u;console.log(`[executeLibraryFunction] Starting execution for analysis ${e}, scenario ${t}`),await $e();const r=await st({id:e,includeScenarios:!0,includeFile:!0});if(!r)throw new Error(`Analysis ${e} not found`);const a=(o=r.scenarios)==null?void 0:o.find(m=>m.id===t);if(!a)throw new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[executeLibraryFunction] Executing ${r.entityName} with scenario ${a.name}`);const s={returnValue:{status:"success",data:((d=(l=(i=a.metadata)==null?void 0:i.data)==null?void 0:l.argumentsData)==null?void 0:d[0])||{},timestamp:new Date().toISOString()},error:null,sideEffects:{consoleOutput:[{level:"log",args:[`Executing ${r.entityName}...`]},{level:"log",args:["Processing input:",JSON.stringify((u=(h=a.metadata)==null?void 0:h.data)==null?void 0:u.argumentsData)]},{level:"log",args:["Execution completed successfully"]}],fileWrites:[],apiCalls:[]},timing:{duration:Math.floor(Math.random()*100)+10,timestamp:new Date().toISOString()}};return console.log(`[executeLibraryFunction] Execution completed for ${r.entityName}`),s}async function Uu({request:e}){if(e.method!=="POST")return z({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("analysisId"),a=t.get("scenarioId");if(!r||!a)return z({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Executing library function for analysis ${r}, scenario ${a}`);const s=await Bu(r,a);return console.log("[API] Function execution completed successfully"),z({success:!0,result:s})}catch(t){return console.log("[API] Error during function execution:",t),z({success:!1,error:"Failed to execute function",details:t instanceof Error?t.message:String(t)},{status:500})}}const Wu=Object.freeze(Object.defineProperty({__proto__:null,action:Uu},Symbol.toStringTag,{value:"Module"}));function Hu({request:e}){return z({status:"ok"})}async function Vu({request:e,context:t}){if(e.method!=="POST")return z({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await it()),!r)return console.error("[Interactive Mode API] Queue not initialized"),z({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 z({error:"Missing required fields: action and analysisId"},{status:400});if(s!=="start"&&s!=="stop")return z({error:'Invalid action. Must be "start" or "stop"'},{status:400});const l=await ze();if(console.log("[Interactive Mode API] projectSlug:",l),!l)return z({error:"Project not initialized"},{status:500});if(s==="start"){const d=await r.enqueue({type:"interactive-start",analysisId:o,scenarioId:i,projectSlug:l});return z({success:!0,action:"start",message:"Interactive mode starting...",jobId:d})}else{const d=await r.enqueue({type:"interactive-stop",analysisId:o,projectSlug:l});return z({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),z({error:"Failed to control interactive mode",details:s},{status:500})}}const Gu=Object.freeze(Object.defineProperty({__proto__:null,action:Vu,loader:Hu},Symbol.toStringTag,{value:"Module"}));async function Ju({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=pe();if(s)for(const o of a){const i=be.join(s,".codeyam","captures","screenshots",o);try{await Ie.unlink(i),console.log(`[API] Deleted screenshot: ${i}`)}catch(l){console.log(`[API] Could not delete screenshot ${i}:`,l instanceof Error?l.message:l)}}}return await ll({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 qu=Object.freeze(Object.defineProperty({__proto__:null,action:Ju},Symbol.toStringTag,{value:"Module"})),Gt="/tmp/codeyam",cr=process.env.CODEYAM_API_BASE||"https://dev.codeyam.com",Hs=500,Ku=Hs*1024*1024;function bt(e,t){try{return Me(`git ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return null}}function yn(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Qu(e){return bt("config user.email",e)}function Zu(e){const t=ee.join(e,".codeyam","debug-report.md");if(!K.existsSync(t))return null;try{return K.readFileSync(t,"utf8")}catch{return null}}function Xu(e,t=20){const r=ee.join(Gt,"local-dev",e,"codeyam","log.txt");if(!K.existsSync(r))return[];try{return K.readFileSync(r,"utf8").split(`
150
+ `).filter(i=>i.includes("CodeYam Log Level 1")).slice(-t)}catch{return[]}}async function eh(e){try{const t=await fetch(`${cr}/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 th(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 nh(e){const{projectRoot:t,projectSlug:r,outputPath:a,metadata:s,screenshot:o,onProgress:i}=e,l=i||(()=>{}),d=Date.now(),h=ee.join(Gt,`delta-staging-${d}`),u=ee.join(h,"delta");K.mkdirSync(u,{recursive:!0});try{const m=bt("diff --binary HEAD",t)||"";K.writeFileSync(ee.join(u,"tracked.patch"),m);const p=bt("ls-files --others --exclude-standard",t);if(p){const b=ee.join(u,"untracked");K.mkdirSync(b,{recursive:!0});for(const x of p.split(`
151
+ `).filter(Boolean)){const w=ee.join(t,x),v=ee.join(b,x);if(K.existsSync(w)){const C=ee.dirname(v);K.mkdirSync(C,{recursive:!0}),K.statSync(w).isFile()&&K.copyFileSync(w,v)}}}const f=ee.join(t,".codeyam");if(K.existsSync(f)){const b=ee.join(u,"codeyam");K.cpSync(f,b,{recursive:!0})}K.writeFileSync(ee.join(u,"meta.json"),JSON.stringify(s,null,2));const g=ee.join(Gt,"local-dev",r,"codeyam","log.txt");K.existsSync(g)?K.copyFileSync(g,ee.join(u,"codeyam-log.txt")):K.writeFileSync(ee.join(u,"codeyam-log.txt"),`# Log file not found
152
+ `);const y=ee.join(t,".codeyam","debug-report.md");K.existsSync(y)&&(K.copyFileSync(y,ee.join(u,"debug-report.md")),l("Debug report included")),o&&o.length>0&&(K.writeFileSync(ee.join(u,"screenshot.jpg"),o),l(`Screenshot included (${yn(o.length)})`));try{Me(`tar -czf "${a}" -C "${h}" delta`,{stdio:"pipe"})}catch(b){throw new Error(`tar failed: ${b.message}`)}}finally{K.rmSync(h,{recursive:!0,force:!0})}}async function rh(e){const{projectRoot:t,projectSlug:r,feedback:a,screenshot:s,onProgress:o}=e,i=o||(()=>{});i("Gathering metadata...");const l=bt("rev-parse HEAD",t);if(!l)throw new Error("At least one commit is required to generate a bundle. Please commit your changes first.");const d=bt("rev-parse --abbrev-ref HEAD",t)||"unknown",h=bt("status --porcelain",t),u=bt("remote get-url origin",t),m=h!==null&&h.length>0,p=Is(r),f=Zu(t);let g=a;f&&(g={...a||{issueType:"other",source:"cli"},debugReport:f},i("Found debug report from /debug-codeyam workflow"));const y={timestamp:new Date().toISOString(),projectSlug:r,git:{sha:l,branch:d,isDirty:m,remoteUrl:u},versions:{cli:p.cliVersion,webserver:p.webserverVersion,node:process.version},system:{platform:process.platform,arch:process.arch},feedback:g},b=Date.now(),x=ee.join(Gt,`base-${l}-${b}.tar.gz`),w=ee.join(Gt,`delta-${r}-${b}.tar.gz`);i("Checking for existing base...");const v=await eh(l);let C=null;v?i("Server already has base, skipping..."):(i("Generating base archive..."),th(t,x),C=K.statSync(x).size,i(`Base archive: ${yn(C)}`)),i("Generating delta archive..."),nh({projectRoot:t,projectSlug:r,outputPath:w,metadata:y,screenshot:s,onProgress:o});const A=K.statSync(w).size;i(`Delta archive: ${yn(A)}`);const P=(C||0)+A;if(P>Ku)throw K.existsSync(x)&&K.unlinkSync(x),K.unlinkSync(w),new Error(`Bundle too large: ${yn(P)} (max: ${Hs} MB). Try removing large files from the project or adding them to .gitignore`);return{basePath:v?null:x,deltaPath:w,metadata:y,baseSha:l,baseSize:C,deltaSize:A}}async function ah(e){const{basePath:t,deltaPath:r,projectSlug:a,metadata:s,baseSha:o,deltaSize:i,onProgress:l}=e,d=l||(()=>{}),h=K.statSync(r),u=t?K.statSync(t):null,m=h.size+((u==null?void 0:u.size)||0);d("Requesting upload URLs...");const p=await fetch(`${cr}/api/reports/request-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectSlug:a,fileSizeBytes:m,baseSha:o,needsBaseUpload:t!==null,deltaSizeBytes:i,metadata:{timestamp:s.timestamp,git:s.git,versions:s.versions,system:s.system,feedback:s.feedback}})});if(!p.ok){const v=await p.json();throw new Error(v.error||`Server returned ${p.status}`)}const{reportId:f,deltaUploadUrl:g,baseUploadUrl:y}=await p.json(),b=[];if(t&&y){d("Uploading base...");const v=K.readFileSync(t);b.push(fetch(y,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:v}).then(C=>{if(!C.ok)throw new Error(`Base upload failed: ${C.status}`)}))}d("Uploading delta...");const x=K.readFileSync(r);b.push(fetch(g,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:x}).then(v=>{if(!v.ok)throw new Error(`Delta upload failed: ${v.status}`)})),await Promise.all(b),d("Confirming upload...");const w=await fetch(`${cr}/api/reports/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reportId:f})});if(!w.ok){const v=await w.json();throw new Error(v.error||`Confirm failed: ${w.status}`)}return t&&K.existsSync(t)&&K.unlinkSync(t),K.unlinkSync(r),{bundleId:f}}async function sh({request:e}){if(e.method!=="POST")return z({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("issueType"),a=t.get("description"),s=t.get("email"),o=t.get("source"),i=t.get("entitySha"),l=t.get("scenarioId"),d=t.get("analysisId"),h=t.get("currentUrl"),u=t.get("screenshot");let m;if(u&&u.size>0){const w=await u.arrayBuffer();m=Buffer.from(w),console.log(`[Bundle] Screenshot received: ${u.size} bytes`)}const p=pe();if(!p)return z({error:"Project root not found"},{status:500});const f=await ze();if(!f)return z({error:"Project slug not found"},{status:500});const g={issueType:r||"other",description:a||void 0,email:s||void 0,source:o||"navbar",entitySha:i||void 0,scenarioId:l||void 0,analysisId:d||void 0,currentUrl:h||void 0,recentActivity:Xu(f,20)};console.log(`[Bundle] Generating bundle for ${f}...`),console.log(`[Bundle] Context: ${g.source}, issue: ${g.issueType}`);const y=await rh({projectRoot:p,projectSlug:f,feedback:g,screenshot:m,onProgress:w=>{console.log(`[Bundle] ${w}`)}}),b=(y.baseSize||0)+y.deltaSize;console.log(`[Bundle] Archives created: delta=${y.deltaSize} bytes${y.basePath?`, base=${y.baseSize} bytes`:" (base reused)"}`);const x=await ah({basePath:y.basePath,deltaPath:y.deltaPath,projectSlug:f,metadata:y.metadata,baseSha:y.baseSha,deltaSize:y.deltaSize,onProgress:w=>{console.log(`[Bundle] ${w}`)}});return console.log(`[Bundle] Upload complete: ${x.bundleId}`),z({success:!0,reportId:x.bundleId,size:b})}catch(t){return console.error("[Bundle] Error:",t),z({error:t.message||"Failed to generate bundle"},{status:500})}}function oh(){const e=pe(),t=e?Qu(e):null;return z({defaultEmail:t})}const ih=Object.freeze(Object.defineProperty({__proto__:null,action:sh,loader:oh},Symbol.toStringTag,{value:"Module"})),Ma=xr(yr);async function lh({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=ch(o),l=i?await dh(o):null;return{pid:o,isRunning:i,processName:l}}));return Response.json({processes:s})}function ch(e){try{return process.kill(e,0),!0}catch{return!1}}async function dh(e){try{const{stdout:t}=await Ma(`ps -p ${e} -o comm=`);return t.trim()||null}catch{try{const{stdout:r}=await Ma(`ps -p ${e} -o args=`),a=r.trim(),s=a.match(/codeyam-(\w+)/);return s?`codeyam-${s[1]}`:a.split(" ")[0]||null}catch{return null}}}const uh=Object.freeze(Object.defineProperty({__proto__:null,loader:lh},Symbol.toStringTag,{value:"Module"}));async function hh({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{analysis:r,scenarios:a}=t;if(!r||!a)return Response.json({error:"Missing required fields: analysis and scenarios"},{status:400});console.log(`[API] Saving scenarios for analysis ${r.id}`),console.log(`[API] Received ${a.length} scenarios to save`),a.forEach((l,d)=>{var m,p,f,g,y;const h=(p=(m=l.metadata)==null?void 0:m.data)==null?void 0:p.argumentsData,u=Array.isArray(h)&&h.length>0?JSON.stringify(h[0]).substring(0,200):"empty-or-not-array";console.log(`[API] Scenario ${d}: ${l.name}`,{id:l.id,projectId:l.projectId,analysisId:l.analysisId,hasMetadata:!!l.metadata,hasData:!!((f=l.metadata)!=null&&f.data),mockDataKeys:(y=(g=l.metadata)==null?void 0:g.data)!=null&&y.mockData?Object.keys(l.metadata.data.mockData):[],argumentsDataLength:Array.isArray(h)?h.length:"not-array",argumentsDataPreview:u})});const s=a.map(l=>({...l,projectId:l.projectId||r.projectId,analysisId:l.analysisId||r.id})),o=await ps(s);if(!o||o.length===0)throw new Error("Failed to save scenarios to database");console.log(`[API] Scenarios saved successfully for analysis ${r.id}`),console.log(`[API] Saved ${o.length} scenarios to database`),o.forEach((l,d)=>{var u,m;const h=(m=(u=l.metadata)==null?void 0:u.data)==null?void 0:m.argumentsData;console.log(`[API] Saved scenario ${d}: ${l.name}`,{id:l.id,argumentsDataLength:Array.isArray(h)?h.length:"not-array"})});const i={...r,scenarios:o};return Response.json({success:!0,analysis:i})}catch(t){return console.error("[API] Error saving scenarios:",t),Response.json({error:"Failed to save scenarios",details:t instanceof Error?t.message:String(t)},{status:500})}}const mh=Object.freeze(Object.defineProperty({__proto__:null,action:hh},Symbol.toStringTag,{value:"Module"}));async function ph({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(!Ta(r))return Response.json({error:"Process not running",pid:r},{status:404});try{process.kill(r,a)}catch(u){return Response.json({error:"Failed to kill process",pid:r,details:u instanceof Error?u.message:String(u)},{status:500})}const i=3e4,l=500,d=Date.now();let h=!0;for(;h&&Date.now()-d<i;)await new Promise(u=>setTimeout(u,l)),h=Ta(r);if(h){console.warn(`Process ${r} didn't die after SIGTERM, sending SIGKILL`);try{process.kill(r,"SIGKILL"),await new Promise(u=>setTimeout(u,2e3))}catch(u){console.error(`Failed to SIGKILL process ${r}:`,u)}}if(s)try{await dt({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 Ta(e){try{return process.kill(e,0),!0}catch{return!1}}const fh=Object.freeze(Object.defineProperty({__proto__:null,action:ph},Symbol.toStringTag,{value:"Module"}));async function gh({params:e}){const t=e["*"];if(!t)return new Response("Screenshot path is required",{status:400});const r=pe();if(!r)return console.error("[screenshot api] Project root not found"),new Response("Project root not found",{status:500});const a=be.join(r,".codeyam","captures","screenshots",t);try{await Ie.access(a);const s=await Ie.readFile(a),o=be.extname(a).toLowerCase(),i=o===".png"?"image/png":o===".jpg"||o===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(s,{status:200,headers:{"Content-Type":i,"Cache-Control":"public, max-age=3600"}})}catch{return new Response("Screenshot not found",{status:404})}}const yh=Object.freeze(Object.defineProperty({__proto__:null,loader:gh},Symbol.toStringTag,{value:"Module"})),Ia={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 Ir({type:e,className:t=""}){const r=Ia[e]||Ia.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 xh={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 mn({variant:e,pid:t,label:r,className:a=""}){const s=xh[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 Fe({screenshotPath:e,cacheBuster:t,alt:r,className:a="",title:s}){const[o,i]=j("loading"),[l,d]=j(!1),h=Pe(null),u=t?`/api/screenshot/${e}?cb=${t}`:`/api/screenshot/${e}`,m=()=>{i("success"),d(!0)},p=()=>{i("error"),d(!1)};return ne(()=>{i("loading"),d(!1);const f=h.current;f!=null&&f.complete&&(f.naturalHeight!==0?(i("success"),d(!0)):(i("error"),d(!1)))},[u]),e?c("div",{className:"relative w-full h-full flex items-center justify-center",title:s,children:[n("img",{ref:h,src:u,alt:r,onLoad:m,onError:p,className:a||"max-w-full max-h-full object-contain",style:{visibility:l?"visible":"hidden",position:l?"relative":"absolute"}}),o==="loading"&&n("div",{className:"absolute inset-0 bg-gray-100 animate-pulse rounded flex items-center justify-center",children:n("svg",{className:"w-8 h-8 text-gray-300",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),o==="error"&&c("div",{className:"absolute inset-0 border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",children:[n("span",{className:"text-2xl text-gray-400",children:"📷"}),n("span",{className:"text-gray-400 whitespace-nowrap",children:"No Screenshot"})]})]}):n("div",{className:"w-full h-full border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",title:s,children:n("span",{className:"text-2xl text-gray-400",children:"📷"})})}let ja=!1;function bh(){if(ja)return;const e=document.createElement("style");e.textContent=`
153
+ @keyframes strongPulse {
154
+ 0%, 100% { opacity: 0.2; }
155
+ 50% { opacity: 1; }
156
+ }
157
+ `,document.head.appendChild(e),ja=!0}function jr({size:e="medium",className:t=""}){typeof document<"u"&&bh();const r={small:{sideDotSize:3,centerDotSize:4,gap:2},medium:{sideDotSize:4,centerDotSize:6,gap:2},large:{sideDotSize:6,centerDotSize:8,gap:3}},{sideDotSize:a,centerDotSize:s,gap:o}=r[e];return c("div",{className:`flex items-center justify-center ${t}`,style:{gap:`${o}px`},role:"status","aria-label":"Loading",children:[n("div",{className:"rounded-full",style:{width:`${a}px`,height:`${a}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0s"}}),n("div",{className:"rounded-full",style:{width:`${s}px`,height:`${s}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.3s"}}),n("div",{className:"rounded-full",style:{width:`${a}px`,height:`${a}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.6s"}})]})}async function vh({request:e,context:t,params:r}){var Q,q,L,T,U,Y,V,le;let a=t.analysisQueue;a||(a=await it());const s=new URL(e.url),o=parseInt(s.searchParams.get("page")||"1",10),i=20,l=r.tab||"current";if(!a)return z({error:"Queue not initialized",state:{paused:!1,jobs:[]},currentRun:void 0,historicalRuns:[],totalHistoricalRuns:0,currentPage:o,totalPages:0,projectSlug:null,commitSha:void 0,queueJobs:[],currentlyExecuting:null,currentEntities:[],tab:l,hasCurrentActivity:!1,queuedCount:0,recentCompletedEntities:[],hasMoreCompletedRuns:!1,currentEntityScenarios:[],currentEntityForScenarios:null,currentAnalysisStatus:null},{status:500});const d=a.getState(),h=await ze();let u=null;if(h&&((Q=d==null?void 0:d.currentlyExecuting)!=null&&Q.commitSha)){const{project:G,branch:B}=await Ye(h),W=await Cn({projectId:G.id,branchId:B.id,shas:[d.currentlyExecuting.commitSha]});u=W&&W.length>0?W[0]:null}else u=await kt();const m=async G=>{const B=await At(G);if(!B)return null;const{getAnalysesForEntity:W}=await Promise.resolve().then(()=>Ol),Z=await W(G,!1);return{...B,analyses:Z||[]}},p=await Promise.all(((d==null?void 0:d.jobs)||[]).map(async G=>{const B=[];if(G.entityShas&&G.entityShas.length>0){const W=G.entityShas.map(F=>m(F)),Z=await Promise.all(W);B.push(...Z.filter(F=>F!==null))}return{...G,entities:B}}));let f=null;if(d!=null&&d.currentlyExecuting){const G=d.currentlyExecuting,B=[];if(G.entityShas&&G.entityShas.length>0){const W=G.entityShas.map(F=>m(F)),Z=await Promise.all(W);B.push(...Z.filter(F=>F!==null))}f={...G,entities:B}}const g=f?p.filter(G=>G.id!==f.id):p,y=((L=(q=u==null?void 0:u.metadata)==null?void 0:q.currentRun)==null?void 0:L.currentEntityShas)||[],x=(await Promise.all(y.map(G=>m(G)))).filter(G=>G!==null),w=[];if(h)try{const{project:G,branch:B}=await Ye(h),W=await Cn({projectId:G.id,branchId:B.id,limit:100});for(const Z of W){const F=((T=Z.metadata)==null?void 0:T.historicalRuns)||[];w.push(...F)}}catch(G){console.error("[activity.tsx] Failed to load historical runs from commits:",G)}const v=[...w].sort((G,B)=>{const W=G.archivedAt||G.createdAt||"";return(B.archivedAt||B.createdAt||"").localeCompare(W)}),C=(o-1)*i,k=C+i,A=v.slice(C,k),P=Math.ceil(v.length/i),M=await Promise.all(A.map(async G=>{const B=G.currentEntityShas||[];if(B.length===0)return{...G,entities:[]};const W=await Promise.all(B.map(Z=>m(Z)));return{...G,entities:W.filter(Z=>Z!==null)}})),I=!!f,N=p.length,$=v.filter(G=>{const B=!!G.failedAt,W=G.readyToBeCaptured,Z=G.capturesCompleted??0,F=W===void 0?!0:W===0||Z>=W;return!B&&!!G.analysisCompletedAt&&F}),_=new Set(((U=f==null?void 0:f.entities)==null?void 0:U.map(G=>G.sha))||[]),S=$.filter(G=>!(G.currentEntityShas||[]).some(W=>_.has(W))),R=(await Promise.all(S.slice(0,3).map(async G=>{const B=G.currentEntityShas||[];if(B.length===0)return{run:G,entities:[]};const W=await Promise.all(B.map(Z=>m(Z)));return{run:G,entities:W.filter(Z=>Z!==null)}}))).flatMap(({run:G,entities:B})=>B.map(W=>({...W,runId:G.id,completedAt:G.analysisCompletedAt||G.archivedAt||G.createdAt})));let D=[],O=null,H=null;if((V=(Y=u==null?void 0:u.metadata)==null?void 0:Y.currentRun)!=null&&V.analysisCompletedAt&&x.length>0){const G=x[0].sha;O=x[0];const B=await In(G);B&&B.length>0&&B[0].scenarios&&(D=B[0].scenarios,H=B[0].status)}return z({state:{...d,jobs:g,currentlyExecuting:f},currentRun:(le=u==null?void 0:u.metadata)==null?void 0:le.currentRun,historicalRuns:M,totalHistoricalRuns:v.length,currentPage:o,totalPages:P,projectSlug:h,commitSha:u==null?void 0:u.sha,queueJobs:g,currentlyExecuting:f,currentEntities:x,tab:l,hasCurrentActivity:I,queuedCount:N,recentCompletedEntities:R,hasMoreCompletedRuns:S.length>3,currentEntityScenarios:D,currentEntityForScenarios:O,currentAnalysisStatus:H})}function wh({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(oe,{to:o.id==="current"?"/activity":`/activity/${o.id}`,className:`
158
+ relative pb-4 px-2 text-sm font-medium transition-colors cursor-pointer
159
+ ${i?"border-b-2":"text-gray-500 hover:text-gray-700"}
160
+ `,style:i?{color:"#005C75",borderColor:"#005C75"}:{},children:c("span",{className:"flex items-center gap-2",children:[o.label,o.count!==null&&o.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${i?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:o.count}),o.count===null&&o.hasContent&&n("span",{className:`
161
+ inline-block w-2 h-2 rounded-full
162
+ ${i?"":"bg-gray-400"}
163
+ `,style:i?{backgroundColor:"#005C75"}:{}})]})},o.id)})})})}function Ch({currentlyExecuting:e,currentRun:t,state:r,projectSlug:a,commitSha:s,onShowLogs:o,recentCompletedEntities:i,hasMoreCompletedRuns:l,currentEntityScenarios:d,currentEntityForScenarios:h,currentAnalysisStatus:u}){var I,N,$,_;const[m,p]=j({}),[f,g]=j({isKilling:!1,current:0,total:0}),y=ht(),b=!!e,x=(e==null?void 0:e.entities)||[],w=!!(t!=null&&t.analysisCompletedAt),v=w&&!!(t!=null&&t.capturePid),C=!w,k=b,A=d||[],{lastLine:P}=mt(a,k);ne(()=>{if(!t)return;const S=[t.analyzerPid,t.capturePid].filter(O=>!!O);if(S.length===0)return;let E=!0;const R=async()=>{try{const H=await(await fetch(`/api/process-status?pids=${S.join(",")}`)).json();if(H.processes&&E){const Q={};H.processes.forEach(q=>{Q[q.pid]={isRunning:q.isRunning,processName:q.processName}}),p(Q)}}catch(O){E&&console.error("Failed to fetch process statuses:",O)}};R();const D=setInterval(()=>void R(),5e3);return()=>{E=!1,clearInterval(D)}},[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid]);const M=x==null?void 0:x[0];return c("div",{className:"flex flex-col gap-[45px]",children:[k?c("div",{className:"rounded-[10px] p-[15px]",style:{backgroundColor:"#f6f9fc",border:"2px solid #e0e9ec"},children:[c("div",{className:"flex items-center gap-2 mb-[15px]",children:[n(at,{size:14,strokeWidth:2.5,className:"animate-spin",style:{color:"#005c75"}}),n("span",{className:"font-medium",style:{fontSize:"14px",lineHeight:"18px",color:"#005c75"},children:v?"Capturing...":"Analyzing..."})]}),M&&c("div",{className:"bg-white border border-[#e1e1e1] rounded-[4px] mb-[15px]",style:{height:"60px",padding:"0 15px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[c("div",{className:"inline-grid place-items-start relative",style:{gridTemplateColumns:"max-content",gridTemplateRows:"max-content",lineHeight:0},children:[n("div",{className:"relative",style:{gridArea:"1 / 1",marginLeft:"10px",marginTop:"8.97px"},children:n("div",{style:{transform:"scale(1.33)"},children:n(Ue,{type:M.entityType||"other"})})}),c("div",{className:"flex flex-col gap-[1px] relative",style:{gridArea:"1 / 1",marginLeft:"49px",marginTop:"0"},children:[c("div",{className:"flex items-center gap-[14px]",children:[n(oe,{to:`/entity/${M.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:M.name}),M.entityType&&n(Ir,{type:M.entityType})]}),n("div",{className:"truncate",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",width:"422px"},title:M.filePath,children:M.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"})]}),v&&A&&A.length>0&&h&&n("div",{className:"flex gap-[10px] overflow-x-auto mb-[15px]",children:A.map(S=>{var q,L,T,U;if(!S.id)return null;const E=(L=(q=S.metadata)==null?void 0:q.screenshotPaths)==null?void 0:L[0],R=(T=S.metadata)==null?void 0:T.noScreenshotSaved,D=E&&!R,O=(U=u==null?void 0:u.scenarios)==null?void 0:U.find(Y=>Y.name===S.name),Q=O&&O.screenshotStartedAt&&!O.screenshotFinishedAt||!D&&!R;return n(oe,{to:`/entity/${h.sha}/scenarios/${S.id}`,className:"border border-solid rounded-[6px] overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"160px",height:"90px",backgroundColor:Q?"#f9f9f9":void 0,borderColor:Q?"#efefef":"#ccc"},children:D?n(Fe,{screenshotPath:E,alt:S.name,className:"w-full h-full object-contain bg-gray-100"}):Q?n("div",{className:"w-full h-full flex items-center justify-center",children:n(jr,{size:"medium"})}):n("div",{className:"w-full h-full bg-gray-100 flex items-center justify-center text-xs text-gray-400",children:"No preview"})},S.id)})}),P&&n("div",{className:"mb-[15px] font-['IBM_Plex_Mono']",style:{fontSize:"12px",lineHeight:"20px",fontWeight:500,color:"#005c75"},children:P}),n("div",{className:"mb-[15px]",style:{height:"1px",backgroundColor:"#e0e9ec"}}),c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center gap-2",children:[c("span",{style:{fontSize:"12px",lineHeight:"15px",fontWeight:400,color:"#000"},children:["Running Processes:"," "]}),(t==null?void 0:t.analyzerPid)&&n(mn,{variant:"analyzer",pid:t.analyzerPid}),(t==null?void 0:t.analyzerPid)&&(C||((I=m[t.analyzerPid])==null?void 0:I.isRunning))&&n(mn,{variant:"running"}),(t==null?void 0:t.capturePid)&&n(mn,{variant:"capture",pid:t.capturePid}),(t==null?void 0:t.capturePid)&&(v||((N=m[t.capturePid])==null?void 0:N.isRunning))&&n(mn,{variant:"running"})]}),((($=m[t==null?void 0:t.analyzerPid])==null?void 0:$.isRunning)||((_=m[t==null?void 0:t.capturePid])==null?void 0:_.isRunning))&&n("button",{onClick:()=>{const S=[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid].filter(D=>{var O;return!!D&&((O=m[D])==null?void 0:O.isRunning)});if(S.length===0)return;const E=S.join(", ");if(!confirm(`Are you sure you want to kill all running processes (${E})?`))return;g({isKilling:!0,current:1,total:S.length}),(async()=>{for(let D=0;D<S.length;D++){const O=S[D];try{await fetch("/api/kill-process",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:O,commitSha:s||""})})}catch(H){console.error(`Failed to kill process ${O}:`,H)}D<S.length-1&&g({isKilling:!0,current:D+2,total:S.length})}g({isKilling:!1,current:0,total:0}),y.revalidate()})()},disabled:f.isKilling,className:"px-[8px] rounded-[4px] transition-colors whitespace-nowrap cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",style:{backgroundColor:"#991b1b",color:"white",fontSize:"12px",lineHeight:"15px",fontWeight:500,height:"27px",width:"114px"},children:f.isKilling?"Killing...":"Kill All Processes"})]})]}):c("div",{className:"bg-[#efefef] rounded-xl p-8 text-center",children:[n("div",{className:"flex justify-center mb-4",children:n("div",{className:"p-[10px] bg-gray-200 rounded",children:n(qa,{size:24,className:"text-gray-600"})})}),n("h3",{className:"font-semibold text-gray-700 mb-2",style:{fontSize:"16px",lineHeight:"24px"},children:"No Current Activity"}),c("p",{className:"text-gray-500",style:{fontSize:"14px",lineHeight:"18px"},children:["There are no analyses currently running. Trigger an analysis from the"," ",n(oe,{to:"/git",className:"text-[#005C75] underline hover:text-[#004a5e] font-medium cursor-pointer",children:"Git"})," ","or"," ",n(oe,{to:"/files",className:"text-[#005C75] underline hover:text-[#004a5e] font-medium cursor-pointer",children:"Files"})," ","page."]})]}),i&&i.length>0&&c("div",{children:[n("h3",{className:"font-semibold",style:{fontSize:"16px",lineHeight:"24px",color:"#343434",marginBottom:"16px"},children:"Recently Completed Analyses"}),n("div",{className:"flex flex-col gap-4",children:i.map(S=>{var D;const E=(D=S.analyses)==null?void 0:D[0],R=(E==null?void 0:E.scenarios)||[];return E==null||E.status,n("div",{className:"rounded-[8px] p-[15px]",style:{backgroundColor:"#f2fcf9",border:"2px solid #aff1a9"},children:c("div",{className:"flex flex-col gap-[15px]",children:[c("div",{className:"flex items-center",children:[n("div",{className:"flex-shrink-0",style:{transform:"scale(1.33)",marginLeft:"10px"},children:n(Ue,{type:S.entityType||"other"})}),c("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[c("div",{className:"flex items-center gap-[5px]",children:[n(oe,{to:`/entity/${S.sha}`,className:"hover:underline cursor-pointer",title:S.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:S.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:S.isUncommitted?"Modified":"Up to date"})]}),n("div",{style:{fontSize:"13px",lineHeight:"18px",color:"#646464",fontWeight:400,width:"422px"},className:"truncate",title:S.filePath,children:S.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:O=>{O.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:O=>{O.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})})]}),R.length>0?n("div",{className:"flex gap-[10px] overflow-x-auto",children:R.map(O=>{var L,T,U;if(!O.id)return null;const H=(T=(L=O.metadata)==null?void 0:L.screenshotPaths)==null?void 0:T[0],Q=(U=O.metadata)==null?void 0:U.noScreenshotSaved,q=H&&!Q;return n(oe,{to:`/entity/${S.sha}/scenarios/${O.id}`,className:"border border-[#ccc] border-solid rounded-[6px] overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"144px",height:"96px"},children:q?n(Fe,{screenshotPath:H,alt:O.name,className:"w-full h-full object-contain bg-gray-100"}):n("div",{className:"w-full h-full bg-gray-100 flex items-center justify-center text-xs text-gray-400",children:"No preview"})},O.id)})}):n("div",{className:"italic",style:{fontSize:"12px",color:"#646464"},children:"No scenarios available"})]})},S.sha)})})]})]})}function Nh({queueJobs:e,state:t,currentRun:r}){if(!e||e.length===0)return c("div",{className:"rounded-xl p-12 text-center",style:{backgroundColor:"#f3f3f3"},children:[n("div",{className:"flex justify-center mb-4",children:n("div",{className:"p-[10px] rounded",style:{backgroundColor:"#e5e5e5"},children:n(Ro,{size:24,style:{color:"#646464"}})})}),n("h3",{className:"font-semibold mb-2",style:{fontSize:"16px",lineHeight:"24px",color:"#343434"},children:"No Queued Jobs"}),n("p",{style:{fontSize:"14px",lineHeight:"18px",color:"#646464"},children:"Analysis jobs will appear here when they are queued but not yet started."})]});const[a,s]=j(null),[o,i]=j(null),[l,d]=j(null),[h,u]=j(!1),m=ht(),p=w=>{s(w)},f=(w,v)=>{w.preventDefault(),i(v)},g=async(w,v)=>{if(w.preventDefault(),!a){i(null);return}const C=e.findIndex(P=>P.id===a);if(C===-1){s(null),i(null);return}if(C===v){s(null),i(null);return}const k=C<v?"down":"up",A=Math.abs(v-C);u(!0);try{for(let P=0;P<A;P++)await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"reorder",jobId:a,direction:k})});m.revalidate()}catch(P){console.error("Failed to reorder job:",P)}finally{u(!1),s(null),i(null)}},y=()=>{h||(s(null),i(null))},b=async w=>{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:w})}),window.location.reload()}catch(v){console.error("Failed to cancel job:",v)}},x=async()=>{if(confirm(`Are you sure you want to cancel all ${e.length} queued jobs?`))try{await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clear"})}),window.location.reload()}catch(w){console.error("Failed to cancel jobs:",w)}};return c("div",{children:[c("div",{className:"flex items-center justify-between mb-4",children:[c("h3",{className:"font-semibold",style:{fontSize:"16px",lineHeight:"24px",color:"#343434"},children:[e.length," Queued Job",e.length!==1?"s":""]}),e.length>0&&n("button",{onClick:()=>void x(),className:"px-[10px] py-0 rounded transition-colors cursor-pointer hover:bg-red-300",style:{backgroundColor:"#ffdcd9",color:"#ef4444",fontSize:"12px",fontWeight:500,height:"29px"},children:"Cancel All"})]}),n("div",{className:"flex flex-col gap-3",children:e.map((w,v)=>{var M,I,N;const C=(M=w.entities)==null?void 0:M[0],k=l===v,A=a===w.id;return c("div",{className:"rounded-lg p-4 relative",style:{backgroundColor:"#f6f9fc",border:"2px solid #005C75",opacity:A||h?.5:1,transform:o===v&&a!==null&&!A?"translateY(-2px)":"translateY(0)",transition:"transform 0.2s ease, opacity 0.2s ease",cursor:h?"not-allowed":A?"grabbing":"grab"},onMouseEnter:()=>d(v),onMouseLeave:()=>d(null),draggable:!h,onDragStart:$=>{p(w.id),$.dataTransfer.effectAllowed="move"},onDragOver:$=>f($,v),onDrop:$=>void g($,v),onDragEnd:y,children:[c("div",{className:"absolute left-4 top-4 flex items-center gap-1.5 flex-shrink-0",children:[n(qa,{size:16,style:{color:"#005C75"}}),c("span",{style:{fontSize:"14px",fontWeight:500,lineHeight:"18px",color:"#005C75"},children:["Job ",v+1]})]}),n("div",{className:"bg-white rounded mt-8",style:{border:"1px solid #e1e1e1",height:"60px"},children:c("div",{className:"flex items-center justify-between h-full px-[15px]",children:[C?c("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{style:{transform:"scale(1.0)"},children:n(Ue,{type:C.entityType||"other"})}),c("div",{className:"flex-1",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(oe,{to:`/entity/${C.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:C.name}),C.entityType&&n(Ir,{type:C.entityType})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:C.filePath})]})]}):c("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{style:{transform:"scale(1.0)"},children:n($o,{size:18,style:{color:"#8e8e8e"}})}),c("div",{className:"flex-1",children:[n("div",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:((I=w.entityNames)==null?void 0:I[0])||(w.type==="analysis"?"Analysis Job":w.type==="recapture"?"Recapture Job":w.type==="debug-setup"?"Debug Setup":w.type.charAt(0).toUpperCase()+w.type.slice(1))}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:((N=w.filePaths)==null?void 0:N[0])||(w.filePaths&&w.filePaths.length>1?`${w.filePaths.length} files`:w.entityShas&&w.entityShas.length>0?`${w.entityShas.length} ${w.entityShas.length===1?"entity":"entities"}`:"Queued for processing")})]})]}),k&&n("div",{className:"mr-2 cursor-grab active:cursor-grabbing",style:{color:"#8e8e8e"},title:"Drag to reorder",children:n(Do,{size:20})}),n("button",{onClick:()=>void b(w.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"})]})})]},w.id)})})]})}function Sh({historicalRuns:e,totalHistoricalRuns:t,currentPage:r,totalPages:a,tab:s,onShowLogs:o}){if(t===0)return c("div",{className:"rounded-xl p-12 text-center",style:{backgroundColor:"#EFEFEF"},children:[n("div",{className:"flex justify-center mb-4",children:n(Lo,{size:24,style:{color:"#646464"}})}),n("h3",{className:"font-semibold mb-2",style:{fontSize:"16px",lineHeight:"24px",color:"#343434"},children:"No Historic Activity"}),n("p",{style:{fontSize:"14px",lineHeight:"18px",color:"#646464"},children:"Completed analyses will appear here for historical reference."})]});const i=[];return e.forEach(l=>{l.entities&&l.entities.length>0&&l.entities.forEach(d=>{i.push({...d,runCreatedAt:l.createdAt})})}),n("div",{className:"flex flex-col gap-4",children:i.slice(0,20).map(l=>{var m;const d=(m=l.analyses)==null?void 0:m[0],h=(d==null?void 0:d.scenarios)||[],u=!l.isUncommitted;return c("div",{className:"rounded-lg p-4",style:{backgroundColor:u?"#f2fcf9":"#fef9e7",border:"2px solid",borderColor:u?"#aff1a9":"#f9d689"},children:[c("div",{className:"flex items-start justify-between mb-3",children:[c("div",{className:"flex items-start gap-3 flex-1",children:[n("div",{style:{transform:"scale(1.0)",marginTop:"2px"},children:n(Ue,{type:l.entityType||"other"})}),c("div",{className:"flex-1",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(oe,{to:`/entity/${l.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#343434"},children:l.name}),n("div",{className:"px-2 py-0.5 rounded",style:{backgroundColor:u?"#e8ffe6":"#fef3cd",color:u?"#00925d":"#a16207",fontSize:"12px",fontWeight:400},children:u?"Up to date":"Out of date"})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#646464"},children:l.filePath})]})]}),n("button",{onClick:o,className:"px-3 py-1 rounded transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),h.length>0&&c("div",{className:"flex gap-2 overflow-x-auto",children:[h.slice(0,8).map(p=>{var b,x,w;if(!p.id)return null;const f=(x=(b=p.metadata)==null?void 0:b.screenshotPaths)==null?void 0:x[0],g=(w=p.metadata)==null?void 0:w.noScreenshotSaved,y=f&&!g;return n(oe,{to:`/entity/${l.sha}/scenarios/${p.id}`,className:"border border-gray-300 rounded overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"120px",height:"80px"},children:y?n(Fe,{screenshotPath:f,alt:p.name,className:"w-full h-full object-cover bg-gray-100"}):n("div",{className:"w-full h-full bg-gray-100 flex items-center justify-center text-xs text-gray-400",children:"No preview"})},p.id)}),h.length>8&&c("div",{className:"flex items-center justify-center flex-shrink-0",style:{width:"120px",height:"80px",fontSize:"12px",color:"#646464"},children:["+",h.length-8," more"]})]})]},`${l.sha}-${l.runCreatedAt}`)})})}const Ah=We(function(){const t=Ke(),r=Va(),[a,s]=j(!1);Et({source:"activity-page"});const o=r.tab||"current";return t?c("div",{className:"px-20 py-12",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-3xl font-semibold text-gray-900 mb-2",children:"Activity"}),n("p",{className:"text-gray-600",children:"View queued, current, and historical analysis activity."})]}),n(wh,{activeTab:o,hasCurrentActivity:t.hasCurrentActivity,queuedCount:t.queuedCount,historicCount:t.totalHistoricalRuns}),o==="current"&&n(Ch,{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(Nh,{queueJobs:t.queueJobs,state:t.state,currentRun:t.currentRun}),o==="historic"&&n(Sh,{historicalRuns:t.historicalRuns,totalHistoricalRuns:t.totalHistoricalRuns,currentPage:t.currentPage,totalPages:t.totalPages,tab:o,onShowLogs:()=>s(!0)}),a&&t.projectSlug&&n(Rt,{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..."})})})}),Eh=Object.freeze(Object.defineProperty({__proto__:null,default:Ah,loader:vh},Symbol.toStringTag,{value:"Module"}));async function Vs(e,t,r){var C,k;await $e();const a=await st({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=pe();if(!s)throw new Error("Project root not found");const o=ee.join(s,".codeyam","config.json"),i=JSON.parse(K.readFileSync(o,"utf8")),{projectSlug:l}=i;if(!l)throw new Error("Project slug not found in config");const d=Rn(l);try{K.writeFileSync(d,"","utf8")}catch{}const{project:h}=await Ye(l),u=((C=h.metadata)==null?void 0:C.packageManager)||"npm",m=3112,p=ot(l),f=((k=h.metadata)==null?void 0:k.webapps)||[];if(f.length===0)throw new Error(`No webapps found in project metadata for project ${l}`);const g=i.environmentVariables||[],y=ol({filePath:a.filePath,webapps:f,environmentVariables:g,port:m,packageManager:u});await $t(e,A=>{if(A&&(A.readyToBeCaptured=!0,A.scenarios))for(const P of A.scenarios)(!t||P.name===t)&&(delete P.screenshotStartedAt,delete P.screenshotFinishedAt,delete P.interactiveStartedAt,delete P.interactiveFinishedAt,delete P.error,delete P.errorStack)});const{jobId:b}=r.enqueue({type:"debug-setup",commitSha:a.commit.sha,projectSlug:l,analysisId:e,scenarioId:t,prepOnly:!0}),x=y.startCommand,w={title:"Debug Setup In Progress",sections:[{heading:"Status",items:[{content:"Setting up debug environment... This may take a minute."},{label:"Project Path",content:p}]},{heading:"What's Happening",items:[{content:"1. Preparing analyzer and dependencies"},{content:"2. Syncing project files"},{content:"3. Setting up mock environment"}]},{heading:"Next Steps (Once Complete)",items:[{label:"1. Open the project directory",content:`code ${p}`,isCode:!0},{label:"2. Start the development server (copy & paste this exact command)",content:x,isCode:!0},{label:"3. View the scenario in your browser",content:`http://localhost:${m}/static/codeyam-sample`,isLink:!0}]}]};return{success:!0,jobId:b,analysisId:e,scenarioId:t,projectPath:p,projectSlug:l,port:m,packageManager:u,framework:y.framework,instructions:w}}async function _h({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 z({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 it()),!o)return z({error:"Queue not initialized"},{status:500});console.log("[Debug Setup API] GET request for:",{analysisId:a,scenarioId:s});try{const i=await Vs(a,s,o);return z({...i,success:!0,message:"Debug setup queued"})}catch(i){return console.error("[Debug Setup API] GET Error:",i),z({error:"Failed to setup debug environment",details:i.message},{status:500})}}async function Ph({request:e,context:t}){if(e.method!=="POST")return z({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await it()),!r)return z({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("analysisId"),o=a.get("scenarioId");if(!s)return z({error:"Missing required field: analysisId"},{status:400});const i=await Vs(s,o,r);return z({...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),z({error:"Failed to setup debug environment",details:s},{status:500})}}const kh=Object.freeze(Object.defineProperty({__proto__:null,action:Ph,loader:_h},Symbol.toStringTag,{value:"Module"}));async function Mh({request:e,context:t}){if(e.method!=="POST")return z({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await it()),!r)return z({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("analysisId"),o=a.get("defaultWidth");if(!s||!o)return z({error:"Missing required fields: analysisId and defaultWidth"},{status:400});const i=parseInt(o,10);if(isNaN(i)||i<320||i>3840)return z({error:"Invalid defaultWidth: must be between 320 and 3840"},{status:400});console.log(`[API] Starting recapture for analysis ${s} with width ${i}`);const l=await $u(s,i,r);return console.log("[API] Recapture queued",l),z({success:!0,message:"Recapture queued",...l})}catch(a){return console.log("[API] Error during recapture:",a),z({error:"Failed to recapture screenshots",details:a instanceof Error?a.message:String(a)},{status:500})}}const Th=Object.freeze(Object.defineProperty({__proto__:null,action:Mh},Symbol.toStringTag,{value:"Module"}));function Ih(e,t){var i,l,d,h,u;const r=((i=e.metadata)==null?void 0:i.isUncommitted)===!0,a=e.analyses&&e.analyses.length>0&&e.analyses.some(m=>m.scenarios&&m.scenarios.length>0);if(!r){const m=!!((l=e.metadata)!=null&&l.previousVersionWithAnalyses),p=a&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha!==e.sha;return m||p?a?{state:"committed_no_simulations",hasSimulations:!0,hasOutdatedSimulations:!0,canGenerateSimulations:!0,badge:{label:"Committed - Simulations Outdated",color:"text-orange-700",bgColor:"bg-orange-50",borderColor:"border-orange-300",icon:"⚠"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not Yet Analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}:a?{state:"committed_with_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up to date",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"✓"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}}const s=!!((d=e.metadata)!=null&&d.previousCommittedSha);if(!!((h=e.metadata)!=null&&h.previousVersionWithAnalyses)||s){const m=a&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha===((u=e.metadata)==null?void 0:u.previousVersionWithAnalyses);return a&&!m?{state:"uncommitted_with_new_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up-to-date Simulations",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"●"}}:a?{state:"uncommitted_outdated_simulations",hasSimulations:!0,hasOutdatedSimulations:!0,canGenerateSimulations:!0,badge:{label:"Edited - Simulations Outdated",color:"text-amber-700",bgColor:"bg-amber-50",borderColor:"border-amber-300",icon:"⚠"}}:{state:"uncommitted_outdated_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not Analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}}else return a?{state:"uncommitted_with_new_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up-to-date Simulations",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"●"}}:{state:"uncommitted_no_previous_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"New",color:"text-purple-700",bgColor:"bg-purple-50",borderColor:"border-purple-200",icon:"+"}}}function jh(e){return Ih(e).hasOutdatedSimulations}function Rr(e,t,r,a,s){var O,H,Q,q,L,T,U,Y;const o=(O=t==null?void 0:t.scenarios)==null?void 0:O.find(V=>V.name===e.name),i=!!(o!=null&&o.startedAt),l=!!(o!=null&&o.screenshotStartedAt),d=!!(o!=null&&o.screenshotFinishedAt),h=!!(o!=null&&o.finishedAt),u=1800*1e3,m=l&&!d&&(o==null?void 0:o.screenshotStartedAt)&&Date.now()-new Date(o.screenshotStartedAt).getTime()>u,p=!!((Q=(H=e.metadata)==null?void 0:H.screenshotPaths)!=null&&Q[0])||!!((q=e.metadata)!=null&&q.executionResult),f=l&&!d,g=o==null?void 0:o.error,y=(T=(L=e.metadata)==null?void 0:L.executionResult)==null?void 0:T.error,b=[];if(t!=null&&t.errors&&t.errors.length>0)for(const V of t.errors)b.push({source:`${V.phase} phase`,message:V.message});if(t!=null&&t.steps)for(const V of t.steps)V.error&&b.push({source:V.name,message:V.error});const x=!p&&!g&&!y&&b.length>0,w=!!(g||y||m||x),v=m?"Capture timed out after 30 minutes":(typeof g=="string"?g:null)||(y==null?void 0:y.message)||(x?`Analysis error: ${b[0].message}`:null),C=m?"The capture process has been running for more than 30 minutes and likely got stuck. Consider re-running the analysis.":(o==null?void 0:o.errorStack)||(y==null?void 0:y.stack)||null,A=(a&&s?s.jobs.some(V=>{var le;return((le=V.entityShas)==null?void 0:le.includes(a))||V.type==="analysis"&&V.entityShas&&V.entityShas.length===0})||((Y=(U=s.currentlyExecuting)==null?void 0:U.entityShas)==null?void 0:Y.includes(a)):!1)&&!i&&!w||!!(o!=null&&o.analyzing)&&!i&&!w,P=i&&!l&&!h&&!w,M=(A||P||f)&&!w,I=(A||P)&&r===!1&&!p;let N;I?N="crashed":w?N="error":p||h?N="completed":f?N="capturing":P?N="starting":A?N="queued":N="pending";let $="📷",_="pending",S=!1,E=`Not captured: ${e.name}`;const R="border-gray-300",D=w||I?"bg-red-50":"bg-white";return w||I?($="⚠️",_="error",E=`Error: ${I?"Analysis process crashed":v||"Unknown error"}`):A?($="⋯",_="queued",E=`Queued: ${e.name}`):P?($="⋯",_="starting",S=!0,E=`Starting server for ${e.name}...`):f&&!w?($="⋯",_="capturing",S=!0,E=`Capturing ${e.name}...`):p&&($="✓",_="completed",E=e.name),{hasError:w||I,errorMessage:I?"Analysis process crashed":v,errorStack:I?"Process terminated unexpectedly before completing analysis":C,isCapturing:f,isCaptured:p,hasCrashed:I,isAnalyzing:M,isQueued:A,isServerStarting:P,status:N,icon:$,iconType:_,shouldSpin:S,title:E,borderColor:R,bgColor:D}}function Gs({scenario:e,entitySha:t,size:r="medium",showBorder:a=!0,isOutdated:s=!1}){var C,k,A,P,M,I;const o=Rr(e,void 0,void 0,t,void 0),i=(C=e.metadata)==null?void 0:C.executionResult,l=!!i,h=(((A=(k=e.metadata)==null?void 0:k.data)==null?void 0:A.argumentsData)||[]).length,u=(i==null?void 0:i.returnValue)!==void 0&&(i==null?void 0:i.returnValue)!==null,m=((M=(P=i==null?void 0:i.sideEffects)==null?void 0:P.consoleOutput)==null?void 0:M.length)||0,p=((I=i==null?void 0:i.timing)==null?void 0:I.duration)||0;let f=0;h>0&&f++,h>2&&f++,u&&f++,m>0&&f++,f=Math.min(3,f);const g=r==="small"?{width:"w-[50px]",height:"h-[38px]",iconSize:"text-base",textSize:"text-[8px]"}:{width:"w-20",height:"h-15",iconSize:"text-xl",textSize:"text-[10px]"},b=o.hasError?{border:"border-red-400",bg:"bg-red-50",icon:"text-red-600",badge:"bg-red-100 text-red-700"}:l?s?{border:"border-amber-500",bg:"bg-amber-50",icon:"text-amber-700",badge:"bg-amber-100 text-amber-700"}:{border:"border-blue-400",bg:"bg-blue-50",icon:"text-blue-600",badge:"bg-blue-100 text-blue-700"}:{border:"border-gray-300 border-dashed",bg:"bg-gray-50",icon:"text-gray-400",badge:"bg-gray-100 text-gray-600"},x=a?`border-2 ${b.border}`:"",w=Array.from({length:3},(N,$)=>n("div",{className:`w-1 h-1 rounded-full ${$<f?b.icon.replace("text-","bg-"):"bg-gray-300"}`},$)),v=o.hasError?`Error: ${o.errorMessage||"Unknown error"}`:l?`${e.name}
164
+ ${h} args → ${u?"value":"void"}${m>0?` (${m} logs)`:""}
165
+ ${p}ms`:`Not executed: ${e.name}`;return c(oe,{to:`/entity/${t}/scenarios/${e.id}`,className:`relative ${g.width} ${g.height} ${x} rounded ${b.bg} flex flex-col items-center justify-center gap-0.5 cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:v,onClick:N=>N.stopPropagation(),children:[n("div",{className:`${b.icon} ${g.iconSize} font-mono font-bold`,children:o.hasError?"⚠":l?"ƒ":"○"}),l&&!o.hasError&&c("div",{className:`flex items-center gap-0.5 ${g.textSize} ${b.badge} px-1 rounded`,children:[n("span",{children:h}),n("span",{children:"→"}),n("span",{children:u?"✓":"∅"})]}),l&&!o.hasError&&r==="medium"&&n("div",{className:"flex gap-0.5 mt-0.5",children:w}),l&&!o.hasError&&p>100&&r==="medium"&&n("div",{className:`absolute top-0.5 right-0.5 ${g.textSize} ${b.badge} px-1 rounded`,children:p>1e3?`${Math.round(p/1e3)}s`:`${p}ms`}),l&&!o.hasError&&m>0&&r==="medium"&&c("div",{className:"absolute bottom-0.5 left-0.5 text-[8px] text-gray-500",children:["📝",m]})]})}function dr({size:e=24,className:t=""}){return c("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":"true",children:[n("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z",fill:"#ef4444",stroke:"none"}),n("line",{x1:"12",y1:"9",x2:"12",y2:"13",stroke:"#FFFFFF",strokeWidth:"2",strokeLinecap:"round"}),n("circle",{cx:"12",cy:"17",r:"1",fill:"#FFFFFF"})]})}function Ra({scenario:e,entity:t,analysisStatus:r,queueState:a,processIsRunning:s,size:o="medium",cacheBuster:i,className:l="",viewMode:d}){var y,b;if(t.entityType==="library")return n(Gs,{scenario:e,entitySha:t.sha,size:o==="small"?"small":"medium"});const u=Rr(e,r,s,t.sha,a),m=o==="small"?{containerClass:"w-16 h-12",iconSize:"text-xl"}:o==="large"?{containerClass:"w-full h-[67px]",iconSize:"text-2xl"}:{containerClass:"w-20 h-15",iconSize:"text-2xl"},p=`relative ${m.containerClass} ${l}`,f=()=>{const x=`/entity/${t.sha}/scenarios/${e.id}`;return d?`${x}/${d}`:x};if(u.isCaptured){const x=(b=(y=e.metadata)==null?void 0:y.screenshotPaths)==null?void 0:b[0];return n(oe,{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(Fe,{screenshotPath:x,cacheBuster:i,alt:e.name,title:e.name,className:"max-w-full max-h-full object-contain object-center"})})}const g=()=>{const x={size:o==="small"?16:o==="large"?24:20,strokeWidth:2},w=n(jr,{size:o});if(u.shouldSpin||u.iconType==="queued"||u.iconType==="pending")return w;switch(u.iconType){case"starting":case"capturing":return w;case"error":return c("div",{className:"flex flex-col items-center justify-center gap-1",children:[n(dr,{size:24}),n("span",{className:"text-[10px] text-[#ef4444] font-medium",children:"Capture Error"})]});case"completed":return n(Oo,{...x});default:return w}};return n(oe,{to:f(),className:`${p} ${u.bgColor} flex flex-col items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:u.title,children:n("div",{className:m.iconSize,children:g()})})}const Mt=70;function Rh({scenarios:e,hiddenScenarios:t=[],analysis:r,selectedScenario:a,entitySha:s,cacheBuster:o,activeTab:i,entityType:l,entity:d,queueState:h,processIsRunning:u,isEntityAnalyzing:m,areScenariosStale:p,viewMode:f,setViewMode:g,onDebugSetup:y,debugFetcher:b,isBreakdownView:x}){const w=Pe(null),[v,C]=j(new Set),[k,A]=j(!1);ne(()=>{w.current&&i==="scenarios"&&w.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[a==null?void 0:a.id,i]);const P=N=>`/entity/${s}/scenarios/${N}`,M=N=>{C($=>{const _=new Set($);return _.has(N)?_.delete(N):_.add(N),_})},I=(N,$=2)=>{const S=N.split(`
166
+ `).slice(0,$).join(" ").trim();return S.length>Mt?S.substring(0,Mt-3):(N.split(`
167
+ `).length>$||N.length>S.length,S)};return c("aside",{className:"w-[220px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-3",children:[g&&c("div",{children:[n("div",{className:"text-[10px] text-[#626262] font-medium mb-[6px]",children:"View"}),c("div",{className:"grid grid-cols-2 gap-0",role:"group","aria-label":"View mode selector",children:[n("button",{className:`px-[7px] h-[22px] text-[10px] font-medium rounded-l-[4px] border border-[#c7c7c7] transition-colors cursor-pointer ${f==="screenshot"?"bg-white text-[#3e3e3e] border-[#c7c7c7]":"bg-[#e1e1e1] text-[#626262] border-[rgba(0,92,117,0.05)] hover:bg-[#d4d4d4]"}`,onClick:()=>g("screenshot"),"aria-label":"Screenshot view","aria-pressed":f==="screenshot",children:"📸 Screenshot"}),n("button",{className:`px-[7px] h-[22px] text-[10px] font-medium rounded-r-[4px] border border-[#c7c7c7] border-l-0 transition-colors cursor-pointer ${f==="interactive"?"bg-white text-[#3e3e3e] border-[#c7c7c7]":"bg-[#e1e1e1] text-[#626262] border-[rgba(0,92,117,0.05)] hover:bg-[#d4d4d4]"}`,onClick:()=>g("interactive"),"aria-label":"Interactive view","aria-pressed":f==="interactive",children:"🎮 Interactive"})]})]}),a&&c("div",{className:"grid grid-cols-2 gap-1",children:[n(oe,{to:`/entity/${s}/scenarios/${a.id}/edit`,className:"h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa] no-underline flex items-center justify-center",title:"Edit Scenario Data",children:"Edit Scenario"}),n("button",{className:"h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa] disabled:bg-gray-400 disabled:text-gray-600 disabled:cursor-not-allowed flex items-center justify-center",onClick:y,disabled:(b==null?void 0:b.state)!=="idle",title:"Setup Debug Environment",children:(b==null?void 0:b.state)==="idle"?"Debug Scenario":"Setting up..."})]}),d&&d.filePath&&n("div",{children:n(oe,{to:`/entity/${s}/create-scenario`,className:"w-full px-[10px] h-[22px] bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#004a5e] no-underline flex items-center justify-center",children:"Create New Scenario"})}),r&&n("div",{children:c(oe,{to:`/entity/${s}/scenarios/breakdown`,className:`w-full px-[10px] py-[6px] border rounded text-[10px] font-normal cursor-pointer transition-colors no-underline flex flex-col items-start bg-white text-[#005c75] ${x?"border-[#005c75]":"border-[#e1e1e1] hover:border-[#005c75]"}`,children:[n("span",{className:"font-semibold",children:"Scenarios Breakdown"}),n("span",{className:"text-[9px] text-[#808080]",children:"View all key attributes and possible scenarios"})]})}),n("div",{className:"border-t border-[#e1e1e1] pt-3",children:n("div",{className:"text-[10px] text-[#626262] font-medium",children:"Scenarios"})}),m&&(p||e.length===0)?c("div",{className:"",children:[c("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#FFF4FC",color:"#FF2AB5",height:"23px"},children:[c("svg",{width:"9",height:"9",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}),n("p",{className:"text-[#8e8e8e] text-xs font-normal m-0 mt-2 text-left leading-5",children:"Scenarios will appear here once analysis completes"})]}):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((N,$)=>{const _=!x&&(a==null?void 0:a.id)===N.id,S=v.has(N.id||"");return N.id?c(oe,{to:P(N.id),ref:_?w:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${_?"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(Ra,{scenario:N,entity:{sha:s,entityType:l},analysisStatus:r==null?void 0:r.status,queueState:h,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),c("div",{className:"px-[7px] py-[6.444px]",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${S?"":"line-clamp-1"}`,children:N.name}),N.description&&n("div",{className:"mt-[4px]",children:c("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[S?N.description:I(N.description),!S&&N.description.length>Mt&&c(ue,{children:["...",n("button",{onClick:E=>{E.preventDefault(),E.stopPropagation(),M(N.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),S&&N.description.length>Mt&&n("button",{onClick:E=>{E.preventDefault(),E.stopPropagation(),M(N.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},$):null})})}),t.length>0&&!(m&&p)&&c("div",{className:"border-t border-[#e1e1e1] pt-3",children:[c("button",{onClick:()=>A(!k),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 ${k?"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,")"]}),k&&c("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((N,$)=>{const _=!x&&(a==null?void 0:a.id)===N.id,S=v.has(N.id||"");return N.id?c(oe,{to:`/entity/${s}/scenarios/${N.id}`,ref:_?w:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${_?"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(Ra,{scenario:N,entity:{sha:s,entityType:l},analysisStatus:r==null?void 0:r.status,queueState:h,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),c("div",{className:"px-[7px] py-[6.444px]",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${S?"":"line-clamp-1"}`,children:N.name}),N.description&&n("div",{className:"mt-[4px]",children:c("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[S?N.description:I(N.description),!S&&N.description.length>Mt&&c(ue,{children:["...",n("button",{onClick:E=>{E.preventDefault(),E.stopPropagation(),M(N.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),S&&N.description.length>Mt&&n("button",{onClick:E=>{E.preventDefault(),E.stopPropagation(),M(N.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},$):null})})]})]})]})}function $h({scenario:e,entitySha:t,onApply:r,onSave:a,onEditMockData:s,onDelete:o,isApplying:i=!1,isSaving:l=!1,saveMessage:d=null,showDeleteConfirm:h=!1,onShowDeleteConfirm:u,isDeleting:m=!1,deleteError:p=null}){const[f,g]=j(""),y=async()=>{await r(f)},b=async x=>{await a(f,x),x||g("")};return c("aside",{className:"w-[220px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-3 h-full",children:[c("div",{className:"border-b border-[#e1e1e1] pb-3",children:[c("div",{className:"flex items-start justify-between mb-2",children:[n("div",{className:"text-[10px] text-[#626262] font-medium",children:"Edit Scenario"}),n(oe,{to:`/entity/${t}`,className:"text-[#626262] hover:text-[#3e3e3e] transition-colors text-sm leading-none no-underline cursor-pointer",title:"Close",children:"×"})]}),n("div",{className:"text-xs font-semibold text-[#626262]",children:e.name})]}),c("div",{className:"flex-1 overflow-y-auto flex flex-col gap-2",children:[c("div",{className:"pt-1",children:[n("label",{htmlFor:"ai-description",className:"block text-xs text-[#343434] font-semibold mb-[6px]",children:"Describe changes to the AI"}),n("textarea",{id:"ai-description",value:f,onChange:x=>g(x.target.value),placeholder:"e.g. change amount of data to zero",className:"w-full px-[7px] py-[6px] border border-[#c7c7c7] rounded-[4px] text-xs focus:outline-none focus:ring-1 focus:ring-[#005c75] focus:border-[#005c75] resize-none",rows:4}),c("button",{onClick:()=>void y(),disabled:i||!f.trim(),className:"w-full mt-1 h-[22px] bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center gap-1",children:[i&&c("svg",{className:"animate-spin h-3 w-3",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),i?"Applying...":"Apply"]})]}),n("div",{className:"border-t border-[#e1e1e1] my-1"}),c("div",{className:"pt-1",children:[n("div",{className:"text-xs text-[#343434] font-semibold mb-[6px]",children:"Change file"}),n("p",{className:"text-[10px] text-[#808080] mb-2",children:"You can edit the data used for this scenario directly."}),n("button",{onClick:s,className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa]",children:"Edit Mock Data"})]}),d&&n("div",{className:`text-[10px] px-[7px] py-[6px] rounded-[4px] ${d.startsWith("Error")?"bg-red-50 text-red-600":"bg-green-50 text-green-600"}`,children:d}),d==="Recapture successful"&&n("div",{children:n(oe,{to:`/entity/${t}`,className:"text-[#005c75] hover:text-[#004a5e] hover:underline text-[10px] cursor-pointer",children:"View updated screenshot on entity page →"})})]}),c("div",{className:"border-t border-[#e1e1e1] pt-2 bg-white flex flex-col gap-1",children:[n("button",{onClick:()=>void b(!1),disabled:l||!f.trim(),className:"w-full h-[22px] bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center",children:l?"Saving...":"Save Scenario Data"}),n("button",{onClick:()=>void b(!0),disabled:l||!f.trim(),className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa] disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center",children:"Save As New"}),o&&c(ue,{children:[h?c("div",{className:"flex flex-col gap-1",children:[c("div",{className:"text-[10px] text-red-600 font-medium",children:['Are you sure you want to delete "',e.name,'"?']}),c("div",{className:"flex gap-1",children:[n("button",{onClick:()=>void o(),disabled:m,className:"flex-1 h-[22px] bg-red-600 text-white rounded text-[10px] font-normal hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors flex items-center justify-center cursor-pointer",children:m?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>u==null?void 0:u(!1),disabled:m,className:"flex-1 h-[22px] bg-gray-100 text-gray-700 border border-gray-300 rounded text-[10px] font-normal hover:bg-gray-200 disabled:opacity-50 transition-colors flex items-center justify-center cursor-pointer",children:"Cancel"})]})]}):n("button",{onClick:()=>u==null?void 0:u(!0),className:"w-full h-[22px] bg-red-50 text-red-600 border border-red-200 rounded text-[10px] font-normal hover:bg-red-100 transition-colors flex items-center justify-center cursor-pointer",children:"Delete Scenario"}),p&&n("div",{className:"text-[10px] text-red-600 bg-red-50 px-[7px] py-[6px] rounded-[4px]",children:p})]})]})]})}function Dh({scenario:e,analysis:t,entity:r}){var i,l,d;const a=((i=e.metadata)==null?void 0:i.executionResult)||null,s=((d=(l=e.metadata)==null?void 0:l.data)==null?void 0:d.argumentsData)||[],o=h=>{var g,y,b;if(!h)return"No execution results available yet. Run the function to capture side effects including console output, file operations, and API calls.";const u=[],m=((g=h.sideEffects)==null?void 0:g.consoleOutput)||[];m.length>0&&(u.push(`Console Output: ${m.length} log ${m.length===1?"entry":"entries"} captured`),m.forEach(x=>{u.push(` [${x.level.toUpperCase()}] ${x.args.join(" ")}`)}));const p=((y=h.sideEffects)==null?void 0:y.fileWrites)||[];p.length>0&&(u.push(`
168
+ File System Operations: ${p.length} ${p.length===1?"operation":"operations"} detected`),p.forEach(x=>{u.push(` ${x.operation}: ${x.path}${x.size?` (${x.size} bytes)`:""}`)}));const f=((b=h.sideEffects)==null?void 0:b.apiCalls)||[];return f.length>0&&(u.push(`
169
+ API Calls: ${f.length} ${f.length===1?"call":"calls"} made`),f.forEach(x=>{u.push(` ${x.method} ${x.url}${x.status?` → ${x.status}`:""}${x.duration?` (${x.duration}ms)`:""}`)})),h.error&&u.push(`
170
+ Error: ${h.error.name||"Error"}: ${h.error.message}`),u.length===0?"No side effects detected. The function executed without console output, file operations, or API calls.":u.join(`
171
+ `)};return c("div",{className:"flex w-full h-full gap-0",children:[c("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Input Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:JSON.stringify(s,null,2)})})]}),c("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Returned Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:a?n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:a.returnValue!==void 0?JSON.stringify(a.returnValue,null,2):"undefined"}):n("div",{className:"text-sm text-gray-500 italic",children:"No execution results yet"})})]}),c("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Side Effects"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-4",children:n("p",{className:"text-sm text-gray-700 leading-[22px] m-0 whitespace-pre-wrap",children:o(a)})})]})]})}const xt={commandBoxBg:"#f6f9fc",commandBoxBorder:"#e1e1e1",commandBoxText:"#005c75",heading:"#000",subtext:"#646464",link:"#005c75"};function Wt({scenarioId:e,analysisId:t}){const[r,a]=j(!1),[s,o]=j(!1),[i,l]=j(null),[d,h]=j(!1),u=e||t;if(!u)return null;const m=`/debug-codeyam ${u}`,p=async()=>{o(!0);try{const{default:g}=await import("html2canvas-pro"),b=(await g(document.body,{scale:.5})).toDataURL("image/jpeg",.8);l(b),a(!0)}catch(g){console.error("Screenshot capture failed:",g),a(!0)}finally{o(!1)}},f=()=>{a(!1),l(null)};return c(ue,{children:[c("div",{className:"text-center p-6 bg-cywhite-100 rounded-lg border-cygray-30 border",children:[n("h3",{className:"font-semibold font-['IBM_Plex_Sans']",style:{fontSize:"18px",lineHeight:"26px",color:xt.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:xt.subtext},children:"Simply run this command in Claude Code:"}),c("div",{className:"flex items-center justify-between rounded mx-auto mb-3 border",style:{backgroundColor:xt.commandBoxBg,borderColor:xt.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:xt.commandBoxText},children:m}),n("button",{onClick:g=>{g.stopPropagation(),navigator.clipboard.writeText(m),h(!0),setTimeout(()=>h(!1),2e3)},className:"ml-3 cursor-pointer p-0 bg-transparent border-none hover:opacity-80 transition-opacity",style:{width:"14px",height:"14px",color:d?"#22c55e":xt.commandBoxText},title:d?"Copied!":"Copy command","aria-label":"Copy command to clipboard",children:d?n(Fo,{size:14}):n(Yo,{size:14})})]}),c("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:"#005c75"},children:["If Claude is unable to address this issue or suggests reporting it,"," ",n("button",{onClick:()=>void p(),disabled:s,className:"underline cursor-pointer bg-transparent border-none p-0 font-normal hover:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:xt.link},children:s?"capturing...":"please do so here"}),"."]})]}),n(ts,{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 $a=1440,pn=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],rt={background:"#ffdcd9",border:"#fda4a4",text:"#ef4444",link:"#991b1b"};function Js({selectedScenario:e,analysis:t,entity:r,viewMode:a,cacheBuster:s,hasScenarios:o,isAnalyzing:i=!1,projectSlug:l,hasAnApiKey:d=!0,processIsRunning:h,queueState:u}){var Z,F,te,ce,he,fe,Ce,Se,Ae,Ee,De;const m=ke(),[p,f]=j(!1),[g,y]=j(!1),[b,x]=j({name:"Desktop",width:$a,height:900}),[w,v]=j($a),[C,k]=j(1),{customSizes:A,addCustomSize:P,removeCustomSize:M}=$s(l),I=se(()=>[...pn,...A],[A]),N=(ge,Te)=>{v(ge);const je=I.find(we=>we.width===ge&&we.height===Te);x({name:(je==null?void 0:je.name)||"Custom",width:ge,height:Te})},$=ge=>{v(ge.width),x({name:ge.name,width:ge.width,height:ge.height})},_=ge=>{P(ge,b.width,b.height??900),y(!1),x(Te=>({...Te,name:ge}))},S=(ge,Te)=>{v(ge);const je=I.find(we=>we.width===ge&&we.height===Te);x(we=>({name:(je==null?void 0:je.name)||"Custom",width:ge,height:we.height}))},E=(F=(Z=e==null?void 0:e.metadata)==null?void 0:Z.screenshotPaths)==null?void 0:F[0],R=se(()=>e?Rr(e,t==null?void 0:t.status,h,r==null?void 0:r.sha,u):null,[e,t==null?void 0:t.status,h,r==null?void 0:r.sha,u]),D=se(()=>{var Te,je;const ge=[];if((Te=t==null?void 0:t.status)!=null&&Te.errors&&t.status.errors.length>0)for(const we of t.status.errors)ge.push({source:`${we.phase} phase`,message:we.message,stack:we.stack});if((je=t==null?void 0:t.status)!=null&&je.steps)for(const we of t.status.steps)we.error&&ge.push({source:we.name,message:we.error,stack:we.errorStack});return ge},[(te=t==null?void 0:t.status)==null?void 0:te.errors,(ce=t==null?void 0:t.status)==null?void 0:ce.steps]),O=(R==null?void 0:R.errorMessage)||null,H=(R==null?void 0:R.errorStack)||null,{interactiveServerUrl:Q,isStarting:q,isLoading:L,showIframe:T,iframeKey:U,onIframeLoad:Y}=tn({analysisId:t==null?void 0:t.id,scenarioId:e==null?void 0:e.id,scenarioName:e==null?void 0:e.name,projectSlug:l,enabled:a==="interactive"}),V=se(()=>Q||null,[Q]),le=!i&&o&&e&&!((fe=(he=e.metadata)==null?void 0:he.screenshotPaths)!=null&&fe[0])&&((Se=(Ce=t==null?void 0:t.status)==null?void 0:Ce.scenarios)==null?void 0:Se.some(ge=>ge.name===e.name&&ge.screenshotStartedAt&&!ge.screenshotFinishedAt)),{lastLine:G}=mt(l,i||a==="interactive"||le||!1);if(!e){if(i&&r)return n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center bg-[#f6f9fc]",children:c("div",{className:"flex flex-col items-center gap-6 max-w-2xl",children:[n("div",{className:"w-12 h-12 mb-2",children:n("svg",{className:"animate-spin",viewBox:"0 0 50 50",children:n("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"#005c75",strokeWidth:"4",strokeDasharray:"31.4 31.4",strokeLinecap:"round"})})}),n("h2",{className:"text-2xl font-semibold text-[#005c75] leading-[30px] m-0 font-['IBM_Plex_Sans']",children:le?"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."}),G&&n("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl",children:G}),l&&n("button",{onClick:()=>f(!0),className:"w-[148px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-sm text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c] font-['IBM_Plex_Sans']",children:"View full logs"})]})});if(!o&&r&&!i){if(D.length>0){const ge=D.length===1?((Ae=D[0])==null?void 0:Ae.message)||"An error occurred during analysis.":`${D.length} errors occurred during analysis.`;return n("div",{className:"flex-1 flex flex-col justify-center items-center px-5",style:{minHeight:"75vh"},children:c("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded",style:{backgroundColor:rt.background,border:`2px solid ${rt.border}`},role:"alert",children:c("div",{className:"flex items-center gap-3",children:[n(dr,{size:24,className:"shrink-0"}),n("div",{className:"flex-1 min-w-0",children:c("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:rt.text},children:[n("span",{className:"font-semibold",children:"Analysis Error."})," ",ge," ",n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:rt.link},children:"See logs"})," ","for details."]})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(Wt,{analysisId:t==null?void 0:t.id})})]})})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-[#f6f9fc]",children:c("div",{className:"max-w-[600px]",children:[n("h2",{className:"text-[28px] font-semibold text-[#343434] mb-4 m-0 leading-10",children:"No simulations yet"}),n("p",{className:"text-base font-normal text-[#3e3e3e] mb-8 leading-6 m-0",children:"Analyze the code to create simulations and create test scenarios automatically."}),r.filePath&&n("button",{onClick:()=>{m.submit({entitySha:r.sha,filePath:r.filePath},{method:"post",action:"/api/analyze"})},disabled:m.state!=="idle",className:"h-[54px] w-[183px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-lg text-base font-medium cursor-pointer transition-all hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed",children:m.state!=="idle"?"Analyzing...":"Analyze"})]})})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center",children:n("p",{className:"text-base text-gray-500 m-0",children:"Select a scenario to view its screenshot"})})}return c(ue,{children:[n("main",{className:"flex-1 bg-[#f9f9f9] overflow-auto flex flex-col min-w-0",children:(i||le&&!E)&&!O&&a==="screenshot"?n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-linear-to-br from-blue-50 to-indigo-50",children:c("div",{className:"max-w-2xl w-full bg-white rounded-t-2xl shadow-xl p-8",children:[c("div",{className:"mb-8",children:[n("div",{className:"inline-flex items-center justify-center w-24 h-24 bg-blue-100 rounded-full mb-6",children:n("span",{className:"text-5xl animate-spin",children:"⚙️"})}),n("h2",{className:"text-3xl font-bold text-gray-900 mb-4 m-0",children:le?`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:le?`Taking screenshots for ${((Ee=t==null?void 0:t.scenarios)==null?void 0:Ee.length)||0} scenario${((De=t==null?void 0:t.scenarios)==null?void 0:De.length)!==1?"s":""}...`:`Generating simulations and scenarios for this ${r==null?void 0:r.entityType} entity...`}),e&&c("p",{className:"text-sm text-blue-600 font-semibold m-0",children:["Currently processing: ",e.name]})]}),G&&n("div",{className:"bg-[#f6f9fc] border-2 border-[#e1e1e1] rounded-lg p-6 mb-6",children:c("div",{className:"flex items-start gap-3",children:[n("span",{className:"text-xl shrink-0",children:"📝"}),c("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2 m-0",children:"Current Progress"}),n("p",{className:"text-sm text-gray-900 font-mono wrap-break-word m-0",title:G,children:G})]})]})}),l&&n("button",{onClick:()=>f(!0),className:"px-6 py-3 bg-[#005c75] text-white border-none rounded-lg text-base font-semibold cursor-pointer transition-all hover:bg-[#004a5e] hover:shadow-lg",children:"📋 View Full Logs"}),n("p",{className:"text-xs text-gray-500 mt-8 m-0",children:"Screenshots will appear here as they are captured. This may take a few minutes."})]})}):a==="screenshot"&&(E||O)||a==="interactive"&&(V||q)||a==="data"?c(ue,{children:[O&&!E&&n("div",{className:"flex-1 flex flex-col justify-center items-center p-6",children:c("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded overflow-auto",style:{backgroundColor:rt.background,border:`2px solid ${rt.border}`,maxHeight:"50vh"},role:"alert",children:c("div",{className:"flex flex-col gap-3",children:[c("div",{className:"flex items-center justify-center gap-2 font-bold",style:{color:rt.text},children:[n(dr,{size:24,className:"shrink-0"}),n("div",{children:"Capture Error"})]}),c("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:rt.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:rt.text},children:O})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(Wt,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})}),a==="interactive"?c("div",{className:"flex-1 flex flex-col min-h-0",children:[V&&c("div",{className:"bg-gray-50 border-b border-gray-200 px-6 py-3 shrink-0 flex justify-center items-center gap-4",children:[n(Uc,{presets:[...pn],customSizes:A,currentWidth:b.width,currentHeight:b.height??900,scale:C,onSizeChange:N,onSaveCustomSize:()=>y(!0),onRemoveCustomSize:M}),e&&r&&c(oe,{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"]})]}),V&&n("div",{className:"bg-[#f6f9fc] border-b border-[rgba(0,92,117,0.25)] flex justify-center",children:n("div",{style:{maxWidth:`${pn[pn.length-1].width}px`,width:"100%"},children:n(js,{currentViewportWidth:w,currentPresetName:b.name,onDevicePresetClick:$,devicePresets:I})})}),n(Ln,{scenarioId:e.id,scenarioName:e.name,iframeUrl:V,isStarting:q,isLoading:L,showIframe:T,iframeKey:U,onIframeLoad:Y,onScaleChange:k,onDimensionChange:S,projectSlug:l,defaultWidth:b.width,defaultHeight:b.height})]}):a==="data"?n("div",{className:"flex-1 min-h-0",children:n(Dh,{scenario:e,analysis:t,entity:r})}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 p-6 flex items-center justify-center",children:n("div",{className:"transition-all duration-300",style:{maxWidth:`${w}px`},children:(E||!O)&&n(Fe,{screenshotPath:E,cacheBuster:s,alt:e.name,className:"w-full rounded-lg shadow-[0_10px_25px_rgba(0,0,0,0.1)] bg-white"})})})})]}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 overflow-auto w-full",children:i&&!E?n("div",{className:"w-full h-full flex items-center justify-center",children:n("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-8",children:c("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"animate-spin text-4xl shrink-0",children:"⚙️"}),c("div",{className:"flex-1",children:[n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Capturing Screenshot"}),c("p",{className:"text-sm text-blue-800 m-0 mb-4",children:["Analysis is in progress for"," ",n("strong",{children:e.name}),". The screenshot will appear here once capture is complete."]}),G&&c("div",{className:"bg-white border border-blue-200 rounded p-4 mt-4",children:[n("h4",{className:"text-xs font-semibold text-blue-800 m-0 mb-2 uppercase tracking-wide",children:"Current Progress"}),n("p",{className:"text-sm text-blue-900 m-0 font-mono wrap-break-word",children:G})]}),l&&n("button",{onClick:()=>f(!0),className:"mt-4 px-4 py-2 bg-[#005c75] text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-[#004a5e]",children:"📋 View Full Logs"})]})]})})}):O?c("div",{className:"w-full h-full flex flex-col items-center justify-center overflow-auto gap-6",children:[!d&&n("div",{className:"bg-blue-50 border-2 border-blue-300 rounded-lg p-8",children:c("div",{className:"flex-1 flex flex-col gap-4 items-center justify-center",children:[c("div",{className:"flex items-start gap-4",children:[n("span",{className:"text-blue-600 text-2xl shrink-0",children:"🔑"}),n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Improve Analysis Quality with an API Key"})]}),c("div",{className:"bg-white border border-blue-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-blue-900 m-0 mb-2 uppercase tracking-wide",children:"CodeYam requires an AI API key for reliable analysis."}),c("ul",{className:"text-sm text-blue-800 m-0 space-y-1 pl-5 list-disc",children:[n("li",{children:"You can use API keys for a variety of models"}),n("li",{children:"Faster analysis processing"}),n("li",{children:"Better handling of complex code structures"}),n("li",{children:"Improved scenario generation quality"})]})]}),n(oe,{to:"/settings",className:"inline-block px-4 py-2 bg-blue-600 text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-blue-700",children:"🔐 Configure API Keys"})]})}),n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:c("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),c("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xl font-semibold text-red-800 m-0 mb-3",children:"Capture Failed"}),n("p",{className:"text-sm text-red-700 m-0 mb-4",children:"An error occurred while capturing this scenario. No screenshot is available."}),c("div",{className:"bg-white border border-red-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-red-800 m-0 mb-2 uppercase tracking-wide",children:"Error Message"}),n("div",{className:"max-h-[300px] overflow-auto",children:n("p",{className:"text-sm text-red-900 m-0 font-mono whitespace-pre-wrap wrap-break-word",children:O})})]}),H&&c("details",{className:"mt-4",children:[n("summary",{className:"text-sm text-red-700 cursor-pointer hover:text-red-900 font-semibold",children:"📋 View full stack trace"}),n("div",{className:"mt-3 bg-white border border-red-200 rounded p-4 overflow-auto",children:n("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:H})})]}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(Wt,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})]}):D.length>0?n("div",{className:"w-full h-full flex items-center justify-center overflow-auto",children:n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:c("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),c("div",{className:"flex-1 min-w-0",children:[n(AnalysisErrorDisplay,{errors:D,title:"Analysis Error",description:D.length===1?"An error occurred during analysis. Screenshot capture was not completed.":`${D.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(Wt,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})}):c("div",{className:"flex flex-col items-center gap-4 text-center",children:[n("span",{className:"text-6xl text-gray-300",children:"📷"}),n("p",{className:"text-lg text-gray-500 m-0",children:"No screenshot available for this scenario"}),n("p",{className:"text-sm text-gray-400 m-0",children:"Try recapturing or debugging this scenario"})]})})})}),p&&l&&n(Rt,{projectSlug:l,onClose:()=>f(!1)}),g&&n(Rs,{width:b.width,height:b.height??900,onSave:_,onCancel:()=>y(!1)})]})}function xn(e){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="object")try{return JSON.stringify(e)}catch{return"[complex object]"}return String(e)}function Da(e,t=15){const r=xn(e);return r.length>t?r.slice(0,t)+"...":r}function Lh({analysis:e,entitySha:t}){const r=ht(),[a,s]=j(e);ne(()=>{s(e)},[e]);const[o,i]=j(!1),[l,d]=j(null),[h,u]=j({}),[m,p]=j(null),f=se(()=>{var C;if(!((C=a==null?void 0:a.metadata)!=null&&C.keyAttributes)||!(a!=null&&a.scenarios))return null;const v=a.scenarios.filter(k=>{var A;return!((A=k.metadata)!=null&&A.sameAsDefault)});return Os(a.metadata.keyAttributes,v)},[a]),g=se(()=>f?ld(f):[],[f]),y=se(()=>a!=null&&a.scenarios?a.scenarios.filter(v=>{var C;return!((C=v.metadata)!=null&&C.sameAsDefault)}):[],[a]),b=re(v=>{if(!f)return[];const C=f.scenariosWithStructuredRefs.find(k=>k.scenario.id===v.id);return(C==null?void 0:C.usedAttributes)||[]},[f]),x=re(async(v,C)=>{var P;if(!a)return;const k=`${v}-${C}`,A=(P=h[k])==null?void 0:P.trim();if(A){i(!0),d(null);try{const M=await fetch("/api/update-valid-values",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"add",analysisId:a.id,analysis:a,keyAttributeIndex:v,valueType:C,value:A})}),I=await M.json();if(!M.ok||!I.success)throw new Error(I.error||"Failed to add value");s(I.analysis),u(N=>({...N,[k]:""})),r.revalidate()}catch(M){d(M instanceof Error?M.message:String(M))}finally{i(!1)}}},[a,h,r]),w=re(async(v,C,k)=>{if(a){i(!0),d(null);try{const A=await fetch("/api/update-valid-values",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"remove",analysisId:a.id,analysis:a,keyAttributeIndex:v,valueType:C,value:"",valueIndex:k})}),P=await A.json();if(!A.ok||!P.success)throw new Error(P.error||"Failed to remove value");s(P.analysis),r.revalidate()}catch(A){d(A instanceof Error?A.message:String(A))}finally{i(!1)}}},[a,r]);return a?!f||f.keyAttributes.length===0?n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#fafafa]",children:c("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Key Attributes"}),n("p",{className:"text-sm",children:"Re-analyze this entity to generate key attributes."})]})}):n("div",{className:"flex-1 overflow-auto bg-[#fafafa]",children:c("div",{className:"p-6 space-y-6",children:[c("div",{className:"bg-white border border-gray-200 rounded-lg p-4",children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0 mb-3",children:"Scenarios Breakdown"}),c("div",{className:"grid grid-cols-4 gap-4 text-center",children:[c("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:y.length}),n("div",{className:"text-xs text-gray-500",children:"Scenarios"})]}),c("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:f.keyAttributes.length}),n("div",{className:"text-xs text-gray-500",children:"Key Attributes"})]}),c("div",{className:"bg-gray-50 rounded-lg p-3",children:[c("div",{className:"text-2xl font-bold text-gray-900",children:[f.usedValidValues,"/",f.totalValidValues]}),n("div",{className:"text-xs text-gray-500",children:"Values Used"})]}),c("div",{className:"bg-gray-50 rounded-lg p-3",children:[c("div",{className:`text-2xl font-bold ${f.coveragePercentage===100?"text-green-600":f.coveragePercentage>=50?"text-amber-600":"text-red-600"}`,children:[f.coveragePercentage.toFixed(0),"%"]}),n("div",{className:"text-xs text-gray-500",children:"Coverage"})]})]})]}),l&&c("div",{className:"p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700",children:[l,n("button",{onClick:()=>d(null),className:"ml-2 text-red-500 hover:underline",children:"Dismiss"})]}),c("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:c("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Scenarios (",y.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:y.length===0?c("div",{className:"p-4 text-center text-gray-500 text-sm",children:["No scenarios yet."," ",n(oe,{to:`/entity/${t}/create-scenario`,className:"text-blue-600 hover:underline",children:"Create one"})]}):y.map(v=>{var A,P,M;const C=(P=(A=v.metadata)==null?void 0:A.screenshotPaths)==null?void 0:P[0],k=b(v);return c("div",{className:"p-4 flex gap-4",children:[n("div",{className:"w-72 h-40 shrink-0 bg-gray-100 rounded overflow-hidden flex items-start justify-center",children:n(Fe,{screenshotPath:C,alt:v.name||"Scenario screenshot",className:"max-w-full max-h-full object-contain object-top"})}),c("div",{className:"flex-1 min-w-0",children:[n("div",{className:"flex items-start justify-between gap-2",children:c("div",{children:[n(oe,{to:`/entity/${t}/scenarios/${v.id}`,className:"font-medium text-gray-900 hover:text-blue-600 no-underline text-sm",children:v.name}),((M=v.metadata)==null?void 0:M.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:v.description}),k.length>0&&n("div",{className:"flex flex-wrap gap-1 mt-2",children:k.map((I,N)=>c("span",{className:`text-xs px-1.5 py-0.5 rounded ${I.isError?"bg-red-50 text-red-700":"bg-blue-50 text-blue-700"}`,children:[String(I.path).split(".").pop(),"=",Da(I.value)]},N))})]})]},v.id)})}),n("div",{className:"px-4 py-3 border-t border-gray-100 bg-gray-50",children:c(oe,{to:`/entity/${t}/create-scenario`,className:"w-full px-4 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 flex items-center justify-center gap-2 no-underline",children:[n("span",{className:"text-lg leading-none",children:"+"}),"Add Scenario"]})})]}),g.length>0&&c("div",{className:"p-3 bg-amber-50 border border-amber-200 rounded-lg",children:[c("p",{className:"text-sm text-amber-800 font-medium mb-2",children:[g.length," unused value",g.length>1?"s":""," — consider adding scenarios to cover these"]}),c("div",{className:"flex flex-wrap gap-1",children:[g.slice(0,10).map((v,C)=>c("span",{className:"text-xs px-2 py-0.5 bg-amber-100 text-amber-700 rounded",children:[String(v.path).split(".").pop(),"=",Da(v.value,20)]},C)),g.length>10&&c("span",{className:"text-xs text-amber-600",children:["+",g.length-10," more"]})]})]}),c("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:c("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Key Attributes (",f.keyAttributes.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:f.keyAttributes.map((v,C)=>{var M;const k=m===v.path,A=v.validValues.filter(I=>I.usedInScenarios.length>0).length,P=v.validValues.length;return c("div",{children:[n("button",{onClick:()=>p(k?null:v.path),className:"w-full px-4 py-3 flex items-start justify-between text-left bg-transparent border-none cursor-pointer hover:bg-gray-50",children:c("div",{className:"flex items-start gap-3 flex-1",children:[n("span",{className:"text-gray-400 text-sm mt-0.5 shrink-0",children:k?"▼":"▶"}),c("div",{className:"flex-1",children:[c("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-mono text-sm font-medium text-gray-900",children:String(v.localVariable)}),c("span",{className:`text-xs px-2 py-0.5 rounded ${A===P?"bg-green-100 text-green-700":A>0?"bg-amber-100 text-amber-700":"bg-gray-100 text-gray-600"}`,children:[A,"/",P," covered"]})]}),v.description&&n("p",{className:"text-sm text-gray-600 mt-1 m-0",children:String(v.description)})]})]})}),k&&c("div",{className:"border-t border-gray-100 px-4 py-3 bg-gray-50/50",children:[c("div",{className:"space-y-2",children:[v.validValues.map(I=>{const N=I.usedInScenarios.length>0;return c("div",{className:"flex items-start gap-3 py-1",children:[n("div",{className:`w-4 h-4 mt-0.5 rounded border flex items-center justify-center shrink-0 ${N?"bg-green-500 border-green-500":"bg-white border-gray-300"}`,children:N&&n("svg",{className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2",children:[n("span",{className:"font-mono text-sm text-gray-800",children:xn(I.value)}),!N&&n("button",{onClick:()=>{w(C,"validValueOptions",I.index)},disabled:o,className:"text-gray-400 hover:text-red-500 text-xs disabled:opacity-50",title:"Remove value",children:"✕"})]}),N&&n("div",{className:"flex flex-wrap gap-1 mt-1",children:I.usedInScenarios.map(($,_)=>n("span",{className:"text-xs px-1.5 py-0.5 bg-gray-100 text-gray-600 rounded",children:String($.name)},_))})]})]},I.index)}),c("div",{className:"flex items-center gap-2 pt-2 border-t border-gray-200 mt-2",children:[n("input",{type:"text",value:h[`${C}-validValueOptions`]||"",onChange:I=>u(N=>({...N,[`${C}-validValueOptions`]:I.target.value})),placeholder:"Add value...",className:"flex-1 text-sm px-2 py-1 border border-gray-200 rounded focus:border-blue-400 focus:outline-none",disabled:o,onKeyDown:I=>{I.key==="Enter"&&x(C,"validValueOptions")}}),n("button",{onClick:()=>{x(C,"validValueOptions")},disabled:o||!((M=h[`${C}-validValueOptions`])!=null&&M.trim()),className:"text-xs px-2 py-1 bg-gray-100 text-gray-700 rounded hover:bg-gray-200 disabled:opacity-50 disabled:cursor-not-allowed",children:"Add"})]})]}),v.errorValues.length>0&&c("div",{className:"mt-4 pt-3 border-t border-gray-200",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Error Values"}),n("div",{className:"space-y-2",children:v.errorValues.map(I=>{const N=I.usedInScenarios.length>0;return c("div",{className:"flex items-start gap-3 py-1",children:[n("div",{className:`w-4 h-4 mt-0.5 rounded border flex items-center justify-center shrink-0 ${N?"bg-red-500 border-red-500":"bg-white border-gray-300"}`,children:N&&n("svg",{className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})}),c("div",{className:"flex-1",children:[n("span",{className:"font-mono text-sm text-gray-800",children:xn(I.value)}),N&&n("div",{className:"flex flex-wrap gap-1 mt-1",children:I.usedInScenarios.map(($,_)=>n("span",{className:"text-xs px-1.5 py-0.5 bg-red-50 text-red-600 rounded",children:String($.name)},_))})]})]},I.index)})})]}),v.dependencies&&v.dependencies.length>0&&c("div",{className:"mt-4 pt-3 border-t border-gray-200",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Required for this attribute to have effect:"}),n("div",{className:"space-y-1.5",children:v.dependencies.map((I,N)=>c("div",{className:"flex items-start gap-2 text-xs",children:[n("span",{className:"text-amber-500 mt-0.5",children:"⚠"}),c("div",{children:[n("code",{className:"font-mono text-gray-800 bg-gray-100 px-1 py-0.5 rounded",children:String(I.path)}),n("span",{className:"text-gray-500 mx-1",children:"="}),n("code",{className:"font-mono text-blue-700 bg-blue-50 px-1 py-0.5 rounded",children:xn(I.requiredValue)}),I.description&&n("span",{className:"text-gray-500 ml-2",children:String(I.description)})]})]},N))})]}),v.sourceLocations&&v.sourceLocations.length>0&&c("div",{className:"mt-4 pt-3 border-t border-gray-200",children:[c("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:["Source Locations (",v.sourceLocations.length,")"]}),n("div",{className:"space-y-2",children:v.sourceLocations.map((I,N)=>c("div",{className:"bg-white rounded-lg p-2 border border-gray-200",children:[c("div",{className:"flex items-center gap-2 text-xs text-gray-600 mb-1",children:[n("span",{className:"font-medium",children:String(I.entityName)}),n("span",{className:"text-gray-400",children:"|"}),c("span",{children:["Line ",I.lineNumber]}),n("span",{className:"text-gray-400",children:"|"}),n("span",{className:"capitalize px-1.5 py-0.5 bg-blue-50 text-blue-700 rounded",children:I.usageType})]}),n("pre",{className:"text-xs bg-gray-900 text-gray-100 p-2 rounded overflow-x-auto font-mono whitespace-pre-wrap",children:n("code",{children:String(I.codeSnippet)})}),I.description&&n("p",{className:"text-xs text-gray-500 mt-1 italic m-0",children:String(I.description)})]},N))})]})]})]},v.path)})})]}),f.scenariosWithoutStructuredRefs.length>0&&c("div",{className:"text-xs text-gray-500 p-3 bg-gray-50 rounded-lg",children:[n("strong",{children:"Note:"})," ",f.scenariosWithoutStructuredRefs.length," scenario(s) don't have structured value references. Re-analyze to update coverage tracking."]})]})}):n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#fafafa]",children:c("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Analysis Found"}),n("p",{className:"text-sm",children:"Analyze this entity to see the scenarios breakdown."})]})})}function La({hasIndirectBadge:e,onAnalyze:t}){return c(ue,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:c("div",{className:"flex items-center justify-end gap-2",children:[e&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:"0 scenarios"})]})}),c("div",{className:"px-5 py-5 bg-white rounded-bl-lg rounded-br-lg flex items-center justify-between",children:[n("p",{className:"text-sm font-normal text-[#8e8e8e] m-0 leading-[22px]",children:"No analyses available for this version."}),n("button",{className:"px-[15px] py-0 h-[23px] bg-[#005c75] text-white rounded text-xs font-medium leading-5 border-none cursor-pointer hover:bg-[#004a5e] transition-colors flex items-center justify-center",onClick:t,children:"Analyze"})]})]})}function Oh({entity:e,history:t}){const[r,a]=j("entity"),[s,o]=j(new Set),i=t.filter(u=>u.analyses.length>0).length,l=se(()=>{const u=new Map;return t.forEach(m=>{m.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:m,analysis:p,scenario:g})})})}),Array.from(u.entries()).map(([m,p])=>{var f;return{name:m,description:((f=p[0])==null?void 0:f.scenario.description)||"",versions:p.sort((g,y)=>{const b=new Date(g.analysis.createdAt||0).getTime();return new Date(y.analysis.createdAt||0).getTime()-b})}})},[t]),d=l.length,h=u=>{o(m=>{const p=new Set(m);return p.has(u)?p.delete(u):p.add(u),p})};return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto",children:c("div",{className:"max-w-[1400px] mx-auto px-8 py-8",children:[n("div",{className:"mb-8",children:c("div",{className:"flex items-center gap-6 border-b-2 border-[#e1e1e1]",children:[c("button",{onClick:()=>a("entity"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${r==="entity"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"text-base font-semibold leading-6",children:"Entity History"}),n("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${r==="entity"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:i})]}),c("button",{onClick:()=>a("scenarios"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${r==="scenarios"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"text-base font-normal leading-6",children:"Scenario Changes"}),n("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${r==="scenarios"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:d})]})]})}),t.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No history available"})}):r==="entity"?c("div",{className:"relative pl-12",children:[t.length>1&&n("div",{className:"absolute left-[17.5px] top-10 bottom-10 w-px bg-[#c7c7c7]"}),t.map((u,m)=>c("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[19px] w-[11.5px] h-[11.5px] rounded-full bg-[#00925d]"}),c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-3 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center gap-3",children:[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"}),c(oe,{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(b=>{var x;return!((x=b.metadata)!=null&&x.sameAsDefault)});return n("div",{children:g.length===0?n(La,{hasIndirectBadge:p.indirect,onAnalyze:()=>{console.log("Analyze version:",u.sha)}}):c(ue,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:c("div",{className:"flex items-center justify-end gap-2",children:[p.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),c("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:[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:c("p",{className:"text-sm text-[#005c75] m-0 leading-[22px]",children:[c("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((b,x)=>{var C,k;const w=(k=(C=b.metadata)==null?void 0:C.screenshotPaths)==null?void 0:k[0],v=`${b.name}-${x}`;return c(oe,{to:`/entity/${u.sha}/scenarios/${b.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:w?n(Fe,{screenshotPath:w,alt:b.name,className:"max-w-full max-h-full object-contain rounded-sm"}):c("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No Screenshot"})]})}),n("div",{className:"p-[5.6px]",children:n("p",{className:"text-[10.2px] font-medium text-[#343434] m-0 leading-[13px] line-clamp-3",children:b.name})})]},v)})})})]})},p.id||f)})}):n(La,{onAnalyze:()=>{console.log("Analyze version:",u.sha)}})]})]},u.sha))]}):n("div",{className:"relative pl-12",children:l.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No scenarios found"})}):l.map((u,m)=>{const 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,c("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[42px] w-[13.26px] h-[13.26px] rounded-full bg-[#00925d]"}),c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[c("div",{className:"px-5 py-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:[n("h3",{className:"text-base font-semibold text-[#232323] m-0 mb-1 leading-6",children:u.name}),u.description&&n("p",{className:"text-sm font-normal text-[#626262] m-0 leading-[22px]",children:u.description})]}),c("div",{className:"p-5 bg-white",children:[f.map((b,x)=>{var P,M;const{version:w,analysis:v,scenario:C}=b,k=(M=(P=C.metadata)==null?void 0:P.screenshotPaths)==null?void 0:M[0],A=x===0;return c("div",{className:`flex gap-5 items-start ${A?"":"mt-5 pt-5 border-t border-[#e1e1e1]"}`,children:[n(oe,{to:`/entity/${w.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(Fe,{screenshotPath:k,alt:C.name,className:"max-w-full max-h-full object-contain rounded-sm"}):c("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No screenshot"})]})}),c("div",{className:"flex-1 flex flex-col gap-2",children:[c("div",{className:"flex items-center gap-2 flex-wrap",children:[w.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"}),A&&u.versions.length>1&&c("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#e0e9ec] text-[#005c75] rounded text-xs font-medium leading-5",children:[u.versions.length," versions"]})]}),c(oe,{to:`/entity/${w.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:w.sha.substring(0,8)})]}),v.createdAt&&c("p",{className:"text-xs font-medium text-[#8e8e8e] m-0 leading-[22px]",children:["Captured:"," ",new Date(v.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})]}),v.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"})]})]},`${w.sha}-${x}`)}),g>0&&c("button",{onClick:()=>h(u.name),className:"mt-5 flex items-center gap-2 text-sm text-[#005c75] bg-transparent border-none cursor-pointer p-0 hover:underline",children:[n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",className:`transition-transform ${p?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),p?"Hide":`${g} previous version${g!==1?"s":""}`]})]})]})]},u.name)})})]})})}function Oa({entity:e,analysisInfo:t,from:r}){const a=ke(),s=a.state!=="idle",o=e.entityType==="visual"||e.entityType==="library",i=l=>{l.preventDefault(),l.stopPropagation(),o&&a.submit({entitySha:e.sha,filePath:e.filePath},{method:"post",action:"/api/analyze"})};return n(oe,{to:`/entity/${e.sha}${r?`?from=${r}`:""}`,className:"block group cursor-pointer",children:c("div",{className:"flex gap-0 border border-gray-200 rounded-lg overflow-hidden transition-all hover:border-[#005c75] hover:shadow-md bg-white h-[100px]",children:[e.screenshotPath?n("div",{className:"w-[125px] h-full bg-gray-50 flex items-center justify-center shrink-0 rounded-bl-[8px] rounded-tl-[8px] border-r border-gray-200",children:n(Fe,{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(Ue,{type:e.entityType})})}),c("div",{className:"flex-1 flex items-center justify-between px-4 min-w-0",children:[c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(Ue,{type:e.entityType}),n("div",{className:"text-base font-medium text-black truncate group-hover:text-[#005c75] transition-colors",children:e.name})]}),n("div",{className:"text-[10px] text-[#8e8e8e] truncate mb-1 font-mono",title:e.filePath,children:e.filePath}),t.hasScenarios&&c("div",{className:"flex items-center gap-2 mt-2",children:[c("span",{className:"px-[5px] py-0 bg-[#efefef] text-[#3e3e3e] rounded text-[10px] font-medium",children:[t.scenarioCount," scenarios"]}),n("span",{className:"text-xs text-[#8e8e8e]",children:t.timestamp})]})]}),n("div",{className:"shrink-0 ml-4",children:t.status==="not_analyzed"?c(ue,{children:[c("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f9f9f9] border border-[#e1e1e1] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#c7c7c7]"}),n("span",{className:"text-[10px] font-semibold text-[#646464]",children:"Not analyzed"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${s?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:s,children:s?"Analyzing...":"Analyze"})]}):t.status==="up_to_date"?c("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f2fcf9] border border-[#c8f2e3] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#00925d]"}),n("span",{className:"text-[10px] font-semibold text-[#00925d]",children:"Up to date"})]}):c(ue,{children:[c("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#e0e9ec] border border-[#e0e9ec] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#005c75]"}),n("span",{className:"text-[10px] font-semibold text-[#005c75]",children:"Out of date"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${s?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:s,children:s?"Analyzing...":"Analyze"})]})})]})]})},e.sha)}const Fa=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 Fh({importedEntities:e,importingEntities:t}){const[r]=qt(),a=r.get("from"),s=ke(),o=s.state!=="idle",i=e.length>0,l=t.length>0,d=p=>p.filter(f=>f.entityType==="visual"||f.entityType==="library"),h=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,m=d(t).length>0;return n("div",{className:"max-w-[1400px] mx-auto",children:c("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[c("div",{className:"px-6 py-4 flex items-start justify-between",children:[c("div",{children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imports"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#deeafc] text-[#2f80ed] rounded-[9.095px] text-xs font-semibold leading-5",children:e.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities imported by this component."})]}),u&&n("button",{onClick:()=>h(e),disabled:o,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:o?"Analyzing...":"Analyze All"})]}),i?n("div",{className:"p-6 space-y-4",children:e.map(p=>n(Oa,{entity:p,analysisInfo:Fa(p),from:a},p.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"No imports."})})]}),c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[c("div",{className:"px-6 py-4 flex items-start justify-between",children:[c("div",{children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imported By"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#f3eefe] text-[#9b51e0] rounded-[9.095px] text-xs font-semibold leading-5",children:t.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities that import this component."})]}),m&&n("button",{onClick:()=>h(t),disabled:o,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:o?"Analyzing...":"Analyze All"})]}),l?n("div",{className:"p-6 space-y-4",children:t.map(p=>n(Oa,{entity:p,analysisInfo:Fa(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 Yh({relatedEntities:e}){return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:n(Fh,{importedEntities:e.importedEntities,importingEntities:e.importingEntities})})}function zh({data:e,defaultExpanded:t=!1,maxDepth:r=3}){return n("div",{className:"font-mono text-sm",children:n(Jt,{data:e,depth:0,defaultExpanded:t,maxDepth:r})})}function Jt({data:e,depth:t,defaultExpanded:r,maxDepth:a,objectKey:s,showInlineToggle:o=!1}){const[i,l]=j(r||t<2);if(ne(()=>{l(r||t<2)},[r,t]),e===null)return n("span",{className:"text-gray-500",children:"null"});if(e===void 0)return n("span",{className:"text-gray-500",children:"undefined"});const d=typeof e;if(d==="string")return c("span",{className:"text-green-600",children:['"',e,'"']});if(d==="number")return n("span",{className:"text-blue-600",children:e});if(d==="boolean")return n("span",{className:"text-purple-600",children:e.toString()});if(Array.isArray(e))return e.length===0?n("span",{className:"text-gray-600",children:"[]"}):c("span",{children:[c("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>l(!i),children:[c("span",{children:[i?"▼":"▶"," ","["]}),!i&&c("span",{children:[e.length,"]"]})]}),i?c(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:e.map((h,u)=>n("div",{className:"py-0.5",children:n(Jt,{data:h,depth:t+1,defaultExpanded:r,maxDepth:a})},u))}),n("div",{className:"text-gray-600",children:"]"})]}):null]});if(d==="object"){const h=Object.keys(e);if(h.length===0)return n("span",{className:"text-gray-600",children:"{}"});const u=p=>p!==null&&typeof p=="object"&&!Array.isArray(p)&&Object.keys(p).length>0,m=p=>Array.isArray(p)&&p.length>0;return c("span",{children:[c("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>l(!i),children:[c("span",{children:[i?"▼":"▶"," ","{"]}),!i&&c("span",{children:[h.length,"}"]})]}),i?c(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:h.map(p=>{const f=e[p],g=u(f),y=m(f);return n("div",{className:"py-0.5",children:g?n($r,{propertyKey:p,value:f,depth:t,defaultExpanded:r,maxDepth:a}):y?n(Dr,{propertyKey:p,value:f,depth:t,defaultExpanded:r,maxDepth:a}):c(ue,{children:[c("span",{className:"text-orange-600",children:[p,": "]}),n(Jt,{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 $r({propertyKey:e,value:t,depth:r,defaultExpanded:a,maxDepth:s}){const[o,i]=j(a||r<2),l=Object.keys(t);return ne(()=>{i(a||r<2)},[a,r]),c(ue,{children:[c("button",{className:"cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded inline-flex items-baseline",style:{marginLeft:"-14px"},onClick:()=>i(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),c("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"{"}),!o&&c("span",{className:"text-gray-600",children:[l.length,"}"]})]}),o&&c(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:l.map(d=>{const h=t[d],u=h!==null&&typeof h=="object"&&!Array.isArray(h)&&Object.keys(h).length>0,m=Array.isArray(h)&&h.length>0;return n("div",{className:"py-0.5",children:u?n($r,{propertyKey:d,value:h,depth:r+1,defaultExpanded:a,maxDepth:s}):m?n(Dr,{propertyKey:d,value:h,depth:r+1,defaultExpanded:a,maxDepth:s}):c(ue,{children:[c("span",{className:"text-orange-600",children:[d,": "]}),n(Jt,{data:h,depth:r+2,defaultExpanded:a,maxDepth:s})]})},d)})}),n("div",{className:"text-gray-600",children:"}"})]})]})}function Dr({propertyKey:e,value:t,depth:r,defaultExpanded:a,maxDepth:s}){const[o,i]=j(a||r<2);return ne(()=>{i(a||r<2)},[a,r]),c(ue,{children:[c("button",{className:"cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded inline-flex items-baseline",style:{marginLeft:"-14px"},onClick:()=>i(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),c("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"["}),!o&&c("span",{className:"text-gray-600",children:[t.length,"]"]})]}),o&&c(ue,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:t.map((l,d)=>{const h=l!==null&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,u=Array.isArray(l)&&l.length>0;return n("div",{className:"py-0.5",children:h?n($r,{propertyKey:d.toString(),value:l,depth:r+1,defaultExpanded:a,maxDepth:s}):u?n(Dr,{propertyKey:d.toString(),value:l,depth:r+1,defaultExpanded:a,maxDepth:s}):n(Jt,{data:l,depth:r+2,defaultExpanded:a,maxDepth:s})},d)})}),n("div",{className:"text-gray-600",children:"]"})]})]})}function tr({label:e,count:t,isActive:r,onClick:a,badgeColorActive:s,badgeTextActive:o}){return c("button",{onClick:a,className:`px-6 py-3 text-sm font-medium relative transition-colors cursor-pointer ${r?"text-[#005c75]":"text-[#3e3e3e] hover:text-gray-900 hover:bg-gray-50"}`,children:[e,t!==void 0&&n("span",{className:`ml-2 px-2 py-0.5 rounded-full text-xs font-semibold ${r?`${s} ${o}`:"bg-gray-200 text-gray-700"}`,children:t}),r&&n("div",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-[#005c75]"})]})}function Ya({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 za({call:e,scenarioName:t}){const[r,a]=j(!1),[s,o]=j("system"),i=p=>new Date(p).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),l=p=>p?`$${p.toFixed(4)}`:null,d=(p,f)=>{if(!p&&!f)return null;const g=[];return p&&g.push(`${p.toLocaleString()} in`),f&&g.push(`${f.toLocaleString()} out`),g.join(" / ")},h=se(()=>{var p,f,g,y,b;try{const x=JSON.parse(e.response);return(g=(f=(p=x.choices)==null?void 0:p[0])==null?void 0:f.message)!=null&&g.content?x.choices[0].message.content:(b=(y=x.content)==null?void 0:y[0])!=null&&b.text?x.content[0].text:e.response}catch{return e.response}},[e.response]),u=se(()=>{try{return JSON.stringify(JSON.parse(e.props),null,2)}catch{return e.props}},[e.props]),m=se(()=>{var p;if(t)return t;try{const f=JSON.parse(e.props);return((p=f==null?void 0:f.scenario)==null?void 0:p.name)||null}catch{return null}},[e.props,t]);return c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-4 bg-[#f6f9fc] border-b border-[#e1e1e1] cursor-pointer hover:bg-[#edf2f7] transition-colors",onClick:()=>a(!r),children:c("div",{className:"flex items-start justify-between gap-4",children:[c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#005c75] text-white rounded text-[11px] font-medium",children:e.prompt_type}),n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-[11px] font-medium",children:e.model}),m&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-[11px] font-medium",children:m}),e.error&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-[11px] font-medium",children:"Error"})]}),c("div",{className:"flex items-center gap-4 text-xs text-[#626262]",children:[n("span",{children:i(e.created_at)}),d(e.input_tokens,e.output_tokens)&&n("span",{children:d(e.input_tokens,e.output_tokens)}),l(e.cost)&&n("span",{className:"text-[#005c75] font-medium",children:l(e.cost)})]}),c("div",{className:"text-[11px] text-[#8a8a8a] font-mono mt-1",children:[".codeyam/llm-calls/",e.object_id,"_",e.id,".json"]})]}),n("svg",{width:"20",height:"20",viewBox:"0 0 16 16",fill:"none",className:`transition-transform shrink-0 ${r?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"#626262",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})}),r&&c("div",{className:"border-t border-[#e1e1e1]",children:[c("div",{className:"flex border-b border-[#e1e1e1] bg-[#fafafa]",children:[n("button",{onClick:()=>o("system"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${s==="system"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"System"}),n("button",{onClick:()=>o("prompt"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${s==="prompt"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Prompt"}),n("button",{onClick:()=>o("response"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${s==="response"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Response"}),n("button",{onClick:()=>o("props"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${s==="props"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Context"})]}),s&&c("div",{className:"p-4 bg-white max-h-[400px] overflow-auto",children:[s==="system"&&n("div",{children:e.system_message?n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.system_message}):n("p",{className:"text-xs text-[#626262] italic m-0",children:"No system message"})}),s==="prompt"&&n("div",{children:n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.prompt_text})}),s==="response"&&c("div",{children:[e.error&&c("div",{className:"mb-4 p-3 bg-[#fef2f2] border border-[#fecaca] rounded",children:[n("h4",{className:"text-xs font-semibold text-[#dc2626] uppercase mb-1",children:"Error"}),n("p",{className:"text-xs text-[#dc2626] m-0",children:e.error})]}),n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:h})]}),s==="props"&&n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:u})]}),e.error&&!s&&n("div",{className:"p-4 bg-[#fef2f2] border-t border-[#fecaca]",children:c("p",{className:"text-xs text-[#dc2626] m-0",children:[n("span",{className:"font-semibold",children:"Error: "}),e.error]})})]})]})}const Ba=["generateEntityScenarios","analyzeEntity","generateDataStructure","generateEntityDescription"];function Bh({entity:e,analysis:t,scenarios:r,onAnalyze:a,llmCalls:s}){var v,C,k,A,P,M,I,N,$;const[o,i]=j("entity"),[l,d]=j("isolatedDataStructure"),[h,u]=j(r.length>0?{scenarioId:r[0].id||r[0].name}:null),[m,p]=j("entity"),{entityLlmCalls:f,scenarioLlmCalls:g,totalLlmCalls:y}=se(()=>{if(!s)return{entityLlmCalls:[],scenarioLlmCalls:[],totalLlmCalls:0};const _=[...s.entityCalls,...s.analysisCalls],S=_.filter(R=>R.object_type==="entity"||Ba.includes(R.prompt_type)),E=_.filter(R=>R.object_type!=="entity"&&!Ba.includes(R.prompt_type));return S.sort((R,D)=>D.created_at-R.created_at),E.sort((R,D)=>D.created_at-R.created_at),{entityLlmCalls:S,scenarioLlmCalls:E,totalLlmCalls:_.length}},[s]),b=[{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:(v=e==null?void 0:e.metadata)==null?void 0:v.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:(A=(k=e==null?void 0:e.metadata)==null?void 0:k.isolatedDataStructure)==null?void 0:A.conditionalUsages,description:"Attributes used in conditionals (if, ternary, switch, &&) - candidates for key attributes"},{id:"keyAttributes",title:"Key Attributes",data:(P=t==null?void 0:t.metadata)==null?void 0:P.keyAttributes,description:"Important attributes identified during analysis"},{id:"importedExports",title:"Imported Dependencies",data:{"Internal Dependencies":(M=e==null?void 0:e.metadata)==null?void 0:M.importedExports,"External Dependencies":(I=e==null?void 0:e.metadata)==null?void 0:I.nodeModuleImports},description:"Internal and external dependencies used by this entity"},{id:"scenariosDataStructure",title:"Scenarios Data Structure",data:(N=t==null?void 0:t.metadata)==null?void 0:N.scenariosDataStructure,description:"Structure template used across all scenarios"}],x=b.filter(_=>_.data!==void 0&&_.data!==null).length;let w=null;if(o==="entity"){const _=b.find(S=>S.id===l);_&&_.data!==void 0&&_.data!==null&&(w={title:_.title,description:_.description,data:_.data})}else if(o==="scenarios"&&h){const _=r.find(S=>(S.id||S.name)===h.scenarioId);_&&(w={title:_.name,description:_.description||"Scenario data and configuration",data:_.metadata})}return c("div",{className:"max-w-[1800px] mx-auto h-full flex flex-col",children:[n("div",{className:"mb-6 shrink-0",children:c("div",{className:"flex border-b border-gray-200 relative",children:[n(tr,{label:"Entity",isActive:o==="entity",onClick:()=>i("entity"),badgeColorActive:"bg-[#e0e9ec]",badgeTextActive:"text-[#005c75]"}),n(tr,{label:"Scenarios",count:r.length,isActive:o==="scenarios",onClick:()=>i("scenarios"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),n(tr,{label:"LLM Calls",count:y,isActive:o==="llm-calls",onClick:()=>i("llm-calls"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),(($=t==null?void 0:t.metadata)==null?void 0:$.analyzerVersion)&&c("div",{className:"ml-auto flex items-center text-xs text-gray-500",children:[n("span",{className:"font-medium",children:"Analyzer:"}),n("span",{className:"ml-1 font-mono",children:t.metadata.analyzerVersion})]})]})}),o==="llm-calls"?c("div",{className:"flex-1 min-h-0",children:[c("div",{className:"flex gap-4 mb-4",children:[c("button",{onClick:()=>p("entity"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${m==="entity"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Entity Calls (",f.length,")"]}),c("button",{onClick:()=>p("scenario"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${m==="scenario"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Scenario Calls (",g.length,")"]})]}),n("div",{className:"space-y-4 overflow-y-auto",style:{maxHeight:"calc(100vh - 350px)"},children:m==="entity"?f.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:n("p",{className:"text-gray-500 text-sm m-0",children:"No entity-level LLM calls found"})}):f.map(_=>n(za,{call:_},_.id)):g.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:n("p",{className:"text-gray-500 text-sm m-0",children:"No scenario-level LLM calls found"})}):g.map(_=>n(za,{call:_},_.id))})]}):c("div",{className:"grid grid-cols-[340px_1fr] gap-6 flex-1 min-h-0",children:[n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 overflow-y-auto",children:o==="entity"?c(ue,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"ENTITY SECTIONS"}),x===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No entity data available."}):n("nav",{className:"space-y-1",children:b.map(_=>{const S=_.data!==void 0&&_.data!==null;return n(Ya,{label:_.title,isActive:l===_.id,onClick:()=>d(_.id),disabled:!S},_.id)})})]}):c(ue,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"SCENARIOS"}),r.length===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No scenarios available."}):n("nav",{className:"space-y-1",children:r.map(_=>{const S=_.id||_.name,E=(h==null?void 0:h.scenarioId)===S;return n(Ya,{label:_.name,isActive:E,onClick:()=>u({scenarioId:S})},S)})})]})}),n("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:w?n(Uh,{title:w.title,description:w.description,data:w.data}):o==="scenarios"&&r.length===0?n(Ua,{title:"No Simulations Yet",description:"Analyze the code to create simulations and create test scenarios automatically.",onAnalyze:a}):o==="entity"?n(Ua,{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 Ua({title:e,description:t,onAnalyze:r}){return c("div",{className:"flex flex-col items-center justify-center h-full bg-[#f6f9fc]",children:[n("h2",{className:"text-[28px] font-semibold text-[#646464] leading-[40px] mb-2 text-center",children:e}),n("p",{className:"text-base text-[#646464] leading-6 mb-6 text-center max-w-[600px]",children:t}),r&&n("button",{onClick:r,className:"h-[54px] w-[183px] bg-[#005c75] text-white text-base font-medium rounded-lg border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]})}function Uh({title:e,description:t,data:r}){const[a,s]=j(!0),[o,i]=j("Copy JSON");return c(ue,{children:[c("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50",children:[n("h3",{className:"text-base font-semibold text-black m-0",children:e}),n("p",{className:"text-sm text-[#646464] mt-1 m-0",children:t})]}),c("div",{className:"px-6 py-4 bg-white flex justify-between items-center",children:[c("div",{className:"flex gap-2",children:[n("button",{onClick:()=>s(!0),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${a?"bg-[#005c75] text-white":"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]"}`,children:"Expand All"}),n("button",{onClick:()=>s(!1),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${a?"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]":"bg-[#005c75] text-white"}`,children:"Collapse All"})]}),n("button",{onClick:()=>{const d=JSON.stringify(r,null,2);navigator.clipboard.writeText(d),i("Copied!"),setTimeout(()=>i("Copy JSON"),2e3)},className:"px-4 h-8 bg-[#343434] hover:bg-[#232323] text-white text-sm font-medium rounded border-none cursor-pointer transition-colors whitespace-nowrap",children:o})]}),n("div",{className:"overflow-y-auto flex-1",children:n("div",{className:"p-6",children:r?n("div",{className:"bg-gray-50 rounded-lg p-3 overflow-x-auto",children:n(zh,{data:r,defaultExpanded:a,maxDepth:99})}):n("div",{className:"text-center py-12 text-gray-500",children:"No data available for this section"})})})]})}function Wh({entity:e,analysis:t,scenarios:r,onAnalyze:a}){const s=ke();return ne(()=>{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(Bh,{entity:e,analysis:t,scenarios:r,onAnalyze:a,llmCalls:s.data})})}function ur({content:e,label:t="Copy",copiedLabel:r="✓ Copied!",className:a="",duration:s=2e3,ariaLabel:o}){const[i,l]=j(!1),d=re(()=>{navigator.clipboard.writeText(e).then(()=>{l(!0),setTimeout(()=>l(!1),s)}).catch(h=>{console.error("Failed to copy:",h)})},[e,s]);return n("button",{onClick:d,className:`cursor-pointer ${a}`,disabled:i,"aria-label":o||(i?"Copied to clipboard":"Copy to clipboard"),"aria-live":"polite",children:i?r:t})}const Hh={margin:0,padding:"24px",backgroundColor:"#101827",fontSize:"14px",lineHeight:"1.5"},Vh={minWidth:"3em",paddingRight:"1em",color:"#6b7280",userSelect:"none"},Gh=2e3,Jh=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 qh({entity:e,entityCode:t}){return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:c("div",{className:"bg-white rounded-tl-lg rounded-tr-lg border border-gray-200 overflow-hidden",children:[c("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50 flex justify-between items-center",children:[c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0",children:"Source Code"}),n("p",{className:"text-xs text-[#646464] font-mono mt-1 m-0",children:e==null?void 0:e.filePath})]}),t&&n(ur,{content:t,label:"Copy Code",duration:Gh,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(hi,{language:Jh(e==null?void 0:e.filePath),style:mi,showLineNumbers:!0,customStyle:Hh,lineNumberStyle:Vh,children:t})}):n("div",{className:"p-12 text-center text-gray-500",children:"No code available"})})]})})}const Kh=({data:e})=>[{title:e!=null&&e.entity?`${e.entity.name} - CodeYam`:"Entity - CodeYam"},{name:"description",content:"View entity scenarios and screenshots"}];function Qh({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 Zh({params:e,request:t,context:r}){const{sha:a}=e;if(!a)throw new Response("Entity SHA is required",{status:400});const o=new URL(t.url).searchParams.get("from"),l=(e["*"]||"").split("/").filter(Boolean),d=l[0]||"scenarios",h=l[1]||null,u=l[2]||null,m=r.analysisQueue,p=m?m.getState():{paused:!1,jobs:[]},[f,g,y,b]=await Promise.all([At(a),ze(),kt(),Yl(pe()||process.cwd())]),x=f?await Er(f):null,w=f?await xs(f.sha):null;let v={importedEntities:[],importingEntities:[]},C=null,k=[];f&&(v=await bs(f),C=await vs(f),k=await Cs(f));const A=!!(f&&k.length>0&&k[0].sha!==f.sha),P=k.length>0?k[0].sha:null,M=!!(k.length>0&&k[0].analyses&&k[0].analyses.length>0),I=f?await ws(f):!1;return z({entity:f??void 0,analysis:x??void 0,currentEntityAnalysis:w??void 0,projectSlug:g,from:o,relatedEntities:v,entityCode:C??void 0,hasNewerVersion:A,newestEntitySha:P,newestVersionHasAnalysis:M,fileModifiedSinceEntity:I,history:k,tab:d,scenarioId:h,viewModeFromUrl:u,currentCommit:y,hasAnApiKey:b,queueState:p})}const Xh=We(function(){var Jr,qr,Kr,Qr,Zr,Xr,ea,ta,na,ra,aa,sa;const t=Ke(),s=(Va()["*"]||"").split("/").filter(Boolean),o=s[0]||"scenarios",i=s[1]||null,l=s[2]||null,d=t.entity,h=t.analysis,u=t.currentEntityAnalysis,m=u||h,p=t.projectSlug;t.from;const f=t.relatedEntities,g=t.entityCode,y=t.hasNewerVersion,b=t.newestEntitySha,x=t.newestVersionHasAnalysis,w=t.fileModifiedSinceEntity,v=t.history,C=t.currentCommit,k=t.hasAnApiKey,A=t.queueState;(Jr=m==null?void 0:m.status)==null||Jr.errors;const P=(m==null?void 0:m.scenarios)||[],M=P.filter(X=>{var de;return!((de=X.metadata)!=null&&de.sameAsDefault)}),I=P.filter(X=>{var de;return(de=X.metadata)==null?void 0:de.sameAsDefault}),N=It(),$=Pe(null);ne(()=>{$.current===null&&($.current=window.history.length)},[]);const _=()=>{if(typeof window>"u")return;const X=window.history.state;if(X===null||(X==null?void 0:X.idx)===void 0||(X==null?void 0:X.idx)===0)N("/");else{const de=window.history.length,xe=$.current;if(xe!==null&&de>xe){const ye=de-xe+1;N(-ye)}else N(-1)}},S=!!A.currentlyExecuting,E=o,R=(qr=C==null?void 0:C.metadata)==null?void 0:qr.currentRun,D=!!(R!=null&&R.createdAt)&&!(R!=null&&R.analysisCompletedAt),O=!!(d!=null&&d.sha&&((Kr=R==null?void 0:R.currentEntityShas)!=null&&Kr.includes(d.sha))),H=!!(d!=null&&d.sha&&((Zr=(Qr=A.currentlyExecuting)==null?void 0:Qr.entityShas)!=null&&Zr.includes(d.sha))),Q=!!(d!=null&&d.sha&&((Xr=A.jobs)!=null&&Xr.some(X=>{var de;return(de=X.entityShas)==null?void 0:de.includes(d.sha)}))),q=O||H||Q,L=q&&((ea=m==null?void 0:m.status)==null?void 0:ea.finishedAt)!=null&&M.length>0&&m.entitySha!==(d==null?void 0:d.sha),T=se(()=>{if(E!=="scenarios")return null;if(i){const X=M.find(de=>de.id===i);if(X)return X}return M.length>0&&!q?M[0]:null},[E,i,M,q]);Et({source:T?"scenario-page":"entity-page",entitySha:d==null?void 0:d.sha,scenarioId:T==null?void 0:T.id,analysisId:m==null?void 0:m.id});const[U,Y]=j(()=>l&&l!=="edit"?l:(d==null?void 0:d.entityType)==="library"?"data":"screenshot");ne(()=>{l&&l!==U&&l!=="edit"&&Y(l)},[l]);const V=l==="edit",[le,G]=j(!1),[B,W]=j(!1),[Z,F]=j(null),[te,ce]=j(!1),[he,fe]=j(!1),[Ce,Se]=j(null),[Ae,Ee]=j(null),[De,ge]=j(0),{interactiveServerUrl:Te,isStarting:je,isLoading:we,showIframe:nn,iframeKey:ie,onIframeLoad:Ve}=tn({analysisId:m==null?void 0:m.id,scenarioId:T==null?void 0:T.id,scenarioName:T==null?void 0:T.name,projectSlug:p,enabled:V&&!!T,refreshTrigger:De}),[Qe,Fn]=j(!1),[sp,op]=j(""),[rn,Ot]=j(!1),[zr,Yn]=j(Date.now()),[an,Br]=j(null),[Xs,sn]=j(!1),[eo,zn]=j(!1),nt=ke(),Be=ke(),gt=ke(),Ge=ke(),Le=ht(),Ur=A.jobs.some(X=>{var de;return(d==null?void 0:d.sha)&&((de=X.entityShas)==null?void 0:de.includes(d.sha))||X.type==="analysis"&&X.commitSha===(C==null?void 0:C.sha)&&X.entityShas&&X.entityShas.length===0}),Bn=q;(ta=d==null?void 0:d.metadata)!=null&&ta.defaultWidth||(na=m==null?void 0:m.metadata)!=null&&na.defaultWidth,nt.state==="submitting"||nt.state,se(()=>{var X;return!!((X=T==null?void 0:T.metadata)!=null&&X.interactiveExamplePath)},[T]);const{isCompleted:Wr}=mt(p,rn);ne(()=>{nt.state==="idle"&&nt.data&&(nt.data.success?setTimeout(()=>{Yn(Date.now()),Le.revalidate(),Ot(!1)},1500):nt.data.error&&(Ot(!1),alert(`Recapture failed: ${nt.data.error}`)))},[nt.state,nt.data,Le]),ne(()=>{rn&&Wr&&setTimeout(()=>{Yn(Date.now()),Le.revalidate(),Ot(!1)},1500)},[rn,Wr,Le]),ne(()=>{if(Be.state==="idle"&&Be.data)if(Be.data.success){Br(Be.data),sn(!0);const X=Be.data.jobId;if(X){const de=async()=>{try{const ye=await fetch("/api/queue?queryType=job&jobId="+encodeURIComponent(X));if(!ye.ok){const Xe=await ye.text();console.error("[Debug Setup] Poll failed with status",ye.status,":",Xe);return}(await ye.json()).status==="completed"&&(clearInterval(xe),Br(Xe=>{var lt,Oe;return Xe?{...Xe,complete:!0,instructions:{title:"Debug Environment Ready ✓",sections:((Oe=(lt=Xe.instructions)==null?void 0:lt.sections)==null?void 0:Oe.map(Ne=>Ne.heading==="Status"?{heading:"Status",items:[{content:"Setup complete! Your debug environment is ready."},...Ne.items.slice(1)]}:Ne.heading==="What's Happening"?null:Ne.heading==="Next Steps (Once Complete)"?{...Ne,heading:"Next Steps"}:Ne).filter(Boolean))||[]}}:null}))}catch(ye){console.error("[Debug Setup] Error polling queue:",ye)}},xe=setInterval(()=>{de().catch(()=>{})},2e3);return()=>{clearInterval(xe)}}else console.warn("[Debug Setup] No job ID returned from debug setup!")}else Be.data.error&&(console.error("[Debug Setup] Error:",Be.data.error),alert(`Debug setup failed: ${Be.data.error}`))},[Be.state,Be.data]),ne(()=>{gt.state==="idle"&&gt.data&&(gt.data.success?setTimeout(()=>{Yn(Date.now()),Le.revalidate(),Ot(!1)},1500):gt.data.error&&(Ot(!1),alert(`Recapture failed: ${gt.data.error}`)))},[gt.state,gt.data,Le]);const Un=()=>{d&&(y&&b&&b!==d.sha?(N(`/entity/${b}/scenarios`),setTimeout(()=>{Ge.submit({entitySha:b,filePath:d.filePath||""},{method:"post",action:"/api/analyze"})},100)):Ge.submit({entitySha:d.sha,filePath:d.filePath||""},{method:"post",action:"/api/analyze"}))};ne(()=>{Ge.state==="idle"&&Ge.data&&(Ge.data.success?Le.revalidate():Ge.data.error&&alert(`Analysis failed: ${Ge.data.error}`))},[Ge.state,Ge.data,d==null?void 0:d.sha,Le]),ne(()=>{const X=setTimeout(()=>{Le.revalidate()},500);return()=>clearTimeout(X)},[]),ne(()=>{if(D||Bn){const X=setInterval(()=>{Le.revalidate()},3e3);return()=>clearInterval(X)}else{const X=setInterval(()=>{Le.revalidate()},5e3),de=setTimeout(()=>{clearInterval(X)},3e4);return()=>{clearInterval(X),clearTimeout(de)}}},[D,Bn,Le]);const to=(X,de)=>X==="scenarios"?`/entity/${d==null?void 0:d.sha}/scenarios`:`/entity/${d==null?void 0:d.sha}/${X}`,no=(X,de)=>`/entity/${d==null?void 0:d.sha}/scenarios/${X}/${de}`,ro=X=>{Y(X),T!=null&&T.id&&(X==="interactive"?N(`/entity/${d==null?void 0:d.sha}/scenarios/${T.id}/fullscreen`,{replace:!0}):N(no(T.id,X),{replace:!0}))},ao=async X=>{var de,xe;if(console.log("[EntityDetail] ===== APPLY CHANGES CALLED =====",{description:X,hasSelectedScenario:!!T,hasAnalysis:!!m}),!T||!m){const ye="Error: No scenario or analysis available";console.error("[EntityDetail]",ye),F(ye);return}G(!0),F(null),console.log("[EntityDetail] Applying changes (preview mode)",{description:X,scenarioId:T.id,scenarioName:T.name,currentData:T.data});try{const ye=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:X,existingScenarios:m.scenarios,scenariosDataStructure:(de=m.metadata)==null?void 0:de.scenariosDataStructure,editingMockName:T.name,editingMockData:Ae||((xe=T.metadata)==null?void 0:xe.data)})}),Ze=await ye.json();if(!ye.ok||!Ze.success)throw new Error(Ze.error||"Failed to generate scenario data");console.log("[EntityDetail] Generated data:",Ze.data),Ee(Ze.data);const Xe=(m.scenarios||[]).map(Ne=>Ne.id===T.id?{...Ne,metadata:{...Ne.metadata,data:Ze.data}}:Ne),lt=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:m,scenarios:Xe})}),Oe=await lt.json();if(!lt.ok||!Oe.success)throw console.error("[EntityDetail] Temp save failed:",Oe),new Error(Oe.error||"Failed to apply preview");if(F("Generating preview. Capturing screenshot..."),Te){console.log("[EntityDetail] Using direct capture from running server",{serverUrl:Te});const Ne=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:Te,scenarioId:T.id,projectId:m.projectId,viewportWidth:1440})}),Ft=await Ne.json();!Ne.ok||!Ft.success?(console.error("[EntityDetail] Direct capture failed:",Ft),F("Preview applied. Screenshot capture failed.")):(console.log("[EntityDetail] Direct capture successful"),F('Preview applied. Click "Save Scenario Data" to persist.'))}else{console.log("[EntityDetail] No server running, using queued recapture");const Ne=new FormData;Ne.append("analysisId",m.id||""),Ne.append("scenarioId",T.id||"");const Ft=await fetch("/api/recapture-scenario",{method:"POST",body:Ne}),Wn=await Ft.json();!Ft.ok||!Wn.success?(console.warn("[EntityDetail] Recapture failed:",Wn.error),F("Preview applied. Screenshot recapture failed.")):(console.log("[EntityDetail] Recapture queued:",Wn.jobId),F('Preview applied. Screenshot will update shortly. Click "Save Scenario Data" to persist.'))}ge(Ne=>Ne+1),Le.revalidate()}catch(ye){console.error("Error applying changes:",ye),F(`Error: ${ye instanceof Error?ye.message:String(ye)}`)}finally{G(!1)}},so=async(X,de)=>{var xe;if(!T||!m){F("Error: No scenario or analysis available");return}W(!0),F(null),console.log("[EntityDetail] Saving scenario to database",{description:X,saveAsNew:de});try{const ye=Ae||((xe=T.metadata)==null?void 0:xe.data);let Ze;if(de){const Oe={...T,id:`${T.name}-${Date.now()}`,name:`${T.name} (Copy)`,metadata:{...T.metadata,data:ye},description:X||T.description};Ze=[...m.scenarios||[],Oe]}else Ze=(m.scenarios||[]).map(Oe=>Oe.id===T.id?{...Oe,metadata:{...Oe.metadata,data:ye},description:X||Oe.description}:Oe);const Xe=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:m,scenarios:Ze})}),lt=await Xe.json();if(!Xe.ok||!lt.success)throw new Error(lt.error||"Failed to save scenarios");console.log("[EntityDetail] Scenarios saved successfully"),F(de?"New scenario created successfully":"Scenario saved successfully"),Ee(null),Le.revalidate()}catch(ye){console.error("Error saving scenario:",ye),F(`Error: ${ye instanceof Error?ye.message:String(ye)}`)}finally{W(!1)}},oo=()=>{console.log("[EntityDetail] Edit mock data clicked"),F("Mock data editor coming soon")},io=async()=>{var X;if(!(T!=null&&T.id)){Se("Cannot delete scenario without ID");return}ce(!0),Se(null);try{const de=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:T.id,screenshotPaths:((X=T.metadata)==null?void 0:X.screenshotPaths)||[]})}),xe=await de.json();if(!de.ok||!xe.success)throw new Error(xe.error||"Failed to delete scenario");N(`/entity/${d==null?void 0:d.sha}/scenarios`)}catch(de){console.error("[EntityDetail] Error deleting scenario:",de),Se(de instanceof Error?de.message:"Failed to delete scenario"),fe(!1)}finally{ce(!1)}},on=m&&d&&m.entitySha!==d.sha,Hr=d?jh(d):!1,Vr=Hr||on||y,Gr=m!==null;return n(Dn,{children:c("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:c("div",{className:"flex items-center h-full px-6 gap-6",children:[c("div",{className:"flex items-center gap-1.5 min-w-0",children:[n("button",{onClick:_,className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("h1",{className:"text-sm font-semibold text-black m-0 leading-[20px] shrink-0",children:d==null?void 0:d.name}),q?c("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#FFF4FC",color:"#FF2AB5",height:"23px"},children:[c("svg",{width:"9",height:"9",viewBox:"0 0 9 9",fill:"none",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):Ur?n("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#f3e5f5",color:"#6a1b9a",height:"23px"},children:"Queued"}):Gr?Vr?n("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"23px"},children:"Out of date"}):n("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"23px"},children:"Up to date"}):n("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#f9f9f9",color:"#646464",height:"23px"},children:"Not analyzed"}),n("span",{className:"text-[#e1e1e1] mx-1.5 shrink-0",children:"|"}),n("span",{className:"text-sm text-[#626262] font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:d==null?void 0:d.filePath,children:d==null?void 0:d.filePath})]}),n("div",{className:"flex items-center gap-3 shrink-0",children:(!Gr||Vr)&&n("button",{onClick:Un,disabled:Ge.state!=="idle",className:"px-[15px] py-0 h-[26px] bg-[#005c75] text-white rounded text-xs font-semibold border-none cursor-pointer hover:bg-[#004a5e] transition-colors disabled:bg-gray-400 disabled:cursor-not-allowed",children:"Analyze"})})]})}),n("div",{className:"bg-[#efefef] border-b border-[#e1e1e1] shrink-0",children:n("div",{className:"flex items-center gap-6 h-10 px-[15px] shrink-0",children:[{id:"scenarios",label:"Scenarios",count:M.length},{id:"related",label:"Related Entities",count:f.importedEntities.length+f.importingEntities.length},{id:"data",label:"Data Structure"},{id:"code",label:"Code"},{id:"history",label:"History"}].map(X=>c(oe,{to:to(X.id),className:`flex items-center justify-center gap-3 shrink-0 text-sm rounded-md transition-colors no-underline ${E===X.id?"bg-[#343434] text-[#efefef] font-medium h-8 px-6":"text-[#3e3e3e] font-normal hover:bg-gray-100 py-1 px-[15px]"}`,children:[X.label,X.count!==void 0&&n("span",{className:`w-[25px] h-5 rounded-md text-xs font-normal flex items-center justify-center ${E===X.id?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:X.count})]},X.id))})}),(y||on&&!u||w&&Hr)&&!q&&!Ur&&c("div",{className:"bg-amber-50 border-b border-amber-200 px-6 py-3 flex items-center justify-between shrink-0",children:[c("div",{className:"flex items-center gap-3",children:[n("svg",{className:"w-5 h-5 text-amber-600",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-amber-800 font-medium",children:on&&!y?"This entity version has not been analyzed yet.":"This entity has been recently changed."}),n("span",{className:"text-amber-600 text-sm",children:y?"You are viewing an older version. A newer version is available.":on?"Showing scenarios from a previous version.":"The file on disk has been modified since this entity was analyzed."})]}),y&&b&&x?n(oe,{to:`/entity/${b}/scenarios`,className:"px-4 py-1.5 bg-amber-600 text-white rounded text-sm font-semibold cursor-pointer hover:bg-amber-700 transition-colors no-underline",children:"View Latest Version"}):n("button",{onClick:Un,disabled:Ge.state!=="idle",className:"px-4 py-1.5 bg-amber-600 text-white rounded text-sm font-semibold border-none cursor-pointer hover:bg-amber-700 transition-colors disabled:bg-gray-400 disabled:cursor-not-allowed",children:"Analyze Changes"})]}),c("div",{className:"flex grow items-stretch justify-center gap-0 min-h-0",children:[E==="scenarios"&&c(ue,{children:[V&&T?n($h,{scenario:T,entitySha:(d==null?void 0:d.sha)||"",onApply:ao,onSave:so,onEditMockData:oo,onDelete:io,isApplying:le,isSaving:B,saveMessage:Z,showDeleteConfirm:he,onShowDeleteConfirm:fe,isDeleting:te,deleteError:Ce}):n(Rh,{scenarios:M,hiddenScenarios:I,analysis:m,selectedScenario:T,entitySha:(d==null?void 0:d.sha)||"",cacheBuster:zr,activeTab:E,entityType:d==null?void 0:d.entityType,entity:d,queueState:A,processIsRunning:S,isEntityAnalyzing:q,areScenariosStale:L,viewMode:U,setViewMode:ro,onDebugSetup:()=>{!(T!=null&&T.id)||!(m!=null&&m.id)||Be.submit({analysisId:m.id,scenarioId:T.id},{method:"post",action:"/api/debug-setup"})},debugFetcher:Be,isBreakdownView:i==="breakdown"}),i==="breakdown"?n(Lh,{analysis:m??null,entitySha:(d==null?void 0:d.sha)||""}):V&&T?n(Ln,{scenarioId:T.id||T.name,scenarioName:T.name,iframeUrl:Te,isStarting:je,isLoading:we,showIframe:nn,iframeKey:ie,onIframeLoad:Ve,projectSlug:p,defaultWidth:1440,defaultHeight:900}):n(Js,{selectedScenario:T,analysis:m,entity:d,viewMode:U,cacheBuster:zr,hasScenarios:M.length>0,isAnalyzing:Bn,projectSlug:p,hasAnApiKey:k,processIsRunning:S,queueState:A})]}),E==="related"&&n(Yh,{relatedEntities:f}),E==="data"&&n(Wh,{entity:d,analysis:m,scenarios:M,onAnalyze:Un}),E==="code"&&n(qh,{entity:d,entityCode:g}),E==="history"&&n(Oh,{entity:d,history:v})]}),eo&&p&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>zn(!1),children:c("div",{className:"bg-white rounded-xl max-w-[1200px] w-full max-h-[90vh] flex flex-col shadow-[0_20px_60px_rgba(0,0,0,0.3)]",onClick:X=>X.stopPropagation(),children:[c("div",{className:"px-6 py-6 border-b border-gray-200 flex justify-between items-center",children:[n("h2",{className:"m-0 text-xl font-semibold text-gray-900",children:"Analysis Logs"}),n("button",{className:"bg-transparent border-none text-[28px] text-gray-500 cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-colors hover:bg-gray-100",onClick:()=>zn(!1),children:"×"})]}),n("div",{className:"flex-1 overflow-hidden",children:n(Rt,{projectSlug:p,onClose:()=>zn(!1)})})]})}),Xs&&an&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>sn(!1),children:c("div",{className:"bg-white rounded-xl max-w-200 w-full max-h-[90vh] flex flex-col shadow-[0_20px_60px_rgba(0,0,0,0.3)]",onClick:X=>X.stopPropagation(),children:[c("div",{className:"px-6 py-6 border-b border-gray-200 flex justify-between items-center",children:[n("div",{className:"flex items-center gap-3",children:n("h2",{className:"m-0 text-xl font-semibold text-gray-900",children:((ra=an.instructions)==null?void 0:ra.title)||"Debug Environment Ready"})}),n("button",{className:"bg-transparent border-none text-[28px] text-gray-500 cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-colors hover:bg-gray-100",onClick:()=>sn(!1),children:"×"})]}),n("div",{className:"px-6",children:n(Wt,{scenarioId:T==null?void 0:T.id,analysisId:m==null?void 0:m.id})}),n("div",{className:"px-6 py-6 overflow-y-auto flex-1",children:n("div",{className:"p-0",children:(sa=(aa=an.instructions)==null?void 0:aa.sections)==null?void 0:sa.map((X,de)=>c("div",{className:"mb-6 last:mb-0",children:[c("h3",{className:"text-base font-semibold text-gray-900 m-0 mb-3 pb-2 border-b-2 border-gray-200 flex items-center gap-2",children:[X.heading==="Status"&&!an.complete&&n("div",{className:"w-6 h-6 border-3 border-purple-600 border-t-transparent rounded-full animate-spin",style:{borderWidth:"3px"}}),X.heading]}),X.items.map((xe,ye)=>c("div",{className:"mb-3 pl-0 last:mb-0",children:[xe.label&&n("div",{className:"font-semibold text-gray-700 mb-1 text-sm",children:xe.label}),xe.isCode?c("div",{className:"relative mt-1",children:[n("code",{className:"block bg-gray-800 text-gray-50 px-3 py-2.5 pr-[90px] rounded-md text-[13px] font-mono overflow-x-auto",children:xe.content}),n(ur,{content:xe.content,label:"📋 Copy",className:"absolute top-2 right-2 px-2.5 py-1 bg-purple-600/90 text-white border-none rounded text-[11px] font-semibold cursor-pointer transition-all backdrop-blur hover:bg-purple-700/95 hover:scale-105 active:scale-95 disabled:opacity-75 disabled:cursor-not-allowed disabled:scale-100"})]}):xe.isLink?c("div",{className:"flex items-center gap-2 mt-1",children:[n("a",{href:xe.content,target:"_blank",rel:"noopener noreferrer",className:"text-purple-600 hover:text-purple-800 underline text-sm font-medium",children:xe.content}),n(ur,{content:xe.content,label:"📋",className:"px-2 py-1 bg-gray-200 text-gray-700 border-none rounded text-[11px] font-semibold cursor-pointer transition-all hover:bg-gray-300 hover:scale-105 active:scale-95"})]}):n("div",{className:"text-gray-600 text-sm leading-relaxed",children:xe.content})]},ye))]},de))})}),n("div",{className:"px-6 py-6 border-t border-gray-200 flex justify-end gap-3",children:n("button",{className:"px-5 py-2.5 bg-gray-500 text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-gray-600",onClick:()=>sn(!1),children:"Close"})})]})})]})})}),em=Object.freeze(Object.defineProperty({__proto__:null,default:Xh,loader:Zh,meta:Kh,shouldRevalidate:Qh},Symbol.toStringTag,{value:"Module"}));async function tm(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 $e();const i=pe();if(!i)throw new Error("Project root not found");console.log(`[analyzeEntities] Project root: ${i}`);const l=be.join(i,".codeyam","config.json"),d=JSON.parse(await Ie.readFile(l,"utf8")),{projectSlug:h,branchId:u}=d;if(!h||!u)throw new Error("Invalid project configuration - missing projectSlug or branchId");console.log(`[analyzeEntities] Project: ${h}, Branch: ${u}`);const m=Rn(h);try{await Ie.writeFile(m,"","utf8"),console.log("[analyzeEntities] Cleared log file")}catch{}const{project:p,branch:f}=await Ye(h);console.log("[analyzeEntities] Loading entities to determine file paths and names...");const g=await St({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(w=>w.filePath).filter(w=>!!w))],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 b=await Ll(p,f,y);console.log(`[analyzeEntities] Created commit ${b.sha.substring(0,8)}`),console.log("[analyzeEntities] Initializing progress tracking..."),await dt({commitSha:b.sha,runStatusUpdate:{queuedAt:new Date().toISOString(),entityCount:t.length,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString()},updateCallback:(w,v)=>{if(!w)return;const C=w.currentRun;if(C&&C.id&&C.archivedAt)return;C&&(C.analysesCompleted&&C.analysesCompleted>0||C.capturesCompleted&&C.capturesCompleted>0)&&ql(w)}}),console.log("[analyzeEntities] Enqueueing analysis job...");const{jobId:x}=o.enqueue({type:"analysis",commitSha:b.sha,projectSlug:h,filePaths:y,entityShas:t,entityNames:g.map(w=>w.name),...a?{context:a}:{},...s?{scenarioCount:s}:{}});return console.log(`[analyzeEntities] Job queued with ID: ${x} for ${t.length} entities`),{jobId:x}}catch(i){throw console.error("[analyzeEntities] Failed:",i),i}}async function nm({request:e,context:t}){if(e.method!=="POST")return z({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await it()),!r)return z({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),s=a.get("entitySha"),o=a.get("entityShas"),i=a.get("filePath"),l=a.get("context"),d=a.get("scenarioCount");let h;if(o)h=o.split(",").filter(Boolean);else if(s)h=[s];else return z({error:"Missing required field: entitySha or entityShas"},{status:400});if(h.length===0)return z({error:"No entities to analyze"},{status:400});console.log(`[API] Starting analysis for ${h.length} entity(ies)`);const u=await St({shas:h}),p=[...new Set(u.map(g=>g.filePath).filter(g=>!!g))].length,{jobId:f}=await tm({entityShas:h,filePaths:i?[i]:void 0,context:l||void 0,scenarioCount:d?parseInt(d,10):void 0,queue:r});return console.log(`[API] Analysis queued with job ID: ${f}`),z({success:!0,message:`Analysis queued for ${h.length} entity(ies)`,entityCount:h.length,fileCount:p,jobId:f})}catch(a){return console.error("[API] Error starting analysis:",a),z({error:"Failed to start analysis",details:a.message},{status:500})}}const rm=Object.freeze(Object.defineProperty({__proto__:null,action:nm},Symbol.toStringTag,{value:"Module"}));function am(e){switch(e){case"queued":return{text:"Queued",bgColor:"#cbf3fa",textColor:"#3098b4",icon:c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]})};case"analyzing":return{text:"Analyzing...",bgColor:"#ffdbf6",textColor:"#ff2ab5",icon:c("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]})};case"up-to-date":return{text:"Up to date",bgColor:"#e8ffe6",textColor:"#00925d",icon:null};case"incomplete":return{text:"Incomplete",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"out-of-date":return{text:"Out of date",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"not-analyzed":return{text:"Not analyzed",bgColor:"#f9f9f9",textColor:"#646464",icon:null}}}function qs(e){if(!e)return"Never";const t=new Date(e),r=new Date;if(t.getDate()===r.getDate()&&t.getMonth()===r.getMonth()&&t.getFullYear()===r.getFullYear()){const s=t.getHours(),o=t.getMinutes(),i=s>=12?"pm":"am",l=s%12||12,d=o.toString().padStart(2,"0");return`Today, ${l}:${d} ${i}`}return t.toLocaleString("en-US",{month:"numeric",day:"numeric",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!0})}function Je(e,t=[],r=!1){var u,m;if(t.some(p=>{var f,g;return!!((f=p.entityShas)!=null&&f.includes(e.sha)||(g=p.entities)!=null&&g.some(y=>y.sha===e.sha))}))return r?"analyzing":"queued";if(!e.analyses||e.analyses.length===0)return"not-analyzed";const s=e.analyses[0];if(!(((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,l=(m=e.metadata)!=null&&m.editedAt?new Date(e.metadata.editedAt).getTime():0,d=s.scenarios||[],h=d.some(p=>{var f,g,y;return((g=(f=p.metadata)==null?void 0:f.screenshotPaths)==null?void 0:g[0])||((y=p.metadata)==null?void 0:y.executionResult)});return i>=l?d.length>0&&h?d.every(f=>{var g,y,b;return((y=(g=f.metadata)==null?void 0:g.screenshotPaths)==null?void 0:y[0])||((b=f.metadata)==null?void 0:b.executionResult)})?"up-to-date":"incomplete":d.length>0?"incomplete":"not-analyzed":"out-of-date"}const sm=()=>[{title:"Simulations - CodeYam"},{name:"description",content:"A visual gallery of your recently captured component screenshots"}];async function om({request:e,context:t}){try{const r=t.analysisQueue,a=r?r.getState():{paused:!1,jobs:[]},s=await Xt();return z({entities:s||[],queueState:a})}catch(r){return console.error("Failed to load simulations:",r),z({entities:[],queueState:{paused:!1,jobs:[]},error:"Failed to load simulations"})}}const im=We(function(){const t=Ke(),r=t.entities,a=t.queueState;Et({source:"simulations-page"});const[s,o]=j(""),[i,l]=j("visual"),d=se(()=>{const y=[];return r.forEach(b=>{var w;const x=(w=b.analyses)==null?void 0:w[0];if(x!=null&&x.scenarios){const v=x.scenarios.filter(C=>{var k;return!((k=C.metadata)!=null&&k.sameAsDefault)}).map(C=>{var $,_,S,E,R;const k=(_=($=C.metadata)==null?void 0:$.screenshotPaths)==null?void 0:_[0],A=(S=C.metadata)==null?void 0:S.noScreenshotSaved,P=k&&!A,M=(R=(E=x.status)==null?void 0:E.scenarios)==null?void 0:R.find(D=>D.name===C.name),I=M&&M.screenshotStartedAt&&!M.screenshotFinishedAt;let N;return P?N="completed":I?N="capturing":N="error",{scenarioName:C.name,scenarioDescription:C.description||"",screenshotPath:k||"",scenarioId:C.id,state:N}}).filter(C=>C.state==="completed"||C.state==="capturing");v.length>0&&y.push({entity:b,screenshots:v,createdAt:x.createdAt||""})}}),y.sort((b,x)=>new Date(x.createdAt).getTime()-new Date(b.createdAt).getTime()),y},[r]),h=se(()=>r.filter(y=>{var w,v;const b=(w=y.analyses)==null?void 0:w[0];return!((v=b==null?void 0:b.scenarios)==null?void 0:v.some(C=>{var k,A;return(A=(k=C.metadata)==null?void 0:k.screenshotPaths)==null?void 0:A[0]}))}),[r]),u=se(()=>d.filter(({entity:y})=>{const b=!s||y.name.toLowerCase().includes(s.toLowerCase()),x=i==="all"||y.entityType===i;return b&&x}),[d,s,i]),m=se(()=>h.filter(y=>{const b=!s||y.name.toLowerCase().includes(s.toLowerCase()),x=i==="all"||y.entityType===i;return b&&x}),[h,s,i]),p=re(y=>{o(y.target.value)},[]),f=re(y=>{l(y.target.value)},[]),g=d.length>0;return n("div",{className:"bg-[#f9f9f9] min-h-screen overflow-y-auto",children:c("div",{className:"px-20 py-12",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-3xl font-semibold text-gray-900 mb-2",children:"Simulations"}),n("p",{className:"text-gray-600",children:"A visual gallery of your recently captured simulations."})]}),!g&&n("div",{className:"bg-[#D1F3F9] border border-[#A5E8F0] rounded-lg p-4 mb-6",children:c("p",{className:"text-sm text-gray-700 m-0",children:["This page will display a visual gallery of your recently captured component simulations."," ",n("strong",{children:"Start by analyzing your first component below."})]})}),c("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),c("div",{className:"flex gap-3",children:[c("div",{className:"relative",children:[c("select",{className:"appearance-none bg-gray-50 border border-gray-200 rounded px-3 pr-8 text-[13px] h-[39px] cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",value:i,onChange:f,children:[n("option",{value:"all",children:"All Types"}),n("option",{value:"visual",children:"Visual"}),n("option",{value:"library",children:"Library"})]}),n(bn,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),c("div",{className:"flex-1 relative",children:[n(Ka,{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:"bg-[#efefef] rounded-lg mb-2 text-[11px] font-normal leading-[16px] text-[#3e3e3e] uppercase",children:c("div",{className:"flex items-center gap-1.5 px-3 py-2",children:[n("span",{children:"ENTITY"}),n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"text-[#3e3e3e]",children:n("path",{d:"M3 5L6 8L9 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})}),c("div",{className:"flex flex-col gap-[3px]",children:[g&&(u.length===0?n("div",{className:"bg-white border border-gray-200 rounded-lg p-8 text-center text-gray-500",children:"No simulations match your filters."}):n(ue,{children:u.map(({entity:y,screenshots:b})=>n(lm,{entity:y,screenshots:b,queueJobs:(a==null?void 0:a.jobs)||[]},y.sha))})),!g&&(m.length===0?n("div",{className:"bg-white border border-gray-200 rounded-b-lg p-8 text-center text-gray-500",children:"No components found matching your filters."}):m.map(y=>n(cm,{entity:y},y.sha)))]})]})})});function lm({entity:e,screenshots:t,queueJobs:r}){var d,h,u;const a=It(),s=t.length||(((u=(h=(d=e.analyses)==null?void 0:d[0])==null?void 0:h.scenarios)==null?void 0:u.length)??0),o=m=>{a(`/entity/${e.sha}/scenarios/${m}?from=simulations`)},i=Je(e,r),l=am(i);return n("div",{className:"bg-white rounded hover:bg-gray-50 transition-colors border-b border-[#e1e1e1]",children:c("div",{className:"px-5 pb-[15px]",children:[c("div",{className:"flex items-center justify-between py-[10px]",children:[c(oe,{to:`/entity/${e.sha}`,className:"flex items-center gap-2 no-underline",children:[n(Ue,{type:e.entityType}),c("span",{className:"font-['IBM_Plex_Sans'] font-medium text-[12px] leading-[15px] text-[#343434]",children:[e.name," (",s,")"]})]}),c("div",{className:"flex items-center gap-2.5",children:[c("span",{className:"px-2 rounded inline-flex items-center gap-1.5 max-w-full whitespace-nowrap overflow-hidden",style:{backgroundColor:l.bgColor,color:l.textColor,height:"23px",fontSize:"10px",lineHeight:"15px"},children:[l.icon,l.text]}),n("button",{onClick:()=>void a(`/entity/${e.sha}/logs`),className:"bg-[#e0e9ec] text-[#005c75] rounded font-['IBM_Plex_Sans'] font-semibold hover:bg-[#d0dfe5] transition-colors px-[10px] py-0 cursor-pointer border-none",style:{fontSize:"10px",lineHeight:"22px"},children:"View Logs"})]})]}),n("div",{className:"flex gap-2.5 overflow-x-auto pb-1",children:t.length>0?t.map(m=>n("button",{onClick:()=>o(m.scenarioId||""),className:"shrink-0 block cursor-pointer bg-transparent border-none p-0",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{"--hover-border":"#005C75",backgroundColor:m.state==="capturing"?"#f9f9f9":"#f3f4f6",borderColor:m.state==="capturing"?"#efefef":"#d1d5db"},onMouseEnter:p=>{m.state==="completed"&&(p.currentTarget.style.borderColor="#005C75",p.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:p=>{p.currentTarget.style.borderColor=m.state==="capturing"?"#efefef":"#d1d5db",p.currentTarget.style.boxShadow="none"},children:m.state==="completed"?n(Fe,{screenshotPath:m.screenshotPath,alt:m.scenarioName,className:"max-w-full max-h-full object-contain"}):m.state==="capturing"?n(jr,{size:"medium"}):null})},m.scenarioId)):n("div",{className:"text-xs text-gray-400 py-4",children:"No screenshots available"})})]})})}function cm({entity:e}){const t=ke(),[r,a]=j(!1),s=()=>{a(!0),t.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};return ne(()=>{t.state==="idle"&&r&&a(!1)},[t.state,r]),n("div",{className:"bg-white rounded hover:bg-gray-100 transition-colors cursor-pointer border-b border-[#e1e1e1]",onClick:s,children:c("div",{className:"px-5 py-4 flex items-center",children:[c("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n(Ue,{type:e.entityType}),c("div",{className:"min-w-0",children:[c("div",{className:"flex items-center gap-3 mb-0.5",children:[n(oe,{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:qs(e.createdAt||null)}),n("div",{className:"w-24 flex justify-end",children:r||t.state!=="idle"?c("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(at,{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 dm=Object.freeze(Object.defineProperty({__proto__:null,default:im,loader:om,meta:sm},Symbol.toStringTag,{value:"Module"}));function um({request:e,context:t}){const r=t.dbNotifier||or;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"})}
172
+
173
+ `)),Math.random().toString(36).substring(7);let i=!1;const l=()=>{if(!i){i=!0,r.off("change",d),clearInterval(h);try{s.close()}catch{}}},d=u=>{try{s.enqueue(o.encode(`data: ${JSON.stringify({type:"db-change",changeType:u.type,timestamp:u.timestamp})}
174
+
175
+ `))}catch{l()}};r.on("change",d);const h=setInterval(()=>{try{s.enqueue(o.encode(`data: ${JSON.stringify({type:"keepalive"})}
176
+
177
+ `))}catch{l()}},3e4);e.signal.addEventListener("abort",l)}});return new Response(a,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}const hm=Object.freeze(Object.defineProperty({__proto__:null,loader:um},Symbol.toStringTag,{value:"Module"}));function wt(){const e=process.memoryUsage(),t=fi.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(ar.totalmem()/1024/1024),freeMemory:Math.round(ar.freemem()/1024/1024)}}}function mm(){const e=wt();console.log(`
178
+ [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 pm(){if(global.gc){console.log("[Memory Profiler] Running garbage collection...");const e=wt();global.gc();const t=wt(),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 fm(){const e=wt(),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 gm({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=pm(),s=wt();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=mm();return Response.json({success:!0,stats:a})}case"leaks":{const a=fm(),s=wt();return Response.json({success:!0,leakCheck:a,stats:s})}default:{const a=wt();return Response.json({success:!0,stats:a,actions:{gc:"/api/memory?action=gc - Force garbage collection (requires --expose-gc)",detailed:"/api/memory?action=detailed - Log detailed stats to console",leaks:"/api/memory?action=leaks - Check for memory leak indicators"}})}}}catch(a){return console.error("[Memory API] Error:",a),Response.json({success:!1,error:a.message},{status:500})}}const ym=Object.freeze(Object.defineProperty({__proto__:null,loader:gm},Symbol.toStringTag,{value:"Module"}));async function xm({request:e,context:t}){var o;let r=t.analysisQueue;if(r||(r=await it()),!r)return z({error:"Queue not initialized"},{status:500});const a=new URL(e.url),s=a.searchParams.get("queryType");if(!s)return z({error:"Missing queryType parameter for GET request"},{status:400});if(s==="job"){const i=a.searchParams.get("jobId");if(!i)return z({error:"Missing jobId parameter for job query"},{status:400});const l=r.getState();if(((o=l.currentlyExecuting)==null?void 0:o.id)===i)return z({jobId:i,status:"running",job:l.currentlyExecuting});const d=l.jobs.find(u=>u.id===i);if(d){const u=l.jobs.indexOf(d);return z({jobId:i,status:"queued",position:u,job:d})}const h=r.getJobResult(i);return h?z({jobId:i,status:h.status==="error"?"failed":"completed",error:h.error}):z({jobId:i,status:"completed"})}if(s==="full"){const i=r.getState(),l=await Promise.all(i.jobs.map(async h=>{const u=[];if(h.entityShas&&h.entityShas.length>0){const m=h.entityShas.map(f=>At(f)),p=await Promise.all(m);u.push(...p.filter(f=>f!==null))}return{id:h.id,type:h.type,commitSha:h.commitSha,projectSlug:h.projectSlug,queuedAt:h.queuedAt,entities:u,filePaths:h.filePaths}}));let d;if(i.currentlyExecuting){const h=i.currentlyExecuting,u=[];if(h.entityShas&&h.entityShas.length>0){const m=h.entityShas.map(f=>At(f)),p=await Promise.all(m);u.push(...p.filter(f=>f!==null))}d={id:h.id,type:h.type,commitSha:h.commitSha,projectSlug:h.projectSlug,queuedAt:h.queuedAt,entities:u,filePaths:h.filePaths}}return z({state:{...i,jobsWithEntities:l,currentlyExecutingWithEntities:d}})}return z({error:"Unknown queryType"},{status:400})}async function bm({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 it(),console.log("[Queue API] Using global queue")),!r)return console.error("[Queue API] ERROR: Queue not initialized in context"),z({error:"Queue not initialized"},{status:500});const a=await e.json(),{action:s,...o}=a;if(console.log("[Queue API] Action:",s,"Params:",Object.keys(o)),s==="enqueue"){const{jobId:i,completion:l}=r.enqueue(o);return l.catch(d=>{console.error(`[Queue API] Job ${i} failed:`,d)}),z({jobId:i,status:"queued"})}if(s==="resume")return r.resume(),z({status:"resumed"});if(s==="pause")return r.pause(),z({status:"paused"});if(s==="remove"){const{jobId:i}=o;return i?r.removeJob(i)?z({status:"removed",jobId:i}):z({error:"Job not found in queue"},{status:404}):z({error:"Missing jobId parameter"},{status:400})}if(s==="clear"){const i=r.clearQueue();return z({status:"cleared",count:i})}if(s==="reorder"){const{jobId:i,direction:l}=o;return!i||!l?z({error:"Missing jobId or direction parameter"},{status:400}):l!=="up"&&l!=="down"?z({error:'Invalid direction: must be "up" or "down"'},{status:400}):r.reorderJob(i,l)?z({status:"reordered",jobId:i,direction:l}):z({error:"Could not reorder job (not found or at boundary)"},{status:400})}return z({error:"Unknown action"},{status:400})}const vm=Object.freeze(Object.defineProperty({__proto__:null,action:bm,loader:xm},Symbol.toStringTag,{value:"Module"})),wm=()=>[{title:"Empty State - CodeYam"},{name:"description",content:"Simulations empty state development view"}],Cm=We(function(){return ke(),n(Dn,{children:c("div",{className:"h-screen bg-[#f9f9f9] flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:c("div",{className:"flex items-center h-full px-6 gap-6",children:[c("div",{className:"flex items-center gap-3 min-w-0",children:[n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),n("h1",{className:"text-lg font-semibold text-black m-0 leading-[26px] shrink-0",children:"Dashboard"}),n("span",{className:"text-xs text-[#626262] font-mono whitespace-nowrap overflow-hidden text-ellipsis min-w-0",children:"codeyam-cli/src/webserver/app/routes/_index.tsx"})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[c("div",{className:"flex items-center gap-2 px-[15px] py-0 h-[26px] bg-[#efefef] border border-[#e1e1e1] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#626262]"}),n("span",{className:"text-xs font-semibold text-[#626262]",children:"Not analyzed"})]}),n("button",{className:"px-[15px] py-0 h-[26px] bg-[#005c75] text-white rounded text-xs font-semibold border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]}),c("div",{className:"flex items-center gap-1 text-[10px] text-[#626262] ml-auto",children:[n("span",{className:"leading-[22px]",children:"Next Entity"}),n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M4 8.5H13M13 8.5L8.5 4M13 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})}),n("div",{className:"bg-[#efefef] border-b border-[#efefef] shrink-0",children:c("div",{className:"flex items-center gap-3 h-11 px-[15px]",children:[c("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded bg-[#343434] text-[#efefef] font-semibold h-8",children:["Scenarios",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#cbf3fa] text-[#005c75] min-w-[25px] text-center",children:"0"})]}),c("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded-[9px] text-[#3e3e3e] font-normal",children:["Related Entities",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#e1e1e1] text-[#3e3e3e] min-w-[25px] text-center",children:"5"})]}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Code"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Data Structure"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"History"})]})}),c("div",{className:"flex flex-1 gap-0 min-h-0",children:[n("div",{className:"w-[165px] bg-[#e1e1e1] border-r border-[#c7c7c7] flex items-center justify-center shrink-0",children:n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-5",children:"No Scenarios"})}),n(Js,{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})]})]})})}),Nm=Object.freeze(Object.defineProperty({__proto__:null,default:Cm,meta:wm},Symbol.toStringTag,{value:"Module"})),Sm=()=>[{title:"CodeYam - Settings"},{name:"description",content:"Configure project settings"}];async function Am({request:e}){try{const t=await _r();if(!t)return z({config:null,secrets:null,versionInfo:null,error:"Project configuration not found"});const r=pe()||process.cwd(),a=await jn(r),s=Is(t.projectSlug);return z({config:t,secrets:{GROQ_API_KEY:a.GROQ_API_KEY||"",ANTHROPIC_API_KEY:a.ANTHROPIC_API_KEY||"",OPENAI_API_KEY:a.OPENAI_API_KEY||""},versionInfo:s,error:null})}catch(t){return console.error("Failed to load config:",t),z({config:null,secrets:null,versionInfo:null,error:"Failed to load configuration"})}}function Em(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 _m({request:e}){try{const t=await e.formData(),r=t.get("universalMocks"),a=t.get("startCommands"),s=t.get("groqApiKey"),o=t.get("anthropicApiKey"),i=t.get("openAiApiKey"),l=t.get("pathsToIgnore");let d;if(r)try{d=JSON.parse(r)}catch{return z({success:!1,error:"Invalid universalMocks JSON format",requiresRestart:!1},{status:400})}let h;if(a)try{h=JSON.parse(a)}catch{return z({success:!1,error:"Invalid startCommands JSON format",requiresRestart:!1},{status:400})}let u;l&&(u=l.split(",").map(g=>g.trim()).map(g=>g.startsWith('"')&&g.endsWith('"')||g.startsWith("'")&&g.endsWith("'")?g.slice(1,-1):g).filter(g=>g.length>0));let m;if(h){const g=await _r();g!=null&&g.webapps&&(m=g.webapps.map((y,b)=>{if(h[b]!==void 0){const x=Em(h[b]);return{...y,startCommand:x}}return y}))}if(!await Ns({universalMocks:d,pathsToIgnore:u,webapps:m}))return z({success:!1,error:"Failed to update configuration",requiresRestart:!1},{status:500});let f=!1;if(s!==void 0||o!==void 0||i!==void 0){const g=pe()||process.cwd(),y=await jn(g);f=s!==void 0&&s!==(y.GROQ_API_KEY||"")||o!==void 0&&o!==(y.ANTHROPIC_API_KEY||"")||i!==void 0&&i!==(y.OPENAI_API_KEY||""),await Fl(g,{...y,GROQ_API_KEY:s||void 0,ANTHROPIC_API_KEY:o||void 0,OPENAI_API_KEY:i||void 0},!0)}return z({success:!0,error:null,requiresRestart:f})}catch(t){return console.log("[Settings Action] Failed to save config:",t),z({success:!1,error:"Failed to save configuration",requiresRestart:!1},{status:500})}}function Wa(e){if(!e)return"";const t=[e.command];return e.args&&e.args.length>0&&t.push(...e.args),t.join(" ")}function Ha({mock:e,onSave:t,onCancel:r}){const[a,s]=j(e.entityName),[o,i]=j(e.filePath),[l,d]=j(e.content);return c("div",{className:"space-y-3",children:[c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Entity Name"}),n("input",{type:"text",value:a,onChange: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"})]}),c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path"}),n("input",{type:"text",value:o,onChange:u=>i(u.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., packages/database/src/lib/kysely/db.ts"})]}),c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:l,onChange: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' }"})]}),c("div",{className:"flex gap-2 justify-end",children:[n("button",{type:"button",onClick:r,className:"px-4 py-2 bg-gray-200 text-gray-800 border-none rounded text-sm cursor-pointer hover:bg-gray-300",children:"Cancel"}),n("button",{type:"button",onClick:()=>{if(!a.trim()||!o.trim()||!l.trim()){alert("All fields are required");return}t({entityName:a,filePath:o,content:l})},className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Save"})]})]})}function Pm(e){try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}const km=We(function(){var W,Z;const{config:t,secrets:r,versionInfo:a,error:s}=Ke(),o=vo(),i=ke(),l=ht(),[d,h]=j("project-metadata");Et({source:"settings-page"});const[u,m]=j((t==null?void 0:t.universalMocks)||[]),[p,f]=j(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[g,y]=j(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[b,x]=j((r==null?void 0:r.GROQ_API_KEY)||""),[w,v]=j((r==null?void 0:r.ANTHROPIC_API_KEY)||""),[C,k]=j((r==null?void 0:r.OPENAI_API_KEY)||""),[A,P]=j(!1),[M,I]=j(!1),[N,$]=j(!1),[_,S]=j(!1),[E,R]=j(!1),[D,O]=j(!1),[H,Q]=j(null),[q,L]=j(!1),[T,U]=j({});ne(()=>{var F;if(t){m(t.universalMocks||[]);const te=(t.pathsToIgnore||[]).join(", ");f(te),y(te);const ce={};(F=t.webapps)==null||F.forEach((he,fe)=>{he.startCommand&&(ce[fe]=Wa(he.startCommand))}),U(ce)}r&&(x(r.GROQ_API_KEY||""),v(r.ANTHROPIC_API_KEY||""),k(r.OPENAI_API_KEY||""))},[t,r]),ne(()=>{if(o!=null&&o.success){S(!0);const F=setTimeout(()=>S(!1),3e3);return()=>clearTimeout(F)}},[o]),ne(()=>{if(i.state==="idle"&&i.data&&!D){console.log("[Settings] Fetcher data:",i.data);const F=i.data;if(F.success){console.log("[Settings] Save successful, revalidating..."),S(!0),O(!0),(p!==g||F.requiresRestart)&&R(!0),l.revalidate();const te=setTimeout(()=>{S(!1),O(!1)},3e3);return()=>clearTimeout(te)}}},[i.state,i.data,D,l,p,g]);const Y=F=>{F.preventDefault();const te=new FormData(F.currentTarget);te.set("universalMocks",JSON.stringify(u)),te.set("startCommands",JSON.stringify(T)),console.log("[Settings] Submitting form data:",{universalMocks:te.get("universalMocks"),startCommands:te.get("startCommands"),openAiApiKey:te.get("openAiApiKey")?"***":"(empty)"}),i.submit(te,{method:"post"})},V=F=>{m([...u,F]),L(!1)},le=(F,te)=>{const ce=[...u];ce[F]=te,m(ce),Q(null)},G=F=>{m(u.filter((te,ce)=>ce!==F))};if(s)return c("div",{className:"max-w-6xl mx-auto p-8 font-sans",children:[n("header",{className:"mb-6 pb-4 border-b border-gray-200",children:n("div",{className:"flex justify-between items-center",children:n("h1",{className:"text-4xl font-bold text-gray-900",children:"Settings"})})}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4",children:n("p",{className:"text-red-700",children:s})})]});const B=[{id:"project-metadata",label:"Project Metadata"},{id:"ai-provider",label:"AI Provider Configuration"},{id:"commands",label:"Commands"},{id:"paths-to-ignore",label:"Paths To Ignore"},{id:"universal-mocks",label:"Universal Mocks"},{id:"current-configuration",label:"Current Configuration"}];return n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-20 py-12 font-sans",children:[c("div",{className:"mb-8 flex justify-between items-start",children:[c("div",{children:[n("h1",{className:"text-3xl font-semibold text-gray-900 mb-2",children:"Settings"}),n("p",{className:"text-gray-600",children:"Project Configuration"})]}),n("button",{type:"submit",form:"settings-form",disabled:i.state==="submitting",className:"px-6 py-2 bg-[#005C75] text-white border-none rounded text-sm font-medium cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 hover:bg-[#004a5d] whitespace-nowrap",children:i.state==="submitting"?"Saving...":"Save Settings"})]}),c("div",{className:"flex gap-8 items-start",children:[n("nav",{className:"w-64 flex-shrink-0",children:n("ul",{className:"space-y-1",children:B.map(F=>n("li",{children:n("button",{type:"button",onClick:()=>h(F.id),className:`w-full text-left px-0 py-2.5 text-sm transition-colors cursor-pointer ${d===F.id?"text-[#005C75] font-medium":"text-gray-600 hover:text-gray-900"}`,children:F.label})},F.id))})}),n("div",{className:"flex-1 min-w-0 -mt-2",children:c("form",{id:"settings-form",onSubmit:Y,className:"space-y-6",children:[d==="project-metadata"&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Project Metadata"}),c("div",{className:"mb-6",children:[n("label",{className:"block mb-2 font-medium text-gray-700",children:"Web Applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-3",children:t.webapps.map((F,te)=>{var ce;return n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:c("div",{className:"space-y-2 text-sm",children:[c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:F.path==="."?"Root":F.path})]}),F.appDirectory&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:F.appDirectory})]}),c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:F.framework})]}),F.startCommand&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",c("span",{className:"text-gray-900 font-mono text-xs",children:[F.startCommand.command," ",(ce=F.startCommand.args)==null?void 0:ce.join(" ")]})]})]})},te)})}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"}),n("p",{className:"mt-2 text-sm text-gray-600",children:"Web applications are detected during initialization. To modify, edit `.codeyam/config.json` or re-run `codeyam init`."})]})]}),d==="ai-provider"&&c("div",{children:[n("h3",{className:"text-lg font-semibold text-gray-800 mb-4",children:"AI Provider API Keys"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure API keys for AI-powered analysis. Choose the provider that best fits your needs."}),c("div",{className:"space-y-6",children:[c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:c("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Groq"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Lightning-fast inference with industry-leading speed. Groq's LPU architecture delivers exceptional performance for real-time AI applications with competitive pricing."}),c("div",{className:"flex gap-3 text-xs",children:[c("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$0.10/1M tokens"]}),c("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 850 tokens/s"]}),c("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Less reliable, but capable of producing reasonable results"]})]})]})}),c("div",{className:"mt-4",children:[n("label",{htmlFor:"groqApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),c("div",{className:"relative",children:[n("input",{type:A?"text":"password",id:"groqApiKey",name:"groqApiKey",value:b,onChange:F=>x(F.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:()=>P(!A),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:A?"Hide":"Show"})]})]})]}),c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:c("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Anthropic Claude"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Advanced reasoning and coding capabilities with superior context understanding. Claude excels at complex analysis tasks and provides highly accurate results with detailed explanations."}),c("div",{className:"flex gap-3 text-xs",children:[c("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$3.00/1M tokens"]}),c("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 120 tokens/s"]}),c("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),c("div",{className:"mt-4",children:[n("label",{htmlFor:"anthropicApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),c("div",{className:"relative",children:[n("input",{type:M?"text":"password",id:"anthropicApiKey",name:"anthropicApiKey",value:w,onChange:F=>v(F.target.value),placeholder:"sk-ant-...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>I(!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"})]})]})]}),c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:c("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"OpenAI GPT"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Industry-standard AI with broad capabilities and extensive ecosystem. GPT models offer reliable performance across diverse tasks with good balance of speed and quality."}),c("div",{className:"flex gap-3 text-xs",children:[c("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$2.50/1M tokens"]}),c("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 150 tokens/s"]}),c("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),c("div",{className:"mt-4",children:[n("label",{htmlFor:"openAiApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),c("div",{className:"relative",children:[n("input",{type:N?"text":"password",id:"openAiApiKey",name:"openAiApiKey",value:C,onChange:F=>k(F.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:()=>$(!N),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:N?"Hide":"Show"})]})]})]})]})]}),d==="commands"&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Commands"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure start commands for your web applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-4",children:t.webapps.map((F,te)=>c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[c("div",{className:"mb-4",children:[n("div",{className:"text-base font-semibold text-gray-900 mb-1",children:F.path==="."?"Root":F.path}),n("div",{className:"text-sm text-gray-600",children:F.framework})]}),c("div",{children:[n("label",{htmlFor:`startCommand-${te}`,className:"block text-sm font-medium text-gray-700 mb-2",children:"Start Command"}),n("input",{type:"text",id:`startCommand-${te}`,name:`startCommand-${te}`,value:T[te]||"",onChange:ce=>U({...T,[te]:ce.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"})]})]},te))}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"})]}),d==="paths-to-ignore"&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Paths To Ignore"}),n("input",{type:"text",id:"pathsToIgnore",name:"pathsToIgnore",value:p,onChange:F=>f(F.target.value),placeholder:"e.g., __tests__, \\.test\\.ts$, ^background (no quotes needed)",className:"w-full px-3 py-3 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-2 focus:ring-[#005C75]/10"}),c("p",{className:"mt-2 text-sm text-gray-600",children:["Comma-separated list of regex patterns for paths to ignore during file watching. Examples:"," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"__tests__"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"\\.test\\.tsx?$"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"^background"}),n("br",{}),n("span",{className:"text-xs text-gray-500 mt-1 inline-block",children:"Note: Files matching patterns in .gitignore are also automatically ignored"})]})]}),d==="universal-mocks"&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Universal Mocks"}),n("p",{className:"mb-3 text-sm text-gray-600",children:"Mock functions that will be applied across all entity simulations"}),u.length===0?c("div",{className:"mb-4",children:[n("div",{className:"text-sm text-gray-500 mb-3",children:"No universal mocks configured"}),n("button",{type:"button",onClick:()=>L(!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:u.map((F,te)=>n("div",{className:"p-4 bg-gray-50 rounded border border-gray-200",children:H===te?n(Ha,{mock:F,onSave:ce=>le(te,ce),onCancel:()=>Q(null)}):n(ue,{children:c("div",{className:"flex justify-between items-start mb-2",children:[c("div",{className:"flex-1",children:[n("div",{className:"font-medium text-gray-800 mb-1",children:F.entityName}),n("div",{className:"text-sm text-gray-600 mb-2",children:F.filePath}),n("pre",{className:"text-xs bg-white p-2 rounded border border-gray-200 overflow-x-auto",children:F.content})]}),c("div",{className:"flex gap-2 ml-3",children:[n("button",{type:"button",onClick:()=>Q(te),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:()=>G(te),className:"px-3 py-1 bg-red-600 text-white border-none rounded text-sm cursor-pointer hover:bg-red-700",children:"Delete"})]})]})})},te))}),u.length>0&&n("button",{type:"button",onClick:()=>L(!0),className:"mt-4 px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}),d==="current-configuration"&&c("div",{className:"space-y-6",children:[t&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Current Configuration"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded mb-6",children:c("div",{className:"space-y-2 text-sm",children:[t.projectSlug&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Project Slug:"})," ",n("span",{className:"text-gray-900",children:t.projectSlug})]}),t.packageManager&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Package Manager:"})," ",n("span",{className:"text-gray-900",children:t.packageManager})]})]})}),t.webapps&&t.webapps.length>0&&c("div",{children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Web Applications"}),n("div",{className:"space-y-3",children:t.webapps.map((F,te)=>n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:c("div",{className:"space-y-2 text-sm",children:[c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:F.path==="."?"Root":F.path})]}),F.appDirectory&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:F.appDirectory})]}),c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:F.framework})]}),F.startCommand&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",n("span",{className:"text-gray-900 font-mono text-xs",children:Wa(F.startCommand)})]})]})},te))})]})]}),a&&c("div",{className:"mt-6",children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Version Information"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:c("div",{className:"space-y-2 text-sm",children:[a.webserverVersion&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Webserver:"})," ",n("span",{className:"text-gray-900 font-mono",children:a.webserverVersion.version||"unknown"})]}),a.templateVersion&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Analyzer Template:"})," ",n("span",{className:"font-mono text-gray-900",children:a.templateVersion.version||((W=a.templateVersion.gitCommit)==null?void 0:W.slice(0,7))||"unknown"}),a.templateVersion.buildTimestamp&&c("span",{className:"text-gray-500 ml-2",children:["(built"," ",Pm(a.templateVersion.buildTimestamp),")"]})]}),a.cachedAnalyzerVersion&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"font-mono text-gray-900",children:a.cachedAnalyzerVersion.version||((Z=a.cachedAnalyzerVersion.gitCommit)==null?void 0:Z.slice(0,7))||"unknown"}),a.isCacheStale?n("span",{className:"ml-2 px-2 py-0.5 bg-amber-100 text-amber-800 rounded text-xs",children:"Stale - will update on next analysis"}):n("span",{className:"ml-2 px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:"Up to date"})]}),!a.cachedAnalyzerVersion&&(t==null?void 0:t.projectSlug)&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"text-gray-500 italic",children:"Not initialized - will be created on first analysis"})]})]})})]})]})]})})]}),(_||E||(o==null?void 0:o.error)||i.data&&typeof i.data=="object"&&"error"in i.data)&&c("div",{className:"mt-6 max-w-5xl mx-auto space-y-3",children:[_&&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!"}),E&&c("div",{className:"text-amber-700 text-sm font-medium bg-amber-50 border border-amber-200 rounded px-4 py-2",children:[n("div",{children:"⚠️ Settings changed. Please restart CodeYam for changes to take effect:"}),n("code",{className:"ml-2 bg-amber-100 px-2 py-1 rounded text-xs",children:"codeyam stop && codeyam"})]}),(o==null?void 0:o.error)&&n("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:o.error}),(()=>{if(i.data&&typeof i.data=="object"&&"error"in i.data){const F=i.data;return typeof F.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:F.error}):null}return null})()]}),q&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:c("div",{className:"bg-white rounded-lg max-w-2xl w-full p-6",children:[n("h2",{className:"text-2xl font-bold mb-4 text-gray-900",children:"Add Universal Mock"}),n(Ha,{mock:{entityName:"",filePath:"",content:""},onSave:V,onCancel:()=>L(!1)})]})})]})})}),Mm=Object.freeze(Object.defineProperty({__proto__:null,action:_m,default:km,loader:Am,meta:Sm},Symbol.toStringTag,{value:"Module"}));async function Tm({params:e}){const t=e["*"];if(!t)return new Response("Static path is required",{status:400});const r=pe();if(!r)return new Response("Project root not found",{status:500});const s=be.extname(t)!==""?t:`${t}.html`,o=be.join(r,".codeyam","captures","static",s);try{await Ie.access(o);let i=await Ie.readFile(o);const l=be.extname(o).toLowerCase();let d="application/octet-stream";if(l===".html"){d="text/html";let h=i.toString("utf-8");const u=h.match(/<script>(window\.__remixContext\s*=\s*\{[\s\S]*?\});?<\/script>/i);if(u)try{const p=u[1].match(/=\s*(\{[\s\S]*\})/);if(p){const f=JSON.parse(p[1]);f.isSpaMode=!0,f.future&&(f.future.v3_lazyRouteDiscovery=!1);const g=`<script>window.__remixContext = ${JSON.stringify(f)};<\/script>`;h=h.replace(u[0],g)}}catch(m){console.error("[Static] Failed to parse Remix context:",m)}i=Buffer.from(h,"utf-8")}else l===".js"||l===".mjs"?d="application/javascript":l===".css"?d="text/css":l===".json"?d="application/json":l===".png"?d="image/png":l===".jpg"||l===".jpeg"?d="image/jpeg":l===".svg"?d="image/svg+xml":l===".woff"?d="font/woff":l===".woff2"?d="font/woff2":l===".ttf"&&(d="font/ttf");return new Response(i,{status:200,headers:{"Content-Type":d,"Cache-Control":"public, max-age=3600","X-Frame-Options":"SAMEORIGIN"}})}catch{return new Response("Static file not found",{status:404})}}const Im=Object.freeze(Object.defineProperty({__proto__:null,loader:Tm},Symbol.toStringTag,{value:"Module"}));function jm(e,t,r=10){var d;const a=new Map,s=h=>h.entityType==="visual"||h.entityType==="library";for(const h of e)s(h)&&a.set(h.sha,{entity:h,depth:0});const o=new Map;for(const h of t){const u=(d=h.metadata)==null?void 0:d.importedBy;if(u)for(const m of Object.keys(u))for(const p of Object.keys(u[m])){const{shas:f}=u[m][p];for(const g of f)o.has(h.sha)||o.set(h.sha,new Set),o.get(h.sha).add(g)}}const i=[],l=new Set;for(const h of e)i.push({sha:h.sha,depth:0}),l.add(h.sha);for(;i.length>0;){const{sha:h,depth:u}=i.shift();if(u>=r)continue;const m=o.get(h);if(m)for(const p of m){if(l.has(p))continue;l.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((h,u)=>h.depth!==u.depth?h.depth-u.depth:h.entity.name.localeCompare(u.entity.name))}function _n(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 h,u;const l=((h=o.metadata)==null?void 0:h.editedAt)||o.createdAt||"";return(((u=i.metadata)==null?void 0:u.editedAt)||i.createdAt||"").localeCompare(l)});r.push(s[0])}return r}function Ks(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 h,u;return a.has(d.filePath)&&((h=d.metadata)==null?void 0:h.isUncommitted)&&!((u=d.metadata)!=null&&u.isSuperseded)}),l=_n(i);r.set(s.path,{status:s,entities:o,editedEntities:l})}return r}function Rm(e,t,r){const a=new Map;if(!r){for(const o of e)if(o.status==="deleted")a.set(o.path,{status:o,entities:[]});else{const i=t.filter(d=>d.filePath===o.path||o.status==="renamed"&&o.oldPath&&d.filePath===o.oldPath),l=_n(i);a.set(o.path,{status:o,entities:l})}return a}const s=new Map;for(const o of r.fileComparisons){const i=new Set;for(const l of o.newEntities)i.add(l.name);for(const l of o.modifiedEntities)i.add(l.name);for(const l of o.deletedEntities)i.add(l.name);i.size>0&&s.set(o.filePath,i)}for(const o of e){const i=s.get(o.path);if(o.status==="deleted")a.set(o.path,{status:o,entities:[]});else{const l=i?t.filter(h=>(h.filePath===o.path||o.status==="renamed"&&o.oldPath&&h.filePath===o.oldPath)&&i.has(h.name)):[],d=_n(l);a.set(o.path,{status:o,entities:d})}}return a}function $m(e,t){const r=new Map,a=Qs(e,t);for(const s of a){const i=jm([s],t).filter(({depth:l})=>l>0);r.set(s.sha,i)}return r}function Qs(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 _n(a)}function Dm({recentSimulations:e}){const t=se(()=>{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 c("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:c("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:e.length>0?`Latest ${e.length} captured screenshot${e.length!==1?"s":""}`:"No simulations captured yet"})]})}),e.length>0?c(ue,{children:[n("div",{className:"space-y-6 mb-5",children:t.map(r=>c("div",{children:[c("div",{className:"mb-3 flex items-center gap-2",children:[n("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center bg-purple-100",children:n(Ht,{size:16,style:{color:"#8B5CF6"}})}),n(oe,{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(oe,{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(Fe,{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(oe,{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 →"})]}):n("div",{className:"flex flex-col items-center",children:c("div",{className:"py-12 px-6 text-center bg-gray-50 rounded-lg w-full flex flex-col items-center justify-center min-h-50",children:[n("div",{className:"mb-4 bg-[#efefef] rounded-lg p-3",children:n(Ht,{size:28,style:{color:"#999999"},strokeWidth:1.5})}),n("p",{className:"text-gray-700 m-0 font-semibold",children:"No simulations captured yet."}),n("p",{className:"text-sm text-gray-500 m-0 mt-2",children:"Run analysis on your visual components to create simulations and capture screenshots."})]})})]})}const Lm="/assets/codeyam-name-logo-CvKwUgHo.svg",Om=()=>[{title:"Dashboard - CodeYam"},{name:"description",content:"CodeYam project dashboard"}];async function Fm({request:e,context:t}){var r,a;try{const s=t.analysisQueue,o=s?s.getState():{paused:!1,jobs:[]},[i,l,d]=await Promise.all([Xt(),ze(),kt()]),h=Bs(),u=i?Ks(h,i):new Map,m=Array.from(u.entries()).sort((N,$)=>N[0].localeCompare($[0])),p=(i==null?void 0:i.length)||0,f=(i==null?void 0:i.filter(N=>N.entityType==="visual").length)||0,g=(i==null?void 0:i.filter(N=>N.entityType==="library").length)||0,y=i?Qs(h,i):[],b=y.length,x=(i==null?void 0:i.filter(N=>(N.analyses??[]).filter($=>$.scenarios&&$.scenarios.length>0).length>0).length)||0,w=(i==null?void 0:i.reduce((N,$)=>{var S,E,R;const _=((R=(E=(S=$.analyses)==null?void 0:S[0])==null?void 0:E.scenarios)==null?void 0:R.length)||0;return N+_},0))||0,v=(i==null?void 0:i.reduce((N,$)=>{var E,R;const S=(((R=(E=$.analyses)==null?void 0:E[0])==null?void 0:R.scenarios)||[]).filter(D=>{var O,H;return(H=(O=D.metadata)==null?void 0:O.screenshotPaths)==null?void 0:H[0]}).length;return N+S},0))||0,C=[];i==null||i.forEach(N=>{var _;const $=(_=N.analyses)==null?void 0:_[0];$!=null&&$.scenarios&&$.scenarios.filter(E=>{var R;return!((R=E.metadata)!=null&&R.sameAsDefault)}).forEach(E=>{var D,O;const R=(O=(D=E.metadata)==null?void 0:D.screenshotPaths)==null?void 0:O[0];R&&C.push({entitySha:N.sha,entityName:N.name,scenarioId:E.id,scenarioName:E.name,screenshotPath:R,createdAt:$.createdAt||""})})}),C.sort((N,$)=>new Date($.createdAt).getTime()-new Date(N.createdAt).getTime());const k=C.slice(0,16),A=(i==null?void 0:i.filter(N=>N.entityType==="visual").filter(N=>{var S,E;const $=(S=N.analyses)==null?void 0:S[0];return!((E=$==null?void 0:$.scenarios)==null?void 0:E.some(R=>{var D,O;return(O=(D=R.metadata)==null?void 0:D.screenshotPaths)==null?void 0:O[0]}))}).slice(0,8))||[],P=(r=d==null?void 0:d.metadata)==null?void 0:r.currentRun,M=((a=P==null?void 0:P.currentEntityShas)==null?void 0:a.length)||0,I=o.jobs.length||0;return z({stats:{totalEntities:p,visualEntities:f,libraryEntities:g,uncommittedEntities:b,entitiesWithAnalyses:x,totalScenarios:w,capturedScreenshots:v,currentlyAnalyzing:M,filesOnQueue:I},uncommittedFiles:m,uncommittedEntitiesList:y,recentSimulations:k,visualEntitiesForSimulation:A,projectSlug:l,queueState:o,currentCommit:d})}catch(s){return console.error("Failed to load dashboard data:",s),z({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 Ym=We(function(){var Q,q;const{stats:t,uncommittedFiles:r,uncommittedEntitiesList:a,recentSimulations:s,visualEntitiesForSimulation:o,projectSlug:i,queueState:l,currentCommit:d}=Ke(),h=ke(),u=ht(),{showToast:m}=wr();Et({source:"dashboard"});const[p,f]=j(new Set),[g,y]=j(null),[b,x]=j(!1),[w,v]=j(!1),{lastLine:C,isCompleted:k}=mt(i,!!g),{simulatingEntity:A,scenarios:P,scenarioStatuses:M,allScenariosCaptured:I}=se(()=>{var B,W;const L={simulatingEntity:null,scenarios:[],scenarioStatuses:[],allScenariosCaptured:!1};if(!g)return L;const T=o==null?void 0:o.find(Z=>Z.sha===g);if(!T)return L;const U=(B=T.analyses)==null?void 0:B[0],Y=(U==null?void 0:U.scenarios)||[],V=((W=U==null?void 0:U.status)==null?void 0:W.scenarios)||[],le=V.filter(Z=>Z.screenshotFinishedAt).length,G=Y.length>0&&le===Y.length;return{simulatingEntity:T,scenarios:Y,scenarioStatuses:V,allScenariosCaptured:G}},[g,o]);ne(()=>{(k||I)&&y(null)},[k,I]);const N=(Q=d==null?void 0:d.metadata)==null?void 0:Q.currentRun,$=new Set((N==null?void 0:N.currentEntityShas)||[]),_=new Set(l.jobs.flatMap(L=>L.entityShas||[])),S=new Set(((q=l.currentlyExecuting)==null?void 0:q.entityShas)||[]),E=a.filter(L=>L.entityType==="visual"||L.entityType==="library"),R=E.filter(L=>!$.has(L.sha)&&!_.has(L.sha)&&!S.has(L.sha)),D=()=>{if(R.length===0){m("All entities are already queued or analyzing","info",3e3);return}const L=R.map(T=>T.sha);v(!0),m(`Starting analysis for ${R.length} entities...`,"info",3e3),h.submit({entityShas:L.join(",")},{method:"post",action:"/api/analyze"})};ne(()=>{if(h.state==="idle"&&h.data){const L=h.data;L.success?(console.log("[Analyze All] Success:",L.message),m(`Analysis started for ${L.entityCount} entities in ${L.fileCount} files. Watch the logs for progress.`,"success",6e3),v(!1)):L.error&&(console.error("[Analyze All] Error:",L.error),m(`Error: ${L.error}`,"error",8e3),v(!1))}},[h.state,h.data,m]);const O=L=>{f(T=>{const U=new Set(T);return U.has(L)?U.delete(L):U.add(L),U})},H=[{label:"Total Entities",value:t.totalEntities,iconType:"folder",link:"/files",color:"#F59E0B"},{label:"Analyzed Entities",value:t.entitiesWithAnalyses,iconType:"check",link:"/simulations",color:"#10B981"},{label:"Visual Components",value:t.visualEntities,iconType:"image",link:"/files?entityType=visual",color:"#8B5CF6"},{label:"Library Functions",value:t.libraryEntities,iconType:"code-xml",link:"/files?entityType=library",color:"#0DBFE9"}];return n("div",{className:"bg-cygray-10 min-h-screen",children:c("div",{className:"px-20 py-12",children:[c("header",{className:"mb-8 flex justify-between items-center",children:[c("div",{className:"flex items-center gap-2",children:[n("img",{src:Lm,alt:"CodeYam",className:"h-3.5"}),n("span",{className:"text-gray-400 text-sm",children:"|"}),c("h1",{className:"text-sm font-normal text-gray-600 m-0",children:["Overview of"," ",n("span",{className:"font-semibold",children:i?i.replace(/-/g," ").replace(/\b\w/g,L=>L.toUpperCase()):"Project"})]})]}),u.state==="loading"&&n("div",{className:"text-blue-600 text-sm font-medium animate-pulse",children:"🔄 Updating..."})]}),n("div",{className:"flex items-center justify-between gap-3",children:H.map((L,T)=>n(oe,{to:L.link,className:"flex-1 bg-white rounded-xl border border-gray-200 overflow-hidden flex transition-all hover:shadow-lg hover:-translate-y-0.5 no-underline cursor-pointer",style:{borderLeft:`4px solid ${L.color}`},children:c("div",{className:"px-6 py-4 flex flex-col gap-3 flex-1",children:[c("div",{className:"flex md:justify-between md:items-start md:flex-row flex-col",children:[n("div",{className:"text-xs text-gray-700 font-medium",children:L.label}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 sm:hidden md:flex",style:{color:L.color},children:"View All →"})]}),c("div",{className:"flex flex-col gap-2",children:[c("div",{className:"flex items-center gap-3",children:[c("div",{className:"rounded-lg p-2 leading-none shrink-0",style:{backgroundColor:`${L.color}15`},children:[L.iconType==="folder"&&n(zo,{size:20,style:{color:L.color}}),L.iconType==="check"&&n(pr,{size:20,style:{color:L.color}}),L.iconType==="image"&&n(Ht,{size:20,style:{color:L.color}}),L.iconType==="code-xml"&&n(Bo,{size:20,style:{color:L.color}})]}),n("div",{className:"text-2xl font-bold text-gray-900 leading-none",children:L.value})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 md:hidden",style:{color:L.color},children:"View All →"})]})]})},T))}),c("div",{className:"mt-12 grid gap-8 items-start",style:{gridTemplateColumns:"repeat(auto-fit, minmax(500px, 1fr))"},children:[c("section",{id:"uncommitted",className:"bg-white border border-gray-200 rounded-xl p-6",children:[c("div",{className:"flex justify-between items-start mb-5",children:[c("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Uncommitted Changes"}),n("p",{className:"text-sm text-gray-500 m-0",children:r.length>0?`${r.length} file${r.length!==1?"s":""} with ${a.length} uncommitted entit${a.length!==1?"ies":"y"}`:"No uncommitted changes detected"})]}),E.length>0&&n("button",{onClick:D,disabled:h.state!=="idle"||w||R.length===0,className:"px-5 py-2.5 text-white border-none rounded-lg text-sm font-semibold cursor-pointer transition-all hover:-translate-y-px disabled:bg-gray-400 disabled:cursor-not-allowed disabled:translate-y-0",style:{backgroundColor:"#005C75"},onMouseEnter:L=>L.currentTarget.style.backgroundColor="#004560",onMouseLeave:L=>L.currentTarget.style.backgroundColor="#005C75",children:h.state!=="idle"||w?"Starting analysis...":R.length===0?"All Queued":"Analyze All"})]}),r.length>0?n("div",{className:"flex flex-col gap-3",children:r.map(([L,T])=>{const U=p.has(L),Y=T.editedEntities||[];return c("div",{className:"bg-white border border-gray-200 border-l-4 rounded-lg overflow-hidden",style:{borderLeftColor:"#306AFF"},children:[n("div",{className:"p-4 cursor-pointer select-none transition-colors hover:bg-gray-50",onClick:()=>O(L),role:"button",tabIndex:0,children:c("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-gray-500 text-xs w-4 shrink-0",children:U?"▼":"▶"}),c("svg",{width:"16",height:"20",viewBox:"0 0 12 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"shrink-0",children:[c("g",{clipPath:"url(#clip0_784_10666)",children:[n("path",{d:"M0 2.55857C0 1.14551 1.14551 0 2.55857 0H8.73194L12 3.3616V13.4414C12 14.8545 10.8545 16 9.44143 16H2.55857C1.14551 16 0 14.8545 0 13.4414V2.55857Z",fill:"#DDDDFE"}),n("path",{d:"M8.72656 3.3307H11.9906L8.72656 0V3.3307Z",fill:"#306AFF"}),n("line",{x1:"1.8125",y1:"5.94825",x2:"10.0235",y2:"5.94825",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"8.82715",x2:"6.01207",y2:"8.82715",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"11.7061",x2:"10.0235",y2:"11.7061",stroke:"#306AFF",strokeWidth:"1.27929"})]}),n("defs",{children:n("clipPath",{id:"clip0_784_10666",children:n("rect",{width:"12",height:"16",fill:"white"})})})]}),c("div",{className:"flex-1 min-w-0",children:[n("span",{className:"font-normal text-gray-900 text-sm block truncate",children:L}),c("span",{className:"text-xs text-gray-500",children:[Y.length," entit",Y.length!==1?"ies":"y"]})]})]})}),U&&n("div",{className:"border-t border-gray-200 bg-gray-50 p-3 flex flex-col gap-2",children:Y.length>0?Y.map(V=>{const le=$.has(V.sha),G=_.has(V.sha)||S.has(V.sha);return c(oe,{to:`/entity/${V.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:B=>B.currentTarget.style.borderColor="#005C75",onMouseLeave:B=>B.currentTarget.style.borderColor="inherit",children:[c("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center",style:{backgroundColor:V.entityType==="visual"?"#8B5CF615":V.entityType==="library"?"#6366F1":"#EC4899"},children:[V.entityType==="visual"&&n(Ht,{size:16,style:{color:"#8B5CF6"}}),V.entityType==="library"&&n(Ja,{size:16,className:"text-white"}),V.entityType==="other"&&n(Uo,{size:16,className:"text-white"})]}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 mb-0.5",children:[n("div",{className:"font-semibold text-gray-900 text-sm",children:V.name}),V.entityType==="visual"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#8B5CF60D",color:"#8B5CF6"},children:"Visual"}),V.entityType==="library"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#0DBFE90D",color:"#0DBFE9"},children:"Library"}),V.entityType==="other"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#EC48990D",color:"#EC4899"},children:"Other"})]}),V.description&&n("div",{className:"text-sm text-gray-500 mt-1 overflow-hidden text-ellipsis whitespace-nowrap",children:V.description})]}),c("div",{className:"flex items-center gap-2 shrink-0",children:[le&&c("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(at,{size:14,className:"animate-spin"}),"Analyzing..."]}),!le&&G&&n("div",{className:"px-2 py-1 bg-purple-50 border border-purple-300 rounded text-xs text-purple-700 font-semibold",children:"⏳ Queued"}),!le&&!G&&n("button",{onClick:B=>{B.preventDefault(),B.stopPropagation(),m(`Starting analysis for ${V.name}...`,"info",3e3),h.submit({entityShas:V.sha},{method:"post",action:"/api/analyze"})},disabled:h.state!=="idle",className:"px-3 py-1.5 text-white border-none rounded text-xs font-medium cursor-pointer transition-all disabled:bg-gray-400 disabled:cursor-not-allowed",style:{backgroundColor:"#005C75"},onMouseEnter:B=>B.currentTarget.style.backgroundColor="#004560",onMouseLeave:B=>B.currentTarget.style.backgroundColor="#005C75",children:"Analyze"})]})]},V.sha)}):n("div",{className:"text-sm text-gray-500 italic p-2",children:"No entity changes detected in this file"})})]},L)})}):c("div",{className:"py-12 px-6 text-center flex flex-col items-center bg-gray-50 rounded-lg min-h-50 justify-center",children:[c("svg",{width:"52",height:"68",viewBox:"0 0 26 34",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"mb-4 opacity-40",children:[c("g",{clipPath:"url(#clip0_784_10631)",children:[n("path",{d:"M0 2.55857C0 1.14551 1.14551 0 2.55857 0H18.9423L26.0318 7.14651V31.4562C26.0318 32.8693 24.8863 34.0148 23.4732 34.0148H2.55857C1.14551 34.0148 0 32.8693 0 31.4562V2.55857Z",fill:"#D9D9D9"}),n("path",{d:"M18.9453 7.08081H26.0261L18.9453 0V7.08081Z",fill:"#646464"}),n("line",{x1:"3.92188",y1:"13.3633",x2:"21.7341",y2:"13.3633",stroke:"#646464",strokeWidth:"1.27929"}),n("line",{x1:"3.92188",y1:"19.4863",x2:"13.0321",y2:"19.4863",stroke:"#646464",strokeWidth:"1.27929"}),n("line",{x1:"3.92188",y1:"25.6016",x2:"21.7341",y2:"25.6016",stroke:"#646464",strokeWidth:"1.27929"})]}),n("defs",{children:n("clipPath",{id:"clip0_784_10631",children:n("rect",{width:"26",height:"34",fill:"white"})})})]}),n("p",{className:"text-sm font-medium text-gray-400 m-0 mb-2",children:"No Uncommitted Changes."})]})]}),!g&&n(Dm,{recentSimulations:s}),g&&c("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:c("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:s.length>0?`Latest ${s.length} captured screenshot${s.length!==1?"s":""}`:"No simulations captured yet"})]})}),g&&c("div",{className:"p-0 bg-white rounded-lg flex flex-col gap-0",children:[A&&n("div",{className:"p-4 rounded-t-lg",style:{backgroundColor:"#F0F5F8",borderBottom:"2px solid #005C75"},children:c("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-[32px] leading-none",children:n(Ue,{type:"visual"})}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"text-base font-bold mb-1",style:{color:"#005C75"},children:["Generating Simulations for ",A.name]}),n("div",{className:"text-[13px] text-gray-500 font-mono overflow-hidden text-ellipsis whitespace-nowrap",children:A.filePath})]})]})}),I?c("div",{className:"flex items-center gap-2 text-sm text-emerald-600 font-medium p-4 bg-emerald-50",children:[n("span",{className:"text-lg",children:"✅"}),c("span",{children:["Complete (",P.length," scenario",P.length!==1?"s":"",")"]})]}):C?c("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(at,{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:()=>x(!0),className:"px-2 py-1.5 bg-gray-500 text-white border-none rounded-md text-[13px] font-medium cursor-pointer transition-all whitespace-nowrap self-start hover:bg-gray-600 hover:-translate-y-px",title:"View analysis logs",children:"📋 Logs"})]}):h.state!=="idle"?c("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(at,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Initializing analysis..."})]}):c("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(at,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Starting analysis..."})]}),P.length>0&&n("div",{className:"flex gap-2 flex-wrap p-4 bg-white border-t border-gray-200",children:P.slice(0,8).map((L,T)=>{var G,B;const U=(B=(G=L.metadata)==null?void 0:G.screenshotPaths)==null?void 0:B[0],Y=M.find(W=>W.name===L.name),V=(Y==null?void 0:Y.screenshotStartedAt)&&!(Y!=null&&Y.screenshotFinishedAt);return U?n(oe,{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(Fe,{screenshotPath:U,alt:L.name,title:L.name,className:"max-w-full max-h-full object-contain object-center"})},T):n("div",{className:"w-20 h-15 border-2 border-dashed border-gray-300 rounded bg-gray-50 flex items-center justify-center text-2xl",title:`Capturing ${L.name}...`,children:n("span",{className:V?"animate-pulse":"text-gray-400",children:V?"⋯":"⏹️"})},T)})})]})]})]}),b&&i&&n(Rt,{projectSlug:i,onClose:()=>x(!1)})]})})}),zm=Object.freeze(Object.defineProperty({__proto__:null,default:Ym,loader:Fm,meta:Om},Symbol.toStringTag,{value:"Module"}));function nr(e){return`${e.filePath||""}::${e.name}`}function Zs(e,t){const r=ke(),{showToast:a}=wr(),[s,o]=j(new Map);ne(()=>{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]),ne(()=>{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(b=>{s.forEach((x,w)=>{x===b&&p.add(w)})})}),e==null||e.forEach(g=>{s.forEach((y,b)=>{y===g&&p.add(b)})}),p.size>0&&o(g=>{const y=new Map(g);return p.forEach(b=>y.delete(b)),y})},[t,e,s]);const i=re(p=>{console.log("Generate analysis clicked for entity:",p.sha,p.name);const f=nr(p);o(y=>new Map(y).set(f,p.sha));const g=new FormData;g.append("entitySha",p.sha),g.append("filePath",p.filePath||""),r.submit(g,{method:"post",action:"/api/analyze"})},[r]),l=re(p=>{const f=p.filter(b=>b.entityType==="visual"||b.entityType==="library");console.log("Generate analysis for all entities:",f.length),o(b=>{const x=new Map(b);return f.forEach(w=>x.set(nr(w),w.sha)),x});const g=f.map(b=>b.sha).join(","),y=new FormData;y.append("entityShas",g),r.submit(y,{method:"post",action:"/api/analyze"})},[r]),d=re(p=>(e==null?void 0:e.includes(p))??!1,[e]),h=re(p=>{const f=nr(p);return s.has(f)},[s]),u=re(p=>{var f;return((f=t==null?void 0:t.jobs)==null?void 0:f.some(g=>{var y;return(y=g.entityShas)==null?void 0:y.includes(p)}))??!1},[t]),m=se(()=>Array.from(s.keys()),[s]);return{isAnalyzing:r.state!=="idle",handleGenerateSimulation:i,handleGenerateAllSimulations:l,isEntityBeingAnalyzed:d,isEntityPending:h,isEntityInQueue:u,pendingEntityKeys:m}}function Lr({showActions:e=!1,sortOrder:t="desc",onSortChange:r,onAnalyzeAll:a,analyzeAllDisabled:s=!1,analyzeAllText:o="Analyze All"}){return n("div",{className:"bg-[#efefef] rounded-lg mb-2 text-[11px] font-normal leading-[16px] text-[#3e3e3e] uppercase",children:c("div",{className:"flex justify-between items-center px-3 py-2",children:[c("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4"}),n("span",{children:"FILE"})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:n("span",{children:"UNCOMMITTED"})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:n("span",{children:"SIMULATIONS"})}),c("div",{className:"flex gap-4 items-center",children:[n("span",{className:"text-center",style:{width:"70px"},children:"ENTITIES"}),c("div",{className:"flex items-center justify-center gap-1 cursor-pointer hover:text-[#232323] transition-colors",style:{width:"116px"},onClick:r,role:"button",tabIndex:0,onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),r==null||r())},children:[n("span",{children:"MODIFIED"}),n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{transform:t==="asc"?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease"},children:n("path",{d:"M3 5L6 8L9 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),e&&n("div",{className:"text-center",style:{width:"127px"},children:a&&n("button",{onClick:a,disabled:s,className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-medium hover:bg-[#004a5e] transition-colors cursor-pointer disabled:bg-gray-400 disabled:cursor-not-allowed whitespace-nowrap px-3 py-1.5 normal-case",title:s?o:"Analyze all entities",children:o})})]})]})]})})}function Bm({status:e,variant:t="compact"}){const r={modified:{label:"M",bgColor:"bg-[#f59e0c]"},added:{label:"A",bgColor:"bg-emerald-500"},deleted:{label:"D",bgColor:"bg-red-500",showWarning:!0},renamed:{label:"R",bgColor:"bg-indigo-500"},untracked:{label:"U",bgColor:"bg-purple-500"}},a={modified:{label:"MODIFIED",textColor:"#BB6BD9"},added:{label:"ADDED",textColor:"#F2994A"},deleted:{label:"DELETED",textColor:"#EF4444"},renamed:{label:"RENAMED",textColor:"#3B82F6"},untracked:{label:"UNTRACKED",textColor:"#6B7280"}};if(t==="full"){const o=a[e]||{label:"UNKNOWN",textColor:"#6B7280"};return n("div",{className:"bg-[#f9f9f9] inline-flex items-center justify-center px-[5px] py-0 rounded",style:{height:"22px"},children:n("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-medium leading-[22px]",style:{color:o.textColor},children:o.label})})}const s=r[e]||{label:"?",bgColor:"bg-gray-500"};return c("div",{className:"inline-flex items-center gap-1",children:[n("span",{className:`inline-flex items-center justify-center w-5 h-5 text-[11px] font-bold text-white rounded ${s.bgColor}`,title:e,children:s.label}),s.showWarning&&n("span",{className:"inline-flex items-center justify-center w-3 h-3 text-[10px] text-amber-600",title:"Warning: File will be deleted",children:"⚠"})]})}function Or({filePath:e,isExpanded:t,onToggle:r,fileStatus:a,simulationPreviews:s,entityCount:o,state:i,lastModified:l,actionButton:d,uncommittedCount:h,children:u,isNotAnalyzable:m=!1,isUncommitted:p=!1}){return c("div",{className:"bg-white overflow-hidden",style:t?{border:"1px solid #e1e1e1",borderLeft:"4px solid #306AFF",borderRadius:"8px"}:{borderBottom:"1px solid #e1e1e1"},children:[c("div",{className:`flex justify-between items-center p-3 cursor-pointer select-none transition-colors ${m?"opacity-50":"hover:bg-gray-200"}`,style:{outlineColor:"#005C75"},onClick:r,role:"button",tabIndex:0,onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),r())},children:[c("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:t?"rotate(90deg)":"none"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:t?"#3e3e3e":"#c7c7c7"})})}),n("img",{src:"/icons/file-icon.svg",alt:"file",className:"w-4 h-5 shrink-0"}),n(rs,{filePath:e}),a&&n(Bm,{status:typeof a=="string"?a:a.status,variant:"full"})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:(p||i==="out-of-date")&&c("div",{className:"flex gap-1.5 items-center",children:[p&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fff3cd",color:"#856404",height:"22px"},children:"Uncommitted"}),i==="out-of-date"&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:s}),c("div",{className:"flex gap-4 items-center",children:[n("div",{className:"flex items-center justify-center",style:{width:"70px"},children:n("div",{className:"bg-[#f9f9f9] flex items-center justify-center px-2 rounded whitespace-nowrap",style:{height:"26px"},children:c("span",{className:"text-[13px] text-[#3e3e3e]",children:[o," ",o===1?"entity":"entities"]})})}),n("div",{className:"text-[12px] text-gray-600 text-center",style:{width:"116px"},children:qs(l)}),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 Fr({entities:e,maxPreviews:t=3}){var a,s,o,i,l;const r=[];for(const d of e){if(r.length>=t)break;const h=((s=(a=d.analyses)==null?void 0:a[0])==null?void 0:s.scenarios)||[];if(d.entityType==="library"){const u=h.find(m=>{var p,f;return((p=m.metadata)==null?void 0:p.executionResult)||((f=m.metadata)==null?void 0:f.error)});u&&r.push({type:"library",scenario:u,entitySha:d.sha})}else if(d.entityType==="visual"){const u=h.find(m=>{var p,f;return(f=(p=m.metadata)==null?void 0:p.screenshotPaths)==null?void 0:f[0]});if(u){const m=(i=(o=u.metadata)==null?void 0:o.screenshotPaths)==null?void 0:i[0],p=!!((l=u.metadata)!=null&&l.error);m&&r.push({type:"screenshot",screenshot:m,hasError:p,scenario:u,entitySha:d.sha})}}}return r.length===0?n("span",{className:"text-gray-400 font-light text-[14px]",children:"—"}):n(ue,{children:r.map((d,h)=>{if(d.type==="screenshot"&&d.screenshot){const u=d.hasError?"border-red-400":"border-gray-200";return c(oe,{to:d.scenario?`/entity/${d.entitySha}/scenarios/${d.scenario.id}`:`/entity/${d.entitySha}`,className:`relative w-[50px] h-[38px] border ${u} rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,onClick:m=>m.stopPropagation(),children:[n(Fe,{screenshotPath:d.screenshot,alt:`Preview ${h+1}`,className:"max-w-full max-h-full object-contain object-center"}),d.hasError&&n("div",{className:"absolute top-0 right-0 w-4 h-4 bg-red-500 text-white flex items-center justify-center text-[10px] rounded-bl",title:"Error during capture",children:n(rr,{size:12,color:"white"})})]},`screenshot-${h}`)}return d.type==="library"&&d.scenario&&d.entitySha?n(Gs,{scenario:d.scenario,entitySha:d.entitySha,size:"small",showBorder:!0},`library-${h}`):null})})}function Yr({entity:e,isActivelyAnalyzing:t,isQueued:r,onGenerateSimulation:a}){var u,m;const s=t||r?[{entityShas:[e.sha]}]:[],o=Je(e,s,t),i=e.entityType==="visual"||e.entityType==="library",l=i&&(o==="not-analyzed"||o==="out-of-date")&&!t&&!r,h=(((m=(u=e.analyses)==null?void 0:u[0])==null?void 0:m.scenarios)||[]).filter(p=>{var f,g;return(g=(f=p.metadata)==null?void 0:f.screenshotPaths)==null?void 0:g[0]});return c("div",{className:"bg-white rounded-lg",children:[c(oe,{to:`/entity/${e.sha}`,className:"flex items-center justify-between p-3 transition-colors hover:bg-gray-100 cursor-pointer",children:[c("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 shrink-0"}),e.entityType==="type"?n("div",{className:"bg-[#ffe1e1] inline-flex items-center justify-center px-[4px] rounded-[4px]",style:{height:"18px",width:"18px"},children:n("div",{className:"w-[10px] h-[10px] flex items-center justify-center",children:n(Ue,{type:"type"})})}):n(Ue,{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(Ir,{type:e.entityType||"other"})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{style:{width:"160px"}}),c("div",{className:"flex gap-4 items-center",children:[n("div",{style:{width:"70px"}}),n("div",{style:{width:"116px"}}),n("div",{style:{width:"127px"},className:"flex justify-center items-center",children:i?o==="queued"?c("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#cbf3fa",color:"#3098b4",height:"26px"},children:[c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]}),"Queued"]}):o==="analyzing"?c("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[c("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):o==="up-to-date"?n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):o==="out-of-date"?n("button",{onClick:p=>{p.preventDefault(),p.stopPropagation(),a(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-medium hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):l&&n("button",{onClick:p=>{p.preventDefault(),p.stopPropagation(),a(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-medium hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Analyze"}):n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"})})]})]})]}),h.length>0&&n("div",{className:"px-3 pb-3 pt-0 flex items-center gap-2 pl-[52px]",children:h.map((p,f)=>{var y,b;const g=(b=(y=p.metadata)==null?void 0:y.screenshotPaths)==null?void 0:b[0];return g?n(oe,{to:`/entity/${e.sha}?scenario=${p.id}`,className:"relative w-[120px] h-[90px] border border-gray-200 rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center hover:border-gray-400 transition-colors",onClick:x=>x.stopPropagation(),children:n(Fe,{screenshotPath:g,alt:p.name,className:"max-w-full max-h-full object-contain object-center"})},p.id):null})})]})}function Um({entities:e,page:t,itemsPerPage:r=50,currentRun:a,filter:s,entityType:o,queueState:i,isEntityPending:l,pendingEntityKeys:d,onGenerateSimulation:h,onGenerateAllSimulations:u,totalFilesCount:m,totalEntitiesCount:p,uncommittedFilesCount:f,showOnlyUncommitted:g,onToggleUncommitted:y}){const[b,x]=qt(),[w,v]=j(new Set),[C,k]=j(""),[A,P]=j(!1),[M,I]=j("all"),[N,$]=j("desc"),_=o||"all",S=se(()=>{let T=e;return _!=="all"&&(T=T.filter(U=>U.entityType===_)),s==="analyzed"&&(T=T.filter(U=>U.analyses&&U.analyses.length>0)),T},[e,_,s]),E=se(()=>{const T=new Map,U=new Map,Y=new Map;S.forEach(B=>{var F,te;const W=`${B.filePath}::${B.name}`,Z=U.get(W);if(!Z)U.set(W,B),Y.set(W,[]);else{const ce=((F=Z.metadata)==null?void 0:F.editedAt)||Z.createdAt||"",he=((te=B.metadata)==null?void 0:te.editedAt)||B.createdAt||"";let fe=!1;if(he>ce)fe=!0;else if(he===ce){const Ce=Z.createdAt||"";fe=(B.createdAt||"")>Ce}fe?(Y.get(W).push(Z),U.set(W,B)):Y.get(W).push(B)}}),U.forEach((B,W)=>{var F;if(!(B.analyses&&B.analyses.length>0)&&((F=B.metadata)!=null&&F.previousVersionWithAnalyses)){const ce=(Y.get(W)||[]).find(he=>{var fe;return he.sha===((fe=B.metadata)==null?void 0:fe.previousVersionWithAnalyses)});ce&&ce.analyses&&ce.analyses.length>0&&(B.analyses=ce.analyses)}}),Array.from(U.values()).sort((B,W)=>{var te,ce,he,fe;const Z=!((te=B.metadata)!=null&&te.notExported)&&!((ce=B.metadata)!=null&&ce.namedExport),F=!((he=W.metadata)!=null&&he.notExported)&&!((fe=W.metadata)!=null&&fe.namedExport);return Z&&!F?-1:!Z&&F?1:0}).forEach(B=>{var ce,he,fe,Ce,Se;const W=B.filePath??"No File Path";T.has(W)||T.set(W,{filePath:W,entities:[],totalCount:0,uncommittedCount:0,lastUpdated:null,previewScreenshots:[],previewScreenshotErrors:[],previewLibraryScenarios:[],state:"up-to-date",simulationCount:0});const Z=T.get(W);Z.entities.push(B),Z.totalCount++,(ce=B.metadata)!=null&&ce.isUncommitted&&Z.uncommittedCount++;const F=((Ce=(fe=(he=B.analyses)==null?void 0:he[0])==null?void 0:fe.scenarios)==null?void 0:Ce.length)||0;Z.simulationCount+=F;const te=((Se=B.metadata)==null?void 0:Se.editedAt)||B.updatedAt;te&&(!Z.lastUpdated||new Date(te)>new Date(Z.lastUpdated))&&(Z.lastUpdated=te)});const V=(i==null?void 0:i.jobs)||[],le=B=>{const W=`${B.filePath||""}::${B.name}`;return(d==null?void 0:d.includes(W))||!1};T.forEach(B=>{const W=B.entities.map(Z=>le(Z)?"queued":Je(Z,V));W.includes("analyzing")||W.includes("queued")?B.state="analyzing":W.includes("incomplete")?B.state="incomplete":W.includes("out-of-date")?B.state="out-of-date":W.includes("not-analyzed")?B.state="not-analyzed":B.state="up-to-date"}),T.forEach(B=>{var W,Z,F,te,ce;for(const he of B.entities){if(B.previewScreenshots.length+B.previewLibraryScenarios.length>=3)break;const Ce=((Z=(W=he.analyses)==null?void 0:W[0])==null?void 0:Z.scenarios)||[];if(he.entityType==="library"){const Se=Ce.find(Ae=>{var Ee,De;return((Ee=Ae.metadata)==null?void 0:Ee.executionResult)||((De=Ae.metadata)==null?void 0:De.error)});Se&&B.previewLibraryScenarios.push({scenario:Se,entitySha:he.sha})}else{const Se=Ce.find(Ae=>{var Ee,De;return(De=(Ee=Ae.metadata)==null?void 0:Ee.screenshotPaths)==null?void 0:De[0]});if(Se){const Ae=(te=(F=Se.metadata)==null?void 0:F.screenshotPaths)==null?void 0:te[0],Ee=!!((ce=Se.metadata)!=null&&ce.error);Ae&&!B.previewScreenshots.includes(Ae)&&(B.previewScreenshots.push(Ae),B.previewScreenshotErrors.push(Ee))}}}});const G=Array.from(T.values());return G.sort((B,W)=>{if(s==="analyzed"){const te=Math.max(...B.entities.filter(he=>{var fe,Ce;return(Ce=(fe=he.analyses)==null?void 0:fe[0])==null?void 0:Ce.createdAt}).map(he=>new Date(he.analyses[0].createdAt).getTime()),0),ce=Math.max(...W.entities.filter(he=>{var fe,Ce;return(Ce=(fe=he.analyses)==null?void 0:fe[0])==null?void 0:Ce.createdAt}).map(he=>new Date(he.analyses[0].createdAt).getTime()),0);return N==="desc"?ce-te:te-ce}if(B.uncommittedCount>0&&W.uncommittedCount===0)return-1;if(B.uncommittedCount===0&&W.uncommittedCount>0)return 1;const Z=B.lastUpdated?new Date(B.lastUpdated).getTime():0,F=W.lastUpdated?new Date(W.lastUpdated).getTime():0;return N==="desc"?F-Z:Z-F}),G},[S,s,N,i,d]),R=se(()=>{let T=E;if(M!=="all"&&(T=T.filter(U=>U.state===M)),C.trim()){const U=C.toLowerCase();T=T.filter(Y=>Y.filePath.toLowerCase().includes(U))}return T},[E,C,M]),D=(t-1)*r,O=D+r,H=R.slice(D,O),Q=Math.ceil(R.length/r),q=T=>{v(U=>{const Y=new Set(U);return Y.has(T)?Y.delete(T):Y.add(T),Y})},L=()=>{$(T=>T==="desc"?"asc":"desc")};return c("div",{children:[c("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),c("div",{className:"flex gap-3",children:[c("div",{className:"relative w-[130px]",children:[c("select",{value:_,onChange:T=>{const U=T.target.value,Y=new URLSearchParams(b);U==="all"?Y.delete("entityType"):Y.set("entityType",U),Y.set("page","1"),x(Y)},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(bn,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),c("div",{className:"relative w-[130px]",children:[c("select",{value:M,onChange:T=>I(T.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(bn,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),c("div",{className:"flex-1 relative",children:[n(Ka,{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:T=>k(T.target.value),className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})]})]}),m!==void 0&&p!==void 0&&f!==void 0&&n("div",{className:"mb-3",children:c("div",{className:"flex items-center justify-between text-[13px]",children:[c("div",{className:"flex items-center gap-3",children:[c("span",{className:"text-gray-900",children:[R.length," ",R.length===1?"file":"files"]}),n("span",{className:"text-gray-300",children:"|"}),c("div",{className:"flex items-center gap-1 group relative",children:[c("span",{className:"text-gray-900",children:[R.reduce((T,U)=>T+U.totalCount,0)," ",R.reduce((T,U)=>T+U.totalCount,0)===1?"entity":"entities"]}),c("svg",{className:"w-3.5 h-3.5 text-[#001f3f]",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[n("circle",{cx:"12",cy:"12",r:"10",strokeWidth:"2"}),n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 16v-4m0-4h.01"})]}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:c("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"text-gray-300",children:"|"}),g?c("button",{onClick:y,className:"flex items-center gap-2 font-medium text-[#005c75] underline hover:text-[#004a5e] transition-colors",children:[R.filter(T=>T.uncommittedCount>0).length," ","uncommitted"," ",R.filter(T=>T.uncommittedCount>0).length===1?"file":"files",n("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M6 18L18 6M6 6l12 12"})})]}):c("button",{onClick:y,className:"font-medium text-[#005c75] underline hover:text-[#004a5e] transition-colors",children:[f," uncommitted"," ",f===1?"file":"files"]})]}),H.length>0&&c("div",{className:"flex gap-6",children:[n("button",{onClick:()=>{v(new Set(H.map(T=>T.filePath))),P(!0)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-medium transition-all cursor-pointer px-3 py-1 rounded",children:"Expand All"}),n("button",{onClick:()=>{v(new Set),P(!1)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-medium transition-all cursor-pointer px-3 py-1 rounded",children:"Collapse All"})]})]})}),n(Lr,{showActions:!0,sortOrder:N,onSortChange:L}),n("div",{className:"flex flex-col gap-[3px]",children:H.map(T=>{const U=w.has(T.filePath),V=T.entities.filter(W=>(W.entityType==="visual"||W.entityType==="library")&&(Je(W,(i==null?void 0:i.jobs)||[])==="not-analyzed"||Je(W,(i==null?void 0:i.jobs)||[])==="out-of-date"||Je(W,(i==null?void 0:i.jobs)||[])==="incomplete")).length>0,le=W=>{var Z;return((Z=a==null?void 0:a.currentEntityShas)==null?void 0:Z.includes(W))||!1},G=W=>{var Z;return l!=null&&l(W)?!0:((Z=i==null?void 0:i.jobs)==null?void 0:Z.some(F=>{var te;return(te=F.entityShas)==null?void 0:te.includes(W.sha)}))||!1},B=W=>{h==null||h(W)};return n(Or,{filePath:T.filePath,isExpanded:U,onToggle:()=>q(T.filePath),simulationPreviews:n(Fr,{entities:T.entities,maxPreviews:1}),entityCount:T.totalCount,state:T.state,lastModified:T.lastUpdated,uncommittedCount:T.uncommittedCount,isUncommitted:T.uncommittedCount>0,actionButton:V?n("button",{onClick:W=>{W.stopPropagation();const Z=T.entities.filter(F=>(F.entityType==="visual"||F.entityType==="library")&&(Je(F,(i==null?void 0:i.jobs)||[])==="not-analyzed"||Je(F,(i==null?void 0:i.jobs)||[])==="out-of-date"||Je(F,(i==null?void 0:i.jobs)||[])==="incomplete"));u==null||u(Z)},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-medium hover:bg-[#004a5e] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Analyze"}):void 0,children:T.entities.sort((W,Z)=>{const F=W.entityType==="visual"||W.entityType==="library",te=Z.entityType==="visual"||Z.entityType==="library";return F&&!te?-1:!F&&te?1:0}).map(W=>n(Yr,{entity:W,isActivelyAnalyzing:le(W.sha),isQueued:G(W),onGenerateSimulation:B},W.sha))},T.filePath)})}),Q>1&&c("div",{className:"flex justify-center items-center gap-4 mt-6 p-4",children:[t>1&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(b),page:String(t-1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"← Previous"}),c("span",{children:["Page ",t," of ",Q]}),t<Q&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(b),page:String(t+1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"Next →"})]})]})}const Wm=()=>[{title:"CodeYam - Files & Entities"},{name:"description",content:"Browse your codebase files and entities"}];async function Hm({request:e,context:t}){try{const r=new URL(e.url),a=parseInt(r.searchParams.get("page")||"1"),s=r.searchParams.get("filter")||null,o=r.searchParams.get("entityType"),i=t.analysisQueue,l=i?i.getState():{paused:!1,jobs:[]},[d,h]=await Promise.all([Xt(),kt()]);return z({entities:d,currentCommit:h,page:a,filter:s,entityType:o,queueState:l})}catch(r){return console.error("Failed to load entities:",r),z({entities:[],currentCommit:null,page:1,filter:null,entityType:null,queueState:{paused:!1,jobs:[]},error:"Failed to load entities"})}}const Vm=We(function(){var w,v,C;const{entities:t,currentCommit:r,page:a,filter:s,entityType:o,queueState:i}=Ke();ht();const[l,d]=qt(),[h,u]=j(!1);Et({source:"files-page"});const{handleGenerateSimulation:m,handleGenerateAllSimulations:p,isEntityPending:f,pendingEntityKeys:g}=Zs((v=(w=r==null?void 0:r.metadata)==null?void 0:w.currentRun)==null?void 0:v.currentEntityShas,i),y=se(()=>{if(!t)return[];const k=new Set([]);for(const A of t)k.add(A.filePath??"No File Path");return Array.from(k)},[t]),b=se(()=>{if(!t)return[];let k=t;return h&&(k=k.filter(A=>{var P;return(P=A.metadata)==null?void 0:P.isUncommitted})),k.sort((A,P)=>{var M,I,N,$,_,S;return(M=A.metadata)!=null&&M.isUncommitted&&!((I=P.metadata)!=null&&I.isUncommitted)?-1:!((N=A.metadata)!=null&&N.isUncommitted)&&(($=P.metadata)!=null&&$.isUncommitted)?1:new Date(((_=P.metadata)==null?void 0:_.editedAt)||0).getTime()-new Date(((S=A.metadata)==null?void 0:S.editedAt)||0).getTime()})},[t,h]),x=se(()=>{var A;if(!t)return[];const k=new Set([]);for(const P of t)(A=P.metadata)!=null&&A.isUncommitted&&k.add(P.filePath??"No File Path");return Array.from(k)},[t]);return t?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-20 py-12 font-sans",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-3xl font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-gray-600",children:"This is a list of all the files in your app."})]}),n(Um,{entities:b,page:a,itemsPerPage:50,currentRun:(C=r==null?void 0:r.metadata)==null?void 0:C.currentRun,filter:s,entityType:o,queueState:i,isEntityPending:f,pendingEntityKeys:g,onGenerateSimulation:m,onGenerateAllSimulations:p,totalFilesCount:y.length,totalEntitiesCount:t.length,uncommittedFilesCount:x.length,showOnlyUncommitted:h,onToggleUncommitted:()=>u(!h)})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-3xl font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:"Unable to retrieve entities"})]})})}),Gm=Object.freeze(Object.defineProperty({__proto__:null,default:Vm,loader:Hm,meta:Wm},Symbol.toStringTag,{value:"Module"}));function Jm(e,t,r){const[a,s]=j(()=>new Set),[o,i]=j(()=>new Set),l=Pe([]),d=Pe([]);return ne(()=>{(t.length!==l.current.length||t.some((y,b)=>y!==l.current[b]))&&(l.current=t,s(y=>{const b=new Set;return t.forEach(x=>{y.has(x)&&b.add(x)}),b}))},[t]),ne(()=>{(r.length!==d.current.length||r.some((y,b)=>y!==d.current[b]))&&(d.current=r,i(y=>{const b=new Set;return r.forEach(x=>{y.has(x)&&b.add(x)}),b}))},[r]),{expandedUncommitted:a,expandedBranch:o,setExpandedUncommitted:s,setExpandedBranch:i,toggleFile:(g,y,b)=>{b(x=>{const w=new Set(x);return w.has(g)?w.delete(g):w.add(g),w})},expandAllUncommitted:()=>{s(new Set(t))},collapseAllUncommitted:()=>{s(new Set)},expandAllBranch:()=>{i(new Set(r))},collapseAllBranch:()=>{i(new Set)}}}function qm(e,t,r){const[a,s]=j(null),[o,i]=j(null),l=ke();ne(()=>{var m,p;((m=l.data)==null?void 0:m.oldContent)!==void 0&&((p=l.data)==null?void 0:p.newContent)!==void 0&&i({oldContent:l.data.oldContent,newContent:l.data.newContent,fileName:l.data.fileName})},[l.data]);const d=m=>{s({type:"file",path:m}),i(null);const p=new FormData;p.append("actionType","getDiff"),p.append("filePath",m),p.append("diffType","branch"),p.append("baseBranch",e),p.append("currentBranch",t||""),l.submit(p,{method:"post"})},h=(m,p)=>{s({type:"entity",path:m,entitySha:p}),i(null);const f=new FormData;f.append("actionType","getDiff"),f.append("filePath",m),f.append("diffType","branch"),f.append("baseBranch",e),f.append("currentBranch",t||""),f.append("entitySha",p),l.submit(f,{method:"post"})},u=()=>{s(null),i(null)};return{diffView:a,diffContent:o,isLoading:l.state==="loading"||l.state==="submitting",handleShowFileDiff:d,handleShowEntityDiff:h,handleCloseDiff:u}}function Km({diffView:e,diffContent:t,isLoading:r,entities:a,onClose:s}){var h;const[o,i]=j(!1),[l,d]=j(!1);return ne(()=>{d(!0)},[]),n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-8 z-50",children:c("div",{className:"bg-white rounded-xl shadow-2xl max-w-6xl w-full max-h-[90vh] flex flex-col",children:[c("div",{className:"p-6 border-b border-[#e1e1e1] flex items-center justify-between",children:[c("div",{children:[n("h2",{className:"font-['IBM_Plex_Sans'] text-2xl font-semibold text-[#232323]",children:e.type==="file"?"File Diff":"Entity Diff"}),n("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e] mt-1",children:e.path}),e.type==="entity"&&e.entitySha&&c("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e]",children:["Entity:"," ",((h=a.find(u=>u.sha===e.entitySha))==null?void 0:h.name)||e.entitySha]})]}),c("div",{className:"flex items-center gap-3",children:[n("button",{onClick:()=>i(!o),className:"px-3 py-1.5 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] text-sm font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",title:o?"Show changes only":"Show full file",children:o?"Show Changes Only":"Show Full File"}),n("button",{onClick:s,className:"text-[#8e8e8e] hover:text-[#626262] transition-colors cursor-pointer",children:n("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]}),n("div",{className:"flex-1 overflow-auto",children:r?n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"Loading diff..."})}):t?n("div",{className:"diff-viewer-wrapper",children:l&&n(gi,{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 Qm({files:e,currentBranch:t,defaultBranch:r,baseBranch:a,allBranches:s,expandedFiles:o,isEntityBeingAnalyzed:i,isEntityQueued:l,sortOrder:d,onToggleFile:h,onBranchChange:u,onGenerateSimulation:m,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}){const b=e.flatMap(([v,{entities:C}])=>{const k=C.filter(A=>i(A.sha)||l(A)).map(A=>A.sha);return k.length>0?[{entityShas:k}]:[]}),x=v=>{const C=v.map(k=>Je(k,b));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"},w=se(()=>[...e].sort((v,C)=>{const k=v[1].entities.reduce((I,N)=>{var _;const $=((_=N.metadata)==null?void 0:_.editedAt)||N.updatedAt;return $?I?new Date($)>new Date(I)?$:I:$:I},null),A=C[1].entities.reduce((I,N)=>{var _;const $=((_=N.metadata)==null?void 0:_.editedAt)||N.updatedAt;return $?I?new Date($)>new Date(I)?$:I:$:I},null);if(!k&&!A)return 0;if(!k)return 1;if(!A)return-1;const P=new Date(k).getTime(),M=new Date(A).getTime();return d==="desc"?M-P:P-M}),[e,d]);return n("div",{children:e.length>0?c("div",{children:[n(Lr,{showActions:!0,sortOrder:d,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}),n("div",{className:"flex flex-col gap-[3px]",children:w.map(([v,{status:C,entities:k,isUncommitted:A}])=>{const P=o.has(v),M=x(k),I=k.reduce((S,E)=>{var D;const R=((D=E.metadata)==null?void 0:D.editedAt)||E.updatedAt;return R?S?new Date(R)>new Date(S)?R:S:R:S},null),$=k.filter(S=>S.entityType==="visual"||S.entityType==="library").length===0;let _;return $?_=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):M==="analyzing"?_=c("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[c("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):M==="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"}):M==="out-of-date"?_=n("button",{onClick:S=>{S.stopPropagation(),k.filter(E=>(E.entityType==="visual"||E.entityType==="library")&&!i(E.sha)&&!l(E)).forEach(E=>m(E))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-medium hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):M==="not-analyzed"&&(_=n("button",{onClick:S=>{S.stopPropagation(),k.filter(E=>(E.entityType==="visual"||E.entityType==="library")&&!i(E.sha)&&!l(E)).forEach(E=>m(E))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-medium hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(Or,{filePath:v,isExpanded:P,onToggle:()=>h(v),fileStatus:C,isUncommitted:A,simulationPreviews:n(Fr,{entities:k,maxPreviews:1}),entityCount:k.length,state:M,lastModified:I,isNotAnalyzable:$,actionButton:_,children:k.sort((S,E)=>{const R=S.entityType==="visual"||S.entityType==="library",D=E.entityType==="visual"||E.entityType==="library";return R&&!D?-1:!R&&D?1:0}).map(S=>n(Yr,{entity:S,isActivelyAnalyzing:i(S.sha),isQueued:l(S),onGenerateSimulation:m},S.sha))},v)})})]}):c("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"No files have been modified in this branch."})]})})}function Zm({files:e,entityImpactMap:t,expandedFiles:r,isEntityBeingAnalyzed:a,isEntityQueued:s,projectSlug:o,baseBranch:i,currentBranch:l,sortOrder:d,onToggleFile:h,onShowFileDiff:u,onGenerateSimulation:m,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}){const b=se(()=>{const v=[];return e.forEach(([C,{editedEntities:k}])=>{const A=k.filter(P=>a(P.sha)||s(P)).map(P=>P.sha);A.length>0&&v.push({entityShas:A})}),v},[e,a,s]),x=se(()=>{const v=new Map;return e.forEach(([C,{editedEntities:k}])=>{const A=k.map(N=>Je(N,b));let P;A.includes("analyzing")||A.includes("queued")?P="analyzing":A.includes("out-of-date")?P="out-of-date":A.includes("not-analyzed")?P="not-analyzed":P="up-to-date";const M=k.reduce((N,$)=>{var S;const _=((S=$.metadata)==null?void 0:S.editedAt)||$.updatedAt;return _&&(!N||new Date(_)>new Date(N))?_:N},null),I=k.filter(N=>N.entityType==="visual"||N.entityType==="library").length;v.set(C,{state:P,lastModified:M,analyzableCount:I})}),v},[e,b]),w=se(()=>[...e].sort((v,C)=>{const k=x.get(v[0]),A=x.get(C[0]),P=k==null?void 0:k.lastModified,M=A==null?void 0:A.lastModified;if(!P&&!M)return 0;if(!P)return 1;if(!M)return-1;const I=new Date(P).getTime(),N=new Date(M).getTime();return d==="desc"?N-I:I-N}),[e,x,d]);return e.length===0?c("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Uncommitted Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"If you edit a file in your project, it will show up here."})]}):c("div",{children:[n(Lr,{showActions:!0,sortOrder:d,onSortChange:p,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}),n("div",{className:"flex flex-col gap-[3px]",children:w.map(([v,{status:C,editedEntities:k}])=>{const A=r.has(v),P=x.get(v),{state:M,lastModified:I,analyzableCount:N}=P,$=N===0;let _;return $?_=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):M==="analyzing"?_=c("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[c("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):M==="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"}):M==="out-of-date"?_=n("button",{onClick:S=>{S.stopPropagation(),k.filter(E=>(E.entityType==="visual"||E.entityType==="library")&&!a(E.sha)&&!s(E)).forEach(E=>m(E))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-medium hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):M==="not-analyzed"&&(_=n("button",{onClick:S=>{S.stopPropagation(),k.filter(E=>(E.entityType==="visual"||E.entityType==="library")&&!a(E.sha)&&!s(E)).forEach(E=>m(E))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-medium hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(Or,{filePath:v,isExpanded:A,onToggle:()=>h(v),fileStatus:C,simulationPreviews:n(Fr,{entities:k,maxPreviews:1}),entityCount:k.length,state:M,lastModified:I,isNotAnalyzable:$,isUncommitted:!0,actionButton:_,children:k.sort((S,E)=>{const R=S.entityType==="visual"||S.entityType==="library",D=E.entityType==="visual"||E.entityType==="library";return R&&!D?-1:!R&&D?1:0}).map(S=>n(Yr,{entity:S,isActivelyAnalyzing:a(S.sha),isQueued:s(S),onGenerateSimulation:m},S.sha))},v)})})]})}function Xm({activeTab:e,onTabChange:t,uncommittedCount:r,branchCount:a}){return n("div",{className:"border-b border-gray-200",children:c("nav",{className:"flex gap-8 items-center",children:[c("button",{onClick:()=>t("branch"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="branch"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[c("span",{className:"flex items-center gap-2",children:["Branch Changes",a>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="branch"?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:a})]}),e==="branch"&&n("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]}),c("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:[c("span",{className:"flex items-center gap-2",children:["Uncommitted Changes",r>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="uncommitted"?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:r})]}),e==="uncommitted"&&n("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]})]})})}const ep=()=>[{title:"Git - CodeYam"},{name:"description",content:"Git status and impact analysis"}];async function tp({request:e}){const t=await e.formData();if(t.get("actionType")==="getDiff"){const a=t.get("filePath"),s=t.get("diffType"),o=t.get("baseBranch"),i=t.get("currentBranch"),l=t.get("entitySha");let d;return s==="branch"?d=gn(a,o,i):d=Su(a),z({...d,entitySha:l})}return z({error:"Unknown action"},{status:400})}async function np({request:e,context:t}){try{const r=new URL(e.url),a=r.searchParams.get("compare"),s=r.searchParams.get("viewBranch"),o=t.analysisQueue,i=o?o.getState():{paused:!1,jobs:[]},[l,d,h]=await Promise.all([Xt(),kt(),ze()]),u=Bs(),m=bu(),p=vu(),f=wu(),g=s||m,y=a||p;let b=[];return g&&g!==y&&(b=Us(y,g)),z({entities:l||[],gitStatus:u,currentBranch:g,actualCurrentBranch:m,defaultBranch:p,allBranches:f,baseBranch:y,branchDiff:b,currentCommit:d,projectSlug:h,queueState:i})}catch(r){return console.error("Failed to load git data:",r),z({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 rp=We(function(){var we,nn;const{entities:t,gitStatus:r,currentBranch:a,actualCurrentBranch:s,defaultBranch:o,allBranches:i,baseBranch:l,branchDiff:d,currentCommit:h,projectSlug:u,queueState:m}=Ke();Et({source:"git-page"});const[p,f]=qt(),[g,y]=j(null),[b,x]=j("desc"),[w,v]=j("branch"),C=p.get("expanded")==="true",k=()=>{x(ie=>ie==="desc"?"asc":"desc")},A=ke(),P=A.data;ne(()=>{a&&l&&a!==l&&A.state==="idle"&&!P&&A.load(`/api/branch-entity-diff?base=${encodeURIComponent(l)}&compare=${encodeURIComponent(a)}`)},[a,l,A,P]);const M=se(()=>{const ie=Ks(r,t);return Array.from(ie.entries()).sort((Ve,Qe)=>Ve[0].localeCompare(Qe[0]))},[r,t]),I=se(()=>{const ie=Rm(d,t,P);return Array.from(ie.entries()).sort((Ve,Qe)=>Ve[0].localeCompare(Qe[0]))},[d,t,P]),N=se(()=>$m(r,t),[r,t]),$=se(()=>w==="uncommitted"?M:I,[w,M,I]),_=se(()=>$.map(([ie])=>ie),[$]),{expandedUncommitted:S,setExpandedUncommitted:E,toggleFile:R,expandAllUncommitted:D,collapseAllUncommitted:O}=Jm(C,_,[]),{diffView:H,diffContent:Q,isLoading:q,handleShowFileDiff:L,handleCloseDiff:T}=qm(l,a),U=(we=h==null?void 0:h.metadata)==null?void 0:we.currentRun,Y=new Set((U==null?void 0:U.currentEntityShas)||[]),V=new Set(m.jobs.flatMap(ie=>ie.entityShas||[])),le=new Set(((nn=m.currentlyExecuting)==null?void 0:nn.entityShas)||[]),{isAnalyzing:G,handleGenerateSimulation:B,handleGenerateAllSimulations:W,isEntityBeingAnalyzed:Z,isEntityPending:F}=Zs(U==null?void 0:U.currentEntityShas,m),te=ie=>F(ie)||V.has(ie.sha)||le.has(ie.sha),ce=ie=>{ie===(s||a)?p.delete("viewBranch"):p.set("viewBranch",ie),f(p)},he=ie=>{ie===o?p.delete("compare"):p.set("compare",ie),f(p)},fe=()=>{const Ve=$.flatMap(([Qe,Fn])=>Fn.editedEntities||Fn.entities||[]).filter(Qe=>!Y.has(Qe.sha)&&!V.has(Qe.sha)&&!le.has(Qe.sha)&&!F(Qe));W(Ve)},Ce=M.length,Se=I.length,Ae=$.flatMap(([ie,Ve])=>Ve.editedEntities||Ve.entities||[]),Ee=Ae.filter(ie=>ie.entityType==="visual"||ie.entityType==="library"),De=Ee.length>0&&Ee.every(ie=>Y.has(ie.sha)),ge=Ee.length>0&&!De&&Ee.every(ie=>V.has(ie.sha)||le.has(ie.sha)),Te=G||De||ge,je=De?"Analyzing...":ge?"Queued...":G?"Analyzing...":"Analyze All";return n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-20 py-12",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-3xl font-semibold text-gray-900 mb-2",children:"Git Changes"}),c("p",{className:"text-gray-600",children:["This is a list of all the files that are affected by your local changes. ",n("strong",{children:"Analyze a file to get simulations."})]})]}),n("div",{className:"mb-6",children:n(Xm,{activeTab:w,onTabChange:v,uncommittedCount:Ce,branchCount:Se})}),a&&w==="branch"&&n("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:a===o?c("div",{className:"text-gray-700",children:["You are currently on the primary branch,"," ",n("span",{className:"text-cyblack-75",children:o}),"."]}):c("div",{className:"flex gap-6 items-center",children:[c("div",{className:"shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Changes in Branch:"}),i.length>0?c("div",{className:"relative w-50",children:[n("select",{value:a,onChange:ie=>ce(ie.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(ie=>n("option",{value:ie,children:ie},ie))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}):n("span",{className:"text-gray-900 font-medium text-[12px]",children:a})]}),c("div",{className:"flex-shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Compared To:"}),c("div",{className:"relative w-[200px]",children:[n("select",{value:l,onChange:ie=>he(ie.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:i.filter(ie=>ie!==a).map(ie=>n("option",{value:ie,children:ie},ie))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]})]}),n("div",{className:"flex-1 mt-6",children:c("div",{className:"relative flex items-center",children:[n("svg",{className:"absolute left-3 w-4 h-4 text-gray-400 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})})]})}),n("div",{className:"mb-3",children:c("div",{className:"flex items-center justify-between text-[13px]",children:[c("div",{className:"flex items-center gap-3",children:[c("span",{className:"text-gray-900",children:[$.length," modified"," ",$.length===1?"file":"files"]}),n("span",{className:"text-gray-300",children:"|"}),c("div",{className:"flex items-center gap-1 group relative",children:[c("span",{className:"text-gray-900",children:[Ae.length," ",Ae.length===1?"entity":"entities"]}),c("svg",{className:"w-3.5 h-3.5 text-[#001f3f]",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[n("circle",{cx:"12",cy:"12",r:"10",strokeWidth:"2"}),n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 16v-4m0-4h.01"})]}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:c("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]})]}),$.length>0&&c("div",{className:"flex gap-6",children:[n("button",{onClick:D,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-medium transition-all cursor-pointer px-3 py-1 rounded",children:"Expand All"}),n("button",{onClick:O,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-medium transition-all cursor-pointer px-3 py-1 rounded",children:"Collapse All"})]})]})}),c("div",{className:"overflow-hidden",children:[w==="branch"&&a&&n(Qm,{files:I,currentBranch:a,defaultBranch:o,baseBranch:l,allBranches:i,expandedFiles:S,isEntityBeingAnalyzed:Z,isEntityQueued:te,sortOrder:b,onToggleFile:ie=>R(ie,S,E),onBranchChange:he,onGenerateSimulation:B,onSortChange:k,onAnalyzeAll:fe,analyzeAllDisabled:Te,analyzeAllText:je}),w==="uncommitted"&&n(Zm,{files:M,entityImpactMap:N,expandedFiles:S,isEntityBeingAnalyzed:Z,isEntityQueued:te,projectSlug:u,baseBranch:l,currentBranch:a,sortOrder:b,onToggleFile:ie=>R(ie,S,E),onShowFileDiff:L,onGenerateSimulation:B,onSortChange:k,onAnalyzeAll:fe,analyzeAllDisabled:Te,analyzeAllText:je})]}),H&&n(Km,{diffView:H,diffContent:Q,isLoading:q,entities:t,onClose:T}),g&&u&&n(Rt,{projectSlug:u,onClose:()=>y(null)})]})})}),ap=Object.freeze(Object.defineProperty({__proto__:null,action:tp,default:rp,loader:np,meta:ep},Symbol.toStringTag,{value:"Module"})),Jp={entry:{module:"/assets/entry.client-CS2cb_eZ.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/index-B1h680n5.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-FHgpM6gc.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/index-B1h680n5.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-CKnwPCDr.js","/assets/ReportIssueModal-DcAUIpD_.js","/assets/useReportContext-1BX144Eg.js","/assets/loader-circle-B7B9V-bu.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/useToast-mBRpZPiu.js","/assets/useLastLogLine-aSv48UbS.js","/assets/LogViewer-xgeCVgSM.js","/assets/EntityTypeIcon-CAneekK2.js","/assets/TruncatedFilePath-DyFZkK0l.js","/assets/chevron-down-Cx24_aWc.js","/assets/circle-check-BOARzkeR.js","/assets/triangle-alert-B6LgvRJg.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-EylcgScH.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useInteractiveMode-0ToGk4K3.js","/assets/useLastLogLine-aSv48UbS.js","/assets/useCustomSizes-Dv18q8LD.js","/assets/cy-logo-cli-CKnwPCDr.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha_.edit.$scenarioId":{id:"routes/entity.$sha_.edit.$scenarioId",parentId:"root",path:"entity/:sha/edit/:scenarioId",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha_.edit._scenarioId-C1H_a_Y3.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/InteractivePreview-Cu16OUmx.js","/assets/useInteractiveMode-0ToGk4K3.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-aSv48UbS.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-DMe7kvgo.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/InteractivePreview-Cu16OUmx.js","/assets/useInteractiveMode-0ToGk4K3.js","/assets/keyAttributeCoverage-CTlFMihX.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-aSv48UbS.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-scenario-data":{id:"routes/api.generate-scenario-data",parentId:"root",path:"api/generate-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.generate-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.update-key-attributes":{id:"routes/api.update-key-attributes",parentId:"root",path:"api/update-key-attributes",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.update-key-attributes-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.llm-calls.$entitySha":{id:"routes/api.llm-calls.$entitySha",parentId:"root",path:"api/llm-calls/:entitySha",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.llm-calls._entitySha-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.link-scenario-value":{id:"routes/api.link-scenario-value",parentId:"root",path:"api/link-scenario-value",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.link-scenario-value-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.update-valid-values":{id:"routes/api.update-valid-values",parentId:"root",path:"api/update-valid-values",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.update-valid-values-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.branch-entity-diff":{id:"routes/api.branch-entity-diff",parentId:"root",path:"api/branch-entity-diff",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.branch-entity-diff-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.capture-screenshot-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.logs._projectSlug-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.execute-function-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.interactive-mode-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.delete-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.generate-report-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.process-status-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.save-scenarios-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.kill-process-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.screenshot._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/activity.(_tab)-BF_aK4y6.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/LogViewer-xgeCVgSM.js","/assets/useLastLogLine-aSv48UbS.js","/assets/useReportContext-1BX144Eg.js","/assets/EntityTypeIcon-CAneekK2.js","/assets/EntityTypeBadge-DLqD3qNt.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/LoadingDots-B0GLXMsr.js","/assets/loader-circle-B7B9V-bu.js","/assets/createLucideIcon-BdhJEx6B.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.debug-setup-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/entity._sha._-D0-YwkBh.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useLastLogLine-aSv48UbS.js","/assets/useInteractiveMode-0ToGk4K3.js","/assets/InteractivePreview-Cu16OUmx.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/LibraryFunctionPreview-CVtiBnY5.js","/assets/LoadingDots-B0GLXMsr.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/ScenarioViewer-BMKg0SAF.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/keyAttributeCoverage-CTlFMihX.js","/assets/EntityTypeIcon-CAneekK2.js","/assets/LogViewer-xgeCVgSM.js","/assets/useReportContext-1BX144Eg.js","/assets/preload-helper-ckwbz45p.js","/assets/useCustomSizes-Dv18q8LD.js","/assets/ReportIssueModal-DcAUIpD_.js","/assets/circle-check-BOARzkeR.js","/assets/triangle-alert-B6LgvRJg.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-CDJZnWhN.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useReportContext-1BX144Eg.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/LoadingDots-B0GLXMsr.js","/assets/EntityTypeIcon-CAneekK2.js","/assets/fileTableUtils-DMJ7zii9.js","/assets/chevron-down-Cx24_aWc.js","/assets/search-CxXUmBSd.js","/assets/loader-circle-B7B9V-bu.js","/assets/createLucideIcon-BdhJEx6B.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.events-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.memory-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/api.queue-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasErrorBoundary:!1,module:"/assets/dev.empty-RJCf3Tvw.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/ScenarioViewer-BMKg0SAF.js","/assets/InteractivePreview-Cu16OUmx.js","/assets/useCustomSizes-Dv18q8LD.js","/assets/LogViewer-xgeCVgSM.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/useLastLogLine-aSv48UbS.js","/assets/useInteractiveMode-0ToGk4K3.js","/assets/preload-helper-ckwbz45p.js","/assets/ReportIssueModal-DcAUIpD_.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/circle-check-BOARzkeR.js","/assets/triangle-alert-B6LgvRJg.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-6D8k8Jp5.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useReportContext-1BX144Eg.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-DSmTpjmK.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useLastLogLine-aSv48UbS.js","/assets/useToast-mBRpZPiu.js","/assets/useReportContext-1BX144Eg.js","/assets/LogViewer-xgeCVgSM.js","/assets/EntityTypeIcon-CAneekK2.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/circle-check-BOARzkeR.js","/assets/loader-circle-B7B9V-bu.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-BW7Cyeyi.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useReportContext-1BX144Eg.js","/assets/EntityItem-Cmysw5OP.js","/assets/fileTableUtils-DMJ7zii9.js","/assets/chevron-down-Cx24_aWc.js","/assets/search-CxXUmBSd.js","/assets/useToast-mBRpZPiu.js","/assets/TruncatedFilePath-DyFZkK0l.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/LibraryFunctionPreview-CVtiBnY5.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-B6LgvRJg.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/EntityTypeIcon-CAneekK2.js","/assets/EntityTypeBadge-DLqD3qNt.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-CZu4fif0.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useReportContext-1BX144Eg.js","/assets/EntityItem-Cmysw5OP.js","/assets/LogViewer-xgeCVgSM.js","/assets/fileTableUtils-DMJ7zii9.js","/assets/useToast-mBRpZPiu.js","/assets/TruncatedFilePath-DyFZkK0l.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/LibraryFunctionPreview-CVtiBnY5.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-B6LgvRJg.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/EntityTypeIcon-CAneekK2.js","/assets/EntityTypeBadge-DLqD3qNt.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0}},url:"/assets/manifest-2d191949.js",version:"2d191949",sri:void 0},qp="build/client",Kp="/",Qp={unstable_optimizeDeps:!1,unstable_subResourceIntegrity:!1,v8_middleware:!1,v8_splitRouteModules:!1,v8_viteEnvironmentApi:!1},Zp=!0,Xp=!1,ef=[],tf={mode:"lazy",manifestPath:"/__manifest"},nf="/",rf={module:xi},af={root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,module:jc},"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:Lc},"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:sd},"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:md},"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:au},"routes/api.update-key-attributes":{id:"routes/api.update-key-attributes",parentId:"root",path:"api/update-key-attributes",index:void 0,caseSensitive:void 0,module:ou},"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:cu},"routes/api.link-scenario-value":{id:"routes/api.link-scenario-value",parentId:"root",path:"api/link-scenario-value",index:void 0,caseSensitive:void 0,module:uu},"routes/api.update-valid-values":{id:"routes/api.update-valid-values",parentId:"root",path:"api/update-valid-values",index:void 0,caseSensitive:void 0,module:mu},"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:Iu},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,module:Ru},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,module:Ou},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,module:zu},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,module:Wu},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,module:Gu},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,module:qu},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,module:ih},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,module:uh},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,module:mh},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,module:fh},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,module:yh},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,module:Eh},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,module:kh},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,module:Th},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,module:em},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,module:rm},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,module:dm},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,module:hm},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,module:ym},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,module:vm},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,module:Nm},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,module:Mm},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,module:Im},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,module:zm},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,module:Gm},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,module:ap}};export{Pl as A,El as B,ps as C,ve as D,qi as E,Ki as F,Pt as G,Li as H,ss as I,Yi as J,os as K,Ui as L,Hi as M,qp as N,Kp as O,$i as P,Qp as Q,Zp as R,Ar as S,Xp as T,ef as U,tf as V,nf as W,rf as X,af as Y,Jp as Z,Mi as a,Tt as b,_t as c,tt as d,Kt as e,Cr as f,Nr as g,as as h,Pi as i,ll as j,sr as k,ut as l,st as m,cs as n,gl as o,Cn as p,St as q,ds as r,us as s,wl as t,dt as u,hs as v,$t as w,Cl as x,ms as y,xa as z};