Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(ingestion): track literal dynamic import namespace use (#1548)

Raghav Chamadiyaea32331ff419
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index ecfb274e6..00708cb35 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -879,9 +879,11 @@ class ASTParser:
# call_expression, which would otherwise fall into the CommonJS
# branch below and be dropped on the floor — a dynamic import
# holds no ``require()`` for ``collect_cjs_requires`` to find.
- # ``imported_names`` is empty because the construct binds a module
- # namespace at runtime, not a static name; the file-to-file edge is
- # what reachability needs.
+ # The construct binds a module namespace at runtime, so record a
+ # wildcard rather than a static name. Downstream unused-export
+ # analysis treats ``*`` as namespace consumption and therefore
+ # keeps the target's exports live without a broad analyzer
+ # exemption.
if (
file_info.language in _TS_JS_LANGUAGES
and stmt_node.type == "call_expression"
@@ -892,7 +894,7 @@ class ASTParser:
Import(
raw_statement=raw,
module_path=module_text,
- imported_names=[],
+ imported_names=["*"],
is_relative=module_text.startswith("."),
resolved_file=None,
bindings=[],
diff --git a/tests/unit/ingestion/parser/test_commonjs_require.py b/tests/unit/ingestion/parser/test_commonjs_require.py
index de864a464..2c2da7f17 100644
--- a/tests/unit/ingestion/parser/test_commonjs_require.py
+++ b/tests/unit/ingestion/parser/test_commonjs_require.py
@@ -158,14 +158,43 @@ def test_module_reference_declarator_is_import_not_symbol(
parser: ASTParser, source: str, name: str, module: str, language: str
) -> None:
result = _parse(parser, source, language=language)
- assert any(i.module_path == module for i in result.imports), (
- f"{source!r} lost its import edge"
- )
+ assert any(i.module_path == module for i in result.imports), f"{source!r} lost its import edge"
assert name not in {s.name for s in result.symbols}, (
f"{source!r} was indexed as a symbol as well as an import"
)
[email protected]("language", ["javascript", "typescript"])
+def test_literal_dynamic_import_records_namespace_consumption(
+ parser: ASTParser, language: str
+) -> None:
+ result = _parse(parser, "import('./lazy');\n", language=language)
+ imp = next(i for i in result.imports if i.module_path == "./lazy")
+ assert imp.imported_names == ["*"]
+
+
[email protected]("language", ["javascript", "typescript"])
+def test_nonliteral_dynamic_import_does_not_invent_precise_import(
+ parser: ASTParser, language: str
+) -> None:
+ result = _parse(parser, "const path = './lazy';\nimport(path);\n", language=language)
+ assert result.imports == []
+
+
[email protected]("language", ["javascript", "typescript"])
+def test_dynamic_import_namespace_does_not_change_static_or_commonjs_imports(
+ parser: ASTParser, language: str
+) -> None:
+ result = _parse(
+ parser,
+ "import { named } from './static';\nconst svc = require('./cjs');\n",
+ language=language,
+ )
+ imported_names = {imp.module_path: imp.imported_names for imp in result.imports}
+ assert imported_names["./static"] == ["named"]
+ assert imported_names["./cjs"] == ["svc"]
+
+
@pytest.mark.parametrize("cast", ["as Foo", "satisfies Foo"])
def test_cast_require_is_not_a_symbol(parser: ASTParser, cast: str) -> None:
"""``const a = require('./x') as Foo`` is idiomatic in TypeScript CJS.
diff --git a/tests/unit/ingestion/test_ts_dynamic_import_dead_code.py b/tests/unit/ingestion/test_ts_dynamic_import_dead_code.py
new file mode 100644
index 000000000..d021e3f4d
--- /dev/null
+++ b/tests/unit/ingestion/test_ts_dynamic_import_dead_code.py
@@ -0,0 +1,64 @@
+"""Literal TS/JS dynamic imports consume the target module namespace."""
+
+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
+
+
+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:
+ parser = ASTParser()
+ builder = GraphBuilder()
+ for path, source in sources.items():
+ builder.add_file(parser.parse_file(_file_info(path), source.encode("utf-8")))
+ return builder.build()
+
+
+def _unused_export_names(graph: nx.DiGraph) -> set[str]:
+ report = DeadCodeAnalyzer(graph, git_meta_map={}).analyze(
+ {"detect_unreachable_files": False, "detect_zombie_packages": False}
+ )
+ return {
+ finding.symbol_name
+ for finding in report.findings
+ if finding.kind == DeadCodeKind.UNUSED_EXPORT
+ }
+
+
+def test_literal_dynamic_import_keeps_target_exports_live() -> None:
+ graph = _graph_from_sources(
+ {
+ "pkg/app.ts": "export async function load() { return import('./lazy'); }\n",
+ "pkg/lazy.ts": "export function UsedByDynamicImport() { return 1; }\n",
+ "pkg/unrelated.ts": "export function TrulyUnused() { return 2; }\n",
+ }
+ )
+
+ edge = graph["pkg/app.ts"]["pkg/lazy.ts"]
+ assert edge["edge_type"] == "imports"
+ assert edge["imported_names"] == ["*"]
+
+ unused = _unused_export_names(graph)
+ assert "UsedByDynamicImport" not in unused
+ assert "TrulyUnused" in unused