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(graph): resolve React Native platform files to import edges (#3711)

Aman62cbeb2ad404
diff --git a/packages/core/src/repowise/core/ingestion/graph/_edges.py b/packages/core/src/repowise/core/ingestion/graph/_edges.py
index b52dd4a61..c315775ed 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_edges.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_edges.py
@@ -20,6 +20,7 @@ from ...co_change import (
from ..models import FILE_DEPENDENCY_EDGE_TYPES, is_dynamic_edge
from ..resolvers import ResolverContext
from ..resolvers.go import read_go_module_path, read_go_modules
+from ..resolvers.typescript import detect_platform_files
from ._stem import build_stem_map
log = structlog.get_logger(__name__)
@@ -220,6 +221,7 @@ class EdgesMixin:
go_module_path=(go_modules[-1][1] if go_modules else read_go_module_path(self._repo_path)),
go_modules=go_modules,
has_sfc_files=any(p.endswith((".vue", ".svelte", ".astro")) for p in path_set),
+ has_platform_files=detect_platform_files(path_set),
parsed_files=self._parsed_files,
# Same reason ``build()`` passes it: a handler that scans file text
# (the Godot ``class_name`` one covers every ``.gd`` in the repo)
diff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.py
index 967f38b10..71fb2a68d 100644
--- a/packages/core/src/repowise/core/ingestion/graph/builder.py
+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py
@@ -26,6 +26,7 @@ from ..models import Import, ParsedFile, Symbol, combine_load_kinds
from ..resolvers import ResolverContext, resolve_import
from ..resolvers.go import read_go_module_path, read_go_modules
from ..resolvers.go_workspace import cached_go_index, go_package_files
+from ..resolvers.typescript import detect_platform_files
from ..symbol_identity import has_overload_identity
from ..type_ref_resolution import resolve_type_refs
from ._edges import EdgesMixin
@@ -426,6 +427,7 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
),
go_modules=go_modules,
has_sfc_files=any(p.endswith((".vue", ".svelte", ".astro")) for p in path_set),
+ has_platform_files=detect_platform_files(path_set),
parsed_files=self._parsed_files,
source_map=self._source_map,
)
@@ -507,6 +509,13 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
from ..resolvers.python import resolve_python_import_all
targets = resolve_python_import_all(imp, path, ctx)
+ elif _lang in ("typescript", "javascript"):
+ # React Native: ``./Button`` also means ``Button.ios.tsx`` /
+ # ``Button.android.tsx`` (Metro platform extensions). A repo
+ # with no such files resolves exactly as before (#3603).
+ from ..resolvers.typescript import resolve_ts_js_import_all
+
+ targets = resolve_ts_js_import_all(imp.module_path, path, ctx)
else:
single = resolve_import(imp.module_path, path, _lang, ctx)
targets = (single,) if single else ()
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/context.py b/packages/core/src/repowise/core/ingestion/resolvers/context.py
index 365555e8e..3e1b3e7da 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/context.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/context.py
@@ -42,6 +42,10 @@ class ResolverContext:
go_module_path: str | None = None
go_modules: tuple[tuple[str, str], ...] = () # (module_dir_posix, module_path), longest-first
has_sfc_files: bool = False # any .vue/.svelte/.astro present in path_set
+ # Any ``<name>.<ios|android|native|web>.<ts|tsx|...>`` file in path_set:
+ # Metro (React Native) picks one of these over ``<name>.<ext>``. False keeps
+ # TS/JS resolution byte-identical to a repo that has no such files.
+ has_platform_files: bool = False
parsed_files: dict | None = None # for Rust crate root detection
# ``{file_info.path: raw source bytes}`` the pipeline already read, same
# keys as *parsed_files*. Warmups that scan file text use it in place of
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/typescript.py b/packages/core/src/repowise/core/ingestion/resolvers/typescript.py
index 16774d0dc..6f22c8fb6 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/typescript.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/typescript.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import posixpath
+from collections.abc import Iterable
from pathlib import Path
from .context import ResolverContext
@@ -10,6 +11,24 @@ from .subpath_imports import resolve_subpath_import
from .svelte_kit import resolve_lib_alias
from .ts_workspace import resolve_via_workspaces
+# Metro (React Native) platform extensions, in sorted order so the candidates
+# generated from them are deterministic.
+PLATFORM_SEGMENTS: tuple[str, ...] = ("android", "ios", "native", "web")
+_PLATFORM_FILE_EXTS: tuple[str, ...] = (".ts", ".tsx", ".mts", ".cts", ".js", ".jsx")
+_PLATFORM_SUFFIXES: tuple[str, ...] = tuple(
+ f".{platform}{ext}" for platform in PLATFORM_SEGMENTS for ext in _PLATFORM_FILE_EXTS
+)
+
+
+def detect_platform_files(paths: Iterable[str]) -> bool:
+ """True when any path is a Metro platform file (``Button.ios.tsx``).
+
+ Computed once where the :class:`ResolverContext` is built, like
+ ``has_sfc_files``, so a repository without platform files never pays for
+ (or is changed by) the platform probing in :func:`resolve_ts_js_import_all`.
+ """
+ return any(p.endswith(_PLATFORM_SUFFIXES) for p in paths)
+
def resolve_ts_js_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:
"""Resolve a TypeScript or JavaScript import to a repo-relative file path."""
@@ -101,3 +120,39 @@ def resolve_ts_js_import(module_path: str, importer_path: str, ctx: ResolverCont
# Fallback: external npm package.
return ctx.add_external_node(module_path)
+
+
+def resolve_ts_js_import_all(
+ module_path: str, importer_path: str, ctx: ResolverContext
+) -> tuple[str, ...]:
+ """Resolve a TS/JS import to every file it can mean, plain file first.
+
+ Metro resolves ``./Button`` to ``Button.ios.tsx`` on iOS and
+ ``Button.android.tsx`` on Android, and ``./haptics`` to ``haptics.native.ts``
+ ahead of ``haptics.ts``. The importer depends on all of them, so each gets
+ an edge. The result is the single-target resolution (if any) followed by the
+ platform files in sorted order, which keeps ``imp.resolved_file`` the plain
+ file whenever there is one.
+
+ Only relative specifiers in a repository that has platform files are
+ expanded (``ctx.has_platform_files``); everything else is exactly
+ :func:`resolve_ts_js_import`.
+ """
+ single = resolve_ts_js_import(module_path, importer_path, ctx)
+ targets: list[str] = [single] if single else []
+ if not ctx.has_platform_files or not module_path.startswith("."):
+ return tuple(targets)
+
+ base_posix = posixpath.normpath(
+ posixpath.join(Path(importer_path).parent.as_posix(), module_path)
+ )
+ platform_targets: set[str] = set()
+ for platform in PLATFORM_SEGMENTS:
+ for ext in _PLATFORM_FILE_EXTS:
+ for stem in (base_posix, f"{base_posix}/index"):
+ candidate = f"{stem}.{platform}{ext}"
+ if candidate in ctx.path_set:
+ platform_targets.add(candidate)
+ platform_targets.discard(single or "")
+ targets.extend(sorted(platform_targets))
+ return tuple(targets)
diff --git a/tests/unit/dead_code/test_react_native_platform_files.py b/tests/unit/dead_code/test_react_native_platform_files.py
new file mode 100644
index 000000000..f0d37043c
--- /dev/null
+++ b/tests/unit/dead_code/test_react_native_platform_files.py
@@ -0,0 +1,94 @@
+"""React Native platform files are reachable, not dead code (#3603).
+
+Metro resolves ``import Button from './Button'`` to ``Button.ios.tsx`` /
+``Button.android.tsx`` and ``./haptics`` to ``haptics.native.ts`` as well as
+``haptics.ts``. Built through the real traverse -> parse -> graph path.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from repowise.core.analysis.dead_code import DeadCodeAnalyzer
+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+
+_FILES = {
+ "package.json": json.dumps({"dependencies": {"react-native": "0.76.0", "react": "18.3.1"}}),
+ "index.js": (
+ "import App from './src/App';\n"
+ "AppRegistry.registerComponent('rnapp', () => App);\n"
+ ),
+ "src/App.tsx": (
+ "import Button from './components/Button';\n"
+ "import { haptic } from './components/haptics';\n"
+ "export default function App() { haptic(); return Button(); }\n"
+ ),
+ "src/components/Button.ios.tsx": "export default function Button() { return null; }\n",
+ "src/components/Button.android.tsx": "export default function Button() { return null; }\n",
+ "src/components/haptics.ts": "export function haptic() {}\n",
+ "src/components/haptics.native.ts": "export function haptic() {}\n",
+}
+
+_PLATFORM_FILES = (
+ "src/components/Button.ios.tsx",
+ "src/components/Button.android.tsx",
+ "src/components/haptics.ts",
+ "src/components/haptics.native.ts",
+)
+
+
+def _build(repo: Path) -> tuple[GraphBuilder, dict[str, bytes]]:
+ builder = GraphBuilder(repo)
+ parser = ASTParser()
+ source_map: dict[str, bytes] = {}
+ for fi in FileTraverser(repo).traverse():
+ src = Path(fi.abs_path).read_bytes()
+ builder.add_file(parser.parse_file(fi, src))
+ source_map[fi.path] = src
+ builder.set_source_map(source_map)
+ builder.build()
+ return builder, source_map
+
+
+def _write(repo: Path, files: dict[str, str]) -> None:
+ for rel, text in files.items():
+ path = repo / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8")
+
+
+def _flagged(repo: Path) -> set[tuple[str, str]]:
+ builder, source_map = _build(repo)
+ report = DeadCodeAnalyzer(
+ builder.graph(), {}, parsed_files=builder._parsed_files, source_map=source_map, repo_root=repo
+ ).analyze({})
+ return {(f.kind.value, f.file_path) for f in report.findings}
+
+
+def test_app_imports_every_platform_file(tmp_path: Path) -> None:
+ _write(tmp_path, _FILES)
+ builder, _ = _build(tmp_path)
+
+ edges = {(u, v) for u, v in builder.graph().edges if u == "src/App.tsx"}
+
+ for target in _PLATFORM_FILES:
+ assert ("src/App.tsx", target) in edges, target
+
+
+def test_platform_files_are_not_reported_as_dead(tmp_path: Path) -> None:
+ _write(tmp_path, _FILES)
+
+ flagged_files = {path for _kind, path in _flagged(tmp_path)}
+
+ for live in _PLATFORM_FILES:
+ assert live not in flagged_files, live
+
+
+def test_a_platform_file_nothing_imports_is_still_dead(tmp_path: Path) -> None:
+ # The control: only an import keeps a platform file alive.
+ _write(tmp_path, {**_FILES, "src/components/Orphan.ios.tsx": "export const Orphan = 1;\n"})
+
+ flagged_files = {path for _kind, path in _flagged(tmp_path)}
+
+ assert "src/components/Orphan.ios.tsx" in flagged_files
diff --git a/tests/unit/ingestion/test_typescript_resolver.py b/tests/unit/ingestion/test_typescript_resolver.py
index 2c178973b..1466821bb 100644
--- a/tests/unit/ingestion/test_typescript_resolver.py
+++ b/tests/unit/ingestion/test_typescript_resolver.py
@@ -17,7 +17,11 @@ from repowise.core.ingestion.resolvers.ts_workspace import (
build_workspace_map,
resolve_via_workspaces,
)
-from repowise.core.ingestion.resolvers.typescript import resolve_ts_js_import
+from repowise.core.ingestion.resolvers.typescript import (
+ detect_platform_files,
+ resolve_ts_js_import,
+ resolve_ts_js_import_all,
+)
def _ctx(repo: Path, paths: list[str], has_sfc: bool = False) -> ResolverContext:
@@ -29,6 +33,7 @@ def _ctx(repo: Path, paths: list[str], has_sfc: bool = False) -> ResolverContext
repo_path=repo,
has_sfc_files=has_sfc
or any(p.endswith((".vue", ".svelte", ".astro")) for p in path_set),
+ has_platform_files=detect_platform_files(path_set),
)
@@ -956,3 +961,87 @@ class TestMtsCtsResolution:
def test_directory_import_resolves_to_index_cts(self, tmp_path: Path) -> None:
ctx = _ctx(tmp_path, ["src/pkg/index.cts", "src/main.ts"])
assert resolve_ts_js_import("./pkg", "src/main.ts", ctx) == "src/pkg/index.cts"
+
+
+_RN_PATHS = [
+ "index.js",
+ "src/App.tsx",
+ "src/components/Button.ios.tsx",
+ "src/components/Button.android.tsx",
+ "src/components/haptics.ts",
+ "src/components/haptics.native.ts",
+]
+
+
+class TestReactNativePlatformFiles:
+ """Metro picks ``X.<ios|android|native|web>.<ext>`` over ``X.<ext>`` (#3603)."""
+
+ def test_flag_set_only_when_a_platform_file_exists(self, tmp_path: Path) -> None:
+ assert _ctx(tmp_path, _RN_PATHS).has_platform_files is True
+ assert _ctx(tmp_path, ["src/foo.ts", "src/foo.test.ts"]).has_platform_files is False
+
+ @pytest.mark.parametrize("name", ["ios", "android", "native", "web"])
+ def test_flag_recognises_each_platform_segment(self, tmp_path: Path, name: str) -> None:
+ assert _ctx(tmp_path, [f"src/a.{name}.ts"]).has_platform_files is True
+
+ def test_flag_ignores_non_trailing_platform_segment(self, tmp_path: Path) -> None:
+ # ``ios`` as a directory or a mid-name token is not a platform extension.
+ ctx = _ctx(tmp_path, ["src/ios/util.ts", "src/ios.config.ts", "src/web.json"])
+ assert ctx.has_platform_files is False
+
+ def test_platform_only_import_resolves_to_every_platform_file(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, _RN_PATHS)
+ assert resolve_ts_js_import_all("./components/Button", "src/App.tsx", ctx) == (
+ "src/components/Button.android.tsx",
+ "src/components/Button.ios.tsx",
+ )
+
+ def test_plain_file_comes_first_then_sorted_platform_files(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, _RN_PATHS)
+ assert resolve_ts_js_import_all("./components/haptics", "src/App.tsx", ctx) == (
+ "src/components/haptics.ts",
+ "src/components/haptics.native.ts",
+ )
+
+ def test_index_form_resolves_through_directory(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ [
+ "src/App.tsx",
+ "src/components/Button/index.ios.tsx",
+ "src/components/Button/index.android.tsx",
+ ],
+ )
+ assert resolve_ts_js_import_all("./components/Button", "src/App.tsx", ctx) == (
+ "src/components/Button/index.android.tsx",
+ "src/components/Button/index.ios.tsx",
+ )
+
+ def test_parent_relative_specifier(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, ["src/screens/Home.tsx", "src/ui/Card.web.tsx", "src/ui/Card.ios.tsx"])
+ assert resolve_ts_js_import_all("../ui/Card", "src/screens/Home.tsx", ctx) == (
+ "src/ui/Card.ios.tsx",
+ "src/ui/Card.web.tsx",
+ )
+
+ def test_unrelated_platform_files_are_not_picked_up(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, [*_RN_PATHS, "src/components/Other.ios.tsx"])
+ targets = resolve_ts_js_import_all("./components/Button", "src/App.tsx", ctx)
+ assert "src/components/Other.ios.tsx" not in targets
+
+ def test_repo_without_platform_files_matches_single_resolver(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, ["src/foo.ts", "src/main.ts"])
+ assert ctx.has_platform_files is False
+ assert resolve_ts_js_import_all("./foo", "src/main.ts", ctx) == ("src/foo.ts",)
+ assert resolve_ts_js_import_all("./missing", "src/main.ts", ctx) == ()
+
+ def test_probing_is_gated_on_the_context_flag(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, _RN_PATHS)
+ ctx.has_platform_files = False
+ assert resolve_ts_js_import_all("./components/Button", "src/App.tsx", ctx) == ()
+
+ def test_non_relative_specifiers_are_unchanged(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, _RN_PATHS)
+ assert resolve_ts_js_import_all("react-native", "src/App.tsx", ctx) == (
+ "external:react-native",
+ )