gitnexus 1.6.6-rc.31 → 1.6.6-rc.32

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 (27) hide show
  1. package/dist/cli/optional-grammars.d.ts +11 -8
  2. package/dist/cli/optional-grammars.js +12 -8
  3. package/dist/core/ingestion/parsing-processor.js +12 -6
  4. package/dist/core/ingestion/scope-extractor.js +7 -1
  5. package/dist/core/ingestion/scope-resolution/graph-bridge/edges.d.ts +21 -0
  6. package/dist/core/ingestion/scope-resolution/graph-bridge/edges.js +37 -0
  7. package/dist/core/ingestion/scope-resolution/graph-bridge/node-lookup.js +7 -1
  8. package/dist/core/ingestion/scope-resolution/passes/receiver-bound-calls.d.ts +5 -0
  9. package/dist/core/ingestion/scope-resolution/passes/receiver-bound-calls.js +50 -2
  10. package/dist/core/ingestion/scope-resolution/scope/walkers.d.ts +28 -0
  11. package/dist/core/ingestion/scope-resolution/scope/walkers.js +75 -23
  12. package/dist/core/ingestion/utils/ast-helpers.d.ts +30 -0
  13. package/dist/core/ingestion/utils/ast-helpers.js +99 -0
  14. package/dist/core/ingestion/workers/parse-worker.js +12 -6
  15. package/package.json +3 -6
  16. package/scripts/build-tree-sitter-dart.cjs +4 -0
  17. package/scripts/build-tree-sitter-proto.cjs +3 -4
  18. package/scripts/build-tree-sitter-swift.cjs +39 -0
  19. package/scripts/materialize-vendor-grammars.cjs +72 -0
  20. package/vendor/tree-sitter-dart/package.json +1 -1
  21. package/vendor/tree-sitter-proto/package.json +1 -1
  22. package/vendor/tree-sitter-swift/package.json +1 -8
  23. package/vendor/node_modules/node-addon-api/node_addon_api.Makefile +0 -6
  24. package/vendor/node_modules/node-addon-api/node_addon_api.target.mk +0 -106
  25. package/vendor/node_modules/node-addon-api/node_addon_api_except.target.mk +0 -110
  26. package/vendor/node_modules/node-addon-api/node_addon_api_except_all.target.mk +0 -106
  27. package/vendor/node_modules/node-addon-api/node_addon_api_maybe.target.mk +0 -106
@@ -1,15 +1,18 @@
1
1
  /**
2
2
  * Optional grammar availability check.
3
3
  *
4
- * tree-sitter-dart and tree-sitter-proto are optionalDependencies that
5
- * require a `node-gyp rebuild` at install time. The build can be skipped
6
- * via GITNEXUS_SKIP_OPTIONAL_GRAMMARS=1 (postinstall scripts), or it can
7
- * silently soft-fail when the C++ toolchain is missing.
4
+ * tree-sitter-dart, tree-sitter-proto, and tree-sitter-swift are vendored
5
+ * under vendor/ and materialized into node_modules/ at postinstall. Dart
6
+ * and Proto are built from source with node-gyp; Swift ships platform
7
+ * prebuilds activated via node-gyp-build. All three can be skipped via
8
+ * GITNEXUS_SKIP_OPTIONAL_GRAMMARS=1 (postinstall scripts), or can silently
9
+ * soft-fail when the toolchain is missing (Dart/Proto) or no prebuild
10
+ * matches the host platform (Swift).
8
11
  *
9
12
  * Either path produces the same observable: the .node binding is absent
10
13
  * at runtime. This helper detects that condition and surfaces a single
11
- * stderr line per missing grammar so users learn why .dart/.proto support
12
- * is unavailable instead of silently getting a degraded index.
14
+ * stderr line per missing grammar so users learn why .dart/.proto/.swift
15
+ * support is unavailable instead of silently getting a degraded index.
13
16
  */
14
17
  export interface MissingGrammar {
15
18
  name: string;
@@ -19,8 +22,8 @@ export interface MissingGrammar {
19
22
  * Returns the list of optional grammars whose native binding cannot be
20
23
  * loaded. Actually `require()`s the package — `require.resolve` would
21
24
  * locate the entry path even when the `.node` binding is absent (the
22
- * `file:` package directory is installed regardless of postinstall
23
- * outcome), giving false negatives for the exact users we want to warn:
25
+ * package directory exists without a working `.node` binding), giving false
26
+ * negatives for the exact users we want to warn:
24
27
  * those who installed with `GITNEXUS_SKIP_OPTIONAL_GRAMMARS=1` or whose
25
28
  * native rebuild soft-failed for missing toolchain.
26
29
  *
@@ -1,15 +1,18 @@
1
1
  /**
2
2
  * Optional grammar availability check.
3
3
  *
4
- * tree-sitter-dart and tree-sitter-proto are optionalDependencies that
5
- * require a `node-gyp rebuild` at install time. The build can be skipped
6
- * via GITNEXUS_SKIP_OPTIONAL_GRAMMARS=1 (postinstall scripts), or it can
7
- * silently soft-fail when the C++ toolchain is missing.
4
+ * tree-sitter-dart, tree-sitter-proto, and tree-sitter-swift are vendored
5
+ * under vendor/ and materialized into node_modules/ at postinstall. Dart
6
+ * and Proto are built from source with node-gyp; Swift ships platform
7
+ * prebuilds activated via node-gyp-build. All three can be skipped via
8
+ * GITNEXUS_SKIP_OPTIONAL_GRAMMARS=1 (postinstall scripts), or can silently
9
+ * soft-fail when the toolchain is missing (Dart/Proto) or no prebuild
10
+ * matches the host platform (Swift).
8
11
  *
9
12
  * Either path produces the same observable: the .node binding is absent
10
13
  * at runtime. This helper detects that condition and surfaces a single
11
- * stderr line per missing grammar so users learn why .dart/.proto support
12
- * is unavailable instead of silently getting a degraded index.
14
+ * stderr line per missing grammar so users learn why .dart/.proto/.swift
15
+ * support is unavailable instead of silently getting a degraded index.
13
16
  */
14
17
  import { createRequire } from 'module';
15
18
  import { cliWarn } from './cli-message.js';
@@ -17,13 +20,14 @@ const _require = createRequire(import.meta.url);
17
20
  const OPTIONAL_GRAMMARS = [
18
21
  { name: 'tree-sitter-dart', pkg: 'tree-sitter-dart', extensions: ['.dart'] },
19
22
  { name: 'tree-sitter-proto', pkg: 'tree-sitter-proto', extensions: ['.proto'] },
23
+ { name: 'tree-sitter-swift', pkg: 'tree-sitter-swift', extensions: ['.swift'] },
20
24
  ];
21
25
  /**
22
26
  * Returns the list of optional grammars whose native binding cannot be
23
27
  * loaded. Actually `require()`s the package — `require.resolve` would
24
28
  * locate the entry path even when the `.node` binding is absent (the
25
- * `file:` package directory is installed regardless of postinstall
26
- * outcome), giving false negatives for the exact users we want to warn:
29
+ * package directory exists without a working `.node` binding), giving false
30
+ * negatives for the exact users we want to warn:
27
31
  * those who installed with `GITNEXUS_SKIP_OPTIONAL_GRAMMARS=1` or whose
28
32
  * native rebuild soft-failed for missing toolchain.
29
33
  *
@@ -7,7 +7,7 @@ import { extractVueScript, isVueSetupTopLevel } from './vue-sfc-extractor.js';
7
7
  import { yieldToEventLoop } from './utils/event-loop.js';
8
8
  import { parseSourceSafe } from '../tree-sitter/safe-parse.js';
9
9
  import { isVerboseIngestionEnabled } from './utils/verbose.js';
10
- import { getDefinitionNodeFromCaptures, findEnclosingClassInfo, getLabelFromCaptures, CLASS_CONTAINER_TYPES, } from './utils/ast-helpers.js';
10
+ import { getDefinitionNodeFromCaptures, findEnclosingClassInfo, findObjectLiteralBindingInfo, getLabelFromCaptures, CLASS_CONTAINER_TYPES, } from './utils/ast-helpers.js';
11
11
  import { detectFrameworkFromAST } from './framework-detection.js';
12
12
  import { buildTypeEnv } from './type-env.js';
13
13
  import { buildMethodProps, arityForIdFromInfo, typeTagForId, constTagForId, buildCollisionGroups, } from './utils/method-props.js';
@@ -400,6 +400,9 @@ const processParsingSequential = async (graph, files, symbolTable, astCache, sco
400
400
  ? cachedFindEnclosingClassInfo(nameNode || definitionNodeForRange, file.path, provider.resolveEnclosingOwner)
401
401
  : null;
402
402
  const enclosingClassId = enclosingClassInfo?.classId ?? null;
403
+ const objectLiteralOwnerInfo = !enclosingClassId && nodeLabel === 'Method' && definitionNode
404
+ ? findObjectLiteralBindingInfo(definitionNode, file.path)
405
+ : null;
403
406
  // Qualify method/property IDs with enclosing class name to avoid collisions
404
407
  // e.g. "Method:animal.dart:Animal.speak" vs "Method:animal.dart:Dog.speak"
405
408
  const qualifiedName = enclosingClassInfo
@@ -615,7 +618,7 @@ const processParsingSequential = async (graph, files, symbolTable, astCache, sco
615
618
  returnType: methodProps.returnType,
616
619
  declaredType,
617
620
  templateArguments: classTemplateArguments,
618
- ownerId: enclosingClassId ?? undefined,
621
+ ownerId: enclosingClassId ?? objectLiteralOwnerInfo?.ownerId ?? undefined,
619
622
  qualifiedName: qualifiedTypeName,
620
623
  });
621
624
  const fileId = generateId('File', file.path);
@@ -630,15 +633,18 @@ const processParsingSequential = async (graph, files, symbolTable, astCache, sco
630
633
  };
631
634
  graph.addRelationship(relationship);
632
635
  // ── HAS_METHOD / HAS_PROPERTY: link member to enclosing class ──
633
- if (enclosingClassId) {
636
+ const ownerIdForMemberEdge = enclosingClassId ?? objectLiteralOwnerInfo?.ownerId ?? null;
637
+ if (ownerIdForMemberEdge) {
634
638
  const memberEdgeType = nodeLabel === 'Property' ? 'HAS_PROPERTY' : 'HAS_METHOD';
635
639
  graph.addRelationship({
636
- id: generateId(memberEdgeType, `${enclosingClassId}->${nodeId}`),
637
- sourceId: enclosingClassId,
640
+ id: generateId(memberEdgeType, `${ownerIdForMemberEdge}->${nodeId}`),
641
+ sourceId: ownerIdForMemberEdge,
638
642
  targetId: nodeId,
639
643
  type: memberEdgeType,
640
644
  confidence: 1.0,
641
- reason: '',
645
+ reason: objectLiteralOwnerInfo
646
+ ? 'object literal method belongs to exported object binding'
647
+ : '',
642
648
  });
643
649
  }
644
650
  });
@@ -511,8 +511,14 @@ function normalizeNodeLabel(kindStr) {
511
511
  case 'property':
512
512
  return 'Property';
513
513
  case 'variable':
514
- case 'const':
515
514
  return 'Variable';
515
+ // `const` / `let` declarations align with the legacy DAG parse phase,
516
+ // which emits `Const` graph nodes via `@definition.const` capture for
517
+ // `lexical_declaration`. Returning `'Const'` here lets resolveDefGraphId's
518
+ // qualified-key path succeed for value receivers without relying on the
519
+ // simple-key fallback (PR #1718 review Finding 1 / 2026-05-21-002 U4).
520
+ case 'const':
521
+ return 'Const';
516
522
  case 'typealias':
517
523
  case 'type_alias':
518
524
  return 'TypeAlias';
@@ -41,3 +41,24 @@ export declare function tryEmitEdge(graph: KnowledgeGraph, scopes: ScopeResoluti
41
41
  };
42
42
  readonly kind: string;
43
43
  }, targetDef: SymbolDefinition, reason: string, seen: Set<string>, confidence?: number, collapseByCallerTarget?: boolean): boolean;
44
+ /**
45
+ * Variant of `tryEmitEdge` that takes a pre-resolved target graph id
46
+ * instead of resolving it from a `SymbolDefinition`. Used by the
47
+ * value-receiver-owner bridge (`receiver-bound-calls.ts` Case 5) where
48
+ * the picked owner-indexed method def carries no `qualifiedName` (object
49
+ * literals have no class owner to seed it) and therefore cannot
50
+ * round-trip through `resolveDefGraphId`. The def's `nodeId` IS the
51
+ * canonical graph node id (written by the parse phase), so the caller
52
+ * passes it directly.
53
+ *
54
+ * All other invariants of `tryEmitEdge` apply: dedup key shape, collapse
55
+ * flag honoring, edge-type mapping, caller-id resolution.
56
+ */
57
+ export declare function tryEmitEdgeWithExplicitTargetId(graph: KnowledgeGraph, scopes: ScopeResolutionIndexes, nodeLookup: GraphNodeLookup, site: {
58
+ readonly inScope: ScopeId;
59
+ readonly atRange: {
60
+ startLine: number;
61
+ startCol: number;
62
+ };
63
+ readonly kind: string;
64
+ }, targetGraphId: string, reason: string, seen: Set<string>, confidence?: number, collapseByCallerTarget?: boolean): boolean;
@@ -77,3 +77,40 @@ export function tryEmitEdge(graph, scopes, nodeLookup, site, targetDef, reason,
77
77
  });
78
78
  return true;
79
79
  }
80
+ /**
81
+ * Variant of `tryEmitEdge` that takes a pre-resolved target graph id
82
+ * instead of resolving it from a `SymbolDefinition`. Used by the
83
+ * value-receiver-owner bridge (`receiver-bound-calls.ts` Case 5) where
84
+ * the picked owner-indexed method def carries no `qualifiedName` (object
85
+ * literals have no class owner to seed it) and therefore cannot
86
+ * round-trip through `resolveDefGraphId`. The def's `nodeId` IS the
87
+ * canonical graph node id (written by the parse phase), so the caller
88
+ * passes it directly.
89
+ *
90
+ * All other invariants of `tryEmitEdge` apply: dedup key shape, collapse
91
+ * flag honoring, edge-type mapping, caller-id resolution.
92
+ */
93
+ export function tryEmitEdgeWithExplicitTargetId(graph, scopes, nodeLookup, site, targetGraphId, reason, seen, confidence = 0.85, collapseByCallerTarget = false) {
94
+ const callerGraphId = resolveCallerGraphId(site.inScope, scopes, nodeLookup);
95
+ const edgeType = mapReferenceKindToEdgeType(site.kind);
96
+ if (callerGraphId === undefined)
97
+ return false;
98
+ if (edgeType === undefined)
99
+ return false;
100
+ const useCollapsed = collapseByCallerTarget && edgeType === 'CALLS';
101
+ const dedupKey = useCollapsed
102
+ ? `${edgeType}:${callerGraphId}->${targetGraphId}`
103
+ : `${edgeType}:${callerGraphId}->${targetGraphId}:${site.atRange.startLine}:${site.atRange.startCol}`;
104
+ if (seen.has(dedupKey))
105
+ return false;
106
+ seen.add(dedupKey);
107
+ graph.addRelationship({
108
+ id: `rel:${dedupKey}`,
109
+ sourceId: callerGraphId,
110
+ targetId: targetGraphId,
111
+ type: edgeType,
112
+ confidence,
113
+ reason,
114
+ });
115
+ return true;
116
+ }
@@ -137,5 +137,11 @@ export function isLinkableLabel(label) {
137
137
  // ACCESSES edges target field nodes (e.g. `user.name = "x"` →
138
138
  // ACCESSES edge to User's `name` Variable/Property node).
139
139
  label === 'Variable' ||
140
- label === 'Property');
140
+ label === 'Property' ||
141
+ // Const is linkable so the value-receiver-owner bridge in
142
+ // `receiver-bound-calls.ts` Case 5 can translate the scope-resolution
143
+ // `Variable` def for `export const fooService = {...}` to the canonical
144
+ // `Const:filePath:name` graph node id, against which object-literal
145
+ // method symbols register their `ownerId` (PR #1718 / issue #1358).
146
+ label === 'Const');
141
147
  }
@@ -21,6 +21,11 @@
21
21
  * but not a namespace prefix → compound resolver
22
22
  * 7. **Case 4 (simple typeBinding)** — `typeRef.rawName` has no dot →
23
23
  * MRO walk + `findOwnedMember`
24
+ * 8. **Case 5 (value-receiver bridge)** — receiver is a `Const`/`Variable`
25
+ * whose `nodeId` is referenced as an `ownerId` in `model.methods`
26
+ * (object-literal services). Last-resort fallback for lowercase
27
+ * receivers with no class-like or type-binding match. Mirrors
28
+ * the legacy DAG bridge in `call-processor.ts`.
24
29
  *
25
30
  * Reordering or merging cases changes resolution semantics.
26
31
  *
@@ -21,6 +21,11 @@
21
21
  * but not a namespace prefix → compound resolver
22
22
  * 7. **Case 4 (simple typeBinding)** — `typeRef.rawName` has no dot →
23
23
  * MRO walk + `findOwnedMember`
24
+ * 8. **Case 5 (value-receiver bridge)** — receiver is a `Const`/`Variable`
25
+ * whose `nodeId` is referenced as an `ownerId` in `model.methods`
26
+ * (object-literal services). Last-resort fallback for lowercase
27
+ * receivers with no class-like or type-binding match. Mirrors
28
+ * the legacy DAG bridge in `call-processor.ts`.
24
29
  *
25
30
  * Reordering or merging cases changes resolution semantics.
26
31
  *
@@ -32,8 +37,8 @@
32
37
  * resolved to a wrong target.
33
38
  */
34
39
  import { collectNamespaceTargets } from '../scope/namespace-targets.js';
35
- import { findClassBindingInScope, findEnclosingClassDef, findExportedDef, findOwnedMember, findReceiverTypeBinding, isClassLike, } from '../scope/walkers.js';
36
- import { tryEmitEdge } from '../graph-bridge/edges.js';
40
+ import { findClassBindingInScope, findEnclosingClassDef, findExportedDef, findOwnedMember, findReceiverTypeBinding, findValueBindingInScope, isClassLike, } from '../scope/walkers.js';
41
+ import { tryEmitEdge, tryEmitEdgeWithExplicitTargetId } from '../graph-bridge/edges.js';
37
42
  import { resolveCompoundReceiverClass } from '../passes/compound-receiver.js';
38
43
  import { resolveDefGraphId } from '../graph-bridge/ids.js';
39
44
  import { narrowOverloadCandidates, isOverloadAmbiguousAfterNormalization, } from './overload-narrowing.js';
@@ -514,6 +519,49 @@ export function emitReceiverBoundCalls(graph, scopes, parsedFiles, nodeLookup, h
514
519
  }
515
520
  }
516
521
  }
522
+ // ── Case 5: value-receiver bridge (object-literal services) ──
523
+ // When prior cases couldn't resolve the receiver as a class or
524
+ // type binding, fall back to value-binding resolution. Covers:
525
+ //
526
+ // export const fooService = { getUser(id) {...} };
527
+ // import { fooService } from './service';
528
+ // fooService.getUser(id); // ← resolve here
529
+ //
530
+ // `fooService` is a `Const`/`Variable` (not class-like, no typeBinding
531
+ // for unannotated literals), so Cases 2-4 skip it. Scope-resolution
532
+ // defs for non-class values carry a synthetic id, so we translate to
533
+ // the canonical graph node ID via `resolveDefGraphId` before owner-
534
+ // indexed lookup — the parser writes the graph node ID as `ownerId`
535
+ // on the method symbol-table entry to match.
536
+ //
537
+ // Object-literal methods do not carry a `qualifiedName` (no class
538
+ // owner to seed it), so the picked def cannot round-trip through
539
+ // `tryEmitEdge` → `resolveDefGraphId`. We use
540
+ // `tryEmitEdgeWithExplicitTargetId` instead, passing `picked.nodeId`
541
+ // directly — same dedup-key shape, collapse-flag honoring, and
542
+ // caller resolution as `tryEmitEdge`.
543
+ const valueDef = findValueBindingInScope(site.inScope, receiverName, scopes);
544
+ if (valueDef !== undefined) {
545
+ const ownerGraphId = resolveDefGraphId(valueDef.filePath, valueDef, nodeLookup) ?? valueDef.nodeId;
546
+ const picked = pickOverload(ownerGraphId, memberName, site, model, provider);
547
+ if (picked === OVERLOAD_AMBIGUOUS) {
548
+ handledSites.add(siteKey);
549
+ continue;
550
+ }
551
+ if (picked !== undefined) {
552
+ const reason = site.kind === 'write' || site.kind === 'read'
553
+ ? site.kind
554
+ : picked.filePath !== parsed.filePath
555
+ ? 'import-resolved'
556
+ : 'global';
557
+ const confidence = site.kind === 'write' || site.kind === 'read' ? 1.0 : 0.85;
558
+ const ok = tryEmitEdgeWithExplicitTargetId(graph, scopes, nodeLookup, site, picked.nodeId, reason, seen, confidence, collapse);
559
+ if (ok)
560
+ emitted++;
561
+ handledSites.add(siteKey);
562
+ continue;
563
+ }
564
+ }
517
565
  }
518
566
  }
519
567
  return emitted;
@@ -91,6 +91,34 @@ export declare function findReceiverTypeBinding(startScope: ScopeId, receiverNam
91
91
  * Without (2) we'd miss every cross-file class-receiver call.
92
92
  */
93
93
  export declare function findClassBindingInScope(startScope: ScopeId, receiverName: string, scopes: ScopeResolutionIndexes): SymbolDefinition | undefined;
94
+ /**
95
+ * Predicate for value-receiver bridge: the labels for which
96
+ * `reconcileOwnership` registers methods/fields under the def's
97
+ * `nodeId` as the `ownerId`. Explicit allowlist so future NodeLabel
98
+ * additions (Module, Namespace, TypeAlias, EnumMember, etc.) do NOT
99
+ * silently widen the bridge — adding a new ownerable label requires
100
+ * touching both this predicate and `reconcileOwnership`.
101
+ *
102
+ * See: `scope-resolution/pipeline/reconcile-ownership.ts` Property /
103
+ * Variable / Const / Static registration block.
104
+ */
105
+ export declare function isOwnableValueLabel(t: string): boolean;
106
+ /**
107
+ * Look up a value-binding (Const/Variable/Property/Static) by name in
108
+ * the given scope's chain. Used by the value-receiver-owner bridge
109
+ * for object-literal services such as:
110
+ *
111
+ * export const fooService = { getUser(id) {...} };
112
+ *
113
+ * where `fooService` is a `Const`/`Variable` whose `nodeId` is the
114
+ * `ownerId` of the member method. Neither `findClassBindingInScope`
115
+ * (rejects non-class-like) nor `findReceiverTypeBinding` (no typeBinding
116
+ * for an unannotated literal) finds it.
117
+ *
118
+ * Mirrors `findClassBindingInScope` exactly; only the accepted def-type
119
+ * predicate differs.
120
+ */
121
+ export declare function findValueBindingInScope(startScope: ScopeId, receiverName: string, scopes: ScopeResolutionIndexes): SymbolDefinition | undefined;
94
122
  /**
95
123
  * Look up a callable (Function/Method/Constructor) by name in the
96
124
  * given scope's chain. Uses the dual-source pattern (scope.bindings +
@@ -150,29 +150,9 @@ export function findReceiverTypeBinding(startScope, receiverName, scopes) {
150
150
  * Without (2) we'd miss every cross-file class-receiver call.
151
151
  */
152
152
  export function findClassBindingInScope(startScope, receiverName, scopes) {
153
- let currentId = startScope;
154
- const visited = new Set();
155
- while (currentId !== null) {
156
- if (visited.has(currentId))
157
- return undefined;
158
- visited.add(currentId);
159
- const scope = scopes.scopeTree.getScope(currentId);
160
- if (scope === undefined)
161
- return undefined;
162
- const localBindings = scope.bindings.get(receiverName);
163
- if (localBindings !== undefined) {
164
- for (const b of localBindings) {
165
- if (isClassLike(b.def.type))
166
- return b.def;
167
- }
168
- }
169
- const importedBindings = lookupBindingsAt(currentId, receiverName, scopes);
170
- for (const b of importedBindings) {
171
- if (isClassLike(b.def.type))
172
- return b.def;
173
- }
174
- currentId = scope.parent;
175
- }
153
+ const local = walkScopeChain(startScope, receiverName, scopes, (def) => isClassLike(def.type));
154
+ if (local !== undefined)
155
+ return local;
176
156
  // Fallback for languages (Go) where namespace-style imports don't
177
157
  // create scope bindings: resolve via QualifiedNameIndex. Only fires
178
158
  // when the scope-chain walk found nothing; single-match wins.
@@ -198,6 +178,78 @@ export function findClassBindingInScope(startScope, receiverName, scopes) {
198
178
  }
199
179
  return undefined;
200
180
  }
181
+ /**
182
+ * Predicate for value-receiver bridge: the labels for which
183
+ * `reconcileOwnership` registers methods/fields under the def's
184
+ * `nodeId` as the `ownerId`. Explicit allowlist so future NodeLabel
185
+ * additions (Module, Namespace, TypeAlias, EnumMember, etc.) do NOT
186
+ * silently widen the bridge — adding a new ownerable label requires
187
+ * touching both this predicate and `reconcileOwnership`.
188
+ *
189
+ * See: `scope-resolution/pipeline/reconcile-ownership.ts` Property /
190
+ * Variable / Const / Static registration block.
191
+ */
192
+ export function isOwnableValueLabel(t) {
193
+ return t === 'Const' || t === 'Variable' || t === 'Property' || t === 'Static';
194
+ }
195
+ /**
196
+ * Look up a value-binding (Const/Variable/Property/Static) by name in
197
+ * the given scope's chain. Used by the value-receiver-owner bridge
198
+ * for object-literal services such as:
199
+ *
200
+ * export const fooService = { getUser(id) {...} };
201
+ *
202
+ * where `fooService` is a `Const`/`Variable` whose `nodeId` is the
203
+ * `ownerId` of the member method. Neither `findClassBindingInScope`
204
+ * (rejects non-class-like) nor `findReceiverTypeBinding` (no typeBinding
205
+ * for an unannotated literal) finds it.
206
+ *
207
+ * Mirrors `findClassBindingInScope` exactly; only the accepted def-type
208
+ * predicate differs.
209
+ */
210
+ export function findValueBindingInScope(startScope, receiverName, scopes) {
211
+ return walkScopeChain(startScope, receiverName, scopes, (def) => isOwnableValueLabel(def.type));
212
+ }
213
+ /**
214
+ * Generic scope-chain walker. Walks from `startScope` toward the root,
215
+ * consulting both the local `scope.bindings` channel and the dual-source
216
+ * `lookupBindingsAt` view (finalized + augmented). At each scope, local
217
+ * bindings are exhausted BEFORE imported/augmented bindings — preserves
218
+ * JavaScript-style lexical scoping where a local `const x` shadows an
219
+ * imported `x` of the same name.
220
+ *
221
+ * Returns the first binding `def` matching `predicate`. Cycles in the
222
+ * scope graph terminate the walk (defensive — should not occur in
223
+ * well-formed inputs).
224
+ */
225
+ function walkScopeChain(startScope, name, scopes, predicate) {
226
+ let currentId = startScope;
227
+ const visited = new Set();
228
+ while (currentId !== null) {
229
+ if (visited.has(currentId))
230
+ return undefined;
231
+ visited.add(currentId);
232
+ const scope = scopes.scopeTree.getScope(currentId);
233
+ if (scope === undefined)
234
+ return undefined;
235
+ // Local first: a `const x` in this scope shadows any imported `x`.
236
+ const localBindings = scope.bindings.get(name);
237
+ if (localBindings !== undefined) {
238
+ for (const b of localBindings) {
239
+ if (predicate(b.def))
240
+ return b.def;
241
+ }
242
+ }
243
+ // Then imported/augmented bindings — only consulted when no local match.
244
+ const importedBindings = lookupBindingsAt(currentId, name, scopes);
245
+ for (const b of importedBindings) {
246
+ if (predicate(b.def))
247
+ return b.def;
248
+ }
249
+ currentId = scope.parent;
250
+ }
251
+ return undefined;
252
+ }
201
253
  /**
202
254
  * Look up a callable (Function/Method/Constructor) by name in the
203
255
  * given scope's chain. Uses the dual-source pattern (scope.bindings +
@@ -46,6 +46,36 @@ export interface EnclosingClassInfo {
46
46
  className: string;
47
47
  }
48
48
  export declare const findEnclosingClassInfo: (node: SyntaxNode, filePath: string, resolveEnclosingOwner?: (node: SyntaxNode) => SyntaxNode | null) => EnclosingClassInfo | null;
49
+ /** Object literal binding info for TS/JS shorthand methods. */
50
+ export interface ObjectLiteralBindingInfo {
51
+ ownerId: string;
52
+ }
53
+ /**
54
+ * Find the file-scope variable that owns an object literal method definition.
55
+ *
56
+ * Covers TypeScript/JavaScript shorthand object methods such as:
57
+ *
58
+ * export const service = { async load() {} };
59
+ *
60
+ * tree-sitter represents `load` as a `method_definition` inside an `object`,
61
+ * not inside a class container. Without this fallback, ingestion emits a
62
+ * top-level `Method` node but no edge from the exported `service` value to
63
+ * that method, so impact queries cannot discover `service.load`.
64
+ *
65
+ * Two-phase walk:
66
+ * Phase A walks up from `node` tracking how many `object` ancestors we
67
+ * cross. The first `variable_declarator` reached with `objectDepth >= 1`
68
+ * is the candidate owner — unless `objectDepth > 1` (the method belongs
69
+ * to a nested object literal; we return null rather than misattribute
70
+ * to the outer binding). Hitting a function/class container before the
71
+ * declarator returns null (catches IIFE-wrapped literals).
72
+ * Phase B walks the declarator's own ancestors. Any function or class
73
+ * ancestor before reaching `program`/`export_statement` returns null
74
+ * (catches `const` declared inside a function body). Any block-statement
75
+ * ancestor also returns null (catches block-scoped declarations inside
76
+ * top-level `if`/`for`/`try`/etc., which cannot be imported).
77
+ */
78
+ export declare const findObjectLiteralBindingInfo: (node: SyntaxNode, filePath: string) => ObjectLiteralBindingInfo | null;
49
79
  /** Convenience wrapper: returns just the class ID string (backward compat). */
50
80
  export declare const findEnclosingClassId: (node: SyntaxNode, filePath: string) => string | null;
51
81
  /**
@@ -385,6 +385,105 @@ export const findEnclosingClassInfo = (node, filePath, resolveEnclosingOwner) =>
385
385
  }
386
386
  return null;
387
387
  };
388
+ /**
389
+ * Block-statement AST types that disqualify an object-literal binding from
390
+ * carrying a HAS_METHOD edge. A `const` declared inside one of these is block-
391
+ * scoped and cannot be imported, so attributing methods to it would create
392
+ * false-positive cross-file edges.
393
+ */
394
+ const BLOCK_SCOPE_BOUNDARY_TYPES = new Set([
395
+ 'statement_block',
396
+ 'if_statement',
397
+ 'else_clause',
398
+ 'for_statement',
399
+ 'for_in_statement',
400
+ 'for_of_statement',
401
+ 'while_statement',
402
+ 'do_statement',
403
+ 'try_statement',
404
+ 'catch_clause',
405
+ 'finally_clause',
406
+ 'switch_statement',
407
+ 'switch_case',
408
+ 'switch_default',
409
+ 'with_statement',
410
+ ]);
411
+ /**
412
+ * Find the file-scope variable that owns an object literal method definition.
413
+ *
414
+ * Covers TypeScript/JavaScript shorthand object methods such as:
415
+ *
416
+ * export const service = { async load() {} };
417
+ *
418
+ * tree-sitter represents `load` as a `method_definition` inside an `object`,
419
+ * not inside a class container. Without this fallback, ingestion emits a
420
+ * top-level `Method` node but no edge from the exported `service` value to
421
+ * that method, so impact queries cannot discover `service.load`.
422
+ *
423
+ * Two-phase walk:
424
+ * Phase A walks up from `node` tracking how many `object` ancestors we
425
+ * cross. The first `variable_declarator` reached with `objectDepth >= 1`
426
+ * is the candidate owner — unless `objectDepth > 1` (the method belongs
427
+ * to a nested object literal; we return null rather than misattribute
428
+ * to the outer binding). Hitting a function/class container before the
429
+ * declarator returns null (catches IIFE-wrapped literals).
430
+ * Phase B walks the declarator's own ancestors. Any function or class
431
+ * ancestor before reaching `program`/`export_statement` returns null
432
+ * (catches `const` declared inside a function body). Any block-statement
433
+ * ancestor also returns null (catches block-scoped declarations inside
434
+ * top-level `if`/`for`/`try`/etc., which cannot be imported).
435
+ */
436
+ export const findObjectLiteralBindingInfo = (node, filePath) => {
437
+ // ── Phase A: walk up from node, count `object` ancestors, find declarator
438
+ let current = node;
439
+ let objectDepth = 0;
440
+ let declarator = null;
441
+ while (current) {
442
+ if (current.type === 'object') {
443
+ objectDepth += 1;
444
+ }
445
+ if (current.type === 'variable_declarator' && objectDepth >= 1) {
446
+ if (objectDepth > 1) {
447
+ // Method belongs to a nested object literal; safe under-approximation.
448
+ return null;
449
+ }
450
+ declarator = current;
451
+ break;
452
+ }
453
+ if (current !== node &&
454
+ (FUNCTION_NODE_TYPES.has(current.type) || CLASS_CONTAINER_TYPES.has(current.type))) {
455
+ // Function/class container encountered before owning declarator
456
+ // (e.g. IIFE-wrapped object literal). Bail out.
457
+ return null;
458
+ }
459
+ current = current.parent;
460
+ }
461
+ if (!declarator)
462
+ return null;
463
+ // ── Phase B: declarator must live at file scope (program / export_statement)
464
+ // with no function, class, or block-statement ancestor in between.
465
+ let anc = declarator.parent;
466
+ while (anc) {
467
+ if (anc.type === 'program' || anc.type === 'export_statement') {
468
+ break;
469
+ }
470
+ if (FUNCTION_NODE_TYPES.has(anc.type) || CLASS_CONTAINER_TYPES.has(anc.type)) {
471
+ return null;
472
+ }
473
+ if (BLOCK_SCOPE_BOUNDARY_TYPES.has(anc.type)) {
474
+ return null;
475
+ }
476
+ anc = anc.parent;
477
+ }
478
+ const nameNode = declarator.childForFieldName?.('name');
479
+ if (!nameNode || nameNode.type !== 'identifier')
480
+ return null;
481
+ const declaration = declarator.parent;
482
+ const ownerLabel = declaration?.type === 'variable_declaration' ? 'Variable' : 'Const';
483
+ return {
484
+ ownerId: generateId(ownerLabel, `${filePath}:${nameNode.text}`),
485
+ };
486
+ };
388
487
  /** Convenience wrapper: returns just the class ID string (backward compat). */
389
488
  export const findEnclosingClassId = (node, filePath) => {
390
489
  return findEnclosingClassInfo(node, filePath)?.classId ?? null;