Skip to content

A self-organizing Obsidian vault that gives AI coding agents persistent memory.

fix: harden npmGlobalRoot against a nameless home, rewritten npmrc keys and untrimmed env values (#403)

Brenno Ferrarie21ed913c8cb
diff --git a/.claude/scripts/lib/qmd.ts b/.claude/scripts/lib/qmd.ts
index 3c65caa..af64c27 100644
--- a/.claude/scripts/lib/qmd.ts
+++ b/.claude/scripts/lib/qmd.ts
@@ -17,7 +17,7 @@
* copies are asserted independently: `tests/qmd.test.ts` locks this file's
* `resolveQmdEntry` + `buildQmdCommand` shape, and `tests/qmd-mcp.test.ts`
* locks the .mjs wrapper's equivalents; `tests/qmd.test.ts` also runs
- * `pickQmdEntry` and `npmGlobalRoot` against both copies. Drift between the
+ * `pickQmdEntry`, `npmGlobalRoot` and `globalQmdEntry` against both copies. Drift between the
* two shows up as a test failure on the CI matrix rather than a silent
* platform bug.
*/
@@ -102,6 +102,8 @@ export interface NpmLocation {
readonly platform?: string;
readonly execPath?: string;
readonly home?: string;
+ /** The OS home lookup; it throws for a UID with no passwd entry. */
+ readonly osHome?: () => string;
/** A file's text, or null when it can't be read. */
readonly readText?: (path: string) => string | null;
}
@@ -122,22 +124,26 @@ function readTextOrNull(path: string): string | null {
* caller asks npm, which gives its exact answer at the old cost.
*
* 1. npm_config_prefix in the env (any case): use it if it's an absolute path
- * with no `${`, else ask npm.
+ * with no `${` and no surrounding whitespace, else ask npm.
* 2. PREFIX, DESTDIR, npm_config_userconfig or npm_config_globalconfig set →
* ask npm.
* 3. ~/.npmrc (HOME before the OS home) or `<node prefix>/etc/npmrc` has a
* line setting `prefix` or `globalconfig`, sections included, or a key
- * built from `${…}` → ask npm. An npmrc with only auth or registry lines
- * (or `save-prefix`) doesn't count.
+ * npm's ini would rewrite (quoted, which it unquotes, escapes and all;
+ * built from `${…}`; or holding `;` or `#`, which cut it, brackets, a
+ * backslash or whitespace) → ask npm. An npmrc with only auth or
+ * registry lines (or `save-prefix`) doesn't count.
* 4. The builtin npmrc: on Windows, the installer's exact
* `prefix=${APPDATA}\npm` → %APPDATA%\npm. Any other line there setting
* `prefix`, `globalconfig` or `userconfig` (which moves the user npmrc),
- * or a key built from `${…}` → ask npm.
+ * or a key npm's ini would rewrite → ask npm.
* 5. Otherwise Node's own prefix.
*
* 4 and 5 hold only when npm sits beside this Node; where it doesn't
* (Homebrew, Debian's packaged npm), ask npm. Env values are read as npm
- * reads them: trimmed, empty ones skipped, the last of several winning.
+ * reads them: only "" skipped, nothing trimmed, the last of several winning
+ * (@npmcli/config's loadEnv, read in npm 10.9.2 on 2026-10-14). Rule 3 needs a home: when
+ * the OS can't name one (a UID with no passwd entry), ask npm.
*
* Packages sit in `<prefix>\node_modules` on Windows and
* `<prefix>/lib/node_modules` elsewhere.
@@ -146,26 +152,36 @@ export function npmGlobalRoot(at: NpmLocation = {}): string | null {
const vars = at.env ?? process.env;
const win = (at.platform ?? process.platform) === "win32";
const execPath = at.execPath ?? process.execPath;
- const home = at.home ?? (vars["HOME"] || homedir());
const readText = at.readText ?? readTextOrNull;
- // As npm's loadEnv reads it: any case, trimmed, empty skipped, the last one winning.
+ // Rule 1's env reading: the last non-empty value, untrimmed.
const npmConfig = (key: string): string | undefined => {
const want = `npm_config_${key}`;
let found: string | undefined;
for (const [name, value] of Object.entries(vars)) {
- if (name.toLowerCase() === want && value?.trim()) found = value.trim();
+ if (name.toLowerCase() === want && value) found = value;
}
return found;
};
const lines = (file: string): string[] =>
(readText(file) ?? "").split(/\r?\n/).map((l) => l.trim()).filter((l) => l !== "" && !/^[;#]/.test(l));
- // A line setting prefix or globalconfig, sections included, or one whose
- // key npm would expand from the environment and so can't be read here.
- const settingLines = (file: string): string[] =>
- lines(file).filter((l) => /^(prefix|globalconfig)\s*=/i.test(l) || /\$\{[^=]*=/.test(l));
+ // Rules 3 and 4: a line setting one of `keys`, or one whose key npm's
+ // ini would turn into something this can't read: quoted (unquoted and
+ // decoded), built from `${…}`, or holding `;` or `#` (ini cuts the key
+ // there), brackets, a backslash or whitespace. Auth keys (`//host/path/:_authToken`, with % ~ +) are
+ // plain. Section headers set nothing.
+ const settingLines = (file: string, keys: readonly string[] = ["prefix", "globalconfig"]): string[] =>
+ lines(file).filter((l) => {
+ if (l.startsWith("[")) return false;
+ const key = l.split("=", 1)[0]!.trim();
+ return keys.includes(key.toLowerCase()) || /^["']|\$\{|[\s[\]\\;#]/.test(key);
+ });
// Absolute in npm's sense: on a Windows host, `\npm` is drive-relative.
+ // Padded values ask npm: how its path handling treats them is not read here.
const exactPath = (value: string): boolean =>
- isAbsolute(value) && !value.includes("${") && (process.platform !== "win32" || !/^[\\/](?![\\/])/.test(value));
+ value === value.trim() &&
+ isAbsolute(value) &&
+ !value.includes("${") &&
+ (process.platform !== "win32" || !/^[\\/](?![\\/])/.test(value));
const layout = (prefix: string): string => (win ? join(prefix, "node_modules") : join(prefix, "lib", "node_modules"));
// 1.
@@ -178,6 +194,12 @@ export function npmGlobalRoot(at: NpmLocation = {}): string | null {
}
// 3.
+ let home: string;
+ try {
+ home = at.home ?? (vars["HOME"] || (at.osHome ?? homedir)());
+ } catch {
+ return null; // no home to find ~/.npmrc in (a UID with no passwd entry)
+ }
const nodePrefix = win ? dirname(execPath) : dirname(dirname(execPath));
if (settingLines(join(home, ".npmrc")).length > 0 || settingLines(join(nodePrefix, "etc", "npmrc")).length > 0) {
return null;
@@ -189,9 +211,7 @@ export function npmGlobalRoot(at: NpmLocation = {}): string | null {
if (readText(join(npmDir, "package.json")) === null) return null;
// 4.
- const builtin = lines(join(npmDir, "npmrc")).filter(
- (l) => /^(prefix|globalconfig|userconfig)\s*=/i.test(l) || /\$\{[^=]*=/.test(l),
- );
+ const builtin = settingLines(join(npmDir, "npmrc"), ["prefix", "globalconfig", "userconfig"]);
if (builtin.length === 0) return layout(nodePrefix); // 5.
const appdata = vars["APPDATA"];
if (!win || builtin.length !== 1 || builtin[0] !== "prefix=${APPDATA}\\npm" || !appdata || !exactPath(appdata)) {
@@ -208,12 +228,21 @@ function qmdEntryUnder(root: string): string | null {
return existsSync(entry) ? entry : null;
}
-function globalQmdEntry(): string | null {
- // Where npm would put a global install, without spawning npm (#349).
- const computed = npmGlobalRoot();
+/**
+ * qmd's entry under npm's global root: under the root `npmGlobalRoot` works
+ * out when qmd is there, else under npm's own answer. A worked-out root
+ * models the npm beside this Node, and the npm on PATH can differ (a
+ * self-upgraded npm on Windows, mixed installs; inferred), so a miss there
+ * still asks npm (#399, 2026-10-14).
+ */
+export function globalQmdEntry(computed: string | null = npmGlobalRoot(), askNpm: () => string | null = askNpmForRoot): string | null {
const known = computed === null ? null : qmdEntryUnder(computed);
if (known !== null) return known;
+ const root = askNpm();
+ return root === null ? null : qmdEntryUnder(root);
+}
+function askNpmForRoot(): string | null {
// Fallback for global npm installs that aren't on this package's resolution
// path — ask npm directly where global packages live. Bounded timeout so a
// hung npm process can't block a fire-and-forget hook indefinitely.
@@ -236,8 +265,7 @@ function globalQmdEntry(): string | null {
}
const root = (npmRoot.stdout ?? "").trim();
- if (root === "" || !isAbsolute(root)) return null;
- return qmdEntryUnder(root);
+ return root === "" || !isAbsolute(root) ? null : root;
}
/**
diff --git a/.claude/scripts/qmd-mcp.d.mts b/.claude/scripts/qmd-mcp.d.mts
index 5a2b6fa..50aba9e 100644
--- a/.claude/scripts/qmd-mcp.d.mts
+++ b/.claude/scripts/qmd-mcp.d.mts
@@ -28,6 +28,8 @@ export function isRunnableQmdEntry(entry: string): boolean;
* "no global npm".
*/
export function npmGlobalRoot(at?: import("./lib/qmd.ts").NpmLocation): string | null;
+/** qmd's entry under npm's global root: a worked-out root is the answer; npm is asked only without one. */
+export function globalQmdEntry(computed?: string | null, askNpm?: () => string | null): string | null;
/**
* Resolve the vault root directory from a `file://` URL and optional env.
diff --git a/.claude/scripts/qmd-mcp.mjs b/.claude/scripts/qmd-mcp.mjs
index feadd21..7e9c7f5 100644
--- a/.claude/scripts/qmd-mcp.mjs
+++ b/.claude/scripts/qmd-mcp.mjs
@@ -135,7 +135,8 @@ function readTextOrNull(path) {
}
/**
- * The duplicate of lib/qmd.ts's npmGlobalRoot, kept in step by hand: change
+ * The duplicate of lib/qmd.ts's npmGlobalRoot (and, below, globalQmdEntry and
+ * askNpmForRoot), kept in step by hand: change
* that one first, then carry the change here with the types removed.
*
* Where npm keeps global packages, without spawning it (#349): `npm root -g`
@@ -145,22 +146,26 @@ function readTextOrNull(path) {
* caller asks npm, which gives its exact answer at the old cost.
*
* 1. npm_config_prefix in the env (any case): use it if it's an absolute path
- * with no `${`, else ask npm.
+ * with no `${` and no surrounding whitespace, else ask npm.
* 2. PREFIX, DESTDIR, npm_config_userconfig or npm_config_globalconfig set →
* ask npm.
* 3. ~/.npmrc (HOME before the OS home) or `<node prefix>/etc/npmrc` has a
* line setting `prefix` or `globalconfig`, sections included, or a key
- * built from `${…}` → ask npm. An npmrc with only auth or registry lines
- * (or `save-prefix`) doesn't count.
+ * npm's ini would rewrite (quoted, which it unquotes, escapes and all;
+ * built from `${…}`; or holding `;` or `#`, which cut it, brackets, a
+ * backslash or whitespace) → ask npm. An npmrc with only auth or
+ * registry lines (or `save-prefix`) doesn't count.
* 4. The builtin npmrc: on Windows, the installer's exact
* `prefix=${APPDATA}\npm` → %APPDATA%\npm. Any other line there setting
* `prefix`, `globalconfig` or `userconfig` (which moves the user npmrc),
- * or a key built from `${…}` → ask npm.
+ * or a key npm's ini would rewrite → ask npm.
* 5. Otherwise Node's own prefix.
*
* 4 and 5 hold only when npm sits beside this Node; where it doesn't
* (Homebrew, Debian's packaged npm), ask npm. Env values are read as npm
- * reads them: trimmed, empty ones skipped, the last of several winning.
+ * reads them: only "" skipped, nothing trimmed, the last of several winning
+ * (@npmcli/config's loadEnv, read in npm 10.9.2 on 2026-10-14). Rule 3 needs a home: when
+ * the OS can't name one (a UID with no passwd entry), ask npm.
*
* Packages sit in `<prefix>\node_modules` on Windows and
* `<prefix>/lib/node_modules` elsewhere.
@@ -169,26 +174,36 @@ export function npmGlobalRoot(at = {}) {
const vars = at.env ?? process.env;
const win = (at.platform ?? process.platform) === "win32";
const execPath = at.execPath ?? process.execPath;
- const home = at.home ?? (vars["HOME"] || homedir());
const readText = at.readText ?? readTextOrNull;
- // As npm's loadEnv reads it: any case, trimmed, empty skipped, the last one winning.
+ // Rule 1's env reading: the last non-empty value, untrimmed.
const npmConfig = (key) => {
const want = `npm_config_${key}`;
let found;
for (const [name, value] of Object.entries(vars)) {
- if (name.toLowerCase() === want && value?.trim()) found = value.trim();
+ if (name.toLowerCase() === want && value) found = value;
}
return found;
};
const lines = (file) =>
(readText(file) ?? "").split(/\r?\n/).map((l) => l.trim()).filter((l) => l !== "" && !/^[;#]/.test(l));
- // A line setting prefix or globalconfig, sections included, or one whose
- // key npm would expand from the environment and so can't be read here.
- const settingLines = (file) =>
- lines(file).filter((l) => /^(prefix|globalconfig)\s*=/i.test(l) || /\$\{[^=]*=/.test(l));
+ // Rules 3 and 4: a line setting one of `keys`, or one whose key npm's
+ // ini would turn into something this can't read: quoted (unquoted and
+ // decoded), built from `${…}`, or holding `;` or `#` (ini cuts the key
+ // there), brackets, a backslash or whitespace. Auth keys (`//host/path/:_authToken`, with % ~ +) are
+ // plain. Section headers set nothing.
+ const settingLines = (file, keys = ["prefix", "globalconfig"]) =>
+ lines(file).filter((l) => {
+ if (l.startsWith("[")) return false;
+ const key = l.split("=", 1)[0].trim();
+ return keys.includes(key.toLowerCase()) || /^["']|\$\{|[\s[\]\\;#]/.test(key);
+ });
// Absolute in npm's sense: on a Windows host, `\npm` is drive-relative.
+ // Padded values ask npm: how its path handling treats them is not read here.
const exactPath = (value) =>
- isAbsolute(value) && !value.includes("${") && (process.platform !== "win32" || !/^[\\/](?![\\/])/.test(value));
+ value === value.trim() &&
+ isAbsolute(value) &&
+ !value.includes("${") &&
+ (process.platform !== "win32" || !/^[\\/](?![\\/])/.test(value));
const layout = (prefix) => (win ? join(prefix, "node_modules") : join(prefix, "lib", "node_modules"));
// 1.
@@ -201,6 +216,12 @@ export function npmGlobalRoot(at = {}) {
}
// 3.
+ let home;
+ try {
+ home = at.home ?? (vars["HOME"] || (at.osHome ?? homedir)());
+ } catch {
+ return null; // no home to find ~/.npmrc in (a UID with no passwd entry)
+ }
const nodePrefix = win ? dirname(execPath) : dirname(dirname(execPath));
if (settingLines(join(home, ".npmrc")).length > 0 || settingLines(join(nodePrefix, "etc", "npmrc")).length > 0) {
return null;
@@ -212,9 +233,7 @@ export function npmGlobalRoot(at = {}) {
if (readText(join(npmDir, "package.json")) === null) return null;
// 4.
- const builtin = lines(join(npmDir, "npmrc")).filter(
- (l) => /^(prefix|globalconfig|userconfig)\s*=/i.test(l) || /\$\{[^=]*=/.test(l),
- );
+ const builtin = settingLines(join(npmDir, "npmrc"), ["prefix", "globalconfig", "userconfig"]);
if (builtin.length === 0) return layout(nodePrefix); // 5.
const appdata = vars["APPDATA"];
if (!win || builtin.length !== 1 || builtin[0] !== "prefix=${APPDATA}\\npm" || !appdata || !exactPath(appdata)) {
@@ -231,12 +250,21 @@ function qmdEntryUnder(root) {
return existsSync(entry) ? entry : null;
}
-function globalQmdEntry() {
- // Where npm would put a global install, without spawning npm (#349).
- const computed = npmGlobalRoot();
+/**
+ * qmd's entry under npm's global root: under the root `npmGlobalRoot` works
+ * out when qmd is there, else under npm's own answer. A worked-out root
+ * models the npm beside this Node, and the npm on PATH can differ (a
+ * self-upgraded npm on Windows, mixed installs; inferred), so a miss there
+ * still asks npm (#399, 2026-10-14).
+ */
+export function globalQmdEntry(computed = npmGlobalRoot(), askNpm = askNpmForRoot) {
const known = computed === null ? null : qmdEntryUnder(computed);
if (known !== null) return known;
+ const root = askNpm();
+ return root === null ? null : qmdEntryUnder(root);
+}
+function askNpmForRoot() {
// Fallback for global npm installs that aren't on this package's resolution
// path — ask npm directly where global packages live. Bounded timeout so a
// hung npm process can't block MCP server startup indefinitely.
@@ -263,11 +291,8 @@ function globalQmdEntry() {
// Guard against success-with-empty-stdout or a relative path — either would
// make join() produce a path anchored at cwd, and existsSync could then
// match a local folder by accident.
- const root = npmRoot.stdout.trim();
- if (root === "" || !isAbsolute(root)) {
- return null;
- }
- return qmdEntryUnder(root);
+ const root = (npmRoot.stdout ?? "").trim();
+ return root === "" || !isAbsolute(root) ? null : root;
}
/**
diff --git a/.claude/scripts/tests/qmd.test.ts b/.claude/scripts/tests/qmd.test.ts
index 53f52f6..2693e6f 100644
--- a/.claude/scripts/tests/qmd.test.ts
+++ b/.claude/scripts/tests/qmd.test.ts
@@ -10,12 +10,13 @@
import { test, describe } from "node:test";
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
-import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
-import { isAbsolute, join, resolve } from "node:path";
+import { dirname, isAbsolute, join, resolve } from "node:path";
import {
buildQmdCommand,
+ globalQmdEntry as globalQmdEntryTs,
isRunnableQmdEntry,
npmGlobalRoot as npmGlobalRootTs,
parseVersionTriple,
@@ -24,10 +25,12 @@ import {
resolveQmdEntry,
} from "../lib/qmd.ts";
import {
+ globalQmdEntry as globalQmdEntryMjs,
isRunnableQmdEntry as isRunnableQmdEntryMjs,
npmGlobalRoot as npmGlobalRootMjs,
pickQmdEntry as pickQmdEntryMjs,
} from "../qmd-mcp.mjs";
+import { rmTemp } from "./_helpers.ts";
/**
* A present-but-broken install used to win just by existing: the first
@@ -222,11 +225,18 @@ describe("qmdVersionAtLeast", () => {
// rest. Both copies of the resolver run the same cases; the last checks the
// real npm on this machine.
+/** qmd's entry, relative to a global root. */
+const QMD_ENTRY = join("@tobilu", "qmd", "dist", "cli", "qmd.js");
+
+/** This process's env without the npm_config_* that `npm test` exports. */
+const withoutNpmConfig = (): Record<string, string | undefined> =>
+ Object.fromEntries(Object.entries(process.env).filter(([name]) => !/^npm_config_/i.test(name)));
+
/** The real npm's answer on this machine, asked at most once for both copies; null without npm. */
let npmAsked: string | null | undefined;
const npmAnswer = (): string | null => {
if (npmAsked === undefined) {
- const npm = spawnSync("npm root -g", { shell: true, encoding: "utf8", timeout: 15_000 });
+ const npm = spawnSync("npm root -g", { shell: true, encoding: "utf8", timeout: 15_000, env: withoutNpmConfig() });
const asked = (npm.stdout ?? "").trim();
npmAsked = npm.status === 0 && asked !== "" ? asked : null;
}
@@ -271,10 +281,13 @@ for (const [label, npmGlobalRoot] of [
assert.equal(posix({ npm_config_prefix: join(tmpdir(), "${NAME}") }), null);
});
- test("1: env values are read as npm reads them: trimmed, empty skipped, the last winning", () => {
+ test("1: env values are read as npm reads them: empty skipped, the last winning, nothing trimmed", () => {
const a = join(tmpdir(), "a");
const b = join(tmpdir(), "b");
- assert.equal(posix({ npm_config_prefix: `${a} ` }), join(a, "lib", "node_modules"));
+ // npm's loadEnv skips only "" and keeps the value as given (@npmcli/config, npm 10.9.2, read 2026-10-14).
+ assert.equal(posix({ npm_config_prefix: `${a} ` }), null, "padded: npm doesn't trim it, so ask npm");
+ assert.equal(posix({ npm_config_prefix: " " }), null, "whitespace is set for npm, not unset");
+ assert.equal(posix({ npm_config_userconfig: " " }), null);
assert.equal(posix({ npm_config_prefix: "" }), join(nodeDir, "lib", "node_modules"), "empty is unset");
assert.equal(posix({ npm_config_prefix: a, NPM_CONFIG_PREFIX: b }), join(b, "lib", "node_modules"));
});
@@ -306,6 +319,35 @@ for (const [label, npmGlobalRoot] of [
assert.equal(posix({}, auth), join(nodeDir, "lib", "node_modules"));
});
+ test("3 and 4: a quoted key asks npm: npm's ini unquotes keys", () => {
+ assert.equal(posix({}, { [userNpmrc]: '"prefix" = /opt/npm' }), null);
+ assert.equal(posix({}, { [userNpmrc]: "'globalconfig'=/opt/g" }), null);
+ assert.equal(posix({}, { [userNpmrc]: '"pre\\u0066ix"=/opt/npm' }), null, "escapes too");
+ assert.equal(posix({}, { [posixBuiltin]: '"prefix"=/opt/homebrew' }), null);
+ });
+
+ test("3: a home the OS can't name (a UID with no passwd entry) asks npm instead of throwing", () => {
+ const noHome = () => {
+ throw new Error("uv_os_homedir returned ENOENT");
+ };
+ const at = (env: Record<string, string>) =>
+ npmGlobalRoot({ env, platform: "linux", execPath: join(nodeDir, "bin", "node"), readText: files({}), osHome: noHome });
+ assert.equal(at({}), null);
+ const p = join(tmpdir(), "env-prefix");
+ assert.equal(at({ NPM_CONFIG_PREFIX: p }), join(p, "lib", "node_modules"), "rule 1 needs no home");
+ });
+
+ test("3: auth keys with %, ~ or + are plain, not a reason to ask npm", () => {
+ const auth = { [userNpmrc]: "//registry.corp/npm/%40team/:_authToken=x\n//host/~user/:_auth=y\n//h/a+b/:always-auth=true" };
+ assert.equal(posix({}, auth), join(nodeDir, "lib", "node_modules"));
+ });
+
+ test("3: a key ini would cut or reshape asks npm: ; or #, brackets, a backslash, inner whitespace", () => {
+ for (const line of ["prefix#moved=/opt/g", "globalconfig;x=/etc/g", "prefix[]=/opt/g", "pre\\fix=/opt/g", "pre fix=/opt/g"]) {
+ assert.equal(posix({}, { [userNpmrc]: line }), null, line);
+ }
+ });
+
test("3: a key npm would build from ${...} asks npm", () => {
assert.equal(posix({}, { [userNpmrc]: "${NPMKEY}=/opt/g" }), null);
});
@@ -365,16 +407,64 @@ for (const [label, npmGlobalRoot] of [
);
});
- // The property that matters: a root worked out here that holds qmd is
- // the root npm would give. A null only costs the spawn it would save.
- test("where it finds qmd on this machine, npm agrees", (t) => {
- const ours = npmGlobalRoot();
- if (ours === null || !existsSync(join(ours, "@tobilu", "qmd", "dist", "cli", "qmd.js"))) {
- return t.skip("no qmd under a worked-out root here; the caller asks npm");
- }
+ // A detector, not a law: a worked-out root models the npm beside this
+ // Node, and PATH's npm can differ (globalQmdEntry asks npm on a miss
+ // for that reason). On a stock install, CI's included, the two agree;
+ // a leg where they don't fails here rather than silently.
+ test("a root worked out on this machine is the one npm gives", (t) => {
+ // Without the npm_config_* that `npm test` exports, or rule 1 only echoes npm back.
+ const ours = npmGlobalRoot({ env: withoutNpmConfig() });
+ if (ours === null) return t.skip("no worked-out root here; the caller asks npm");
const answer = npmAnswer();
if (answer === null) return t.skip("npm is not available here");
assert.equal(resolve(ours).toLowerCase(), resolve(answer).toLowerCase());
});
});
}
+
+for (const [label, globalQmdEntry] of [
+ ["lib/qmd.ts", globalQmdEntryTs],
+ ["qmd-mcp.mjs", globalQmdEntryMjs],
+] as const) {
+ describe(`${label} globalQmdEntry`, () => {
+ const withRoot = (run: (root: string) => void): void => {
+ const root = mkdtempSync(join(tmpdir(), "npm-root-"));
+ try {
+ run(root);
+ } finally {
+ rmTemp(root);
+ }
+ };
+
+ test("qmd under a worked-out root is found without asking npm", () => {
+ withRoot((root) => {
+ const entry = join(root, QMD_ENTRY);
+ mkdirSync(dirname(entry), { recursive: true });
+ writeFileSync(entry, "");
+ let asked = false;
+ assert.equal(globalQmdEntry(root, () => ((asked = true), null)), entry);
+ assert.equal(asked, false, "no npm root -g spawn");
+ });
+ });
+
+ test("a worked-out root without qmd still asks npm: the npm on PATH can differ", () => {
+ withRoot((computed) => {
+ withRoot((npms) => {
+ const entry = join(npms, QMD_ENTRY);
+ mkdirSync(dirname(entry), { recursive: true });
+ writeFileSync(entry, "");
+ assert.equal(globalQmdEntry(computed, () => npms), entry);
+ });
+ });
+ });
+
+ test("no worked-out root asks npm, and finds qmd under its answer", () => {
+ withRoot((root) => {
+ const entry = join(root, QMD_ENTRY);
+ mkdirSync(dirname(entry), { recursive: true });
+ writeFileSync(entry, "");
+ assert.equal(globalQmdEntry(null, () => root), entry);
+ });
+ });
+ });
+}