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): record the exported name for aliased TS/JS imports (#1691)
Aman kumar5fdbbb151143
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex 41989c9c2..9b964d78e 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -1526,6 +1526,10 @@ class CallResolver:Read off the raw import statements rather than ``_import_names``, whichonly carries bindings that resolved to a file — precisely the ones thisneeds to exclude.++ The names wanted here are the ones *this file writes*, which is what+ ``Import.local_names`` answers: ``imported_names`` carries the source+ module's name, and under an alias the two differ."""names = self._external_names.get(file_path)if names is not None:@@ -1536,7 +1540,7 @@ class CallResolver:for imp in parsed.imports if parsed else ():if imp.resolved_file and not imp.resolved_file.startswith("external:"):continue- bound = (*imp.imported_names, imp.module_path.rsplit(".", 1)[-1])+ bound = (*imp.local_names, imp.module_path.rsplit(".", 1)[-1])found.update(name for name in bound if name and name != "*")names = frozenset(found)diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.pyindex 221a131fd..29100e49a 100644--- a/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py@@ -59,7 +59,7 @@ def _extract_require_bindings(if key is not None and val is not None:exported = node_text(key, src)local = node_text(val, src)- names.append(local)+ names.append(exported)bindings.append(NamedBinding(local_name=local, exported_name=exported, source_file=None))@@ -72,11 +72,21 @@ def extract_ts_js_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NHandles both ``import ... from`` and barrel ``export ... from`` (re-export)statements — the query tags re-exports carrying a ``source`` as- ``@import.statement`` so they flow through the same pipeline. For a- re-export, ``imported_names`` carries the name as it exists in the *source*- module (``export { A as B } from`` records ``A``), so the dead-code- analyzer can match it to the re-exported symbol and an ``index.ts`` barrel- no longer hides every component it forwards.+ ``@import.statement`` so they flow through the same pipeline.++ ``imported_names`` carries names as they exist in the *source* module, for+ named imports (``import { A as B } from`` records ``A``) exactly as for+ re-exports (``export { A as B } from`` records ``A``) — that is what+ downstream matches against, because the dead-code analyzer compares it to+ the source file's symbol names. Recording the local alias instead made+ every aliased import read as "no importers", so an alias-only consumer got+ its export reported ``safe_to_delete``; aliasing is forced whenever two+ modules export the same name, so registries of same-named symbols took the+ brunt. The local alias stays on the binding (``local_name``) for call+ resolution. Default and namespace imports keep the local name: their+ source-side name is ``default`` / the whole module, so the local name is+ the only useful one, and the analyzer's namespace rescue matches it+ against the file stem."""require_result = _extract_require_bindings(stmt_node, src)if require_result is not None:@@ -144,7 +154,7 @@ def extract_ts_js_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[Nif name_node:exported = node_text(name_node, src)local = node_text(alias_node, src) if alias_node else exported- names.append(local)+ names.append(exported)bindings.append(NamedBinding(local_name=local, exported_name=exported, source_file=Nonediff --git a/packages/core/src/repowise/core/ingestion/framework_edges/base.py b/packages/core/src/repowise/core/ingestion/framework_edges/base.pyindex 101676af8..3cb03a4a1 100644--- a/packages/core/src/repowise/core/ingestion/framework_edges/base.py+++ b/packages/core/src/repowise/core/ingestion/framework_edges/base.py@@ -163,12 +163,16 @@ def _build_ts_var_to_file(DSL back to the file that exports it, so a synthetic edge from theDSL call site to the handler module can be emitted. Pulling thisbuilder up to ``base`` avoids three near-identical copies.++ Keyed on ``local_names``, not ``imported_names``: the DSL names the+ handler as this file sees it, so ``import { handler as apiHandler }``+ has to answer to ``apiHandler``."""from ..resolvers import resolve_importvar_to_file: dict[str, str] = {}for imp in parsed.imports:- for name in imp.imported_names:+ for name in imp.local_names:resolved = resolve_import(imp.module_path,path,diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.pyindex 5cfa421b7..8ecacafc0 100644--- a/packages/core/src/repowise/core/ingestion/models.py+++ b/packages/core/src/repowise/core/ingestion/models.py@@ -229,6 +229,24 @@ class Import:bindings: list[NamedBinding] = field(default_factory=list)is_reexport: bool = False # True for `pub use` (Rust) or re-export patterns+ @property+ def local_names(self) -> list[str]:+ """The names this statement writes into the importing file's namespace.++ ``imported_names`` carries names as they exist in the *source* module,+ because that is what reachability matches against — under an alias+ (``import { A as B }``, ``from m import a as b``) the two differ. A+ caller that wants to recognise an identifier *as it appears in this+ file* — a router DSL naming a handler, an exclusion list for call+ resolution — must read the bindings instead, and this is that read.++ Falls back to ``imported_names`` for the languages whose extractors+ emit no bindings, where the two are the same list by construction. For+ a re-export nothing is truly bound locally; the alias is returned,+ being the token that appears in this file.+ """+ return [b.local_name for b in self.bindings] or list(self.imported_names)+@dataclassclass CallReceiver:diff --git a/tests/unit/ingestion/test_ts_import_alias_dead_code.py b/tests/unit/ingestion/test_ts_import_alias_dead_code.pynew file mode 100644index 000000000..80bad94f3--- /dev/null+++ b/tests/unit/ingestion/test_ts_import_alias_dead_code.py@@ -0,0 +1,183 @@+"""Regression tests: TS/JS aliased imports keep the imported symbol live.++``import { beta as renamedBeta } from "./lib"`` used to stamp the *local*+alias on the imports edge, so the unused-export pass — which asks whether the+*source* module's symbol name appears in ``imported_names`` — never matched+and reported ``beta`` as ``safe_to_delete``. Aliasing is mandatory whenever+two modules export the same name, so registries of same-named symbols got the+worst of it. These tests drive the real parser → GraphBuilder →+DeadCodeAnalyzer and assert the aliased symbol is no longer flagged.+"""++from __future__ import annotations++from datetime import datetime++import networkx as nx++from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind+from repowise.core.ingestion.graph import GraphBuilder+from repowise.core.ingestion.models import FileInfo+from repowise.core.ingestion.parser import ASTParser++_PARSER = ASTParser()+++def _file_info(path: str) -> FileInfo:+ return FileInfo(+ path=path,+ abs_path=f"/repo/{path}",+ language="typescript",+ size_bytes=100,+ git_hash="",+ last_modified=datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )+++def _graph_from_sources(sources: dict[str, str]) -> nx.DiGraph:+ builder = GraphBuilder()+ for path, src in sources.items():+ parsed = _PARSER.parse_file(_file_info(path), src.encode("utf-8"))+ builder.add_file(parsed)+ return builder.build()+++def _unused_export_names(graph: nx.DiGraph) -> set[str]:+ analyzer = DeadCodeAnalyzer(graph, git_meta_map={})+ report = analyzer.analyze({"detect_unreachable_files": False, "detect_zombie_packages": False})+ return {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}+++def _imported_names(src: str, path: str = "pkg/m.ts") -> list[str]:+ """Parse a single-statement TS source and return the edge's imported names."""+ parsed = _PARSER.parse_file(_file_info(path), src.encode("utf-8"))+ assert parsed.imports, f"no import captured for: {src!r}"+ return parsed.imports[0].imported_names+++def _bindings(src: str, path: str = "pkg/m.ts") -> list[tuple[str, str | None]]:+ parsed = _PARSER.parse_file(_file_info(path), src.encode("utf-8"))+ assert parsed.imports, f"no import captured for: {src!r}"+ return [(b.local_name, b.exported_name) for b in parsed.imports[0].bindings]+++def _local_names(src: str, path: str = "pkg/m.ts") -> list[str]:+ parsed = _PARSER.parse_file(_file_info(path), src.encode("utf-8"))+ assert parsed.imports, f"no import captured for: {src!r}"+ return parsed.imports[0].local_names+++# ---------------------------------------------------------------------------+# Binding extraction — import statements+# ---------------------------------------------------------------------------+++class TestImportAliasBindings:+ def test_plain_named_import_records_source_name(self) -> None:+ assert _imported_names('import { alpha } from "./lib";') == ["alpha"]++ def test_aliased_named_import_records_source_name(self) -> None:+ # `beta as renamedBeta` imports the source module's `beta`;+ # reachability is about beta.+ assert _imported_names('import { beta as renamedBeta } from "./lib";') == ["beta"]++ def test_aliased_named_import_keeps_local_name_on_binding(self) -> None:+ # Call resolution still needs the local alias to resolve `renamedBeta(...)`.+ assert _bindings('import { beta as renamedBeta } from "./lib";') == [+ ("renamedBeta", "beta")+ ]++ def test_aliased_require_destructure_records_source_name(self) -> None:+ assert _imported_names('const { beta: renamedBeta } = require("./lib");') == ["beta"]++ def test_aliased_require_destructure_keeps_local_name_on_binding(self) -> None:+ assert _bindings('const { beta: renamedBeta } = require("./lib");') == [+ ("renamedBeta", "beta")+ ]++ def test_default_import_still_records_local_name(self) -> None:+ # The source name is literally `default`; the local name is the only+ # useful one, and the namespace rescue matches it against the file stem.+ assert _imported_names('import React from "./react";') == ["React"]++ def test_namespace_import_still_records_local_name(self) -> None:+ assert _imported_names('import * as utils from "./utils";') == ["utils"]+++class TestLocalNames:+ """``Import.local_names`` is what a caller reads to recognise an identifier+ as it appears in the importing file — a router DSL naming a handler, or the+ external-binding exclusion in call resolution."""++ def test_alias_local_name_is_the_alias(self) -> None:+ src = 'import { beta as renamedBeta } from "./lib";'+ assert _local_names(src) == ["renamedBeta"]+ assert _imported_names(src) == ["beta"]++ def test_plain_import_local_name_matches_the_source_name(self) -> None:+ assert _local_names('import { alpha } from "./lib";') == ["alpha"]++ def test_require_destructure_alias_local_name_is_the_alias(self) -> None:+ assert _local_names('const { beta: renamedBeta } = require("./lib");') == ["renamedBeta"]+++# ---------------------------------------------------------------------------+# End-to-end: parser → graph → dead-code analyzer+# ---------------------------------------------------------------------------+++_LIB = """+export function alpha() { return 1 }+export function beta() { return 2 }+"""+++class TestAliasedImportNotDeadCode:+ def test_value_position_aliased_import_is_not_unused(self) -> None:+ # Value-position references only: no call edge exists to rescue the+ # symbol, so the imports edge is the sole usage signal.+ graph = _graph_from_sources(+ {+ "lib.ts": _LIB,+ "registry.ts": """+import { alpha } from "./lib"+import { beta as renamedBeta } from "./lib"++export const registry = [alpha, renamedBeta]+""",+ }+ )+ flagged = _unused_export_names(graph)+ assert "beta" not in flagged+ assert "alpha" not in flagged++ def test_aliased_require_destructure_is_not_unused(self) -> None:+ graph = _graph_from_sources(+ {+ "lib.ts": _LIB,+ "registry.ts": """+const { beta: renamedBeta } = require("./lib")++module.exports = { registry: [renamedBeta] }+""",+ }+ )+ assert "beta" not in _unused_export_names(graph)++ def test_genuinely_unimported_symbol_is_still_flagged(self) -> None:+ # The alias fix must not blanket-rescue everything in the target file.+ graph = _graph_from_sources(+ {+ "lib.ts": _LIB,+ "registry.ts": """+import { beta as renamedBeta } from "./lib"++export const registry = [renamedBeta]+""",+ }+ )+ assert "alpha" in _unused_export_names(graph)