@codeyam/codeyam-cli 0.1.0-staging.842873f → 0.1.0-staging.8df382d

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 (1070) 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 +31 -27
  5. package/analyzer-template/packages/ai/index.ts +21 -5
  6. package/analyzer-template/packages/ai/package.json +5 -5
  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 +235 -66
  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 +1421 -92
  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 +689 -89
  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 +9 -7
  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 +1342 -169
  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 +88 -11
  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 +61 -15
  392. package/analyzer-template/project/startScenarioCapture.ts +79 -41
  393. package/analyzer-template/project/writeMockDataTsx.ts +454 -67
  394. package/analyzer-template/project/writeScenarioClientWrapper.ts +21 -0
  395. package/analyzer-template/project/writeScenarioComponents.ts +1500 -237
  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 +1190 -130
  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 +72 -12
  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 +53 -15
  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 +392 -56
  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 +1107 -161
  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 +37 -22
  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/init.js +49 -257
  477. package/codeyam-cli/src/commands/init.js.map +1 -1
  478. package/codeyam-cli/src/commands/memory.js +254 -0
  479. package/codeyam-cli/src/commands/memory.js.map +1 -0
  480. package/codeyam-cli/src/commands/recapture.js +228 -0
  481. package/codeyam-cli/src/commands/recapture.js.map +1 -0
  482. package/codeyam-cli/src/commands/report.js +72 -24
  483. package/codeyam-cli/src/commands/report.js.map +1 -1
  484. package/codeyam-cli/src/commands/setup-sandbox.js +2 -0
  485. package/codeyam-cli/src/commands/setup-sandbox.js.map +1 -1
  486. package/codeyam-cli/src/commands/setup-simulations.js +284 -0
  487. package/codeyam-cli/src/commands/setup-simulations.js.map +1 -0
  488. package/codeyam-cli/src/commands/start.js +8 -12
  489. package/codeyam-cli/src/commands/start.js.map +1 -1
  490. package/codeyam-cli/src/commands/status.js +23 -1
  491. package/codeyam-cli/src/commands/status.js.map +1 -1
  492. package/codeyam-cli/src/commands/test-startup.js +3 -1
  493. package/codeyam-cli/src/commands/test-startup.js.map +1 -1
  494. package/codeyam-cli/src/commands/verify.js +14 -2
  495. package/codeyam-cli/src/commands/verify.js.map +1 -1
  496. package/codeyam-cli/src/commands/wipe.js +108 -0
  497. package/codeyam-cli/src/commands/wipe.js.map +1 -0
  498. package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js +185 -0
  499. package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js.map +1 -0
  500. package/codeyam-cli/src/utils/__tests__/serverVersionStaleness.test.js +81 -0
  501. package/codeyam-cli/src/utils/__tests__/serverVersionStaleness.test.js.map +1 -0
  502. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js +128 -82
  503. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js.map +1 -1
  504. package/codeyam-cli/src/utils/analysisRunner.js +29 -15
  505. package/codeyam-cli/src/utils/analysisRunner.js.map +1 -1
  506. package/codeyam-cli/src/utils/analyzer.js +7 -0
  507. package/codeyam-cli/src/utils/analyzer.js.map +1 -1
  508. package/codeyam-cli/src/utils/backgroundServer.js +104 -23
  509. package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
  510. package/codeyam-cli/src/utils/database.js +91 -5
  511. package/codeyam-cli/src/utils/database.js.map +1 -1
  512. package/codeyam-cli/src/utils/generateReport.js +253 -106
  513. package/codeyam-cli/src/utils/generateReport.js.map +1 -1
  514. package/codeyam-cli/src/utils/git.js +79 -0
  515. package/codeyam-cli/src/utils/git.js.map +1 -0
  516. package/codeyam-cli/src/utils/install-skills.js +78 -44
  517. package/codeyam-cli/src/utils/install-skills.js.map +1 -1
  518. package/codeyam-cli/src/utils/labsAutoCheck.js +19 -0
  519. package/codeyam-cli/src/utils/labsAutoCheck.js.map +1 -0
  520. package/codeyam-cli/src/utils/npmVersionCheck.js +76 -0
  521. package/codeyam-cli/src/utils/npmVersionCheck.js.map +1 -0
  522. package/codeyam-cli/src/utils/progress.js +7 -0
  523. package/codeyam-cli/src/utils/progress.js.map +1 -1
  524. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js +38 -0
  525. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js.map +1 -1
  526. package/codeyam-cli/src/utils/queue/job.js +249 -16
  527. package/codeyam-cli/src/utils/queue/job.js.map +1 -1
  528. package/codeyam-cli/src/utils/queue/manager.js +103 -7
  529. package/codeyam-cli/src/utils/queue/manager.js.map +1 -1
  530. package/codeyam-cli/src/utils/queue/persistence.js.map +1 -1
  531. package/codeyam-cli/src/utils/requireSimulations.js +10 -0
  532. package/codeyam-cli/src/utils/requireSimulations.js.map +1 -0
  533. package/codeyam-cli/src/utils/ruleReflection/__tests__/confusionDetector.test.js +82 -0
  534. package/codeyam-cli/src/utils/ruleReflection/__tests__/confusionDetector.test.js.map +1 -0
  535. package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js +229 -0
  536. package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js.map +1 -0
  537. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js +67 -0
  538. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js.map +1 -0
  539. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/captureFixture.js +105 -0
  540. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/captureFixture.js.map +1 -0
  541. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/loadCapturedFixture.js +34 -0
  542. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/loadCapturedFixture.js.map +1 -0
  543. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/runClaude.js +162 -0
  544. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/runClaude.js.map +1 -0
  545. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js +74 -0
  546. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js.map +1 -0
  547. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js +376 -0
  548. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js.map +1 -0
  549. package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js +113 -0
  550. package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js.map +1 -0
  551. package/codeyam-cli/src/utils/ruleReflection/__tests__/transcriptParser.test.js +127 -0
  552. package/codeyam-cli/src/utils/ruleReflection/__tests__/transcriptParser.test.js.map +1 -0
  553. package/codeyam-cli/src/utils/ruleReflection/confusionDetector.js +50 -0
  554. package/codeyam-cli/src/utils/ruleReflection/confusionDetector.js.map +1 -0
  555. package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js +116 -0
  556. package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js.map +1 -0
  557. package/codeyam-cli/src/utils/ruleReflection/index.js +5 -0
  558. package/codeyam-cli/src/utils/ruleReflection/index.js.map +1 -0
  559. package/codeyam-cli/src/utils/ruleReflection/promptBuilder.js +44 -0
  560. package/codeyam-cli/src/utils/ruleReflection/promptBuilder.js.map +1 -0
  561. package/codeyam-cli/src/utils/ruleReflection/transcriptParser.js +85 -0
  562. package/codeyam-cli/src/utils/ruleReflection/transcriptParser.js.map +1 -0
  563. package/codeyam-cli/src/utils/ruleReflection/types.js +5 -0
  564. package/codeyam-cli/src/utils/ruleReflection/types.js.map +1 -0
  565. package/codeyam-cli/src/utils/rules/__tests__/parser.test.js +83 -0
  566. package/codeyam-cli/src/utils/rules/__tests__/parser.test.js.map +1 -0
  567. package/codeyam-cli/src/utils/rules/__tests__/pathMatcher.test.js +118 -0
  568. package/codeyam-cli/src/utils/rules/__tests__/pathMatcher.test.js.map +1 -0
  569. package/codeyam-cli/src/utils/rules/__tests__/rulePlacement.test.js +72 -0
  570. package/codeyam-cli/src/utils/rules/__tests__/rulePlacement.test.js.map +1 -0
  571. package/codeyam-cli/src/utils/rules/__tests__/ruleState.test.js +293 -0
  572. package/codeyam-cli/src/utils/rules/__tests__/ruleState.test.js.map +1 -0
  573. package/codeyam-cli/src/utils/rules/__tests__/sourceFiles.test.js +76 -0
  574. package/codeyam-cli/src/utils/rules/__tests__/sourceFiles.test.js.map +1 -0
  575. package/codeyam-cli/src/utils/rules/index.js +7 -0
  576. package/codeyam-cli/src/utils/rules/index.js.map +1 -0
  577. package/codeyam-cli/src/utils/rules/parser.js +93 -0
  578. package/codeyam-cli/src/utils/rules/parser.js.map +1 -0
  579. package/codeyam-cli/src/utils/rules/pathMatcher.js +49 -0
  580. package/codeyam-cli/src/utils/rules/pathMatcher.js.map +1 -0
  581. package/codeyam-cli/src/utils/rules/rulePlacement.js +65 -0
  582. package/codeyam-cli/src/utils/rules/rulePlacement.js.map +1 -0
  583. package/codeyam-cli/src/utils/rules/ruleState.js +150 -0
  584. package/codeyam-cli/src/utils/rules/ruleState.js.map +1 -0
  585. package/codeyam-cli/src/utils/rules/sourceFiles.js +43 -0
  586. package/codeyam-cli/src/utils/rules/sourceFiles.js.map +1 -0
  587. package/codeyam-cli/src/utils/rules/staleness.js +137 -0
  588. package/codeyam-cli/src/utils/rules/staleness.js.map +1 -0
  589. package/codeyam-cli/src/utils/serverState.js +37 -10
  590. package/codeyam-cli/src/utils/serverState.js.map +1 -1
  591. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +21 -42
  592. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
  593. package/codeyam-cli/src/utils/simulationGateMiddleware.js +159 -0
  594. package/codeyam-cli/src/utils/simulationGateMiddleware.js.map +1 -0
  595. package/codeyam-cli/src/utils/syncMocksMiddleware.js +5 -24
  596. package/codeyam-cli/src/utils/syncMocksMiddleware.js.map +1 -1
  597. package/codeyam-cli/src/utils/versionInfo.js +67 -15
  598. package/codeyam-cli/src/utils/versionInfo.js.map +1 -1
  599. package/codeyam-cli/src/utils/wipe.js +128 -0
  600. package/codeyam-cli/src/utils/wipe.js.map +1 -0
  601. package/codeyam-cli/src/webserver/__tests__/dependency-smoke.test.js +66 -0
  602. package/codeyam-cli/src/webserver/__tests__/dependency-smoke.test.js.map +1 -0
  603. package/codeyam-cli/src/webserver/app/lib/database.js +118 -6
  604. package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
  605. package/codeyam-cli/src/webserver/app/lib/dbNotifier.js.map +1 -1
  606. package/codeyam-cli/src/webserver/app/routes/api.agent-transcripts.js +486 -0
  607. package/codeyam-cli/src/webserver/app/routes/api.agent-transcripts.js.map +1 -0
  608. package/codeyam-cli/src/webserver/backgroundServer.js +65 -10
  609. package/codeyam-cli/src/webserver/backgroundServer.js.map +1 -1
  610. package/codeyam-cli/src/webserver/bootstrap.js +60 -0
  611. package/codeyam-cli/src/webserver/bootstrap.js.map +1 -0
  612. package/codeyam-cli/src/webserver/build/client/assets/CopyButton-CtmbP4Gl.js +1 -0
  613. package/codeyam-cli/src/webserver/build/client/assets/EntityItem-DlMph_Hm.js +11 -0
  614. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeBadge-kykTbcnD.js → EntityTypeBadge-B-0PjGOU.js} +1 -1
  615. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-DN9eiJAO.js +41 -0
  616. package/codeyam-cli/src/webserver/build/client/assets/InlineSpinner-C1rIyZdV.js +34 -0
  617. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-rE_fI2h2.js +25 -0
  618. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-CnatsCw2.js +3 -0
  619. package/codeyam-cli/src/webserver/build/client/assets/LoadingDots-CSP6DZrh.js +6 -0
  620. package/codeyam-cli/src/webserver/build/client/assets/LogViewer-CMK8Q7yk.js +3 -0
  621. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-TCV_HBjy.js +11 -0
  622. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-CG2uh31y.js +1 -0
  623. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-CU_TDYd8.js +10 -0
  624. package/codeyam-cli/src/webserver/build/client/assets/{TruncatedFilePath-C06nsHKY.js → TruncatedFilePath-D7IoaWUW.js} +1 -1
  625. package/codeyam-cli/src/webserver/build/client/assets/_index-B8z7mjR-.js +11 -0
  626. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-DZu78RI1.js +27 -0
  627. package/codeyam-cli/src/webserver/build/client/assets/agent-transcripts-DxCa1oBt.js +23 -0
  628. package/codeyam-cli/src/webserver/build/client/assets/api.agent-transcripts-l0sNRNKZ.js +1 -0
  629. package/codeyam-cli/src/webserver/build/client/assets/api.health-l0sNRNKZ.js +1 -0
  630. package/codeyam-cli/src/webserver/build/client/assets/api.labs-unlock-l0sNRNKZ.js +1 -0
  631. package/codeyam-cli/src/webserver/build/client/assets/api.memory-profile-l0sNRNKZ.js +1 -0
  632. package/codeyam-cli/src/webserver/build/client/assets/api.restart-server-l0sNRNKZ.js +1 -0
  633. package/codeyam-cli/src/webserver/build/client/assets/api.rule-path-l0sNRNKZ.js +1 -0
  634. package/codeyam-cli/src/webserver/build/client/assets/api.save-fixture-l0sNRNKZ.js +1 -0
  635. package/codeyam-cli/src/webserver/build/client/assets/book-open-Bp5FLkd4.js +6 -0
  636. package/codeyam-cli/src/webserver/build/client/assets/chevron-down-DQJA9f4o.js +6 -0
  637. package/codeyam-cli/src/webserver/build/client/assets/chunk-JZWAC4HX-7VptmeIr.js +51 -0
  638. package/codeyam-cli/src/webserver/build/client/assets/circle-check-B6C4LY9o.js +6 -0
  639. package/codeyam-cli/src/webserver/build/client/assets/copy-6nzYCu0G.js +11 -0
  640. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-D-QUFOwe.js +21 -0
  641. package/codeyam-cli/src/webserver/build/client/assets/{cy-logo-cli-C1gnJVOL.svg → cy-logo-cli-CCKUIm0S.svg} +2 -2
  642. package/codeyam-cli/src/webserver/build/client/assets/cy-logo-cli-DcX-ZS3p.js +1 -0
  643. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-DmzSmblj.js +1 -0
  644. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-CYqBrC9s.js → entity._sha._--zvFJ4OH.js} +22 -15
  645. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-DVTcUnur.js +6 -0
  646. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-BVgNO76F.js +6 -0
  647. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-C7ysA4Jq.js +5 -0
  648. package/codeyam-cli/src/webserver/build/client/assets/entry.client-CU6EUArK.js +29 -0
  649. package/codeyam-cli/src/webserver/build/client/assets/executionFlowCoverage-BWhdfn70.js +1 -0
  650. package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-EWpfFU4X.js +1 -0
  651. package/codeyam-cli/src/webserver/build/client/assets/files-CrxAoWIL.js +1 -0
  652. package/codeyam-cli/src/webserver/build/client/assets/git-BldHtKeW.js +15 -0
  653. package/codeyam-cli/src/webserver/build/client/assets/globals-B4MPiL7S.css +1 -0
  654. package/codeyam-cli/src/webserver/build/client/assets/html2canvas-pro.esm-fmIEn3Bc.js +9 -0
  655. package/codeyam-cli/src/webserver/build/client/assets/index-7-1FmlHo.js +9 -0
  656. package/codeyam-cli/src/webserver/build/client/assets/index-DuYcwYp_.js +3 -0
  657. package/codeyam-cli/src/webserver/build/client/assets/labs-CPPVOSWB.js +1 -0
  658. package/codeyam-cli/src/webserver/build/client/assets/loader-circle-BnDcD54R.js +6 -0
  659. package/codeyam-cli/src/webserver/build/client/assets/manifest-c1fc3656.js +1 -0
  660. package/codeyam-cli/src/webserver/build/client/assets/memory-CfpYxpNu.js +93 -0
  661. package/codeyam-cli/src/webserver/build/client/assets/pause-DhQX2g22.js +11 -0
  662. package/codeyam-cli/src/webserver/build/client/assets/preload-helper-ckwbz45p.js +1 -0
  663. package/codeyam-cli/src/webserver/build/client/assets/root-CAAbm4U5.js +62 -0
  664. package/codeyam-cli/src/webserver/build/client/assets/scenarioStatus-B_8jpV3e.js +1 -0
  665. package/codeyam-cli/src/webserver/build/client/assets/search-DborVoKD.js +6 -0
  666. package/codeyam-cli/src/webserver/build/client/assets/settings-BpLDWmGh.js +1 -0
  667. package/codeyam-cli/src/webserver/build/client/assets/simulations-BtrtCYJg.js +1 -0
  668. package/codeyam-cli/src/webserver/build/client/assets/terminal-Bs4NC-VZ.js +11 -0
  669. package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-DTf3Jojp.js +6 -0
  670. package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-D_bDZyDU.js +1 -0
  671. package/codeyam-cli/src/webserver/build/client/assets/{useLastLogLine-Blr5oZDE.js → useLastLogLine-DZp6rrQD.js} +1 -1
  672. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-BsQb6rFd.js +1 -0
  673. package/codeyam-cli/src/webserver/build/client/assets/{useToast-Bbf4Hokd.js → useToast-BOur3mUv.js} +1 -1
  674. package/codeyam-cli/src/webserver/build/server/assets/index-B8A_aaGG.js +1 -0
  675. package/codeyam-cli/src/webserver/build/server/assets/server-build-69rRZnZo.js +286 -0
  676. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  677. package/codeyam-cli/src/webserver/build-info.json +5 -5
  678. package/codeyam-cli/src/webserver/devServer.js +1 -3
  679. package/codeyam-cli/src/webserver/devServer.js.map +1 -1
  680. package/codeyam-cli/src/webserver/server.js +35 -25
  681. package/codeyam-cli/src/webserver/server.js.map +1 -1
  682. package/codeyam-cli/templates/{codeyam-debug-skill.md → codeyam-debug.md} +48 -4
  683. package/codeyam-cli/templates/codeyam-diagnose.md +481 -0
  684. package/codeyam-cli/templates/codeyam-memory-hook.sh +199 -0
  685. package/codeyam-cli/templates/codeyam-memory.md +396 -0
  686. package/codeyam-cli/templates/codeyam-new-rule.md +11 -0
  687. package/codeyam-cli/templates/{codeyam-setup-skill.md → codeyam-setup.md} +151 -4
  688. package/codeyam-cli/templates/{codeyam-sim-skill.md → codeyam-sim.md} +1 -1
  689. package/codeyam-cli/templates/{codeyam-test-skill.md → codeyam-test.md} +1 -1
  690. package/codeyam-cli/templates/{codeyam-verify-skill.md → codeyam-verify.md} +1 -1
  691. package/codeyam-cli/templates/hooks/staleness-check.sh +43 -0
  692. package/codeyam-cli/templates/prompts/conversation-guidance.txt +32 -0
  693. package/codeyam-cli/templates/prompts/conversation-prompt.txt +28 -0
  694. package/codeyam-cli/templates/prompts/interruption-prompt.txt +31 -0
  695. package/codeyam-cli/templates/prompts/stale-rules-prompt.txt +24 -0
  696. package/codeyam-cli/templates/rule-notification-hook.py +56 -0
  697. package/codeyam-cli/templates/rule-reflection-hook.py +627 -0
  698. package/codeyam-cli/templates/rules-instructions.md +77 -0
  699. package/package.json +26 -23
  700. package/packages/ai/index.js +8 -6
  701. package/packages/ai/index.js.map +1 -1
  702. package/packages/ai/src/lib/analyzeScope.js +181 -13
  703. package/packages/ai/src/lib/analyzeScope.js.map +1 -1
  704. package/packages/ai/src/lib/astScopes/arrayDerivationDetector.js +150 -0
  705. package/packages/ai/src/lib/astScopes/arrayDerivationDetector.js.map +1 -0
  706. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js +154 -9
  707. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js.map +1 -1
  708. package/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.js +435 -0
  709. package/packages/ai/src/lib/astScopes/conditionalEffectsExtractor.js.map +1 -0
  710. package/packages/ai/src/lib/astScopes/methodSemantics.js +138 -23
  711. package/packages/ai/src/lib/astScopes/methodSemantics.js.map +1 -1
  712. package/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.js +10 -14
  713. package/packages/ai/src/lib/astScopes/patterns/forInStatementHandler.js.map +1 -1
  714. package/packages/ai/src/lib/astScopes/patterns/ifStatementHandler.js +8 -0
  715. package/packages/ai/src/lib/astScopes/patterns/ifStatementHandler.js.map +1 -1
  716. package/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.js +23 -0
  717. package/packages/ai/src/lib/astScopes/patterns/switchStatementHandler.js.map +1 -1
  718. package/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.js +138 -1
  719. package/packages/ai/src/lib/astScopes/patterns/variableDeclarationHandler.js.map +1 -1
  720. package/packages/ai/src/lib/astScopes/processExpression.js +1235 -104
  721. package/packages/ai/src/lib/astScopes/processExpression.js.map +1 -1
  722. package/packages/ai/src/lib/astScopes/sharedPatterns.js +25 -0
  723. package/packages/ai/src/lib/astScopes/sharedPatterns.js.map +1 -1
  724. package/packages/ai/src/lib/checkAllAttributes.js +24 -9
  725. package/packages/ai/src/lib/checkAllAttributes.js.map +1 -1
  726. package/packages/ai/src/lib/completionCall.js +178 -36
  727. package/packages/ai/src/lib/completionCall.js.map +1 -1
  728. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +2171 -224
  729. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
  730. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js +19 -4
  731. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/JavascriptFrameworkManager.js.map +1 -1
  732. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js +661 -0
  733. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/MuiManager.js.map +1 -0
  734. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js +180 -56
  735. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js.map +1 -1
  736. package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js +13 -3
  737. package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js.map +1 -1
  738. package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js +6 -4
  739. package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js.map +1 -1
  740. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js +66 -2
  741. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js.map +1 -1
  742. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js +139 -13
  743. package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js.map +1 -1
  744. package/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.js +63 -0
  745. package/packages/ai/src/lib/dataStructure/helpers/coerceObjectsToPrimitivesBySchema.js.map +1 -0
  746. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js +142 -12
  747. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js.map +1 -1
  748. package/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.js +86 -0
  749. package/packages/ai/src/lib/dataStructure/helpers/convertNullToUndefinedBySchema.js.map +1 -0
  750. package/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.js +173 -0
  751. package/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.js.map +1 -0
  752. package/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.js +37 -20
  753. package/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.js.map +1 -1
  754. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js +371 -73
  755. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js.map +1 -1
  756. package/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.js +107 -0
  757. package/packages/ai/src/lib/dataStructure/helpers/fixNullIdsBySchema.js.map +1 -0
  758. package/packages/ai/src/lib/dataStructureChunking.js +130 -0
  759. package/packages/ai/src/lib/dataStructureChunking.js.map +1 -0
  760. package/packages/ai/src/lib/deepEqual.js +32 -0
  761. package/packages/ai/src/lib/deepEqual.js.map +1 -0
  762. package/packages/ai/src/lib/e2eDataTracking.js +241 -0
  763. package/packages/ai/src/lib/e2eDataTracking.js.map +1 -0
  764. package/packages/ai/src/lib/extractCriticalDataKeys.js +96 -0
  765. package/packages/ai/src/lib/extractCriticalDataKeys.js.map +1 -0
  766. package/packages/ai/src/lib/generateChangesEntityScenarioData.js +62 -5
  767. package/packages/ai/src/lib/generateChangesEntityScenarioData.js.map +1 -1
  768. package/packages/ai/src/lib/generateChangesEntityScenarios.js +81 -90
  769. package/packages/ai/src/lib/generateChangesEntityScenarios.js.map +1 -1
  770. package/packages/ai/src/lib/generateEntityDataStructure.js +50 -1
  771. package/packages/ai/src/lib/generateEntityDataStructure.js.map +1 -1
  772. package/packages/ai/src/lib/generateEntityScenarioData.js +1128 -85
  773. package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
  774. package/packages/ai/src/lib/generateEntityScenarios.js +193 -83
  775. package/packages/ai/src/lib/generateEntityScenarios.js.map +1 -1
  776. package/packages/ai/src/lib/generateExecutionFlows.js +495 -0
  777. package/packages/ai/src/lib/generateExecutionFlows.js.map +1 -0
  778. package/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.js +380 -0
  779. package/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.js.map +1 -0
  780. package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js +1807 -0
  781. package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js.map +1 -0
  782. package/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.js +194 -0
  783. package/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.js.map +1 -0
  784. package/packages/ai/src/lib/getConditionalUsagesFromCode.js +84 -14
  785. package/packages/ai/src/lib/getConditionalUsagesFromCode.js.map +1 -1
  786. package/packages/ai/src/lib/guessScenarioDataFromDescription.js +2 -1
  787. package/packages/ai/src/lib/guessScenarioDataFromDescription.js.map +1 -1
  788. package/packages/ai/src/lib/isolateScopes.js +270 -7
  789. package/packages/ai/src/lib/isolateScopes.js.map +1 -1
  790. package/packages/ai/src/lib/mergeJsonTypeDefinitions.js +5 -0
  791. package/packages/ai/src/lib/mergeJsonTypeDefinitions.js.map +1 -1
  792. package/packages/ai/src/lib/mergeStatements.js +88 -46
  793. package/packages/ai/src/lib/mergeStatements.js.map +1 -1
  794. package/packages/ai/src/lib/promptGenerators/collapseNullableObjects.js +97 -0
  795. package/packages/ai/src/lib/promptGenerators/collapseNullableObjects.js.map +1 -0
  796. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js +16 -4
  797. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js.map +1 -1
  798. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js +1 -1
  799. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js.map +1 -1
  800. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js +21 -64
  801. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js.map +1 -1
  802. package/packages/ai/src/lib/promptGenerators/generateChunkPrompt.js +54 -0
  803. package/packages/ai/src/lib/promptGenerators/generateChunkPrompt.js.map +1 -0
  804. package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js +83 -6
  805. package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js.map +1 -1
  806. package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js +10 -34
  807. package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js.map +1 -1
  808. package/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.js +45 -0
  809. package/packages/ai/src/lib/promptGenerators/generateMissingKeysPrompt.js.map +1 -0
  810. package/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.js +16 -3
  811. package/packages/ai/src/lib/promptGenerators/guessNewScenarioDataFromDescriptionGenerator.js.map +1 -1
  812. package/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.js +335 -0
  813. package/packages/ai/src/lib/promptGenerators/simplifyKeysForLLM.js.map +1 -0
  814. package/packages/ai/src/lib/resolvePathToControllable.js +677 -0
  815. package/packages/ai/src/lib/resolvePathToControllable.js.map +1 -0
  816. package/packages/ai/src/lib/splitOutsideParentheses.js +3 -1
  817. package/packages/ai/src/lib/splitOutsideParentheses.js.map +1 -1
  818. package/packages/ai/src/lib/worker/SerializableDataStructure.js +29 -0
  819. package/packages/ai/src/lib/worker/SerializableDataStructure.js.map +1 -1
  820. package/packages/ai/src/lib/worker/analyzeScopeWorker.js +98 -1
  821. package/packages/ai/src/lib/worker/analyzeScopeWorker.js.map +1 -1
  822. package/packages/analyze/index.js +1 -0
  823. package/packages/analyze/index.js.map +1 -1
  824. package/packages/analyze/src/lib/FileAnalyzer.js +75 -36
  825. package/packages/analyze/src/lib/FileAnalyzer.js.map +1 -1
  826. package/packages/analyze/src/lib/ProjectAnalyzer.js +96 -26
  827. package/packages/analyze/src/lib/ProjectAnalyzer.js.map +1 -1
  828. package/packages/analyze/src/lib/analysisContext.js +30 -5
  829. package/packages/analyze/src/lib/analysisContext.js.map +1 -1
  830. package/packages/analyze/src/lib/asts/nodes/getNodeType.js +1 -0
  831. package/packages/analyze/src/lib/asts/nodes/getNodeType.js.map +1 -1
  832. package/packages/analyze/src/lib/asts/nodes/index.js +1 -0
  833. package/packages/analyze/src/lib/asts/nodes/index.js.map +1 -1
  834. package/packages/analyze/src/lib/asts/nodes/isAsyncFunction.js +52 -0
  835. package/packages/analyze/src/lib/asts/nodes/isAsyncFunction.js.map +1 -0
  836. package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js +14 -0
  837. package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js.map +1 -1
  838. package/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.js +14 -0
  839. package/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.js.map +1 -1
  840. package/packages/analyze/src/lib/asts/sourceFiles/getAllExports.js +6 -0
  841. package/packages/analyze/src/lib/asts/sourceFiles/getAllExports.js.map +1 -1
  842. package/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.js +6 -0
  843. package/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.js.map +1 -1
  844. package/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.js +39 -1
  845. package/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.js.map +1 -1
  846. package/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.js +2 -1
  847. package/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.js.map +1 -1
  848. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +428 -123
  849. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
  850. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +42 -1
  851. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
  852. package/packages/analyze/src/lib/files/analyze/dependencyResolver.js +5 -0
  853. package/packages/analyze/src/lib/files/analyze/dependencyResolver.js.map +1 -1
  854. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js +2 -0
  855. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js.map +1 -1
  856. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js +2 -1
  857. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js.map +1 -1
  858. package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js +31 -10
  859. package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js.map +1 -1
  860. package/packages/analyze/src/lib/files/analyzeChange.js +21 -11
  861. package/packages/analyze/src/lib/files/analyzeChange.js.map +1 -1
  862. package/packages/analyze/src/lib/files/analyzeEntity.js +9 -8
  863. package/packages/analyze/src/lib/files/analyzeEntity.js.map +1 -1
  864. package/packages/analyze/src/lib/files/analyzeInitial.js +9 -10
  865. package/packages/analyze/src/lib/files/analyzeInitial.js.map +1 -1
  866. package/packages/analyze/src/lib/files/analyzeRemixRoute.js +3 -2
  867. package/packages/analyze/src/lib/files/analyzeRemixRoute.js.map +1 -1
  868. package/packages/analyze/src/lib/files/enums/steps.js +1 -1
  869. package/packages/analyze/src/lib/files/enums/steps.js.map +1 -1
  870. package/packages/analyze/src/lib/files/getImportedExports.js +17 -8
  871. package/packages/analyze/src/lib/files/getImportedExports.js.map +1 -1
  872. package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js +880 -0
  873. package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js.map +1 -0
  874. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js +255 -0
  875. package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js.map +1 -0
  876. package/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.js +85 -0
  877. package/packages/analyze/src/lib/files/scenarios/enrichUnknownTypesFromSourceEquivalencies.js.map +1 -0
  878. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js +536 -73
  879. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js.map +1 -1
  880. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.js +1 -1
  881. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarioData.js.map +1 -1
  882. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.js +29 -34
  883. package/packages/analyze/src/lib/files/scenarios/generateChangesScenarios.js.map +1 -1
  884. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +404 -85
  885. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
  886. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js +144 -0
  887. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js.map +1 -0
  888. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js +56 -69
  889. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js.map +1 -1
  890. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js +4 -8
  891. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js.map +1 -1
  892. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +875 -141
  893. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
  894. package/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.js +46 -9
  895. package/packages/analyze/src/lib/files/scenarios/mergeValidatedDataStructures.js.map +1 -1
  896. package/packages/analyze/src/lib/files/setImportedExports.js +2 -1
  897. package/packages/analyze/src/lib/files/setImportedExports.js.map +1 -1
  898. package/packages/analyze/src/lib/index.js +1 -0
  899. package/packages/analyze/src/lib/index.js.map +1 -1
  900. package/packages/analyze/src/lib/utils/getFileByPath.js +12 -0
  901. package/packages/analyze/src/lib/utils/getFileByPath.js.map +1 -0
  902. package/packages/aws/src/lib/ecs/ecsDefineContainer.js +2 -2
  903. package/packages/aws/src/lib/ecs/ecsDefineContainer.js.map +1 -1
  904. package/packages/aws/src/lib/ecs/ecsTaskFactory.js +17 -61
  905. package/packages/aws/src/lib/ecs/ecsTaskFactory.js.map +1 -1
  906. package/packages/database/src/lib/analysisBranchToDb.js +1 -1
  907. package/packages/database/src/lib/analysisBranchToDb.js.map +1 -1
  908. package/packages/database/src/lib/analysisToDb.js +1 -1
  909. package/packages/database/src/lib/analysisToDb.js.map +1 -1
  910. package/packages/database/src/lib/branchToDb.js +1 -1
  911. package/packages/database/src/lib/branchToDb.js.map +1 -1
  912. package/packages/database/src/lib/commitBranchToDb.js +1 -1
  913. package/packages/database/src/lib/commitBranchToDb.js.map +1 -1
  914. package/packages/database/src/lib/commitToDb.js +1 -1
  915. package/packages/database/src/lib/commitToDb.js.map +1 -1
  916. package/packages/database/src/lib/fileToDb.js +1 -1
  917. package/packages/database/src/lib/fileToDb.js.map +1 -1
  918. package/packages/database/src/lib/kysely/db.js +13 -3
  919. package/packages/database/src/lib/kysely/db.js.map +1 -1
  920. package/packages/database/src/lib/kysely/tables/commitsTable.js +3 -0
  921. package/packages/database/src/lib/kysely/tables/commitsTable.js.map +1 -1
  922. package/packages/database/src/lib/kysely/tables/debugReportsTable.js +9 -3
  923. package/packages/database/src/lib/kysely/tables/debugReportsTable.js.map +1 -1
  924. package/packages/database/src/lib/kysely/tables/labsRequestsTable.js +35 -0
  925. package/packages/database/src/lib/kysely/tables/labsRequestsTable.js.map +1 -0
  926. package/packages/database/src/lib/loadAnalyses.js +45 -2
  927. package/packages/database/src/lib/loadAnalyses.js.map +1 -1
  928. package/packages/database/src/lib/loadAnalysis.js +8 -0
  929. package/packages/database/src/lib/loadAnalysis.js.map +1 -1
  930. package/packages/database/src/lib/loadBranch.js +11 -1
  931. package/packages/database/src/lib/loadBranch.js.map +1 -1
  932. package/packages/database/src/lib/loadCommit.js +7 -0
  933. package/packages/database/src/lib/loadCommit.js.map +1 -1
  934. package/packages/database/src/lib/loadCommits.js +22 -1
  935. package/packages/database/src/lib/loadCommits.js.map +1 -1
  936. package/packages/database/src/lib/loadEntities.js +23 -4
  937. package/packages/database/src/lib/loadEntities.js.map +1 -1
  938. package/packages/database/src/lib/loadEntityBranches.js +9 -0
  939. package/packages/database/src/lib/loadEntityBranches.js.map +1 -1
  940. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js +23 -5
  941. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
  942. package/packages/database/src/lib/projectToDb.js +1 -1
  943. package/packages/database/src/lib/projectToDb.js.map +1 -1
  944. package/packages/database/src/lib/saveFiles.js +1 -1
  945. package/packages/database/src/lib/saveFiles.js.map +1 -1
  946. package/packages/database/src/lib/scenarioToDb.js +1 -1
  947. package/packages/database/src/lib/scenarioToDb.js.map +1 -1
  948. package/packages/database/src/lib/updateCommitMetadata.js +5 -4
  949. package/packages/database/src/lib/updateCommitMetadata.js.map +1 -1
  950. package/packages/generate/index.js +3 -0
  951. package/packages/generate/index.js.map +1 -1
  952. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +16 -1
  953. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
  954. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +189 -0
  955. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -0
  956. package/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js +53 -0
  957. package/packages/generate/src/lib/componentScenarioPage/generateScenarioServerComponent.js.map +1 -0
  958. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +8 -4
  959. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
  960. package/packages/generate/src/lib/deepMerge.js +27 -1
  961. package/packages/generate/src/lib/deepMerge.js.map +1 -1
  962. package/packages/generate/src/lib/directExecutionScript.js +10 -1
  963. package/packages/generate/src/lib/directExecutionScript.js.map +1 -1
  964. package/packages/generate/src/lib/getComponentScenarioPath.js +7 -3
  965. package/packages/generate/src/lib/getComponentScenarioPath.js.map +1 -1
  966. package/packages/generate/src/lib/scenarioComponentForServer.js +89 -0
  967. package/packages/generate/src/lib/scenarioComponentForServer.js.map +1 -0
  968. package/packages/github/src/lib/loadOrCreateCommit.js +10 -0
  969. package/packages/github/src/lib/loadOrCreateCommit.js.map +1 -1
  970. package/packages/github/src/lib/syncPrimaryBranch.js +3 -0
  971. package/packages/github/src/lib/syncPrimaryBranch.js.map +1 -1
  972. package/packages/process/index.js +3 -0
  973. package/packages/process/index.js.map +1 -0
  974. package/packages/process/src/GlobalProcessManager.js.map +1 -0
  975. package/{background/src/lib/process → packages/process/src}/ProcessManager.js +1 -1
  976. package/packages/process/src/ProcessManager.js.map +1 -0
  977. package/packages/process/src/index.js.map +1 -0
  978. package/packages/process/src/managedExecAsync.js.map +1 -0
  979. package/packages/types/index.js.map +1 -1
  980. package/packages/utils/src/lib/applyUniversalMocks.js +26 -2
  981. package/packages/utils/src/lib/applyUniversalMocks.js.map +1 -1
  982. package/packages/utils/src/lib/fs/rsyncCopy.js +98 -3
  983. package/packages/utils/src/lib/fs/rsyncCopy.js.map +1 -1
  984. package/packages/utils/src/lib/lightweightEntityExtractor.js +25 -0
  985. package/packages/utils/src/lib/lightweightEntityExtractor.js.map +1 -1
  986. package/packages/utils/src/lib/safeFileName.js +29 -3
  987. package/packages/utils/src/lib/safeFileName.js.map +1 -1
  988. package/scripts/finalize-analyzer.cjs +8 -74
  989. package/analyzer-template/packages/ai/src/lib/findMatchingAttribute.ts +0 -102
  990. package/analyzer-template/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.ts +0 -197
  991. package/analyzer-template/packages/ai/src/lib/generateChangesEntityKeyAttributes.ts +0 -271
  992. package/analyzer-template/packages/ai/src/lib/generateEntityKeyAttributes.ts +0 -294
  993. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.ts +0 -67
  994. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.ts +0 -115
  995. package/analyzer-template/process/INTEGRATION_COMPLETE.md +0 -333
  996. package/analyzer-template/process/INTEGRATION_EXAMPLE.md +0 -525
  997. package/analyzer-template/process/README.md +0 -507
  998. package/background/src/lib/process/GlobalProcessManager.js.map +0 -1
  999. package/background/src/lib/process/ProcessManager.js.map +0 -1
  1000. package/background/src/lib/process/index.js.map +0 -1
  1001. package/background/src/lib/process/managedExecAsync.js.map +0 -1
  1002. package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js +0 -238
  1003. package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js.map +0 -1
  1004. package/codeyam-cli/src/commands/detect-universal-mocks.js +0 -118
  1005. package/codeyam-cli/src/commands/detect-universal-mocks.js.map +0 -1
  1006. package/codeyam-cli/src/commands/list.js +0 -31
  1007. package/codeyam-cli/src/commands/list.js.map +0 -1
  1008. package/codeyam-cli/src/commands/webapp-info.js +0 -146
  1009. package/codeyam-cli/src/commands/webapp-info.js.map +0 -1
  1010. package/codeyam-cli/src/utils/universal-mocks.js +0 -152
  1011. package/codeyam-cli/src/utils/universal-mocks.js.map +0 -1
  1012. package/codeyam-cli/src/webserver/build/client/assets/EntityItem-D4htqD-x.js +0 -1
  1013. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-Catz6XEN.js +0 -1
  1014. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-TlHocYno.js +0 -26
  1015. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-CVMmGuIc.js +0 -3
  1016. package/codeyam-cli/src/webserver/build/client/assets/LogViewer-JkfQ-VaI.js +0 -3
  1017. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-CVZ0H4BL.js +0 -1
  1018. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-BrMAP1nP.js +0 -1
  1019. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-CJhE4cCv.js +0 -5
  1020. package/codeyam-cli/src/webserver/build/client/assets/_index-faVIcr_i.js +0 -1
  1021. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-CLMa2sgx.js +0 -7
  1022. package/codeyam-cli/src/webserver/build/client/assets/chevron-down-DwYjrK_h.js +0 -1
  1023. package/codeyam-cli/src/webserver/build/client/assets/chunk-WWGJGFF6-CgXbbZRx.js +0 -26
  1024. package/codeyam-cli/src/webserver/build/client/assets/circle-check-B2oHQ-zo.js +0 -1
  1025. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-BBYuR56H.js +0 -1
  1026. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-CT0Q5lVu.js +0 -1
  1027. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-Bj5GHkhb.js +0 -1
  1028. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-eW5z9AyZ.js +0 -5
  1029. package/codeyam-cli/src/webserver/build/client/assets/entry.client-B9tSboXM.js +0 -5
  1030. package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-CmO-EZAB.js +0 -1
  1031. package/codeyam-cli/src/webserver/build/client/assets/files-DLinnTOx.js +0 -1
  1032. package/codeyam-cli/src/webserver/build/client/assets/git-CIxwBQvb.js +0 -12
  1033. package/codeyam-cli/src/webserver/build/client/assets/globals-xPz593l2.css +0 -1
  1034. package/codeyam-cli/src/webserver/build/client/assets/html2canvas-pro.esm-XQCGvadH.js +0 -5
  1035. package/codeyam-cli/src/webserver/build/client/assets/index-_LjBsTxX.js +0 -8
  1036. package/codeyam-cli/src/webserver/build/client/assets/loader-circle-D_EGChhq.js +0 -1
  1037. package/codeyam-cli/src/webserver/build/client/assets/manifest-ca438c41.js +0 -1
  1038. package/codeyam-cli/src/webserver/build/client/assets/root-CHHYHuzL.js +0 -16
  1039. package/codeyam-cli/src/webserver/build/client/assets/search-DY8yoDpH.js +0 -1
  1040. package/codeyam-cli/src/webserver/build/client/assets/server-build-CMKNK2uU.css +0 -1
  1041. package/codeyam-cli/src/webserver/build/client/assets/settings-BT6wVHd5.js +0 -1
  1042. package/codeyam-cli/src/webserver/build/client/assets/simulations-gv3H7JV7.js +0 -1
  1043. package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-BthANBVv.js +0 -1
  1044. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-CANr3QJ5.js +0 -1
  1045. package/codeyam-cli/src/webserver/build/server/assets/index-BtBPtyHx.js +0 -1
  1046. package/codeyam-cli/src/webserver/build/server/assets/server-build-N2cTnejq.js +0 -166
  1047. package/codeyam-cli/templates/codeyam-stop-hook.sh +0 -284
  1048. package/codeyam-cli/templates/debug-command.md +0 -141
  1049. package/packages/ai/src/lib/findMatchingAttribute.js +0 -77
  1050. package/packages/ai/src/lib/findMatchingAttribute.js.map +0 -1
  1051. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js +0 -136
  1052. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js.map +0 -1
  1053. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js +0 -220
  1054. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js.map +0 -1
  1055. package/packages/ai/src/lib/generateEntityKeyAttributes.js +0 -241
  1056. package/packages/ai/src/lib/generateEntityKeyAttributes.js.map +0 -1
  1057. package/packages/ai/src/lib/isFrontend.js +0 -5
  1058. package/packages/ai/src/lib/isFrontend.js.map +0 -1
  1059. package/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.js +0 -40
  1060. package/packages/ai/src/lib/promptGenerators/generateEntityKeyAttributesGenerator.js.map +0 -1
  1061. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js +0 -72
  1062. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js.map +0 -1
  1063. /package/analyzer-template/{process → packages/process/src}/GlobalProcessManager.ts +0 -0
  1064. /package/analyzer-template/{process → packages/process/src}/ProcessManager.ts +0 -0
  1065. /package/analyzer-template/{process → packages/process/src}/index.ts +0 -0
  1066. /package/analyzer-template/{process → packages/process/src}/managedExecAsync.ts +0 -0
  1067. /package/codeyam-cli/src/webserver/build/client/assets/{InteractivePreview-CMKNK2uU.css → styles-CMKNK2uU.css} +0 -0
  1068. /package/{background/src/lib/process → packages/process/src}/GlobalProcessManager.js +0 -0
  1069. /package/{background/src/lib/process → packages/process/src}/index.js +0 -0
  1070. /package/{background/src/lib/process → packages/process/src}/managedExecAsync.js +0 -0
@@ -7,6 +7,52 @@ import { splitOutsideParenthesesAndArrays } from "../../../../../packages/ai/ind
7
7
  import * as fs from 'fs';
8
8
  import * as path from 'path';
9
9
  import ts from 'typescript';
10
+ import { applyServerOnlyMocks } from "./serverOnlyModules.js";
11
+ // Debug timing helper for tracking where time is spent
12
+ const DEBUG_TIMING = process.env.DEBUG_WRITE_SCENARIO === 'true';
13
+ let debugStartTime;
14
+ let debugLastTime;
15
+ // Timeout protection to prevent infinite hangs
16
+ const WRITE_SCENARIO_TIMEOUT_MS = parseInt(process.env.WRITE_SCENARIO_TIMEOUT_MS || '300000', // Default 5 minutes
17
+ 10);
18
+ class WriteScenarioTimeoutError extends Error {
19
+ constructor(operation, timeoutMs) {
20
+ super(`WriteScenarioComponents timed out after ${timeoutMs}ms during: ${operation}`);
21
+ this.name = 'WriteScenarioTimeoutError';
22
+ }
23
+ }
24
+ async function withTimeout(operation, promise, timeoutMs = WRITE_SCENARIO_TIMEOUT_MS) {
25
+ let timeoutId;
26
+ const timeoutPromise = new Promise((_, reject) => {
27
+ timeoutId = setTimeout(() => {
28
+ reject(new WriteScenarioTimeoutError(operation, timeoutMs));
29
+ }, timeoutMs);
30
+ });
31
+ try {
32
+ return await Promise.race([promise, timeoutPromise]);
33
+ }
34
+ finally {
35
+ if (timeoutId)
36
+ clearTimeout(timeoutId);
37
+ }
38
+ }
39
+ function debugLog(message, extra) {
40
+ if (!DEBUG_TIMING)
41
+ return;
42
+ const now = Date.now();
43
+ if (!debugStartTime) {
44
+ debugStartTime = now;
45
+ debugLastTime = now;
46
+ }
47
+ const elapsed = now - debugStartTime;
48
+ const delta = now - debugLastTime;
49
+ debugLastTime = now;
50
+ console.log(`[WriteScenario +${elapsed}ms Δ${delta}ms] ${message}`, extra ? JSON.stringify(extra, null, 2) : '');
51
+ }
52
+ function resetDebugTiming() {
53
+ debugStartTime = 0;
54
+ debugLastTime = 0;
55
+ }
10
56
  /**
11
57
  * Find the end position of the last import/export-from statement using TypeScript AST.
12
58
  * This is more reliable than regex for handling multiline imports, comments, etc.
@@ -16,7 +62,10 @@ import ts from 'typescript';
16
62
  */
17
63
  function findEndOfImports(content) {
18
64
  try {
19
- const sourceFile = ts.createSourceFile('temp.ts', content, ts.ScriptTarget.Latest, true);
65
+ // Use temp.tsx to enable JSX parsing - otherwise TypeScript may misparse
66
+ // JSX content containing the word "import" (e.g., "Entities that import this")
67
+ // as an import statement, causing mock code to be inserted in the wrong location.
68
+ const sourceFile = ts.createSourceFile('temp.tsx', content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
20
69
  let lastImportEnd = 0;
21
70
  // Visit all top-level statements to find import/export declarations
22
71
  for (const statement of sourceFile.statements) {
@@ -45,6 +94,106 @@ function findEndOfImports(content) {
45
94
  function escapeRegExp(str) {
46
95
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
47
96
  }
97
+ /**
98
+ * Remove a named import from file content using TypeScript AST.
99
+ * Handles both regular imports (`EntityName`) and type-only imports (`type EntityName`).
100
+ *
101
+ * @param fileContent - The file content to modify
102
+ * @param entityName - The name of the entity to remove from imports
103
+ * @returns The modified file content with the entity removed from imports
104
+ */
105
+ function removeNamedImportAst(fileContent, entityName) {
106
+ try {
107
+ const sourceFile = ts.createSourceFile('temp.tsx', fileContent, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
108
+ const replacements = [];
109
+ for (const statement of sourceFile.statements) {
110
+ if (!ts.isImportDeclaration(statement))
111
+ continue;
112
+ if (!statement.importClause?.namedBindings)
113
+ continue;
114
+ if (!ts.isNamedImports(statement.importClause.namedBindings))
115
+ continue;
116
+ const namedImports = statement.importClause.namedBindings;
117
+ const elements = namedImports.elements;
118
+ // Find the element that matches our entity name
119
+ const matchingIndex = elements.findIndex((el) => el.name.text === entityName);
120
+ if (matchingIndex === -1)
121
+ continue;
122
+ // Check if there's a default import (e.g., `import DefaultName, { NamedImport } from '...'`)
123
+ const hasDefaultImport = !!statement.importClause.name;
124
+ // If this is the only named import AND there's no default import, remove the entire statement
125
+ if (elements.length === 1 && !hasDefaultImport) {
126
+ // Find the end including any trailing newline
127
+ let end = statement.getEnd();
128
+ const afterStatement = fileContent.slice(end);
129
+ const trailingNewline = afterStatement.match(/^\r?\n/);
130
+ if (trailingNewline) {
131
+ end += trailingNewline[0].length;
132
+ }
133
+ replacements.push({
134
+ start: statement.getStart(sourceFile),
135
+ end,
136
+ replacement: '',
137
+ });
138
+ continue;
139
+ }
140
+ // Otherwise, rebuild the import without this element
141
+ const remainingElements = elements.filter((_, i) => i !== matchingIndex);
142
+ // Get the module specifier
143
+ const moduleSpecifier = statement.moduleSpecifier;
144
+ if (!ts.isStringLiteral(moduleSpecifier))
145
+ continue;
146
+ // Preserve import type modifier if present
147
+ const importTypePrefix = statement.importClause.isTypeOnly ? 'type ' : '';
148
+ // Get the default import name if present
149
+ const defaultImportName = statement.importClause.name?.text;
150
+ let newImport;
151
+ if (remainingElements.length === 0) {
152
+ // All named imports were removed, but there's a default import to preserve
153
+ // (we only get here when hasDefaultImport is true, because otherwise we'd have
154
+ // removed the whole statement at the elements.length === 1 check above)
155
+ newImport = `import ${defaultImportName} from ${moduleSpecifier.getText(sourceFile)};`;
156
+ }
157
+ else {
158
+ // Build the new named imports string
159
+ const newNamedImports = remainingElements
160
+ .map((el) => {
161
+ const isTypeOnly = el.isTypeOnly;
162
+ const name = el.name.text;
163
+ const propertyName = el.propertyName?.text;
164
+ if (propertyName) {
165
+ return isTypeOnly
166
+ ? `type ${propertyName} as ${name}`
167
+ : `${propertyName} as ${name}`;
168
+ }
169
+ return isTypeOnly ? `type ${name}` : name;
170
+ })
171
+ .join(', ');
172
+ // Build the new import statement, preserving default import if present
173
+ const defaultImportPrefix = defaultImportName
174
+ ? `${defaultImportName}, `
175
+ : '';
176
+ newImport = `import ${importTypePrefix}${defaultImportPrefix}{ ${newNamedImports} } from ${moduleSpecifier.getText(sourceFile)};`;
177
+ }
178
+ replacements.push({
179
+ start: statement.getStart(sourceFile),
180
+ end: statement.getEnd(),
181
+ replacement: newImport,
182
+ });
183
+ }
184
+ // Apply replacements in reverse order to preserve positions
185
+ let result = fileContent;
186
+ replacements.sort((a, b) => b.start - a.start);
187
+ for (const { start, end, replacement } of replacements) {
188
+ result = result.slice(0, start) + replacement + result.slice(end);
189
+ }
190
+ return result;
191
+ }
192
+ catch (error) {
193
+ console.warn('[removeNamedImportAst] Failed to parse file:', error);
194
+ return fileContent; // Return original content on error
195
+ }
196
+ }
48
197
  /**
49
198
  * Map nested dist paths to src paths.
50
199
  * Some build tools create nested structures like:
@@ -123,7 +272,6 @@ function convertDtsToStubs(content, entityName) {
123
272
  result = result.replace(/export\s*\{\s*\}\s*;?\s*$/g, '');
124
273
  // Keep export type and export interface statements as-is (they're valid in .ts)
125
274
  // No transformation needed for these
126
- console.log(`CodeYam: Converted .d.ts content for entity "${entityName}". Result length: ${result.length}`);
127
275
  return result;
128
276
  }
129
277
  /**
@@ -261,7 +409,6 @@ function stripHtmlBodyTags(fileContent, filePath, framework) {
261
409
  if (!/<html[^>]*>/.test(fileContent) || !/<body[^>]*>/.test(fileContent)) {
262
410
  return fileContent;
263
411
  }
264
- console.log(`CodeYam: Stripping <html> and <body> tags from root layout: ${filePath}`);
265
412
  // Extract the body className/attributes if any, to preserve styling
266
413
  const bodyMatch = fileContent.match(/<body([^>]*)>/);
267
414
  const bodyAttributes = bodyMatch?.[1]?.trim() || '';
@@ -299,10 +446,146 @@ function stripHtmlBodyTags(fileContent, filePath, framework) {
299
446
  }
300
447
  return result;
301
448
  }
449
+ /**
450
+ * Strip `import "server-only"` or `import 'server-only'` directives from file content.
451
+ *
452
+ * Next.js "server-only" package is used to mark modules that should only run on the server.
453
+ * When we generate scenario components for client-side rendering in the browser, importing
454
+ * a file with this directive causes an error:
455
+ *
456
+ * "You're importing a component that needs 'server-only'. That only works in a Server Component"
457
+ *
458
+ * Since our scenario components are rendered client-side for capture purposes, we need to
459
+ * strip this import to allow the file to be imported.
460
+ */
461
+ function stripServerOnlyImport(fileContent) {
462
+ // Match import "server-only" or import 'server-only' with optional semicolon and newline
463
+ // Handles both double and single quotes, with or without trailing semicolon
464
+ return fileContent.replace(/import\s+["']server-only["'];?\s*\n?/g, '');
465
+ }
466
+ /**
467
+ * Extract all internal import paths from file content.
468
+ * Internal imports are those that start with '.', '@/', '~/', or are relative paths.
469
+ * Excludes node_modules imports (bare specifiers like 'react', '@prisma/client').
470
+ */
471
+ function extractInternalImportPaths(fileContent) {
472
+ // Always use AST parsing - regex with nested quantifiers can cause catastrophic
473
+ // backtracking that hangs on a single .exec() call (before iteration limits kick in)
474
+ return extractInternalImportPathsAst(fileContent);
475
+ }
476
+ /**
477
+ * Extract internal import paths using TypeScript AST - more reliable for large files
478
+ */
479
+ function extractInternalImportPathsAst(fileContent) {
480
+ const importPaths = [];
481
+ try {
482
+ // Use temp.tsx to enable JSX parsing for consistent handling of JSX files
483
+ const sourceFile = ts.createSourceFile('temp.tsx', fileContent, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
484
+ for (const statement of sourceFile.statements) {
485
+ if (ts.isImportDeclaration(statement) && statement.moduleSpecifier) {
486
+ const moduleSpecifier = statement.moduleSpecifier;
487
+ if (ts.isStringLiteral(moduleSpecifier)) {
488
+ const importPath = moduleSpecifier.text;
489
+ // Skip node_modules imports (bare specifiers)
490
+ if (importPath.startsWith('.') ||
491
+ importPath.startsWith('@/') ||
492
+ importPath.startsWith('~/') ||
493
+ importPath.startsWith('#')) {
494
+ importPaths.push(importPath);
495
+ }
496
+ }
497
+ }
498
+ }
499
+ }
500
+ catch (error) {
501
+ console.warn('[extractInternalImportPathsAst] Failed to parse file:', error);
502
+ }
503
+ return importPaths;
504
+ }
505
+ /**
506
+ * Resolve an import path to a file path relative to the project.
507
+ * Handles path aliases like @/, ~/, and relative paths.
508
+ */
509
+ function resolveImportPath(importPath, currentFilePath, project) {
510
+ let resolvedPath;
511
+ let appPrefix = '';
512
+ if (importPath.startsWith('./') || importPath.startsWith('../')) {
513
+ // Relative import - resolve relative to current file
514
+ const currentDir = currentFilePath.split('/').slice(0, -1).join('/');
515
+ const parts = [...currentDir.split('/'), ...importPath.split('/')];
516
+ const resolved = [];
517
+ for (const part of parts) {
518
+ if (part === '..') {
519
+ resolved.pop();
520
+ }
521
+ else if (part !== '.' && part !== '') {
522
+ resolved.push(part);
523
+ }
524
+ }
525
+ resolvedPath = resolved.join('/');
526
+ }
527
+ else if (importPath.startsWith('@/') || importPath.startsWith('~/')) {
528
+ // Path alias - strip the prefix
529
+ resolvedPath = importPath.slice(2);
530
+ // Infer app prefix from current file path
531
+ // e.g., if currentFilePath is "apps/web/lib/user/service.ts"
532
+ // and import is "@/modules/auth/lib/brevo", the actual file is at
533
+ // "apps/web/modules/auth/lib/brevo.ts"
534
+ // We detect this by checking if current file starts with "apps/XXX/"
535
+ const appMatch = currentFilePath.match(/^(apps\/[^/]+\/)/);
536
+ if (appMatch) {
537
+ appPrefix = appMatch[1];
538
+ }
539
+ }
540
+ else if (importPath.startsWith('#')) {
541
+ // Package imports - not supported yet
542
+ return null;
543
+ }
544
+ else {
545
+ // Unknown format
546
+ return null;
547
+ }
548
+ // Try to find the file with various extensions
549
+ const extensions = ['', '.ts', '.tsx', '.js', '.jsx'];
550
+ // First try with app prefix (for monorepo structures like apps/web/)
551
+ if (appPrefix) {
552
+ for (const ext of extensions) {
553
+ const fullPath = appPrefix + resolvedPath + ext;
554
+ const file = project.files?.find((f) => f.path === fullPath);
555
+ if (file) {
556
+ return file.path;
557
+ }
558
+ }
559
+ // Try index files with prefix
560
+ for (const ext of ['.ts', '.tsx', '.js', '.jsx']) {
561
+ const indexPath = `${appPrefix}${resolvedPath}/index${ext}`;
562
+ const file = project.files?.find((f) => f.path === indexPath);
563
+ if (file) {
564
+ return file.path;
565
+ }
566
+ }
567
+ }
568
+ // Then try without prefix (for simpler project structures)
569
+ for (const ext of extensions) {
570
+ const fullPath = resolvedPath + ext;
571
+ const file = project.files?.find((f) => f.path === fullPath);
572
+ if (file) {
573
+ return file.path;
574
+ }
575
+ }
576
+ // Try index files
577
+ for (const ext of ['.ts', '.tsx', '.js', '.jsx']) {
578
+ const indexPath = `${resolvedPath}/index${ext}`;
579
+ const file = project.files?.find((f) => f.path === indexPath);
580
+ if (file) {
581
+ return file.path;
582
+ }
583
+ }
584
+ return null;
585
+ }
302
586
  // Version for tracking deployments - increment when making changes
303
- const WRITE_SCENARIO_COMPONENTS_VERSION = '2.1.0-ast-based-import-detection';
587
+ const WRITE_SCENARIO_COMPONENTS_VERSION = '2.5.17-configurable-server-mocks';
304
588
  function addMockToContent(fileContent, importedExport, fileAnalyses, rootAnalysis, relativeMocksDir, scenarioName, importPath) {
305
- console.log(`CodeYam [v${WRITE_SCENARIO_COMPONENTS_VERSION}]: Adding mock for ${importedExport.name} from ${importedExport.filePath}`);
306
589
  // First try to find dependency schemas in fileAnalyses (for same-file dependencies)
307
590
  let dependencySchemas = fileAnalyses.find((a) => !!a.metadata?.mergedDataStructure?.dependencySchemas?.[importedExport.filePath]?.[importedExport.name])?.metadata?.mergedDataStructure?.dependencySchemas;
308
591
  // If not found in fileAnalyses, use root analysis's dependency schemas
@@ -313,57 +596,106 @@ function addMockToContent(fileContent, importedExport, fileAnalyses, rootAnalysi
313
596
  }
314
597
  // Check if we have multiple calls with different variable names
315
598
  // This requires generating separate mock functions for each call site
316
- const hasMultipleCallsWithVariables = importedExport.calls &&
317
- importedExport.calls.length > 1 &&
599
+ //
600
+ // IMPORTANT: calls array may contain BOTH base hook calls (e.g., "useFetcher<Type>()")
601
+ // AND method chain usages (e.g., "useFetcher().functionCallReturnValue.submit(...)").
602
+ // We only want to count base hook calls for the length comparison with callVariableNames.
603
+ // A "base call" is one that ends with "()" possibly preceded by a type annotation,
604
+ // without any subsequent method chains like ".functionCallReturnValue" or ".submit(...)".
605
+ const baseHookCalls = importedExport.calls?.filter((call) => {
606
+ // Base hook calls match patterns like:
607
+ // - "useFetcher()"
608
+ // - "useFetcher<Type>()"
609
+ // - "useFetcher<{ complex: Type }>()"
610
+ // They end with "()" and don't have method chains after the call.
611
+ // Method chains contain ".functionCallReturnValue" or have property access after "()".
612
+ return (call.endsWith('()') &&
613
+ !call.includes('.functionCallReturnValue') &&
614
+ // Also exclude method chains like "hook().something" or "hook().method()"
615
+ !call.match(/\(\)\.[a-zA-Z]/));
616
+ });
617
+ // Determine if we can generate unique mock functions for multiple variables.
618
+ // We need:
619
+ // 1. Multiple variable names (callVariableNames.length > 1)
620
+ // 2. Base hook calls to match them (baseHookCalls.length > 0)
621
+ // Note: We use min(baseHookCalls.length, callVariableNames.length) for iteration
622
+ // to handle cases where data might be slightly out of sync (stale entries).
623
+ const hasMultipleCallsWithVariables = baseHookCalls &&
624
+ baseHookCalls.length > 1 &&
318
625
  importedExport.callVariableNames &&
319
- importedExport.callVariableNames.length === importedExport.calls.length;
320
- // DEBUG: Log import info for multiple calls debugging
321
- if (importedExport.name === 'useFetcher' ||
322
- importedExport.name?.includes('Fetcher')) {
323
- console.log('CodeYam DEBUG: addMockToContent useFetcher import:', JSON.stringify({
324
- name: importedExport.name,
325
- calls: importedExport.calls,
326
- callVariableNames: importedExport.callVariableNames,
327
- hasMultipleCallsWithVariables,
328
- isMocked: importedExport.isMocked,
329
- }, null, 2));
330
- }
626
+ importedExport.callVariableNames.length > 1 &&
627
+ // Only proceed if we have at least as many base calls as variable names,
628
+ // OR they're close enough (within 1) to handle minor sync issues
629
+ Math.abs(baseHookCalls.length - importedExport.callVariableNames.length) <=
630
+ 1;
331
631
  let mockCode;
332
632
  const variableMockCodes = [];
333
633
  if (hasMultipleCallsWithVariables) {
334
634
  // Generate separate mock functions for each variable-qualified call
335
- // Track variable name occurrences to disambiguate when same variable is reused
336
- // (mirrors the logic in gatherDataForMocks)
635
+ // Look up canonical keys from dataForMocks and track variable names for function naming
636
+ // Get all call signature keys for this hook from dataForMocks
637
+ const dataForMocks = rootAnalysis.metadata?.scenariosDataStructure?.dataForMocks;
638
+ // Match keys that start with the hook name (e.g., "useFetcher" matches "useFetcher<User>()")
639
+ const callSignatureKeysForHook = dataForMocks
640
+ ? Object.keys(dataForMocks).filter((key) => {
641
+ const hookBaseName = importedExport.name.split(/[<(]/)[0];
642
+ const keyBaseName = key.split(/[<(]/)[0];
643
+ return keyBaseName === hookBaseName;
644
+ })
645
+ : [];
646
+ // Track variable name occurrences for unique function naming
337
647
  const variableNameCounts = {};
338
- for (let i = 0; i < importedExport.calls.length; i++) {
648
+ // Use the minimum of both array lengths to handle slight mismatches
649
+ // (e.g., stale data from previous analysis runs)
650
+ const iterationLimit = Math.min(baseHookCalls.length, importedExport.callVariableNames.length);
651
+ for (let i = 0; i < iterationLimit; i++) {
339
652
  const variableName = importedExport.callVariableNames[i];
340
653
  if (!variableName)
341
654
  continue;
342
655
  // Calculate the occurrence index for this variable name
343
656
  const occurrence = variableNameCounts[variableName] ?? 0;
344
657
  variableNameCounts[variableName] = occurrence + 1;
345
- // If this is a reused variable name (occurrence > 0), append index
346
- // e.g., "fetcher[1] <- useFetcher" for the second usage of "fetcher"
658
+ // Build indexed variable name for function naming
347
659
  const indexedVariableName = occurrence > 0 ? `${variableName}[${occurrence}]` : variableName;
348
- // Generate mock code for this specific call using variable-qualified name
349
- // Format: "variableName <- functionName" (reads as "variableName receives from functionName")
350
- const qualifiedName = `${indexedVariableName} <- ${importedExport.name}`;
351
- const variableMockCode = constructMockCode(qualifiedName, dependencySchemas, importedExport.entityType);
660
+ // Use safe function name with underscores instead of brackets
661
+ // e.g., fetcher[1] -> fetcher_1
662
+ const safeFunctionName = indexedVariableName.replace(/\[(\d+)\]/g, '_$1');
663
+ // Compute unique mock function name for call site replacement
664
+ // e.g., useFetcher_entityDiffFetcher, useFetcher_reportFetcher
665
+ const mockFunctionName = `${importedExport.name}_${safeFunctionName}`;
666
+ // Use the call signature from baseHookCalls[i] as the data key
667
+ // This matches what's stored in dataForMocks
668
+ const callSignature = baseHookCalls[i];
669
+ // Generate mock code using the call signature directly
670
+ // This prevents "symbol already declared" errors when multiple calls exist
671
+ // Check if this is a package import that won't have scenario copies
672
+ const isPackageImportForMock = importPath?.startsWith('@');
673
+ const variableMockCode = constructMockCode(callSignature, // Use call signature format for data lookup
674
+ dependencySchemas, importedExport.entityType, undefined, // No need for separate canonical key
675
+ {
676
+ uniqueFunctionSuffix: safeFunctionName, // Use variable name for unique function naming
677
+ // For node_modules or package imports, skip spreading from __cyOriginal
678
+ // since those packages/files don't export *__cyOriginal variants
679
+ skipOriginalSpread: importedExport.isNodeModule || isPackageImportForMock,
680
+ });
352
681
  if (variableMockCode) {
353
682
  variableMockCodes.push(variableMockCode);
354
683
  // Replace the call site with the variable-specific mock function
355
684
  // e.g., useFetcher<BranchEntityDiffResult>() -> useFetcher_entityDiffFetcher()
356
685
  // e.g., useFetcher() -> useFetcher_reportFetcher()
357
- // For indexed variables: useFetcher() -> useFetcher_fetcher_1()
358
- const callSignature = importedExport.calls[i];
359
686
  // Escape special regex characters in the call signature
360
687
  const escapedCallSignature = callSignature.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
361
- // Create regex that matches the call (with optional whitespace variations)
362
- const callRegex = new RegExp(escapedCallSignature.replace(/\s+/g, '\\s*'), 'g');
363
- // Use safe function name with underscores instead of brackets
364
- // e.g., fetcher[1] -> fetcher_1
365
- const safeFunctionName = indexedVariableName.replace(/\[(\d+)\]/g, '_$1');
366
- const mockFunctionName = `${importedExport.name}_${safeFunctionName}`;
688
+ // Create regex that matches the call (with optional whitespace variations).
689
+ // TypeScript formatters commonly break type parameters across lines, e.g.:
690
+ // useLoaderData<
691
+ // typeof loader
692
+ // >()
693
+ // So we allow optional whitespace around < and > delimiters, not just
694
+ // where whitespace already exists in the call signature string.
695
+ const callRegex = new RegExp(escapedCallSignature
696
+ .replace(/\s+/g, '\\s*')
697
+ .replace(/</g, '\\s*<\\s*')
698
+ .replace(/>/g, '\\s*>\\s*'), 'gs');
367
699
  fileContent = fileContent.replace(callRegex, `${mockFunctionName}()`);
368
700
  }
369
701
  }
@@ -378,74 +710,146 @@ function addMockToContent(fileContent, importedExport, fileAnalyses, rootAnalysi
378
710
  ? importedExport.callVariableNames[0]
379
711
  : undefined;
380
712
  if (singleCallVariableName) {
381
- // For single variable assignments, use the variable-qualified key for data lookup
382
- // but keep the original function name (no need for unique function names when there's only one assignment)
383
- const qualifiedKey = `${singleCallVariableName} <- ${importedExport.name}`;
384
- mockCode = `const ${importedExport.name}ReturnValue = scenarios().data()?.["${qualifiedKey}"];
385
-
386
- function ${importedExport.name}() {
387
- return ${importedExport.name}ReturnValue;
713
+ // For single variable assignments, use the call signature directly from dataForMocks
714
+ const dataForMocks = rootAnalysis.metadata?.scenariosDataStructure?.dataForMocks;
715
+ // Find matching call signature key in dataForMocks
716
+ // IMPORTANT: First try exact match with type parameters (e.g., "useLoaderData<LoaderData>()")
717
+ // to avoid picking the wrong variant (e.g., "useLoaderData<typeof loader>()" which may
718
+ // have different properties). Fall back to base name matching only if exact match fails.
719
+ const hookBaseName = importedExport.name.split(/[<(]/)[0];
720
+ const expectedKey = importedExport.calls?.[0];
721
+ let callSignatureKey;
722
+ if (dataForMocks) {
723
+ const keys = Object.keys(dataForMocks);
724
+ // First try exact match with the expected call signature
725
+ if (expectedKey && keys.includes(expectedKey)) {
726
+ callSignatureKey = expectedKey;
727
+ }
728
+ else {
729
+ // Fall back to base name matching
730
+ callSignatureKey = keys.find((key) => {
731
+ // Split on ., <, or ( to get the true base name
732
+ // This handles both "useFlags()" -> "useFlags" and "trpc.useUtils()" -> "trpc"
733
+ const keyBaseName = key.split(/[.<(]/)[0];
734
+ return keyBaseName === hookBaseName;
735
+ });
736
+ }
737
+ }
738
+ // Use the call signature if found, otherwise construct it
739
+ const dataKey = callSignatureKey ??
740
+ importedExport.calls?.[0] ??
741
+ `${importedExport.name}()`;
742
+ // IMPORTANT: If the dataKey is a method chain (e.g., "trpc.useUtils()"), we should
743
+ // use the base name (e.g., "trpc") when calling constructMockCode. This ensures
744
+ // constructMockCode generates a complete nested mock from the schema without
745
+ // referencing __cyOriginal variables.
746
+ const dataKeyBaseName = dataKey.split(/[.<(]/)[0];
747
+ const isMethodChainDataKey = dataKeyBaseName === importedExport.name &&
748
+ dataKey !== importedExport.name &&
749
+ dataKey.includes('.');
750
+ const mockNameToUse = isMethodChainDataKey
751
+ ? importedExport.name
752
+ : dataKey;
753
+ // Keep the original function name since there's only one call
754
+ // Check if this is a package import that won't have scenario copies
755
+ const isPackageImportForSingleCall = importPath?.startsWith('@');
756
+ mockCode = constructMockCode(mockNameToUse, dependencySchemas, importedExport.entityType, undefined, {
757
+ keepOriginalFunctionName: true,
758
+ // For node_modules or package imports, skip spreading from __cyOriginal
759
+ // since those packages/files don't export *__cyOriginal variants
760
+ skipOriginalSpread: importedExport.isNodeModule || isPackageImportForSingleCall,
761
+ });
762
+ // If constructMockCode didn't generate code, fall back to simple return
763
+ // IMPORTANT: We inline scenarios().data() inside the function rather than
764
+ // storing in a const - see comment in constructMockCode.ts for why.
765
+ if (!mockCode) {
766
+ mockCode = `// PATCHED: memoize to return stable reference (prevents infinite useEffect re-triggers)
767
+ const _${importedExport.name}Ref = {
768
+ current: null,
769
+ };
770
+ function ${importedExport.name}(...args) {
771
+ if (!_${importedExport.name}Ref.current) {
772
+ _${importedExport.name}Ref.current = scenarios().data()?.["${dataKey}"];
773
+ }
774
+ return _${importedExport.name}Ref.current;
388
775
  }`;
776
+ }
389
777
  }
390
778
  else {
391
- // Check if any analysis (fileAnalyses or rootAnalysis) has this function's data
392
- // under a variable-qualified key. The entity that CALLS the function (e.g., FileTableRow)
393
- // has the dataForMocks with the variable-qualified key, not the root analysis (e.g., GitView).
394
- let variableQualifiedKey;
395
- // First check fileAnalyses (the analyses for the entity being written)
396
- for (const analysis of fileAnalyses) {
397
- const dataForMocks = analysis.metadata?.scenariosDataStructure?.dataForMocks;
398
- if (dataForMocks) {
399
- variableQualifiedKey = Object.keys(dataForMocks).find((key) => {
400
- const match = key.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\s*<-\s*(.+)$/);
401
- return match && match[2] === importedExport.name;
402
- });
403
- if (variableQualifiedKey) {
404
- break;
405
- }
779
+ // Helper to find matching call signature key from dataForMocks
780
+ // IMPORTANT: First try exact match with type parameters (e.g., "useLoaderData<LoaderData>()")
781
+ // to avoid picking the wrong variant. Fall back to base name matching only if needed.
782
+ const hookBaseName = importedExport.name.split(/[<(]/)[0];
783
+ const expectedKey = importedExport.calls?.[0];
784
+ const findMatchingKey = (dataForMocks) => {
785
+ if (!dataForMocks)
786
+ return undefined;
787
+ const keys = Object.keys(dataForMocks);
788
+ // First try exact match with the expected call signature
789
+ if (expectedKey && keys.includes(expectedKey)) {
790
+ return expectedKey;
406
791
  }
407
- }
408
- // If not found in fileAnalyses, fall back to rootAnalysis
409
- if (!variableQualifiedKey) {
410
- const dataForMocks = rootAnalysis.metadata?.scenariosDataStructure?.dataForMocks;
411
- if (dataForMocks) {
412
- variableQualifiedKey = Object.keys(dataForMocks).find((key) => {
413
- const match = key.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\s*<-\s*(.+)$/);
414
- return match && match[2] === importedExport.name;
415
- });
792
+ // Fall back to base name matching
793
+ return keys.find((key) => {
794
+ // Split on ., <, or ( to get the true base name
795
+ // This handles both "useFlags()" -> "useFlags" and "trpc.useUtils()" -> "trpc"
796
+ const keyBaseName = key.split(/[.<(]/)[0];
797
+ return keyBaseName === hookBaseName;
798
+ });
799
+ };
800
+ // Check rootAnalysis FIRST for matching keys.
801
+ // The mock DATA is generated from rootAnalysis, so the mock CODE must
802
+ // also use rootAnalysis keys to ensure the lookup succeeds.
803
+ let dataKey = findMatchingKey(rootAnalysis.metadata?.scenariosDataStructure?.dataForMocks);
804
+ // If not found in rootAnalysis, fall back to fileAnalyses
805
+ if (!dataKey) {
806
+ for (const analysis of fileAnalyses) {
807
+ dataKey = findMatchingKey(analysis.metadata?.scenariosDataStructure?.dataForMocks);
808
+ if (dataKey)
809
+ break;
416
810
  }
417
811
  }
418
- if (variableQualifiedKey) {
419
- // Use the variable-qualified key found in the analysis
420
- mockCode = `const ${importedExport.name}ReturnValue = scenarios().data()?.["${variableQualifiedKey}"];
421
-
422
- function ${importedExport.name}() {
423
- return ${importedExport.name}ReturnValue;
812
+ // Use the data key if found, otherwise use call signature or function name.
813
+ // IMPORTANT: If the dataKey is a method chain (e.g., "trpc.useUtils()"), we should
814
+ // use the base name (e.g., "trpc") when calling constructMockCode. This ensures
815
+ // constructMockCode generates a complete nested mock from the schema without
816
+ // referencing __cyOriginal variables. The __cyOriginal pattern is only needed
817
+ // for partial mocking where we preserve some original methods, not for complete
818
+ // method-chain mocks where we provide all implementations.
819
+ const dataKeyBaseName = dataKey?.split(/[.<(]/)[0];
820
+ const isMethodChainDataKey = dataKey &&
821
+ dataKeyBaseName === importedExport.name &&
822
+ dataKey !== importedExport.name &&
823
+ dataKey.includes('.');
824
+ const mockNameToUse = isMethodChainDataKey
825
+ ? importedExport.name
826
+ : (dataKey ?? importedExport.calls?.[0] ?? `${importedExport.name}()`);
827
+ mockCode = constructMockCode(mockNameToUse, dependencySchemas, importedExport.entityType, undefined, {
828
+ keepOriginalFunctionName: true,
829
+ // For node_modules or package imports, skip spreading from __cyOriginal
830
+ // since those packages/files don't export *__cyOriginal variants
831
+ skipOriginalSpread: importedExport.isNodeModule || importPath?.startsWith('@'),
832
+ });
833
+ // If constructMockCode didn't generate code, fall back to simple return
834
+ // IMPORTANT: We inline scenarios().data() inside the function rather than
835
+ // storing in a const - see comment in constructMockCode.ts for why.
836
+ if (!mockCode && dataKey) {
837
+ mockCode = `// PATCHED: memoize to return stable reference (prevents infinite useEffect re-triggers)
838
+ const _${importedExport.name}Ref = {
839
+ current: null,
840
+ };
841
+ function ${importedExport.name}(...args) {
842
+ if (!_${importedExport.name}Ref.current) {
843
+ _${importedExport.name}Ref.current = scenarios().data()?.["${dataKey}"];
844
+ }
845
+ return _${importedExport.name}Ref.current;
424
846
  }`;
425
847
  }
426
- else {
427
- // Original behavior for calls without variable names
428
- mockCode = constructMockCode(importedExport.name, dependencySchemas, importedExport.entityType);
429
- }
430
848
  }
431
849
  }
432
850
  // Combine all mock codes
433
851
  const allMockCodes = variableMockCodes.length > 0 ? variableMockCodes.join('\n\n') : mockCode;
434
852
  if (!allMockCodes) {
435
- console.log('CodeYam Error: Mock code not found', JSON.stringify({
436
- importedExportFilePath: importedExport.filePath,
437
- importedExportEntityName: importedExport.name,
438
- hasMultipleCallsWithVariables,
439
- analysisIds: fileAnalyses.map((a) => ({
440
- id: a.id,
441
- filePath: a.filePath,
442
- entityName: a.entityName,
443
- })),
444
- analysisFilePath: fileAnalyses?.[0]?.filePath,
445
- analysisEntityNames: fileAnalyses.map((a) => a.entityName),
446
- dependencySchemas: fileAnalyses.find((a) => !!a.entity.metadata?.isolatedDataStructure?.dependencySchemas?.[importedExport.filePath]?.[importedExport.name])?.entity.metadata?.isolatedDataStructure?.dependencySchemas,
447
- allDependencySchemas: fileAnalyses.map((a) => a.entity.metadata?.isolatedDataStructure?.dependencySchemas),
448
- }, null, 2));
449
853
  return fileContent;
450
854
  }
451
855
  if (importPath) {
@@ -458,13 +862,44 @@ function ${importedExport.name}() {
458
862
  else {
459
863
  // Escape regex special characters in importPath (e.g., brackets in [environmentId])
460
864
  const escapedImportPath = importPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
461
- const importRegExp = new RegExp(`(import(?:(?!${firstPart}|from|import)[\\s\\S])*?)${firstPart}(?:,\\s*)?((?:(?!import)[\\s\\S])*?from\\s+['"]${escapedImportPath}['"])`, 'm');
462
- if (importedExportNameParts.length > 1) {
865
+ // Use a simpler, more robust regex pattern that matches the fallback path.
866
+ // Key improvements:
867
+ // 1. Uses escapeRegExp(firstPart) to handle special characters in function names
868
+ // 2. Uses word boundaries (\b) to prevent partial matches
869
+ // 3. Handles comma BEFORE or AFTER the name: (?:,\s*|\s*,)?
870
+ // 4. Matches specific import path (escapedImportPath)
871
+ const importRegExp = new RegExp(`(import\\s*\\{[^}]*?)\\b${escapeRegExp(firstPart)}\\b(?:,\\s*|\\s*,)?((?:[^}]*\\}\\s*from\\s*['"]${escapedImportPath}['"];?))`, 'm');
872
+ // Check if any call signature has multiple parts (e.g., "logger.error(error)")
873
+ // If so, the mock code will spread from __cyOriginal, so we need to rename the import
874
+ // EXCEPT:
875
+ // 1. For node_module imports, the __cyOriginal pattern doesn't work because
876
+ // the original package doesn't export *__cyOriginal variants.
877
+ // 2. For package imports (starting with @), the __cyOriginal pattern doesn't work
878
+ // because scenario copies aren't created for package files - they keep the
879
+ // original import path which doesn't export *__cyOriginal.
880
+ const anyCallHasMultipleParts = importedExport.calls?.some((call) => {
881
+ const callParts = splitOutsideParenthesesAndArrays(call);
882
+ return callParts.length > 1;
883
+ });
884
+ // Package imports (starting with @) don't get scenario copies, so __cyOriginal won't exist
885
+ const isPackageImport = importPath.startsWith('@');
886
+ const shouldRenameToOriginal = !importedExport.isNodeModule &&
887
+ !isPackageImport &&
888
+ (importedExportNameParts.length > 1 || anyCallHasMultipleParts);
889
+ if (shouldRenameToOriginal) {
463
890
  fileContent = fileContent.replace(importRegExp, `$1${firstPart}__cyOriginal$2`);
464
891
  }
465
892
  else {
466
893
  fileContent = fileContent.replace(importRegExp, '$1$2');
467
894
  }
895
+ // Also handle namespace imports (import * as foo from '...')
896
+ // These need to be renamed to foo__cyOriginal when the mock code spreads from the original.
897
+ // Note: We match any path (not just escapedImportPath) because the import path may have
898
+ // been rewritten by transitive import handling before this code runs.
899
+ if (shouldRenameToOriginal) {
900
+ const namespaceImportRegExp = new RegExp(`(import\\s+\\*\\s+as\\s+)${escapeRegExp(firstPart)}(\\s+from\\s+['"][^'"]*['"])`, 'm');
901
+ fileContent = fileContent.replace(namespaceImportRegExp, `$1${firstPart}__cyOriginal$2`);
902
+ }
468
903
  // Remove empty imports entirely to avoid partial commenting issues with multiline imports
469
904
  // This handles both single-line and multiline empty imports
470
905
  fileContent = fileContent.replace(/import\s*\{\s*\}\s*from\s+['"][^'"]*['"];?\s*\n?/g, '');
@@ -480,7 +915,17 @@ function ${importedExport.name}() {
480
915
  // This handles imports like: import { useEnvironment, otherThing } from "any/path"
481
916
  // Removes useEnvironment but keeps otherThing
482
917
  const namedImportRegExp = new RegExp(`(import\\s*\\{[^}]*?)\\b${escapeRegExp(firstPart)}\\b(?:,\\s*|\\s*,)?((?:[^}]*\\}\\s*from\\s*['"][^'"]*['"];?))`, 'm');
483
- if (importedExportNameParts.length > 1) {
918
+ // Check if any call signature has multiple parts (e.g., "logger.error(error)")
919
+ // If so, the mock code will spread from __cyOriginal, so we need to rename the import
920
+ // EXCEPT: For node_module imports, the __cyOriginal pattern doesn't work because
921
+ // the original package doesn't export *__cyOriginal variants.
922
+ const anyCallHasMultipleParts = importedExport.calls?.some((call) => {
923
+ const callParts = splitOutsideParenthesesAndArrays(call);
924
+ return callParts.length > 1;
925
+ });
926
+ const shouldRenameToOriginal = !importedExport.isNodeModule &&
927
+ (importedExportNameParts.length > 1 || anyCallHasMultipleParts);
928
+ if (shouldRenameToOriginal) {
484
929
  // Rename the import instead of removing (for destructured access patterns)
485
930
  fileContent = fileContent.replace(namedImportRegExp, `$1${firstPart}__cyOriginal$2`);
486
931
  }
@@ -504,7 +949,6 @@ function ${importedExport.name}() {
504
949
  insertContent += `\n\n// Mock constructed using mocksDataStructure from analyses: ${fileAnalyses.map((a) => a.id).join(', ')}\n${allMockCodes}`;
505
950
  if (lastImportEnd > 0) {
506
951
  // Insert after the last original import
507
- console.log(`CodeYam [v${WRITE_SCENARIO_COMPONENTS_VERSION}]: Inserting mock at position ${lastImportEnd} (after imports), not at end`);
508
952
  fileContent =
509
953
  fileContent.slice(0, lastImportEnd) +
510
954
  insertContent +
@@ -512,7 +956,6 @@ function ${importedExport.name}() {
512
956
  }
513
957
  else {
514
958
  // Fallback: append at end if no imports found
515
- console.log(`CodeYam [v${WRITE_SCENARIO_COMPONENTS_VERSION}]: No imports found, appending mock at end`);
516
959
  fileContent += insertContent;
517
960
  }
518
961
  return fileContent;
@@ -659,6 +1102,14 @@ function captureArgumentsForTesting(args) {
659
1102
  }
660
1103
  export default async function writeScenarioComponents({ project, file, entity, rootAnalysis, scenario, context, projectAnalyzer, framework, mocksDir, rootFile, namespaceMocks, writtenScenarioComponents = {}, fileStore, exportAsNamed, }) {
661
1104
  var _a;
1105
+ // Reset debug timing for this invocation
1106
+ resetDebugTiming();
1107
+ debugLog('START writeScenarioComponents', {
1108
+ filePath: file.path,
1109
+ entityName: entity.name,
1110
+ scenarioName: scenario.name,
1111
+ isRootFile: !rootFile || rootFile === file,
1112
+ });
662
1113
  // Capture arguments for testing if debug mode is enabled
663
1114
  captureArgumentsForTesting({
664
1115
  project,
@@ -731,7 +1182,6 @@ export default async function writeScenarioComponents({ project, file, entity, r
731
1182
  // .d.ts files only have type declarations (e.g., "export declare const logger")
732
1183
  // which don't provide runtime exports. We need to generate actual stub implementations.
733
1184
  if (file.path.endsWith('.d.ts')) {
734
- console.log(`CodeYam: Converting .d.ts file to stub implementations: ${file.path}`);
735
1185
  fileContent = convertDtsToStubs(fileContent, entity.name);
736
1186
  // After basic .d.ts conversion, enhance the entity's stub with proper mock code
737
1187
  // if we have dependency schema data showing its methods/properties.
@@ -803,7 +1253,23 @@ export default async function writeScenarioComponents({ project, file, entity, r
803
1253
  return 1;
804
1254
  return 0;
805
1255
  });
1256
+ debugLog('Starting main importedExports loop', {
1257
+ count: sortedImportedExports.length,
1258
+ fileContentLength: fileContent.length,
1259
+ });
1260
+ let importedExportIndex = 0;
1261
+ const loopStartTime = Date.now();
1262
+ console.log(`[WriteScenario] Starting import loop for ${entity.name}: ${sortedImportedExports.length} imports`);
806
1263
  for (const importedExport of sortedImportedExports) {
1264
+ importedExportIndex++;
1265
+ if (importedExportIndex % 5 === 0 || importedExportIndex === 1) {
1266
+ console.log(`[WriteScenario] ${entity.name} import ${importedExportIndex}/${sortedImportedExports.length}: ${importedExport.name} elapsed=${Date.now() - loopStartTime}ms`);
1267
+ debugLog(`Processing importedExport ${importedExportIndex}/${sortedImportedExports.length}`, {
1268
+ name: importedExport.name,
1269
+ filePath: importedExport.filePath,
1270
+ isMocked: importedExport.isMocked,
1271
+ });
1272
+ }
807
1273
  // IMPORTANT: The import mapping keys may be either absolute or relative paths
808
1274
  // depending on how they were created by the file analyzer. We try multiple formats.
809
1275
  // Also need to normalize paths to handle /tmp vs /private/tmp on macOS
@@ -852,12 +1318,6 @@ export default async function writeScenarioComponents({ project, file, entity, r
852
1318
  // where the entity code lives, not the re-export file.
853
1319
  if (!isSameFile) {
854
1320
  if (!writtenScenarioComponents[importedExportFilePath]?.includes(importedExport.name)) {
855
- // Skip recursion for type/data entities - they don't need scenario components
856
- // Only recurse for visual and library entities that need mocking
857
- if (importedExportEntity.entityType === 'type' ||
858
- importedExportEntity.entityType === 'data') {
859
- continue;
860
- }
861
1321
  // Use fileStore for O(1) lookup when available
862
1322
  let fileNotMocked = fileStore
863
1323
  ? fileStore.getByPath(importedExportFilePath)
@@ -883,30 +1343,89 @@ export default async function writeScenarioComponents({ project, file, entity, r
883
1343
  !fileStore.isContentLoaded(fileNotMocked.path)) {
884
1344
  fileNotMocked = await fileStore.ensureContent(fileNotMocked.path);
885
1345
  }
886
- // When a default export is imported as named (via index re-export), we need
887
- // to add a named re-export to the scenario component so the import works.
888
- // e.g., if file has `export default X` but parent does `import { X } from '...'`
889
- const needsNamedReExport = importedExport.resolvedIsDefault === true &&
890
- importedExport.isDefault === false;
891
- const { scenarioComponentPaths: newScenarioComponentPaths, writtenScenarioComponents: updatedWrittenScenarioComponents, } = await writeScenarioComponents({
892
- project,
893
- file: fileNotMocked,
894
- entity: importedExportEntity,
895
- rootAnalysis,
896
- scenario,
897
- context,
898
- projectAnalyzer,
899
- framework,
900
- mocksDir,
901
- rootFile,
902
- namespaceMocks,
903
- writtenScenarioComponents,
904
- fileStore,
905
- // Pass the import name so we can add `export { default as Name };`
906
- exportAsNamed: needsNamedReExport ? importedExport.name : undefined,
907
- });
908
- writtenScenarioComponents = updatedWrittenScenarioComponents;
909
- scenarioComponentPaths.push(...newScenarioComponentPaths);
1346
+ // For type/data entities, create a transformed copy WITHOUT recursion.
1347
+ // Data entities don't need mocking - they're just constants/types that need
1348
+ // to be available. But we still need to:
1349
+ // 1. Strip server-only imports (Next.js directive that breaks client components)
1350
+ // 2. Write the transformed file so imports can be rewritten to point to it
1351
+ if (importedExportEntity.entityType === 'type' ||
1352
+ importedExportEntity.entityType === 'data') {
1353
+ // For data entities, we write ONE transformed copy per source file, not per entity.
1354
+ // Check if we've already written ANY entity from this file - if so, skip writing.
1355
+ // Use a special marker '__data_file_written__' to track file-level writes.
1356
+ // Also track which SHA was used via '__data_file_sha__:xxx' so subsequent
1357
+ // entities from the same file can reuse it for import rewriting.
1358
+ const dataFileWritten = writtenScenarioComponents[importedExportFilePath]?.includes('__data_file_written__');
1359
+ if (!dataFileWritten) {
1360
+ // Construct the scenario file path for the data file
1361
+ // Use a file-level identifier (first entity's sha) for consistency
1362
+ const dataFileBasePath = safeFolder(fileNotMocked.path.split('/').slice(0, -1).join('/'));
1363
+ const dataFileExtension = fileNotMocked.name.split('.').pop();
1364
+ const dataFileIsIndex = isIndexPath(fileNotMocked.path);
1365
+ // Use 'data' prefix to distinguish from entity-specific files
1366
+ const dataScenarioPath = `${PROJECT_RELATIVE_PATH}/${dataFileBasePath}/${importedExportEntity.sha}_${dataFileIsIndex ? 'index_' : ''}data_${safeFileName(scenario.name)}.${dataFileExtension}`;
1367
+ // Get the file content and apply transformations
1368
+ let dataFileContent = fileNotMocked.content ?? '';
1369
+ // Strip server-only imports - these break when imported by client components
1370
+ dataFileContent = stripServerOnlyImport(dataFileContent);
1371
+ dataFileContent = applyServerOnlyMocks(dataFileContent);
1372
+ // Write the transformed data entity file
1373
+ await writeFile(dataScenarioPath, dataFileContent);
1374
+ scenarioComponentPaths.push(dataScenarioPath);
1375
+ // Mark file as written so we don't duplicate for other entities from same file
1376
+ if (!writtenScenarioComponents[importedExportFilePath]) {
1377
+ writtenScenarioComponents[importedExportFilePath] = [];
1378
+ }
1379
+ writtenScenarioComponents[importedExportFilePath].push('__data_file_written__');
1380
+ // Also store the SHA used for this data file so subsequent entities can use it
1381
+ writtenScenarioComponents[importedExportFilePath].push(`__data_file_sha__:${importedExportEntity.sha}`);
1382
+ }
1383
+ // Mark this specific entity as written (for the entity-level check)
1384
+ if (!writtenScenarioComponents[importedExportFilePath]) {
1385
+ writtenScenarioComponents[importedExportFilePath] = [];
1386
+ }
1387
+ writtenScenarioComponents[importedExportFilePath].push(importedExport.name);
1388
+ // Don't recurse - data entities don't need their dependencies processed
1389
+ // The import rewriting will happen later in this same loop iteration
1390
+ // (at lines ~1590-1702) to point imports to this transformed file
1391
+ }
1392
+ else {
1393
+ // For visual/library entities, recurse to process their dependencies
1394
+ // When a default export is imported as named (via index re-export), we need
1395
+ // to add a named re-export to the scenario component so the import works.
1396
+ // e.g., if file has `export default X` but parent does `import { X } from '...'`
1397
+ const needsNamedReExport = importedExport.resolvedIsDefault === true &&
1398
+ importedExport.isDefault === false;
1399
+ console.log(`[WriteScenario] RECURSE START: ${entity.name} -> ${importedExportEntity.name}`);
1400
+ const recurseStartTime = Date.now();
1401
+ debugLog(`Recursing into writeScenarioComponents for ${importedExportEntity.name}`, {
1402
+ entityName: importedExportEntity.name,
1403
+ filePath: fileNotMocked.path,
1404
+ });
1405
+ const { scenarioComponentPaths: newScenarioComponentPaths, writtenScenarioComponents: updatedWrittenScenarioComponents, } = await withTimeout(`recursive writeScenarioComponents for ${importedExportEntity.name}`, writeScenarioComponents({
1406
+ project,
1407
+ file: fileNotMocked,
1408
+ entity: importedExportEntity,
1409
+ rootAnalysis,
1410
+ scenario,
1411
+ context,
1412
+ projectAnalyzer,
1413
+ framework,
1414
+ mocksDir,
1415
+ rootFile,
1416
+ namespaceMocks,
1417
+ writtenScenarioComponents,
1418
+ fileStore,
1419
+ // Pass the import name so we can add `export { default as Name };`
1420
+ exportAsNamed: needsNamedReExport
1421
+ ? importedExport.name
1422
+ : undefined,
1423
+ }), 180000);
1424
+ console.log(`[WriteScenario] RECURSE END: ${entity.name} -> ${importedExportEntity.name} took ${Date.now() - recurseStartTime}ms`);
1425
+ debugLog(`Completed recursive writeScenarioComponents for ${importedExportEntity.name}`);
1426
+ writtenScenarioComponents = updatedWrittenScenarioComponents;
1427
+ scenarioComponentPaths.push(...newScenarioComponentPaths);
1428
+ }
910
1429
  }
911
1430
  }
912
1431
  }
@@ -921,16 +1440,22 @@ export default async function writeScenarioComponents({ project, file, entity, r
921
1440
  // Data and type entities should be preserved - they're not callable and may have methods
922
1441
  // that stubbing would break (e.g., Zod schemas with .superRefine())
923
1442
  const isDataEntity = entityType === 'data' || entityType === 'type';
924
- // Heuristic: Zod schemas are often misclassified as 'library' but should be preserved
925
- // Detect by: name starts with Z + uppercase letter, AND has Zod method calls
926
- const looksLikeZodSchema = entityType === 'library' &&
927
- /^Z[A-Z]/.test(importedExport.name) &&
928
- importedExport.calls?.some((call) => /\.(superRefine|refine|transform|default|optional|nullable|array|object|string|number|boolean|parse|safeParse)\s*\(/.test(call));
929
- if (looksLikeZodSchema) {
930
- console.log(`CodeYam: Detected Zod schema "${importedExport.name}" (misclassified as library) - will preserve`);
931
- }
932
- // Callable entities can be safely stubbed (but not Zod schemas)
933
- const isCallable = !isDataEntity && !looksLikeZodSchema && entityType !== undefined;
1443
+ // If calls data shows the entity is only accessed via properties/methods
1444
+ // (e.g., formValidator.validate(), schema.superRefine()) and never directly
1445
+ // invoked (e.g., getInitialProps()), it's used as an object and should be
1446
+ // preserved rather than replaced with a Proxy stub.
1447
+ const onlyPropertyAccessed = importedExport.calls?.length > 0 &&
1448
+ !importedExport.calls.some((call) => {
1449
+ const afterName = call.slice(importedExport.name.length);
1450
+ return afterName.startsWith('(') || afterName.startsWith('<');
1451
+ });
1452
+ // Callable entities can be safely stubbed. Entities that are only
1453
+ // property-accessed should be preserved (their methods need to work).
1454
+ // 'other' entities are unknown types — safer to preserve than stub.
1455
+ const isCallable = !isDataEntity &&
1456
+ !onlyPropertyAccessed &&
1457
+ entityType !== undefined &&
1458
+ entityType !== 'other';
934
1459
  // Determine what action to take
935
1460
  const shouldStripAndReplace = hasMock;
936
1461
  const shouldStripAndStub = !hasMock && importedExport.isMocked && isCallable;
@@ -944,7 +1469,6 @@ export default async function writeScenarioComponents({ project, file, entity, r
944
1469
  if (shouldPreserve) {
945
1470
  // For data entities (like Zod schemas), don't strip or stub - preserve the original
946
1471
  // This ensures schema methods like .superRefine() continue to work
947
- console.log(`CodeYam: Preserving ${importedExport.name} (entityType: ${entityType}) - not stripping data entities`);
948
1472
  // Don't modify fileContent - keep the original code
949
1473
  }
950
1474
  else if (shouldStripAndReplace || shouldStripAndStub) {
@@ -962,7 +1486,6 @@ export default async function writeScenarioComponents({ project, file, entity, r
962
1486
  // This prevents ReferenceError at runtime when the stripped
963
1487
  // function is called (e.g., local helper functions like getInitialProps).
964
1488
  const functionName = importedExport.name;
965
- console.log(`CodeYam: Generating stub mock for ${functionName} (entityType: ${entityType}) in ${file.path}`);
966
1489
  // Add scenarios import if not present
967
1490
  if (fileContent.indexOf('import { scenarios } from') === -1) {
968
1491
  const mockDataPath = `${relativeMocksDir}/MockData_${safeFileName(scenario.name)}`;
@@ -1072,6 +1595,25 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1072
1595
  }
1073
1596
  const fileName = actualScenarioFilePathRelative.split('/').pop();
1074
1597
  const fileNotMockedIsIndex = isIndexPath(fileNotMocked?.path);
1598
+ // For data/type entities, use 'data' instead of entity name since we write
1599
+ // ONE file per source file (not per entity) for data entities
1600
+ const isDataEntity = importedExportEntity?.entityType === 'data' ||
1601
+ importedExportEntity?.entityType === 'type';
1602
+ const scenarioFileName = isDataEntity
1603
+ ? 'data'
1604
+ : safeFileName(importedExportEntity.name);
1605
+ // For data entities, look up the SHA that was used to create the data file
1606
+ // (stored when the file was first written). This ensures all entities from
1607
+ // the same source file have their imports rewritten to point to the same file.
1608
+ // Use actualScenarioFilePathRelative as the key since that's what matches
1609
+ // importedExportFilePath used when storing (both are relative paths).
1610
+ let entityShaForPath = importedExportEntity.sha;
1611
+ if (isDataEntity && actualScenarioFilePathRelative) {
1612
+ const storedShaMarker = writtenScenarioComponents[actualScenarioFilePathRelative]?.find((m) => m.startsWith('__data_file_sha__:'));
1613
+ if (storedShaMarker) {
1614
+ entityShaForPath = storedShaMarker.replace('__data_file_sha__:', '');
1615
+ }
1616
+ }
1075
1617
  const mockFilePath = isFrameworkRoute(fileNotMocked, importedExportEntity, framework, fileNotMocked === rootFile)
1076
1618
  ? getFrameworkRoutePath({
1077
1619
  file: fileNotMocked,
@@ -1086,7 +1628,7 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1086
1628
  .split('.')
1087
1629
  .slice(0, -1)
1088
1630
  .join('.')
1089
- : actualScenarioFilePathRelative.replace(`${fileName}`, `${importedExportEntity.sha}_${fileNotMockedIsIndex ? 'index_' : ''}${safeFileName(importedExportEntity.name)}_${safeFileName(scenario.name)}`);
1631
+ : actualScenarioFilePathRelative.replace(`${fileName}`, `${entityShaForPath}_${fileNotMockedIsIndex ? 'index_' : ''}${scenarioFileName}_${safeFileName(scenario.name)}`);
1090
1632
  const path = safeFolder(getRelativePath(filePath, mockFilePath));
1091
1633
  // If we have an import mapping, use it to find the import string to replace
1092
1634
  // Otherwise, skip rewriting (we can't find the import statement without knowing what to search for)
@@ -1117,19 +1659,26 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1117
1659
  // This handles cases where multiple entities are imported from the same index file
1118
1660
  // (e.g., import { A, B, C } from '@pkg') and each has its own scenario file
1119
1661
  const entityImportName = importedExport.name;
1120
- const newImport = `import { ${entityImportName} } from '${path}';`;
1662
+ // Use default import syntax for default exports, named import for named exports
1663
+ const newImport = importedExport.isDefault
1664
+ ? `import ${entityImportName} from '${path}';`
1665
+ : `import { ${entityImportName} } from '${path}';`;
1121
1666
  // First, try to remove this entity from the already-rewritten grouped import
1122
1667
  // This prevents duplicate/conflicting imports
1123
- // Match patterns like "EntityName," or ", EntityName" or "EntityName" (if only one)
1124
- // Note: entityImportName needs escaping since JS identifiers can contain $ (a regex metacharacter)
1668
+ // Use AST-based removal to properly handle type-only imports like `type EntityName`
1125
1669
  const escapedEntityName = escapeRegExp(entityImportName);
1126
- const removeFromGroupedImportPatterns = [
1127
- new RegExp(`\\b${escapedEntityName}\\s*,\\s*`, 'g'), // "EntityName, "
1128
- new RegExp(`\\s*,\\s*${escapedEntityName}\\b`, 'g'), // ", EntityName"
1129
- ];
1130
- for (const pattern of removeFromGroupedImportPatterns) {
1131
- fileContent = fileContent.replace(pattern, '');
1670
+ // For default imports: remove "DefaultName, " from "import DefaultName, { ... }"
1671
+ // This handles the case where a default export is being split out
1672
+ if (importedExport.isDefault) {
1673
+ const defaultImportPattern = new RegExp(`(import\\s+)${escapedEntityName}\\s*,\\s*(\\{)`, 'gm');
1674
+ fileContent = fileContent.replace(defaultImportPattern, '$1$2');
1132
1675
  }
1676
+ // Remove the named import using AST parsing
1677
+ // This properly handles:
1678
+ // - Regular imports: `import { EntityName } from '...'`
1679
+ // - Type-only imports: `import { type EntityName } from '...'`
1680
+ // - Mixed imports: `import { type EntityName, OtherName } from '...'`
1681
+ fileContent = removeNamedImportAst(fileContent, entityImportName);
1133
1682
  // Add the new import at the beginning of fileContent
1134
1683
  // Note: The header comment (// Scenario:) doesn't exist yet - it's prepended at writeFile time
1135
1684
  // So prepending here puts the import right after the header in the final output
@@ -1143,17 +1692,30 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1143
1692
  }
1144
1693
  }
1145
1694
  }
1695
+ // Track post-import-loop timing
1696
+ const postLoopStartTime = Date.now();
1697
+ console.log(`[WriteScenario] POST-LOOP START: ${entity.name}`);
1698
+ // Collect universal mocks BEFORE processing nodeModuleImports
1699
+ // This is needed to check if a node module import is handled by a universal mock
1700
+ const universalMocks = project.metadata?.universalMocks ?? [];
1701
+ const nodeModuleUniversalMocks = universalMocks.filter((mock) => mock.nodeModule && mock.content);
1702
+ // Create a set of import paths that have universal mocks for quick lookup
1703
+ const universalMockPaths = new Set(nodeModuleUniversalMocks.map((mock) => mock.filePath));
1146
1704
  for (const nodeModuleImport of nodeModuleImports) {
1147
1705
  if (!nodeModuleImport.isMocked)
1148
1706
  continue;
1707
+ // Skip generating local mock functions for imports that have universal mocks.
1708
+ // Universal mocks provide the exports via rewritten import paths (handled below).
1709
+ // Generating a local mock function would cause "name defined multiple times" errors.
1710
+ if (universalMockPaths.has(nodeModuleImport.filePath)) {
1711
+ continue;
1712
+ }
1149
1713
  fileContent = addMockToContent(fileContent, nodeModuleImport, fileAnalyses, rootAnalysis, relativeMocksDir, scenario.name, importMapping[nodeModuleImport.filePath] ?? nodeModuleImport.filePath);
1150
1714
  }
1151
1715
  // Rewrite node_module imports that have universal mocks
1152
1716
  // Universal mocks create mock files at __codeyamMocks__/{safeFileName}.tsx
1153
1717
  // We need to rewrite imports like `import { logger } from "@formbricks/logger"`
1154
1718
  // to `import { logger } from "../__codeyamMocks__/_formbricks_logger.js"`
1155
- const universalMocks = project.metadata?.universalMocks ?? [];
1156
- const nodeModuleUniversalMocks = universalMocks.filter((mock) => mock.nodeModule && mock.content);
1157
1719
  for (const universalMock of nodeModuleUniversalMocks) {
1158
1720
  const originalPath = universalMock.filePath;
1159
1721
  // Create the mock file name using the same safeFileName function as writeUniversalMocks
@@ -1166,6 +1728,7 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1166
1728
  const importRegex = new RegExp(`(import\\s+(?:\\{[^}]*\\}|\\*\\s+as\\s+\\w+|\\w+)\\s+from\\s+)['"]${originalPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}['"]`, 'g');
1167
1729
  fileContent = fileContent.replace(importRegex, `$1'${mockFileRelativePath}'`);
1168
1730
  }
1731
+ console.log(`[WriteScenario] POST-LOOP ${entity.name}: node+universal mocks took ${Date.now() - postLoopStartTime}ms`);
1169
1732
  if (rootAnalysis.entitySha === entity.sha &&
1170
1733
  entity.metadata?.notExported &&
1171
1734
  entity.name !== 'default') {
@@ -1201,17 +1764,351 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1201
1764
  scenario,
1202
1765
  });
1203
1766
  }
1767
+ debugLog('Route path computed', { scenarioComponentPath });
1204
1768
  // Strip <html> and <body> tags from root layout files for Next.js
1205
1769
  // These tags cause hydration errors when the scenario layout is nested under the real root
1770
+ debugLog('Starting stripHtmlBodyTags');
1206
1771
  fileContent = stripHtmlBodyTags(fileContent, file.path, framework);
1772
+ debugLog('Completed stripHtmlBodyTags');
1773
+ // Strip "server-only" imports for Next.js
1774
+ // These cause errors when the scenario component is rendered client-side
1775
+ debugLog('Starting stripServerOnlyImport');
1776
+ fileContent = stripServerOnlyImport(fileContent);
1777
+ debugLog('Starting applyServerOnlyMocks');
1778
+ fileContent = applyServerOnlyMocks(fileContent);
1779
+ debugLog('Completed server-only processing');
1207
1780
  // Rewrite asset imports (CSS, images, fonts, etc.) to correct relative paths
1208
1781
  // The original file path is relative to PROJECT_RELATIVE_PATH, the new path is scenarioComponentPath
1782
+ debugLog('Starting rewriteAssetImports');
1209
1783
  fileContent = rewriteAssetImports(fileContent, `${PROJECT_RELATIVE_PATH}/${file.path}`, scenarioComponentPath);
1784
+ debugLog('Completed rewriteAssetImports');
1210
1785
  // Rewrite relative TypeScript/JavaScript module imports to correct relative paths
1211
1786
  // This handles cases where the file is moved (e.g., from [environmentId]/ to _environmentId_/)
1212
1787
  // and relative imports like "./lib/organization" need to be rewritten
1788
+ debugLog('Starting rewriteRelativeModuleImports');
1213
1789
  fileContent = rewriteRelativeModuleImports(fileContent, `${PROJECT_RELATIVE_PATH}/${file.path}`, scenarioComponentPath);
1214
- console.log('Writing scenario component', file.path, entity.name, scenarioComponentPath, fileContent.length);
1790
+ debugLog('Completed rewriteRelativeModuleImports');
1791
+ console.log(`[WriteScenario] POST-LOOP ${entity.name}: transformations took ${Date.now() - postLoopStartTime}ms`);
1792
+ /**
1793
+ * Recursively process a file's imports to create transitive copies with server-only stripped.
1794
+ * This handles chains of arbitrary depth: A -> B -> C -> D where each needs server-only removed.
1795
+ * Uses a visited set to detect and break circular import chains.
1796
+ *
1797
+ * @param content - The file content to process
1798
+ * @param sourceFilePath - The original source file path (for resolving relative imports)
1799
+ * @param targetFilePath - The path where this content will be written (for computing relative imports)
1800
+ * @param visitedPaths - Set of file paths currently being processed (for cycle detection)
1801
+ * @returns The modified content with imports rewritten to point to transitive copies
1802
+ */
1803
+ async function processTransitiveImportsRecursively(content, sourceFilePath, targetFilePath, visitedPaths = new Set(), depth = 0, startTime = Date.now()) {
1804
+ // Global timeout for entire transitive processing
1805
+ const GLOBAL_TIMEOUT_MS = 180000; // 3 minutes max for all transitive processing (complex components need more time)
1806
+ const elapsed = Date.now() - startTime;
1807
+ if (elapsed > GLOBAL_TIMEOUT_MS) {
1808
+ throw new Error(`processTransitiveImportsRecursively exceeded ${GLOBAL_TIMEOUT_MS}ms (elapsed: ${elapsed}ms) at depth=${depth} for ${sourceFilePath}`);
1809
+ }
1810
+ const importPaths = extractInternalImportPaths(content);
1811
+ // Always log to help debug timeout issues
1812
+ console.log(`[TransitiveImports] depth=${depth} file=${path.basename(sourceFilePath)} imports=${importPaths.length} visited=${visitedPaths.size} elapsed=${Date.now() - startTime}ms`);
1813
+ debugLog(`processTransitiveImportsRecursively depth=${depth}`, {
1814
+ sourceFilePath,
1815
+ importCount: importPaths.length,
1816
+ visitedCount: visitedPaths.size,
1817
+ });
1818
+ let modifiedContent = content;
1819
+ // Safety check: limit iterations to prevent infinite loops
1820
+ const MAX_IMPORTS_PER_FILE = 100;
1821
+ if (importPaths.length > MAX_IMPORTS_PER_FILE) {
1822
+ console.warn(`[WriteScenario] WARNING: File ${sourceFilePath} has ${importPaths.length} imports (> ${MAX_IMPORTS_PER_FILE}), limiting processing`);
1823
+ }
1824
+ let importIndex = 0;
1825
+ debugLog(`Starting import loop at depth=${depth}, ${importPaths.length} imports to process`);
1826
+ const slicedImports = importPaths.slice(0, MAX_IMPORTS_PER_FILE);
1827
+ for (const importPath of slicedImports) {
1828
+ if (!importPath) {
1829
+ continue;
1830
+ }
1831
+ importIndex++;
1832
+ debugLog(`[LOOP] depth=${depth} import ${importIndex}/${Math.min(importPaths.length, MAX_IMPORTS_PER_FILE)}: ${importPath}`);
1833
+ debugLog(`[LOOP] Calling resolveImportPath...`);
1834
+ const resolvedPath = resolveImportPath(importPath, sourceFilePath, project);
1835
+ debugLog(`[LOOP] resolveImportPath returned: ${resolvedPath?.slice(0, 80) ?? 'null'}`);
1836
+ if (!resolvedPath)
1837
+ continue;
1838
+ debugLog(`[LOOP] Looking up importFile...`);
1839
+ let importFile = fileStore
1840
+ ? fileStore.getByPath(resolvedPath)
1841
+ : project.files?.find((f) => f.path === resolvedPath);
1842
+ debugLog(`[LOOP] importFile lookup result: ${importFile ? 'found' : 'not found'}`);
1843
+ if (!importFile)
1844
+ continue;
1845
+ // Build the transitive file path (needed for import rewriting even if we skip creating)
1846
+ const basePath = safeFolder(importFile.path.split('/').slice(0, -1).join('/'));
1847
+ const extension = importFile.name.split('.').pop();
1848
+ const isIndex = isIndexPath(importFile.path);
1849
+ // Limit pathHash length to prevent ENAMETOOLONG errors on macOS (255 char limit)
1850
+ const pathHash = safeFileName(importFile.path, { maxLength: 80 });
1851
+ const scenarioSlug = safeFileName(scenario.name, { maxLength: 60 });
1852
+ const transitiveFilePath = `${PROJECT_RELATIVE_PATH}/${basePath}/${pathHash}_${isIndex ? 'index_' : ''}transitive_${scenarioSlug}.${extension}`;
1853
+ // Check if this is a circular import (we're already processing this file)
1854
+ const isCircularImport = visitedPaths.has(resolvedPath);
1855
+ // Check if already processed
1856
+ const alreadyProcessed = writtenScenarioComponents[resolvedPath]?.includes('__transitive_file_written__');
1857
+ // Only create the transitive file if not circular and not already processed
1858
+ if (!isCircularImport && !alreadyProcessed) {
1859
+ // Load content if needed
1860
+ if (!importFile.content && fileStore) {
1861
+ importFile = await fileStore.ensureContent(resolvedPath);
1862
+ }
1863
+ if (!importFile?.content) {
1864
+ // Can't create transitive, but still try to rewrite import below
1865
+ }
1866
+ else {
1867
+ // Mark as being processed BEFORE recursing (to detect cycles)
1868
+ visitedPaths.add(resolvedPath);
1869
+ // Strip server-only and mock server-only packages, then recursively process imports
1870
+ let transitiveContent = stripServerOnlyImport(importFile.content);
1871
+ transitiveContent = applyServerOnlyMocks(transitiveContent);
1872
+ debugLog(`processTransitiveImportsRecursively depth=${depth} for ${importFile.path}`);
1873
+ debugLog(`Calling processTransitiveImportsRecursively depth=${depth + 1} for ${importFile.path}`);
1874
+ transitiveContent = await withTimeout(`processTransitiveImportsRecursively depth=${depth} for ${path.basename(importFile.path)}`, processTransitiveImportsRecursively(transitiveContent, importFile.path, transitiveFilePath, visitedPaths, depth + 1, startTime), 30000);
1875
+ debugLog(`withTimeout returned for depth=${depth}, transitiveContent length=${transitiveContent.length}`);
1876
+ debugLog(`Completed processTransitiveImportsRecursively depth=${depth} for ${importFile.path}`);
1877
+ debugLog(`Writing transitive file depth=${depth}`, {
1878
+ transitiveFilePath: path.basename(transitiveFilePath),
1879
+ contentLength: transitiveContent.length,
1880
+ });
1881
+ await writeFile(transitiveFilePath, transitiveContent);
1882
+ debugLog(`Wrote transitive file depth=${depth}`);
1883
+ scenarioComponentPaths.push(transitiveFilePath);
1884
+ if (!writtenScenarioComponents[resolvedPath]) {
1885
+ writtenScenarioComponents[resolvedPath] = [];
1886
+ }
1887
+ writtenScenarioComponents[resolvedPath].push('__transitive_file_written__');
1888
+ }
1889
+ }
1890
+ // ALWAYS rewrite the import to point to the transitive copy
1891
+ // (even for circular imports or already-processed files)
1892
+ debugLog(`Rewriting import path depth=${depth}`, {
1893
+ importPath,
1894
+ resolvedPath,
1895
+ });
1896
+ const relativePath = getRelativePath(targetFilePath, transitiveFilePath);
1897
+ const relativePathWithoutExt = relativePath.replace(/\.(ts|tsx|js|jsx)$/, '');
1898
+ const safeRelativePath = safeFolder(relativePathWithoutExt);
1899
+ const escapedImportPath = importPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1900
+ debugLog(`Applying regex depth=${depth}`, {
1901
+ escapedImportPath,
1902
+ contentLength: modifiedContent.length,
1903
+ });
1904
+ // Quick check if the import path even exists in content
1905
+ const simpleCheck = modifiedContent.includes(importPath);
1906
+ debugLog(`Simple check: importPath "${importPath}" exists: ${simpleCheck}`);
1907
+ if (!simpleCheck) {
1908
+ debugLog(`Skipping regex - import path not found in content`);
1909
+ }
1910
+ else {
1911
+ const regexPattern = `(from\\s*["'])${escapedImportPath}(["'])`;
1912
+ debugLog(`Regex pattern: ${regexPattern.slice(0, 100)}`);
1913
+ const importRegex = new RegExp(regexPattern, 'g');
1914
+ debugLog(`About to call replace...`);
1915
+ // Timing for regex replace to detect slow operations
1916
+ const replaceStart = Date.now();
1917
+ modifiedContent = modifiedContent.replace(importRegex, `$1${safeRelativePath}$2`);
1918
+ const replaceTime = Date.now() - replaceStart;
1919
+ if (replaceTime > 100) {
1920
+ console.warn(`[WriteScenario] SLOW regex replace: ${replaceTime}ms for pattern ${regexPattern.slice(0, 50)} on ${modifiedContent.length} bytes`);
1921
+ }
1922
+ debugLog(`Regex applied depth=${depth} in ${replaceTime}ms`);
1923
+ }
1924
+ debugLog(`[LOOP END] depth=${depth} import ${importIndex} completed`);
1925
+ }
1926
+ debugLog(`[LOOP DONE] Exiting import loop at depth=${depth}`);
1927
+ debugLog(`Returning from processTransitiveImportsRecursively depth=${depth}`);
1928
+ return modifiedContent;
1929
+ }
1930
+ console.log(`[WriteScenario] POST-LOOP ${entity.name}: before remaining imports ${Date.now() - postLoopStartTime}ms`);
1931
+ // Process remaining internal imports that weren't in importedExports
1932
+ // This handles transitive dependencies: when the file content includes code (e.g., from
1933
+ // other functions in the same file) that imports from files with "server-only"
1934
+ debugLog('Extracting remaining import paths');
1935
+ const remainingImportPaths = extractInternalImportPaths(fileContent);
1936
+ debugLog('Found remaining import paths', {
1937
+ count: remainingImportPaths.length,
1938
+ });
1939
+ // Get all file paths that are in importedExports - these are handled by main processing
1940
+ const importedExportFilePaths = new Set(allImportedExports.map((ie) => ie.resolvedFilePath || ie.filePath));
1941
+ debugLog('Starting remaining imports loop', {
1942
+ remainingCount: remainingImportPaths.length,
1943
+ importedExportCount: importedExportFilePaths.size,
1944
+ });
1945
+ let remainingImportIndex = 0;
1946
+ debugLog(`[REMAINING] Starting remaining imports loop, ${remainingImportPaths.length} imports`);
1947
+ for (const importPath of remainingImportPaths) {
1948
+ remainingImportIndex++;
1949
+ debugLog(`[REMAINING LOOP] import ${remainingImportIndex}/${remainingImportPaths.length}: ${importPath}`);
1950
+ // Skip imports that point to generated CodeYam files (same skip logic as
1951
+ // rewriteRelativeModuleImports). Without this, MockData files from earlier
1952
+ // captures that get discovered by the TypeScript compiler would be treated as
1953
+ // regular imports, creating transitive copies with stale content.
1954
+ const scenarioFilePattern = /[a-f0-9]{64}_\w+_[A-Z]\w*$/;
1955
+ const mockDataPattern = /__codeyamMocks__\//;
1956
+ if (scenarioFilePattern.test(importPath) ||
1957
+ mockDataPattern.test(importPath)) {
1958
+ continue;
1959
+ }
1960
+ // Resolve the import path to a project file path
1961
+ const resolvedFilePath = resolveImportPath(importPath, file.path, project);
1962
+ if (!resolvedFilePath) {
1963
+ // Can't resolve - might be a path we don't handle, skip it
1964
+ continue;
1965
+ }
1966
+ // Find the file in project.files, using fileStore for O(1) lookup when available
1967
+ // We need to find the file BEFORE checking importedExports to see if it has server-only
1968
+ let targetFile = fileStore
1969
+ ? fileStore.getByPath(resolvedFilePath)
1970
+ : project.files?.find((f) => f.path === resolvedFilePath);
1971
+ // Skip if this import is in importedExports - it's handled by the main processing loop
1972
+ // UNLESS the file contains "server-only", in which case we still need a transitive copy
1973
+ // with server-only stripped (even if some exports from the file are mocked).
1974
+ if (importedExportFilePaths.has(resolvedFilePath)) {
1975
+ // Check if the file has server-only before skipping
1976
+ let fileContent = targetFile?.content;
1977
+ if (!fileContent && targetFile && fileStore) {
1978
+ // Load content to check for server-only
1979
+ const loadedFile = await fileStore.ensureContent(resolvedFilePath);
1980
+ fileContent = loadedFile?.content;
1981
+ if (loadedFile) {
1982
+ targetFile = loadedFile;
1983
+ }
1984
+ }
1985
+ const hasServerOnly = fileContent && /import\s+["']server-only["']/.test(fileContent);
1986
+ if (!hasServerOnly) {
1987
+ continue;
1988
+ }
1989
+ // File has server-only - continue processing to create transitive copy
1990
+ }
1991
+ if (!targetFile) {
1992
+ continue;
1993
+ }
1994
+ // Compute the transformed file path (needed for import rewriting even if already processed)
1995
+ const targetFileBasePath = safeFolder(targetFile.path.split('/').slice(0, -1).join('/'));
1996
+ const targetFileExtension = targetFile.name.split('.').pop();
1997
+ const targetFileIsIndex = isIndexPath(targetFile.path);
1998
+ // Limit path hash length to prevent ENAMETOOLONG errors
1999
+ const filePathHash = safeFileName(targetFile.path, { maxLength: 80 });
2000
+ const targetScenarioSlug = safeFileName(scenario.name, { maxLength: 60 });
2001
+ const transformedFilePath = `${PROJECT_RELATIVE_PATH}/${targetFileBasePath}/${filePathHash}_${targetFileIsIndex ? 'index_' : ''}transitive_${targetScenarioSlug}.${targetFileExtension}`;
2002
+ // Check if we've already processed this file as a transitive copy
2003
+ // Note: __data_file_written__ is for entity-specific scenario files with different naming,
2004
+ // but we still need transitive copies for server-only stripping. Data entity files may
2005
+ // only export specific items, so we need a full transitive copy with all exports.
2006
+ const alreadyTransitive = writtenScenarioComponents[resolvedFilePath]?.includes('__transitive_file_written__');
2007
+ if (!alreadyTransitive) {
2008
+ // Ensure content is loaded (LazyFileStore loads content on-demand)
2009
+ if (!targetFile.content && fileStore) {
2010
+ targetFile = await fileStore.ensureContent(resolvedFilePath);
2011
+ }
2012
+ if (!targetFile?.content) {
2013
+ continue;
2014
+ }
2015
+ // Get the file content and apply transformations
2016
+ let transformedContent = targetFile.content;
2017
+ transformedContent = stripServerOnlyImport(transformedContent);
2018
+ transformedContent = applyServerOnlyMocks(transformedContent);
2019
+ // Recursively process this transitive file's imports
2020
+ // This handles the nested case: service.ts → brevo.ts → constants.ts
2021
+ const nestedImportPaths = extractInternalImportPaths(transformedContent);
2022
+ debugLog(`[NESTED] Processing ${nestedImportPaths.length} nested imports for ${targetFile.path}`);
2023
+ let nestedIndex = 0;
2024
+ for (const nestedImportPath of nestedImportPaths) {
2025
+ nestedIndex++;
2026
+ debugLog(`[NESTED LOOP] import ${nestedIndex}/${nestedImportPaths.length}: ${nestedImportPath}`);
2027
+ const nestedResolvedPath = resolveImportPath(nestedImportPath, targetFile.path, project);
2028
+ if (!nestedResolvedPath)
2029
+ continue;
2030
+ // Get file info for building the transformed path
2031
+ let nestedFile = fileStore
2032
+ ? fileStore.getByPath(nestedResolvedPath)
2033
+ : project.files?.find((f) => f.path === nestedResolvedPath);
2034
+ if (!nestedFile)
2035
+ continue;
2036
+ // Build the transformed path (needed for import rewriting even if already processed)
2037
+ const nestedBasePath = safeFolder(nestedFile.path.split('/').slice(0, -1).join('/'));
2038
+ const nestedExtension = nestedFile.name.split('.').pop();
2039
+ const nestedIsIndex = isIndexPath(nestedFile.path);
2040
+ // Limit path hash length to prevent ENAMETOOLONG errors
2041
+ const nestedPathHash = safeFileName(nestedFile.path, { maxLength: 80 });
2042
+ const nestedScenarioSlug = safeFileName(scenario.name, {
2043
+ maxLength: 60,
2044
+ });
2045
+ const nestedTransformedPath = `${PROJECT_RELATIVE_PATH}/${nestedBasePath}/${nestedPathHash}_${nestedIsIndex ? 'index_' : ''}transitive_${nestedScenarioSlug}.${nestedExtension}`;
2046
+ // Check if already processed as a transitive file (we can rewrite to point to it)
2047
+ // Note: __data_file_written__ is for entity-specific scenario files with different naming,
2048
+ // but we still need transitive copies for server-only stripping in the import chain
2049
+ const nestedAlreadyTransitive = writtenScenarioComponents[nestedResolvedPath]?.includes('__transitive_file_written__');
2050
+ if (!nestedAlreadyTransitive) {
2051
+ // Ensure content is loaded for nested files
2052
+ if (!nestedFile.content && fileStore) {
2053
+ nestedFile = await fileStore.ensureContent(nestedResolvedPath);
2054
+ }
2055
+ if (!nestedFile?.content)
2056
+ continue;
2057
+ // Strip server-only, mock server-only packages, and recursively process imports
2058
+ // This handles chains of any depth: A -> B -> C -> D
2059
+ let nestedContent = stripServerOnlyImport(nestedFile.content);
2060
+ nestedContent = applyServerOnlyMocks(nestedContent);
2061
+ debugLog(`processTransitiveImportsRecursively (nested) for ${nestedFile.path}`);
2062
+ nestedContent = await withTimeout(`processTransitiveImportsRecursively (nested) for ${path.basename(nestedFile.path)}`, processTransitiveImportsRecursively(nestedContent, nestedFile.path, nestedTransformedPath), 30000);
2063
+ debugLog(`Completed processTransitiveImportsRecursively (nested) for ${nestedFile.path}`);
2064
+ await writeFile(nestedTransformedPath, nestedContent);
2065
+ scenarioComponentPaths.push(nestedTransformedPath);
2066
+ // Mark as written
2067
+ if (!writtenScenarioComponents[nestedResolvedPath]) {
2068
+ writtenScenarioComponents[nestedResolvedPath] = [];
2069
+ }
2070
+ writtenScenarioComponents[nestedResolvedPath].push('__transitive_file_written__');
2071
+ }
2072
+ // Rewrite the import to point to the transitive copy
2073
+ const nestedRelativePath = getRelativePath(transformedFilePath, nestedTransformedPath);
2074
+ // Strip the extension before applying safeFolder - import paths in TypeScript
2075
+ // should NOT include extensions (Next.js resolves .ts/.tsx automatically).
2076
+ // Without this, safeFolder converts ".ts" to "_ts" causing "Module not found" errors.
2077
+ const nestedRelativePathWithoutExt = nestedRelativePath.replace(/\.(ts|tsx|js|jsx)$/, '');
2078
+ const safeNestedRelativePath = safeFolder(nestedRelativePathWithoutExt);
2079
+ const escapedNestedImportPath = nestedImportPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
2080
+ const nestedImportRegex = new RegExp(`(from\\s*["'])${escapedNestedImportPath}(["'])`, 'g');
2081
+ transformedContent = transformedContent.replace(nestedImportRegex, `$1${safeNestedRelativePath}$2`);
2082
+ }
2083
+ // Re-check if file was written during recursive processing
2084
+ // (processTransitiveImportsRecursively might have created this file while processing
2085
+ // a nested import that circularly imports back to this file)
2086
+ const writtenDuringRecursion = writtenScenarioComponents[resolvedFilePath]?.includes('__transitive_file_written__');
2087
+ if (!writtenDuringRecursion) {
2088
+ // Write the transformed file
2089
+ await writeFile(transformedFilePath, transformedContent);
2090
+ scenarioComponentPaths.push(transformedFilePath);
2091
+ // Mark as written
2092
+ if (!writtenScenarioComponents[resolvedFilePath]) {
2093
+ writtenScenarioComponents[resolvedFilePath] = [];
2094
+ }
2095
+ writtenScenarioComponents[resolvedFilePath].push('__transitive_file_written__');
2096
+ }
2097
+ }
2098
+ // ALWAYS rewrite the import in fileContent to point to the transformed file
2099
+ // (even if the transitive copy was already created by another entity)
2100
+ const relativePath = getRelativePath(scenarioComponentPath, transformedFilePath);
2101
+ // Strip the extension before applying safeFolder - import paths in TypeScript
2102
+ // should NOT include extensions (Next.js resolves .ts/.tsx automatically).
2103
+ // Without this, safeFolder converts ".ts" to "_ts" causing "Module not found" errors.
2104
+ const relativePathWithoutExt = relativePath.replace(/\.(ts|tsx|js|jsx)$/, '');
2105
+ const safeRelativePath = safeFolder(relativePathWithoutExt);
2106
+ // Escape special regex characters in the import path
2107
+ const escapedImportPath = importPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
2108
+ const importRegex = new RegExp(`(from\\s*["'])${escapedImportPath}(["'])`, 'g');
2109
+ fileContent = fileContent.replace(importRegex, `$1${safeRelativePath}$2`);
2110
+ }
2111
+ console.log(`[WriteScenario] POST-LOOP ${entity.name}: remaining imports loop took ${Date.now() - postLoopStartTime}ms`);
1215
2112
  const scenarioComponentComment = `// This file is auto-generated by CodeYam. Do not edit this file manually.
1216
2113
  // This file contains content for a scenario component:
1217
2114
  // Analyses being written: ${JSON.stringify(fileAnalyses?.map((a) => ({ id: a.id, entityName: a.entityName })))}
@@ -1222,25 +2119,74 @@ ${exportKeyword}const ${functionName} = new Proxy(() => scenarios().data()?.["${
1222
2119
  // Entity: ${rootAnalysis.entitySha} ${rootAnalysis.entityName}
1223
2120
  // Scenario: ${scenario.id} - ${scenario.name}
1224
2121
  `;
2122
+ // Final pass: Rename any namespace imports (import * as X from '...') that have
2123
+ // corresponding mock code using ...X__cyOriginal spread pattern.
2124
+ // This handles cases where:
2125
+ // 1. The import path was rewritten by transitive import handling
2126
+ // 2. The import wasn't caught by the earlier renaming logic
2127
+ // We scan for all __cyOriginal references in the mock code and ensure the imports are renamed.
2128
+ const cyOriginalReferences = fileContent.match(/\.\.\.(\w+)__cyOriginal/g);
2129
+ if (cyOriginalReferences) {
2130
+ const uniqueNames = [
2131
+ ...new Set(cyOriginalReferences.map((ref) => ref.replace('...', '').replace('__cyOriginal', ''))),
2132
+ ];
2133
+ for (const name of uniqueNames) {
2134
+ // Match namespace imports for this name that haven't been renamed yet
2135
+ const namespaceImportRegex = new RegExp(`(import\\s+\\*\\s+as\\s+)${escapeRegExp(name)}(\\s+from\\s+['"][^'"]*['"])`, 'g');
2136
+ fileContent = fileContent.replace(namespaceImportRegex, `$1${name}__cyOriginal$2`);
2137
+ }
2138
+ }
2139
+ // For route components (page.tsx, layout.tsx), the component IS the Next.js page.
2140
+ // There's no wrapper page to inject argumentsData as props (unlike non-route components
2141
+ // which get a scenarioComponent wrapper). We need to wrap the default export so that
2142
+ // the scenario's argumentsData is passed as props to the component.
2143
+ if (isFrameworkRoute(file, entity, framework, file === rootFile) &&
2144
+ rootAnalysis.metadata?.scenariosDataStructure?.arguments?.length > 0) {
2145
+ const positionalArguments = rootAnalysis.metadata.scenariosDataStructure.arguments;
2146
+ const hasNamedArgs = positionalArguments.length === 1 &&
2147
+ typeof positionalArguments[0] === 'object';
2148
+ if (hasNamedArgs) {
2149
+ // Match: export default function Name(
2150
+ // Also: export default async function Name(
2151
+ const defaultExportMatch = fileContent.match(/export\s+default\s+(async\s+)?function\s+(\w+)\s*\(/);
2152
+ if (defaultExportMatch) {
2153
+ const funcName = defaultExportMatch[2];
2154
+ // Remove "export default" from the original function declaration
2155
+ fileContent = fileContent.replace(/export\s+default\s+(async\s+)?function\s+(\w+)\s*\(/, '$1function $2(');
2156
+ // Ensure scenarios import is present
2157
+ const mockDataPath = `${relativeMocksDir}/MockData_${safeFileName(scenario.name)}`;
2158
+ if (fileContent.indexOf('import { scenarios } from') === -1) {
2159
+ fileContent = `import { scenarios } from "${mockDataPath}";\n\n${fileContent}`;
2160
+ }
2161
+ // Add wrapper default export that injects argumentsData as props
2162
+ fileContent += `\n\nexport default function _CYRouteWrapper(props: any) {
2163
+ const _cyArgs = scenarios().data()?.['arguments']?.[0] ?? {};
2164
+ return <${funcName} {...props} {..._cyArgs} />;
2165
+ }\n`;
2166
+ }
2167
+ }
2168
+ }
1225
2169
  // Use the directive that was extracted at the beginning of processing
1226
2170
  // This ensures it stays at the very top even after imports are prepended
2171
+ // NOTE: We only preserve "use client" directives, NOT "use server" directives.
2172
+ // Server action files get mocked with objects that aren't async functions,
2173
+ // which would violate Next.js's "use server" requirement:
2174
+ // "A 'use server' file can only export async functions, found object."
1227
2175
  let finalContent;
1228
- if (extractedDirective) {
2176
+ if (extractedDirective && extractedDirective.includes('client')) {
1229
2177
  finalContent = `${extractedDirective}\n\n${scenarioComponentComment}\n\n${fileContent}`;
1230
- console.log(`CodeYam: Placed "${extractedDirective}" directive at top of file: ${scenarioComponentPath}`);
1231
2178
  }
1232
2179
  else {
1233
2180
  finalContent = `${scenarioComponentComment}\n\n${fileContent}`;
1234
2181
  }
2182
+ debugLog('About to write final scenario file', {
2183
+ scenarioComponentPath,
2184
+ contentLength: finalContent.length,
2185
+ });
1235
2186
  await writeFile(scenarioComponentPath, finalContent);
2187
+ debugLog('Successfully wrote scenario file');
1236
2188
  scenarioComponentPaths.push(scenarioComponentPath);
1237
- console.log('CodeYam [writeScenarioComponents]: Generated scenario files', {
1238
- entityName: entity.name,
1239
- filePath: file.path,
1240
- scenarioName: scenario.name,
1241
- scenarioComponentPathsGenerated: scenarioComponentPaths,
1242
- writtenScenarioComponentKeys: Object.keys(writtenScenarioComponents),
1243
- });
2189
+ console.log(`[WriteScenario] POST-LOOP ${entity.name}: COMPLETE total=${Date.now() - postLoopStartTime}ms`);
1244
2190
  return { scenarioComponentPaths, writtenScenarioComponents };
1245
2191
  }
1246
2192
  //# sourceMappingURL=writeScenarioComponents.js.map