|
| 1 | +// Shared resolver for spawning a package's CLI cross-platform (#1939). |
| 2 | +// |
| 3 | +// Ported from the MCP Inspector for #4864, where `verify:typecheck-coverage` |
| 4 | +// spawns tsc through it; `#N` in these comments are that repo's issues. |
| 5 | +// |
| 6 | +// On Windows, `npx`/`npm` are `.cmd` shims, not executables — a shell-free |
| 7 | +// `execFileSync`/`spawnSync` cannot start one (Node refuses `.cmd`/`.bat` |
| 8 | +// spawns without `shell: true` since the CVE-2024-27980 hardening) and throws |
| 9 | +// `ENOENT`. GitHub CI runs Linux, so the gate stayed green there while being |
| 10 | +// unrunnable for any Windows contributor. Instead of shelling through `npx`, |
| 11 | +// resolve the JS entry behind the package's bin and run it with |
| 12 | +// `process.execPath`: cross-platform, shell-free (no quoting hazards), faster |
| 13 | +// (no npx resolution), and pinned to the locally installed package exactly as |
| 14 | +// `npx --no-install` was. |
| 15 | + |
| 16 | +import { existsSync, readFileSync } from "node:fs"; |
| 17 | +import { createRequire } from "node:module"; |
| 18 | +import path from "node:path"; |
| 19 | + |
| 20 | +/** |
| 21 | + * Absolute path of the JS entry behind a package's bin (e.g. typescript's |
| 22 | + * `tsc`, vite's `vite`), resolved from `fromDir` up the node_modules tree — |
| 23 | + * the same walk `npx --no-install` does, minus the `.cmd` shim a shell-free |
| 24 | + * spawn can't start on Windows. Reads the package's manifest and takes the |
| 25 | + * path out of its `bin` field (what npx itself does) rather than resolving the |
| 26 | + * bin path directly, because an `exports` map blocks deep resolution — Vite 8 |
| 27 | + * doesn't export `./bin/vite.js`, so `require.resolve("vite/bin/vite.js")` |
| 28 | + * throws `ERR_PACKAGE_PATH_NOT_EXPORTED`. |
| 29 | + * |
| 30 | + * Throws if the package isn't installed from `fromDir`, declares no such bin, |
| 31 | + * or declares one whose file is missing — the caller decides whether that's a |
| 32 | + * hard "cannot measure" error or a fallback. |
| 33 | + */ |
| 34 | +export function resolveNodeBin(pkg, binName, fromDir) { |
| 35 | + const pkgPath = resolveManifest(pkg, fromDir); |
| 36 | + const manifest = JSON.parse(readFileSync(pkgPath, "utf8")); |
| 37 | + const { bin } = manifest; |
| 38 | + // A string-form `bin` is npm's shorthand for ONE command, named after the |
| 39 | + // package (unscoped). It does not make every requested `binName` valid, so |
| 40 | + // match it rather than accepting whatever was asked for — otherwise a typo |
| 41 | + // silently resolves the package's only executable instead of failing. |
| 42 | + const rel = |
| 43 | + typeof bin === "string" |
| 44 | + ? unscopedName(manifest.name ?? pkg) === binName |
| 45 | + ? bin |
| 46 | + : undefined |
| 47 | + : bin?.[binName]; |
| 48 | + if (typeof rel !== "string") |
| 49 | + throw new Error(`${pkg} declares no "${binName}" bin in its package.json`); |
| 50 | + const entry = path.join(path.dirname(pkgPath), rel); |
| 51 | + // A declared bin whose file is absent is a partial install, and it fails |
| 52 | + // *silently* downstream: `process.execPath <missing>` still spawns fine and |
| 53 | + // exits 1 with nothing on stdout, which `rawProjectListing` records as "no |
| 54 | + // diagnostic captured" and turns into the bogus every-file-uncovered report |
| 55 | + // this helper exists to eliminate. Fail here, where the remedy is actionable. |
| 56 | + if (!existsSync(entry)) |
| 57 | + throw new Error( |
| 58 | + `${pkg}'s "${binName}" bin points at a missing file: ${entry}`, |
| 59 | + ); |
| 60 | + return entry; |
| 61 | +} |
| 62 | + |
| 63 | +/** |
| 64 | + * The package's own `package.json`, found by walking the same `node_modules` |
| 65 | + * chain Node's resolver would from `fromDir` — deliberately NOT via |
| 66 | + * `require.resolve("<pkg>/package.json")`. |
| 67 | + * |
| 68 | + * That shortcut reads as safe and isn't: subpath resolution is governed by the |
| 69 | + * package's `exports`, and a package may declare one that omits `./package.json` |
| 70 | + * (Node dropped its special case for it, so there is no guaranteed export). Such |
| 71 | + * a package throws `ERR_PACKAGE_PATH_NOT_EXPORTED` here even though its bin is |
| 72 | + * installed and perfectly spawnable — a false "not installed" that would send |
| 73 | + * someone to `npm install` for a package already on disk. `resolve.paths()` |
| 74 | + * gives the search dirs without consulting `exports` at all. |
| 75 | + * |
| 76 | + * Its list is then filtered to the `node_modules` directories on `fromDir`'s |
| 77 | + * own ancestor chain, because `resolve.paths()` also appends Node's GLOBAL |
| 78 | + * FOLDERS (`$HOME/.node_modules`, `$HOME/.node_libraries`, `$PREFIX/lib/node`) |
| 79 | + * and any `NODE_PATH` entries. Accepting those would quietly break the |
| 80 | + * guarantee this module exists to keep — that the spawned tsc/vite is the |
| 81 | + * REPO-PINNED one, exactly as `npx --no-install` promised. A missing repo |
| 82 | + * install would then find a globally installed TypeScript and measure the |
| 83 | + * programs with the wrong compiler, instead of failing with the actionable |
| 84 | + * "run npm install" this helper is supposed to produce. |
| 85 | + */ |
| 86 | +function resolveManifest(pkg, fromDir) { |
| 87 | + const require = createRequire(path.join(fromDir, "package.json")); |
| 88 | + // `resolve.paths` returns null only for builtins, which have no bin to find. |
| 89 | + for (const dir of localSearchDirs( |
| 90 | + require.resolve.paths(pkg) ?? [], |
| 91 | + fromDir, |
| 92 | + )) { |
| 93 | + const candidate = path.join(dir, ...pkg.split("/"), "package.json"); |
| 94 | + if (existsSync(candidate)) return candidate; |
| 95 | + } |
| 96 | + throw new Error(`cannot find ${pkg} from ${fromDir}`); |
| 97 | +} |
| 98 | + |
| 99 | +/** |
| 100 | + * The subset of `resolve.paths()` that is a `node_modules` directory sitting |
| 101 | + * directly under `fromDir` or one of its ancestors — i.e. the local walk, with |
| 102 | + * Node's global folders and `NODE_PATH` dropped. Exported for its own test. |
| 103 | + */ |
| 104 | +export function localSearchDirs(dirs, fromDir) { |
| 105 | + const ancestors = new Set(); |
| 106 | + for (let dir = path.resolve(fromDir); ; dir = path.dirname(dir)) { |
| 107 | + ancestors.add(dir); |
| 108 | + if (dir === path.dirname(dir)) break; |
| 109 | + } |
| 110 | + return dirs.filter( |
| 111 | + (dir) => |
| 112 | + path.basename(dir) === "node_modules" && |
| 113 | + ancestors.has(path.dirname(path.resolve(dir))), |
| 114 | + ); |
| 115 | +} |
| 116 | + |
| 117 | +/** `@scope/name` → `name`; an unscoped name is returned unchanged. */ |
| 118 | +function unscopedName(name) { |
| 119 | + return name.startsWith("@") ? name.slice(name.indexOf("/") + 1) : name; |
| 120 | +} |
0 commit comments