Download scripts/check_strict_inventory.py from VoiceOfML/Search: direct link, hf CLI and curl.
- Browser
- Download file 7.8 kB
-
https://huggingface.co/spaces/VoiceOfML/Search/resolve/main/scripts/check_strict_inventory.py
- Command line
-
hf download hf://spaces/VoiceOfML/Search/scripts/check_strict_inventory.py
-
curl -L -o check_strict_inventory.py https://huggingface.co/spaces/VoiceOfML/Search/resolve/main/scripts/check_strict_inventory.py
7.8 kB
| """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()) | |