#!/usr/bin/env node // Run some test files of a package by path — and fail when none ran. // // node scripts/test-files.mjs […] // pnpm test:files editor "app/channels/[slug]/videos/fetchWindowsAction.test.ts" // // `tsx --test ` (node's test runner) reads each path as a GLOB, so a // Next route directory like `[slug]` is a character class: the file matches // nothing, 0 tests run, and it exits 0 — a green run that tested nothing. Here // a path that names a file is escaped to match only itself, and a run whose // summary says 0 tests is a failure. It runs under ARCHILYZER_NO_NETWORK=1, as // every test script does. import { spawn } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); /** A path written so node's test-runner glob matches exactly that file. */ export function literalGlob(p) { return p.replace(/[[*?{}()+@]/g, (c) => `[${c}]`); } /** The top-level `# tests N` of a TAP run, or null when there is none. */ export function testsRan(tap) { const all = [...tap.matchAll(/^# tests (\d+)$/gm)]; return all.length ? Number(all.at(-1)[1]) : null; } async function main(argv) { const [pkg, ...files] = argv; if (!pkg || files.length === 0) { process.stderr.write("usage: node scripts/test-files.mjs […]\n"); return 2; } const cwd = path.resolve(ROOT, pkg); const args = files.map((f) => (fs.existsSync(path.resolve(cwd, f)) ? literalGlob(f) : f)); const tsx = path.join(ROOT, "node_modules", ".bin", "tsx"); // The test harness's switch (common/lib/noNetwork.mjs): nothing the run starts reaches another host. const env = { ...process.env, ARCHILYZER_NO_NETWORK: "1", // A file URL: a checkout path with spaces needs no quoting. NODE_OPTIONS: `--import=${pathToFileURL(path.join(ROOT, "common", "lib", "noNetwork.mjs")).href} ${process.env.NODE_OPTIONS ?? ""}`.trim(), }; const child = spawn(tsx, ["--test", ...args], { cwd, env, stdio: ["ignore", "pipe", "inherit"] }); let out = ""; child.stdout.on("data", (d) => { out += d; process.stdout.write(d); }); const code = await new Promise((r) => child.on("close", (c) => r(c ?? 1))); const ran = testsRan(out); if (code === 0 && !ran) { process.stderr.write(`test-files: no test ran (${ran === null ? "no summary" : "0 tests"}) — check the paths: ${files.join(" ")}\n`); return 1; } return code; } if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { process.exit(await main(process.argv.slice(2))); }