File size: 7,799 Bytes
faff844 f235f15 9c293b0 551ecc9 9c293b0 faff844 a8b90d8 faff844 18a9f73 faff844 4f47fa3 faff844 dac2ca2 551ecc9 faff844 dac2ca2 551ecc9 dac2ca2 9c293b0 551ecc9 faff844 9c293b0 7fd5ae8 9c293b0 faff844 9c293b0 faff844 9c293b0 551ecc9 faff844 18a9f73 9c293b0 18a9f73 551ecc9 faff844 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 | """Fail when new production sources are outside existing strict type gates.
The JSON inventory is the explicit legacy debt, not a source exclusion from
basic checks. Removing an entry requires adding its file to a strict gate.
"""
from __future__ import annotations
import json
from pathlib import Path
import re
import shutil
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
DEBT_FILE = "quality/baselines/strict-inventory-debt.json"
STRICT_FRONTEND_PROJECTS = (
"config/types/jsconfig.strict.json",
"config/types/jsconfig.service-worker-strict.json",
"config/types/jsconfig.chapter-worker-strict.json",
)
REQUIRED_FRONTEND_FLAGS = (
"noUncheckedIndexedAccess", "exactOptionalPropertyTypes", "noImplicitOverride",
"noImplicitReturns", "noFallthroughCasesInSwitch", "noUnusedLocals", "noUnusedParameters",
)
def browser_sources(root: Path) -> set[str]:
return {path.relative_to(root).as_posix() for path in (root / "static").rglob("*")
if path.is_file() and path.suffix in (".js", ".mjs")
and path.relative_to(root).parts[:2] != ("static", "vendor")}
def backend_sources(root: Path) -> set[str]:
return {path.relative_to(root).as_posix() for path in (root / "backend").rglob("*.py")
if "__pycache__" not in path.relative_to(root).parts}
def inventory_errors(root: Path, js_strict: set[str], js_basic: set[str],
py_strict: set[str], debt: dict[str, list[str]],
previous_debt: dict[str, list[str]] | None = None) -> list[str]:
groups = {
"browser_js": (browser_sources(root), js_strict),
"backend_python": (backend_sources(root) | {"app.py"}, py_strict),
}
errors: list[str] = []
if set(debt) != set(groups):
errors.append("debt inventory must contain browser_js and backend_python only")
for name, (sources, strict) in groups.items():
baseline = debt.get(name, [])
if len(baseline) != len(set(baseline)):
errors.append(f"duplicate {name} debt entries")
if previous_debt is not None:
for path in sorted(set(baseline) - set(previous_debt.get(name, []))):
errors.append(f"strict debt cannot grow: {path}")
missing = sources - strict
for path in sorted(missing - set(baseline)):
errors.append(f"new {name} source is not in a strict gate: {path}")
for path in sorted(set(baseline) - missing):
errors.append(f"stale {name} debt entry (remove it): {path}")
for path in sorted(browser_sources(root) - js_basic):
errors.append(f"browser source is not in the basic gate: {path}")
for path in sorted(backend_sources(root) | {"app.py"}):
if re.search(r"#\s*(?:type:\s*ignore|pyright:\s*(?:ignore|strict|basic|off))\b",
(root / path).read_text()):
errors.append(f"inline Python type suppression or mode directive is forbidden: {path}")
for path in sorted(browser_sources(root)):
if re.search(r"@ts-(?:nocheck|ignore|expect-error)\b", (root / path).read_text()):
errors.append(f"inline JavaScript type suppression is forbidden: {path}")
return errors
def compiler_files(root: Path, config: str, *, strict: bool = False) -> set[str]:
if config not in (*STRICT_FRONTEND_PROJECTS, "config/types/jsconfig.check.json",
"config/types/jsconfig.service-worker.json"):
raise ValueError("unknown TypeScript configuration")
node = shutil.which("node")
if node is None:
raise RuntimeError("node is required to inspect the TypeScript graph")
compiler = root / "node_modules/typescript/bin/tsc"
# The executable is resolved from PATH and all remaining arguments are
# fixed project paths selected from the allowlist above, never shell input.
if strict:
resolved = subprocess.run([node, str(compiler), "--project", config, "--showConfig"], # noqa: S603
cwd=root, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=60)
if resolved.returncode:
raise RuntimeError(f"{config}: {resolved.stdout}")
options = json.loads(resolved.stdout).get("compilerOptions", {})
if (not all(options.get(key) is True for key in ("allowJs", "checkJs", "noEmit"))
or options.get("noCheck", False) is not False):
raise RuntimeError(f"{config}: strict JavaScript checking must remain enabled")
for option in ("strictNullChecks", "noImplicitAny"):
if options.get(option, options.get("strict", False)) is not True:
raise RuntimeError(f"{config}: effective {option} must be enabled")
for flag in REQUIRED_FRONTEND_FLAGS:
if options.get(flag) is not True:
raise RuntimeError(f"{config}: effective {flag} must be enabled")
# Check top-level bindings even in browser classic scripts; this graph never emits.
if options.get("moduleDetection") != "force":
raise RuntimeError(f"{config}: effective moduleDetection must be force for top-level unused checking")
result = subprocess.run([node, str(compiler), "--project", config, "--listFilesOnly"], # noqa: S603
cwd=root, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=60)
if result.returncode:
raise RuntimeError(f"{config}: {result.stdout}")
paths: set[str] = set()
for line in result.stdout.splitlines():
path = Path(line).resolve()
if path.is_relative_to(root):
paths.add(path.relative_to(root).as_posix())
return paths
def main() -> int:
types = json.loads((ROOT / "package.json").read_text())["scripts"]["types"]
commands = {command.strip() for command in types.split("&&")}
for project in STRICT_FRONTEND_PROJECTS:
if f"tsc --project {project}" not in commands:
raise RuntimeError(f"{project}: npm run types must compile this strict frontend project")
basic = (compiler_files(ROOT, "config/types/jsconfig.check.json")
| compiler_files(ROOT, "config/types/jsconfig.service-worker.json"))
strict = set().union(*(compiler_files(ROOT, project, strict=True) for project in STRICT_FRONTEND_PROJECTS))
py_config = json.loads((ROOT / "pyrightconfig.strict.json").read_text())
if py_config.get("typeCheckingMode") != "strict":
raise RuntimeError("backend strict type gate must use strict mode")
basic_py = json.loads((ROOT / "pyrightconfig.json").read_text())
if set(basic_py.get("include", [])) != {"app.py", "backend"}:
raise RuntimeError("basic Python gate must include app.py and the complete backend tree")
py_strict = set(py_config["include"])
debt = json.loads((ROOT / DEBT_FILE).read_text())
previous = json.loads(Path(sys.argv[1]).read_text()) if len(sys.argv) == 2 else None
if len(sys.argv) > 2:
raise RuntimeError("usage: python scripts/check_strict_inventory.py [BASELINE_DEBT_JSON]")
browser = browser_sources(ROOT)
errors = inventory_errors(ROOT, strict, basic, py_strict, debt, previous)
for path in sorted((browser - strict) & set(debt.get("browser_js", []))):
errors.append(f"browser source must be checked with all seven frontend flags: {path}")
if errors:
print("\n".join(errors), file=sys.stderr)
return 1
python_sources = backend_sources(ROOT) | {"app.py"}
print(f"Strict inventory: JS {len(browser & strict)}/{len(browser)}; "
f"backend and entry {len(python_sources & py_strict)}/{len(python_sources)}; "
"no new ungated files; all seven frontend flags enforced")
return 0
if __name__ == "__main__":
raise SystemExit(main())
|