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): resolve TS workspace members from pnpm-workspace.yaml (#1454)

Alex Mitelman73116e4df224
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/pnpm_workspace.py b/packages/core/src/repowise/core/ingestion/resolvers/pnpm_workspace.py
new file mode 100644
index 000000000..4136e0b5a
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/resolvers/pnpm_workspace.py
@@ -0,0 +1,71 @@
+"""``pnpm-workspace.yaml`` member-glob reading.
+
+Separate from ``ts_workspace`` because it is a manifest reader rather than
+part of import resolution — the same split the other package managers get
+(``rust_workspace``, ``go_workspace``, ``php_composer``, ``scala_build``).
+``ts_workspace`` consumes the globs this returns.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+# pnpm names this file exactly. ``.yml`` is a long-standing request
+# (pnpm/pnpm#1380), not a supported spelling — honouring it would map
+# members from a manifest pnpm itself ignores.
+PNPM_WORKSPACE_FILENAME = "pnpm-workspace.yaml"
+
+
+def read_pnpm_workspace_patterns(repo_path: Path) -> tuple[list[str], list[str]] | None:
+ """Return ``(includes, excludes)`` member globs from ``pnpm-workspace.yaml``.
+
+ ``None`` means "not a pnpm workspace" — the manifest is absent or could
+ not be parsed. That is distinct from ``([], [])``, which means "a pnpm
+ workspace that declares no member globs", i.e. root-only: pnpm's
+ ``packages`` setting is optional and "if the field is omitted, only the
+ root package is included in the workspace". Since pnpm 10 the same file
+ also holds ``catalog``, ``onlyBuiltDependencies`` and other settings, so
+ a manifest with no ``packages`` key is normal rather than an error.
+
+ pnpm ignores ``package.json``'s ``workspaces`` field entirely, so a pnpm
+ monorepo declares its members only here::
+
+ packages:
+ - "apps/*"
+ - "packages/*"
+ - "!**/__fixtures__/**"
+
+ A leading ``!`` negates the pattern. Negated entries come back separately
+ because the caller applies them by expanding them the same way it expands
+ the includes and subtracting the result — see
+ :func:`~repowise.core.ingestion.resolvers.ts_workspace.build_workspace_info`.
+ """
+ import yaml
+
+ manifest = repo_path / PNPM_WORKSPACE_FILENAME
+ if not manifest.is_file():
+ return None
+ try:
+ data = yaml.safe_load(manifest.read_text(encoding="utf-8", errors="ignore"))
+ except Exception:
+ return None
+ if not isinstance(data, dict):
+ return None
+ entries = data.get("packages")
+ if not isinstance(entries, list):
+ # A settings-only manifest (catalog, onlyBuiltDependencies, ...) is
+ # still a pnpm workspace — root-only.
+ return [], []
+ includes: list[str] = []
+ excludes: list[str] = []
+ for entry in entries:
+ if not isinstance(entry, str):
+ continue
+ pattern = entry.strip()
+ if pattern.startswith("!"):
+ negated = pattern[1:].strip()
+ if negated:
+ excludes.append(negated)
+ elif pattern:
+ includes.append(pattern)
+ return includes, excludes
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 783d64b1f..58120bf01 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py
@@ -1,10 +1,15 @@
"""npm/yarn/pnpm workspace package resolution for TypeScript imports.
Reads the root ``package.json``'s ``workspaces`` field (string list or
-``{"packages": [...]}`` form), expands glob patterns, and reads each
-sibling package's ``name`` field. The resulting ``{pkg_name: dir_posix}``
-map lets the TS resolver turn ``import x from "@myorg/foo"`` into the
-correct intra-repo file rather than an ``external:`` node.
+``{"packages": [...]}`` form) and ``pnpm-workspace.yaml``'s ``packages``
+list, expands glob patterns, and reads each sibling package's ``name``
+field. The resulting ``{pkg_name: dir_posix}`` map lets the TS resolver
+turn ``import x from "@myorg/foo"`` into the correct intra-repo file
+rather than an ``external:`` node.
+
+Both manifests are consulted because they are not interchangeable: pnpm
+does not read the ``workspaces`` field at all, so a pnpm monorepo
+declares its members only in ``pnpm-workspace.yaml``.
Subpath imports (``@myorg/foo/bar/baz``) honour Node.js ``"exports"``
subpath patterns when the workspace's ``package.json`` declares them:
@@ -24,12 +29,16 @@ flattened to the first plausible source target. Packages without an
from __future__ import annotations
+import contextlib
import json
+import posixpath
import re
from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING, Any
+from .pnpm_workspace import read_pnpm_workspace_patterns
+
if TYPE_CHECKING:
from .context import ResolverContext
@@ -232,11 +241,89 @@ def _read_workspaces_field(pkg_data: dict) -> list[str]:
def build_workspace_map(repo_path: Path | None) -> dict[str, str]:
"""Return ``{package_name: dir_posix}`` for every workspace package.
- Empty dict if no root ``package.json`` or no ``workspaces`` field.
+ Empty dict when neither ``package.json``'s ``workspaces`` field nor
+ ``pnpm-workspace.yaml`` declares any members.
"""
return {name: info["dir"] for name, info in build_workspace_info(repo_path).items()}
+@dataclass(frozen=True)
+class _WorkspaceDeclaration:
+ """Which globs govern a repo's workspace, and whether the root is a member."""
+
+ includes: tuple[str, ...]
+ excludes: tuple[str, ...]
+ include_root: bool
+
+ @property
+ def is_empty(self) -> bool:
+ return not self.includes and not self.include_root
+
+
+def _read_workspace_declaration(repo_path: Path) -> _WorkspaceDeclaration:
+ """Resolve the governing manifest into member globs.
+
+ pnpm keeps its member globs in ``pnpm-workspace.yaml`` and does not read
+ ``package.json``'s ``workspaces`` field at all, so the two manifests are
+ not interchangeable and must not be merged: unioning them would register a
+ member pnpm never installs, turning a registry dependency into a fake
+ intra-repo edge. When the pnpm manifest is present it is authoritative.
+ """
+ pnpm = read_pnpm_workspace_patterns(repo_path)
+ if pnpm is not None:
+ includes, excludes = pnpm
+ # "The root package is always included, even when custom location
+ # wildcards are used" — pnpm's ``packages`` setting. So a root-only
+ # workspace (no ``packages`` key) still has exactly one member.
+ return _WorkspaceDeclaration(tuple(includes), tuple(excludes), include_root=True)
+
+ root_pkg = repo_path / "package.json"
+ if not root_pkg.is_file():
+ return _WorkspaceDeclaration((), (), include_root=False)
+ try:
+ data = json.loads(root_pkg.read_text(encoding="utf-8", errors="ignore"))
+ except Exception:
+ return _WorkspaceDeclaration((), (), include_root=False)
+ if not isinstance(data, dict):
+ return _WorkspaceDeclaration((), (), include_root=False)
+ return _WorkspaceDeclaration(
+ tuple(_read_workspaces_field(data)), (), include_root=False
+ )
+
+
+def _expand_member_dirs(repo_path: Path, declared: _WorkspaceDeclaration) -> list[Path]:
+ """Expand member globs to directories, minus the negated ones.
+
+ Negated entries are expanded with the SAME globber as the includes and
+ subtracted, rather than matched with a second pattern language. ``pathspec``
+ was the obvious candidate and is wrong here: it implements git-ignore
+ semantics, under which a slashless ``foo`` matches at any depth and a
+ directory match swallows its descendants, so ``!foo`` and ``!packages/*``
+ would silently drop members pnpm keeps. ``Path.glob`` anchors at the repo
+ root and honours single-segment ``*``, which is what fast-glob (pnpm's
+ matcher) does for these forms.
+
+ The root, when it is a member, is never subject to the negated patterns.
+
+ Both loops tolerate a pattern ``Path.glob`` refuses: the strings come from
+ a hand-written manifest, and an absolute entry raises ``NotImplementedError``
+ while an empty one raises ``ValueError``. A bad entry drops itself rather
+ than the whole workspace, which is how every other manifest read in this
+ module already behaves.
+ """
+ excluded: set[Path] = set()
+ for pattern in declared.excludes:
+ with contextlib.suppress(NotImplementedError, ValueError):
+ excluded.update(p for p in repo_path.glob(pattern) if p.is_dir())
+
+ dirs: list[Path] = [repo_path] if declared.include_root else []
+ for pattern in declared.includes:
+ with contextlib.suppress(NotImplementedError, ValueError):
+ globbed = [repo_path] if pattern == "." else repo_path.glob(pattern)
+ dirs.extend(p for p in globbed if p.is_dir() and p not in excluded)
+ return dirs
+
+
def build_workspace_info(repo_path: Path | None) -> dict[str, dict[str, Any]]:
"""Return ``{pkg_name: {"dir": <posix>, "exports": {...}, "main": str|None}}``.
@@ -248,47 +335,34 @@ def build_workspace_info(repo_path: Path | None) -> dict[str, dict[str, Any]]:
"""
if repo_path is None or not repo_path.is_dir():
return {}
- root_pkg = repo_path / "package.json"
- if not root_pkg.is_file():
- return {}
- try:
- data = json.loads(root_pkg.read_text(encoding="utf-8", errors="ignore"))
- except Exception:
- return {}
- if not isinstance(data, dict):
- return {}
- patterns = _read_workspaces_field(data)
- if not patterns:
+ declared = _read_workspace_declaration(repo_path)
+ if declared.is_empty:
return {}
result: dict[str, dict[str, Any]] = {}
- for pattern in patterns:
- ws_dirs = [repo_path] if pattern == "." else repo_path.glob(pattern)
- for ws_dir in ws_dirs:
- if not ws_dir.is_dir():
- continue
- ws_pkg = ws_dir / "package.json"
- if not ws_pkg.is_file():
- continue
- try:
- ws_data = json.loads(ws_pkg.read_text(encoding="utf-8", errors="ignore"))
- except Exception:
- continue
- if not isinstance(ws_data, dict):
- continue
- name = ws_data.get("name")
- if not isinstance(name, str) or not name:
- continue
- try:
- rel = ws_dir.relative_to(repo_path).as_posix()
- except ValueError:
- continue
- result[name] = {
- "dir": rel,
- "exports": _build_exports_map(ws_data),
- "main": ws_data.get("module") if isinstance(ws_data.get("module"), str)
- else (ws_data.get("main") if isinstance(ws_data.get("main"), str) else None),
- }
+ for ws_dir in _expand_member_dirs(repo_path, declared):
+ try:
+ rel = ws_dir.relative_to(repo_path).as_posix()
+ except ValueError:
+ continue
+ ws_pkg = ws_dir / "package.json"
+ if not ws_pkg.is_file():
+ continue
+ try:
+ ws_data = json.loads(ws_pkg.read_text(encoding="utf-8", errors="ignore"))
+ except Exception:
+ continue
+ if not isinstance(ws_data, dict):
+ continue
+ name = ws_data.get("name")
+ if not isinstance(name, str) or not name:
+ continue
+ result[name] = {
+ "dir": rel,
+ "exports": _build_exports_map(ws_data),
+ "main": ws_data.get("module") if isinstance(ws_data.get("module"), str)
+ else (ws_data.get("main") if isinstance(ws_data.get("main"), str) else None),
+ }
return result
@@ -313,6 +387,35 @@ _PROBE_EXTENSIONS: tuple[str, ...] = (
)
+def _normalize_repo_rel(base: str) -> str:
+ """Collapse a joined repo-relative path so it can match ``path_set``.
+
+ Callers build candidates as ``f"{pkg_dir}/{sub}"``, and the workspace
+ ROOT's dir is ``"."`` (pnpm always includes the root; npm/yarn repos may
+ list ``"."`` explicitly). That join yields ``"./src/index.ts"``, which
+ never equals the repo-relative ``"src/index.ts"`` a path set holds — so
+ without this every root-package import silently failed to resolve.
+
+ A trailing slash survives: one caller uses the result as a ``startswith``
+ prefix, where dropping it would let ``src/locales`` also match
+ ``src/locales-old``.
+
+ A path that collapses ENTIRELY to the root (``"./"`` — the root package's
+ ``"."`` joined with an empty subpath) normalizes to ``""``, not ``"./"``:
+ ``posixpath.normpath("./")`` is ``"."``, and re-appending the slash would
+ leave a prefix no repo-relative path starts with. That case is reachable
+ from ``_expand_exports_wildcard`` whenever a root package's wildcard
+ target sits at the repo root (``{"./*": "./*.ts"}``) rather than under a
+ subdirectory, and it silently dropped every match.
+ """
+ if not (base.startswith("./") or "/./" in base):
+ return base
+ normalized = posixpath.normpath(base)
+ if normalized == ".":
+ return ""
+ return f"{normalized}/" if base.endswith("/") and not normalized.endswith("/") else normalized
+
+
def _probe_path(base: str, path_set: set[str]) -> str | None:
"""Locate a concrete file for ``base`` (a repo-relative path stem).
@@ -321,6 +424,7 @@ def _probe_path(base: str, path_set: set[str]) -> str | None:
pattern). Then probes common TS/JS extensions and ``index.*``
children so directory-shaped specifiers resolve to a barrel file.
"""
+ base = _normalize_repo_rel(base)
if base in path_set:
return base
for ext in _PROBE_EXTENSIONS:
@@ -445,7 +549,10 @@ def _expand_exports_wildcard(
# suffix=``.ts``. The Node spec only allows one ``*`` per pattern.
stripped = target.lstrip("./")
prefix, _, suffix = stripped.partition("*")
- base_prefix = f"{pkg_dir}/{prefix}"
+ # Normalized because this is a startswith probe rather than a _probe_path
+ # lookup — a root package's ``"."`` dir would otherwise make every
+ # candidate fail the prefix test.
+ base_prefix = _normalize_repo_rel(f"{pkg_dir}/{prefix}")
matches: set[str] = set()
for candidate in path_set:
if not candidate.startswith(base_prefix):
diff --git a/tests/unit/ingestion/test_typescript_resolver.py b/tests/unit/ingestion/test_typescript_resolver.py
index 8cb290cfc..a4ad9f371 100644
--- a/tests/unit/ingestion/test_typescript_resolver.py
+++ b/tests/unit/ingestion/test_typescript_resolver.py
@@ -10,6 +10,8 @@ import pytest
from repowise.core.ingestion.resolvers.context import ResolverContext
from repowise.core.ingestion.resolvers.ts_workspace import (
+ _normalize_repo_rel,
+ build_ts_workspace_index,
build_workspace_map,
resolve_via_workspaces,
)
@@ -99,6 +101,238 @@ class TestWorkspaceMap:
def test_empty_when_no_root_package(self, tmp_path: Path) -> None:
assert build_workspace_map(tmp_path) == {}
+ def test_empty_workspaces_entry_drops_itself_not_the_workspace(
+ self, tmp_path: Path
+ ) -> None:
+ # ``Path.glob("")`` raises ValueError. Unlike the pnpm reader, which
+ # drops blank entries before they reach the globber, the ``workspaces``
+ # field passes every string straight through — so the guard in
+ # ``_expand_member_dirs`` is what keeps one blank entry from costing
+ # the whole map.
+ (tmp_path / "package.json").write_text(
+ json.dumps({"workspaces": ["", "packages/*"]})
+ )
+ pkg = tmp_path / "packages" / "a"
+ pkg.mkdir(parents=True)
+ (pkg / "package.json").write_text(json.dumps({"name": "@org/a"}))
+ assert build_workspace_map(tmp_path) == {"@org/a": "packages/a"}
+
+
+class TestPnpmWorkspaceMap:
+ """pnpm declares members in ``pnpm-workspace.yaml``, never in ``workspaces``."""
+
+ def _pkg(self, tmp_path: Path, rel: str, name: str) -> None:
+ pkg_dir = tmp_path / rel
+ pkg_dir.mkdir(parents=True)
+ (pkg_dir / "package.json").write_text(json.dumps({"name": name}))
+
+ def _root(self, tmp_path: Path) -> None:
+ """An unnamed private root, the common pnpm shape — not a member."""
+ (tmp_path / "package.json").write_text(json.dumps({"private": True}))
+
+ def test_pnpm_workspace_yaml_is_read(self, tmp_path: Path) -> None:
+ # A pnpm root package.json carries no ``workspaces`` field at all.
+ self._root(tmp_path)
+ (tmp_path / "pnpm-workspace.yaml").write_text(
+ 'packages:\n - "apps/*"\n - "packages/*"\n'
+ )
+ self._pkg(tmp_path, "apps/console", "@org/console")
+ self._pkg(tmp_path, "packages/domain", "@org/domain")
+ assert build_workspace_map(tmp_path) == {
+ "@org/console": "apps/console",
+ "@org/domain": "packages/domain",
+ }
+
+ def test_named_root_is_a_member(self, tmp_path: Path) -> None:
+ # "The root package is always included, even when custom location
+ # wildcards are used" — pnpm's ``packages`` setting.
+ (tmp_path / "package.json").write_text(json.dumps({"name": "@org/root"}))
+ (tmp_path / "pnpm-workspace.yaml").write_text('packages:\n - "packages/*"\n')
+ self._pkg(tmp_path, "packages/a", "@org/a")
+ assert build_workspace_map(tmp_path) == {
+ "@org/root": ".",
+ "@org/a": "packages/a",
+ }
+
+ def test_root_is_not_subject_to_negation(self, tmp_path: Path) -> None:
+ (tmp_path / "package.json").write_text(json.dumps({"name": "@org/root"}))
+ (tmp_path / "pnpm-workspace.yaml").write_text(
+ 'packages:\n - "packages/*"\n - "!**"\n'
+ )
+ assert build_workspace_map(tmp_path) == {"@org/root": "."}
+
+ def test_yml_extension_is_not_a_pnpm_manifest(self, tmp_path: Path) -> None:
+ # pnpm reads only ``pnpm-workspace.yaml``; ``.yml`` is an open request
+ # (pnpm/pnpm#1380). Honouring it would map members pnpm never installs.
+ self._root(tmp_path)
+ (tmp_path / "pnpm-workspace.yml").write_text('packages:\n - "libs/*"\n')
+ self._pkg(tmp_path, "libs/core", "@org/core")
+ assert build_workspace_map(tmp_path) == {}
+
+ def test_non_glob_entry_resolved(self, tmp_path: Path) -> None:
+ # ``- scripts`` (a plain directory, no glob) is legal pnpm.
+ self._root(tmp_path)
+ (tmp_path / "pnpm-workspace.yaml").write_text("packages:\n - scripts\n")
+ self._pkg(tmp_path, "scripts", "@org/scripts")
+ assert build_workspace_map(tmp_path) == {"@org/scripts": "scripts"}
+
+ def test_negated_pattern_excludes_member(self, tmp_path: Path) -> None:
+ self._root(tmp_path)
+ (tmp_path / "pnpm-workspace.yaml").write_text(
+ 'packages:\n - "packages/**"\n - "!**/__fixtures__/**"\n'
+ )
+ self._pkg(tmp_path, "packages/real", "@org/real")
+ self._pkg(tmp_path, "packages/__fixtures__/fake", "@org/fake")
+ assert build_workspace_map(tmp_path) == {"@org/real": "packages/real"}
+
+ def test_slashless_negation_is_anchored_at_the_root(self, tmp_path: Path) -> None:
+ # fast-glob (pnpm's matcher) anchors a slashless pattern at the
+ # workspace root, so ``!fixtures`` must NOT drop packages/fixtures.
+ # git-ignore semantics would match it at any depth — the reason this
+ # is expanded with Path.glob rather than pathspec.
+ self._root(tmp_path)
+ (tmp_path / "pnpm-workspace.yaml").write_text(
+ 'packages:\n - "packages/*"\n - "!fixtures"\n'
+ )
+ self._pkg(tmp_path, "packages/fixtures", "@org/fixtures")
+ assert build_workspace_map(tmp_path) == {"@org/fixtures": "packages/fixtures"}
+
+ def test_negation_does_not_swallow_nested_members(self, tmp_path: Path) -> None:
+ # ``!packages/*`` excludes direct children only. Under git-ignore
+ # semantics a directory match also removes everything beneath it,
+ # which would wrongly drop packages/group/nested.
+ self._root(tmp_path)
+ (tmp_path / "pnpm-workspace.yaml").write_text(
+ 'packages:\n - "packages/**"\n - "!packages/*"\n'
+ )
+ self._pkg(tmp_path, "packages/top", "@org/top")
+ self._pkg(tmp_path, "packages/group/nested", "@org/nested")
+ assert build_workspace_map(tmp_path) == {"@org/nested": "packages/group/nested"}
+
+ def test_pnpm_manifest_wins_over_package_json_workspaces(self, tmp_path: Path) -> None:
+ # pnpm does not read the ``workspaces`` field, so a member declared
+ # only there is one pnpm never installs. Mapping it would invent an
+ # intra-repo edge for what is really a registry dependency.
+ (tmp_path / "package.json").write_text(
+ json.dumps({"private": True, "workspaces": ["legacy/*"]})
+ )
+ (tmp_path / "pnpm-workspace.yaml").write_text('packages:\n - "packages/*"\n')
+ self._pkg(tmp_path, "legacy/old", "@org/old")
+ self._pkg(tmp_path, "packages/new", "@org/new")
+ assert build_workspace_map(tmp_path) == {"@org/new": "packages/new"}
+
+ def test_catalog_only_manifest_is_a_root_only_workspace(self, tmp_path: Path) -> None:
+ # Since pnpm 10 the file also holds settings. ``packages`` is optional
+ # and "if the field is omitted, only the root package is included".
+ (tmp_path / "package.json").write_text(json.dumps({"name": "@org/root"}))
+ (tmp_path / "pnpm-workspace.yaml").write_text("catalog:\n react: ^19.0.0\n")
+ self._pkg(tmp_path, "packages/a", "@org/a")
+ assert build_workspace_map(tmp_path) == {"@org/root": "."}
+
+ def test_malformed_yaml_is_not_fatal(self, tmp_path: Path) -> None:
+ self._root(tmp_path)
+ (tmp_path / "pnpm-workspace.yaml").write_text("packages:\n - [unclosed\n")
+ assert build_workspace_map(tmp_path) == {}
+
+ @pytest.mark.parametrize("bad", ["/abs/packages/*", "!/abs/*"])
+ def test_unglobbable_entry_drops_itself_not_the_workspace(
+ self, tmp_path: Path, bad: str
+ ) -> None:
+ # ``Path.glob`` refuses an absolute pattern (NotImplementedError). The
+ # strings are manifest-supplied and this path runs unguarded under
+ # ``resolve_via_workspaces``, so a bad entry must cost its own member
+ # rather than every member. Both the include and the exclude loop.
+ self._root(tmp_path)
+ (tmp_path / "pnpm-workspace.yaml").write_text(
+ f'packages:\n - "packages/*"\n - "{bad}"\n'
+ )
+ self._pkg(tmp_path, "packages/a", "@org/a")
+ assert build_workspace_map(tmp_path) == {"@org/a": "packages/a"}
+
+ def test_resolves_import_through_pnpm_member(self, tmp_path: Path) -> None:
+ # The end-to-end claim: a member found only via pnpm-workspace.yaml
+ # still resolves through its own ``exports`` map, so a cross-package
+ # import becomes an intra-repo edge instead of an ``external:`` node.
+ self._root(tmp_path)
+ (tmp_path / "pnpm-workspace.yaml").write_text('packages:\n - "packages/*"\n')
+ pkg_dir = tmp_path / "packages" / "domain"
+ pkg_dir.mkdir(parents=True)
+ (pkg_dir / "package.json").write_text(
+ json.dumps({"name": "@org/domain", "exports": {".": "./src/index.ts"}})
+ )
+ ctx = _ctx(tmp_path, ["packages/domain/src/index.ts"])
+ assert resolve_via_workspaces("@org/domain", ctx) == "packages/domain/src/index.ts"
+
+
+class TestRootPackageResolution:
+ """A workspace member AT the repo root carries ``dir == "."``.
+
+ Joining that with a subpath yields ``./src/index.ts``, which never equals
+ the repo-relative ``src/index.ts`` a path set holds. These cover both
+ managers because the defect predates pnpm support: an npm/yarn repo
+ listing ``"."`` in ``workspaces`` mapped the member but never resolved it.
+ """
+
+ def test_npm_root_workspace_resolves_via_exports(self, tmp_path: Path) -> None:
+ (tmp_path / "package.json").write_text(
+ json.dumps(
+ {"name": "@org/root", "workspaces": ["."], "exports": {".": "./src/index.ts"}}
+ )
+ )
+ ctx = _ctx(tmp_path, ["src/index.ts"])
+ assert build_workspace_map(tmp_path) == {"@org/root": "."}
+ assert resolve_via_workspaces("@org/root", ctx) == "src/index.ts"
+
+ def test_pnpm_root_resolves_via_main(self, tmp_path: Path) -> None:
+ (tmp_path / "package.json").write_text(
+ json.dumps({"name": "@org/root", "main": "./src/entry.ts"})
+ )
+ (tmp_path / "pnpm-workspace.yaml").write_text("packages: []\n")
+ ctx = _ctx(tmp_path, ["src/entry.ts"])
+ assert resolve_via_workspaces("@org/root", ctx) == "src/entry.ts"
+
+ def test_root_subpath_import_resolves(self, tmp_path: Path) -> None:
+ (tmp_path / "package.json").write_text(json.dumps({"name": "@org/root"}))
+ (tmp_path / "pnpm-workspace.yaml").write_text("packages: []\n")
+ ctx = _ctx(tmp_path, ["src/util/date.ts"])
+ assert resolve_via_workspaces("@org/root/src/util/date", ctx) == "src/util/date.ts"
+
+ def test_root_exports_wildcard_expands(self, tmp_path: Path) -> None:
+ (tmp_path / "package.json").write_text(
+ json.dumps({"name": "@org/root", "exports": {"./lib/*": "./src/lib/*.ts"}})
+ )
+ (tmp_path / "pnpm-workspace.yaml").write_text("packages: []\n")
+ ctx = _ctx(tmp_path, ["src/lib/a.ts", "src/lib/b.ts", "src/other.ts"])
+ index = build_ts_workspace_index(ctx)
+ assert index.exports_entry_paths == {"src/lib/a.ts", "src/lib/b.ts"}
+
+ def test_root_exports_wildcard_at_repo_root_expands(self, tmp_path: Path) -> None:
+ """A root package whose wildcard target has NO directory prefix.
+
+ ``{"./*": "./*.ts"}`` on a ``dir == "."`` member joins to ``"./"``,
+ which collapses entirely to the repo root. The sibling test above
+ cannot see this: its ``./src/lib/*.ts`` target keeps a non-empty
+ ``src/lib/`` prefix, so the join never reaches the degenerate case.
+ Left unguarded the prefix stayed ``"./"``, no repo-relative path
+ started with it, and every wildcard-exported root file dropped out of
+ ``exports_entry_paths`` — a false-positive dead-code source.
+ """
+ (tmp_path / "package.json").write_text(
+ json.dumps({"name": "@org/root", "exports": {"./*": "./*.ts"}})
+ )
+ (tmp_path / "pnpm-workspace.yaml").write_text("packages: []\n")
+ ctx = _ctx(tmp_path, ["index.ts", "util.ts", "notes.md"])
+ index = build_ts_workspace_index(ctx)
+ assert index.exports_entry_paths == {"index.ts", "util.ts"}
+
+ def test_normalize_repo_rel_collapses_bare_root(self) -> None:
+ """The unit under the case above — ``"./"`` is the repo root, i.e. ``""``."""
+ assert _normalize_repo_rel("./") == ""
+ # Unchanged for every non-degenerate shape.
+ assert _normalize_repo_rel("./src/lib/") == "src/lib/"
+ assert _normalize_repo_rel("./src/index.ts") == "src/index.ts"
+ assert _normalize_repo_rel("pkgs/a/src/") == "pkgs/a/src/"
+
class TestWorkspaceResolution:
def test_resolves_workspace_subpath(self, tmp_path: Path) -> None: