@codeyam/codeyam-cli 0.1.0-staging.e38f7bd → 0.1.0-staging.fef152f

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 (1052) 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 +30 -26
  5. package/analyzer-template/packages/ai/index.ts +21 -5
  6. package/analyzer-template/packages/ai/package.json +4 -4
  7. package/analyzer-template/packages/ai/src/lib/__mocks__/completionCall.ts +122 -0
  8. package/analyzer-template/packages/ai/src/lib/analyzeScope.ts +228 -24
  9. package/analyzer-template/packages/ai/src/lib/astScopes/arrayDerivationDetector.ts +199 -0
  10. package/analyzer-template/packages/ai/src/lib/astScopes/astScopeAnalyzer.ts +205 -10
  11. package/analyzer-template/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.ts +644 -0
  12. package/analyzer-template/packages/ai/src/lib/astScopes/methodSemantics.ts +181 -23
  13. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.ts +10 -17
  14. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/ifStatementHandler.ts +18 -0
  15. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.ts +38 -1
  16. package/analyzer-template/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.ts +181 -1
  17. package/analyzer-template/packages/ai/src/lib/astScopes/processExpression.ts +1619 -125
  18. package/analyzer-template/packages/ai/src/lib/astScopes/sharedPatterns.ts +28 -0
  19. package/analyzer-template/packages/ai/src/lib/astScopes/types.ts +324 -5
  20. package/analyzer-template/packages/ai/src/lib/checkAllAttributes.ts +29 -10
  21. package/analyzer-template/packages/ai/src/lib/completionCall.ts +216 -36
  22. package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +2761 -390
  23. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.ts +21 -4
  24. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.ts +976 -0
  25. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.ts +243 -77
  26. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.ts +16 -3
  27. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.ts +6 -4
  28. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.ts +71 -2
  29. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.ts +161 -19
  30. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.ts +70 -0
  31. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.ts +163 -14
  32. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.ts +98 -0
  33. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.ts +179 -0
  34. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.ts +40 -30
  35. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.ts +441 -82
  36. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.ts +129 -0
  37. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/stripNullableMarkers.ts +35 -0
  38. package/analyzer-template/packages/ai/src/lib/dataStructureChunking.ts +183 -0
  39. package/analyzer-template/packages/ai/src/lib/deepEqual.ts +30 -0
  40. package/analyzer-template/packages/ai/src/lib/e2eDataTracking.ts +334 -0
  41. package/analyzer-template/packages/ai/src/lib/extractCriticalDataKeys.ts +120 -0
  42. package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarioData.ts +74 -7
  43. package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarios.ts +89 -112
  44. package/analyzer-template/packages/ai/src/lib/generateEntityDataStructure.ts +63 -2
  45. package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +1419 -101
  46. package/analyzer-template/packages/ai/src/lib/generateEntityScenarios.ts +216 -109
  47. package/analyzer-template/packages/ai/src/lib/generateExecutionFlows.ts +710 -0
  48. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.ts +528 -0
  49. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionals.ts +2484 -0
  50. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.ts +239 -0
  51. package/analyzer-template/packages/ai/src/lib/getConditionalUsagesFromCode.ts +143 -31
  52. package/analyzer-template/packages/ai/src/lib/guessScenarioDataFromDescription.ts +8 -2
  53. package/analyzer-template/packages/ai/src/lib/isolateScopes.ts +328 -7
  54. package/analyzer-template/packages/ai/src/lib/mergeJsonTypeDefinitions.ts +5 -0
  55. package/analyzer-template/packages/ai/src/lib/mergeStatements.ts +111 -87
  56. package/analyzer-template/packages/ai/src/lib/promptGenerators/collapseNullableObjects.ts +118 -0
  57. package/analyzer-template/packages/ai/src/lib/promptGenerators/gatherAttributesMap.ts +17 -7
  58. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.ts +1 -1
  59. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.ts +32 -102
  60. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChunkPrompt.ts +82 -0
  61. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateCriticalKeysPrompt.ts +103 -0
  62. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.ts +110 -6
  63. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.ts +14 -53
  64. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.ts +58 -0
  65. package/analyzer-template/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.ts +28 -2
  66. package/analyzer-template/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.ts +391 -0
  67. package/analyzer-template/packages/ai/src/lib/resolvePathToControllable.ts +824 -0
  68. package/analyzer-template/packages/ai/src/lib/splitOutsideParentheses.ts +5 -1
  69. package/analyzer-template/packages/ai/src/lib/validateExecutionFlowPaths.ts +531 -0
  70. package/analyzer-template/packages/ai/src/lib/worker/SerializableDataStructure.ts +127 -3
  71. package/analyzer-template/packages/ai/src/lib/worker/analyzeScopeWorker.ts +121 -2
  72. package/analyzer-template/packages/analyze/index.ts +2 -0
  73. package/analyzer-template/packages/analyze/src/lib/FileAnalyzer.ts +79 -59
  74. package/analyzer-template/packages/analyze/src/lib/ProjectAnalyzer.ts +113 -26
  75. package/analyzer-template/packages/analyze/src/lib/analysisContext.ts +44 -4
  76. package/analyzer-template/packages/analyze/src/lib/asts/nodes/getNodeType.ts +1 -0
  77. package/analyzer-template/packages/analyze/src/lib/asts/nodes/index.ts +1 -0
  78. package/analyzer-template/packages/analyze/src/lib/asts/nodes/isAsyncFunction.ts +67 -0
  79. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.ts +19 -0
  80. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.ts +19 -0
  81. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllExports.ts +11 -0
  82. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.ts +8 -0
  83. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.ts +49 -1
  84. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.ts +2 -1
  85. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.ts +570 -180
  86. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +54 -1
  87. package/analyzer-template/packages/analyze/src/lib/files/analyze/dependencyResolver.ts +6 -0
  88. package/analyzer-template/packages/analyze/src/lib/files/analyze/findOrCreateEntity.ts +3 -0
  89. package/analyzer-template/packages/analyze/src/lib/files/analyze/gatherEntityMap.ts +4 -2
  90. package/analyzer-template/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.ts +33 -10
  91. package/analyzer-template/packages/analyze/src/lib/files/analyzeChange.ts +31 -15
  92. package/analyzer-template/packages/analyze/src/lib/files/analyzeEntity.ts +11 -7
  93. package/analyzer-template/packages/analyze/src/lib/files/analyzeInitial.ts +11 -12
  94. package/analyzer-template/packages/analyze/src/lib/files/analyzeRemixRoute.ts +4 -5
  95. package/analyzer-template/packages/analyze/src/lib/files/enums/steps.ts +1 -1
  96. package/analyzer-template/packages/analyze/src/lib/files/getImportedExports.ts +22 -13
  97. package/analyzer-template/packages/analyze/src/lib/files/scenarios/TransformationTracer.ts +1315 -0
  98. package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.ts +313 -0
  99. package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.ts +102 -0
  100. package/analyzer-template/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.ts +711 -78
  101. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.ts +1 -1
  102. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.ts +28 -62
  103. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +550 -137
  104. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.ts +264 -0
  105. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarioData.ts +78 -83
  106. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarios.ts +4 -8
  107. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +1067 -167
  108. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.ts +56 -11
  109. package/analyzer-template/packages/analyze/src/lib/files/scenarios/propagateArrayItemSchemas.ts +474 -0
  110. package/analyzer-template/packages/analyze/src/lib/files/setImportedExports.ts +2 -1
  111. package/analyzer-template/packages/analyze/src/lib/index.ts +1 -0
  112. package/analyzer-template/packages/analyze/src/lib/utils/getFileByPath.ts +19 -0
  113. package/analyzer-template/packages/aws/codebuild/index.ts +1 -0
  114. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.d.ts +11 -1
  115. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.d.ts.map +1 -1
  116. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.js +29 -18
  117. package/analyzer-template/packages/aws/dist/src/lib/codebuild/waitForBuild.js.map +1 -1
  118. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.d.ts +2 -2
  119. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.d.ts.map +1 -1
  120. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.js +2 -2
  121. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsDefineContainer.js.map +1 -1
  122. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.d.ts +8 -18
  123. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.d.ts.map +1 -1
  124. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.js +17 -61
  125. package/analyzer-template/packages/aws/dist/src/lib/ecs/ecsTaskFactory.js.map +1 -1
  126. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.d.ts +15 -0
  127. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.d.ts.map +1 -0
  128. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.js +31 -0
  129. package/analyzer-template/packages/aws/dist/src/lib/s3/checkS3ObjectExists.js.map +1 -0
  130. package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.d.ts.map +1 -1
  131. package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.js +8 -1
  132. package/analyzer-template/packages/aws/dist/src/lib/s3/uploadFileToS3.js.map +1 -1
  133. package/analyzer-template/packages/aws/package.json +10 -10
  134. package/analyzer-template/packages/aws/s3/index.ts +1 -0
  135. package/analyzer-template/packages/aws/src/lib/codebuild/waitForBuild.ts +43 -19
  136. package/analyzer-template/packages/aws/src/lib/ecs/ecsDefineContainer.ts +3 -3
  137. package/analyzer-template/packages/aws/src/lib/ecs/ecsTaskFactory.ts +17 -69
  138. package/analyzer-template/packages/aws/src/lib/s3/checkS3ObjectExists.ts +47 -0
  139. package/analyzer-template/packages/aws/src/lib/s3/uploadFileToS3.ts +8 -1
  140. package/analyzer-template/packages/database/package.json +1 -1
  141. package/analyzer-template/packages/database/src/lib/analysisBranchToDb.ts +1 -1
  142. package/analyzer-template/packages/database/src/lib/analysisToDb.ts +1 -1
  143. package/analyzer-template/packages/database/src/lib/branchToDb.ts +1 -1
  144. package/analyzer-template/packages/database/src/lib/commitBranchToDb.ts +1 -1
  145. package/analyzer-template/packages/database/src/lib/commitToDb.ts +1 -1
  146. package/analyzer-template/packages/database/src/lib/fileToDb.ts +1 -1
  147. package/analyzer-template/packages/database/src/lib/kysely/db.ts +18 -5
  148. package/analyzer-template/packages/database/src/lib/kysely/tableRelations.ts +2 -2
  149. package/analyzer-template/packages/database/src/lib/kysely/tables/commitsTable.ts +6 -0
  150. package/analyzer-template/packages/database/src/lib/kysely/tables/debugReportsTable.ts +36 -9
  151. package/analyzer-template/packages/database/src/lib/kysely/tables/labsRequestsTable.ts +52 -0
  152. package/analyzer-template/packages/database/src/lib/loadAnalyses.ts +58 -1
  153. package/analyzer-template/packages/database/src/lib/loadAnalysis.ts +13 -0
  154. package/analyzer-template/packages/database/src/lib/loadBranch.ts +16 -1
  155. package/analyzer-template/packages/database/src/lib/loadCommit.ts +11 -0
  156. package/analyzer-template/packages/database/src/lib/loadCommits.ts +28 -0
  157. package/analyzer-template/packages/database/src/lib/loadEntities.ts +26 -3
  158. package/analyzer-template/packages/database/src/lib/loadEntityBranches.ts +12 -0
  159. package/analyzer-template/packages/database/src/lib/loadReadyToBeCapturedAnalyses.ts +30 -5
  160. package/analyzer-template/packages/database/src/lib/projectToDb.ts +1 -1
  161. package/analyzer-template/packages/database/src/lib/saveFiles.ts +1 -1
  162. package/analyzer-template/packages/database/src/lib/scenarioToDb.ts +1 -1
  163. package/analyzer-template/packages/database/src/lib/updateCommitMetadata.ts +7 -14
  164. package/analyzer-template/packages/database/src/lib/userScenarioToDb.ts +1 -1
  165. package/analyzer-template/packages/generate/index.ts +3 -0
  166. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.ts +17 -1
  167. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.ts +193 -0
  168. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.ts +73 -0
  169. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.ts +9 -4
  170. package/analyzer-template/packages/generate/src/lib/deepMerge.ts +26 -1
  171. package/analyzer-template/packages/generate/src/lib/directExecutionScript.ts +17 -2
  172. package/analyzer-template/packages/generate/src/lib/getComponentScenarioPath.ts +8 -3
  173. package/analyzer-template/packages/generate/src/lib/scenarioComponentForServer.ts +114 -0
  174. package/analyzer-template/packages/github/dist/database/src/lib/analysisBranchToDb.js +1 -1
  175. package/analyzer-template/packages/github/dist/database/src/lib/analysisBranchToDb.js.map +1 -1
  176. package/analyzer-template/packages/github/dist/database/src/lib/analysisToDb.js +1 -1
  177. package/analyzer-template/packages/github/dist/database/src/lib/analysisToDb.js.map +1 -1
  178. package/analyzer-template/packages/github/dist/database/src/lib/branchToDb.js +1 -1
  179. package/analyzer-template/packages/github/dist/database/src/lib/branchToDb.js.map +1 -1
  180. package/analyzer-template/packages/github/dist/database/src/lib/commitBranchToDb.js +1 -1
  181. package/analyzer-template/packages/github/dist/database/src/lib/commitBranchToDb.js.map +1 -1
  182. package/analyzer-template/packages/github/dist/database/src/lib/commitToDb.js +1 -1
  183. package/analyzer-template/packages/github/dist/database/src/lib/commitToDb.js.map +1 -1
  184. package/analyzer-template/packages/github/dist/database/src/lib/fileToDb.js +1 -1
  185. package/analyzer-template/packages/github/dist/database/src/lib/fileToDb.js.map +1 -1
  186. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts +4 -2
  187. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts.map +1 -1
  188. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js +13 -3
  189. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js.map +1 -1
  190. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tableRelations.d.ts +2 -2
  191. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts +1 -11
  192. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/analysesTable.d.ts.map +1 -1
  193. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.d.ts +1 -0
  194. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.d.ts.map +1 -1
  195. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.js +3 -0
  196. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/commitsTable.js.map +1 -1
  197. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts +30 -7
  198. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts.map +1 -1
  199. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.js +9 -3
  200. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.js.map +1 -1
  201. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entitiesTable.d.ts +1 -0
  202. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/entitiesTable.d.ts.map +1 -1
  203. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.d.ts +23 -0
  204. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.d.ts.map +1 -0
  205. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.js +35 -0
  206. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.js.map +1 -0
  207. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts +2 -6
  208. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts.map +1 -1
  209. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.d.ts +2 -0
  210. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.d.ts.map +1 -1
  211. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.js +45 -2
  212. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalyses.js.map +1 -1
  213. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.d.ts.map +1 -1
  214. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.js +8 -0
  215. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.js.map +1 -1
  216. package/analyzer-template/packages/github/dist/database/src/lib/loadBranch.js +11 -1
  217. package/analyzer-template/packages/github/dist/database/src/lib/loadBranch.js.map +1 -1
  218. package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.d.ts.map +1 -1
  219. package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.js +7 -0
  220. package/analyzer-template/packages/github/dist/database/src/lib/loadCommit.js.map +1 -1
  221. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.d.ts +3 -1
  222. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.d.ts.map +1 -1
  223. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js +22 -1
  224. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js.map +1 -1
  225. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.d.ts +3 -1
  226. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.d.ts.map +1 -1
  227. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js +23 -4
  228. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js.map +1 -1
  229. package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.d.ts.map +1 -1
  230. package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.js +9 -0
  231. package/analyzer-template/packages/github/dist/database/src/lib/loadEntityBranches.js.map +1 -1
  232. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.d.ts.map +1 -1
  233. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js +23 -5
  234. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
  235. package/analyzer-template/packages/github/dist/database/src/lib/projectToDb.js +1 -1
  236. package/analyzer-template/packages/github/dist/database/src/lib/projectToDb.js.map +1 -1
  237. package/analyzer-template/packages/github/dist/database/src/lib/saveFiles.js +1 -1
  238. package/analyzer-template/packages/github/dist/database/src/lib/saveFiles.js.map +1 -1
  239. package/analyzer-template/packages/github/dist/database/src/lib/scenarioToDb.js +1 -1
  240. package/analyzer-template/packages/github/dist/database/src/lib/scenarioToDb.js.map +1 -1
  241. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts +2 -2
  242. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts.map +1 -1
  243. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js +5 -4
  244. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js.map +1 -1
  245. package/analyzer-template/packages/github/dist/generate/index.d.ts +3 -0
  246. package/analyzer-template/packages/github/dist/generate/index.d.ts.map +1 -1
  247. package/analyzer-template/packages/github/dist/generate/index.js +3 -0
  248. package/analyzer-template/packages/github/dist/generate/index.js.map +1 -1
  249. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.d.ts.map +1 -1
  250. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +16 -1
  251. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
  252. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.d.ts +9 -0
  253. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.d.ts.map +1 -0
  254. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +189 -0
  255. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -0
  256. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.d.ts +20 -0
  257. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.d.ts.map +1 -0
  258. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js +53 -0
  259. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js.map +1 -0
  260. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.d.ts.map +1 -1
  261. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +8 -4
  262. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
  263. package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.d.ts.map +1 -1
  264. package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.js +27 -1
  265. package/analyzer-template/packages/github/dist/generate/src/lib/deepMerge.js.map +1 -1
  266. package/analyzer-template/packages/github/dist/generate/src/lib/directExecutionScript.d.ts.map +1 -1
  267. package/analyzer-template/packages/github/dist/generate/src/lib/directExecutionScript.js +10 -1
  268. package/analyzer-template/packages/github/dist/generate/src/lib/directExecutionScript.js.map +1 -1
  269. package/analyzer-template/packages/github/dist/generate/src/lib/getComponentScenarioPath.d.ts.map +1 -1
  270. package/analyzer-template/packages/github/dist/generate/src/lib/getComponentScenarioPath.js +7 -3
  271. package/analyzer-template/packages/github/dist/generate/src/lib/getComponentScenarioPath.js.map +1 -1
  272. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.d.ts +8 -0
  273. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.d.ts.map +1 -0
  274. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.js +89 -0
  275. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponentForServer.js.map +1 -0
  276. package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.d.ts.map +1 -1
  277. package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.js +10 -0
  278. package/analyzer-template/packages/github/dist/github/src/lib/loadOrCreateCommit.js.map +1 -1
  279. package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.d.ts.map +1 -1
  280. package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.js +3 -0
  281. package/analyzer-template/packages/github/dist/github/src/lib/syncPrimaryBranch.js.map +1 -1
  282. package/analyzer-template/packages/github/dist/types/index.d.ts +2 -2
  283. package/analyzer-template/packages/github/dist/types/index.d.ts.map +1 -1
  284. package/analyzer-template/packages/github/dist/types/index.js.map +1 -1
  285. package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts +87 -13
  286. package/analyzer-template/packages/github/dist/types/src/types/Analysis.d.ts.map +1 -1
  287. package/analyzer-template/packages/github/dist/types/src/types/Commit.d.ts +2 -0
  288. package/analyzer-template/packages/github/dist/types/src/types/Commit.d.ts.map +1 -1
  289. package/analyzer-template/packages/github/dist/types/src/types/Entity.d.ts +2 -0
  290. package/analyzer-template/packages/github/dist/types/src/types/Entity.d.ts.map +1 -1
  291. package/analyzer-template/packages/github/dist/types/src/types/ProjectMetadata.d.ts +7 -0
  292. package/analyzer-template/packages/github/dist/types/src/types/ProjectMetadata.d.ts.map +1 -1
  293. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts +11 -6
  294. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts.map +1 -1
  295. package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts +199 -3
  296. package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
  297. package/analyzer-template/packages/github/dist/types/src/types/ScopeAnalysis.d.ts +6 -1
  298. package/analyzer-template/packages/github/dist/types/src/types/ScopeAnalysis.d.ts.map +1 -1
  299. package/analyzer-template/packages/github/dist/types/src/types/StatementInfo.d.ts +2 -0
  300. package/analyzer-template/packages/github/dist/types/src/types/StatementInfo.d.ts.map +1 -1
  301. package/analyzer-template/packages/github/dist/utils/src/lib/applyUniversalMocks.d.ts.map +1 -1
  302. package/analyzer-template/packages/github/dist/utils/src/lib/applyUniversalMocks.js +26 -2
  303. package/analyzer-template/packages/github/dist/utils/src/lib/applyUniversalMocks.js.map +1 -1
  304. package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.d.ts.map +1 -1
  305. package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.js +25 -0
  306. package/analyzer-template/packages/github/dist/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
  307. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.d.ts +9 -1
  308. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.d.ts.map +1 -1
  309. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.js +29 -3
  310. package/analyzer-template/packages/github/dist/utils/src/lib/safeFileName.js.map +1 -1
  311. package/analyzer-template/packages/github/package.json +1 -1
  312. package/analyzer-template/packages/github/src/lib/loadOrCreateCommit.ts +14 -0
  313. package/analyzer-template/packages/github/src/lib/syncPrimaryBranch.ts +2 -0
  314. package/analyzer-template/packages/process/index.ts +2 -0
  315. package/analyzer-template/packages/process/package.json +12 -0
  316. package/analyzer-template/packages/process/tsconfig.json +8 -0
  317. package/analyzer-template/packages/types/index.ts +5 -0
  318. package/analyzer-template/packages/types/src/types/Analysis.ts +104 -13
  319. package/analyzer-template/packages/types/src/types/Commit.ts +2 -0
  320. package/analyzer-template/packages/types/src/types/Entity.ts +2 -0
  321. package/analyzer-template/packages/types/src/types/ProjectMetadata.ts +7 -0
  322. package/analyzer-template/packages/types/src/types/Scenario.ts +11 -10
  323. package/analyzer-template/packages/types/src/types/ScenariosDataStructure.ts +228 -3
  324. package/analyzer-template/packages/types/src/types/ScopeAnalysis.ts +6 -1
  325. package/analyzer-template/packages/types/src/types/StatementInfo.ts +2 -0
  326. package/analyzer-template/packages/ui-components/package.json +4 -4
  327. package/analyzer-template/packages/ui-components/src/components/ScenarioDetailInteractiveView.tsx +23 -7
  328. package/analyzer-template/packages/utils/dist/types/index.d.ts +2 -2
  329. package/analyzer-template/packages/utils/dist/types/index.d.ts.map +1 -1
  330. package/analyzer-template/packages/utils/dist/types/index.js.map +1 -1
  331. package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts +87 -13
  332. package/analyzer-template/packages/utils/dist/types/src/types/Analysis.d.ts.map +1 -1
  333. package/analyzer-template/packages/utils/dist/types/src/types/Commit.d.ts +2 -0
  334. package/analyzer-template/packages/utils/dist/types/src/types/Commit.d.ts.map +1 -1
  335. package/analyzer-template/packages/utils/dist/types/src/types/Entity.d.ts +2 -0
  336. package/analyzer-template/packages/utils/dist/types/src/types/Entity.d.ts.map +1 -1
  337. package/analyzer-template/packages/utils/dist/types/src/types/ProjectMetadata.d.ts +7 -0
  338. package/analyzer-template/packages/utils/dist/types/src/types/ProjectMetadata.d.ts.map +1 -1
  339. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts +11 -6
  340. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts.map +1 -1
  341. package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts +199 -3
  342. package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
  343. package/analyzer-template/packages/utils/dist/types/src/types/ScopeAnalysis.d.ts +6 -1
  344. package/analyzer-template/packages/utils/dist/types/src/types/ScopeAnalysis.d.ts.map +1 -1
  345. package/analyzer-template/packages/utils/dist/types/src/types/StatementInfo.d.ts +2 -0
  346. package/analyzer-template/packages/utils/dist/types/src/types/StatementInfo.d.ts.map +1 -1
  347. package/analyzer-template/packages/utils/dist/utils/src/lib/applyUniversalMocks.d.ts.map +1 -1
  348. package/analyzer-template/packages/utils/dist/utils/src/lib/applyUniversalMocks.js +26 -2
  349. package/analyzer-template/packages/utils/dist/utils/src/lib/applyUniversalMocks.js.map +1 -1
  350. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.d.ts.map +1 -1
  351. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js +98 -3
  352. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js.map +1 -1
  353. package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.d.ts.map +1 -1
  354. package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.js +25 -0
  355. package/analyzer-template/packages/utils/dist/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
  356. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.d.ts +9 -1
  357. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.d.ts.map +1 -1
  358. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.js +29 -3
  359. package/analyzer-template/packages/utils/dist/utils/src/lib/safeFileName.js.map +1 -1
  360. package/analyzer-template/packages/utils/src/lib/applyUniversalMocks.ts +28 -2
  361. package/analyzer-template/packages/utils/src/lib/fs/rsyncCopy.ts +121 -3
  362. package/analyzer-template/packages/utils/src/lib/lightweightEntityExtractor.ts +27 -0
  363. package/analyzer-template/packages/utils/src/lib/safeFileName.ts +48 -3
  364. package/analyzer-template/playwright/capture.ts +57 -26
  365. package/analyzer-template/playwright/captureStatic.ts +1 -1
  366. package/analyzer-template/playwright/getCodeYamInfo.ts +12 -7
  367. package/analyzer-template/playwright/takeElementScreenshot.ts +26 -11
  368. package/analyzer-template/playwright/takeScreenshot.ts +15 -9
  369. package/analyzer-template/playwright/waitForServer.ts +21 -6
  370. package/analyzer-template/project/TESTING.md +83 -0
  371. package/analyzer-template/project/analyzeBaselineCommit.ts +9 -0
  372. package/analyzer-template/project/analyzeBranchCommit.ts +4 -0
  373. package/analyzer-template/project/analyzeFileEntities.ts +4 -0
  374. package/analyzer-template/project/analyzeRegularCommit.ts +9 -0
  375. package/analyzer-template/project/captureLibraryFunctionDirect.ts +29 -26
  376. package/analyzer-template/project/constructMockCode.ts +1347 -159
  377. package/analyzer-template/project/controller/startController.ts +16 -1
  378. package/analyzer-template/project/createEntitiesAndSortFiles.ts +83 -0
  379. package/analyzer-template/project/executeLibraryFunctionDirect.ts +7 -3
  380. package/analyzer-template/project/loadReadyToBeCaptured.ts +82 -42
  381. package/analyzer-template/project/mocks/analyzeFileMock.ts +8 -7
  382. package/analyzer-template/project/orchestrateCapture/AwsCaptureTaskRunner.ts +12 -4
  383. package/analyzer-template/project/orchestrateCapture/KyselyAnalysisLoader.ts +13 -9
  384. package/analyzer-template/project/orchestrateCapture/SequentialCaptureTaskRunner.ts +93 -42
  385. package/analyzer-template/project/orchestrateCapture/taskRunner.ts +4 -2
  386. package/analyzer-template/project/orchestrateCapture.ts +92 -13
  387. package/analyzer-template/project/reconcileMockDataKeys.ts +245 -2
  388. package/analyzer-template/project/runAnalysis.ts +11 -0
  389. package/analyzer-template/project/runMultiScenarioServer.ts +11 -10
  390. package/analyzer-template/project/serverOnlyModules.ts +413 -0
  391. package/analyzer-template/project/start.ts +72 -19
  392. package/analyzer-template/project/startScenarioCapture.ts +79 -41
  393. package/analyzer-template/project/writeMockDataTsx.ts +466 -73
  394. package/analyzer-template/project/writeScenarioClientWrapper.ts +21 -0
  395. package/analyzer-template/project/writeScenarioComponents.ts +1509 -226
  396. package/analyzer-template/project/writeScenarioFiles.ts +26 -0
  397. package/analyzer-template/project/writeSimpleRoot.ts +56 -22
  398. package/analyzer-template/project/writeUniversalMocks.ts +32 -11
  399. package/analyzer-template/scripts/comboWorkerLoop.cjs +99 -50
  400. package/analyzer-template/scripts/defaultCmd.sh +9 -0
  401. package/analyzer-template/tsconfig.json +2 -1
  402. package/background/src/lib/local/createLocalAnalyzer.js +2 -30
  403. package/background/src/lib/local/createLocalAnalyzer.js.map +1 -1
  404. package/background/src/lib/local/execAsync.js +1 -1
  405. package/background/src/lib/local/execAsync.js.map +1 -1
  406. package/background/src/lib/virtualized/common/execAsync.js +1 -1
  407. package/background/src/lib/virtualized/common/execAsync.js.map +1 -1
  408. package/background/src/lib/virtualized/project/analyzeBaselineCommit.js +7 -1
  409. package/background/src/lib/virtualized/project/analyzeBaselineCommit.js.map +1 -1
  410. package/background/src/lib/virtualized/project/analyzeBranchCommit.js +2 -1
  411. package/background/src/lib/virtualized/project/analyzeBranchCommit.js.map +1 -1
  412. package/background/src/lib/virtualized/project/analyzeFileEntities.js +2 -1
  413. package/background/src/lib/virtualized/project/analyzeFileEntities.js.map +1 -1
  414. package/background/src/lib/virtualized/project/analyzeRegularCommit.js +7 -1
  415. package/background/src/lib/virtualized/project/analyzeRegularCommit.js.map +1 -1
  416. package/background/src/lib/virtualized/project/captureLibraryFunctionDirect.js +3 -3
  417. package/background/src/lib/virtualized/project/captureLibraryFunctionDirect.js.map +1 -1
  418. package/background/src/lib/virtualized/project/constructMockCode.js +1194 -120
  419. package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
  420. package/background/src/lib/virtualized/project/controller/startController.js +11 -1
  421. package/background/src/lib/virtualized/project/controller/startController.js.map +1 -1
  422. package/background/src/lib/virtualized/project/createEntitiesAndSortFiles.js +73 -1
  423. package/background/src/lib/virtualized/project/createEntitiesAndSortFiles.js.map +1 -1
  424. package/background/src/lib/virtualized/project/executeLibraryFunctionDirect.js +6 -3
  425. package/background/src/lib/virtualized/project/executeLibraryFunctionDirect.js.map +1 -1
  426. package/background/src/lib/virtualized/project/loadReadyToBeCaptured.js +34 -9
  427. package/background/src/lib/virtualized/project/loadReadyToBeCaptured.js.map +1 -1
  428. package/background/src/lib/virtualized/project/mocks/analyzeFileMock.js +7 -7
  429. package/background/src/lib/virtualized/project/mocks/analyzeFileMock.js.map +1 -1
  430. package/background/src/lib/virtualized/project/orchestrateCapture/AwsCaptureTaskRunner.js +2 -2
  431. package/background/src/lib/virtualized/project/orchestrateCapture/AwsCaptureTaskRunner.js.map +1 -1
  432. package/background/src/lib/virtualized/project/orchestrateCapture/KyselyAnalysisLoader.js +12 -6
  433. package/background/src/lib/virtualized/project/orchestrateCapture/KyselyAnalysisLoader.js.map +1 -1
  434. package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js +73 -36
  435. package/background/src/lib/virtualized/project/orchestrateCapture/SequentialCaptureTaskRunner.js.map +1 -1
  436. package/background/src/lib/virtualized/project/orchestrateCapture.js +76 -14
  437. package/background/src/lib/virtualized/project/orchestrateCapture.js.map +1 -1
  438. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js +204 -2
  439. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js.map +1 -1
  440. package/background/src/lib/virtualized/project/runAnalysis.js +9 -0
  441. package/background/src/lib/virtualized/project/runAnalysis.js.map +1 -1
  442. package/background/src/lib/virtualized/project/runMultiScenarioServer.js +11 -9
  443. package/background/src/lib/virtualized/project/runMultiScenarioServer.js.map +1 -1
  444. package/background/src/lib/virtualized/project/serverOnlyModules.js +338 -0
  445. package/background/src/lib/virtualized/project/serverOnlyModules.js.map +1 -0
  446. package/background/src/lib/virtualized/project/start.js +62 -19
  447. package/background/src/lib/virtualized/project/start.js.map +1 -1
  448. package/background/src/lib/virtualized/project/startScenarioCapture.js +61 -31
  449. package/background/src/lib/virtualized/project/startScenarioCapture.js.map +1 -1
  450. package/background/src/lib/virtualized/project/writeMockDataTsx.js +404 -62
  451. package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
  452. package/background/src/lib/virtualized/project/writeScenarioClientWrapper.js +15 -0
  453. package/background/src/lib/virtualized/project/writeScenarioClientWrapper.js.map +1 -0
  454. package/background/src/lib/virtualized/project/writeScenarioComponents.js +1112 -153
  455. package/background/src/lib/virtualized/project/writeScenarioComponents.js.map +1 -1
  456. package/background/src/lib/virtualized/project/writeScenarioFiles.js +19 -0
  457. package/background/src/lib/virtualized/project/writeScenarioFiles.js.map +1 -1
  458. package/background/src/lib/virtualized/project/writeSimpleRoot.js +57 -20
  459. package/background/src/lib/virtualized/project/writeSimpleRoot.js.map +1 -1
  460. package/background/src/lib/virtualized/project/writeUniversalMocks.js +27 -12
  461. package/background/src/lib/virtualized/project/writeUniversalMocks.js.map +1 -1
  462. package/codeyam-cli/scripts/apply-setup.js +180 -0
  463. package/codeyam-cli/scripts/apply-setup.js.map +1 -1
  464. package/codeyam-cli/src/cli.js +38 -17
  465. package/codeyam-cli/src/cli.js.map +1 -1
  466. package/codeyam-cli/src/codeyam-cli.js +18 -2
  467. package/codeyam-cli/src/codeyam-cli.js.map +1 -1
  468. package/codeyam-cli/src/commands/analyze.js +5 -3
  469. package/codeyam-cli/src/commands/analyze.js.map +1 -1
  470. package/codeyam-cli/src/commands/baseline.js +176 -0
  471. package/codeyam-cli/src/commands/baseline.js.map +1 -0
  472. package/codeyam-cli/src/commands/debug.js +44 -18
  473. package/codeyam-cli/src/commands/debug.js.map +1 -1
  474. package/codeyam-cli/src/commands/default.js +30 -34
  475. package/codeyam-cli/src/commands/default.js.map +1 -1
  476. package/codeyam-cli/src/commands/detect-universal-mocks.js +2 -0
  477. package/codeyam-cli/src/commands/detect-universal-mocks.js.map +1 -1
  478. package/codeyam-cli/src/commands/init.js +49 -257
  479. package/codeyam-cli/src/commands/init.js.map +1 -1
  480. package/codeyam-cli/src/commands/memory.js +254 -0
  481. package/codeyam-cli/src/commands/memory.js.map +1 -0
  482. package/codeyam-cli/src/commands/recapture.js +228 -0
  483. package/codeyam-cli/src/commands/recapture.js.map +1 -0
  484. package/codeyam-cli/src/commands/report.js +72 -24
  485. package/codeyam-cli/src/commands/report.js.map +1 -1
  486. package/codeyam-cli/src/commands/setup-sandbox.js +2 -0
  487. package/codeyam-cli/src/commands/setup-sandbox.js.map +1 -1
  488. package/codeyam-cli/src/commands/setup-simulations.js +284 -0
  489. package/codeyam-cli/src/commands/setup-simulations.js.map +1 -0
  490. package/codeyam-cli/src/commands/start.js +8 -12
  491. package/codeyam-cli/src/commands/start.js.map +1 -1
  492. package/codeyam-cli/src/commands/status.js +23 -1
  493. package/codeyam-cli/src/commands/status.js.map +1 -1
  494. package/codeyam-cli/src/commands/test-startup.js +3 -1
  495. package/codeyam-cli/src/commands/test-startup.js.map +1 -1
  496. package/codeyam-cli/src/commands/verify.js +14 -2
  497. package/codeyam-cli/src/commands/verify.js.map +1 -1
  498. package/codeyam-cli/src/commands/wipe.js +108 -0
  499. package/codeyam-cli/src/commands/wipe.js.map +1 -0
  500. package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js +185 -0
  501. package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js.map +1 -0
  502. package/codeyam-cli/src/utils/__tests__/serverVersionStaleness.test.js +81 -0
  503. package/codeyam-cli/src/utils/__tests__/serverVersionStaleness.test.js.map +1 -0
  504. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js +128 -82
  505. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js.map +1 -1
  506. package/codeyam-cli/src/utils/analysisRunner.js +29 -15
  507. package/codeyam-cli/src/utils/analysisRunner.js.map +1 -1
  508. package/codeyam-cli/src/utils/analyzer.js +7 -0
  509. package/codeyam-cli/src/utils/analyzer.js.map +1 -1
  510. package/codeyam-cli/src/utils/backgroundServer.js +104 -23
  511. package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
  512. package/codeyam-cli/src/utils/database.js +91 -5
  513. package/codeyam-cli/src/utils/database.js.map +1 -1
  514. package/codeyam-cli/src/utils/generateReport.js +253 -106
  515. package/codeyam-cli/src/utils/generateReport.js.map +1 -1
  516. package/codeyam-cli/src/utils/git.js +79 -0
  517. package/codeyam-cli/src/utils/git.js.map +1 -0
  518. package/codeyam-cli/src/utils/install-skills.js +76 -42
  519. package/codeyam-cli/src/utils/install-skills.js.map +1 -1
  520. package/codeyam-cli/src/utils/labsAutoCheck.js +19 -0
  521. package/codeyam-cli/src/utils/labsAutoCheck.js.map +1 -0
  522. package/codeyam-cli/src/utils/npmVersionCheck.js +76 -0
  523. package/codeyam-cli/src/utils/npmVersionCheck.js.map +1 -0
  524. package/codeyam-cli/src/utils/progress.js +7 -0
  525. package/codeyam-cli/src/utils/progress.js.map +1 -1
  526. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js +38 -0
  527. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js.map +1 -1
  528. package/codeyam-cli/src/utils/queue/job.js +249 -16
  529. package/codeyam-cli/src/utils/queue/job.js.map +1 -1
  530. package/codeyam-cli/src/utils/queue/manager.js +103 -7
  531. package/codeyam-cli/src/utils/queue/manager.js.map +1 -1
  532. package/codeyam-cli/src/utils/queue/persistence.js.map +1 -1
  533. package/codeyam-cli/src/utils/requireSimulations.js +10 -0
  534. package/codeyam-cli/src/utils/requireSimulations.js.map +1 -0
  535. package/codeyam-cli/src/utils/ruleReflection/__tests__/confusionDetector.test.js +82 -0
  536. package/codeyam-cli/src/utils/ruleReflection/__tests__/confusionDetector.test.js.map +1 -0
  537. package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js +230 -0
  538. package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js.map +1 -0
  539. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js +67 -0
  540. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js.map +1 -0
  541. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/captureFixture.js +105 -0
  542. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/captureFixture.js.map +1 -0
  543. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/loadCapturedFixture.js +34 -0
  544. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/loadCapturedFixture.js.map +1 -0
  545. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/runClaude.js +162 -0
  546. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/runClaude.js.map +1 -0
  547. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js +74 -0
  548. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js.map +1 -0
  549. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js +376 -0
  550. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js.map +1 -0
  551. package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js +116 -0
  552. package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js.map +1 -0
  553. package/codeyam-cli/src/utils/ruleReflection/__tests__/transcriptParser.test.js +127 -0
  554. package/codeyam-cli/src/utils/ruleReflection/__tests__/transcriptParser.test.js.map +1 -0
  555. package/codeyam-cli/src/utils/ruleReflection/confusionDetector.js +50 -0
  556. package/codeyam-cli/src/utils/ruleReflection/confusionDetector.js.map +1 -0
  557. package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js +116 -0
  558. package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js.map +1 -0
  559. package/codeyam-cli/src/utils/ruleReflection/index.js +5 -0
  560. package/codeyam-cli/src/utils/ruleReflection/index.js.map +1 -0
  561. package/codeyam-cli/src/utils/ruleReflection/promptBuilder.js +44 -0
  562. package/codeyam-cli/src/utils/ruleReflection/promptBuilder.js.map +1 -0
  563. package/codeyam-cli/src/utils/ruleReflection/transcriptParser.js +85 -0
  564. package/codeyam-cli/src/utils/ruleReflection/transcriptParser.js.map +1 -0
  565. package/codeyam-cli/src/utils/ruleReflection/types.js +5 -0
  566. package/codeyam-cli/src/utils/ruleReflection/types.js.map +1 -0
  567. package/codeyam-cli/src/utils/rules/__tests__/pathMatcher.test.js +84 -0
  568. package/codeyam-cli/src/utils/rules/__tests__/pathMatcher.test.js.map +1 -0
  569. package/codeyam-cli/src/utils/rules/__tests__/ruleState.test.js +293 -0
  570. package/codeyam-cli/src/utils/rules/__tests__/ruleState.test.js.map +1 -0
  571. package/codeyam-cli/src/utils/rules/__tests__/sourceFiles.test.js +83 -0
  572. package/codeyam-cli/src/utils/rules/__tests__/sourceFiles.test.js.map +1 -0
  573. package/codeyam-cli/src/utils/rules/index.js +7 -0
  574. package/codeyam-cli/src/utils/rules/index.js.map +1 -0
  575. package/codeyam-cli/src/utils/rules/parser.js +83 -0
  576. package/codeyam-cli/src/utils/rules/parser.js.map +1 -0
  577. package/codeyam-cli/src/utils/rules/pathMatcher.js +28 -0
  578. package/codeyam-cli/src/utils/rules/pathMatcher.js.map +1 -0
  579. package/codeyam-cli/src/utils/rules/ruleState.js +150 -0
  580. package/codeyam-cli/src/utils/rules/ruleState.js.map +1 -0
  581. package/codeyam-cli/src/utils/rules/sourceFiles.js +47 -0
  582. package/codeyam-cli/src/utils/rules/sourceFiles.js.map +1 -0
  583. package/codeyam-cli/src/utils/rules/staleness.js +137 -0
  584. package/codeyam-cli/src/utils/rules/staleness.js.map +1 -0
  585. package/codeyam-cli/src/utils/serverState.js +37 -10
  586. package/codeyam-cli/src/utils/serverState.js.map +1 -1
  587. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +21 -42
  588. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
  589. package/codeyam-cli/src/utils/simulationGateMiddleware.js +138 -0
  590. package/codeyam-cli/src/utils/simulationGateMiddleware.js.map +1 -0
  591. package/codeyam-cli/src/utils/syncMocksMiddleware.js +5 -24
  592. package/codeyam-cli/src/utils/syncMocksMiddleware.js.map +1 -1
  593. package/codeyam-cli/src/utils/versionInfo.js +67 -15
  594. package/codeyam-cli/src/utils/versionInfo.js.map +1 -1
  595. package/codeyam-cli/src/utils/wipe.js +128 -0
  596. package/codeyam-cli/src/utils/wipe.js.map +1 -0
  597. package/codeyam-cli/src/webserver/__tests__/dependency-smoke.test.js +66 -0
  598. package/codeyam-cli/src/webserver/__tests__/dependency-smoke.test.js.map +1 -0
  599. package/codeyam-cli/src/webserver/app/lib/database.js +118 -6
  600. package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
  601. package/codeyam-cli/src/webserver/app/lib/dbNotifier.js.map +1 -1
  602. package/codeyam-cli/src/webserver/backgroundServer.js +55 -10
  603. package/codeyam-cli/src/webserver/backgroundServer.js.map +1 -1
  604. package/codeyam-cli/src/webserver/bootstrap.js +60 -0
  605. package/codeyam-cli/src/webserver/bootstrap.js.map +1 -0
  606. package/codeyam-cli/src/webserver/build/client/assets/CopyButton-jNYXRRNI.js +1 -0
  607. package/codeyam-cli/src/webserver/build/client/assets/EntityItem-bwuHPyTa.js +11 -0
  608. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeBadge-kykTbcnD.js → EntityTypeBadge-CvzqMxcu.js} +1 -1
  609. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-BH0XDim7.js +41 -0
  610. package/codeyam-cli/src/webserver/build/client/assets/InlineSpinner-EhOseatT.js +34 -0
  611. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-yjIHlOGa.js +25 -0
  612. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-Cq5o8jL4.js +3 -0
  613. package/codeyam-cli/src/webserver/build/client/assets/LoadingDots-BvMu2i-g.js +6 -0
  614. package/codeyam-cli/src/webserver/build/client/assets/LogViewer-kgBTLoJD.js +3 -0
  615. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-BzPgx-xO.js +11 -0
  616. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-CwZrv-Ok.js +1 -0
  617. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-BX2Ny2Qj.js +10 -0
  618. package/codeyam-cli/src/webserver/build/client/assets/{TruncatedFilePath-C06nsHKY.js → TruncatedFilePath-CDpEprKa.js} +1 -1
  619. package/codeyam-cli/src/webserver/build/client/assets/_index-BRx8ZGZo.js +11 -0
  620. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-4S4yPfFw.js +27 -0
  621. package/codeyam-cli/src/webserver/build/client/assets/agent-transcripts-DHKuQSmR.js +17 -0
  622. package/codeyam-cli/src/webserver/build/client/assets/api.agent-transcripts-l0sNRNKZ.js +1 -0
  623. package/codeyam-cli/src/webserver/build/client/assets/api.health-l0sNRNKZ.js +1 -0
  624. package/codeyam-cli/src/webserver/build/client/assets/api.labs-unlock-l0sNRNKZ.js +1 -0
  625. package/codeyam-cli/src/webserver/build/client/assets/api.memory-profile-l0sNRNKZ.js +1 -0
  626. package/codeyam-cli/src/webserver/build/client/assets/api.restart-server-l0sNRNKZ.js +1 -0
  627. package/codeyam-cli/src/webserver/build/client/assets/api.save-fixture-l0sNRNKZ.js +1 -0
  628. package/codeyam-cli/src/webserver/build/client/assets/book-open-D4IPYH_y.js +6 -0
  629. package/codeyam-cli/src/webserver/build/client/assets/chevron-down-CG65viiV.js +6 -0
  630. package/codeyam-cli/src/webserver/build/client/assets/chunk-JZWAC4HX-DB3aFuEO.js +51 -0
  631. package/codeyam-cli/src/webserver/build/client/assets/circle-check-igfMr5DY.js +6 -0
  632. package/codeyam-cli/src/webserver/build/client/assets/copy-Coc4o_8c.js +11 -0
  633. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-D1zB-pYc.js +21 -0
  634. package/codeyam-cli/src/webserver/build/client/assets/{cy-logo-cli-C1gnJVOL.svg → cy-logo-cli-CCKUIm0S.svg} +2 -2
  635. package/codeyam-cli/src/webserver/build/client/assets/cy-logo-cli-DcX-ZS3p.js +1 -0
  636. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-JTAjQ54M.js +1 -0
  637. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-CYqBrC9s.js → entity._sha._-B0h9AqE6.js} +22 -15
  638. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-DjLxr2JB.js +6 -0
  639. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-CtYowLOt.js +6 -0
  640. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-PePWg17F.js +5 -0
  641. package/codeyam-cli/src/webserver/build/client/assets/entry.client-I-Wo99C_.js +29 -0
  642. package/codeyam-cli/src/webserver/build/client/assets/executionFlowCoverage-BWhdfn70.js +1 -0
  643. package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-9sMMAiWJ.js +1 -0
  644. package/codeyam-cli/src/webserver/build/client/assets/files-Co65J0s3.js +1 -0
  645. package/codeyam-cli/src/webserver/build/client/assets/git-BdHOxVfg.js +15 -0
  646. package/codeyam-cli/src/webserver/build/client/assets/globals-Dzl-jeq-.css +1 -0
  647. package/codeyam-cli/src/webserver/build/client/assets/html2canvas-pro.esm-fmIEn3Bc.js +9 -0
  648. package/codeyam-cli/src/webserver/build/client/assets/index-CUM5iXwc.js +9 -0
  649. package/codeyam-cli/src/webserver/build/client/assets/index-_417gcQW.js +3 -0
  650. package/codeyam-cli/src/webserver/build/client/assets/labs-DAvt-sy-.js +1 -0
  651. package/codeyam-cli/src/webserver/build/client/assets/loader-circle-TzRHMVog.js +6 -0
  652. package/codeyam-cli/src/webserver/build/client/assets/manifest-2d0e2ebb.js +1 -0
  653. package/codeyam-cli/src/webserver/build/client/assets/memory-DVGtTawo.js +92 -0
  654. package/codeyam-cli/src/webserver/build/client/assets/pause-hjzB7t2z.js +11 -0
  655. package/codeyam-cli/src/webserver/build/client/assets/preload-helper-ckwbz45p.js +1 -0
  656. package/codeyam-cli/src/webserver/build/client/assets/root-Bg3WICdl.js +62 -0
  657. package/codeyam-cli/src/webserver/build/client/assets/scenarioStatus-B_8jpV3e.js +1 -0
  658. package/codeyam-cli/src/webserver/build/client/assets/search-DcAwD_Ln.js +6 -0
  659. package/codeyam-cli/src/webserver/build/client/assets/settings-CclxrcPK.js +1 -0
  660. package/codeyam-cli/src/webserver/build/client/assets/simulations-DVNJVQgD.js +1 -0
  661. package/codeyam-cli/src/webserver/build/client/assets/terminal-DbEAHMbA.js +11 -0
  662. package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-CAD5b1o_.js +6 -0
  663. package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-BqgrAzs3.js +1 -0
  664. package/codeyam-cli/src/webserver/build/client/assets/{useLastLogLine-Blr5oZDE.js → useLastLogLine-DAFqfEDH.js} +1 -1
  665. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-DZlYx2c4.js +1 -0
  666. package/codeyam-cli/src/webserver/build/client/assets/{useToast-Bbf4Hokd.js → useToast-ihdMtlf6.js} +1 -1
  667. package/codeyam-cli/src/webserver/build/server/assets/index-CpreP2n8.js +1 -0
  668. package/codeyam-cli/src/webserver/build/server/assets/server-build-DyvoFrHR.js +273 -0
  669. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  670. package/codeyam-cli/src/webserver/build-info.json +5 -5
  671. package/codeyam-cli/src/webserver/devServer.js +1 -3
  672. package/codeyam-cli/src/webserver/devServer.js.map +1 -1
  673. package/codeyam-cli/src/webserver/server.js +35 -25
  674. package/codeyam-cli/src/webserver/server.js.map +1 -1
  675. package/codeyam-cli/templates/{codeyam-debug-skill.md → codeyam-debug.md} +48 -4
  676. package/codeyam-cli/templates/codeyam-diagnose.md +481 -0
  677. package/codeyam-cli/templates/codeyam-memory-hook.sh +199 -0
  678. package/codeyam-cli/templates/codeyam-memory.md +396 -0
  679. package/codeyam-cli/templates/codeyam-new-rule.md +13 -0
  680. package/codeyam-cli/templates/{codeyam-setup-skill.md → codeyam-setup.md} +151 -4
  681. package/codeyam-cli/templates/{codeyam-sim-skill.md → codeyam-sim.md} +1 -1
  682. package/codeyam-cli/templates/{codeyam-test-skill.md → codeyam-test.md} +1 -1
  683. package/codeyam-cli/templates/{codeyam-verify-skill.md → codeyam-verify.md} +1 -1
  684. package/codeyam-cli/templates/rule-notification-hook.py +56 -0
  685. package/codeyam-cli/templates/rule-reflection-hook.py +627 -0
  686. package/codeyam-cli/templates/rules-instructions.md +132 -0
  687. package/package.json +26 -23
  688. package/packages/ai/index.js +8 -6
  689. package/packages/ai/index.js.map +1 -1
  690. package/packages/ai/src/lib/analyzeScope.js +181 -13
  691. package/packages/ai/src/lib/analyzeScope.js.map +1 -1
  692. package/packages/ai/src/lib/astScopes/arrayDerivationDetector.js +150 -0
  693. package/packages/ai/src/lib/astScopes/arrayDerivationDetector.js.map +1 -0
  694. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js +154 -9
  695. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js.map +1 -1
  696. package/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.js +435 -0
  697. package/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.js.map +1 -0
  698. package/packages/ai/src/lib/astScopes/methodSemantics.js +138 -23
  699. package/packages/ai/src/lib/astScopes/methodSemantics.js.map +1 -1
  700. package/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.js +10 -14
  701. package/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.js.map +1 -1
  702. package/packages/ai/src/lib/astScopes/patterns/ifStatementHandler.js +8 -0
  703. package/packages/ai/src/lib/astScopes/patterns/ifStatementHandler.js.map +1 -1
  704. package/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.js +23 -0
  705. package/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.js.map +1 -1
  706. package/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.js +138 -1
  707. package/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.js.map +1 -1
  708. package/packages/ai/src/lib/astScopes/processExpression.js +1235 -104
  709. package/packages/ai/src/lib/astScopes/processExpression.js.map +1 -1
  710. package/packages/ai/src/lib/astScopes/sharedPatterns.js +25 -0
  711. package/packages/ai/src/lib/astScopes/sharedPatterns.js.map +1 -1
  712. package/packages/ai/src/lib/checkAllAttributes.js +24 -9
  713. package/packages/ai/src/lib/checkAllAttributes.js.map +1 -1
  714. package/packages/ai/src/lib/completionCall.js +178 -31
  715. package/packages/ai/src/lib/completionCall.js.map +1 -1
  716. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +2171 -224
  717. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
  718. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js +19 -4
  719. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js.map +1 -1
  720. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js +661 -0
  721. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js.map +1 -0
  722. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js +180 -56
  723. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js.map +1 -1
  724. package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js +13 -3
  725. package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js.map +1 -1
  726. package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js +6 -4
  727. package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js.map +1 -1
  728. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js +66 -2
  729. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js.map +1 -1
  730. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js +139 -13
  731. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js.map +1 -1
  732. package/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.js +63 -0
  733. package/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.js.map +1 -0
  734. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js +142 -12
  735. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js.map +1 -1
  736. package/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.js +86 -0
  737. package/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.js.map +1 -0
  738. package/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.js +173 -0
  739. package/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.js.map +1 -0
  740. package/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.js +37 -20
  741. package/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.js.map +1 -1
  742. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js +371 -73
  743. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js.map +1 -1
  744. package/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.js +107 -0
  745. package/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.js.map +1 -0
  746. package/packages/ai/src/lib/dataStructureChunking.js +130 -0
  747. package/packages/ai/src/lib/dataStructureChunking.js.map +1 -0
  748. package/packages/ai/src/lib/deepEqual.js +32 -0
  749. package/packages/ai/src/lib/deepEqual.js.map +1 -0
  750. package/packages/ai/src/lib/e2eDataTracking.js +241 -0
  751. package/packages/ai/src/lib/e2eDataTracking.js.map +1 -0
  752. package/packages/ai/src/lib/extractCriticalDataKeys.js +96 -0
  753. package/packages/ai/src/lib/extractCriticalDataKeys.js.map +1 -0
  754. package/packages/ai/src/lib/generateChangesEntityScenarioData.js +62 -5
  755. package/packages/ai/src/lib/generateChangesEntityScenarioData.js.map +1 -1
  756. package/packages/ai/src/lib/generateChangesEntityScenarios.js +81 -90
  757. package/packages/ai/src/lib/generateChangesEntityScenarios.js.map +1 -1
  758. package/packages/ai/src/lib/generateEntityDataStructure.js +50 -1
  759. package/packages/ai/src/lib/generateEntityDataStructure.js.map +1 -1
  760. package/packages/ai/src/lib/generateEntityScenarioData.js +1127 -91
  761. package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
  762. package/packages/ai/src/lib/generateEntityScenarios.js +193 -83
  763. package/packages/ai/src/lib/generateEntityScenarios.js.map +1 -1
  764. package/packages/ai/src/lib/generateExecutionFlows.js +495 -0
  765. package/packages/ai/src/lib/generateExecutionFlows.js.map +1 -0
  766. package/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.js +380 -0
  767. package/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.js.map +1 -0
  768. package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js +1807 -0
  769. package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js.map +1 -0
  770. package/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.js +194 -0
  771. package/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.js.map +1 -0
  772. package/packages/ai/src/lib/getConditionalUsagesFromCode.js +84 -14
  773. package/packages/ai/src/lib/getConditionalUsagesFromCode.js.map +1 -1
  774. package/packages/ai/src/lib/guessScenarioDataFromDescription.js +2 -1
  775. package/packages/ai/src/lib/guessScenarioDataFromDescription.js.map +1 -1
  776. package/packages/ai/src/lib/isolateScopes.js +270 -7
  777. package/packages/ai/src/lib/isolateScopes.js.map +1 -1
  778. package/packages/ai/src/lib/mergeJsonTypeDefinitions.js +5 -0
  779. package/packages/ai/src/lib/mergeJsonTypeDefinitions.js.map +1 -1
  780. package/packages/ai/src/lib/mergeStatements.js +88 -46
  781. package/packages/ai/src/lib/mergeStatements.js.map +1 -1
  782. package/packages/ai/src/lib/promptGenerators/collapseNullableObjects.js +97 -0
  783. package/packages/ai/src/lib/promptGenerators/collapseNullableObjects.js.map +1 -0
  784. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js +16 -4
  785. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js.map +1 -1
  786. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js +1 -1
  787. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js.map +1 -1
  788. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js +21 -64
  789. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js.map +1 -1
  790. package/packages/ai/src/lib/promptGenerators/generateChunkPrompt.js +54 -0
  791. package/packages/ai/src/lib/promptGenerators/generateChunkPrompt.js.map +1 -0
  792. package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js +83 -6
  793. package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js.map +1 -1
  794. package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js +10 -34
  795. package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js.map +1 -1
  796. package/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.js +45 -0
  797. package/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.js.map +1 -0
  798. package/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.js +16 -3
  799. package/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.js.map +1 -1
  800. package/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.js +335 -0
  801. package/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.js.map +1 -0
  802. package/packages/ai/src/lib/resolvePathToControllable.js +677 -0
  803. package/packages/ai/src/lib/resolvePathToControllable.js.map +1 -0
  804. package/packages/ai/src/lib/splitOutsideParentheses.js +3 -1
  805. package/packages/ai/src/lib/splitOutsideParentheses.js.map +1 -1
  806. package/packages/ai/src/lib/worker/SerializableDataStructure.js +29 -0
  807. package/packages/ai/src/lib/worker/SerializableDataStructure.js.map +1 -1
  808. package/packages/ai/src/lib/worker/analyzeScopeWorker.js +98 -1
  809. package/packages/ai/src/lib/worker/analyzeScopeWorker.js.map +1 -1
  810. package/packages/analyze/index.js +1 -0
  811. package/packages/analyze/index.js.map +1 -1
  812. package/packages/analyze/src/lib/FileAnalyzer.js +75 -36
  813. package/packages/analyze/src/lib/FileAnalyzer.js.map +1 -1
  814. package/packages/analyze/src/lib/ProjectAnalyzer.js +96 -26
  815. package/packages/analyze/src/lib/ProjectAnalyzer.js.map +1 -1
  816. package/packages/analyze/src/lib/analysisContext.js +30 -5
  817. package/packages/analyze/src/lib/analysisContext.js.map +1 -1
  818. package/packages/analyze/src/lib/asts/nodes/getNodeType.js +1 -0
  819. package/packages/analyze/src/lib/asts/nodes/getNodeType.js.map +1 -1
  820. package/packages/analyze/src/lib/asts/nodes/index.js +1 -0
  821. package/packages/analyze/src/lib/asts/nodes/index.js.map +1 -1
  822. package/packages/analyze/src/lib/asts/nodes/isAsyncFunction.js +52 -0
  823. package/packages/analyze/src/lib/asts/nodes/isAsyncFunction.js.map +1 -0
  824. package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js +14 -0
  825. package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js.map +1 -1
  826. package/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.js +14 -0
  827. package/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.js.map +1 -1
  828. package/packages/analyze/src/lib/asts/sourceFiles/getAllExports.js +6 -0
  829. package/packages/analyze/src/lib/asts/sourceFiles/getAllExports.js.map +1 -1
  830. package/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.js +6 -0
  831. package/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.js.map +1 -1
  832. package/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.js +39 -1
  833. package/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.js.map +1 -1
  834. package/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.js +2 -1
  835. package/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.js.map +1 -1
  836. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +428 -123
  837. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
  838. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +42 -1
  839. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
  840. package/packages/analyze/src/lib/files/analyze/dependencyResolver.js +5 -0
  841. package/packages/analyze/src/lib/files/analyze/dependencyResolver.js.map +1 -1
  842. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js +2 -0
  843. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js.map +1 -1
  844. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js +2 -1
  845. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js.map +1 -1
  846. package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js +31 -10
  847. package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js.map +1 -1
  848. package/packages/analyze/src/lib/files/analyzeChange.js +21 -11
  849. package/packages/analyze/src/lib/files/analyzeChange.js.map +1 -1
  850. package/packages/analyze/src/lib/files/analyzeEntity.js +9 -8
  851. package/packages/analyze/src/lib/files/analyzeEntity.js.map +1 -1
  852. package/packages/analyze/src/lib/files/analyzeInitial.js +9 -10
  853. package/packages/analyze/src/lib/files/analyzeInitial.js.map +1 -1
  854. package/packages/analyze/src/lib/files/analyzeRemixRoute.js +3 -2
  855. package/packages/analyze/src/lib/files/analyzeRemixRoute.js.map +1 -1
  856. package/packages/analyze/src/lib/files/enums/steps.js +1 -1
  857. package/packages/analyze/src/lib/files/enums/steps.js.map +1 -1
  858. package/packages/analyze/src/lib/files/getImportedExports.js +17 -8
  859. package/packages/analyze/src/lib/files/getImportedExports.js.map +1 -1
  860. package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js +880 -0
  861. package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js.map +1 -0
  862. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js +255 -0
  863. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js.map +1 -0
  864. package/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.js +85 -0
  865. package/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.js.map +1 -0
  866. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js +550 -62
  867. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js.map +1 -1
  868. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.js +1 -1
  869. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.js.map +1 -1
  870. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.js +29 -34
  871. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.js.map +1 -1
  872. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +404 -85
  873. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
  874. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js +144 -0
  875. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js.map +1 -0
  876. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js +56 -69
  877. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js.map +1 -1
  878. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js +4 -8
  879. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js.map +1 -1
  880. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +875 -141
  881. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
  882. package/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.js +46 -9
  883. package/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.js.map +1 -1
  884. package/packages/analyze/src/lib/files/setImportedExports.js +2 -1
  885. package/packages/analyze/src/lib/files/setImportedExports.js.map +1 -1
  886. package/packages/analyze/src/lib/index.js +1 -0
  887. package/packages/analyze/src/lib/index.js.map +1 -1
  888. package/packages/analyze/src/lib/utils/getFileByPath.js +12 -0
  889. package/packages/analyze/src/lib/utils/getFileByPath.js.map +1 -0
  890. package/packages/aws/src/lib/ecs/ecsDefineContainer.js +2 -2
  891. package/packages/aws/src/lib/ecs/ecsDefineContainer.js.map +1 -1
  892. package/packages/aws/src/lib/ecs/ecsTaskFactory.js +17 -61
  893. package/packages/aws/src/lib/ecs/ecsTaskFactory.js.map +1 -1
  894. package/packages/database/src/lib/analysisBranchToDb.js +1 -1
  895. package/packages/database/src/lib/analysisBranchToDb.js.map +1 -1
  896. package/packages/database/src/lib/analysisToDb.js +1 -1
  897. package/packages/database/src/lib/analysisToDb.js.map +1 -1
  898. package/packages/database/src/lib/branchToDb.js +1 -1
  899. package/packages/database/src/lib/branchToDb.js.map +1 -1
  900. package/packages/database/src/lib/commitBranchToDb.js +1 -1
  901. package/packages/database/src/lib/commitBranchToDb.js.map +1 -1
  902. package/packages/database/src/lib/commitToDb.js +1 -1
  903. package/packages/database/src/lib/commitToDb.js.map +1 -1
  904. package/packages/database/src/lib/fileToDb.js +1 -1
  905. package/packages/database/src/lib/fileToDb.js.map +1 -1
  906. package/packages/database/src/lib/kysely/db.js +13 -3
  907. package/packages/database/src/lib/kysely/db.js.map +1 -1
  908. package/packages/database/src/lib/kysely/tables/commitsTable.js +3 -0
  909. package/packages/database/src/lib/kysely/tables/commitsTable.js.map +1 -1
  910. package/packages/database/src/lib/kysely/tables/debugReportsTable.js +9 -3
  911. package/packages/database/src/lib/kysely/tables/debugReportsTable.js.map +1 -1
  912. package/packages/database/src/lib/kysely/tables/labsRequestsTable.js +35 -0
  913. package/packages/database/src/lib/kysely/tables/labsRequestsTable.js.map +1 -0
  914. package/packages/database/src/lib/loadAnalyses.js +45 -2
  915. package/packages/database/src/lib/loadAnalyses.js.map +1 -1
  916. package/packages/database/src/lib/loadAnalysis.js +8 -0
  917. package/packages/database/src/lib/loadAnalysis.js.map +1 -1
  918. package/packages/database/src/lib/loadBranch.js +11 -1
  919. package/packages/database/src/lib/loadBranch.js.map +1 -1
  920. package/packages/database/src/lib/loadCommit.js +7 -0
  921. package/packages/database/src/lib/loadCommit.js.map +1 -1
  922. package/packages/database/src/lib/loadCommits.js +22 -1
  923. package/packages/database/src/lib/loadCommits.js.map +1 -1
  924. package/packages/database/src/lib/loadEntities.js +23 -4
  925. package/packages/database/src/lib/loadEntities.js.map +1 -1
  926. package/packages/database/src/lib/loadEntityBranches.js +9 -0
  927. package/packages/database/src/lib/loadEntityBranches.js.map +1 -1
  928. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js +23 -5
  929. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
  930. package/packages/database/src/lib/projectToDb.js +1 -1
  931. package/packages/database/src/lib/projectToDb.js.map +1 -1
  932. package/packages/database/src/lib/saveFiles.js +1 -1
  933. package/packages/database/src/lib/saveFiles.js.map +1 -1
  934. package/packages/database/src/lib/scenarioToDb.js +1 -1
  935. package/packages/database/src/lib/scenarioToDb.js.map +1 -1
  936. package/packages/database/src/lib/updateCommitMetadata.js +5 -4
  937. package/packages/database/src/lib/updateCommitMetadata.js.map +1 -1
  938. package/packages/generate/index.js +3 -0
  939. package/packages/generate/index.js.map +1 -1
  940. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +16 -1
  941. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
  942. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +189 -0
  943. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -0
  944. package/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js +53 -0
  945. package/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js.map +1 -0
  946. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +8 -4
  947. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
  948. package/packages/generate/src/lib/deepMerge.js +27 -1
  949. package/packages/generate/src/lib/deepMerge.js.map +1 -1
  950. package/packages/generate/src/lib/directExecutionScript.js +10 -1
  951. package/packages/generate/src/lib/directExecutionScript.js.map +1 -1
  952. package/packages/generate/src/lib/getComponentScenarioPath.js +7 -3
  953. package/packages/generate/src/lib/getComponentScenarioPath.js.map +1 -1
  954. package/packages/generate/src/lib/scenarioComponentForServer.js +89 -0
  955. package/packages/generate/src/lib/scenarioComponentForServer.js.map +1 -0
  956. package/packages/github/src/lib/loadOrCreateCommit.js +10 -0
  957. package/packages/github/src/lib/loadOrCreateCommit.js.map +1 -1
  958. package/packages/github/src/lib/syncPrimaryBranch.js +3 -0
  959. package/packages/github/src/lib/syncPrimaryBranch.js.map +1 -1
  960. package/packages/process/index.js +3 -0
  961. package/packages/process/index.js.map +1 -0
  962. package/packages/process/src/GlobalProcessManager.js.map +1 -0
  963. package/{background/src/lib/process → packages/process/src}/ProcessManager.js +1 -1
  964. package/packages/process/src/ProcessManager.js.map +1 -0
  965. package/packages/process/src/index.js.map +1 -0
  966. package/packages/process/src/managedExecAsync.js.map +1 -0
  967. package/packages/types/index.js.map +1 -1
  968. package/packages/utils/src/lib/applyUniversalMocks.js +26 -2
  969. package/packages/utils/src/lib/applyUniversalMocks.js.map +1 -1
  970. package/packages/utils/src/lib/fs/rsyncCopy.js +98 -3
  971. package/packages/utils/src/lib/fs/rsyncCopy.js.map +1 -1
  972. package/packages/utils/src/lib/lightweightEntityExtractor.js +25 -0
  973. package/packages/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
  974. package/packages/utils/src/lib/safeFileName.js +29 -3
  975. package/packages/utils/src/lib/safeFileName.js.map +1 -1
  976. package/scripts/finalize-analyzer.cjs +8 -74
  977. package/analyzer-template/packages/ai/src/lib/findMatchingAttribute.ts +0 -102
  978. package/analyzer-template/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.ts +0 -197
  979. package/analyzer-template/packages/ai/src/lib/generateChangesEntityKeyAttributes.ts +0 -271
  980. package/analyzer-template/packages/ai/src/lib/generateEntityKeyAttributes.ts +0 -294
  981. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.ts +0 -67
  982. package/analyzer-template/packages/ai/src/lib/transformMockDataToMatchSchema.ts +0 -156
  983. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.ts +0 -115
  984. package/analyzer-template/process/INTEGRATION_COMPLETE.md +0 -333
  985. package/analyzer-template/process/INTEGRATION_EXAMPLE.md +0 -525
  986. package/analyzer-template/process/README.md +0 -507
  987. package/background/src/lib/process/GlobalProcessManager.js.map +0 -1
  988. package/background/src/lib/process/ProcessManager.js.map +0 -1
  989. package/background/src/lib/process/index.js.map +0 -1
  990. package/background/src/lib/process/managedExecAsync.js.map +0 -1
  991. package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js +0 -238
  992. package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js.map +0 -1
  993. package/codeyam-cli/src/webserver/build/client/assets/EntityItem-D4htqD-x.js +0 -1
  994. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-Catz6XEN.js +0 -1
  995. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-TlHocYno.js +0 -26
  996. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-CVMmGuIc.js +0 -3
  997. package/codeyam-cli/src/webserver/build/client/assets/LogViewer-JkfQ-VaI.js +0 -3
  998. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-CVZ0H4BL.js +0 -1
  999. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-BrMAP1nP.js +0 -1
  1000. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-CJhE4cCv.js +0 -5
  1001. package/codeyam-cli/src/webserver/build/client/assets/_index-faVIcr_i.js +0 -1
  1002. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-CLMa2sgx.js +0 -7
  1003. package/codeyam-cli/src/webserver/build/client/assets/chevron-down-DwYjrK_h.js +0 -1
  1004. package/codeyam-cli/src/webserver/build/client/assets/chunk-WWGJGFF6-CgXbbZRx.js +0 -26
  1005. package/codeyam-cli/src/webserver/build/client/assets/circle-check-B2oHQ-zo.js +0 -1
  1006. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-BBYuR56H.js +0 -1
  1007. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-CT0Q5lVu.js +0 -1
  1008. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-Bj5GHkhb.js +0 -1
  1009. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-eW5z9AyZ.js +0 -5
  1010. package/codeyam-cli/src/webserver/build/client/assets/entry.client-B9tSboXM.js +0 -5
  1011. package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-CmO-EZAB.js +0 -1
  1012. package/codeyam-cli/src/webserver/build/client/assets/files-DLinnTOx.js +0 -1
  1013. package/codeyam-cli/src/webserver/build/client/assets/git-CIxwBQvb.js +0 -12
  1014. package/codeyam-cli/src/webserver/build/client/assets/globals-xPz593l2.css +0 -1
  1015. package/codeyam-cli/src/webserver/build/client/assets/html2canvas-pro.esm-XQCGvadH.js +0 -5
  1016. package/codeyam-cli/src/webserver/build/client/assets/index-_LjBsTxX.js +0 -8
  1017. package/codeyam-cli/src/webserver/build/client/assets/loader-circle-D_EGChhq.js +0 -1
  1018. package/codeyam-cli/src/webserver/build/client/assets/manifest-ca438c41.js +0 -1
  1019. package/codeyam-cli/src/webserver/build/client/assets/root-CHHYHuzL.js +0 -16
  1020. package/codeyam-cli/src/webserver/build/client/assets/search-DY8yoDpH.js +0 -1
  1021. package/codeyam-cli/src/webserver/build/client/assets/server-build-CMKNK2uU.css +0 -1
  1022. package/codeyam-cli/src/webserver/build/client/assets/settings-BT6wVHd5.js +0 -1
  1023. package/codeyam-cli/src/webserver/build/client/assets/simulations-gv3H7JV7.js +0 -1
  1024. package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-BthANBVv.js +0 -1
  1025. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-CANr3QJ5.js +0 -1
  1026. package/codeyam-cli/src/webserver/build/server/assets/index-BtBPtyHx.js +0 -1
  1027. package/codeyam-cli/src/webserver/build/server/assets/server-build-N2cTnejq.js +0 -166
  1028. package/codeyam-cli/templates/debug-command.md +0 -141
  1029. package/packages/ai/src/lib/findMatchingAttribute.js +0 -77
  1030. package/packages/ai/src/lib/findMatchingAttribute.js.map +0 -1
  1031. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js +0 -136
  1032. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js.map +0 -1
  1033. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js +0 -220
  1034. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js.map +0 -1
  1035. package/packages/ai/src/lib/generateEntityKeyAttributes.js +0 -241
  1036. package/packages/ai/src/lib/generateEntityKeyAttributes.js.map +0 -1
  1037. package/packages/ai/src/lib/isFrontend.js +0 -5
  1038. package/packages/ai/src/lib/isFrontend.js.map +0 -1
  1039. package/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.js +0 -40
  1040. package/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.js.map +0 -1
  1041. package/packages/ai/src/lib/transformMockDataToMatchSchema.js +0 -124
  1042. package/packages/ai/src/lib/transformMockDataToMatchSchema.js.map +0 -1
  1043. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js +0 -72
  1044. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js.map +0 -1
  1045. /package/analyzer-template/{process → packages/process/src}/GlobalProcessManager.ts +0 -0
  1046. /package/analyzer-template/{process → packages/process/src}/ProcessManager.ts +0 -0
  1047. /package/analyzer-template/{process → packages/process/src}/index.ts +0 -0
  1048. /package/analyzer-template/{process → packages/process/src}/managedExecAsync.ts +0 -0
  1049. /package/codeyam-cli/src/webserver/build/client/assets/{InteractivePreview-CMKNK2uU.css → styles-CMKNK2uU.css} +0 -0
  1050. /package/{background/src/lib/process → packages/process/src}/GlobalProcessManager.js +0 -0
  1051. /package/{background/src/lib/process → packages/process/src}/index.js +0 -0
  1052. /package/{background/src/lib/process → packages/process/src}/managedExecAsync.js +0 -0
@@ -25,6 +25,68 @@ import * as fs from 'fs';
25
25
  import * as path from 'path';
26
26
  import ts from 'typescript';
27
27
  import { LazyFileStore } from './LazyFileStore';
28
+ import { applyServerOnlyMocks } from './serverOnlyModules';
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
+ }
28
90
 
29
91
  /**
30
92
  * Find the end position of the last import/export-from statement using TypeScript AST.
@@ -35,11 +97,15 @@ import { LazyFileStore } from './LazyFileStore';
35
97
  */
36
98
  function findEndOfImports(content: string): number {
37
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.
38
103
  const sourceFile = ts.createSourceFile(
39
- 'temp.ts',
104
+ 'temp.tsx',
40
105
  content,
41
106
  ts.ScriptTarget.Latest,
42
107
  true,
108
+ ts.ScriptKind.TSX,
43
109
  );
44
110
 
45
111
  let lastImportEnd = 0;
@@ -74,6 +140,125 @@ function escapeRegExp(str: string): string {
74
140
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
75
141
  }
76
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
+
77
262
  /**
78
263
  * Map nested dist paths to src paths.
79
264
  * Some build tools create nested structures like:
@@ -263,10 +448,6 @@ function convertDtsToStubs(content: string, entityName: string): string {
263
448
  // Keep export type and export interface statements as-is (they're valid in .ts)
264
449
  // No transformation needed for these
265
450
 
266
- console.log(
267
- `CodeYam: Converted .d.ts content for entity "${entityName}". Result length: ${result.length}`,
268
- );
269
-
270
451
  return result;
271
452
  }
272
453
 
@@ -452,10 +633,6 @@ function stripHtmlBodyTags(
452
633
  return fileContent;
453
634
  }
454
635
 
455
- console.log(
456
- `CodeYam: Stripping <html> and <body> tags from root layout: ${filePath}`,
457
- );
458
-
459
636
  // Extract the body className/attributes if any, to preserve styling
460
637
  const bodyMatch = fileContent.match(/<body([^>]*)>/);
461
638
  const bodyAttributes = bodyMatch?.[1]?.trim() || '';
@@ -501,8 +678,171 @@ function stripHtmlBodyTags(
501
678
  return result;
502
679
  }
503
680
 
681
+ /**
682
+ * Strip `import "server-only"` or `import 'server-only'` directives from file content.
683
+ *
684
+ * Next.js "server-only" package is used to mark modules that should only run on the server.
685
+ * When we generate scenario components for client-side rendering in the browser, importing
686
+ * a file with this directive causes an error:
687
+ *
688
+ * "You're importing a component that needs 'server-only'. That only works in a Server Component"
689
+ *
690
+ * Since our scenario components are rendered client-side for capture purposes, we need to
691
+ * strip this import to allow the file to be imported.
692
+ */
693
+ function stripServerOnlyImport(fileContent: string): string {
694
+ // Match import "server-only" or import 'server-only' with optional semicolon and newline
695
+ // Handles both double and single quotes, with or without trailing semicolon
696
+ return fileContent.replace(/import\s+["']server-only["'];?\s*\n?/g, '');
697
+ }
698
+
699
+ /**
700
+ * Extract all internal import paths from file content.
701
+ * Internal imports are those that start with '.', '@/', '~/', or are relative paths.
702
+ * Excludes node_modules imports (bare specifiers like 'react', '@prisma/client').
703
+ */
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[] {
714
+ const importPaths: string[] = [];
715
+
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
+ }
742
+ }
743
+ } catch (error) {
744
+ console.warn(
745
+ '[extractInternalImportPathsAst] Failed to parse file:',
746
+ error,
747
+ );
748
+ }
749
+
750
+ return importPaths;
751
+ }
752
+
753
+ /**
754
+ * Resolve an import path to a file path relative to the project.
755
+ * Handles path aliases like @/, ~/, and relative paths.
756
+ */
757
+ function resolveImportPath(
758
+ importPath: string,
759
+ currentFilePath: string,
760
+ project: Project,
761
+ ): string | null {
762
+ let resolvedPath: string;
763
+ let appPrefix = '';
764
+
765
+ if (importPath.startsWith('./') || importPath.startsWith('../')) {
766
+ // Relative import - resolve relative to current file
767
+ const currentDir = currentFilePath.split('/').slice(0, -1).join('/');
768
+ const parts = [...currentDir.split('/'), ...importPath.split('/')];
769
+ const resolved: string[] = [];
770
+
771
+ for (const part of parts) {
772
+ if (part === '..') {
773
+ resolved.pop();
774
+ } else if (part !== '.' && part !== '') {
775
+ resolved.push(part);
776
+ }
777
+ }
778
+ resolvedPath = resolved.join('/');
779
+ } else if (importPath.startsWith('@/') || importPath.startsWith('~/')) {
780
+ // Path alias - strip the prefix
781
+ resolvedPath = importPath.slice(2);
782
+
783
+ // Infer app prefix from current file path
784
+ // e.g., if currentFilePath is "apps/web/lib/user/service.ts"
785
+ // and import is "@/modules/auth/lib/brevo", the actual file is at
786
+ // "apps/web/modules/auth/lib/brevo.ts"
787
+ // We detect this by checking if current file starts with "apps/XXX/"
788
+ const appMatch = currentFilePath.match(/^(apps\/[^/]+\/)/);
789
+ if (appMatch) {
790
+ appPrefix = appMatch[1];
791
+ }
792
+ } else if (importPath.startsWith('#')) {
793
+ // Package imports - not supported yet
794
+ return null;
795
+ } else {
796
+ // Unknown format
797
+ return null;
798
+ }
799
+
800
+ // Try to find the file with various extensions
801
+ const extensions = ['', '.ts', '.tsx', '.js', '.jsx'];
802
+
803
+ // First try with app prefix (for monorepo structures like apps/web/)
804
+ if (appPrefix) {
805
+ for (const ext of extensions) {
806
+ const fullPath = appPrefix + resolvedPath + ext;
807
+ const file = project.files?.find((f) => f.path === fullPath);
808
+ if (file) {
809
+ return file.path;
810
+ }
811
+ }
812
+
813
+ // Try index files with prefix
814
+ for (const ext of ['.ts', '.tsx', '.js', '.jsx']) {
815
+ const indexPath = `${appPrefix}${resolvedPath}/index${ext}`;
816
+ const file = project.files?.find((f) => f.path === indexPath);
817
+ if (file) {
818
+ return file.path;
819
+ }
820
+ }
821
+ }
822
+
823
+ // Then try without prefix (for simpler project structures)
824
+ for (const ext of extensions) {
825
+ const fullPath = resolvedPath + ext;
826
+ const file = project.files?.find((f) => f.path === fullPath);
827
+ if (file) {
828
+ return file.path;
829
+ }
830
+ }
831
+
832
+ // Try index files
833
+ for (const ext of ['.ts', '.tsx', '.js', '.jsx']) {
834
+ const indexPath = `${resolvedPath}/index${ext}`;
835
+ const file = project.files?.find((f) => f.path === indexPath);
836
+ if (file) {
837
+ return file.path;
838
+ }
839
+ }
840
+
841
+ return null;
842
+ }
843
+
504
844
  // Version for tracking deployments - increment when making changes
505
- const WRITE_SCENARIO_COMPONENTS_VERSION = '2.1.0-ast-based-import-detection';
845
+ const WRITE_SCENARIO_COMPONENTS_VERSION = '2.5.17-configurable-server-mocks';
506
846
 
507
847
  function addMockToContent(
508
848
  fileContent: string,
@@ -513,9 +853,6 @@ function addMockToContent(
513
853
  scenarioName: string,
514
854
  importPath?: string,
515
855
  ) {
516
- console.log(
517
- `CodeYam [v${WRITE_SCENARIO_COMPONENTS_VERSION}]: Adding mock for ${importedExport.name} from ${importedExport.filePath}`,
518
- );
519
856
  // First try to find dependency schemas in fileAnalyses (for same-file dependencies)
520
857
  let dependencySchemas = fileAnalyses.find(
521
858
  (a) =>
@@ -533,49 +870,110 @@ function addMockToContent(
533
870
 
534
871
  // Check if we have multiple calls with different variable names
535
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).
536
900
  const hasMultipleCallsWithVariables =
537
- importedExport.calls &&
538
- importedExport.calls.length > 1 &&
901
+ baseHookCalls &&
902
+ baseHookCalls.length > 1 &&
539
903
  importedExport.callVariableNames &&
540
- importedExport.callVariableNames.length === importedExport.calls.length;
541
-
542
- // DEBUG: Log import info for multiple calls debugging
543
- if (
544
- importedExport.name === 'useFetcher' ||
545
- importedExport.name?.includes('Fetcher')
546
- ) {
547
- console.log(
548
- 'CodeYam DEBUG: addMockToContent useFetcher import:',
549
- JSON.stringify(
550
- {
551
- name: importedExport.name,
552
- calls: importedExport.calls,
553
- callVariableNames: importedExport.callVariableNames,
554
- hasMultipleCallsWithVariables,
555
- isMocked: importedExport.isMocked,
556
- },
557
- null,
558
- 2,
559
- ),
560
- );
561
- }
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;
562
909
 
563
910
  let mockCode: string | undefined;
564
911
  const variableMockCodes: string[] = [];
565
912
 
566
913
  if (hasMultipleCallsWithVariables) {
567
914
  // Generate separate mock functions for each variable-qualified call
568
- for (let i = 0; i < importedExport.calls!.length; i++) {
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
930
+ const variableNameCounts: Record<string, number> = {};
931
+
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++) {
569
939
  const variableName = importedExport.callVariableNames![i];
570
940
  if (!variableName) continue;
571
941
 
572
- // Generate mock code for this specific call using variable-qualified name
573
- // Format: "variableName <- functionName" (reads as "variableName receives from functionName")
574
- const qualifiedName = `${variableName} <- ${importedExport.name}`;
942
+ // Calculate the occurrence index for this variable name
943
+ const occurrence = variableNameCounts[variableName] ?? 0;
944
+ variableNameCounts[variableName] = occurrence + 1;
945
+
946
+ // Build indexed variable name for function naming
947
+ const indexedVariableName =
948
+ occurrence > 0 ? `${variableName}[${occurrence}]` : variableName;
949
+
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('@');
575
965
  const variableMockCode = constructMockCode(
576
- qualifiedName,
966
+ callSignature, // Use call signature format for data lookup
577
967
  dependencySchemas,
578
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
+ },
579
977
  );
580
978
 
581
979
  if (variableMockCode) {
@@ -584,18 +982,25 @@ function addMockToContent(
584
982
  // Replace the call site with the variable-specific mock function
585
983
  // e.g., useFetcher<BranchEntityDiffResult>() -> useFetcher_entityDiffFetcher()
586
984
  // e.g., useFetcher() -> useFetcher_reportFetcher()
587
- const callSignature = importedExport.calls![i];
588
985
  // Escape special regex characters in the call signature
589
986
  const escapedCallSignature = callSignature.replace(
590
987
  /[.*+?^${}()|[\]\\]/g,
591
988
  '\\$&',
592
989
  );
593
- // Create regex that matches the call (with optional whitespace variations)
990
+ // Create regex that matches the call (with optional whitespace variations).
991
+ // TypeScript formatters commonly break type parameters across lines, e.g.:
992
+ // useLoaderData<
993
+ // typeof loader
994
+ // >()
995
+ // So we allow optional whitespace around < and > delimiters, not just
996
+ // where whitespace already exists in the call signature string.
594
997
  const callRegex = new RegExp(
595
- escapedCallSignature.replace(/\s+/g, '\\s*'),
596
- 'g',
998
+ escapedCallSignature
999
+ .replace(/\s+/g, '\\s*')
1000
+ .replace(/</g, '\\s*<\\s*')
1001
+ .replace(/>/g, '\\s*>\\s*'),
1002
+ 'gs',
597
1003
  );
598
- const mockFunctionName = `${importedExport.name}_${variableName}`;
599
1004
  fileContent = fileContent.replace(callRegex, `${mockFunctionName}()`);
600
1005
  }
601
1006
  }
@@ -611,61 +1016,172 @@ function addMockToContent(
611
1016
  : undefined;
612
1017
 
613
1018
  if (singleCallVariableName) {
614
- // For single variable assignments, use the variable-qualified key for data lookup
615
- // but keep the original function name (no need for unique function names when there's only one assignment)
616
- const qualifiedKey = `${singleCallVariableName} <- ${importedExport.name}`;
617
- mockCode = `const ${importedExport.name}ReturnValue = scenarios().data()?.["${qualifiedKey}"];
1019
+ // For single variable assignments, use the call signature directly from dataForMocks
1020
+ const dataForMocks =
1021
+ rootAnalysis.metadata?.scenariosDataStructure?.dataForMocks;
1022
+
1023
+ // Find matching call signature key in dataForMocks
1024
+ // IMPORTANT: First try exact match with type parameters (e.g., "useLoaderData<LoaderData>()")
1025
+ // to avoid picking the wrong variant (e.g., "useLoaderData<typeof loader>()" which may
1026
+ // have different properties). Fall back to base name matching only if exact match fails.
1027
+ const hookBaseName = importedExport.name.split(/[<(]/)[0];
1028
+ const expectedKey = importedExport.calls?.[0];
1029
+ let callSignatureKey: string | undefined;
1030
+
1031
+ if (dataForMocks) {
1032
+ const keys = Object.keys(dataForMocks);
1033
+
1034
+ // First try exact match with the expected call signature
1035
+ if (expectedKey && keys.includes(expectedKey)) {
1036
+ callSignatureKey = expectedKey;
1037
+ } else {
1038
+ // Fall back to base name matching
1039
+ callSignatureKey = keys.find((key) => {
1040
+ // Split on ., <, or ( to get the true base name
1041
+ // This handles both "useFlags()" -> "useFlags" and "trpc.useUtils()" -> "trpc"
1042
+ const keyBaseName = key.split(/[.<(]/)[0];
1043
+ return keyBaseName === hookBaseName;
1044
+ });
1045
+ }
1046
+ }
618
1047
 
619
- function ${importedExport.name}() {
620
- return ${importedExport.name}ReturnValue;
1048
+ // Use the call signature if found, otherwise construct it
1049
+ const dataKey =
1050
+ callSignatureKey ??
1051
+ importedExport.calls?.[0] ??
1052
+ `${importedExport.name}()`;
1053
+
1054
+ // IMPORTANT: If the dataKey is a method chain (e.g., "trpc.useUtils()"), we should
1055
+ // use the base name (e.g., "trpc") when calling constructMockCode. This ensures
1056
+ // constructMockCode generates a complete nested mock from the schema without
1057
+ // referencing __cyOriginal variables.
1058
+ const dataKeyBaseName = dataKey.split(/[.<(]/)[0];
1059
+ const isMethodChainDataKey =
1060
+ dataKeyBaseName === importedExport.name &&
1061
+ dataKey !== importedExport.name &&
1062
+ dataKey.includes('.');
1063
+ const mockNameToUse = isMethodChainDataKey
1064
+ ? importedExport.name
1065
+ : dataKey;
1066
+
1067
+ // Keep the original function name since there's only one call
1068
+ // Check if this is a package import that won't have scenario copies
1069
+ const isPackageImportForSingleCall = importPath?.startsWith('@');
1070
+ mockCode = constructMockCode(
1071
+ mockNameToUse,
1072
+ dependencySchemas,
1073
+ importedExport.entityType,
1074
+ undefined,
1075
+ {
1076
+ keepOriginalFunctionName: true,
1077
+ // For node_modules or package imports, skip spreading from __cyOriginal
1078
+ // since those packages/files don't export *__cyOriginal variants
1079
+ skipOriginalSpread:
1080
+ importedExport.isNodeModule || isPackageImportForSingleCall,
1081
+ },
1082
+ );
1083
+ // If constructMockCode didn't generate code, fall back to simple return
1084
+ // IMPORTANT: We inline scenarios().data() inside the function rather than
1085
+ // storing in a const - see comment in constructMockCode.ts for why.
1086
+ if (!mockCode) {
1087
+ mockCode = `// PATCHED: memoize to return stable reference (prevents infinite useEffect re-triggers)
1088
+ const _${importedExport.name}Ref = {
1089
+ current: null,
1090
+ };
1091
+ function ${importedExport.name}(...args) {
1092
+ if (!_${importedExport.name}Ref.current) {
1093
+ _${importedExport.name}Ref.current = scenarios().data()?.["${dataKey}"];
1094
+ }
1095
+ return _${importedExport.name}Ref.current;
621
1096
  }`;
1097
+ }
622
1098
  } else {
623
- // Check if any analysis (fileAnalyses or rootAnalysis) has this function's data
624
- // under a variable-qualified key. The entity that CALLS the function (e.g., FileTableRow)
625
- // has the dataForMocks with the variable-qualified key, not the root analysis (e.g., GitView).
626
- let variableQualifiedKey: string | undefined;
627
-
628
- // First check fileAnalyses (the analyses for the entity being written)
629
- for (const analysis of fileAnalyses) {
630
- const dataForMocks =
631
- analysis.metadata?.scenariosDataStructure?.dataForMocks;
632
- if (dataForMocks) {
633
- variableQualifiedKey = Object.keys(dataForMocks).find((key) => {
634
- const match = key.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\s*<-\s*(.+)$/);
635
- return match && match[2] === importedExport.name;
636
- });
637
- if (variableQualifiedKey) {
638
- break;
639
- }
1099
+ // Helper to find matching call signature key from dataForMocks
1100
+ // IMPORTANT: First try exact match with type parameters (e.g., "useLoaderData<LoaderData>()")
1101
+ // to avoid picking the wrong variant. Fall back to base name matching only if needed.
1102
+ const hookBaseName = importedExport.name.split(/[<(]/)[0];
1103
+ const expectedKey = importedExport.calls?.[0];
1104
+ const findMatchingKey = (
1105
+ dataForMocks: Record<string, unknown> | undefined,
1106
+ ): string | undefined => {
1107
+ if (!dataForMocks) return undefined;
1108
+ const keys = Object.keys(dataForMocks);
1109
+
1110
+ // First try exact match with the expected call signature
1111
+ if (expectedKey && keys.includes(expectedKey)) {
1112
+ return expectedKey;
640
1113
  }
641
- }
642
1114
 
643
- // If not found in fileAnalyses, fall back to rootAnalysis
644
- if (!variableQualifiedKey) {
645
- const dataForMocks =
646
- rootAnalysis.metadata?.scenariosDataStructure?.dataForMocks;
647
- if (dataForMocks) {
648
- variableQualifiedKey = Object.keys(dataForMocks).find((key) => {
649
- const match = key.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\s*<-\s*(.+)$/);
650
- return match && match[2] === importedExport.name;
651
- });
1115
+ // Fall back to base name matching
1116
+ return keys.find((key) => {
1117
+ // Split on ., <, or ( to get the true base name
1118
+ // This handles both "useFlags()" -> "useFlags" and "trpc.useUtils()" -> "trpc"
1119
+ const keyBaseName = key.split(/[.<(]/)[0];
1120
+ return keyBaseName === hookBaseName;
1121
+ });
1122
+ };
1123
+
1124
+ // Check rootAnalysis FIRST for matching keys.
1125
+ // The mock DATA is generated from rootAnalysis, so the mock CODE must
1126
+ // also use rootAnalysis keys to ensure the lookup succeeds.
1127
+ let dataKey = findMatchingKey(
1128
+ rootAnalysis.metadata?.scenariosDataStructure?.dataForMocks,
1129
+ );
1130
+
1131
+ // If not found in rootAnalysis, fall back to fileAnalyses
1132
+ if (!dataKey) {
1133
+ for (const analysis of fileAnalyses) {
1134
+ dataKey = findMatchingKey(
1135
+ analysis.metadata?.scenariosDataStructure?.dataForMocks,
1136
+ );
1137
+ if (dataKey) break;
652
1138
  }
653
1139
  }
654
1140
 
655
- if (variableQualifiedKey) {
656
- // Use the variable-qualified key found in the analysis
657
- mockCode = `const ${importedExport.name}ReturnValue = scenarios().data()?.["${variableQualifiedKey}"];
658
-
659
- function ${importedExport.name}() {
660
- return ${importedExport.name}ReturnValue;
1141
+ // Use the data key if found, otherwise use call signature or function name.
1142
+ // IMPORTANT: If the dataKey is a method chain (e.g., "trpc.useUtils()"), we should
1143
+ // use the base name (e.g., "trpc") when calling constructMockCode. This ensures
1144
+ // constructMockCode generates a complete nested mock from the schema without
1145
+ // referencing __cyOriginal variables. The __cyOriginal pattern is only needed
1146
+ // for partial mocking where we preserve some original methods, not for complete
1147
+ // method-chain mocks where we provide all implementations.
1148
+ const dataKeyBaseName = dataKey?.split(/[.<(]/)[0];
1149
+ const isMethodChainDataKey =
1150
+ dataKey &&
1151
+ dataKeyBaseName === importedExport.name &&
1152
+ dataKey !== importedExport.name &&
1153
+ dataKey.includes('.');
1154
+ const mockNameToUse = isMethodChainDataKey
1155
+ ? importedExport.name
1156
+ : (dataKey ?? importedExport.calls?.[0] ?? `${importedExport.name}()`);
1157
+
1158
+ mockCode = constructMockCode(
1159
+ mockNameToUse,
1160
+ dependencySchemas,
1161
+ importedExport.entityType,
1162
+ undefined,
1163
+ {
1164
+ keepOriginalFunctionName: true,
1165
+ // For node_modules or package imports, skip spreading from __cyOriginal
1166
+ // since those packages/files don't export *__cyOriginal variants
1167
+ skipOriginalSpread:
1168
+ importedExport.isNodeModule || importPath?.startsWith('@'),
1169
+ },
1170
+ );
1171
+ // If constructMockCode didn't generate code, fall back to simple return
1172
+ // IMPORTANT: We inline scenarios().data() inside the function rather than
1173
+ // storing in a const - see comment in constructMockCode.ts for why.
1174
+ if (!mockCode && dataKey) {
1175
+ mockCode = `// PATCHED: memoize to return stable reference (prevents infinite useEffect re-triggers)
1176
+ const _${importedExport.name}Ref = {
1177
+ current: null,
1178
+ };
1179
+ function ${importedExport.name}(...args) {
1180
+ if (!_${importedExport.name}Ref.current) {
1181
+ _${importedExport.name}Ref.current = scenarios().data()?.["${dataKey}"];
1182
+ }
1183
+ return _${importedExport.name}Ref.current;
661
1184
  }`;
662
- } else {
663
- // Original behavior for calls without variable names
664
- mockCode = constructMockCode(
665
- importedExport.name,
666
- dependencySchemas,
667
- importedExport.entityType,
668
- );
669
1185
  }
670
1186
  }
671
1187
  }
@@ -675,35 +1191,6 @@ function ${importedExport.name}() {
675
1191
  variableMockCodes.length > 0 ? variableMockCodes.join('\n\n') : mockCode;
676
1192
 
677
1193
  if (!allMockCodes) {
678
- console.log(
679
- 'CodeYam Error: Mock code not found',
680
- JSON.stringify(
681
- {
682
- importedExportFilePath: importedExport.filePath,
683
- importedExportEntityName: importedExport.name,
684
- hasMultipleCallsWithVariables,
685
- analysisIds: fileAnalyses.map((a) => ({
686
- id: a.id,
687
- filePath: a.filePath,
688
- entityName: a.entityName,
689
- })),
690
- analysisFilePath: fileAnalyses?.[0]?.filePath,
691
- analysisEntityNames: fileAnalyses.map((a) => a.entityName),
692
- dependencySchemas: fileAnalyses.find(
693
- (a) =>
694
- !!a.entity.metadata?.isolatedDataStructure?.dependencySchemas?.[
695
- importedExport.filePath
696
- ]?.[importedExport.name],
697
- )?.entity.metadata?.isolatedDataStructure?.dependencySchemas,
698
- allDependencySchemas: fileAnalyses.map(
699
- (a) => a.entity.metadata?.isolatedDataStructure?.dependencySchemas,
700
- ),
701
- },
702
- null,
703
- 2,
704
- ),
705
- );
706
-
707
1194
  return fileContent;
708
1195
  }
709
1196
 
@@ -725,12 +1212,39 @@ function ${importedExport.name}() {
725
1212
  /[.*+?^${}()|[\]\\]/g,
726
1213
  '\\$&',
727
1214
  );
1215
+ // Use a simpler, more robust regex pattern that matches the fallback path.
1216
+ // Key improvements:
1217
+ // 1. Uses escapeRegExp(firstPart) to handle special characters in function names
1218
+ // 2. Uses word boundaries (\b) to prevent partial matches
1219
+ // 3. Handles comma BEFORE or AFTER the name: (?:,\s*|\s*,)?
1220
+ // 4. Matches specific import path (escapedImportPath)
728
1221
  const importRegExp = new RegExp(
729
- `(import(?:(?!${firstPart}|from|import)[\\s\\S])*?)${firstPart}(?:,\\s*)?((?:(?!import)[\\s\\S])*?from\\s+['"]${escapedImportPath}['"])`,
1222
+ `(import\\s*\\{[^}]*?)\\b${escapeRegExp(firstPart)}\\b(?:,\\s*|\\s*,)?((?:[^}]*\\}\\s*from\\s*['"]${escapedImportPath}['"];?))`,
730
1223
  'm',
731
1224
  );
732
1225
 
733
- if (importedExportNameParts.length > 1) {
1226
+ // Check if any call signature has multiple parts (e.g., "logger.error(error)")
1227
+ // If so, the mock code will spread from __cyOriginal, so we need to rename the import
1228
+ // EXCEPT:
1229
+ // 1. For node_module imports, the __cyOriginal pattern doesn't work because
1230
+ // the original package doesn't export *__cyOriginal variants.
1231
+ // 2. For package imports (starting with @), the __cyOriginal pattern doesn't work
1232
+ // because scenario copies aren't created for package files - they keep the
1233
+ // original import path which doesn't export *__cyOriginal.
1234
+ const anyCallHasMultipleParts = importedExport.calls?.some((call) => {
1235
+ const callParts = splitOutsideParenthesesAndArrays(call);
1236
+ return callParts.length > 1;
1237
+ });
1238
+
1239
+ // Package imports (starting with @) don't get scenario copies, so __cyOriginal won't exist
1240
+ const isPackageImport = importPath.startsWith('@');
1241
+
1242
+ const shouldRenameToOriginal =
1243
+ !importedExport.isNodeModule &&
1244
+ !isPackageImport &&
1245
+ (importedExportNameParts.length > 1 || anyCallHasMultipleParts);
1246
+
1247
+ if (shouldRenameToOriginal) {
734
1248
  fileContent = fileContent.replace(
735
1249
  importRegExp,
736
1250
  `$1${firstPart}__cyOriginal$2`,
@@ -739,6 +1253,21 @@ function ${importedExport.name}() {
739
1253
  fileContent = fileContent.replace(importRegExp, '$1$2');
740
1254
  }
741
1255
 
1256
+ // Also handle namespace imports (import * as foo from '...')
1257
+ // These need to be renamed to foo__cyOriginal when the mock code spreads from the original.
1258
+ // Note: We match any path (not just escapedImportPath) because the import path may have
1259
+ // been rewritten by transitive import handling before this code runs.
1260
+ if (shouldRenameToOriginal) {
1261
+ const namespaceImportRegExp = new RegExp(
1262
+ `(import\\s+\\*\\s+as\\s+)${escapeRegExp(firstPart)}(\\s+from\\s+['"][^'"]*['"])`,
1263
+ 'm',
1264
+ );
1265
+ fileContent = fileContent.replace(
1266
+ namespaceImportRegExp,
1267
+ `$1${firstPart}__cyOriginal$2`,
1268
+ );
1269
+ }
1270
+
742
1271
  // Remove empty imports entirely to avoid partial commenting issues with multiline imports
743
1272
  // This handles both single-line and multiline empty imports
744
1273
  fileContent = fileContent.replace(
@@ -763,7 +1292,20 @@ function ${importedExport.name}() {
763
1292
  'm',
764
1293
  );
765
1294
 
766
- if (importedExportNameParts.length > 1) {
1295
+ // Check if any call signature has multiple parts (e.g., "logger.error(error)")
1296
+ // If so, the mock code will spread from __cyOriginal, so we need to rename the import
1297
+ // EXCEPT: For node_module imports, the __cyOriginal pattern doesn't work because
1298
+ // the original package doesn't export *__cyOriginal variants.
1299
+ const anyCallHasMultipleParts = importedExport.calls?.some((call) => {
1300
+ const callParts = splitOutsideParenthesesAndArrays(call);
1301
+ return callParts.length > 1;
1302
+ });
1303
+
1304
+ const shouldRenameToOriginal =
1305
+ !importedExport.isNodeModule &&
1306
+ (importedExportNameParts.length > 1 || anyCallHasMultipleParts);
1307
+
1308
+ if (shouldRenameToOriginal) {
767
1309
  // Rename the import instead of removing (for destructured access patterns)
768
1310
  fileContent = fileContent.replace(
769
1311
  namedImportRegExp,
@@ -798,18 +1340,12 @@ function ${importedExport.name}() {
798
1340
 
799
1341
  if (lastImportEnd > 0) {
800
1342
  // Insert after the last original import
801
- console.log(
802
- `CodeYam [v${WRITE_SCENARIO_COMPONENTS_VERSION}]: Inserting mock at position ${lastImportEnd} (after imports), not at end`,
803
- );
804
1343
  fileContent =
805
1344
  fileContent.slice(0, lastImportEnd) +
806
1345
  insertContent +
807
1346
  fileContent.slice(lastImportEnd);
808
1347
  } else {
809
1348
  // Fallback: append at end if no imports found
810
- console.log(
811
- `CodeYam [v${WRITE_SCENARIO_COMPONENTS_VERSION}]: No imports found, appending mock at end`,
812
- );
813
1349
  fileContent += insertContent;
814
1350
  }
815
1351
 
@@ -991,6 +1527,15 @@ export default async function writeScenarioComponents({
991
1527
  scenarioComponentPaths: string[];
992
1528
  writtenScenarioComponents: { [key: string]: string[] };
993
1529
  }> {
1530
+ // Reset debug timing for this invocation
1531
+ resetDebugTiming();
1532
+ debugLog('START writeScenarioComponents', {
1533
+ filePath: file.path,
1534
+ entityName: entity.name,
1535
+ scenarioName: scenario.name,
1536
+ isRootFile: !rootFile || rootFile === file,
1537
+ });
1538
+
994
1539
  // Capture arguments for testing if debug mode is enabled
995
1540
  captureArgumentsForTesting({
996
1541
  project,
@@ -1112,9 +1657,6 @@ export default async function writeScenarioComponents({
1112
1657
  // .d.ts files only have type declarations (e.g., "export declare const logger")
1113
1658
  // which don't provide runtime exports. We need to generate actual stub implementations.
1114
1659
  if (file.path.endsWith('.d.ts')) {
1115
- console.log(
1116
- `CodeYam: Converting .d.ts file to stub implementations: ${file.path}`,
1117
- );
1118
1660
  fileContent = convertDtsToStubs(fileContent, entity.name);
1119
1661
 
1120
1662
  // After basic .d.ts conversion, enhance the entity's stub with proper mock code
@@ -1213,7 +1755,31 @@ export default async function writeScenarioComponents({
1213
1755
  return 0;
1214
1756
  });
1215
1757
 
1758
+ debugLog('Starting main importedExports loop', {
1759
+ count: sortedImportedExports.length,
1760
+ fileContentLength: fileContent.length,
1761
+ });
1762
+
1763
+ let importedExportIndex = 0;
1764
+ const loopStartTime = Date.now();
1765
+ console.log(
1766
+ `[WriteScenario] Starting import loop for ${entity.name}: ${sortedImportedExports.length} imports`,
1767
+ );
1216
1768
  for (const importedExport of sortedImportedExports) {
1769
+ importedExportIndex++;
1770
+ if (importedExportIndex % 5 === 0 || importedExportIndex === 1) {
1771
+ console.log(
1772
+ `[WriteScenario] ${entity.name} import ${importedExportIndex}/${sortedImportedExports.length}: ${importedExport.name} elapsed=${Date.now() - loopStartTime}ms`,
1773
+ );
1774
+ debugLog(
1775
+ `Processing importedExport ${importedExportIndex}/${sortedImportedExports.length}`,
1776
+ {
1777
+ name: importedExport.name,
1778
+ filePath: importedExport.filePath,
1779
+ isMocked: importedExport.isMocked,
1780
+ },
1781
+ );
1782
+ }
1217
1783
  // IMPORTANT: The import mapping keys may be either absolute or relative paths
1218
1784
  // depending on how they were created by the file analyzer. We try multiple formats.
1219
1785
  // Also need to normalize paths to handle /tmp vs /private/tmp on macOS
@@ -1285,15 +1851,6 @@ export default async function writeScenarioComponents({
1285
1851
  importedExport.name,
1286
1852
  )
1287
1853
  ) {
1288
- // Skip recursion for type/data entities - they don't need scenario components
1289
- // Only recurse for visual and library entities that need mocking
1290
- if (
1291
- importedExportEntity.entityType === 'type' ||
1292
- importedExportEntity.entityType === 'data'
1293
- ) {
1294
- continue;
1295
- }
1296
-
1297
1854
  // Use fileStore for O(1) lookup when available
1298
1855
  let fileNotMocked = fileStore
1299
1856
  ? fileStore.getByPath(importedExportFilePath)
@@ -1327,35 +1884,126 @@ export default async function writeScenarioComponents({
1327
1884
  fileNotMocked = await fileStore.ensureContent(fileNotMocked.path);
1328
1885
  }
1329
1886
 
1330
- // When a default export is imported as named (via index re-export), we need
1331
- // to add a named re-export to the scenario component so the import works.
1332
- // e.g., if file has `export default X` but parent does `import { X } from '...'`
1333
- const needsNamedReExport =
1334
- importedExport.resolvedIsDefault === true &&
1335
- importedExport.isDefault === false;
1336
-
1337
- const {
1338
- scenarioComponentPaths: newScenarioComponentPaths,
1339
- writtenScenarioComponents: updatedWrittenScenarioComponents,
1340
- } = await writeScenarioComponents({
1341
- project,
1342
- file: fileNotMocked,
1343
- entity: importedExportEntity,
1344
- rootAnalysis,
1345
- scenario,
1346
- context,
1347
- projectAnalyzer,
1348
- framework,
1349
- mocksDir,
1350
- rootFile,
1351
- namespaceMocks,
1352
- writtenScenarioComponents,
1353
- fileStore,
1354
- // Pass the import name so we can add `export { default as Name };`
1355
- exportAsNamed: needsNamedReExport ? importedExport.name : undefined,
1356
- });
1357
- writtenScenarioComponents = updatedWrittenScenarioComponents;
1358
- scenarioComponentPaths.push(...newScenarioComponentPaths);
1887
+ // For type/data entities, create a transformed copy WITHOUT recursion.
1888
+ // Data entities don't need mocking - they're just constants/types that need
1889
+ // to be available. But we still need to:
1890
+ // 1. Strip server-only imports (Next.js directive that breaks client components)
1891
+ // 2. Write the transformed file so imports can be rewritten to point to it
1892
+ if (
1893
+ importedExportEntity.entityType === 'type' ||
1894
+ importedExportEntity.entityType === 'data'
1895
+ ) {
1896
+ // For data entities, we write ONE transformed copy per source file, not per entity.
1897
+ // Check if we've already written ANY entity from this file - if so, skip writing.
1898
+ // Use a special marker '__data_file_written__' to track file-level writes.
1899
+ // Also track which SHA was used via '__data_file_sha__:xxx' so subsequent
1900
+ // entities from the same file can reuse it for import rewriting.
1901
+ const dataFileWritten = writtenScenarioComponents[
1902
+ importedExportFilePath
1903
+ ]?.includes('__data_file_written__');
1904
+
1905
+ if (!dataFileWritten) {
1906
+ // Construct the scenario file path for the data file
1907
+ // Use a file-level identifier (first entity's sha) for consistency
1908
+ const dataFileBasePath = safeFolder(
1909
+ fileNotMocked.path.split('/').slice(0, -1).join('/'),
1910
+ );
1911
+ const dataFileExtension = fileNotMocked.name.split('.').pop();
1912
+ const dataFileIsIndex = isIndexPath(fileNotMocked.path);
1913
+ // Use 'data' prefix to distinguish from entity-specific files
1914
+ const dataScenarioPath = `${PROJECT_RELATIVE_PATH}/${dataFileBasePath}/${importedExportEntity.sha}_${dataFileIsIndex ? 'index_' : ''}data_${safeFileName(scenario.name)}.${dataFileExtension}`;
1915
+
1916
+ // Get the file content and apply transformations
1917
+ let dataFileContent = fileNotMocked.content ?? '';
1918
+
1919
+ // Strip server-only imports - these break when imported by client components
1920
+ dataFileContent = stripServerOnlyImport(dataFileContent);
1921
+ dataFileContent = applyServerOnlyMocks(dataFileContent);
1922
+
1923
+ // Write the transformed data entity file
1924
+ await writeFile(dataScenarioPath, dataFileContent);
1925
+ scenarioComponentPaths.push(dataScenarioPath);
1926
+
1927
+ // Mark file as written so we don't duplicate for other entities from same file
1928
+ if (!writtenScenarioComponents[importedExportFilePath]) {
1929
+ writtenScenarioComponents[importedExportFilePath] = [];
1930
+ }
1931
+ writtenScenarioComponents[importedExportFilePath].push(
1932
+ '__data_file_written__',
1933
+ );
1934
+ // Also store the SHA used for this data file so subsequent entities can use it
1935
+ writtenScenarioComponents[importedExportFilePath].push(
1936
+ `__data_file_sha__:${importedExportEntity.sha}`,
1937
+ );
1938
+ }
1939
+
1940
+ // Mark this specific entity as written (for the entity-level check)
1941
+ if (!writtenScenarioComponents[importedExportFilePath]) {
1942
+ writtenScenarioComponents[importedExportFilePath] = [];
1943
+ }
1944
+ writtenScenarioComponents[importedExportFilePath].push(
1945
+ importedExport.name,
1946
+ );
1947
+
1948
+ // Don't recurse - data entities don't need their dependencies processed
1949
+ // The import rewriting will happen later in this same loop iteration
1950
+ // (at lines ~1590-1702) to point imports to this transformed file
1951
+ } else {
1952
+ // For visual/library entities, recurse to process their dependencies
1953
+
1954
+ // When a default export is imported as named (via index re-export), we need
1955
+ // to add a named re-export to the scenario component so the import works.
1956
+ // e.g., if file has `export default X` but parent does `import { X } from '...'`
1957
+ const needsNamedReExport =
1958
+ importedExport.resolvedIsDefault === true &&
1959
+ importedExport.isDefault === false;
1960
+
1961
+ console.log(
1962
+ `[WriteScenario] RECURSE START: ${entity.name} -> ${importedExportEntity.name}`,
1963
+ );
1964
+ const recurseStartTime = Date.now();
1965
+ debugLog(
1966
+ `Recursing into writeScenarioComponents for ${importedExportEntity.name}`,
1967
+ {
1968
+ entityName: importedExportEntity.name,
1969
+ filePath: fileNotMocked.path,
1970
+ },
1971
+ );
1972
+ const {
1973
+ scenarioComponentPaths: newScenarioComponentPaths,
1974
+ writtenScenarioComponents: updatedWrittenScenarioComponents,
1975
+ } = await withTimeout(
1976
+ `recursive writeScenarioComponents for ${importedExportEntity.name}`,
1977
+ writeScenarioComponents({
1978
+ project,
1979
+ file: fileNotMocked,
1980
+ entity: importedExportEntity,
1981
+ rootAnalysis,
1982
+ scenario,
1983
+ context,
1984
+ projectAnalyzer,
1985
+ framework,
1986
+ mocksDir,
1987
+ rootFile,
1988
+ namespaceMocks,
1989
+ writtenScenarioComponents,
1990
+ fileStore,
1991
+ // Pass the import name so we can add `export { default as Name };`
1992
+ exportAsNamed: needsNamedReExport
1993
+ ? importedExport.name
1994
+ : undefined,
1995
+ }),
1996
+ 180000, // 3 minute timeout for recursive calls (complex components need more time)
1997
+ );
1998
+ console.log(
1999
+ `[WriteScenario] RECURSE END: ${entity.name} -> ${importedExportEntity.name} took ${Date.now() - recurseStartTime}ms`,
2000
+ );
2001
+ debugLog(
2002
+ `Completed recursive writeScenarioComponents for ${importedExportEntity.name}`,
2003
+ );
2004
+ writtenScenarioComponents = updatedWrittenScenarioComponents;
2005
+ scenarioComponentPaths.push(...newScenarioComponentPaths);
2006
+ }
1359
2007
  }
1360
2008
  }
1361
2009
  } else if (
@@ -1372,26 +2020,25 @@ export default async function writeScenarioComponents({
1372
2020
  // that stubbing would break (e.g., Zod schemas with .superRefine())
1373
2021
  const isDataEntity = entityType === 'data' || entityType === 'type';
1374
2022
 
1375
- // Heuristic: Zod schemas are often misclassified as 'library' but should be preserved
1376
- // Detect by: name starts with Z + uppercase letter, AND has Zod method calls
1377
- const looksLikeZodSchema =
1378
- entityType === 'library' &&
1379
- /^Z[A-Z]/.test(importedExport.name) &&
1380
- importedExport.calls?.some((call: string) =>
1381
- /\.(superRefine|refine|transform|default|optional|nullable|array|object|string|number|boolean|parse|safeParse)\s*\(/.test(
1382
- call,
1383
- ),
1384
- );
1385
-
1386
- if (looksLikeZodSchema) {
1387
- console.log(
1388
- `CodeYam: Detected Zod schema "${importedExport.name}" (misclassified as library) - will preserve`,
1389
- );
1390
- }
2023
+ // If calls data shows the entity is only accessed via properties/methods
2024
+ // (e.g., formValidator.validate(), schema.superRefine()) and never directly
2025
+ // invoked (e.g., getInitialProps()), it's used as an object and should be
2026
+ // preserved rather than replaced with a Proxy stub.
2027
+ const onlyPropertyAccessed =
2028
+ importedExport.calls?.length > 0 &&
2029
+ !importedExport.calls.some((call: string) => {
2030
+ const afterName = call.slice(importedExport.name.length);
2031
+ return afterName.startsWith('(') || afterName.startsWith('<');
2032
+ });
1391
2033
 
1392
- // Callable entities can be safely stubbed (but not Zod schemas)
2034
+ // Callable entities can be safely stubbed. Entities that are only
2035
+ // property-accessed should be preserved (their methods need to work).
2036
+ // 'other' entities are unknown types — safer to preserve than stub.
1393
2037
  const isCallable =
1394
- !isDataEntity && !looksLikeZodSchema && entityType !== undefined;
2038
+ !isDataEntity &&
2039
+ !onlyPropertyAccessed &&
2040
+ entityType !== undefined &&
2041
+ entityType !== 'other';
1395
2042
 
1396
2043
  // Determine what action to take
1397
2044
  const shouldStripAndReplace = hasMock;
@@ -1411,9 +2058,6 @@ export default async function writeScenarioComponents({
1411
2058
  if (shouldPreserve) {
1412
2059
  // For data entities (like Zod schemas), don't strip or stub - preserve the original
1413
2060
  // This ensures schema methods like .superRefine() continue to work
1414
- console.log(
1415
- `CodeYam: Preserving ${importedExport.name} (entityType: ${entityType}) - not stripping data entities`,
1416
- );
1417
2061
  // Don't modify fileContent - keep the original code
1418
2062
  } else if (shouldStripAndReplace || shouldStripAndStub) {
1419
2063
  // Strip the original code
@@ -1437,9 +2081,6 @@ export default async function writeScenarioComponents({
1437
2081
  // This prevents ReferenceError at runtime when the stripped
1438
2082
  // function is called (e.g., local helper functions like getInitialProps).
1439
2083
  const functionName = importedExport.name;
1440
- console.log(
1441
- `CodeYam: Generating stub mock for ${functionName} (entityType: ${entityType}) in ${file.path}`,
1442
- );
1443
2084
 
1444
2085
  // Add scenarios import if not present
1445
2086
  if (fileContent.indexOf('import { scenarios } from') === -1) {
@@ -1574,6 +2215,31 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1574
2215
 
1575
2216
  const fileName = actualScenarioFilePathRelative.split('/').pop();
1576
2217
  const fileNotMockedIsIndex = isIndexPath(fileNotMocked?.path);
2218
+
2219
+ // For data/type entities, use 'data' instead of entity name since we write
2220
+ // ONE file per source file (not per entity) for data entities
2221
+ const isDataEntity =
2222
+ importedExportEntity?.entityType === 'data' ||
2223
+ importedExportEntity?.entityType === 'type';
2224
+ const scenarioFileName = isDataEntity
2225
+ ? 'data'
2226
+ : safeFileName(importedExportEntity.name);
2227
+
2228
+ // For data entities, look up the SHA that was used to create the data file
2229
+ // (stored when the file was first written). This ensures all entities from
2230
+ // the same source file have their imports rewritten to point to the same file.
2231
+ // Use actualScenarioFilePathRelative as the key since that's what matches
2232
+ // importedExportFilePath used when storing (both are relative paths).
2233
+ let entityShaForPath = importedExportEntity.sha;
2234
+ if (isDataEntity && actualScenarioFilePathRelative) {
2235
+ const storedShaMarker = writtenScenarioComponents[
2236
+ actualScenarioFilePathRelative
2237
+ ]?.find((m) => m.startsWith('__data_file_sha__:'));
2238
+ if (storedShaMarker) {
2239
+ entityShaForPath = storedShaMarker.replace('__data_file_sha__:', '');
2240
+ }
2241
+ }
2242
+
1577
2243
  const mockFilePath = isFrameworkRoute(
1578
2244
  fileNotMocked,
1579
2245
  importedExportEntity,
@@ -1595,7 +2261,7 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1595
2261
  .join('.')
1596
2262
  : actualScenarioFilePathRelative.replace(
1597
2263
  `${fileName}`,
1598
- `${importedExportEntity.sha}_${fileNotMockedIsIndex ? 'index_' : ''}${safeFileName(importedExportEntity.name)}_${safeFileName(scenario.name)}`,
2264
+ `${entityShaForPath}_${fileNotMockedIsIndex ? 'index_' : ''}${scenarioFileName}_${safeFileName(scenario.name)}`,
1599
2265
  );
1600
2266
 
1601
2267
  const path = safeFolder(getRelativePath(filePath, mockFilePath));
@@ -1636,21 +2302,33 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1636
2302
  // This handles cases where multiple entities are imported from the same index file
1637
2303
  // (e.g., import { A, B, C } from '@pkg') and each has its own scenario file
1638
2304
  const entityImportName = importedExport.name;
1639
- const newImport = `import { ${entityImportName} } from '${path}';`;
2305
+ // Use default import syntax for default exports, named import for named exports
2306
+ const newImport = importedExport.isDefault
2307
+ ? `import ${entityImportName} from '${path}';`
2308
+ : `import { ${entityImportName} } from '${path}';`;
1640
2309
 
1641
2310
  // First, try to remove this entity from the already-rewritten grouped import
1642
2311
  // This prevents duplicate/conflicting imports
1643
- // Match patterns like "EntityName," or ", EntityName" or "EntityName" (if only one)
1644
- // Note: entityImportName needs escaping since JS identifiers can contain $ (a regex metacharacter)
2312
+ // Use AST-based removal to properly handle type-only imports like `type EntityName`
1645
2313
  const escapedEntityName = escapeRegExp(entityImportName);
1646
- const removeFromGroupedImportPatterns = [
1647
- new RegExp(`\\b${escapedEntityName}\\s*,\\s*`, 'g'), // "EntityName, "
1648
- new RegExp(`\\s*,\\s*${escapedEntityName}\\b`, 'g'), // ", EntityName"
1649
- ];
1650
- for (const pattern of removeFromGroupedImportPatterns) {
1651
- fileContent = fileContent.replace(pattern, '');
2314
+
2315
+ // For default imports: remove "DefaultName, " from "import DefaultName, { ... }"
2316
+ // This handles the case where a default export is being split out
2317
+ if (importedExport.isDefault) {
2318
+ const defaultImportPattern = new RegExp(
2319
+ `(import\\s+)${escapedEntityName}\\s*,\\s*(\\{)`,
2320
+ 'gm',
2321
+ );
2322
+ fileContent = fileContent.replace(defaultImportPattern, '$1$2');
1652
2323
  }
1653
2324
 
2325
+ // Remove the named import using AST parsing
2326
+ // This properly handles:
2327
+ // - Regular imports: `import { EntityName } from '...'`
2328
+ // - Type-only imports: `import { type EntityName } from '...'`
2329
+ // - Mixed imports: `import { type EntityName, OtherName } from '...'`
2330
+ fileContent = removeNamedImportAst(fileContent, entityImportName);
2331
+
1654
2332
  // Add the new import at the beginning of fileContent
1655
2333
  // Note: The header comment (// Scenario:) doesn't exist yet - it's prepended at writeFile time
1656
2334
  // So prepending here puts the import right after the header in the final output
@@ -1665,9 +2343,32 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1665
2343
  }
1666
2344
  }
1667
2345
 
2346
+ // Track post-import-loop timing
2347
+ const postLoopStartTime = Date.now();
2348
+ console.log(`[WriteScenario] POST-LOOP START: ${entity.name}`);
2349
+
2350
+ // Collect universal mocks BEFORE processing nodeModuleImports
2351
+ // This is needed to check if a node module import is handled by a universal mock
2352
+ const universalMocks = project.metadata?.universalMocks ?? [];
2353
+ const nodeModuleUniversalMocks = universalMocks.filter(
2354
+ (mock) => mock.nodeModule && mock.content,
2355
+ );
2356
+
2357
+ // Create a set of import paths that have universal mocks for quick lookup
2358
+ const universalMockPaths = new Set(
2359
+ nodeModuleUniversalMocks.map((mock) => mock.filePath),
2360
+ );
2361
+
1668
2362
  for (const nodeModuleImport of nodeModuleImports) {
1669
2363
  if (!nodeModuleImport.isMocked) continue;
1670
2364
 
2365
+ // Skip generating local mock functions for imports that have universal mocks.
2366
+ // Universal mocks provide the exports via rewritten import paths (handled below).
2367
+ // Generating a local mock function would cause "name defined multiple times" errors.
2368
+ if (universalMockPaths.has(nodeModuleImport.filePath)) {
2369
+ continue;
2370
+ }
2371
+
1671
2372
  fileContent = addMockToContent(
1672
2373
  fileContent,
1673
2374
  nodeModuleImport,
@@ -1683,10 +2384,6 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1683
2384
  // Universal mocks create mock files at __codeyamMocks__/{safeFileName}.tsx
1684
2385
  // We need to rewrite imports like `import { logger } from "@formbricks/logger"`
1685
2386
  // to `import { logger } from "../__codeyamMocks__/_formbricks_logger"`
1686
- const universalMocks = project.metadata?.universalMocks ?? [];
1687
- const nodeModuleUniversalMocks = universalMocks.filter(
1688
- (mock) => mock.nodeModule && mock.content,
1689
- );
1690
2387
 
1691
2388
  for (const universalMock of nodeModuleUniversalMocks) {
1692
2389
  const originalPath = universalMock.filePath;
@@ -1709,6 +2406,10 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1709
2406
  );
1710
2407
  }
1711
2408
 
2409
+ console.log(
2410
+ `[WriteScenario] POST-LOOP ${entity.name}: node+universal mocks took ${Date.now() - postLoopStartTime}ms`,
2411
+ );
2412
+
1712
2413
  if (
1713
2414
  rootAnalysis.entitySha === entity.sha &&
1714
2415
  entity.metadata?.notExported &&
@@ -1750,33 +2451,540 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1750
2451
  });
1751
2452
  }
1752
2453
 
2454
+ debugLog('Route path computed', { scenarioComponentPath });
2455
+
1753
2456
  // Strip <html> and <body> tags from root layout files for Next.js
1754
2457
  // These tags cause hydration errors when the scenario layout is nested under the real root
2458
+ debugLog('Starting stripHtmlBodyTags');
1755
2459
  fileContent = stripHtmlBodyTags(fileContent, file.path, framework);
2460
+ debugLog('Completed stripHtmlBodyTags');
2461
+
2462
+ // Strip "server-only" imports for Next.js
2463
+ // These cause errors when the scenario component is rendered client-side
2464
+ debugLog('Starting stripServerOnlyImport');
2465
+ fileContent = stripServerOnlyImport(fileContent);
2466
+ debugLog('Starting applyServerOnlyMocks');
2467
+ fileContent = applyServerOnlyMocks(fileContent);
2468
+ debugLog('Completed server-only processing');
1756
2469
 
1757
2470
  // Rewrite asset imports (CSS, images, fonts, etc.) to correct relative paths
1758
2471
  // The original file path is relative to PROJECT_RELATIVE_PATH, the new path is scenarioComponentPath
2472
+ debugLog('Starting rewriteAssetImports');
1759
2473
  fileContent = rewriteAssetImports(
1760
2474
  fileContent,
1761
2475
  `${PROJECT_RELATIVE_PATH}/${file.path}`,
1762
2476
  scenarioComponentPath,
1763
2477
  );
2478
+ debugLog('Completed rewriteAssetImports');
1764
2479
 
1765
2480
  // Rewrite relative TypeScript/JavaScript module imports to correct relative paths
1766
2481
  // This handles cases where the file is moved (e.g., from [environmentId]/ to _environmentId_/)
1767
2482
  // and relative imports like "./lib/organization" need to be rewritten
2483
+ debugLog('Starting rewriteRelativeModuleImports');
1768
2484
  fileContent = rewriteRelativeModuleImports(
1769
2485
  fileContent,
1770
2486
  `${PROJECT_RELATIVE_PATH}/${file.path}`,
1771
2487
  scenarioComponentPath,
1772
2488
  );
2489
+ debugLog('Completed rewriteRelativeModuleImports');
1773
2490
 
1774
2491
  console.log(
1775
- 'Writing scenario component',
1776
- file.path,
1777
- entity.name,
1778
- scenarioComponentPath,
1779
- fileContent.length,
2492
+ `[WriteScenario] POST-LOOP ${entity.name}: transformations took ${Date.now() - postLoopStartTime}ms`,
2493
+ );
2494
+
2495
+ /**
2496
+ * Recursively process a file's imports to create transitive copies with server-only stripped.
2497
+ * This handles chains of arbitrary depth: A -> B -> C -> D where each needs server-only removed.
2498
+ * Uses a visited set to detect and break circular import chains.
2499
+ *
2500
+ * @param content - The file content to process
2501
+ * @param sourceFilePath - The original source file path (for resolving relative imports)
2502
+ * @param targetFilePath - The path where this content will be written (for computing relative imports)
2503
+ * @param visitedPaths - Set of file paths currently being processed (for cycle detection)
2504
+ * @returns The modified content with imports rewritten to point to transitive copies
2505
+ */
2506
+ async function processTransitiveImportsRecursively(
2507
+ content: string,
2508
+ sourceFilePath: string,
2509
+ targetFilePath: string,
2510
+ visitedPaths: Set<string> = new Set(),
2511
+ depth: number = 0,
2512
+ startTime: number = Date.now(),
2513
+ ): Promise<string> {
2514
+ // Global timeout for entire transitive processing
2515
+ const GLOBAL_TIMEOUT_MS = 180000; // 3 minutes max for all transitive processing (complex components need more time)
2516
+ const elapsed = Date.now() - startTime;
2517
+ if (elapsed > GLOBAL_TIMEOUT_MS) {
2518
+ throw new Error(
2519
+ `processTransitiveImportsRecursively exceeded ${GLOBAL_TIMEOUT_MS}ms (elapsed: ${elapsed}ms) at depth=${depth} for ${sourceFilePath}`,
2520
+ );
2521
+ }
2522
+
2523
+ const importPaths = extractInternalImportPaths(content);
2524
+ // Always log to help debug timeout issues
2525
+ console.log(
2526
+ `[TransitiveImports] depth=${depth} file=${path.basename(sourceFilePath)} imports=${importPaths.length} visited=${visitedPaths.size} elapsed=${Date.now() - startTime}ms`,
2527
+ );
2528
+ debugLog(`processTransitiveImportsRecursively depth=${depth}`, {
2529
+ sourceFilePath,
2530
+ importCount: importPaths.length,
2531
+ visitedCount: visitedPaths.size,
2532
+ });
2533
+ let modifiedContent = content;
2534
+
2535
+ // Safety check: limit iterations to prevent infinite loops
2536
+ const MAX_IMPORTS_PER_FILE = 100;
2537
+ if (importPaths.length > MAX_IMPORTS_PER_FILE) {
2538
+ console.warn(
2539
+ `[WriteScenario] WARNING: File ${sourceFilePath} has ${importPaths.length} imports (> ${MAX_IMPORTS_PER_FILE}), limiting processing`,
2540
+ );
2541
+ }
2542
+
2543
+ let importIndex = 0;
2544
+ debugLog(
2545
+ `Starting import loop at depth=${depth}, ${importPaths.length} imports to process`,
2546
+ );
2547
+ const slicedImports = importPaths.slice(0, MAX_IMPORTS_PER_FILE);
2548
+ for (const importPath of slicedImports) {
2549
+ if (!importPath) {
2550
+ continue;
2551
+ }
2552
+ importIndex++;
2553
+ debugLog(
2554
+ `[LOOP] depth=${depth} import ${importIndex}/${Math.min(importPaths.length, MAX_IMPORTS_PER_FILE)}: ${importPath}`,
2555
+ );
2556
+ debugLog(`[LOOP] Calling resolveImportPath...`);
2557
+ const resolvedPath = resolveImportPath(
2558
+ importPath,
2559
+ sourceFilePath,
2560
+ project,
2561
+ );
2562
+ debugLog(
2563
+ `[LOOP] resolveImportPath returned: ${resolvedPath?.slice(0, 80) ?? 'null'}`,
2564
+ );
2565
+ if (!resolvedPath) continue;
2566
+
2567
+ debugLog(`[LOOP] Looking up importFile...`);
2568
+ let importFile = fileStore
2569
+ ? fileStore.getByPath(resolvedPath)
2570
+ : project.files?.find((f) => f.path === resolvedPath);
2571
+ debugLog(
2572
+ `[LOOP] importFile lookup result: ${importFile ? 'found' : 'not found'}`,
2573
+ );
2574
+ if (!importFile) continue;
2575
+
2576
+ // Build the transitive file path (needed for import rewriting even if we skip creating)
2577
+ const basePath = safeFolder(
2578
+ importFile.path.split('/').slice(0, -1).join('/'),
2579
+ );
2580
+ const extension = importFile.name.split('.').pop();
2581
+ const isIndex = isIndexPath(importFile.path);
2582
+ // Limit pathHash length to prevent ENAMETOOLONG errors on macOS (255 char limit)
2583
+ const pathHash = safeFileName(importFile.path, { maxLength: 80 });
2584
+ const scenarioSlug = safeFileName(scenario.name, { maxLength: 60 });
2585
+ const transitiveFilePath = `${PROJECT_RELATIVE_PATH}/${basePath}/${pathHash}_${isIndex ? 'index_' : ''}transitive_${scenarioSlug}.${extension}`;
2586
+
2587
+ // Check if this is a circular import (we're already processing this file)
2588
+ const isCircularImport = visitedPaths.has(resolvedPath);
2589
+
2590
+ // Check if already processed
2591
+ const alreadyProcessed = writtenScenarioComponents[
2592
+ resolvedPath
2593
+ ]?.includes('__transitive_file_written__');
2594
+
2595
+ // Only create the transitive file if not circular and not already processed
2596
+ if (!isCircularImport && !alreadyProcessed) {
2597
+ // Load content if needed
2598
+ if (!importFile.content && fileStore) {
2599
+ importFile = await fileStore.ensureContent(resolvedPath);
2600
+ }
2601
+ if (!importFile?.content) {
2602
+ // Can't create transitive, but still try to rewrite import below
2603
+ } else {
2604
+ // Mark as being processed BEFORE recursing (to detect cycles)
2605
+ visitedPaths.add(resolvedPath);
2606
+
2607
+ // Strip server-only and mock server-only packages, then recursively process imports
2608
+ let transitiveContent = stripServerOnlyImport(importFile.content);
2609
+ transitiveContent = applyServerOnlyMocks(transitiveContent);
2610
+ debugLog(
2611
+ `processTransitiveImportsRecursively depth=${depth} for ${importFile.path}`,
2612
+ );
2613
+ debugLog(
2614
+ `Calling processTransitiveImportsRecursively depth=${depth + 1} for ${importFile.path}`,
2615
+ );
2616
+ transitiveContent = await withTimeout(
2617
+ `processTransitiveImportsRecursively depth=${depth} for ${path.basename(importFile.path)}`,
2618
+ processTransitiveImportsRecursively(
2619
+ transitiveContent,
2620
+ importFile.path,
2621
+ transitiveFilePath,
2622
+ visitedPaths,
2623
+ depth + 1,
2624
+ startTime, // Pass through the original start time
2625
+ ),
2626
+ 30000, // 30 second timeout per transitive import
2627
+ );
2628
+ debugLog(
2629
+ `withTimeout returned for depth=${depth}, transitiveContent length=${transitiveContent.length}`,
2630
+ );
2631
+ debugLog(
2632
+ `Completed processTransitiveImportsRecursively depth=${depth} for ${importFile.path}`,
2633
+ );
2634
+
2635
+ debugLog(`Writing transitive file depth=${depth}`, {
2636
+ transitiveFilePath: path.basename(transitiveFilePath),
2637
+ contentLength: transitiveContent.length,
2638
+ });
2639
+ await writeFile(transitiveFilePath, transitiveContent);
2640
+ debugLog(`Wrote transitive file depth=${depth}`);
2641
+ scenarioComponentPaths.push(transitiveFilePath);
2642
+
2643
+ if (!writtenScenarioComponents[resolvedPath]) {
2644
+ writtenScenarioComponents[resolvedPath] = [];
2645
+ }
2646
+ writtenScenarioComponents[resolvedPath].push(
2647
+ '__transitive_file_written__',
2648
+ );
2649
+ }
2650
+ }
2651
+
2652
+ // ALWAYS rewrite the import to point to the transitive copy
2653
+ // (even for circular imports or already-processed files)
2654
+ debugLog(`Rewriting import path depth=${depth}`, {
2655
+ importPath,
2656
+ resolvedPath,
2657
+ });
2658
+ const relativePath = getRelativePath(targetFilePath, transitiveFilePath);
2659
+ const relativePathWithoutExt = relativePath.replace(
2660
+ /\.(ts|tsx|js|jsx)$/,
2661
+ '',
2662
+ );
2663
+ const safeRelativePath = safeFolder(relativePathWithoutExt);
2664
+ const escapedImportPath = importPath.replace(
2665
+ /[.*+?^${}()|[\]\\]/g,
2666
+ '\\$&',
2667
+ );
2668
+ debugLog(`Applying regex depth=${depth}`, {
2669
+ escapedImportPath,
2670
+ contentLength: modifiedContent.length,
2671
+ });
2672
+ // Quick check if the import path even exists in content
2673
+ const simpleCheck = modifiedContent.includes(importPath);
2674
+ debugLog(
2675
+ `Simple check: importPath "${importPath}" exists: ${simpleCheck}`,
2676
+ );
2677
+ if (!simpleCheck) {
2678
+ debugLog(`Skipping regex - import path not found in content`);
2679
+ } else {
2680
+ const regexPattern = `(from\\s*["'])${escapedImportPath}(["'])`;
2681
+ debugLog(`Regex pattern: ${regexPattern.slice(0, 100)}`);
2682
+ const importRegex = new RegExp(regexPattern, 'g');
2683
+ debugLog(`About to call replace...`);
2684
+
2685
+ // Timing for regex replace to detect slow operations
2686
+ const replaceStart = Date.now();
2687
+ modifiedContent = modifiedContent.replace(
2688
+ importRegex,
2689
+ `$1${safeRelativePath}$2`,
2690
+ );
2691
+ const replaceTime = Date.now() - replaceStart;
2692
+ if (replaceTime > 100) {
2693
+ console.warn(
2694
+ `[WriteScenario] SLOW regex replace: ${replaceTime}ms for pattern ${regexPattern.slice(0, 50)} on ${modifiedContent.length} bytes`,
2695
+ );
2696
+ }
2697
+ debugLog(`Regex applied depth=${depth} in ${replaceTime}ms`);
2698
+ }
2699
+ debugLog(`[LOOP END] depth=${depth} import ${importIndex} completed`);
2700
+ }
2701
+
2702
+ debugLog(`[LOOP DONE] Exiting import loop at depth=${depth}`);
2703
+ debugLog(
2704
+ `Returning from processTransitiveImportsRecursively depth=${depth}`,
2705
+ );
2706
+ return modifiedContent;
2707
+ }
2708
+
2709
+ console.log(
2710
+ `[WriteScenario] POST-LOOP ${entity.name}: before remaining imports ${Date.now() - postLoopStartTime}ms`,
2711
+ );
2712
+
2713
+ // Process remaining internal imports that weren't in importedExports
2714
+ // This handles transitive dependencies: when the file content includes code (e.g., from
2715
+ // other functions in the same file) that imports from files with "server-only"
2716
+ debugLog('Extracting remaining import paths');
2717
+ const remainingImportPaths = extractInternalImportPaths(fileContent);
2718
+ debugLog('Found remaining import paths', {
2719
+ count: remainingImportPaths.length,
2720
+ });
2721
+
2722
+ // Get all file paths that are in importedExports - these are handled by main processing
2723
+ const importedExportFilePaths = new Set(
2724
+ allImportedExports.map((ie) => ie.resolvedFilePath || ie.filePath),
2725
+ );
2726
+
2727
+ debugLog('Starting remaining imports loop', {
2728
+ remainingCount: remainingImportPaths.length,
2729
+ importedExportCount: importedExportFilePaths.size,
2730
+ });
2731
+
2732
+ let remainingImportIndex = 0;
2733
+ debugLog(
2734
+ `[REMAINING] Starting remaining imports loop, ${remainingImportPaths.length} imports`,
2735
+ );
2736
+ for (const importPath of remainingImportPaths) {
2737
+ remainingImportIndex++;
2738
+ debugLog(
2739
+ `[REMAINING LOOP] import ${remainingImportIndex}/${remainingImportPaths.length}: ${importPath}`,
2740
+ );
2741
+
2742
+ // Skip imports that point to generated CodeYam files (same skip logic as
2743
+ // rewriteRelativeModuleImports). Without this, MockData files from earlier
2744
+ // captures that get discovered by the TypeScript compiler would be treated as
2745
+ // regular imports, creating transitive copies with stale content.
2746
+ const scenarioFilePattern = /[a-f0-9]{64}_\w+_[A-Z]\w*$/;
2747
+ const mockDataPattern = /__codeyamMocks__\//;
2748
+ if (
2749
+ scenarioFilePattern.test(importPath) ||
2750
+ mockDataPattern.test(importPath)
2751
+ ) {
2752
+ continue;
2753
+ }
2754
+
2755
+ // Resolve the import path to a project file path
2756
+ const resolvedFilePath = resolveImportPath(importPath, file.path, project);
2757
+
2758
+ if (!resolvedFilePath) {
2759
+ // Can't resolve - might be a path we don't handle, skip it
2760
+ continue;
2761
+ }
2762
+
2763
+ // Find the file in project.files, using fileStore for O(1) lookup when available
2764
+ // We need to find the file BEFORE checking importedExports to see if it has server-only
2765
+ let targetFile = fileStore
2766
+ ? fileStore.getByPath(resolvedFilePath)
2767
+ : project.files?.find((f) => f.path === resolvedFilePath);
2768
+
2769
+ // Skip if this import is in importedExports - it's handled by the main processing loop
2770
+ // UNLESS the file contains "server-only", in which case we still need a transitive copy
2771
+ // with server-only stripped (even if some exports from the file are mocked).
2772
+ if (importedExportFilePaths.has(resolvedFilePath)) {
2773
+ // Check if the file has server-only before skipping
2774
+ let fileContent = targetFile?.content;
2775
+ if (!fileContent && targetFile && fileStore) {
2776
+ // Load content to check for server-only
2777
+ const loadedFile = await fileStore.ensureContent(resolvedFilePath);
2778
+ fileContent = loadedFile?.content;
2779
+ if (loadedFile) {
2780
+ targetFile = loadedFile;
2781
+ }
2782
+ }
2783
+
2784
+ const hasServerOnly =
2785
+ fileContent && /import\s+["']server-only["']/.test(fileContent);
2786
+
2787
+ if (!hasServerOnly) {
2788
+ continue;
2789
+ }
2790
+ // File has server-only - continue processing to create transitive copy
2791
+ }
2792
+ if (!targetFile) {
2793
+ continue;
2794
+ }
2795
+
2796
+ // Compute the transformed file path (needed for import rewriting even if already processed)
2797
+ const targetFileBasePath = safeFolder(
2798
+ targetFile.path.split('/').slice(0, -1).join('/'),
2799
+ );
2800
+ const targetFileExtension = targetFile.name.split('.').pop();
2801
+ const targetFileIsIndex = isIndexPath(targetFile.path);
2802
+ // Limit path hash length to prevent ENAMETOOLONG errors
2803
+ const filePathHash = safeFileName(targetFile.path, { maxLength: 80 });
2804
+ const targetScenarioSlug = safeFileName(scenario.name, { maxLength: 60 });
2805
+ const transformedFilePath = `${PROJECT_RELATIVE_PATH}/${targetFileBasePath}/${filePathHash}_${targetFileIsIndex ? 'index_' : ''}transitive_${targetScenarioSlug}.${targetFileExtension}`;
2806
+
2807
+ // Check if we've already processed this file as a transitive copy
2808
+ // Note: __data_file_written__ is for entity-specific scenario files with different naming,
2809
+ // but we still need transitive copies for server-only stripping. Data entity files may
2810
+ // only export specific items, so we need a full transitive copy with all exports.
2811
+ const alreadyTransitive = writtenScenarioComponents[
2812
+ resolvedFilePath
2813
+ ]?.includes('__transitive_file_written__');
2814
+
2815
+ if (!alreadyTransitive) {
2816
+ // Ensure content is loaded (LazyFileStore loads content on-demand)
2817
+ if (!targetFile.content && fileStore) {
2818
+ targetFile = await fileStore.ensureContent(resolvedFilePath);
2819
+ }
2820
+ if (!targetFile?.content) {
2821
+ continue;
2822
+ }
2823
+
2824
+ // Get the file content and apply transformations
2825
+ let transformedContent = targetFile.content;
2826
+ transformedContent = stripServerOnlyImport(transformedContent);
2827
+ transformedContent = applyServerOnlyMocks(transformedContent);
2828
+
2829
+ // Recursively process this transitive file's imports
2830
+ // This handles the nested case: service.ts → brevo.ts → constants.ts
2831
+ const nestedImportPaths = extractInternalImportPaths(transformedContent);
2832
+ debugLog(
2833
+ `[NESTED] Processing ${nestedImportPaths.length} nested imports for ${targetFile.path}`,
2834
+ );
2835
+ let nestedIndex = 0;
2836
+ for (const nestedImportPath of nestedImportPaths) {
2837
+ nestedIndex++;
2838
+ debugLog(
2839
+ `[NESTED LOOP] import ${nestedIndex}/${nestedImportPaths.length}: ${nestedImportPath}`,
2840
+ );
2841
+ const nestedResolvedPath = resolveImportPath(
2842
+ nestedImportPath,
2843
+ targetFile.path,
2844
+ project,
2845
+ );
2846
+ if (!nestedResolvedPath) continue;
2847
+
2848
+ // Get file info for building the transformed path
2849
+ let nestedFile = fileStore
2850
+ ? fileStore.getByPath(nestedResolvedPath)
2851
+ : project.files?.find((f) => f.path === nestedResolvedPath);
2852
+ if (!nestedFile) continue;
2853
+
2854
+ // Build the transformed path (needed for import rewriting even if already processed)
2855
+ const nestedBasePath = safeFolder(
2856
+ nestedFile.path.split('/').slice(0, -1).join('/'),
2857
+ );
2858
+ const nestedExtension = nestedFile.name.split('.').pop();
2859
+ const nestedIsIndex = isIndexPath(nestedFile.path);
2860
+ // Limit path hash length to prevent ENAMETOOLONG errors
2861
+ const nestedPathHash = safeFileName(nestedFile.path, { maxLength: 80 });
2862
+ const nestedScenarioSlug = safeFileName(scenario.name, {
2863
+ maxLength: 60,
2864
+ });
2865
+ const nestedTransformedPath = `${PROJECT_RELATIVE_PATH}/${nestedBasePath}/${nestedPathHash}_${nestedIsIndex ? 'index_' : ''}transitive_${nestedScenarioSlug}.${nestedExtension}`;
2866
+
2867
+ // Check if already processed as a transitive file (we can rewrite to point to it)
2868
+ // Note: __data_file_written__ is for entity-specific scenario files with different naming,
2869
+ // but we still need transitive copies for server-only stripping in the import chain
2870
+ const nestedAlreadyTransitive = writtenScenarioComponents[
2871
+ nestedResolvedPath
2872
+ ]?.includes('__transitive_file_written__');
2873
+
2874
+ if (!nestedAlreadyTransitive) {
2875
+ // Ensure content is loaded for nested files
2876
+ if (!nestedFile.content && fileStore) {
2877
+ nestedFile = await fileStore.ensureContent(nestedResolvedPath);
2878
+ }
2879
+ if (!nestedFile?.content) continue;
2880
+
2881
+ // Strip server-only, mock server-only packages, and recursively process imports
2882
+ // This handles chains of any depth: A -> B -> C -> D
2883
+ let nestedContent = stripServerOnlyImport(nestedFile.content);
2884
+ nestedContent = applyServerOnlyMocks(nestedContent);
2885
+ debugLog(
2886
+ `processTransitiveImportsRecursively (nested) for ${nestedFile.path}`,
2887
+ );
2888
+ nestedContent = await withTimeout(
2889
+ `processTransitiveImportsRecursively (nested) for ${path.basename(nestedFile.path)}`,
2890
+ processTransitiveImportsRecursively(
2891
+ nestedContent,
2892
+ nestedFile.path,
2893
+ nestedTransformedPath,
2894
+ ),
2895
+ 30000, // 30 second timeout per nested transitive import
2896
+ );
2897
+ debugLog(
2898
+ `Completed processTransitiveImportsRecursively (nested) for ${nestedFile.path}`,
2899
+ );
2900
+
2901
+ await writeFile(nestedTransformedPath, nestedContent);
2902
+ scenarioComponentPaths.push(nestedTransformedPath);
2903
+
2904
+ // Mark as written
2905
+ if (!writtenScenarioComponents[nestedResolvedPath]) {
2906
+ writtenScenarioComponents[nestedResolvedPath] = [];
2907
+ }
2908
+ writtenScenarioComponents[nestedResolvedPath].push(
2909
+ '__transitive_file_written__',
2910
+ );
2911
+ }
2912
+
2913
+ // Rewrite the import to point to the transitive copy
2914
+ const nestedRelativePath = getRelativePath(
2915
+ transformedFilePath,
2916
+ nestedTransformedPath,
2917
+ );
2918
+ // Strip the extension before applying safeFolder - import paths in TypeScript
2919
+ // should NOT include extensions (Next.js resolves .ts/.tsx automatically).
2920
+ // Without this, safeFolder converts ".ts" to "_ts" causing "Module not found" errors.
2921
+ const nestedRelativePathWithoutExt = nestedRelativePath.replace(
2922
+ /\.(ts|tsx|js|jsx)$/,
2923
+ '',
2924
+ );
2925
+ const safeNestedRelativePath = safeFolder(nestedRelativePathWithoutExt);
2926
+ const escapedNestedImportPath = nestedImportPath.replace(
2927
+ /[.*+?^${}()|[\]\\]/g,
2928
+ '\\$&',
2929
+ );
2930
+ const nestedImportRegex = new RegExp(
2931
+ `(from\\s*["'])${escapedNestedImportPath}(["'])`,
2932
+ 'g',
2933
+ );
2934
+ transformedContent = transformedContent.replace(
2935
+ nestedImportRegex,
2936
+ `$1${safeNestedRelativePath}$2`,
2937
+ );
2938
+ }
2939
+
2940
+ // Re-check if file was written during recursive processing
2941
+ // (processTransitiveImportsRecursively might have created this file while processing
2942
+ // a nested import that circularly imports back to this file)
2943
+ const writtenDuringRecursion = writtenScenarioComponents[
2944
+ resolvedFilePath
2945
+ ]?.includes('__transitive_file_written__');
2946
+
2947
+ if (!writtenDuringRecursion) {
2948
+ // Write the transformed file
2949
+ await writeFile(transformedFilePath, transformedContent);
2950
+ scenarioComponentPaths.push(transformedFilePath);
2951
+
2952
+ // Mark as written
2953
+ if (!writtenScenarioComponents[resolvedFilePath]) {
2954
+ writtenScenarioComponents[resolvedFilePath] = [];
2955
+ }
2956
+ writtenScenarioComponents[resolvedFilePath].push(
2957
+ '__transitive_file_written__',
2958
+ );
2959
+ }
2960
+ }
2961
+
2962
+ // ALWAYS rewrite the import in fileContent to point to the transformed file
2963
+ // (even if the transitive copy was already created by another entity)
2964
+ const relativePath = getRelativePath(
2965
+ scenarioComponentPath,
2966
+ transformedFilePath,
2967
+ );
2968
+ // Strip the extension before applying safeFolder - import paths in TypeScript
2969
+ // should NOT include extensions (Next.js resolves .ts/.tsx automatically).
2970
+ // Without this, safeFolder converts ".ts" to "_ts" causing "Module not found" errors.
2971
+ const relativePathWithoutExt = relativePath.replace(
2972
+ /\.(ts|tsx|js|jsx)$/,
2973
+ '',
2974
+ );
2975
+ const safeRelativePath = safeFolder(relativePathWithoutExt);
2976
+
2977
+ // Escape special regex characters in the import path
2978
+ const escapedImportPath = importPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
2979
+ const importRegex = new RegExp(
2980
+ `(from\\s*["'])${escapedImportPath}(["'])`,
2981
+ 'g',
2982
+ );
2983
+ fileContent = fileContent.replace(importRegex, `$1${safeRelativePath}$2`);
2984
+ }
2985
+
2986
+ console.log(
2987
+ `[WriteScenario] POST-LOOP ${entity.name}: remaining imports loop took ${Date.now() - postLoopStartTime}ms`,
1780
2988
  );
1781
2989
 
1782
2990
  const scenarioComponentComment = `// This file is auto-generated by CodeYam. Do not edit this file manually.
@@ -1790,28 +2998,103 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1790
2998
  // Scenario: ${scenario.id} - ${scenario.name}
1791
2999
  `;
1792
3000
 
3001
+ // Final pass: Rename any namespace imports (import * as X from '...') that have
3002
+ // corresponding mock code using ...X__cyOriginal spread pattern.
3003
+ // This handles cases where:
3004
+ // 1. The import path was rewritten by transitive import handling
3005
+ // 2. The import wasn't caught by the earlier renaming logic
3006
+ // We scan for all __cyOriginal references in the mock code and ensure the imports are renamed.
3007
+ const cyOriginalReferences = fileContent.match(/\.\.\.(\w+)__cyOriginal/g);
3008
+ if (cyOriginalReferences) {
3009
+ const uniqueNames = [
3010
+ ...new Set(
3011
+ cyOriginalReferences.map((ref) =>
3012
+ ref.replace('...', '').replace('__cyOriginal', ''),
3013
+ ),
3014
+ ),
3015
+ ];
3016
+ for (const name of uniqueNames) {
3017
+ // Match namespace imports for this name that haven't been renamed yet
3018
+ const namespaceImportRegex = new RegExp(
3019
+ `(import\\s+\\*\\s+as\\s+)${escapeRegExp(name)}(\\s+from\\s+['"][^'"]*['"])`,
3020
+ 'g',
3021
+ );
3022
+ fileContent = fileContent.replace(
3023
+ namespaceImportRegex,
3024
+ `$1${name}__cyOriginal$2`,
3025
+ );
3026
+ }
3027
+ }
3028
+
3029
+ // For route components (page.tsx, layout.tsx), the component IS the Next.js page.
3030
+ // There's no wrapper page to inject argumentsData as props (unlike non-route components
3031
+ // which get a scenarioComponent wrapper). We need to wrap the default export so that
3032
+ // the scenario's argumentsData is passed as props to the component.
3033
+ if (
3034
+ isFrameworkRoute(file, entity, framework, file === rootFile) &&
3035
+ rootAnalysis.metadata?.scenariosDataStructure?.arguments?.length > 0
3036
+ ) {
3037
+ const positionalArguments =
3038
+ rootAnalysis.metadata.scenariosDataStructure.arguments;
3039
+ const hasNamedArgs =
3040
+ positionalArguments.length === 1 &&
3041
+ typeof positionalArguments[0] === 'object';
3042
+
3043
+ if (hasNamedArgs) {
3044
+ // Match: export default function Name(
3045
+ // Also: export default async function Name(
3046
+ const defaultExportMatch = fileContent.match(
3047
+ /export\s+default\s+(async\s+)?function\s+(\w+)\s*\(/,
3048
+ );
3049
+
3050
+ if (defaultExportMatch) {
3051
+ const funcName = defaultExportMatch[2];
3052
+
3053
+ // Remove "export default" from the original function declaration
3054
+ fileContent = fileContent.replace(
3055
+ /export\s+default\s+(async\s+)?function\s+(\w+)\s*\(/,
3056
+ '$1function $2(',
3057
+ );
3058
+
3059
+ // Ensure scenarios import is present
3060
+ const mockDataPath = `${relativeMocksDir}/MockData_${safeFileName(scenario.name)}`;
3061
+ if (fileContent.indexOf('import { scenarios } from') === -1) {
3062
+ fileContent = `import { scenarios } from "${mockDataPath}";\n\n${fileContent}`;
3063
+ }
3064
+
3065
+ // Add wrapper default export that injects argumentsData as props
3066
+ fileContent += `\n\nexport default function _CYRouteWrapper(props: any) {
3067
+ const _cyArgs = scenarios().data()?.['arguments']?.[0] ?? {};
3068
+ return <${funcName} {...props} {..._cyArgs} />;
3069
+ }\n`;
3070
+ }
3071
+ }
3072
+ }
3073
+
1793
3074
  // Use the directive that was extracted at the beginning of processing
1794
3075
  // This ensures it stays at the very top even after imports are prepended
3076
+ // NOTE: We only preserve "use client" directives, NOT "use server" directives.
3077
+ // Server action files get mocked with objects that aren't async functions,
3078
+ // which would violate Next.js's "use server" requirement:
3079
+ // "A 'use server' file can only export async functions, found object."
1795
3080
  let finalContent: string;
1796
- if (extractedDirective) {
3081
+ if (extractedDirective && extractedDirective.includes('client')) {
1797
3082
  finalContent = `${extractedDirective}\n\n${scenarioComponentComment}\n\n${fileContent}`;
1798
- console.log(
1799
- `CodeYam: Placed "${extractedDirective}" directive at top of file: ${scenarioComponentPath}`,
1800
- );
1801
3083
  } else {
1802
3084
  finalContent = `${scenarioComponentComment}\n\n${fileContent}`;
1803
3085
  }
1804
3086
 
3087
+ debugLog('About to write final scenario file', {
3088
+ scenarioComponentPath,
3089
+ contentLength: finalContent.length,
3090
+ });
1805
3091
  await writeFile(scenarioComponentPath, finalContent);
3092
+ debugLog('Successfully wrote scenario file');
1806
3093
  scenarioComponentPaths.push(scenarioComponentPath);
1807
3094
 
1808
- console.log('CodeYam [writeScenarioComponents]: Generated scenario files', {
1809
- entityName: entity.name,
1810
- filePath: file.path,
1811
- scenarioName: scenario.name,
1812
- scenarioComponentPathsGenerated: scenarioComponentPaths,
1813
- writtenScenarioComponentKeys: Object.keys(writtenScenarioComponents),
1814
- });
3095
+ console.log(
3096
+ `[WriteScenario] POST-LOOP ${entity.name}: COMPLETE total=${Date.now() - postLoopStartTime}ms`,
3097
+ );
1815
3098
 
1816
3099
  return { scenarioComponentPaths, writtenScenarioComponents };
1817
3100
  }