@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,77 +1,214 @@
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
- import { joinParenthesesAndArrays, splitOutsideParenthesesAndArrays, } from "../splitOutsideParentheses.js";
24
81
  import fillInSchemaGapsAndUnknowns from "./helpers/fillInSchemaGapsAndUnknowns.js";
25
82
  import ensureSchemaConsistency from "./helpers/ensureSchemaConsistency.js";
26
- import cleanOutBoundary from "../cleanOutBoundary.js";
27
83
  import cleanPath from "./helpers/cleanPath.js";
84
+ import { PathManager } from "./helpers/PathManager.js";
85
+ import { uniqueId, uniqueScopeVariables, uniqueScopeAndPaths, } from "./helpers/uniqueIdUtils.js";
86
+ import selectBestValue from "./helpers/selectBestValue.js";
87
+ import { VisitedTracker } from "./helpers/VisitedTracker.js";
88
+ import { DebugTracer } from "./helpers/DebugTracer.js";
89
+ import { BatchSchemaProcessor } from "./helpers/BatchSchemaProcessor.js";
90
+ import { ScopeTreeManager, ROOT_SCOPE_NAME, } from "./helpers/ScopeTreeManager.js";
28
91
  import cleanScopeNodeName from "./helpers/cleanScopeNodeName.js";
29
92
  import getFunctionCallRoot from "./helpers/getFunctionCallRoot.js";
30
93
  import cleanPathOfNonTransformingFunctions from "./helpers/cleanPathOfNonTransformingFunctions.js";
31
94
  import { arrayMethodsSet } from "./helpers/cleanNonObjectFunctions.js";
32
- const ROOT_SCOPE_NAME = 'root';
33
95
  // DEBUG: Performance metrics
34
96
  export let maxEquivalencyChainDepth = 0;
35
97
  export let addToSchemaCallCount = 0;
36
98
  export let followEquivalenciesCallCount = 0;
99
+ export let followEquivalenciesEarlyExitCount = 0;
100
+ export let followEquivalenciesEarlyExitPhase1Count = 0;
101
+ export let followEquivalenciesWithWorkCount = 0;
37
102
  export let addEquivalencyCallCount = 0;
38
103
  export function resetScopeDataStructureMetrics() {
39
104
  maxEquivalencyChainDepth = 0;
40
105
  addToSchemaCallCount = 0;
41
106
  followEquivalenciesCallCount = 0;
107
+ followEquivalenciesEarlyExitCount = 0;
108
+ followEquivalenciesEarlyExitPhase1Count = 0;
109
+ followEquivalenciesWithWorkCount = 0;
42
110
  addEquivalencyCallCount = 0;
43
111
  }
112
+ // Performance: Pre-computed Sets for equivalency reason filtering (O(1) vs O(n))
113
+ const ALLOWED_EQUIVALENCY_REASONS = new Set([
114
+ 'original equivalency',
115
+ 'implicit parent equivalency',
116
+ 'explicit parent equivalency',
117
+ 'transformed non-object function equivalency - original equivalency',
118
+ 'equivalency to external function call',
119
+ 'functionCall to function signature equivalency',
120
+ 'explicit parent signature',
121
+ 'useState setter call equivalency',
122
+ 'non-object function argument function signature equivalency1',
123
+ 'non-object function argument function signature equivalency2',
124
+ 'returnValue to functionCallReturnValue equivalency',
125
+ '.map() function deconstruction',
126
+ 'useMemo return value equivalent to first argument return value',
127
+ 'useState value equivalency',
128
+ 'Node .then() equivalency',
129
+ 'Explicit array deconstruction equivalency value',
130
+ 'forwardRef equivalency',
131
+ 'forwardRef signature to child signature equivalency',
132
+ 'captured function call return value equivalency',
133
+ 'original equivalency - rerouted via useCallback',
134
+ 'non-object function argument function signature equivalency1 - rerouted via useCallback',
135
+ 'non-object function argument function signature equivalency2 - rerouted via useCallback',
136
+ 'implicit parent equivalency - rerouted via useCallback',
137
+ 'Spread operator equivalency key update: implicit parent equivalency',
138
+ 'Array.from() equivalency',
139
+ 'propagated sub-property equivalency',
140
+ 'propagated function call return sub-property equivalency',
141
+ 'where was this function called from', // Added: tracks which scope called an external function
142
+ ]);
143
+ const SILENTLY_IGNORED_EQUIVALENCY_REASONS = new Set([
144
+ 'signature of functionCall',
145
+ 'transformed non-object function equivalency - implicit parent equivalency',
146
+ 'transformed non-object function equivalency - non-object function argument function signature equivalency1',
147
+ 'transformed non-object function equivalency - non-object function argument function signature equivalency2',
148
+ 'transformed non-object function equivalency - equivalency to external function call',
149
+ 'Explicit array deconstruction equivalency key',
150
+ 'transformed non-object function equivalency - useState setter call equivalency',
151
+ 'transformed non-object function equivalency - implicit parent equivalency - rerouted via useCallback',
152
+ 'transformed non-object function equivalency - Array.from() equivalency',
153
+ 'Spread operator equivalency key update: Explicit array deconstruction equivalency value',
154
+ ]);
44
155
  export class ScopeDataStructure {
156
+ // Getter for backward compatibility - returns the tree structure
157
+ get scopeTree() {
158
+ return this.scopeTreeManager.getTree();
159
+ }
45
160
  constructor(managers, scopeName = ROOT_SCOPE_NAME, scopeText, scopeAnalysis) {
46
161
  this.debugCount = 0;
47
162
  this.onlyEquivalencies = true;
48
163
  this.equivalencyManagers = [];
49
164
  this.scopeNodes = {};
50
- this.scopeTree = { name: ROOT_SCOPE_NAME, children: [] };
165
+ this.scopeTreeManager = new ScopeTreeManager();
51
166
  this.externalFunctionCalls = [];
52
167
  this.environmentVariables = [];
53
168
  this.equivalencyDatabase = [];
169
+ /**
170
+ * Conditional usages collected during AST analysis.
171
+ * Maps local variable path to array of usages.
172
+ */
173
+ this.rawConditionalUsages = {};
54
174
  this.lastAddToSchemaId = 0;
55
175
  this.lastEquivalencyId = 0;
56
176
  this.lastEquivalencyDatabaseId = 0;
57
- this.pathPartsCache = new Map();
58
- this.pathJoinCache = new Map();
177
+ this.pathManager = new PathManager();
178
+ this.visitedTracker = new VisitedTracker();
59
179
  this.equivalencyDatabaseCache = new Map();
60
180
  // Inverted index: maps uniqueId -> EquivalencyDatabaseEntry for O(1) lookup
61
181
  this.intermediatesOrderIndex = new Map();
62
- this.globalVisited = new Set();
63
- // Separate visited set for addComplexSourcePathVariables - uses scope::path only (not value)
64
- // This allows addComplexSourcePathVariables to run for each unique scope+path combo,
65
- // while the main globalVisited uses scope+path+value for fine-grained deduplication
66
- this.complexSourceVisited = new Set();
182
+ // Index for O(1) lookup of external function calls by name
183
+ // Invalidated by setting to null; rebuilt lazily on next access
184
+ this.externalFunctionCallsIndex = null;
185
+ // Debug tracer for selective path/scope tracing
186
+ // Enable via: CODEYAM_DEBUG=true CODEYAM_DEBUG_PATHS="user.*,signature" npm test
187
+ this.tracer = new DebugTracer({
188
+ enabled: process.env.CODEYAM_DEBUG === 'true',
189
+ pathPatterns: process.env.CODEYAM_DEBUG_PATHS
190
+ ? process.env.CODEYAM_DEBUG_PATHS.split(',').map((p) => new RegExp(p))
191
+ : [],
192
+ scopePatterns: process.env.CODEYAM_DEBUG_SCOPES
193
+ ? process.env.CODEYAM_DEBUG_SCOPES.split(',').map((p) => new RegExp(p))
194
+ : [],
195
+ maxDepth: 20,
196
+ });
197
+ // Batch processor for converting recursive addToSchema calls to iterative processing
198
+ // This eliminates deep recursion and allows for better work deduplication
199
+ this.batchProcessor = null;
200
+ // Track items already in the batch queue to prevent duplicates
201
+ // For external function calls, uses path-only keys (no value) for more aggressive deduplication
202
+ this.batchQueuedSet = null;
67
203
  this.equivalencyManagers.push(...managers);
68
- this.scopeTree.name = scopeName;
204
+ this.scopeTreeManager.setRootName(scopeName);
69
205
  this.addScopeAnalysis(scopeName, scopeText, scopeAnalysis);
70
206
  }
71
207
  addScopeAnalysis(scopeNodeName, scopeText, scopeAnalysis, parentScopeName, isStatic) {
72
208
  try {
73
- if (scopeNodeName !== this.scopeTree.name && !parentScopeName) {
74
- parentScopeName = this.scopeTree.name;
209
+ if (scopeNodeName !== this.scopeTreeManager.getRootName() &&
210
+ !parentScopeName) {
211
+ parentScopeName = this.scopeTreeManager.getRootName();
75
212
  }
76
213
  let tree = [];
77
214
  if (parentScopeName) {
@@ -112,7 +249,7 @@ export class ScopeDataStructure {
112
249
  }
113
250
  catch (error) {
114
251
  console.log('CodeYam Error: Failed to add scope analysis for scope:', JSON.stringify({
115
- rootScopeName: this.scopeTree.name,
252
+ rootScopeName: this.scopeTreeManager.getRootName(),
116
253
  scopeNodeName,
117
254
  scopeNodeText: scopeText,
118
255
  isolatedStructure: scopeAnalysis.isolatedStructure,
@@ -121,26 +258,46 @@ export class ScopeDataStructure {
121
258
  throw error;
122
259
  }
123
260
  }
261
+ /**
262
+ * Phase 2: Build complete schemas by following all equivalencies.
263
+ *
264
+ * This is the main entry point for schema building. Call this after all
265
+ * scopes have been added via `addScopeAnalysis()`.
266
+ *
267
+ * ## What Happens
268
+ *
269
+ * 1. Resets state (visited tracker, schemas, database)
270
+ * 2. For each scope, follows equivalencies to build complete schemas
271
+ * 3. Filters out internal function calls (keeps only external-facing)
272
+ * 4. Propagates source/usage relationships for querying
273
+ *
274
+ * ## After Calling
275
+ *
276
+ * You can then use:
277
+ * - `getSchema()` - Get the built schema for a scope
278
+ * - `getSourceEquivalencies()` - Find where data comes from
279
+ * - `getUsageEquivalencies()` - Find where data is used
280
+ */
124
281
  async captureCompleteSchema() {
282
+ // Reset state for Phase 2
125
283
  this.onlyEquivalencies = false;
126
284
  this.equivalencyDatabase = [];
127
- this.equivalencyDatabaseCache.clear(); // Clear cache when database is reset
128
- this.intermediatesOrderIndex.clear(); // Clear inverted index when database is reset
129
- this.globalVisited = new Set([]);
285
+ this.equivalencyDatabaseCache.clear();
286
+ this.intermediatesOrderIndex.clear();
287
+ this.visitedTracker.resetGlobalVisited();
130
288
  for (const externalFunctionCall of this.externalFunctionCalls) {
131
289
  externalFunctionCall.schema = {};
132
290
  }
133
- // for (const scopeNode of Object.values(this.scopeNodes)) {
291
+ // Build schemas for all scopes in parallel
134
292
  await Promise.all(Object.values(this.scopeNodes).map(async (scopeNode) => {
135
293
  scopeNode.schema = {};
136
294
  await this.determineEquivalenciesAndBuildSchema(scopeNode);
137
295
  }));
138
- // }
139
296
  const validExternalFacingScopeNames = new Set([
140
- this.scopeTree.name,
297
+ this.scopeTreeManager.getRootName(),
141
298
  ]);
142
299
  this.externalFunctionCalls = this.externalFunctionCalls.filter((efc) => {
143
- const efcName = efc.name.split('<')[0];
300
+ const efcName = this.pathManager.stripGenerics(efc.name);
144
301
  for (const manager of this.equivalencyManagers) {
145
302
  if (manager.internalFunctions.has(efcName)) {
146
303
  return false;
@@ -149,43 +306,67 @@ export class ScopeDataStructure {
149
306
  validExternalFacingScopeNames.add(efcName);
150
307
  return true;
151
308
  });
309
+ this.invalidateExternalFunctionCallsIndex();
310
+ // Pre-compute array methods list once (avoids Array.from() in hot loop)
311
+ const arrayMethodsList = Array.from(arrayMethodsSet);
312
+ const containsArrayMethod = (path) => arrayMethodsList.some((method) => path.includes(`.${method}(`));
152
313
  for (const entry of this.equivalencyDatabase) {
153
- entry.usages = entry.usages.filter((usage) => validExternalFacingScopeNames.has(usage.scopeNodeName.split('<')[0]) &&
154
- (usage.schemaPath.startsWith('returnValue') ||
155
- usage.schemaPath.startsWith(usage.scopeNodeName.split('<')[0])) &&
156
- !Array.from(arrayMethodsSet).some((method) => usage.schemaPath.includes(`.${method}(`)));
157
- entry.sourceCandidates = entry.sourceCandidates.filter((candidate) => validExternalFacingScopeNames.has(candidate.scopeNodeName.split('<')[0]) &&
158
- (candidate.schemaPath.startsWith('signature[') ||
159
- candidate.schemaPath.startsWith(candidate.scopeNodeName.split('<')[0])) &&
160
- !Array.from(arrayMethodsSet).some((method) => candidate.schemaPath.includes(`.${method}(`)));
161
- }
162
- this.propagateSourceAndUsageEquivalencies(this.scopeNodes[this.scopeTree.name]);
314
+ entry.usages = entry.usages.filter((usage) => {
315
+ const baseName = this.pathManager.stripGenerics(usage.scopeNodeName);
316
+ return (validExternalFacingScopeNames.has(baseName) &&
317
+ (usage.schemaPath.startsWith('returnValue') ||
318
+ usage.schemaPath.startsWith(baseName)) &&
319
+ !containsArrayMethod(usage.schemaPath));
320
+ });
321
+ entry.sourceCandidates = entry.sourceCandidates.filter((candidate) => {
322
+ const baseName = this.pathManager.stripGenerics(candidate.scopeNodeName);
323
+ return (validExternalFacingScopeNames.has(baseName) &&
324
+ (candidate.schemaPath.startsWith('signature[') ||
325
+ candidate.schemaPath.startsWith(baseName)) &&
326
+ !containsArrayMethod(candidate.schemaPath));
327
+ });
328
+ }
329
+ this.propagateSourceAndUsageEquivalencies(this.scopeNodes[this.scopeTreeManager.getRootName()]);
163
330
  for (const externalFunctionCall of this.externalFunctionCalls) {
164
- const t = new Date().getTime();
165
- // console.info("Start Propagating", JSON.stringify({
166
- // externalFunctionCallName: externalFunctionCall.name,
167
- // // sourceEquivalencies: externalFunctionCall.sourceEquivalencies,
168
- // }, null, 2));
169
331
  this.propagateSourceAndUsageEquivalencies(externalFunctionCall);
170
- const elapsedTime = new Date().getTime() - t;
171
- if (elapsedTime > 100) {
172
- console.warn('Long Propagation Time', {
173
- externalFunctionCallName: externalFunctionCall.name,
174
- time: elapsedTime,
175
- });
176
- // throw new Error("STOP - LONG PROPAGATION TIME")
177
- }
178
- // console.info("Done Propagating", JSON.stringify({
179
- // externalFunctionCallName: externalFunctionCall.name,
180
- // // sourceEquivalencies: externalFunctionCall.sourceEquivalencies,
181
- // // usageEquivalencies: externalFunctionCall.usageEquivalencies,
182
- // time: elapsedTime
183
- // }, null, 2))
184
332
  }
185
333
  }
334
+ /**
335
+ * Core method: Adds a path/value to a scope's schema and follows equivalencies.
336
+ *
337
+ * This is the heart of schema building. For each path, it:
338
+ * 1. Validates the path and checks if already visited
339
+ * 2. Adds the path → value mapping to the scope's schema
340
+ * 3. Follows any equivalencies to propagate the schema to linked paths
341
+ * 4. Tracks the equivalency chain for source/usage database
342
+ *
343
+ * ## Cycle Detection
344
+ *
345
+ * Uses `visitedTracker.checkAndMarkGlobalVisited()` to prevent infinite loops.
346
+ * A path is considered visited if the exact (scope, path, value) tuple has
347
+ * been processed before.
348
+ *
349
+ * ## Equivalency Following
350
+ *
351
+ * When a path has equivalencies (e.g., `user` → `props.user`), this method
352
+ * recursively calls itself to add the equivalent path to its scope's schema.
353
+ *
354
+ * @param path - Schema path to add (e.g., 'user.id')
355
+ * @param value - Type value (e.g., 'string', 'number')
356
+ * @param scopeNode - The scope to add to
357
+ * @param equivalencyValueChain - Tracks the chain for database population
358
+ * @param traceId - Debug ID for tracing specific paths
359
+ */
186
360
  addToSchema({ path, value, scopeNode, equivalencyValueChain = [], traceId, }) {
187
361
  addToSchemaCallCount++;
188
- // DEBUG: Detect infinite loops
362
+ // Trace entry for debugging
363
+ this.tracer.traceEnter('addToSchema', {
364
+ path,
365
+ scope: scopeNode?.name,
366
+ value,
367
+ chainDepth: equivalencyValueChain.length,
368
+ });
369
+ // Safety: Detect runaway recursion
189
370
  if (addToSchemaCallCount > 500000) {
190
371
  console.error('INFINITE LOOP DETECTED in addToSchema', {
191
372
  callCount: addToSchemaCallCount,
@@ -199,14 +380,16 @@ export class ScopeDataStructure {
199
380
  if (equivalencyValueChain.length > maxEquivalencyChainDepth) {
200
381
  maxEquivalencyChainDepth = equivalencyValueChain.length;
201
382
  }
202
- if (!scopeNode)
383
+ if (!scopeNode) {
203
384
  return;
385
+ }
204
386
  if (!this.isValidPath(path)) {
205
387
  if (traceId) {
206
388
  console.info('Debug propagation: not a valid path', { path, traceId });
207
389
  }
208
390
  return;
209
391
  }
392
+ // Update chain metadata for database tracking
210
393
  if (equivalencyValueChain.length > 0) {
211
394
  equivalencyValueChain[equivalencyValueChain.length - 1].addToSchemaId =
212
395
  ++this.lastAddToSchemaId;
@@ -216,88 +399,35 @@ export class ScopeDataStructure {
216
399
  value,
217
400
  };
218
401
  }
219
- // Use this debugging to track down an infinite loop
220
- // traceId ||= 0;
221
- // traceId += 1;
222
- // if (traceId) {
223
- // console.info(JSON.stringify({ traceId, path, value, scopeNodeName: scopeNode.name }, null, 2));
224
- // }
225
- // if (traceId > 30) {
226
- // console.warn(
227
- // 'HIGH TRACEID',
228
- // JSON.stringify(
229
- // {
230
- // path,
231
- // value,
232
- // scopeNodeName: scopeNode.name,
233
- // equivalencyValueChain,
234
- // },
235
- // null,
236
- // 2,
237
- // ),
238
- // );
239
- // throw new Error('STOP - HIGH TRACEID');
240
- // }
241
- // Use this debugging to trace a specific path through the propagation
242
- const debugLevel = 0; // 0 for minimal, 1 for executed paths, 2 for all paths info
243
- // if ((!this.onlyEquivalencies && path === 'entity.sha') || traceId) {
244
- // traceId ||= 0;
245
- // traceId += 1;
246
- // if (traceId === 1) {
247
- // this.debugCount += 1;
248
- // if (this.debugCount > 5) throw new Error('STOP - HIGH DEBUG COUNT');
249
- // console.warn('START');
250
- // }
251
- // console.info(
252
- // 'Debug Propagation: Adding to schema',
253
- // JSON.stringify(
254
- // {
255
- // // traceId,
256
- // path,
257
- // value,
258
- // scopeNodeName: scopeNode.name,
259
- // reason:
260
- // equivalencyValueChain[equivalencyValueChain.length - 1]?.reason,
261
- // // previous:
262
- // // equivalencyValueChain[equivalencyValueChain.length - 1],
263
- // text: scopeNode.text,
264
- // // tree: scopeNode.tree,
265
- // // onlyEquivalencies: this.onlyEquivalencies,
266
- // // equivalencyValueChain,
267
- // // scopeNode
268
- // // instatiatedVeriables: scopeNode.instantiatedVariables,
269
- // // parentInstantiatedVariables: scopeNode.parentInstantiatedVariables,
270
- // // isolatedStructure: scopeNode.analysis.isolatedStructure,
271
- // // isolatedEquivalencies: scopeNode.analysis.isolatedEquivalentVariables,
272
- // // equivalencies: traceId === 1 ? scopeNode.equivalencies : 'skipped',
273
- // // functionCalls: scopeNode.functionCalls,
274
- // // externalFunctionCalls: this.externalFunctionCalls.filter(fc => fc.callScope.includes(scopeNode.name))
275
- // },
276
- // null,
277
- // 2,
278
- // ),
279
- // );
280
- // // if (traceId > 1) traceId = undefined;
281
- // throw new Error('STOP ON ADD');
282
- // }
402
+ // Debug level: 0=minimal, 1=executed paths, 2=all paths (set via traceId)
403
+ const debugLevel = 0;
404
+ // ─────────────────────────────────────────────────────────────────────────
405
+ // SECTION 1: Handle complex source paths (paths with multiple data origins)
406
+ // ─────────────────────────────────────────────────────────────────────────
283
407
  const equivalenciesDatabaseEntry = this.getEquivalenciesDatabaseEntry(scopeNode.name, path);
284
- // Call addComplexSourcePathVariables like the original code (before visited check)
408
+ // Process complex source paths (before visited check, per original design)
285
409
  this.addComplexSourcePathVariables(equivalenciesDatabaseEntry, scopeNode, path, equivalencyValueChain, traceId);
286
- const uniqueIdentifier = `${scopeNode.name}::${path}::${value}`;
287
- if (this.globalVisited.has(uniqueIdentifier)) {
410
+ // ─────────────────────────────────────────────────────────────────────────
411
+ // SECTION 2: Cycle detection - skip if already visited with this value
412
+ // ─────────────────────────────────────────────────────────────────────────
413
+ if (this.visitedTracker.checkAndMarkGlobalVisited(scopeNode.name, path, value)) {
288
414
  if (traceId) {
289
- console.info('Debug propagation: already globally visited path', JSON.stringify({
290
- uniqueIdentifier,
291
- // equivalencyValueChain,
292
- }, null, 2));
415
+ console.info('Debug: already visited', {
416
+ key: `${scopeNode.name}::${path}::${value}`,
417
+ });
293
418
  }
419
+ // Still record in database even if visited (captures full chain)
294
420
  if (!this.onlyEquivalencies) {
295
421
  this.addToEquivalencyDatabase(equivalencyValueChain, traceId);
296
422
  }
297
423
  return;
298
424
  }
299
- this.globalVisited.add(uniqueIdentifier);
425
+ // Continue complex source processing after visited check
300
426
  this.captureComplexSourcePaths(equivalenciesDatabaseEntry, scopeNode, path, equivalencyValueChain, traceId);
427
+ // ─────────────────────────────────────────────────────────────────────────
428
+ // SECTION 3: Process each subpath to follow equivalencies
429
+ // For path "user.profile.name", processes: "user", "user.profile", "user.profile.name"
430
+ // ─────────────────────────────────────────────────────────────────────────
301
431
  const pathParts = this.splitPath(path);
302
432
  this.checkForArrayItemPath(pathParts, scopeNode, equivalencyValueChain);
303
433
  let propagated = false;
@@ -385,45 +515,42 @@ export class ScopeDataStructure {
385
515
  }
386
516
  }
387
517
  }
518
+ // ─────────────────────────────────────────────────────────────────────────
519
+ // SECTION 4: Write to schema if appropriate
520
+ // Only writes if: (a) path not set or is 'unknown', AND
521
+ // (b) path belongs to this scope (instantiated, signature, or return)
522
+ // ─────────────────────────────────────────────────────────────────────────
388
523
  const writeToCurrentScopeSchema = (!scopeNode.schema[path] || scopeNode.schema[path] === 'unknown') &&
389
524
  (!scopeNode.instantiatedVariables ||
390
525
  scopeNode.instantiatedVariables.includes(pathParts[0]) ||
391
526
  pathParts[0].startsWith('signature[') ||
392
527
  pathParts[0].startsWith('returnValue'));
393
- // Safe early exit: if we've already set this exact schema value, skip processing
528
+ // Early exit if schema already has this exact value
394
529
  if (scopeNode.schema[path] === value && value !== 'unknown') {
395
530
  return;
396
531
  }
397
532
  if (writeToCurrentScopeSchema) {
398
533
  if (traceId && debugLevel > 0) {
399
- console.info('Debug Propagation: currentScope executed', {
400
- traceId,
534
+ console.info('Debug: writing schema', {
401
535
  path,
402
- pathParts,
403
- scopeNodeName: scopeNode.name,
536
+ value,
537
+ scope: scopeNode.name,
404
538
  });
405
539
  }
406
540
  scopeNode.schema[path] = value;
407
541
  }
542
+ // ─────────────────────────────────────────────────────────────────────────
543
+ // SECTION 5: Record in equivalency database (Phase 2 only)
544
+ // ─────────────────────────────────────────────────────────────────────────
408
545
  if (!this.onlyEquivalencies) {
409
546
  this.addToEquivalencyDatabase(equivalencyValueChain, traceId);
410
547
  }
411
548
  if (traceId) {
412
- console.info('Debug Propagation: exiting', JSON.stringify({
413
- traceId,
414
- scopeNodeName: scopeNode.name,
549
+ console.info('Debug: addToSchema complete', {
550
+ scope: scopeNode.name,
415
551
  path,
416
552
  value,
417
- // schemaValue: scopeNode.schema[path],
418
- // propagated,
419
- // scopeInfoText: scopeNode.text,
420
- // equivalencyValueChain//: equivalencyValueChain.map(
421
- // (ev) => ev.currentPath.schemaPath,
422
- // ),
423
- // sourceEquivalencies: scopeNode.sourceEquivalencies[path] ?? [],
424
- // usageEquivalencies: scopeNode.usageEquivalencies[path] ?? [],
425
- // checkpoints,
426
- }, null, 2));
553
+ });
427
554
  }
428
555
  }
429
556
  removeFromSchema(path, schema = {}, scopeName) {
@@ -444,52 +571,16 @@ export class ScopeDataStructure {
444
571
  });
445
572
  throw new Error(`Infinite loop detected: addEquivalency called ${addEquivalencyCallCount} times`);
446
573
  }
447
- // Temporary debugging to track down unnecessary equivalencies
448
- if (![
449
- 'original equivalency',
450
- 'implicit parent equivalency',
451
- 'explicit parent equivalency',
452
- 'transformed non-object function equivalency - original equivalency',
453
- 'equivalency to external function call',
454
- 'functionCall to function signature equivalency', // 1 failure
455
- 'explicit parent signature',
456
- 'useState setter call equivalency',
457
- 'non-object function argument function signature equivalency1',
458
- 'non-object function argument function signature equivalency2',
459
- 'returnValue to functionCallReturnValue equivalency', // 2 failures
460
- '.map() function deconstruction', // 1 failure
461
- 'useMemo return value equivalent to first argument return value',
462
- 'useState value equivalency', // 1 failure
463
- 'Node .then() equivalency', // 1 failure
464
- 'Explicit array deconstruction equivalency value', // 1 failure
465
- 'forwardRef equivalency',
466
- 'forwardRef signature to child signature equivalency', // 1 failure
467
- 'captured function call return value equivalency', // 1 failure (in ScopeDataStructure.test.ts)
468
- 'original equivalency - rerouted via useCallback', // 1 failure
469
- 'non-object function argument function signature equivalency1 - rerouted via useCallback', // 1 failure
470
- 'non-object function argument function signature equivalency2 - rerouted via useCallback', // 1 failure
471
- 'implicit parent equivalency - rerouted via useCallback', // 1 failure
472
- 'Spread operator equivalency key update: implicit parent equivalency', // 1 failure
473
- 'Array.from() equivalency',
474
- 'propagated sub-property equivalency',
475
- 'propagated function call return sub-property equivalency',
476
- ].includes(equivalencyReason)) {
477
- if ([
478
- 'signature of functionCall',
479
- 'transformed non-object function equivalency - implicit parent equivalency',
480
- 'transformed non-object function equivalency - non-object function argument function signature equivalency1',
481
- 'transformed non-object function equivalency - non-object function argument function signature equivalency2',
482
- 'transformed non-object function equivalency - equivalency to external function call',
483
- 'Explicit array deconstruction equivalency key',
484
- 'transformed non-object function equivalency - useState setter call equivalency',
485
- 'transformed non-object function equivalency - implicit parent equivalency - rerouted via useCallback',
486
- 'transformed non-object function equivalency - Array.from() equivalency',
487
- 'Spread operator equivalency key update: Explicit array deconstruction equivalency value',
488
- ].includes(equivalencyReason)) {
574
+ // Filter equivalency reasons - use pre-computed Sets for O(1) lookup
575
+ if (!ALLOWED_EQUIVALENCY_REASONS.has(equivalencyReason)) {
576
+ if (SILENTLY_IGNORED_EQUIVALENCY_REASONS.has(equivalencyReason)) {
489
577
  return;
490
578
  }
491
579
  else {
580
+ // Log and skip - if an equivalency reason isn't in ALLOWED or SILENTLY_IGNORED,
581
+ // it shouldn't be stored (was previously missing the return)
492
582
  console.info('Not tracked equivalency reason', { equivalencyReason });
583
+ return;
493
584
  }
494
585
  }
495
586
  if (!equivalentScopeName) {
@@ -618,7 +709,8 @@ export class ScopeDataStructure {
618
709
  if (!functionCallInfo.equivalencies) {
619
710
  functionCallInfo.equivalencies = {};
620
711
  }
621
- const existingFunctionCall = this.externalFunctionCalls.find((fc) => getFunctionCallRoot(functionCallInfo.callSignature) === fc.name);
712
+ const searchKey = getFunctionCallRoot(functionCallInfo.callSignature);
713
+ const existingFunctionCall = this.getExternalFunctionCallsIndex().get(searchKey);
622
714
  if (existingFunctionCall) {
623
715
  existingFunctionCall.schema = {
624
716
  ...existingFunctionCall.schema,
@@ -635,6 +727,7 @@ export class ScopeDataStructure {
635
727
  !callingScopeNode.parentInstantiatedVariables?.includes(functionCallInfoNameParts[0]);
636
728
  if (isExternal) {
637
729
  this.externalFunctionCalls.push(functionCallInfo);
730
+ this.invalidateExternalFunctionCallsIndex();
638
731
  }
639
732
  }
640
733
  }
@@ -656,7 +749,7 @@ export class ScopeDataStructure {
656
749
  // );
657
750
  // }
658
751
  const getRootOrExternalFunctionCallInfo = (name) => {
659
- return name === this.scopeTree.name
752
+ return name === this.scopeTreeManager.getRootName()
660
753
  ? this.getScopeNode()
661
754
  : this.getExternalFunctionCallInfo(name);
662
755
  };
@@ -674,82 +767,49 @@ export class ScopeDataStructure {
674
767
  schemaPath === safePath ||
675
768
  safePath.startsWith(schemaPath));
676
769
  });
770
+ // PERF: Build a Map for O(1) lookup instead of O(n) inner loop
771
+ // Map from "remaining parts joined" to equivalentSchemaPath
772
+ const equivalentSchemaPathMap = new Map();
773
+ for (const equivalentSchemaPath of Object.keys(equivalentScopeNode.schema)) {
774
+ // Quick string check before expensive path splitting
775
+ if (!(equivalentSchemaPath.startsWith(equivalentPath) ||
776
+ equivalentSchemaPath === equivalentPath ||
777
+ equivalentPath.startsWith(equivalentSchemaPath))) {
778
+ continue;
779
+ }
780
+ const equivalentSchemaPathParts = this.splitPath(equivalentSchemaPath);
781
+ if (!equivalentPathParts.every((p, i) => equivalentSchemaPathParts[i] === p)) {
782
+ continue;
783
+ }
784
+ const remainingEquivalentSchemaPathParts = equivalentSchemaPathParts.slice(equivalentPathParts.length);
785
+ // Use | as separator since it won't appear in path parts
786
+ const key = remainingEquivalentSchemaPathParts.join('|');
787
+ equivalentSchemaPathMap.set(key, equivalentSchemaPath);
788
+ }
677
789
  for (const schemaPath of relevantSchemaPaths) {
678
790
  const schemaPathParts = this.splitPath(schemaPath);
679
791
  if (!pathParts.every((p, i) => schemaPathParts[i] === p)) {
680
792
  continue;
681
793
  }
682
794
  const remainingSchemaPathParts = schemaPathParts.slice(pathParts.length);
683
- let missingEquivalentPath = false;
684
- // Performance optimization: pre-filter equivalent schema paths
685
- const relevantEquivalentSchemaPaths = Object.keys(equivalentScopeNode.schema).filter((equivalentSchemaPath) => {
686
- // Quick string check before expensive path splitting
687
- return (equivalentSchemaPath.startsWith(equivalentPath) ||
688
- equivalentSchemaPath === equivalentPath ||
689
- equivalentPath.startsWith(equivalentSchemaPath));
690
- });
691
- for (const equivalentSchemaPath of relevantEquivalentSchemaPaths) {
692
- const equivalentSchemaPathParts = this.splitPath(equivalentSchemaPath);
693
- if (!equivalentPathParts.every((p, i) => equivalentSchemaPathParts[i] === p)) {
694
- continue;
695
- }
696
- const remainingEquivalentSchemaPathParts = equivalentSchemaPathParts.slice(equivalentPathParts.length);
697
- if (remainingSchemaPathParts.length !==
698
- remainingEquivalentSchemaPathParts.length ||
699
- !remainingEquivalentSchemaPathParts.every((p, i) => p === remainingSchemaPathParts[i])) {
700
- missingEquivalentPath = true;
701
- continue;
702
- }
703
- missingEquivalentPath = false;
795
+ // PERF: O(1) Map lookup instead of O(n) inner loop
796
+ const remainingKey = remainingSchemaPathParts.join('|');
797
+ const equivalentSchemaPath = equivalentSchemaPathMap.get(remainingKey);
798
+ if (equivalentSchemaPath) {
704
799
  const value1 = scopeNode.schema[schemaPath];
705
800
  const value2 = equivalentScopeNode.schema[equivalentSchemaPath];
706
- let bestValue = value1 ?? value2 ?? 'unknown';
707
- if (value2 &&
708
- ((bestValue === 'unknown' && value2 !== 'unknown') ||
709
- (bestValue.includes('unknown') && !value2.includes('unknown')))) {
710
- bestValue = value2;
711
- }
801
+ const bestValue = selectBestValue(value1, value2);
712
802
  scopeNode.schema[schemaPath] = bestValue;
713
803
  equivalentScopeNode.schema[equivalentSchemaPath] = bestValue;
714
- // if (traceId) {
715
- // console.info('Debug Propagate: Assign Best Value', {
716
- // traceId,
717
- // sourceScopeNodeName: scopeNode.name,
718
- // path,
719
- // schemaPath,
720
- // usageScopeNodeName: equivalentScopeNode.name,
721
- // equivalentPath,
722
- // equivalentSchemaPath,
723
- // remainingSchemaPathParts,
724
- // remainingEquivalentSchemaPathParts,
725
- // value1,
726
- // value2,
727
- // bestValue,
728
- // });
729
- // }
730
- break;
731
804
  }
732
- if (missingEquivalentPath &&
733
- (scopeNode.name.includes('____cyScope') ||
734
- !('instantiatedVariables' in equivalentScopeNode))) {
805
+ else if (scopeNode.name.includes('____cyScope') ||
806
+ !('instantiatedVariables' in equivalentScopeNode)) {
807
+ // No matching equivalent path found - create one if needed
735
808
  // Only necessary for internal function scopes or external function scopes
736
809
  const newEquivalentPath = this.joinPathParts([
737
810
  equivalentPath,
738
811
  ...remainingSchemaPathParts,
739
812
  ]);
740
- // if (traceId) {
741
- // console.info('Debug Propagate: missing equivalent path', {
742
- // traceId,
743
- // scopeNodeName: scopeNode.name,
744
- // path,
745
- // equivalentPath,
746
- // schemaPath,
747
- // remainingSchemaPathParts,
748
- // equivalentScopeNodeName: equivalentScopeNode.name,
749
- // // equivalentScopeNodeSchema: equivalentScopeNode.schema,
750
- // newEquivalentPath,
751
- // });
752
- // }
753
813
  equivalentScopeNode.schema[newEquivalentPath] =
754
814
  scopeNode.schema[schemaPath];
755
815
  }
@@ -772,83 +832,26 @@ export class ScopeDataStructure {
772
832
  }
773
833
  }
774
834
  splitPath(path) {
775
- if (this.pathPartsCache.has(path)) {
776
- return structuredClone(this.pathPartsCache.get(path));
777
- }
778
- const pathParts = splitOutsideParenthesesAndArrays(path);
779
- this.pathPartsCache.set(path, structuredClone(pathParts));
780
- return pathParts;
835
+ return this.pathManager.splitPath(path);
781
836
  }
782
837
  joinPathParts(pathParts) {
783
- const cacheKey = pathParts.join('|');
784
- if (this.pathJoinCache.has(cacheKey)) {
785
- return this.pathJoinCache.get(cacheKey);
786
- }
787
- const result = joinParenthesesAndArrays(pathParts);
788
- this.pathJoinCache.set(cacheKey, result);
789
- return result;
838
+ return this.pathManager.joinPathParts(pathParts);
790
839
  }
791
840
  // PRIVATE METHODS //
792
- uniqueId({ scopeNodeName, schemaPath, value, }) {
793
- const parts = [scopeNodeName, schemaPath, value].filter(Boolean);
794
- return parts.join('::');
841
+ uniqueId(params) {
842
+ return uniqueId(params);
795
843
  }
796
844
  uniqueScopeVariables(scopeVariables) {
797
- return this.uniqueScopeAndPaths(scopeVariables);
845
+ return uniqueScopeVariables(scopeVariables);
798
846
  }
799
847
  uniqueScopeAndPaths(scopeVariables) {
800
- if (!scopeVariables || scopeVariables.length === 0)
801
- return [];
802
- // Optimize from O(n²) to O(n) using Set for deduplication
803
- const seen = new Set();
804
- return scopeVariables.filter((varItem) => {
805
- const key = `${varItem.scopeNodeName}::${varItem.schemaPath}`;
806
- if (seen.has(key)) {
807
- return false;
808
- }
809
- seen.add(key);
810
- return true;
811
- });
848
+ return uniqueScopeAndPaths(scopeVariables);
812
849
  }
813
850
  isValidPath(path) {
814
- if (typeof path !== 'string') {
815
- return false;
816
- }
817
- if (!path) {
818
- return false;
819
- }
820
- if (path === 'true' || path === 'false') {
821
- return false;
822
- }
823
- if (!isNaN(Number(path))) {
824
- return false;
825
- }
826
- if (path.match(/^['"]/)) {
827
- return false;
828
- }
829
- return this.splitPath(path).every((part) => {
830
- if (cleanOutBoundary(cleanOutBoundary(cleanOutBoundary(part, '<', '>'), '[', ']')).match(/\s/)) {
831
- return false;
832
- }
833
- return true;
834
- });
851
+ return this.pathManager.isValidPath(path);
835
852
  }
836
853
  addToTree(pathParts) {
837
- let scopeTreeNode = { children: [this.scopeTree] };
838
- for (const pathPart of pathParts) {
839
- const existingChild = scopeTreeNode.children.find((child) => child.name === pathPart);
840
- if (existingChild) {
841
- scopeTreeNode = existingChild;
842
- }
843
- else {
844
- const childScopeTreeNode = {
845
- name: pathPart,
846
- children: [],
847
- };
848
- scopeTreeNode.children.push(childScopeTreeNode);
849
- scopeTreeNode = childScopeTreeNode;
850
- }
851
- }
854
+ this.scopeTreeManager.addPath(pathParts);
852
855
  }
853
856
  setInstantiatedVariables(scopeNode) {
854
857
  let instantiatedVariables = scopeNode.analysis?.instantiatedVariables ?? [];
@@ -947,12 +950,15 @@ export class ScopeDataStructure {
947
950
  }
948
951
  }
949
952
  }
953
+ // PERF: Enable batch processing to convert recursive addToSchema calls to iterative
954
+ // This eliminates deep call stacks and improves deduplication
955
+ this.batchProcessor = new BatchSchemaProcessor();
956
+ this.batchQueuedSet = new Set();
950
957
  for (const key of Array.from(allPaths)) {
951
958
  let value = isolatedStructure[key] ?? 'unknown';
952
959
  if (['null', 'undefined'].includes(value)) {
953
960
  value = 'unknown';
954
961
  }
955
- const startTime = new Date().getTime();
956
962
  this.addToSchema({
957
963
  path: cleanPath(key, allPaths),
958
964
  value,
@@ -965,19 +971,39 @@ export class ScopeDataStructure {
965
971
  },
966
972
  ],
967
973
  });
968
- // const timeDiff = new Date().getTime() - startTime;
969
- // if (timeDiff / 1000 > 1) {
970
- // console.info('SLOW', {
971
- // timeDiff,
972
- // root: this.scopeTree.name,
973
- // scopeNodeName: scopeNode.name,
974
- // schemaPath: key,
975
- // onlyEquivalencies: this.onlyEquivalencies,
976
- // });
977
- // }
978
- }
974
+ // Process any work queued by followEquivalencies
975
+ this.processBatchQueue();
976
+ }
977
+ // Final pass to ensure all queued work is processed
978
+ this.processBatchQueue();
979
+ // Clean up batch processor
980
+ this.batchProcessor = null;
981
+ this.batchQueuedSet = null;
979
982
  this.validateSchema(scopeNode, false, false);
980
983
  }
984
+ /**
985
+ * Process all items in the batch queue.
986
+ * Each item may queue more work via followEquivalencies.
987
+ */
988
+ processBatchQueue() {
989
+ if (!this.batchProcessor)
990
+ return;
991
+ while (this.batchProcessor.hasWork()) {
992
+ const item = this.batchProcessor.getNextWork();
993
+ if (!item)
994
+ break;
995
+ const scopeNode = this.getScopeOrFunctionCallInfo(item.scopeNodeName);
996
+ if (!scopeNode)
997
+ continue;
998
+ this.addToSchema({
999
+ path: item.path,
1000
+ value: item.value,
1001
+ scopeNode,
1002
+ equivalencyValueChain: item.equivalencyValueChain,
1003
+ traceId: item.traceId,
1004
+ });
1005
+ }
1006
+ }
981
1007
  /**
982
1008
  * Propagates returnValue.* sub-properties from a callback scope to the usage path.
983
1009
  *
@@ -1155,11 +1181,11 @@ export class ScopeDataStructure {
1155
1181
  }
1156
1182
  }
1157
1183
  checkForArrayItemPath(pathParts, scopeNode, equivalencyValueChain) {
1158
- const arrayItemPath = joinParenthesesAndArrays([...pathParts, '[]']);
1184
+ const arrayItemPath = this.joinPathParts([...pathParts, '[]']);
1159
1185
  if (scopeNode.equivalencies[arrayItemPath]) {
1160
1186
  const firstEquivalency = equivalencyValueChain[0].currentPath;
1161
- const newFirstEquivalencyPath = joinParenthesesAndArrays([
1162
- ...splitOutsideParenthesesAndArrays(firstEquivalency.schemaPath),
1187
+ const newFirstEquivalencyPath = this.joinPathParts([
1188
+ ...this.splitPath(firstEquivalency.schemaPath),
1163
1189
  '[]',
1164
1190
  ]);
1165
1191
  this.addToSchema({
@@ -1176,27 +1202,77 @@ export class ScopeDataStructure {
1176
1202
  });
1177
1203
  }
1178
1204
  }
1205
+ /**
1206
+ * Follows equivalencies for a subpath and recursively calls addToSchema.
1207
+ *
1208
+ * This is the recursive heart of schema propagation. When we have:
1209
+ * `user` equivalent to `props.user`
1210
+ * And we're processing `user.id`, this method will:
1211
+ * 1. Find the equivalency `user` → `props.user`
1212
+ * 2. Reconstruct the full path: `props.user.id`
1213
+ * 3. Recursively call addToSchema for the equivalent scope
1214
+ *
1215
+ * ## Function-Ambivalent Paths
1216
+ *
1217
+ * Handles paths like `data.map(fn)` by also checking equivalencies
1218
+ * for `data.map` (without the function argument). This allows
1219
+ * array method chains to propagate correctly.
1220
+ *
1221
+ * @param scopeNode - Current scope being processed
1222
+ * @param path - Full original path (e.g., 'user.profile.name')
1223
+ * @param pathParts - Split version of path
1224
+ * @param subPath - Current subpath being checked (e.g., 'user.profile')
1225
+ * @param subPathParts - Split version of subPath
1226
+ * @param value - Type value to propagate
1227
+ * @param equivalencyValueChain - Chain tracking for database
1228
+ * @param traceId - Debug ID
1229
+ * @param debugLevel - 0=minimal, 1=executed, 2=verbose
1230
+ */
1179
1231
  followEquivalencies(scopeNode, path, pathParts, subPath, subPathParts, value, equivalencyValueChain, traceId, debugLevel = 0) {
1180
1232
  followEquivalenciesCallCount++;
1233
+ // Trace for debugging
1234
+ this.tracer.trace('followEquivalencies', {
1235
+ path,
1236
+ scope: scopeNode.name,
1237
+ subPath,
1238
+ hasEquivalencies: (scopeNode.equivalencies[subPath]?.length ?? 0) > 0,
1239
+ });
1181
1240
  let propagated = false;
1241
+ // ─────────────────────────────────────────────────────────────────────────
1242
+ // Step 1: Collect equivalencies (including function-ambivalent paths)
1243
+ // ─────────────────────────────────────────────────────────────────────────
1182
1244
  let equivalentValues = scopeNode.equivalencies[subPath] ?? [];
1183
1245
  let functionAmbivalentSubPath = subPath;
1184
1246
  let functionAmbivalentSubPathParts = subPathParts;
1185
- if (subPathParts[subPathParts.length - 1].indexOf('(') > -1) {
1247
+ // For paths like `data.map(fn)`, also check `data.map` equivalencies
1248
+ // PERF: Only do the expensive function-ambivalent processing if:
1249
+ // 1. No equivalencies found yet, AND
1250
+ // 2. The subpath ends with a function call (contains '(')
1251
+ const lastPart = subPathParts[subPathParts.length - 1];
1252
+ if (lastPart.indexOf('(') > -1) {
1253
+ // Check function-ambivalent path for equivalencies
1186
1254
  functionAmbivalentSubPathParts = [
1187
1255
  ...subPathParts.slice(0, -1),
1188
- subPathParts[subPathParts.length - 1].split('(')[0],
1256
+ lastPart.split('(')[0],
1189
1257
  ];
1190
1258
  functionAmbivalentSubPath = this.joinPathParts(functionAmbivalentSubPathParts);
1191
- equivalentValues = [
1192
- ...(equivalentValues ?? []),
1193
- ...(scopeNode.equivalencies[functionAmbivalentSubPath] ?? []),
1194
- ];
1259
+ const functionAmbivalentEquivalencies = scopeNode.equivalencies[functionAmbivalentSubPath];
1260
+ if (functionAmbivalentEquivalencies?.length > 0) {
1261
+ equivalentValues = [
1262
+ ...equivalentValues,
1263
+ ...functionAmbivalentEquivalencies,
1264
+ ];
1265
+ }
1195
1266
  }
1196
1267
  // Early exit optimization: if no equivalencies to follow, skip expensive processing
1197
1268
  if (equivalentValues.length === 0) {
1269
+ followEquivalenciesEarlyExitCount++;
1270
+ if (this.onlyEquivalencies) {
1271
+ followEquivalenciesEarlyExitPhase1Count++;
1272
+ }
1198
1273
  return false;
1199
1274
  }
1275
+ followEquivalenciesWithWorkCount++;
1200
1276
  if (traceId && debugLevel > 1) {
1201
1277
  console.info('Debug Propagation: equivalence', JSON.stringify({
1202
1278
  traceId,
@@ -1212,10 +1288,17 @@ export class ScopeDataStructure {
1212
1288
  }, null, 2));
1213
1289
  }
1214
1290
  const uniqueEquivalentValues = this.uniqueScopeVariables(equivalentValues);
1291
+ // PERF: Only create Set when chain is non-empty (common case avoids allocation)
1292
+ // Pre-compute Set of chain IDs for O(1) cycle detection instead of O(n) .some()
1293
+ const chainIdSet = equivalencyValueChain.length > 0
1294
+ ? new Set(equivalencyValueChain.map((ev) => ev.id))
1295
+ : null;
1215
1296
  for (let index = 0; index < uniqueEquivalentValues.length; ++index) {
1216
1297
  const equivalentValue = uniqueEquivalentValues[index];
1217
- if (equivalentValue.id !== -1 &&
1218
- equivalencyValueChain.some((ev) => ev.id === equivalentValue.id)) {
1298
+ // O(1) cycle check using Set instead of O(n) .some()
1299
+ if (chainIdSet &&
1300
+ equivalentValue.id !== -1 &&
1301
+ chainIdSet.has(equivalentValue.id)) {
1219
1302
  if (traceId) {
1220
1303
  console.info('Debug Propagation: skipping circular equivalence', JSON.stringify({
1221
1304
  traceId,
@@ -1243,8 +1326,12 @@ export class ScopeDataStructure {
1243
1326
  if (lastRelevantSubPathPart.endsWith(')') &&
1244
1327
  schemaPathParts[schemaPathParts.length - 1] ===
1245
1328
  lastRelevantSubPathPart.split('(')[0]) {
1246
- schemaPathParts[schemaPathParts.length - 1] = lastRelevantSubPathPart;
1247
- schemaPath = this.joinPathParts(schemaPathParts);
1329
+ // PERF: Don't mutate the array - create a new one to avoid requiring structuredClone
1330
+ const updatedSchemaPathParts = [
1331
+ ...schemaPathParts.slice(0, -1),
1332
+ lastRelevantSubPathPart,
1333
+ ];
1334
+ schemaPath = this.joinPathParts(updatedSchemaPathParts);
1248
1335
  }
1249
1336
  const remainingPathParts = pathParts.slice(relevantSubPathParts.length);
1250
1337
  const remainingPath = this.joinPathParts(remainingPathParts);
@@ -1287,23 +1374,27 @@ export class ScopeDataStructure {
1287
1374
  // equivalencies: scopeNode.equivalencies,
1288
1375
  }, null, 2));
1289
1376
  }
1290
- const localEquivalencyValueChain = structuredClone(equivalencyValueChain);
1291
- localEquivalencyValueChain.push({
1292
- id: equivalentValue.id,
1293
- source: 'equivalence',
1294
- previousPath: {
1295
- scopeNodeName: scopeNode.name,
1296
- schemaPath: path,
1297
- value,
1298
- },
1299
- currentPath: {
1300
- scopeNodeName: equivalentScopeNode.name,
1301
- schemaPath: newEquivalentPath,
1302
- value,
1377
+ // PERF: Use spread instead of structuredClone - the chain items are immutable
1378
+ // so shallow copy is sufficient and much faster (structuredClone is expensive)
1379
+ const localEquivalencyValueChain = [
1380
+ ...equivalencyValueChain,
1381
+ {
1382
+ id: equivalentValue.id,
1383
+ source: 'equivalence',
1384
+ previousPath: {
1385
+ scopeNodeName: scopeNode.name,
1386
+ schemaPath: path,
1387
+ value,
1388
+ },
1389
+ currentPath: {
1390
+ scopeNodeName: equivalentScopeNode.name,
1391
+ schemaPath: newEquivalentPath,
1392
+ value,
1393
+ },
1394
+ reason: equivalentValue.equivalencyReason,
1395
+ traceId,
1303
1396
  },
1304
- reason: equivalentValue.equivalencyReason,
1305
- traceId,
1306
- });
1397
+ ];
1307
1398
  // writeEquivalencyToFile(
1308
1399
  // scopeNode.name,
1309
1400
  // subPath,
@@ -1313,13 +1404,48 @@ export class ScopeDataStructure {
1313
1404
  // equivalentValue.equivalencyReason,
1314
1405
  // )
1315
1406
  propagated = true;
1316
- this.addToSchema({
1317
- path: newEquivalentPath,
1318
- value,
1319
- scopeNode: equivalentScopeNode,
1320
- equivalencyValueChain: localEquivalencyValueChain,
1321
- traceId,
1322
- });
1407
+ // PERF: If batch processor is active, queue work instead of recursing
1408
+ // This converts deep recursion to iterative processing
1409
+ if (this.batchProcessor) {
1410
+ // PERF OPTIMIZATION: For external function calls, use path-only key (ignore value)
1411
+ // External FCs don't have internals to analyze, so processing the same path
1412
+ // with different values is redundant - we're just tracking data flow
1413
+ const isExternalFc = equivalentValue.equivalencyReason ===
1414
+ 'equivalency to external function call' ||
1415
+ this.getExternalFunctionCallInfo(equivalentScopeNode.name) !==
1416
+ undefined;
1417
+ const queueKey = isExternalFc
1418
+ ? `${equivalentScopeNode.name}::${newEquivalentPath}` // path-only for external FC
1419
+ : `${equivalentScopeNode.name}::${newEquivalentPath}::${value}`; // full key otherwise
1420
+ // Always check visited - it catches already-processed items
1421
+ const alreadyVisited = this.visitedTracker.hasGlobalVisited(equivalentScopeNode.name, newEquivalentPath, value);
1422
+ // For external FCs, queueKey is path-only so this catches any-value duplicates
1423
+ const alreadyQueued = this.batchQueuedSet?.has(queueKey);
1424
+ if (alreadyVisited || alreadyQueued) {
1425
+ // Still record in database to capture the chain (as addToSchema does)
1426
+ this.addToEquivalencyDatabase(localEquivalencyValueChain, traceId);
1427
+ }
1428
+ else {
1429
+ // Mark as queued to prevent duplicate queue entries
1430
+ this.batchQueuedSet?.add(queueKey);
1431
+ this.batchProcessor.addWork({
1432
+ scopeNodeName: equivalentScopeNode.name,
1433
+ path: newEquivalentPath,
1434
+ value,
1435
+ equivalencyValueChain: localEquivalencyValueChain,
1436
+ traceId,
1437
+ });
1438
+ }
1439
+ }
1440
+ else {
1441
+ this.addToSchema({
1442
+ path: newEquivalentPath,
1443
+ value,
1444
+ scopeNode: equivalentScopeNode,
1445
+ equivalencyValueChain: localEquivalencyValueChain,
1446
+ traceId,
1447
+ });
1448
+ }
1323
1449
  }
1324
1450
  }
1325
1451
  return propagated;
@@ -1343,11 +1469,9 @@ export class ScopeDataStructure {
1343
1469
  const usageScopeNode = this.getScopeOrFunctionCallInfo(usageEquivalency.scopeNodeName);
1344
1470
  // Guard against infinite recursion by tracking which paths we've already
1345
1471
  // added from addComplexSourcePathVariables
1346
- const complexPathKey = `${usageScopeNode.name}::${newUsageEquivalentPath}`;
1347
- if (this.complexSourceVisited.has(complexPathKey)) {
1472
+ if (this.visitedTracker.checkAndMarkComplexSourceVisited(usageScopeNode.name, newUsageEquivalentPath)) {
1348
1473
  continue;
1349
1474
  }
1350
- this.complexSourceVisited.add(complexPathKey);
1351
1475
  this.addToSchema({
1352
1476
  path: newUsageEquivalentPath,
1353
1477
  value: 'unknown',
@@ -1542,6 +1666,7 @@ export class ScopeDataStructure {
1542
1666
  if (functionScope) {
1543
1667
  functionScope.functionCalls.push(externalFunctionCallInfo);
1544
1668
  this.externalFunctionCalls.splice(i, 1);
1669
+ this.invalidateExternalFunctionCallsIndex();
1545
1670
  for (const equivalentPath in externalFunctionCallInfo.equivalencies) {
1546
1671
  let localEquivalentPath = equivalentPath;
1547
1672
  if (localEquivalentPath.startsWith(externalFunctionCallInfo.callSignature)) {
@@ -1584,15 +1709,17 @@ export class ScopeDataStructure {
1584
1709
  for (const key in scopeNode.equivalencies) {
1585
1710
  const keyParts = this.splitPath(key);
1586
1711
  if (keyParts.length > 1) {
1587
- const lastPart = keyParts.pop();
1712
+ // PERF: Don't mutate the array - use indexing instead of pop() to avoid requiring structuredClone
1713
+ const lastPart = keyParts[keyParts.length - 1];
1588
1714
  if (lastPart.startsWith('signature[')) {
1589
- const functionCall = keyParts[keyParts.length - 1];
1715
+ const keyPartsWithoutLast = keyParts.slice(0, -1);
1716
+ const functionCall = keyPartsWithoutLast[keyPartsWithoutLast.length - 1];
1590
1717
  const argumentsIndex = functionCall.indexOf('(');
1591
1718
  const functionName = this.joinPathParts([
1592
- ...keyParts.slice(0, -1),
1719
+ ...keyPartsWithoutLast.slice(0, -1),
1593
1720
  functionCall.slice(0, argumentsIndex === -1 ? undefined : argumentsIndex),
1594
1721
  ]);
1595
- const callSignature = this.joinPathParts(keyParts);
1722
+ const callSignature = this.joinPathParts(keyPartsWithoutLast);
1596
1723
  const functionCallInfo = {
1597
1724
  name: functionName,
1598
1725
  callSignature,
@@ -1604,15 +1731,17 @@ export class ScopeDataStructure {
1604
1731
  for (const equivalentValues of scopeNode.equivalencies[key]) {
1605
1732
  const equivalentValueParts = this.splitPath(equivalentValues.schemaPath);
1606
1733
  if (equivalentValueParts.length > 1) {
1607
- const lastPart = equivalentValueParts.pop();
1734
+ // PERF: Don't mutate the array - use indexing instead of pop() to avoid requiring structuredClone
1735
+ const lastPart = equivalentValueParts[equivalentValueParts.length - 1];
1608
1736
  if (lastPart.startsWith('functionCallReturnValue')) {
1609
- const functionCall = equivalentValueParts[equivalentValueParts.length - 1];
1737
+ const partsWithoutLast = equivalentValueParts.slice(0, -1);
1738
+ const functionCall = partsWithoutLast[partsWithoutLast.length - 1];
1610
1739
  const argumentsIndex = functionCall.indexOf('(');
1611
1740
  const functionName = this.joinPathParts([
1612
- ...equivalentValueParts.slice(0, -1),
1741
+ ...partsWithoutLast.slice(0, -1),
1613
1742
  functionCall.slice(0, argumentsIndex === -1 ? undefined : argumentsIndex),
1614
1743
  ]);
1615
- const callSignature = this.joinPathParts(equivalentValueParts);
1744
+ const callSignature = this.joinPathParts(partsWithoutLast);
1616
1745
  const functionCallInfo = {
1617
1746
  name: functionName,
1618
1747
  callSignature,
@@ -1757,7 +1886,7 @@ export class ScopeDataStructure {
1757
1886
  return this.getExternalFunctionCallInfo(scopeName);
1758
1887
  }
1759
1888
  getScopeNode(scopeName) {
1760
- const scopeNode = this.scopeNodes[scopeName ?? this.scopeTree.name];
1889
+ const scopeNode = this.scopeNodes[scopeName ?? this.scopeTreeManager.getRootName()];
1761
1890
  if (scopeNode)
1762
1891
  return scopeNode;
1763
1892
  for (const scopeNodeName in this.scopeNodes) {
@@ -1766,20 +1895,54 @@ export class ScopeDataStructure {
1766
1895
  }
1767
1896
  }
1768
1897
  }
1898
+ /**
1899
+ * Gets or builds the external function calls index for O(1) lookup.
1900
+ * The index maps both the full name and the name without generics to the FunctionCallInfo.
1901
+ */
1902
+ getExternalFunctionCallsIndex() {
1903
+ if (this.externalFunctionCallsIndex === null) {
1904
+ this.externalFunctionCallsIndex = new Map();
1905
+ for (const efc of this.externalFunctionCalls) {
1906
+ this.externalFunctionCallsIndex.set(efc.name, efc);
1907
+ // Also index by name without generics (e.g., 'MyFunction<T>' -> 'MyFunction')
1908
+ const nameWithoutGenerics = this.pathManager.stripGenerics(efc.name);
1909
+ if (nameWithoutGenerics !== efc.name) {
1910
+ this.externalFunctionCallsIndex.set(nameWithoutGenerics, efc);
1911
+ }
1912
+ }
1913
+ }
1914
+ return this.externalFunctionCallsIndex;
1915
+ }
1916
+ /**
1917
+ * Invalidates the external function calls index.
1918
+ * Call this after any mutation to externalFunctionCalls array.
1919
+ */
1920
+ invalidateExternalFunctionCallsIndex() {
1921
+ this.externalFunctionCallsIndex = null;
1922
+ }
1769
1923
  getExternalFunctionCallInfo(functionName) {
1770
- return this.externalFunctionCalls.find((efc) => efc.name === getFunctionCallRoot(functionName) ||
1771
- efc.name.split('<')[0] === getFunctionCallRoot(functionName));
1924
+ const searchKey = getFunctionCallRoot(functionName);
1925
+ const index = this.getExternalFunctionCallsIndex();
1926
+ // First try exact match
1927
+ const exact = index.get(searchKey);
1928
+ if (exact)
1929
+ return exact;
1930
+ // Fallback to the original find for edge cases not covered by index
1931
+ return this.externalFunctionCalls.find((efc) => efc.name === searchKey ||
1932
+ this.pathManager.stripGenerics(efc.name) === searchKey);
1772
1933
  }
1773
1934
  getScopeAnalysis(scopeName) {
1774
- return this.scopeNodes[scopeName ?? this.scopeTree.name].analysis;
1935
+ return this.scopeNodes[scopeName ?? this.scopeTreeManager.getRootName()]
1936
+ .analysis;
1775
1937
  }
1776
1938
  getAnalysisTree() {
1777
1939
  return this.scopeTree;
1778
1940
  }
1779
1941
  getSchema({ scopeName, fillInUnknowns, }) {
1780
- const scopeNode = this.scopeNodes[scopeName ?? this.scopeTree.name];
1942
+ const scopeNode = this.scopeNodes[scopeName ?? this.scopeTreeManager.getRootName()];
1781
1943
  if (!scopeNode) {
1782
- const externalFunctionCallSchema = this.externalFunctionCalls.find((call) => call.name === getFunctionCallRoot(scopeName))?.schema;
1944
+ const searchKey = getFunctionCallRoot(scopeName);
1945
+ const externalFunctionCallSchema = this.getExternalFunctionCallsIndex().get(searchKey)?.schema;
1783
1946
  if (!externalFunctionCallSchema)
1784
1947
  return;
1785
1948
  return Object.keys(externalFunctionCallSchema).reduce((acc, key) => {
@@ -1802,7 +1965,9 @@ export class ScopeDataStructure {
1802
1965
  if (this.equivalencyDatabaseCache.has(cacheKey)) {
1803
1966
  return this.equivalencyDatabaseCache.get(cacheKey);
1804
1967
  }
1805
- const result = this.equivalencyDatabase.find((entry) => entry.intermediatesOrder[cacheKey] !== undefined);
1968
+ // PERF: Use inverted index for O(1) lookup instead of O(n) array scan
1969
+ // The intermediatesOrderIndex maps pathId (scopeNodeName::schemaPath) to entry
1970
+ const result = this.intermediatesOrderIndex.get(cacheKey);
1806
1971
  this.equivalencyDatabaseCache.set(cacheKey, result);
1807
1972
  return result;
1808
1973
  }
@@ -1865,12 +2030,12 @@ export class ScopeDataStructure {
1865
2030
  }
1866
2031
  }
1867
2032
  }
1868
- const tempScopeNode = this.createTempScopeNode(functionName ?? this.scopeTree.name, signatureInSchema, equivalencies);
2033
+ const tempScopeNode = this.createTempScopeNode(functionName ?? this.scopeTreeManager.getRootName(), signatureInSchema, equivalencies);
1869
2034
  this.validateSchema(tempScopeNode, true, fillInUnknowns);
1870
2035
  return tempScopeNode.schema;
1871
2036
  }
1872
2037
  getReturnValue({ functionName, fillInUnknowns, }) {
1873
- const scopeName = functionName ?? this.scopeTree.name;
2038
+ const scopeName = functionName ?? this.scopeTreeManager.getRootName();
1874
2039
  const scopeNode = this.scopeNodes[scopeName];
1875
2040
  let schema = {};
1876
2041
  if (scopeNode) {
@@ -1887,12 +2052,7 @@ export class ScopeDataStructure {
1887
2052
  for (const schemaPath in externalFunctionCall.schema) {
1888
2053
  const value1 = schema[schemaPath];
1889
2054
  const value2 = externalFunctionCall.schema[schemaPath];
1890
- let bestValue = value1 ?? value2;
1891
- if (bestValue === 'unknown' ||
1892
- (bestValue.includes('unknown') && !value2.includes('unknown'))) {
1893
- bestValue = value2;
1894
- }
1895
- schema[schemaPath] = bestValue;
2055
+ schema[schemaPath] = selectBestValue(value1, value2, value2);
1896
2056
  }
1897
2057
  }
1898
2058
  }
@@ -1989,7 +2149,7 @@ export class ScopeDataStructure {
1989
2149
  return scopeText;
1990
2150
  }
1991
2151
  getEquivalentSignatureVariables() {
1992
- const scopeNode = this.scopeNodes[this.scopeTree.name];
2152
+ const scopeNode = this.scopeNodes[this.scopeTreeManager.getRootName()];
1993
2153
  const equivalentSignatureVariables = {};
1994
2154
  for (const [path, equivalentValues] of Object.entries(scopeNode.equivalencies)) {
1995
2155
  for (const equivalentValue of equivalentValues) {
@@ -2001,7 +2161,7 @@ export class ScopeDataStructure {
2001
2161
  return equivalentSignatureVariables;
2002
2162
  }
2003
2163
  getVariableInfo(variableName, scopeName, final) {
2004
- const scopeNode = this.getScopeOrFunctionCallInfo(scopeName ?? this.scopeTree.name);
2164
+ const scopeNode = this.getScopeOrFunctionCallInfo(scopeName ?? this.scopeTreeManager.getRootName());
2005
2165
  if (!scopeNode)
2006
2166
  return;
2007
2167
  let equivalents = scopeNode.equivalencies[variableName];
@@ -2028,7 +2188,7 @@ export class ScopeDataStructure {
2028
2188
  });
2029
2189
  return { ...acc, ...filterdSchema };
2030
2190
  }, {});
2031
- const tempScopeNode = this.createTempScopeNode(scopeName ?? this.scopeTree.name, relevantSchema);
2191
+ const tempScopeNode = this.createTempScopeNode(scopeName ?? this.scopeTreeManager.getRootName(), relevantSchema);
2032
2192
  this.validateSchema(tempScopeNode, true, final);
2033
2193
  return {
2034
2194
  name: variableName,
@@ -2042,6 +2202,50 @@ export class ScopeDataStructure {
2042
2202
  getEnvironmentVariables() {
2043
2203
  return this.environmentVariables;
2044
2204
  }
2205
+ /**
2206
+ * Add conditional usages from AST analysis.
2207
+ * Called during scope analysis to collect all conditionals.
2208
+ */
2209
+ addConditionalUsages(usages) {
2210
+ for (const [path, pathUsages] of Object.entries(usages)) {
2211
+ if (!this.rawConditionalUsages[path]) {
2212
+ this.rawConditionalUsages[path] = [];
2213
+ }
2214
+ // Deduplicate usages
2215
+ for (const usage of pathUsages) {
2216
+ const exists = this.rawConditionalUsages[path].some((existing) => existing.location === usage.location &&
2217
+ existing.conditionType === usage.conditionType &&
2218
+ JSON.stringify(existing.comparedValues) ===
2219
+ JSON.stringify(usage.comparedValues));
2220
+ if (!exists) {
2221
+ this.rawConditionalUsages[path].push(usage);
2222
+ }
2223
+ }
2224
+ }
2225
+ }
2226
+ /**
2227
+ * Get enriched conditional usages with source tracing.
2228
+ * Uses explainPath to trace each local variable back to its data source.
2229
+ */
2230
+ getEnrichedConditionalUsages() {
2231
+ const enriched = {};
2232
+ for (const [path, usages] of Object.entries(this.rawConditionalUsages)) {
2233
+ // Try to trace this path back to a data source
2234
+ // First, try the root scope
2235
+ const rootScopeName = this.scopeTreeManager.getTree().name;
2236
+ const explanation = this.explainPath(rootScopeName, path);
2237
+ let sourceDataPath;
2238
+ if (explanation.source) {
2239
+ // Build the full data path: scopeName.path
2240
+ sourceDataPath = `${explanation.source.scope}.${explanation.source.path}`;
2241
+ }
2242
+ enriched[path] = usages.map((usage) => ({
2243
+ ...usage,
2244
+ sourceDataPath,
2245
+ }));
2246
+ }
2247
+ return enriched;
2248
+ }
2045
2249
  toSerializable() {
2046
2250
  // Helper to convert ScopeVariable to SerializableScopeVariable
2047
2251
  const toSerializableVariable = (vars) => vars.map((v) => ({
@@ -2090,13 +2294,427 @@ export class ScopeDataStructure {
2090
2294
  // Get equivalent signature variables
2091
2295
  const equivalentSignatureVariables = this.getEquivalentSignatureVariables();
2092
2296
  const environmentVariables = this.getEnvironmentVariables();
2297
+ // Get enriched conditional usages with source tracing
2298
+ const enrichedConditionalUsages = this.getEnrichedConditionalUsages();
2299
+ const conditionalUsages = Object.keys(enrichedConditionalUsages).length > 0
2300
+ ? enrichedConditionalUsages
2301
+ : undefined;
2093
2302
  return {
2094
2303
  externalFunctionCalls,
2095
2304
  rootFunction,
2096
2305
  functionResults,
2097
2306
  equivalentSignatureVariables,
2098
2307
  environmentVariables,
2308
+ conditionalUsages,
2099
2309
  };
2100
2310
  }
2311
+ // ═══════════════════════════════════════════════════════════════════════════
2312
+ // DEBUGGING HELPERS
2313
+ // These methods help understand what's happening during analysis.
2314
+ // Use them when investigating why a path is missing or has the wrong type.
2315
+ // ═══════════════════════════════════════════════════════════════════════════
2316
+ /**
2317
+ * Explains a path by tracing its equivalencies and showing where data comes from.
2318
+ *
2319
+ * @example
2320
+ * ```typescript
2321
+ * const explanation = sds.explainPath('MyComponent', 'user.id');
2322
+ * console.log(explanation);
2323
+ * // {
2324
+ * // path: 'user.id',
2325
+ * // scope: 'MyComponent',
2326
+ * // schemaValue: 'string',
2327
+ * // equivalencies: [
2328
+ * // { scope: 'MyComponent', path: 'signature[0].user.id' },
2329
+ * // { scope: 'UserProfile', path: 'props.user.id' }
2330
+ * // ],
2331
+ * // source: { scope: 'fetchUser', path: 'functionCallReturnValue(fetch).data.user.id' }
2332
+ * // }
2333
+ * ```
2334
+ */
2335
+ explainPath(scopeName, path) {
2336
+ const scopeNode = this.getScopeOrFunctionCallInfo(scopeName);
2337
+ if (!scopeNode) {
2338
+ return {
2339
+ path,
2340
+ scope: scopeName,
2341
+ schemaValue: undefined,
2342
+ equivalencies: [],
2343
+ databaseEntry: undefined,
2344
+ source: undefined,
2345
+ };
2346
+ }
2347
+ const schemaValue = scopeNode.schema?.[path];
2348
+ const rawEquivalencies = scopeNode.equivalencies?.[path] ?? [];
2349
+ const equivalencies = rawEquivalencies.map((eq) => ({
2350
+ scope: eq.scopeNodeName,
2351
+ path: eq.schemaPath,
2352
+ reason: eq.equivalencyReason,
2353
+ }));
2354
+ const databaseEntry = this.getEquivalenciesDatabaseEntry(scopeName, path);
2355
+ const source = databaseEntry?.sourceCandidates?.[0] &&
2356
+ databaseEntry.sourceCandidates.length > 0
2357
+ ? {
2358
+ scope: databaseEntry.sourceCandidates[0].scopeNodeName,
2359
+ path: databaseEntry.sourceCandidates[0].schemaPath,
2360
+ }
2361
+ : undefined;
2362
+ return {
2363
+ path,
2364
+ scope: scopeName,
2365
+ schemaValue,
2366
+ equivalencies,
2367
+ databaseEntry,
2368
+ source,
2369
+ };
2370
+ }
2371
+ /**
2372
+ * Dumps the current state of analysis for inspection.
2373
+ * Useful for understanding the overall state or finding issues.
2374
+ *
2375
+ * @param options - What to include in the dump
2376
+ * @returns A summary object with requested data
2377
+ */
2378
+ dumpState(options) {
2379
+ const includeSchemas = options?.includeSchemas ?? false;
2380
+ const includeEquivalencies = options?.includeEquivalencies ?? false;
2381
+ const scopeFilter = options?.scopeFilter;
2382
+ const scopeNames = Object.keys(this.scopeNodes).filter((name) => !scopeFilter || name.includes(scopeFilter));
2383
+ const scopes = scopeNames.map((name) => {
2384
+ const node = this.scopeNodes[name];
2385
+ const result = {
2386
+ name,
2387
+ schemaKeyCount: Object.keys(node.schema ?? {}).length,
2388
+ equivalencyKeyCount: Object.keys(node.equivalencies ?? {}).length,
2389
+ functionCallCount: node.functionCalls?.length ?? 0,
2390
+ };
2391
+ if (includeSchemas) {
2392
+ result.schema = node.schema;
2393
+ }
2394
+ if (includeEquivalencies) {
2395
+ result.equivalencies = Object.entries(node.equivalencies ?? {}).reduce((acc, [key, vals]) => {
2396
+ acc[key] = vals.map((v) => ({
2397
+ scope: v.scopeNodeName,
2398
+ path: v.schemaPath,
2399
+ }));
2400
+ return acc;
2401
+ }, {});
2402
+ }
2403
+ return result;
2404
+ });
2405
+ return {
2406
+ scopeCount: Object.keys(this.scopeNodes).length,
2407
+ externalCallCount: this.externalFunctionCalls.length,
2408
+ equivalencyDatabaseSize: this.equivalencyDatabase.length,
2409
+ metrics: {
2410
+ addToSchemaCallCount,
2411
+ followEquivalenciesCallCount,
2412
+ maxEquivalencyChainDepth,
2413
+ },
2414
+ scopes,
2415
+ };
2416
+ }
2417
+ /**
2418
+ * Traces the full equivalency chain for a path, showing how data flows.
2419
+ * This is the most detailed debugging tool for understanding data tracing.
2420
+ *
2421
+ * @example
2422
+ * ```typescript
2423
+ * const chain = sds.traceEquivalencyChain('MyComponent', 'user.id');
2424
+ * // Returns array of steps showing how user.id is traced back to its source
2425
+ * ```
2426
+ */
2427
+ traceEquivalencyChain(scopeName, path, maxDepth = 20) {
2428
+ const chain = [];
2429
+ const visited = new Set();
2430
+ const queue = [
2431
+ { scope: scopeName, path, depth: 0 },
2432
+ ];
2433
+ while (queue.length > 0 && chain.length < maxDepth) {
2434
+ const current = queue.shift();
2435
+ const key = `${current.scope}::${current.path}`;
2436
+ if (visited.has(key))
2437
+ continue;
2438
+ visited.add(key);
2439
+ const scopeNode = this.getScopeOrFunctionCallInfo(current.scope);
2440
+ const schemaValue = scopeNode?.schema?.[current.path];
2441
+ const rawEquivalencies = scopeNode?.equivalencies?.[current.path] ?? [];
2442
+ const nextEquivalencies = rawEquivalencies.map((eq) => ({
2443
+ scope: eq.scopeNodeName,
2444
+ path: eq.schemaPath,
2445
+ reason: eq.equivalencyReason,
2446
+ }));
2447
+ chain.push({
2448
+ step: chain.length + 1,
2449
+ scope: current.scope,
2450
+ path: current.path,
2451
+ schemaValue,
2452
+ nextEquivalencies,
2453
+ });
2454
+ // Add next equivalencies to queue for further tracing
2455
+ for (const eq of nextEquivalencies) {
2456
+ const nextKey = `${eq.scope}::${eq.path}`;
2457
+ if (!visited.has(nextKey)) {
2458
+ queue.push({
2459
+ scope: eq.scope,
2460
+ path: eq.path,
2461
+ depth: current.depth + 1,
2462
+ });
2463
+ }
2464
+ }
2465
+ }
2466
+ return chain;
2467
+ }
2468
+ /**
2469
+ * Finds all paths in a scope that match a pattern.
2470
+ * Useful for finding related paths when debugging.
2471
+ *
2472
+ * @example
2473
+ * ```typescript
2474
+ * const paths = sds.findPaths('MyComponent', /user/);
2475
+ * // Returns all schema paths containing "user"
2476
+ * ```
2477
+ */
2478
+ findPaths(scopeName, pattern) {
2479
+ const scopeNode = this.getScopeOrFunctionCallInfo(scopeName);
2480
+ if (!scopeNode)
2481
+ return [];
2482
+ const regex = typeof pattern === 'string' ? new RegExp(pattern) : pattern;
2483
+ const results = [];
2484
+ // Search in schema
2485
+ for (const [path, value] of Object.entries(scopeNode.schema ?? {})) {
2486
+ if (regex.test(path)) {
2487
+ results.push({
2488
+ path,
2489
+ value,
2490
+ hasEquivalencies: !!scopeNode.equivalencies?.[path]?.length,
2491
+ });
2492
+ }
2493
+ }
2494
+ // Also search equivalency keys that might not be in schema
2495
+ for (const path of Object.keys(scopeNode.equivalencies ?? {})) {
2496
+ if (regex.test(path) && !results.find((r) => r.path === path)) {
2497
+ results.push({
2498
+ path,
2499
+ value: scopeNode.schema?.[path] ?? 'not-in-schema',
2500
+ hasEquivalencies: true,
2501
+ });
2502
+ }
2503
+ }
2504
+ return results.sort((a, b) => a.path.localeCompare(b.path));
2505
+ }
2506
+ /**
2507
+ * Returns a summary of why a path might be missing from the schema.
2508
+ * Checks common issues that cause paths to not appear.
2509
+ */
2510
+ diagnoseMissingPath(scopeName, path) {
2511
+ const scopeNode = this.getScopeOrFunctionCallInfo(scopeName);
2512
+ const possibleReasons = [];
2513
+ const suggestions = [];
2514
+ if (!scopeNode) {
2515
+ possibleReasons.push(`Scope "${scopeName}" does not exist`);
2516
+ suggestions.push(`Available scopes: ${Object.keys(this.scopeNodes).join(', ')}`);
2517
+ return {
2518
+ exists: false,
2519
+ inSchema: false,
2520
+ inEquivalencies: false,
2521
+ possibleReasons,
2522
+ suggestions,
2523
+ };
2524
+ }
2525
+ const inSchema = path in (scopeNode.schema ?? {});
2526
+ const inEquivalencies = path in (scopeNode.equivalencies ?? {});
2527
+ if (inSchema) {
2528
+ return {
2529
+ exists: true,
2530
+ inSchema: true,
2531
+ inEquivalencies,
2532
+ possibleReasons: [],
2533
+ suggestions: [],
2534
+ };
2535
+ }
2536
+ // Check for similar paths
2537
+ const allPaths = [
2538
+ ...Object.keys(scopeNode.schema ?? {}),
2539
+ ...Object.keys(scopeNode.equivalencies ?? {}),
2540
+ ];
2541
+ const similarPaths = allPaths.filter((p) => {
2542
+ const pathParts = path.split('.');
2543
+ const pParts = p.split('.');
2544
+ return (pathParts.some((part) => pParts.includes(part)) ||
2545
+ p.includes(path) ||
2546
+ path.includes(p));
2547
+ });
2548
+ if (similarPaths.length > 0) {
2549
+ possibleReasons.push(`Path "${path}" not found but similar paths exist`);
2550
+ suggestions.push(`Similar paths: ${similarPaths.slice(0, 5).join(', ')}`);
2551
+ }
2552
+ // Check if it's a partial path
2553
+ const parentPath = path.split('.').slice(0, -1).join('.');
2554
+ if (parentPath && scopeNode.schema?.[parentPath]) {
2555
+ possibleReasons.push(`Parent path "${parentPath}" exists with value "${scopeNode.schema[parentPath]}"`);
2556
+ suggestions.push(`The property might not have been accessed in the analyzed code`);
2557
+ }
2558
+ // Check visited tracker
2559
+ const wasVisited = this.visitedTracker.wasVisited(scopeName, path);
2560
+ if (wasVisited) {
2561
+ possibleReasons.push(`Path was visited during analysis but not written`);
2562
+ suggestions.push(`Check if the path was filtered by isValidPath() or hit cycle detection`);
2563
+ }
2564
+ if (possibleReasons.length === 0) {
2565
+ possibleReasons.push(`Path "${path}" was never encountered during analysis`);
2566
+ suggestions.push(`Verify the path is accessed in the source code being analyzed`);
2567
+ }
2568
+ return {
2569
+ exists: false,
2570
+ inSchema,
2571
+ inEquivalencies,
2572
+ possibleReasons,
2573
+ suggestions,
2574
+ };
2575
+ }
2576
+ /**
2577
+ * Analyzes the stored equivalencies to provide aggregate statistics.
2578
+ * Call this AFTER analysis completes to understand equivalency patterns.
2579
+ *
2580
+ * @example
2581
+ * ```typescript
2582
+ * const analysis = sds.analyzeEquivalencies();
2583
+ * console.log(analysis.byReason); // Count by reason
2584
+ * console.log(analysis.byScope); // Count by scope
2585
+ * console.log(analysis.hotSpots); // Scopes with most equivalencies
2586
+ * ```
2587
+ */
2588
+ analyzeEquivalencies() {
2589
+ const byReason = {};
2590
+ const byScope = {};
2591
+ let total = 0;
2592
+ // Collect from all scope nodes
2593
+ for (const scopeName of Object.keys(this.scopeNodes)) {
2594
+ const scopeNode = this.scopeNodes[scopeName];
2595
+ const equivalencies = scopeNode.equivalencies ?? {};
2596
+ for (const path of Object.keys(equivalencies)) {
2597
+ for (const eq of equivalencies[path]) {
2598
+ total++;
2599
+ const reason = eq.equivalencyReason ?? 'unknown';
2600
+ byReason[reason] = (byReason[reason] ?? 0) + 1;
2601
+ byScope[scopeName] = (byScope[scopeName] ?? 0) + 1;
2602
+ }
2603
+ }
2604
+ }
2605
+ // Also check external function calls
2606
+ for (const fc of this.externalFunctionCalls) {
2607
+ const equivalencies = fc.equivalencies ?? {};
2608
+ for (const path of Object.keys(equivalencies)) {
2609
+ for (const eq of equivalencies[path]) {
2610
+ total++;
2611
+ const reason = eq.equivalencyReason ?? 'unknown';
2612
+ byReason[reason] = (byReason[reason] ?? 0) + 1;
2613
+ byScope[fc.name] = (byScope[fc.name] ?? 0) + 1;
2614
+ }
2615
+ }
2616
+ }
2617
+ // Find hot spots (scopes with most equivalencies)
2618
+ const hotSpots = Object.entries(byScope)
2619
+ .map(([scope, count]) => ({ scope, count }))
2620
+ .sort((a, b) => b.count - a.count)
2621
+ .slice(0, 10);
2622
+ // Find reasons that appear in stored equivalencies but aren't in ALLOWED list
2623
+ const unusedReasons = Object.keys(byReason).filter((reason) => !ALLOWED_EQUIVALENCY_REASONS.has(reason));
2624
+ return {
2625
+ total,
2626
+ byReason,
2627
+ byScope,
2628
+ hotSpots,
2629
+ unusedReasons,
2630
+ };
2631
+ }
2632
+ /**
2633
+ * Validates equivalencies and identifies potential problems.
2634
+ * Returns actionable issues that may indicate bugs or optimization opportunities.
2635
+ *
2636
+ * @example
2637
+ * ```typescript
2638
+ * const issues = sds.validateEquivalencies();
2639
+ * if (issues.length > 0) {
2640
+ * console.log('Found issues:', issues);
2641
+ * }
2642
+ * ```
2643
+ */
2644
+ validateEquivalencies() {
2645
+ const issues = [];
2646
+ const allScopeNames = new Set([
2647
+ ...Object.keys(this.scopeNodes),
2648
+ ...this.externalFunctionCalls.map((fc) => fc.name),
2649
+ ]);
2650
+ // Check all scope nodes
2651
+ for (const scopeName of Object.keys(this.scopeNodes)) {
2652
+ const scopeNode = this.scopeNodes[scopeName];
2653
+ const equivalencies = scopeNode.equivalencies ?? {};
2654
+ for (const [path, eqs] of Object.entries(equivalencies)) {
2655
+ for (const eq of eqs) {
2656
+ // Check 1: Does the target scope exist?
2657
+ if (!allScopeNames.has(eq.scopeNodeName)) {
2658
+ issues.push({
2659
+ type: 'broken_reference',
2660
+ severity: 'error',
2661
+ scope: scopeName,
2662
+ path,
2663
+ details: `Equivalency points to non-existent scope "${eq.scopeNodeName}"`,
2664
+ });
2665
+ continue;
2666
+ }
2667
+ // Check 2: Does the target path exist in target scope's schema or equivalencies?
2668
+ const targetScope = this.getScopeOrFunctionCallInfo(eq.scopeNodeName);
2669
+ if (targetScope) {
2670
+ const hasInSchema = eq.schemaPath in (targetScope.schema ?? {});
2671
+ const hasInEquivalencies = eq.schemaPath in (targetScope.equivalencies ?? {});
2672
+ // Only flag as dead end if it's a leaf path (no sub-properties exist)
2673
+ if (!hasInSchema && !hasInEquivalencies) {
2674
+ const hasSubPaths = Object.keys(targetScope.schema ?? {}).some((p) => p.startsWith(eq.schemaPath + '.') ||
2675
+ p.startsWith(eq.schemaPath + '['));
2676
+ if (!hasSubPaths) {
2677
+ issues.push({
2678
+ type: 'dead_end',
2679
+ severity: 'warning',
2680
+ scope: scopeName,
2681
+ path,
2682
+ details: `Equivalency to "${eq.scopeNodeName}::${eq.schemaPath}" - path not in schema`,
2683
+ });
2684
+ }
2685
+ }
2686
+ }
2687
+ }
2688
+ // Check 3: Trace chain depth
2689
+ const chain = this.traceEquivalencyChain(scopeName, path, 50);
2690
+ if (chain.length >= 20) {
2691
+ issues.push({
2692
+ type: 'long_chain',
2693
+ severity: 'warning',
2694
+ scope: scopeName,
2695
+ path,
2696
+ details: `Equivalency chain depth is ${chain.length} (may impact performance)`,
2697
+ });
2698
+ }
2699
+ // Check for potential cycles (chain that returns to starting point)
2700
+ const visited = new Set();
2701
+ for (const step of chain) {
2702
+ const key = `${step.scope}::${step.path}`;
2703
+ if (visited.has(key)) {
2704
+ issues.push({
2705
+ type: 'circular',
2706
+ severity: 'warning',
2707
+ scope: scopeName,
2708
+ path,
2709
+ details: `Circular reference detected at ${key}`,
2710
+ });
2711
+ break;
2712
+ }
2713
+ visited.add(key);
2714
+ }
2715
+ }
2716
+ }
2717
+ return issues;
2718
+ }
2101
2719
  }
2102
2720
  //# sourceMappingURL=ScopeDataStructure.js.map