@codeyam/codeyam-cli 0.1.0-staging.596f0eb → 0.1.0-staging.6e699e5

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 (696) hide show
  1. package/analyzer-template/.build-info.json +8 -8
  2. package/analyzer-template/common/execAsync.ts +1 -1
  3. package/analyzer-template/log.txt +3 -3
  4. package/analyzer-template/package.json +10 -6
  5. package/analyzer-template/packages/ai/index.ts +10 -3
  6. package/analyzer-template/packages/ai/package.json +1 -1
  7. package/analyzer-template/packages/ai/src/lib/__mocks__/completionCall.ts +122 -0
  8. package/analyzer-template/packages/ai/src/lib/analyzeScope.ts +128 -6
  9. package/analyzer-template/packages/ai/src/lib/astScopes/arrayDerivationDetector.ts +199 -0
  10. package/analyzer-template/packages/ai/src/lib/astScopes/astScopeAnalyzer.ts +138 -1
  11. package/analyzer-template/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.ts +644 -0
  12. package/analyzer-template/packages/ai/src/lib/astScopes/methodSemantics.ts +140 -6
  13. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/ifStatementHandler.ts +18 -0
  14. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.ts +38 -1
  15. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.ts +181 -1
  16. package/analyzer-template/packages/ai/src/lib/astScopes/processExpression.ts +1239 -104
  17. package/analyzer-template/packages/ai/src/lib/astScopes/types.ts +304 -0
  18. package/analyzer-template/packages/ai/src/lib/checkAllAttributes.ts +29 -10
  19. package/analyzer-template/packages/ai/src/lib/completionCall.ts +216 -36
  20. package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +1501 -138
  21. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.ts +2 -1
  22. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.ts +976 -0
  23. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.ts +243 -77
  24. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.ts +19 -1
  25. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.ts +103 -6
  26. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.ts +23 -0
  27. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.ts +98 -0
  28. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.ts +42 -2
  29. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.ts +129 -0
  30. package/analyzer-template/packages/ai/src/lib/dataStructureChunking.ts +156 -0
  31. package/analyzer-template/packages/ai/src/lib/deepEqual.ts +30 -0
  32. package/analyzer-template/packages/ai/src/lib/e2eDataTracking.ts +334 -0
  33. package/analyzer-template/packages/ai/src/lib/extractCriticalDataKeys.ts +120 -0
  34. package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarioData.ts +74 -7
  35. package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarios.ts +89 -112
  36. package/analyzer-template/packages/ai/src/lib/generateEntityDataStructure.ts +6 -0
  37. package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +1111 -91
  38. package/analyzer-template/packages/ai/src/lib/generateEntityScenarios.ts +207 -104
  39. package/analyzer-template/packages/ai/src/lib/generateExecutionFlows.ts +570 -0
  40. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.ts +528 -0
  41. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionals.ts +1977 -0
  42. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.ts +239 -0
  43. package/analyzer-template/packages/ai/src/lib/getConditionalUsagesFromCode.ts +143 -31
  44. package/analyzer-template/packages/ai/src/lib/guessScenarioDataFromDescription.ts +8 -2
  45. package/analyzer-template/packages/ai/src/lib/isolateScopes.ts +276 -3
  46. package/analyzer-template/packages/ai/src/lib/mergeStatements.ts +33 -3
  47. package/analyzer-template/packages/ai/src/lib/promptGenerators/gatherAttributesMap.ts +7 -0
  48. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.ts +1 -1
  49. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.ts +32 -102
  50. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChunkPrompt.ts +82 -0
  51. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateCriticalKeysPrompt.ts +103 -0
  52. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.ts +90 -6
  53. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.ts +14 -53
  54. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.ts +58 -0
  55. package/analyzer-template/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.ts +28 -2
  56. package/analyzer-template/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.ts +391 -0
  57. package/analyzer-template/packages/ai/src/lib/resolvePathToControllable.ts +812 -0
  58. package/analyzer-template/packages/ai/src/lib/splitOutsideParentheses.ts +5 -1
  59. package/analyzer-template/packages/ai/src/lib/validateExecutionFlowPaths.ts +531 -0
  60. package/analyzer-template/packages/ai/src/lib/worker/SerializableDataStructure.ts +123 -0
  61. package/analyzer-template/packages/ai/src/lib/worker/analyzeScopeWorker.ts +8 -1
  62. package/analyzer-template/packages/analyze/src/lib/FileAnalyzer.ts +14 -0
  63. package/analyzer-template/packages/analyze/src/lib/analysisContext.ts +44 -4
  64. package/analyzer-template/packages/analyze/src/lib/asts/nodes/index.ts +1 -0
  65. package/analyzer-template/packages/analyze/src/lib/asts/nodes/isAsyncFunction.ts +67 -0
  66. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.ts +455 -267
  67. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +18 -0
  68. package/analyzer-template/packages/analyze/src/lib/files/analyze/findOrCreateEntity.ts +3 -0
  69. package/analyzer-template/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.ts +33 -7
  70. package/analyzer-template/packages/analyze/src/lib/files/analyzeChange.ts +31 -15
  71. package/analyzer-template/packages/analyze/src/lib/files/analyzeEntity.ts +11 -7
  72. package/analyzer-template/packages/analyze/src/lib/files/analyzeInitial.ts +11 -12
  73. package/analyzer-template/packages/analyze/src/lib/files/enums/steps.ts +1 -1
  74. package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.ts +265 -0
  75. package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.ts +102 -0
  76. package/analyzer-template/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.ts +588 -52
  77. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.ts +1 -1
  78. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.ts +28 -62
  79. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +336 -133
  80. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.ts +156 -0
  81. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarioData.ts +78 -83
  82. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarios.ts +4 -8
  83. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +461 -94
  84. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.ts +56 -11
  85. package/analyzer-template/packages/aws/codebuild/index.ts +1 -0
  86. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.d.ts +11 -1
  87. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.d.ts.map +1 -1
  88. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.js +29 -18
  89. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.js.map +1 -1
  90. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.d.ts +2 -2
  91. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.d.ts.map +1 -1
  92. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.js +2 -2
  93. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.js.map +1 -1
  94. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.d.ts +8 -18
  95. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.d.ts.map +1 -1
  96. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.js +17 -61
  97. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.js.map +1 -1
  98. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.d.ts +15 -0
  99. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.d.ts.map +1 -0
  100. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.js +31 -0
  101. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.js.map +1 -0
  102. package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.d.ts.map +1 -1
  103. package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.js +8 -1
  104. package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.js.map +1 -1
  105. package/analyzer-template/packages/aws/package.json +3 -3
  106. package/analyzer-template/packages/aws/s3/index.ts +1 -0
  107. package/analyzer-template/packages/aws/src/lib/codebuild/waitForBuild.ts +43 -19
  108. package/analyzer-template/packages/aws/src/lib/ecs/ecsDefineContainer.ts +3 -3
  109. package/analyzer-template/packages/aws/src/lib/ecs/ecsTaskFactory.ts +17 -69
  110. package/analyzer-template/packages/aws/src/lib/s3/checkS3ObjectExists.ts +47 -0
  111. package/analyzer-template/packages/aws/src/lib/s3/uploadFileToS3.ts +8 -1
  112. package/analyzer-template/packages/database/src/lib/kysely/db.ts +4 -4
  113. package/analyzer-template/packages/database/src/lib/kysely/tableRelations.ts +2 -2
  114. package/analyzer-template/packages/database/src/lib/kysely/tables/debugReportsTable.ts +36 -9
  115. package/analyzer-template/packages/database/src/lib/loadReadyToBeCapturedAnalyses.ts +7 -3
  116. package/analyzer-template/packages/generate/index.ts +3 -0
  117. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.ts +17 -1
  118. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.ts +193 -0
  119. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.ts +73 -0
  120. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.ts +9 -4
  121. package/analyzer-template/packages/generate/src/lib/deepMerge.ts +26 -1
  122. package/analyzer-template/packages/generate/src/lib/scenarioComponentForServer.ts +114 -0
  123. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts +2 -2
  124. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js +2 -2
  125. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tableRelations.d.ts +2 -2
  126. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts +1 -11
  127. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts.map +1 -1
  128. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts +30 -7
  129. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts.map +1 -1
  130. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.js +9 -3
  131. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.js.map +1 -1
  132. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entitiesTable.d.ts +1 -0
  133. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entitiesTable.d.ts.map +1 -1
  134. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts +2 -6
  135. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts.map +1 -1
  136. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.d.ts.map +1 -1
  137. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js +7 -4
  138. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
  139. package/analyzer-template/packages/github/dist/generate/index.d.ts +3 -0
  140. package/analyzer-template/packages/github/dist/generate/index.d.ts.map +1 -1
  141. package/analyzer-template/packages/github/dist/generate/index.js +3 -0
  142. package/analyzer-template/packages/github/dist/generate/index.js.map +1 -1
  143. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.d.ts.map +1 -1
  144. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +16 -1
  145. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
  146. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.d.ts +9 -0
  147. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.d.ts.map +1 -0
  148. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +189 -0
  149. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -0
  150. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.d.ts +20 -0
  151. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.d.ts.map +1 -0
  152. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js +53 -0
  153. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js.map +1 -0
  154. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.d.ts.map +1 -1
  155. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +8 -4
  156. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
  157. package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.d.ts.map +1 -1
  158. package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.js +27 -1
  159. package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.js.map +1 -1
  160. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.d.ts +8 -0
  161. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.d.ts.map +1 -0
  162. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.js +89 -0
  163. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.js.map +1 -0
  164. package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.d.ts.map +1 -1
  165. package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.js +10 -0
  166. package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.js.map +1 -1
  167. package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.d.ts.map +1 -1
  168. package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.js +3 -0
  169. package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.js.map +1 -1
  170. package/analyzer-template/packages/github/dist/types/index.d.ts +2 -2
  171. package/analyzer-template/packages/github/dist/types/index.d.ts.map +1 -1
  172. package/analyzer-template/packages/github/dist/types/index.js.map +1 -1
  173. package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts +87 -13
  174. package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts.map +1 -1
  175. package/analyzer-template/packages/github/dist/types/src/types/Entity.d.ts +2 -0
  176. package/analyzer-template/packages/github/dist/types/src/types/Entity.d.ts.map +1 -1
  177. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts +11 -6
  178. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts.map +1 -1
  179. package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts +196 -0
  180. package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
  181. package/analyzer-template/packages/github/dist/types/src/types/StatementInfo.d.ts +2 -0
  182. package/analyzer-template/packages/github/dist/types/src/types/StatementInfo.d.ts.map +1 -1
  183. package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.d.ts.map +1 -1
  184. package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.js +25 -0
  185. package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
  186. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.d.ts +9 -1
  187. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.d.ts.map +1 -1
  188. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.js +29 -3
  189. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.js.map +1 -1
  190. package/analyzer-template/packages/github/src/lib/loadOrCreateCommit.ts +14 -0
  191. package/analyzer-template/packages/github/src/lib/syncPrimaryBranch.ts +2 -0
  192. package/analyzer-template/packages/process/index.ts +2 -0
  193. package/analyzer-template/packages/process/package.json +12 -0
  194. package/analyzer-template/packages/process/tsconfig.json +8 -0
  195. package/analyzer-template/packages/types/index.ts +5 -0
  196. package/analyzer-template/packages/types/src/types/Analysis.ts +104 -13
  197. package/analyzer-template/packages/types/src/types/Entity.ts +2 -0
  198. package/analyzer-template/packages/types/src/types/Scenario.ts +11 -10
  199. package/analyzer-template/packages/types/src/types/ScenariosDataStructure.ts +224 -0
  200. package/analyzer-template/packages/types/src/types/StatementInfo.ts +2 -0
  201. package/analyzer-template/packages/ui-components/src/components/ScenarioDetailInteractiveView.tsx +23 -7
  202. package/analyzer-template/packages/utils/dist/types/index.d.ts +2 -2
  203. package/analyzer-template/packages/utils/dist/types/index.d.ts.map +1 -1
  204. package/analyzer-template/packages/utils/dist/types/index.js.map +1 -1
  205. package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts +87 -13
  206. package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts.map +1 -1
  207. package/analyzer-template/packages/utils/dist/types/src/types/Entity.d.ts +2 -0
  208. package/analyzer-template/packages/utils/dist/types/src/types/Entity.d.ts.map +1 -1
  209. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts +11 -6
  210. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts.map +1 -1
  211. package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts +196 -0
  212. package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
  213. package/analyzer-template/packages/utils/dist/types/src/types/StatementInfo.d.ts +2 -0
  214. package/analyzer-template/packages/utils/dist/types/src/types/StatementInfo.d.ts.map +1 -1
  215. package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.d.ts.map +1 -1
  216. package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.js +25 -0
  217. package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
  218. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.d.ts +9 -1
  219. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.d.ts.map +1 -1
  220. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.js +29 -3
  221. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.js.map +1 -1
  222. package/analyzer-template/packages/utils/src/lib/lightweightEntityExtractor.ts +27 -0
  223. package/analyzer-template/packages/utils/src/lib/safeFileName.ts +48 -3
  224. package/analyzer-template/playwright/capture.ts +37 -18
  225. package/analyzer-template/playwright/getCodeYamInfo.ts +12 -7
  226. package/analyzer-template/playwright/takeElementScreenshot.ts +26 -11
  227. package/analyzer-template/playwright/takeScreenshot.ts +9 -7
  228. package/analyzer-template/playwright/waitForServer.ts +21 -6
  229. package/analyzer-template/project/analyzeBaselineCommit.ts +4 -0
  230. package/analyzer-template/project/analyzeBranchCommit.ts +4 -0
  231. package/analyzer-template/project/analyzeFileEntities.ts +4 -0
  232. package/analyzer-template/project/analyzeRegularCommit.ts +4 -0
  233. package/analyzer-template/project/constructMockCode.ts +1181 -160
  234. package/analyzer-template/project/controller/startController.ts +16 -1
  235. package/analyzer-template/project/executeLibraryFunctionDirect.ts +7 -3
  236. package/analyzer-template/project/mocks/analyzeFileMock.ts +8 -7
  237. package/analyzer-template/project/orchestrateCapture/KyselyAnalysisLoader.ts +3 -6
  238. package/analyzer-template/project/orchestrateCapture/SequentialCaptureTaskRunner.ts +82 -36
  239. package/analyzer-template/project/orchestrateCapture.ts +36 -3
  240. package/analyzer-template/project/reconcileMockDataKeys.ts +245 -2
  241. package/analyzer-template/project/runAnalysis.ts +11 -0
  242. package/analyzer-template/project/runMultiScenarioServer.ts +11 -10
  243. package/analyzer-template/project/serverOnlyModules.ts +194 -21
  244. package/analyzer-template/project/start.ts +26 -4
  245. package/analyzer-template/project/startScenarioCapture.ts +79 -41
  246. package/analyzer-template/project/writeMockDataTsx.ts +232 -57
  247. package/analyzer-template/project/writeScenarioClientWrapper.ts +21 -0
  248. package/analyzer-template/project/writeScenarioComponents.ts +769 -181
  249. package/analyzer-template/project/writeScenarioFiles.ts +26 -0
  250. package/analyzer-template/project/writeSimpleRoot.ts +13 -15
  251. package/analyzer-template/scripts/comboWorkerLoop.cjs +1 -0
  252. package/analyzer-template/scripts/defaultCmd.sh +9 -0
  253. package/analyzer-template/tsconfig.json +2 -1
  254. package/background/src/lib/local/createLocalAnalyzer.js +1 -29
  255. package/background/src/lib/local/createLocalAnalyzer.js.map +1 -1
  256. package/background/src/lib/local/execAsync.js +1 -1
  257. package/background/src/lib/local/execAsync.js.map +1 -1
  258. package/background/src/lib/virtualized/common/execAsync.js +1 -1
  259. package/background/src/lib/virtualized/common/execAsync.js.map +1 -1
  260. package/background/src/lib/virtualized/project/analyzeBaselineCommit.js +2 -1
  261. package/background/src/lib/virtualized/project/analyzeBaselineCommit.js.map +1 -1
  262. package/background/src/lib/virtualized/project/analyzeBranchCommit.js +2 -1
  263. package/background/src/lib/virtualized/project/analyzeBranchCommit.js.map +1 -1
  264. package/background/src/lib/virtualized/project/analyzeFileEntities.js +2 -1
  265. package/background/src/lib/virtualized/project/analyzeFileEntities.js.map +1 -1
  266. package/background/src/lib/virtualized/project/analyzeRegularCommit.js +2 -1
  267. package/background/src/lib/virtualized/project/analyzeRegularCommit.js.map +1 -1
  268. package/background/src/lib/virtualized/project/constructMockCode.js +1053 -124
  269. package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
  270. package/background/src/lib/virtualized/project/controller/startController.js +11 -1
  271. package/background/src/lib/virtualized/project/controller/startController.js.map +1 -1
  272. package/background/src/lib/virtualized/project/executeLibraryFunctionDirect.js +6 -3
  273. package/background/src/lib/virtualized/project/executeLibraryFunctionDirect.js.map +1 -1
  274. package/background/src/lib/virtualized/project/mocks/analyzeFileMock.js +7 -7
  275. package/background/src/lib/virtualized/project/mocks/analyzeFileMock.js.map +1 -1
  276. package/background/src/lib/virtualized/project/orchestrateCapture/KyselyAnalysisLoader.js +3 -2
  277. package/background/src/lib/virtualized/project/orchestrateCapture/KyselyAnalysisLoader.js.map +1 -1
  278. package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js +69 -32
  279. package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js.map +1 -1
  280. package/background/src/lib/virtualized/project/orchestrateCapture.js +27 -4
  281. package/background/src/lib/virtualized/project/orchestrateCapture.js.map +1 -1
  282. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js +204 -2
  283. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js.map +1 -1
  284. package/background/src/lib/virtualized/project/runAnalysis.js +9 -0
  285. package/background/src/lib/virtualized/project/runAnalysis.js.map +1 -1
  286. package/background/src/lib/virtualized/project/runMultiScenarioServer.js +11 -9
  287. package/background/src/lib/virtualized/project/runMultiScenarioServer.js.map +1 -1
  288. package/background/src/lib/virtualized/project/serverOnlyModules.js +163 -23
  289. package/background/src/lib/virtualized/project/serverOnlyModules.js.map +1 -1
  290. package/background/src/lib/virtualized/project/start.js +21 -4
  291. package/background/src/lib/virtualized/project/start.js.map +1 -1
  292. package/background/src/lib/virtualized/project/startScenarioCapture.js +61 -31
  293. package/background/src/lib/virtualized/project/startScenarioCapture.js.map +1 -1
  294. package/background/src/lib/virtualized/project/writeMockDataTsx.js +199 -50
  295. package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
  296. package/background/src/lib/virtualized/project/writeScenarioClientWrapper.js +15 -0
  297. package/background/src/lib/virtualized/project/writeScenarioClientWrapper.js.map +1 -0
  298. package/background/src/lib/virtualized/project/writeScenarioComponents.js +552 -125
  299. package/background/src/lib/virtualized/project/writeScenarioComponents.js.map +1 -1
  300. package/background/src/lib/virtualized/project/writeScenarioFiles.js +19 -0
  301. package/background/src/lib/virtualized/project/writeScenarioFiles.js.map +1 -1
  302. package/background/src/lib/virtualized/project/writeSimpleRoot.js +13 -13
  303. package/background/src/lib/virtualized/project/writeSimpleRoot.js.map +1 -1
  304. package/codeyam-cli/src/cli.js +7 -1
  305. package/codeyam-cli/src/cli.js.map +1 -1
  306. package/codeyam-cli/src/commands/analyze.js +1 -1
  307. package/codeyam-cli/src/commands/analyze.js.map +1 -1
  308. package/codeyam-cli/src/commands/baseline.js +174 -0
  309. package/codeyam-cli/src/commands/baseline.js.map +1 -0
  310. package/codeyam-cli/src/commands/debug.js +40 -18
  311. package/codeyam-cli/src/commands/debug.js.map +1 -1
  312. package/codeyam-cli/src/commands/default.js +0 -15
  313. package/codeyam-cli/src/commands/default.js.map +1 -1
  314. package/codeyam-cli/src/commands/recapture.js +226 -0
  315. package/codeyam-cli/src/commands/recapture.js.map +1 -0
  316. package/codeyam-cli/src/commands/report.js +72 -24
  317. package/codeyam-cli/src/commands/report.js.map +1 -1
  318. package/codeyam-cli/src/commands/start.js +8 -12
  319. package/codeyam-cli/src/commands/start.js.map +1 -1
  320. package/codeyam-cli/src/commands/status.js +23 -1
  321. package/codeyam-cli/src/commands/status.js.map +1 -1
  322. package/codeyam-cli/src/commands/test-startup.js +1 -1
  323. package/codeyam-cli/src/commands/test-startup.js.map +1 -1
  324. package/codeyam-cli/src/commands/wipe.js +108 -0
  325. package/codeyam-cli/src/commands/wipe.js.map +1 -0
  326. package/codeyam-cli/src/utils/__tests__/serverVersionStaleness.test.js +81 -0
  327. package/codeyam-cli/src/utils/__tests__/serverVersionStaleness.test.js.map +1 -0
  328. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js +31 -27
  329. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js.map +1 -1
  330. package/codeyam-cli/src/utils/analysisRunner.js +8 -13
  331. package/codeyam-cli/src/utils/analysisRunner.js.map +1 -1
  332. package/codeyam-cli/src/utils/backgroundServer.js +14 -4
  333. package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
  334. package/codeyam-cli/src/utils/database.js +91 -5
  335. package/codeyam-cli/src/utils/database.js.map +1 -1
  336. package/codeyam-cli/src/utils/generateReport.js +253 -106
  337. package/codeyam-cli/src/utils/generateReport.js.map +1 -1
  338. package/codeyam-cli/src/utils/git.js +79 -0
  339. package/codeyam-cli/src/utils/git.js.map +1 -0
  340. package/codeyam-cli/src/utils/install-skills.js +31 -17
  341. package/codeyam-cli/src/utils/install-skills.js.map +1 -1
  342. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js +38 -0
  343. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js.map +1 -1
  344. package/codeyam-cli/src/utils/queue/job.js +245 -16
  345. package/codeyam-cli/src/utils/queue/job.js.map +1 -1
  346. package/codeyam-cli/src/utils/queue/manager.js +25 -7
  347. package/codeyam-cli/src/utils/queue/manager.js.map +1 -1
  348. package/codeyam-cli/src/utils/queue/persistence.js.map +1 -1
  349. package/codeyam-cli/src/utils/serverState.js.map +1 -1
  350. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +7 -5
  351. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
  352. package/codeyam-cli/src/utils/versionInfo.js +25 -19
  353. package/codeyam-cli/src/utils/versionInfo.js.map +1 -1
  354. package/codeyam-cli/src/utils/wipe.js +128 -0
  355. package/codeyam-cli/src/utils/wipe.js.map +1 -0
  356. package/codeyam-cli/src/webserver/app/lib/database.js +98 -1
  357. package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
  358. package/codeyam-cli/src/webserver/app/lib/dbNotifier.js.map +1 -1
  359. package/codeyam-cli/src/webserver/backgroundServer.js +5 -10
  360. package/codeyam-cli/src/webserver/backgroundServer.js.map +1 -1
  361. package/codeyam-cli/src/webserver/bootstrap.js +49 -0
  362. package/codeyam-cli/src/webserver/bootstrap.js.map +1 -0
  363. package/codeyam-cli/src/webserver/build/client/assets/EntityItem-BXhEawa3.js +1 -0
  364. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeBadge-efWKDYMr.js → EntityTypeBadge-DLqD3qNt.js} +1 -1
  365. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-Ba2JVPzP.js +41 -0
  366. package/codeyam-cli/src/webserver/build/client/assets/InlineSpinner-C8lyxW9k.js +34 -0
  367. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-aht4aafF.js +25 -0
  368. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-CVtiBnY5.js +3 -0
  369. package/codeyam-cli/src/webserver/build/client/assets/LoadingDots-B0GLXMsr.js +6 -0
  370. package/codeyam-cli/src/webserver/build/client/assets/LogViewer-xgeCVgSM.js +3 -0
  371. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-D4TZhLuw.js +21 -0
  372. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-DuDvi0jm.js +1 -0
  373. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-DEx02QDa.js +10 -0
  374. package/codeyam-cli/src/webserver/build/client/assets/{TruncatedFilePath-COPstp9J.js → TruncatedFilePath-DyFZkK0l.js} +1 -1
  375. package/codeyam-cli/src/webserver/build/client/assets/_index-BwqWJOgH.js +11 -0
  376. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-DoLIqZX2.js +37 -0
  377. package/codeyam-cli/src/webserver/build/client/assets/api.health-l0sNRNKZ.js +1 -0
  378. package/codeyam-cli/src/webserver/build/client/assets/api.restart-server-l0sNRNKZ.js +1 -0
  379. package/codeyam-cli/src/webserver/build/client/assets/api.rules-l0sNRNKZ.js +1 -0
  380. package/codeyam-cli/src/webserver/build/client/assets/chevron-down-Cx24_aWc.js +6 -0
  381. package/codeyam-cli/src/webserver/build/client/assets/chunk-EPOLDU6W-CXRTFQ3F.js +51 -0
  382. package/codeyam-cli/src/webserver/build/client/assets/circle-check-BOARzkeR.js +6 -0
  383. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-BdhJEx6B.js +21 -0
  384. package/codeyam-cli/src/webserver/build/client/assets/{cy-logo-cli-C1gnJVOL.svg → cy-logo-cli-CCKUIm0S.svg} +2 -2
  385. package/codeyam-cli/src/webserver/build/client/assets/cy-logo-cli-DcX-ZS3p.js +1 -0
  386. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-BRb-0kQl.js +1 -0
  387. package/codeyam-cli/src/webserver/build/client/assets/entity._sha._-C2N4Op8e.js +23 -0
  388. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-DavjRmOY.js +6 -0
  389. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-D1T4TGjf.js +6 -0
  390. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-CTBG2mmz.js +5 -0
  391. package/codeyam-cli/src/webserver/build/client/assets/entry.client-CS2cb_eZ.js +29 -0
  392. package/codeyam-cli/src/webserver/build/client/assets/executionFlowCoverage-BWhdfn70.js +1 -0
  393. package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-DMJ7zii9.js +1 -0
  394. package/codeyam-cli/src/webserver/build/client/assets/files-Cs4MdYtv.js +1 -0
  395. package/codeyam-cli/src/webserver/build/client/assets/git-B4RJRvYB.js +15 -0
  396. package/codeyam-cli/src/webserver/build/client/assets/git-commit-horizontal-CysbcZxi.js +6 -0
  397. package/codeyam-cli/src/webserver/build/client/assets/globals-DMUaGAqV.css +1 -0
  398. package/codeyam-cli/src/webserver/build/client/assets/html2canvas-pro.esm-fmIEn3Bc.js +9 -0
  399. package/codeyam-cli/src/webserver/build/client/assets/index-B1h680n5.js +9 -0
  400. package/codeyam-cli/src/webserver/build/client/assets/index-lzqtyFU8.js +3 -0
  401. package/codeyam-cli/src/webserver/build/client/assets/loader-circle-B7B9V-bu.js +6 -0
  402. package/codeyam-cli/src/webserver/build/client/assets/manifest-f874c610.js +1 -0
  403. package/codeyam-cli/src/webserver/build/client/assets/preload-helper-ckwbz45p.js +1 -0
  404. package/codeyam-cli/src/webserver/build/client/assets/root-Bz5TunQg.js +57 -0
  405. package/codeyam-cli/src/webserver/build/client/assets/rules-hEkvVw2-.js +97 -0
  406. package/codeyam-cli/src/webserver/build/client/assets/scenarioStatus-B_8jpV3e.js +1 -0
  407. package/codeyam-cli/src/webserver/build/client/assets/search-CxXUmBSd.js +6 -0
  408. package/codeyam-cli/src/webserver/build/client/assets/settings-CS5f3WzT.js +1 -0
  409. package/codeyam-cli/src/webserver/build/client/assets/simulations-DwFIBT09.js +1 -0
  410. package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-B6LgvRJg.js +6 -0
  411. package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-C1v1PQzo.js +1 -0
  412. package/codeyam-cli/src/webserver/build/client/assets/{useLastLogLine-3pmpUQB-.js → useLastLogLine-aSv48UbS.js} +1 -1
  413. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-DYxHZQuP.js +1 -0
  414. package/codeyam-cli/src/webserver/build/client/assets/{useToast-DEyawJ8r.js → useToast-mBRpZPiu.js} +1 -1
  415. package/codeyam-cli/src/webserver/build/server/assets/index-967OuJoF.js +1 -0
  416. package/codeyam-cli/src/webserver/build/server/assets/server-build-DRTmerg9.js +257 -0
  417. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  418. package/codeyam-cli/src/webserver/build-info.json +5 -5
  419. package/codeyam-cli/src/webserver/devServer.js +1 -3
  420. package/codeyam-cli/src/webserver/devServer.js.map +1 -1
  421. package/codeyam-cli/src/webserver/server.js +35 -25
  422. package/codeyam-cli/src/webserver/server.js.map +1 -1
  423. package/codeyam-cli/templates/codeyam-power-rules-hook.sh +200 -0
  424. package/codeyam-cli/templates/{codeyam-debug-skill.md → codeyam:debug.md} +48 -4
  425. package/codeyam-cli/templates/codeyam:diagnose.md +650 -0
  426. package/codeyam-cli/templates/codeyam:new-rule.md +13 -0
  427. package/codeyam-cli/templates/codeyam:power-rules.md +447 -0
  428. package/codeyam-cli/templates/{codeyam-setup-skill.md → codeyam:setup.md} +139 -4
  429. package/codeyam-cli/templates/{codeyam-sim-skill.md → codeyam:sim.md} +1 -1
  430. package/codeyam-cli/templates/{codeyam-test-skill.md → codeyam:test.md} +1 -1
  431. package/codeyam-cli/templates/{codeyam-verify-skill.md → codeyam:verify.md} +1 -1
  432. package/package.json +17 -16
  433. package/packages/ai/index.js +5 -4
  434. package/packages/ai/index.js.map +1 -1
  435. package/packages/ai/src/lib/analyzeScope.js +99 -0
  436. package/packages/ai/src/lib/analyzeScope.js.map +1 -1
  437. package/packages/ai/src/lib/astScopes/arrayDerivationDetector.js +150 -0
  438. package/packages/ai/src/lib/astScopes/arrayDerivationDetector.js.map +1 -0
  439. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js +100 -1
  440. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js.map +1 -1
  441. package/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.js +435 -0
  442. package/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.js.map +1 -0
  443. package/packages/ai/src/lib/astScopes/methodSemantics.js +97 -6
  444. package/packages/ai/src/lib/astScopes/methodSemantics.js.map +1 -1
  445. package/packages/ai/src/lib/astScopes/patterns/ifStatementHandler.js +8 -0
  446. package/packages/ai/src/lib/astScopes/patterns/ifStatementHandler.js.map +1 -1
  447. package/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.js +23 -0
  448. package/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.js.map +1 -1
  449. package/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.js +138 -1
  450. package/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.js.map +1 -1
  451. package/packages/ai/src/lib/astScopes/processExpression.js +945 -87
  452. package/packages/ai/src/lib/astScopes/processExpression.js.map +1 -1
  453. package/packages/ai/src/lib/checkAllAttributes.js +24 -9
  454. package/packages/ai/src/lib/checkAllAttributes.js.map +1 -1
  455. package/packages/ai/src/lib/completionCall.js +178 -31
  456. package/packages/ai/src/lib/completionCall.js.map +1 -1
  457. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +1198 -82
  458. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
  459. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js +2 -1
  460. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js.map +1 -1
  461. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js +661 -0
  462. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js.map +1 -0
  463. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js +180 -56
  464. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js.map +1 -1
  465. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js +16 -1
  466. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js.map +1 -1
  467. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js +86 -4
  468. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js.map +1 -1
  469. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js +20 -0
  470. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js.map +1 -1
  471. package/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.js +86 -0
  472. package/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.js.map +1 -0
  473. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js +34 -3
  474. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js.map +1 -1
  475. package/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.js +107 -0
  476. package/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.js.map +1 -0
  477. package/packages/ai/src/lib/dataStructureChunking.js +111 -0
  478. package/packages/ai/src/lib/dataStructureChunking.js.map +1 -0
  479. package/packages/ai/src/lib/deepEqual.js +32 -0
  480. package/packages/ai/src/lib/deepEqual.js.map +1 -0
  481. package/packages/ai/src/lib/e2eDataTracking.js +241 -0
  482. package/packages/ai/src/lib/e2eDataTracking.js.map +1 -0
  483. package/packages/ai/src/lib/extractCriticalDataKeys.js +96 -0
  484. package/packages/ai/src/lib/extractCriticalDataKeys.js.map +1 -0
  485. package/packages/ai/src/lib/generateChangesEntityScenarioData.js +62 -5
  486. package/packages/ai/src/lib/generateChangesEntityScenarioData.js.map +1 -1
  487. package/packages/ai/src/lib/generateChangesEntityScenarios.js +81 -90
  488. package/packages/ai/src/lib/generateChangesEntityScenarios.js.map +1 -1
  489. package/packages/ai/src/lib/generateEntityDataStructure.js +5 -0
  490. package/packages/ai/src/lib/generateEntityDataStructure.js.map +1 -1
  491. package/packages/ai/src/lib/generateEntityScenarioData.js +904 -84
  492. package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
  493. package/packages/ai/src/lib/generateEntityScenarios.js +186 -82
  494. package/packages/ai/src/lib/generateEntityScenarios.js.map +1 -1
  495. package/packages/ai/src/lib/generateExecutionFlows.js +392 -0
  496. package/packages/ai/src/lib/generateExecutionFlows.js.map +1 -0
  497. package/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.js +380 -0
  498. package/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.js.map +1 -0
  499. package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js +1440 -0
  500. package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js.map +1 -0
  501. package/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.js +194 -0
  502. package/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.js.map +1 -0
  503. package/packages/ai/src/lib/getConditionalUsagesFromCode.js +84 -14
  504. package/packages/ai/src/lib/getConditionalUsagesFromCode.js.map +1 -1
  505. package/packages/ai/src/lib/guessScenarioDataFromDescription.js +2 -1
  506. package/packages/ai/src/lib/guessScenarioDataFromDescription.js.map +1 -1
  507. package/packages/ai/src/lib/isolateScopes.js +231 -4
  508. package/packages/ai/src/lib/isolateScopes.js.map +1 -1
  509. package/packages/ai/src/lib/mergeStatements.js +26 -3
  510. package/packages/ai/src/lib/mergeStatements.js.map +1 -1
  511. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js +6 -0
  512. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js.map +1 -1
  513. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js +1 -1
  514. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js.map +1 -1
  515. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js +21 -64
  516. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js.map +1 -1
  517. package/packages/ai/src/lib/promptGenerators/generateChunkPrompt.js +54 -0
  518. package/packages/ai/src/lib/promptGenerators/generateChunkPrompt.js.map +1 -0
  519. package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js +68 -6
  520. package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js.map +1 -1
  521. package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js +10 -34
  522. package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js.map +1 -1
  523. package/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.js +45 -0
  524. package/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.js.map +1 -0
  525. package/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.js +16 -3
  526. package/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.js.map +1 -1
  527. package/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.js +335 -0
  528. package/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.js.map +1 -0
  529. package/packages/ai/src/lib/resolvePathToControllable.js +667 -0
  530. package/packages/ai/src/lib/resolvePathToControllable.js.map +1 -0
  531. package/packages/ai/src/lib/splitOutsideParentheses.js +3 -1
  532. package/packages/ai/src/lib/splitOutsideParentheses.js.map +1 -1
  533. package/packages/ai/src/lib/worker/SerializableDataStructure.js +29 -0
  534. package/packages/ai/src/lib/worker/SerializableDataStructure.js.map +1 -1
  535. package/packages/ai/src/lib/worker/analyzeScopeWorker.js +4 -0
  536. package/packages/ai/src/lib/worker/analyzeScopeWorker.js.map +1 -1
  537. package/packages/analyze/src/lib/FileAnalyzer.js +15 -0
  538. package/packages/analyze/src/lib/FileAnalyzer.js.map +1 -1
  539. package/packages/analyze/src/lib/analysisContext.js +30 -5
  540. package/packages/analyze/src/lib/analysisContext.js.map +1 -1
  541. package/packages/analyze/src/lib/asts/nodes/index.js +1 -0
  542. package/packages/analyze/src/lib/asts/nodes/index.js.map +1 -1
  543. package/packages/analyze/src/lib/asts/nodes/isAsyncFunction.js +52 -0
  544. package/packages/analyze/src/lib/asts/nodes/isAsyncFunction.js.map +1 -0
  545. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +218 -50
  546. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
  547. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +10 -0
  548. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
  549. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js +2 -0
  550. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js.map +1 -1
  551. package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js +31 -7
  552. package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js.map +1 -1
  553. package/packages/analyze/src/lib/files/analyzeChange.js +21 -11
  554. package/packages/analyze/src/lib/files/analyzeChange.js.map +1 -1
  555. package/packages/analyze/src/lib/files/analyzeEntity.js +9 -8
  556. package/packages/analyze/src/lib/files/analyzeEntity.js.map +1 -1
  557. package/packages/analyze/src/lib/files/analyzeInitial.js +9 -10
  558. package/packages/analyze/src/lib/files/analyzeInitial.js.map +1 -1
  559. package/packages/analyze/src/lib/files/enums/steps.js +1 -1
  560. package/packages/analyze/src/lib/files/enums/steps.js.map +1 -1
  561. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js +209 -0
  562. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js.map +1 -0
  563. package/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.js +85 -0
  564. package/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.js.map +1 -0
  565. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js +458 -48
  566. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js.map +1 -1
  567. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.js +1 -1
  568. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.js.map +1 -1
  569. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.js +29 -34
  570. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.js.map +1 -1
  571. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +264 -78
  572. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
  573. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js +96 -0
  574. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js.map +1 -0
  575. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js +56 -69
  576. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js.map +1 -1
  577. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js +4 -8
  578. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js.map +1 -1
  579. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +372 -89
  580. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
  581. package/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.js +46 -9
  582. package/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.js.map +1 -1
  583. package/packages/aws/src/lib/ecs/ecsDefineContainer.js +2 -2
  584. package/packages/aws/src/lib/ecs/ecsDefineContainer.js.map +1 -1
  585. package/packages/aws/src/lib/ecs/ecsTaskFactory.js +17 -61
  586. package/packages/aws/src/lib/ecs/ecsTaskFactory.js.map +1 -1
  587. package/packages/database/src/lib/kysely/db.js +2 -2
  588. package/packages/database/src/lib/kysely/tables/debugReportsTable.js +9 -3
  589. package/packages/database/src/lib/kysely/tables/debugReportsTable.js.map +1 -1
  590. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js +7 -4
  591. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
  592. package/packages/generate/index.js +3 -0
  593. package/packages/generate/index.js.map +1 -1
  594. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +16 -1
  595. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
  596. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +189 -0
  597. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -0
  598. package/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js +53 -0
  599. package/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js.map +1 -0
  600. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +8 -4
  601. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
  602. package/packages/generate/src/lib/deepMerge.js +27 -1
  603. package/packages/generate/src/lib/deepMerge.js.map +1 -1
  604. package/packages/generate/src/lib/scenarioComponentForServer.js +89 -0
  605. package/packages/generate/src/lib/scenarioComponentForServer.js.map +1 -0
  606. package/packages/github/src/lib/loadOrCreateCommit.js +10 -0
  607. package/packages/github/src/lib/loadOrCreateCommit.js.map +1 -1
  608. package/packages/github/src/lib/syncPrimaryBranch.js +3 -0
  609. package/packages/github/src/lib/syncPrimaryBranch.js.map +1 -1
  610. package/packages/process/index.js +3 -0
  611. package/packages/process/index.js.map +1 -0
  612. package/packages/process/src/GlobalProcessManager.js.map +1 -0
  613. package/{background/src/lib/process → packages/process/src}/ProcessManager.js +1 -1
  614. package/packages/process/src/ProcessManager.js.map +1 -0
  615. package/packages/process/src/index.js.map +1 -0
  616. package/packages/process/src/managedExecAsync.js.map +1 -0
  617. package/packages/types/index.js.map +1 -1
  618. package/packages/utils/src/lib/lightweightEntityExtractor.js +25 -0
  619. package/packages/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
  620. package/packages/utils/src/lib/safeFileName.js +29 -3
  621. package/packages/utils/src/lib/safeFileName.js.map +1 -1
  622. package/scripts/finalize-analyzer.cjs +6 -4
  623. package/analyzer-template/packages/ai/src/lib/findMatchingAttribute.ts +0 -102
  624. package/analyzer-template/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.ts +0 -197
  625. package/analyzer-template/packages/ai/src/lib/generateChangesEntityKeyAttributes.ts +0 -271
  626. package/analyzer-template/packages/ai/src/lib/generateEntityKeyAttributes.ts +0 -294
  627. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.ts +0 -67
  628. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.ts +0 -115
  629. package/analyzer-template/process/INTEGRATION_COMPLETE.md +0 -333
  630. package/analyzer-template/process/INTEGRATION_EXAMPLE.md +0 -525
  631. package/analyzer-template/process/README.md +0 -507
  632. package/background/src/lib/process/GlobalProcessManager.js.map +0 -1
  633. package/background/src/lib/process/ProcessManager.js.map +0 -1
  634. package/background/src/lib/process/index.js.map +0 -1
  635. package/background/src/lib/process/managedExecAsync.js.map +0 -1
  636. package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js +0 -238
  637. package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js.map +0 -1
  638. package/codeyam-cli/src/webserver/build/client/assets/EntityItem-CVbSvOjo.js +0 -1
  639. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-DcwcHyl5.js +0 -1
  640. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-WgwC1GfJ.js +0 -26
  641. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-IEKom9O2.js +0 -3
  642. package/codeyam-cli/src/webserver/build/client/assets/LogViewer-BYnfxbUG.js +0 -3
  643. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-_lBPJCzG.js +0 -1
  644. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-lHVhvsu_.js +0 -1
  645. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-d_TBk4GQ.js +0 -5
  646. package/codeyam-cli/src/webserver/build/client/assets/_index-kGT7VUqj.js +0 -1
  647. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-DDGmhu7P.js +0 -7
  648. package/codeyam-cli/src/webserver/build/client/assets/chevron-down-n_HPRfM_.js +0 -1
  649. package/codeyam-cli/src/webserver/build/client/assets/chunk-WWGJGFF6-CbVoyx1U.js +0 -26
  650. package/codeyam-cli/src/webserver/build/client/assets/circle-check-D1VOYveA.js +0 -1
  651. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-YR8jjAlu.js +0 -1
  652. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-B8vP3V_s.js +0 -1
  653. package/codeyam-cli/src/webserver/build/client/assets/entity._sha._-CN6aLCT1.js +0 -16
  654. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-DA5Jeu2P.js +0 -1
  655. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-BTeitalf.js +0 -5
  656. package/codeyam-cli/src/webserver/build/client/assets/entry.client-du6UEYD-.js +0 -13
  657. package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-BpjkhMoi.js +0 -1
  658. package/codeyam-cli/src/webserver/build/client/assets/files-BQGvk4lJ.js +0 -1
  659. package/codeyam-cli/src/webserver/build/client/assets/git-DVdYRT-I.js +0 -12
  660. package/codeyam-cli/src/webserver/build/client/assets/globals-CO-U8Bpo.css +0 -1
  661. package/codeyam-cli/src/webserver/build/client/assets/html2canvas-pro.esm-XQCGvadH.js +0 -5
  662. package/codeyam-cli/src/webserver/build/client/assets/index-DCG-vks0.js +0 -1
  663. package/codeyam-cli/src/webserver/build/client/assets/loader-circle-GazdNeLl.js +0 -1
  664. package/codeyam-cli/src/webserver/build/client/assets/manifest-0b694d28.js +0 -1
  665. package/codeyam-cli/src/webserver/build/client/assets/root-D3tQP7hx.js +0 -16
  666. package/codeyam-cli/src/webserver/build/client/assets/search-CIY6XmtE.js +0 -1
  667. package/codeyam-cli/src/webserver/build/client/assets/server-build-CMKNK2uU.css +0 -1
  668. package/codeyam-cli/src/webserver/build/client/assets/settings-CoMDgElu.js +0 -1
  669. package/codeyam-cli/src/webserver/build/client/assets/simulations-agkniXp2.js +0 -1
  670. package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-B2VUcygF.js +0 -1
  671. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-EvdK-zXP.js +0 -1
  672. package/codeyam-cli/src/webserver/build/server/assets/index-DGVHQEXD.js +0 -1
  673. package/codeyam-cli/src/webserver/build/server/assets/server-build-CghkTkIL.js +0 -166
  674. package/codeyam-cli/templates/debug-command.md +0 -303
  675. package/packages/ai/src/lib/findMatchingAttribute.js +0 -77
  676. package/packages/ai/src/lib/findMatchingAttribute.js.map +0 -1
  677. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js +0 -136
  678. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js.map +0 -1
  679. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js +0 -220
  680. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js.map +0 -1
  681. package/packages/ai/src/lib/generateEntityKeyAttributes.js +0 -241
  682. package/packages/ai/src/lib/generateEntityKeyAttributes.js.map +0 -1
  683. package/packages/ai/src/lib/isFrontend.js +0 -5
  684. package/packages/ai/src/lib/isFrontend.js.map +0 -1
  685. package/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.js +0 -40
  686. package/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.js.map +0 -1
  687. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js +0 -72
  688. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js.map +0 -1
  689. /package/analyzer-template/{process → packages/process/src}/GlobalProcessManager.ts +0 -0
  690. /package/analyzer-template/{process → packages/process/src}/ProcessManager.ts +0 -0
  691. /package/analyzer-template/{process → packages/process/src}/index.ts +0 -0
  692. /package/analyzer-template/{process → packages/process/src}/managedExecAsync.ts +0 -0
  693. /package/codeyam-cli/src/webserver/build/client/assets/{InteractivePreview-CMKNK2uU.css → styles-CMKNK2uU.css} +0 -0
  694. /package/{background/src/lib/process → packages/process/src}/GlobalProcessManager.js +0 -0
  695. /package/{background/src/lib/process → packages/process/src}/index.js +0 -0
  696. /package/{background/src/lib/process → packages/process/src}/managedExecAsync.js +0 -0
@@ -27,6 +27,67 @@ import ts from 'typescript';
27
27
  import { LazyFileStore } from './LazyFileStore';
28
28
  import { applyServerOnlyMocks } from './serverOnlyModules';
29
29
 
30
+ // Debug timing helper for tracking where time is spent
31
+ const DEBUG_TIMING = process.env.DEBUG_WRITE_SCENARIO === 'true';
32
+ let debugStartTime: number;
33
+ let debugLastTime: number;
34
+
35
+ // Timeout protection to prevent infinite hangs
36
+ const WRITE_SCENARIO_TIMEOUT_MS = parseInt(
37
+ process.env.WRITE_SCENARIO_TIMEOUT_MS || '300000', // Default 5 minutes
38
+ 10,
39
+ );
40
+
41
+ class WriteScenarioTimeoutError extends Error {
42
+ constructor(operation: string, timeoutMs: number) {
43
+ super(
44
+ `WriteScenarioComponents timed out after ${timeoutMs}ms during: ${operation}`,
45
+ );
46
+ this.name = 'WriteScenarioTimeoutError';
47
+ }
48
+ }
49
+
50
+ async function withTimeout<T>(
51
+ operation: string,
52
+ promise: Promise<T>,
53
+ timeoutMs: number = WRITE_SCENARIO_TIMEOUT_MS,
54
+ ): Promise<T> {
55
+ let timeoutId: NodeJS.Timeout | undefined;
56
+
57
+ const timeoutPromise = new Promise<never>((_, reject) => {
58
+ timeoutId = setTimeout(() => {
59
+ reject(new WriteScenarioTimeoutError(operation, timeoutMs));
60
+ }, timeoutMs);
61
+ });
62
+
63
+ try {
64
+ return await Promise.race([promise, timeoutPromise]);
65
+ } finally {
66
+ if (timeoutId) clearTimeout(timeoutId);
67
+ }
68
+ }
69
+
70
+ function debugLog(message: string, extra?: Record<string, unknown>): void {
71
+ if (!DEBUG_TIMING) return;
72
+ const now = Date.now();
73
+ if (!debugStartTime) {
74
+ debugStartTime = now;
75
+ debugLastTime = now;
76
+ }
77
+ const elapsed = now - debugStartTime;
78
+ const delta = now - debugLastTime;
79
+ debugLastTime = now;
80
+ console.log(
81
+ `[WriteScenario +${elapsed}ms Δ${delta}ms] ${message}`,
82
+ extra ? JSON.stringify(extra, null, 2) : '',
83
+ );
84
+ }
85
+
86
+ function resetDebugTiming(): void {
87
+ debugStartTime = 0;
88
+ debugLastTime = 0;
89
+ }
90
+
30
91
  /**
31
92
  * Find the end position of the last import/export-from statement using TypeScript AST.
32
93
  * This is more reliable than regex for handling multiline imports, comments, etc.
@@ -36,11 +97,15 @@ import { applyServerOnlyMocks } from './serverOnlyModules';
36
97
  */
37
98
  function findEndOfImports(content: string): number {
38
99
  try {
100
+ // Use temp.tsx to enable JSX parsing - otherwise TypeScript may misparse
101
+ // JSX content containing the word "import" (e.g., "Entities that import this")
102
+ // as an import statement, causing mock code to be inserted in the wrong location.
39
103
  const sourceFile = ts.createSourceFile(
40
- 'temp.ts',
104
+ 'temp.tsx',
41
105
  content,
42
106
  ts.ScriptTarget.Latest,
43
107
  true,
108
+ ts.ScriptKind.TSX,
44
109
  );
45
110
 
46
111
  let lastImportEnd = 0;
@@ -75,6 +140,125 @@ function escapeRegExp(str: string): string {
75
140
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
76
141
  }
77
142
 
143
+ /**
144
+ * Remove a named import from file content using TypeScript AST.
145
+ * Handles both regular imports (`EntityName`) and type-only imports (`type EntityName`).
146
+ *
147
+ * @param fileContent - The file content to modify
148
+ * @param entityName - The name of the entity to remove from imports
149
+ * @returns The modified file content with the entity removed from imports
150
+ */
151
+ function removeNamedImportAst(fileContent: string, entityName: string): string {
152
+ try {
153
+ const sourceFile = ts.createSourceFile(
154
+ 'temp.tsx',
155
+ fileContent,
156
+ ts.ScriptTarget.Latest,
157
+ true,
158
+ ts.ScriptKind.TSX,
159
+ );
160
+
161
+ const replacements: { start: number; end: number; replacement: string }[] =
162
+ [];
163
+
164
+ for (const statement of sourceFile.statements) {
165
+ if (!ts.isImportDeclaration(statement)) continue;
166
+ if (!statement.importClause?.namedBindings) continue;
167
+ if (!ts.isNamedImports(statement.importClause.namedBindings)) continue;
168
+
169
+ const namedImports = statement.importClause.namedBindings;
170
+ const elements = namedImports.elements;
171
+
172
+ // Find the element that matches our entity name
173
+ const matchingIndex = elements.findIndex(
174
+ (el) => el.name.text === entityName,
175
+ );
176
+ if (matchingIndex === -1) continue;
177
+
178
+ // Check if there's a default import (e.g., `import DefaultName, { NamedImport } from '...'`)
179
+ const hasDefaultImport = !!statement.importClause.name;
180
+
181
+ // If this is the only named import AND there's no default import, remove the entire statement
182
+ if (elements.length === 1 && !hasDefaultImport) {
183
+ // Find the end including any trailing newline
184
+ let end = statement.getEnd();
185
+ const afterStatement = fileContent.slice(end);
186
+ const trailingNewline = afterStatement.match(/^\r?\n/);
187
+ if (trailingNewline) {
188
+ end += trailingNewline[0].length;
189
+ }
190
+ replacements.push({
191
+ start: statement.getStart(sourceFile),
192
+ end,
193
+ replacement: '',
194
+ });
195
+ continue;
196
+ }
197
+
198
+ // Otherwise, rebuild the import without this element
199
+ const remainingElements = elements.filter((_, i) => i !== matchingIndex);
200
+
201
+ // Get the module specifier
202
+ const moduleSpecifier = statement.moduleSpecifier;
203
+ if (!ts.isStringLiteral(moduleSpecifier)) continue;
204
+
205
+ // Preserve import type modifier if present
206
+ const importTypePrefix = statement.importClause.isTypeOnly ? 'type ' : '';
207
+
208
+ // Get the default import name if present
209
+ const defaultImportName = statement.importClause.name?.text;
210
+
211
+ let newImport: string;
212
+
213
+ if (remainingElements.length === 0) {
214
+ // All named imports were removed, but there's a default import to preserve
215
+ // (we only get here when hasDefaultImport is true, because otherwise we'd have
216
+ // removed the whole statement at the elements.length === 1 check above)
217
+ newImport = `import ${defaultImportName} from ${moduleSpecifier.getText(sourceFile)};`;
218
+ } else {
219
+ // Build the new named imports string
220
+ const newNamedImports = remainingElements
221
+ .map((el) => {
222
+ const isTypeOnly = el.isTypeOnly;
223
+ const name = el.name.text;
224
+ const propertyName = el.propertyName?.text;
225
+ if (propertyName) {
226
+ return isTypeOnly
227
+ ? `type ${propertyName} as ${name}`
228
+ : `${propertyName} as ${name}`;
229
+ }
230
+ return isTypeOnly ? `type ${name}` : name;
231
+ })
232
+ .join(', ');
233
+
234
+ // Build the new import statement, preserving default import if present
235
+ const defaultImportPrefix = defaultImportName
236
+ ? `${defaultImportName}, `
237
+ : '';
238
+ newImport = `import ${importTypePrefix}${defaultImportPrefix}{ ${newNamedImports} } from ${moduleSpecifier.getText(sourceFile)};`;
239
+ }
240
+
241
+ replacements.push({
242
+ start: statement.getStart(sourceFile),
243
+ end: statement.getEnd(),
244
+ replacement: newImport,
245
+ });
246
+ }
247
+
248
+ // Apply replacements in reverse order to preserve positions
249
+ let result = fileContent;
250
+ replacements.sort((a, b) => b.start - a.start);
251
+ for (const { start, end, replacement } of replacements) {
252
+ result = result.slice(0, start) + replacement + result.slice(end);
253
+ }
254
+
255
+ return result;
256
+ } catch (error) {
257
+ console.warn('[removeNamedImportAst] Failed to parse file:', error);
258
+ return fileContent; // Return original content on error
259
+ }
260
+ }
261
+
78
262
  /**
79
263
  * Map nested dist paths to src paths.
80
264
  * Some build tools create nested structures like:
@@ -518,27 +702,49 @@ function stripServerOnlyImport(fileContent: string): string {
518
702
  * Excludes node_modules imports (bare specifiers like 'react', '@prisma/client').
519
703
  */
520
704
  function extractInternalImportPaths(fileContent: string): string[] {
705
+ // Always use AST parsing - regex with nested quantifiers can cause catastrophic
706
+ // backtracking that hangs on a single .exec() call (before iteration limits kick in)
707
+ return extractInternalImportPathsAst(fileContent);
708
+ }
709
+
710
+ /**
711
+ * Extract internal import paths using TypeScript AST - more reliable for large files
712
+ */
713
+ function extractInternalImportPathsAst(fileContent: string): string[] {
521
714
  const importPaths: string[] = [];
522
715
 
523
- // Match import statements with their paths
524
- // Handles: import x from "path", import { x } from "path", import * as x from "path"
525
- const importRegex =
526
- /import\s+(?:(?:\{[^}]*\}|\*\s+as\s+\w+|\w+)\s*,?\s*)*\s*from\s*["']([^"']+)["']/g;
527
-
528
- let match;
529
- while ((match = importRegex.exec(fileContent)) !== null) {
530
- const importPath = match[1];
531
-
532
- // Skip node_modules imports (bare specifiers)
533
- // Internal imports start with '.', '@/', '~/' or similar path aliases
534
- if (
535
- importPath.startsWith('.') ||
536
- importPath.startsWith('@/') ||
537
- importPath.startsWith('~/') ||
538
- importPath.startsWith('#')
539
- ) {
540
- importPaths.push(importPath);
716
+ try {
717
+ // Use temp.tsx to enable JSX parsing for consistent handling of JSX files
718
+ const sourceFile = ts.createSourceFile(
719
+ 'temp.tsx',
720
+ fileContent,
721
+ ts.ScriptTarget.Latest,
722
+ true,
723
+ ts.ScriptKind.TSX,
724
+ );
725
+
726
+ for (const statement of sourceFile.statements) {
727
+ if (ts.isImportDeclaration(statement) && statement.moduleSpecifier) {
728
+ const moduleSpecifier = statement.moduleSpecifier;
729
+ if (ts.isStringLiteral(moduleSpecifier)) {
730
+ const importPath = moduleSpecifier.text;
731
+ // Skip node_modules imports (bare specifiers)
732
+ if (
733
+ importPath.startsWith('.') ||
734
+ importPath.startsWith('@/') ||
735
+ importPath.startsWith('~/') ||
736
+ importPath.startsWith('#')
737
+ ) {
738
+ importPaths.push(importPath);
739
+ }
740
+ }
741
+ }
541
742
  }
743
+ } catch (error) {
744
+ console.warn(
745
+ '[extractInternalImportPathsAst] Failed to parse file:',
746
+ error,
747
+ );
542
748
  }
543
749
 
544
750
  return importPaths;
@@ -664,22 +870,72 @@ function addMockToContent(
664
870
 
665
871
  // Check if we have multiple calls with different variable names
666
872
  // This requires generating separate mock functions for each call site
873
+ //
874
+ // IMPORTANT: calls array may contain BOTH base hook calls (e.g., "useFetcher<Type>()")
875
+ // AND method chain usages (e.g., "useFetcher().functionCallReturnValue.submit(...)").
876
+ // We only want to count base hook calls for the length comparison with callVariableNames.
877
+ // A "base call" is one that ends with "()" possibly preceded by a type annotation,
878
+ // without any subsequent method chains like ".functionCallReturnValue" or ".submit(...)".
879
+ const baseHookCalls = importedExport.calls?.filter((call) => {
880
+ // Base hook calls match patterns like:
881
+ // - "useFetcher()"
882
+ // - "useFetcher<Type>()"
883
+ // - "useFetcher<{ complex: Type }>()"
884
+ // They end with "()" and don't have method chains after the call.
885
+ // Method chains contain ".functionCallReturnValue" or have property access after "()".
886
+ return (
887
+ call.endsWith('()') &&
888
+ !call.includes('.functionCallReturnValue') &&
889
+ // Also exclude method chains like "hook().something" or "hook().method()"
890
+ !call.match(/\(\)\.[a-zA-Z]/)
891
+ );
892
+ });
893
+
894
+ // Determine if we can generate unique mock functions for multiple variables.
895
+ // We need:
896
+ // 1. Multiple variable names (callVariableNames.length > 1)
897
+ // 2. Base hook calls to match them (baseHookCalls.length > 0)
898
+ // Note: We use min(baseHookCalls.length, callVariableNames.length) for iteration
899
+ // to handle cases where data might be slightly out of sync (stale entries).
667
900
  const hasMultipleCallsWithVariables =
668
- importedExport.calls &&
669
- importedExport.calls.length > 1 &&
901
+ baseHookCalls &&
902
+ baseHookCalls.length > 1 &&
670
903
  importedExport.callVariableNames &&
671
- importedExport.callVariableNames.length === importedExport.calls.length;
904
+ importedExport.callVariableNames.length > 1 &&
905
+ // Only proceed if we have at least as many base calls as variable names,
906
+ // OR they're close enough (within 1) to handle minor sync issues
907
+ Math.abs(baseHookCalls.length - importedExport.callVariableNames.length) <=
908
+ 1;
672
909
 
673
910
  let mockCode: string | undefined;
674
911
  const variableMockCodes: string[] = [];
675
912
 
676
913
  if (hasMultipleCallsWithVariables) {
677
914
  // Generate separate mock functions for each variable-qualified call
678
- // Track variable name occurrences to disambiguate when same variable is reused
679
- // (mirrors the logic in gatherDataForMocks)
915
+ // Look up canonical keys from dataForMocks and track variable names for function naming
916
+
917
+ // Get all call signature keys for this hook from dataForMocks
918
+ const dataForMocks =
919
+ rootAnalysis.metadata?.scenariosDataStructure?.dataForMocks;
920
+ // Match keys that start with the hook name (e.g., "useFetcher" matches "useFetcher<User>()")
921
+ const callSignatureKeysForHook = dataForMocks
922
+ ? Object.keys(dataForMocks).filter((key) => {
923
+ const hookBaseName = importedExport.name.split(/[<(]/)[0];
924
+ const keyBaseName = key.split(/[<(]/)[0];
925
+ return keyBaseName === hookBaseName;
926
+ })
927
+ : [];
928
+
929
+ // Track variable name occurrences for unique function naming
680
930
  const variableNameCounts: Record<string, number> = {};
681
931
 
682
- for (let i = 0; i < importedExport.calls!.length; i++) {
932
+ // Use the minimum of both array lengths to handle slight mismatches
933
+ // (e.g., stale data from previous analysis runs)
934
+ const iterationLimit = Math.min(
935
+ baseHookCalls!.length,
936
+ importedExport.callVariableNames!.length,
937
+ );
938
+ for (let i = 0; i < iterationLimit; i++) {
683
939
  const variableName = importedExport.callVariableNames![i];
684
940
  if (!variableName) continue;
685
941
 
@@ -687,18 +943,37 @@ function addMockToContent(
687
943
  const occurrence = variableNameCounts[variableName] ?? 0;
688
944
  variableNameCounts[variableName] = occurrence + 1;
689
945
 
690
- // If this is a reused variable name (occurrence > 0), append index
691
- // e.g., "fetcher[1] <- useFetcher" for the second usage of "fetcher"
946
+ // Build indexed variable name for function naming
692
947
  const indexedVariableName =
693
948
  occurrence > 0 ? `${variableName}[${occurrence}]` : variableName;
694
949
 
695
- // Generate mock code for this specific call using variable-qualified name
696
- // Format: "variableName <- functionName" (reads as "variableName receives from functionName")
697
- const qualifiedName = `${indexedVariableName} <- ${importedExport.name}`;
950
+ // Use safe function name with underscores instead of brackets
951
+ // e.g., fetcher[1] -> fetcher_1
952
+ const safeFunctionName = indexedVariableName.replace(/\[(\d+)\]/g, '_$1');
953
+ // Compute unique mock function name for call site replacement
954
+ // e.g., useFetcher_entityDiffFetcher, useFetcher_reportFetcher
955
+ const mockFunctionName = `${importedExport.name}_${safeFunctionName}`;
956
+
957
+ // Use the call signature from baseHookCalls[i] as the data key
958
+ // This matches what's stored in dataForMocks
959
+ const callSignature = baseHookCalls![i];
960
+
961
+ // Generate mock code using the call signature directly
962
+ // This prevents "symbol already declared" errors when multiple calls exist
963
+ // Check if this is a package import that won't have scenario copies
964
+ const isPackageImportForMock = importPath?.startsWith('@');
698
965
  const variableMockCode = constructMockCode(
699
- qualifiedName,
966
+ callSignature, // Use call signature format for data lookup
700
967
  dependencySchemas,
701
968
  importedExport.entityType,
969
+ undefined, // No need for separate canonical key
970
+ {
971
+ uniqueFunctionSuffix: safeFunctionName, // Use variable name for unique function naming
972
+ // For node_modules or package imports, skip spreading from __cyOriginal
973
+ // since those packages/files don't export *__cyOriginal variants
974
+ skipOriginalSpread:
975
+ importedExport.isNodeModule || isPackageImportForMock,
976
+ },
702
977
  );
703
978
 
704
979
  if (variableMockCode) {
@@ -707,8 +982,6 @@ function addMockToContent(
707
982
  // Replace the call site with the variable-specific mock function
708
983
  // e.g., useFetcher<BranchEntityDiffResult>() -> useFetcher_entityDiffFetcher()
709
984
  // e.g., useFetcher() -> useFetcher_reportFetcher()
710
- // For indexed variables: useFetcher() -> useFetcher_fetcher_1()
711
- const callSignature = importedExport.calls![i];
712
985
  // Escape special regex characters in the call signature
713
986
  const escapedCallSignature = callSignature.replace(
714
987
  /[.*+?^${}()|[\]\\]/g,
@@ -719,13 +992,6 @@ function addMockToContent(
719
992
  escapedCallSignature.replace(/\s+/g, '\\s*'),
720
993
  'g',
721
994
  );
722
- // Use safe function name with underscores instead of brackets
723
- // e.g., fetcher[1] -> fetcher_1
724
- const safeFunctionName = indexedVariableName.replace(
725
- /\[(\d+)\]/g,
726
- '_$1',
727
- );
728
- const mockFunctionName = `${importedExport.name}_${safeFunctionName}`;
729
995
  fileContent = fileContent.replace(callRegex, `${mockFunctionName}()`);
730
996
  }
731
997
  }
@@ -741,83 +1007,133 @@ function addMockToContent(
741
1007
  : undefined;
742
1008
 
743
1009
  if (singleCallVariableName) {
744
- // For single variable assignments, use the variable-qualified key for data lookup
745
- // Use constructMockCode to generate proper dispatch functions for nested function calls
746
- // (e.g., useTranslation returns { t } where t() needs to dispatch based on translation key)
747
- const qualifiedKey = `${singleCallVariableName} <- ${importedExport.name}`;
748
- // Keep the original function name since there's only one call - no need for unique names
1010
+ // For single variable assignments, use the call signature directly from dataForMocks
1011
+ const dataForMocks =
1012
+ rootAnalysis.metadata?.scenariosDataStructure?.dataForMocks;
1013
+
1014
+ // Find matching call signature key in dataForMocks
1015
+ const hookBaseName = importedExport.name.split(/[<(]/)[0];
1016
+ const callSignatureKey = dataForMocks
1017
+ ? Object.keys(dataForMocks).find((key) => {
1018
+ // Split on ., <, or ( to get the true base name
1019
+ // This handles both "useFlags()" -> "useFlags" and "trpc.useUtils()" -> "trpc"
1020
+ const keyBaseName = key.split(/[.<(]/)[0];
1021
+ return keyBaseName === hookBaseName;
1022
+ })
1023
+ : undefined;
1024
+
1025
+ // Use the call signature if found, otherwise construct it
1026
+ const dataKey =
1027
+ callSignatureKey ??
1028
+ importedExport.calls?.[0] ??
1029
+ `${importedExport.name}()`;
1030
+
1031
+ // IMPORTANT: If the dataKey is a method chain (e.g., "trpc.useUtils()"), we should
1032
+ // use the base name (e.g., "trpc") when calling constructMockCode. This ensures
1033
+ // constructMockCode generates a complete nested mock from the schema without
1034
+ // referencing __cyOriginal variables.
1035
+ const dataKeyBaseName = dataKey.split(/[.<(]/)[0];
1036
+ const isMethodChainDataKey =
1037
+ dataKeyBaseName === importedExport.name &&
1038
+ dataKey !== importedExport.name &&
1039
+ dataKey.includes('.');
1040
+ const mockNameToUse = isMethodChainDataKey
1041
+ ? importedExport.name
1042
+ : dataKey;
1043
+
1044
+ // Keep the original function name since there's only one call
1045
+ // Check if this is a package import that won't have scenario copies
1046
+ const isPackageImportForSingleCall = importPath?.startsWith('@');
749
1047
  mockCode = constructMockCode(
750
- qualifiedKey,
1048
+ mockNameToUse,
751
1049
  dependencySchemas,
752
1050
  importedExport.entityType,
753
- { keepOriginalFunctionName: true },
1051
+ undefined,
1052
+ {
1053
+ keepOriginalFunctionName: true,
1054
+ // For node_modules or package imports, skip spreading from __cyOriginal
1055
+ // since those packages/files don't export *__cyOriginal variants
1056
+ skipOriginalSpread:
1057
+ importedExport.isNodeModule || isPackageImportForSingleCall,
1058
+ },
754
1059
  );
755
1060
  // If constructMockCode didn't generate code, fall back to simple return
1061
+ // IMPORTANT: We inline scenarios().data() inside the function rather than
1062
+ // storing in a const - see comment in constructMockCode.ts for why.
756
1063
  if (!mockCode) {
757
- mockCode = `const ${importedExport.name}ReturnValue = scenarios().data()?.["${qualifiedKey}"];
758
-
759
- function ${importedExport.name}() {
760
- return ${importedExport.name}ReturnValue;
1064
+ mockCode = `function ${importedExport.name}(...args) {
1065
+ return scenarios().data()?.["${dataKey}"];
761
1066
  }`;
762
1067
  }
763
1068
  } else {
764
- // Check if any analysis (fileAnalyses or rootAnalysis) has this function's data
765
- // under a variable-qualified key. The entity that CALLS the function (e.g., FileTableRow)
766
- // has the dataForMocks with the variable-qualified key, not the root analysis (e.g., GitView).
767
- let variableQualifiedKey: string | undefined;
768
-
769
- // First check fileAnalyses (the analyses for the entity being written)
770
- for (const analysis of fileAnalyses) {
771
- const dataForMocks =
772
- analysis.metadata?.scenariosDataStructure?.dataForMocks;
773
- if (dataForMocks) {
774
- variableQualifiedKey = Object.keys(dataForMocks).find((key) => {
775
- const match = key.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\s*<-\s*(.+)$/);
776
- return match && match[2] === importedExport.name;
777
- });
778
- if (variableQualifiedKey) {
779
- break;
780
- }
781
- }
782
- }
1069
+ // Helper to find matching call signature key from dataForMocks
1070
+ const hookBaseName = importedExport.name.split(/[<(]/)[0];
1071
+ const findMatchingKey = (
1072
+ dataForMocks: Record<string, unknown> | undefined,
1073
+ ): string | undefined => {
1074
+ if (!dataForMocks) return undefined;
1075
+ return Object.keys(dataForMocks).find((key) => {
1076
+ // Split on ., <, or ( to get the true base name
1077
+ // This handles both "useFlags()" -> "useFlags" and "trpc.useUtils()" -> "trpc"
1078
+ const keyBaseName = key.split(/[.<(]/)[0];
1079
+ return keyBaseName === hookBaseName;
1080
+ });
1081
+ };
783
1082
 
784
- // If not found in fileAnalyses, fall back to rootAnalysis
785
- if (!variableQualifiedKey) {
786
- const dataForMocks =
787
- rootAnalysis.metadata?.scenariosDataStructure?.dataForMocks;
788
- if (dataForMocks) {
789
- variableQualifiedKey = Object.keys(dataForMocks).find((key) => {
790
- const match = key.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\s*<-\s*(.+)$/);
791
- return match && match[2] === importedExport.name;
792
- });
1083
+ // Check rootAnalysis FIRST for matching keys.
1084
+ // The mock DATA is generated from rootAnalysis, so the mock CODE must
1085
+ // also use rootAnalysis keys to ensure the lookup succeeds.
1086
+ let dataKey = findMatchingKey(
1087
+ rootAnalysis.metadata?.scenariosDataStructure?.dataForMocks,
1088
+ );
1089
+
1090
+ // If not found in rootAnalysis, fall back to fileAnalyses
1091
+ if (!dataKey) {
1092
+ for (const analysis of fileAnalyses) {
1093
+ dataKey = findMatchingKey(
1094
+ analysis.metadata?.scenariosDataStructure?.dataForMocks,
1095
+ );
1096
+ if (dataKey) break;
793
1097
  }
794
1098
  }
795
1099
 
796
- if (variableQualifiedKey) {
797
- // Use the variable-qualified key found in the analysis
798
- // Use constructMockCode to generate proper dispatch functions for nested function calls
799
- // Keep the original function name since there's only one call - no need for unique names
800
- mockCode = constructMockCode(
801
- variableQualifiedKey,
802
- dependencySchemas,
803
- importedExport.entityType,
804
- { keepOriginalFunctionName: true },
805
- );
806
- // If constructMockCode didn't generate code, fall back to simple return
807
- if (!mockCode) {
808
- mockCode = `const ${importedExport.name}ReturnValue = scenarios().data()?.["${variableQualifiedKey}"];
1100
+ // Use the data key if found, otherwise use call signature or function name.
1101
+ // IMPORTANT: If the dataKey is a method chain (e.g., "trpc.useUtils()"), we should
1102
+ // use the base name (e.g., "trpc") when calling constructMockCode. This ensures
1103
+ // constructMockCode generates a complete nested mock from the schema without
1104
+ // referencing __cyOriginal variables. The __cyOriginal pattern is only needed
1105
+ // for partial mocking where we preserve some original methods, not for complete
1106
+ // method-chain mocks where we provide all implementations.
1107
+ const dataKeyBaseName = dataKey?.split(/[.<(]/)[0];
1108
+ const isMethodChainDataKey =
1109
+ dataKey &&
1110
+ dataKeyBaseName === importedExport.name &&
1111
+ dataKey !== importedExport.name &&
1112
+ dataKey.includes('.');
1113
+ const mockNameToUse = isMethodChainDataKey
1114
+ ? importedExport.name
1115
+ : (dataKey ?? importedExport.calls?.[0] ?? `${importedExport.name}()`);
809
1116
 
810
- function ${importedExport.name}() {
811
- return ${importedExport.name}ReturnValue;
1117
+ mockCode = constructMockCode(
1118
+ mockNameToUse,
1119
+ dependencySchemas,
1120
+ importedExport.entityType,
1121
+ undefined,
1122
+ {
1123
+ keepOriginalFunctionName: true,
1124
+ // For node_modules or package imports, skip spreading from __cyOriginal
1125
+ // since those packages/files don't export *__cyOriginal variants
1126
+ skipOriginalSpread:
1127
+ importedExport.isNodeModule || importPath?.startsWith('@'),
1128
+ },
1129
+ );
1130
+ // If constructMockCode didn't generate code, fall back to simple return
1131
+ // IMPORTANT: We inline scenarios().data() inside the function rather than
1132
+ // storing in a const - see comment in constructMockCode.ts for why.
1133
+ if (!mockCode && dataKey) {
1134
+ mockCode = `function ${importedExport.name}(...args) {
1135
+ return scenarios().data()?.["${dataKey}"];
812
1136
  }`;
813
- }
814
- } else {
815
- // Original behavior for calls without variable names
816
- mockCode = constructMockCode(
817
- importedExport.name,
818
- dependencySchemas,
819
- importedExport.entityType,
820
- );
821
1137
  }
822
1138
  }
823
1139
  }
@@ -848,12 +1164,39 @@ function ${importedExport.name}() {
848
1164
  /[.*+?^${}()|[\]\\]/g,
849
1165
  '\\$&',
850
1166
  );
1167
+ // Use a simpler, more robust regex pattern that matches the fallback path.
1168
+ // Key improvements:
1169
+ // 1. Uses escapeRegExp(firstPart) to handle special characters in function names
1170
+ // 2. Uses word boundaries (\b) to prevent partial matches
1171
+ // 3. Handles comma BEFORE or AFTER the name: (?:,\s*|\s*,)?
1172
+ // 4. Matches specific import path (escapedImportPath)
851
1173
  const importRegExp = new RegExp(
852
- `(import(?:(?!${firstPart}|from|import)[\\s\\S])*?)${firstPart}(?:,\\s*)?((?:(?!import)[\\s\\S])*?from\\s+['"]${escapedImportPath}['"])`,
1174
+ `(import\\s*\\{[^}]*?)\\b${escapeRegExp(firstPart)}\\b(?:,\\s*|\\s*,)?((?:[^}]*\\}\\s*from\\s*['"]${escapedImportPath}['"];?))`,
853
1175
  'm',
854
1176
  );
855
1177
 
856
- if (importedExportNameParts.length > 1) {
1178
+ // Check if any call signature has multiple parts (e.g., "logger.error(error)")
1179
+ // If so, the mock code will spread from __cyOriginal, so we need to rename the import
1180
+ // EXCEPT:
1181
+ // 1. For node_module imports, the __cyOriginal pattern doesn't work because
1182
+ // the original package doesn't export *__cyOriginal variants.
1183
+ // 2. For package imports (starting with @), the __cyOriginal pattern doesn't work
1184
+ // because scenario copies aren't created for package files - they keep the
1185
+ // original import path which doesn't export *__cyOriginal.
1186
+ const anyCallHasMultipleParts = importedExport.calls?.some((call) => {
1187
+ const callParts = splitOutsideParenthesesAndArrays(call);
1188
+ return callParts.length > 1;
1189
+ });
1190
+
1191
+ // Package imports (starting with @) don't get scenario copies, so __cyOriginal won't exist
1192
+ const isPackageImport = importPath.startsWith('@');
1193
+
1194
+ const shouldRenameToOriginal =
1195
+ !importedExport.isNodeModule &&
1196
+ !isPackageImport &&
1197
+ (importedExportNameParts.length > 1 || anyCallHasMultipleParts);
1198
+
1199
+ if (shouldRenameToOriginal) {
857
1200
  fileContent = fileContent.replace(
858
1201
  importRegExp,
859
1202
  `$1${firstPart}__cyOriginal$2`,
@@ -886,7 +1229,20 @@ function ${importedExport.name}() {
886
1229
  'm',
887
1230
  );
888
1231
 
889
- if (importedExportNameParts.length > 1) {
1232
+ // Check if any call signature has multiple parts (e.g., "logger.error(error)")
1233
+ // If so, the mock code will spread from __cyOriginal, so we need to rename the import
1234
+ // EXCEPT: For node_module imports, the __cyOriginal pattern doesn't work because
1235
+ // the original package doesn't export *__cyOriginal variants.
1236
+ const anyCallHasMultipleParts = importedExport.calls?.some((call) => {
1237
+ const callParts = splitOutsideParenthesesAndArrays(call);
1238
+ return callParts.length > 1;
1239
+ });
1240
+
1241
+ const shouldRenameToOriginal =
1242
+ !importedExport.isNodeModule &&
1243
+ (importedExportNameParts.length > 1 || anyCallHasMultipleParts);
1244
+
1245
+ if (shouldRenameToOriginal) {
890
1246
  // Rename the import instead of removing (for destructured access patterns)
891
1247
  fileContent = fileContent.replace(
892
1248
  namedImportRegExp,
@@ -1108,6 +1464,15 @@ export default async function writeScenarioComponents({
1108
1464
  scenarioComponentPaths: string[];
1109
1465
  writtenScenarioComponents: { [key: string]: string[] };
1110
1466
  }> {
1467
+ // Reset debug timing for this invocation
1468
+ resetDebugTiming();
1469
+ debugLog('START writeScenarioComponents', {
1470
+ filePath: file.path,
1471
+ entityName: entity.name,
1472
+ scenarioName: scenario.name,
1473
+ isRootFile: !rootFile || rootFile === file,
1474
+ });
1475
+
1111
1476
  // Capture arguments for testing if debug mode is enabled
1112
1477
  captureArgumentsForTesting({
1113
1478
  project,
@@ -1327,7 +1692,31 @@ export default async function writeScenarioComponents({
1327
1692
  return 0;
1328
1693
  });
1329
1694
 
1695
+ debugLog('Starting main importedExports loop', {
1696
+ count: sortedImportedExports.length,
1697
+ fileContentLength: fileContent.length,
1698
+ });
1699
+
1700
+ let importedExportIndex = 0;
1701
+ const loopStartTime = Date.now();
1702
+ console.log(
1703
+ `[WriteScenario] Starting import loop for ${entity.name}: ${sortedImportedExports.length} imports`,
1704
+ );
1330
1705
  for (const importedExport of sortedImportedExports) {
1706
+ importedExportIndex++;
1707
+ if (importedExportIndex % 5 === 0 || importedExportIndex === 1) {
1708
+ console.log(
1709
+ `[WriteScenario] ${entity.name} import ${importedExportIndex}/${sortedImportedExports.length}: ${importedExport.name} elapsed=${Date.now() - loopStartTime}ms`,
1710
+ );
1711
+ debugLog(
1712
+ `Processing importedExport ${importedExportIndex}/${sortedImportedExports.length}`,
1713
+ {
1714
+ name: importedExport.name,
1715
+ filePath: importedExport.filePath,
1716
+ isMocked: importedExport.isMocked,
1717
+ },
1718
+ );
1719
+ }
1331
1720
  // IMPORTANT: The import mapping keys may be either absolute or relative paths
1332
1721
  // depending on how they were created by the file analyzer. We try multiple formats.
1333
1722
  // Also need to normalize paths to handle /tmp vs /private/tmp on macOS
@@ -1506,28 +1895,49 @@ export default async function writeScenarioComponents({
1506
1895
  importedExport.resolvedIsDefault === true &&
1507
1896
  importedExport.isDefault === false;
1508
1897
 
1898
+ console.log(
1899
+ `[WriteScenario] RECURSE START: ${entity.name} -> ${importedExportEntity.name}`,
1900
+ );
1901
+ const recurseStartTime = Date.now();
1902
+ debugLog(
1903
+ `Recursing into writeScenarioComponents for ${importedExportEntity.name}`,
1904
+ {
1905
+ entityName: importedExportEntity.name,
1906
+ filePath: fileNotMocked.path,
1907
+ },
1908
+ );
1509
1909
  const {
1510
1910
  scenarioComponentPaths: newScenarioComponentPaths,
1511
1911
  writtenScenarioComponents: updatedWrittenScenarioComponents,
1512
- } = await writeScenarioComponents({
1513
- project,
1514
- file: fileNotMocked,
1515
- entity: importedExportEntity,
1516
- rootAnalysis,
1517
- scenario,
1518
- context,
1519
- projectAnalyzer,
1520
- framework,
1521
- mocksDir,
1522
- rootFile,
1523
- namespaceMocks,
1524
- writtenScenarioComponents,
1525
- fileStore,
1526
- // Pass the import name so we can add `export { default as Name };`
1527
- exportAsNamed: needsNamedReExport
1528
- ? importedExport.name
1529
- : undefined,
1530
- });
1912
+ } = await withTimeout(
1913
+ `recursive writeScenarioComponents for ${importedExportEntity.name}`,
1914
+ writeScenarioComponents({
1915
+ project,
1916
+ file: fileNotMocked,
1917
+ entity: importedExportEntity,
1918
+ rootAnalysis,
1919
+ scenario,
1920
+ context,
1921
+ projectAnalyzer,
1922
+ framework,
1923
+ mocksDir,
1924
+ rootFile,
1925
+ namespaceMocks,
1926
+ writtenScenarioComponents,
1927
+ fileStore,
1928
+ // Pass the import name so we can add `export { default as Name };`
1929
+ exportAsNamed: needsNamedReExport
1930
+ ? importedExport.name
1931
+ : undefined,
1932
+ }),
1933
+ 180000, // 3 minute timeout for recursive calls (complex components need more time)
1934
+ );
1935
+ console.log(
1936
+ `[WriteScenario] RECURSE END: ${entity.name} -> ${importedExportEntity.name} took ${Date.now() - recurseStartTime}ms`,
1937
+ );
1938
+ debugLog(
1939
+ `Completed recursive writeScenarioComponents for ${importedExportEntity.name}`,
1940
+ );
1531
1941
  writtenScenarioComponents = updatedWrittenScenarioComponents;
1532
1942
  scenarioComponentPaths.push(...newScenarioComponentPaths);
1533
1943
  }
@@ -1831,9 +2241,7 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1831
2241
 
1832
2242
  // First, try to remove this entity from the already-rewritten grouped import
1833
2243
  // This prevents duplicate/conflicting imports
1834
- // IMPORTANT: Only remove from import statements, NOT from the entire file!
1835
- // The global patterns used previously would also match type annotations like:
1836
- // "param: MyType," in function signatures, corrupting the syntax.
2244
+ // Use AST-based removal to properly handle type-only imports like `type EntityName`
1837
2245
  const escapedEntityName = escapeRegExp(entityImportName);
1838
2246
 
1839
2247
  // For default imports: remove "DefaultName, " from "import DefaultName, { ... }"
@@ -1846,33 +2254,12 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1846
2254
  fileContent = fileContent.replace(defaultImportPattern, '$1$2');
1847
2255
  }
1848
2256
 
1849
- // Match import statements that contain this entity and remove just the entity
1850
- // Pattern: import { ... EntityName, ... } from '...'
1851
- // We match the full import and use a replacer function to remove the entity name
1852
- const importWithEntityPattern = new RegExp(
1853
- `(import\\s*\\{)([^}]*\\b${escapedEntityName}\\b[^}]*)(\\}\\s*from\\s*['"][^'"]*['"];?)`,
1854
- 'gm',
1855
- );
1856
- fileContent = fileContent.replace(
1857
- importWithEntityPattern,
1858
- (match, prefix, namedImports, suffix) => {
1859
- // Remove the entity name from the named imports
1860
- let cleaned = namedImports
1861
- .replace(new RegExp(`\\b${escapedEntityName}\\s*,\\s*`), '') // "EntityName, "
1862
- .replace(new RegExp(`\\s*,\\s*${escapedEntityName}\\b`), '') // ", EntityName"
1863
- .replace(new RegExp(`\\b${escapedEntityName}\\b`), ''); // "EntityName" (only one)
1864
- // Clean up any double commas or leading/trailing commas
1865
- cleaned = cleaned
1866
- .replace(/,\s*,/g, ',')
1867
- .replace(/^\s*,\s*/, '')
1868
- .replace(/\s*,\s*$/, '');
1869
- // If no imports left, remove the entire import statement
1870
- if (cleaned.trim() === '') {
1871
- return '';
1872
- }
1873
- return prefix + cleaned + suffix;
1874
- },
1875
- );
2257
+ // Remove the named import using AST parsing
2258
+ // This properly handles:
2259
+ // - Regular imports: `import { EntityName } from '...'`
2260
+ // - Type-only imports: `import { type EntityName } from '...'`
2261
+ // - Mixed imports: `import { type EntityName, OtherName } from '...'`
2262
+ fileContent = removeNamedImportAst(fileContent, entityImportName);
1876
2263
 
1877
2264
  // Add the new import at the beginning of fileContent
1878
2265
  // Note: The header comment (// Scenario:) doesn't exist yet - it's prepended at writeFile time
@@ -1888,9 +2275,32 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1888
2275
  }
1889
2276
  }
1890
2277
 
2278
+ // Track post-import-loop timing
2279
+ const postLoopStartTime = Date.now();
2280
+ console.log(`[WriteScenario] POST-LOOP START: ${entity.name}`);
2281
+
2282
+ // Collect universal mocks BEFORE processing nodeModuleImports
2283
+ // This is needed to check if a node module import is handled by a universal mock
2284
+ const universalMocks = project.metadata?.universalMocks ?? [];
2285
+ const nodeModuleUniversalMocks = universalMocks.filter(
2286
+ (mock) => mock.nodeModule && mock.content,
2287
+ );
2288
+
2289
+ // Create a set of import paths that have universal mocks for quick lookup
2290
+ const universalMockPaths = new Set(
2291
+ nodeModuleUniversalMocks.map((mock) => mock.filePath),
2292
+ );
2293
+
1891
2294
  for (const nodeModuleImport of nodeModuleImports) {
1892
2295
  if (!nodeModuleImport.isMocked) continue;
1893
2296
 
2297
+ // Skip generating local mock functions for imports that have universal mocks.
2298
+ // Universal mocks provide the exports via rewritten import paths (handled below).
2299
+ // Generating a local mock function would cause "name defined multiple times" errors.
2300
+ if (universalMockPaths.has(nodeModuleImport.filePath)) {
2301
+ continue;
2302
+ }
2303
+
1894
2304
  fileContent = addMockToContent(
1895
2305
  fileContent,
1896
2306
  nodeModuleImport,
@@ -1906,10 +2316,6 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1906
2316
  // Universal mocks create mock files at __codeyamMocks__/{safeFileName}.tsx
1907
2317
  // We need to rewrite imports like `import { logger } from "@formbricks/logger"`
1908
2318
  // to `import { logger } from "../__codeyamMocks__/_formbricks_logger"`
1909
- const universalMocks = project.metadata?.universalMocks ?? [];
1910
- const nodeModuleUniversalMocks = universalMocks.filter(
1911
- (mock) => mock.nodeModule && mock.content,
1912
- );
1913
2319
 
1914
2320
  for (const universalMock of nodeModuleUniversalMocks) {
1915
2321
  const originalPath = universalMock.filePath;
@@ -1932,6 +2338,10 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1932
2338
  );
1933
2339
  }
1934
2340
 
2341
+ console.log(
2342
+ `[WriteScenario] POST-LOOP ${entity.name}: node+universal mocks took ${Date.now() - postLoopStartTime}ms`,
2343
+ );
2344
+
1935
2345
  if (
1936
2346
  rootAnalysis.entitySha === entity.sha &&
1937
2347
  entity.metadata?.notExported &&
@@ -1973,31 +2383,46 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1973
2383
  });
1974
2384
  }
1975
2385
 
2386
+ debugLog('Route path computed', { scenarioComponentPath });
2387
+
1976
2388
  // Strip <html> and <body> tags from root layout files for Next.js
1977
2389
  // These tags cause hydration errors when the scenario layout is nested under the real root
2390
+ debugLog('Starting stripHtmlBodyTags');
1978
2391
  fileContent = stripHtmlBodyTags(fileContent, file.path, framework);
2392
+ debugLog('Completed stripHtmlBodyTags');
1979
2393
 
1980
2394
  // Strip "server-only" imports for Next.js
1981
2395
  // These cause errors when the scenario component is rendered client-side
2396
+ debugLog('Starting stripServerOnlyImport');
1982
2397
  fileContent = stripServerOnlyImport(fileContent);
2398
+ debugLog('Starting applyServerOnlyMocks');
1983
2399
  fileContent = applyServerOnlyMocks(fileContent);
2400
+ debugLog('Completed server-only processing');
1984
2401
 
1985
2402
  // Rewrite asset imports (CSS, images, fonts, etc.) to correct relative paths
1986
2403
  // The original file path is relative to PROJECT_RELATIVE_PATH, the new path is scenarioComponentPath
2404
+ debugLog('Starting rewriteAssetImports');
1987
2405
  fileContent = rewriteAssetImports(
1988
2406
  fileContent,
1989
2407
  `${PROJECT_RELATIVE_PATH}/${file.path}`,
1990
2408
  scenarioComponentPath,
1991
2409
  );
2410
+ debugLog('Completed rewriteAssetImports');
1992
2411
 
1993
2412
  // Rewrite relative TypeScript/JavaScript module imports to correct relative paths
1994
2413
  // This handles cases where the file is moved (e.g., from [environmentId]/ to _environmentId_/)
1995
2414
  // and relative imports like "./lib/organization" need to be rewritten
2415
+ debugLog('Starting rewriteRelativeModuleImports');
1996
2416
  fileContent = rewriteRelativeModuleImports(
1997
2417
  fileContent,
1998
2418
  `${PROJECT_RELATIVE_PATH}/${file.path}`,
1999
2419
  scenarioComponentPath,
2000
2420
  );
2421
+ debugLog('Completed rewriteRelativeModuleImports');
2422
+
2423
+ console.log(
2424
+ `[WriteScenario] POST-LOOP ${entity.name}: transformations took ${Date.now() - postLoopStartTime}ms`,
2425
+ );
2001
2426
 
2002
2427
  /**
2003
2428
  * Recursively process a file's imports to create transitive copies with server-only stripped.
@@ -2015,21 +2440,69 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
2015
2440
  sourceFilePath: string,
2016
2441
  targetFilePath: string,
2017
2442
  visitedPaths: Set<string> = new Set(),
2443
+ depth: number = 0,
2444
+ startTime: number = Date.now(),
2018
2445
  ): Promise<string> {
2446
+ // Global timeout for entire transitive processing
2447
+ const GLOBAL_TIMEOUT_MS = 180000; // 3 minutes max for all transitive processing (complex components need more time)
2448
+ const elapsed = Date.now() - startTime;
2449
+ if (elapsed > GLOBAL_TIMEOUT_MS) {
2450
+ throw new Error(
2451
+ `processTransitiveImportsRecursively exceeded ${GLOBAL_TIMEOUT_MS}ms (elapsed: ${elapsed}ms) at depth=${depth} for ${sourceFilePath}`,
2452
+ );
2453
+ }
2454
+
2019
2455
  const importPaths = extractInternalImportPaths(content);
2456
+ // Always log to help debug timeout issues
2457
+ console.log(
2458
+ `[TransitiveImports] depth=${depth} file=${path.basename(sourceFilePath)} imports=${importPaths.length} visited=${visitedPaths.size} elapsed=${Date.now() - startTime}ms`,
2459
+ );
2460
+ debugLog(`processTransitiveImportsRecursively depth=${depth}`, {
2461
+ sourceFilePath,
2462
+ importCount: importPaths.length,
2463
+ visitedCount: visitedPaths.size,
2464
+ });
2020
2465
  let modifiedContent = content;
2021
2466
 
2022
- for (const importPath of importPaths) {
2467
+ // Safety check: limit iterations to prevent infinite loops
2468
+ const MAX_IMPORTS_PER_FILE = 100;
2469
+ if (importPaths.length > MAX_IMPORTS_PER_FILE) {
2470
+ console.warn(
2471
+ `[WriteScenario] WARNING: File ${sourceFilePath} has ${importPaths.length} imports (> ${MAX_IMPORTS_PER_FILE}), limiting processing`,
2472
+ );
2473
+ }
2474
+
2475
+ let importIndex = 0;
2476
+ debugLog(
2477
+ `Starting import loop at depth=${depth}, ${importPaths.length} imports to process`,
2478
+ );
2479
+ const slicedImports = importPaths.slice(0, MAX_IMPORTS_PER_FILE);
2480
+ for (const importPath of slicedImports) {
2481
+ if (!importPath) {
2482
+ continue;
2483
+ }
2484
+ importIndex++;
2485
+ debugLog(
2486
+ `[LOOP] depth=${depth} import ${importIndex}/${Math.min(importPaths.length, MAX_IMPORTS_PER_FILE)}: ${importPath}`,
2487
+ );
2488
+ debugLog(`[LOOP] Calling resolveImportPath...`);
2023
2489
  const resolvedPath = resolveImportPath(
2024
2490
  importPath,
2025
2491
  sourceFilePath,
2026
2492
  project,
2027
2493
  );
2494
+ debugLog(
2495
+ `[LOOP] resolveImportPath returned: ${resolvedPath?.slice(0, 80) ?? 'null'}`,
2496
+ );
2028
2497
  if (!resolvedPath) continue;
2029
2498
 
2499
+ debugLog(`[LOOP] Looking up importFile...`);
2030
2500
  let importFile = fileStore
2031
2501
  ? fileStore.getByPath(resolvedPath)
2032
2502
  : project.files?.find((f) => f.path === resolvedPath);
2503
+ debugLog(
2504
+ `[LOOP] importFile lookup result: ${importFile ? 'found' : 'not found'}`,
2505
+ );
2033
2506
  if (!importFile) continue;
2034
2507
 
2035
2508
  // Build the transitive file path (needed for import rewriting even if we skip creating)
@@ -2038,8 +2511,10 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
2038
2511
  );
2039
2512
  const extension = importFile.name.split('.').pop();
2040
2513
  const isIndex = isIndexPath(importFile.path);
2041
- const pathHash = safeFileName(importFile.path);
2042
- const transitiveFilePath = `${PROJECT_RELATIVE_PATH}/${basePath}/${pathHash}_${isIndex ? 'index_' : ''}transitive_${safeFileName(scenario.name)}.${extension}`;
2514
+ // Limit pathHash length to prevent ENAMETOOLONG errors on macOS (255 char limit)
2515
+ const pathHash = safeFileName(importFile.path, { maxLength: 80 });
2516
+ const scenarioSlug = safeFileName(scenario.name, { maxLength: 60 });
2517
+ const transitiveFilePath = `${PROJECT_RELATIVE_PATH}/${basePath}/${pathHash}_${isIndex ? 'index_' : ''}transitive_${scenarioSlug}.${extension}`;
2043
2518
 
2044
2519
  // Check if this is a circular import (we're already processing this file)
2045
2520
  const isCircularImport = visitedPaths.has(resolvedPath);
@@ -2064,14 +2539,37 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
2064
2539
  // Strip server-only and mock server-only packages, then recursively process imports
2065
2540
  let transitiveContent = stripServerOnlyImport(importFile.content);
2066
2541
  transitiveContent = applyServerOnlyMocks(transitiveContent);
2067
- transitiveContent = await processTransitiveImportsRecursively(
2068
- transitiveContent,
2069
- importFile.path,
2070
- transitiveFilePath,
2071
- visitedPaths,
2542
+ debugLog(
2543
+ `processTransitiveImportsRecursively depth=${depth} for ${importFile.path}`,
2544
+ );
2545
+ debugLog(
2546
+ `Calling processTransitiveImportsRecursively depth=${depth + 1} for ${importFile.path}`,
2547
+ );
2548
+ transitiveContent = await withTimeout(
2549
+ `processTransitiveImportsRecursively depth=${depth} for ${path.basename(importFile.path)}`,
2550
+ processTransitiveImportsRecursively(
2551
+ transitiveContent,
2552
+ importFile.path,
2553
+ transitiveFilePath,
2554
+ visitedPaths,
2555
+ depth + 1,
2556
+ startTime, // Pass through the original start time
2557
+ ),
2558
+ 30000, // 30 second timeout per transitive import
2559
+ );
2560
+ debugLog(
2561
+ `withTimeout returned for depth=${depth}, transitiveContent length=${transitiveContent.length}`,
2562
+ );
2563
+ debugLog(
2564
+ `Completed processTransitiveImportsRecursively depth=${depth} for ${importFile.path}`,
2072
2565
  );
2073
2566
 
2567
+ debugLog(`Writing transitive file depth=${depth}`, {
2568
+ transitiveFilePath: path.basename(transitiveFilePath),
2569
+ contentLength: transitiveContent.length,
2570
+ });
2074
2571
  await writeFile(transitiveFilePath, transitiveContent);
2572
+ debugLog(`Wrote transitive file depth=${depth}`);
2075
2573
  scenarioComponentPaths.push(transitiveFilePath);
2076
2574
 
2077
2575
  if (!writtenScenarioComponents[resolvedPath]) {
@@ -2085,6 +2583,10 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
2085
2583
 
2086
2584
  // ALWAYS rewrite the import to point to the transitive copy
2087
2585
  // (even for circular imports or already-processed files)
2586
+ debugLog(`Rewriting import path depth=${depth}`, {
2587
+ importPath,
2588
+ resolvedPath,
2589
+ });
2088
2590
  const relativePath = getRelativePath(targetFilePath, transitiveFilePath);
2089
2591
  const relativePathWithoutExt = relativePath.replace(
2090
2592
  /\.(ts|tsx|js|jsx)$/,
@@ -2095,30 +2597,79 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
2095
2597
  /[.*+?^${}()|[\]\\]/g,
2096
2598
  '\\$&',
2097
2599
  );
2098
- const importRegex = new RegExp(
2099
- `(from\\s*["'])${escapedImportPath}(["'])`,
2100
- 'g',
2101
- );
2102
- modifiedContent = modifiedContent.replace(
2103
- importRegex,
2104
- `$1${safeRelativePath}$2`,
2600
+ debugLog(`Applying regex depth=${depth}`, {
2601
+ escapedImportPath,
2602
+ contentLength: modifiedContent.length,
2603
+ });
2604
+ // Quick check if the import path even exists in content
2605
+ const simpleCheck = modifiedContent.includes(importPath);
2606
+ debugLog(
2607
+ `Simple check: importPath "${importPath}" exists: ${simpleCheck}`,
2105
2608
  );
2609
+ if (!simpleCheck) {
2610
+ debugLog(`Skipping regex - import path not found in content`);
2611
+ } else {
2612
+ const regexPattern = `(from\\s*["'])${escapedImportPath}(["'])`;
2613
+ debugLog(`Regex pattern: ${regexPattern.slice(0, 100)}`);
2614
+ const importRegex = new RegExp(regexPattern, 'g');
2615
+ debugLog(`About to call replace...`);
2616
+
2617
+ // Timing for regex replace to detect slow operations
2618
+ const replaceStart = Date.now();
2619
+ modifiedContent = modifiedContent.replace(
2620
+ importRegex,
2621
+ `$1${safeRelativePath}$2`,
2622
+ );
2623
+ const replaceTime = Date.now() - replaceStart;
2624
+ if (replaceTime > 100) {
2625
+ console.warn(
2626
+ `[WriteScenario] SLOW regex replace: ${replaceTime}ms for pattern ${regexPattern.slice(0, 50)} on ${modifiedContent.length} bytes`,
2627
+ );
2628
+ }
2629
+ debugLog(`Regex applied depth=${depth} in ${replaceTime}ms`);
2630
+ }
2631
+ debugLog(`[LOOP END] depth=${depth} import ${importIndex} completed`);
2106
2632
  }
2107
2633
 
2634
+ debugLog(`[LOOP DONE] Exiting import loop at depth=${depth}`);
2635
+ debugLog(
2636
+ `Returning from processTransitiveImportsRecursively depth=${depth}`,
2637
+ );
2108
2638
  return modifiedContent;
2109
2639
  }
2110
2640
 
2641
+ console.log(
2642
+ `[WriteScenario] POST-LOOP ${entity.name}: before remaining imports ${Date.now() - postLoopStartTime}ms`,
2643
+ );
2644
+
2111
2645
  // Process remaining internal imports that weren't in importedExports
2112
2646
  // This handles transitive dependencies: when the file content includes code (e.g., from
2113
2647
  // other functions in the same file) that imports from files with "server-only"
2648
+ debugLog('Extracting remaining import paths');
2114
2649
  const remainingImportPaths = extractInternalImportPaths(fileContent);
2650
+ debugLog('Found remaining import paths', {
2651
+ count: remainingImportPaths.length,
2652
+ });
2115
2653
 
2116
2654
  // Get all file paths that are in importedExports - these are handled by main processing
2117
2655
  const importedExportFilePaths = new Set(
2118
2656
  allImportedExports.map((ie) => ie.resolvedFilePath || ie.filePath),
2119
2657
  );
2120
2658
 
2659
+ debugLog('Starting remaining imports loop', {
2660
+ remainingCount: remainingImportPaths.length,
2661
+ importedExportCount: importedExportFilePaths.size,
2662
+ });
2663
+
2664
+ let remainingImportIndex = 0;
2665
+ debugLog(
2666
+ `[REMAINING] Starting remaining imports loop, ${remainingImportPaths.length} imports`,
2667
+ );
2121
2668
  for (const importPath of remainingImportPaths) {
2669
+ remainingImportIndex++;
2670
+ debugLog(
2671
+ `[REMAINING LOOP] import ${remainingImportIndex}/${remainingImportPaths.length}: ${importPath}`,
2672
+ );
2122
2673
  // Resolve the import path to a project file path
2123
2674
  const resolvedFilePath = resolveImportPath(importPath, file.path, project);
2124
2675
 
@@ -2166,8 +2717,10 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
2166
2717
  );
2167
2718
  const targetFileExtension = targetFile.name.split('.').pop();
2168
2719
  const targetFileIsIndex = isIndexPath(targetFile.path);
2169
- const filePathHash = safeFileName(targetFile.path);
2170
- const transformedFilePath = `${PROJECT_RELATIVE_PATH}/${targetFileBasePath}/${filePathHash}_${targetFileIsIndex ? 'index_' : ''}transitive_${safeFileName(scenario.name)}.${targetFileExtension}`;
2720
+ // Limit path hash length to prevent ENAMETOOLONG errors
2721
+ const filePathHash = safeFileName(targetFile.path, { maxLength: 80 });
2722
+ const targetScenarioSlug = safeFileName(scenario.name, { maxLength: 60 });
2723
+ const transformedFilePath = `${PROJECT_RELATIVE_PATH}/${targetFileBasePath}/${filePathHash}_${targetFileIsIndex ? 'index_' : ''}transitive_${targetScenarioSlug}.${targetFileExtension}`;
2171
2724
 
2172
2725
  // Check if we've already processed this file as a transitive copy
2173
2726
  // Note: __data_file_written__ is for entity-specific scenario files with different naming,
@@ -2194,7 +2747,15 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
2194
2747
  // Recursively process this transitive file's imports
2195
2748
  // This handles the nested case: service.ts → brevo.ts → constants.ts
2196
2749
  const nestedImportPaths = extractInternalImportPaths(transformedContent);
2750
+ debugLog(
2751
+ `[NESTED] Processing ${nestedImportPaths.length} nested imports for ${targetFile.path}`,
2752
+ );
2753
+ let nestedIndex = 0;
2197
2754
  for (const nestedImportPath of nestedImportPaths) {
2755
+ nestedIndex++;
2756
+ debugLog(
2757
+ `[NESTED LOOP] import ${nestedIndex}/${nestedImportPaths.length}: ${nestedImportPath}`,
2758
+ );
2198
2759
  const nestedResolvedPath = resolveImportPath(
2199
2760
  nestedImportPath,
2200
2761
  targetFile.path,
@@ -2214,8 +2775,12 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
2214
2775
  );
2215
2776
  const nestedExtension = nestedFile.name.split('.').pop();
2216
2777
  const nestedIsIndex = isIndexPath(nestedFile.path);
2217
- const nestedPathHash = safeFileName(nestedFile.path);
2218
- const nestedTransformedPath = `${PROJECT_RELATIVE_PATH}/${nestedBasePath}/${nestedPathHash}_${nestedIsIndex ? 'index_' : ''}transitive_${safeFileName(scenario.name)}.${nestedExtension}`;
2778
+ // Limit path hash length to prevent ENAMETOOLONG errors
2779
+ const nestedPathHash = safeFileName(nestedFile.path, { maxLength: 80 });
2780
+ const nestedScenarioSlug = safeFileName(scenario.name, {
2781
+ maxLength: 60,
2782
+ });
2783
+ const nestedTransformedPath = `${PROJECT_RELATIVE_PATH}/${nestedBasePath}/${nestedPathHash}_${nestedIsIndex ? 'index_' : ''}transitive_${nestedScenarioSlug}.${nestedExtension}`;
2219
2784
 
2220
2785
  // Check if already processed as a transitive file (we can rewrite to point to it)
2221
2786
  // Note: __data_file_written__ is for entity-specific scenario files with different naming,
@@ -2235,10 +2800,20 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
2235
2800
  // This handles chains of any depth: A -> B -> C -> D
2236
2801
  let nestedContent = stripServerOnlyImport(nestedFile.content);
2237
2802
  nestedContent = applyServerOnlyMocks(nestedContent);
2238
- nestedContent = await processTransitiveImportsRecursively(
2239
- nestedContent,
2240
- nestedFile.path,
2241
- nestedTransformedPath,
2803
+ debugLog(
2804
+ `processTransitiveImportsRecursively (nested) for ${nestedFile.path}`,
2805
+ );
2806
+ nestedContent = await withTimeout(
2807
+ `processTransitiveImportsRecursively (nested) for ${path.basename(nestedFile.path)}`,
2808
+ processTransitiveImportsRecursively(
2809
+ nestedContent,
2810
+ nestedFile.path,
2811
+ nestedTransformedPath,
2812
+ ),
2813
+ 30000, // 30 second timeout per nested transitive import
2814
+ );
2815
+ debugLog(
2816
+ `Completed processTransitiveImportsRecursively (nested) for ${nestedFile.path}`,
2242
2817
  );
2243
2818
 
2244
2819
  await writeFile(nestedTransformedPath, nestedContent);
@@ -2326,6 +2901,10 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
2326
2901
  fileContent = fileContent.replace(importRegex, `$1${safeRelativePath}$2`);
2327
2902
  }
2328
2903
 
2904
+ console.log(
2905
+ `[WriteScenario] POST-LOOP ${entity.name}: remaining imports loop took ${Date.now() - postLoopStartTime}ms`,
2906
+ );
2907
+
2329
2908
  const scenarioComponentComment = `// This file is auto-generated by CodeYam. Do not edit this file manually.
2330
2909
  // This file contains content for a scenario component:
2331
2910
  // Analyses being written: ${JSON.stringify(fileAnalyses?.map((a) => ({ id: a.id, entityName: a.entityName })))}
@@ -2350,8 +2929,17 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
2350
2929
  finalContent = `${scenarioComponentComment}\n\n${fileContent}`;
2351
2930
  }
2352
2931
 
2932
+ debugLog('About to write final scenario file', {
2933
+ scenarioComponentPath,
2934
+ contentLength: finalContent.length,
2935
+ });
2353
2936
  await writeFile(scenarioComponentPath, finalContent);
2937
+ debugLog('Successfully wrote scenario file');
2354
2938
  scenarioComponentPaths.push(scenarioComponentPath);
2355
2939
 
2940
+ console.log(
2941
+ `[WriteScenario] POST-LOOP ${entity.name}: COMPLETE total=${Date.now() - postLoopStartTime}ms`,
2942
+ );
2943
+
2356
2944
  return { scenarioComponentPaths, writtenScenarioComponents };
2357
2945
  }