@codeyam/codeyam-cli 0.1.21 → 0.1.23

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