Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(ingestion): resolve unique ambient TypeScript types (#2999)
Just One More Nighta9222702bb9c
diff --git a/packages/core/src/repowise/core/ingestion/queries/typescript.scm b/packages/core/src/repowise/core/ingestion/queries/typescript.scmindex bb305be00..0066f556f 100644--- a/packages/core/src/repowise/core/ingestion/queries/typescript.scm+++ b/packages/core/src/repowise/core/ingestion/queries/typescript.scm@@ -390,3 +390,7 @@(union_type (_) @param.type)(intersection_type (_) @param.type)(conditional_type (_) @param.type)++; Generic type arguments can be the only mention of an ambient type:+; ``Partial<AmbientSettings>`` or ``decodeConfig<AmbientSettings>()``.+(type_arguments (type_identifier) @param.type)diff --git a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py b/packages/core/src/repowise/core/ingestion/type_ref_resolution.pyindex 241618aa1..8a5a5d02b 100644--- a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py+++ b/packages/core/src/repowise/core/ingestion/type_ref_resolution.py@@ -42,6 +42,7 @@ language tag.from __future__ import annotations+import refrom collections.abc import Callablefrom pathlib import Pathfrom typing import TYPE_CHECKING, Any@@ -673,6 +674,10 @@ def _resolve_ts_type_refs(same_file_refs.add(name)continuetarget = name_to_source.get(name) or namespace_to_source.get(name)+ if target is None:+ target = _find_unique_ambient_declaration(+ name, from_path, graph, defined_names, ctx+ )if target is None:target = _find_ts_type_in_stem_map(name, from_path, ctx, graph, defined_names@@ -694,6 +699,75 @@ def _resolve_ts_type_refs(return emitted+def _find_unique_ambient_declaration(+ type_name: str,+ from_path: str,+ graph: nx.DiGraph,+ defined_names: dict[str, set[str]],+ ctx: ResolverContext,+) -> str | None:+ """Resolve an unimported type from one ambient ``.d.ts`` owner."""+ owners_by_name = getattr(ctx, "_ts_ambient_type_owners", None)+ if owners_by_name is None:+ owners_by_name: dict[str, list[str]] = {}+ for path, names in defined_names.items():+ if not path.endswith(".d.ts") or not graph.has_node(path):+ continue+ ambient_names = _ambient_declaration_names(path, names, ctx)+ for name in ambient_names:+ owners_by_name.setdefault(name, []).append(path)+ ctx.__dict__["_ts_ambient_type_owners"] = owners_by_name+ owners = [path for path in owners_by_name.get(type_name, ()) if path != from_path]+ return owners[0] if len(owners) == 1 else None+++def _ambient_declaration_names(+ path: str, defined_names: set[str], ctx: ResolverContext+) -> set[str]:+ """Names declared globally in a script or a module's ``declare global``."""+ parsed = (ctx.parsed_files or {}).get(path)+ if parsed is None:+ return set()+ has_module_syntax = bool(parsed.imports or parsed.exports)+ if not has_module_syntax:+ return set(defined_names)+ raw = (ctx.source_map or {}).get(path)+ if raw is None:+ try:+ raw = Path(parsed.file_info.abs_path).read_bytes()+ except OSError:+ return set()+ try:+ import tree_sitter_typescript as ts+ from tree_sitter import Language, Parser++ source = raw.decode("utf-8", errors="replace")+ root = Parser(Language(ts.language_typescript())).parse(raw).root_node+ encoded = source.encode("utf-8")+ except Exception:+ return set()+ global_names: set[str] = set()+ stack = [root]+ while stack:+ node = stack.pop()+ if node.type == "ambient_declaration":+ prefix = encoded[node.start_byte : min(node.end_byte, node.start_byte + 40)]+ if re.match(rb"declare\s+global\b", prefix):+ nested = [node]+ while nested:+ declaration = nested.pop()+ name = declaration.child_by_field_name("name")+ if name is not None:+ type_name = encoded[name.start_byte : name.end_byte].decode(+ "utf-8", errors="replace"+ )+ if type_name in defined_names:+ global_names.add(type_name)+ nested.extend(declaration.children)+ stack.extend(node.children)+ return global_names++def _find_ts_type_in_stem_map(type_name: str,from_path: str,diff --git a/tests/unit/ingestion/test_ts_type_use.py b/tests/unit/ingestion/test_ts_type_use.pyindex f58ef07e2..52bcd509a 100644--- a/tests/unit/ingestion/test_ts_type_use.py+++ b/tests/unit/ingestion/test_ts_type_use.py@@ -167,6 +167,73 @@ _TYPE_ONLY_SOURCES = {class TestTsTypeUseEdges:+ def test_generic_argument_resolves_ambient_type(self, tmp_path: Path) -> None:+ graph = _build_graph(+ tmp_path,+ {+ "ambient.d.ts": (+ "declare global { interface AmbientSettings { endpoint: string } }\n"+ "export {}\n"+ ),+ "consumer.ts": (+ "function read(): Partial<AmbientSettings> {\n"+ " return decodeConfig<AmbientSettings>('payload')\n"+ "}\n"+ ),+ },+ )+ edge = graph.get_edge_data("consumer.ts", "ambient.d.ts", {})+ assert edge["edge_type"] == "type_use"+ assert "AmbientSettings" in edge["type_uses"]++ def test_unique_global_declaration_emits_file_type_use(self, tmp_path: Path) -> None:+ graph = _build_graph(+ tmp_path,+ {+ "ambient.d.ts": "interface AmbientSettings { endpoint: string }\n",+ "consumer.ts": (+ "export function readSettings(env: AmbientSettings): string { return env.endpoint }\n"+ ),+ },+ )+ edge = graph.get_edge_data("consumer.ts", "ambient.d.ts", {})+ assert edge+ assert edge["edge_type"] == "type_use"+ assert "AmbientSettings" in edge["type_uses"]++ def test_exported_module_declaration_is_not_treated_as_global(self, tmp_path: Path) -> None:+ graph = _build_graph(+ tmp_path,+ {+ "types.d.ts": "export interface AmbientSettings { endpoint: string }\n",+ "consumer.ts": (+ "export function readSettings(env: AmbientSettings): string { return env.endpoint }\n"+ ),+ },+ )+ assert not graph.has_edge("consumer.ts", "types.d.ts")++ def test_module_declaration_only_resolves_names_inside_declare_global(+ self, tmp_path: Path+ ) -> None:+ graph = _build_graph(+ tmp_path,+ {+ "types.d.ts": (+ "export {};\n"+ "declare global { interface AmbientSettings { endpoint: string } }\n"+ "export interface ModuleOnly { value: string }\n"+ ),+ "consumer.ts": (+ "export function readSettings(env: AmbientSettings): string { return env.endpoint }\n"+ "export function readModuleType(value: ModuleOnly): string { return value.value }\n"+ ),+ },+ )+ edge = graph.get_edge_data("consumer.ts", "types.d.ts", {})+ assert edge and "AmbientSettings" in edge["type_uses"]+ assert "ModuleOnly" not in edge["type_uses"]+def test_type_only_import_produces_type_use_provenance(self, tmp_path: Path) -> None:diff --git a/tests/unit/ingestion/test_type_head_identifiers.py b/tests/unit/ingestion/test_type_head_identifiers.pyindex 6b3ddf521..a336d7b87 100644--- a/tests/unit/ingestion/test_type_head_identifiers.py+++ b/tests/unit/ingestion/test_type_head_identifiers.py@@ -133,20 +133,19 @@ CASES: list[tuple[str, str, str, str, list[tuple[str, str]]]] = ["typescript","ts","generic-builtin-outer",- # Defect: the builtin outer (Promise) is correctly filtered, but the- # inner user type (Foo) is never captured separately — TS has no- # equivalent of C#'s type_argument_list rescue. Produces nothing.+ # The builtin outer (Promise) is filtered, and the inner generic+ # argument (Foo) is captured via (type_arguments (type_identifier) @param.type)."function f(a: Promise<Foo>) {}\n",- [],+ [("Foo", "param_type")],),("typescript","ts","generic-user-outer",- # Defect: same loss when the outer is a non-builtin — only the- # outer head (Container) survives; the inner arg (Foo) is dropped.+ # Both the outer head (Container) and the inner generic argument+ # (Foo) are captured."function f(a: Container<Foo>) {}\n",- [("Container", "param_type")],+ [("Container", "param_type"), ("Foo", "param_type")],),("typescript", "ts", "qualified", "function f(a: ns.Foo) {}\n", [("Foo", "param_type")]),("typescript", "ts", "array-wrapper", "function f(a: Foo[]) {}\n", [("Foo", "param_type")]),