fix(cli): precompute bare root help startup path

This commit is contained in:
Vincent Koc
2026-03-24 12:23:25 -07:00
parent 91b1e41132
commit 805bff6e7e
3 changed files with 72 additions and 8 deletions

View File

@@ -1,5 +1,6 @@
#!/usr/bin/env node
import { readFileSync } from "node:fs";
import { access } from "node:fs/promises";
import module from "node:module";
import { fileURLToPath } from "node:url";
@@ -85,8 +86,6 @@ const installProcessWarningFilter = async () => {
}
};
await installProcessWarningFilter();
const tryImport = async (specifier) => {
try {
await import(specifier);
@@ -126,10 +125,56 @@ const buildMissingEntryErrorMessage = async () => {
return lines.join("\n");
};
if (await tryImport("./dist/entry.js")) {
// OK
} else if (await tryImport("./dist/entry.mjs")) {
const isBareRootHelpInvocation = (argv) =>
argv.length === 3 && (argv[2] === "--help" || argv[2] === "-h");
const loadPrecomputedRootHelpText = () => {
try {
const raw = readFileSync(new URL("./dist/cli-startup-metadata.json", import.meta.url), "utf8");
const parsed = JSON.parse(raw);
return typeof parsed?.rootHelpText === "string" && parsed.rootHelpText.length > 0
? parsed.rootHelpText
: null;
} catch {
return null;
}
};
const tryOutputBareRootHelp = async () => {
if (!isBareRootHelpInvocation(process.argv)) {
return false;
}
const precomputed = loadPrecomputedRootHelpText();
if (precomputed) {
process.stdout.write(precomputed);
return true;
}
for (const specifier of ["./dist/cli/program/root-help.js", "./dist/cli/program/root-help.mjs"]) {
try {
const mod = await import(specifier);
if (typeof mod.outputRootHelp === "function") {
mod.outputRootHelp();
return true;
}
} catch (err) {
if (isDirectModuleNotFoundError(err, specifier)) {
continue;
}
throw err;
}
}
return false;
};
if (await tryOutputBareRootHelp()) {
// OK
} else {
throw new Error(await buildMissingEntryErrorMessage());
await installProcessWarningFilter();
if (await tryImport("./dist/entry.js")) {
// OK
} else if (await tryImport("./dist/entry.mjs")) {
// OK
} else {
throw new Error(await buildMissingEntryErrorMessage());
}
}