@codeyam/codeyam-cli 0.1.0-staging.09652b8 → 0.1.0-staging.28f73cf

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 (287) hide show
  1. package/analyzer-template/.build-info.json +7 -7
  2. package/analyzer-template/log.txt +3 -3
  3. package/analyzer-template/package.json +7 -6
  4. package/analyzer-template/packages/ai/index.ts +2 -0
  5. package/analyzer-template/packages/ai/package.json +2 -2
  6. package/analyzer-template/packages/ai/src/lib/analyzeScope.ts +24 -0
  7. package/analyzer-template/packages/ai/src/lib/astScopes/processExpression.ts +14 -0
  8. package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +1402 -546
  9. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/FunctionCallManager.ts +138 -0
  10. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.ts +1 -1
  11. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.ts +139 -0
  12. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/DebugTracer.ts +224 -0
  13. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/PathManager.ts +203 -0
  14. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/README.md +294 -0
  15. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.ts +161 -0
  16. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/VisitedTracker.ts +235 -0
  17. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.ts +2 -0
  18. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/selectBestValue.ts +70 -0
  19. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/uniqueIdUtils.ts +113 -0
  20. package/analyzer-template/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.ts +36 -0
  21. package/analyzer-template/packages/ai/src/lib/generateEntityKeyAttributes.ts +32 -8
  22. package/analyzer-template/packages/ai/src/lib/getConditionalUsagesFromCode.ts +27 -6
  23. package/analyzer-template/packages/ai/src/lib/promptGenerators/gatherAttributesMap.ts +42 -4
  24. package/analyzer-template/packages/ai/src/lib/worker/SerializableDataStructure.ts +39 -0
  25. package/analyzer-template/packages/analyze/src/lib/FileAnalyzer.ts +18 -6
  26. package/analyzer-template/packages/analyze/src/lib/asts/nodes/index.ts +2 -1
  27. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.ts +8 -10
  28. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +6 -1
  29. package/analyzer-template/packages/analyze/src/lib/files/analyze/gatherEntityMap.ts +8 -6
  30. package/analyzer-template/packages/analyze/src/lib/files/analyze/trackEntityCircularDependencies.ts +5 -13
  31. package/analyzer-template/packages/analyze/src/lib/files/analyzeChange.ts +34 -15
  32. package/analyzer-template/packages/analyze/src/lib/files/analyzeEntity.ts +17 -3
  33. package/analyzer-template/packages/analyze/src/lib/files/analyzeInitial.ts +35 -16
  34. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +7 -1
  35. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.ts +9 -1
  36. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarioData.ts +6 -1
  37. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarios.ts +9 -1
  38. package/analyzer-template/packages/aws/dist/src/lib/s3/getPresignedUrl.d.ts +23 -0
  39. package/analyzer-template/packages/aws/dist/src/lib/s3/getPresignedUrl.d.ts.map +1 -0
  40. package/analyzer-template/packages/aws/dist/src/lib/s3/getPresignedUrl.js +30 -0
  41. package/analyzer-template/packages/aws/dist/src/lib/s3/getPresignedUrl.js.map +1 -0
  42. package/analyzer-template/packages/aws/package.json +5 -4
  43. package/analyzer-template/packages/aws/s3/index.ts +4 -0
  44. package/analyzer-template/packages/aws/src/lib/s3/getPresignedUrl.ts +62 -0
  45. package/analyzer-template/packages/generate/src/lib/scenarioComponent.ts +6 -3
  46. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponent.d.ts.map +1 -1
  47. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponent.js +5 -3
  48. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponent.js.map +1 -1
  49. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/db.d.ts +2 -0
  50. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/db.d.ts.map +1 -1
  51. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/db.js +3 -0
  52. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/db.js.map +1 -1
  53. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tableRelations.d.ts +2 -0
  54. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tableRelations.d.ts.map +1 -1
  55. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/debugReportsTable.d.ts +37 -0
  56. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/debugReportsTable.d.ts.map +1 -0
  57. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/debugReportsTable.js +27 -0
  58. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/debugReportsTable.js.map +1 -0
  59. package/analyzer-template/packages/github/dist/utils/index.d.ts +1 -0
  60. package/analyzer-template/packages/github/dist/utils/index.d.ts.map +1 -1
  61. package/analyzer-template/packages/github/dist/utils/index.js +1 -0
  62. package/analyzer-template/packages/github/dist/utils/index.js.map +1 -1
  63. package/analyzer-template/packages/github/dist/utils/src/lib/Semaphore.d.ts +25 -0
  64. package/analyzer-template/packages/github/dist/utils/src/lib/Semaphore.d.ts.map +1 -0
  65. package/analyzer-template/packages/github/dist/utils/src/lib/Semaphore.js +40 -0
  66. package/analyzer-template/packages/github/dist/utils/src/lib/Semaphore.js.map +1 -0
  67. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getRemixRoutePath.d.ts.map +1 -1
  68. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getRemixRoutePath.js +2 -1
  69. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getRemixRoutePath.js.map +1 -1
  70. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.d.ts.map +1 -1
  71. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.js +1 -0
  72. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.js.map +1 -1
  73. package/analyzer-template/packages/supabase/src/lib/kysely/db.ts +6 -0
  74. package/analyzer-template/packages/supabase/src/lib/kysely/tableRelations.ts +3 -0
  75. package/analyzer-template/packages/supabase/src/lib/kysely/tables/debugReportsTable.ts +61 -0
  76. package/analyzer-template/packages/utils/dist/utils/index.d.ts +1 -0
  77. package/analyzer-template/packages/utils/dist/utils/index.d.ts.map +1 -1
  78. package/analyzer-template/packages/utils/dist/utils/index.js +1 -0
  79. package/analyzer-template/packages/utils/dist/utils/index.js.map +1 -1
  80. package/analyzer-template/packages/utils/dist/utils/src/lib/Semaphore.d.ts +25 -0
  81. package/analyzer-template/packages/utils/dist/utils/src/lib/Semaphore.d.ts.map +1 -0
  82. package/analyzer-template/packages/utils/dist/utils/src/lib/Semaphore.js +40 -0
  83. package/analyzer-template/packages/utils/dist/utils/src/lib/Semaphore.js.map +1 -0
  84. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getRemixRoutePath.d.ts.map +1 -1
  85. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getRemixRoutePath.js +2 -1
  86. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getRemixRoutePath.js.map +1 -1
  87. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.d.ts.map +1 -1
  88. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.js +1 -0
  89. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.js.map +1 -1
  90. package/analyzer-template/packages/utils/index.ts +1 -0
  91. package/analyzer-template/packages/utils/src/lib/Semaphore.ts +42 -0
  92. package/analyzer-template/packages/utils/src/lib/frameworks/getRemixRoutePath.ts +2 -1
  93. package/analyzer-template/packages/utils/src/lib/frameworks/remixRouteFileNameToRoute.ts +1 -0
  94. package/analyzer-template/project/constructMockCode.ts +170 -6
  95. package/analyzer-template/project/reconcileMockDataKeys.ts +13 -0
  96. package/analyzer-template/project/start.ts +1 -11
  97. package/analyzer-template/project/writeMockDataTsx.ts +32 -1
  98. package/analyzer-template/project/writeScenarioComponents.ts +164 -18
  99. package/analyzer-template/project/writeUniversalMocks.ts +66 -8
  100. package/background/src/lib/virtualized/project/constructMockCode.js +158 -7
  101. package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
  102. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js +12 -0
  103. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js.map +1 -1
  104. package/background/src/lib/virtualized/project/start.js +1 -8
  105. package/background/src/lib/virtualized/project/start.js.map +1 -1
  106. package/background/src/lib/virtualized/project/writeMockDataTsx.js +25 -1
  107. package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
  108. package/background/src/lib/virtualized/project/writeScenarioComponents.js +129 -17
  109. package/background/src/lib/virtualized/project/writeScenarioComponents.js.map +1 -1
  110. package/background/src/lib/virtualized/project/writeUniversalMocks.js +56 -7
  111. package/background/src/lib/virtualized/project/writeUniversalMocks.js.map +1 -1
  112. package/codeyam-cli/src/cli.js +6 -0
  113. package/codeyam-cli/src/cli.js.map +1 -1
  114. package/codeyam-cli/src/codeyam-cli.js +0 -0
  115. package/codeyam-cli/src/commands/debug.js +221 -0
  116. package/codeyam-cli/src/commands/debug.js.map +1 -0
  117. package/codeyam-cli/src/commands/report.js +102 -0
  118. package/codeyam-cli/src/commands/report.js.map +1 -0
  119. package/codeyam-cli/src/commands/setup-sandbox.js +164 -0
  120. package/codeyam-cli/src/commands/setup-sandbox.js.map +1 -0
  121. package/codeyam-cli/src/utils/__tests__/cleanupAnalysisFiles.test.js +6 -6
  122. package/codeyam-cli/src/utils/__tests__/cleanupAnalysisFiles.test.js.map +1 -1
  123. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js +8 -0
  124. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js.map +1 -1
  125. package/codeyam-cli/src/utils/analyzer.js +30 -0
  126. package/codeyam-cli/src/utils/analyzer.js.map +1 -1
  127. package/codeyam-cli/src/utils/cleanupAnalysisFiles.js +2 -2
  128. package/codeyam-cli/src/utils/cleanupAnalysisFiles.js.map +1 -1
  129. package/codeyam-cli/src/utils/generateReport.js +219 -0
  130. package/codeyam-cli/src/utils/generateReport.js.map +1 -0
  131. package/codeyam-cli/src/utils/install-skills.js +7 -0
  132. package/codeyam-cli/src/utils/install-skills.js.map +1 -1
  133. package/codeyam-cli/src/utils/queue/__tests__/job.pidTracking.test.js +1 -0
  134. package/codeyam-cli/src/utils/queue/__tests__/job.pidTracking.test.js.map +1 -1
  135. package/codeyam-cli/src/utils/queue/job.js +5 -1
  136. package/codeyam-cli/src/utils/queue/job.js.map +1 -1
  137. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +4 -0
  138. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
  139. package/codeyam-cli/src/webserver/app/lib/database.js +50 -2
  140. package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
  141. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-D5ZHFomX.js +1 -0
  142. package/codeyam-cli/src/webserver/build/client/assets/{InteractivePreview-CDnfNKKQ.js → InteractivePreview-XDSzQLOY.js} +2 -2
  143. package/codeyam-cli/src/webserver/build/client/assets/{LibraryFunctionPreview-DUS-3h7I.js → LibraryFunctionPreview-BYVx9KFp.js} +1 -1
  144. package/codeyam-cli/src/webserver/build/client/assets/{LogViewer-TJzDQku1.js → LogViewer-CRcT5fOZ.js} +1 -1
  145. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-BORLgi0X.js +1 -0
  146. package/codeyam-cli/src/webserver/build/client/assets/{SafeScreenshot-BgdlWM6p.js → SafeScreenshot-Bual6h18.js} +1 -1
  147. package/codeyam-cli/src/webserver/build/client/assets/ScenarioPreview-Bi-YUMa-.js +6 -0
  148. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-4D2vLLJz.js +5 -0
  149. package/codeyam-cli/src/webserver/build/client/assets/_index-BC200mfN.js +1 -0
  150. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-CxvZPkCv.js +10 -0
  151. package/codeyam-cli/src/webserver/build/client/assets/api.generate-report-l0sNRNKZ.js +1 -0
  152. package/codeyam-cli/src/webserver/build/client/assets/chart-column-B8fb6wnw.js +1 -0
  153. package/codeyam-cli/src/webserver/build/client/assets/{chunk-WWGJGFF6-DvL0YqDJ.js → chunk-WWGJGFF6-De6i8FUT.js} +1 -1
  154. package/codeyam-cli/src/webserver/build/client/assets/circle-alert-IdsgAK39.js +1 -0
  155. package/codeyam-cli/src/webserver/build/client/assets/circle-check-BACUUf75.js +1 -0
  156. package/codeyam-cli/src/webserver/build/client/assets/clock-vWeoCemX.js +1 -0
  157. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-CS7XDrKv.js +1 -0
  158. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-DIOEw_3i.js +1 -0
  159. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-3bYjyojg.js → entity._sha._-8Els_3Wb.js} +10 -10
  160. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha_.create-scenario-DtfwpN9J.js → entity._sha_.create-scenario-C3FZJx1w.js} +1 -1
  161. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-YJz_igar.js +5 -0
  162. package/codeyam-cli/src/webserver/build/client/assets/entityStatus-BEqj2qBy.js +1 -0
  163. package/codeyam-cli/src/webserver/build/client/assets/entry.client-DiP0q291.js +5 -0
  164. package/codeyam-cli/src/webserver/build/client/assets/file-text-LM0mgxXE.js +1 -0
  165. package/codeyam-cli/src/webserver/build/client/assets/files-Dxh9CcaV.js +1 -0
  166. package/codeyam-cli/src/webserver/build/client/assets/{git-WoKohOtW.js → git-BXmqrWCH.js} +10 -10
  167. package/codeyam-cli/src/webserver/build/client/assets/globals-BGS74ED-.css +1 -0
  168. package/codeyam-cli/src/webserver/build/client/assets/html2canvas-pro.esm-XQCGvadH.js +5 -0
  169. package/codeyam-cli/src/webserver/build/client/assets/{index-Vvbl94Xc.js → index-D-zYbzFZ.js} +2 -2
  170. package/codeyam-cli/src/webserver/build/client/assets/loader-circle-BXPKbHEb.js +1 -0
  171. package/codeyam-cli/src/webserver/build/client/assets/manifest-1af162d4.js +1 -0
  172. package/codeyam-cli/src/webserver/build/client/assets/root-DB7VgjCY.js +16 -0
  173. package/codeyam-cli/src/webserver/build/client/assets/settings-5zF_GOcS.js +1 -0
  174. package/codeyam-cli/src/webserver/build/client/assets/{settings-LuiJ1UIm.js → settings-Dc4MlMpK.js} +1 -1
  175. package/codeyam-cli/src/webserver/build/client/assets/simulations-BQ-02-jB.js +1 -0
  176. package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-D7k-ArFa.js +1 -0
  177. package/codeyam-cli/src/webserver/build/client/assets/{useLastLogLine-CpUcCv1V.js → useLastLogLine-AlhS7g5F.js} +1 -1
  178. package/codeyam-cli/src/webserver/build/client/assets/useToast-Ddo4UQv7.js +1 -0
  179. package/codeyam-cli/src/webserver/build/client/assets/zap-_jw-9DCp.js +1 -0
  180. package/codeyam-cli/src/webserver/build/server/assets/{index-DzbqTxoN.js → index-D4JpXSIO.js} +1 -1
  181. package/codeyam-cli/src/webserver/build/server/assets/server-build-vwbN7n65.js +169 -0
  182. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  183. package/codeyam-cli/src/webserver/build-info.json +5 -5
  184. package/codeyam-cli/templates/codeyam-setup-skill.md +65 -85
  185. package/codeyam-cli/templates/debug-command.md +125 -0
  186. package/package.json +4 -6
  187. package/packages/ai/index.js +1 -1
  188. package/packages/ai/index.js.map +1 -1
  189. package/packages/ai/src/lib/analyzeScope.js +13 -0
  190. package/packages/ai/src/lib/analyzeScope.js.map +1 -1
  191. package/packages/ai/src/lib/astScopes/processExpression.js +12 -0
  192. package/packages/ai/src/lib/astScopes/processExpression.js.map +1 -1
  193. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +1023 -405
  194. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
  195. package/packages/ai/src/lib/dataStructure/equivalencyManagers/FunctionCallManager.js +137 -1
  196. package/packages/ai/src/lib/dataStructure/equivalencyManagers/FunctionCallManager.js.map +1 -1
  197. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js +1 -1
  198. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js.map +1 -1
  199. package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js +112 -0
  200. package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js.map +1 -0
  201. package/packages/ai/src/lib/dataStructure/helpers/DebugTracer.js +176 -0
  202. package/packages/ai/src/lib/dataStructure/helpers/DebugTracer.js.map +1 -0
  203. package/packages/ai/src/lib/dataStructure/helpers/PathManager.js +178 -0
  204. package/packages/ai/src/lib/dataStructure/helpers/PathManager.js.map +1 -0
  205. package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js +138 -0
  206. package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js.map +1 -0
  207. package/packages/ai/src/lib/dataStructure/helpers/VisitedTracker.js +199 -0
  208. package/packages/ai/src/lib/dataStructure/helpers/VisitedTracker.js.map +1 -0
  209. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js +2 -0
  210. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js.map +1 -1
  211. package/packages/ai/src/lib/dataStructure/helpers/selectBestValue.js +62 -0
  212. package/packages/ai/src/lib/dataStructure/helpers/selectBestValue.js.map +1 -0
  213. package/packages/ai/src/lib/dataStructure/helpers/uniqueIdUtils.js +90 -0
  214. package/packages/ai/src/lib/dataStructure/helpers/uniqueIdUtils.js.map +1 -0
  215. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js +22 -0
  216. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js.map +1 -1
  217. package/packages/ai/src/lib/generateEntityKeyAttributes.js +32 -8
  218. package/packages/ai/src/lib/generateEntityKeyAttributes.js.map +1 -1
  219. package/packages/ai/src/lib/getConditionalUsagesFromCode.js +13 -8
  220. package/packages/ai/src/lib/getConditionalUsagesFromCode.js.map +1 -1
  221. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js +36 -3
  222. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js.map +1 -1
  223. package/packages/ai/src/lib/worker/SerializableDataStructure.js +7 -0
  224. package/packages/ai/src/lib/worker/SerializableDataStructure.js.map +1 -1
  225. package/packages/analyze/src/lib/FileAnalyzer.js +17 -5
  226. package/packages/analyze/src/lib/FileAnalyzer.js.map +1 -1
  227. package/packages/analyze/src/lib/asts/nodes/index.js +2 -1
  228. package/packages/analyze/src/lib/asts/nodes/index.js.map +1 -1
  229. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +6 -8
  230. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
  231. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +5 -1
  232. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
  233. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js +8 -2
  234. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js.map +1 -1
  235. package/packages/analyze/src/lib/files/analyze/trackEntityCircularDependencies.js +5 -8
  236. package/packages/analyze/src/lib/files/analyze/trackEntityCircularDependencies.js.map +1 -1
  237. package/packages/analyze/src/lib/files/analyzeChange.js +21 -9
  238. package/packages/analyze/src/lib/files/analyzeChange.js.map +1 -1
  239. package/packages/analyze/src/lib/files/analyzeEntity.js +10 -4
  240. package/packages/analyze/src/lib/files/analyzeEntity.js.map +1 -1
  241. package/packages/analyze/src/lib/files/analyzeInitial.js +21 -9
  242. package/packages/analyze/src/lib/files/analyzeInitial.js.map +1 -1
  243. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +6 -1
  244. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
  245. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js +9 -1
  246. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js.map +1 -1
  247. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js +5 -1
  248. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js.map +1 -1
  249. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js +9 -1
  250. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js.map +1 -1
  251. package/packages/generate/src/lib/scenarioComponent.js +5 -3
  252. package/packages/generate/src/lib/scenarioComponent.js.map +1 -1
  253. package/packages/supabase/src/lib/kysely/db.js +3 -0
  254. package/packages/supabase/src/lib/kysely/db.js.map +1 -1
  255. package/packages/supabase/src/lib/kysely/tables/debugReportsTable.js +27 -0
  256. package/packages/supabase/src/lib/kysely/tables/debugReportsTable.js.map +1 -0
  257. package/packages/utils/index.js +1 -0
  258. package/packages/utils/index.js.map +1 -1
  259. package/packages/utils/src/lib/Semaphore.js +40 -0
  260. package/packages/utils/src/lib/Semaphore.js.map +1 -0
  261. package/packages/utils/src/lib/frameworks/getRemixRoutePath.js +2 -1
  262. package/packages/utils/src/lib/frameworks/getRemixRoutePath.js.map +1 -1
  263. package/packages/utils/src/lib/frameworks/remixRouteFileNameToRoute.js +1 -0
  264. package/packages/utils/src/lib/frameworks/remixRouteFileNameToRoute.js.map +1 -1
  265. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-B9Sf8e9w.js +0 -1
  266. package/codeyam-cli/src/webserver/build/client/assets/ScenarioPreview-Bl6GY-OE.js +0 -6
  267. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-BDq8RX50.js +0 -5
  268. package/codeyam-cli/src/webserver/build/client/assets/_index-Bh3y3Wsl.js +0 -1
  269. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-tq7Bl6-t.js +0 -10
  270. package/codeyam-cli/src/webserver/build/client/assets/chart-column-q9_nHfwv.js +0 -1
  271. package/codeyam-cli/src/webserver/build/client/assets/circle-alert-CKMpA1v_.js +0 -1
  272. package/codeyam-cli/src/webserver/build/client/assets/clock-Wnfog8Qw.js +0 -1
  273. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-C_ixaqqh.js +0 -1
  274. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-QecTs_sq.js +0 -5
  275. package/codeyam-cli/src/webserver/build/client/assets/entry.client-hnkEgHrC.js +0 -5
  276. package/codeyam-cli/src/webserver/build/client/assets/file-text-CvCVdKLW.js +0 -1
  277. package/codeyam-cli/src/webserver/build/client/assets/files-DgUCYhbd.js +0 -1
  278. package/codeyam-cli/src/webserver/build/client/assets/globals-DZfbt0u5.css +0 -1
  279. package/codeyam-cli/src/webserver/build/client/assets/loader-circle-Bxm63UxG.js +0 -1
  280. package/codeyam-cli/src/webserver/build/client/assets/manifest-c90b8608.js +0 -1
  281. package/codeyam-cli/src/webserver/build/client/assets/root-DrVZQamX.js +0 -16
  282. package/codeyam-cli/src/webserver/build/client/assets/search-CJkk16Ct.js +0 -1
  283. package/codeyam-cli/src/webserver/build/client/assets/settings-ConzHeiL.js +0 -1
  284. package/codeyam-cli/src/webserver/build/client/assets/simulations-B9LRwAej.js +0 -1
  285. package/codeyam-cli/src/webserver/build/client/assets/useToast-DOxmMaSg.js +0 -1
  286. package/codeyam-cli/src/webserver/build/client/assets/zap-D5R1FAcH.js +0 -1
  287. package/codeyam-cli/src/webserver/build/server/assets/server-build-DGGis3OZ.js +0 -166
@@ -1,36 +1,104 @@
1
- /* ScopeDataStructure
1
+ /**
2
+ * ScopeDataStructure
2
3
  *
3
- * The ScopeDateStructure takes the output of the ASTAnalyzer and merges
4
- * all scopes to determine a complete schema for the function.
4
+ * The core engine for CodeYam's static analysis. Takes AST analysis output and
5
+ * determines the complete data schema for a function by tracking how data flows
6
+ * through the code.
5
7
  *
6
- * It does two passes through all scopes.
8
+ * ## High-Level Architecture
7
9
  *
8
- * The first establishes equivalencies,
9
- * such as implicit parent scope -> nested child scope equivalencies.
10
+ * ```
11
+ * ┌─────────────────┐ ┌─────────────────────────────────────────────┐
12
+ * │ AST Analyzer │────▶│ ScopeDataStructure │
13
+ * │ (per-scope) │ │ │
14
+ * └─────────────────┘ │ Phase 1: Discovery (onlyEquivalencies) │
15
+ * │ ├─ Process each scope's analysis │
16
+ * │ ├─ Build equivalency relationships │
17
+ * │ └─ Track nested scope hierarchy │
18
+ * │ │
19
+ * │ Phase 2: Schema Building │
20
+ * │ ├─ Follow all equivalencies │
21
+ * │ ├─ Build complete schemas at data sources │
22
+ * │ └─ Populate equivalencyDatabase │
23
+ * └─────────────────────────────────────────────┘
24
+ * │
25
+ * ▼
26
+ * ┌─────────────────────────────────────────────┐
27
+ * │ Output │
28
+ * │ • Function signature schemas │
29
+ * │ • Return value types │
30
+ * │ • External API call schemas │
31
+ * │ • Data flow (source → usage) mappings │
32
+ * └─────────────────────────────────────────────┘
33
+ * ```
10
34
  *
11
- * The second pass follows all equivalencies to build up a complete schema at the
12
- * source of the data (either the function's signature arguments or an external
13
- * API call made from within the function). While following the equivalencies the
14
- * second pass populates the equivalencyDatabase which tracks all equivalent values
15
- * and provides easy access to determine where data comes from and where it is used
16
- * to call external functions. This makes it possible to combine schemas between
17
- * functions to create a complete schema for a dependency tree.
35
+ * ## Key Concepts
18
36
  *
19
- * There are a number of getter functions that provide easy access to signature data
20
- * and return values for the function being analyzed and any function called from the
21
- * function being analyzed.
37
+ * ### Equivalencies
38
+ * When code assigns one variable to another (`const user = props.user`), we create
39
+ * an "equivalency" linking the two paths. Following these links lets us trace data
40
+ * back to its source (function arguments or API returns).
41
+ *
42
+ * ### Schema Paths
43
+ * Dot-separated strings describing data structure:
44
+ * - `signature[0].user.id` - First arg's user.id property
45
+ * - `items[].name` - name property of array elements
46
+ * - `functionCallReturnValue(fetch).data` - Return from fetch() call
47
+ *
48
+ * ### Two-Phase Processing
49
+ * 1. **Phase 1 (Discovery)**: `onlyEquivalencies = true`
50
+ * - Processes scopes, builds equivalency graph
51
+ * - Does NOT populate schemas yet
52
+ *
53
+ * 2. **Phase 2 (Schema Building)**: `captureCompleteSchema()`
54
+ * - Follows equivalencies to build complete schemas
55
+ * - Populates `equivalencyDatabase` for source/usage queries
56
+ *
57
+ * ## Key Methods (Entry Points)
58
+ *
59
+ * - `constructor(scopeName, scopeText, managers, scopeAnalysis)` - Initialize with root scope
60
+ * - `addScopeAnalysis(scopeName, text, analysis)` - Add nested scope
61
+ * - `captureCompleteSchema()` - Trigger Phase 2 processing
62
+ * - `getSchema({scopeName})` - Get schema for a scope
63
+ * - `getFunctionSignature({functionName})` - Get function signature schema
64
+ * - `getSourceEquivalencies()` - Find where data comes from
65
+ * - `getUsageEquivalencies()` - Find where data is used
66
+ *
67
+ * ## Debugging Tips
68
+ *
69
+ * - Enable metrics: `addToSchemaCallCount`, `followEquivalenciesCallCount`
70
+ * - Check `scopeNode.equivalencies` for raw equivalency data
71
+ * - Use `getEquivalenciesDatabaseEntry(scope, path)` to trace a specific path
72
+ * - The `visitedTracker` prevents infinite loops - if data is missing, check if
73
+ * it was already visited with a different value
74
+ *
75
+ * ## Related Files
76
+ *
77
+ * - `helpers/` - Extracted utility modules (PathManager, VisitedTracker, etc.)
78
+ * - `equivalencyManagers/` - Plugins that create equivalencies from AST patterns
79
+ * - `helpers/README.md` - Overview of the helper module architecture
22
80
  */
23
81
 
24
82
  import { ScopeAnalysis } from '~codeyam/types';
25
- import {
26
- joinParenthesesAndArrays,
27
- splitOutsideParenthesesAndArrays,
28
- } from '../splitOutsideParentheses';
29
83
  import { EquivalencyManager } from './equivalencyManagers/EquivalencyManager';
30
84
  import fillInSchemaGapsAndUnknowns from './helpers/fillInSchemaGapsAndUnknowns';
31
85
  import ensureSchemaConsistency from './helpers/ensureSchemaConsistency';
32
- import cleanOutBoundary from '../cleanOutBoundary';
33
86
  import cleanPath from './helpers/cleanPath';
87
+ import { PathManager } from './helpers/PathManager';
88
+ import {
89
+ uniqueId,
90
+ uniqueScopeVariables,
91
+ uniqueScopeAndPaths,
92
+ } from './helpers/uniqueIdUtils';
93
+ import selectBestValue from './helpers/selectBestValue';
94
+ import { VisitedTracker } from './helpers/VisitedTracker';
95
+ import { DebugTracer } from './helpers/DebugTracer';
96
+ import { BatchSchemaProcessor } from './helpers/BatchSchemaProcessor';
97
+ import {
98
+ ScopeTreeManager,
99
+ ROOT_SCOPE_NAME,
100
+ ScopeTreeNode,
101
+ } from './helpers/ScopeTreeManager';
34
102
  import cleanScopeNodeName from './helpers/cleanScopeNodeName';
35
103
  import getFunctionCallRoot from './helpers/getFunctionCallRoot';
36
104
  import cleanPathOfNonTransformingFunctions from './helpers/cleanPathOfNonTransformingFunctions';
@@ -42,38 +110,10 @@ import type {
42
110
  SerializableScopeVariable,
43
111
  } from '../worker/SerializableDataStructure';
44
112
 
45
- // import { appendFileSync } from 'node:fs';
46
- // function writeEquivalencyToFile(
47
- // scopeNodeName: string,
48
- // path: string,
49
- // equivalentScopeNodeName: string,
50
- // equivalentPath: string,
51
- // newEquivalentPath: string,
52
- // equivalencyReason: string,
53
- // ) {
54
- // if ([
55
- // 'original equivalency'
56
- // ].includes(equivalencyReason)) {
57
- // return
58
- // }
59
-
60
- // appendFileSync('equivalencies.txt', '\n\n');
61
- // appendFileSync('equivalencies.txt',
62
- // JSON.stringify(
63
- // {
64
- // newEquivalentPath,
65
- // scopeNodeName,
66
- // path,
67
- // equivalentScopeNodeName,
68
- // equivalentPath,
69
- // equivalencyReason,
70
- // },
71
- // null,
72
- // 2,
73
- // ),
74
- // );
75
- // }
76
-
113
+ /**
114
+ * ScopeInfo represents a function scope discovered during AST analysis.
115
+ * Contains the raw analysis data before it's processed into a ScopeNode.
116
+ */
77
117
  export interface ScopeInfo {
78
118
  name: string;
79
119
  text: string;
@@ -87,46 +127,94 @@ export interface ScopeInfo {
87
127
  analysis?: any;
88
128
  }
89
129
 
130
+ /**
131
+ * ScopeNode is the processed representation of a function scope.
132
+ * Contains the schema and equivalencies built during analysis.
133
+ *
134
+ * Key fields:
135
+ * - `schema`: Map of path → type (e.g., `{ 'user.id': 'string' }`)
136
+ * - `equivalencies`: Map of path → equivalent paths in other scopes
137
+ * - `functionCalls`: External function calls made from this scope
138
+ */
90
139
  export interface ScopeNode {
140
+ /** Unique scope name, may include suffix like `____cyScope0A` for disambiguation */
91
141
  name: string;
142
+ /** Path from root scope to this scope (e.g., ['outer', 'inner']) */
92
143
  tree: string[];
144
+ /** Original source code text of the function */
93
145
  text: string;
146
+ /** Raw AST analysis output */
94
147
  analysis: ScopeAnalysis;
148
+ /** True if this is a static class method */
95
149
  isStatic?: boolean;
150
+ /** The built schema: maps schema paths to type values */
96
151
  schema: Record<string, string>;
97
- equivalencies: Record<string, ScopeVariable[]>; // Trace data attributes to the source of the data
152
+ /** Maps local paths to equivalent paths in other scopes (for tracing data flow) */
153
+ equivalencies: Record<string, ScopeVariable[]>;
154
+ /** External function calls made from this scope */
98
155
  functionCalls: FunctionCallInfo[];
156
+ /** True if this scope is a function definition (vs. class/module) */
99
157
  isFunctionDefinition: boolean;
100
- instantiatedVariables?: string[]; // Variables instantiated in this scope
101
- parentInstantiatedVariables?: string[]; // Variables instantiated in the parent scope that are available in this scope
158
+ /** Variables created in this scope (e.g., via `const x = ...`) */
159
+ instantiatedVariables?: string[];
160
+ /** Variables from parent scope accessible in this scope */
161
+ parentInstantiatedVariables?: string[];
102
162
  }
103
163
 
104
- export interface ScopeTreeNode {
105
- name: string;
106
- children: ScopeTreeNode[];
107
- }
164
+ // Re-export ScopeTreeNode from ScopeTreeManager for backward compatibility
165
+ export type { ScopeTreeNode };
108
166
 
167
+ /**
168
+ * ScopeVariable represents a reference to a specific path in a specific scope.
169
+ * Used in equivalency chains to track data flow.
170
+ */
109
171
  export interface ScopeVariable {
110
- id: number; // Never go through the same equivalency twice
172
+ /** Unique ID to prevent processing the same equivalency twice */
173
+ id: number;
174
+ /** Name of the scope containing this variable */
111
175
  scopeNodeName: string;
176
+ /** Schema path (e.g., 'signature[0].user.id') */
112
177
  schemaPath: string;
178
+ /** Why this equivalency exists (e.g., 'destructuring', 'assignment') */
113
179
  equivalencyReason: string;
114
180
  }
115
181
 
182
+ /**
183
+ * VariableInfo is the public representation of a tracked variable.
184
+ * Returned by getter methods like `getVariableInfo()`.
185
+ */
116
186
  export interface VariableInfo {
117
187
  name: string;
118
188
  equivalentTo?: ScopeVariable[];
119
189
  schema: Record<string, string>;
120
190
  }
121
191
 
192
+ /**
193
+ * FunctionCallInfo tracks an external function call and its data flow.
194
+ * Used to understand what data is passed to external APIs.
195
+ */
122
196
  export interface FunctionCallInfo {
197
+ /** Function name (e.g., 'fetch', 'console.log') */
123
198
  name: string;
199
+ /** How the function was called (e.g., 'fetch(url, options)') */
124
200
  callSignature: string;
201
+ /** Scope where the call was made */
125
202
  callScope: string;
126
- schema?: Record<string, string>; // For tracking schema of external function calls
127
- equivalencies?: Record<string, ScopeVariable[]>; // Trace all signature data back to original source (either root scope signature of functionCallReturnValue of another external function call)
203
+ /** Schema of arguments passed to the function */
204
+ schema?: Record<string, string>;
205
+ /** Traces argument data back to original source */
206
+ equivalencies?: Record<string, ScopeVariable[]>;
128
207
  }
129
208
 
209
+ /**
210
+ * EquivalencyValueChainItem tracks a single step in an equivalency chain.
211
+ * Used internally during schema building to trace data from usage back to source.
212
+ *
213
+ * Example chain for `const { user } = props; return user.name;`:
214
+ * 1. returnValue → user.name (reason: 'return statement')
215
+ * 2. user.name → props.user.name (reason: 'destructuring')
216
+ * 3. props.user.name → signature[0].user.name (reason: 'parameter')
217
+ */
130
218
  export interface EquivalencyValueChainItem {
131
219
  id: number;
132
220
  addToSchemaId?: number;
@@ -145,43 +233,124 @@ export interface EquivalencyValueChainItem {
145
233
  traceId?: number;
146
234
  }
147
235
 
236
+ /**
237
+ * EquivalencyDatabaseEntry links data sources to their usages.
238
+ *
239
+ * After analysis, use `getSourceEquivalencies()` and `getUsageEquivalencies()`
240
+ * to query this database and understand data flow:
241
+ * - sourceCandidates: Where the data originates (function args, API returns)
242
+ * - usages: Where the data is consumed (return values, JSX props, API calls)
243
+ * - intermediatesOrder: All paths in the chain, ordered by distance from source
244
+ */
148
245
  export interface EquivalencyDatabaseEntry {
149
246
  id: number;
247
+ /** Paths where data originates (signature args, API returns) */
150
248
  sourceCandidates: Pick<ScopeVariable, 'schemaPath' | 'scopeNodeName'>[];
249
+ /** Paths where data is consumed (return values, JSX props) */
151
250
  usages: Pick<ScopeVariable, 'schemaPath' | 'scopeNodeName'>[];
251
+ /** All intermediate paths with their distance from source (0 = source) */
152
252
  intermediatesOrder: Record<string, number>;
153
- complexSourceEquivalencies: Set<string>; // subsets of this equivalent path that each have different data sources (e.g. the variable analysisEntityPair has a different source for analysisEntityPair.analysis vs analysisEntityPair.entity)
253
+ /** Paths with multiple distinct sources (e.g., object with props from different origins) */
254
+ complexSourceEquivalencies: Set<string>;
154
255
  }
155
256
 
156
- const ROOT_SCOPE_NAME = 'root';
157
-
158
257
  // DEBUG: Performance metrics
159
258
  export let maxEquivalencyChainDepth = 0;
160
259
  export let addToSchemaCallCount = 0;
161
260
  export let followEquivalenciesCallCount = 0;
261
+ export let followEquivalenciesEarlyExitCount = 0;
262
+ export let followEquivalenciesEarlyExitPhase1Count = 0;
263
+ export let followEquivalenciesWithWorkCount = 0;
162
264
  export let addEquivalencyCallCount = 0;
163
265
  export function resetScopeDataStructureMetrics() {
164
266
  maxEquivalencyChainDepth = 0;
165
267
  addToSchemaCallCount = 0;
166
268
  followEquivalenciesCallCount = 0;
269
+ followEquivalenciesEarlyExitCount = 0;
270
+ followEquivalenciesEarlyExitPhase1Count = 0;
271
+ followEquivalenciesWithWorkCount = 0;
167
272
  addEquivalencyCallCount = 0;
168
273
  }
169
274
 
275
+ // Performance: Pre-computed Sets for equivalency reason filtering (O(1) vs O(n))
276
+ const ALLOWED_EQUIVALENCY_REASONS = new Set([
277
+ 'original equivalency',
278
+ 'implicit parent equivalency',
279
+ 'explicit parent equivalency',
280
+ 'transformed non-object function equivalency - original equivalency',
281
+ 'equivalency to external function call',
282
+ 'functionCall to function signature equivalency',
283
+ 'explicit parent signature',
284
+ 'useState setter call equivalency',
285
+ 'non-object function argument function signature equivalency1',
286
+ 'non-object function argument function signature equivalency2',
287
+ 'returnValue to functionCallReturnValue equivalency',
288
+ '.map() function deconstruction',
289
+ 'useMemo return value equivalent to first argument return value',
290
+ 'useState value equivalency',
291
+ 'Node .then() equivalency',
292
+ 'Explicit array deconstruction equivalency value',
293
+ 'forwardRef equivalency',
294
+ 'forwardRef signature to child signature equivalency',
295
+ 'captured function call return value equivalency',
296
+ 'original equivalency - rerouted via useCallback',
297
+ 'non-object function argument function signature equivalency1 - rerouted via useCallback',
298
+ 'non-object function argument function signature equivalency2 - rerouted via useCallback',
299
+ 'implicit parent equivalency - rerouted via useCallback',
300
+ 'Spread operator equivalency key update: implicit parent equivalency',
301
+ 'Array.from() equivalency',
302
+ 'propagated sub-property equivalency',
303
+ 'propagated function call return sub-property equivalency',
304
+ 'where was this function called from', // Added: tracks which scope called an external function
305
+ ]);
306
+
307
+ const SILENTLY_IGNORED_EQUIVALENCY_REASONS = new Set([
308
+ 'signature of functionCall',
309
+ 'transformed non-object function equivalency - implicit parent equivalency',
310
+ 'transformed non-object function equivalency - non-object function argument function signature equivalency1',
311
+ 'transformed non-object function equivalency - non-object function argument function signature equivalency2',
312
+ 'transformed non-object function equivalency - equivalency to external function call',
313
+ 'Explicit array deconstruction equivalency key',
314
+ 'transformed non-object function equivalency - useState setter call equivalency',
315
+ 'transformed non-object function equivalency - implicit parent equivalency - rerouted via useCallback',
316
+ 'transformed non-object function equivalency - Array.from() equivalency',
317
+ 'Spread operator equivalency key update: Explicit array deconstruction equivalency value',
318
+ ]);
319
+
170
320
  export class ScopeDataStructure {
171
321
  debugCount = 0;
172
322
  onlyEquivalencies = true;
173
323
  equivalencyManagers: EquivalencyManager[] = [];
174
324
  scopeNodes: Record<string, ScopeNode> = {};
175
- scopeTree: ScopeTreeNode = { name: ROOT_SCOPE_NAME, children: [] };
325
+ private scopeTreeManager: ScopeTreeManager = new ScopeTreeManager();
176
326
  externalFunctionCalls: FunctionCallInfo[] = [];
327
+
328
+ // Getter for backward compatibility - returns the tree structure
329
+ get scopeTree(): ScopeTreeNode {
330
+ return this.scopeTreeManager.getTree();
331
+ }
177
332
  environmentVariables: string[] = [];
178
333
  equivalencyDatabase: EquivalencyDatabaseEntry[] = [];
179
334
 
335
+ /**
336
+ * Conditional usages collected during AST analysis.
337
+ * Maps local variable path to array of usages.
338
+ */
339
+ private rawConditionalUsages: Record<
340
+ string,
341
+ Array<{
342
+ path: string;
343
+ conditionType: 'truthiness' | 'comparison' | 'switch';
344
+ comparedValues?: string[];
345
+ location: 'if' | 'ternary' | 'logical-and' | 'switch';
346
+ }>
347
+ > = {};
348
+
180
349
  private lastAddToSchemaId = 0;
181
350
  private lastEquivalencyId = 0;
182
351
  private lastEquivalencyDatabaseId = 0;
183
- private pathPartsCache: Map<string, string[]> = new Map();
184
- private pathJoinCache: Map<string, string> = new Map();
352
+ private pathManager: PathManager = new PathManager();
353
+ private visitedTracker: VisitedTracker = new VisitedTracker();
185
354
  private equivalencyDatabaseCache: Map<
186
355
  string,
187
356
  EquivalencyDatabaseEntry | undefined
@@ -189,11 +358,31 @@ export class ScopeDataStructure {
189
358
  // Inverted index: maps uniqueId -> EquivalencyDatabaseEntry for O(1) lookup
190
359
  private intermediatesOrderIndex: Map<string, EquivalencyDatabaseEntry> =
191
360
  new Map();
192
- private globalVisited: Set<string> = new Set();
193
- // Separate visited set for addComplexSourcePathVariables - uses scope::path only (not value)
194
- // This allows addComplexSourcePathVariables to run for each unique scope+path combo,
195
- // while the main globalVisited uses scope+path+value for fine-grained deduplication
196
- private complexSourceVisited: Set<string> = new Set();
361
+
362
+ // Index for O(1) lookup of external function calls by name
363
+ // Invalidated by setting to null; rebuilt lazily on next access
364
+ private externalFunctionCallsIndex: Map<string, FunctionCallInfo> | null =
365
+ null;
366
+
367
+ // Debug tracer for selective path/scope tracing
368
+ // Enable via: CODEYAM_DEBUG=true CODEYAM_DEBUG_PATHS="user.*,signature" npm test
369
+ private tracer: DebugTracer = new DebugTracer({
370
+ enabled: process.env.CODEYAM_DEBUG === 'true',
371
+ pathPatterns: process.env.CODEYAM_DEBUG_PATHS
372
+ ? process.env.CODEYAM_DEBUG_PATHS.split(',').map((p) => new RegExp(p))
373
+ : [],
374
+ scopePatterns: process.env.CODEYAM_DEBUG_SCOPES
375
+ ? process.env.CODEYAM_DEBUG_SCOPES.split(',').map((p) => new RegExp(p))
376
+ : [],
377
+ maxDepth: 20,
378
+ });
379
+
380
+ // Batch processor for converting recursive addToSchema calls to iterative processing
381
+ // This eliminates deep recursion and allows for better work deduplication
382
+ private batchProcessor: BatchSchemaProcessor | null = null;
383
+ // Track items already in the batch queue to prevent duplicates
384
+ // For external function calls, uses path-only keys (no value) for more aggressive deduplication
385
+ private batchQueuedSet: Set<string> | null = null;
197
386
 
198
387
  constructor(
199
388
  managers: EquivalencyManager[],
@@ -202,7 +391,7 @@ export class ScopeDataStructure {
202
391
  scopeAnalysis: ScopeAnalysis,
203
392
  ) {
204
393
  this.equivalencyManagers.push(...managers);
205
- this.scopeTree.name = scopeName;
394
+ this.scopeTreeManager.setRootName(scopeName);
206
395
  this.addScopeAnalysis(scopeName, scopeText, scopeAnalysis);
207
396
  }
208
397
 
@@ -214,8 +403,11 @@ export class ScopeDataStructure {
214
403
  isStatic?: boolean,
215
404
  ) {
216
405
  try {
217
- if (scopeNodeName !== this.scopeTree.name && !parentScopeName) {
218
- parentScopeName = this.scopeTree.name;
406
+ if (
407
+ scopeNodeName !== this.scopeTreeManager.getRootName() &&
408
+ !parentScopeName
409
+ ) {
410
+ parentScopeName = this.scopeTreeManager.getRootName();
219
411
  }
220
412
 
221
413
  let tree: any[] = [];
@@ -268,7 +460,7 @@ export class ScopeDataStructure {
268
460
  'CodeYam Error: Failed to add scope analysis for scope:',
269
461
  JSON.stringify(
270
462
  {
271
- rootScopeName: this.scopeTree.name,
463
+ rootScopeName: this.scopeTreeManager.getRootName(),
272
464
  scopeNodeName,
273
465
  scopeNodeText: scopeText,
274
466
  isolatedStructure: scopeAnalysis.isolatedStructure,
@@ -283,30 +475,51 @@ export class ScopeDataStructure {
283
475
  }
284
476
  }
285
477
 
478
+ /**
479
+ * Phase 2: Build complete schemas by following all equivalencies.
480
+ *
481
+ * This is the main entry point for schema building. Call this after all
482
+ * scopes have been added via `addScopeAnalysis()`.
483
+ *
484
+ * ## What Happens
485
+ *
486
+ * 1. Resets state (visited tracker, schemas, database)
487
+ * 2. For each scope, follows equivalencies to build complete schemas
488
+ * 3. Filters out internal function calls (keeps only external-facing)
489
+ * 4. Propagates source/usage relationships for querying
490
+ *
491
+ * ## After Calling
492
+ *
493
+ * You can then use:
494
+ * - `getSchema()` - Get the built schema for a scope
495
+ * - `getSourceEquivalencies()` - Find where data comes from
496
+ * - `getUsageEquivalencies()` - Find where data is used
497
+ */
286
498
  async captureCompleteSchema() {
499
+ // Reset state for Phase 2
287
500
  this.onlyEquivalencies = false;
288
501
  this.equivalencyDatabase = [];
289
- this.equivalencyDatabaseCache.clear(); // Clear cache when database is reset
290
- this.intermediatesOrderIndex.clear(); // Clear inverted index when database is reset
291
- this.globalVisited = new Set([]);
502
+ this.equivalencyDatabaseCache.clear();
503
+ this.intermediatesOrderIndex.clear();
504
+ this.visitedTracker.resetGlobalVisited();
292
505
 
293
506
  for (const externalFunctionCall of this.externalFunctionCalls) {
294
507
  externalFunctionCall.schema = {};
295
508
  }
296
509
 
297
- // for (const scopeNode of Object.values(this.scopeNodes)) {
510
+ // Build schemas for all scopes in parallel
298
511
  await Promise.all(
299
512
  Object.values(this.scopeNodes).map(async (scopeNode) => {
300
513
  scopeNode.schema = {};
301
514
  await this.determineEquivalenciesAndBuildSchema(scopeNode);
302
515
  }),
303
516
  );
304
- // }
517
+
305
518
  const validExternalFacingScopeNames = new Set<string>([
306
- this.scopeTree.name,
519
+ this.scopeTreeManager.getRootName(),
307
520
  ]);
308
521
  this.externalFunctionCalls = this.externalFunctionCalls.filter((efc) => {
309
- const efcName = efc.name.split('<')[0];
522
+ const efcName = this.pathManager.stripGenerics(efc.name);
310
523
  for (const manager of this.equivalencyManagers) {
311
524
  if (manager.internalFunctions.has(efcName)) {
312
525
  return false;
@@ -315,65 +528,71 @@ export class ScopeDataStructure {
315
528
  validExternalFacingScopeNames.add(efcName);
316
529
  return true;
317
530
  });
531
+ this.invalidateExternalFunctionCallsIndex();
532
+
533
+ // Pre-compute array methods list once (avoids Array.from() in hot loop)
534
+ const arrayMethodsList = Array.from(arrayMethodsSet);
535
+ const containsArrayMethod = (path: string) =>
536
+ arrayMethodsList.some((method) => path.includes(`.${method}(`));
318
537
 
319
538
  for (const entry of this.equivalencyDatabase) {
320
- entry.usages = entry.usages.filter(
321
- (usage) =>
322
- validExternalFacingScopeNames.has(
323
- usage.scopeNodeName.split('<')[0],
324
- ) &&
539
+ entry.usages = entry.usages.filter((usage) => {
540
+ const baseName = this.pathManager.stripGenerics(usage.scopeNodeName);
541
+ return (
542
+ validExternalFacingScopeNames.has(baseName) &&
325
543
  (usage.schemaPath.startsWith('returnValue') ||
326
- usage.schemaPath.startsWith(usage.scopeNodeName.split('<')[0])) &&
327
- !Array.from(arrayMethodsSet).some((method) =>
328
- usage.schemaPath.includes(`.${method}(`),
329
- ),
330
- );
331
- entry.sourceCandidates = entry.sourceCandidates.filter(
332
- (candidate) =>
333
- validExternalFacingScopeNames.has(
334
- candidate.scopeNodeName.split('<')[0],
335
- ) &&
544
+ usage.schemaPath.startsWith(baseName)) &&
545
+ !containsArrayMethod(usage.schemaPath)
546
+ );
547
+ });
548
+ entry.sourceCandidates = entry.sourceCandidates.filter((candidate) => {
549
+ const baseName = this.pathManager.stripGenerics(
550
+ candidate.scopeNodeName,
551
+ );
552
+ return (
553
+ validExternalFacingScopeNames.has(baseName) &&
336
554
  (candidate.schemaPath.startsWith('signature[') ||
337
- candidate.schemaPath.startsWith(
338
- candidate.scopeNodeName.split('<')[0],
339
- )) &&
340
- !Array.from(arrayMethodsSet).some((method) =>
341
- candidate.schemaPath.includes(`.${method}(`),
342
- ),
343
- );
555
+ candidate.schemaPath.startsWith(baseName)) &&
556
+ !containsArrayMethod(candidate.schemaPath)
557
+ );
558
+ });
344
559
  }
345
560
 
346
561
  this.propagateSourceAndUsageEquivalencies(
347
- this.scopeNodes[this.scopeTree.name],
562
+ this.scopeNodes[this.scopeTreeManager.getRootName()],
348
563
  );
349
564
 
350
565
  for (const externalFunctionCall of this.externalFunctionCalls) {
351
- const t = new Date().getTime();
352
- // console.info("Start Propagating", JSON.stringify({
353
- // externalFunctionCallName: externalFunctionCall.name,
354
- // // sourceEquivalencies: externalFunctionCall.sourceEquivalencies,
355
- // }, null, 2));
356
-
357
566
  this.propagateSourceAndUsageEquivalencies(externalFunctionCall);
358
-
359
- const elapsedTime = new Date().getTime() - t;
360
- if (elapsedTime > 100) {
361
- console.warn('Long Propagation Time', {
362
- externalFunctionCallName: externalFunctionCall.name,
363
- time: elapsedTime,
364
- });
365
- // throw new Error("STOP - LONG PROPAGATION TIME")
366
- }
367
-
368
- // console.info("Done Propagating", JSON.stringify({
369
- // externalFunctionCallName: externalFunctionCall.name,
370
- // // sourceEquivalencies: externalFunctionCall.sourceEquivalencies,
371
- // // usageEquivalencies: externalFunctionCall.usageEquivalencies,
372
- // time: elapsedTime
373
- // }, null, 2))
374
567
  }
375
568
  }
376
569
 
570
+ /**
571
+ * Core method: Adds a path/value to a scope's schema and follows equivalencies.
572
+ *
573
+ * This is the heart of schema building. For each path, it:
574
+ * 1. Validates the path and checks if already visited
575
+ * 2. Adds the path → value mapping to the scope's schema
576
+ * 3. Follows any equivalencies to propagate the schema to linked paths
577
+ * 4. Tracks the equivalency chain for source/usage database
578
+ *
579
+ * ## Cycle Detection
580
+ *
581
+ * Uses `visitedTracker.checkAndMarkGlobalVisited()` to prevent infinite loops.
582
+ * A path is considered visited if the exact (scope, path, value) tuple has
583
+ * been processed before.
584
+ *
585
+ * ## Equivalency Following
586
+ *
587
+ * When a path has equivalencies (e.g., `user` → `props.user`), this method
588
+ * recursively calls itself to add the equivalent path to its scope's schema.
589
+ *
590
+ * @param path - Schema path to add (e.g., 'user.id')
591
+ * @param value - Type value (e.g., 'string', 'number')
592
+ * @param scopeNode - The scope to add to
593
+ * @param equivalencyValueChain - Tracks the chain for database population
594
+ * @param traceId - Debug ID for tracing specific paths
595
+ */
377
596
  addToSchema({
378
597
  path,
379
598
  value,
@@ -388,7 +607,16 @@ export class ScopeDataStructure {
388
607
  traceId?: number;
389
608
  }) {
390
609
  addToSchemaCallCount++;
391
- // DEBUG: Detect infinite loops
610
+
611
+ // Trace entry for debugging
612
+ this.tracer.traceEnter('addToSchema', {
613
+ path,
614
+ scope: scopeNode?.name,
615
+ value,
616
+ chainDepth: equivalencyValueChain.length,
617
+ });
618
+
619
+ // Safety: Detect runaway recursion
392
620
  if (addToSchemaCallCount > 500000) {
393
621
  console.error('INFINITE LOOP DETECTED in addToSchema', {
394
622
  callCount: addToSchemaCallCount,
@@ -404,7 +632,9 @@ export class ScopeDataStructure {
404
632
  if (equivalencyValueChain.length > maxEquivalencyChainDepth) {
405
633
  maxEquivalencyChainDepth = equivalencyValueChain.length;
406
634
  }
407
- if (!scopeNode) return;
635
+ if (!scopeNode) {
636
+ return;
637
+ }
408
638
 
409
639
  if (!this.isValidPath(path)) {
410
640
  if (traceId) {
@@ -413,6 +643,7 @@ export class ScopeDataStructure {
413
643
  return;
414
644
  }
415
645
 
646
+ // Update chain metadata for database tracking
416
647
  if (equivalencyValueChain.length > 0) {
417
648
  equivalencyValueChain[equivalencyValueChain.length - 1].addToSchemaId =
418
649
  ++this.lastAddToSchemaId;
@@ -423,79 +654,18 @@ export class ScopeDataStructure {
423
654
  };
424
655
  }
425
656
 
426
- // Use this debugging to track down an infinite loop
427
- // traceId ||= 0;
428
- // traceId += 1;
429
- // if (traceId) {
430
- // console.info(JSON.stringify({ traceId, path, value, scopeNodeName: scopeNode.name }, null, 2));
431
- // }
432
- // if (traceId > 30) {
433
- // console.warn(
434
- // 'HIGH TRACEID',
435
- // JSON.stringify(
436
- // {
437
- // path,
438
- // value,
439
- // scopeNodeName: scopeNode.name,
440
- // equivalencyValueChain,
441
- // },
442
- // null,
443
- // 2,
444
- // ),
445
- // );
446
- // throw new Error('STOP - HIGH TRACEID');
447
- // }
448
-
449
- // Use this debugging to trace a specific path through the propagation
450
- const debugLevel = 0; // 0 for minimal, 1 for executed paths, 2 for all paths info
451
- // if ((!this.onlyEquivalencies && path === 'entity.sha') || traceId) {
452
- // traceId ||= 0;
453
- // traceId += 1;
454
- // if (traceId === 1) {
455
- // this.debugCount += 1;
456
- // if (this.debugCount > 5) throw new Error('STOP - HIGH DEBUG COUNT');
457
- // console.warn('START');
458
- // }
459
-
460
- // console.info(
461
- // 'Debug Propagation: Adding to schema',
462
- // JSON.stringify(
463
- // {
464
- // // traceId,
465
- // path,
466
- // value,
467
- // scopeNodeName: scopeNode.name,
468
- // reason:
469
- // equivalencyValueChain[equivalencyValueChain.length - 1]?.reason,
470
- // // previous:
471
- // // equivalencyValueChain[equivalencyValueChain.length - 1],
472
- // text: scopeNode.text,
473
- // // tree: scopeNode.tree,
474
- // // onlyEquivalencies: this.onlyEquivalencies,
475
- // // equivalencyValueChain,
476
- // // scopeNode
477
- // // instatiatedVeriables: scopeNode.instantiatedVariables,
478
- // // parentInstantiatedVariables: scopeNode.parentInstantiatedVariables,
479
- // // isolatedStructure: scopeNode.analysis.isolatedStructure,
480
- // // isolatedEquivalencies: scopeNode.analysis.isolatedEquivalentVariables,
481
- // // equivalencies: traceId === 1 ? scopeNode.equivalencies : 'skipped',
482
- // // functionCalls: scopeNode.functionCalls,
483
- // // externalFunctionCalls: this.externalFunctionCalls.filter(fc => fc.callScope.includes(scopeNode.name))
484
- // },
485
- // null,
486
- // 2,
487
- // ),
488
- // );
489
- // // if (traceId > 1) traceId = undefined;
490
- // throw new Error('STOP ON ADD');
491
- // }
657
+ // Debug level: 0=minimal, 1=executed paths, 2=all paths (set via traceId)
658
+ const debugLevel = 0;
492
659
 
660
+ // ─────────────────────────────────────────────────────────────────────────
661
+ // SECTION 1: Handle complex source paths (paths with multiple data origins)
662
+ // ─────────────────────────────────────────────────────────────────────────
493
663
  const equivalenciesDatabaseEntry = this.getEquivalenciesDatabaseEntry(
494
664
  scopeNode.name,
495
665
  path,
496
666
  );
497
667
 
498
- // Call addComplexSourcePathVariables like the original code (before visited check)
668
+ // Process complex source paths (before visited check, per original design)
499
669
  this.addComplexSourcePathVariables(
500
670
  equivalenciesDatabaseEntry,
501
671
  scopeNode,
@@ -504,23 +674,19 @@ export class ScopeDataStructure {
504
674
  traceId,
505
675
  );
506
676
 
507
- const uniqueIdentifier = `${scopeNode.name}::${path}::${value}`;
508
-
509
- if (this.globalVisited.has(uniqueIdentifier)) {
677
+ // ─────────────────────────────────────────────────────────────────────────
678
+ // SECTION 2: Cycle detection - skip if already visited with this value
679
+ // ─────────────────────────────────────────────────────────────────────────
680
+ if (
681
+ this.visitedTracker.checkAndMarkGlobalVisited(scopeNode.name, path, value)
682
+ ) {
510
683
  if (traceId) {
511
- console.info(
512
- 'Debug propagation: already globally visited path',
513
- JSON.stringify(
514
- {
515
- uniqueIdentifier,
516
- // equivalencyValueChain,
517
- },
518
- null,
519
- 2,
520
- ),
521
- );
684
+ console.info('Debug: already visited', {
685
+ key: `${scopeNode.name}::${path}::${value}`,
686
+ });
522
687
  }
523
688
 
689
+ // Still record in database even if visited (captures full chain)
524
690
  if (!this.onlyEquivalencies) {
525
691
  this.addToEquivalencyDatabase(equivalencyValueChain, traceId);
526
692
  }
@@ -528,8 +694,7 @@ export class ScopeDataStructure {
528
694
  return;
529
695
  }
530
696
 
531
- this.globalVisited.add(uniqueIdentifier);
532
-
697
+ // Continue complex source processing after visited check
533
698
  this.captureComplexSourcePaths(
534
699
  equivalenciesDatabaseEntry,
535
700
  scopeNode,
@@ -538,6 +703,10 @@ export class ScopeDataStructure {
538
703
  traceId,
539
704
  );
540
705
 
706
+ // ─────────────────────────────────────────────────────────────────────────
707
+ // SECTION 3: Process each subpath to follow equivalencies
708
+ // For path "user.profile.name", processes: "user", "user.profile", "user.profile.name"
709
+ // ─────────────────────────────────────────────────────────────────────────
541
710
  const pathParts = this.splitPath(path);
542
711
 
543
712
  this.checkForArrayItemPath(pathParts, scopeNode, equivalencyValueChain);
@@ -656,6 +825,11 @@ export class ScopeDataStructure {
656
825
  }
657
826
  }
658
827
 
828
+ // ─────────────────────────────────────────────────────────────────────────
829
+ // SECTION 4: Write to schema if appropriate
830
+ // Only writes if: (a) path not set or is 'unknown', AND
831
+ // (b) path belongs to this scope (instantiated, signature, or return)
832
+ // ─────────────────────────────────────────────────────────────────────────
659
833
  const writeToCurrentScopeSchema =
660
834
  (!scopeNode.schema[path] || scopeNode.schema[path] === 'unknown') &&
661
835
  (!scopeNode.instantiatedVariables ||
@@ -663,50 +837,35 @@ export class ScopeDataStructure {
663
837
  pathParts[0].startsWith('signature[') ||
664
838
  pathParts[0].startsWith('returnValue'));
665
839
 
666
- // Safe early exit: if we've already set this exact schema value, skip processing
840
+ // Early exit if schema already has this exact value
667
841
  if (scopeNode.schema[path] === value && value !== 'unknown') {
668
842
  return;
669
843
  }
670
844
 
671
845
  if (writeToCurrentScopeSchema) {
672
846
  if (traceId && debugLevel > 0) {
673
- console.info('Debug Propagation: currentScope executed', {
674
- traceId,
847
+ console.info('Debug: writing schema', {
675
848
  path,
676
- pathParts,
677
- scopeNodeName: scopeNode.name,
849
+ value,
850
+ scope: scopeNode.name,
678
851
  });
679
852
  }
680
853
  scopeNode.schema[path] = value;
681
854
  }
682
855
 
856
+ // ─────────────────────────────────────────────────────────────────────────
857
+ // SECTION 5: Record in equivalency database (Phase 2 only)
858
+ // ─────────────────────────────────────────────────────────────────────────
683
859
  if (!this.onlyEquivalencies) {
684
860
  this.addToEquivalencyDatabase(equivalencyValueChain, traceId);
685
861
  }
686
862
 
687
863
  if (traceId) {
688
- console.info(
689
- 'Debug Propagation: exiting',
690
- JSON.stringify(
691
- {
692
- traceId,
693
- scopeNodeName: scopeNode.name,
694
- path,
695
- value,
696
- // schemaValue: scopeNode.schema[path],
697
- // propagated,
698
- // scopeInfoText: scopeNode.text,
699
- // equivalencyValueChain//: equivalencyValueChain.map(
700
- // (ev) => ev.currentPath.schemaPath,
701
- // ),
702
- // sourceEquivalencies: scopeNode.sourceEquivalencies[path] ?? [],
703
- // usageEquivalencies: scopeNode.usageEquivalencies[path] ?? [],
704
- // checkpoints,
705
- },
706
- null,
707
- 2,
708
- ),
709
- );
864
+ console.info('Debug: addToSchema complete', {
865
+ scope: scopeNode.name,
866
+ path,
867
+ value,
868
+ });
710
869
  }
711
870
  }
712
871
 
@@ -742,55 +901,15 @@ export class ScopeDataStructure {
742
901
  `Infinite loop detected: addEquivalency called ${addEquivalencyCallCount} times`,
743
902
  );
744
903
  }
745
- // Temporary debugging to track down unnecessary equivalencies
746
- if (
747
- ![
748
- 'original equivalency',
749
- 'implicit parent equivalency',
750
- 'explicit parent equivalency',
751
- 'transformed non-object function equivalency - original equivalency',
752
- 'equivalency to external function call',
753
- 'functionCall to function signature equivalency', // 1 failure
754
- 'explicit parent signature',
755
- 'useState setter call equivalency',
756
- 'non-object function argument function signature equivalency1',
757
- 'non-object function argument function signature equivalency2',
758
- 'returnValue to functionCallReturnValue equivalency', // 2 failures
759
- '.map() function deconstruction', // 1 failure
760
- 'useMemo return value equivalent to first argument return value',
761
- 'useState value equivalency', // 1 failure
762
- 'Node .then() equivalency', // 1 failure
763
- 'Explicit array deconstruction equivalency value', // 1 failure
764
- 'forwardRef equivalency',
765
- 'forwardRef signature to child signature equivalency', // 1 failure
766
- 'captured function call return value equivalency', // 1 failure (in ScopeDataStructure.test.ts)
767
- 'original equivalency - rerouted via useCallback', // 1 failure
768
- 'non-object function argument function signature equivalency1 - rerouted via useCallback', // 1 failure
769
- 'non-object function argument function signature equivalency2 - rerouted via useCallback', // 1 failure
770
- 'implicit parent equivalency - rerouted via useCallback', // 1 failure
771
- 'Spread operator equivalency key update: implicit parent equivalency', // 1 failure
772
- 'Array.from() equivalency',
773
- 'propagated sub-property equivalency',
774
- 'propagated function call return sub-property equivalency',
775
- ].includes(equivalencyReason)
776
- ) {
777
- if (
778
- [
779
- 'signature of functionCall',
780
- 'transformed non-object function equivalency - implicit parent equivalency',
781
- 'transformed non-object function equivalency - non-object function argument function signature equivalency1',
782
- 'transformed non-object function equivalency - non-object function argument function signature equivalency2',
783
- 'transformed non-object function equivalency - equivalency to external function call',
784
- 'Explicit array deconstruction equivalency key',
785
- 'transformed non-object function equivalency - useState setter call equivalency',
786
- 'transformed non-object function equivalency - implicit parent equivalency - rerouted via useCallback',
787
- 'transformed non-object function equivalency - Array.from() equivalency',
788
- 'Spread operator equivalency key update: Explicit array deconstruction equivalency value',
789
- ].includes(equivalencyReason)
790
- ) {
904
+ // Filter equivalency reasons - use pre-computed Sets for O(1) lookup
905
+ if (!ALLOWED_EQUIVALENCY_REASONS.has(equivalencyReason)) {
906
+ if (SILENTLY_IGNORED_EQUIVALENCY_REASONS.has(equivalencyReason)) {
791
907
  return;
792
908
  } else {
909
+ // Log and skip - if an equivalency reason isn't in ALLOWED or SILENTLY_IGNORED,
910
+ // it shouldn't be stored (was previously missing the return)
793
911
  console.info('Not tracked equivalency reason', { equivalencyReason });
912
+ return;
794
913
  }
795
914
  }
796
915
 
@@ -954,9 +1073,9 @@ export class ScopeDataStructure {
954
1073
  functionCallInfo.equivalencies = {};
955
1074
  }
956
1075
 
957
- const existingFunctionCall = this.externalFunctionCalls.find(
958
- (fc) => getFunctionCallRoot(functionCallInfo.callSignature) === fc.name,
959
- );
1076
+ const searchKey = getFunctionCallRoot(functionCallInfo.callSignature);
1077
+ const existingFunctionCall =
1078
+ this.getExternalFunctionCallsIndex().get(searchKey);
960
1079
  if (existingFunctionCall) {
961
1080
  existingFunctionCall.schema = {
962
1081
  ...existingFunctionCall.schema,
@@ -979,6 +1098,7 @@ export class ScopeDataStructure {
979
1098
 
980
1099
  if (isExternal) {
981
1100
  this.externalFunctionCalls.push(functionCallInfo);
1101
+ this.invalidateExternalFunctionCallsIndex();
982
1102
  }
983
1103
  }
984
1104
  }
@@ -1005,7 +1125,7 @@ export class ScopeDataStructure {
1005
1125
  // }
1006
1126
 
1007
1127
  const getRootOrExternalFunctionCallInfo = (name: string) => {
1008
- return name === this.scopeTree.name
1128
+ return name === this.scopeTreeManager.getRootName()
1009
1129
  ? this.getScopeNode()
1010
1130
  : this.getExternalFunctionCallInfo(name);
1011
1131
  };
@@ -1036,6 +1156,40 @@ export class ScopeDataStructure {
1036
1156
  },
1037
1157
  );
1038
1158
 
1159
+ // PERF: Build a Map for O(1) lookup instead of O(n) inner loop
1160
+ // Map from "remaining parts joined" to equivalentSchemaPath
1161
+ const equivalentSchemaPathMap = new Map<string, string>();
1162
+ for (const equivalentSchemaPath of Object.keys(
1163
+ equivalentScopeNode.schema,
1164
+ )) {
1165
+ // Quick string check before expensive path splitting
1166
+ if (
1167
+ !(
1168
+ equivalentSchemaPath.startsWith(equivalentPath) ||
1169
+ equivalentSchemaPath === equivalentPath ||
1170
+ equivalentPath.startsWith(equivalentSchemaPath)
1171
+ )
1172
+ ) {
1173
+ continue;
1174
+ }
1175
+
1176
+ const equivalentSchemaPathParts = this.splitPath(equivalentSchemaPath);
1177
+
1178
+ if (
1179
+ !equivalentPathParts.every(
1180
+ (p, i) => equivalentSchemaPathParts[i] === p,
1181
+ )
1182
+ ) {
1183
+ continue;
1184
+ }
1185
+
1186
+ const remainingEquivalentSchemaPathParts =
1187
+ equivalentSchemaPathParts.slice(equivalentPathParts.length);
1188
+ // Use | as separator since it won't appear in path parts
1189
+ const key = remainingEquivalentSchemaPathParts.join('|');
1190
+ equivalentSchemaPathMap.set(key, equivalentSchemaPath);
1191
+ }
1192
+
1039
1193
  for (const schemaPath of relevantSchemaPaths) {
1040
1194
  const schemaPathParts = this.splitPath(schemaPath);
1041
1195
 
@@ -1047,106 +1201,29 @@ export class ScopeDataStructure {
1047
1201
  pathParts.length,
1048
1202
  );
1049
1203
 
1050
- let missingEquivalentPath = false;
1051
-
1052
- // Performance optimization: pre-filter equivalent schema paths
1053
- const relevantEquivalentSchemaPaths = Object.keys(
1054
- equivalentScopeNode.schema,
1055
- ).filter((equivalentSchemaPath) => {
1056
- // Quick string check before expensive path splitting
1057
- return (
1058
- equivalentSchemaPath.startsWith(equivalentPath) ||
1059
- equivalentSchemaPath === equivalentPath ||
1060
- equivalentPath.startsWith(equivalentSchemaPath)
1061
- );
1062
- });
1063
-
1064
- for (const equivalentSchemaPath of relevantEquivalentSchemaPaths) {
1065
- const equivalentSchemaPathParts =
1066
- this.splitPath(equivalentSchemaPath);
1067
-
1068
- if (
1069
- !equivalentPathParts.every(
1070
- (p, i) => equivalentSchemaPathParts[i] === p,
1071
- )
1072
- ) {
1073
- continue;
1074
- }
1075
-
1076
- const remainingEquivalentSchemaPathParts =
1077
- equivalentSchemaPathParts.slice(equivalentPathParts.length);
1078
-
1079
- if (
1080
- remainingSchemaPathParts.length !==
1081
- remainingEquivalentSchemaPathParts.length ||
1082
- !remainingEquivalentSchemaPathParts.every(
1083
- (p, i) => p === remainingSchemaPathParts[i],
1084
- )
1085
- ) {
1086
- missingEquivalentPath = true;
1087
- continue;
1088
- }
1089
- missingEquivalentPath = false;
1204
+ // PERF: O(1) Map lookup instead of O(n) inner loop
1205
+ const remainingKey = remainingSchemaPathParts.join('|');
1206
+ const equivalentSchemaPath = equivalentSchemaPathMap.get(remainingKey);
1090
1207
 
1208
+ if (equivalentSchemaPath) {
1091
1209
  const value1 = scopeNode.schema[schemaPath];
1092
1210
  const value2 = equivalentScopeNode.schema[equivalentSchemaPath];
1093
1211
 
1094
- let bestValue = value1 ?? value2 ?? 'unknown';
1095
- if (
1096
- value2 &&
1097
- ((bestValue === 'unknown' && value2 !== 'unknown') ||
1098
- (bestValue.includes('unknown') && !value2.includes('unknown')))
1099
- ) {
1100
- bestValue = value2;
1101
- }
1212
+ const bestValue = selectBestValue(value1, value2);
1102
1213
 
1103
1214
  scopeNode.schema[schemaPath] = bestValue;
1104
1215
  equivalentScopeNode.schema[equivalentSchemaPath] = bestValue;
1105
-
1106
- // if (traceId) {
1107
- // console.info('Debug Propagate: Assign Best Value', {
1108
- // traceId,
1109
- // sourceScopeNodeName: scopeNode.name,
1110
- // path,
1111
- // schemaPath,
1112
- // usageScopeNodeName: equivalentScopeNode.name,
1113
- // equivalentPath,
1114
- // equivalentSchemaPath,
1115
- // remainingSchemaPathParts,
1116
- // remainingEquivalentSchemaPathParts,
1117
- // value1,
1118
- // value2,
1119
- // bestValue,
1120
- // });
1121
- // }
1122
- break;
1123
- }
1124
-
1125
- if (
1126
- missingEquivalentPath &&
1127
- (scopeNode.name.includes('____cyScope') ||
1128
- !('instantiatedVariables' in equivalentScopeNode))
1216
+ } else if (
1217
+ scopeNode.name.includes('____cyScope') ||
1218
+ !('instantiatedVariables' in equivalentScopeNode)
1129
1219
  ) {
1220
+ // No matching equivalent path found - create one if needed
1130
1221
  // Only necessary for internal function scopes or external function scopes
1131
1222
  const newEquivalentPath = this.joinPathParts([
1132
1223
  equivalentPath,
1133
1224
  ...remainingSchemaPathParts,
1134
1225
  ]);
1135
1226
 
1136
- // if (traceId) {
1137
- // console.info('Debug Propagate: missing equivalent path', {
1138
- // traceId,
1139
- // scopeNodeName: scopeNode.name,
1140
- // path,
1141
- // equivalentPath,
1142
- // schemaPath,
1143
- // remainingSchemaPathParts,
1144
- // equivalentScopeNodeName: equivalentScopeNode.name,
1145
- // // equivalentScopeNodeSchema: equivalentScopeNode.schema,
1146
- // newEquivalentPath,
1147
- // });
1148
- // }
1149
-
1150
1227
  equivalentScopeNode.schema[newEquivalentPath] =
1151
1228
  scopeNode.schema[schemaPath];
1152
1229
  }
@@ -1188,111 +1265,40 @@ export class ScopeDataStructure {
1188
1265
  }
1189
1266
  }
1190
1267
 
1191
- splitPath(path: string): string[] {
1192
- if (this.pathPartsCache.has(path)) {
1193
- return structuredClone(this.pathPartsCache.get(path)!);
1194
- }
1195
- const pathParts = splitOutsideParenthesesAndArrays(path);
1196
- this.pathPartsCache.set(path, structuredClone(pathParts));
1197
- return pathParts;
1268
+ splitPath(path: string): readonly string[] {
1269
+ return this.pathManager.splitPath(path);
1198
1270
  }
1199
1271
 
1200
- joinPathParts(pathParts: string[]): string {
1201
- const cacheKey = pathParts.join('|');
1202
- if (this.pathJoinCache.has(cacheKey)) {
1203
- return this.pathJoinCache.get(cacheKey)!;
1204
- }
1205
- const result = joinParenthesesAndArrays(pathParts);
1206
- this.pathJoinCache.set(cacheKey, result);
1207
- return result;
1272
+ joinPathParts(pathParts: readonly string[]): string {
1273
+ return this.pathManager.joinPathParts(pathParts);
1208
1274
  }
1209
1275
 
1210
1276
  // PRIVATE METHODS //
1211
1277
 
1212
- private uniqueId({
1213
- scopeNodeName,
1214
- schemaPath,
1215
- value,
1216
- }: {
1278
+ private uniqueId(params: {
1217
1279
  scopeNodeName: string;
1218
1280
  schemaPath: string;
1219
1281
  value?: string;
1220
1282
  }): string {
1221
- const parts = [scopeNodeName, schemaPath, value].filter(Boolean);
1222
- return parts.join('::');
1283
+ return uniqueId(params);
1223
1284
  }
1224
1285
 
1225
1286
  private uniqueScopeVariables(scopeVariables: ScopeVariable[]) {
1226
- return this.uniqueScopeAndPaths(scopeVariables) as ScopeVariable[];
1287
+ return uniqueScopeVariables(scopeVariables);
1227
1288
  }
1228
1289
 
1229
1290
  private uniqueScopeAndPaths(
1230
1291
  scopeVariables: Pick<ScopeVariable, 'scopeNodeName' | 'schemaPath'>[],
1231
1292
  ) {
1232
- if (!scopeVariables || scopeVariables.length === 0) return [];
1233
-
1234
- // Optimize from O(n²) to O(n) using Set for deduplication
1235
- const seen = new Set<string>();
1236
- return scopeVariables.filter((varItem) => {
1237
- const key = `${varItem.scopeNodeName}::${varItem.schemaPath}`;
1238
- if (seen.has(key)) {
1239
- return false;
1240
- }
1241
- seen.add(key);
1242
- return true;
1243
- });
1293
+ return uniqueScopeAndPaths(scopeVariables);
1244
1294
  }
1245
1295
 
1246
1296
  private isValidPath(path: string): boolean {
1247
- if (typeof path !== 'string') {
1248
- return false;
1249
- }
1250
-
1251
- if (!path) {
1252
- return false;
1253
- }
1254
-
1255
- if (path === 'true' || path === 'false') {
1256
- return false;
1257
- }
1258
-
1259
- if (!isNaN(Number(path))) {
1260
- return false;
1261
- }
1262
-
1263
- if (path.match(/^['"]/)) {
1264
- return false;
1265
- }
1266
-
1267
- return this.splitPath(path).every((part) => {
1268
- if (
1269
- cleanOutBoundary(
1270
- cleanOutBoundary(cleanOutBoundary(part, '<', '>'), '[', ']'),
1271
- ).match(/\s/)
1272
- ) {
1273
- return false;
1274
- }
1275
- return true;
1276
- });
1297
+ return this.pathManager.isValidPath(path);
1277
1298
  }
1278
1299
 
1279
1300
  private addToTree(pathParts: string[]) {
1280
- let scopeTreeNode = { children: [this.scopeTree] };
1281
- for (const pathPart of pathParts) {
1282
- const existingChild = scopeTreeNode.children.find(
1283
- (child) => child.name === pathPart,
1284
- );
1285
- if (existingChild) {
1286
- scopeTreeNode = existingChild;
1287
- } else {
1288
- const childScopeTreeNode = {
1289
- name: pathPart,
1290
- children: [] as any[],
1291
- };
1292
- scopeTreeNode.children.push(childScopeTreeNode);
1293
- scopeTreeNode = childScopeTreeNode;
1294
- }
1295
- }
1301
+ this.scopeTreeManager.addPath(pathParts);
1296
1302
  }
1297
1303
 
1298
1304
  private setInstantiatedVariables(scopeNode: ScopeNode) {
@@ -1468,6 +1474,11 @@ export class ScopeDataStructure {
1468
1474
  }
1469
1475
  }
1470
1476
 
1477
+ // PERF: Enable batch processing to convert recursive addToSchema calls to iterative
1478
+ // This eliminates deep call stacks and improves deduplication
1479
+ this.batchProcessor = new BatchSchemaProcessor();
1480
+ this.batchQueuedSet = new Set();
1481
+
1471
1482
  for (const key of Array.from(allPaths)) {
1472
1483
  let value = isolatedStructure[key] ?? 'unknown';
1473
1484
 
@@ -1475,7 +1486,6 @@ export class ScopeDataStructure {
1475
1486
  value = 'unknown';
1476
1487
  }
1477
1488
 
1478
- const startTime = new Date().getTime();
1479
1489
  this.addToSchema({
1480
1490
  path: cleanPath(key, allPaths),
1481
1491
  value,
@@ -1489,21 +1499,47 @@ export class ScopeDataStructure {
1489
1499
  ],
1490
1500
  });
1491
1501
 
1492
- // const timeDiff = new Date().getTime() - startTime;
1493
- // if (timeDiff / 1000 > 1) {
1494
- // console.info('SLOW', {
1495
- // timeDiff,
1496
- // root: this.scopeTree.name,
1497
- // scopeNodeName: scopeNode.name,
1498
- // schemaPath: key,
1499
- // onlyEquivalencies: this.onlyEquivalencies,
1500
- // });
1501
- // }
1502
+ // Process any work queued by followEquivalencies
1503
+ this.processBatchQueue();
1502
1504
  }
1503
1505
 
1506
+ // Final pass to ensure all queued work is processed
1507
+ this.processBatchQueue();
1508
+
1509
+ // Clean up batch processor
1510
+ this.batchProcessor = null;
1511
+ this.batchQueuedSet = null;
1512
+
1504
1513
  this.validateSchema(scopeNode, false, false);
1505
1514
  }
1506
1515
 
1516
+ /**
1517
+ * Process all items in the batch queue.
1518
+ * Each item may queue more work via followEquivalencies.
1519
+ */
1520
+ private processBatchQueue(): void {
1521
+ if (!this.batchProcessor) return;
1522
+
1523
+ while (this.batchProcessor.hasWork()) {
1524
+ const item = this.batchProcessor.getNextWork();
1525
+ if (!item) break;
1526
+
1527
+ const scopeNode = this.getScopeOrFunctionCallInfo(
1528
+ item.scopeNodeName,
1529
+ ) as ScopeNode;
1530
+ if (!scopeNode) continue;
1531
+
1532
+ this.addToSchema({
1533
+ path: item.path,
1534
+ value: item.value,
1535
+ scopeNode,
1536
+ equivalencyValueChain:
1537
+ item.equivalencyValueChain as EquivalencyValueChainItem[],
1538
+ traceId: item.traceId,
1539
+ });
1540
+ }
1541
+ }
1542
+
1507
1543
  /**
1508
1544
  * Propagates returnValue.* sub-properties from a callback scope to the usage path.
1509
1545
  *
@@ -1756,15 +1792,15 @@ export class ScopeDataStructure {
1756
1792
  }
1757
1793
 
1758
1794
  private checkForArrayItemPath(
1759
- pathParts: string[],
1795
+ pathParts: readonly string[],
1760
1796
  scopeNode: ScopeNode,
1761
1797
  equivalencyValueChain: EquivalencyValueChainItem[],
1762
1798
  ) {
1763
- const arrayItemPath = joinParenthesesAndArrays([...pathParts, '[]']);
1799
+ const arrayItemPath = this.joinPathParts([...pathParts, '[]']);
1764
1800
  if (scopeNode.equivalencies[arrayItemPath]) {
1765
1801
  const firstEquivalency = equivalencyValueChain[0].currentPath;
1766
- const newFirstEquivalencyPath = joinParenthesesAndArrays([
1767
- ...splitOutsideParenthesesAndArrays(firstEquivalency.schemaPath),
1802
+ const newFirstEquivalencyPath = this.joinPathParts([
1803
+ ...this.splitPath(firstEquivalency.schemaPath),
1768
1804
  '[]',
1769
1805
  ]);
1770
1806
  this.addToSchema({
@@ -1782,41 +1818,95 @@ export class ScopeDataStructure {
1782
1818
  }
1783
1819
  }
1784
1820
 
1821
+ /**
1822
+ * Follows equivalencies for a subpath and recursively calls addToSchema.
1823
+ *
1824
+ * This is the recursive heart of schema propagation. When we have:
1825
+ * `user` equivalent to `props.user`
1826
+ * And we're processing `user.id`, this method will:
1827
+ * 1. Find the equivalency `user` → `props.user`
1828
+ * 2. Reconstruct the full path: `props.user.id`
1829
+ * 3. Recursively call addToSchema for the equivalent scope
1830
+ *
1831
+ * ## Function-Ambivalent Paths
1832
+ *
1833
+ * Handles paths like `data.map(fn)` by also checking equivalencies
1834
+ * for `data.map` (without the function argument). This allows
1835
+ * array method chains to propagate correctly.
1836
+ *
1837
+ * @param scopeNode - Current scope being processed
1838
+ * @param path - Full original path (e.g., 'user.profile.name')
1839
+ * @param pathParts - Split version of path
1840
+ * @param subPath - Current subpath being checked (e.g., 'user.profile')
1841
+ * @param subPathParts - Split version of subPath
1842
+ * @param value - Type value to propagate
1843
+ * @param equivalencyValueChain - Chain tracking for database
1844
+ * @param traceId - Debug ID
1845
+ * @param debugLevel - 0=minimal, 1=executed, 2=verbose
1846
+ */
1785
1847
  private followEquivalencies(
1786
1848
  scopeNode: ScopeNode,
1787
1849
  path: string,
1788
- pathParts: string[],
1850
+ pathParts: readonly string[],
1789
1851
  subPath: string,
1790
- subPathParts: string[],
1852
+ subPathParts: readonly string[],
1791
1853
  value: string,
1792
1854
  equivalencyValueChain: EquivalencyValueChainItem[],
1793
1855
  traceId?: number,
1794
1856
  debugLevel = 0,
1795
1857
  ) {
1796
1858
  followEquivalenciesCallCount++;
1859
+
1860
+ // Trace for debugging
1861
+ this.tracer.trace('followEquivalencies', {
1862
+ path,
1863
+ scope: scopeNode.name,
1864
+ subPath,
1865
+ hasEquivalencies: (scopeNode.equivalencies[subPath]?.length ?? 0) > 0,
1866
+ });
1867
+
1797
1868
  let propagated = false;
1869
+
1870
+ // ─────────────────────────────────────────────────────────────────────────
1871
+ // Step 1: Collect equivalencies (including function-ambivalent paths)
1872
+ // ─────────────────────────────────────────────────────────────────────────
1798
1873
  let equivalentValues = scopeNode.equivalencies[subPath] ?? [];
1799
1874
  let functionAmbivalentSubPath = subPath;
1800
1875
  let functionAmbivalentSubPathParts = subPathParts;
1801
1876
 
1802
- if (subPathParts[subPathParts.length - 1].indexOf('(') > -1) {
1877
+ // For paths like `data.map(fn)`, also check `data.map` equivalencies
1878
+ // PERF: Only do the expensive function-ambivalent processing if:
1879
+ // 1. No equivalencies found yet, AND
1880
+ // 2. The subpath ends with a function call (contains '(')
1881
+ const lastPart = subPathParts[subPathParts.length - 1];
1882
+ if (lastPart.indexOf('(') > -1) {
1883
+ // Check function-ambivalent path for equivalencies
1803
1884
  functionAmbivalentSubPathParts = [
1804
1885
  ...subPathParts.slice(0, -1),
1805
- subPathParts[subPathParts.length - 1].split('(')[0],
1886
+ lastPart.split('(')[0],
1806
1887
  ];
1807
1888
  functionAmbivalentSubPath = this.joinPathParts(
1808
1889
  functionAmbivalentSubPathParts,
1809
1890
  );
1810
- equivalentValues = [
1811
- ...(equivalentValues ?? []),
1812
- ...(scopeNode.equivalencies[functionAmbivalentSubPath] ?? []),
1813
- ];
1891
+ const functionAmbivalentEquivalencies =
1892
+ scopeNode.equivalencies[functionAmbivalentSubPath];
1893
+ if (functionAmbivalentEquivalencies?.length > 0) {
1894
+ equivalentValues = [
1895
+ ...equivalentValues,
1896
+ ...functionAmbivalentEquivalencies,
1897
+ ];
1898
+ }
1814
1899
  }
1815
1900
 
1816
1901
  // Early exit optimization: if no equivalencies to follow, skip expensive processing
1817
1902
  if (equivalentValues.length === 0) {
1903
+ followEquivalenciesEarlyExitCount++;
1904
+ if (this.onlyEquivalencies) {
1905
+ followEquivalenciesEarlyExitPhase1Count++;
1906
+ }
1818
1907
  return false;
1819
1908
  }
1909
+ followEquivalenciesWithWorkCount++;
1820
1910
 
1821
1911
  if (traceId && debugLevel > 1) {
1822
1912
  console.info(
@@ -1842,12 +1932,21 @@ export class ScopeDataStructure {
1842
1932
 
1843
1933
  const uniqueEquivalentValues = this.uniqueScopeVariables(equivalentValues);
1844
1934
 
1935
+ // PERF: Only create Set when chain is non-empty (common case avoids allocation)
1936
+ // Pre-compute Set of chain IDs for O(1) cycle detection instead of O(n) .some()
1937
+ const chainIdSet =
1938
+ equivalencyValueChain.length > 0
1939
+ ? new Set(equivalencyValueChain.map((ev) => ev.id))
1940
+ : null;
1941
+
1845
1942
  for (let index = 0; index < uniqueEquivalentValues.length; ++index) {
1846
1943
  const equivalentValue = uniqueEquivalentValues[index];
1847
1944
 
1945
+ // O(1) cycle check using Set instead of O(n) .some()
1848
1946
  if (
1947
+ chainIdSet &&
1849
1948
  equivalentValue.id !== -1 &&
1850
- equivalencyValueChain.some((ev) => ev.id === equivalentValue.id)
1949
+ chainIdSet.has(equivalentValue.id)
1851
1950
  ) {
1852
1951
  if (traceId) {
1853
1952
  console.info(
@@ -1898,8 +1997,12 @@ export class ScopeDataStructure {
1898
1997
  schemaPathParts[schemaPathParts.length - 1] ===
1899
1998
  lastRelevantSubPathPart.split('(')[0]
1900
1999
  ) {
1901
- schemaPathParts[schemaPathParts.length - 1] = lastRelevantSubPathPart;
1902
- schemaPath = this.joinPathParts(schemaPathParts);
2000
+ // PERF: Don't mutate the array - create a new one to avoid requiring structuredClone
2001
+ const updatedSchemaPathParts = [
2002
+ ...schemaPathParts.slice(0, -1),
2003
+ lastRelevantSubPathPart,
2004
+ ];
2005
+ schemaPath = this.joinPathParts(updatedSchemaPathParts);
1903
2006
  }
1904
2007
 
1905
2008
  const remainingPathParts = pathParts.slice(relevantSubPathParts.length);
@@ -1959,25 +2062,27 @@ export class ScopeDataStructure {
1959
2062
  );
1960
2063
  }
1961
2064
 
1962
- const localEquivalencyValueChain = structuredClone(
1963
- equivalencyValueChain,
1964
- );
1965
- localEquivalencyValueChain.push({
1966
- id: equivalentValue.id,
1967
- source: 'equivalence',
1968
- previousPath: {
1969
- scopeNodeName: scopeNode.name,
1970
- schemaPath: path,
1971
- value,
1972
- },
1973
- currentPath: {
1974
- scopeNodeName: equivalentScopeNode.name,
1975
- schemaPath: newEquivalentPath,
1976
- value,
2065
+ // PERF: Use spread instead of structuredClone - the chain items are immutable
2066
+ // so shallow copy is sufficient and much faster (structuredClone is expensive)
2067
+ const localEquivalencyValueChain = [
2068
+ ...equivalencyValueChain,
2069
+ {
2070
+ id: equivalentValue.id,
2071
+ source: 'equivalence',
2072
+ previousPath: {
2073
+ scopeNodeName: scopeNode.name,
2074
+ schemaPath: path,
2075
+ value,
2076
+ },
2077
+ currentPath: {
2078
+ scopeNodeName: equivalentScopeNode.name,
2079
+ schemaPath: newEquivalentPath,
2080
+ value,
2081
+ },
2082
+ reason: equivalentValue.equivalencyReason,
2083
+ traceId,
1977
2084
  },
1978
- reason: equivalentValue.equivalencyReason,
1979
- traceId,
1980
- });
2085
+ ];
1981
2086
 
1982
2087
  // writeEquivalencyToFile(
1983
2088
  // scopeNode.name,
@@ -1989,13 +2094,57 @@ export class ScopeDataStructure {
1989
2094
  // )
1990
2095
 
1991
2096
  propagated = true;
1992
- this.addToSchema({
1993
- path: newEquivalentPath,
1994
- value,
1995
- scopeNode: equivalentScopeNode,
1996
- equivalencyValueChain: localEquivalencyValueChain,
1997
- traceId,
1998
- });
2097
+
2098
+ // PERF: If batch processor is active, queue work instead of recursing
2099
+ // This converts deep recursion to iterative processing
2100
+ if (this.batchProcessor) {
2101
+ // PERF OPTIMIZATION: For external function calls, use path-only key (ignore value)
2102
+ // External FCs don't have internals to analyze, so processing the same path
2103
+ // with different values is redundant - we're just tracking data flow
2104
+ const isExternalFc =
2105
+ equivalentValue.equivalencyReason ===
2106
+ 'equivalency to external function call' ||
2107
+ this.getExternalFunctionCallInfo(equivalentScopeNode.name) !==
2108
+ undefined;
2109
+ const queueKey = isExternalFc
2110
+ ? `${equivalentScopeNode.name}::${newEquivalentPath}` // path-only for external FC
2111
+ : `${equivalentScopeNode.name}::${newEquivalentPath}::${value}`; // full key otherwise
2112
+
2113
+ // Always check visited - it catches already-processed items
2114
+ const alreadyVisited = this.visitedTracker.hasGlobalVisited(
2115
+ equivalentScopeNode.name,
2116
+ newEquivalentPath,
2117
+ value,
2118
+ );
2119
+ // For external FCs, queueKey is path-only so this catches any-value duplicates
2120
+ const alreadyQueued = this.batchQueuedSet?.has(queueKey);
2121
+
2122
+ if (alreadyVisited || alreadyQueued) {
2123
+ // Still record in database to capture the chain (as addToSchema does)
2124
+ this.addToEquivalencyDatabase(
2125
+ localEquivalencyValueChain as EquivalencyValueChainItem[],
2126
+ traceId,
2127
+ );
2128
+ } else {
2129
+ // Mark as queued to prevent duplicate queue entries
2130
+ this.batchQueuedSet?.add(queueKey);
2131
+ this.batchProcessor.addWork({
2132
+ scopeNodeName: equivalentScopeNode.name,
2133
+ path: newEquivalentPath,
2134
+ value,
2135
+ equivalencyValueChain: localEquivalencyValueChain,
2136
+ traceId,
2137
+ });
2138
+ }
2139
+ } else {
2140
+ this.addToSchema({
2141
+ path: newEquivalentPath,
2142
+ value,
2143
+ scopeNode: equivalentScopeNode,
2144
+ equivalencyValueChain: localEquivalencyValueChain,
2145
+ traceId,
2146
+ });
2147
+ }
1999
2148
  }
2000
2149
  }
2001
2150
 
@@ -2036,11 +2185,14 @@ export class ScopeDataStructure {
2036
2185
 
2037
2186
  // Guard against infinite recursion by tracking which paths we've already
2038
2187
  // added from addComplexSourcePathVariables
2039
- const complexPathKey = `${usageScopeNode.name}::${newUsageEquivalentPath}`;
2040
- if (this.complexSourceVisited.has(complexPathKey)) {
2188
+ if (
2189
+ this.visitedTracker.checkAndMarkComplexSourceVisited(
2190
+ usageScopeNode.name,
2191
+ newUsageEquivalentPath,
2192
+ )
2193
+ ) {
2041
2194
  continue;
2042
2195
  }
2043
- this.complexSourceVisited.add(complexPathKey);
2044
2196
 
2045
2197
  this.addToSchema({
2046
2198
  path: newUsageEquivalentPath,
@@ -2328,6 +2480,7 @@ export class ScopeDataStructure {
2328
2480
  if (functionScope) {
2329
2481
  functionScope.functionCalls.push(externalFunctionCallInfo);
2330
2482
  this.externalFunctionCalls.splice(i, 1);
2483
+ this.invalidateExternalFunctionCallsIndex();
2331
2484
 
2332
2485
  for (const equivalentPath in externalFunctionCallInfo.equivalencies) {
2333
2486
  let localEquivalentPath = equivalentPath;
@@ -2395,18 +2548,21 @@ export class ScopeDataStructure {
2395
2548
  for (const key in scopeNode.equivalencies) {
2396
2549
  const keyParts = this.splitPath(key);
2397
2550
  if (keyParts.length > 1) {
2398
- const lastPart = keyParts.pop();
2551
+ // PERF: Don't mutate the array - use indexing instead of pop() to avoid requiring structuredClone
2552
+ const lastPart = keyParts[keyParts.length - 1];
2399
2553
  if (lastPart.startsWith('signature[')) {
2400
- const functionCall = keyParts[keyParts.length - 1];
2554
+ const keyPartsWithoutLast = keyParts.slice(0, -1);
2555
+ const functionCall =
2556
+ keyPartsWithoutLast[keyPartsWithoutLast.length - 1];
2401
2557
  const argumentsIndex = functionCall.indexOf('(');
2402
2558
  const functionName = this.joinPathParts([
2403
- ...keyParts.slice(0, -1),
2559
+ ...keyPartsWithoutLast.slice(0, -1),
2404
2560
  functionCall.slice(
2405
2561
  0,
2406
2562
  argumentsIndex === -1 ? undefined : argumentsIndex,
2407
2563
  ),
2408
2564
  ]);
2409
- const callSignature = this.joinPathParts(keyParts);
2565
+ const callSignature = this.joinPathParts(keyPartsWithoutLast);
2410
2566
 
2411
2567
  const functionCallInfo = {
2412
2568
  name: functionName,
@@ -2423,19 +2579,21 @@ export class ScopeDataStructure {
2423
2579
  equivalentValues.schemaPath,
2424
2580
  );
2425
2581
  if (equivalentValueParts.length > 1) {
2426
- const lastPart = equivalentValueParts.pop();
2582
+ // PERF: Don't mutate the array - use indexing instead of pop() to avoid requiring structuredClone
2583
+ const lastPart =
2584
+ equivalentValueParts[equivalentValueParts.length - 1];
2427
2585
  if (lastPart.startsWith('functionCallReturnValue')) {
2428
- const functionCall =
2429
- equivalentValueParts[equivalentValueParts.length - 1];
2586
+ const partsWithoutLast = equivalentValueParts.slice(0, -1);
2587
+ const functionCall = partsWithoutLast[partsWithoutLast.length - 1];
2430
2588
  const argumentsIndex = functionCall.indexOf('(');
2431
2589
  const functionName = this.joinPathParts([
2432
- ...equivalentValueParts.slice(0, -1),
2590
+ ...partsWithoutLast.slice(0, -1),
2433
2591
  functionCall.slice(
2434
2592
  0,
2435
2593
  argumentsIndex === -1 ? undefined : argumentsIndex,
2436
2594
  ),
2437
2595
  ]);
2438
- const callSignature = this.joinPathParts(equivalentValueParts);
2596
+ const callSignature = this.joinPathParts(partsWithoutLast);
2439
2597
 
2440
2598
  const functionCallInfo = {
2441
2599
  name: functionName,
@@ -2636,7 +2794,8 @@ export class ScopeDataStructure {
2636
2794
  }
2637
2795
 
2638
2796
  getScopeNode(scopeName?: string): ScopeNode | undefined {
2639
- const scopeNode = this.scopeNodes[scopeName ?? this.scopeTree.name];
2797
+ const scopeNode =
2798
+ this.scopeNodes[scopeName ?? this.scopeTreeManager.getRootName()];
2640
2799
  if (scopeNode) return scopeNode;
2641
2800
 
2642
2801
  for (const scopeNodeName in this.scopeNodes) {
@@ -2646,18 +2805,54 @@ export class ScopeDataStructure {
2646
2805
  }
2647
2806
  }
2648
2807
 
2808
+ /**
2809
+ * Gets or builds the external function calls index for O(1) lookup.
2810
+ * The index maps both the full name and the name without generics to the FunctionCallInfo.
2811
+ */
2812
+ private getExternalFunctionCallsIndex(): Map<string, FunctionCallInfo> {
2813
+ if (this.externalFunctionCallsIndex === null) {
2814
+ this.externalFunctionCallsIndex = new Map();
2815
+ for (const efc of this.externalFunctionCalls) {
2816
+ this.externalFunctionCallsIndex.set(efc.name, efc);
2817
+ // Also index by name without generics (e.g., 'MyFunction<T>' -> 'MyFunction')
2818
+ const nameWithoutGenerics = this.pathManager.stripGenerics(efc.name);
2819
+ if (nameWithoutGenerics !== efc.name) {
2820
+ this.externalFunctionCallsIndex.set(nameWithoutGenerics, efc);
2821
+ }
2822
+ }
2823
+ }
2824
+ return this.externalFunctionCallsIndex;
2825
+ }
2826
+
2827
+ /**
2828
+ * Invalidates the external function calls index.
2829
+ * Call this after any mutation to externalFunctionCalls array.
2830
+ */
2831
+ private invalidateExternalFunctionCallsIndex(): void {
2832
+ this.externalFunctionCallsIndex = null;
2833
+ }
2834
+
2649
2835
  getExternalFunctionCallInfo(
2650
2836
  functionName: string,
2651
2837
  ): FunctionCallInfo | undefined {
2838
+ const searchKey = getFunctionCallRoot(functionName);
2839
+ const index = this.getExternalFunctionCallsIndex();
2840
+
2841
+ // First try exact match
2842
+ const exact = index.get(searchKey);
2843
+ if (exact) return exact;
2844
+
2845
+ // Fallback to the original find for edge cases not covered by index
2652
2846
  return this.externalFunctionCalls.find(
2653
2847
  (efc) =>
2654
- efc.name === getFunctionCallRoot(functionName) ||
2655
- efc.name.split('<')[0] === getFunctionCallRoot(functionName),
2848
+ efc.name === searchKey ||
2849
+ this.pathManager.stripGenerics(efc.name) === searchKey,
2656
2850
  );
2657
2851
  }
2658
2852
 
2659
2853
  getScopeAnalysis(scopeName?: string): ScopeAnalysis | undefined {
2660
- return this.scopeNodes[scopeName ?? this.scopeTree.name].analysis;
2854
+ return this.scopeNodes[scopeName ?? this.scopeTreeManager.getRootName()]
2855
+ .analysis;
2661
2856
  }
2662
2857
 
2663
2858
  getAnalysisTree(): ScopeTreeNode {
@@ -2671,12 +2866,13 @@ export class ScopeDataStructure {
2671
2866
  scopeName?: string;
2672
2867
  fillInUnknowns?: boolean;
2673
2868
  }): any {
2674
- const scopeNode = this.scopeNodes[scopeName ?? this.scopeTree.name];
2869
+ const scopeNode =
2870
+ this.scopeNodes[scopeName ?? this.scopeTreeManager.getRootName()];
2675
2871
 
2676
2872
  if (!scopeNode) {
2677
- const externalFunctionCallSchema = this.externalFunctionCalls.find(
2678
- (call) => call.name === getFunctionCallRoot(scopeName),
2679
- )?.schema;
2873
+ const searchKey = getFunctionCallRoot(scopeName);
2874
+ const externalFunctionCallSchema =
2875
+ this.getExternalFunctionCallsIndex().get(searchKey)?.schema;
2680
2876
 
2681
2877
  if (!externalFunctionCallSchema) return;
2682
2878
 
@@ -2709,9 +2905,9 @@ export class ScopeDataStructure {
2709
2905
  return this.equivalencyDatabaseCache.get(cacheKey);
2710
2906
  }
2711
2907
 
2712
- const result = this.equivalencyDatabase.find(
2713
- (entry) => entry.intermediatesOrder[cacheKey] !== undefined,
2714
- );
2908
+ // PERF: Use inverted index for O(1) lookup instead of O(n) array scan
2909
+ // The intermediatesOrderIndex maps pathId (scopeNodeName::schemaPath) to entry
2910
+ const result = this.intermediatesOrderIndex.get(cacheKey);
2715
2911
 
2716
2912
  this.equivalencyDatabaseCache.set(cacheKey, result);
2717
2913
  return result;
@@ -2815,7 +3011,7 @@ export class ScopeDataStructure {
2815
3011
  }
2816
3012
 
2817
3013
  const tempScopeNode = this.createTempScopeNode(
2818
- functionName ?? this.scopeTree.name,
3014
+ functionName ?? this.scopeTreeManager.getRootName(),
2819
3015
  signatureInSchema,
2820
3016
  equivalencies,
2821
3017
  );
@@ -2832,7 +3028,7 @@ export class ScopeDataStructure {
2832
3028
  functionName?: string;
2833
3029
  fillInUnknowns?: boolean;
2834
3030
  }) {
2835
- const scopeName = functionName ?? this.scopeTree.name;
3031
+ const scopeName = functionName ?? this.scopeTreeManager.getRootName();
2836
3032
  const scopeNode = this.scopeNodes[scopeName];
2837
3033
 
2838
3034
  let schema: ScopeNode['schema'] = {};
@@ -2857,14 +3053,7 @@ export class ScopeDataStructure {
2857
3053
  for (const schemaPath in externalFunctionCall.schema) {
2858
3054
  const value1 = schema[schemaPath];
2859
3055
  const value2 = externalFunctionCall.schema[schemaPath];
2860
- let bestValue = value1 ?? value2;
2861
- if (
2862
- bestValue === 'unknown' ||
2863
- (bestValue.includes('unknown') && !value2.includes('unknown'))
2864
- ) {
2865
- bestValue = value2;
2866
- }
2867
- schema[schemaPath] = bestValue;
3056
+ schema[schemaPath] = selectBestValue(value1, value2, value2);
2868
3057
  }
2869
3058
  }
2870
3059
  }
@@ -2990,7 +3179,7 @@ export class ScopeDataStructure {
2990
3179
  }
2991
3180
 
2992
3181
  getEquivalentSignatureVariables() {
2993
- const scopeNode = this.scopeNodes[this.scopeTree.name];
3182
+ const scopeNode = this.scopeNodes[this.scopeTreeManager.getRootName()];
2994
3183
 
2995
3184
  const equivalentSignatureVariables: Record<string, string> = {};
2996
3185
  for (const [path, equivalentValues] of Object.entries(
@@ -3012,7 +3201,7 @@ export class ScopeDataStructure {
3012
3201
  final?: boolean,
3013
3202
  ): VariableInfo | undefined {
3014
3203
  const scopeNode = this.getScopeOrFunctionCallInfo(
3015
- scopeName ?? this.scopeTree.name,
3204
+ scopeName ?? this.scopeTreeManager.getRootName(),
3016
3205
  );
3017
3206
  if (!scopeNode) return;
3018
3207
 
@@ -3049,7 +3238,7 @@ export class ScopeDataStructure {
3049
3238
  );
3050
3239
 
3051
3240
  const tempScopeNode = this.createTempScopeNode(
3052
- scopeName ?? this.scopeTree.name,
3241
+ scopeName ?? this.scopeTreeManager.getRootName(),
3053
3242
  relevantSchema,
3054
3243
  );
3055
3244
 
@@ -3070,6 +3259,87 @@ export class ScopeDataStructure {
3070
3259
  return this.environmentVariables;
3071
3260
  }
3072
3261
 
3262
+ /**
3263
+ * Add conditional usages from AST analysis.
3264
+ * Called during scope analysis to collect all conditionals.
3265
+ */
3266
+ addConditionalUsages(
3267
+ usages: Record<
3268
+ string,
3269
+ Array<{
3270
+ path: string;
3271
+ conditionType: 'truthiness' | 'comparison' | 'switch';
3272
+ comparedValues?: string[];
3273
+ location: 'if' | 'ternary' | 'logical-and' | 'switch';
3274
+ }>
3275
+ >,
3276
+ ): void {
3277
+ for (const [path, pathUsages] of Object.entries(usages)) {
3278
+ if (!this.rawConditionalUsages[path]) {
3279
+ this.rawConditionalUsages[path] = [];
3280
+ }
3281
+ // Deduplicate usages
3282
+ for (const usage of pathUsages) {
3283
+ const exists = this.rawConditionalUsages[path].some(
3284
+ (existing) =>
3285
+ existing.location === usage.location &&
3286
+ existing.conditionType === usage.conditionType &&
3287
+ JSON.stringify(existing.comparedValues) ===
3288
+ JSON.stringify(usage.comparedValues),
3289
+ );
3290
+ if (!exists) {
3291
+ this.rawConditionalUsages[path].push(usage);
3292
+ }
3293
+ }
3294
+ }
3295
+ }
3296
+
3297
+ /**
3298
+ * Get enriched conditional usages with source tracing.
3299
+ * Uses explainPath to trace each local variable back to its data source.
3300
+ */
3301
+ getEnrichedConditionalUsages(): Record<
3302
+ string,
3303
+ Array<{
3304
+ path: string;
3305
+ conditionType: 'truthiness' | 'comparison' | 'switch';
3306
+ comparedValues?: string[];
3307
+ location: 'if' | 'ternary' | 'logical-and' | 'switch';
3308
+ sourceDataPath?: string;
3309
+ }>
3310
+ > {
3311
+ const enriched: Record<
3312
+ string,
3313
+ Array<{
3314
+ path: string;
3315
+ conditionType: 'truthiness' | 'comparison' | 'switch';
3316
+ comparedValues?: string[];
3317
+ location: 'if' | 'ternary' | 'logical-and' | 'switch';
3318
+ sourceDataPath?: string;
3319
+ }>
3320
+ > = {};
3321
+
3322
+ for (const [path, usages] of Object.entries(this.rawConditionalUsages)) {
3323
+ // Try to trace this path back to a data source
3324
+ // First, try the root scope
3325
+ const rootScopeName = this.scopeTreeManager.getTree().name;
3326
+ const explanation = this.explainPath(rootScopeName, path);
3327
+
3328
+ let sourceDataPath: string | undefined;
3329
+ if (explanation.source) {
3330
+ // Build the full data path: scopeName.path
3331
+ sourceDataPath = `${explanation.source.scope}.${explanation.source.path}`;
3332
+ }
3333
+
3334
+ enriched[path] = usages.map((usage) => ({
3335
+ ...usage,
3336
+ sourceDataPath,
3337
+ }));
3338
+ }
3339
+
3340
+ return enriched;
3341
+ }
3342
+
3073
3343
  toSerializable(): SerializableDataStructure {
3074
3344
  // Helper to convert ScopeVariable to SerializableScopeVariable
3075
3345
  const toSerializableVariable = (
@@ -3148,12 +3418,598 @@ export class ScopeDataStructure {
3148
3418
 
3149
3419
  const environmentVariables = this.getEnvironmentVariables();
3150
3420
 
3421
+ // Get enriched conditional usages with source tracing
3422
+ const enrichedConditionalUsages = this.getEnrichedConditionalUsages();
3423
+ const conditionalUsages =
3424
+ Object.keys(enrichedConditionalUsages).length > 0
3425
+ ? enrichedConditionalUsages
3426
+ : undefined;
3427
+
3151
3428
  return {
3152
3429
  externalFunctionCalls,
3153
3430
  rootFunction,
3154
3431
  functionResults,
3155
3432
  equivalentSignatureVariables,
3156
3433
  environmentVariables,
3434
+ conditionalUsages,
3157
3435
  };
3158
3436
  }
3437
+
3438
+ // ═══════════════════════════════════════════════════════════════════════════
3439
+ // DEBUGGING HELPERS
3440
+ // These methods help understand what's happening during analysis.
3441
+ // Use them when investigating why a path is missing or has the wrong type.
3442
+ // ═══════════════════════════════════════════════════════════════════════════
3443
+
3444
+ /**
3445
+ * Explains a path by tracing its equivalencies and showing where data comes from.
3446
+ *
3447
+ * @example
3448
+ * ```typescript
3449
+ * const explanation = sds.explainPath('MyComponent', 'user.id');
3450
+ * console.log(explanation);
3451
+ * // {
3452
+ * // path: 'user.id',
3453
+ * // scope: 'MyComponent',
3454
+ * // schemaValue: 'string',
3455
+ * // equivalencies: [
3456
+ * // { scope: 'MyComponent', path: 'signature[0].user.id' },
3457
+ * // { scope: 'UserProfile', path: 'props.user.id' }
3458
+ * // ],
3459
+ * // source: { scope: 'fetchUser', path: 'functionCallReturnValue(fetch).data.user.id' }
3460
+ * // }
3461
+ * ```
3462
+ */
3463
+ explainPath(
3464
+ scopeName: string,
3465
+ path: string,
3466
+ ): {
3467
+ path: string;
3468
+ scope: string;
3469
+ schemaValue: string | undefined;
3470
+ equivalencies: Array<{ scope: string; path: string; reason?: string }>;
3471
+ databaseEntry: EquivalencyDatabaseEntry | undefined;
3472
+ source: { scope: string; path: string } | undefined;
3473
+ } {
3474
+ const scopeNode = this.getScopeOrFunctionCallInfo(scopeName);
3475
+ if (!scopeNode) {
3476
+ return {
3477
+ path,
3478
+ scope: scopeName,
3479
+ schemaValue: undefined,
3480
+ equivalencies: [],
3481
+ databaseEntry: undefined,
3482
+ source: undefined,
3483
+ };
3484
+ }
3485
+
3486
+ const schemaValue = scopeNode.schema?.[path];
3487
+ const rawEquivalencies = scopeNode.equivalencies?.[path] ?? [];
3488
+
3489
+ const equivalencies = rawEquivalencies.map((eq) => ({
3490
+ scope: eq.scopeNodeName,
3491
+ path: eq.schemaPath,
3492
+ reason: eq.equivalencyReason,
3493
+ }));
3494
+
3495
+ const databaseEntry = this.getEquivalenciesDatabaseEntry(scopeName, path);
3496
+ const source =
3497
+ databaseEntry?.sourceCandidates?.[0] &&
3498
+ databaseEntry.sourceCandidates.length > 0
3499
+ ? {
3500
+ scope: databaseEntry.sourceCandidates[0].scopeNodeName,
3501
+ path: databaseEntry.sourceCandidates[0].schemaPath,
3502
+ }
3503
+ : undefined;
3504
+
3505
+ return {
3506
+ path,
3507
+ scope: scopeName,
3508
+ schemaValue,
3509
+ equivalencies,
3510
+ databaseEntry,
3511
+ source,
3512
+ };
3513
+ }
3514
+
3515
+ /**
3516
+ * Dumps the current state of analysis for inspection.
3517
+ * Useful for understanding the overall state or finding issues.
3518
+ *
3519
+ * @param options - What to include in the dump
3520
+ * @returns A summary object with requested data
3521
+ */
3522
+ dumpState(options?: {
3523
+ includeSchemas?: boolean;
3524
+ includeEquivalencies?: boolean;
3525
+ scopeFilter?: string;
3526
+ }): {
3527
+ scopeCount: number;
3528
+ externalCallCount: number;
3529
+ equivalencyDatabaseSize: number;
3530
+ metrics: {
3531
+ addToSchemaCallCount: number;
3532
+ followEquivalenciesCallCount: number;
3533
+ maxEquivalencyChainDepth: number;
3534
+ };
3535
+ scopes: Array<{
3536
+ name: string;
3537
+ schemaKeyCount: number;
3538
+ equivalencyKeyCount: number;
3539
+ functionCallCount: number;
3540
+ schema?: Record<string, string>;
3541
+ equivalencies?: Record<string, Array<{ scope: string; path: string }>>;
3542
+ }>;
3543
+ } {
3544
+ const includeSchemas = options?.includeSchemas ?? false;
3545
+ const includeEquivalencies = options?.includeEquivalencies ?? false;
3546
+ const scopeFilter = options?.scopeFilter;
3547
+
3548
+ const scopeNames = Object.keys(this.scopeNodes).filter(
3549
+ (name) => !scopeFilter || name.includes(scopeFilter),
3550
+ );
3551
+
3552
+ const scopes = scopeNames.map((name) => {
3553
+ const node = this.scopeNodes[name];
3554
+ const result: {
3555
+ name: string;
3556
+ schemaKeyCount: number;
3557
+ equivalencyKeyCount: number;
3558
+ functionCallCount: number;
3559
+ schema?: Record<string, string>;
3560
+ equivalencies?: Record<string, Array<{ scope: string; path: string }>>;
3561
+ } = {
3562
+ name,
3563
+ schemaKeyCount: Object.keys(node.schema ?? {}).length,
3564
+ equivalencyKeyCount: Object.keys(node.equivalencies ?? {}).length,
3565
+ functionCallCount: node.functionCalls?.length ?? 0,
3566
+ };
3567
+
3568
+ if (includeSchemas) {
3569
+ result.schema = node.schema;
3570
+ }
3571
+
3572
+ if (includeEquivalencies) {
3573
+ result.equivalencies = Object.entries(node.equivalencies ?? {}).reduce(
3574
+ (acc, [key, vals]) => {
3575
+ acc[key] = vals.map((v) => ({
3576
+ scope: v.scopeNodeName,
3577
+ path: v.schemaPath,
3578
+ }));
3579
+ return acc;
3580
+ },
3581
+ {} as Record<string, Array<{ scope: string; path: string }>>,
3582
+ );
3583
+ }
3584
+
3585
+ return result;
3586
+ });
3587
+
3588
+ return {
3589
+ scopeCount: Object.keys(this.scopeNodes).length,
3590
+ externalCallCount: this.externalFunctionCalls.length,
3591
+ equivalencyDatabaseSize: this.equivalencyDatabase.length,
3592
+ metrics: {
3593
+ addToSchemaCallCount,
3594
+ followEquivalenciesCallCount,
3595
+ maxEquivalencyChainDepth,
3596
+ },
3597
+ scopes,
3598
+ };
3599
+ }
3600
+
3601
+ /**
3602
+ * Traces the full equivalency chain for a path, showing how data flows.
3603
+ * This is the most detailed debugging tool for understanding data tracing.
3604
+ *
3605
+ * @example
3606
+ * ```typescript
3607
+ * const chain = sds.traceEquivalencyChain('MyComponent', 'user.id');
3608
+ * // Returns array of steps showing how user.id is traced back to its source
3609
+ * ```
3610
+ */
3611
+ traceEquivalencyChain(
3612
+ scopeName: string,
3613
+ path: string,
3614
+ maxDepth = 20,
3615
+ ): Array<{
3616
+ step: number;
3617
+ scope: string;
3618
+ path: string;
3619
+ schemaValue?: string;
3620
+ nextEquivalencies: Array<{ scope: string; path: string; reason?: string }>;
3621
+ }> {
3622
+ const chain: Array<{
3623
+ step: number;
3624
+ scope: string;
3625
+ path: string;
3626
+ schemaValue?: string;
3627
+ nextEquivalencies: Array<{
3628
+ scope: string;
3629
+ path: string;
3630
+ reason?: string;
3631
+ }>;
3632
+ }> = [];
3633
+
3634
+ const visited = new Set<string>();
3635
+ const queue: Array<{ scope: string; path: string; depth: number }> = [
3636
+ { scope: scopeName, path, depth: 0 },
3637
+ ];
3638
+
3639
+ while (queue.length > 0 && chain.length < maxDepth) {
3640
+ const current = queue.shift()!;
3641
+ const key = `${current.scope}::${current.path}`;
3642
+
3643
+ if (visited.has(key)) continue;
3644
+ visited.add(key);
3645
+
3646
+ const scopeNode = this.getScopeOrFunctionCallInfo(current.scope);
3647
+ const schemaValue = scopeNode?.schema?.[current.path];
3648
+ const rawEquivalencies = scopeNode?.equivalencies?.[current.path] ?? [];
3649
+
3650
+ const nextEquivalencies = rawEquivalencies.map((eq) => ({
3651
+ scope: eq.scopeNodeName,
3652
+ path: eq.schemaPath,
3653
+ reason: eq.equivalencyReason,
3654
+ }));
3655
+
3656
+ chain.push({
3657
+ step: chain.length + 1,
3658
+ scope: current.scope,
3659
+ path: current.path,
3660
+ schemaValue,
3661
+ nextEquivalencies,
3662
+ });
3663
+
3664
+ // Add next equivalencies to queue for further tracing
3665
+ for (const eq of nextEquivalencies) {
3666
+ const nextKey = `${eq.scope}::${eq.path}`;
3667
+ if (!visited.has(nextKey)) {
3668
+ queue.push({
3669
+ scope: eq.scope,
3670
+ path: eq.path,
3671
+ depth: current.depth + 1,
3672
+ });
3673
+ }
3674
+ }
3675
+ }
3676
+
3677
+ return chain;
3678
+ }
3679
+
3680
+ /**
3681
+ * Finds all paths in a scope that match a pattern.
3682
+ * Useful for finding related paths when debugging.
3683
+ *
3684
+ * @example
3685
+ * ```typescript
3686
+ * const paths = sds.findPaths('MyComponent', /user/);
3687
+ * // Returns all schema paths containing "user"
3688
+ * ```
3689
+ */
3690
+ findPaths(
3691
+ scopeName: string,
3692
+ pattern: RegExp | string,
3693
+ ): Array<{ path: string; value: string; hasEquivalencies: boolean }> {
3694
+ const scopeNode = this.getScopeOrFunctionCallInfo(scopeName);
3695
+ if (!scopeNode) return [];
3696
+
3697
+ const regex = typeof pattern === 'string' ? new RegExp(pattern) : pattern;
3698
+ const results: Array<{
3699
+ path: string;
3700
+ value: string;
3701
+ hasEquivalencies: boolean;
3702
+ }> = [];
3703
+
3704
+ // Search in schema
3705
+ for (const [path, value] of Object.entries(scopeNode.schema ?? {})) {
3706
+ if (regex.test(path)) {
3707
+ results.push({
3708
+ path,
3709
+ value,
3710
+ hasEquivalencies: !!scopeNode.equivalencies?.[path]?.length,
3711
+ });
3712
+ }
3713
+ }
3714
+
3715
+ // Also search equivalency keys that might not be in schema
3716
+ for (const path of Object.keys(scopeNode.equivalencies ?? {})) {
3717
+ if (regex.test(path) && !results.find((r) => r.path === path)) {
3718
+ results.push({
3719
+ path,
3720
+ value: scopeNode.schema?.[path] ?? 'not-in-schema',
3721
+ hasEquivalencies: true,
3722
+ });
3723
+ }
3724
+ }
3725
+
3726
+ return results.sort((a, b) => a.path.localeCompare(b.path));
3727
+ }
3728
+
3729
+ /**
3730
+ * Returns a summary of why a path might be missing from the schema.
3731
+ * Checks common issues that cause paths to not appear.
3732
+ */
3733
+ diagnoseMissingPath(
3734
+ scopeName: string,
3735
+ path: string,
3736
+ ): {
3737
+ exists: boolean;
3738
+ inSchema: boolean;
3739
+ inEquivalencies: boolean;
3740
+ possibleReasons: string[];
3741
+ suggestions: string[];
3742
+ } {
3743
+ const scopeNode = this.getScopeOrFunctionCallInfo(scopeName);
3744
+ const possibleReasons: string[] = [];
3745
+ const suggestions: string[] = [];
3746
+
3747
+ if (!scopeNode) {
3748
+ possibleReasons.push(`Scope "${scopeName}" does not exist`);
3749
+ suggestions.push(
3750
+ `Available scopes: ${Object.keys(this.scopeNodes).join(', ')}`,
3751
+ );
3752
+ return {
3753
+ exists: false,
3754
+ inSchema: false,
3755
+ inEquivalencies: false,
3756
+ possibleReasons,
3757
+ suggestions,
3758
+ };
3759
+ }
3760
+
3761
+ const inSchema = path in (scopeNode.schema ?? {});
3762
+ const inEquivalencies = path in (scopeNode.equivalencies ?? {});
3763
+
3764
+ if (inSchema) {
3765
+ return {
3766
+ exists: true,
3767
+ inSchema: true,
3768
+ inEquivalencies,
3769
+ possibleReasons: [],
3770
+ suggestions: [],
3771
+ };
3772
+ }
3773
+
3774
+ // Check for similar paths
3775
+ const allPaths = [
3776
+ ...Object.keys(scopeNode.schema ?? {}),
3777
+ ...Object.keys(scopeNode.equivalencies ?? {}),
3778
+ ];
3779
+
3780
+ const similarPaths = allPaths.filter((p) => {
3781
+ const pathParts = path.split('.');
3782
+ const pParts = p.split('.');
3783
+ return (
3784
+ pathParts.some((part) => pParts.includes(part)) ||
3785
+ p.includes(path) ||
3786
+ path.includes(p)
3787
+ );
3788
+ });
3789
+
3790
+ if (similarPaths.length > 0) {
3791
+ possibleReasons.push(`Path "${path}" not found but similar paths exist`);
3792
+ suggestions.push(`Similar paths: ${similarPaths.slice(0, 5).join(', ')}`);
3793
+ }
3794
+
3795
+ // Check if it's a partial path
3796
+ const parentPath = path.split('.').slice(0, -1).join('.');
3797
+ if (parentPath && scopeNode.schema?.[parentPath]) {
3798
+ possibleReasons.push(
3799
+ `Parent path "${parentPath}" exists with value "${scopeNode.schema[parentPath]}"`,
3800
+ );
3801
+ suggestions.push(
3802
+ `The property might not have been accessed in the analyzed code`,
3803
+ );
3804
+ }
3805
+
3806
+ // Check visited tracker
3807
+ const wasVisited = this.visitedTracker.wasVisited(scopeName, path);
3808
+ if (wasVisited) {
3809
+ possibleReasons.push(`Path was visited during analysis but not written`);
3810
+ suggestions.push(
3811
+ `Check if the path was filtered by isValidPath() or hit cycle detection`,
3812
+ );
3813
+ }
3814
+
3815
+ if (possibleReasons.length === 0) {
3816
+ possibleReasons.push(
3817
+ `Path "${path}" was never encountered during analysis`,
3818
+ );
3819
+ suggestions.push(
3820
+ `Verify the path is accessed in the source code being analyzed`,
3821
+ );
3822
+ }
3823
+
3824
+ return {
3825
+ exists: false,
3826
+ inSchema,
3827
+ inEquivalencies,
3828
+ possibleReasons,
3829
+ suggestions,
3830
+ };
3831
+ }
3832
+
3833
+ /**
3834
+ * Analyzes the stored equivalencies to provide aggregate statistics.
3835
+ * Call this AFTER analysis completes to understand equivalency patterns.
3836
+ *
3837
+ * @example
3838
+ * ```typescript
3839
+ * const analysis = sds.analyzeEquivalencies();
3840
+ * console.log(analysis.byReason); // Count by reason
3841
+ * console.log(analysis.byScope); // Count by scope
3842
+ * console.log(analysis.hotSpots); // Scopes with most equivalencies
3843
+ * ```
3844
+ */
3845
+ analyzeEquivalencies(): {
3846
+ total: number;
3847
+ byReason: Record<string, number>;
3848
+ byScope: Record<string, number>;
3849
+ hotSpots: Array<{ scope: string; count: number }>;
3850
+ unusedReasons: string[];
3851
+ } {
3852
+ const byReason: Record<string, number> = {};
3853
+ const byScope: Record<string, number> = {};
3854
+ let total = 0;
3855
+
3856
+ // Collect from all scope nodes
3857
+ for (const scopeName of Object.keys(this.scopeNodes)) {
3858
+ const scopeNode = this.scopeNodes[scopeName];
3859
+ const equivalencies = scopeNode.equivalencies ?? {};
3860
+
3861
+ for (const path of Object.keys(equivalencies)) {
3862
+ for (const eq of equivalencies[path]) {
3863
+ total++;
3864
+ const reason = eq.equivalencyReason ?? 'unknown';
3865
+ byReason[reason] = (byReason[reason] ?? 0) + 1;
3866
+ byScope[scopeName] = (byScope[scopeName] ?? 0) + 1;
3867
+ }
3868
+ }
3869
+ }
3870
+
3871
+ // Also check external function calls
3872
+ for (const fc of this.externalFunctionCalls) {
3873
+ const equivalencies = fc.equivalencies ?? {};
3874
+ for (const path of Object.keys(equivalencies)) {
3875
+ for (const eq of equivalencies[path]) {
3876
+ total++;
3877
+ const reason = eq.equivalencyReason ?? 'unknown';
3878
+ byReason[reason] = (byReason[reason] ?? 0) + 1;
3879
+ byScope[fc.name] = (byScope[fc.name] ?? 0) + 1;
3880
+ }
3881
+ }
3882
+ }
3883
+
3884
+ // Find hot spots (scopes with most equivalencies)
3885
+ const hotSpots = Object.entries(byScope)
3886
+ .map(([scope, count]) => ({ scope, count }))
3887
+ .sort((a, b) => b.count - a.count)
3888
+ .slice(0, 10);
3889
+
3890
+ // Find reasons that appear in stored equivalencies but aren't in ALLOWED list
3891
+ const unusedReasons = Object.keys(byReason).filter(
3892
+ (reason) => !ALLOWED_EQUIVALENCY_REASONS.has(reason),
3893
+ );
3894
+
3895
+ return {
3896
+ total,
3897
+ byReason,
3898
+ byScope,
3899
+ hotSpots,
3900
+ unusedReasons,
3901
+ };
3902
+ }
3903
+
3904
+ /**
3905
+ * Validates equivalencies and identifies potential problems.
3906
+ * Returns actionable issues that may indicate bugs or optimization opportunities.
3907
+ *
3908
+ * @example
3909
+ * ```typescript
3910
+ * const issues = sds.validateEquivalencies();
3911
+ * if (issues.length > 0) {
3912
+ * console.log('Found issues:', issues);
3913
+ * }
3914
+ * ```
3915
+ */
3916
+ validateEquivalencies(): Array<{
3917
+ type: 'broken_reference' | 'dead_end' | 'long_chain' | 'circular';
3918
+ severity: 'error' | 'warning';
3919
+ scope: string;
3920
+ path: string;
3921
+ details: string;
3922
+ }> {
3923
+ const issues: Array<{
3924
+ type: 'broken_reference' | 'dead_end' | 'long_chain' | 'circular';
3925
+ severity: 'error' | 'warning';
3926
+ scope: string;
3927
+ path: string;
3928
+ details: string;
3929
+ }> = [];
3930
+
3931
+ const allScopeNames = new Set([
3932
+ ...Object.keys(this.scopeNodes),
3933
+ ...this.externalFunctionCalls.map((fc) => fc.name),
3934
+ ]);
3935
+
3936
+ // Check all scope nodes
3937
+ for (const scopeName of Object.keys(this.scopeNodes)) {
3938
+ const scopeNode = this.scopeNodes[scopeName];
3939
+ const equivalencies = scopeNode.equivalencies ?? {};
3940
+
3941
+ for (const [path, eqs] of Object.entries(equivalencies)) {
3942
+ for (const eq of eqs) {
3943
+ // Check 1: Does the target scope exist?
3944
+ if (!allScopeNames.has(eq.scopeNodeName)) {
3945
+ issues.push({
3946
+ type: 'broken_reference',
3947
+ severity: 'error',
3948
+ scope: scopeName,
3949
+ path,
3950
+ details: `Equivalency points to non-existent scope "${eq.scopeNodeName}"`,
3951
+ });
3952
+ continue;
3953
+ }
3954
+
3955
+ // Check 2: Does the target path exist in target scope's schema or equivalencies?
3956
+ const targetScope = this.getScopeOrFunctionCallInfo(eq.scopeNodeName);
3957
+ if (targetScope) {
3958
+ const hasInSchema = eq.schemaPath in (targetScope.schema ?? {});
3959
+ const hasInEquivalencies =
3960
+ eq.schemaPath in (targetScope.equivalencies ?? {});
3961
+
3962
+ // Only flag as dead end if it's a leaf path (no sub-properties exist)
3963
+ if (!hasInSchema && !hasInEquivalencies) {
3964
+ const hasSubPaths = Object.keys(targetScope.schema ?? {}).some(
3965
+ (p) =>
3966
+ p.startsWith(eq.schemaPath + '.') ||
3967
+ p.startsWith(eq.schemaPath + '['),
3968
+ );
3969
+ if (!hasSubPaths) {
3970
+ issues.push({
3971
+ type: 'dead_end',
3972
+ severity: 'warning',
3973
+ scope: scopeName,
3974
+ path,
3975
+ details: `Equivalency to "${eq.scopeNodeName}::${eq.schemaPath}" - path not in schema`,
3976
+ });
3977
+ }
3978
+ }
3979
+ }
3980
+ }
3981
+
3982
+ // Check 3: Trace chain depth
3983
+ const chain = this.traceEquivalencyChain(scopeName, path, 50);
3984
+ if (chain.length >= 20) {
3985
+ issues.push({
3986
+ type: 'long_chain',
3987
+ severity: 'warning',
3988
+ scope: scopeName,
3989
+ path,
3990
+ details: `Equivalency chain depth is ${chain.length} (may impact performance)`,
3991
+ });
3992
+ }
3993
+
3994
+ // Check for potential cycles (chain that returns to starting point)
3995
+ const visited = new Set<string>();
3996
+ for (const step of chain) {
3997
+ const key = `${step.scope}::${step.path}`;
3998
+ if (visited.has(key)) {
3999
+ issues.push({
4000
+ type: 'circular',
4001
+ severity: 'warning',
4002
+ scope: scopeName,
4003
+ path,
4004
+ details: `Circular reference detected at ${key}`,
4005
+ });
4006
+ break;
4007
+ }
4008
+ visited.add(key);
4009
+ }
4010
+ }
4011
+ }
4012
+
4013
+ return issues;
4014
+ }
3159
4015
  }