Skip to content

Commit d9e3582

Browse files
committed
fix(cli): resolve package.json at runtime to fix ERR_MODULE_NOT_FOUND
Replace static JSON import with lazy runtime read. The static import broke in dist/ because tsc does not copy JSON files to the output directory. Version is now read on demand (only when --version is used) and cached for subsequent calls.
1 parent 9d29799 commit d9e3582

1 file changed

Lines changed: 36 additions & 2 deletions

File tree

src/cli/program.ts

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,37 @@
1+
import { existsSync, readFileSync } from "node:fs";
2+
import { dirname, resolve } from "node:path";
3+
import { fileURLToPath } from "node:url";
14
import { Command } from "commander";
2-
import packageJson from "../../package.json" with { type: "json" };
35
import { buildCommander } from "./define-command.js";
46
import type { CommandDef } from "./define-command.js";
7+
8+
let cachedVersion: string | undefined;
9+
10+
function getVersion(): string {
11+
if (cachedVersion === undefined) {
12+
const __dirname = dirname(fileURLToPath(import.meta.url));
13+
// Works from both src/cli/ (../../) and dist/src/cli/ (../../../)
14+
const candidates = [
15+
resolve(__dirname, "../../package.json"),
16+
resolve(__dirname, "../../../package.json"),
17+
];
18+
const pkgPath = candidates.find(
19+
(p) => existsSync(p) && !p.includes("/dist/"),
20+
);
21+
if (!pkgPath) throw new Error("Could not find sysprom package.json");
22+
const pkg: unknown = JSON.parse(readFileSync(pkgPath, "utf8"));
23+
if (
24+
typeof pkg !== "object" ||
25+
pkg === null ||
26+
!("version" in pkg) ||
27+
typeof pkg.version !== "string"
28+
) {
29+
throw new Error("Invalid package.json: missing version field");
30+
}
31+
cachedVersion = pkg.version;
32+
}
33+
return cachedVersion;
34+
}
535
import { validateCommand } from "./commands/validate.js";
636
import { statsCommand } from "./commands/stats.js";
737
import { json2mdCommand } from "./commands/json2md.js";
@@ -27,7 +57,11 @@ program
2757
.description(
2858
"System Provenance Model CLI — record where every part of a system came from",
2959
)
30-
.version(packageJson.version)
60+
.option("-V, --version", "output the version number")
61+
.on("option:version", () => {
62+
console.log(getVersion());
63+
process.exit(0);
64+
})
3165
.showHelpAfterError(true);
3266

3367
export const commands: CommandDef[] = [

0 commit comments

Comments
 (0)