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): bind a workspace package that publishes only from a build directory (#1670)

Raghav Chamadiyaa81aeefec008
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py
index 58120bf01..a8ced2070 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py
@@ -169,8 +169,48 @@ def _flatten_export_value(value: Any) -> str | None:
return None
-def _build_exports_map(pkg_data: dict) -> dict[str, str]:
- """Return ``{exports_key: relative_target}`` for a workspace package.
+def _ordered_export_targets(value: Any) -> tuple[str, ...]:
+ """Every target a Node ``exports`` entry can mean, best first.
+
+ The head is exactly what :func:`_flatten_export_value` chose, so a package
+ whose ranked condition names a file the repository contains binds the file
+ it always bound. The tail is every other leaf, ranked conditions before
+ unranked ones, and is reached only when the head names nothing indexed.
+
+ The tail has to exist because a package may publish its sources under a
+ condition no fixed list can name — zod uses ``@zod/source`` — while every
+ condition this module ranks names build output a source checkout does not
+ contain, leaving the whole package unresolvable.
+ """
+ ordered: list[str] = []
+ head = _flatten_export_value(value)
+ if head is not None:
+ ordered.append(head)
+
+ def walk(node: Any) -> None:
+ if isinstance(node, str):
+ if node not in ordered:
+ ordered.append(node)
+ elif isinstance(node, list):
+ for item in node:
+ walk(item)
+ elif isinstance(node, dict):
+ for cond in _CONDITION_PRIORITY:
+ if cond in node:
+ walk(node[cond])
+ for cond, inner in node.items():
+ if cond not in _CONDITION_PRIORITY:
+ walk(inner)
+
+ walk(value)
+ return tuple(ordered)
+
+
+_DECLARATION_SUFFIXES: tuple[str, ...] = (".d.ts", ".d.mts", ".d.cts")
+
+
+def _build_exports_map(pkg_data: dict) -> dict[str, tuple[str, ...]]:
+ """Return ``{exports_key: (target, ...)}`` for a workspace package.
``exports`` may be a single string (shorthand for ``{".": <str>}``)
or a subpath dict. Keys that don't start with ``.`` are dropped (the
@@ -180,34 +220,40 @@ def _build_exports_map(pkg_data: dict) -> dict[str, str]:
if raw is None:
return {}
if isinstance(raw, str):
- return {".": raw}
+ return {".": (raw,)}
if not isinstance(raw, dict):
return {}
- out: dict[str, str] = {}
+ out: dict[str, tuple[str, ...]] = {}
for key, value in raw.items():
if not isinstance(key, str) or not key.startswith("."):
continue
- flat = _flatten_export_value(value)
- if flat is None:
+ # A key whose ranked walk yields nothing is dropped, exactly as before.
+ # Keeping it on the strength of a spare candidate alone would let that
+ # candidate answer in the exports step, ahead of the fallbacks that
+ # answer for such a key today — a moved binding rather than a new one.
+ if _flatten_export_value(value) is None:
continue
- out[key] = flat
+ out[key] = _ordered_export_targets(value)
return out
-def _match_export_key(subpath: str, exports_map: dict[str, str]) -> str | None:
+def _match_export_key(
+ subpath: str, exports_map: dict[str, tuple[str, ...]]
+) -> tuple[str, ...] | None:
"""Resolve a subpath against an ``exports`` map.
``subpath`` is the part of the import specifier after the package
name, with no leading slash (``""`` for the bare package, ``"lib/x"``
for ``@org/pkg/lib/x``). Exact keys win over wildcard patterns; among
- wildcards the longest static prefix wins (Node spec).
+ wildcards the longest static prefix wins (Node spec). Returns the
+ matched key's candidate targets in priority order.
"""
key = "." if subpath == "" else "./" + subpath
if key in exports_map:
return exports_map[key]
- best_target: str | None = None
+ best_targets: tuple[str, ...] | None = None
best_prefix_len = -1
- for pattern, target in exports_map.items():
+ for pattern, targets in exports_map.items():
if "*" not in pattern:
continue
prefix, _, suffix = pattern.partition("*")
@@ -220,11 +266,16 @@ def _match_export_key(subpath: str, exports_map: dict[str, str]) -> str | None:
if suffix
else key[len(prefix) :]
)
- resolved = target.replace("*", captured, 1) if "*" in target else target
if len(prefix) > best_prefix_len:
- best_target = resolved
+ # Beyond the head, a candidate carrying no ``*`` is dropped: the
+ # same fixed file would otherwise answer every distinct subpath
+ # under this key, quietly collapsing them onto one another.
+ kept = targets[:1] + tuple(t for t in targets[1:] if "*" in t)
+ best_targets = tuple(
+ t.replace("*", captured, 1) if "*" in t else t for t in kept
+ )
best_prefix_len = len(prefix)
- return best_target
+ return best_targets
def _read_workspaces_field(pkg_data: dict) -> list[str]:
@@ -462,22 +513,45 @@ def resolve_via_workspaces(module_path: str, ctx: ResolverContext) -> str | None
pkg = info[best_name]
dir_posix: str = pkg["dir"]
- exports_map: dict[str, str] = pkg["exports"]
+ exports_map: dict[str, tuple[str, ...]] = pkg["exports"]
sub = module_path[len(best_name) :].lstrip("/")
- # 1) ``exports`` field — the package's authoritative subpath map.
- if exports_map:
- target = _match_export_key(sub, exports_map)
- if target is not None:
- # Targets are package-relative ("./src/lib/foo.ts"). Strip the
- # leading "./" and join with the package dir to get a repo path.
- stripped = target.lstrip("./")
- resolved = _probe_path(f"{dir_posix}/{stripped}", ctx.path_set)
+ targets = _match_export_key(sub, exports_map) if exports_map else None
+
+ def probe_target(target: str) -> str | None:
+ # Targets are package-relative ("./src/lib/foo.ts"). Strip the
+ # leading "./" and join with the package dir to get a repo path.
+ return _probe_path(f"{dir_posix}/{target.lstrip('./')}", ctx.path_set)
+
+ def spare_export_target() -> str | None:
+ """A candidate past the ranked one, for when nothing else answered.
+
+ Kept behind every pre-existing probe so this can only fill a specifier
+ that resolved to nothing: a package naming its sources under a
+ condition no fixed list ranks is unreachable otherwise, but reordering
+ would move imports that already bind, which is a different change.
+
+ A declaration file is never taken here. It carries no bodies, so
+ binding one as an entry resolves every call through it to a signature
+ — worse than the external node it would replace, which claims nothing.
+ """
+ for target in (targets or ())[1:]:
+ if target.endswith(_DECLARATION_SUFFIXES):
+ continue
+ resolved = probe_target(target)
if resolved is not None:
return resolved
+ return None
+
+ # 1) ``exports`` field — the package's authoritative subpath map.
+ if targets:
+ resolved = probe_target(targets[0])
+ if resolved is not None:
+ return resolved
# 2) Bare-package fallback — no ``exports[.]`` entry: try index.*,
- # then ``main``/``module`` from package.json.
+ # then ``main``/``module`` from package.json, then the entries a
+ # package publishing only from a build directory leaves reachable.
if not sub:
cand = _probe_path(f"{dir_posix}/index", ctx.path_set)
if cand is not None:
@@ -487,6 +561,13 @@ def resolve_via_workspaces(module_path: str, ctx: ResolverContext) -> str | None
cand = _probe_path(f"{dir_posix}/{main.lstrip('./')}", ctx.path_set)
if cand is not None:
return cand
+ cand = spare_export_target()
+ if cand is not None:
+ return cand
+ for source_root in ("src", "lib"):
+ cand = _probe_path(f"{dir_posix}/{source_root}/index", ctx.path_set)
+ if cand is not None:
+ return cand
return None
# 3) Subpath fallback — packages without ``exports`` (plain monorepo
@@ -500,7 +581,7 @@ def resolve_via_workspaces(module_path: str, ctx: ResolverContext) -> str | None
cand = _probe_path(f"{dir_posix}/{src_root}/{sub}", ctx.path_set)
if cand is not None:
return cand
- return None
+ return spare_export_target()
# ---------------------------------------------------------------------------
@@ -580,9 +661,15 @@ def build_ts_workspace_index(ctx: ResolverContext) -> TsWorkspaceIndex:
path_set = ctx.path_set
for _name, pkg in packages.items():
dir_posix: str = pkg["dir"]
- exports_map: dict[str, str] = pkg.get("exports") or {}
- for pattern, target in exports_map.items():
- entries.update(_expand_exports_wildcard(target, pattern, dir_posix, path_set))
+ exports_map: dict[str, tuple[str, ...]] = pkg.get("exports") or {}
+ for pattern, targets in exports_map.items():
+ # The ranked target only. The spare candidates exist to bind an
+ # import the resolver would otherwise drop; letting them widen the
+ # published-entry set would suppress dead-code findings instead,
+ # which is a different change and is not what was measured here.
+ entries.update(
+ _expand_exports_wildcard(targets[0], pattern, dir_posix, path_set)
+ )
# ``main``/``module`` shorthand — package's primary entry.
main = pkg.get("main")
if isinstance(main, str):
diff --git a/tests/unit/ingestion/test_typescript_resolver.py b/tests/unit/ingestion/test_typescript_resolver.py
index a4ad9f371..799e2d2d6 100644
--- a/tests/unit/ingestion/test_typescript_resolver.py
+++ b/tests/unit/ingestion/test_typescript_resolver.py
@@ -477,6 +477,175 @@ class TestWorkspaceExportsField:
== "packages/ui/src/util.ts"
)
+ def test_exports_condition_naming_absent_build_output_is_passed_over(
+ self, tmp_path: Path
+ ) -> None:
+ # Every condition this module ranks names a built artefact a source
+ # checkout does not contain, and the package publishes its TypeScript
+ # under a condition no fixed list can name. Collapsing to one ranked
+ # target left the whole package unresolvable.
+ _setup_workspace(
+ tmp_path,
+ "@org/ui",
+ {
+ "exports": {
+ ".": {
+ "@org/source": "./src/index.ts",
+ "types": "./index.d.cts",
+ "import": "./index.js",
+ "require": "./index.cjs",
+ }
+ }
+ },
+ )
+ ctx = _ctx(tmp_path, ["packages/ui/src/index.ts"])
+ assert resolve_via_workspaces("@org/ui", ctx) == "packages/ui/src/index.ts"
+
+ def test_ranked_condition_still_wins_when_both_targets_exist(
+ self, tmp_path: Path
+ ) -> None:
+ # The guard on the guard: continuing past an absent target must not
+ # become a preference for source, or every package shipping both a
+ # build and its sources would change which file it binds.
+ _setup_workspace(
+ tmp_path,
+ "@org/ui",
+ {
+ "exports": {
+ ".": {
+ "@org/source": "./src/index.ts",
+ "import": "./dist/index.js",
+ }
+ }
+ },
+ )
+ ctx = _ctx(tmp_path, ["packages/ui/src/index.ts", "packages/ui/dist/index.js"])
+ assert resolve_via_workspaces("@org/ui", ctx) == "packages/ui/dist/index.js"
+
+ def test_nested_unranked_condition_does_not_outrank_a_later_ranked_one(
+ self, tmp_path: Path
+ ) -> None:
+ # ``import`` outranks ``require``, but its subtree holds only conditions
+ # this module does not rank, so the old collapse skipped the whole
+ # branch and chose ``require``. Enumerating candidates must not promote
+ # the development build to the head of the list.
+ _setup_workspace(
+ tmp_path,
+ "@org/ui",
+ {
+ "exports": {
+ ".": {
+ "import": {"development": "./dev.js"},
+ "require": "./index.cjs",
+ }
+ }
+ },
+ )
+ ctx = _ctx(tmp_path, ["packages/ui/dev.js", "packages/ui/index.cjs"])
+ assert resolve_via_workspaces("@org/ui", ctx) == "packages/ui/index.cjs"
+
+ def test_entry_with_no_ranked_condition_still_falls_through(
+ self, tmp_path: Path
+ ) -> None:
+ # No condition here is one the module ranks, so the key was dropped
+ # outright and the subpath probe below answered. Keeping the key on the
+ # strength of a spare candidate would let ``./internal.ts`` answer from
+ # the exports step instead — a moved binding, not a new one.
+ _setup_workspace(
+ tmp_path,
+ "@org/ui",
+ {"exports": {".": {"bespoke": "./internal.ts"}}},
+ )
+ ctx = _ctx(tmp_path, ["packages/ui/internal.ts", "packages/ui/index.ts"])
+ assert resolve_via_workspaces("@org/ui", ctx) == "packages/ui/index.ts"
+
+ def test_spare_export_target_never_displaces_the_index_probe(
+ self, tmp_path: Path
+ ) -> None:
+ # vue's shape: the ranked condition names an absent build artefact, a
+ # lower condition names a committed ``index.mjs``, and the package root
+ # also holds the ``index.js`` the probe below already bound. The spare
+ # candidate must stay behind that probe, or the change stops being an
+ # addition and starts moving imports that already resolve.
+ _setup_workspace(
+ tmp_path,
+ "@org/ui",
+ {
+ "main": "index.js",
+ "exports": {
+ ".": {
+ "import": {
+ "default": "./dist/ui.esm-bundler.js",
+ "node": "./index.mjs",
+ }
+ }
+ },
+ },
+ )
+ ctx = _ctx(tmp_path, ["packages/ui/index.js", "packages/ui/index.mjs"])
+ assert resolve_via_workspaces("@org/ui", ctx) == "packages/ui/index.js"
+
+ def test_declaration_file_is_not_taken_as_a_fallback_entry(
+ self, tmp_path: Path
+ ) -> None:
+ # The built entry is absent and the committed type declarations are
+ # not. Binding them would resolve every call through this package to a
+ # signature with no body.
+ _setup_workspace(
+ tmp_path,
+ "@org/ui",
+ {
+ "exports": {
+ ".": {"import": "./dist/index.js", "types": "./types/index.d.ts"}
+ }
+ },
+ )
+ ctx = _ctx(tmp_path, ["packages/ui/types/index.d.ts"])
+ assert resolve_via_workspaces("@org/ui", ctx) is None
+
+ def test_wildcard_key_does_not_fall_back_to_a_fixed_target(
+ self, tmp_path: Path
+ ) -> None:
+ # The fixed target would answer for every subpath under the key, so
+ # two distinct imports would collapse onto one unrelated file.
+ _setup_workspace(
+ tmp_path,
+ "@org/ui",
+ {
+ "exports": {
+ "./features/*": {
+ "import": "./src/features/*.mjs",
+ "custom": "./src/shared.ts",
+ }
+ }
+ },
+ )
+ ctx = _ctx(tmp_path, ["packages/ui/src/shared.ts", "packages/ui/src/features/a.ts"])
+ assert resolve_via_workspaces("@org/ui/features/a", ctx) != "packages/ui/src/shared.ts"
+
+ def test_bare_package_falls_back_to_source_entry(self, tmp_path: Path) -> None:
+ # No ``exports`` at all and every manifest field names a build
+ # directory the repository does not contain, so the import became an
+ # external node while the sources sat beside it.
+ _setup_workspace(
+ tmp_path,
+ "@org/ui",
+ {
+ "main": "./dist/ui.cjs",
+ "module": "./dist/ui.js",
+ "types": "./types/index.d.ts",
+ },
+ )
+ ctx = _ctx(tmp_path, ["packages/ui/src/index.ts"])
+ assert resolve_via_workspaces("@org/ui", ctx) == "packages/ui/src/index.ts"
+
+ def test_source_entry_fallback_does_not_displace_a_resolving_main(
+ self, tmp_path: Path
+ ) -> None:
+ _setup_workspace(tmp_path, "@org/ui", {"main": "./entry.ts"})
+ ctx = _ctx(tmp_path, ["packages/ui/entry.ts", "packages/ui/src/index.ts"])
+ assert resolve_via_workspaces("@org/ui", ctx) == "packages/ui/entry.ts"
+
def test_exports_bare_dot_root(self, tmp_path: Path) -> None:
_setup_workspace(
tmp_path,