Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 26 additions & 8 deletions scripts/scip_harness/run_typescript_delta.sh
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,11 @@ if [[ -n "${SCIP_TS_PROJECTS:-}" ]]; then
SCIP_TS_PATHS=0 # the dist-export rewrite is for an unbuilt workspace, not named projects
elif discovered=$("$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" discover "$CHECKOUT") && [[ -n "$discovered" ]]; then
# umbrella root tsconfig: index member projects instead of loading the root.
# One path per line (a member directory may contain a space).
# One path per line (a member directory may contain a space). SCIP_TS_PATHS
# stays as configured: the rewrite lands in the config each member is indexed
# through, and in an unbuilt workspace it resolves imports between members.
mapfile -t PROJECTS <<<"$discovered"
Comment thread
zlareb1 marked this conversation as resolved.
Resolved
WORKSPACES=""
SCIP_TS_PATHS=0
fi
# Ownership uses the full discovered set even when a delta indexes a subset,
# so a root-level tsconfig cannot keep documents a more specific member owns.
Expand Down Expand Up @@ -103,21 +104,28 @@ PYEOF
fi
fi

# paths_rewrite [tsconfig...]: scip_ts_paths.py over the given configs, or
# over every workspace package's tsconfig.json when none is given; the same
# files are restored on exit.
paths_rewrite() {
local args=("$CHECKOUT") cfg
for cfg in "$@"; do args+=(--config "$cfg"); done
"$PYTHON" "$HARNESS_DIR/scip_ts_paths.py" "${args[@]}" >&2
# shellcheck disable=SC2016 # $PYTHON and $HARNESS_DIR expand when the exit hook runs
on_exit '"$PYTHON" "$HARNESS_DIR/scip_ts_paths.py" '"$(printf '%q ' "${args[@]}")"'--restore >/dev/null 2>&1'
}

# index_workspace: scip-typescript over the checkout into $WORK/index.scip.
# Everything it writes into the tree (the tsconfig paths, a named project's
# tsconfig.scip.json and package.json stub) is undone on exit.
index_workspace() {
local targets=() proj
if [[ "$SCIP_TS_PATHS" == "1" ]]; then
"$PYTHON" "$HARNESS_DIR/scip_ts_paths.py" "$CHECKOUT" >&2
# shellcheck disable=SC2016 # expanded when the exit hook runs
on_exit '"$PYTHON" "$HARNESS_DIR/scip_ts_paths.py" "$CHECKOUT" --restore >/dev/null 2>&1'
fi
local targets=() configs=() proj
for proj in "${PROJECTS[@]}"; do
proj=${proj%/}
# An umbrella reference may name a tsconfig file (e.g. tsconfig.build.json).
if [[ -f "$proj" ]]; then
targets+=("$proj")
configs+=("$proj")
continue
fi
[[ -d "$proj" ]] || {
Expand All @@ -126,6 +134,7 @@ index_workspace() {
}
if [[ -f "$proj/tsconfig.json" ]]; then
targets+=("$proj")
configs+=("$proj/tsconfig.json")
continue
fi
on_exit "rm -f $(printf %q "$proj/tsconfig.scip.json")"
Expand All @@ -140,7 +149,16 @@ JSONEOF
printf '{"name": "scip-%s", "version": "0.0.0", "private": true}\n' "${proj//\//-}" >"$proj/package.json"
fi
targets+=("$proj/tsconfig.scip.json")
configs+=("$proj/tsconfig.scip.json")
done
if [[ "$SCIP_TS_PATHS" == "1" ]]; then
# A member list rewrites exactly the configs the indexer is given.
if [[ ${#ALL_PROJECTS[@]} -eq 0 ]]; then
paths_rewrite
elif [[ ${#configs[@]} -gt 0 ]]; then
Comment thread
zlareb1 marked this conversation as resolved.
Resolved
paths_rewrite "${configs[@]}"
fi
fi
local ws=()
[[ -n "$WORKSPACES" ]] && ws=("$WORKSPACES")
# One indexer process per member: scip-typescript walks every target in a
Expand Down
268 changes: 226 additions & 42 deletions scripts/scip_harness/scip_ts_paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,19 @@
package's `exports` (and `main` / `types`), mapping each specifier to the
SOURCE file the build target came from (`dist/` → `src/`, `.js` → `.ts` /
`.tsx`, an existing file wins), and writes them into the consumer packages'
`tsconfig.json` — a backup `tsconfig.json.scip-bak` sits beside each, and
`--restore` puts the originals back. Run it before `scip-typescript index`
`tsconfig.json`, or into the files `--config` names, which are the configs
the indexer is given — a backup `<name>.scip-bak` sits beside each, and
`--restore` with the same arguments puts the originals back. Each config is
computed from the configs as the project wrote them, so one that extends a
config rewritten in the same pass gets the same entries in either order, and
never the entries added for that parent. A `paths` written into a tsconfig
replaces the one its `extends` chain set, so the aliases in effect are
carried over, and the added entries are written against the `baseUrl` in
effect, which is left as it is. An entry is left out when an alias in effect
already matches its specifier. Run it before `scip-typescript index`
on a checkout that has no build output; skip it on a built checkout.

python scip_ts_paths.py <checkout> [--restore] [--dry-run]
python scip_ts_paths.py <checkout> [--config <tsconfig>]... [--restore] [--dry-run]
"""

from __future__ import annotations
Expand All @@ -26,11 +34,14 @@
import os
import re
import sys
from collections.abc import Iterable
from pathlib import Path
from typing import Any

_BUILD_DIRS = ("dist", "build", "lib", "out", "esm", "cjs")
_SRC_EXTS = (".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs")
_CONDITIONS = ("types", "import", "module", "default", "require", "node")
_CONFIG_DIR = "${configdir}"


def _pick(target):
Expand Down Expand Up @@ -121,9 +132,19 @@ def _expand_pattern(pkg_dir: Path, key: str, target: str) -> list[tuple[str, str
return out


def paths_for(consumer_dir: Path, packages: list[tuple[str, Path, dict]]) -> dict[str, list[str]]:
def _relative(path: Path, base: Path, dotted: bool) -> str:
"""`path` relative to `base`; `dotted` writes the leading `./` that a
`paths` entry needs when no `baseUrl` is in effect."""
rel = os.path.relpath(path, base).replace(os.sep, "/")
return "./" + rel if dotted and not rel.startswith("../") and rel != ".." else rel


def paths_for(
consumer_dir: Path, packages: list[tuple[str, Path, dict]], base_url: Path | None = None
) -> dict[str, list[str]]:
"""{specifier: [relative source path]} for every exported subpath of
every OTHER workspace package, relative to the consumer's tsconfig."""
every OTHER workspace package, relative to the `baseUrl` in effect, or
to the consumer's tsconfig when there is none."""
paths: dict[str, list[str]] = {}
for name, pkg_dir, data in packages:
if pkg_dir == consumer_dir:
Expand Down Expand Up @@ -153,59 +174,222 @@ def paths_for(consumer_dir: Path, packages: list[tuple[str, Path, dict]]) -> dic
if src is None:
continue
spec = name if key == "." else name + key[1:]
paths[spec] = [os.path.relpath(src, consumer_dir).replace(os.sep, "/")]
paths[spec] = [_relative(src, base_url or consumer_dir, base_url is None)]
return paths


def _config_text(path: Path) -> str:
"""A tsconfig as the project wrote it: the backup of one this script
has patched, else the file itself."""
backup = path.with_name(path.name + ".scip-bak")
return (backup if backup.is_file() else path).read_text(encoding="utf-8")


def _parse_tsconfig(text: str) -> dict[str, Any] | None:
# TypeScript reads a file without its byte order mark, which json rejects
text = text.removeprefix("\ufeff")
# tsconfig allows comments and trailing commas; strip them for json
# (outside string literals: `"@/*"` is a path pattern, not a comment)
stripped = re.sub(
r'("(?:\\.|[^"\\])*")|//[^\n]*|/\*.*?\*/',
lambda m: m.group(1) or "",
text,
flags=re.S,
)
stripped = re.sub(
r'("(?:\\.|[^"\\])*")|,(?=\s*[}\]])',
lambda m: m.group(1) or "",
stripped,
)
try:
cfg = json.loads(stripped)
except ValueError:
return None
return cfg if isinstance(cfg, dict) else None


def _extends_target(spec: str, from_dir: Path) -> Path | None:
"""The file an `extends` entry names: a path from the extending config,
or a config under `node_modules` found by its path. A package that names
its config through `exports` or a `tsconfig` field is not resolved."""
if spec.startswith((".", "/")):
bases = [from_dir / spec]
else:
bases = [d / "node_modules" / spec for d in (from_dir, *from_dir.parents)]
for base in bases:
for cand in (base, base.with_name(base.name + ".json"), base / "tsconfig.json"):
if cand.is_file():
return cand
return None


def _has_config_dir(value: str) -> bool:
"""TypeScript matches the `${configDir}` template in any case."""
return value[: len(_CONFIG_DIR)].lower() == _CONFIG_DIR


def _from_config(value: str, cfg_dir: Path, leaf_dir: Path) -> Path:
"""A relative option value as a directory: from the config that wrote
it, or from the extending config for `${configDir}`."""
if _has_config_dir(value):
return Path(os.path.normpath(leaf_dir / value[len(_CONFIG_DIR) :].lstrip("/")))
return Path(os.path.normpath(cfg_dir / value))


class ExtendsNotFollowed(Exception):
"""An `extends` entry that cannot be resolved or parsed: the options it
would give are unknown, so a `paths` written over them could replace
aliases this script cannot see."""


def effective_options(
cfg: dict[str, Any], cfg_dir: Path, leaf_dir: Path, seen: frozenset[Path] = frozenset()
) -> tuple[dict[str, Any] | None, Path, Path | None]:
"""(`paths`, the directory its entries resolve from without a `baseUrl`,
the `baseUrl` directory) in effect for a tsconfig. Each option comes from
the last config in the `extends` chain that sets it, whole. `seen` holds
the configs being walked: one met again is skipped, as TypeScript's
resolution stack does (TS18000). Raises `ExtendsNotFollowed`."""
paths: dict[str, Any] | None = None
paths_dir, base_url = cfg_dir, None
ext = cfg.get("extends")
specs = [ext] if isinstance(ext, str) else ext if isinstance(ext, list) else []
for spec in specs:
target = _extends_target(spec, cfg_dir) if isinstance(spec, str) else None
if target is not None and target.resolve() in seen:
continue
try:
parent = _parse_tsconfig(_config_text(target)) if target else None
except OSError:
parent = None
if target is None or parent is None:
raise ExtendsNotFollowed(str(spec))
p, p_dir, b = effective_options(parent, target.parent, leaf_dir, seen | {target.resolve()})
if p is not None:
paths, paths_dir = p, p_dir
if b is not None:
base_url = b
co = cfg.get("compilerOptions")
if isinstance(co, dict):
if isinstance(co.get("paths"), dict):
paths, paths_dir = co["paths"], cfg_dir
if isinstance(co.get("baseUrl"), str):
base_url = _from_config(co["baseUrl"], cfg_dir, leaf_dir)
return paths, paths_dir, base_url


def _rebased(paths: dict[str, Any], from_dir: Path, to_dir: Path) -> dict[str, Any]:
"""Inherited `paths` entries, which resolve from the config that wrote
them when no `baseUrl` is set, rewritten to resolve from `to_dir`."""
if from_dir == to_dir:
return dict(paths)
out: dict[str, Any] = {}
for key, targets in paths.items():
if not isinstance(targets, list):
out[key] = targets
continue
out[key] = [
_relative(Path(os.path.normpath(from_dir / t)), to_dir, True)
if isinstance(t, str) and not _has_config_dir(t) and not os.path.isabs(t)
else t
for t in targets
]
return out


def _matched(spec: str, keys: Iterable[str]) -> bool:
"""Whether a `paths` key already takes `spec`: the key itself, or a
pattern with one `*` whose prefix and suffix fit around it. TypeScript
tries an exact key first and then the matching pattern with the longest
prefix (`matchPatternOrExact`), so an added exact key would take the
specifier from any of them. A key with two stars matches nothing."""
for key in keys:
prefix, star, suffix = key.partition("*")
if not star:
if key == spec:
return True
elif (
"*" not in suffix
and len(spec) >= len(prefix) + len(suffix)
and spec.startswith(prefix)
and spec.endswith(suffix)
):
return True
return False


def _owner(cfg_dir: Path, packages: list[tuple[str, Path, dict[str, Any]]]) -> Path | None:
"""The directory of the innermost workspace package holding a config."""
holders = [d for _n, d, _ in packages if cfg_dir == d or d in cfg_dir.parents]
return max(holders, key=lambda d: len(d.parts), default=None)


def _patch(
tsconfig: Path, root: Path, packages: list[tuple[str, Path, dict[str, Any]]], dry: bool
) -> bool:
"""Write the workspace entries into one tsconfig; whether it changed."""
cfg_dir = tsconfig.parent
cfg = _parse_tsconfig(_config_text(tsconfig))
if cfg is None:
print(f"skip {tsconfig}: not parseable", file=sys.stderr)
return False
try:
existing, existing_dir, base_url = effective_options(
cfg, cfg_dir, cfg_dir, frozenset({tsconfig.resolve()})
)
except ExtendsNotFollowed as err:
print(f"skip {tsconfig}: extends not followed ({err})", file=sys.stderr)
return False
owner = _owner(cfg_dir, packages)
paths = paths_for(cfg_dir, [p for p in packages if p[1] != owner], base_url)
# a specifier an alias in effect matches keeps that alias
paths = {k: v for k, v in paths.items() if not _matched(k, existing or {})}
if not paths:
return False
if existing and base_url is None:
existing = _rebased(existing, existing_dir, cfg_dir)
co = cfg.setdefault("compilerOptions", {})
# the aliases already in effect win; the baseUrl in effect stays
co["paths"] = {**paths, **(existing or {})}
rel = os.path.relpath(tsconfig, root).replace(os.sep, "/")
print(f"{rel}: +{len(paths)} paths")
if dry:
return False
backup = tsconfig.with_name(tsconfig.name + ".scip-bak")
if not backup.exists():
backup.write_bytes(tsconfig.read_bytes())
tsconfig.write_text(json.dumps(cfg, indent=2) + "\n", encoding="utf-8")
return True


def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("checkout")
ap.add_argument(
"--config",
action="append",
default=[],
help="a tsconfig to patch, relative to the checkout (repeatable); "
"default: every workspace package's tsconfig.json",
)
ap.add_argument("--restore", action="store_true")
ap.add_argument("--dry-run", action="store_true")
args = ap.parse_args()
root = Path(args.checkout).resolve()
packages = workspace_packages(root)
if args.config:
configs = list(dict.fromkeys(Path(os.path.normpath(root / c)) for c in args.config))
else:
configs = [pkg_dir / "tsconfig.json" for _n, pkg_dir, _d in packages]
changed = 0
for _name, pkg_dir, _data in packages:
tsconfig = pkg_dir / "tsconfig.json"
backup = pkg_dir / "tsconfig.json.scip-bak"
for tsconfig in configs:
backup = tsconfig.with_name(tsconfig.name + ".scip-bak")
if args.restore:
if backup.exists():
backup.replace(tsconfig)
changed += 1
continue
if not tsconfig.exists():
continue
paths = paths_for(pkg_dir, packages)
if not paths:
continue
text = tsconfig.read_text(encoding="utf-8")
# tsconfig allows comments and trailing commas; strip them for json
# (outside string literals: `"@/*"` is a path pattern, not a comment)
stripped = re.sub(
r'("(?:\\.|[^"\\])*")|//[^\n]*|/\*.*?\*/',
lambda m: m.group(1) or "",
text,
flags=re.S,
)
stripped = re.sub(r",(\s*[}\]])", r"\1", stripped)
try:
cfg = json.loads(stripped)
except ValueError:
print(f"skip {tsconfig}: not parseable", file=sys.stderr)
continue
co = cfg.setdefault("compilerOptions", {})
existing = co.get("paths") or {}
co["paths"] = {**paths, **existing} # a package's own aliases win
co.setdefault("baseUrl", ".")
if args.dry_run:
print(f"{tsconfig.relative_to(root)}: +{len(paths)} paths")
continue
if not backup.exists():
backup.write_text(text, encoding="utf-8")
tsconfig.write_text(json.dumps(cfg, indent=2) + "\n", encoding="utf-8")
changed += 1
print(f"{tsconfig.relative_to(root)}: +{len(paths)} paths")
elif tsconfig.exists():
changed += _patch(tsconfig, root, packages, args.dry_run)
print(f"{'restored' if args.restore else 'patched'} {changed} tsconfig(s)")
return 0

Expand Down
Loading
Loading