@codeyam/codeyam-cli 0.1.0-staging.7c30edc → 0.1.0-staging.7dbcbd8

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 (911) hide show
  1. package/analyzer-template/.build-info.json +8 -8
  2. package/analyzer-template/log.txt +3 -3
  3. package/analyzer-template/package.json +24 -24
  4. package/analyzer-template/packages/ai/index.ts +1 -0
  5. package/analyzer-template/packages/ai/package.json +3 -3
  6. package/analyzer-template/packages/ai/src/lib/analyzeScope.ts +14 -0
  7. package/analyzer-template/packages/ai/src/lib/astScopes/astScopeAnalyzer.ts +34 -3
  8. package/analyzer-template/packages/ai/src/lib/astScopes/methodSemantics.ts +135 -0
  9. package/analyzer-template/packages/ai/src/lib/astScopes/nodeToSource.ts +19 -0
  10. package/analyzer-template/packages/ai/src/lib/astScopes/paths.ts +11 -4
  11. package/analyzer-template/packages/ai/src/lib/completionCall.ts +114 -113
  12. package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +295 -14
  13. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/ParentScopeManager.ts +10 -3
  14. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.ts +16 -6
  15. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/coercePrimitivesToArraysBySchema.ts +62 -0
  16. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.ts +29 -18
  17. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/stripNullableMarkers.ts +35 -0
  18. package/analyzer-template/packages/ai/src/lib/dataStructureChunking.ts +15 -6
  19. package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +78 -2
  20. package/analyzer-template/packages/ai/src/lib/generateExecutionFlows.ts +96 -33
  21. package/analyzer-template/packages/analyze/index.ts +4 -1
  22. package/analyzer-template/packages/analyze/src/lib/ProjectAnalyzer.ts +19 -7
  23. package/analyzer-template/packages/analyze/src/lib/asts/index.ts +7 -2
  24. package/analyzer-template/packages/analyze/src/lib/asts/nodes/getNodeType.ts +1 -0
  25. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.ts +46 -2
  26. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +14 -37
  27. package/analyzer-template/packages/analyze/src/lib/files/analyze/dependencyResolver.ts +0 -6
  28. package/analyzer-template/packages/analyze/src/lib/files/analyze/findOrCreateEntity.ts +22 -6
  29. package/analyzer-template/packages/analyze/src/lib/files/analyze/gatherEntityMap.ts +9 -12
  30. package/analyzer-template/packages/analyze/src/lib/files/analyze/trackEntityCircularDependencies.ts +21 -0
  31. package/analyzer-template/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.ts +82 -10
  32. package/analyzer-template/packages/analyze/src/lib/files/analyzeChange.ts +4 -0
  33. package/analyzer-template/packages/analyze/src/lib/files/analyzeInitial.ts +4 -0
  34. package/analyzer-template/packages/analyze/src/lib/files/analyzeNextRoute.ts +8 -3
  35. package/analyzer-template/packages/analyze/src/lib/files/scenarios/TransformationTracer.ts +65 -28
  36. package/analyzer-template/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.ts +50 -25
  37. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +322 -58
  38. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.ts +0 -98
  39. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +1712 -1394
  40. package/analyzer-template/packages/aws/package.json +10 -10
  41. package/analyzer-template/packages/database/index.ts +1 -0
  42. package/analyzer-template/packages/database/package.json +4 -4
  43. package/analyzer-template/packages/database/src/lib/kysely/db.ts +8 -0
  44. package/analyzer-template/packages/database/src/lib/kysely/tables/debugReportsTable.ts +1 -1
  45. package/analyzer-template/packages/database/src/lib/kysely/tables/editorScenariosTable.ts +164 -0
  46. package/analyzer-template/packages/database/src/lib/loadAnalysis.ts +25 -15
  47. package/analyzer-template/packages/database/src/lib/loadCommits.ts +31 -20
  48. package/analyzer-template/packages/database/src/lib/loadEntities.ts +0 -6
  49. package/analyzer-template/packages/database/src/lib/loadEntity.ts +19 -8
  50. package/analyzer-template/packages/database/src/lib/loadReadyToBeCapturedAnalyses.ts +0 -5
  51. package/analyzer-template/packages/database/src/lib/updateCommitMetadata.ts +94 -143
  52. package/analyzer-template/packages/database/src/lib/updateFreshAnalysisStatus.ts +58 -42
  53. package/analyzer-template/packages/database/src/lib/updateFreshAnalysisStatusWithScenarios.ts +81 -65
  54. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.ts +29 -1
  55. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.ts +33 -5
  56. package/analyzer-template/packages/github/dist/database/index.d.ts +1 -0
  57. package/analyzer-template/packages/github/dist/database/index.d.ts.map +1 -1
  58. package/analyzer-template/packages/github/dist/database/index.js +1 -0
  59. package/analyzer-template/packages/github/dist/database/index.js.map +1 -1
  60. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts +2 -0
  61. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts.map +1 -1
  62. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js +5 -0
  63. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js.map +1 -1
  64. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/debugReportsTable.d.ts +1 -1
  65. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.d.ts +29 -0
  66. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.d.ts.map +1 -0
  67. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.js +149 -0
  68. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.js.map +1 -0
  69. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts +5 -0
  70. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/scenariosTable.d.ts.map +1 -1
  71. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.d.ts.map +1 -1
  72. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.js +7 -1
  73. package/analyzer-template/packages/github/dist/database/src/lib/loadAnalysis.js.map +1 -1
  74. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.d.ts.map +1 -1
  75. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js +23 -13
  76. package/analyzer-template/packages/github/dist/database/src/lib/loadCommits.js.map +1 -1
  77. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.d.ts.map +1 -1
  78. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js +0 -6
  79. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js.map +1 -1
  80. package/analyzer-template/packages/github/dist/database/src/lib/loadEntity.d.ts +4 -1
  81. package/analyzer-template/packages/github/dist/database/src/lib/loadEntity.d.ts.map +1 -1
  82. package/analyzer-template/packages/github/dist/database/src/lib/loadEntity.js +5 -5
  83. package/analyzer-template/packages/github/dist/database/src/lib/loadEntity.js.map +1 -1
  84. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.d.ts.map +1 -1
  85. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js +1 -4
  86. package/analyzer-template/packages/github/dist/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
  87. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts.map +1 -1
  88. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js +76 -90
  89. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js.map +1 -1
  90. package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatus.d.ts.map +1 -1
  91. package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatus.js +41 -30
  92. package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatus.js.map +1 -1
  93. package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatusWithScenarios.d.ts.map +1 -1
  94. package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatusWithScenarios.js +68 -57
  95. package/analyzer-template/packages/github/dist/database/src/lib/updateFreshAnalysisStatusWithScenarios.js.map +1 -1
  96. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.d.ts.map +1 -1
  97. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +29 -1
  98. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -1
  99. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.d.ts.map +1 -1
  100. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +33 -5
  101. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
  102. package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.d.ts +2 -0
  103. package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.d.ts.map +1 -1
  104. package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.js +2 -0
  105. package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.js.map +1 -1
  106. package/analyzer-template/packages/github/dist/types/src/types/ProjectMetadata.d.ts +1 -0
  107. package/analyzer-template/packages/github/dist/types/src/types/ProjectMetadata.d.ts.map +1 -1
  108. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts +10 -0
  109. package/analyzer-template/packages/github/dist/types/src/types/Scenario.d.ts.map +1 -1
  110. package/analyzer-template/packages/github/package.json +1 -1
  111. package/analyzer-template/packages/types/src/enums/ProjectFramework.ts +2 -0
  112. package/analyzer-template/packages/types/src/types/ProjectMetadata.ts +1 -0
  113. package/analyzer-template/packages/types/src/types/Scenario.ts +10 -0
  114. package/analyzer-template/packages/ui-components/package.json +1 -1
  115. package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.d.ts +2 -0
  116. package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.d.ts.map +1 -1
  117. package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.js +2 -0
  118. package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.js.map +1 -1
  119. package/analyzer-template/packages/utils/dist/types/src/types/ProjectMetadata.d.ts +1 -0
  120. package/analyzer-template/packages/utils/dist/types/src/types/ProjectMetadata.d.ts.map +1 -1
  121. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts +10 -0
  122. package/analyzer-template/packages/utils/dist/types/src/types/Scenario.d.ts.map +1 -1
  123. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.d.ts +3 -1
  124. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.d.ts.map +1 -1
  125. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js +120 -4
  126. package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js.map +1 -1
  127. package/analyzer-template/packages/utils/src/lib/fs/rsyncCopy.ts +148 -3
  128. package/analyzer-template/playwright/captureFromUrl.ts +89 -82
  129. package/analyzer-template/project/analyzeFileEntities.ts +26 -0
  130. package/analyzer-template/project/constructMockCode.ts +170 -50
  131. package/analyzer-template/project/orchestrateCapture.ts +4 -1
  132. package/analyzer-template/project/reconcileMockDataKeys.ts +19 -14
  133. package/analyzer-template/project/runMultiScenarioServer.ts +26 -3
  134. package/analyzer-template/project/start.ts +3 -0
  135. package/analyzer-template/project/startScenarioCapture.ts +9 -0
  136. package/analyzer-template/project/writeClientLogRoute.ts +125 -0
  137. package/analyzer-template/project/writeMockDataTsx.ts +17 -0
  138. package/analyzer-template/project/writeScenarioComponents.ts +110 -17
  139. package/analyzer-template/tsconfig.json +13 -1
  140. package/background/src/lib/virtualized/project/analyzeFileEntities.js +22 -0
  141. package/background/src/lib/virtualized/project/analyzeFileEntities.js.map +1 -1
  142. package/background/src/lib/virtualized/project/constructMockCode.js +145 -41
  143. package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
  144. package/background/src/lib/virtualized/project/orchestrateCapture.js +4 -1
  145. package/background/src/lib/virtualized/project/orchestrateCapture.js.map +1 -1
  146. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js +17 -11
  147. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js.map +1 -1
  148. package/background/src/lib/virtualized/project/runMultiScenarioServer.js +23 -3
  149. package/background/src/lib/virtualized/project/runMultiScenarioServer.js.map +1 -1
  150. package/background/src/lib/virtualized/project/start.js +2 -0
  151. package/background/src/lib/virtualized/project/start.js.map +1 -1
  152. package/background/src/lib/virtualized/project/startScenarioCapture.js +5 -0
  153. package/background/src/lib/virtualized/project/startScenarioCapture.js.map +1 -1
  154. package/background/src/lib/virtualized/project/writeClientLogRoute.js +110 -0
  155. package/background/src/lib/virtualized/project/writeClientLogRoute.js.map +1 -0
  156. package/background/src/lib/virtualized/project/writeMockDataTsx.js +12 -0
  157. package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
  158. package/background/src/lib/virtualized/project/writeScenarioComponents.js +83 -12
  159. package/background/src/lib/virtualized/project/writeScenarioComponents.js.map +1 -1
  160. package/codeyam-cli/scripts/apply-setup.js +209 -12
  161. package/codeyam-cli/scripts/apply-setup.js.map +1 -1
  162. package/codeyam-cli/src/__tests__/memory-scripts/filter-session.test.js +196 -0
  163. package/codeyam-cli/src/__tests__/memory-scripts/filter-session.test.js.map +1 -0
  164. package/codeyam-cli/src/__tests__/memory-scripts/read-json-field.test.js +114 -0
  165. package/codeyam-cli/src/__tests__/memory-scripts/read-json-field.test.js.map +1 -0
  166. package/codeyam-cli/src/__tests__/memory-scripts/ripgrep-fallback.test.js +149 -0
  167. package/codeyam-cli/src/__tests__/memory-scripts/ripgrep-fallback.test.js.map +1 -0
  168. package/codeyam-cli/src/cli.js +56 -25
  169. package/codeyam-cli/src/cli.js.map +1 -1
  170. package/codeyam-cli/src/commands/__tests__/editor.analyzeImportsArgs.test.js +47 -0
  171. package/codeyam-cli/src/commands/__tests__/editor.analyzeImportsArgs.test.js.map +1 -0
  172. package/codeyam-cli/src/commands/__tests__/editor.auditNoAutoAnalysis.test.js +71 -0
  173. package/codeyam-cli/src/commands/__tests__/editor.auditNoAutoAnalysis.test.js.map +1 -0
  174. package/codeyam-cli/src/commands/__tests__/editor.designSystem.test.js +30 -0
  175. package/codeyam-cli/src/commands/__tests__/editor.designSystem.test.js.map +1 -0
  176. package/codeyam-cli/src/commands/__tests__/editor.isolateArgs.test.js +51 -0
  177. package/codeyam-cli/src/commands/__tests__/editor.isolateArgs.test.js.map +1 -0
  178. package/codeyam-cli/src/commands/__tests__/editor.statePersistence.test.js +55 -0
  179. package/codeyam-cli/src/commands/__tests__/editor.statePersistence.test.js.map +1 -0
  180. package/codeyam-cli/src/commands/__tests__/editor.stepDispatch.test.js +56 -0
  181. package/codeyam-cli/src/commands/__tests__/editor.stepDispatch.test.js.map +1 -0
  182. package/codeyam-cli/src/commands/__tests__/init.gitignore.test.js +137 -47
  183. package/codeyam-cli/src/commands/__tests__/init.gitignore.test.js.map +1 -1
  184. package/codeyam-cli/src/commands/analyze.js +19 -9
  185. package/codeyam-cli/src/commands/analyze.js.map +1 -1
  186. package/codeyam-cli/src/commands/default.js +20 -3
  187. package/codeyam-cli/src/commands/default.js.map +1 -1
  188. package/codeyam-cli/src/commands/editor.js +6313 -0
  189. package/codeyam-cli/src/commands/editor.js.map +1 -0
  190. package/codeyam-cli/src/commands/editorAnalyzeImportsArgs.js +23 -0
  191. package/codeyam-cli/src/commands/editorAnalyzeImportsArgs.js.map +1 -0
  192. package/codeyam-cli/src/commands/editorIsolateArgs.js +25 -0
  193. package/codeyam-cli/src/commands/editorIsolateArgs.js.map +1 -0
  194. package/codeyam-cli/src/commands/init.js +129 -45
  195. package/codeyam-cli/src/commands/init.js.map +1 -1
  196. package/codeyam-cli/src/commands/memory.js +89 -75
  197. package/codeyam-cli/src/commands/memory.js.map +1 -1
  198. package/codeyam-cli/src/commands/setup-simulations.js +1 -1
  199. package/codeyam-cli/src/commands/telemetry.js +37 -0
  200. package/codeyam-cli/src/commands/telemetry.js.map +1 -0
  201. package/codeyam-cli/src/commands/verify.js +12 -2
  202. package/codeyam-cli/src/commands/verify.js.map +1 -1
  203. package/codeyam-cli/src/data/designSystems.js +27 -0
  204. package/codeyam-cli/src/data/designSystems.js.map +1 -0
  205. package/codeyam-cli/src/data/techStacks.js +77 -0
  206. package/codeyam-cli/src/data/techStacks.js.map +1 -0
  207. package/codeyam-cli/src/utils/__tests__/analyzerFinalization.test.js +173 -0
  208. package/codeyam-cli/src/utils/__tests__/analyzerFinalization.test.js.map +1 -0
  209. package/codeyam-cli/src/utils/__tests__/backgroundServer.test.js +46 -0
  210. package/codeyam-cli/src/utils/__tests__/backgroundServer.test.js.map +1 -0
  211. package/codeyam-cli/src/utils/__tests__/devServerState.test.js +226 -0
  212. package/codeyam-cli/src/utils/__tests__/devServerState.test.js.map +1 -0
  213. package/codeyam-cli/src/utils/__tests__/editorApi.test.js +181 -0
  214. package/codeyam-cli/src/utils/__tests__/editorApi.test.js.map +1 -0
  215. package/codeyam-cli/src/utils/__tests__/editorAudit.test.js +4160 -0
  216. package/codeyam-cli/src/utils/__tests__/editorAudit.test.js.map +1 -0
  217. package/codeyam-cli/src/utils/__tests__/editorBroadcastViewport.test.js +76 -0
  218. package/codeyam-cli/src/utils/__tests__/editorBroadcastViewport.test.js.map +1 -0
  219. package/codeyam-cli/src/utils/__tests__/editorCapture.test.js +93 -0
  220. package/codeyam-cli/src/utils/__tests__/editorCapture.test.js.map +1 -0
  221. package/codeyam-cli/src/utils/__tests__/editorCaptureScenarioSeeding.test.js +137 -0
  222. package/codeyam-cli/src/utils/__tests__/editorCaptureScenarioSeeding.test.js.map +1 -0
  223. package/codeyam-cli/src/utils/__tests__/editorDeleteScenario.test.js +100 -0
  224. package/codeyam-cli/src/utils/__tests__/editorDeleteScenario.test.js.map +1 -0
  225. package/codeyam-cli/src/utils/__tests__/editorDevServer.test.js +304 -0
  226. package/codeyam-cli/src/utils/__tests__/editorDevServer.test.js.map +1 -0
  227. package/codeyam-cli/src/utils/__tests__/editorEntityChangeStatus.test.js +194 -0
  228. package/codeyam-cli/src/utils/__tests__/editorEntityChangeStatus.test.js.map +1 -0
  229. package/codeyam-cli/src/utils/__tests__/editorEntityHelpers.test.js +381 -0
  230. package/codeyam-cli/src/utils/__tests__/editorEntityHelpers.test.js.map +1 -0
  231. package/codeyam-cli/src/utils/__tests__/editorGuardMiddleware.test.js +67 -0
  232. package/codeyam-cli/src/utils/__tests__/editorGuardMiddleware.test.js.map +1 -0
  233. package/codeyam-cli/src/utils/__tests__/editorImageVerifier.test.js +294 -0
  234. package/codeyam-cli/src/utils/__tests__/editorImageVerifier.test.js.map +1 -0
  235. package/codeyam-cli/src/utils/__tests__/editorJournal.test.js +542 -0
  236. package/codeyam-cli/src/utils/__tests__/editorJournal.test.js.map +1 -0
  237. package/codeyam-cli/src/utils/__tests__/editorLoaderHelpers.test.js +594 -0
  238. package/codeyam-cli/src/utils/__tests__/editorLoaderHelpers.test.js.map +1 -0
  239. package/codeyam-cli/src/utils/__tests__/editorMigration.test.js +435 -0
  240. package/codeyam-cli/src/utils/__tests__/editorMigration.test.js.map +1 -0
  241. package/codeyam-cli/src/utils/__tests__/editorMockState.test.js +270 -0
  242. package/codeyam-cli/src/utils/__tests__/editorMockState.test.js.map +1 -0
  243. package/codeyam-cli/src/utils/__tests__/editorPreloadHelpers.test.js +217 -0
  244. package/codeyam-cli/src/utils/__tests__/editorPreloadHelpers.test.js.map +1 -0
  245. package/codeyam-cli/src/utils/__tests__/editorPreview.test.js +361 -0
  246. package/codeyam-cli/src/utils/__tests__/editorPreview.test.js.map +1 -0
  247. package/codeyam-cli/src/utils/__tests__/editorProxySession.test.js +250 -0
  248. package/codeyam-cli/src/utils/__tests__/editorProxySession.test.js.map +1 -0
  249. package/codeyam-cli/src/utils/__tests__/editorRoadmap.test.js +1108 -0
  250. package/codeyam-cli/src/utils/__tests__/editorRoadmap.test.js.map +1 -0
  251. package/codeyam-cli/src/utils/__tests__/editorScenarioLookup.test.js +139 -0
  252. package/codeyam-cli/src/utils/__tests__/editorScenarioLookup.test.js.map +1 -0
  253. package/codeyam-cli/src/utils/__tests__/editorScenarioSwitch.test.js +411 -0
  254. package/codeyam-cli/src/utils/__tests__/editorScenarioSwitch.test.js.map +1 -0
  255. package/codeyam-cli/src/utils/__tests__/editorScenarios.test.js +1768 -0
  256. package/codeyam-cli/src/utils/__tests__/editorScenarios.test.js.map +1 -0
  257. package/codeyam-cli/src/utils/__tests__/editorSeedAdapter.test.js +413 -0
  258. package/codeyam-cli/src/utils/__tests__/editorSeedAdapter.test.js.map +1 -0
  259. package/codeyam-cli/src/utils/__tests__/editorSeedAdapterPrismaValidation.test.js +143 -0
  260. package/codeyam-cli/src/utils/__tests__/editorSeedAdapterPrismaValidation.test.js.map +1 -0
  261. package/codeyam-cli/src/utils/__tests__/editorSessionFilter.test.js +66 -0
  262. package/codeyam-cli/src/utils/__tests__/editorSessionFilter.test.js.map +1 -0
  263. package/codeyam-cli/src/utils/__tests__/editorShouldRevalidate.test.js +53 -0
  264. package/codeyam-cli/src/utils/__tests__/editorShouldRevalidate.test.js.map +1 -0
  265. package/codeyam-cli/src/utils/__tests__/entityChangeStatus.test.js +2121 -0
  266. package/codeyam-cli/src/utils/__tests__/entityChangeStatus.test.js.map +1 -0
  267. package/codeyam-cli/src/utils/__tests__/envFile.test.js +125 -0
  268. package/codeyam-cli/src/utils/__tests__/envFile.test.js.map +1 -0
  269. package/codeyam-cli/src/utils/__tests__/git.editor.test.js +134 -0
  270. package/codeyam-cli/src/utils/__tests__/git.editor.test.js.map +1 -0
  271. package/codeyam-cli/src/utils/__tests__/glossaryAdd.test.js +177 -0
  272. package/codeyam-cli/src/utils/__tests__/glossaryAdd.test.js.map +1 -0
  273. package/codeyam-cli/src/utils/__tests__/handoffContext.test.js +500 -0
  274. package/codeyam-cli/src/utils/__tests__/handoffContext.test.js.map +1 -0
  275. package/codeyam-cli/src/utils/__tests__/journalCaptureStabilization.test.js +122 -0
  276. package/codeyam-cli/src/utils/__tests__/journalCaptureStabilization.test.js.map +1 -0
  277. package/codeyam-cli/src/utils/__tests__/manualEntityAnalysis.test.js +302 -0
  278. package/codeyam-cli/src/utils/__tests__/manualEntityAnalysis.test.js.map +1 -0
  279. package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js +185 -0
  280. package/codeyam-cli/src/utils/__tests__/npmVersionCheck.test.js.map +1 -0
  281. package/codeyam-cli/src/utils/__tests__/parseRegisterArg.test.js +129 -0
  282. package/codeyam-cli/src/utils/__tests__/parseRegisterArg.test.js.map +1 -0
  283. package/codeyam-cli/src/utils/__tests__/pathIgnoring.test.js +9 -0
  284. package/codeyam-cli/src/utils/__tests__/pathIgnoring.test.js.map +1 -1
  285. package/codeyam-cli/src/utils/__tests__/project.test.js +65 -0
  286. package/codeyam-cli/src/utils/__tests__/project.test.js.map +1 -0
  287. package/codeyam-cli/src/utils/__tests__/registerScenarioResult.test.js +127 -0
  288. package/codeyam-cli/src/utils/__tests__/registerScenarioResult.test.js.map +1 -0
  289. package/codeyam-cli/src/utils/__tests__/routePatternMatching.test.js +118 -0
  290. package/codeyam-cli/src/utils/__tests__/routePatternMatching.test.js.map +1 -0
  291. package/codeyam-cli/src/utils/__tests__/scenarioCoverage.test.js +284 -0
  292. package/codeyam-cli/src/utils/__tests__/scenarioCoverage.test.js.map +1 -0
  293. package/codeyam-cli/src/utils/__tests__/scenarioMarkers.test.js +121 -0
  294. package/codeyam-cli/src/utils/__tests__/scenarioMarkers.test.js.map +1 -0
  295. package/codeyam-cli/src/utils/__tests__/scenariosManifest.test.js +672 -0
  296. package/codeyam-cli/src/utils/__tests__/scenariosManifest.test.js.map +1 -0
  297. package/codeyam-cli/src/utils/__tests__/screenshotHash.test.js +84 -0
  298. package/codeyam-cli/src/utils/__tests__/screenshotHash.test.js.map +1 -0
  299. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js +62 -15
  300. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js.map +1 -1
  301. package/codeyam-cli/src/utils/__tests__/telemetry.test.js +159 -0
  302. package/codeyam-cli/src/utils/__tests__/telemetry.test.js.map +1 -0
  303. package/codeyam-cli/src/utils/__tests__/templateConsistency.test.js +51 -0
  304. package/codeyam-cli/src/utils/__tests__/templateConsistency.test.js.map +1 -0
  305. package/codeyam-cli/src/utils/__tests__/testRunner.test.js +216 -0
  306. package/codeyam-cli/src/utils/__tests__/testRunner.test.js.map +1 -0
  307. package/codeyam-cli/src/utils/__tests__/webappDetection.test.js +148 -0
  308. package/codeyam-cli/src/utils/__tests__/webappDetection.test.js.map +1 -0
  309. package/codeyam-cli/src/utils/analysisRunner.js +39 -8
  310. package/codeyam-cli/src/utils/analysisRunner.js.map +1 -1
  311. package/codeyam-cli/src/utils/analyzer.js +19 -0
  312. package/codeyam-cli/src/utils/analyzer.js.map +1 -1
  313. package/codeyam-cli/src/utils/analyzerFinalization.js +100 -0
  314. package/codeyam-cli/src/utils/analyzerFinalization.js.map +1 -0
  315. package/codeyam-cli/src/utils/backgroundServer.js +193 -34
  316. package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
  317. package/codeyam-cli/src/utils/buildFlags.js +4 -0
  318. package/codeyam-cli/src/utils/buildFlags.js.map +1 -0
  319. package/codeyam-cli/src/utils/database.js +37 -2
  320. package/codeyam-cli/src/utils/database.js.map +1 -1
  321. package/codeyam-cli/src/utils/designSystemShowcase.js +810 -0
  322. package/codeyam-cli/src/utils/designSystemShowcase.js.map +1 -0
  323. package/codeyam-cli/src/utils/devModeEvents.js +40 -0
  324. package/codeyam-cli/src/utils/devModeEvents.js.map +1 -0
  325. package/codeyam-cli/src/utils/devServerState.js +103 -0
  326. package/codeyam-cli/src/utils/devServerState.js.map +1 -0
  327. package/codeyam-cli/src/utils/editorApi.js +95 -0
  328. package/codeyam-cli/src/utils/editorApi.js.map +1 -0
  329. package/codeyam-cli/src/utils/editorAudit.js +849 -0
  330. package/codeyam-cli/src/utils/editorAudit.js.map +1 -0
  331. package/codeyam-cli/src/utils/editorBroadcastViewport.js +26 -0
  332. package/codeyam-cli/src/utils/editorBroadcastViewport.js.map +1 -0
  333. package/codeyam-cli/src/utils/editorCapture.js +102 -0
  334. package/codeyam-cli/src/utils/editorCapture.js.map +1 -0
  335. package/codeyam-cli/src/utils/editorDeleteScenario.js +67 -0
  336. package/codeyam-cli/src/utils/editorDeleteScenario.js.map +1 -0
  337. package/codeyam-cli/src/utils/editorDevServer.js +197 -0
  338. package/codeyam-cli/src/utils/editorDevServer.js.map +1 -0
  339. package/codeyam-cli/src/utils/editorEntityChangeStatus.js +50 -0
  340. package/codeyam-cli/src/utils/editorEntityChangeStatus.js.map +1 -0
  341. package/codeyam-cli/src/utils/editorEntityHelpers.js +144 -0
  342. package/codeyam-cli/src/utils/editorEntityHelpers.js.map +1 -0
  343. package/codeyam-cli/src/utils/editorGuard.js +36 -0
  344. package/codeyam-cli/src/utils/editorGuard.js.map +1 -0
  345. package/codeyam-cli/src/utils/editorImageVerifier.js +155 -0
  346. package/codeyam-cli/src/utils/editorImageVerifier.js.map +1 -0
  347. package/codeyam-cli/src/utils/editorJournal.js +225 -0
  348. package/codeyam-cli/src/utils/editorJournal.js.map +1 -0
  349. package/codeyam-cli/src/utils/editorLoaderHelpers.js +152 -0
  350. package/codeyam-cli/src/utils/editorLoaderHelpers.js.map +1 -0
  351. package/codeyam-cli/src/utils/editorMigration.js +224 -0
  352. package/codeyam-cli/src/utils/editorMigration.js.map +1 -0
  353. package/codeyam-cli/src/utils/editorMockState.js +248 -0
  354. package/codeyam-cli/src/utils/editorMockState.js.map +1 -0
  355. package/codeyam-cli/src/utils/editorPreloadHelpers.js +135 -0
  356. package/codeyam-cli/src/utils/editorPreloadHelpers.js.map +1 -0
  357. package/codeyam-cli/src/utils/editorPreview.js +139 -0
  358. package/codeyam-cli/src/utils/editorPreview.js.map +1 -0
  359. package/codeyam-cli/src/utils/editorRecapture.js +109 -0
  360. package/codeyam-cli/src/utils/editorRecapture.js.map +1 -0
  361. package/codeyam-cli/src/utils/editorRoadmap.js +574 -0
  362. package/codeyam-cli/src/utils/editorRoadmap.js.map +1 -0
  363. package/codeyam-cli/src/utils/editorScenarioSwitch.js +149 -0
  364. package/codeyam-cli/src/utils/editorScenarioSwitch.js.map +1 -0
  365. package/codeyam-cli/src/utils/editorScenarios.js +687 -0
  366. package/codeyam-cli/src/utils/editorScenarios.js.map +1 -0
  367. package/codeyam-cli/src/utils/editorSeedAdapter.js +475 -0
  368. package/codeyam-cli/src/utils/editorSeedAdapter.js.map +1 -0
  369. package/codeyam-cli/src/utils/editorShouldRevalidate.js +21 -0
  370. package/codeyam-cli/src/utils/editorShouldRevalidate.js.map +1 -0
  371. package/codeyam-cli/src/utils/entityChangeStatus.js +394 -0
  372. package/codeyam-cli/src/utils/entityChangeStatus.js.map +1 -0
  373. package/codeyam-cli/src/utils/entityChangeStatus.server.js +227 -0
  374. package/codeyam-cli/src/utils/entityChangeStatus.server.js.map +1 -0
  375. package/codeyam-cli/src/utils/envFile.js +90 -0
  376. package/codeyam-cli/src/utils/envFile.js.map +1 -0
  377. package/codeyam-cli/src/utils/fileMetadata.js +5 -0
  378. package/codeyam-cli/src/utils/fileMetadata.js.map +1 -1
  379. package/codeyam-cli/src/utils/fileWatcher.js +63 -9
  380. package/codeyam-cli/src/utils/fileWatcher.js.map +1 -1
  381. package/codeyam-cli/src/utils/generateReport.js +2 -2
  382. package/codeyam-cli/src/utils/git.js +103 -0
  383. package/codeyam-cli/src/utils/git.js.map +1 -1
  384. package/codeyam-cli/src/utils/glossaryAdd.js +74 -0
  385. package/codeyam-cli/src/utils/glossaryAdd.js.map +1 -0
  386. package/codeyam-cli/src/utils/handoffContext.js +257 -0
  387. package/codeyam-cli/src/utils/handoffContext.js.map +1 -0
  388. package/codeyam-cli/src/utils/install-skills.js +106 -20
  389. package/codeyam-cli/src/utils/install-skills.js.map +1 -1
  390. package/codeyam-cli/src/utils/interactiveSyncWatcher.js +126 -0
  391. package/codeyam-cli/src/utils/interactiveSyncWatcher.js.map +1 -0
  392. package/codeyam-cli/src/utils/labsAutoCheck.js +0 -29
  393. package/codeyam-cli/src/utils/labsAutoCheck.js.map +1 -1
  394. package/codeyam-cli/src/utils/manualEntityAnalysis.js +196 -0
  395. package/codeyam-cli/src/utils/manualEntityAnalysis.js.map +1 -0
  396. package/codeyam-cli/src/utils/npmVersionCheck.js +76 -0
  397. package/codeyam-cli/src/utils/npmVersionCheck.js.map +1 -0
  398. package/codeyam-cli/src/utils/parseRegisterArg.js +31 -0
  399. package/codeyam-cli/src/utils/parseRegisterArg.js.map +1 -0
  400. package/codeyam-cli/src/utils/pathIgnoring.js +19 -7
  401. package/codeyam-cli/src/utils/pathIgnoring.js.map +1 -1
  402. package/codeyam-cli/src/utils/progress.js +2 -2
  403. package/codeyam-cli/src/utils/progress.js.map +1 -1
  404. package/codeyam-cli/src/utils/project.js +15 -5
  405. package/codeyam-cli/src/utils/project.js.map +1 -1
  406. package/codeyam-cli/src/utils/queue/__tests__/heartbeat.test.js +11 -11
  407. package/codeyam-cli/src/utils/queue/__tests__/heartbeat.test.js.map +1 -1
  408. package/codeyam-cli/src/utils/queue/__tests__/job.interactiveStart.test.js +159 -0
  409. package/codeyam-cli/src/utils/queue/__tests__/job.interactiveStart.test.js.map +1 -0
  410. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js +22 -0
  411. package/codeyam-cli/src/utils/queue/__tests__/manager.test.js.map +1 -1
  412. package/codeyam-cli/src/utils/queue/heartbeat.js +13 -5
  413. package/codeyam-cli/src/utils/queue/heartbeat.js.map +1 -1
  414. package/codeyam-cli/src/utils/queue/job.js +105 -7
  415. package/codeyam-cli/src/utils/queue/job.js.map +1 -1
  416. package/codeyam-cli/src/utils/queue/manager.js +7 -6
  417. package/codeyam-cli/src/utils/queue/manager.js.map +1 -1
  418. package/codeyam-cli/src/utils/registerScenarioResult.js +52 -0
  419. package/codeyam-cli/src/utils/registerScenarioResult.js.map +1 -0
  420. package/codeyam-cli/src/utils/requireSimulations.js +1 -1
  421. package/codeyam-cli/src/utils/requireSimulations.js.map +1 -1
  422. package/codeyam-cli/src/utils/routePatternMatching.js +129 -0
  423. package/codeyam-cli/src/utils/routePatternMatching.js.map +1 -0
  424. package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js +5 -6
  425. package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js.map +1 -1
  426. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js +1 -1
  427. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/assertRules.js.map +1 -1
  428. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js +0 -1
  429. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/helpers/setupTempProject.js.map +1 -1
  430. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js +2 -4
  431. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js.map +1 -1
  432. package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js +4 -6
  433. package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js.map +1 -1
  434. package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js +1 -1
  435. package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js.map +1 -1
  436. package/codeyam-cli/src/utils/rules/__tests__/parser.test.js +83 -0
  437. package/codeyam-cli/src/utils/rules/__tests__/parser.test.js.map +1 -0
  438. package/codeyam-cli/src/utils/rules/__tests__/pathMatcher.test.js +118 -0
  439. package/codeyam-cli/src/utils/rules/__tests__/pathMatcher.test.js.map +1 -0
  440. package/codeyam-cli/src/utils/rules/__tests__/rulePlacement.test.js +72 -0
  441. package/codeyam-cli/src/utils/rules/__tests__/rulePlacement.test.js.map +1 -0
  442. package/codeyam-cli/src/utils/rules/__tests__/sourceFiles.test.js +76 -0
  443. package/codeyam-cli/src/utils/rules/__tests__/sourceFiles.test.js.map +1 -0
  444. package/codeyam-cli/src/utils/rules/index.js +1 -0
  445. package/codeyam-cli/src/utils/rules/index.js.map +1 -1
  446. package/codeyam-cli/src/utils/rules/parser.js +14 -4
  447. package/codeyam-cli/src/utils/rules/parser.js.map +1 -1
  448. package/codeyam-cli/src/utils/rules/pathMatcher.js +34 -3
  449. package/codeyam-cli/src/utils/rules/pathMatcher.js.map +1 -1
  450. package/codeyam-cli/src/utils/rules/rulePlacement.js +65 -0
  451. package/codeyam-cli/src/utils/rules/rulePlacement.js.map +1 -0
  452. package/codeyam-cli/src/utils/rules/sourceFiles.js +43 -0
  453. package/codeyam-cli/src/utils/rules/sourceFiles.js.map +1 -0
  454. package/codeyam-cli/src/utils/scenarioCoverage.js +77 -0
  455. package/codeyam-cli/src/utils/scenarioCoverage.js.map +1 -0
  456. package/codeyam-cli/src/utils/scenarioMarkers.js +134 -0
  457. package/codeyam-cli/src/utils/scenarioMarkers.js.map +1 -0
  458. package/codeyam-cli/src/utils/scenariosManifest.js +313 -0
  459. package/codeyam-cli/src/utils/scenariosManifest.js.map +1 -0
  460. package/codeyam-cli/src/utils/screenshotHash.js +26 -0
  461. package/codeyam-cli/src/utils/screenshotHash.js.map +1 -0
  462. package/codeyam-cli/src/utils/serverState.js +57 -2
  463. package/codeyam-cli/src/utils/serverState.js.map +1 -1
  464. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +90 -18
  465. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
  466. package/codeyam-cli/src/utils/simulationGateMiddleware.js +175 -0
  467. package/codeyam-cli/src/utils/simulationGateMiddleware.js.map +1 -0
  468. package/codeyam-cli/src/utils/slugUtils.js +25 -0
  469. package/codeyam-cli/src/utils/slugUtils.js.map +1 -0
  470. package/codeyam-cli/src/utils/syncMocksMiddleware.js +7 -26
  471. package/codeyam-cli/src/utils/syncMocksMiddleware.js.map +1 -1
  472. package/codeyam-cli/src/utils/techStackConfig.js +38 -0
  473. package/codeyam-cli/src/utils/techStackConfig.js.map +1 -0
  474. package/codeyam-cli/src/utils/techStackConfig.test.js +85 -0
  475. package/codeyam-cli/src/utils/techStackConfig.test.js.map +1 -0
  476. package/codeyam-cli/src/utils/telemetry.js +106 -0
  477. package/codeyam-cli/src/utils/telemetry.js.map +1 -0
  478. package/codeyam-cli/src/utils/telemetryMiddleware.js +22 -0
  479. package/codeyam-cli/src/utils/telemetryMiddleware.js.map +1 -0
  480. package/codeyam-cli/src/utils/testResultCache.js +53 -0
  481. package/codeyam-cli/src/utils/testResultCache.js.map +1 -0
  482. package/codeyam-cli/src/utils/testResultCache.server.js +81 -0
  483. package/codeyam-cli/src/utils/testResultCache.server.js.map +1 -0
  484. package/codeyam-cli/src/utils/testResultCache.server.test.js +187 -0
  485. package/codeyam-cli/src/utils/testResultCache.server.test.js.map +1 -0
  486. package/codeyam-cli/src/utils/testResultCache.test.js +230 -0
  487. package/codeyam-cli/src/utils/testResultCache.test.js.map +1 -0
  488. package/codeyam-cli/src/utils/testRunner.js +350 -0
  489. package/codeyam-cli/src/utils/testRunner.js.map +1 -0
  490. package/codeyam-cli/src/utils/transcriptPruning.js +67 -0
  491. package/codeyam-cli/src/utils/transcriptPruning.js.map +1 -0
  492. package/codeyam-cli/src/utils/versionInfo.js +46 -0
  493. package/codeyam-cli/src/utils/versionInfo.js.map +1 -1
  494. package/codeyam-cli/src/utils/webappDetection.js +38 -3
  495. package/codeyam-cli/src/utils/webappDetection.js.map +1 -1
  496. package/codeyam-cli/src/webserver/__tests__/api.interactive-switch-scenario.test.js +99 -0
  497. package/codeyam-cli/src/webserver/__tests__/api.interactive-switch-scenario.test.js.map +1 -0
  498. package/codeyam-cli/src/webserver/__tests__/buildPtyEnv.test.js +153 -0
  499. package/codeyam-cli/src/webserver/__tests__/buildPtyEnv.test.js.map +1 -0
  500. package/codeyam-cli/src/webserver/__tests__/clientErrors.test.js +107 -0
  501. package/codeyam-cli/src/webserver/__tests__/clientErrors.test.js.map +1 -0
  502. package/codeyam-cli/src/webserver/__tests__/dependency-smoke.test.js +66 -0
  503. package/codeyam-cli/src/webserver/__tests__/dependency-smoke.test.js.map +1 -0
  504. package/codeyam-cli/src/webserver/__tests__/editorProxy.test.js +1000 -0
  505. package/codeyam-cli/src/webserver/__tests__/editorProxy.test.js.map +1 -0
  506. package/codeyam-cli/src/webserver/__tests__/idleDetector.test.js +315 -0
  507. package/codeyam-cli/src/webserver/__tests__/idleDetector.test.js.map +1 -0
  508. package/codeyam-cli/src/webserver/__tests__/stripClaudeCommand.test.js +135 -0
  509. package/codeyam-cli/src/webserver/__tests__/stripClaudeCommand.test.js.map +1 -0
  510. package/codeyam-cli/src/webserver/app/lib/clientErrors.js +86 -0
  511. package/codeyam-cli/src/webserver/app/lib/clientErrors.js.map +1 -0
  512. package/codeyam-cli/src/webserver/app/lib/database.js +41 -27
  513. package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
  514. package/codeyam-cli/src/webserver/app/lib/dbNotifier.js.map +1 -1
  515. package/codeyam-cli/src/webserver/app/lib/git.js +397 -0
  516. package/codeyam-cli/src/webserver/app/lib/git.js.map +1 -0
  517. package/codeyam-cli/src/webserver/app/routes/api.interactive-switch-scenario.js +34 -0
  518. package/codeyam-cli/src/webserver/app/routes/api.interactive-switch-scenario.js.map +1 -0
  519. package/codeyam-cli/src/webserver/app/types/editor.js +8 -0
  520. package/codeyam-cli/src/webserver/app/types/editor.js.map +1 -0
  521. package/codeyam-cli/src/webserver/backgroundServer.js +166 -48
  522. package/codeyam-cli/src/webserver/backgroundServer.js.map +1 -1
  523. package/codeyam-cli/src/webserver/bootstrap.js +11 -0
  524. package/codeyam-cli/src/webserver/bootstrap.js.map +1 -1
  525. package/codeyam-cli/src/webserver/build/client/assets/CopyButton-DTBZZfSk.js +1 -0
  526. package/codeyam-cli/src/webserver/build/client/assets/{EntityItem-B86KKU7e.js → EntityItem-BxclONWq.js} +5 -5
  527. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeBadge-CQgyEGV-.js +1 -0
  528. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeIcon-BqY8gDAW.js → EntityTypeIcon-BsnEOJZ_.js} +9 -9
  529. package/codeyam-cli/src/webserver/build/client/assets/InlineSpinner-ByaELMbv.js +1 -0
  530. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-6WjVfhxX.js +25 -0
  531. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-ChX-Hp7W.js +3 -0
  532. package/codeyam-cli/src/webserver/build/client/assets/{LoadingDots-Bs7Nn1Jr.js → LoadingDots-By5zI316.js} +1 -1
  533. package/codeyam-cli/src/webserver/build/client/assets/{LogViewer-Bm3PmcCz.js → LogViewer-C-9zQdXg.js} +3 -3
  534. package/codeyam-cli/src/webserver/build/client/assets/MiniClaudeChat-Bs2_Oua4.js +36 -0
  535. package/codeyam-cli/src/webserver/build/client/assets/{ReportIssueModal-C6PKeMYR.js → ReportIssueModal-DQsceHVv.js} +4 -4
  536. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-DThcm_9M.js +1 -0
  537. package/codeyam-cli/src/webserver/build/client/assets/{ScenarioViewer-BNLaXBHR.js → ScenarioViewer-Cl4oOA3A.js} +3 -3
  538. package/codeyam-cli/src/webserver/build/client/assets/Spinner-CIil5-gb.js +34 -0
  539. package/codeyam-cli/src/webserver/build/client/assets/TruncatedFilePath-CK7-NaPZ.js +1 -0
  540. package/codeyam-cli/src/webserver/build/client/assets/ViewportInspectBar-BqkA9zyZ.js +1 -0
  541. package/codeyam-cli/src/webserver/build/client/assets/{_index-B3TDXxnk.js → _index-DnOgyseQ.js} +4 -4
  542. package/codeyam-cli/src/webserver/build/client/assets/{activity.(_tab)-BtBFH820.js → activity.(_tab)-DqM9hbNE.js} +8 -8
  543. package/codeyam-cli/src/webserver/build/client/assets/addon-canvas-DpzMmAy5.js +1 -0
  544. package/codeyam-cli/src/webserver/build/client/assets/addon-fit-YJmn1quW.js +12 -0
  545. package/codeyam-cli/src/webserver/build/client/assets/addon-web-links-C58dYPwR.js +1 -0
  546. package/codeyam-cli/src/webserver/build/client/assets/addon-webgl-DI8QOUvO.js +58 -0
  547. package/codeyam-cli/src/webserver/build/client/assets/agent-transcripts-B8NCeOrm.js +22 -0
  548. package/codeyam-cli/src/webserver/build/client/assets/api.editor-audit-l0sNRNKZ.js +1 -0
  549. package/codeyam-cli/src/webserver/build/client/assets/api.editor-capture-scenario-l0sNRNKZ.js +1 -0
  550. package/codeyam-cli/src/webserver/build/client/assets/api.editor-client-errors-l0sNRNKZ.js +1 -0
  551. package/codeyam-cli/src/webserver/build/client/assets/api.editor-commit-l0sNRNKZ.js +1 -0
  552. package/codeyam-cli/src/webserver/build/client/assets/api.editor-database-verify-l0sNRNKZ.js +1 -0
  553. package/codeyam-cli/src/webserver/build/client/assets/api.editor-dev-server-l0sNRNKZ.js +1 -0
  554. package/codeyam-cli/src/webserver/build/client/assets/api.editor-entity-status-l0sNRNKZ.js +1 -0
  555. package/codeyam-cli/src/webserver/build/client/assets/api.editor-file-diff-l0sNRNKZ.js +1 -0
  556. package/codeyam-cli/src/webserver/build/client/assets/api.editor-file-l0sNRNKZ.js +1 -0
  557. package/codeyam-cli/src/webserver/build/client/assets/api.editor-github-verify-l0sNRNKZ.js +1 -0
  558. package/codeyam-cli/src/webserver/build/client/assets/api.editor-handoff-l0sNRNKZ.js +1 -0
  559. package/codeyam-cli/src/webserver/build/client/assets/api.editor-hosting-verify-l0sNRNKZ.js +1 -0
  560. package/codeyam-cli/src/webserver/build/client/assets/api.editor-journal-entry-l0sNRNKZ.js +1 -0
  561. package/codeyam-cli/src/webserver/build/client/assets/api.editor-journal-image._-l0sNRNKZ.js +1 -0
  562. package/codeyam-cli/src/webserver/build/client/assets/api.editor-journal-l0sNRNKZ.js +1 -0
  563. package/codeyam-cli/src/webserver/build/client/assets/api.editor-journal-screenshot-l0sNRNKZ.js +1 -0
  564. package/codeyam-cli/src/webserver/build/client/assets/api.editor-journal-update-l0sNRNKZ.js +1 -0
  565. package/codeyam-cli/src/webserver/build/client/assets/api.editor-load-commit-l0sNRNKZ.js +1 -0
  566. package/codeyam-cli/src/webserver/build/client/assets/api.editor-project-info-l0sNRNKZ.js +1 -0
  567. package/codeyam-cli/src/webserver/build/client/assets/api.editor-recapture-stale-l0sNRNKZ.js +1 -0
  568. package/codeyam-cli/src/webserver/build/client/assets/api.editor-refresh-l0sNRNKZ.js +1 -0
  569. package/codeyam-cli/src/webserver/build/client/assets/api.editor-register-scenario-l0sNRNKZ.js +1 -0
  570. package/codeyam-cli/src/webserver/build/client/assets/api.editor-rename-scenario-l0sNRNKZ.js +1 -0
  571. package/codeyam-cli/src/webserver/build/client/assets/api.editor-roadmap-l0sNRNKZ.js +1 -0
  572. package/codeyam-cli/src/webserver/build/client/assets/api.editor-save-scenario-data-l0sNRNKZ.js +1 -0
  573. package/codeyam-cli/src/webserver/build/client/assets/api.editor-save-seed-state-l0sNRNKZ.js +1 -0
  574. package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenario-coverage-l0sNRNKZ.js +1 -0
  575. package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenario-data-l0sNRNKZ.js +1 -0
  576. package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenario-image._-l0sNRNKZ.js +1 -0
  577. package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenario-prompt-l0sNRNKZ.js +1 -0
  578. package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenarios-l0sNRNKZ.js +1 -0
  579. package/codeyam-cli/src/webserver/build/client/assets/api.editor-schema-l0sNRNKZ.js +1 -0
  580. package/codeyam-cli/src/webserver/build/client/assets/api.editor-session-l0sNRNKZ.js +1 -0
  581. package/codeyam-cli/src/webserver/build/client/assets/api.editor-switch-scenario-l0sNRNKZ.js +1 -0
  582. package/codeyam-cli/src/webserver/build/client/assets/api.editor-test-results-l0sNRNKZ.js +1 -0
  583. package/codeyam-cli/src/webserver/build/client/assets/api.editor-verify-routes-l0sNRNKZ.js +1 -0
  584. package/codeyam-cli/src/webserver/build/client/assets/api.interactive-switch-scenario-l0sNRNKZ.js +1 -0
  585. package/codeyam-cli/src/webserver/build/client/assets/api.rule-path-l0sNRNKZ.js +1 -0
  586. package/codeyam-cli/src/webserver/build/client/assets/{book-open-PttOB2SF.js → book-open-BFSIqZgO.js} +2 -2
  587. package/codeyam-cli/src/webserver/build/client/assets/{chevron-down-TJp6ofnp.js → chevron-down-B9fDzFVh.js} +2 -2
  588. package/codeyam-cli/src/webserver/build/client/assets/chunk-UVKPFVEO-Bmq2apuh.js +43 -0
  589. package/codeyam-cli/src/webserver/build/client/assets/{circle-check-CXhHQYrI.js → circle-check-DLPObLUx.js} +2 -2
  590. package/codeyam-cli/src/webserver/build/client/assets/{copy-6y9ALfGT.js → copy-DXEmO0TD.js} +3 -3
  591. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-BwyFiRot.js +41 -0
  592. package/codeyam-cli/src/webserver/build/client/assets/cy-logo-cli-Coe5NhbS.js +1 -0
  593. package/codeyam-cli/src/webserver/build/client/assets/{cy-logo-cli-CCKUIm0S.svg → cy-logo-cli-DoA97ML3.svg} +2 -2
  594. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-iRhRIFlp.js +1 -0
  595. package/codeyam-cli/src/webserver/build/client/assets/editor._tab-BZPBzV73.js +1 -0
  596. package/codeyam-cli/src/webserver/build/client/assets/editor.entity.(_sha)-DhtVC4aI.js +161 -0
  597. package/codeyam-cli/src/webserver/build/client/assets/editorPreview-C6fEYHrh.js +41 -0
  598. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-n38keI1k.js → entity._sha._-pc-vc6wO.js} +14 -13
  599. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.dev-C8AyYgYT.js +6 -0
  600. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-DziaVQX1.js +6 -0
  601. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-BTcpgIpC.js +6 -0
  602. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha_.edit._scenarioId-38yPijoD.js → entity._sha_.edit._scenarioId-D_O_ajfZ.js} +2 -2
  603. package/codeyam-cli/src/webserver/build/client/assets/{entry.client-BSHEfydn.js → entry.client-j1Vi0bco.js} +6 -6
  604. package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-Daa96Fr1.js +1 -0
  605. package/codeyam-cli/src/webserver/build/client/assets/files-kuny2Q_s.js +1 -0
  606. package/codeyam-cli/src/webserver/build/client/assets/git-DgCZPMie.js +1 -0
  607. package/codeyam-cli/src/webserver/build/client/assets/globals-L-aUIeux.css +1 -0
  608. package/codeyam-cli/src/webserver/build/client/assets/{index-CcsFv748.js → index-BliGSSpl.js} +1 -1
  609. package/codeyam-cli/src/webserver/build/client/assets/index-SqjQKTdH.js +15 -0
  610. package/codeyam-cli/src/webserver/build/client/assets/{index-ChN9-fAY.js → index-vyrZD2g4.js} +1 -1
  611. package/codeyam-cli/src/webserver/build/client/assets/jsx-runtime-D_zvdyIk.js +9 -0
  612. package/codeyam-cli/src/webserver/build/client/assets/labs-c3yLxSEp.js +1 -0
  613. package/codeyam-cli/src/webserver/build/client/assets/{loader-circle-CTqLEAGU.js → loader-circle-D-q28GLF.js} +2 -2
  614. package/codeyam-cli/src/webserver/build/client/assets/manifest-79d0d81a.js +1 -0
  615. package/codeyam-cli/src/webserver/build/client/assets/memory-CEWIUC4t.js +101 -0
  616. package/codeyam-cli/src/webserver/build/client/assets/{pause-D6vreykR.js → pause-BP6fitdh.js} +3 -3
  617. package/codeyam-cli/src/webserver/build/client/assets/root-L2V0jea7.js +80 -0
  618. package/codeyam-cli/src/webserver/build/client/assets/{search-B8VUL8nl.js → search-BooqacKS.js} +2 -2
  619. package/codeyam-cli/src/webserver/build/client/assets/settings-BM0nbryO.js +1 -0
  620. package/codeyam-cli/src/webserver/build/client/assets/simulations-ovy6FjRY.js +1 -0
  621. package/codeyam-cli/src/webserver/build/client/assets/{terminal-BrCP7uQo.js → terminal-DHemCJIs.js} +3 -3
  622. package/codeyam-cli/src/webserver/build/client/assets/{triangle-alert-BZz2NjYa.js → triangle-alert-D87ekDl8.js} +2 -2
  623. package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-Dk0Tciqg.js +1 -0
  624. package/codeyam-cli/src/webserver/build/client/assets/useLastLogLine-C8QvIe05.js +2 -0
  625. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-jkCytuYz.js +1 -0
  626. package/codeyam-cli/src/webserver/build/client/assets/useToast-BgqkixU9.js +1 -0
  627. package/codeyam-cli/src/webserver/build/client/assets/xterm-BqvuqXEL.js +27 -0
  628. package/codeyam-cli/src/webserver/build/client/sound-test.html +98 -0
  629. package/codeyam-cli/src/webserver/build/server/assets/analysisRunner-QgInFGdU.js +16 -0
  630. package/codeyam-cli/src/webserver/build/server/assets/index-zblh9auj.js +1 -0
  631. package/codeyam-cli/src/webserver/build/server/assets/init-DaE0CBjk.js +14 -0
  632. package/codeyam-cli/src/webserver/build/server/assets/progress-CHTtrxFG.js +1 -0
  633. package/codeyam-cli/src/webserver/build/server/assets/server-build-CNvgz1cC.js +853 -0
  634. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  635. package/codeyam-cli/src/webserver/build-info.json +5 -5
  636. package/codeyam-cli/src/webserver/devServer.js +39 -5
  637. package/codeyam-cli/src/webserver/devServer.js.map +1 -1
  638. package/codeyam-cli/src/webserver/editorProxy.js +1263 -0
  639. package/codeyam-cli/src/webserver/editorProxy.js.map +1 -0
  640. package/codeyam-cli/src/webserver/idleDetector.js +130 -0
  641. package/codeyam-cli/src/webserver/idleDetector.js.map +1 -0
  642. package/codeyam-cli/src/webserver/mockStateEvents.js +28 -0
  643. package/codeyam-cli/src/webserver/mockStateEvents.js.map +1 -0
  644. package/codeyam-cli/src/webserver/public/sound-test.html +98 -0
  645. package/codeyam-cli/src/webserver/scripts/codeyam-preload.mjs +414 -0
  646. package/codeyam-cli/src/webserver/scripts/journalCapture.ts +283 -0
  647. package/codeyam-cli/src/webserver/server.js +446 -1
  648. package/codeyam-cli/src/webserver/server.js.map +1 -1
  649. package/codeyam-cli/src/webserver/terminalServer.js +1043 -0
  650. package/codeyam-cli/src/webserver/terminalServer.js.map +1 -0
  651. package/codeyam-cli/templates/__tests__/editor-step-hook.prompt-capture.test.ts +118 -0
  652. package/codeyam-cli/templates/chrome-extension-react/EXTENSION_SETUP.md +75 -0
  653. package/codeyam-cli/templates/chrome-extension-react/README.md +46 -0
  654. package/codeyam-cli/templates/chrome-extension-react/gitignore +15 -0
  655. package/codeyam-cli/templates/chrome-extension-react/index.html +12 -0
  656. package/codeyam-cli/templates/chrome-extension-react/package.json +27 -0
  657. package/codeyam-cli/templates/chrome-extension-react/popup.html +12 -0
  658. package/codeyam-cli/templates/chrome-extension-react/public/manifest.json +15 -0
  659. package/codeyam-cli/templates/chrome-extension-react/src/background/service-worker.ts +7 -0
  660. package/codeyam-cli/templates/chrome-extension-react/src/globals.css +6 -0
  661. package/codeyam-cli/templates/chrome-extension-react/src/lib/storage.ts +37 -0
  662. package/codeyam-cli/templates/chrome-extension-react/src/popup/App.tsx +12 -0
  663. package/codeyam-cli/templates/chrome-extension-react/src/popup/main.tsx +10 -0
  664. package/codeyam-cli/templates/chrome-extension-react/tsconfig.json +24 -0
  665. package/codeyam-cli/templates/chrome-extension-react/vite.config.ts +41 -0
  666. package/codeyam-cli/templates/codeyam-editor-claude.md +149 -0
  667. package/codeyam-cli/templates/codeyam-editor-codex.md +61 -0
  668. package/codeyam-cli/templates/codeyam-editor-gemini.md +59 -0
  669. package/codeyam-cli/templates/codeyam-editor-reference.md +216 -0
  670. package/codeyam-cli/templates/{codeyam:diagnose.md → commands/codeyam-diagnose.md} +1 -1
  671. package/codeyam-cli/templates/design-systems/clean-dashboard-design-system.md +255 -0
  672. package/codeyam-cli/templates/design-systems/editorial-design-system.md +267 -0
  673. package/codeyam-cli/templates/design-systems/mono-brutalist-design-system.md +256 -0
  674. package/codeyam-cli/templates/design-systems/neo-brutalist-design-system.md +294 -0
  675. package/codeyam-cli/templates/editor-step-hook.py +368 -0
  676. package/codeyam-cli/templates/expo-react-native/MOBILE_SETUP.md +288 -0
  677. package/codeyam-cli/templates/expo-react-native/README.md +41 -0
  678. package/codeyam-cli/templates/expo-react-native/__tests__/.gitkeep +0 -0
  679. package/codeyam-cli/templates/expo-react-native/app/_layout.tsx +15 -0
  680. package/codeyam-cli/templates/expo-react-native/app/index.tsx +36 -0
  681. package/codeyam-cli/templates/expo-react-native/app.json +29 -0
  682. package/codeyam-cli/templates/expo-react-native/babel.config.js +10 -0
  683. package/codeyam-cli/templates/expo-react-native/gitignore +14 -0
  684. package/codeyam-cli/templates/expo-react-native/global.css +10 -0
  685. package/codeyam-cli/templates/expo-react-native/lib/storage.ts +32 -0
  686. package/codeyam-cli/templates/expo-react-native/lib/theme.ts +73 -0
  687. package/codeyam-cli/templates/expo-react-native/metro.config.js +6 -0
  688. package/codeyam-cli/templates/expo-react-native/nativewind-env.d.ts +1 -0
  689. package/codeyam-cli/templates/expo-react-native/package.json +54 -0
  690. package/codeyam-cli/templates/expo-react-native/patches/expo-modules-autolinking+3.0.24.patch +29 -0
  691. package/codeyam-cli/templates/expo-react-native/tailwind.config.js +10 -0
  692. package/codeyam-cli/templates/expo-react-native/tsconfig.json +10 -0
  693. package/codeyam-cli/templates/hooks/staleness-check.sh +43 -0
  694. package/codeyam-cli/templates/isolation-route/expo-router.tsx.template +54 -0
  695. package/codeyam-cli/templates/isolation-route/next-app.tsx.template +80 -0
  696. package/codeyam-cli/templates/isolation-route/next-pages.tsx.template +79 -0
  697. package/codeyam-cli/templates/isolation-route/vite-react.tsx.template +78 -0
  698. package/codeyam-cli/templates/msw/browser-setup.ts.template +47 -0
  699. package/codeyam-cli/templates/msw/handler-router.ts.template +47 -0
  700. package/codeyam-cli/templates/msw/server-setup.ts.template +52 -0
  701. package/codeyam-cli/templates/nextjs-prisma-sqlite/AUTH_PATTERNS.md +308 -0
  702. package/codeyam-cli/templates/nextjs-prisma-sqlite/AUTH_UPGRADE.md +304 -0
  703. package/codeyam-cli/templates/nextjs-prisma-sqlite/DATABASE.md +126 -0
  704. package/codeyam-cli/templates/nextjs-prisma-sqlite/FEATURE_PATTERNS.md +37 -0
  705. package/codeyam-cli/templates/nextjs-prisma-sqlite/README.md +53 -0
  706. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/api/todos/route.ts +17 -0
  707. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/codeyam-isolate/layout.tsx +12 -0
  708. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/globals.css +26 -0
  709. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/layout.tsx +34 -0
  710. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/lib/prisma.ts +24 -0
  711. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/page.tsx +10 -0
  712. package/codeyam-cli/templates/nextjs-prisma-sqlite/env +4 -0
  713. package/codeyam-cli/templates/nextjs-prisma-sqlite/eslint.config.mjs +11 -0
  714. package/codeyam-cli/templates/nextjs-prisma-sqlite/gitignore +65 -0
  715. package/codeyam-cli/templates/nextjs-prisma-sqlite/next.config.ts +14 -0
  716. package/codeyam-cli/templates/nextjs-prisma-sqlite/package.json +39 -0
  717. package/codeyam-cli/templates/nextjs-prisma-sqlite/postcss.config.mjs +7 -0
  718. package/codeyam-cli/templates/nextjs-prisma-sqlite/prisma/schema.prisma +27 -0
  719. package/codeyam-cli/templates/nextjs-prisma-sqlite/prisma/seed.ts +40 -0
  720. package/codeyam-cli/templates/nextjs-prisma-sqlite/prisma.config.ts +12 -0
  721. package/codeyam-cli/templates/nextjs-prisma-sqlite/seed-adapter.ts +140 -0
  722. package/codeyam-cli/templates/nextjs-prisma-sqlite/tsconfig.json +34 -0
  723. package/codeyam-cli/templates/nextjs-prisma-sqlite/vitest.config.ts +13 -0
  724. package/codeyam-cli/templates/nextjs-prisma-supabase/README.md +52 -0
  725. package/codeyam-cli/templates/nextjs-prisma-supabase/SUPABASE_SETUP.md +104 -0
  726. package/codeyam-cli/templates/nextjs-prisma-supabase/app/api/todos/route.ts +17 -0
  727. package/codeyam-cli/templates/nextjs-prisma-supabase/app/globals.css +26 -0
  728. package/codeyam-cli/templates/nextjs-prisma-supabase/app/layout.tsx +34 -0
  729. package/codeyam-cli/templates/nextjs-prisma-supabase/app/lib/prisma.ts +20 -0
  730. package/codeyam-cli/templates/nextjs-prisma-supabase/app/lib/supabase.ts +12 -0
  731. package/codeyam-cli/templates/nextjs-prisma-supabase/app/page.tsx +10 -0
  732. package/codeyam-cli/templates/nextjs-prisma-supabase/env +9 -0
  733. package/codeyam-cli/templates/nextjs-prisma-supabase/eslint.config.mjs +11 -0
  734. package/codeyam-cli/templates/nextjs-prisma-supabase/gitignore +40 -0
  735. package/codeyam-cli/templates/nextjs-prisma-supabase/next.config.ts +11 -0
  736. package/codeyam-cli/templates/nextjs-prisma-supabase/package.json +37 -0
  737. package/codeyam-cli/templates/nextjs-prisma-supabase/postcss.config.mjs +7 -0
  738. package/codeyam-cli/templates/nextjs-prisma-supabase/prisma/schema.prisma +27 -0
  739. package/codeyam-cli/templates/nextjs-prisma-supabase/prisma/seed.ts +39 -0
  740. package/codeyam-cli/templates/nextjs-prisma-supabase/prisma.config.ts +12 -0
  741. package/codeyam-cli/templates/nextjs-prisma-supabase/tsconfig.json +34 -0
  742. package/codeyam-cli/templates/prompts/conversation-guidance.txt +44 -0
  743. package/codeyam-cli/templates/prompts/conversation-prompt.txt +28 -0
  744. package/codeyam-cli/templates/prompts/interruption-prompt.txt +31 -0
  745. package/codeyam-cli/templates/prompts/stale-rules-prompt.txt +24 -0
  746. package/codeyam-cli/templates/rule-notification-hook.py +44 -17
  747. package/codeyam-cli/templates/rule-reflection-hook.py +25 -5
  748. package/codeyam-cli/templates/rules-instructions.md +34 -88
  749. package/codeyam-cli/templates/seed-adapters/supabase.ts +475 -0
  750. package/codeyam-cli/templates/{codeyam:debug.md → skills/codeyam-debug/SKILL.md} +1 -1
  751. package/codeyam-cli/templates/skills/codeyam-dev-mode/SKILL.md +237 -0
  752. package/codeyam-cli/templates/skills/codeyam-editor/SKILL.md +244 -0
  753. package/codeyam-cli/templates/{codeyam:memory.md → skills/codeyam-memory/SKILL.md} +222 -3
  754. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/deprecated-prompt.md +100 -0
  755. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/detect-deprecated-patterns.mjs +139 -0
  756. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/find-exports.mjs +52 -0
  757. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/misleading-api-prompt.md +117 -0
  758. package/codeyam-cli/templates/skills/codeyam-memory/scripts/lib/read-json-field.mjs +61 -0
  759. package/codeyam-cli/templates/skills/codeyam-memory/scripts/lib/ripgrep-fallback.mjs +155 -0
  760. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/analyze-prompt.md +46 -0
  761. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/cleanup.mjs +13 -0
  762. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/filter-session.mjs +95 -0
  763. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/preprocess.mjs +160 -0
  764. package/codeyam-cli/templates/{codeyam:new-rule.md → skills/codeyam-new-rule/SKILL.md} +1 -3
  765. package/codeyam-cli/templates/{codeyam:setup.md → skills/codeyam-setup/SKILL.md} +1 -1
  766. package/codeyam-cli/templates/{codeyam:sim.md → skills/codeyam-sim/SKILL.md} +1 -1
  767. package/codeyam-cli/templates/{codeyam:test.md → skills/codeyam-test/SKILL.md} +1 -1
  768. package/codeyam-cli/templates/{codeyam:verify.md → skills/codeyam-verify/SKILL.md} +1 -1
  769. package/package.json +28 -20
  770. package/packages/ai/index.js +1 -1
  771. package/packages/ai/index.js.map +1 -1
  772. package/packages/ai/src/lib/analyzeScope.js +14 -0
  773. package/packages/ai/src/lib/analyzeScope.js.map +1 -1
  774. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js +22 -4
  775. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js.map +1 -1
  776. package/packages/ai/src/lib/astScopes/methodSemantics.js +99 -0
  777. package/packages/ai/src/lib/astScopes/methodSemantics.js.map +1 -1
  778. package/packages/ai/src/lib/astScopes/nodeToSource.js +16 -0
  779. package/packages/ai/src/lib/astScopes/nodeToSource.js.map +1 -1
  780. package/packages/ai/src/lib/astScopes/paths.js +12 -3
  781. package/packages/ai/src/lib/astScopes/paths.js.map +1 -1
  782. package/packages/ai/src/lib/completionCall.js +10 -7
  783. package/packages/ai/src/lib/completionCall.js.map +1 -1
  784. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +261 -13
  785. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
  786. package/packages/ai/src/lib/dataStructure/equivalencyManagers/ParentScopeManager.js +9 -2
  787. package/packages/ai/src/lib/dataStructure/equivalencyManagers/ParentScopeManager.js.map +1 -1
  788. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js +14 -4
  789. package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js.map +1 -1
  790. package/packages/ai/src/lib/dataStructure/helpers/coercePrimitivesToArraysBySchema.js +54 -0
  791. package/packages/ai/src/lib/dataStructure/helpers/coercePrimitivesToArraysBySchema.js.map +1 -0
  792. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js +24 -16
  793. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js.map +1 -1
  794. package/packages/ai/src/lib/dataStructure/helpers/stripNullableMarkers.js +34 -0
  795. package/packages/ai/src/lib/dataStructure/helpers/stripNullableMarkers.js.map +1 -0
  796. package/packages/ai/src/lib/dataStructureChunking.js +9 -5
  797. package/packages/ai/src/lib/dataStructureChunking.js.map +1 -1
  798. package/packages/ai/src/lib/generateEntityScenarioData.js +57 -2
  799. package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
  800. package/packages/ai/src/lib/generateExecutionFlows.js +81 -11
  801. package/packages/ai/src/lib/generateExecutionFlows.js.map +1 -1
  802. package/packages/analyze/index.js +1 -1
  803. package/packages/analyze/index.js.map +1 -1
  804. package/packages/analyze/src/lib/ProjectAnalyzer.js +13 -4
  805. package/packages/analyze/src/lib/ProjectAnalyzer.js.map +1 -1
  806. package/packages/analyze/src/lib/asts/index.js +4 -2
  807. package/packages/analyze/src/lib/asts/index.js.map +1 -1
  808. package/packages/analyze/src/lib/asts/nodes/getNodeType.js +1 -0
  809. package/packages/analyze/src/lib/asts/nodes/getNodeType.js.map +1 -1
  810. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +27 -3
  811. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
  812. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +14 -27
  813. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
  814. package/packages/analyze/src/lib/files/analyze/dependencyResolver.js +0 -5
  815. package/packages/analyze/src/lib/files/analyze/dependencyResolver.js.map +1 -1
  816. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js +12 -2
  817. package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js.map +1 -1
  818. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js +9 -7
  819. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js.map +1 -1
  820. package/packages/analyze/src/lib/files/analyze/trackEntityCircularDependencies.js +14 -0
  821. package/packages/analyze/src/lib/files/analyze/trackEntityCircularDependencies.js.map +1 -1
  822. package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js +44 -11
  823. package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js.map +1 -1
  824. package/packages/analyze/src/lib/files/analyzeChange.js +1 -0
  825. package/packages/analyze/src/lib/files/analyzeChange.js.map +1 -1
  826. package/packages/analyze/src/lib/files/analyzeInitial.js +1 -0
  827. package/packages/analyze/src/lib/files/analyzeInitial.js.map +1 -1
  828. package/packages/analyze/src/lib/files/analyzeNextRoute.js +5 -1
  829. package/packages/analyze/src/lib/files/analyzeNextRoute.js.map +1 -1
  830. package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js +54 -27
  831. package/packages/analyze/src/lib/files/scenarios/TransformationTracer.js.map +1 -1
  832. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js +42 -13
  833. package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js.map +1 -1
  834. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +185 -28
  835. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
  836. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js +0 -40
  837. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js.map +1 -1
  838. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +1388 -1143
  839. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
  840. package/packages/database/index.js +1 -0
  841. package/packages/database/index.js.map +1 -1
  842. package/packages/database/src/lib/kysely/db.js +5 -0
  843. package/packages/database/src/lib/kysely/db.js.map +1 -1
  844. package/packages/database/src/lib/kysely/tables/editorScenariosTable.js +149 -0
  845. package/packages/database/src/lib/kysely/tables/editorScenariosTable.js.map +1 -0
  846. package/packages/database/src/lib/loadAnalysis.js +7 -1
  847. package/packages/database/src/lib/loadAnalysis.js.map +1 -1
  848. package/packages/database/src/lib/loadCommits.js +23 -13
  849. package/packages/database/src/lib/loadCommits.js.map +1 -1
  850. package/packages/database/src/lib/loadEntities.js +0 -6
  851. package/packages/database/src/lib/loadEntities.js.map +1 -1
  852. package/packages/database/src/lib/loadEntity.js +5 -5
  853. package/packages/database/src/lib/loadEntity.js.map +1 -1
  854. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js +1 -4
  855. package/packages/database/src/lib/loadReadyToBeCapturedAnalyses.js.map +1 -1
  856. package/packages/database/src/lib/updateCommitMetadata.js +76 -90
  857. package/packages/database/src/lib/updateCommitMetadata.js.map +1 -1
  858. package/packages/database/src/lib/updateFreshAnalysisStatus.js +41 -30
  859. package/packages/database/src/lib/updateFreshAnalysisStatus.js.map +1 -1
  860. package/packages/database/src/lib/updateFreshAnalysisStatusWithScenarios.js +68 -57
  861. package/packages/database/src/lib/updateFreshAnalysisStatusWithScenarios.js.map +1 -1
  862. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js +29 -1
  863. package/packages/generate/src/lib/componentScenarioPage/generateScenarioClientWrapper.js.map +1 -1
  864. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js +33 -5
  865. package/packages/generate/src/lib/componentScenarioPage/getIFrameMessageListenerCode.js.map +1 -1
  866. package/packages/types/src/enums/ProjectFramework.js +2 -0
  867. package/packages/types/src/enums/ProjectFramework.js.map +1 -1
  868. package/packages/utils/src/lib/fs/rsyncCopy.js +120 -4
  869. package/packages/utils/src/lib/fs/rsyncCopy.js.map +1 -1
  870. package/scripts/npm-post-install.cjs +34 -0
  871. package/codeyam-cli/src/commands/detect-universal-mocks.js +0 -120
  872. package/codeyam-cli/src/commands/detect-universal-mocks.js.map +0 -1
  873. package/codeyam-cli/src/commands/list.js +0 -31
  874. package/codeyam-cli/src/commands/list.js.map +0 -1
  875. package/codeyam-cli/src/commands/webapp-info.js +0 -146
  876. package/codeyam-cli/src/commands/webapp-info.js.map +0 -1
  877. package/codeyam-cli/src/utils/universal-mocks.js +0 -152
  878. package/codeyam-cli/src/utils/universal-mocks.js.map +0 -1
  879. package/codeyam-cli/src/webserver/build/client/assets/CopyButton-CA3JxPb7.js +0 -1
  880. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeBadge-B5ctlSYt.js +0 -1
  881. package/codeyam-cli/src/webserver/build/client/assets/InlineSpinner-ClaLpuOo.js +0 -34
  882. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-BDhPilK7.js +0 -25
  883. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-VeqEBv9v.js +0 -3
  884. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-Gq3Ocjo6.js +0 -1
  885. package/codeyam-cli/src/webserver/build/client/assets/TruncatedFilePath-CiwXDxLh.js +0 -1
  886. package/codeyam-cli/src/webserver/build/client/assets/agent-transcripts-CN61MOMa.js +0 -11
  887. package/codeyam-cli/src/webserver/build/client/assets/chunk-JZWAC4HX-JE9ZIoBl.js +0 -51
  888. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-Ca9fAY46.js +0 -21
  889. package/codeyam-cli/src/webserver/build/client/assets/cy-logo-cli-DcX-ZS3p.js +0 -1
  890. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-C5lqplTC.js +0 -1
  891. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-CBoafmVs.js +0 -6
  892. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-DGgZjdFg.js +0 -6
  893. package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-DCPhhSMo.js +0 -1
  894. package/codeyam-cli/src/webserver/build/client/assets/files-0N0YJQv7.js +0 -1
  895. package/codeyam-cli/src/webserver/build/client/assets/git-DXnyr8uP.js +0 -15
  896. package/codeyam-cli/src/webserver/build/client/assets/globals-CuCsBc3b.css +0 -1
  897. package/codeyam-cli/src/webserver/build/client/assets/labs-CB3MGcys.js +0 -1
  898. package/codeyam-cli/src/webserver/build/client/assets/manifest-de6ccaf4.js +0 -1
  899. package/codeyam-cli/src/webserver/build/client/assets/memory-DCA-kLYt.js +0 -81
  900. package/codeyam-cli/src/webserver/build/client/assets/root-F7e6dvys.js +0 -62
  901. package/codeyam-cli/src/webserver/build/client/assets/settings-BejnUJ6R.js +0 -1
  902. package/codeyam-cli/src/webserver/build/client/assets/simulations-CPoAg7Zo.js +0 -1
  903. package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-DNwUduNu.js +0 -1
  904. package/codeyam-cli/src/webserver/build/client/assets/useLastLogLine-COky1GVF.js +0 -2
  905. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-CpZgwliL.js +0 -1
  906. package/codeyam-cli/src/webserver/build/client/assets/useToast-Bv9JFvUO.js +0 -1
  907. package/codeyam-cli/src/webserver/build/server/assets/index-CFKHuovO.js +0 -1
  908. package/codeyam-cli/src/webserver/build/server/assets/server-build-BQe9Dh4p.js +0 -260
  909. package/codeyam-cli/templates/codeyam-stop-hook.sh +0 -284
  910. package/scripts/finalize-analyzer.cjs +0 -13
  911. /package/codeyam-cli/src/webserver/build/client/assets/{api.labs-survey-l0sNRNKZ.js → api.dev-mode-events-l0sNRNKZ.js} +0 -0
@@ -25,6 +25,34 @@ function getTypeParameter(functionName) {
25
25
  }
26
26
  return null;
27
27
  }
28
+ /**
29
+ * Check if a schema path contains a Set/Map collection method call.
30
+ * Paths like `.has(articleId)`, `.delete(articleId)`, `.add(articleId)` represent
31
+ * membership checks on Sets/Maps, not meaningful data flow for schema generation.
32
+ * These create massive combinatorial explosions when every filter field (filterRatings,
33
+ * filterPublications, filterAuthors, etc.) × every method (has, delete, add) gets
34
+ * tracked as a separate equivalency.
35
+ */
36
+ const COLLECTION_METHOD_PATTERN = /\.(?:has|delete|add|clear|get|set)\(/;
37
+ function isCollectionMethodPath(path) {
38
+ return COLLECTION_METHOD_PATTERN.test(path);
39
+ }
40
+ /**
41
+ * Check if a path contains an inline object literal inside a function call argument.
42
+ * e.g., setUndoEntry({ label: '...', undo: () => {} }) has '{' inside '(' ')'.
43
+ * These paths are call-site snapshots where the source code text was captured
44
+ * as the path. They don't represent schema structure and are very expensive to
45
+ * parse (avg 319 chars). They account for ~55% of equivalencies in complex entities.
46
+ */
47
+ const INLINE_OBJECT_ARG_PATTERN = /\([^)]*\{[^}]*:/;
48
+ function hasInlineObjectArg(path) {
49
+ // Match function calls containing object literals with key-value pairs.
50
+ // Pattern: open paren, then { with a : inside before closing }.
51
+ // e.g., setUndoEntry({ label: '...' }) matches
52
+ // e.g., find(item) does NOT match
53
+ // e.g., fn({a:1, b:2}) matches
54
+ return INLINE_OBJECT_ARG_PATTERN.test(path);
55
+ }
28
56
  // Primitive types that should not have child paths
29
57
  const PRIMITIVE_TYPES = new Set([
30
58
  'number',
@@ -35,6 +63,7 @@ const PRIMITIVE_TYPES = new Set([
35
63
  ]);
36
64
  // Check if a type string represents a primitive type
37
65
  // Handles union types like "string | undefined" or "number | null"
66
+ // Also handles string literal unions like "'suggestion' | 'warning' | 'tip'"
38
67
  function isPrimitiveType(typeStr) {
39
68
  if (PRIMITIVE_TYPES.has(typeStr)) {
40
69
  return true;
@@ -42,9 +71,12 @@ function isPrimitiveType(typeStr) {
42
71
  // Check union types - if ALL parts of the union are primitives, it's primitive
43
72
  // e.g., "string | undefined" -> ["string", "undefined"] -> both are primitive -> true
44
73
  // e.g., "object | null" -> ["object", "null"] -> object is not primitive -> false
74
+ // e.g., "'suggestion' | 'warning'" -> string literal union -> true
45
75
  if (typeStr.includes('|')) {
46
76
  const parts = typeStr.split('|').map((p) => p.trim());
47
- return parts.every((part) => PRIMITIVE_TYPES.has(part));
77
+ return parts.every((part) => PRIMITIVE_TYPES.has(part) ||
78
+ // String literal values like 'suggestion', 'warning' are primitives
79
+ (part.startsWith("'") && part.endsWith("'")));
48
80
  }
49
81
  return false;
50
82
  }
@@ -83,9 +115,19 @@ function pathPartMatches(pathPart, schemaPathPart) {
83
115
  }
84
116
  function bestValueFromOptions(options) {
85
117
  options = options.filter(Boolean);
86
- const known = options.find((o) => !o.includes('unknown'));
87
- if (known) {
88
- return known;
118
+ const known = options.filter((o) => !o.includes('unknown'));
119
+ if (known.length > 0) {
120
+ // Among known values, prefer string literal unions over bare primitives.
121
+ // e.g., "'draft' | 'inProgress' | 'paused' | 'completed'" is more specific than "string".
122
+ // This handles cases where a dependency schema has a bare type like "string" but the
123
+ // child entity's analysis has the actual literal union from TypeScript type resolution.
124
+ if (known.length > 1 && known.some((o) => PRIMITIVE_TYPES.has(o))) {
125
+ const literalUnion = known.find((o) => !PRIMITIVE_TYPES.has(o) && o.includes("'"));
126
+ if (literalUnion) {
127
+ return literalUnion;
128
+ }
129
+ }
130
+ return known[0];
89
131
  }
90
132
  const notUnknown = options.find((o) => o !== 'unknown');
91
133
  if (notUnknown) {
@@ -93,7 +135,31 @@ function bestValueFromOptions(options) {
93
135
  }
94
136
  return options[0] ?? 'unknown';
95
137
  }
96
- export default function mergeInDependentDataStructure({ importedExports, dependentAnalyses, rootScopeName, dataStructure, dependencySchemas, }) {
138
+ /** Timeout (ms) for the merge operation. Throws DataStructureTimeoutError if exceeded.
139
+ * All successful merges complete in <300ms. Anything exceeding 2s is pathological. */
140
+ const MERGE_TIMEOUT_MS = 2000;
141
+ /** Cap for schema size during postfix application and dep copy.
142
+ * Successful merges produce <3K ret keys. Beyond 5K, further entries
143
+ * are cross-products of unrelated equivalencies — noise, not signal. */
144
+ const SCHEMA_KEY_CAP = 5000;
145
+ export class DataStructureTimeoutError extends Error {
146
+ constructor(entityName, elapsedMs) {
147
+ super(`Data structure merge timed out for ${entityName} after ${Math.round(elapsedMs / 1000)}s (limit: ${MERGE_TIMEOUT_MS / 1000}s)`);
148
+ this.name = 'DataStructureTimeoutError';
149
+ }
150
+ }
151
+ export default function mergeInDependentDataStructure({ importedExports, dependentAnalyses, rootScopeName, dataStructure, dependencySchemas, timeoutMs = MERGE_TIMEOUT_MS, }) {
152
+ const mergeStartTime = Date.now();
153
+ const mergeDeadline = timeoutMs > 0 ? mergeStartTime + timeoutMs : 0;
154
+ /** Call in hot loops. Throws DataStructureTimeoutError if deadline exceeded.
155
+ * Date.now() is ~20ns — negligible vs the ms-scale string ops in each iteration. */
156
+ const checkDeadline = () => {
157
+ if (!mergeDeadline)
158
+ return;
159
+ if (Date.now() > mergeDeadline) {
160
+ throw new DataStructureTimeoutError(rootScopeName, Date.now() - mergeStartTime);
161
+ }
162
+ };
97
163
  const mergedDataStructure = {
98
164
  signatureSchema: { ...(dataStructure.signatureSchema ?? {}) },
99
165
  returnValueSchema: { ...(dataStructure.returnValueSchema ?? {}) },
@@ -102,505 +168,591 @@ export default function mergeInDependentDataStructure({ importedExports, depende
102
168
  dependencySchemas: {},
103
169
  environmentVariables: [...(dataStructure.environmentVariables || [])],
104
170
  };
105
- // Build a set of functions that have multiple DIFFERENT type parameters.
106
- // For these functions, we must NOT normalize paths to avoid merging different schemas.
107
- // e.g., if we have both useFetcher<{ data: UserData }>() and useFetcher<{ data: ConfigData }>(),
108
- // they must stay separate and not both become 'returnValue'.
109
- const functionsWithMultipleTypeParams = new Set();
110
- const typeParamsByFunction = {};
111
- // Helper to scan a schema for type parameters
112
- const scanSchemaForTypeParams = (schema) => {
113
- for (const schemaPath of Object.keys(schema ?? {})) {
114
- const parts = splitOutsideParenthesesAndArrays(schemaPath);
115
- if (parts.length > 0) {
116
- const firstPart = parts[0];
117
- const typeParam = getTypeParameter(firstPart);
118
- if (typeParam) {
119
- const baseName = cleanFunctionName(firstPart);
120
- typeParamsByFunction[baseName] || (typeParamsByFunction[baseName] = new Set());
121
- typeParamsByFunction[baseName].add(typeParam);
122
- if (typeParamsByFunction[baseName].size > 1) {
123
- functionsWithMultipleTypeParams.add(baseName);
171
+ try {
172
+ // Build a set of functions that have multiple DIFFERENT type parameters.
173
+ // For these functions, we must NOT normalize paths to avoid merging different schemas.
174
+ // e.g., if we have both useFetcher<{ data: UserData }>() and useFetcher<{ data: ConfigData }>(),
175
+ // they must stay separate and not both become 'returnValue'.
176
+ const functionsWithMultipleTypeParams = new Set();
177
+ const typeParamsByFunction = {};
178
+ // Helper to scan a schema for type parameters
179
+ const scanSchemaForTypeParams = (schema) => {
180
+ for (const schemaPath of Object.keys(schema ?? {})) {
181
+ const parts = splitOutsideParenthesesAndArrays(schemaPath);
182
+ if (parts.length > 0) {
183
+ const firstPart = parts[0];
184
+ const typeParam = getTypeParameter(firstPart);
185
+ if (typeParam) {
186
+ const baseName = cleanFunctionName(firstPart);
187
+ typeParamsByFunction[baseName] || (typeParamsByFunction[baseName] = new Set());
188
+ typeParamsByFunction[baseName].add(typeParam);
189
+ if (typeParamsByFunction[baseName].size > 1) {
190
+ functionsWithMultipleTypeParams.add(baseName);
191
+ }
124
192
  }
125
193
  }
126
194
  }
195
+ };
196
+ // Scan the root entity's schema
197
+ scanSchemaForTypeParams(dataStructure.returnValueSchema);
198
+ // Also scan all dependency schemas for type parameters
199
+ for (const filePath of Object.keys(dependencySchemas ?? {})) {
200
+ for (const name of Object.keys(dependencySchemas[filePath] ?? {})) {
201
+ scanSchemaForTypeParams(dependencySchemas[filePath][name]?.returnValueSchema);
202
+ }
127
203
  }
128
- };
129
- // Scan the root entity's schema
130
- scanSchemaForTypeParams(dataStructure.returnValueSchema);
131
- // Also scan all dependency schemas for type parameters
132
- for (const filePath of Object.keys(dependencySchemas ?? {})) {
133
- for (const name of Object.keys(dependencySchemas[filePath] ?? {})) {
134
- scanSchemaForTypeParams(dependencySchemas[filePath][name]?.returnValueSchema);
135
- }
136
- }
137
- let equivalentSchemaPaths = [];
138
- // Pre-build a lookup map from cleaned function name to dependency for O(1) lookups.
139
- // This avoids O(n) linear search in findRelevantDependency which was causing O(n²) performance.
140
- const dependencyByCleanedName = new Map();
141
- for (const dep of importedExports) {
142
- const cleanedName = cleanFunctionName(dep.name);
143
- if (!dependencyByCleanedName.has(cleanedName)) {
144
- dependencyByCleanedName.set(cleanedName, dep);
145
- }
146
- }
147
- const findRelevantDependency = (functionName) => {
148
- return dependencyByCleanedName.get(cleanFunctionName(functionName));
149
- };
150
- const findRelevantDependentDataStructure = (functionName) => {
151
- const dependency = findRelevantDependency(functionName);
152
- if (!dependency)
153
- return;
154
- return dependencySchemas?.[dependency.filePath]?.[dependency.name];
155
- };
156
- const findRelevantDependentAnalysisDataStructure = (functionName) => {
157
- const dependency = findRelevantDependency(functionName);
158
- if (!dependency)
159
- return;
160
- const dependentAnalysis = dependentAnalyses[dependency.filePath]?.[dependency.name];
161
- if (!dependentAnalysis?.metadata?.mergedDataStructure) {
162
- return;
163
- }
164
- return dependentAnalysis.metadata.mergedDataStructure;
165
- };
166
- const findOrCreateDependentSchemas = (dependency) => {
167
- var _a, _b;
168
- const { filePath, name } = dependency;
169
- (_a = mergedDataStructure.dependencySchemas)[filePath] || (_a[filePath] = {});
170
- (_b = mergedDataStructure.dependencySchemas[filePath])[name] || (_b[name] = {
171
- signatureSchema: {},
172
- returnValueSchema: {},
173
- });
174
- return mergedDataStructure.dependencySchemas[filePath][name];
175
- };
176
- const cleanSchema = (schema, context) => {
177
- transformationTracer.traceSchemaTransform(rootScopeName, 'cleanKnownObjectFunctionsFromMapping', schema, cleanKnownObjectFunctionsFromMapping, context);
178
- };
179
- const translatePath = (path, dependencyName) => {
180
- if (path.startsWith(dependencyName)) {
181
- const pathParts = splitOutsideParenthesesAndArrays(path);
182
- if (pathParts.length > 1) {
183
- if (pathParts[1].startsWith('functionCallReturnValue')) {
184
- // Check if this function has multiple DIFFERENT type parameters.
185
- // If so, DON'T normalize to returnValue - keep the full path to avoid
186
- // merging different type-parameterized variants together.
187
- // e.g., useFetcher<{ data: UserData }>().functionCallReturnValue.data
188
- // should NOT be merged with useFetcher<{ data: ConfigData }>().functionCallReturnValue.data
189
- const baseName = cleanFunctionName(pathParts[0]);
190
- if (functionsWithMultipleTypeParams.has(baseName)) {
191
- return path; // Keep the original path with type parameters
192
- }
193
- // functionCallReturnValue immediately follows - normalize to returnValue
194
- // e.g., useAuth().functionCallReturnValue.user -> returnValue.user
195
- return joinParenthesesAndArrays([
196
- 'returnValue',
197
- ...pathParts.slice(2),
198
- ]);
199
- }
200
- else if (pathParts[0].endsWith(')') &&
201
- pathParts[1].startsWith('signature[')) {
202
- // Hook-style with signature access (e.g., BranchChangesTab().signature[0]...)
203
- // Strip the function name for signature equivalency matching
204
- return joinParenthesesAndArrays(pathParts.slice(1));
205
- }
206
- // For all other cases (object-style APIs like getSupabase().auth and
207
- // direct object references like supabase.from), preserve the path as-is.
208
- // The prefix must be kept for proper schema lookups in constructMockCode
209
- // and gatherDataForMocks.
204
+ let equivalentSchemaPaths = [];
205
+ // O(1) index for findOrCreateEquivalentSchemaPathsEntry.
206
+ // Maps "(rootPath)::(normalizedFuncName)" → the entry containing that root.
207
+ // This replaces the O(E) linear search that was causing O(E²) gather performance.
208
+ const espIndex = new Map();
209
+ const espIndexKey = (path, functionName) => {
210
+ const normalized = cleanFunctionName(functionName);
211
+ const funcKey = normalized === rootScopeName ? '__self__' : normalized || '__self__';
212
+ return `${path}::${funcKey}`;
213
+ };
214
+ const updateEspIndex = (entry) => {
215
+ for (const root of entry.equivalentRoots) {
216
+ const funcName = root.function?.name ?? rootScopeName;
217
+ espIndex.set(espIndexKey(root.schemaRootPath, funcName), entry);
218
+ }
219
+ };
220
+ // Pre-build a lookup map from cleaned function name to dependency for O(1) lookups.
221
+ // This avoids O(n) linear search in findRelevantDependency which was causing O(n²) performance.
222
+ const dependencyByCleanedName = new Map();
223
+ for (const dep of importedExports) {
224
+ const cleanedName = cleanFunctionName(dep.name);
225
+ if (!dependencyByCleanedName.has(cleanedName)) {
226
+ dependencyByCleanedName.set(cleanedName, dep);
210
227
  }
211
228
  }
212
- return path;
213
- };
214
- const gatherAllEquivalentSchemaPaths = (functionName, sourceAndUsageEquivalencies, dataStructure) => {
215
- if (!sourceAndUsageEquivalencies)
216
- return;
217
- const findOrCreateEquivalentSchemaPathsEntry = (allPaths) => {
218
- const equivalentRoots = allPaths
219
- .filter((p) => p.functionName === rootScopeName ||
220
- !!findRelevantDependency(p.functionName))
221
- .map((p) => ({
222
- schemaRootPath: p.path,
223
- function: p.functionName === rootScopeName
224
- ? undefined
225
- : findRelevantDependency(p.functionName),
226
- }));
227
- let equivalentSchemaPathsEntry;
228
- // Collect the signature indices from the new roots we want to add
229
- const newRootSignatureIndices = new Set();
230
- for (const root of equivalentRoots) {
231
- const idx = extractSignatureIndex(root.schemaRootPath);
232
- if (idx !== undefined) {
233
- newRootSignatureIndices.add(idx);
234
- }
229
+ const findRelevantDependency = (functionName) => {
230
+ return dependencyByCleanedName.get(cleanFunctionName(functionName));
231
+ };
232
+ const findRelevantDependentDataStructure = (functionName) => {
233
+ const dependency = findRelevantDependency(functionName);
234
+ if (!dependency)
235
+ return;
236
+ return dependencySchemas?.[dependency.filePath]?.[dependency.name];
237
+ };
238
+ const findRelevantDependentAnalysisDataStructure = (functionName) => {
239
+ const dependency = findRelevantDependency(functionName);
240
+ if (!dependency)
241
+ return;
242
+ const dependentAnalysis = dependentAnalyses[dependency.filePath]?.[dependency.name];
243
+ if (!dependentAnalysis?.metadata?.mergedDataStructure) {
244
+ return;
235
245
  }
236
- for (const pathInfo of allPaths) {
237
- if (!equivalentSchemaPathsEntry) {
238
- equivalentSchemaPathsEntry = equivalentSchemaPaths.find((esp) => {
239
- // First check: does this entry have a matching root?
240
- const hasMatchingRoot = esp.equivalentRoots.some((er) => er.schemaRootPath === pathInfo.path &&
241
- (er.function?.name ===
242
- cleanFunctionName(pathInfo.functionName) ||
243
- (!er.function &&
244
- cleanFunctionName(pathInfo.functionName) ===
245
- rootScopeName)));
246
- if (!hasMatchingRoot)
247
- return false;
248
- // Second check: would adding our new roots create a signature index conflict?
249
- // An entry should NOT contain roots with different signature indices from the same function.
250
- if (newRootSignatureIndices.size > 0) {
251
- // Get all signature indices in the existing entry (grouped by function)
252
- const existingIndicesByFunction = new Map();
253
- for (const er of esp.equivalentRoots) {
254
- const funcKey = er.function
255
- ? `${er.function.name}::${er.function.filePath}`
256
- : '__self__';
257
- const idx = extractSignatureIndex(er.schemaRootPath);
258
- if (idx !== undefined) {
259
- if (!existingIndicesByFunction.has(funcKey)) {
260
- existingIndicesByFunction.set(funcKey, new Set());
261
- }
262
- existingIndicesByFunction.get(funcKey).add(idx);
263
- }
264
- }
265
- // Check if adding our new roots would create a conflict
266
- for (const newRoot of equivalentRoots) {
267
- const funcKey = newRoot.function
268
- ? `${newRoot.function.name}::${newRoot.function.filePath}`
269
- : '__self__';
270
- const newIdx = extractSignatureIndex(newRoot.schemaRootPath);
271
- if (newIdx !== undefined) {
272
- const existingIndices = existingIndicesByFunction.get(funcKey);
273
- if (existingIndices && existingIndices.size > 0) {
274
- // If this function already has signature indices, check for conflict
275
- if (!existingIndices.has(newIdx)) {
276
- // Conflict: entry has indices like [1] but we want to add [2]
277
- return false;
278
- }
279
- }
280
- }
281
- }
246
+ return dependentAnalysis.metadata.mergedDataStructure;
247
+ };
248
+ const findOrCreateDependentSchemas = (dependency) => {
249
+ var _a, _b;
250
+ const { filePath, name } = dependency;
251
+ (_a = mergedDataStructure.dependencySchemas)[filePath] || (_a[filePath] = {});
252
+ (_b = mergedDataStructure.dependencySchemas[filePath])[name] || (_b[name] = {
253
+ signatureSchema: {},
254
+ returnValueSchema: {},
255
+ });
256
+ return mergedDataStructure.dependencySchemas[filePath][name];
257
+ };
258
+ const cleanSchema = (schema, context) => {
259
+ transformationTracer.traceSchemaTransform(rootScopeName, 'cleanKnownObjectFunctionsFromMapping', schema, cleanKnownObjectFunctionsFromMapping, context);
260
+ };
261
+ // Cache translatePath results the same path is often translated multiple times
262
+ // (once per equivalency entry that references it). Avoids redundant
263
+ // splitOutsideParenthesesAndArrays calls on long paths.
264
+ const translatePathCache = new Map();
265
+ const translatePath = (path, dependencyName) => {
266
+ const cacheKey = `${dependencyName}\0${path}`;
267
+ const cached = translatePathCache.get(cacheKey);
268
+ if (cached !== undefined)
269
+ return cached;
270
+ let result = path;
271
+ if (path.startsWith(dependencyName)) {
272
+ const pathParts = splitOutsideParenthesesAndArrays(path);
273
+ if (pathParts.length > 1) {
274
+ if (pathParts[1].startsWith('functionCallReturnValue')) {
275
+ // Check if this function has multiple DIFFERENT type parameters.
276
+ // If so, DON'T normalize to returnValue - keep the full path to avoid
277
+ // merging different type-parameterized variants together.
278
+ const baseName = cleanFunctionName(pathParts[0]);
279
+ if (!functionsWithMultipleTypeParams.has(baseName)) {
280
+ // functionCallReturnValue immediately follows - normalize to returnValue
281
+ result = joinParenthesesAndArrays([
282
+ 'returnValue',
283
+ ...pathParts.slice(2),
284
+ ]);
282
285
  }
283
- return true;
284
- });
286
+ }
287
+ else if (pathParts[0].endsWith(')') &&
288
+ pathParts[1].startsWith('signature[')) {
289
+ // Hook-style with signature access
290
+ result = joinParenthesesAndArrays(pathParts.slice(1));
291
+ }
285
292
  }
286
293
  }
287
- if (!equivalentSchemaPathsEntry) {
288
- // Before creating a new entry, filter out roots that have conflicting
289
- // signature indices from the same function. An entry should never contain
290
- // roots with different signature indices from the same function.
291
- // This prevents the bug where signature[1], signature[2], signature[4]
292
- // all get merged together due to incorrect sourceEquivalencies.
293
- let filteredRoots = equivalentRoots;
294
- if (newRootSignatureIndices.size > 1) {
295
- // There are multiple signature indices - we need to filter to keep only
296
- // one consistent set. We'll keep the roots that match the PRIMARY index
297
- // (the first signature index we encounter from self, or the lowest index).
298
- // First, determine the primary index - prefer the self root's index
299
- let primaryIndex;
300
- for (const root of equivalentRoots) {
301
- if (!root.function) {
302
- // This is a self root
303
- const idx = extractSignatureIndex(root.schemaRootPath);
304
- if (idx !== undefined) {
305
- primaryIndex = idx;
306
- break;
307
- }
294
+ translatePathCache.set(cacheKey, result);
295
+ return result;
296
+ };
297
+ const gatherAllEquivalentSchemaPaths = (functionName, sourceAndUsageEquivalencies, dataStructure) => {
298
+ checkDeadline();
299
+ if (!sourceAndUsageEquivalencies)
300
+ return;
301
+ const normalizedSchemaCache = new Map();
302
+ const getSchemaIndex = (schema) => {
303
+ if (!schema)
304
+ return { byFirstPart: new Map() };
305
+ const cached = normalizedSchemaCache.get(schema);
306
+ if (cached)
307
+ return cached;
308
+ const byFirstPart = new Map();
309
+ for (const path in schema) {
310
+ checkDeadline();
311
+ let parts = splitOutsideParenthesesAndArrays(path);
312
+ if (parts[0].startsWith(functionName)) {
313
+ const baseName = cleanFunctionName(parts[0]);
314
+ if (!functionsWithMultipleTypeParams.has(baseName)) {
315
+ parts =
316
+ parts[1] === 'functionCallReturnValue'
317
+ ? ['returnValue', ...parts.slice(2)]
318
+ : parts.slice(1);
308
319
  }
309
320
  }
310
- // If no self root has a signature index, use the lowest index
311
- if (primaryIndex === undefined) {
312
- primaryIndex = Math.min(...newRootSignatureIndices);
321
+ const entry = { path, parts };
322
+ // Index by the base of the first part (before any function call args)
323
+ const firstPart = parts[0] ?? '';
324
+ const parenIdx = firstPart.indexOf('(');
325
+ const firstPartBase = parenIdx >= 0 ? firstPart.slice(0, parenIdx) : firstPart;
326
+ let bucket = byFirstPart.get(firstPartBase);
327
+ if (!bucket) {
328
+ bucket = [];
329
+ byFirstPart.set(firstPartBase, bucket);
313
330
  }
314
- // Filter roots: keep if no signature index OR signature index matches primary
315
- filteredRoots = equivalentRoots.filter((root) => {
316
- const idx = extractSignatureIndex(root.schemaRootPath);
317
- return idx === undefined || idx === primaryIndex;
318
- });
331
+ bucket.push(entry);
319
332
  }
320
- equivalentSchemaPathsEntry = {
321
- equivalentRoots: filteredRoots,
322
- equivalentPostfixes: {},
323
- };
324
- equivalentSchemaPaths.push(equivalentSchemaPathsEntry);
325
- }
326
- else {
327
- equivalentSchemaPathsEntry.equivalentRoots.push(...equivalentRoots);
328
- }
329
- // Deduplicate roots using a Set for O(n) instead of O(n²)
330
- const seenRoots = new Set();
331
- equivalentSchemaPathsEntry.equivalentRoots =
332
- equivalentSchemaPathsEntry.equivalentRoots.filter((er) => {
333
- const key = er.schemaRootPath + '::' + (er.function?.name ?? '');
334
- if (seenRoots.has(key))
335
- return false;
336
- seenRoots.add(key);
337
- return true;
338
- });
339
- return equivalentSchemaPathsEntry;
340
- };
341
- // Helper to extract function name from a path that starts with a function call.
342
- // e.g., 'ScenarioViewer().signature[0].scenario' -> 'ScenarioViewer'
343
- // Returns undefined if the path doesn't start with a function call or the function isn't a dependency.
344
- const extractFunctionNameFromPath = (path) => {
345
- const parts = splitOutsideParenthesesAndArrays(path);
346
- if (parts.length > 0 && parts[0].endsWith(')')) {
347
- // Extract the function name without the () suffix and type params
348
- const funcCallPart = parts[0];
349
- const funcName = cleanFunctionName(funcCallPart.replace(/\(\)$/, ''));
350
- // Check if this function is a dependency
351
- if (findRelevantDependency(funcName)) {
352
- return funcName;
333
+ const result = { byFirstPart };
334
+ normalizedSchemaCache.set(schema, result);
335
+ return result;
336
+ };
337
+ const findOrCreateEquivalentSchemaPathsEntry = (allPaths) => {
338
+ const equivalentRoots = allPaths
339
+ .filter((p) => p.functionName === rootScopeName ||
340
+ !!findRelevantDependency(p.functionName))
341
+ .map((p) => ({
342
+ schemaRootPath: p.path,
343
+ function: p.functionName === rootScopeName
344
+ ? undefined
345
+ : findRelevantDependency(p.functionName),
346
+ }));
347
+ let equivalentSchemaPathsEntry;
348
+ // Collect the signature indices from the new roots we want to add
349
+ const newRootSignatureIndices = new Set();
350
+ for (const root of equivalentRoots) {
351
+ const idx = extractSignatureIndex(root.schemaRootPath);
352
+ if (idx !== undefined) {
353
+ newRootSignatureIndices.add(idx);
354
+ }
353
355
  }
354
- }
355
- return undefined;
356
- };
357
- const allEquivalencies = [
358
- sourceAndUsageEquivalencies.usageEquivalencies,
359
- sourceAndUsageEquivalencies.sourceEquivalencies,
360
- ].filter(Boolean);
361
- for (const equivalencies of allEquivalencies) {
362
- const schemaPathEntries = Object.entries(equivalencies);
363
- for (const [schemaPath, usages] of schemaPathEntries) {
364
- // First, check if the raw schemaPath starts with a function call to a dependency.
365
- // If so, use that dependency name for translation (so translatePath can strip the prefix).
366
- const extractedFuncName = extractFunctionNameFromPath(schemaPath);
367
- const effectiveFunctionName = extractedFuncName || functionName;
368
- const translatedPath = translatePath(schemaPath, effectiveFunctionName);
369
- const allPaths = [
370
- { path: translatedPath, functionName: effectiveFunctionName },
371
- ...usages.map((u) => ({
372
- path: translatePath(u.schemaPath, u.scopeNodeName),
373
- functionName: u.scopeNodeName,
374
- })),
375
- ].filter((pathInfo) => !pathInfo.path.includes('.map('));
376
- // Fix 38: Derive base paths from property access paths.
377
- // When we have equivalent paths like:
378
- // Parent: signature[0].scenarios[].name
379
- // Child: signature[0].selectedScenario.name
380
- // We want to derive the base paths by finding the common suffix:
381
- // Common suffix: .name
382
- // Parent base: signature[0].scenarios[]
383
- // Child base: signature[0].selectedScenario
384
- // This allows the merge to find nested child schema fields under the base prop.
385
- // Find child signature paths (paths from child components)
386
- const childPaths = allPaths.filter((p) => p.functionName &&
387
- p.functionName !== rootScopeName &&
388
- p.functionName !== effectiveFunctionName);
389
- // Find parent paths (paths from this component)
390
- const parentPaths = allPaths.filter((p) => !p.functionName ||
391
- p.functionName === rootScopeName ||
392
- p.functionName === effectiveFunctionName);
393
- const derivedBasePaths = [];
394
- // For each child path, find its equivalent parent path and derive bases
395
- for (const childPathInfo of childPaths) {
396
- const childParts = splitOutsideParenthesesAndArrays(childPathInfo.path);
397
- // Look for a parent path that shares a common suffix with this child path
398
- for (const parentPathInfo of parentPaths) {
399
- const parentParts = splitOutsideParenthesesAndArrays(parentPathInfo.path);
400
- // Find the common suffix (from the end)
401
- let commonSuffixLength = 0;
402
- const minLen = Math.min(childParts.length, parentParts.length);
403
- for (let i = 1; i <= minLen; i++) {
404
- if (childParts[childParts.length - i] ===
405
- parentParts[parentParts.length - i]) {
406
- commonSuffixLength = i;
407
- }
408
- else {
409
- break;
356
+ // Use espIndex Map for O(1) lookup instead of O(E) linear search.
357
+ // Falls back to linear search only when Map hit has a signature index conflict.
358
+ for (const pathInfo of allPaths) {
359
+ checkDeadline();
360
+ if (equivalentSchemaPathsEntry)
361
+ break;
362
+ const candidate = espIndex.get(espIndexKey(pathInfo.path, pathInfo.functionName));
363
+ if (!candidate)
364
+ continue;
365
+ // Verify no signature index conflict with the candidate entry
366
+ if (newRootSignatureIndices.size > 0) {
367
+ const existingIndicesByFunction = new Map();
368
+ for (const er of candidate.equivalentRoots) {
369
+ const funcKey = er.function
370
+ ? `${er.function.name}::${er.function.filePath}`
371
+ : '__self__';
372
+ const idx = extractSignatureIndex(er.schemaRootPath);
373
+ if (idx !== undefined) {
374
+ if (!existingIndicesByFunction.has(funcKey)) {
375
+ existingIndicesByFunction.set(funcKey, new Set());
376
+ }
377
+ existingIndicesByFunction.get(funcKey).add(idx);
410
378
  }
411
379
  }
412
- // If there's a common suffix and both paths have more parts than the suffix
413
- if (commonSuffixLength > 0 &&
414
- childParts.length > commonSuffixLength &&
415
- parentParts.length > commonSuffixLength) {
416
- const childBaseParts = childParts.slice(0, childParts.length - commonSuffixLength);
417
- const parentBaseParts = parentParts.slice(0, parentParts.length - commonSuffixLength);
418
- // Only derive if BOTH paths look like signature paths.
419
- // This ensures we're handling JSX child-to-parent prop mappings,
420
- // not other complex equivalencies like function call returns.
421
- const isChildSignaturePath = childBaseParts[0]?.startsWith('signature[') ||
422
- (childBaseParts[0]?.endsWith(')') &&
423
- childBaseParts[1]?.startsWith('signature['));
424
- const isParentSignaturePath = parentBaseParts[0]?.startsWith('signature[');
425
- if (isChildSignaturePath && isParentSignaturePath) {
426
- const childBase = joinParenthesesAndArrays(childBaseParts);
427
- const parentBase = joinParenthesesAndArrays(parentBaseParts);
428
- // Only derive if:
429
- // 1. Parent has array iteration (e.g., scenarios[]) and child does NOT
430
- // 2. Bases are different
431
- // 3. Child base is NOT just "signature[N]" (too generic - every component has this)
432
- // We only want specific prop paths like "signature[0].selectedScenario"
433
- // This targets array-to-object mappings like scenarios[] -> selectedScenario
434
- const parentHasArrayIterator = parentBase.includes('[]');
435
- const childHasArrayIterator = childBase.includes('[]');
436
- // Skip if child base is just the generic signature marker (e.g., "signature[0]")
437
- const childBaseIsGenericSignature = /^signature\[\d+\]$/.test(childBase);
438
- if (childBase !== parentBase &&
439
- parentHasArrayIterator &&
440
- !childHasArrayIterator &&
441
- !childBaseIsGenericSignature) {
442
- // Add child base if not already present
443
- const childBaseExists = allPaths.some((p) => p.path === childBase) ||
444
- derivedBasePaths.some((p) => p.path === childBase);
445
- if (!childBaseExists) {
446
- derivedBasePaths.push({
447
- path: childBase,
448
- functionName: childPathInfo.functionName,
449
- });
450
- }
451
- // Add parent base if not already present
452
- const parentBaseExists = allPaths.some((p) => p.path === parentBase) ||
453
- derivedBasePaths.some((p) => p.path === parentBase);
454
- if (!parentBaseExists) {
455
- derivedBasePaths.push({
456
- path: parentBase,
457
- functionName: parentPathInfo.functionName,
458
- });
380
+ let hasConflict = false;
381
+ for (const newRoot of equivalentRoots) {
382
+ const funcKey = newRoot.function
383
+ ? `${newRoot.function.name}::${newRoot.function.filePath}`
384
+ : '__self__';
385
+ const newIdx = extractSignatureIndex(newRoot.schemaRootPath);
386
+ if (newIdx !== undefined) {
387
+ const existingIndices = existingIndicesByFunction.get(funcKey);
388
+ if (existingIndices && existingIndices.size > 0) {
389
+ if (!existingIndices.has(newIdx)) {
390
+ hasConflict = true;
391
+ break;
459
392
  }
460
393
  }
461
394
  }
462
395
  }
396
+ if (hasConflict)
397
+ continue;
463
398
  }
399
+ equivalentSchemaPathsEntry = candidate;
464
400
  }
465
- allPaths.push(...derivedBasePaths);
466
- const entry = findOrCreateEquivalentSchemaPathsEntry(allPaths);
467
- // Trace equivalency gathering - helps debug why paths may not be connected
468
- if (allPaths.length > 1) {
469
- transformationTracer.operation(rootScopeName, {
470
- operation: 'gatherEquivalency',
471
- stage: 'gathering',
472
- path: translatedPath,
473
- context: {
474
- sourceFunction: functionName,
475
- equivalentPaths: allPaths.map((p) => ({
476
- path: p.path,
477
- function: p.functionName,
478
- })),
479
- equivalentRoots: entry.equivalentRoots.map((r) => ({
480
- path: r.schemaRootPath,
481
- function: r.function?.name,
482
- })),
483
- },
484
- });
401
+ if (!equivalentSchemaPathsEntry) {
402
+ // Before creating a new entry, filter out roots that have conflicting
403
+ // signature indices from the same function. An entry should never contain
404
+ // roots with different signature indices from the same function.
405
+ // This prevents the bug where signature[1], signature[2], signature[4]
406
+ // all get merged together due to incorrect sourceEquivalencies.
407
+ let filteredRoots = equivalentRoots;
408
+ if (newRootSignatureIndices.size > 1) {
409
+ // There are multiple signature indices - we need to filter to keep only
410
+ // one consistent set. We'll keep the roots that match the PRIMARY index
411
+ // (the first signature index we encounter from self, or the lowest index).
412
+ // First, determine the primary index - prefer the self root's index
413
+ let primaryIndex;
414
+ for (const root of equivalentRoots) {
415
+ if (!root.function) {
416
+ // This is a self root
417
+ const idx = extractSignatureIndex(root.schemaRootPath);
418
+ if (idx !== undefined) {
419
+ primaryIndex = idx;
420
+ break;
421
+ }
422
+ }
423
+ }
424
+ // If no self root has a signature index, use the lowest index
425
+ if (primaryIndex === undefined) {
426
+ primaryIndex = Math.min(...newRootSignatureIndices);
427
+ }
428
+ // Filter roots: keep if no signature index OR signature index matches primary
429
+ filteredRoots = equivalentRoots.filter((root) => {
430
+ const idx = extractSignatureIndex(root.schemaRootPath);
431
+ return idx === undefined || idx === primaryIndex;
432
+ });
433
+ }
434
+ equivalentSchemaPathsEntry = {
435
+ equivalentRoots: filteredRoots,
436
+ equivalentPostfixes: {},
437
+ };
438
+ equivalentSchemaPaths.push(equivalentSchemaPathsEntry);
439
+ }
440
+ else {
441
+ equivalentSchemaPathsEntry.equivalentRoots.push(...equivalentRoots);
485
442
  }
486
- for (const equivalentRoot of entry.equivalentRoots) {
487
- const dataStructures = equivalentRoot.function &&
488
- equivalentRoot.function.name !== rootScopeName
489
- ? [
490
- findRelevantDependentDataStructure(equivalentRoot.function.name),
491
- findRelevantDependentAnalysisDataStructure(equivalentRoot.function.name),
492
- ]
493
- : [dataStructure];
494
- // Determine if this is a signature schema path.
495
- // The path might be 'signature[0]...' directly, or 'FuncName().signature[0]...' if it has a function prefix.
496
- const schemaRootParts = splitOutsideParenthesesAndArrays(equivalentRoot.schemaRootPath);
497
- const isSignaturePath = equivalentRoot.schemaRootPath.startsWith('signature[') ||
498
- (schemaRootParts[0]?.endsWith(')') &&
499
- schemaRootParts[1]?.startsWith('signature['));
500
- const schemas = dataStructures.map((dataStructure) => isSignaturePath
501
- ? dataStructure?.signatureSchema
502
- : dataStructure?.returnValueSchema);
503
- let pathParts = splitOutsideParenthesesAndArrays(equivalentRoot.schemaRootPath);
504
- // Fix: When processing a child component's schema, the schemaRootPath has the function
505
- // prefix (e.g., 'ScenarioViewer().signature[0].scenario'), but the child's schema paths
506
- // don't have that prefix (e.g., 'signature[0].scenario.metadata.screenshotPaths').
507
- // Strip the function prefix from pathParts so they can match.
508
- if (equivalentRoot.function &&
509
- pathParts[0].endsWith(')') &&
510
- pathParts[1]?.startsWith('signature[')) {
511
- pathParts = pathParts.slice(1);
443
+ // Deduplicate roots using a Set for O(n) instead of O(n²)
444
+ const seenRoots = new Set();
445
+ equivalentSchemaPathsEntry.equivalentRoots =
446
+ equivalentSchemaPathsEntry.equivalentRoots.filter((er) => {
447
+ const key = er.schemaRootPath + '::' + (er.function?.name ?? '');
448
+ if (seenRoots.has(key))
449
+ return false;
450
+ seenRoots.add(key);
451
+ return true;
452
+ });
453
+ // Keep the espIndex in sync after adding/deduplicating roots
454
+ updateEspIndex(equivalentSchemaPathsEntry);
455
+ return equivalentSchemaPathsEntry;
456
+ };
457
+ // Helper to extract function name from a path that starts with a function call.
458
+ // e.g., 'ScenarioViewer().signature[0].scenario' -> 'ScenarioViewer'
459
+ // Returns undefined if the path doesn't start with a function call or the function isn't a dependency.
460
+ const extractFunctionNameFromPath = (path) => {
461
+ const parts = splitOutsideParenthesesAndArrays(path);
462
+ if (parts.length > 0 && parts[0].endsWith(')')) {
463
+ // Extract the function name without the () suffix and type params
464
+ const funcCallPart = parts[0];
465
+ const funcName = cleanFunctionName(funcCallPart.replace(/\(\)$/, ''));
466
+ // Check if this function is a dependency
467
+ if (findRelevantDependency(funcName)) {
468
+ return funcName;
512
469
  }
513
- for (const schema of schemas) {
514
- for (const schemaPath in schema) {
515
- let schemaPathParts = splitOutsideParenthesesAndArrays(schemaPath);
516
- if (schemaPathParts[0].startsWith(functionName)) {
517
- // Only normalize if the function doesn't have multiple different type parameters
518
- const baseName = cleanFunctionName(schemaPathParts[0]);
519
- if (!functionsWithMultipleTypeParams.has(baseName)) {
520
- schemaPathParts =
521
- schemaPathParts[1] === 'functionCallReturnValue'
522
- ? ['returnValue', ...schemaPathParts.slice(2)]
523
- : schemaPathParts.slice(1);
470
+ }
471
+ return undefined;
472
+ };
473
+ const allEquivalencies = [
474
+ sourceAndUsageEquivalencies.usageEquivalencies,
475
+ sourceAndUsageEquivalencies.sourceEquivalencies,
476
+ ].filter(Boolean);
477
+ // Global dedup across ALL equivalency entries. The same (scope, targetPath)
478
+ // pair often appears in 30-50 different source entries (e.g., every variable
479
+ // that flows through loadView references the same 50 target paths).
480
+ // Processing these redundantly accounts for 96% of work in the gather phase.
481
+ const globalSeenTargets = new Set();
482
+ for (const equivalencies of allEquivalencies) {
483
+ const schemaPathEntries = Object.entries(equivalencies);
484
+ for (const [schemaPath, usages] of schemaPathEntries) {
485
+ checkDeadline();
486
+ // Skip equivalency entries whose source path is a Set/Map membership operation.
487
+ // Patterns like `.has(articleId)`, `.delete(articleId)`, `.add(articleId)` on
488
+ // Sets/Maps represent membership checks, not meaningful data flow for schema generation.
489
+ // In the Margo LibraryPage case, these account for 74% of all equivalency targets
490
+ // (19,444 of 26,340) and cause a combinatorial explosion in the merge.
491
+ if (isCollectionMethodPath(schemaPath))
492
+ continue;
493
+ // Skip paths with inline object literals in function call arguments.
494
+ // These are call-site snapshots (e.g., setUndoEntry({ label: '...', undo: ... }))
495
+ // that embed source code text as path strings. They're expensive to parse
496
+ // and don't contribute useful schema information.
497
+ if (hasInlineObjectArg(schemaPath))
498
+ continue;
499
+ // First, check if the raw schemaPath starts with a function call to a dependency.
500
+ // If so, use that dependency name for translation (so translatePath can strip the prefix).
501
+ const extractedFuncName = extractFunctionNameFromPath(schemaPath);
502
+ const effectiveFunctionName = extractedFuncName || functionName;
503
+ const translatedPath = translatePath(schemaPath, effectiveFunctionName);
504
+ const allPathsRaw = [
505
+ { path: translatedPath, functionName: effectiveFunctionName },
506
+ ...usages
507
+ .filter((u) => !isCollectionMethodPath(u.schemaPath))
508
+ .map((u) => ({
509
+ path: translatePath(u.schemaPath, u.scopeNodeName),
510
+ functionName: u.scopeNodeName,
511
+ })),
512
+ ].filter((pathInfo) => !pathInfo.path.includes('.map('));
513
+ // Deduplicate by translated path + function name, both within this entry
514
+ // AND across all entries. The same target path appears in 30-50 different
515
+ // source entries (every variable flowing through loadView references the same
516
+ // 50 target paths). Without global dedup, we process 5,533 targets instead of 217.
517
+ const allPaths = allPathsRaw.filter((p) => {
518
+ const key = `${p.functionName ?? ''}::${p.path}`;
519
+ if (globalSeenTargets.has(key))
520
+ return false;
521
+ globalSeenTargets.add(key);
522
+ return true;
523
+ });
524
+ // Fix 38: Derive base paths from property access paths.
525
+ // When we have equivalent paths like:
526
+ // Parent: signature[0].scenarios[].name
527
+ // Child: signature[0].selectedScenario.name
528
+ // We want to derive the base paths by finding the common suffix:
529
+ // Common suffix: .name
530
+ // Parent base: signature[0].scenarios[]
531
+ // Child base: signature[0].selectedScenario
532
+ // This allows the merge to find nested child schema fields under the base prop.
533
+ // Find child signature paths (paths from child components)
534
+ const childPaths = allPaths.filter((p) => p.functionName &&
535
+ p.functionName !== rootScopeName &&
536
+ p.functionName !== effectiveFunctionName);
537
+ // Find parent paths (paths from this component)
538
+ const parentPaths = allPaths.filter((p) => !p.functionName ||
539
+ p.functionName === rootScopeName ||
540
+ p.functionName === effectiveFunctionName);
541
+ const derivedBasePaths = [];
542
+ const allPathSet = new Set(allPaths.map((p) => p.path));
543
+ const derivedBasePathSet = new Set();
544
+ // For each child path, find its equivalent parent path and derive bases
545
+ for (const childPathInfo of childPaths) {
546
+ checkDeadline();
547
+ const childParts = splitOutsideParenthesesAndArrays(childPathInfo.path);
548
+ // Look for a parent path that shares a common suffix with this child path
549
+ for (const parentPathInfo of parentPaths) {
550
+ const parentParts = splitOutsideParenthesesAndArrays(parentPathInfo.path);
551
+ // Find the common suffix (from the end)
552
+ let commonSuffixLength = 0;
553
+ const minLen = Math.min(childParts.length, parentParts.length);
554
+ for (let i = 1; i <= minLen; i++) {
555
+ if (childParts[childParts.length - i] ===
556
+ parentParts[parentParts.length - i]) {
557
+ commonSuffixLength = i;
524
558
  }
525
- }
526
- if (schemaPathParts.length < pathParts.length)
527
- continue;
528
- // Check if all path parts match (allowing function call variants)
529
- let allMatch = true;
530
- let matchedUpToIndex = pathParts.length;
531
- for (let i = 0; i < pathParts.length; i++) {
532
- if (!pathPartMatches(pathParts[i], schemaPathParts[i])) {
533
- allMatch = false;
559
+ else {
534
560
  break;
535
561
  }
536
- // If the last pathPart matched a function call variant,
537
- // we need to include it in the postfix calculation
538
- if (i === pathParts.length - 1 &&
539
- schemaPathParts[i] !== pathParts[i] &&
540
- schemaPathParts[i].startsWith(pathParts[i] + '(')) {
541
- // The schemaPathPart is a function call variant (e.g., 'isEntityBeingAnalyzed(entity.sha)')
542
- // We want to include this as part of the postfix
543
- matchedUpToIndex = i;
562
+ }
563
+ // If there's a common suffix and both paths have more parts than the suffix
564
+ if (commonSuffixLength > 0 &&
565
+ childParts.length > commonSuffixLength &&
566
+ parentParts.length > commonSuffixLength) {
567
+ const childBaseParts = childParts.slice(0, childParts.length - commonSuffixLength);
568
+ const parentBaseParts = parentParts.slice(0, parentParts.length - commonSuffixLength);
569
+ // Only derive if BOTH paths look like signature paths.
570
+ // This ensures we're handling JSX child-to-parent prop mappings,
571
+ // not other complex equivalencies like function call returns.
572
+ const isChildSignaturePath = childBaseParts[0]?.startsWith('signature[') ||
573
+ (childBaseParts[0]?.endsWith(')') &&
574
+ childBaseParts[1]?.startsWith('signature['));
575
+ const isParentSignaturePath = parentBaseParts[0]?.startsWith('signature[');
576
+ if (isChildSignaturePath && isParentSignaturePath) {
577
+ const childBase = joinParenthesesAndArrays(childBaseParts);
578
+ const parentBase = joinParenthesesAndArrays(parentBaseParts);
579
+ // Only derive if:
580
+ // 1. Parent has array iteration (e.g., scenarios[]) and child does NOT
581
+ // 2. Bases are different
582
+ // 3. Child base is NOT just "signature[N]" (too generic - every component has this)
583
+ // We only want specific prop paths like "signature[0].selectedScenario"
584
+ // This targets array-to-object mappings like scenarios[] -> selectedScenario
585
+ const parentHasArrayIterator = parentBase.includes('[]');
586
+ const childHasArrayIterator = childBase.includes('[]');
587
+ // Skip if child base is just the generic signature marker (e.g., "signature[0]")
588
+ const childBaseIsGenericSignature = /^signature\[\d+\]$/.test(childBase);
589
+ if (childBase !== parentBase &&
590
+ parentHasArrayIterator &&
591
+ !childHasArrayIterator &&
592
+ !childBaseIsGenericSignature) {
593
+ // Add child base if not already present (O(1) Set lookup)
594
+ if (!allPathSet.has(childBase) &&
595
+ !derivedBasePathSet.has(childBase)) {
596
+ derivedBasePaths.push({
597
+ path: childBase,
598
+ functionName: childPathInfo.functionName,
599
+ });
600
+ derivedBasePathSet.add(childBase);
601
+ }
602
+ // Add parent base if not already present (O(1) Set lookup)
603
+ if (!allPathSet.has(parentBase) &&
604
+ !derivedBasePathSet.has(parentBase)) {
605
+ derivedBasePaths.push({
606
+ path: parentBase,
607
+ functionName: parentPathInfo.functionName,
608
+ });
609
+ derivedBasePathSet.add(parentBase);
610
+ }
611
+ }
544
612
  }
545
613
  }
546
- if (allMatch) {
547
- // When we matched a function call variant at the end (e.g., 'foo' matched 'foo(args)'),
548
- // the base itself should be marked as a function, and the function call details
549
- // should be included as sub-paths
550
- if (matchedUpToIndex < pathParts.length) {
551
- // This is a function call variant match at the last position
552
- // Mark the base as a function (empty postfix = the base path itself)
553
- entry.equivalentPostfixes[''] = bestValueFromOptions([
554
- entry.equivalentPostfixes[''],
555
- 'function',
556
- ]);
557
- // Also capture the function call and any remaining parts
558
- // e.g., 'isEntityBeingAnalyzed(entity.sha)' or 'isEntityBeingAnalyzed(entity.sha).functionCallReturnValue'
559
- const funcCallPart = schemaPathParts[matchedUpToIndex];
560
- const baseName = pathParts[matchedUpToIndex]; // e.g., 'isEntityBeingAnalyzed'
561
- const argsMatch = funcCallPart.match(/\(.*\)$/);
562
- if (argsMatch) {
563
- // Create postfix using just the args portion: (entity.sha) instead of isEntityBeingAnalyzed(entity.sha)
564
- // This avoids duplicating the base name in the final path
565
- const argsPortion = argsMatch[0]; // e.g., '(entity.sha)'
566
- const remainingParts = schemaPathParts.slice(matchedUpToIndex + 1);
567
- // Build the postfix as: (args).remaining.parts
568
- const funcPostfix = joinParenthesesAndArrays([
569
- argsPortion,
570
- ...remainingParts,
571
- ]);
572
- entry.equivalentPostfixes[funcPostfix] = entry
573
- .equivalentPostfixes[funcPostfix]
574
- ? bestValueFromOptions([
575
- entry.equivalentPostfixes[funcPostfix],
576
- schema[schemaPath],
577
- ])
578
- : schema[schemaPath];
614
+ }
615
+ }
616
+ allPaths.push(...derivedBasePaths);
617
+ const entry = findOrCreateEquivalentSchemaPathsEntry(allPaths);
618
+ // Trace equivalency gathering - helps debug why paths may not be connected
619
+ if (allPaths.length > 1) {
620
+ transformationTracer.operation(rootScopeName, {
621
+ operation: 'gatherEquivalency',
622
+ stage: 'gathering',
623
+ path: translatedPath,
624
+ context: {
625
+ sourceFunction: functionName,
626
+ equivalentPaths: allPaths.map((p) => ({
627
+ path: p.path,
628
+ function: p.functionName,
629
+ })),
630
+ equivalentRoots: entry.equivalentRoots.map((r) => ({
631
+ path: r.schemaRootPath,
632
+ function: r.function?.name,
633
+ })),
634
+ },
635
+ });
636
+ }
637
+ for (const equivalentRoot of entry.equivalentRoots) {
638
+ checkDeadline();
639
+ const dataStructures = equivalentRoot.function &&
640
+ equivalentRoot.function.name !== rootScopeName
641
+ ? [
642
+ findRelevantDependentDataStructure(equivalentRoot.function.name),
643
+ findRelevantDependentAnalysisDataStructure(equivalentRoot.function.name),
644
+ ]
645
+ : [dataStructure];
646
+ // Determine if this is a signature schema path.
647
+ // The path might be 'signature[0]...' directly, or 'FuncName().signature[0]...' if it has a function prefix.
648
+ const schemaRootParts = splitOutsideParenthesesAndArrays(equivalentRoot.schemaRootPath);
649
+ const isSignaturePath = equivalentRoot.schemaRootPath.startsWith('signature[') ||
650
+ (schemaRootParts[0]?.endsWith(')') &&
651
+ schemaRootParts[1]?.startsWith('signature['));
652
+ const schemas = dataStructures.map((dataStructure) => isSignaturePath
653
+ ? dataStructure?.signatureSchema
654
+ : dataStructure?.returnValueSchema);
655
+ let pathParts = splitOutsideParenthesesAndArrays(equivalentRoot.schemaRootPath);
656
+ // Fix: When processing a child component's schema, the schemaRootPath has the function
657
+ // prefix (e.g., 'ScenarioViewer().signature[0].scenario'), but the child's schema paths
658
+ // don't have that prefix (e.g., 'signature[0].scenario.metadata.screenshotPaths').
659
+ // Strip the function prefix from pathParts so they can match.
660
+ if (equivalentRoot.function &&
661
+ pathParts[0].endsWith(')') &&
662
+ pathParts[1]?.startsWith('signature[')) {
663
+ pathParts = pathParts.slice(1);
664
+ }
665
+ for (const schema of schemas) {
666
+ // Use pre-computed index to only iterate schema entries whose
667
+ // normalized first part matches pathParts[0], instead of all entries.
668
+ const schemaIndex = getSchemaIndex(schema);
669
+ const lookupPart = pathParts[0] ?? '';
670
+ const lookupParenIdx = lookupPart.indexOf('(');
671
+ const lookupBase = lookupParenIdx >= 0
672
+ ? lookupPart.slice(0, lookupParenIdx)
673
+ : lookupPart;
674
+ const candidates = schemaIndex.byFirstPart.get(lookupBase) || [];
675
+ for (const { path: schemaPath, parts: schemaPathParts, } of candidates) {
676
+ checkDeadline();
677
+ if (schemaPathParts.length < pathParts.length)
678
+ continue;
679
+ // Check if all path parts match (allowing function call variants)
680
+ let allMatch = true;
681
+ let matchedUpToIndex = pathParts.length;
682
+ for (let i = 0; i < pathParts.length; i++) {
683
+ if (!pathPartMatches(pathParts[i], schemaPathParts[i])) {
684
+ allMatch = false;
685
+ break;
686
+ }
687
+ // If the last pathPart matched a function call variant,
688
+ // we need to include it in the postfix calculation
689
+ if (i === pathParts.length - 1 &&
690
+ schemaPathParts[i] !== pathParts[i] &&
691
+ schemaPathParts[i].startsWith(pathParts[i] + '(')) {
692
+ // The schemaPathPart is a function call variant (e.g., 'isEntityBeingAnalyzed(entity.sha)')
693
+ // We want to include this as part of the postfix
694
+ matchedUpToIndex = i;
579
695
  }
580
696
  }
581
- else {
582
- // Regular exact match - use the standard postfix logic
583
- const postfix = joinParenthesesAndArrays(schemaPathParts.slice(matchedUpToIndex));
584
- const previousValue = entry.equivalentPostfixes[postfix];
585
- const newValue = schema[schemaPath];
586
- entry.equivalentPostfixes[postfix] = previousValue
587
- ? bestValueFromOptions([previousValue, newValue])
588
- : newValue;
589
- // Trace postfix gathering - shows where type info comes from
590
- if (entry.equivalentPostfixes[postfix] !== previousValue) {
591
- transformationTracer.operation(rootScopeName, {
592
- operation: 'gatherPostfix',
593
- stage: 'gathering',
594
- path: postfix || '(root)',
595
- before: previousValue,
596
- after: entry.equivalentPostfixes[postfix],
597
- context: {
598
- sourceSchemaPath: schemaPath,
599
- sourceFunction: equivalentRoot.function?.name || rootScopeName,
600
- equivalentRootPath: equivalentRoot.schemaRootPath,
601
- rawValue: newValue,
602
- },
603
- });
697
+ if (allMatch) {
698
+ // When we matched a function call variant at the end (e.g., 'foo' matched 'foo(args)'),
699
+ // the base itself should be marked as a function, and the function call details
700
+ // should be included as sub-paths
701
+ if (matchedUpToIndex < pathParts.length) {
702
+ // This is a function call variant match at the last position
703
+ // Mark the base as a function (empty postfix = the base path itself)
704
+ entry.equivalentPostfixes[''] = bestValueFromOptions([
705
+ entry.equivalentPostfixes[''],
706
+ 'function',
707
+ ]);
708
+ // Also capture the function call and any remaining parts
709
+ // e.g., 'isEntityBeingAnalyzed(entity.sha)' or 'isEntityBeingAnalyzed(entity.sha).functionCallReturnValue'
710
+ const funcCallPart = schemaPathParts[matchedUpToIndex];
711
+ const baseName = pathParts[matchedUpToIndex]; // e.g., 'isEntityBeingAnalyzed'
712
+ const argsMatch = funcCallPart.match(/\(.*\)$/);
713
+ if (argsMatch) {
714
+ // Create postfix using just the args portion: (entity.sha) instead of isEntityBeingAnalyzed(entity.sha)
715
+ // This avoids duplicating the base name in the final path
716
+ const argsPortion = argsMatch[0]; // e.g., '(entity.sha)'
717
+ const remainingParts = schemaPathParts.slice(matchedUpToIndex + 1);
718
+ // Build the postfix as: (args).remaining.parts
719
+ const funcPostfix = joinParenthesesAndArrays([
720
+ argsPortion,
721
+ ...remainingParts,
722
+ ]);
723
+ entry.equivalentPostfixes[funcPostfix] = entry
724
+ .equivalentPostfixes[funcPostfix]
725
+ ? bestValueFromOptions([
726
+ entry.equivalentPostfixes[funcPostfix],
727
+ schema[schemaPath],
728
+ ])
729
+ : schema[schemaPath];
730
+ }
731
+ }
732
+ else {
733
+ // Regular exact match - use the standard postfix logic
734
+ const postfix = joinParenthesesAndArrays(schemaPathParts.slice(matchedUpToIndex));
735
+ const previousValue = entry.equivalentPostfixes[postfix];
736
+ const newValue = schema[schemaPath];
737
+ entry.equivalentPostfixes[postfix] = previousValue
738
+ ? bestValueFromOptions([previousValue, newValue])
739
+ : newValue;
740
+ // Trace postfix gathering - shows where type info comes from
741
+ if (entry.equivalentPostfixes[postfix] !== previousValue) {
742
+ transformationTracer.operation(rootScopeName, {
743
+ operation: 'gatherPostfix',
744
+ stage: 'gathering',
745
+ path: postfix || '(root)',
746
+ before: previousValue,
747
+ after: entry.equivalentPostfixes[postfix],
748
+ context: {
749
+ sourceSchemaPath: schemaPath,
750
+ sourceFunction: equivalentRoot.function?.name || rootScopeName,
751
+ equivalentRootPath: equivalentRoot.schemaRootPath,
752
+ rawValue: newValue,
753
+ },
754
+ });
755
+ }
604
756
  }
605
757
  }
606
758
  }
@@ -608,771 +760,864 @@ export default function mergeInDependentDataStructure({ importedExports, depende
608
760
  }
609
761
  }
610
762
  }
611
- }
612
- if (Object.keys(dataStructure?.returnValueSchema ?? {}).length > 0) {
613
- // Find all paths that contain functionCallReturnValue and extract unique base paths
614
- // For each path containing functionCallReturnValue, find the FIRST occurrence and use
615
- // that as a base path. This handles nested cases like:
616
- // X().functionCallReturnValue.A.B.Y().functionCallReturnValue
617
- // where we want both X().functionCallReturnValue and Y().functionCallReturnValue as bases
618
- const allBasePaths = new Set();
619
- for (const path of Object.keys(dataStructure.returnValueSchema)) {
620
- const parts = splitOutsideParenthesesAndArrays(path);
621
- // Find all positions of functionCallReturnValue and create base paths for each
622
- for (let i = 0; i < parts.length; i++) {
623
- if (parts[i] === 'functionCallReturnValue') {
624
- const basePath = joinParenthesesAndArrays(parts.slice(0, i + 1));
625
- allBasePaths.add(basePath);
763
+ if (Object.keys(dataStructure?.returnValueSchema ?? {}).length > 0) {
764
+ // Find all paths that contain functionCallReturnValue and extract unique base paths
765
+ // For each path containing functionCallReturnValue, find the FIRST occurrence and use
766
+ // that as a base path. This handles nested cases like:
767
+ // X().functionCallReturnValue.A.B.Y().functionCallReturnValue
768
+ // where we want both X().functionCallReturnValue and Y().functionCallReturnValue as bases
769
+ const allBasePaths = new Set();
770
+ for (const path of Object.keys(dataStructure.returnValueSchema)) {
771
+ checkDeadline();
772
+ const parts = splitOutsideParenthesesAndArrays(path);
773
+ // Find all positions of functionCallReturnValue and create base paths for each
774
+ for (let i = 0; i < parts.length; i++) {
775
+ if (parts[i] === 'functionCallReturnValue') {
776
+ const basePath = joinParenthesesAndArrays(parts.slice(0, i + 1));
777
+ allBasePaths.add(basePath);
778
+ }
626
779
  }
627
780
  }
628
- }
629
- // Sort by length so shorter paths are processed first
630
- const sortedBasePaths = [...allBasePaths].sort((a, b) => a.length - b.length);
631
- for (const basePath of sortedBasePaths) {
632
- const translatedBasePath = translatePath(basePath, functionName);
633
- const entry = findOrCreateEquivalentSchemaPathsEntry([
634
- { path: translatedBasePath, functionName: functionName },
635
- ]);
636
- entry.equivalentRoots.push({
637
- schemaRootPath: translatedBasePath,
638
- function: findRelevantDependency(functionName),
639
- });
640
- const basePathParts = splitOutsideParenthesesAndArrays(basePath);
641
- for (const schemaPath in dataStructure.returnValueSchema) {
642
- const schemaPathParts = splitOutsideParenthesesAndArrays(schemaPath);
643
- if (schemaPathParts.length < basePathParts.length)
644
- continue;
645
- // Check if this schemaPath actually starts with this basePath
646
- // (not just has the same length prefix)
647
- const prefixParts = schemaPathParts.slice(0, basePathParts.length);
648
- if (joinParenthesesAndArrays(prefixParts) !==
649
- joinParenthesesAndArrays(basePathParts)) {
650
- continue;
781
+ // Sort by length so shorter paths are processed first
782
+ const sortedBasePaths = [...allBasePaths].sort((a, b) => a.length - b.length);
783
+ for (const basePath of sortedBasePaths) {
784
+ const translatedBasePath = translatePath(basePath, functionName);
785
+ const entry = findOrCreateEquivalentSchemaPathsEntry([
786
+ { path: translatedBasePath, functionName: functionName },
787
+ ]);
788
+ const newRoot = {
789
+ schemaRootPath: translatedBasePath,
790
+ function: findRelevantDependency(functionName),
791
+ };
792
+ entry.equivalentRoots.push(newRoot);
793
+ // Update index for the newly added root
794
+ const newRootFuncName = newRoot.function?.name ?? rootScopeName;
795
+ espIndex.set(espIndexKey(newRoot.schemaRootPath, newRootFuncName), entry);
796
+ const basePathParts = splitOutsideParenthesesAndArrays(basePath);
797
+ for (const schemaPath in dataStructure.returnValueSchema) {
798
+ checkDeadline();
799
+ const schemaPathParts = splitOutsideParenthesesAndArrays(schemaPath);
800
+ if (schemaPathParts.length < basePathParts.length)
801
+ continue;
802
+ // Check if this schemaPath actually starts with this basePath
803
+ // (not just has the same length prefix)
804
+ const prefixParts = schemaPathParts.slice(0, basePathParts.length);
805
+ if (joinParenthesesAndArrays(prefixParts) !==
806
+ joinParenthesesAndArrays(basePathParts)) {
807
+ continue;
808
+ }
809
+ const postfix = joinParenthesesAndArrays(schemaPathParts.slice(basePathParts.length));
810
+ const newValue = entry.equivalentPostfixes[postfix]
811
+ ? bestValueFromOptions([
812
+ entry.equivalentPostfixes[postfix],
813
+ dataStructure.returnValueSchema[schemaPath],
814
+ ])
815
+ : dataStructure.returnValueSchema[schemaPath];
816
+ entry.equivalentPostfixes[postfix] = newValue;
651
817
  }
652
- const postfix = joinParenthesesAndArrays(schemaPathParts.slice(basePathParts.length));
653
- const newValue = entry.equivalentPostfixes[postfix]
654
- ? bestValueFromOptions([
655
- entry.equivalentPostfixes[postfix],
656
- dataStructure.returnValueSchema[schemaPath],
657
- ])
658
- : dataStructure.returnValueSchema[schemaPath];
659
- entry.equivalentPostfixes[postfix] = newValue;
660
818
  }
661
819
  }
662
- }
663
- };
664
- const mergeAllEquivalentSchemaPaths = () => {
665
- const mergedEquivalentSchemaPaths = [];
666
- // Pre-pass: Connect entries with array/array-element relationships.
667
- // This handles cases like:
668
- // - Entry A has root 'surveys' (array)
669
- // - Entry B has root 'surveys[]' (array element)
670
- // These need to be connected so Entry B's field postfixes flow to Entry A.
671
- // We do this before the main merge to ensure the connection happens regardless
672
- // of processing order.
673
- for (const esp of equivalentSchemaPaths) {
674
- for (const root of esp.equivalentRoots) {
675
- if (root.schemaRootPath.endsWith('[]')) {
676
- // Find a matching parent entry with the base array path
677
- const baseArrayPath = root.schemaRootPath.slice(0, -2);
678
- const parentEntry = equivalentSchemaPaths.find((other) => other !== esp &&
679
- other.equivalentRoots.some((otherRoot) => otherRoot.schemaRootPath === baseArrayPath &&
680
- otherRoot.function?.name === root.function?.name &&
681
- otherRoot.function?.filePath === root.function?.filePath));
682
- if (parentEntry) {
683
- // Add transformed postfixes from child (array element) to parent (array)
684
- // so they can be applied with [] prefix to parent paths
685
- for (const [postfixPath, postfixValue] of Object.entries(esp.equivalentPostfixes)) {
686
- const transformedPostfix = joinParenthesesAndArrays(['[]', postfixPath].filter(Boolean));
687
- if (!(transformedPostfix in parentEntry.equivalentPostfixes)) {
688
- parentEntry.equivalentPostfixes[transformedPostfix] =
689
- postfixValue;
820
+ };
821
+ const mergeAllEquivalentSchemaPaths = () => {
822
+ const mergedEquivalentSchemaPaths = [];
823
+ // Pre-pass: Connect entries with array/array-element relationships.
824
+ // This handles cases like:
825
+ // - Entry A has root 'surveys' (array)
826
+ // - Entry B has root 'surveys[]' (array element)
827
+ // These need to be connected so Entry B's field postfixes flow to Entry A.
828
+ // We do this before the main merge to ensure the connection happens regardless
829
+ // of processing order.
830
+ for (const esp of equivalentSchemaPaths) {
831
+ checkDeadline();
832
+ for (const root of esp.equivalentRoots) {
833
+ if (root.schemaRootPath.endsWith('[]')) {
834
+ // Find a matching parent entry with the base array path
835
+ const baseArrayPath = root.schemaRootPath.slice(0, -2);
836
+ const parentEntry = equivalentSchemaPaths.find((other) => other !== esp &&
837
+ other.equivalentRoots.some((otherRoot) => otherRoot.schemaRootPath === baseArrayPath &&
838
+ otherRoot.function?.name === root.function?.name &&
839
+ otherRoot.function?.filePath === root.function?.filePath));
840
+ if (parentEntry) {
841
+ // Add transformed postfixes from child (array element) to parent (array)
842
+ // so they can be applied with [] prefix to parent paths
843
+ for (const [postfixPath, postfixValue] of Object.entries(esp.equivalentPostfixes)) {
844
+ checkDeadline();
845
+ const transformedPostfix = joinParenthesesAndArrays(['[]', postfixPath].filter(Boolean));
846
+ if (!(transformedPostfix in parentEntry.equivalentPostfixes)) {
847
+ parentEntry.equivalentPostfixes[transformedPostfix] =
848
+ postfixValue;
849
+ }
690
850
  }
691
851
  }
692
852
  }
693
853
  }
694
854
  }
695
- }
696
- const findEquivalentSchemaPathEntry = (schemaSubPath, equivalentRootFunction) => {
697
- let postfix;
698
- // Get the signature index we're looking for (if any)
699
- const lookingForSignatureIndex = extractSignatureIndex(schemaSubPath);
700
- const equivalentEntry = mergedEquivalentSchemaPaths.find((esp) => esp.equivalentRoots.some((er) => {
701
- if ((schemaSubPath.startsWith('returnValue') ||
702
- schemaSubPath.startsWith('signature[')) &&
703
- (er.function?.name !== equivalentRootFunction?.name ||
704
- er.function?.filePath !== equivalentRootFunction?.filePath)) {
705
- return false;
706
- }
707
- if (schemaSubPath === er.schemaRootPath) {
708
- // Additional check: if we're looking for a signature path, make sure
709
- // the entry doesn't already have DIFFERENT signature indices.
710
- // This prevents entries with signature[1], signature[2], signature[4]
711
- // from all being merged together.
712
- if (lookingForSignatureIndex !== undefined) {
713
- const hasConflictingSignatureIndex = esp.equivalentRoots.some((otherRoot) => {
714
- // Only check roots from the same function
715
- if (otherRoot.function?.name !== equivalentRootFunction?.name ||
716
- otherRoot.function?.filePath !==
717
- equivalentRootFunction?.filePath) {
855
+ const findEquivalentSchemaPathEntry = (schemaSubPath, equivalentRootFunction) => {
856
+ let postfix;
857
+ // Get the signature index we're looking for (if any)
858
+ const lookingForSignatureIndex = extractSignatureIndex(schemaSubPath);
859
+ const equivalentEntry = mergedEquivalentSchemaPaths.find((esp) => esp.equivalentRoots.some((er) => {
860
+ if ((schemaSubPath.startsWith('returnValue') ||
861
+ schemaSubPath.startsWith('signature[')) &&
862
+ (er.function?.name !== equivalentRootFunction?.name ||
863
+ er.function?.filePath !== equivalentRootFunction?.filePath)) {
864
+ return false;
865
+ }
866
+ if (schemaSubPath === er.schemaRootPath) {
867
+ // Additional check: if we're looking for a signature path, make sure
868
+ // the entry doesn't already have DIFFERENT signature indices.
869
+ // This prevents entries with signature[1], signature[2], signature[4]
870
+ // from all being merged together.
871
+ if (lookingForSignatureIndex !== undefined) {
872
+ const hasConflictingSignatureIndex = esp.equivalentRoots.some((otherRoot) => {
873
+ // Only check roots from the same function
874
+ if (otherRoot.function?.name !==
875
+ equivalentRootFunction?.name ||
876
+ otherRoot.function?.filePath !==
877
+ equivalentRootFunction?.filePath) {
878
+ return false;
879
+ }
880
+ const otherIndex = extractSignatureIndex(otherRoot.schemaRootPath);
881
+ return (otherIndex !== undefined &&
882
+ otherIndex !== lookingForSignatureIndex);
883
+ });
884
+ if (hasConflictingSignatureIndex) {
718
885
  return false;
719
886
  }
720
- const otherIndex = extractSignatureIndex(otherRoot.schemaRootPath);
721
- return (otherIndex !== undefined &&
722
- otherIndex !== lookingForSignatureIndex);
723
- });
724
- if (hasConflictingSignatureIndex) {
725
- return false;
726
887
  }
888
+ postfix = er.postfix;
889
+ return true;
727
890
  }
728
- postfix = er.postfix;
729
- return true;
730
- }
731
- return false;
732
- }));
733
- return { equivalentEntry, postfix };
734
- };
735
- const sortedEquivalentSchemaPaths = equivalentSchemaPaths.sort((a, b) => Math.max(...a.equivalentRoots.map((er) => splitOutsideParenthesesAndArrays(er.schemaRootPath).length)) -
736
- Math.max(...b.equivalentRoots.map((er) => splitOutsideParenthesesAndArrays(er.schemaRootPath).length)));
737
- for (const esp of sortedEquivalentSchemaPaths) {
738
- if (esp.equivalentRoots.length === 0)
739
- continue;
740
- let bestCandidateLength;
741
- let bestCandidate;
742
- let postfix;
743
- for (const equivalentRoot of esp.equivalentRoots) {
744
- const rootSchemaPath = equivalentRoot.schemaRootPath;
745
- const schemaPathParts = splitOutsideParenthesesAndArrays(rootSchemaPath);
746
- for (let i = 0; i < schemaPathParts.length; i++) {
747
- const subPath = joinParenthesesAndArrays(schemaPathParts.slice(0, i + 1));
748
- const { equivalentEntry, postfix: equivalentEntryPostfix } = findEquivalentSchemaPathEntry(subPath, equivalentRoot.function);
749
- if (equivalentEntry &&
750
- (!bestCandidateLength || bestCandidateLength > i + 1)) {
751
- bestCandidate = equivalentEntry;
752
- bestCandidateLength = i + 1;
753
- postfix = joinParenthesesAndArrays([equivalentEntryPostfix, ...schemaPathParts.slice(i + 1)].filter(Boolean));
891
+ return false;
892
+ }));
893
+ return { equivalentEntry, postfix };
894
+ };
895
+ const sortedEquivalentSchemaPaths = equivalentSchemaPaths.sort((a, b) => Math.max(...a.equivalentRoots.map((er) => splitOutsideParenthesesAndArrays(er.schemaRootPath).length)) -
896
+ Math.max(...b.equivalentRoots.map((er) => splitOutsideParenthesesAndArrays(er.schemaRootPath).length)));
897
+ for (const esp of sortedEquivalentSchemaPaths) {
898
+ checkDeadline();
899
+ if (esp.equivalentRoots.length === 0)
900
+ continue;
901
+ let bestCandidateLength;
902
+ let bestCandidate;
903
+ let postfix;
904
+ for (const equivalentRoot of esp.equivalentRoots) {
905
+ const rootSchemaPath = equivalentRoot.schemaRootPath;
906
+ const schemaPathParts = splitOutsideParenthesesAndArrays(rootSchemaPath);
907
+ for (let i = 0; i < schemaPathParts.length; i++) {
908
+ const subPath = joinParenthesesAndArrays(schemaPathParts.slice(0, i + 1));
909
+ const { equivalentEntry, postfix: equivalentEntryPostfix } = findEquivalentSchemaPathEntry(subPath, equivalentRoot.function);
910
+ if (equivalentEntry &&
911
+ (!bestCandidateLength || bestCandidateLength > i + 1)) {
912
+ bestCandidate = equivalentEntry;
913
+ bestCandidateLength = i + 1;
914
+ postfix = joinParenthesesAndArrays([
915
+ equivalentEntryPostfix,
916
+ ...schemaPathParts.slice(i + 1),
917
+ ].filter(Boolean));
918
+ }
754
919
  }
755
920
  }
756
- }
757
- if (bestCandidate) {
758
- for (const root of esp.equivalentRoots) {
759
- if (postfix.length > 0) {
760
- root.postfix = postfix;
921
+ if (bestCandidate) {
922
+ for (const root of esp.equivalentRoots) {
923
+ if (postfix.length > 0) {
924
+ root.postfix = postfix;
925
+ }
926
+ bestCandidate.equivalentRoots.push(root);
761
927
  }
762
- bestCandidate.equivalentRoots.push(root);
928
+ const postfixesToMerge = postfix.length > 0
929
+ ? Object.keys(esp.equivalentPostfixes).reduce((acc, postfixPath) => {
930
+ const fullPath = joinParenthesesAndArrays([
931
+ postfix,
932
+ postfixPath,
933
+ ]);
934
+ acc[fullPath] = esp.equivalentPostfixes[postfixPath];
935
+ return acc;
936
+ }, {})
937
+ : esp.equivalentPostfixes;
938
+ bestCandidate.equivalentPostfixes = {
939
+ ...bestCandidate.equivalentPostfixes,
940
+ ...postfixesToMerge,
941
+ };
942
+ }
943
+ else {
944
+ mergedEquivalentSchemaPaths.push(esp);
763
945
  }
764
- const postfixesToMerge = postfix.length > 0
765
- ? Object.keys(esp.equivalentPostfixes).reduce((acc, postfixPath) => {
766
- const fullPath = joinParenthesesAndArrays([
767
- postfix,
768
- postfixPath,
769
- ]);
770
- acc[fullPath] = esp.equivalentPostfixes[postfixPath];
771
- return acc;
772
- }, {})
773
- : esp.equivalentPostfixes;
774
- bestCandidate.equivalentPostfixes = {
775
- ...bestCandidate.equivalentPostfixes,
776
- ...postfixesToMerge,
777
- };
778
946
  }
779
- else {
780
- mergedEquivalentSchemaPaths.push(esp);
947
+ return mergedEquivalentSchemaPaths;
948
+ };
949
+ // Build a lookup of mocked dependencies to skip their internal implementation
950
+ const mockedDependencies = new Set();
951
+ for (const dep of importedExports) {
952
+ if (dep.isMocked) {
953
+ mockedDependencies.add(`${dep.filePath}::${dep.name}`);
781
954
  }
782
955
  }
783
- return mergedEquivalentSchemaPaths;
784
- };
785
- // Build a lookup of mocked dependencies to skip their internal implementation
786
- const mockedDependencies = new Set();
787
- for (const dep of importedExports) {
788
- if (dep.isMocked) {
789
- mockedDependencies.add(`${dep.filePath}::${dep.name}`);
790
- }
791
- }
792
- gatherAllEquivalentSchemaPaths(rootScopeName, dataStructure);
793
- // Process dependencySchemas for all dependencies (including mocked ones)
794
- // dependencySchemas contains usage information (how dependencies are called),
795
- // not internal implementation, so we want this for mocked dependencies too
796
- for (const dependency of importedExports) {
797
- const dependentDataStructure = dependencySchemas?.[dependency.filePath]?.[dependency.name];
798
- if (!dependentDataStructure)
799
- continue;
800
- gatherAllEquivalentSchemaPaths(dependency.name, dependentDataStructure, dependentDataStructure);
801
- }
802
- for (const filePath in dependentAnalyses) {
803
- for (const name in dependentAnalyses[filePath]) {
804
- // Skip mocked dependencies - we don't want to merge in their internal implementation
805
- if (mockedDependencies.has(`${filePath}::${name}`)) {
956
+ gatherAllEquivalentSchemaPaths(rootScopeName, dataStructure);
957
+ // Process dependencySchemas for all dependencies (including mocked ones)
958
+ // dependencySchemas contains usage information (how dependencies are called),
959
+ // not internal implementation, so we want this for mocked dependencies too
960
+ for (const dependency of importedExports) {
961
+ checkDeadline();
962
+ const dependentDataStructure = dependencySchemas?.[dependency.filePath]?.[dependency.name];
963
+ if (!dependentDataStructure)
806
964
  continue;
807
- }
808
- const childMergedDataStructure = dependentAnalyses[filePath][name].metadata?.mergedDataStructure || {};
809
- gatherAllEquivalentSchemaPaths(name, childMergedDataStructure);
965
+ gatherAllEquivalentSchemaPaths(dependency.name, dependentDataStructure, dependentDataStructure);
810
966
  }
811
- }
812
- equivalentSchemaPaths = mergeAllEquivalentSchemaPaths();
813
- for (const esp of equivalentSchemaPaths) {
814
- // Pre-compute which postfixes have children to avoid O() lookups in the inner loop.
815
- // A postfix "has children" if there are other postfixes that extend it.
816
- const postfixesWithChildren = new Set();
817
- const postfixKeys = Object.keys(esp.equivalentPostfixes);
818
- // Check for empty postfix having children (any other postfixes exist)
819
- if (postfixKeys.length > 1 && '' in esp.equivalentPostfixes) {
820
- postfixesWithChildren.add('');
821
- }
822
- // Check for array element postfixes having children using a prefix set.
823
- // This avoids O(n²) scans across large postfix lists.
824
- // e.g., 'currentEntities[]' has children if a path like 'currentEntities[].sha' exists.
825
- const postfixPrefixSet = new Set();
826
- for (const postfixPath of postfixKeys) {
827
- if (!postfixPath)
828
- continue;
829
- const parts = splitOutsideParenthesesAndArrays(postfixPath);
830
- for (let i = 1; i < parts.length; i++) {
831
- postfixPrefixSet.add(joinParenthesesAndArrays(parts.slice(0, i)));
967
+ for (const filePath in dependentAnalyses) {
968
+ for (const name in dependentAnalyses[filePath]) {
969
+ // Skip mocked dependencies - we don't want to merge in their internal implementation
970
+ if (mockedDependencies.has(`${filePath}::${name}`)) {
971
+ continue;
972
+ }
973
+ const childMergedDataStructure = dependentAnalyses[filePath][name].metadata?.mergedDataStructure || {};
974
+ gatherAllEquivalentSchemaPaths(name, childMergedDataStructure);
832
975
  }
833
976
  }
834
- for (const postfixPath of postfixKeys) {
835
- if (postfixPath.endsWith('[]') && postfixPrefixSet.has(postfixPath)) {
836
- postfixesWithChildren.add(postfixPath);
977
+ const gatherElapsed = Date.now() - mergeStartTime;
978
+ equivalentSchemaPaths = mergeAllEquivalentSchemaPaths();
979
+ const mergeEspElapsed = Date.now() - mergeStartTime;
980
+ // Collect schemas that need cleaning — batch the calls for the end instead of
981
+ // calling cleanSchema inside the inner root loop (which was O(roots * schemaSize)).
982
+ const schemasToClean = new Set();
983
+ for (const esp of equivalentSchemaPaths) {
984
+ checkDeadline();
985
+ // Pre-compute which postfixes have children to avoid O(n²) lookups in the inner loop.
986
+ // A postfix "has children" if there are other postfixes that extend it.
987
+ const postfixesWithChildren = new Set();
988
+ const postfixKeys = Object.keys(esp.equivalentPostfixes);
989
+ // Pre-parse ALL postfix paths once. These parsed parts are reused in:
990
+ // 1. The children detection loop below
991
+ // 2. The inner postfix application loop (lines that split postfixPath and equivalentRoot.postfix)
992
+ // This eliminates thousands of redundant splitOutsideParenthesesAndArrays calls.
993
+ const postfixPartsCache = new Map();
994
+ for (const postfixPath of postfixKeys) {
995
+ if (!postfixPath)
996
+ continue;
997
+ postfixPartsCache.set(postfixPath, splitOutsideParenthesesAndArrays(postfixPath));
837
998
  }
838
- }
839
- // Deduplicate equivalentRoots that would write to the same schema paths.
840
- // Roots with the same (function, schemaRootPath, postfix) are redundant.
841
- const seenRootKeys = new Set();
842
- const uniqueRoots = esp.equivalentRoots.filter((root) => {
843
- const key = `${root.function?.filePath ?? ''}::${root.function?.name ?? ''}::${root.schemaRootPath}::${root.postfix ?? ''}`;
844
- if (seenRootKeys.has(key))
845
- return false;
846
- seenRootKeys.add(key);
847
- return true;
848
- });
849
- for (const equivalentRoot of uniqueRoots) {
850
- let merged;
851
- if (equivalentRoot.function) {
852
- merged = findOrCreateDependentSchemas(equivalentRoot.function);
999
+ // Check for empty postfix having children (any other postfixes exist)
1000
+ if (postfixKeys.length > 1 && '' in esp.equivalentPostfixes) {
1001
+ postfixesWithChildren.add('');
853
1002
  }
854
- else {
855
- merged = mergedDataStructure;
1003
+ // Check for array element postfixes having children using a prefix set.
1004
+ // This avoids O(n²) scans across large postfix lists.
1005
+ // e.g., 'currentEntities[]' has children if a path like 'currentEntities[].sha' exists.
1006
+ const postfixPrefixSet = new Set();
1007
+ for (const postfixPath of postfixKeys) {
1008
+ if (!postfixPath)
1009
+ continue;
1010
+ const parts = postfixPartsCache.get(postfixPath);
1011
+ for (let i = 1; i < parts.length; i++) {
1012
+ postfixPrefixSet.add(joinParenthesesAndArrays(parts.slice(0, i)));
1013
+ }
856
1014
  }
857
- if (!merged)
858
- continue;
859
- const schema = equivalentRoot.schemaRootPath.startsWith('signature[')
860
- ? merged.signatureSchema
861
- : merged.returnValueSchema;
862
- for (const [postfixPath, postfixValue] of Object.entries(esp.equivalentPostfixes)) {
863
- let relevantPostfix = postfixPath;
864
- if (equivalentRoot.postfix) {
865
- // Check if postfixPath starts with equivalentRoot.postfix at a path boundary.
866
- // Must ensure exact path part match - "entityCode" should NOT match "entity" prefix.
867
- // Valid: "entity.foo" starts with "entity" (boundary at '.')
868
- // Valid: "entity[0]" starts with "entity" (boundary at '[')
869
- // Invalid: "entityCode" starts with "entity" (no boundary, different property)
870
- if (!postfixPath.startsWith(equivalentRoot.postfix)) {
871
- continue;
872
- }
873
- // Additional check: ensure the match is at a path boundary
874
- const nextChar = postfixPath[equivalentRoot.postfix.length];
875
- if (nextChar !== undefined && nextChar !== '.' && nextChar !== '[') {
876
- // The postfixPath continues with more characters that aren't a path separator.
877
- // This means "entity" matched "entityCode" which is wrong - they're different properties.
878
- continue;
879
- }
880
- const postFixPathParts = splitOutsideParenthesesAndArrays(postfixPath);
881
- const equivalentRootPostFixParts = splitOutsideParenthesesAndArrays(equivalentRoot.postfix);
882
- relevantPostfix = joinParenthesesAndArrays(postFixPathParts.slice(equivalentRootPostFixParts.length));
1015
+ for (const postfixPath of postfixKeys) {
1016
+ if (postfixPath.endsWith('[]') && postfixPrefixSet.has(postfixPath)) {
1017
+ postfixesWithChildren.add(postfixPath);
883
1018
  }
884
- const newSchemaPath = joinParenthesesAndArrays([
885
- equivalentRoot.schemaRootPath,
886
- relevantPostfix,
887
- ]);
888
- // Skip paths that would go through a primitive type
889
- // e.g., if schema has 'entities[].scenarioCount': 'number', skip 'entities[].scenarioCount.sha'
890
- if (wouldGoThroughPrimitive(newSchemaPath, schema)) {
891
- transformationTracer.operation(rootScopeName, {
892
- operation: 'skipPrimitivePath',
893
- stage: 'merged',
894
- path: newSchemaPath,
895
- context: {
896
- reason: 'would go through primitive type',
897
- postfixValue,
898
- },
899
- });
900
- continue;
1019
+ }
1020
+ // Deduplicate equivalentRoots that would write to the same schema paths.
1021
+ // Roots with the same (function, schemaRootPath, postfix) are redundant.
1022
+ const seenRootKeys = new Set();
1023
+ const uniqueRoots = esp.equivalentRoots.filter((root) => {
1024
+ const key = `${root.function?.filePath ?? ''}::${root.function?.name ?? ''}::${root.schemaRootPath}::${root.postfix ?? ''}`;
1025
+ if (seenRootKeys.has(key))
1026
+ return false;
1027
+ seenRootKeys.add(key);
1028
+ return true;
1029
+ });
1030
+ for (const equivalentRoot of uniqueRoots) {
1031
+ checkDeadline();
1032
+ let merged;
1033
+ if (equivalentRoot.function) {
1034
+ merged = findOrCreateDependentSchemas(equivalentRoot.function);
901
1035
  }
902
- // Skip setting primitive type when there are child postfixes that indicate structure.
903
- // This prevents downgrading an object/array element to a primitive type.
904
- // Uses pre-computed postfixesWithChildren Set for O(1) lookup instead of O(n) iteration.
905
- const hasChildPostfixes = (relevantPostfix === '' || relevantPostfix.endsWith('[]')) &&
906
- postfixesWithChildren.has(postfixPath);
907
- if (PRIMITIVE_TYPES.has(postfixValue) && hasChildPostfixes) {
908
- continue;
1036
+ else {
1037
+ merged = mergedDataStructure;
909
1038
  }
910
- // Don't overwrite a more specific type with a less specific one
911
- // This can happen when nested roots share entries with their parent roots
912
- const existingType = schema[newSchemaPath];
913
- if (existingType) {
914
- // Don't overwrite a primitive type with 'object' or 'array'
915
- // e.g., if schema has 'entities[].scenarioCount': 'number', don't overwrite with 'object'
916
- if (PRIMITIVE_TYPES.has(existingType) &&
917
- (postfixValue === 'object' || postfixValue === 'array')) {
1039
+ if (!merged)
1040
+ continue;
1041
+ const schema = equivalentRoot.schemaRootPath.startsWith('signature[')
1042
+ ? merged.signatureSchema
1043
+ : merged.returnValueSchema;
1044
+ // Skip if this schema has already grown past the cap
1045
+ if (Object.keys(schema).length > SCHEMA_KEY_CAP)
1046
+ continue;
1047
+ for (const [postfixPath, postfixValue] of Object.entries(esp.equivalentPostfixes)) {
1048
+ checkDeadline();
1049
+ let relevantPostfix = postfixPath;
1050
+ if (equivalentRoot.postfix) {
1051
+ // Check if postfixPath starts with equivalentRoot.postfix at a path boundary.
1052
+ // Must ensure exact path part match - "entityCode" should NOT match "entity" prefix.
1053
+ // Valid: "entity.foo" starts with "entity" (boundary at '.')
1054
+ // Valid: "entity[0]" starts with "entity" (boundary at '[')
1055
+ // Invalid: "entityCode" starts with "entity" (no boundary, different property)
1056
+ if (!postfixPath.startsWith(equivalentRoot.postfix)) {
1057
+ continue;
1058
+ }
1059
+ // Additional check: ensure the match is at a path boundary
1060
+ const nextChar = postfixPath[equivalentRoot.postfix.length];
1061
+ if (nextChar !== undefined &&
1062
+ nextChar !== '.' &&
1063
+ nextChar !== '[') {
1064
+ // The postfixPath continues with more characters that aren't a path separator.
1065
+ // This means "entity" matched "entityCode" which is wrong - they're different properties.
1066
+ continue;
1067
+ }
1068
+ const postFixPathParts = postfixPartsCache.get(postfixPath) ??
1069
+ splitOutsideParenthesesAndArrays(postfixPath);
1070
+ // Cache equivalentRoot.postfix parts — same root reused across all postfixes
1071
+ if (!postfixPartsCache.has(equivalentRoot.postfix)) {
1072
+ postfixPartsCache.set(equivalentRoot.postfix, splitOutsideParenthesesAndArrays(equivalentRoot.postfix));
1073
+ }
1074
+ const equivalentRootPostFixParts = postfixPartsCache.get(equivalentRoot.postfix);
1075
+ relevantPostfix = joinParenthesesAndArrays(postFixPathParts.slice(equivalentRootPostFixParts.length));
1076
+ }
1077
+ const newSchemaPath = joinParenthesesAndArrays([
1078
+ equivalentRoot.schemaRootPath,
1079
+ relevantPostfix,
1080
+ ]);
1081
+ // Skip paths that would go through a primitive type
1082
+ // e.g., if schema has 'entities[].scenarioCount': 'number', skip 'entities[].scenarioCount.sha'
1083
+ if (wouldGoThroughPrimitive(newSchemaPath, schema)) {
918
1084
  transformationTracer.operation(rootScopeName, {
919
- operation: 'skipTypeDowngrade',
1085
+ operation: 'skipPrimitivePath',
920
1086
  stage: 'merged',
921
1087
  path: newSchemaPath,
922
1088
  context: {
923
- reason: 'would overwrite primitive with object/array',
924
- existingType,
925
- newType: postfixValue,
1089
+ reason: 'would go through primitive type',
1090
+ postfixValue,
926
1091
  },
927
1092
  });
928
1093
  continue;
929
1094
  }
930
- // Don't overwrite a complex/union type with a primitive
931
- // e.g., if schema has 'scenarios[]': 'Scenario | null', don't overwrite with 'string'
932
- if (!PRIMITIVE_TYPES.has(existingType) &&
933
- PRIMITIVE_TYPES.has(postfixValue)) {
934
- transformationTracer.operation(rootScopeName, {
935
- operation: 'skipTypeDowngrade',
936
- stage: 'merged',
937
- path: newSchemaPath,
938
- context: {
939
- reason: 'would overwrite complex type with primitive',
940
- existingType,
941
- newType: postfixValue,
942
- },
943
- });
1095
+ // Skip setting primitive type when there are child postfixes that indicate structure.
1096
+ // This prevents downgrading an object/array element to a primitive type.
1097
+ // Uses pre-computed postfixesWithChildren Set for O(1) lookup instead of O(n) iteration.
1098
+ const hasChildPostfixes = (relevantPostfix === '' || relevantPostfix.endsWith('[]')) &&
1099
+ postfixesWithChildren.has(postfixPath);
1100
+ if (PRIMITIVE_TYPES.has(postfixValue) && hasChildPostfixes) {
944
1101
  continue;
945
1102
  }
1103
+ // Don't overwrite a more specific type with a less specific one
1104
+ // This can happen when nested roots share entries with their parent roots
1105
+ const existingType = schema[newSchemaPath];
1106
+ if (existingType) {
1107
+ // Don't overwrite a primitive type with 'object' or 'array'
1108
+ // e.g., if schema has 'entities[].scenarioCount': 'number', don't overwrite with 'object'
1109
+ if (PRIMITIVE_TYPES.has(existingType) &&
1110
+ (postfixValue === 'object' || postfixValue === 'array')) {
1111
+ transformationTracer.operation(rootScopeName, {
1112
+ operation: 'skipTypeDowngrade',
1113
+ stage: 'merged',
1114
+ path: newSchemaPath,
1115
+ context: {
1116
+ reason: 'would overwrite primitive with object/array',
1117
+ existingType,
1118
+ newType: postfixValue,
1119
+ },
1120
+ });
1121
+ continue;
1122
+ }
1123
+ // Don't overwrite a complex/union type with a primitive
1124
+ // e.g., if schema has 'scenarios[]': 'Scenario | null', don't overwrite with 'string'
1125
+ if (!PRIMITIVE_TYPES.has(existingType) &&
1126
+ PRIMITIVE_TYPES.has(postfixValue)) {
1127
+ transformationTracer.operation(rootScopeName, {
1128
+ operation: 'skipTypeDowngrade',
1129
+ stage: 'merged',
1130
+ path: newSchemaPath,
1131
+ context: {
1132
+ reason: 'would overwrite complex type with primitive',
1133
+ existingType,
1134
+ newType: postfixValue,
1135
+ },
1136
+ });
1137
+ continue;
1138
+ }
1139
+ }
1140
+ // Log the successful postfix merge
1141
+ transformationTracer.operation(rootScopeName, {
1142
+ operation: 'mergePostfix',
1143
+ stage: 'merged',
1144
+ path: newSchemaPath,
1145
+ before: existingType,
1146
+ after: postfixValue,
1147
+ context: {
1148
+ schemaRootPath: equivalentRoot.schemaRootPath,
1149
+ postfix: relevantPostfix,
1150
+ dependency: equivalentRoot.function?.name,
1151
+ },
1152
+ });
1153
+ schema[newSchemaPath] = postfixValue;
946
1154
  }
947
- // Log the successful postfix merge
948
- transformationTracer.operation(rootScopeName, {
949
- operation: 'mergePostfix',
950
- stage: 'merged',
951
- path: newSchemaPath,
952
- before: existingType,
953
- after: postfixValue,
954
- context: {
955
- schemaRootPath: equivalentRoot.schemaRootPath,
956
- postfix: relevantPostfix,
957
- dependency: equivalentRoot.function?.name,
958
- },
959
- });
960
- schema[newSchemaPath] = postfixValue;
1155
+ schemasToClean.add(schema);
961
1156
  }
1157
+ }
1158
+ const postfixElapsed = Date.now() - mergeStartTime;
1159
+ // Batch-clean all modified schemas once (instead of once per root per ESP entry)
1160
+ for (const schema of schemasToClean) {
962
1161
  cleanSchema(schema, { stage: 'afterMergePostfix' });
963
1162
  }
964
- }
965
- // Propagate equivalency-derived attributes to generic function call variants.
966
- // When attributes are traced via equivalencies (e.g., fileComparisons from buildDataMap.signature[2]),
967
- // they get written to non-generic paths (returnValue.data.x or funcName().functionCallReturnValue.data.x).
968
- // If the ORIGINAL input schema has generic variants (funcName<T>().functionCallReturnValue.data),
969
- // we need to copy the attributes to those paths too.
970
- for (const filePath in mergedDataStructure.dependencySchemas) {
971
- for (const depName in mergedDataStructure.dependencySchemas[filePath]) {
972
- const depSchema = mergedDataStructure.dependencySchemas[filePath][depName];
973
- const returnValueSchema = depSchema.returnValueSchema;
974
- // Look at the ORIGINAL input dependencySchemas for generic variants,
975
- // since the merged schema may have lost them during equivalency processing
976
- const originalSchema = dependencySchemas?.[filePath]?.[depName];
977
- const schemaToSearchForGenericVariants = originalSchema?.returnValueSchema || returnValueSchema;
978
- // Find all unique generic variants of this function
979
- // e.g., useFetcher<BranchEntityDiffResult>() from useFetcher<BranchEntityDiffResult>().functionCallReturnValue.data
980
- const genericVariants = new Set();
981
- const genericRegex = new RegExp(`^${depName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}<[^>]+>\\(\\)`);
982
- for (const path in schemaToSearchForGenericVariants) {
983
- const match = path.match(genericRegex);
984
- if (match) {
985
- genericVariants.add(match[0]);
1163
+ const cleanElapsed = Date.now() - mergeStartTime;
1164
+ // Propagate equivalency-derived attributes to generic function call variants.
1165
+ // When attributes are traced via equivalencies (e.g., fileComparisons from buildDataMap.signature[2]),
1166
+ // they get written to non-generic paths (returnValue.data.x or funcName().functionCallReturnValue.data.x).
1167
+ // If the ORIGINAL input schema has generic variants (funcName<T>().functionCallReturnValue.data),
1168
+ // we need to copy the attributes to those paths too.
1169
+ for (const filePath in mergedDataStructure.dependencySchemas) {
1170
+ for (const depName in mergedDataStructure.dependencySchemas[filePath]) {
1171
+ const depSchema = mergedDataStructure.dependencySchemas[filePath][depName];
1172
+ const returnValueSchema = depSchema.returnValueSchema;
1173
+ // Look at the ORIGINAL input dependencySchemas for generic variants,
1174
+ // since the merged schema may have lost them during equivalency processing
1175
+ const originalSchema = dependencySchemas?.[filePath]?.[depName];
1176
+ const schemaToSearchForGenericVariants = originalSchema?.returnValueSchema || returnValueSchema;
1177
+ // Find all unique generic variants of this function
1178
+ // e.g., useFetcher<BranchEntityDiffResult>() from useFetcher<BranchEntityDiffResult>().functionCallReturnValue.data
1179
+ const genericVariants = new Set();
1180
+ const genericRegex = new RegExp(`^${depName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}<[^>]+>\\(\\)`);
1181
+ for (const path in schemaToSearchForGenericVariants) {
1182
+ checkDeadline();
1183
+ const match = path.match(genericRegex);
1184
+ if (match) {
1185
+ genericVariants.add(match[0]);
1186
+ }
986
1187
  }
987
- }
988
- if (genericVariants.size === 0)
989
- continue;
990
- // For each returnValue. path or non-generic function call path,
991
- // create corresponding paths for each generic variant
992
- const pathsToAdd = [];
993
- for (const path in returnValueSchema) {
994
- const value = returnValueSchema[path];
995
- // Handle returnValue. paths
996
- if (path.startsWith('returnValue.')) {
997
- const suffix = path.slice('returnValue.'.length);
998
- for (const genericVariant of genericVariants) {
999
- const genericPath = `${genericVariant}.functionCallReturnValue.${suffix}`;
1000
- if (!(genericPath in returnValueSchema)) {
1001
- pathsToAdd.push([genericPath, value]);
1188
+ if (genericVariants.size === 0)
1189
+ continue;
1190
+ // For each returnValue. path or non-generic function call path,
1191
+ // create corresponding paths for each generic variant
1192
+ const pathsToAdd = [];
1193
+ for (const path in returnValueSchema) {
1194
+ checkDeadline();
1195
+ const value = returnValueSchema[path];
1196
+ // Handle returnValue. paths
1197
+ if (path.startsWith('returnValue.')) {
1198
+ const suffix = path.slice('returnValue.'.length);
1199
+ for (const genericVariant of genericVariants) {
1200
+ const genericPath = `${genericVariant}.functionCallReturnValue.${suffix}`;
1201
+ if (!(genericPath in returnValueSchema)) {
1202
+ pathsToAdd.push([genericPath, value]);
1203
+ }
1002
1204
  }
1003
1205
  }
1004
- }
1005
- // Handle non-generic function call paths like depName().functionCallReturnValue.x
1006
- else if (path.startsWith(`${depName}().functionCallReturnValue.`)) {
1007
- const suffix = path.slice(`${depName}().functionCallReturnValue.`.length);
1008
- for (const genericVariant of genericVariants) {
1009
- const genericPath = `${genericVariant}.functionCallReturnValue.${suffix}`;
1010
- if (!(genericPath in returnValueSchema)) {
1011
- pathsToAdd.push([genericPath, value]);
1206
+ // Handle non-generic function call paths like depName().functionCallReturnValue.x
1207
+ else if (path.startsWith(`${depName}().functionCallReturnValue.`)) {
1208
+ const suffix = path.slice(`${depName}().functionCallReturnValue.`.length);
1209
+ for (const genericVariant of genericVariants) {
1210
+ const genericPath = `${genericVariant}.functionCallReturnValue.${suffix}`;
1211
+ if (!(genericPath in returnValueSchema)) {
1212
+ pathsToAdd.push([genericPath, value]);
1213
+ }
1012
1214
  }
1013
1215
  }
1014
1216
  }
1217
+ // Add the new generic variant paths
1218
+ for (const [path, value] of pathsToAdd) {
1219
+ returnValueSchema[path] = value;
1220
+ }
1015
1221
  }
1016
- // Add the new generic variant paths
1017
- for (const [path, value] of pathsToAdd) {
1018
- returnValueSchema[path] = value;
1019
- }
1020
- }
1021
- }
1022
- // For mocked dependencies: copy paths from dependencySchemas (usage info) and normalize
1023
- // returnValue. paths that were created by equivalency processing.
1024
- // This ensures all paths use the consistent functionName().functionCallReturnValue. format.
1025
- for (const dependency of importedExports) {
1026
- if (!dependency.isMocked)
1027
- continue;
1028
- const srcSchema = dependencySchemas?.[dependency.filePath]?.[dependency.name];
1029
- if (!srcSchema?.returnValueSchema)
1030
- continue;
1031
- const depSchema = findOrCreateDependentSchemas({
1032
- filePath: dependency.filePath,
1033
- name: dependency.name,
1034
- });
1035
- // First, normalize any returnValue paths that were written by equivalency processing
1036
- // to the standard functionName().functionCallReturnValue format.
1037
- // This includes both returnValue. (dot) and returnValue[ (array) paths.
1038
- const pathsToNormalize = [];
1039
- for (const path in depSchema.returnValueSchema) {
1040
- if (path === 'returnValue' ||
1041
- path.startsWith('returnValue.') ||
1042
- path.startsWith('returnValue[')) {
1043
- pathsToNormalize.push([path, depSchema.returnValueSchema[path]]);
1044
- }
1045
- }
1046
- for (const [path, value] of pathsToNormalize) {
1047
- delete depSchema.returnValueSchema[path];
1048
- let normalizedPath;
1049
- if (path === 'returnValue') {
1050
- normalizedPath = `${dependency.name}().functionCallReturnValue`;
1051
- }
1052
- else if (path.startsWith('returnValue.')) {
1053
- normalizedPath = path.replace(/^returnValue\./, `${dependency.name}().functionCallReturnValue.`);
1054
- }
1055
- else {
1056
- // path.startsWith('returnValue[')
1057
- // e.g., returnValue[] -> getOptions().functionCallReturnValue[]
1058
- // e.g., returnValue[].label -> getOptions().functionCallReturnValue[].label
1059
- normalizedPath = path.replace(/^returnValue/, `${dependency.name}().functionCallReturnValue`);
1060
- }
1061
- transformationTracer.operation(rootScopeName, {
1062
- operation: 'normalizeReturnValuePath',
1063
- stage: 'merged',
1064
- path: normalizedPath,
1065
- before: path,
1066
- after: normalizedPath,
1067
- context: { dependency: dependency.name, value },
1068
- });
1069
- depSchema.returnValueSchema[normalizedPath] = value;
1070
1222
  }
1071
- // Now copy paths from the source schema (dependencySchemas)
1072
- for (const path in srcSchema.returnValueSchema) {
1073
- const value = srcSchema.returnValueSchema[path];
1074
- // Normalize paths starting with 'returnValue' to use the standard format:
1075
- // 'returnValue.foo' -> 'dependencyName().functionCallReturnValue.foo'
1076
- // This ensures consistency across the codebase and allows constructMockCode
1077
- // and gatherDataForMocks to work correctly.
1078
- if (path === 'returnValue' || path.startsWith('returnValue.')) {
1079
- // Convert 'returnValue' -> 'name().functionCallReturnValue'
1080
- // Convert 'returnValue.foo' -> 'name().functionCallReturnValue.foo'
1081
- const normalizedPath = path === 'returnValue'
1082
- ? `${dependency.name}().functionCallReturnValue`
1083
- : path.replace(/^returnValue\./, `${dependency.name}().functionCallReturnValue.`);
1084
- // Always write srcSchema values - they take precedence over equivalency-derived values
1085
- depSchema.returnValueSchema[normalizedPath] = value;
1223
+ // For mocked dependencies: copy paths from dependencySchemas (usage info) and normalize
1224
+ // returnValue. paths that were created by equivalency processing.
1225
+ // This ensures all paths use the consistent functionName().functionCallReturnValue. format.
1226
+ for (const dependency of importedExports) {
1227
+ if (!dependency.isMocked)
1086
1228
  continue;
1087
- }
1088
- // Copy paths containing functionCallReturnValue (return value structures)
1089
- // These are needed for constructMockCode to build the proper mock data hierarchy
1090
- // Example: supabase.auth.getSession().functionCallReturnValue.data.session
1091
- if (path.includes('.functionCallReturnValue')) {
1092
- // Always write srcSchema values - they take precedence over equivalency-derived values
1093
- depSchema.returnValueSchema[path] = value;
1229
+ const srcSchema = dependencySchemas?.[dependency.filePath]?.[dependency.name];
1230
+ if (!srcSchema?.returnValueSchema)
1094
1231
  continue;
1232
+ const depSchema = findOrCreateDependentSchemas({
1233
+ filePath: dependency.filePath,
1234
+ name: dependency.name,
1235
+ });
1236
+ // First, normalize any returnValue paths that were written by equivalency processing
1237
+ // to the standard functionName().functionCallReturnValue format.
1238
+ // This includes both returnValue. (dot) and returnValue[ (array) paths.
1239
+ const pathsToNormalize = [];
1240
+ for (const path in depSchema.returnValueSchema) {
1241
+ checkDeadline();
1242
+ if (path === 'returnValue' ||
1243
+ path.startsWith('returnValue.') ||
1244
+ path.startsWith('returnValue[')) {
1245
+ pathsToNormalize.push([path, depSchema.returnValueSchema[path]]);
1246
+ }
1095
1247
  }
1096
- // Copy function-typed paths that end with () (are function calls)
1097
- // These include:
1098
- // - Function stubs without functionCallReturnValue (like onAuthStateChange)
1099
- // - Function markers with async-function type (like getSession(): async-function)
1100
- // which are needed for constructMockCode to know to generate async functions
1101
- // Skip paths starting with 'returnValue' - they were already handled above
1102
- if (['function', 'async-function'].includes(value) &&
1103
- path.endsWith(')') &&
1104
- !path.startsWith('returnValue')) {
1105
- if (!(path in depSchema.returnValueSchema)) {
1106
- depSchema.returnValueSchema[path] = value;
1248
+ for (const [path, value] of pathsToNormalize) {
1249
+ delete depSchema.returnValueSchema[path];
1250
+ let normalizedPath;
1251
+ if (path === 'returnValue') {
1252
+ normalizedPath = `${dependency.name}().functionCallReturnValue`;
1253
+ }
1254
+ else if (path.startsWith('returnValue.')) {
1255
+ normalizedPath = path.replace(/^returnValue\./, `${dependency.name}().functionCallReturnValue.`);
1256
+ }
1257
+ else {
1258
+ // path.startsWith('returnValue[')
1259
+ // e.g., returnValue[] -> getOptions().functionCallReturnValue[]
1260
+ // e.g., returnValue[].label -> getOptions().functionCallReturnValue[].label
1261
+ normalizedPath = path.replace(/^returnValue/, `${dependency.name}().functionCallReturnValue`);
1107
1262
  }
1263
+ transformationTracer.operation(rootScopeName, {
1264
+ operation: 'normalizeReturnValuePath',
1265
+ stage: 'merged',
1266
+ path: normalizedPath,
1267
+ before: path,
1268
+ after: normalizedPath,
1269
+ context: { dependency: dependency.name, value },
1270
+ });
1271
+ depSchema.returnValueSchema[normalizedPath] = value;
1108
1272
  }
1109
- // Copy object-typed paths for chained API access patterns (like trpc.customer.getCustomersByOrg)
1110
- // These intermediate paths are needed for constructMockCode to build the nested mock structure.
1111
- // Example: for trpc.customer.getCustomersByOrg.useQuery().functionCallReturnValue.data,
1112
- // we need 'trpc', 'trpc.customer', 'trpc.customer.getCustomersByOrg' all typed as 'object'.
1113
- // Skip paths starting with 'returnValue' - they were already handled above
1114
- //
1115
- // EXCEPTION: For function-style dependencies like getSupabase(), skip intermediate object
1116
- // paths like 'getSupabase().auth' that are just property access after a function call.
1117
- // These aren't needed because constructMockCode can infer the structure from the actual
1118
- // function call paths like 'getSupabase().auth.getUser()'. We only need object paths
1119
- // for object-style dependencies like 'supabase.auth' where the dependency itself is an object.
1120
- if (value === 'object' && !path.startsWith('returnValue')) {
1121
- // Check if this is a function-style dependency (path starts with name() or name<T>())
1122
- const isFunctionStyleDependency = path.startsWith(`${dependency.name}()`) ||
1123
- path.match(new RegExp(`^${dependency.name}<[^>]+>\\(\\)`));
1124
- // For function-style dependencies, skip intermediate object paths
1125
- // Only keep object paths that are within functionCallReturnValue
1126
- if (isFunctionStyleDependency &&
1127
- !path.includes('.functionCallReturnValue')) {
1273
+ // Now copy paths from the source schema (dependencySchemas)
1274
+ for (const path in srcSchema.returnValueSchema) {
1275
+ checkDeadline();
1276
+ const value = srcSchema.returnValueSchema[path];
1277
+ // Normalize paths starting with 'returnValue' to use the standard format:
1278
+ // 'returnValue.foo' -> 'dependencyName().functionCallReturnValue.foo'
1279
+ // This ensures consistency across the codebase and allows constructMockCode
1280
+ // and gatherDataForMocks to work correctly.
1281
+ if (path === 'returnValue' || path.startsWith('returnValue.')) {
1282
+ // Convert 'returnValue' -> 'name().functionCallReturnValue'
1283
+ // Convert 'returnValue.foo' -> 'name().functionCallReturnValue.foo'
1284
+ const normalizedPath = path === 'returnValue'
1285
+ ? `${dependency.name}().functionCallReturnValue`
1286
+ : path.replace(/^returnValue\./, `${dependency.name}().functionCallReturnValue.`);
1287
+ // Always write srcSchema values - they take precedence over equivalency-derived values
1288
+ depSchema.returnValueSchema[normalizedPath] = value;
1128
1289
  continue;
1129
1290
  }
1130
- if (!(path in depSchema.returnValueSchema)) {
1291
+ // Copy paths containing functionCallReturnValue (return value structures)
1292
+ // These are needed for constructMockCode to build the proper mock data hierarchy
1293
+ // Example: supabase.auth.getSession().functionCallReturnValue.data.session
1294
+ if (path.includes('.functionCallReturnValue')) {
1295
+ // Always write srcSchema values - they take precedence over equivalency-derived values
1131
1296
  depSchema.returnValueSchema[path] = value;
1132
- }
1133
- }
1134
- }
1135
- cleanSchema(depSchema.returnValueSchema, {
1136
- stage: 'afterMockedDependencyMerge',
1137
- dependency: dependency.name,
1138
- });
1139
- // Pull signature requirements from downstream functions into the mocked return value.
1140
- // When a mocked function's return flows into another function's signature (via usageEquivalencies),
1141
- // we need to include that function's signature requirements in the mock.
1142
- //
1143
- // Example: fromE5() returns a currency object that flows to calculateTotalPrice(price, quantity).
1144
- // calculateTotalPrice's signatureSchema shows signature[0].multiply() is required.
1145
- // We need to add multiply() to fromE5's mock return value.
1146
- const usageEquivalencies = srcSchema.usageEquivalencies ?? {};
1147
- for (const [returnPath, equivalencies] of Object.entries(usageEquivalencies)) {
1148
- // Only process return value paths (functionCallReturnValue)
1149
- if (!returnPath.includes('.functionCallReturnValue'))
1150
- continue;
1151
- for (const equiv of equivalencies) {
1152
- // Check if this equivalency points to a signature path
1153
- const signatureMatch = equiv.schemaPath.match(/\.signature\[(\d+)\]$/);
1154
- if (!signatureMatch)
1155
1297
  continue;
1156
- const targetFunctionName = cleanFunctionName(equiv.scopeNodeName);
1157
- const signatureIndex = signatureMatch[1];
1158
- // Look up the target function's analysis to get its signature requirements
1159
- // First try dependentAnalyses, then dependencySchemas
1160
- let targetSignatureSchema;
1161
- // Check dependentAnalyses first (has the full merged analysis)
1162
- for (const depFilePath in dependentAnalyses) {
1163
- const analysis = dependentAnalyses[depFilePath]?.[targetFunctionName];
1164
- if (analysis?.metadata?.mergedDataStructure?.signatureSchema) {
1165
- targetSignatureSchema =
1166
- analysis.metadata.mergedDataStructure.signatureSchema;
1167
- break;
1168
- }
1169
1298
  }
1170
- // Fallback to dependencySchemas if not found
1171
- if (!targetSignatureSchema) {
1172
- for (const depFilePath in dependencySchemas) {
1173
- const schema = dependencySchemas[depFilePath]?.[targetFunctionName];
1174
- if (schema?.signatureSchema) {
1175
- targetSignatureSchema = schema.signatureSchema;
1176
- break;
1177
- }
1299
+ // Copy function-typed paths that end with () (are function calls)
1300
+ // These include:
1301
+ // - Function stubs without functionCallReturnValue (like onAuthStateChange)
1302
+ // - Function markers with async-function type (like getSession(): async-function)
1303
+ // which are needed for constructMockCode to know to generate async functions
1304
+ // Skip paths starting with 'returnValue' - they were already handled above
1305
+ if (['function', 'async-function'].includes(value) &&
1306
+ path.endsWith(')') &&
1307
+ !path.startsWith('returnValue')) {
1308
+ if (!(path in depSchema.returnValueSchema)) {
1309
+ depSchema.returnValueSchema[path] = value;
1178
1310
  }
1179
1311
  }
1180
- if (!targetSignatureSchema)
1181
- continue;
1182
- // Find all paths in the target's signatureSchema that extend from signature[N]
1183
- // e.g., signature[0].multiply(quantity) -> .multiply(quantity)
1184
- const signaturePrefix = `signature[${signatureIndex}]`;
1185
- for (const [sigPath, sigType] of Object.entries(targetSignatureSchema)) {
1186
- if (!sigPath.startsWith(signaturePrefix))
1312
+ // Copy object-typed paths for chained API access patterns (like trpc.customer.getCustomersByOrg)
1313
+ // These intermediate paths are needed for constructMockCode to build the nested mock structure.
1314
+ // Example: for trpc.customer.getCustomersByOrg.useQuery().functionCallReturnValue.data,
1315
+ // we need 'trpc', 'trpc.customer', 'trpc.customer.getCustomersByOrg' all typed as 'object'.
1316
+ // Skip paths starting with 'returnValue' - they were already handled above
1317
+ //
1318
+ // EXCEPTION: For function-style dependencies like getSupabase(), skip intermediate object
1319
+ // paths like 'getSupabase().auth' that are just property access after a function call.
1320
+ // These aren't needed because constructMockCode can infer the structure from the actual
1321
+ // function call paths like 'getSupabase().auth.getUser()'. We only need object paths
1322
+ // for object-style dependencies like 'supabase.auth' where the dependency itself is an object.
1323
+ if (value === 'object' && !path.startsWith('returnValue')) {
1324
+ // Check if this is a function-style dependency (path starts with name() or name<T>())
1325
+ const isFunctionStyleDependency = path.startsWith(`${dependency.name}()`) ||
1326
+ path.match(new RegExp(`^${dependency.name}<[^>]+>\\(\\)`));
1327
+ // For function-style dependencies, skip intermediate object paths
1328
+ // Only keep object paths that are within functionCallReturnValue
1329
+ if (isFunctionStyleDependency &&
1330
+ !path.includes('.functionCallReturnValue')) {
1187
1331
  continue;
1188
- // Skip the base signature[N] path itself - we only want the method/property extensions
1189
- if (sigPath === signaturePrefix)
1190
- continue;
1191
- // Extract the suffix after signature[N] (e.g., ".multiply(quantity)")
1192
- const suffix = sigPath.slice(signaturePrefix.length);
1193
- // Build the path for the mocked return value
1194
- // e.g., fromE5(priceE5).functionCallReturnValue.multiply(quantity)
1195
- const returnValuePath = returnPath + suffix;
1196
- // Add to the mocked dependency's return value schema if not already present
1197
- if (!(returnValuePath in depSchema.returnValueSchema)) {
1198
- depSchema.returnValueSchema[returnValuePath] = sigType;
1332
+ }
1333
+ if (!(path in depSchema.returnValueSchema)) {
1334
+ depSchema.returnValueSchema[path] = value;
1199
1335
  }
1200
1336
  }
1201
1337
  }
1202
- }
1203
- cleanSchema(depSchema.returnValueSchema, {
1204
- stage: 'afterSignatureRequirementsMerge',
1205
- dependency: dependency.name,
1206
- });
1207
- }
1208
- // Process the input dependencySchemas FIRST (before child dependentAnalyses).
1209
- // This ensures the parent entity's direct usage of dependencies takes precedence.
1210
- // When both parent and child use the same dependency (e.g., useLoaderData),
1211
- // the parent's schema paths are preserved, and child's paths are merged in later.
1212
- //
1213
- // Some dependencies (like .d.ts type declaration files) may not have:
1214
- // - Equivalencies with the root scope
1215
- // - A dependent analysis (they're just type declarations)
1216
- // - Be marked as mocked
1217
- // Without this, their schemas would be lost entirely.
1218
- for (const filePath in dependencySchemas) {
1219
- for (const name in dependencySchemas[filePath]) {
1220
- const srcSchema = dependencySchemas[filePath][name];
1221
- if (!srcSchema)
1222
- continue;
1223
- // Skip mocked dependencies - they were already processed above with path normalization
1224
- if (mockedDependencies.has(`${filePath}::${name}`)) {
1225
- continue;
1226
- }
1227
- // Check if this dependency was already processed by equivalencies
1228
- const existingSchema = mergedDataStructure.dependencySchemas[filePath]?.[name];
1229
- // Only add if no existing schema (equivalencies didn't process it)
1230
- if (!existingSchema) {
1231
- const depSchema = findOrCreateDependentSchemas({ filePath, name });
1232
- for (const path in srcSchema.returnValueSchema) {
1233
- depSchema.returnValueSchema[path] = srcSchema.returnValueSchema[path];
1234
- }
1235
- for (const path in srcSchema.signatureSchema) {
1236
- depSchema.signatureSchema[path] = srcSchema.signatureSchema[path];
1237
- }
1238
- // Clean known object functions (like String.prototype.replace, Array.prototype.map)
1239
- // from the copied schema. Without this, method call paths on primitives like
1240
- // "projectSlug.replace(...)" would cause convertDotNotation to create nested
1241
- // object structures instead of preserving the primitive type.
1242
- cleanSchema(depSchema.returnValueSchema, {
1243
- stage: 'afterDependencySchemaCopy',
1244
- filePath,
1245
- dependency: name,
1246
- });
1247
- }
1248
- // TYPE REFINEMENT: Check if dependentAnalyses has a more specific type for this dependency.
1249
- // When a parent passes `entity.filePath` (string | undefined) to a child component
1250
- // that requires `filePath: string`, we should use the child's more specific type.
1251
- // This prevents mock data from having undefined values for required props.
1338
+ cleanSchema(depSchema.returnValueSchema, {
1339
+ stage: 'afterMockedDependencyMerge',
1340
+ dependency: dependency.name,
1341
+ });
1342
+ // Pull signature requirements from downstream functions into the mocked return value.
1343
+ // When a mocked function's return flows into another function's signature (via usageEquivalencies),
1344
+ // we need to include that function's signature requirements in the mock.
1252
1345
  //
1253
- // This runs REGARDLESS of whether equivalencies already processed the schema,
1254
- // because equivalencies copy the parent's type (string | undefined), not the child's
1255
- // required type (string).
1256
- const depSchema = findOrCreateDependentSchemas({ filePath, name });
1257
- const childAnalysis = dependentAnalyses[filePath]?.[name];
1258
- const childSignatureSchema = childAnalysis?.metadata?.mergedDataStructure?.signatureSchema;
1259
- if (childSignatureSchema) {
1260
- for (const path in depSchema.signatureSchema) {
1261
- const parentType = depSchema.signatureSchema[path];
1262
- const childType = childSignatureSchema[path];
1263
- if (parentType && childType) {
1264
- // Check if parent has optional type and child has required type
1265
- const parentIsOptional = parentType.includes('| undefined') ||
1266
- parentType.includes('| null');
1267
- const childIsOptional = childType.includes('| undefined') || childType.includes('| null');
1268
- // If child requires a more specific type (not optional), use it
1269
- if (parentIsOptional && !childIsOptional) {
1270
- depSchema.signatureSchema[path] = childType;
1346
+ // Example: fromE5() returns a currency object that flows to calculateTotalPrice(price, quantity).
1347
+ // calculateTotalPrice's signatureSchema shows signature[0].multiply() is required.
1348
+ // We need to add multiply() to fromE5's mock return value.
1349
+ const usageEquivalencies = srcSchema.usageEquivalencies ?? {};
1350
+ for (const [returnPath, equivalencies] of Object.entries(usageEquivalencies)) {
1351
+ // Only process return value paths (functionCallReturnValue)
1352
+ if (!returnPath.includes('.functionCallReturnValue'))
1353
+ continue;
1354
+ for (const equiv of equivalencies) {
1355
+ // Check if this equivalency points to a signature path
1356
+ const signatureMatch = equiv.schemaPath.match(/\.signature\[(\d+)\]$/);
1357
+ if (!signatureMatch)
1358
+ continue;
1359
+ const targetFunctionName = cleanFunctionName(equiv.scopeNodeName);
1360
+ const signatureIndex = signatureMatch[1];
1361
+ // Look up the target function's analysis to get its signature requirements
1362
+ // First try dependentAnalyses, then dependencySchemas
1363
+ let targetSignatureSchema;
1364
+ // Check dependentAnalyses first (has the full merged analysis)
1365
+ for (const depFilePath in dependentAnalyses) {
1366
+ const analysis = dependentAnalyses[depFilePath]?.[targetFunctionName];
1367
+ if (analysis?.metadata?.mergedDataStructure?.signatureSchema) {
1368
+ targetSignatureSchema =
1369
+ analysis.metadata.mergedDataStructure.signatureSchema;
1370
+ break;
1371
+ }
1372
+ }
1373
+ // Fallback to dependencySchemas if not found
1374
+ if (!targetSignatureSchema) {
1375
+ for (const depFilePath in dependencySchemas) {
1376
+ const schema = dependencySchemas[depFilePath]?.[targetFunctionName];
1377
+ if (schema?.signatureSchema) {
1378
+ targetSignatureSchema = schema.signatureSchema;
1379
+ break;
1380
+ }
1381
+ }
1382
+ }
1383
+ if (!targetSignatureSchema)
1384
+ continue;
1385
+ // Find all paths in the target's signatureSchema that extend from signature[N]
1386
+ // e.g., signature[0].multiply(quantity) -> .multiply(quantity)
1387
+ const signaturePrefix = `signature[${signatureIndex}]`;
1388
+ for (const [sigPath, sigType] of Object.entries(targetSignatureSchema)) {
1389
+ if (!sigPath.startsWith(signaturePrefix))
1390
+ continue;
1391
+ // Skip the base signature[N] path itself - we only want the method/property extensions
1392
+ if (sigPath === signaturePrefix)
1393
+ continue;
1394
+ // Extract the suffix after signature[N] (e.g., ".multiply(quantity)")
1395
+ const suffix = sigPath.slice(signaturePrefix.length);
1396
+ // Build the path for the mocked return value
1397
+ // e.g., fromE5(priceE5).functionCallReturnValue.multiply(quantity)
1398
+ const returnValuePath = returnPath + suffix;
1399
+ // Add to the mocked dependency's return value schema if not already present
1400
+ if (!(returnValuePath in depSchema.returnValueSchema)) {
1401
+ depSchema.returnValueSchema[returnValuePath] = sigType;
1271
1402
  }
1272
1403
  }
1273
1404
  }
1274
1405
  }
1275
- // For functions with multiple different type parameters, also create separate entries
1276
- // for each type-parameterized variant. This allows gatherDataForMocks to look up
1277
- // the specific schema for each call signature.
1278
- // This runs regardless of whether the base entry already existed, since we need
1279
- // the separate variant entries for proper schema lookup.
1280
- const baseName = cleanFunctionName(name);
1281
- if (functionsWithMultipleTypeParams.has(baseName)) {
1282
- // Find all unique type-parameterized call signatures in the schema
1283
- const typeParamVariants = new Set();
1284
- for (const path of Object.keys(srcSchema.returnValueSchema)) {
1285
- const parts = splitOutsideParenthesesAndArrays(path);
1286
- if (parts.length > 0 &&
1287
- parts[0].includes('<') &&
1288
- parts[0].endsWith(')')) {
1289
- typeParamVariants.add(parts[0]);
1290
- }
1406
+ cleanSchema(depSchema.returnValueSchema, {
1407
+ stage: 'afterSignatureRequirementsMerge',
1408
+ dependency: dependency.name,
1409
+ });
1410
+ }
1411
+ // Process the input dependencySchemas FIRST (before child dependentAnalyses).
1412
+ // This ensures the parent entity's direct usage of dependencies takes precedence.
1413
+ // When both parent and child use the same dependency (e.g., useLoaderData),
1414
+ // the parent's schema paths are preserved, and child's paths are merged in later.
1415
+ //
1416
+ // Some dependencies (like .d.ts type declaration files) may not have:
1417
+ // - Equivalencies with the root scope
1418
+ // - A dependent analysis (they're just type declarations)
1419
+ // - Be marked as mocked
1420
+ // Without this, their schemas would be lost entirely.
1421
+ for (const filePath in dependencySchemas) {
1422
+ for (const name in dependencySchemas[filePath]) {
1423
+ const srcSchema = dependencySchemas[filePath][name];
1424
+ if (!srcSchema)
1425
+ continue;
1426
+ // Skip mocked dependencies - they were already processed above with path normalization
1427
+ if (mockedDependencies.has(`${filePath}::${name}`)) {
1428
+ continue;
1291
1429
  }
1292
- // Create a separate entry for each type-parameterized variant
1293
- for (const variant of typeParamVariants) {
1294
- const variantSchema = findOrCreateDependentSchemas({
1295
- filePath,
1296
- name: variant,
1297
- });
1298
- // Copy only paths that belong to this variant
1430
+ // Check if this dependency was already processed by equivalencies
1431
+ const existingSchema = mergedDataStructure.dependencySchemas[filePath]?.[name];
1432
+ // Only add if no existing schema (equivalencies didn't process it)
1433
+ if (!existingSchema) {
1434
+ const depSchema = findOrCreateDependentSchemas({ filePath, name });
1299
1435
  for (const path in srcSchema.returnValueSchema) {
1300
- if (path.startsWith(variant)) {
1301
- variantSchema.returnValueSchema[path] =
1302
- srcSchema.returnValueSchema[path];
1303
- }
1436
+ checkDeadline();
1437
+ depSchema.returnValueSchema[path] =
1438
+ srcSchema.returnValueSchema[path];
1439
+ }
1440
+ for (const path in srcSchema.signatureSchema) {
1441
+ checkDeadline();
1442
+ depSchema.signatureSchema[path] = srcSchema.signatureSchema[path];
1304
1443
  }
1305
- cleanSchema(variantSchema.returnValueSchema, {
1306
- stage: 'afterTypeVariantCopy',
1444
+ // Clean known object functions (like String.prototype.replace, Array.prototype.map)
1445
+ // from the copied schema. Without this, method call paths on primitives like
1446
+ // "projectSlug.replace(...)" would cause convertDotNotation to create nested
1447
+ // object structures instead of preserving the primitive type.
1448
+ cleanSchema(depSchema.returnValueSchema, {
1449
+ stage: 'afterDependencySchemaCopy',
1307
1450
  filePath,
1308
1451
  dependency: name,
1309
- variant,
1310
1452
  });
1311
1453
  }
1312
- }
1313
- }
1314
- }
1315
- // Ensure ALL dependencies from dependentAnalyses are included in dependencySchemas,
1316
- // even if they have no equivalencies with the root scope.
1317
- // This preserves nested functionCallReturnValue paths that would otherwise be lost.
1318
- // EXCEPT: Skip mocked dependencies - we don't want their internal implementation details.
1319
- for (const filePath in dependentAnalyses) {
1320
- for (const name in dependentAnalyses[filePath]) {
1321
- const dependentMergedDataStructure = dependentAnalyses[filePath][name].metadata?.mergedDataStructure;
1322
- if (!dependentMergedDataStructure)
1323
- continue;
1324
- const isMocked = mockedDependencies.has(`${filePath}::${name}`);
1325
- // For mocked dependencies: ONLY copy nested dependencySchemas (skip internal implementation)
1326
- // For non-mocked dependencies: copy everything (signature, returnValue, and nested dependencySchemas)
1327
- if (!isMocked) {
1328
- // Create the dependency schema entry if it doesn't exist
1454
+ // TYPE REFINEMENT: Check if dependentAnalyses has a more specific type for this dependency.
1455
+ // When a parent passes `entity.filePath` (string | undefined) to a child component
1456
+ // that requires `filePath: string`, we should use the child's more specific type.
1457
+ // This prevents mock data from having undefined values for required props.
1458
+ //
1459
+ // This runs REGARDLESS of whether equivalencies already processed the schema,
1460
+ // because equivalencies copy the parent's type (string | undefined), not the child's
1461
+ // required type (string).
1329
1462
  const depSchema = findOrCreateDependentSchemas({ filePath, name });
1330
- // Copy over all paths from the dependent's returnValueSchema
1331
- // Only add paths that don't already exist (don't overwrite values set by equivalencies)
1332
- for (const path in dependentMergedDataStructure.returnValueSchema) {
1333
- const translatedPath = translatePath(path, name);
1334
- if (!(translatedPath in depSchema.returnValueSchema)) {
1335
- depSchema.returnValueSchema[translatedPath] =
1336
- dependentMergedDataStructure.returnValueSchema[path];
1463
+ const childAnalysis = dependentAnalyses[filePath]?.[name];
1464
+ const childSignatureSchema = childAnalysis?.metadata?.mergedDataStructure?.signatureSchema;
1465
+ if (childSignatureSchema) {
1466
+ for (const path in depSchema.signatureSchema) {
1467
+ checkDeadline();
1468
+ const parentType = depSchema.signatureSchema[path];
1469
+ const childType = childSignatureSchema[path];
1470
+ if (parentType && childType) {
1471
+ // Check if parent has optional type and child has required type
1472
+ const parentIsOptional = parentType.includes('| undefined') ||
1473
+ parentType.includes('| null');
1474
+ const childIsOptional = childType.includes('| undefined') ||
1475
+ childType.includes('| null');
1476
+ // If child requires a more specific type (not optional), use it
1477
+ if (parentIsOptional && !childIsOptional) {
1478
+ depSchema.signatureSchema[path] = childType;
1479
+ }
1480
+ }
1337
1481
  }
1338
1482
  }
1339
- // Copy over signature schema as well
1340
- for (const path in dependentMergedDataStructure.signatureSchema) {
1341
- const translatedPath = translatePath(path, name);
1342
- if (!(translatedPath in depSchema.signatureSchema)) {
1343
- depSchema.signatureSchema[translatedPath] =
1344
- dependentMergedDataStructure.signatureSchema[path];
1483
+ // For functions with multiple different type parameters, also create separate entries
1484
+ // for each type-parameterized variant. This allows gatherDataForMocks to look up
1485
+ // the specific schema for each call signature.
1486
+ // This runs regardless of whether the base entry already existed, since we need
1487
+ // the separate variant entries for proper schema lookup.
1488
+ const baseName = cleanFunctionName(name);
1489
+ if (functionsWithMultipleTypeParams.has(baseName)) {
1490
+ // Find all unique type-parameterized call signatures in the schema
1491
+ const typeParamVariants = new Set();
1492
+ for (const path of Object.keys(srcSchema.returnValueSchema)) {
1493
+ const parts = splitOutsideParenthesesAndArrays(path);
1494
+ if (parts.length > 0 &&
1495
+ parts[0].includes('<') &&
1496
+ parts[0].endsWith(')')) {
1497
+ typeParamVariants.add(parts[0]);
1498
+ }
1345
1499
  }
1346
- }
1347
- }
1348
- // Copy nested dependencySchemas for ALL entities (including mocked ones)
1349
- // This represents what dependencies THIS entity uses, not its internal implementation
1350
- if (dependentMergedDataStructure.dependencySchemas) {
1351
- for (const depFilePath in dependentMergedDataStructure.dependencySchemas) {
1352
- for (const depName in dependentMergedDataStructure.dependencySchemas[depFilePath]) {
1353
- const nestedDepSchema = dependentMergedDataStructure.dependencySchemas[depFilePath][depName];
1354
- const targetDepSchema = findOrCreateDependentSchemas({
1355
- filePath: depFilePath,
1356
- name: depName,
1500
+ // Create a separate entry for each type-parameterized variant
1501
+ for (const variant of typeParamVariants) {
1502
+ const variantSchema = findOrCreateDependentSchemas({
1503
+ filePath,
1504
+ name: variant,
1357
1505
  });
1358
- // Merge in the nested dependency schemas
1359
- for (const path in nestedDepSchema.returnValueSchema) {
1360
- if (!(path in targetDepSchema.returnValueSchema)) {
1361
- const value = nestedDepSchema.returnValueSchema[path];
1362
- targetDepSchema.returnValueSchema[path] = value;
1506
+ // Copy only paths that belong to this variant
1507
+ for (const path in srcSchema.returnValueSchema) {
1508
+ checkDeadline();
1509
+ if (path.startsWith(variant)) {
1510
+ variantSchema.returnValueSchema[path] =
1511
+ srcSchema.returnValueSchema[path];
1363
1512
  }
1364
1513
  }
1365
- for (const path in nestedDepSchema.signatureSchema) {
1366
- if (!(path in targetDepSchema.signatureSchema)) {
1367
- targetDepSchema.signatureSchema[path] =
1368
- nestedDepSchema.signatureSchema[path];
1514
+ cleanSchema(variantSchema.returnValueSchema, {
1515
+ stage: 'afterTypeVariantCopy',
1516
+ filePath,
1517
+ dependency: name,
1518
+ variant,
1519
+ });
1520
+ }
1521
+ }
1522
+ }
1523
+ }
1524
+ // Ensure ALL dependencies from dependentAnalyses are included in dependencySchemas,
1525
+ // even if they have no equivalencies with the root scope.
1526
+ // This preserves nested functionCallReturnValue paths that would otherwise be lost.
1527
+ // EXCEPT: Skip mocked dependencies - we don't want their internal implementation details.
1528
+ for (const filePath in dependentAnalyses) {
1529
+ for (const name in dependentAnalyses[filePath]) {
1530
+ checkDeadline();
1531
+ const dependentMergedDataStructure = dependentAnalyses[filePath][name].metadata?.mergedDataStructure;
1532
+ if (!dependentMergedDataStructure)
1533
+ continue;
1534
+ const isMocked = mockedDependencies.has(`${filePath}::${name}`);
1535
+ // For mocked dependencies: ONLY copy nested dependencySchemas (skip internal implementation)
1536
+ // For non-mocked dependencies: copy everything (signature, returnValue, and nested dependencySchemas)
1537
+ if (!isMocked) {
1538
+ // Create the dependency schema entry if it doesn't exist
1539
+ const depSchema = findOrCreateDependentSchemas({ filePath, name });
1540
+ // Copy over paths from the dependent's returnValueSchema.
1541
+ // Only add paths that don't already exist (don't overwrite values set by equivalencies).
1542
+ // Skip if either source or target exceeds the cap — copying 2,531 paths from
1543
+ // ArticleTable with translatePath on each takes ~1.5s for one entity.
1544
+ const srcRetSize = Object.keys(dependentMergedDataStructure.returnValueSchema || {}).length;
1545
+ if (srcRetSize > SCHEMA_KEY_CAP ||
1546
+ Object.keys(depSchema.returnValueSchema).length > SCHEMA_KEY_CAP)
1547
+ continue;
1548
+ for (const path in dependentMergedDataStructure.returnValueSchema) {
1549
+ // Fast path: only call translatePath when the path starts with the
1550
+ // dependency name (e.g., "ArticleTable().functionCallReturnValue.x").
1551
+ // Most paths start with "returnValue" or "signature" and don't need translation.
1552
+ const translatedPath = path.startsWith(name)
1553
+ ? translatePath(path, name)
1554
+ : path;
1555
+ if (!(translatedPath in depSchema.returnValueSchema)) {
1556
+ depSchema.returnValueSchema[translatedPath] =
1557
+ dependentMergedDataStructure.returnValueSchema[path];
1558
+ }
1559
+ }
1560
+ // Copy over signature schema as well
1561
+ for (const path in dependentMergedDataStructure.signatureSchema) {
1562
+ const translatedPath = path.startsWith(name)
1563
+ ? translatePath(path, name)
1564
+ : path;
1565
+ if (!(translatedPath in depSchema.signatureSchema)) {
1566
+ depSchema.signatureSchema[translatedPath] =
1567
+ dependentMergedDataStructure.signatureSchema[path];
1568
+ }
1569
+ }
1570
+ }
1571
+ // Copy nested dependencySchemas for ALL entities (including mocked ones)
1572
+ // This represents what dependencies THIS entity uses, not its internal implementation
1573
+ if (dependentMergedDataStructure.dependencySchemas) {
1574
+ for (const depFilePath in dependentMergedDataStructure.dependencySchemas) {
1575
+ for (const depName in dependentMergedDataStructure
1576
+ .dependencySchemas[depFilePath]) {
1577
+ const nestedDepSchema = dependentMergedDataStructure.dependencySchemas[depFilePath][depName];
1578
+ const targetDepSchema = findOrCreateDependentSchemas({
1579
+ filePath: depFilePath,
1580
+ name: depName,
1581
+ });
1582
+ // Merge in the nested dependency schemas
1583
+ for (const path in nestedDepSchema.returnValueSchema) {
1584
+ checkDeadline();
1585
+ if (!(path in targetDepSchema.returnValueSchema)) {
1586
+ const value = nestedDepSchema.returnValueSchema[path];
1587
+ targetDepSchema.returnValueSchema[path] = value;
1588
+ }
1589
+ }
1590
+ for (const path in nestedDepSchema.signatureSchema) {
1591
+ checkDeadline();
1592
+ if (!(path in targetDepSchema.signatureSchema)) {
1593
+ targetDepSchema.signatureSchema[path] =
1594
+ nestedDepSchema.signatureSchema[path];
1595
+ }
1369
1596
  }
1370
1597
  }
1371
1598
  }
1372
1599
  }
1373
1600
  }
1374
1601
  }
1602
+ const totalElapsed = Date.now() - mergeStartTime;
1603
+ const retKeys = Object.keys(mergedDataStructure.returnValueSchema).length;
1604
+ // Only log phase breakdown for slow merges (>2s)
1605
+ if (totalElapsed > 2000) {
1606
+ console.log(`CodeYam Log Level 2: ${rootScopeName} merge phases: gather=${gatherElapsed}ms mergeESP=${mergeEspElapsed - gatherElapsed}ms postfix=${postfixElapsed - mergeEspElapsed}ms clean=${cleanElapsed - postfixElapsed}ms depCopy=${totalElapsed - cleanElapsed}ms total=${totalElapsed}ms ret=${retKeys}`);
1607
+ }
1608
+ return mergedDataStructure;
1609
+ }
1610
+ catch (error) {
1611
+ if (error instanceof DataStructureTimeoutError) {
1612
+ // Return partial results instead of propagating the timeout.
1613
+ // By this point, mergedDataStructure has valid data from completed phases
1614
+ // (gather + mergeESP complete in <1s, postfix/clean/depCopy may be partial).
1615
+ const retKeys = Object.keys(mergedDataStructure.returnValueSchema).length;
1616
+ console.log(`CodeYam Log Level 1: ${rootScopeName} merge timed out — returning partial results (${retKeys} ret keys, ${Math.round((Date.now() - mergeStartTime) / 1000)}s)`);
1617
+ mergedDataStructure.timedOut = true;
1618
+ return mergedDataStructure;
1619
+ }
1620
+ throw error;
1375
1621
  }
1376
- return mergedDataStructure;
1377
1622
  }
1378
1623
  //# sourceMappingURL=mergeInDependentDataStructure.js.map