@codeyam/codeyam-cli 0.1.0-staging.73a4bf4 → 0.1.0-staging.78c1cad

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