@codeyam/codeyam-cli 0.1.0-staging.1 → 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 (440) 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 +8 -7
  4. package/analyzer-template/packages/ai/index.ts +2 -1
  5. package/analyzer-template/packages/ai/package.json +2 -2
  6. package/analyzer-template/packages/ai/scripts/ai-test-matrix.mjs +424 -0
  7. package/analyzer-template/packages/ai/src/lib/analyzeScope.ts +24 -0
  8. package/analyzer-template/packages/ai/src/lib/astScopes/astScopeAnalyzer.ts +6 -16
  9. package/analyzer-template/packages/ai/src/lib/astScopes/methodSemantics.ts +197 -0
  10. package/analyzer-template/packages/ai/src/lib/astScopes/paths.ts +28 -2
  11. package/analyzer-template/packages/ai/src/lib/astScopes/processExpression.ts +127 -4
  12. package/analyzer-template/packages/ai/src/lib/checkAllAttributes.ts +1 -3
  13. package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +1821 -542
  14. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/FunctionCallManager.ts +138 -0
  15. package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.ts +1 -1
  16. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.ts +139 -0
  17. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/DebugTracer.ts +224 -0
  18. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/PathManager.ts +203 -0
  19. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/README.md +294 -0
  20. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.ts +161 -0
  21. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/VisitedTracker.ts +235 -0
  22. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.ts +14 -6
  23. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/selectBestValue.ts +70 -0
  24. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/uniqueIdUtils.ts +113 -0
  25. package/analyzer-template/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.ts +36 -0
  26. package/analyzer-template/packages/ai/src/lib/generateChangesEntityDocumentation.ts +20 -2
  27. package/analyzer-template/packages/ai/src/lib/generateChangesEntityKeyAttributes.ts +51 -107
  28. package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarioData.ts +56 -160
  29. package/analyzer-template/packages/ai/src/lib/generateChangesEntityScenarios.ts +79 -265
  30. package/analyzer-template/packages/ai/src/lib/generateEntityDocumentation.ts +16 -2
  31. package/analyzer-template/packages/ai/src/lib/generateEntityKeyAttributes.ts +53 -176
  32. package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +53 -154
  33. package/analyzer-template/packages/ai/src/lib/generateEntityScenarios.ts +84 -254
  34. package/analyzer-template/packages/ai/src/lib/generateStatementAnalysis.ts +48 -71
  35. package/analyzer-template/packages/ai/src/lib/getConditionalUsagesFromCode.ts +27 -6
  36. package/analyzer-template/packages/ai/src/lib/getLLMCallStats.ts +0 -14
  37. package/analyzer-template/packages/ai/src/lib/modelInfo.ts +15 -0
  38. package/analyzer-template/packages/ai/src/lib/promptGenerators/gatherAttributesMap.ts +42 -4
  39. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityDocumentationGenerator.ts +8 -33
  40. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.ts +54 -62
  41. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.ts +93 -109
  42. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityDocumentationGenerator.ts +8 -27
  43. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.ts +33 -38
  44. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.ts +30 -30
  45. package/analyzer-template/packages/ai/src/lib/types/index.ts +2 -0
  46. package/analyzer-template/packages/ai/src/lib/worker/SerializableDataStructure.ts +39 -0
  47. package/analyzer-template/packages/analyze/src/lib/FileAnalyzer.ts +52 -6
  48. package/analyzer-template/packages/analyze/src/lib/asts/nodes/index.ts +2 -1
  49. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.ts +238 -0
  50. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getDeclaredEntityNode.ts +25 -0
  51. package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/index.ts +2 -0
  52. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.ts +8 -10
  53. package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +6 -1
  54. package/analyzer-template/packages/analyze/src/lib/files/analyze/gatherEntityMap.ts +8 -6
  55. package/analyzer-template/packages/analyze/src/lib/files/analyze/trackEntityCircularDependencies.ts +5 -13
  56. package/analyzer-template/packages/analyze/src/lib/files/analyzeChange.ts +34 -15
  57. package/analyzer-template/packages/analyze/src/lib/files/analyzeEntity.ts +17 -3
  58. package/analyzer-template/packages/analyze/src/lib/files/analyzeInitial.ts +35 -16
  59. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +7 -1
  60. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.ts +9 -1
  61. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarioData.ts +6 -1
  62. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateScenarios.ts +9 -1
  63. package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +15 -7
  64. package/analyzer-template/packages/aws/dist/src/lib/s3/getPresignedUrl.d.ts +23 -0
  65. package/analyzer-template/packages/aws/dist/src/lib/s3/getPresignedUrl.d.ts.map +1 -0
  66. package/analyzer-template/packages/aws/dist/src/lib/s3/getPresignedUrl.js +30 -0
  67. package/analyzer-template/packages/aws/dist/src/lib/s3/getPresignedUrl.js.map +1 -0
  68. package/analyzer-template/packages/aws/package.json +5 -4
  69. package/analyzer-template/packages/aws/s3/index.ts +4 -0
  70. package/analyzer-template/packages/aws/src/lib/s3/getPresignedUrl.ts +62 -0
  71. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.ts +28 -21
  72. package/analyzer-template/packages/generate/src/lib/componentScenarioPage/componentScenarioPageRemix.ts +18 -11
  73. package/analyzer-template/packages/generate/src/lib/scenarioComponent.ts +6 -3
  74. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.d.ts.map +1 -1
  75. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +28 -21
  76. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
  77. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageRemix.d.ts.map +1 -1
  78. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageRemix.js +18 -11
  79. package/analyzer-template/packages/github/dist/generate/src/lib/componentScenarioPage/componentScenarioPageRemix.js.map +1 -1
  80. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponent.d.ts.map +1 -1
  81. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponent.js +5 -3
  82. package/analyzer-template/packages/github/dist/generate/src/lib/scenarioComponent.js.map +1 -1
  83. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/db.d.ts +2 -0
  84. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/db.d.ts.map +1 -1
  85. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/db.js +3 -0
  86. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/db.js.map +1 -1
  87. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tableRelations.d.ts +2 -0
  88. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tableRelations.d.ts.map +1 -1
  89. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/debugReportsTable.d.ts +37 -0
  90. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/debugReportsTable.d.ts.map +1 -0
  91. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/debugReportsTable.js +27 -0
  92. package/analyzer-template/packages/github/dist/supabase/src/lib/kysely/tables/debugReportsTable.js.map +1 -0
  93. package/analyzer-template/packages/github/dist/utils/index.d.ts +2 -0
  94. package/analyzer-template/packages/github/dist/utils/index.d.ts.map +1 -1
  95. package/analyzer-template/packages/github/dist/utils/index.js +2 -0
  96. package/analyzer-template/packages/github/dist/utils/index.js.map +1 -1
  97. package/analyzer-template/packages/github/dist/utils/src/lib/Semaphore.d.ts +25 -0
  98. package/analyzer-template/packages/github/dist/utils/src/lib/Semaphore.d.ts.map +1 -0
  99. package/analyzer-template/packages/github/dist/utils/src/lib/Semaphore.js +40 -0
  100. package/analyzer-template/packages/github/dist/utils/src/lib/Semaphore.js.map +1 -0
  101. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getNextRoutePath.d.ts.map +1 -1
  102. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getNextRoutePath.js +5 -3
  103. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getNextRoutePath.js.map +1 -1
  104. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getRemixRoutePath.d.ts.map +1 -1
  105. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getRemixRoutePath.js +2 -1
  106. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/getRemixRoutePath.js.map +1 -1
  107. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.d.ts.map +1 -1
  108. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.js +2 -1
  109. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.js.map +1 -1
  110. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.d.ts.map +1 -1
  111. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.js +1 -0
  112. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.js.map +1 -1
  113. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.d.ts +12 -0
  114. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.d.ts.map +1 -0
  115. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.js +32 -0
  116. package/analyzer-template/packages/github/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.js.map +1 -0
  117. package/analyzer-template/packages/supabase/src/lib/kysely/db.ts +6 -0
  118. package/analyzer-template/packages/supabase/src/lib/kysely/tableRelations.ts +3 -0
  119. package/analyzer-template/packages/supabase/src/lib/kysely/tables/debugReportsTable.ts +61 -0
  120. package/analyzer-template/packages/ui-components/src/scenario-editor/components/DataItemEditor.tsx +1 -1
  121. package/analyzer-template/packages/utils/dist/utils/index.d.ts +2 -0
  122. package/analyzer-template/packages/utils/dist/utils/index.d.ts.map +1 -1
  123. package/analyzer-template/packages/utils/dist/utils/index.js +2 -0
  124. package/analyzer-template/packages/utils/dist/utils/index.js.map +1 -1
  125. package/analyzer-template/packages/utils/dist/utils/src/lib/Semaphore.d.ts +25 -0
  126. package/analyzer-template/packages/utils/dist/utils/src/lib/Semaphore.d.ts.map +1 -0
  127. package/analyzer-template/packages/utils/dist/utils/src/lib/Semaphore.js +40 -0
  128. package/analyzer-template/packages/utils/dist/utils/src/lib/Semaphore.js.map +1 -0
  129. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getNextRoutePath.d.ts.map +1 -1
  130. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getNextRoutePath.js +5 -3
  131. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getNextRoutePath.js.map +1 -1
  132. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getRemixRoutePath.d.ts.map +1 -1
  133. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getRemixRoutePath.js +2 -1
  134. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/getRemixRoutePath.js.map +1 -1
  135. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.d.ts.map +1 -1
  136. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.js +2 -1
  137. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/nextRouteFileNameToRoute.js.map +1 -1
  138. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.d.ts.map +1 -1
  139. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.js +1 -0
  140. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/remixRouteFileNameToRoute.js.map +1 -1
  141. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.d.ts +12 -0
  142. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.d.ts.map +1 -0
  143. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.js +32 -0
  144. package/analyzer-template/packages/utils/dist/utils/src/lib/frameworks/sanitizeNextRouteSegments.js.map +1 -0
  145. package/analyzer-template/packages/utils/index.ts +2 -0
  146. package/analyzer-template/packages/utils/src/lib/Semaphore.ts +42 -0
  147. package/analyzer-template/packages/utils/src/lib/frameworks/getNextRoutePath.ts +8 -3
  148. package/analyzer-template/packages/utils/src/lib/frameworks/getRemixRoutePath.ts +2 -1
  149. package/analyzer-template/packages/utils/src/lib/frameworks/nextRouteFileNameToRoute.ts +2 -1
  150. package/analyzer-template/packages/utils/src/lib/frameworks/remixRouteFileNameToRoute.ts +1 -0
  151. package/analyzer-template/packages/utils/src/lib/frameworks/sanitizeNextRouteSegments.ts +33 -0
  152. package/analyzer-template/project/constructMockCode.ts +170 -6
  153. package/analyzer-template/project/reconcileMockDataKeys.ts +13 -0
  154. package/analyzer-template/project/start.ts +1 -11
  155. package/analyzer-template/project/startScenarioCapture.ts +24 -0
  156. package/analyzer-template/project/trackGeneratedFiles.ts +41 -0
  157. package/analyzer-template/project/writeMockDataTsx.ts +125 -4
  158. package/analyzer-template/project/writeScenarioComponents.ts +199 -45
  159. package/analyzer-template/project/writeUniversalMocks.ts +72 -10
  160. package/background/src/lib/virtualized/project/constructMockCode.js +158 -7
  161. package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
  162. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js +12 -0
  163. package/background/src/lib/virtualized/project/reconcileMockDataKeys.js.map +1 -1
  164. package/background/src/lib/virtualized/project/start.js +1 -8
  165. package/background/src/lib/virtualized/project/start.js.map +1 -1
  166. package/background/src/lib/virtualized/project/startScenarioCapture.js +18 -0
  167. package/background/src/lib/virtualized/project/startScenarioCapture.js.map +1 -1
  168. package/background/src/lib/virtualized/project/trackGeneratedFiles.js +30 -0
  169. package/background/src/lib/virtualized/project/trackGeneratedFiles.js.map +1 -0
  170. package/background/src/lib/virtualized/project/writeMockDataTsx.js +95 -3
  171. package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
  172. package/background/src/lib/virtualized/project/writeScenarioComponents.js +144 -28
  173. package/background/src/lib/virtualized/project/writeScenarioComponents.js.map +1 -1
  174. package/background/src/lib/virtualized/project/writeUniversalMocks.js +59 -9
  175. package/background/src/lib/virtualized/project/writeUniversalMocks.js.map +1 -1
  176. package/codeyam-cli/scripts/apply-setup.js +288 -0
  177. package/codeyam-cli/scripts/apply-setup.js.map +1 -0
  178. package/codeyam-cli/scripts/extract-setup.js +130 -0
  179. package/codeyam-cli/scripts/extract-setup.js.map +1 -0
  180. package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js +238 -0
  181. package/codeyam-cli/scripts/fixtures/cal.com/universal-mocks/packages/prisma/index.js.map +1 -0
  182. package/codeyam-cli/src/cli.js +6 -0
  183. package/codeyam-cli/src/cli.js.map +1 -1
  184. package/codeyam-cli/src/codeyam-cli.js +0 -0
  185. package/codeyam-cli/src/commands/debug.js +221 -0
  186. package/codeyam-cli/src/commands/debug.js.map +1 -0
  187. package/codeyam-cli/src/commands/init.js +4 -23
  188. package/codeyam-cli/src/commands/init.js.map +1 -1
  189. package/codeyam-cli/src/commands/report.js +102 -0
  190. package/codeyam-cli/src/commands/report.js.map +1 -0
  191. package/codeyam-cli/src/commands/setup-sandbox.js +164 -0
  192. package/codeyam-cli/src/commands/setup-sandbox.js.map +1 -0
  193. package/codeyam-cli/src/utils/__tests__/cleanupAnalysisFiles.test.js +6 -6
  194. package/codeyam-cli/src/utils/__tests__/cleanupAnalysisFiles.test.js.map +1 -1
  195. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js +8 -0
  196. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js.map +1 -1
  197. package/codeyam-cli/src/utils/analysisRunner.js +4 -3
  198. package/codeyam-cli/src/utils/analysisRunner.js.map +1 -1
  199. package/codeyam-cli/src/utils/analyzer.js +30 -0
  200. package/codeyam-cli/src/utils/analyzer.js.map +1 -1
  201. package/codeyam-cli/src/utils/backgroundServer.js +25 -5
  202. package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
  203. package/codeyam-cli/src/utils/cleanupAnalysisFiles.js +2 -2
  204. package/codeyam-cli/src/utils/cleanupAnalysisFiles.js.map +1 -1
  205. package/codeyam-cli/src/utils/fileWatcher.js +75 -5
  206. package/codeyam-cli/src/utils/fileWatcher.js.map +1 -1
  207. package/codeyam-cli/src/utils/generateReport.js +219 -0
  208. package/codeyam-cli/src/utils/generateReport.js.map +1 -0
  209. package/codeyam-cli/src/utils/install-skills.js +7 -0
  210. package/codeyam-cli/src/utils/install-skills.js.map +1 -1
  211. package/codeyam-cli/src/utils/queue/__tests__/job.pidTracking.test.js +1 -0
  212. package/codeyam-cli/src/utils/queue/__tests__/job.pidTracking.test.js.map +1 -1
  213. package/codeyam-cli/src/utils/queue/job.js +8 -3
  214. package/codeyam-cli/src/utils/queue/job.js.map +1 -1
  215. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +4 -0
  216. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
  217. package/codeyam-cli/src/utils/webappDetection.js +2 -1
  218. package/codeyam-cli/src/utils/webappDetection.js.map +1 -1
  219. package/codeyam-cli/src/webserver/app/lib/database.js +63 -2
  220. package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
  221. package/codeyam-cli/src/webserver/backgroundServer.js +15 -35
  222. package/codeyam-cli/src/webserver/backgroundServer.js.map +1 -1
  223. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-D5ZHFomX.js +1 -0
  224. package/codeyam-cli/src/webserver/build/client/assets/{InteractivePreview-Dh-FldQK.js → InteractivePreview-XDSzQLOY.js} +3 -3
  225. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-BYVx9KFp.js +3 -0
  226. package/codeyam-cli/src/webserver/build/client/assets/{LogViewer-Dp6DC845.js → LogViewer-CRcT5fOZ.js} +1 -1
  227. package/codeyam-cli/src/webserver/build/client/assets/ReportIssueModal-BORLgi0X.js +1 -0
  228. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-Bual6h18.js +1 -0
  229. package/codeyam-cli/src/webserver/build/client/assets/ScenarioPreview-Bi-YUMa-.js +6 -0
  230. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-4D2vLLJz.js +5 -0
  231. package/codeyam-cli/src/webserver/build/client/assets/_index-BC200mfN.js +1 -0
  232. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-CxvZPkCv.js +10 -0
  233. package/codeyam-cli/src/webserver/build/client/assets/api.generate-report-l0sNRNKZ.js +1 -0
  234. package/codeyam-cli/src/webserver/build/client/assets/{chart-column-B2I7jQx2.js → chart-column-B8fb6wnw.js} +1 -1
  235. package/codeyam-cli/src/webserver/build/client/assets/chunk-WWGJGFF6-De6i8FUT.js +26 -0
  236. package/codeyam-cli/src/webserver/build/client/assets/{circle-alert-GwwOAbhw.js → circle-alert-IdsgAK39.js} +1 -1
  237. package/codeyam-cli/src/webserver/build/client/assets/circle-check-BACUUf75.js +1 -0
  238. package/codeyam-cli/src/webserver/build/client/assets/clock-vWeoCemX.js +1 -0
  239. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-CS7XDrKv.js +1 -0
  240. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-DIOEw_3i.js +1 -0
  241. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-1Z6D0fLM.js → entity._sha._-8Els_3Wb.js} +10 -10
  242. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-C3FZJx1w.js +1 -0
  243. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-YJz_igar.js +5 -0
  244. package/codeyam-cli/src/webserver/build/client/assets/entityStatus-BEqj2qBy.js +1 -0
  245. package/codeyam-cli/src/webserver/build/client/assets/{entityVersioning-DO2gCvXv.js → entityVersioning-Bk_YB1jM.js} +1 -1
  246. package/codeyam-cli/src/webserver/build/client/assets/entry.client-DiP0q291.js +5 -0
  247. package/codeyam-cli/src/webserver/build/client/assets/file-text-LM0mgxXE.js +1 -0
  248. package/codeyam-cli/src/webserver/build/client/assets/files-Dxh9CcaV.js +1 -0
  249. package/codeyam-cli/src/webserver/build/client/assets/git-BXmqrWCH.js +12 -0
  250. package/codeyam-cli/src/webserver/build/client/assets/globals-BGS74ED-.css +1 -0
  251. package/codeyam-cli/src/webserver/build/client/assets/html2canvas-pro.esm-XQCGvadH.js +5 -0
  252. package/codeyam-cli/src/webserver/build/client/assets/index-D-zYbzFZ.js +8 -0
  253. package/codeyam-cli/src/webserver/build/client/assets/{loader-circle-DN7Vr40D.js → loader-circle-BXPKbHEb.js} +1 -1
  254. package/codeyam-cli/src/webserver/build/client/assets/manifest-1af162d4.js +1 -0
  255. package/codeyam-cli/src/webserver/build/client/assets/root-DB7VgjCY.js +16 -0
  256. package/codeyam-cli/src/webserver/build/client/assets/{settings-MZc4XdmE.js → settings-5zF_GOcS.js} +1 -1
  257. package/codeyam-cli/src/webserver/build/client/assets/settings-Dc4MlMpK.js +1 -0
  258. package/codeyam-cli/src/webserver/build/client/assets/simulations-BQ-02-jB.js +1 -0
  259. package/codeyam-cli/src/webserver/build/client/assets/triangle-alert-D7k-ArFa.js +1 -0
  260. package/codeyam-cli/src/webserver/build/client/assets/{useLastLogLine-BBlyqxij.js → useLastLogLine-AlhS7g5F.js} +1 -1
  261. package/codeyam-cli/src/webserver/build/client/assets/useToast-Ddo4UQv7.js +1 -0
  262. package/codeyam-cli/src/webserver/build/client/assets/{zap-B4gsLUZQ.js → zap-_jw-9DCp.js} +1 -1
  263. package/codeyam-cli/src/webserver/build/server/assets/index-D4JpXSIO.js +1 -0
  264. package/codeyam-cli/src/webserver/build/server/assets/server-build-vwbN7n65.js +169 -0
  265. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  266. package/codeyam-cli/src/webserver/build-info.json +5 -5
  267. package/codeyam-cli/src/webserver/server.js +1 -1
  268. package/codeyam-cli/src/webserver/server.js.map +1 -1
  269. package/codeyam-cli/templates/codeyam-setup-skill.md +85 -94
  270. package/codeyam-cli/templates/debug-command.md +125 -0
  271. package/package.json +9 -11
  272. package/packages/ai/index.js +1 -2
  273. package/packages/ai/index.js.map +1 -1
  274. package/packages/ai/src/lib/analyzeScope.js +13 -0
  275. package/packages/ai/src/lib/analyzeScope.js.map +1 -1
  276. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js +6 -15
  277. package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js.map +1 -1
  278. package/packages/ai/src/lib/astScopes/methodSemantics.js +134 -0
  279. package/packages/ai/src/lib/astScopes/methodSemantics.js.map +1 -1
  280. package/packages/ai/src/lib/astScopes/paths.js +28 -3
  281. package/packages/ai/src/lib/astScopes/paths.js.map +1 -1
  282. package/packages/ai/src/lib/astScopes/processExpression.js +111 -3
  283. package/packages/ai/src/lib/astScopes/processExpression.js.map +1 -1
  284. package/packages/ai/src/lib/checkAllAttributes.js +1 -3
  285. package/packages/ai/src/lib/checkAllAttributes.js.map +1 -1
  286. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +1320 -396
  287. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
  288. package/packages/ai/src/lib/dataStructure/equivalencyManagers/FunctionCallManager.js +137 -1
  289. package/packages/ai/src/lib/dataStructure/equivalencyManagers/FunctionCallManager.js.map +1 -1
  290. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js +1 -1
  291. package/packages/ai/src/lib/dataStructure/equivalencyManagers/frameworks/ReactFrameworkManager.js.map +1 -1
  292. package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js +112 -0
  293. package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js.map +1 -0
  294. package/packages/ai/src/lib/dataStructure/helpers/DebugTracer.js +176 -0
  295. package/packages/ai/src/lib/dataStructure/helpers/DebugTracer.js.map +1 -0
  296. package/packages/ai/src/lib/dataStructure/helpers/PathManager.js +178 -0
  297. package/packages/ai/src/lib/dataStructure/helpers/PathManager.js.map +1 -0
  298. package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js +138 -0
  299. package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js.map +1 -0
  300. package/packages/ai/src/lib/dataStructure/helpers/VisitedTracker.js +199 -0
  301. package/packages/ai/src/lib/dataStructure/helpers/VisitedTracker.js.map +1 -0
  302. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js +14 -6
  303. package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js.map +1 -1
  304. package/packages/ai/src/lib/dataStructure/helpers/selectBestValue.js +62 -0
  305. package/packages/ai/src/lib/dataStructure/helpers/selectBestValue.js.map +1 -0
  306. package/packages/ai/src/lib/dataStructure/helpers/uniqueIdUtils.js +90 -0
  307. package/packages/ai/src/lib/dataStructure/helpers/uniqueIdUtils.js.map +1 -0
  308. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js +22 -0
  309. package/packages/ai/src/lib/gatherRelevantDependentKeyAttributes.js.map +1 -1
  310. package/packages/ai/src/lib/generateChangesEntityDocumentation.js +19 -1
  311. package/packages/ai/src/lib/generateChangesEntityDocumentation.js.map +1 -1
  312. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js +51 -107
  313. package/packages/ai/src/lib/generateChangesEntityKeyAttributes.js.map +1 -1
  314. package/packages/ai/src/lib/generateChangesEntityScenarioData.js +55 -156
  315. package/packages/ai/src/lib/generateChangesEntityScenarioData.js.map +1 -1
  316. package/packages/ai/src/lib/generateChangesEntityScenarios.js +79 -262
  317. package/packages/ai/src/lib/generateChangesEntityScenarios.js.map +1 -1
  318. package/packages/ai/src/lib/generateEntityDocumentation.js +15 -1
  319. package/packages/ai/src/lib/generateEntityDocumentation.js.map +1 -1
  320. package/packages/ai/src/lib/generateEntityKeyAttributes.js +53 -176
  321. package/packages/ai/src/lib/generateEntityKeyAttributes.js.map +1 -1
  322. package/packages/ai/src/lib/generateEntityScenarioData.js +52 -152
  323. package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
  324. package/packages/ai/src/lib/generateEntityScenarios.js +88 -258
  325. package/packages/ai/src/lib/generateEntityScenarios.js.map +1 -1
  326. package/packages/ai/src/lib/generateStatementAnalysis.js +46 -71
  327. package/packages/ai/src/lib/generateStatementAnalysis.js.map +1 -1
  328. package/packages/ai/src/lib/getConditionalUsagesFromCode.js +13 -8
  329. package/packages/ai/src/lib/getConditionalUsagesFromCode.js.map +1 -1
  330. package/packages/ai/src/lib/getLLMCallStats.js +0 -14
  331. package/packages/ai/src/lib/getLLMCallStats.js.map +1 -1
  332. package/packages/ai/src/lib/modelInfo.js +15 -0
  333. package/packages/ai/src/lib/modelInfo.js.map +1 -1
  334. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js +36 -3
  335. package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js.map +1 -1
  336. package/packages/ai/src/lib/promptGenerators/generateChangesEntityDocumentationGenerator.js +8 -33
  337. package/packages/ai/src/lib/promptGenerators/generateChangesEntityDocumentationGenerator.js.map +1 -1
  338. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js +35 -41
  339. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenarioDataGenerator.js.map +1 -1
  340. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js +59 -72
  341. package/packages/ai/src/lib/promptGenerators/generateChangesEntityScenariosGenerator.js.map +1 -1
  342. package/packages/ai/src/lib/promptGenerators/generateEntityDocumentationGenerator.js +8 -27
  343. package/packages/ai/src/lib/promptGenerators/generateEntityDocumentationGenerator.js.map +1 -1
  344. package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js +24 -27
  345. package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js.map +1 -1
  346. package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js +21 -22
  347. package/packages/ai/src/lib/promptGenerators/generateEntityScenariosGenerator.js.map +1 -1
  348. package/packages/ai/src/lib/types/index.js +2 -0
  349. package/packages/ai/src/lib/types/index.js.map +1 -1
  350. package/packages/ai/src/lib/worker/SerializableDataStructure.js +7 -0
  351. package/packages/ai/src/lib/worker/SerializableDataStructure.js.map +1 -1
  352. package/packages/analyze/src/lib/FileAnalyzer.js +45 -5
  353. package/packages/analyze/src/lib/FileAnalyzer.js.map +1 -1
  354. package/packages/analyze/src/lib/asts/nodes/index.js +2 -1
  355. package/packages/analyze/src/lib/asts/nodes/index.js.map +1 -1
  356. package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js +191 -0
  357. package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js.map +1 -0
  358. package/packages/analyze/src/lib/asts/sourceFiles/getDeclaredEntityNode.js +16 -0
  359. package/packages/analyze/src/lib/asts/sourceFiles/getDeclaredEntityNode.js.map +1 -0
  360. package/packages/analyze/src/lib/asts/sourceFiles/index.js +2 -0
  361. package/packages/analyze/src/lib/asts/sourceFiles/index.js.map +1 -1
  362. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +6 -8
  363. package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
  364. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +5 -1
  365. package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
  366. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js +8 -2
  367. package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js.map +1 -1
  368. package/packages/analyze/src/lib/files/analyze/trackEntityCircularDependencies.js +5 -8
  369. package/packages/analyze/src/lib/files/analyze/trackEntityCircularDependencies.js.map +1 -1
  370. package/packages/analyze/src/lib/files/analyzeChange.js +21 -9
  371. package/packages/analyze/src/lib/files/analyzeChange.js.map +1 -1
  372. package/packages/analyze/src/lib/files/analyzeEntity.js +10 -4
  373. package/packages/analyze/src/lib/files/analyzeEntity.js.map +1 -1
  374. package/packages/analyze/src/lib/files/analyzeInitial.js +21 -9
  375. package/packages/analyze/src/lib/files/analyzeInitial.js.map +1 -1
  376. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +6 -1
  377. package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
  378. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js +9 -1
  379. package/packages/analyze/src/lib/files/scenarios/generateKeyAttributes.js.map +1 -1
  380. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js +5 -1
  381. package/packages/analyze/src/lib/files/scenarios/generateScenarioData.js.map +1 -1
  382. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js +9 -1
  383. package/packages/analyze/src/lib/files/scenarios/generateScenarios.js.map +1 -1
  384. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +16 -7
  385. package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
  386. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js +28 -21
  387. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageNext.js.map +1 -1
  388. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageRemix.js +18 -11
  389. package/packages/generate/src/lib/componentScenarioPage/componentScenarioPageRemix.js.map +1 -1
  390. package/packages/generate/src/lib/scenarioComponent.js +5 -3
  391. package/packages/generate/src/lib/scenarioComponent.js.map +1 -1
  392. package/packages/supabase/src/lib/kysely/db.js +3 -0
  393. package/packages/supabase/src/lib/kysely/db.js.map +1 -1
  394. package/packages/supabase/src/lib/kysely/tables/debugReportsTable.js +27 -0
  395. package/packages/supabase/src/lib/kysely/tables/debugReportsTable.js.map +1 -0
  396. package/packages/utils/index.js +2 -0
  397. package/packages/utils/index.js.map +1 -1
  398. package/packages/utils/src/lib/Semaphore.js +40 -0
  399. package/packages/utils/src/lib/Semaphore.js.map +1 -0
  400. package/packages/utils/src/lib/frameworks/getNextRoutePath.js +5 -3
  401. package/packages/utils/src/lib/frameworks/getNextRoutePath.js.map +1 -1
  402. package/packages/utils/src/lib/frameworks/getRemixRoutePath.js +2 -1
  403. package/packages/utils/src/lib/frameworks/getRemixRoutePath.js.map +1 -1
  404. package/packages/utils/src/lib/frameworks/nextRouteFileNameToRoute.js +2 -1
  405. package/packages/utils/src/lib/frameworks/nextRouteFileNameToRoute.js.map +1 -1
  406. package/packages/utils/src/lib/frameworks/remixRouteFileNameToRoute.js +1 -0
  407. package/packages/utils/src/lib/frameworks/remixRouteFileNameToRoute.js.map +1 -1
  408. package/packages/utils/src/lib/frameworks/sanitizeNextRouteSegments.js +32 -0
  409. package/packages/utils/src/lib/frameworks/sanitizeNextRouteSegments.js.map +1 -0
  410. package/analyzer-template/packages/ai/src/lib/generateEntityDataMap.ts +0 -375
  411. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeIcon-GqWwt5wG.js +0 -1
  412. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-p0fuyqGQ.js +0 -3
  413. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-xwuhwsZH.js +0 -1
  414. package/codeyam-cli/src/webserver/build/client/assets/ScenarioPreview-Bl2IRh55.js +0 -1
  415. package/codeyam-cli/src/webserver/build/client/assets/ScenarioViewer-M2QuSHKC.js +0 -5
  416. package/codeyam-cli/src/webserver/build/client/assets/_index-CAVtep9Q.js +0 -1
  417. package/codeyam-cli/src/webserver/build/client/assets/activity.(_tab)-CLmzsLsT.js +0 -10
  418. package/codeyam-cli/src/webserver/build/client/assets/components-CAx5ONX_.js +0 -40
  419. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-CgyOwWip.js +0 -1
  420. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-DGy3zrli.js +0 -1
  421. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-ChAdTrrU.js +0 -1
  422. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.edit._scenarioId-D9L7267w.js +0 -5
  423. package/codeyam-cli/src/webserver/build/client/assets/entry.client-C6FRgjPr.js +0 -1
  424. package/codeyam-cli/src/webserver/build/client/assets/files-C3-cQjgv.js +0 -1
  425. package/codeyam-cli/src/webserver/build/client/assets/git-Dp4EB9nv.js +0 -12
  426. package/codeyam-cli/src/webserver/build/client/assets/globals-Da3jt49-.css +0 -1
  427. package/codeyam-cli/src/webserver/build/client/assets/manifest-172a4629.js +0 -1
  428. package/codeyam-cli/src/webserver/build/client/assets/root-COyVTsPq.js +0 -16
  429. package/codeyam-cli/src/webserver/build/client/assets/search-CvyP_1Lo.js +0 -1
  430. package/codeyam-cli/src/webserver/build/client/assets/settings-Hbf8b7J_.js +0 -1
  431. package/codeyam-cli/src/webserver/build/client/assets/simulations-BMBi0VzO.js +0 -1
  432. package/codeyam-cli/src/webserver/build/client/assets/useToast-C_VxoXTh.js +0 -1
  433. package/codeyam-cli/src/webserver/build/client/cy-logo-cli.svg +0 -13
  434. package/codeyam-cli/src/webserver/build/server/assets/index-eAULANMV.js +0 -1
  435. package/codeyam-cli/src/webserver/build/server/assets/server-build-lutv16q5.js +0 -161
  436. package/codeyam-cli/src/webserver/public/cy-logo-cli.svg +0 -13
  437. package/packages/ai/src/lib/generateEntityDataMap.js +0 -335
  438. package/packages/ai/src/lib/generateEntityDataMap.js.map +0 -1
  439. package/packages/ai/src/lib/promptGenerators/generateEntityDataMapGenerator.js +0 -17
  440. package/packages/ai/src/lib/promptGenerators/generateEntityDataMapGenerator.js.map +0 -1
@@ -1,71 +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;
102
+ export let addEquivalencyCallCount = 0;
37
103
  export function resetScopeDataStructureMetrics() {
38
104
  maxEquivalencyChainDepth = 0;
39
105
  addToSchemaCallCount = 0;
40
106
  followEquivalenciesCallCount = 0;
107
+ followEquivalenciesEarlyExitCount = 0;
108
+ followEquivalenciesEarlyExitPhase1Count = 0;
109
+ followEquivalenciesWithWorkCount = 0;
110
+ addEquivalencyCallCount = 0;
41
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
+ ]);
42
155
  export class ScopeDataStructure {
156
+ // Getter for backward compatibility - returns the tree structure
157
+ get scopeTree() {
158
+ return this.scopeTreeManager.getTree();
159
+ }
43
160
  constructor(managers, scopeName = ROOT_SCOPE_NAME, scopeText, scopeAnalysis) {
44
161
  this.debugCount = 0;
45
162
  this.onlyEquivalencies = true;
46
163
  this.equivalencyManagers = [];
47
164
  this.scopeNodes = {};
48
- this.scopeTree = { name: ROOT_SCOPE_NAME, children: [] };
165
+ this.scopeTreeManager = new ScopeTreeManager();
49
166
  this.externalFunctionCalls = [];
50
167
  this.environmentVariables = [];
51
168
  this.equivalencyDatabase = [];
169
+ /**
170
+ * Conditional usages collected during AST analysis.
171
+ * Maps local variable path to array of usages.
172
+ */
173
+ this.rawConditionalUsages = {};
52
174
  this.lastAddToSchemaId = 0;
53
175
  this.lastEquivalencyId = 0;
54
176
  this.lastEquivalencyDatabaseId = 0;
55
- this.pathPartsCache = new Map();
56
- this.pathJoinCache = new Map();
177
+ this.pathManager = new PathManager();
178
+ this.visitedTracker = new VisitedTracker();
57
179
  this.equivalencyDatabaseCache = new Map();
58
180
  // Inverted index: maps uniqueId -> EquivalencyDatabaseEntry for O(1) lookup
59
181
  this.intermediatesOrderIndex = new Map();
60
- this.globalVisited = 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;
61
203
  this.equivalencyManagers.push(...managers);
62
- this.scopeTree.name = scopeName;
204
+ this.scopeTreeManager.setRootName(scopeName);
63
205
  this.addScopeAnalysis(scopeName, scopeText, scopeAnalysis);
64
206
  }
65
207
  addScopeAnalysis(scopeNodeName, scopeText, scopeAnalysis, parentScopeName, isStatic) {
66
208
  try {
67
- if (scopeNodeName !== this.scopeTree.name && !parentScopeName) {
68
- parentScopeName = this.scopeTree.name;
209
+ if (scopeNodeName !== this.scopeTreeManager.getRootName() &&
210
+ !parentScopeName) {
211
+ parentScopeName = this.scopeTreeManager.getRootName();
69
212
  }
70
213
  let tree = [];
71
214
  if (parentScopeName) {
@@ -106,7 +249,7 @@ export class ScopeDataStructure {
106
249
  }
107
250
  catch (error) {
108
251
  console.log('CodeYam Error: Failed to add scope analysis for scope:', JSON.stringify({
109
- rootScopeName: this.scopeTree.name,
252
+ rootScopeName: this.scopeTreeManager.getRootName(),
110
253
  scopeNodeName,
111
254
  scopeNodeText: scopeText,
112
255
  isolatedStructure: scopeAnalysis.isolatedStructure,
@@ -115,26 +258,46 @@ export class ScopeDataStructure {
115
258
  throw error;
116
259
  }
117
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
+ */
118
281
  async captureCompleteSchema() {
282
+ // Reset state for Phase 2
119
283
  this.onlyEquivalencies = false;
120
284
  this.equivalencyDatabase = [];
121
- this.equivalencyDatabaseCache.clear(); // Clear cache when database is reset
122
- this.intermediatesOrderIndex.clear(); // Clear inverted index when database is reset
123
- this.globalVisited = new Set([]);
285
+ this.equivalencyDatabaseCache.clear();
286
+ this.intermediatesOrderIndex.clear();
287
+ this.visitedTracker.resetGlobalVisited();
124
288
  for (const externalFunctionCall of this.externalFunctionCalls) {
125
289
  externalFunctionCall.schema = {};
126
290
  }
127
- // for (const scopeNode of Object.values(this.scopeNodes)) {
291
+ // Build schemas for all scopes in parallel
128
292
  await Promise.all(Object.values(this.scopeNodes).map(async (scopeNode) => {
129
293
  scopeNode.schema = {};
130
294
  await this.determineEquivalenciesAndBuildSchema(scopeNode);
131
295
  }));
132
- // }
133
296
  const validExternalFacingScopeNames = new Set([
134
- this.scopeTree.name,
297
+ this.scopeTreeManager.getRootName(),
135
298
  ]);
136
299
  this.externalFunctionCalls = this.externalFunctionCalls.filter((efc) => {
137
- const efcName = efc.name.split('<')[0];
300
+ const efcName = this.pathManager.stripGenerics(efc.name);
138
301
  for (const manager of this.equivalencyManagers) {
139
302
  if (manager.internalFunctions.has(efcName)) {
140
303
  return false;
@@ -143,54 +306,90 @@ export class ScopeDataStructure {
143
306
  validExternalFacingScopeNames.add(efcName);
144
307
  return true;
145
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}(`));
146
313
  for (const entry of this.equivalencyDatabase) {
147
- entry.usages = entry.usages.filter((usage) => validExternalFacingScopeNames.has(usage.scopeNodeName.split('<')[0]) &&
148
- (usage.schemaPath.startsWith('returnValue') ||
149
- usage.schemaPath.startsWith(usage.scopeNodeName.split('<')[0])) &&
150
- !Array.from(arrayMethodsSet).some((method) => usage.schemaPath.includes(`.${method}(`)));
151
- entry.sourceCandidates = entry.sourceCandidates.filter((candidate) => validExternalFacingScopeNames.has(candidate.scopeNodeName.split('<')[0]) &&
152
- (candidate.schemaPath.startsWith('signature[') ||
153
- candidate.schemaPath.startsWith(candidate.scopeNodeName.split('<')[0])) &&
154
- !Array.from(arrayMethodsSet).some((method) => candidate.schemaPath.includes(`.${method}(`)));
155
- }
156
- 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()]);
157
330
  for (const externalFunctionCall of this.externalFunctionCalls) {
158
- const t = new Date().getTime();
159
- // console.info("Start Propagating", JSON.stringify({
160
- // externalFunctionCallName: externalFunctionCall.name,
161
- // // sourceEquivalencies: externalFunctionCall.sourceEquivalencies,
162
- // }, null, 2));
163
331
  this.propagateSourceAndUsageEquivalencies(externalFunctionCall);
164
- const elapsedTime = new Date().getTime() - t;
165
- if (elapsedTime > 100) {
166
- console.warn('Long Propagation Time', {
167
- externalFunctionCallName: externalFunctionCall.name,
168
- time: elapsedTime,
169
- });
170
- // throw new Error("STOP - LONG PROPAGATION TIME")
171
- }
172
- // console.info("Done Propagating", JSON.stringify({
173
- // externalFunctionCallName: externalFunctionCall.name,
174
- // // sourceEquivalencies: externalFunctionCall.sourceEquivalencies,
175
- // // usageEquivalencies: externalFunctionCall.usageEquivalencies,
176
- // time: elapsedTime
177
- // }, null, 2))
178
332
  }
179
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
+ */
180
360
  addToSchema({ path, value, scopeNode, equivalencyValueChain = [], traceId, }) {
181
361
  addToSchemaCallCount++;
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
370
+ if (addToSchemaCallCount > 500000) {
371
+ console.error('INFINITE LOOP DETECTED in addToSchema', {
372
+ callCount: addToSchemaCallCount,
373
+ path,
374
+ value,
375
+ scopeNodeName: scopeNode?.name,
376
+ });
377
+ throw new Error(`Infinite loop detected: addToSchema called ${addToSchemaCallCount} times`);
378
+ }
182
379
  // Track max chain depth
183
380
  if (equivalencyValueChain.length > maxEquivalencyChainDepth) {
184
381
  maxEquivalencyChainDepth = equivalencyValueChain.length;
185
382
  }
186
- if (!scopeNode)
383
+ if (!scopeNode) {
187
384
  return;
385
+ }
188
386
  if (!this.isValidPath(path)) {
189
387
  if (traceId) {
190
388
  console.info('Debug propagation: not a valid path', { path, traceId });
191
389
  }
192
390
  return;
193
391
  }
392
+ // Update chain metadata for database tracking
194
393
  if (equivalencyValueChain.length > 0) {
195
394
  equivalencyValueChain[equivalencyValueChain.length - 1].addToSchemaId =
196
395
  ++this.lastAddToSchemaId;
@@ -200,87 +399,35 @@ export class ScopeDataStructure {
200
399
  value,
201
400
  };
202
401
  }
203
- // Use this debugging to track down an infinite loop
204
- // traceId ||= 0;
205
- // traceId += 1;
206
- // if (traceId) {
207
- // console.info(JSON.stringify({ traceId, path, value, scopeNodeName: scopeNode.name }, null, 2));
208
- // }
209
- // if (traceId > 30) {
210
- // console.warn(
211
- // 'HIGH TRACEID',
212
- // JSON.stringify(
213
- // {
214
- // path,
215
- // value,
216
- // scopeNodeName: scopeNode.name,
217
- // equivalencyValueChain,
218
- // },
219
- // null,
220
- // 2,
221
- // ),
222
- // );
223
- // throw new Error('STOP - HIGH TRACEID');
224
- // }
225
- // Use this debugging to trace a specific path through the propagation
226
- const debugLevel = 0; // 0 for minimal, 1 for executed paths, 2 for all paths info
227
- // if ((!this.onlyEquivalencies && path === 'entity.sha') || traceId) {
228
- // traceId ||= 0;
229
- // traceId += 1;
230
- // if (traceId === 1) {
231
- // this.debugCount += 1;
232
- // if (this.debugCount > 5) throw new Error('STOP - HIGH DEBUG COUNT');
233
- // console.warn('START');
234
- // }
235
- // console.info(
236
- // 'Debug Propagation: Adding to schema',
237
- // JSON.stringify(
238
- // {
239
- // // traceId,
240
- // path,
241
- // value,
242
- // scopeNodeName: scopeNode.name,
243
- // reason:
244
- // equivalencyValueChain[equivalencyValueChain.length - 1]?.reason,
245
- // // previous:
246
- // // equivalencyValueChain[equivalencyValueChain.length - 1],
247
- // text: scopeNode.text,
248
- // // tree: scopeNode.tree,
249
- // // onlyEquivalencies: this.onlyEquivalencies,
250
- // // equivalencyValueChain,
251
- // // scopeNode
252
- // // instatiatedVeriables: scopeNode.instantiatedVariables,
253
- // // parentInstantiatedVariables: scopeNode.parentInstantiatedVariables,
254
- // // isolatedStructure: scopeNode.analysis.isolatedStructure,
255
- // // isolatedEquivalencies: scopeNode.analysis.isolatedEquivalentVariables,
256
- // // equivalencies: traceId === 1 ? scopeNode.equivalencies : 'skipped',
257
- // // functionCalls: scopeNode.functionCalls,
258
- // // externalFunctionCalls: this.externalFunctionCalls.filter(fc => fc.callScope.includes(scopeNode.name))
259
- // },
260
- // null,
261
- // 2,
262
- // ),
263
- // );
264
- // // if (traceId > 1) traceId = undefined;
265
- // throw new Error('STOP ON ADD');
266
- // }
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
+ // ─────────────────────────────────────────────────────────────────────────
267
407
  const equivalenciesDatabaseEntry = this.getEquivalenciesDatabaseEntry(scopeNode.name, path);
408
+ // Process complex source paths (before visited check, per original design)
268
409
  this.addComplexSourcePathVariables(equivalenciesDatabaseEntry, scopeNode, path, equivalencyValueChain, traceId);
269
- const uniqueIdentifier = `${scopeNode.name}::${path}::${value}`;
270
- 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)) {
271
414
  if (traceId) {
272
- console.info('Debug propagation: already globally visited path', JSON.stringify({
273
- uniqueIdentifier,
274
- // equivalencyValueChain,
275
- }, null, 2));
415
+ console.info('Debug: already visited', {
416
+ key: `${scopeNode.name}::${path}::${value}`,
417
+ });
276
418
  }
419
+ // Still record in database even if visited (captures full chain)
277
420
  if (!this.onlyEquivalencies) {
278
421
  this.addToEquivalencyDatabase(equivalencyValueChain, traceId);
279
422
  }
280
423
  return;
281
424
  }
282
- this.globalVisited.add(uniqueIdentifier);
425
+ // Continue complex source processing after visited check
283
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
+ // ─────────────────────────────────────────────────────────────────────────
284
431
  const pathParts = this.splitPath(path);
285
432
  this.checkForArrayItemPath(pathParts, scopeNode, equivalencyValueChain);
286
433
  let propagated = false;
@@ -368,45 +515,42 @@ export class ScopeDataStructure {
368
515
  }
369
516
  }
370
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
+ // ─────────────────────────────────────────────────────────────────────────
371
523
  const writeToCurrentScopeSchema = (!scopeNode.schema[path] || scopeNode.schema[path] === 'unknown') &&
372
524
  (!scopeNode.instantiatedVariables ||
373
525
  scopeNode.instantiatedVariables.includes(pathParts[0]) ||
374
526
  pathParts[0].startsWith('signature[') ||
375
527
  pathParts[0].startsWith('returnValue'));
376
- // Safe early exit: if we've already set this exact schema value, skip processing
528
+ // Early exit if schema already has this exact value
377
529
  if (scopeNode.schema[path] === value && value !== 'unknown') {
378
530
  return;
379
531
  }
380
532
  if (writeToCurrentScopeSchema) {
381
533
  if (traceId && debugLevel > 0) {
382
- console.info('Debug Propagation: currentScope executed', {
383
- traceId,
534
+ console.info('Debug: writing schema', {
384
535
  path,
385
- pathParts,
386
- scopeNodeName: scopeNode.name,
536
+ value,
537
+ scope: scopeNode.name,
387
538
  });
388
539
  }
389
540
  scopeNode.schema[path] = value;
390
541
  }
542
+ // ─────────────────────────────────────────────────────────────────────────
543
+ // SECTION 5: Record in equivalency database (Phase 2 only)
544
+ // ─────────────────────────────────────────────────────────────────────────
391
545
  if (!this.onlyEquivalencies) {
392
546
  this.addToEquivalencyDatabase(equivalencyValueChain, traceId);
393
547
  }
394
548
  if (traceId) {
395
- console.info('Debug Propagation: exiting', JSON.stringify({
396
- traceId,
397
- scopeNodeName: scopeNode.name,
549
+ console.info('Debug: addToSchema complete', {
550
+ scope: scopeNode.name,
398
551
  path,
399
552
  value,
400
- // schemaValue: scopeNode.schema[path],
401
- // propagated,
402
- // scopeInfoText: scopeNode.text,
403
- // equivalencyValueChain//: equivalencyValueChain.map(
404
- // (ev) => ev.currentPath.schemaPath,
405
- // ),
406
- // sourceEquivalencies: scopeNode.sourceEquivalencies[path] ?? [],
407
- // usageEquivalencies: scopeNode.usageEquivalencies[path] ?? [],
408
- // checkpoints,
409
- }, null, 2));
553
+ });
410
554
  }
411
555
  }
412
556
  removeFromSchema(path, schema = {}, scopeName) {
@@ -414,50 +558,29 @@ export class ScopeDataStructure {
414
558
  }
415
559
  addEquivalency(path, equivalentPath, equivalentScopeName, scopeNode, equivalencyReason, equivalencyValueChain, traceId) {
416
560
  var _a;
417
- // Temporary debugging to track down unnecessary equivalencies
418
- if (![
419
- 'original equivalency',
420
- 'implicit parent equivalency',
421
- 'explicit parent equivalency',
422
- 'transformed non-object function equivalency - original equivalency',
423
- 'equivalency to external function call',
424
- 'functionCall to function signature equivalency', // 1 failure
425
- 'explicit parent signature',
426
- 'useState setter call equivalency',
427
- 'non-object function argument function signature equivalency1',
428
- 'non-object function argument function signature equivalency2',
429
- 'returnValue to functionCallReturnValue equivalency', // 2 failures
430
- '.map() function deconstruction', // 1 failure
431
- 'useMemo return value equivalent to first argument return value',
432
- 'useState value equivalency', // 1 failure
433
- 'Node .then() equivalency', // 1 failure
434
- 'Explicit array deconstruction equivalency value', // 1 failure
435
- 'forwardRef equivalency',
436
- 'forwardRef signature to child signature equivalency', // 1 failure
437
- 'captured function call return value equivalency', // 1 failure (in ScopeDataStructure.test.ts)
438
- 'original equivalency - rerouted via useCallback', // 1 failure
439
- 'non-object function argument function signature equivalency1 - rerouted via useCallback', // 1 failure
440
- 'non-object function argument function signature equivalency2 - rerouted via useCallback', // 1 failure
441
- 'implicit parent equivalency - rerouted via useCallback', // 1 failure
442
- 'Spread operator equivalency key update: implicit parent equivalency', // 1 failure
443
- 'Array.from() equivalency',
444
- ].includes(equivalencyReason)) {
445
- if ([
446
- 'signature of functionCall',
447
- 'transformed non-object function equivalency - implicit parent equivalency',
448
- 'transformed non-object function equivalency - non-object function argument function signature equivalency1',
449
- 'transformed non-object function equivalency - non-object function argument function signature equivalency2',
450
- 'transformed non-object function equivalency - equivalency to external function call',
451
- 'Explicit array deconstruction equivalency key',
452
- 'transformed non-object function equivalency - useState setter call equivalency',
453
- 'transformed non-object function equivalency - implicit parent equivalency - rerouted via useCallback',
454
- 'transformed non-object function equivalency - Array.from() equivalency',
455
- 'Spread operator equivalency key update: Explicit array deconstruction equivalency value',
456
- ].includes(equivalencyReason)) {
561
+ // DEBUG: Detect infinite loops
562
+ addEquivalencyCallCount++;
563
+ if (addEquivalencyCallCount > 50000) {
564
+ console.error('INFINITE LOOP DETECTED in addEquivalency', {
565
+ callCount: addEquivalencyCallCount,
566
+ path,
567
+ equivalentPath,
568
+ equivalentScopeName,
569
+ scopeNodeName: scopeNode.name,
570
+ equivalencyReason,
571
+ });
572
+ throw new Error(`Infinite loop detected: addEquivalency called ${addEquivalencyCallCount} times`);
573
+ }
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)) {
457
577
  return;
458
578
  }
459
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)
460
582
  console.info('Not tracked equivalency reason', { equivalencyReason });
583
+ return;
461
584
  }
462
585
  }
463
586
  if (!equivalentScopeName) {
@@ -471,8 +594,41 @@ export class ScopeDataStructure {
471
594
  }
472
595
  (_a = scopeNode.equivalencies)[path] || (_a[path] = []);
473
596
  const existing = scopeNode.equivalencies[path];
474
- if (existing.find((v) => v.schemaPath === equivalentPath &&
475
- v.scopeNodeName === equivalentScopeName)) {
597
+ const existingEquivalency = existing.find((v) => v.schemaPath === equivalentPath &&
598
+ v.scopeNodeName === equivalentScopeName);
599
+ if (existingEquivalency) {
600
+ // During Phase 2 (onlyEquivalencies=false), we need to still process the equivalency
601
+ // to build the chain and add to the database, even if the equivalency already exists
602
+ if (!this.onlyEquivalencies) {
603
+ const equivalentScopeNode = this.getScopeOrFunctionCallInfo(equivalentScopeName);
604
+ if (equivalentScopeNode) {
605
+ // Extract function call name from path if it looks like a function call path
606
+ // e.g., "ChildComponent().signature[0].dataItem" -> "ChildComponent"
607
+ const pathMatch = path.match(/^([^().]+)\(\)/);
608
+ const previousPathScopeNodeName = pathMatch
609
+ ? pathMatch[1]
610
+ : scopeNode.name;
611
+ this.addToSchema({
612
+ path: equivalentPath,
613
+ value: 'unknown',
614
+ scopeNode: equivalentScopeNode,
615
+ equivalencyValueChain: [
616
+ ...(equivalencyValueChain ?? []),
617
+ {
618
+ id: existingEquivalency.id,
619
+ source: 'duplicate equivalency - Phase 2',
620
+ reason: equivalencyReason,
621
+ previousPath: {
622
+ scopeNodeName: previousPathScopeNodeName,
623
+ schemaPath: path,
624
+ value: scopeNode.schema[path],
625
+ },
626
+ },
627
+ ],
628
+ traceId,
629
+ });
630
+ }
631
+ }
476
632
  return;
477
633
  }
478
634
  const id = ++this.lastEquivalencyId;
@@ -553,7 +709,8 @@ export class ScopeDataStructure {
553
709
  if (!functionCallInfo.equivalencies) {
554
710
  functionCallInfo.equivalencies = {};
555
711
  }
556
- const existingFunctionCall = this.externalFunctionCalls.find((fc) => getFunctionCallRoot(functionCallInfo.callSignature) === fc.name);
712
+ const searchKey = getFunctionCallRoot(functionCallInfo.callSignature);
713
+ const existingFunctionCall = this.getExternalFunctionCallsIndex().get(searchKey);
557
714
  if (existingFunctionCall) {
558
715
  existingFunctionCall.schema = {
559
716
  ...existingFunctionCall.schema,
@@ -570,6 +727,7 @@ export class ScopeDataStructure {
570
727
  !callingScopeNode.parentInstantiatedVariables?.includes(functionCallInfoNameParts[0]);
571
728
  if (isExternal) {
572
729
  this.externalFunctionCalls.push(functionCallInfo);
730
+ this.invalidateExternalFunctionCallsIndex();
573
731
  }
574
732
  }
575
733
  }
@@ -591,7 +749,7 @@ export class ScopeDataStructure {
591
749
  // );
592
750
  // }
593
751
  const getRootOrExternalFunctionCallInfo = (name) => {
594
- return name === this.scopeTree.name
752
+ return name === this.scopeTreeManager.getRootName()
595
753
  ? this.getScopeNode()
596
754
  : this.getExternalFunctionCallInfo(name);
597
755
  };
@@ -609,82 +767,49 @@ export class ScopeDataStructure {
609
767
  schemaPath === safePath ||
610
768
  safePath.startsWith(schemaPath));
611
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
+ }
612
789
  for (const schemaPath of relevantSchemaPaths) {
613
790
  const schemaPathParts = this.splitPath(schemaPath);
614
791
  if (!pathParts.every((p, i) => schemaPathParts[i] === p)) {
615
792
  continue;
616
793
  }
617
794
  const remainingSchemaPathParts = schemaPathParts.slice(pathParts.length);
618
- let missingEquivalentPath = false;
619
- // Performance optimization: pre-filter equivalent schema paths
620
- const relevantEquivalentSchemaPaths = Object.keys(equivalentScopeNode.schema).filter((equivalentSchemaPath) => {
621
- // Quick string check before expensive path splitting
622
- return (equivalentSchemaPath.startsWith(equivalentPath) ||
623
- equivalentSchemaPath === equivalentPath ||
624
- equivalentPath.startsWith(equivalentSchemaPath));
625
- });
626
- for (const equivalentSchemaPath of relevantEquivalentSchemaPaths) {
627
- const equivalentSchemaPathParts = this.splitPath(equivalentSchemaPath);
628
- if (!equivalentPathParts.every((p, i) => equivalentSchemaPathParts[i] === p)) {
629
- continue;
630
- }
631
- const remainingEquivalentSchemaPathParts = equivalentSchemaPathParts.slice(equivalentPathParts.length);
632
- if (remainingSchemaPathParts.length !==
633
- remainingEquivalentSchemaPathParts.length ||
634
- !remainingEquivalentSchemaPathParts.every((p, i) => p === remainingSchemaPathParts[i])) {
635
- missingEquivalentPath = true;
636
- continue;
637
- }
638
- 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) {
639
799
  const value1 = scopeNode.schema[schemaPath];
640
800
  const value2 = equivalentScopeNode.schema[equivalentSchemaPath];
641
- let bestValue = value1 ?? value2 ?? 'unknown';
642
- if (value2 &&
643
- ((bestValue === 'unknown' && value2 !== 'unknown') ||
644
- (bestValue.includes('unknown') && !value2.includes('unknown')))) {
645
- bestValue = value2;
646
- }
801
+ const bestValue = selectBestValue(value1, value2);
647
802
  scopeNode.schema[schemaPath] = bestValue;
648
803
  equivalentScopeNode.schema[equivalentSchemaPath] = bestValue;
649
- // if (traceId) {
650
- // console.info('Debug Propagate: Assign Best Value', {
651
- // traceId,
652
- // sourceScopeNodeName: scopeNode.name,
653
- // path,
654
- // schemaPath,
655
- // usageScopeNodeName: equivalentScopeNode.name,
656
- // equivalentPath,
657
- // equivalentSchemaPath,
658
- // remainingSchemaPathParts,
659
- // remainingEquivalentSchemaPathParts,
660
- // value1,
661
- // value2,
662
- // bestValue,
663
- // });
664
- // }
665
- break;
666
804
  }
667
- if (missingEquivalentPath &&
668
- (scopeNode.name.includes('____cyScope') ||
669
- !('instantiatedVariables' in equivalentScopeNode))) {
805
+ else if (scopeNode.name.includes('____cyScope') ||
806
+ !('instantiatedVariables' in equivalentScopeNode)) {
807
+ // No matching equivalent path found - create one if needed
670
808
  // Only necessary for internal function scopes or external function scopes
671
809
  const newEquivalentPath = this.joinPathParts([
672
810
  equivalentPath,
673
811
  ...remainingSchemaPathParts,
674
812
  ]);
675
- // if (traceId) {
676
- // console.info('Debug Propagate: missing equivalent path', {
677
- // traceId,
678
- // scopeNodeName: scopeNode.name,
679
- // path,
680
- // equivalentPath,
681
- // schemaPath,
682
- // remainingSchemaPathParts,
683
- // equivalentScopeNodeName: equivalentScopeNode.name,
684
- // // equivalentScopeNodeSchema: equivalentScopeNode.schema,
685
- // newEquivalentPath,
686
- // });
687
- // }
688
813
  equivalentScopeNode.schema[newEquivalentPath] =
689
814
  scopeNode.schema[schemaPath];
690
815
  }
@@ -707,83 +832,26 @@ export class ScopeDataStructure {
707
832
  }
708
833
  }
709
834
  splitPath(path) {
710
- if (this.pathPartsCache.has(path)) {
711
- return structuredClone(this.pathPartsCache.get(path));
712
- }
713
- const pathParts = splitOutsideParenthesesAndArrays(path);
714
- this.pathPartsCache.set(path, structuredClone(pathParts));
715
- return pathParts;
835
+ return this.pathManager.splitPath(path);
716
836
  }
717
837
  joinPathParts(pathParts) {
718
- const cacheKey = pathParts.join('|');
719
- if (this.pathJoinCache.has(cacheKey)) {
720
- return this.pathJoinCache.get(cacheKey);
721
- }
722
- const result = joinParenthesesAndArrays(pathParts);
723
- this.pathJoinCache.set(cacheKey, result);
724
- return result;
838
+ return this.pathManager.joinPathParts(pathParts);
725
839
  }
726
840
  // PRIVATE METHODS //
727
- uniqueId({ scopeNodeName, schemaPath, value, }) {
728
- const parts = [scopeNodeName, schemaPath, value].filter(Boolean);
729
- return parts.join('::');
841
+ uniqueId(params) {
842
+ return uniqueId(params);
730
843
  }
731
844
  uniqueScopeVariables(scopeVariables) {
732
- return this.uniqueScopeAndPaths(scopeVariables);
845
+ return uniqueScopeVariables(scopeVariables);
733
846
  }
734
847
  uniqueScopeAndPaths(scopeVariables) {
735
- if (!scopeVariables || scopeVariables.length === 0)
736
- return [];
737
- // Optimize from O(n²) to O(n) using Set for deduplication
738
- const seen = new Set();
739
- return scopeVariables.filter((varItem) => {
740
- const key = `${varItem.scopeNodeName}::${varItem.schemaPath}`;
741
- if (seen.has(key)) {
742
- return false;
743
- }
744
- seen.add(key);
745
- return true;
746
- });
848
+ return uniqueScopeAndPaths(scopeVariables);
747
849
  }
748
850
  isValidPath(path) {
749
- if (typeof path !== 'string') {
750
- return false;
751
- }
752
- if (!path) {
753
- return false;
754
- }
755
- if (path === 'true' || path === 'false') {
756
- return false;
757
- }
758
- if (!isNaN(Number(path))) {
759
- return false;
760
- }
761
- if (path.match(/^['"]/)) {
762
- return false;
763
- }
764
- return this.splitPath(path).every((part) => {
765
- if (cleanOutBoundary(cleanOutBoundary(cleanOutBoundary(part, '<', '>'), '[', ']')).match(/\s/)) {
766
- return false;
767
- }
768
- return true;
769
- });
851
+ return this.pathManager.isValidPath(path);
770
852
  }
771
853
  addToTree(pathParts) {
772
- let scopeTreeNode = { children: [this.scopeTree] };
773
- for (const pathPart of pathParts) {
774
- const existingChild = scopeTreeNode.children.find((child) => child.name === pathPart);
775
- if (existingChild) {
776
- scopeTreeNode = existingChild;
777
- }
778
- else {
779
- const childScopeTreeNode = {
780
- name: pathPart,
781
- children: [],
782
- };
783
- scopeTreeNode.children.push(childScopeTreeNode);
784
- scopeTreeNode = childScopeTreeNode;
785
- }
786
- }
854
+ this.scopeTreeManager.addPath(pathParts);
787
855
  }
788
856
  setInstantiatedVariables(scopeNode) {
789
857
  let instantiatedVariables = scopeNode.analysis?.instantiatedVariables ?? [];
@@ -834,14 +902,63 @@ export class ScopeDataStructure {
834
902
  path = cleanPath(path.replace(/::cyDuplicateKey\d+::/g, ''), allPaths);
835
903
  equivalentValue = cleanPath(equivalentValue.replace(/::cyDuplicateKey\d+::/g, ''), allPaths);
836
904
  this.addEquivalency(path, equivalentValue, scopeNode.name, scopeNode, 'original equivalency');
905
+ // Propagate sub-property equivalencies when the equivalentValue is a simple variable
906
+ // that has sub-properties defined in the isolatedEquivalentVariables.
907
+ // This handles cases like: dataItem={{ structure: completeDataStructure }}
908
+ // where completeDataStructure has sub-properties like completeDataStructure['Function Arguments']
909
+ // We need to propagate these to create: dataItem.structure['Function Arguments'] equivalencies
910
+ const isSimpleVariable = !equivalentValue.startsWith('signature[') &&
911
+ !equivalentValue.includes('functionCallReturnValue') &&
912
+ !equivalentValue.includes('.') &&
913
+ !equivalentValue.includes('[');
914
+ if (isSimpleVariable) {
915
+ // Look in current scope and all parent scopes for sub-properties
916
+ const scopesToCheck = [scopeNode.name, ...scopeNode.tree];
917
+ for (const scopeName of scopesToCheck) {
918
+ const checkScope = this.scopeNodes[scopeName];
919
+ if (!checkScope?.analysis?.isolatedEquivalentVariables)
920
+ continue;
921
+ for (const [subPath, subValue] of Object.entries(checkScope.analysis.isolatedEquivalentVariables)) {
922
+ // Check if this is a sub-property of the equivalentValue variable
923
+ // e.g., completeDataStructure['Function Arguments'] or completeDataStructure.foo
924
+ const matchesDot = subPath.startsWith(equivalentValue + '.');
925
+ const matchesBracket = subPath.startsWith(equivalentValue + '[');
926
+ if (matchesDot || matchesBracket) {
927
+ const subPropertyPath = subPath.substring(equivalentValue.length);
928
+ const newPath = cleanPath(path + subPropertyPath, allPaths);
929
+ const newEquivalentValue = cleanPath(subValue.replace(/::cyDuplicateKey\d+::/g, ''), allPaths);
930
+ if (newEquivalentValue &&
931
+ this.isValidPath(newEquivalentValue)) {
932
+ this.addEquivalency(newPath, newEquivalentValue, checkScope.name, // Use the scope where the sub-property was found
933
+ scopeNode, 'propagated sub-property equivalency');
934
+ }
935
+ }
936
+ // Also check if equivalentValue itself maps to a functionCallReturnValue
937
+ // e.g., result = useMemo(...).functionCallReturnValue
938
+ if (subPath === equivalentValue &&
939
+ typeof subValue === 'string' &&
940
+ subValue.endsWith('.functionCallReturnValue')) {
941
+ this.propagateFunctionCallReturnSubProperties(path, subValue, scopeNode, allPaths);
942
+ }
943
+ }
944
+ }
945
+ }
946
+ // Handle function call return values by propagating returnValue.* sub-properties
947
+ // from the callback scope to the usage path
948
+ if (equivalentValue.endsWith('.functionCallReturnValue')) {
949
+ this.propagateFunctionCallReturnSubProperties(path, equivalentValue, scopeNode, allPaths);
950
+ }
837
951
  }
838
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();
839
957
  for (const key of Array.from(allPaths)) {
840
958
  let value = isolatedStructure[key] ?? 'unknown';
841
959
  if (['null', 'undefined'].includes(value)) {
842
960
  value = 'unknown';
843
961
  }
844
- const startTime = new Date().getTime();
845
962
  this.addToSchema({
846
963
  path: cleanPath(key, allPaths),
847
964
  value,
@@ -854,25 +971,221 @@ export class ScopeDataStructure {
854
971
  },
855
972
  ],
856
973
  });
857
- // const timeDiff = new Date().getTime() - startTime;
858
- // if (timeDiff / 1000 > 1) {
859
- // console.info('SLOW', {
860
- // timeDiff,
861
- // root: this.scopeTree.name,
862
- // scopeNodeName: scopeNode.name,
863
- // schemaPath: key,
864
- // onlyEquivalencies: this.onlyEquivalencies,
865
- // });
866
- // }
867
- }
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;
868
982
  this.validateSchema(scopeNode, false, false);
869
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
+ }
1007
+ /**
1008
+ * Propagates returnValue.* sub-properties from a callback scope to the usage path.
1009
+ *
1010
+ * When we have an equivalency like:
1011
+ * DataItemEditor().signature[0].structure -> getData().functionCallReturnValue
1012
+ *
1013
+ * And the callback scope for getData has:
1014
+ * returnValue.args -> dataStructure.arguments
1015
+ *
1016
+ * This method creates the transitive equivalency:
1017
+ * DataItemEditor().signature[0].structure.args -> signature[0].dataStructure.arguments
1018
+ *
1019
+ * It also resolves variable references through parent scopes (e.g., dataStructure -> signature[0].dataStructure)
1020
+ * and ensures the database entry is updated with the usage path.
1021
+ */
1022
+ propagateFunctionCallReturnSubProperties(path, equivalentValue, scopeNode, allPaths) {
1023
+ // Try to find the callback scope name from different patterns:
1024
+ // 1. "getData().functionCallReturnValue" → look up getData variable to find scope
1025
+ // 2. "useMemo(cyScope1(), [...]).functionCallReturnValue" → extract cyScope1 directly
1026
+ let callbackScopeName;
1027
+ // Pattern 1: Simple function call like getData().functionCallReturnValue
1028
+ const simpleFunctionMatch = equivalentValue.match(/^(\w+)\(\)\.functionCallReturnValue$/);
1029
+ if (simpleFunctionMatch) {
1030
+ const functionName = simpleFunctionMatch[1];
1031
+ // Find the function reference in current or parent scopes
1032
+ const scopesToCheck = [scopeNode.name, ...scopeNode.tree];
1033
+ for (const scopeName of scopesToCheck) {
1034
+ const checkScope = this.scopeNodes[scopeName];
1035
+ if (!checkScope?.analysis?.isolatedEquivalentVariables)
1036
+ continue;
1037
+ const functionRef = checkScope.analysis.isolatedEquivalentVariables[functionName];
1038
+ if (typeof functionRef === 'string' && functionRef.endsWith('F')) {
1039
+ callbackScopeName = functionRef.slice(0, -1);
1040
+ break;
1041
+ }
1042
+ }
1043
+ }
1044
+ // Pattern 2: useMemo/useCallback with callback scope
1045
+ // e.g., "useMemo(cyScope1(), [deps]).functionCallReturnValue"
1046
+ if (!callbackScopeName) {
1047
+ const useMemoMatch = equivalentValue.match(/^useMemo\((\w+)\(\),\s*\[.*\]\)\.functionCallReturnValue$/);
1048
+ if (useMemoMatch) {
1049
+ callbackScopeName = useMemoMatch[1];
1050
+ }
1051
+ }
1052
+ if (!callbackScopeName)
1053
+ return;
1054
+ const callbackScope = this.scopeNodes[callbackScopeName];
1055
+ if (!callbackScope)
1056
+ return;
1057
+ // Look for returnValue.* sub-properties in the callback scope
1058
+ if (!callbackScope.analysis?.isolatedEquivalentVariables)
1059
+ return;
1060
+ const isolatedVars = callbackScope.analysis.isolatedEquivalentVariables;
1061
+ // First, check if returnValue is an alias to another variable (e.g., returnValue = intermediate)
1062
+ // If so, we need to look for that variable's sub-properties too
1063
+ const returnValueAlias = typeof isolatedVars.returnValue === 'string' &&
1064
+ !isolatedVars.returnValue.includes('.')
1065
+ ? isolatedVars.returnValue
1066
+ : undefined;
1067
+ // Pattern 3: Object.keys(X).reduce() - the reduce result has the same sub-properties as X
1068
+ // When returnValue = "Object.keys(source).reduce(...).functionCallReturnValue", look for source.* sub-properties
1069
+ let reduceSourceVar;
1070
+ if (typeof isolatedVars.returnValue === 'string') {
1071
+ const reduceMatch = isolatedVars.returnValue.match(/^Object\.keys\((\w+)\)\.reduce\(.*\)\.functionCallReturnValue$/);
1072
+ if (reduceMatch) {
1073
+ reduceSourceVar = reduceMatch[1];
1074
+ }
1075
+ }
1076
+ for (const [subPath, subValue] of Object.entries(isolatedVars)) {
1077
+ // Check for direct returnValue.* sub-properties
1078
+ const isReturnValueSub = subPath.startsWith('returnValue.') ||
1079
+ subPath.startsWith('returnValue[');
1080
+ // Also check for alias.* sub-properties (e.g., intermediate.args when returnValue = intermediate)
1081
+ const isAliasSub = returnValueAlias &&
1082
+ (subPath.startsWith(returnValueAlias + '.') ||
1083
+ subPath.startsWith(returnValueAlias + '['));
1084
+ // Also check for reduce source.* sub-properties (e.g., source['Function Arguments'] when returnValue = Object.keys(source).reduce())
1085
+ const isReduceSourceSub = reduceSourceVar &&
1086
+ (subPath.startsWith(reduceSourceVar + '.') ||
1087
+ subPath.startsWith(reduceSourceVar + '['));
1088
+ if (typeof subValue !== 'string' ||
1089
+ (!isReturnValueSub && !isAliasSub && !isReduceSourceSub))
1090
+ continue;
1091
+ // Convert alias/reduceSource paths to returnValue paths
1092
+ let effectiveSubPath = subPath;
1093
+ if (isAliasSub && !isReturnValueSub) {
1094
+ // Replace the alias prefix with returnValue
1095
+ effectiveSubPath =
1096
+ 'returnValue' + subPath.substring(returnValueAlias.length);
1097
+ }
1098
+ else if (isReduceSourceSub && !isReturnValueSub && !isAliasSub) {
1099
+ // Replace the reduce source prefix with returnValue
1100
+ effectiveSubPath =
1101
+ 'returnValue' + subPath.substring(reduceSourceVar.length);
1102
+ }
1103
+ const subPropertyPath = effectiveSubPath.substring('returnValue'.length);
1104
+ const newPath = cleanPath(path + subPropertyPath, allPaths);
1105
+ let newEquivalentValue = cleanPath(subValue.replace(/::cyDuplicateKey\d+::/g, ''), allPaths);
1106
+ // Resolve variable references through parent scope equivalencies
1107
+ const resolved = this.resolveVariableThroughParentScopes(newEquivalentValue, callbackScope, allPaths);
1108
+ newEquivalentValue = resolved.resolvedPath;
1109
+ const equivalentScopeName = resolved.scopeName;
1110
+ if (!newEquivalentValue || !this.isValidPath(newEquivalentValue))
1111
+ continue;
1112
+ this.addEquivalency(newPath, newEquivalentValue, equivalentScopeName, scopeNode, 'propagated function call return sub-property equivalency');
1113
+ // Ensure the database entry has the usage path
1114
+ this.addUsageToEquivalencyDatabaseEntry(newPath, newEquivalentValue, equivalentScopeName, scopeNode.name);
1115
+ }
1116
+ }
1117
+ /**
1118
+ * Resolves a variable path through parent scope equivalencies.
1119
+ *
1120
+ * For example, if the path is "dataStructure.arguments" and the parent scope has
1121
+ * dataStructure -> signature[0].dataStructure, this returns:
1122
+ * { resolvedPath: "signature[0].dataStructure.arguments", scopeName: "ParentScope" }
1123
+ */
1124
+ resolveVariableThroughParentScopes(path, callbackScope, allPaths) {
1125
+ if (!path)
1126
+ return { resolvedPath: undefined, scopeName: callbackScope.name };
1127
+ // Extract the root variable name
1128
+ const dotIndex = path.indexOf('.');
1129
+ const bracketIndex = path.indexOf('[');
1130
+ let firstDelimiter = -1;
1131
+ if (dotIndex > -1 && bracketIndex > -1) {
1132
+ firstDelimiter = Math.min(dotIndex, bracketIndex);
1133
+ }
1134
+ else {
1135
+ firstDelimiter = dotIndex > -1 ? dotIndex : bracketIndex;
1136
+ }
1137
+ if (firstDelimiter === -1)
1138
+ return { resolvedPath: path, scopeName: callbackScope.name };
1139
+ const rootVar = path.substring(0, firstDelimiter);
1140
+ const restOfPath = path.substring(firstDelimiter);
1141
+ // Look in parent scopes for the root variable's equivalency
1142
+ for (const parentScopeName of callbackScope.tree || []) {
1143
+ const parentScope = this.scopeNodes[parentScopeName];
1144
+ if (!parentScope?.analysis?.isolatedEquivalentVariables)
1145
+ continue;
1146
+ const rootEquiv = parentScope.analysis.isolatedEquivalentVariables[rootVar];
1147
+ if (typeof rootEquiv === 'string') {
1148
+ return {
1149
+ resolvedPath: cleanPath(rootEquiv + restOfPath, allPaths),
1150
+ scopeName: parentScopeName,
1151
+ };
1152
+ }
1153
+ }
1154
+ return { resolvedPath: path, scopeName: callbackScope.name };
1155
+ }
1156
+ /**
1157
+ * Adds a usage path to the equivalency database entry that has the given source.
1158
+ *
1159
+ * The addEquivalency call creates the equivalency but doesn't always properly
1160
+ * link the usage in the database, so we need to do it explicitly.
1161
+ */
1162
+ addUsageToEquivalencyDatabaseEntry(usagePath, sourcePath, sourceScopeName, fallbackScopeName) {
1163
+ const usageEntry = {
1164
+ scopeNodeName: usagePath.match(/^([^().]+)\(\)/)
1165
+ ? (usagePath.match(/^([^().]+)\(\)/)?.[1] ?? fallbackScopeName)
1166
+ : fallbackScopeName,
1167
+ schemaPath: usagePath,
1168
+ };
1169
+ const sourceKey = `${sourceScopeName}::${sourcePath}`;
1170
+ for (const entry of this.equivalencyDatabase) {
1171
+ if (entry.intermediatesOrder[sourceKey] === 0 ||
1172
+ entry.sourceCandidates.some((sc) => sc.scopeNodeName === sourceScopeName &&
1173
+ sc.schemaPath === sourcePath)) {
1174
+ const usageExists = entry.usages.some((u) => u.scopeNodeName === usageEntry.scopeNodeName &&
1175
+ u.schemaPath === usageEntry.schemaPath);
1176
+ if (!usageExists) {
1177
+ entry.usages.push(usageEntry);
1178
+ }
1179
+ break;
1180
+ }
1181
+ }
1182
+ }
870
1183
  checkForArrayItemPath(pathParts, scopeNode, equivalencyValueChain) {
871
- const arrayItemPath = joinParenthesesAndArrays([...pathParts, '[]']);
1184
+ const arrayItemPath = this.joinPathParts([...pathParts, '[]']);
872
1185
  if (scopeNode.equivalencies[arrayItemPath]) {
873
1186
  const firstEquivalency = equivalencyValueChain[0].currentPath;
874
- const newFirstEquivalencyPath = joinParenthesesAndArrays([
875
- ...splitOutsideParenthesesAndArrays(firstEquivalency.schemaPath),
1187
+ const newFirstEquivalencyPath = this.joinPathParts([
1188
+ ...this.splitPath(firstEquivalency.schemaPath),
876
1189
  '[]',
877
1190
  ]);
878
1191
  this.addToSchema({
@@ -889,27 +1202,77 @@ export class ScopeDataStructure {
889
1202
  });
890
1203
  }
891
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
+ */
892
1231
  followEquivalencies(scopeNode, path, pathParts, subPath, subPathParts, value, equivalencyValueChain, traceId, debugLevel = 0) {
893
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
+ });
894
1240
  let propagated = false;
1241
+ // ─────────────────────────────────────────────────────────────────────────
1242
+ // Step 1: Collect equivalencies (including function-ambivalent paths)
1243
+ // ─────────────────────────────────────────────────────────────────────────
895
1244
  let equivalentValues = scopeNode.equivalencies[subPath] ?? [];
896
1245
  let functionAmbivalentSubPath = subPath;
897
1246
  let functionAmbivalentSubPathParts = subPathParts;
898
- 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
899
1254
  functionAmbivalentSubPathParts = [
900
1255
  ...subPathParts.slice(0, -1),
901
- subPathParts[subPathParts.length - 1].split('(')[0],
1256
+ lastPart.split('(')[0],
902
1257
  ];
903
1258
  functionAmbivalentSubPath = this.joinPathParts(functionAmbivalentSubPathParts);
904
- equivalentValues = [
905
- ...(equivalentValues ?? []),
906
- ...(scopeNode.equivalencies[functionAmbivalentSubPath] ?? []),
907
- ];
1259
+ const functionAmbivalentEquivalencies = scopeNode.equivalencies[functionAmbivalentSubPath];
1260
+ if (functionAmbivalentEquivalencies?.length > 0) {
1261
+ equivalentValues = [
1262
+ ...equivalentValues,
1263
+ ...functionAmbivalentEquivalencies,
1264
+ ];
1265
+ }
908
1266
  }
909
1267
  // Early exit optimization: if no equivalencies to follow, skip expensive processing
910
1268
  if (equivalentValues.length === 0) {
1269
+ followEquivalenciesEarlyExitCount++;
1270
+ if (this.onlyEquivalencies) {
1271
+ followEquivalenciesEarlyExitPhase1Count++;
1272
+ }
911
1273
  return false;
912
1274
  }
1275
+ followEquivalenciesWithWorkCount++;
913
1276
  if (traceId && debugLevel > 1) {
914
1277
  console.info('Debug Propagation: equivalence', JSON.stringify({
915
1278
  traceId,
@@ -925,10 +1288,17 @@ export class ScopeDataStructure {
925
1288
  }, null, 2));
926
1289
  }
927
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;
928
1296
  for (let index = 0; index < uniqueEquivalentValues.length; ++index) {
929
1297
  const equivalentValue = uniqueEquivalentValues[index];
930
- if (equivalentValue.id !== -1 &&
931
- 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)) {
932
1302
  if (traceId) {
933
1303
  console.info('Debug Propagation: skipping circular equivalence', JSON.stringify({
934
1304
  traceId,
@@ -956,8 +1326,12 @@ export class ScopeDataStructure {
956
1326
  if (lastRelevantSubPathPart.endsWith(')') &&
957
1327
  schemaPathParts[schemaPathParts.length - 1] ===
958
1328
  lastRelevantSubPathPart.split('(')[0]) {
959
- schemaPathParts[schemaPathParts.length - 1] = lastRelevantSubPathPart;
960
- 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);
961
1335
  }
962
1336
  const remainingPathParts = pathParts.slice(relevantSubPathParts.length);
963
1337
  const remainingPath = this.joinPathParts(remainingPathParts);
@@ -1000,23 +1374,27 @@ export class ScopeDataStructure {
1000
1374
  // equivalencies: scopeNode.equivalencies,
1001
1375
  }, null, 2));
1002
1376
  }
1003
- const localEquivalencyValueChain = structuredClone(equivalencyValueChain);
1004
- localEquivalencyValueChain.push({
1005
- id: equivalentValue.id,
1006
- source: 'equivalence',
1007
- previousPath: {
1008
- scopeNodeName: scopeNode.name,
1009
- schemaPath: path,
1010
- value,
1011
- },
1012
- currentPath: {
1013
- scopeNodeName: equivalentScopeNode.name,
1014
- schemaPath: newEquivalentPath,
1015
- 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,
1016
1396
  },
1017
- reason: equivalentValue.equivalencyReason,
1018
- traceId,
1019
- });
1397
+ ];
1020
1398
  // writeEquivalencyToFile(
1021
1399
  // scopeNode.name,
1022
1400
  // subPath,
@@ -1026,13 +1404,48 @@ export class ScopeDataStructure {
1026
1404
  // equivalentValue.equivalencyReason,
1027
1405
  // )
1028
1406
  propagated = true;
1029
- this.addToSchema({
1030
- path: newEquivalentPath,
1031
- value,
1032
- scopeNode: equivalentScopeNode,
1033
- equivalencyValueChain: localEquivalencyValueChain,
1034
- traceId,
1035
- });
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
+ }
1036
1449
  }
1037
1450
  }
1038
1451
  return propagated;
@@ -1054,6 +1467,11 @@ export class ScopeDataStructure {
1054
1467
  return;
1055
1468
  }
1056
1469
  const usageScopeNode = this.getScopeOrFunctionCallInfo(usageEquivalency.scopeNodeName);
1470
+ // Guard against infinite recursion by tracking which paths we've already
1471
+ // added from addComplexSourcePathVariables
1472
+ if (this.visitedTracker.checkAndMarkComplexSourceVisited(usageScopeNode.name, newUsageEquivalentPath)) {
1473
+ continue;
1474
+ }
1057
1475
  this.addToSchema({
1058
1476
  path: newUsageEquivalentPath,
1059
1477
  value: 'unknown',
@@ -1162,6 +1580,7 @@ export class ScopeDataStructure {
1162
1580
  }
1163
1581
  for (let i = 0; i < cleanEquivalencyValueChain.length; ++i) {
1164
1582
  const pathInfo = cleanEquivalencyValueChain[i].currentPath;
1583
+ const previousPath = cleanEquivalencyValueChain[i].previousPath;
1165
1584
  const schemaPathParts = this.splitPath(pathInfo.schemaPath);
1166
1585
  const isSignaturePath = schemaPathParts.findIndex((p) => p.startsWith('signature[')) > 0;
1167
1586
  if (schemaPathParts[0].startsWith('returnValue') ||
@@ -1171,6 +1590,17 @@ export class ScopeDataStructure {
1171
1590
  ) {
1172
1591
  databaseEntry.usages.push(pathInfo);
1173
1592
  }
1593
+ // Also add previousPath as a usage if it matches the criteria
1594
+ // This handles propagated sub-property equivalencies where the JSX prop path
1595
+ // is in previousPath and should be tracked as a usage
1596
+ if (previousPath) {
1597
+ const prevSchemaPathParts = this.splitPath(previousPath.schemaPath);
1598
+ const isPrevSignaturePath = prevSchemaPathParts.findIndex((p) => p.startsWith('signature[')) > 0;
1599
+ if (prevSchemaPathParts[0].startsWith('returnValue') ||
1600
+ isPrevSignaturePath) {
1601
+ databaseEntry.usages.push(previousPath);
1602
+ }
1603
+ }
1174
1604
  const pathId = this.uniqueId(pathInfo);
1175
1605
  let intermediateIndex = cleanEquivalencyValueChain.length - i - 1;
1176
1606
  const existingIntermediateIndex = databaseEntry.intermediatesOrder[pathId];
@@ -1236,6 +1666,7 @@ export class ScopeDataStructure {
1236
1666
  if (functionScope) {
1237
1667
  functionScope.functionCalls.push(externalFunctionCallInfo);
1238
1668
  this.externalFunctionCalls.splice(i, 1);
1669
+ this.invalidateExternalFunctionCallsIndex();
1239
1670
  for (const equivalentPath in externalFunctionCallInfo.equivalencies) {
1240
1671
  let localEquivalentPath = equivalentPath;
1241
1672
  if (localEquivalentPath.startsWith(externalFunctionCallInfo.callSignature)) {
@@ -1278,15 +1709,17 @@ export class ScopeDataStructure {
1278
1709
  for (const key in scopeNode.equivalencies) {
1279
1710
  const keyParts = this.splitPath(key);
1280
1711
  if (keyParts.length > 1) {
1281
- 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];
1282
1714
  if (lastPart.startsWith('signature[')) {
1283
- const functionCall = keyParts[keyParts.length - 1];
1715
+ const keyPartsWithoutLast = keyParts.slice(0, -1);
1716
+ const functionCall = keyPartsWithoutLast[keyPartsWithoutLast.length - 1];
1284
1717
  const argumentsIndex = functionCall.indexOf('(');
1285
1718
  const functionName = this.joinPathParts([
1286
- ...keyParts.slice(0, -1),
1719
+ ...keyPartsWithoutLast.slice(0, -1),
1287
1720
  functionCall.slice(0, argumentsIndex === -1 ? undefined : argumentsIndex),
1288
1721
  ]);
1289
- const callSignature = this.joinPathParts(keyParts);
1722
+ const callSignature = this.joinPathParts(keyPartsWithoutLast);
1290
1723
  const functionCallInfo = {
1291
1724
  name: functionName,
1292
1725
  callSignature,
@@ -1298,15 +1731,17 @@ export class ScopeDataStructure {
1298
1731
  for (const equivalentValues of scopeNode.equivalencies[key]) {
1299
1732
  const equivalentValueParts = this.splitPath(equivalentValues.schemaPath);
1300
1733
  if (equivalentValueParts.length > 1) {
1301
- 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];
1302
1736
  if (lastPart.startsWith('functionCallReturnValue')) {
1303
- const functionCall = equivalentValueParts[equivalentValueParts.length - 1];
1737
+ const partsWithoutLast = equivalentValueParts.slice(0, -1);
1738
+ const functionCall = partsWithoutLast[partsWithoutLast.length - 1];
1304
1739
  const argumentsIndex = functionCall.indexOf('(');
1305
1740
  const functionName = this.joinPathParts([
1306
- ...equivalentValueParts.slice(0, -1),
1741
+ ...partsWithoutLast.slice(0, -1),
1307
1742
  functionCall.slice(0, argumentsIndex === -1 ? undefined : argumentsIndex),
1308
1743
  ]);
1309
- const callSignature = this.joinPathParts(equivalentValueParts);
1744
+ const callSignature = this.joinPathParts(partsWithoutLast);
1310
1745
  const functionCallInfo = {
1311
1746
  name: functionName,
1312
1747
  callSignature,
@@ -1451,7 +1886,7 @@ export class ScopeDataStructure {
1451
1886
  return this.getExternalFunctionCallInfo(scopeName);
1452
1887
  }
1453
1888
  getScopeNode(scopeName) {
1454
- const scopeNode = this.scopeNodes[scopeName ?? this.scopeTree.name];
1889
+ const scopeNode = this.scopeNodes[scopeName ?? this.scopeTreeManager.getRootName()];
1455
1890
  if (scopeNode)
1456
1891
  return scopeNode;
1457
1892
  for (const scopeNodeName in this.scopeNodes) {
@@ -1460,20 +1895,54 @@ export class ScopeDataStructure {
1460
1895
  }
1461
1896
  }
1462
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
+ }
1463
1923
  getExternalFunctionCallInfo(functionName) {
1464
- return this.externalFunctionCalls.find((efc) => efc.name === getFunctionCallRoot(functionName) ||
1465
- 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);
1466
1933
  }
1467
1934
  getScopeAnalysis(scopeName) {
1468
- return this.scopeNodes[scopeName ?? this.scopeTree.name].analysis;
1935
+ return this.scopeNodes[scopeName ?? this.scopeTreeManager.getRootName()]
1936
+ .analysis;
1469
1937
  }
1470
1938
  getAnalysisTree() {
1471
1939
  return this.scopeTree;
1472
1940
  }
1473
1941
  getSchema({ scopeName, fillInUnknowns, }) {
1474
- const scopeNode = this.scopeNodes[scopeName ?? this.scopeTree.name];
1942
+ const scopeNode = this.scopeNodes[scopeName ?? this.scopeTreeManager.getRootName()];
1475
1943
  if (!scopeNode) {
1476
- const externalFunctionCallSchema = this.externalFunctionCalls.find((call) => call.name === getFunctionCallRoot(scopeName))?.schema;
1944
+ const searchKey = getFunctionCallRoot(scopeName);
1945
+ const externalFunctionCallSchema = this.getExternalFunctionCallsIndex().get(searchKey)?.schema;
1477
1946
  if (!externalFunctionCallSchema)
1478
1947
  return;
1479
1948
  return Object.keys(externalFunctionCallSchema).reduce((acc, key) => {
@@ -1496,7 +1965,9 @@ export class ScopeDataStructure {
1496
1965
  if (this.equivalencyDatabaseCache.has(cacheKey)) {
1497
1966
  return this.equivalencyDatabaseCache.get(cacheKey);
1498
1967
  }
1499
- 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);
1500
1971
  this.equivalencyDatabaseCache.set(cacheKey, result);
1501
1972
  return result;
1502
1973
  }
@@ -1559,12 +2030,12 @@ export class ScopeDataStructure {
1559
2030
  }
1560
2031
  }
1561
2032
  }
1562
- const tempScopeNode = this.createTempScopeNode(functionName ?? this.scopeTree.name, signatureInSchema, equivalencies);
2033
+ const tempScopeNode = this.createTempScopeNode(functionName ?? this.scopeTreeManager.getRootName(), signatureInSchema, equivalencies);
1563
2034
  this.validateSchema(tempScopeNode, true, fillInUnknowns);
1564
2035
  return tempScopeNode.schema;
1565
2036
  }
1566
2037
  getReturnValue({ functionName, fillInUnknowns, }) {
1567
- const scopeName = functionName ?? this.scopeTree.name;
2038
+ const scopeName = functionName ?? this.scopeTreeManager.getRootName();
1568
2039
  const scopeNode = this.scopeNodes[scopeName];
1569
2040
  let schema = {};
1570
2041
  if (scopeNode) {
@@ -1581,12 +2052,7 @@ export class ScopeDataStructure {
1581
2052
  for (const schemaPath in externalFunctionCall.schema) {
1582
2053
  const value1 = schema[schemaPath];
1583
2054
  const value2 = externalFunctionCall.schema[schemaPath];
1584
- let bestValue = value1 ?? value2;
1585
- if (bestValue === 'unknown' ||
1586
- (bestValue.includes('unknown') && !value2.includes('unknown'))) {
1587
- bestValue = value2;
1588
- }
1589
- schema[schemaPath] = bestValue;
2055
+ schema[schemaPath] = selectBestValue(value1, value2, value2);
1590
2056
  }
1591
2057
  }
1592
2058
  }
@@ -1683,7 +2149,7 @@ export class ScopeDataStructure {
1683
2149
  return scopeText;
1684
2150
  }
1685
2151
  getEquivalentSignatureVariables() {
1686
- const scopeNode = this.scopeNodes[this.scopeTree.name];
2152
+ const scopeNode = this.scopeNodes[this.scopeTreeManager.getRootName()];
1687
2153
  const equivalentSignatureVariables = {};
1688
2154
  for (const [path, equivalentValues] of Object.entries(scopeNode.equivalencies)) {
1689
2155
  for (const equivalentValue of equivalentValues) {
@@ -1695,7 +2161,7 @@ export class ScopeDataStructure {
1695
2161
  return equivalentSignatureVariables;
1696
2162
  }
1697
2163
  getVariableInfo(variableName, scopeName, final) {
1698
- const scopeNode = this.getScopeOrFunctionCallInfo(scopeName ?? this.scopeTree.name);
2164
+ const scopeNode = this.getScopeOrFunctionCallInfo(scopeName ?? this.scopeTreeManager.getRootName());
1699
2165
  if (!scopeNode)
1700
2166
  return;
1701
2167
  let equivalents = scopeNode.equivalencies[variableName];
@@ -1722,7 +2188,7 @@ export class ScopeDataStructure {
1722
2188
  });
1723
2189
  return { ...acc, ...filterdSchema };
1724
2190
  }, {});
1725
- const tempScopeNode = this.createTempScopeNode(scopeName ?? this.scopeTree.name, relevantSchema);
2191
+ const tempScopeNode = this.createTempScopeNode(scopeName ?? this.scopeTreeManager.getRootName(), relevantSchema);
1726
2192
  this.validateSchema(tempScopeNode, true, final);
1727
2193
  return {
1728
2194
  name: variableName,
@@ -1736,6 +2202,50 @@ export class ScopeDataStructure {
1736
2202
  getEnvironmentVariables() {
1737
2203
  return this.environmentVariables;
1738
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
+ }
1739
2249
  toSerializable() {
1740
2250
  // Helper to convert ScopeVariable to SerializableScopeVariable
1741
2251
  const toSerializableVariable = (vars) => vars.map((v) => ({
@@ -1784,13 +2294,427 @@ export class ScopeDataStructure {
1784
2294
  // Get equivalent signature variables
1785
2295
  const equivalentSignatureVariables = this.getEquivalentSignatureVariables();
1786
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;
1787
2302
  return {
1788
2303
  externalFunctionCalls,
1789
2304
  rootFunction,
1790
2305
  functionResults,
1791
2306
  equivalentSignatureVariables,
1792
2307
  environmentVariables,
2308
+ conditionalUsages,
1793
2309
  };
1794
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
+ }
1795
2719
  }
1796
2720
  //# sourceMappingURL=ScopeDataStructure.js.map