@codeyam/codeyam-cli 0.1.0-staging.8e7b1bd → 0.1.0-staging.b8a55ba

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 (385) hide show
  1. package/analyzer-template/.build-info.json +7 -7
  2. package/analyzer-template/log.txt +3 -3
  3. package/analyzer-template/package.json +7 -6
  4. package/analyzer-template/packages/ai/package.json +1 -1
  5. package/analyzer-template/packages/ai/src/lib/analyzeScope.ts +2 -0
  6. package/analyzer-template/packages/ai/src/lib/astScopes/astScopeAnalyzer.ts +22 -0
  7. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.ts +23 -1
  8. package/analyzer-template/packages/ai/src/lib/astScopes/processExpression.ts +401 -106
  9. package/analyzer-template/packages/ai/src/lib/astScopes/types.ts +60 -0
  10. package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +661 -50
  11. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.ts +14 -2
  12. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.ts +715 -0
  13. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.ts +123 -1
  14. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.ts +19 -1
  15. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.ts +23 -1
  16. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.ts +23 -0
  17. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.ts +34 -1
  18. package/analyzer-template/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.ts +236 -24
  19. package/analyzer-template/packages/ai/src/lib/generateChangesEntityKeyAttributes.ts +18 -1
  20. package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarios.ts +37 -4
  21. package/analyzer-template/packages/ai/src/lib/generateEntityDataStructure.ts +5 -0
  22. package/analyzer-template/packages/ai/src/lib/generateEntityKeyAttributes.ts +213 -12
  23. package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +11 -15
  24. package/analyzer-template/packages/ai/src/lib/generateEntityScenarios.ts +114 -11
  25. package/analyzer-template/packages/ai/src/lib/getConditionalUsagesFromCode.ts +143 -31
  26. package/analyzer-template/packages/ai/src/lib/guessScenarioDataFromDescription.ts +8 -2
  27. package/analyzer-template/packages/ai/src/lib/promptGenerators/gatherAttributesMap.ts +7 -0
  28. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.ts +42 -2
  29. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.ts +38 -2
  30. package/analyzer-template/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.ts +28 -2
  31. package/analyzer-template/packages/ai/src/lib/worker/SerializableDataStructure.ts +5 -0
  32. package/analyzer-template/packages/ai/src/lib/worker/analyzeScopeWorker.ts +8 -1
  33. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.ts +339 -145
  34. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +20 -0
  35. package/analyzer-template/packages/analyze/src/lib/files/getImportedExports.ts +8 -1
  36. package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.ts +158 -0
  37. package/analyzer-template/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.ts +107 -18
  38. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.ts +1 -1
  39. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +223 -103
  40. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.ts +10 -5
  41. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarioData.ts +172 -83
  42. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarios.ts +2 -5
  43. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +97 -27
  44. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.d.ts +15 -0
  45. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.d.ts.map +1 -0
  46. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.js +31 -0
  47. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.js.map +1 -0
  48. package/analyzer-template/packages/aws/package.json +1 -1
  49. package/analyzer-template/packages/aws/s3/index.ts +1 -0
  50. package/analyzer-template/packages/aws/src/lib/s3/checkS3ObjectExists.ts +47 -0
  51. package/analyzer-template/packages/database/src/lib/kysely/db.ts +4 -4
  52. package/analyzer-template/packages/database/src/lib/kysely/tableRelations.ts +2 -2
  53. package/analyzer-template/packages/database/src/lib/kysely/tables/debugReportsTable.ts +20 -9
  54. package/analyzer-template/packages/database/src/lib/loadReadyToBeCapturedAnalyses.ts +3 -2
  55. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.ts +9 -4
  56. package/analyzer-template/packages/generate/src/lib/deepMerge.ts +26 -1
  57. package/analyzer-template/packages/generate/src/lib/getComponentScenarioPath.ts +8 -3
  58. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts +2 -2
  59. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js +2 -2
  60. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tableRelations.d.ts +2 -2
  61. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts +8 -1
  62. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts.map +1 -1
  63. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts +14 -7
  64. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts.map +1 -1
  65. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.js +9 -3
  66. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.js.map +1 -1
  67. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts +1 -1
  68. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts.map +1 -1
  69. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.d.ts.map +1 -1
  70. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js +4 -2
  71. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
  72. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.d.ts.map +1 -1
  73. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +8 -4
  74. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
  75. package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.d.ts.map +1 -1
  76. package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.js +27 -1
  77. package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.js.map +1 -1
  78. package/analyzer-template/packages/github/dist/generate/src/lib/getComponentScenarioPath.d.ts.map +1 -1
  79. package/analyzer-template/packages/github/dist/generate/src/lib/getComponentScenarioPath.js +7 -3
  80. package/analyzer-template/packages/github/dist/generate/src/lib/getComponentScenarioPath.js.map +1 -1
  81. package/analyzer-template/packages/github/dist/types/index.d.ts +4 -3
  82. package/analyzer-template/packages/github/dist/types/index.d.ts.map +1 -1
  83. package/analyzer-template/packages/github/dist/types/index.js +1 -0
  84. package/analyzer-template/packages/github/dist/types/index.js.map +1 -1
  85. package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts +31 -1
  86. package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts.map +1 -1
  87. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts +51 -1
  88. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts.map +1 -1
  89. package/analyzer-template/packages/github/dist/types/src/types/Scenario.js +21 -1
  90. package/analyzer-template/packages/github/dist/types/src/types/Scenario.js.map +1 -1
  91. package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts +48 -0
  92. package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
  93. package/analyzer-template/packages/github/dist/utils/src/lib/applyUniversalMocks.d.ts.map +1 -1
  94. package/analyzer-template/packages/github/dist/utils/src/lib/applyUniversalMocks.js +26 -2
  95. package/analyzer-template/packages/github/dist/utils/src/lib/applyUniversalMocks.js.map +1 -1
  96. package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.d.ts.map +1 -1
  97. package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.js +25 -0
  98. package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
  99. package/analyzer-template/packages/types/index.ts +8 -0
  100. package/analyzer-template/packages/types/src/types/Analysis.ts +32 -1
  101. package/analyzer-template/packages/types/src/types/Scenario.ts +75 -6
  102. package/analyzer-template/packages/types/src/types/ScenariosDataStructure.ts +49 -0
  103. package/analyzer-template/packages/ui-components/package.json +4 -4
  104. package/analyzer-template/packages/ui-components/src/components/ScenarioDetailInteractiveView.tsx +23 -7
  105. package/analyzer-template/packages/utils/dist/types/index.d.ts +4 -3
  106. package/analyzer-template/packages/utils/dist/types/index.d.ts.map +1 -1
  107. package/analyzer-template/packages/utils/dist/types/index.js +1 -0
  108. package/analyzer-template/packages/utils/dist/types/index.js.map +1 -1
  109. package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts +31 -1
  110. package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts.map +1 -1
  111. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts +51 -1
  112. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts.map +1 -1
  113. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.js +21 -1
  114. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.js.map +1 -1
  115. package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts +48 -0
  116. package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
  117. package/analyzer-template/packages/utils/dist/utils/src/lib/applyUniversalMocks.d.ts.map +1 -1
  118. package/analyzer-template/packages/utils/dist/utils/src/lib/applyUniversalMocks.js +26 -2
  119. package/analyzer-template/packages/utils/dist/utils/src/lib/applyUniversalMocks.js.map +1 -1
  120. package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.d.ts.map +1 -1
  121. package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.js +25 -0
  122. package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
  123. package/analyzer-template/packages/utils/src/lib/applyUniversalMocks.ts +28 -2
  124. package/analyzer-template/packages/utils/src/lib/lightweightEntityExtractor.ts +27 -0
  125. package/analyzer-template/playwright/takeElementScreenshot.ts +26 -11
  126. package/analyzer-template/playwright/takeScreenshot.ts +9 -7
  127. package/analyzer-template/project/TESTING.md +83 -0
  128. package/analyzer-template/project/constructMockCode.ts +151 -30
  129. package/analyzer-template/project/loadReadyToBeCaptured.ts +17 -1
  130. package/analyzer-template/project/orchestrateCapture/KyselyAnalysisLoader.ts +16 -9
  131. package/analyzer-template/project/orchestrateCapture/SequentialCaptureTaskRunner.ts +77 -37
  132. package/analyzer-template/project/reconcileMockDataKeys.ts +104 -3
  133. package/analyzer-template/project/runMultiScenarioServer.ts +11 -10
  134. package/analyzer-template/project/serverOnlyModules.ts +288 -0
  135. package/analyzer-template/project/start.ts +10 -0
  136. package/analyzer-template/project/startScenarioCapture.ts +73 -41
  137. package/analyzer-template/project/writeMockDataTsx.ts +103 -40
  138. package/analyzer-template/project/writeScenarioComponents.ts +1162 -203
  139. package/analyzer-template/project/writeSimpleRoot.ts +26 -4
  140. package/analyzer-template/project/writeUniversalMocks.ts +32 -11
  141. package/background/src/lib/virtualized/project/constructMockCode.js +132 -25
  142. package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
  143. package/background/src/lib/virtualized/project/loadReadyToBeCaptured.js +15 -1
  144. package/background/src/lib/virtualized/project/loadReadyToBeCaptured.js.map +1 -1
  145. package/background/src/lib/virtualized/project/orchestrateCapture/KyselyAnalysisLoader.js +11 -6
  146. package/background/src/lib/virtualized/project/orchestrateCapture/KyselyAnalysisLoader.js.map +1 -1
  147. package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js +67 -32
  148. package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js.map +1 -1
  149. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js +65 -4
  150. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js.map +1 -1
  151. package/background/src/lib/virtualized/project/runMultiScenarioServer.js +11 -9
  152. package/background/src/lib/virtualized/project/runMultiScenarioServer.js.map +1 -1
  153. package/background/src/lib/virtualized/project/serverOnlyModules.js +235 -0
  154. package/background/src/lib/virtualized/project/serverOnlyModules.js.map +1 -0
  155. package/background/src/lib/virtualized/project/start.js +6 -0
  156. package/background/src/lib/virtualized/project/start.js.map +1 -1
  157. package/background/src/lib/virtualized/project/startScenarioCapture.js +54 -31
  158. package/background/src/lib/virtualized/project/startScenarioCapture.js.map +1 -1
  159. package/background/src/lib/virtualized/project/writeMockDataTsx.js +87 -34
  160. package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
  161. package/background/src/lib/virtualized/project/writeScenarioComponents.js +852 -133
  162. package/background/src/lib/virtualized/project/writeScenarioComponents.js.map +1 -1
  163. package/background/src/lib/virtualized/project/writeSimpleRoot.js +25 -2
  164. package/background/src/lib/virtualized/project/writeSimpleRoot.js.map +1 -1
  165. package/background/src/lib/virtualized/project/writeUniversalMocks.js +27 -12
  166. package/background/src/lib/virtualized/project/writeUniversalMocks.js.map +1 -1
  167. package/codeyam-cli/scripts/fixtures/formbricks/universal-mocks/apps/web/lib/instance/service.js +7 -0
  168. package/codeyam-cli/scripts/fixtures/formbricks/universal-mocks/apps/web/lib/instance/service.js.map +1 -0
  169. package/codeyam-cli/src/cli.js +2 -0
  170. package/codeyam-cli/src/cli.js.map +1 -1
  171. package/codeyam-cli/src/commands/debug.js +14 -2
  172. package/codeyam-cli/src/commands/debug.js.map +1 -1
  173. package/codeyam-cli/src/commands/recapture.js +215 -0
  174. package/codeyam-cli/src/commands/recapture.js.map +1 -0
  175. package/codeyam-cli/src/commands/report.js +26 -23
  176. package/codeyam-cli/src/commands/report.js.map +1 -1
  177. package/codeyam-cli/src/utils/backgroundServer.js +2 -2
  178. package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
  179. package/codeyam-cli/src/utils/generateReport.js +252 -106
  180. package/codeyam-cli/src/utils/generateReport.js.map +1 -1
  181. package/codeyam-cli/src/utils/install-skills.js +2 -7
  182. package/codeyam-cli/src/utils/install-skills.js.map +1 -1
  183. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js +38 -0
  184. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js.map +1 -1
  185. package/codeyam-cli/src/utils/queue/job.js +140 -16
  186. package/codeyam-cli/src/utils/queue/job.js.map +1 -1
  187. package/codeyam-cli/src/utils/queue/manager.js +19 -7
  188. package/codeyam-cli/src/utils/queue/manager.js.map +1 -1
  189. package/codeyam-cli/src/utils/queue/persistence.js.map +1 -1
  190. package/codeyam-cli/src/webserver/app/lib/database.js +47 -0
  191. package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
  192. package/codeyam-cli/src/webserver/app/lib/dbNotifier.js.map +1 -1
  193. package/codeyam-cli/src/webserver/backgroundServer.js +5 -10
  194. package/codeyam-cli/src/webserver/backgroundServer.js.map +1 -1
  195. package/codeyam-cli/src/webserver/bootstrap.js +9 -0
  196. package/codeyam-cli/src/webserver/bootstrap.js.map +1 -0
  197. package/codeyam-cli/src/webserver/build/client/assets/EntityItem-wXL1Z2Aq.js +1 -0
  198. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeBadge-DQeyk25_.js → EntityTypeBadge-CzGX-miz.js} +1 -1
  199. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-CXFKsCOD.js +41 -0
  200. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-D-9pXIaY.js +25 -0
  201. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-CBQPrpT0.js +3 -0
  202. package/codeyam-cli/src/webserver/build/client/assets/LoadingDots-D1CdlbrV.js +6 -0
  203. package/codeyam-cli/src/webserver/build/client/assets/LogViewer-wDPcZNKx.js +3 -0
  204. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-4lcOlid-.js +11 -0
  205. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-BfmDgXxG.js +1 -0
  206. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-CUxUNEEC.js +15 -0
  207. package/codeyam-cli/src/webserver/build/client/assets/{TruncatedFilePath-ayCJdUAc.js → TruncatedFilePath-6J7zDUD5.js} +1 -1
  208. package/codeyam-cli/src/webserver/build/client/assets/_index-DHImXdXq.js +11 -0
  209. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-2mG6mjVb.js +32 -0
  210. package/codeyam-cli/src/webserver/build/client/assets/api.link-scenario-value-l0sNRNKZ.js +1 -0
  211. package/codeyam-cli/src/webserver/build/client/assets/api.update-key-attributes-l0sNRNKZ.js +1 -0
  212. package/codeyam-cli/src/webserver/build/client/assets/api.update-valid-values-l0sNRNKZ.js +1 -0
  213. package/codeyam-cli/src/webserver/build/client/assets/chevron-down-BYimnrHg.js +6 -0
  214. package/codeyam-cli/src/webserver/build/client/assets/chunk-JMJ3UQ3L-BambyYE_.js +51 -0
  215. package/codeyam-cli/src/webserver/build/client/assets/circle-check-CaVsIRxt.js +6 -0
  216. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-CgUsG7ib.js +21 -0
  217. package/codeyam-cli/src/webserver/build/client/assets/cy-logo-cli-CKnwPCDr.js +1 -0
  218. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-DW_hdGUc.js +1 -0
  219. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-FHOVOgFN.js → entity._sha._-zUEpfPsu.js} +22 -15
  220. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-DyB90fWk.js +1 -0
  221. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-D_3ero5o.js +1 -0
  222. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-CfLCUi9S.js +5 -0
  223. package/codeyam-cli/src/webserver/build/client/assets/entry.client-DKJyZfAY.js +29 -0
  224. package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-DAtOlaWE.js +1 -0
  225. package/codeyam-cli/src/webserver/build/client/assets/files-ClR0d32A.js +1 -0
  226. package/codeyam-cli/src/webserver/build/client/assets/git-D62Lxxmv.js +15 -0
  227. package/codeyam-cli/src/webserver/build/client/assets/globals-C6vQASxy.css +1 -0
  228. package/codeyam-cli/src/webserver/build/client/assets/html2canvas-pro.esm-fmIEn3Bc.js +9 -0
  229. package/codeyam-cli/src/webserver/build/client/assets/index-BosqDOlH.js +3 -0
  230. package/codeyam-cli/src/webserver/build/client/assets/index-CzNNiTkw.js +9 -0
  231. package/codeyam-cli/src/webserver/build/client/assets/keyAttributeCoverage-CTlFMihX.js +1 -0
  232. package/codeyam-cli/src/webserver/build/client/assets/loader-circle-CNp9QFCX.js +6 -0
  233. package/codeyam-cli/src/webserver/build/client/assets/manifest-09d684be.js +1 -0
  234. package/codeyam-cli/src/webserver/build/client/assets/preload-helper-ckwbz45p.js +1 -0
  235. package/codeyam-cli/src/webserver/build/client/assets/root-BxJUvKau.js +56 -0
  236. package/codeyam-cli/src/webserver/build/client/assets/scenarioStatus-B_8jpV3e.js +1 -0
  237. package/codeyam-cli/src/webserver/build/client/assets/search-DDGjYAMJ.js +6 -0
  238. package/codeyam-cli/src/webserver/build/client/assets/settings-DgTyB-Wg.js +1 -0
  239. package/codeyam-cli/src/webserver/build/client/assets/simulations-CoNWGt0K.js +1 -0
  240. package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-CBc5dE1s.js +6 -0
  241. package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-BMIGFP-m.js +1 -0
  242. package/codeyam-cli/src/webserver/build/client/assets/useInteractiveMode-Dk_FQqWJ.js +1 -0
  243. package/codeyam-cli/src/webserver/build/client/assets/{useLastLogLine-DOGXmJcI.js → useLastLogLine-BqPPNjAl.js} +1 -1
  244. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-DsJbgMY9.js +1 -0
  245. package/codeyam-cli/src/webserver/build/client/assets/{useToast-C07gRg7Z.js → useToast-DWHcCcl1.js} +1 -1
  246. package/codeyam-cli/src/webserver/build/server/assets/index-CV6i1S1A.js +1 -0
  247. package/codeyam-cli/src/webserver/build/server/assets/server-build-BDlyhfrv.js +175 -0
  248. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  249. package/codeyam-cli/src/webserver/build-info.json +5 -5
  250. package/codeyam-cli/src/webserver/devServer.js +1 -3
  251. package/codeyam-cli/src/webserver/devServer.js.map +1 -1
  252. package/codeyam-cli/templates/debug-codeyam.md +620 -0
  253. package/package.json +14 -14
  254. package/packages/ai/src/lib/analyzeScope.js +2 -0
  255. package/packages/ai/src/lib/analyzeScope.js.map +1 -1
  256. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js +16 -0
  257. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js.map +1 -1
  258. package/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.js +16 -0
  259. package/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.js.map +1 -1
  260. package/packages/ai/src/lib/astScopes/processExpression.js +305 -88
  261. package/packages/ai/src/lib/astScopes/processExpression.js.map +1 -1
  262. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +523 -42
  263. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
  264. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js +12 -2
  265. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js.map +1 -1
  266. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js +454 -0
  267. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js.map +1 -0
  268. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js +103 -1
  269. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js.map +1 -1
  270. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js +16 -1
  271. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js.map +1 -1
  272. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js +19 -1
  273. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js.map +1 -1
  274. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js +20 -0
  275. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js.map +1 -1
  276. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js +28 -2
  277. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js.map +1 -1
  278. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js +179 -17
  279. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js.map +1 -1
  280. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js +6 -0
  281. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js.map +1 -1
  282. package/packages/ai/src/lib/generateChangesEntityScenarios.js +37 -4
  283. package/packages/ai/src/lib/generateChangesEntityScenarios.js.map +1 -1
  284. package/packages/ai/src/lib/generateEntityDataStructure.js +4 -0
  285. package/packages/ai/src/lib/generateEntityDataStructure.js.map +1 -1
  286. package/packages/ai/src/lib/generateEntityKeyAttributes.js +176 -9
  287. package/packages/ai/src/lib/generateEntityKeyAttributes.js.map +1 -1
  288. package/packages/ai/src/lib/generateEntityScenarioData.js +11 -15
  289. package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
  290. package/packages/ai/src/lib/generateEntityScenarios.js +105 -9
  291. package/packages/ai/src/lib/generateEntityScenarios.js.map +1 -1
  292. package/packages/ai/src/lib/getConditionalUsagesFromCode.js +84 -14
  293. package/packages/ai/src/lib/getConditionalUsagesFromCode.js.map +1 -1
  294. package/packages/ai/src/lib/guessScenarioDataFromDescription.js +2 -1
  295. package/packages/ai/src/lib/guessScenarioDataFromDescription.js.map +1 -1
  296. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js +6 -0
  297. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js.map +1 -1
  298. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js +38 -2
  299. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js.map +1 -1
  300. package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js +38 -2
  301. package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js.map +1 -1
  302. package/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.js +16 -3
  303. package/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.js.map +1 -1
  304. package/packages/ai/src/lib/worker/SerializableDataStructure.js.map +1 -1
  305. package/packages/ai/src/lib/worker/analyzeScopeWorker.js +4 -0
  306. package/packages/ai/src/lib/worker/analyzeScopeWorker.js.map +1 -1
  307. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +258 -110
  308. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
  309. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +18 -0
  310. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
  311. package/packages/analyze/src/lib/files/getImportedExports.js +6 -1
  312. package/packages/analyze/src/lib/files/getImportedExports.js.map +1 -1
  313. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js +125 -0
  314. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js.map +1 -0
  315. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js +74 -19
  316. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js.map +1 -1
  317. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.js +1 -1
  318. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.js.map +1 -1
  319. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +175 -58
  320. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
  321. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js +10 -5
  322. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js.map +1 -1
  323. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js +127 -69
  324. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js.map +1 -1
  325. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js +2 -5
  326. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js.map +1 -1
  327. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +74 -23
  328. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
  329. package/packages/database/src/lib/kysely/db.js +2 -2
  330. package/packages/database/src/lib/kysely/tables/debugReportsTable.js +9 -3
  331. package/packages/database/src/lib/kysely/tables/debugReportsTable.js.map +1 -1
  332. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js +4 -2
  333. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
  334. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +8 -4
  335. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
  336. package/packages/generate/src/lib/deepMerge.js +27 -1
  337. package/packages/generate/src/lib/deepMerge.js.map +1 -1
  338. package/packages/generate/src/lib/getComponentScenarioPath.js +7 -3
  339. package/packages/generate/src/lib/getComponentScenarioPath.js.map +1 -1
  340. package/packages/types/index.js +1 -0
  341. package/packages/types/index.js.map +1 -1
  342. package/packages/types/src/types/Scenario.js +21 -1
  343. package/packages/types/src/types/Scenario.js.map +1 -1
  344. package/packages/utils/src/lib/applyUniversalMocks.js +26 -2
  345. package/packages/utils/src/lib/applyUniversalMocks.js.map +1 -1
  346. package/packages/utils/src/lib/lightweightEntityExtractor.js +25 -0
  347. package/packages/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
  348. package/scripts/finalize-analyzer.cjs +3 -1
  349. package/codeyam-cli/src/webserver/build/client/assets/EntityItem-CWKV2GEz.js +0 -1
  350. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-D2hFeDeg.js +0 -1
  351. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-C8K-4kKP.js +0 -26
  352. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-DgXLv61M.js +0 -3
  353. package/codeyam-cli/src/webserver/build/client/assets/LogViewer-DFdLQbPS.js +0 -3
  354. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-DlRDjT4h.js +0 -1
  355. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-7UkVL-UI.js +0 -1
  356. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-XjtsGuPo.js +0 -5
  357. package/codeyam-cli/src/webserver/build/client/assets/_index-D2eJjWLf.js +0 -1
  358. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-w6sbwlOd.js +0 -7
  359. package/codeyam-cli/src/webserver/build/client/assets/chevron-down-BBNQ8hup.js +0 -1
  360. package/codeyam-cli/src/webserver/build/client/assets/chunk-WWGJGFF6-Bex4RrGs.js +0 -26
  361. package/codeyam-cli/src/webserver/build/client/assets/circle-check-cdhjVtom.js +0 -1
  362. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-DkgmwwRC.js +0 -1
  363. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-CwLmCS0J.js +0 -1
  364. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-YZ-kM3ZG.js +0 -1
  365. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-BeQlz94_.js +0 -5
  366. package/codeyam-cli/src/webserver/build/client/assets/entry.client-DN2XXM7Z.js +0 -5
  367. package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-CUeAIQNI.js +0 -1
  368. package/codeyam-cli/src/webserver/build/client/assets/files-ccMQfhGf.js +0 -1
  369. package/codeyam-cli/src/webserver/build/client/assets/git-JmESAHx5.js +0 -12
  370. package/codeyam-cli/src/webserver/build/client/assets/globals-CO-U8Bpo.css +0 -1
  371. package/codeyam-cli/src/webserver/build/client/assets/html2canvas-pro.esm-XQCGvadH.js +0 -5
  372. package/codeyam-cli/src/webserver/build/client/assets/index-DsL9BiOc.js +0 -8
  373. package/codeyam-cli/src/webserver/build/client/assets/loader-circle-COYCR2oZ.js +0 -1
  374. package/codeyam-cli/src/webserver/build/client/assets/manifest-90adba57.js +0 -1
  375. package/codeyam-cli/src/webserver/build/client/assets/root-DfbVEEjF.js +0 -16
  376. package/codeyam-cli/src/webserver/build/client/assets/search-DvK9iMBu.js +0 -1
  377. package/codeyam-cli/src/webserver/build/client/assets/server-build-CMKNK2uU.css +0 -1
  378. package/codeyam-cli/src/webserver/build/client/assets/settings-9LTbit4Z.js +0 -1
  379. package/codeyam-cli/src/webserver/build/client/assets/simulations-BrxN5ZtV.js +0 -1
  380. package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-Iv0p8T-1.js +0 -1
  381. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-BWmSRPH6.js +0 -1
  382. package/codeyam-cli/src/webserver/build/server/assets/index-CE_1qXCG.js +0 -1
  383. package/codeyam-cli/src/webserver/build/server/assets/server-build-BY_VDhiD.js +0 -166
  384. package/codeyam-cli/templates/debug-command.md +0 -141
  385. /package/codeyam-cli/src/webserver/build/client/assets/{InteractivePreview-CMKNK2uU.css → styles-CMKNK2uU.css} +0 -0
@@ -7,6 +7,52 @@ import { splitOutsideParenthesesAndArrays } from "../../../../../packages/ai/ind
7
7
  import * as fs from 'fs';
8
8
  import * as path from 'path';
9
9
  import ts from 'typescript';
10
+ import { applyServerOnlyMocks } from "./serverOnlyModules.js";
11
+ // Debug timing helper for tracking where time is spent
12
+ const DEBUG_TIMING = process.env.DEBUG_WRITE_SCENARIO === 'true';
13
+ let debugStartTime;
14
+ let debugLastTime;
15
+ // Timeout protection to prevent infinite hangs
16
+ const WRITE_SCENARIO_TIMEOUT_MS = parseInt(process.env.WRITE_SCENARIO_TIMEOUT_MS || '300000', // Default 5 minutes
17
+ 10);
18
+ class WriteScenarioTimeoutError extends Error {
19
+ constructor(operation, timeoutMs) {
20
+ super(`WriteScenarioComponents timed out after ${timeoutMs}ms during: ${operation}`);
21
+ this.name = 'WriteScenarioTimeoutError';
22
+ }
23
+ }
24
+ async function withTimeout(operation, promise, timeoutMs = WRITE_SCENARIO_TIMEOUT_MS) {
25
+ let timeoutId;
26
+ const timeoutPromise = new Promise((_, reject) => {
27
+ timeoutId = setTimeout(() => {
28
+ reject(new WriteScenarioTimeoutError(operation, timeoutMs));
29
+ }, timeoutMs);
30
+ });
31
+ try {
32
+ return await Promise.race([promise, timeoutPromise]);
33
+ }
34
+ finally {
35
+ if (timeoutId)
36
+ clearTimeout(timeoutId);
37
+ }
38
+ }
39
+ function debugLog(message, extra) {
40
+ if (!DEBUG_TIMING)
41
+ return;
42
+ const now = Date.now();
43
+ if (!debugStartTime) {
44
+ debugStartTime = now;
45
+ debugLastTime = now;
46
+ }
47
+ const elapsed = now - debugStartTime;
48
+ const delta = now - debugLastTime;
49
+ debugLastTime = now;
50
+ console.log(`[WriteScenario +${elapsed}ms Δ${delta}ms] ${message}`, extra ? JSON.stringify(extra, null, 2) : '');
51
+ }
52
+ function resetDebugTiming() {
53
+ debugStartTime = 0;
54
+ debugLastTime = 0;
55
+ }
10
56
  /**
11
57
  * Find the end position of the last import/export-from statement using TypeScript AST.
12
58
  * This is more reliable than regex for handling multiline imports, comments, etc.
@@ -45,6 +91,106 @@ function findEndOfImports(content) {
45
91
  function escapeRegExp(str) {
46
92
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
47
93
  }
94
+ /**
95
+ * Remove a named import from file content using TypeScript AST.
96
+ * Handles both regular imports (`EntityName`) and type-only imports (`type EntityName`).
97
+ *
98
+ * @param fileContent - The file content to modify
99
+ * @param entityName - The name of the entity to remove from imports
100
+ * @returns The modified file content with the entity removed from imports
101
+ */
102
+ function removeNamedImportAst(fileContent, entityName) {
103
+ try {
104
+ const sourceFile = ts.createSourceFile('temp.tsx', fileContent, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
105
+ const replacements = [];
106
+ for (const statement of sourceFile.statements) {
107
+ if (!ts.isImportDeclaration(statement))
108
+ continue;
109
+ if (!statement.importClause?.namedBindings)
110
+ continue;
111
+ if (!ts.isNamedImports(statement.importClause.namedBindings))
112
+ continue;
113
+ const namedImports = statement.importClause.namedBindings;
114
+ const elements = namedImports.elements;
115
+ // Find the element that matches our entity name
116
+ const matchingIndex = elements.findIndex((el) => el.name.text === entityName);
117
+ if (matchingIndex === -1)
118
+ continue;
119
+ // Check if there's a default import (e.g., `import DefaultName, { NamedImport } from '...'`)
120
+ const hasDefaultImport = !!statement.importClause.name;
121
+ // If this is the only named import AND there's no default import, remove the entire statement
122
+ if (elements.length === 1 && !hasDefaultImport) {
123
+ // Find the end including any trailing newline
124
+ let end = statement.getEnd();
125
+ const afterStatement = fileContent.slice(end);
126
+ const trailingNewline = afterStatement.match(/^\r?\n/);
127
+ if (trailingNewline) {
128
+ end += trailingNewline[0].length;
129
+ }
130
+ replacements.push({
131
+ start: statement.getStart(sourceFile),
132
+ end,
133
+ replacement: '',
134
+ });
135
+ continue;
136
+ }
137
+ // Otherwise, rebuild the import without this element
138
+ const remainingElements = elements.filter((_, i) => i !== matchingIndex);
139
+ // Get the module specifier
140
+ const moduleSpecifier = statement.moduleSpecifier;
141
+ if (!ts.isStringLiteral(moduleSpecifier))
142
+ continue;
143
+ // Preserve import type modifier if present
144
+ const importTypePrefix = statement.importClause.isTypeOnly ? 'type ' : '';
145
+ // Get the default import name if present
146
+ const defaultImportName = statement.importClause.name?.text;
147
+ let newImport;
148
+ if (remainingElements.length === 0) {
149
+ // All named imports were removed, but there's a default import to preserve
150
+ // (we only get here when hasDefaultImport is true, because otherwise we'd have
151
+ // removed the whole statement at the elements.length === 1 check above)
152
+ newImport = `import ${defaultImportName} from ${moduleSpecifier.getText(sourceFile)};`;
153
+ }
154
+ else {
155
+ // Build the new named imports string
156
+ const newNamedImports = remainingElements
157
+ .map((el) => {
158
+ const isTypeOnly = el.isTypeOnly;
159
+ const name = el.name.text;
160
+ const propertyName = el.propertyName?.text;
161
+ if (propertyName) {
162
+ return isTypeOnly
163
+ ? `type ${propertyName} as ${name}`
164
+ : `${propertyName} as ${name}`;
165
+ }
166
+ return isTypeOnly ? `type ${name}` : name;
167
+ })
168
+ .join(', ');
169
+ // Build the new import statement, preserving default import if present
170
+ const defaultImportPrefix = defaultImportName
171
+ ? `${defaultImportName}, `
172
+ : '';
173
+ newImport = `import ${importTypePrefix}${defaultImportPrefix}{ ${newNamedImports} } from ${moduleSpecifier.getText(sourceFile)};`;
174
+ }
175
+ replacements.push({
176
+ start: statement.getStart(sourceFile),
177
+ end: statement.getEnd(),
178
+ replacement: newImport,
179
+ });
180
+ }
181
+ // Apply replacements in reverse order to preserve positions
182
+ let result = fileContent;
183
+ replacements.sort((a, b) => b.start - a.start);
184
+ for (const { start, end, replacement } of replacements) {
185
+ result = result.slice(0, start) + replacement + result.slice(end);
186
+ }
187
+ return result;
188
+ }
189
+ catch (error) {
190
+ console.warn('[removeNamedImportAst] Failed to parse file:', error);
191
+ return fileContent; // Return original content on error
192
+ }
193
+ }
48
194
  /**
49
195
  * Map nested dist paths to src paths.
50
196
  * Some build tools create nested structures like:
@@ -123,7 +269,6 @@ function convertDtsToStubs(content, entityName) {
123
269
  result = result.replace(/export\s*\{\s*\}\s*;?\s*$/g, '');
124
270
  // Keep export type and export interface statements as-is (they're valid in .ts)
125
271
  // No transformation needed for these
126
- console.log(`CodeYam: Converted .d.ts content for entity "${entityName}". Result length: ${result.length}`);
127
272
  return result;
128
273
  }
129
274
  /**
@@ -261,7 +406,6 @@ function stripHtmlBodyTags(fileContent, filePath, framework) {
261
406
  if (!/<html[^>]*>/.test(fileContent) || !/<body[^>]*>/.test(fileContent)) {
262
407
  return fileContent;
263
408
  }
264
- console.log(`CodeYam: Stripping <html> and <body> tags from root layout: ${filePath}`);
265
409
  // Extract the body className/attributes if any, to preserve styling
266
410
  const bodyMatch = fileContent.match(/<body([^>]*)>/);
267
411
  const bodyAttributes = bodyMatch?.[1]?.trim() || '';
@@ -299,10 +443,145 @@ function stripHtmlBodyTags(fileContent, filePath, framework) {
299
443
  }
300
444
  return result;
301
445
  }
446
+ /**
447
+ * Strip `import "server-only"` or `import 'server-only'` directives from file content.
448
+ *
449
+ * Next.js "server-only" package is used to mark modules that should only run on the server.
450
+ * When we generate scenario components for client-side rendering in the browser, importing
451
+ * a file with this directive causes an error:
452
+ *
453
+ * "You're importing a component that needs 'server-only'. That only works in a Server Component"
454
+ *
455
+ * Since our scenario components are rendered client-side for capture purposes, we need to
456
+ * strip this import to allow the file to be imported.
457
+ */
458
+ function stripServerOnlyImport(fileContent) {
459
+ // Match import "server-only" or import 'server-only' with optional semicolon and newline
460
+ // Handles both double and single quotes, with or without trailing semicolon
461
+ return fileContent.replace(/import\s+["']server-only["'];?\s*\n?/g, '');
462
+ }
463
+ /**
464
+ * Extract all internal import paths from file content.
465
+ * Internal imports are those that start with '.', '@/', '~/', or are relative paths.
466
+ * Excludes node_modules imports (bare specifiers like 'react', '@prisma/client').
467
+ */
468
+ function extractInternalImportPaths(fileContent) {
469
+ // Always use AST parsing - regex with nested quantifiers can cause catastrophic
470
+ // backtracking that hangs on a single .exec() call (before iteration limits kick in)
471
+ return extractInternalImportPathsAst(fileContent);
472
+ }
473
+ /**
474
+ * Extract internal import paths using TypeScript AST - more reliable for large files
475
+ */
476
+ function extractInternalImportPathsAst(fileContent) {
477
+ const importPaths = [];
478
+ try {
479
+ const sourceFile = ts.createSourceFile('temp.ts', fileContent, ts.ScriptTarget.Latest, true);
480
+ for (const statement of sourceFile.statements) {
481
+ if (ts.isImportDeclaration(statement) && statement.moduleSpecifier) {
482
+ const moduleSpecifier = statement.moduleSpecifier;
483
+ if (ts.isStringLiteral(moduleSpecifier)) {
484
+ const importPath = moduleSpecifier.text;
485
+ // Skip node_modules imports (bare specifiers)
486
+ if (importPath.startsWith('.') ||
487
+ importPath.startsWith('@/') ||
488
+ importPath.startsWith('~/') ||
489
+ importPath.startsWith('#')) {
490
+ importPaths.push(importPath);
491
+ }
492
+ }
493
+ }
494
+ }
495
+ }
496
+ catch (error) {
497
+ console.warn('[extractInternalImportPathsAst] Failed to parse file:', error);
498
+ }
499
+ return importPaths;
500
+ }
501
+ /**
502
+ * Resolve an import path to a file path relative to the project.
503
+ * Handles path aliases like @/, ~/, and relative paths.
504
+ */
505
+ function resolveImportPath(importPath, currentFilePath, project) {
506
+ let resolvedPath;
507
+ let appPrefix = '';
508
+ if (importPath.startsWith('./') || importPath.startsWith('../')) {
509
+ // Relative import - resolve relative to current file
510
+ const currentDir = currentFilePath.split('/').slice(0, -1).join('/');
511
+ const parts = [...currentDir.split('/'), ...importPath.split('/')];
512
+ const resolved = [];
513
+ for (const part of parts) {
514
+ if (part === '..') {
515
+ resolved.pop();
516
+ }
517
+ else if (part !== '.' && part !== '') {
518
+ resolved.push(part);
519
+ }
520
+ }
521
+ resolvedPath = resolved.join('/');
522
+ }
523
+ else if (importPath.startsWith('@/') || importPath.startsWith('~/')) {
524
+ // Path alias - strip the prefix
525
+ resolvedPath = importPath.slice(2);
526
+ // Infer app prefix from current file path
527
+ // e.g., if currentFilePath is "apps/web/lib/user/service.ts"
528
+ // and import is "@/modules/auth/lib/brevo", the actual file is at
529
+ // "apps/web/modules/auth/lib/brevo.ts"
530
+ // We detect this by checking if current file starts with "apps/XXX/"
531
+ const appMatch = currentFilePath.match(/^(apps\/[^/]+\/)/);
532
+ if (appMatch) {
533
+ appPrefix = appMatch[1];
534
+ }
535
+ }
536
+ else if (importPath.startsWith('#')) {
537
+ // Package imports - not supported yet
538
+ return null;
539
+ }
540
+ else {
541
+ // Unknown format
542
+ return null;
543
+ }
544
+ // Try to find the file with various extensions
545
+ const extensions = ['', '.ts', '.tsx', '.js', '.jsx'];
546
+ // First try with app prefix (for monorepo structures like apps/web/)
547
+ if (appPrefix) {
548
+ for (const ext of extensions) {
549
+ const fullPath = appPrefix + resolvedPath + ext;
550
+ const file = project.files?.find((f) => f.path === fullPath);
551
+ if (file) {
552
+ return file.path;
553
+ }
554
+ }
555
+ // Try index files with prefix
556
+ for (const ext of ['.ts', '.tsx', '.js', '.jsx']) {
557
+ const indexPath = `${appPrefix}${resolvedPath}/index${ext}`;
558
+ const file = project.files?.find((f) => f.path === indexPath);
559
+ if (file) {
560
+ return file.path;
561
+ }
562
+ }
563
+ }
564
+ // Then try without prefix (for simpler project structures)
565
+ for (const ext of extensions) {
566
+ const fullPath = resolvedPath + ext;
567
+ const file = project.files?.find((f) => f.path === fullPath);
568
+ if (file) {
569
+ return file.path;
570
+ }
571
+ }
572
+ // Try index files
573
+ for (const ext of ['.ts', '.tsx', '.js', '.jsx']) {
574
+ const indexPath = `${resolvedPath}/index${ext}`;
575
+ const file = project.files?.find((f) => f.path === indexPath);
576
+ if (file) {
577
+ return file.path;
578
+ }
579
+ }
580
+ return null;
581
+ }
302
582
  // Version for tracking deployments - increment when making changes
303
- const WRITE_SCENARIO_COMPONENTS_VERSION = '2.1.0-ast-based-import-detection';
583
+ const WRITE_SCENARIO_COMPONENTS_VERSION = '2.5.17-configurable-server-mocks';
304
584
  function addMockToContent(fileContent, importedExport, fileAnalyses, rootAnalysis, relativeMocksDir, scenarioName, importPath) {
305
- console.log(`CodeYam [v${WRITE_SCENARIO_COMPONENTS_VERSION}]: Adding mock for ${importedExport.name} from ${importedExport.filePath}`);
306
585
  // First try to find dependency schemas in fileAnalyses (for same-file dependencies)
307
586
  let dependencySchemas = fileAnalyses.find((a) => !!a.metadata?.mergedDataStructure?.dependencySchemas?.[importedExport.filePath]?.[importedExport.name])?.metadata?.mergedDataStructure?.dependencySchemas;
308
587
  // If not found in fileAnalyses, use root analysis's dependency schemas
@@ -317,23 +596,27 @@ function addMockToContent(fileContent, importedExport, fileAnalyses, rootAnalysi
317
596
  importedExport.calls.length > 1 &&
318
597
  importedExport.callVariableNames &&
319
598
  importedExport.callVariableNames.length === importedExport.calls.length;
320
- // DEBUG: Log import info for multiple calls debugging
321
- if (importedExport.name === 'useFetcher' ||
322
- importedExport.name?.includes('Fetcher')) {
323
- console.log('CodeYam DEBUG: addMockToContent useFetcher import:', JSON.stringify({
324
- name: importedExport.name,
325
- calls: importedExport.calls,
326
- callVariableNames: importedExport.callVariableNames,
327
- hasMultipleCallsWithVariables,
328
- isMocked: importedExport.isMocked,
329
- }, null, 2));
330
- }
331
599
  let mockCode;
332
600
  const variableMockCodes = [];
333
601
  if (hasMultipleCallsWithVariables) {
334
602
  // Generate separate mock functions for each variable-qualified call
335
- // Track variable name occurrences to disambiguate when same variable is reused
336
- // (mirrors the logic in gatherDataForMocks)
603
+ // Look up canonical keys from dataForMocks and track variable names for function naming
604
+ // Get all canonical keys for this hook (sorted by index)
605
+ const dataForMocks = rootAnalysis.metadata?.scenariosDataStructure?.dataForMocks;
606
+ const canonicalKeysForHook = dataForMocks
607
+ ? Object.keys(dataForMocks)
608
+ .filter((key) => {
609
+ const match = key.match(/^[^:]+::([^:]+)::\d+$/);
610
+ return match && match[1] === importedExport.name;
611
+ })
612
+ .sort((a, b) => {
613
+ // Sort by the index part (last ::N)
614
+ const indexA = parseInt(a.split('::').pop() || '0');
615
+ const indexB = parseInt(b.split('::').pop() || '0');
616
+ return indexA - indexB;
617
+ })
618
+ : [];
619
+ // Track variable name occurrences for unique function naming
337
620
  const variableNameCounts = {};
338
621
  for (let i = 0; i < importedExport.calls.length; i++) {
339
622
  const variableName = importedExport.callVariableNames[i];
@@ -342,28 +625,34 @@ function addMockToContent(fileContent, importedExport, fileAnalyses, rootAnalysi
342
625
  // Calculate the occurrence index for this variable name
343
626
  const occurrence = variableNameCounts[variableName] ?? 0;
344
627
  variableNameCounts[variableName] = occurrence + 1;
345
- // If this is a reused variable name (occurrence > 0), append index
346
- // e.g., "fetcher[1] <- useFetcher" for the second usage of "fetcher"
628
+ // Build indexed variable name for function naming
347
629
  const indexedVariableName = occurrence > 0 ? `${variableName}[${occurrence}]` : variableName;
348
- // Generate mock code for this specific call using variable-qualified name
349
- // Format: "variableName <- functionName" (reads as "variableName receives from functionName")
350
- const qualifiedName = `${indexedVariableName} <- ${importedExport.name}`;
351
- const variableMockCode = constructMockCode(qualifiedName, dependencySchemas, importedExport.entityType);
630
+ // Use safe function name with underscores instead of brackets
631
+ // e.g., fetcher[1] -> fetcher_1
632
+ const safeFunctionName = indexedVariableName.replace(/\[(\d+)\]/g, '_$1');
633
+ // Compute unique mock function name for call site replacement
634
+ // e.g., useFetcher_entityDiffFetcher, useFetcher_reportFetcher
635
+ const mockFunctionName = `${importedExport.name}_${safeFunctionName}`;
636
+ // Use the canonical key at index i if available
637
+ const canonicalKey = canonicalKeysForHook[i];
638
+ // Use variable-qualified format that constructMockCode understands
639
+ // e.g., "entityDiffFetcher <- useFetcher" for schema lookup
640
+ // This generates unique variable names like useFetcher_entityDiffFetcherReturnValue
641
+ const qualifiedMockName = `${indexedVariableName} <- ${importedExport.name}`;
642
+ // Generate mock code using the variable-qualified name and canonical key for data lookup
643
+ // This prevents "symbol already declared" errors when multiple calls exist
644
+ const variableMockCode = constructMockCode(qualifiedMockName, // Use variable-qualified format for unique naming
645
+ dependencySchemas, importedExport.entityType, canonicalKey);
352
646
  if (variableMockCode) {
353
647
  variableMockCodes.push(variableMockCode);
354
648
  // Replace the call site with the variable-specific mock function
355
649
  // e.g., useFetcher<BranchEntityDiffResult>() -> useFetcher_entityDiffFetcher()
356
650
  // e.g., useFetcher() -> useFetcher_reportFetcher()
357
- // For indexed variables: useFetcher() -> useFetcher_fetcher_1()
358
651
  const callSignature = importedExport.calls[i];
359
652
  // Escape special regex characters in the call signature
360
653
  const escapedCallSignature = callSignature.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
361
654
  // Create regex that matches the call (with optional whitespace variations)
362
655
  const callRegex = new RegExp(escapedCallSignature.replace(/\s+/g, '\\s*'), 'g');
363
- // Use safe function name with underscores instead of brackets
364
- // e.g., fetcher[1] -> fetcher_1
365
- const safeFunctionName = indexedVariableName.replace(/\[(\d+)\]/g, '_$1');
366
- const mockFunctionName = `${importedExport.name}_${safeFunctionName}`;
367
656
  fileContent = fileContent.replace(callRegex, `${mockFunctionName}()`);
368
657
  }
369
658
  }
@@ -378,50 +667,83 @@ function addMockToContent(fileContent, importedExport, fileAnalyses, rootAnalysi
378
667
  ? importedExport.callVariableNames[0]
379
668
  : undefined;
380
669
  if (singleCallVariableName) {
381
- // For single variable assignments, use the variable-qualified key for data lookup
382
- // but keep the original function name (no need for unique function names when there's only one assignment)
383
- const qualifiedKey = `${singleCallVariableName} <- ${importedExport.name}`;
384
- mockCode = `const ${importedExport.name}ReturnValue = scenarios().data()?.["${qualifiedKey}"];
670
+ // For single variable assignments, look up canonical key from dataForMocks
671
+ const dataForMocks = rootAnalysis.metadata?.scenariosDataStructure?.dataForMocks;
672
+ let canonicalKey = dataForMocks
673
+ ? Object.keys(dataForMocks).find((key) => {
674
+ // Check canonical key format: EntityName::hookName::index
675
+ const canonicalMatch = key.match(/^[^:]+::([^:]+)::\d+$/);
676
+ if (canonicalMatch && canonicalMatch[1] === importedExport.name) {
677
+ return true;
678
+ }
679
+ // Fall back to legacy format
680
+ const legacyMatch = key.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\s*<-\s*(.+)$/);
681
+ return legacyMatch && legacyMatch[2] === importedExport.name;
682
+ })
683
+ : undefined;
684
+ // If no canonical key found in dataForMocks, use variable-qualified format directly
685
+ // This allows constructMockCode to find the schema in dependencySchemas
686
+ if (!canonicalKey) {
687
+ canonicalKey = `${singleCallVariableName} <- ${importedExport.name}`;
688
+ }
689
+ // Keep the original function name since there's only one call
690
+ mockCode = constructMockCode(importedExport.name, dependencySchemas, importedExport.entityType, canonicalKey, { keepOriginalFunctionName: true });
691
+ // If constructMockCode didn't generate code, fall back to simple return
692
+ if (!mockCode) {
693
+ mockCode = `const ${importedExport.name}ReturnValue = scenarios().data()?.["${canonicalKey}"];
385
694
 
386
695
  function ${importedExport.name}() {
387
696
  return ${importedExport.name}ReturnValue;
388
697
  }`;
698
+ }
389
699
  }
390
700
  else {
391
- // Check if any analysis (fileAnalyses or rootAnalysis) has this function's data
392
- // under a variable-qualified key. The entity that CALLS the function (e.g., FileTableRow)
393
- // has the dataForMocks with the variable-qualified key, not the root analysis (e.g., GitView).
394
- let variableQualifiedKey;
395
- // First check fileAnalyses (the analyses for the entity being written)
396
- for (const analysis of fileAnalyses) {
397
- const dataForMocks = analysis.metadata?.scenariosDataStructure?.dataForMocks;
398
- if (dataForMocks) {
399
- variableQualifiedKey = Object.keys(dataForMocks).find((key) => {
400
- const match = key.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\s*<-\s*(.+)$/);
401
- return match && match[2] === importedExport.name;
402
- });
403
- if (variableQualifiedKey) {
404
- break;
701
+ // Look for canonical key (format: EntityName::hookName::index) or legacy variable-qualified key
702
+ let canonicalKey;
703
+ // Helper to find matching key from dataForMocks
704
+ const findMatchingKey = (dataForMocks) => {
705
+ if (!dataForMocks)
706
+ return undefined;
707
+ return Object.keys(dataForMocks).find((key) => {
708
+ // Check canonical key format: EntityName::hookName::index
709
+ const canonicalMatch = key.match(/^[^:]+::([^:]+)::\d+$/);
710
+ if (canonicalMatch && canonicalMatch[1] === importedExport.name) {
711
+ return true;
405
712
  }
713
+ // Fall back to legacy variable-qualified format: variableName <- functionName
714
+ const legacyMatch = key.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\s*<-\s*(.+)$/);
715
+ return legacyMatch && legacyMatch[2] === importedExport.name;
716
+ });
717
+ };
718
+ // CRITICAL: Check rootAnalysis FIRST for canonical keys.
719
+ // This ensures we use the same keys that will be in the mock DATA.
720
+ // The mock DATA is generated from rootAnalysis, so the mock CODE must
721
+ // also use rootAnalysis keys to ensure the lookup succeeds.
722
+ // Bug scenario (if we check fileAnalyses first):
723
+ // - Child component's fileAnalysis has: "ChildComponent::hook::0"
724
+ // - Root's dataForMocks has: "RootEntity::hook::0"
725
+ // - Mock CODE uses child key, but mock DATA has root key → lookup fails
726
+ canonicalKey = findMatchingKey(rootAnalysis.metadata?.scenariosDataStructure?.dataForMocks);
727
+ // If not found in rootAnalysis, fall back to fileAnalyses
728
+ if (!canonicalKey) {
729
+ for (const analysis of fileAnalyses) {
730
+ canonicalKey = findMatchingKey(analysis.metadata?.scenariosDataStructure?.dataForMocks);
731
+ if (canonicalKey)
732
+ break;
406
733
  }
407
734
  }
408
- // If not found in fileAnalyses, fall back to rootAnalysis
409
- if (!variableQualifiedKey) {
410
- const dataForMocks = rootAnalysis.metadata?.scenariosDataStructure?.dataForMocks;
411
- if (dataForMocks) {
412
- variableQualifiedKey = Object.keys(dataForMocks).find((key) => {
413
- const match = key.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\s*<-\s*(.+)$/);
414
- return match && match[2] === importedExport.name;
415
- });
416
- }
417
- }
418
- if (variableQualifiedKey) {
419
- // Use the variable-qualified key found in the analysis
420
- mockCode = `const ${importedExport.name}ReturnValue = scenarios().data()?.["${variableQualifiedKey}"];
735
+ if (canonicalKey) {
736
+ // Use the canonical key for data lookup
737
+ // Keep the original function name since there's only one call
738
+ mockCode = constructMockCode(importedExport.name, dependencySchemas, importedExport.entityType, canonicalKey, { keepOriginalFunctionName: true });
739
+ // If constructMockCode didn't generate code, fall back to simple return
740
+ if (!mockCode) {
741
+ mockCode = `const ${importedExport.name}ReturnValue = scenarios().data()?.["${canonicalKey}"];
421
742
 
422
743
  function ${importedExport.name}() {
423
744
  return ${importedExport.name}ReturnValue;
424
745
  }`;
746
+ }
425
747
  }
426
748
  else {
427
749
  // Original behavior for calls without variable names
@@ -432,20 +754,6 @@ function ${importedExport.name}() {
432
754
  // Combine all mock codes
433
755
  const allMockCodes = variableMockCodes.length > 0 ? variableMockCodes.join('\n\n') : mockCode;
434
756
  if (!allMockCodes) {
435
- console.log('CodeYam Error: Mock code not found', JSON.stringify({
436
- importedExportFilePath: importedExport.filePath,
437
- importedExportEntityName: importedExport.name,
438
- hasMultipleCallsWithVariables,
439
- analysisIds: fileAnalyses.map((a) => ({
440
- id: a.id,
441
- filePath: a.filePath,
442
- entityName: a.entityName,
443
- })),
444
- analysisFilePath: fileAnalyses?.[0]?.filePath,
445
- analysisEntityNames: fileAnalyses.map((a) => a.entityName),
446
- dependencySchemas: fileAnalyses.find((a) => !!a.entity.metadata?.isolatedDataStructure?.dependencySchemas?.[importedExport.filePath]?.[importedExport.name])?.entity.metadata?.isolatedDataStructure?.dependencySchemas,
447
- allDependencySchemas: fileAnalyses.map((a) => a.entity.metadata?.isolatedDataStructure?.dependencySchemas),
448
- }, null, 2));
449
757
  return fileContent;
450
758
  }
451
759
  if (importPath) {
@@ -504,7 +812,6 @@ function ${importedExport.name}() {
504
812
  insertContent += `\n\n// Mock constructed using mocksDataStructure from analyses: ${fileAnalyses.map((a) => a.id).join(', ')}\n${allMockCodes}`;
505
813
  if (lastImportEnd > 0) {
506
814
  // Insert after the last original import
507
- console.log(`CodeYam [v${WRITE_SCENARIO_COMPONENTS_VERSION}]: Inserting mock at position ${lastImportEnd} (after imports), not at end`);
508
815
  fileContent =
509
816
  fileContent.slice(0, lastImportEnd) +
510
817
  insertContent +
@@ -512,7 +819,6 @@ function ${importedExport.name}() {
512
819
  }
513
820
  else {
514
821
  // Fallback: append at end if no imports found
515
- console.log(`CodeYam [v${WRITE_SCENARIO_COMPONENTS_VERSION}]: No imports found, appending mock at end`);
516
822
  fileContent += insertContent;
517
823
  }
518
824
  return fileContent;
@@ -659,6 +965,14 @@ function captureArgumentsForTesting(args) {
659
965
  }
660
966
  export default async function writeScenarioComponents({ project, file, entity, rootAnalysis, scenario, context, projectAnalyzer, framework, mocksDir, rootFile, namespaceMocks, writtenScenarioComponents = {}, fileStore, exportAsNamed, }) {
661
967
  var _a;
968
+ // Reset debug timing for this invocation
969
+ resetDebugTiming();
970
+ debugLog('START writeScenarioComponents', {
971
+ filePath: file.path,
972
+ entityName: entity.name,
973
+ scenarioName: scenario.name,
974
+ isRootFile: !rootFile || rootFile === file,
975
+ });
662
976
  // Capture arguments for testing if debug mode is enabled
663
977
  captureArgumentsForTesting({
664
978
  project,
@@ -731,7 +1045,6 @@ export default async function writeScenarioComponents({ project, file, entity, r
731
1045
  // .d.ts files only have type declarations (e.g., "export declare const logger")
732
1046
  // which don't provide runtime exports. We need to generate actual stub implementations.
733
1047
  if (file.path.endsWith('.d.ts')) {
734
- console.log(`CodeYam: Converting .d.ts file to stub implementations: ${file.path}`);
735
1048
  fileContent = convertDtsToStubs(fileContent, entity.name);
736
1049
  // After basic .d.ts conversion, enhance the entity's stub with proper mock code
737
1050
  // if we have dependency schema data showing its methods/properties.
@@ -803,7 +1116,20 @@ export default async function writeScenarioComponents({ project, file, entity, r
803
1116
  return 1;
804
1117
  return 0;
805
1118
  });
1119
+ debugLog('Starting main importedExports loop', {
1120
+ count: sortedImportedExports.length,
1121
+ fileContentLength: fileContent.length,
1122
+ });
1123
+ let importedExportIndex = 0;
806
1124
  for (const importedExport of sortedImportedExports) {
1125
+ importedExportIndex++;
1126
+ if (importedExportIndex % 5 === 0 || importedExportIndex === 1) {
1127
+ debugLog(`Processing importedExport ${importedExportIndex}/${sortedImportedExports.length}`, {
1128
+ name: importedExport.name,
1129
+ filePath: importedExport.filePath,
1130
+ isMocked: importedExport.isMocked,
1131
+ });
1132
+ }
807
1133
  // IMPORTANT: The import mapping keys may be either absolute or relative paths
808
1134
  // depending on how they were created by the file analyzer. We try multiple formats.
809
1135
  // Also need to normalize paths to handle /tmp vs /private/tmp on macOS
@@ -852,12 +1178,6 @@ export default async function writeScenarioComponents({ project, file, entity, r
852
1178
  // where the entity code lives, not the re-export file.
853
1179
  if (!isSameFile) {
854
1180
  if (!writtenScenarioComponents[importedExportFilePath]?.includes(importedExport.name)) {
855
- // Skip recursion for type/data entities - they don't need scenario components
856
- // Only recurse for visual and library entities that need mocking
857
- if (importedExportEntity.entityType === 'type' ||
858
- importedExportEntity.entityType === 'data') {
859
- continue;
860
- }
861
1181
  // Use fileStore for O(1) lookup when available
862
1182
  let fileNotMocked = fileStore
863
1183
  ? fileStore.getByPath(importedExportFilePath)
@@ -883,30 +1203,86 @@ export default async function writeScenarioComponents({ project, file, entity, r
883
1203
  !fileStore.isContentLoaded(fileNotMocked.path)) {
884
1204
  fileNotMocked = await fileStore.ensureContent(fileNotMocked.path);
885
1205
  }
886
- // When a default export is imported as named (via index re-export), we need
887
- // to add a named re-export to the scenario component so the import works.
888
- // e.g., if file has `export default X` but parent does `import { X } from '...'`
889
- const needsNamedReExport = importedExport.resolvedIsDefault === true &&
890
- importedExport.isDefault === false;
891
- const { scenarioComponentPaths: newScenarioComponentPaths, writtenScenarioComponents: updatedWrittenScenarioComponents, } = await writeScenarioComponents({
892
- project,
893
- file: fileNotMocked,
894
- entity: importedExportEntity,
895
- rootAnalysis,
896
- scenario,
897
- context,
898
- projectAnalyzer,
899
- framework,
900
- mocksDir,
901
- rootFile,
902
- namespaceMocks,
903
- writtenScenarioComponents,
904
- fileStore,
905
- // Pass the import name so we can add `export { default as Name };`
906
- exportAsNamed: needsNamedReExport ? importedExport.name : undefined,
907
- });
908
- writtenScenarioComponents = updatedWrittenScenarioComponents;
909
- scenarioComponentPaths.push(...newScenarioComponentPaths);
1206
+ // For type/data entities, create a transformed copy WITHOUT recursion.
1207
+ // Data entities don't need mocking - they're just constants/types that need
1208
+ // to be available. But we still need to:
1209
+ // 1. Strip server-only imports (Next.js directive that breaks client components)
1210
+ // 2. Write the transformed file so imports can be rewritten to point to it
1211
+ if (importedExportEntity.entityType === 'type' ||
1212
+ importedExportEntity.entityType === 'data') {
1213
+ // For data entities, we write ONE transformed copy per source file, not per entity.
1214
+ // Check if we've already written ANY entity from this file - if so, skip writing.
1215
+ // Use a special marker '__data_file_written__' to track file-level writes.
1216
+ // Also track which SHA was used via '__data_file_sha__:xxx' so subsequent
1217
+ // entities from the same file can reuse it for import rewriting.
1218
+ const dataFileWritten = writtenScenarioComponents[importedExportFilePath]?.includes('__data_file_written__');
1219
+ if (!dataFileWritten) {
1220
+ // Construct the scenario file path for the data file
1221
+ // Use a file-level identifier (first entity's sha) for consistency
1222
+ const dataFileBasePath = safeFolder(fileNotMocked.path.split('/').slice(0, -1).join('/'));
1223
+ const dataFileExtension = fileNotMocked.name.split('.').pop();
1224
+ const dataFileIsIndex = isIndexPath(fileNotMocked.path);
1225
+ // Use 'data' prefix to distinguish from entity-specific files
1226
+ const dataScenarioPath = `${PROJECT_RELATIVE_PATH}/${dataFileBasePath}/${importedExportEntity.sha}_${dataFileIsIndex ? 'index_' : ''}data_${safeFileName(scenario.name)}.${dataFileExtension}`;
1227
+ // Get the file content and apply transformations
1228
+ let dataFileContent = fileNotMocked.content ?? '';
1229
+ // Strip server-only imports - these break when imported by client components
1230
+ dataFileContent = stripServerOnlyImport(dataFileContent);
1231
+ dataFileContent = applyServerOnlyMocks(dataFileContent);
1232
+ // Write the transformed data entity file
1233
+ await writeFile(dataScenarioPath, dataFileContent);
1234
+ scenarioComponentPaths.push(dataScenarioPath);
1235
+ // Mark file as written so we don't duplicate for other entities from same file
1236
+ if (!writtenScenarioComponents[importedExportFilePath]) {
1237
+ writtenScenarioComponents[importedExportFilePath] = [];
1238
+ }
1239
+ writtenScenarioComponents[importedExportFilePath].push('__data_file_written__');
1240
+ // Also store the SHA used for this data file so subsequent entities can use it
1241
+ writtenScenarioComponents[importedExportFilePath].push(`__data_file_sha__:${importedExportEntity.sha}`);
1242
+ }
1243
+ // Mark this specific entity as written (for the entity-level check)
1244
+ if (!writtenScenarioComponents[importedExportFilePath]) {
1245
+ writtenScenarioComponents[importedExportFilePath] = [];
1246
+ }
1247
+ writtenScenarioComponents[importedExportFilePath].push(importedExport.name);
1248
+ // Don't recurse - data entities don't need their dependencies processed
1249
+ // The import rewriting will happen later in this same loop iteration
1250
+ // (at lines ~1590-1702) to point imports to this transformed file
1251
+ }
1252
+ else {
1253
+ // For visual/library entities, recurse to process their dependencies
1254
+ // When a default export is imported as named (via index re-export), we need
1255
+ // to add a named re-export to the scenario component so the import works.
1256
+ // e.g., if file has `export default X` but parent does `import { X } from '...'`
1257
+ const needsNamedReExport = importedExport.resolvedIsDefault === true &&
1258
+ importedExport.isDefault === false;
1259
+ debugLog(`Recursing into writeScenarioComponents for ${importedExportEntity.name}`, {
1260
+ entityName: importedExportEntity.name,
1261
+ filePath: fileNotMocked.path,
1262
+ });
1263
+ const { scenarioComponentPaths: newScenarioComponentPaths, writtenScenarioComponents: updatedWrittenScenarioComponents, } = await withTimeout(`recursive writeScenarioComponents for ${importedExportEntity.name}`, writeScenarioComponents({
1264
+ project,
1265
+ file: fileNotMocked,
1266
+ entity: importedExportEntity,
1267
+ rootAnalysis,
1268
+ scenario,
1269
+ context,
1270
+ projectAnalyzer,
1271
+ framework,
1272
+ mocksDir,
1273
+ rootFile,
1274
+ namespaceMocks,
1275
+ writtenScenarioComponents,
1276
+ fileStore,
1277
+ // Pass the import name so we can add `export { default as Name };`
1278
+ exportAsNamed: needsNamedReExport
1279
+ ? importedExport.name
1280
+ : undefined,
1281
+ }), 60000);
1282
+ debugLog(`Completed recursive writeScenarioComponents for ${importedExportEntity.name}`);
1283
+ writtenScenarioComponents = updatedWrittenScenarioComponents;
1284
+ scenarioComponentPaths.push(...newScenarioComponentPaths);
1285
+ }
910
1286
  }
911
1287
  }
912
1288
  }
@@ -926,9 +1302,6 @@ export default async function writeScenarioComponents({ project, file, entity, r
926
1302
  const looksLikeZodSchema = entityType === 'library' &&
927
1303
  /^Z[A-Z]/.test(importedExport.name) &&
928
1304
  importedExport.calls?.some((call) => /\.(superRefine|refine|transform|default|optional|nullable|array|object|string|number|boolean|parse|safeParse)\s*\(/.test(call));
929
- if (looksLikeZodSchema) {
930
- console.log(`CodeYam: Detected Zod schema "${importedExport.name}" (misclassified as library) - will preserve`);
931
- }
932
1305
  // Callable entities can be safely stubbed (but not Zod schemas)
933
1306
  const isCallable = !isDataEntity && !looksLikeZodSchema && entityType !== undefined;
934
1307
  // Determine what action to take
@@ -944,7 +1317,6 @@ export default async function writeScenarioComponents({ project, file, entity, r
944
1317
  if (shouldPreserve) {
945
1318
  // For data entities (like Zod schemas), don't strip or stub - preserve the original
946
1319
  // This ensures schema methods like .superRefine() continue to work
947
- console.log(`CodeYam: Preserving ${importedExport.name} (entityType: ${entityType}) - not stripping data entities`);
948
1320
  // Don't modify fileContent - keep the original code
949
1321
  }
950
1322
  else if (shouldStripAndReplace || shouldStripAndStub) {
@@ -962,7 +1334,6 @@ export default async function writeScenarioComponents({ project, file, entity, r
962
1334
  // This prevents ReferenceError at runtime when the stripped
963
1335
  // function is called (e.g., local helper functions like getInitialProps).
964
1336
  const functionName = importedExport.name;
965
- console.log(`CodeYam: Generating stub mock for ${functionName} (entityType: ${entityType}) in ${file.path}`);
966
1337
  // Add scenarios import if not present
967
1338
  if (fileContent.indexOf('import { scenarios } from') === -1) {
968
1339
  const mockDataPath = `${relativeMocksDir}/MockData_${safeFileName(scenario.name)}`;
@@ -1072,6 +1443,25 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1072
1443
  }
1073
1444
  const fileName = actualScenarioFilePathRelative.split('/').pop();
1074
1445
  const fileNotMockedIsIndex = isIndexPath(fileNotMocked?.path);
1446
+ // For data/type entities, use 'data' instead of entity name since we write
1447
+ // ONE file per source file (not per entity) for data entities
1448
+ const isDataEntity = importedExportEntity?.entityType === 'data' ||
1449
+ importedExportEntity?.entityType === 'type';
1450
+ const scenarioFileName = isDataEntity
1451
+ ? 'data'
1452
+ : safeFileName(importedExportEntity.name);
1453
+ // For data entities, look up the SHA that was used to create the data file
1454
+ // (stored when the file was first written). This ensures all entities from
1455
+ // the same source file have their imports rewritten to point to the same file.
1456
+ // Use actualScenarioFilePathRelative as the key since that's what matches
1457
+ // importedExportFilePath used when storing (both are relative paths).
1458
+ let entityShaForPath = importedExportEntity.sha;
1459
+ if (isDataEntity && actualScenarioFilePathRelative) {
1460
+ const storedShaMarker = writtenScenarioComponents[actualScenarioFilePathRelative]?.find((m) => m.startsWith('__data_file_sha__:'));
1461
+ if (storedShaMarker) {
1462
+ entityShaForPath = storedShaMarker.replace('__data_file_sha__:', '');
1463
+ }
1464
+ }
1075
1465
  const mockFilePath = isFrameworkRoute(fileNotMocked, importedExportEntity, framework, fileNotMocked === rootFile)
1076
1466
  ? getFrameworkRoutePath({
1077
1467
  file: fileNotMocked,
@@ -1086,7 +1476,7 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1086
1476
  .split('.')
1087
1477
  .slice(0, -1)
1088
1478
  .join('.')
1089
- : actualScenarioFilePathRelative.replace(`${fileName}`, `${importedExportEntity.sha}_${fileNotMockedIsIndex ? 'index_' : ''}${safeFileName(importedExportEntity.name)}_${safeFileName(scenario.name)}`);
1479
+ : actualScenarioFilePathRelative.replace(`${fileName}`, `${entityShaForPath}_${fileNotMockedIsIndex ? 'index_' : ''}${scenarioFileName}_${safeFileName(scenario.name)}`);
1090
1480
  const path = safeFolder(getRelativePath(filePath, mockFilePath));
1091
1481
  // If we have an import mapping, use it to find the import string to replace
1092
1482
  // Otherwise, skip rewriting (we can't find the import statement without knowing what to search for)
@@ -1117,19 +1507,26 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1117
1507
  // This handles cases where multiple entities are imported from the same index file
1118
1508
  // (e.g., import { A, B, C } from '@pkg') and each has its own scenario file
1119
1509
  const entityImportName = importedExport.name;
1120
- const newImport = `import { ${entityImportName} } from '${path}';`;
1510
+ // Use default import syntax for default exports, named import for named exports
1511
+ const newImport = importedExport.isDefault
1512
+ ? `import ${entityImportName} from '${path}';`
1513
+ : `import { ${entityImportName} } from '${path}';`;
1121
1514
  // First, try to remove this entity from the already-rewritten grouped import
1122
1515
  // This prevents duplicate/conflicting imports
1123
- // Match patterns like "EntityName," or ", EntityName" or "EntityName" (if only one)
1124
- // Note: entityImportName needs escaping since JS identifiers can contain $ (a regex metacharacter)
1516
+ // Use AST-based removal to properly handle type-only imports like `type EntityName`
1125
1517
  const escapedEntityName = escapeRegExp(entityImportName);
1126
- const removeFromGroupedImportPatterns = [
1127
- new RegExp(`\\b${escapedEntityName}\\s*,\\s*`, 'g'), // "EntityName, "
1128
- new RegExp(`\\s*,\\s*${escapedEntityName}\\b`, 'g'), // ", EntityName"
1129
- ];
1130
- for (const pattern of removeFromGroupedImportPatterns) {
1131
- fileContent = fileContent.replace(pattern, '');
1518
+ // For default imports: remove "DefaultName, " from "import DefaultName, { ... }"
1519
+ // This handles the case where a default export is being split out
1520
+ if (importedExport.isDefault) {
1521
+ const defaultImportPattern = new RegExp(`(import\\s+)${escapedEntityName}\\s*,\\s*(\\{)`, 'gm');
1522
+ fileContent = fileContent.replace(defaultImportPattern, '$1$2');
1132
1523
  }
1524
+ // Remove the named import using AST parsing
1525
+ // This properly handles:
1526
+ // - Regular imports: `import { EntityName } from '...'`
1527
+ // - Type-only imports: `import { type EntityName } from '...'`
1528
+ // - Mixed imports: `import { type EntityName, OtherName } from '...'`
1529
+ fileContent = removeNamedImportAst(fileContent, entityImportName);
1133
1530
  // Add the new import at the beginning of fileContent
1134
1531
  // Note: The header comment (// Scenario:) doesn't exist yet - it's prepended at writeFile time
1135
1532
  // So prepending here puts the import right after the header in the final output
@@ -1143,17 +1540,27 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1143
1540
  }
1144
1541
  }
1145
1542
  }
1543
+ // Collect universal mocks BEFORE processing nodeModuleImports
1544
+ // This is needed to check if a node module import is handled by a universal mock
1545
+ const universalMocks = project.metadata?.universalMocks ?? [];
1546
+ const nodeModuleUniversalMocks = universalMocks.filter((mock) => mock.nodeModule && mock.content);
1547
+ // Create a set of import paths that have universal mocks for quick lookup
1548
+ const universalMockPaths = new Set(nodeModuleUniversalMocks.map((mock) => mock.filePath));
1146
1549
  for (const nodeModuleImport of nodeModuleImports) {
1147
1550
  if (!nodeModuleImport.isMocked)
1148
1551
  continue;
1552
+ // Skip generating local mock functions for imports that have universal mocks.
1553
+ // Universal mocks provide the exports via rewritten import paths (handled below).
1554
+ // Generating a local mock function would cause "name defined multiple times" errors.
1555
+ if (universalMockPaths.has(nodeModuleImport.filePath)) {
1556
+ continue;
1557
+ }
1149
1558
  fileContent = addMockToContent(fileContent, nodeModuleImport, fileAnalyses, rootAnalysis, relativeMocksDir, scenario.name, importMapping[nodeModuleImport.filePath] ?? nodeModuleImport.filePath);
1150
1559
  }
1151
1560
  // Rewrite node_module imports that have universal mocks
1152
1561
  // Universal mocks create mock files at __codeyamMocks__/{safeFileName}.tsx
1153
1562
  // We need to rewrite imports like `import { logger } from "@formbricks/logger"`
1154
1563
  // to `import { logger } from "../__codeyamMocks__/_formbricks_logger.js"`
1155
- const universalMocks = project.metadata?.universalMocks ?? [];
1156
- const nodeModuleUniversalMocks = universalMocks.filter((mock) => mock.nodeModule && mock.content);
1157
1564
  for (const universalMock of nodeModuleUniversalMocks) {
1158
1565
  const originalPath = universalMock.filePath;
1159
1566
  // Create the mock file name using the same safeFileName function as writeUniversalMocks
@@ -1201,17 +1608,328 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1201
1608
  scenario,
1202
1609
  });
1203
1610
  }
1611
+ debugLog('Route path computed', { scenarioComponentPath });
1204
1612
  // Strip <html> and <body> tags from root layout files for Next.js
1205
1613
  // These tags cause hydration errors when the scenario layout is nested under the real root
1614
+ debugLog('Starting stripHtmlBodyTags');
1206
1615
  fileContent = stripHtmlBodyTags(fileContent, file.path, framework);
1616
+ debugLog('Completed stripHtmlBodyTags');
1617
+ // Strip "server-only" imports for Next.js
1618
+ // These cause errors when the scenario component is rendered client-side
1619
+ debugLog('Starting stripServerOnlyImport');
1620
+ fileContent = stripServerOnlyImport(fileContent);
1621
+ debugLog('Starting applyServerOnlyMocks');
1622
+ fileContent = applyServerOnlyMocks(fileContent);
1623
+ debugLog('Completed server-only processing');
1207
1624
  // Rewrite asset imports (CSS, images, fonts, etc.) to correct relative paths
1208
1625
  // The original file path is relative to PROJECT_RELATIVE_PATH, the new path is scenarioComponentPath
1626
+ debugLog('Starting rewriteAssetImports');
1209
1627
  fileContent = rewriteAssetImports(fileContent, `${PROJECT_RELATIVE_PATH}/${file.path}`, scenarioComponentPath);
1628
+ debugLog('Completed rewriteAssetImports');
1210
1629
  // Rewrite relative TypeScript/JavaScript module imports to correct relative paths
1211
1630
  // This handles cases where the file is moved (e.g., from [environmentId]/ to _environmentId_/)
1212
1631
  // and relative imports like "./lib/organization" need to be rewritten
1632
+ debugLog('Starting rewriteRelativeModuleImports');
1213
1633
  fileContent = rewriteRelativeModuleImports(fileContent, `${PROJECT_RELATIVE_PATH}/${file.path}`, scenarioComponentPath);
1214
- console.log('Writing scenario component', file.path, entity.name, scenarioComponentPath, fileContent.length);
1634
+ debugLog('Completed rewriteRelativeModuleImports');
1635
+ /**
1636
+ * Recursively process a file's imports to create transitive copies with server-only stripped.
1637
+ * This handles chains of arbitrary depth: A -> B -> C -> D where each needs server-only removed.
1638
+ * Uses a visited set to detect and break circular import chains.
1639
+ *
1640
+ * @param content - The file content to process
1641
+ * @param sourceFilePath - The original source file path (for resolving relative imports)
1642
+ * @param targetFilePath - The path where this content will be written (for computing relative imports)
1643
+ * @param visitedPaths - Set of file paths currently being processed (for cycle detection)
1644
+ * @returns The modified content with imports rewritten to point to transitive copies
1645
+ */
1646
+ async function processTransitiveImportsRecursively(content, sourceFilePath, targetFilePath, visitedPaths = new Set(), depth = 0, startTime = Date.now()) {
1647
+ // Global timeout for entire transitive processing
1648
+ const GLOBAL_TIMEOUT_MS = 60000; // 1 minute max for all transitive processing
1649
+ const elapsed = Date.now() - startTime;
1650
+ if (elapsed > GLOBAL_TIMEOUT_MS) {
1651
+ throw new Error(`processTransitiveImportsRecursively exceeded ${GLOBAL_TIMEOUT_MS}ms (elapsed: ${elapsed}ms) at depth=${depth} for ${sourceFilePath}`);
1652
+ }
1653
+ const importPaths = extractInternalImportPaths(content);
1654
+ debugLog(`processTransitiveImportsRecursively depth=${depth}`, {
1655
+ sourceFilePath,
1656
+ importCount: importPaths.length,
1657
+ visitedCount: visitedPaths.size,
1658
+ });
1659
+ let modifiedContent = content;
1660
+ // Safety check: limit iterations to prevent infinite loops
1661
+ const MAX_IMPORTS_PER_FILE = 100;
1662
+ if (importPaths.length > MAX_IMPORTS_PER_FILE) {
1663
+ console.warn(`[WriteScenario] WARNING: File ${sourceFilePath} has ${importPaths.length} imports (> ${MAX_IMPORTS_PER_FILE}), limiting processing`);
1664
+ }
1665
+ let importIndex = 0;
1666
+ debugLog(`Starting import loop at depth=${depth}, ${importPaths.length} imports to process`);
1667
+ const slicedImports = importPaths.slice(0, MAX_IMPORTS_PER_FILE);
1668
+ for (const importPath of slicedImports) {
1669
+ if (!importPath) {
1670
+ continue;
1671
+ }
1672
+ importIndex++;
1673
+ debugLog(`[LOOP] depth=${depth} import ${importIndex}/${Math.min(importPaths.length, MAX_IMPORTS_PER_FILE)}: ${importPath}`);
1674
+ debugLog(`[LOOP] Calling resolveImportPath...`);
1675
+ const resolvedPath = resolveImportPath(importPath, sourceFilePath, project);
1676
+ debugLog(`[LOOP] resolveImportPath returned: ${resolvedPath?.slice(0, 80) ?? 'null'}`);
1677
+ if (!resolvedPath)
1678
+ continue;
1679
+ debugLog(`[LOOP] Looking up importFile...`);
1680
+ let importFile = fileStore
1681
+ ? fileStore.getByPath(resolvedPath)
1682
+ : project.files?.find((f) => f.path === resolvedPath);
1683
+ debugLog(`[LOOP] importFile lookup result: ${importFile ? 'found' : 'not found'}`);
1684
+ if (!importFile)
1685
+ continue;
1686
+ // Build the transitive file path (needed for import rewriting even if we skip creating)
1687
+ const basePath = safeFolder(importFile.path.split('/').slice(0, -1).join('/'));
1688
+ const extension = importFile.name.split('.').pop();
1689
+ const isIndex = isIndexPath(importFile.path);
1690
+ const pathHash = safeFileName(importFile.path);
1691
+ const transitiveFilePath = `${PROJECT_RELATIVE_PATH}/${basePath}/${pathHash}_${isIndex ? 'index_' : ''}transitive_${safeFileName(scenario.name)}.${extension}`;
1692
+ // Check if this is a circular import (we're already processing this file)
1693
+ const isCircularImport = visitedPaths.has(resolvedPath);
1694
+ // Check if already processed
1695
+ const alreadyProcessed = writtenScenarioComponents[resolvedPath]?.includes('__transitive_file_written__');
1696
+ // Only create the transitive file if not circular and not already processed
1697
+ if (!isCircularImport && !alreadyProcessed) {
1698
+ // Load content if needed
1699
+ if (!importFile.content && fileStore) {
1700
+ importFile = await fileStore.ensureContent(resolvedPath);
1701
+ }
1702
+ if (!importFile?.content) {
1703
+ // Can't create transitive, but still try to rewrite import below
1704
+ }
1705
+ else {
1706
+ // Mark as being processed BEFORE recursing (to detect cycles)
1707
+ visitedPaths.add(resolvedPath);
1708
+ // Strip server-only and mock server-only packages, then recursively process imports
1709
+ let transitiveContent = stripServerOnlyImport(importFile.content);
1710
+ transitiveContent = applyServerOnlyMocks(transitiveContent);
1711
+ debugLog(`processTransitiveImportsRecursively depth=${depth} for ${importFile.path}`);
1712
+ debugLog(`Calling processTransitiveImportsRecursively depth=${depth + 1} for ${importFile.path}`);
1713
+ transitiveContent = await withTimeout(`processTransitiveImportsRecursively depth=${depth} for ${path.basename(importFile.path)}`, processTransitiveImportsRecursively(transitiveContent, importFile.path, transitiveFilePath, visitedPaths, depth + 1, startTime), 30000);
1714
+ debugLog(`withTimeout returned for depth=${depth}, transitiveContent length=${transitiveContent.length}`);
1715
+ debugLog(`Completed processTransitiveImportsRecursively depth=${depth} for ${importFile.path}`);
1716
+ debugLog(`Writing transitive file depth=${depth}`, {
1717
+ transitiveFilePath: path.basename(transitiveFilePath),
1718
+ contentLength: transitiveContent.length,
1719
+ });
1720
+ await writeFile(transitiveFilePath, transitiveContent);
1721
+ debugLog(`Wrote transitive file depth=${depth}`);
1722
+ scenarioComponentPaths.push(transitiveFilePath);
1723
+ if (!writtenScenarioComponents[resolvedPath]) {
1724
+ writtenScenarioComponents[resolvedPath] = [];
1725
+ }
1726
+ writtenScenarioComponents[resolvedPath].push('__transitive_file_written__');
1727
+ }
1728
+ }
1729
+ // ALWAYS rewrite the import to point to the transitive copy
1730
+ // (even for circular imports or already-processed files)
1731
+ debugLog(`Rewriting import path depth=${depth}`, {
1732
+ importPath,
1733
+ resolvedPath,
1734
+ });
1735
+ const relativePath = getRelativePath(targetFilePath, transitiveFilePath);
1736
+ const relativePathWithoutExt = relativePath.replace(/\.(ts|tsx|js|jsx)$/, '');
1737
+ const safeRelativePath = safeFolder(relativePathWithoutExt);
1738
+ const escapedImportPath = importPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1739
+ debugLog(`Applying regex depth=${depth}`, {
1740
+ escapedImportPath,
1741
+ contentLength: modifiedContent.length,
1742
+ });
1743
+ // Quick check if the import path even exists in content
1744
+ const simpleCheck = modifiedContent.includes(importPath);
1745
+ debugLog(`Simple check: importPath "${importPath}" exists: ${simpleCheck}`);
1746
+ if (!simpleCheck) {
1747
+ debugLog(`Skipping regex - import path not found in content`);
1748
+ }
1749
+ else {
1750
+ const regexPattern = `(from\\s*["'])${escapedImportPath}(["'])`;
1751
+ debugLog(`Regex pattern: ${regexPattern.slice(0, 100)}`);
1752
+ const importRegex = new RegExp(regexPattern, 'g');
1753
+ debugLog(`About to call replace...`);
1754
+ // Timing for regex replace to detect slow operations
1755
+ const replaceStart = Date.now();
1756
+ modifiedContent = modifiedContent.replace(importRegex, `$1${safeRelativePath}$2`);
1757
+ const replaceTime = Date.now() - replaceStart;
1758
+ if (replaceTime > 100) {
1759
+ console.warn(`[WriteScenario] SLOW regex replace: ${replaceTime}ms for pattern ${regexPattern.slice(0, 50)} on ${modifiedContent.length} bytes`);
1760
+ }
1761
+ debugLog(`Regex applied depth=${depth} in ${replaceTime}ms`);
1762
+ }
1763
+ debugLog(`[LOOP END] depth=${depth} import ${importIndex} completed`);
1764
+ }
1765
+ debugLog(`[LOOP DONE] Exiting import loop at depth=${depth}`);
1766
+ debugLog(`Returning from processTransitiveImportsRecursively depth=${depth}`);
1767
+ return modifiedContent;
1768
+ }
1769
+ // Process remaining internal imports that weren't in importedExports
1770
+ // This handles transitive dependencies: when the file content includes code (e.g., from
1771
+ // other functions in the same file) that imports from files with "server-only"
1772
+ debugLog('Extracting remaining import paths');
1773
+ const remainingImportPaths = extractInternalImportPaths(fileContent);
1774
+ debugLog('Found remaining import paths', {
1775
+ count: remainingImportPaths.length,
1776
+ });
1777
+ // Get all file paths that are in importedExports - these are handled by main processing
1778
+ const importedExportFilePaths = new Set(allImportedExports.map((ie) => ie.resolvedFilePath || ie.filePath));
1779
+ debugLog('Starting remaining imports loop', {
1780
+ remainingCount: remainingImportPaths.length,
1781
+ importedExportCount: importedExportFilePaths.size,
1782
+ });
1783
+ let remainingImportIndex = 0;
1784
+ debugLog(`[REMAINING] Starting remaining imports loop, ${remainingImportPaths.length} imports`);
1785
+ for (const importPath of remainingImportPaths) {
1786
+ remainingImportIndex++;
1787
+ debugLog(`[REMAINING LOOP] import ${remainingImportIndex}/${remainingImportPaths.length}: ${importPath}`);
1788
+ // Resolve the import path to a project file path
1789
+ const resolvedFilePath = resolveImportPath(importPath, file.path, project);
1790
+ if (!resolvedFilePath) {
1791
+ // Can't resolve - might be a path we don't handle, skip it
1792
+ continue;
1793
+ }
1794
+ // Find the file in project.files, using fileStore for O(1) lookup when available
1795
+ // We need to find the file BEFORE checking importedExports to see if it has server-only
1796
+ let targetFile = fileStore
1797
+ ? fileStore.getByPath(resolvedFilePath)
1798
+ : project.files?.find((f) => f.path === resolvedFilePath);
1799
+ // Skip if this import is in importedExports - it's handled by the main processing loop
1800
+ // UNLESS the file contains "server-only", in which case we still need a transitive copy
1801
+ // with server-only stripped (even if some exports from the file are mocked).
1802
+ if (importedExportFilePaths.has(resolvedFilePath)) {
1803
+ // Check if the file has server-only before skipping
1804
+ let fileContent = targetFile?.content;
1805
+ if (!fileContent && targetFile && fileStore) {
1806
+ // Load content to check for server-only
1807
+ const loadedFile = await fileStore.ensureContent(resolvedFilePath);
1808
+ fileContent = loadedFile?.content;
1809
+ if (loadedFile) {
1810
+ targetFile = loadedFile;
1811
+ }
1812
+ }
1813
+ const hasServerOnly = fileContent && /import\s+["']server-only["']/.test(fileContent);
1814
+ if (!hasServerOnly) {
1815
+ continue;
1816
+ }
1817
+ // File has server-only - continue processing to create transitive copy
1818
+ }
1819
+ if (!targetFile) {
1820
+ continue;
1821
+ }
1822
+ // Compute the transformed file path (needed for import rewriting even if already processed)
1823
+ const targetFileBasePath = safeFolder(targetFile.path.split('/').slice(0, -1).join('/'));
1824
+ const targetFileExtension = targetFile.name.split('.').pop();
1825
+ const targetFileIsIndex = isIndexPath(targetFile.path);
1826
+ const filePathHash = safeFileName(targetFile.path);
1827
+ const transformedFilePath = `${PROJECT_RELATIVE_PATH}/${targetFileBasePath}/${filePathHash}_${targetFileIsIndex ? 'index_' : ''}transitive_${safeFileName(scenario.name)}.${targetFileExtension}`;
1828
+ // Check if we've already processed this file as a transitive copy
1829
+ // Note: __data_file_written__ is for entity-specific scenario files with different naming,
1830
+ // but we still need transitive copies for server-only stripping. Data entity files may
1831
+ // only export specific items, so we need a full transitive copy with all exports.
1832
+ const alreadyTransitive = writtenScenarioComponents[resolvedFilePath]?.includes('__transitive_file_written__');
1833
+ if (!alreadyTransitive) {
1834
+ // Ensure content is loaded (LazyFileStore loads content on-demand)
1835
+ if (!targetFile.content && fileStore) {
1836
+ targetFile = await fileStore.ensureContent(resolvedFilePath);
1837
+ }
1838
+ if (!targetFile?.content) {
1839
+ continue;
1840
+ }
1841
+ // Get the file content and apply transformations
1842
+ let transformedContent = targetFile.content;
1843
+ transformedContent = stripServerOnlyImport(transformedContent);
1844
+ transformedContent = applyServerOnlyMocks(transformedContent);
1845
+ // Recursively process this transitive file's imports
1846
+ // This handles the nested case: service.ts → brevo.ts → constants.ts
1847
+ const nestedImportPaths = extractInternalImportPaths(transformedContent);
1848
+ debugLog(`[NESTED] Processing ${nestedImportPaths.length} nested imports for ${targetFile.path}`);
1849
+ let nestedIndex = 0;
1850
+ for (const nestedImportPath of nestedImportPaths) {
1851
+ nestedIndex++;
1852
+ debugLog(`[NESTED LOOP] import ${nestedIndex}/${nestedImportPaths.length}: ${nestedImportPath}`);
1853
+ const nestedResolvedPath = resolveImportPath(nestedImportPath, targetFile.path, project);
1854
+ if (!nestedResolvedPath)
1855
+ continue;
1856
+ // Get file info for building the transformed path
1857
+ let nestedFile = fileStore
1858
+ ? fileStore.getByPath(nestedResolvedPath)
1859
+ : project.files?.find((f) => f.path === nestedResolvedPath);
1860
+ if (!nestedFile)
1861
+ continue;
1862
+ // Build the transformed path (needed for import rewriting even if already processed)
1863
+ const nestedBasePath = safeFolder(nestedFile.path.split('/').slice(0, -1).join('/'));
1864
+ const nestedExtension = nestedFile.name.split('.').pop();
1865
+ const nestedIsIndex = isIndexPath(nestedFile.path);
1866
+ const nestedPathHash = safeFileName(nestedFile.path);
1867
+ const nestedTransformedPath = `${PROJECT_RELATIVE_PATH}/${nestedBasePath}/${nestedPathHash}_${nestedIsIndex ? 'index_' : ''}transitive_${safeFileName(scenario.name)}.${nestedExtension}`;
1868
+ // Check if already processed as a transitive file (we can rewrite to point to it)
1869
+ // Note: __data_file_written__ is for entity-specific scenario files with different naming,
1870
+ // but we still need transitive copies for server-only stripping in the import chain
1871
+ const nestedAlreadyTransitive = writtenScenarioComponents[nestedResolvedPath]?.includes('__transitive_file_written__');
1872
+ if (!nestedAlreadyTransitive) {
1873
+ // Ensure content is loaded for nested files
1874
+ if (!nestedFile.content && fileStore) {
1875
+ nestedFile = await fileStore.ensureContent(nestedResolvedPath);
1876
+ }
1877
+ if (!nestedFile?.content)
1878
+ continue;
1879
+ // Strip server-only, mock server-only packages, and recursively process imports
1880
+ // This handles chains of any depth: A -> B -> C -> D
1881
+ let nestedContent = stripServerOnlyImport(nestedFile.content);
1882
+ nestedContent = applyServerOnlyMocks(nestedContent);
1883
+ debugLog(`processTransitiveImportsRecursively (nested) for ${nestedFile.path}`);
1884
+ nestedContent = await withTimeout(`processTransitiveImportsRecursively (nested) for ${path.basename(nestedFile.path)}`, processTransitiveImportsRecursively(nestedContent, nestedFile.path, nestedTransformedPath), 30000);
1885
+ debugLog(`Completed processTransitiveImportsRecursively (nested) for ${nestedFile.path}`);
1886
+ await writeFile(nestedTransformedPath, nestedContent);
1887
+ scenarioComponentPaths.push(nestedTransformedPath);
1888
+ // Mark as written
1889
+ if (!writtenScenarioComponents[nestedResolvedPath]) {
1890
+ writtenScenarioComponents[nestedResolvedPath] = [];
1891
+ }
1892
+ writtenScenarioComponents[nestedResolvedPath].push('__transitive_file_written__');
1893
+ }
1894
+ // Rewrite the import to point to the transitive copy
1895
+ const nestedRelativePath = getRelativePath(transformedFilePath, nestedTransformedPath);
1896
+ // Strip the extension before applying safeFolder - import paths in TypeScript
1897
+ // should NOT include extensions (Next.js resolves .ts/.tsx automatically).
1898
+ // Without this, safeFolder converts ".ts" to "_ts" causing "Module not found" errors.
1899
+ const nestedRelativePathWithoutExt = nestedRelativePath.replace(/\.(ts|tsx|js|jsx)$/, '');
1900
+ const safeNestedRelativePath = safeFolder(nestedRelativePathWithoutExt);
1901
+ const escapedNestedImportPath = nestedImportPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1902
+ const nestedImportRegex = new RegExp(`(from\\s*["'])${escapedNestedImportPath}(["'])`, 'g');
1903
+ transformedContent = transformedContent.replace(nestedImportRegex, `$1${safeNestedRelativePath}$2`);
1904
+ }
1905
+ // Re-check if file was written during recursive processing
1906
+ // (processTransitiveImportsRecursively might have created this file while processing
1907
+ // a nested import that circularly imports back to this file)
1908
+ const writtenDuringRecursion = writtenScenarioComponents[resolvedFilePath]?.includes('__transitive_file_written__');
1909
+ if (!writtenDuringRecursion) {
1910
+ // Write the transformed file
1911
+ await writeFile(transformedFilePath, transformedContent);
1912
+ scenarioComponentPaths.push(transformedFilePath);
1913
+ // Mark as written
1914
+ if (!writtenScenarioComponents[resolvedFilePath]) {
1915
+ writtenScenarioComponents[resolvedFilePath] = [];
1916
+ }
1917
+ writtenScenarioComponents[resolvedFilePath].push('__transitive_file_written__');
1918
+ }
1919
+ }
1920
+ // ALWAYS rewrite the import in fileContent to point to the transformed file
1921
+ // (even if the transitive copy was already created by another entity)
1922
+ const relativePath = getRelativePath(scenarioComponentPath, transformedFilePath);
1923
+ // Strip the extension before applying safeFolder - import paths in TypeScript
1924
+ // should NOT include extensions (Next.js resolves .ts/.tsx automatically).
1925
+ // Without this, safeFolder converts ".ts" to "_ts" causing "Module not found" errors.
1926
+ const relativePathWithoutExt = relativePath.replace(/\.(ts|tsx|js|jsx)$/, '');
1927
+ const safeRelativePath = safeFolder(relativePathWithoutExt);
1928
+ // Escape special regex characters in the import path
1929
+ const escapedImportPath = importPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1930
+ const importRegex = new RegExp(`(from\\s*["'])${escapedImportPath}(["'])`, 'g');
1931
+ fileContent = fileContent.replace(importRegex, `$1${safeRelativePath}$2`);
1932
+ }
1215
1933
  const scenarioComponentComment = `// This file is auto-generated by CodeYam. Do not edit this file manually.
1216
1934
  // This file contains content for a scenario component:
1217
1935
  // Analyses being written: ${JSON.stringify(fileAnalyses?.map((a) => ({ id: a.id, entityName: a.entityName })))}
@@ -1224,23 +1942,24 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1224
1942
  `;
1225
1943
  // Use the directive that was extracted at the beginning of processing
1226
1944
  // This ensures it stays at the very top even after imports are prepended
1945
+ // NOTE: We only preserve "use client" directives, NOT "use server" directives.
1946
+ // Server action files get mocked with objects that aren't async functions,
1947
+ // which would violate Next.js's "use server" requirement:
1948
+ // "A 'use server' file can only export async functions, found object."
1227
1949
  let finalContent;
1228
- if (extractedDirective) {
1950
+ if (extractedDirective && extractedDirective.includes('client')) {
1229
1951
  finalContent = `${extractedDirective}\n\n${scenarioComponentComment}\n\n${fileContent}`;
1230
- console.log(`CodeYam: Placed "${extractedDirective}" directive at top of file: ${scenarioComponentPath}`);
1231
1952
  }
1232
1953
  else {
1233
1954
  finalContent = `${scenarioComponentComment}\n\n${fileContent}`;
1234
1955
  }
1956
+ debugLog('About to write final scenario file', {
1957
+ scenarioComponentPath,
1958
+ contentLength: finalContent.length,
1959
+ });
1235
1960
  await writeFile(scenarioComponentPath, finalContent);
1961
+ debugLog('Successfully wrote scenario file');
1236
1962
  scenarioComponentPaths.push(scenarioComponentPath);
1237
- console.log('CodeYam [writeScenarioComponents]: Generated scenario files', {
1238
- entityName: entity.name,
1239
- filePath: file.path,
1240
- scenarioName: scenario.name,
1241
- scenarioComponentPathsGenerated: scenarioComponentPaths,
1242
- writtenScenarioComponentKeys: Object.keys(writtenScenarioComponents),
1243
- });
1244
1963
  return { scenarioComponentPaths, writtenScenarioComponents };
1245
1964
  }
1246
1965
  //# sourceMappingURL=writeScenarioComponents.js.map