Compare commits

...

2 Commits

Author SHA1 Message Date
diegosouzapw
bb51db4552 fix(cli): keep the startup plugin hook inside plugins.mjs so the entrypoint stays under its size baseline
Moves the --version short-circuit and the env-based context into
loadCliPlugins(), leaving bin/omniroute.mjs with a two-line call.
Bundle size goes from 10401 to 10353 bytes (baseline 10384).

Refs #21056
2026-11-23 17:41:45 -03:00
diegosouzapw
6b61dde53c fix(cli): load plugins at startup and install them where discovery looks (#21056) 2026-11-23 15:44:30 -03:00
7 changed files with 320 additions and 43 deletions

View File

@@ -1,29 +1,28 @@
import { spawnSync } from "node:child_process";
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { t } from "../i18n.mjs";
import { emit } from "../output.mjs";
import { discoverPlugins } from "../plugins.mjs";
import { getPluginPrefix, resolvePluginSpec, runPluginNpm } from "../pluginNpm.mjs";
import { readFileSync } from "node:fs";
import { dirname } from "node:path";
import { fileURLToPath } from "node:url";
// Run npm with an explicit argument array and no shell. Passing args this way
// (instead of string-interpolating into `execSync`) prevents a malicious plugin
// name like `foo; rm -rf ~` or `` foo`id` `` from being interpreted by the shell.
function runNpm(args) {
const isBun = Boolean(process.versions.bun);
const pm = isBun ? "bun" : "npm";
const cmdArgs = isBun && args[0] === "install" ? ["add", ...args.slice(1)] : args;
const res = spawnSync(pm, cmdArgs, { stdio: "inherit", shell: false });
if (res.error) throw res.error;
if (typeof res.status === "number" && res.status !== 0) {
throw new Error(`${pm} exited with code ${res.status}`);
}
}
const HOST_MAJOR = Number(
JSON.parse(
readFileSync(
join(dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "package.json"),
"utf8"
)
).version.split(".")[0]
);
const HOST_RANGE = `>=${HOST_MAJOR}.0.0`;
const TEMPLATE_INDEX = `export const meta = {
name: "PLUGIN_NAME",
version: "0.1.0",
description: "OmniRoute plugin",
omnirouteApi: ">=4.0.0",
omnirouteApi: "HOST_RANGE",
};
export function register(program, ctx) {
@@ -65,8 +64,7 @@ export function registerPlugin(program) {
.description(t("plugin.install") || "Install a plugin")
.option("-y, --yes", "Skip confirmation prompt")
.action(async (name, opts) => {
const isLocal = name.startsWith("./") || name.startsWith("/") || name.startsWith("../");
const pkgName = isLocal ? name : `omniroute-cmd-${name}`;
const pkgName = resolvePluginSpec(name);
if (!opts.yes) {
process.stderr.write(
@@ -83,10 +81,10 @@ export function registerPlugin(program) {
}
try {
runNpm(["install", "-g", pkgName]);
runPluginNpm(["install", "--prefix", getPluginPrefix(), pkgName]);
process.stdout.write(`\n✓ Installed: ${pkgName}\n`);
} catch {
process.stderr.write(`✗ Failed to install ${pkgName}\n`);
} catch (err) {
process.stderr.write(`✗ Failed to install ${pkgName}: ${err.message}\n`);
process.exit(1);
}
});
@@ -105,10 +103,10 @@ export function registerPlugin(program) {
}
}
try {
runNpm(["uninstall", "-g", pkgName]);
runPluginNpm(["uninstall", "--prefix", getPluginPrefix(), pkgName]);
process.stdout.write(`✓ Removed: ${pkgName}\n`);
} catch {
process.stderr.write(`✗ Failed to remove ${pkgName}\n`);
} catch (err) {
process.stderr.write(`✗ Failed to remove ${pkgName}: ${err.message}\n`);
process.exit(1);
}
});
@@ -161,7 +159,7 @@ export function registerPlugin(program) {
try {
if (name) {
const pkg = `omniroute-cmd-${name}`;
runNpm(["update", "-g", pkg]);
runPluginNpm(["update", "--prefix", getPluginPrefix(), pkg]);
process.stdout.write(`✓ Updated: ${pkg}\n`);
return;
}
@@ -176,10 +174,10 @@ export function registerPlugin(program) {
process.stdout.write("No plugins installed to update.\n");
return;
}
runNpm(["update", "-g", ...names]);
runPluginNpm(["update", "--prefix", getPluginPrefix(), ...names]);
process.stdout.write(`✓ Updated: ${names.join(", ")}\n`);
} catch {
process.stderr.write(`✗ Update failed\n`);
} catch (err) {
process.stderr.write(`✗ Update failed: ${err.message}\n`);
process.exit(1);
}
});
@@ -204,14 +202,17 @@ export function registerPlugin(program) {
type: "module",
main: "index.mjs",
description: `OmniRoute CLI plugin: ${safeName}`,
engines: { omniroute: ">=4.0.0" },
engines: { omniroute: HOST_RANGE },
keywords: ["omniroute-plugin", "omniroute-cmd"],
},
null,
2
) + "\n"
);
writeFileSync(join(dir, "index.mjs"), TEMPLATE_INDEX.replace(/PLUGIN_NAME/g, safeName));
writeFileSync(
join(dir, "index.mjs"),
TEMPLATE_INDEX.replace(/PLUGIN_NAME/g, safeName).replace(/HOST_RANGE/g, HOST_RANGE)
);
writeFileSync(
join(dir, "README.md"),
`# omniroute-cmd-${safeName}\n\nAn OmniRoute CLI plugin.\n\n## Install\n\n\`\`\`bash\nomniroute plugin install ${safeName}\n\`\`\`\n`

82
bin/cli/pluginNpm.mjs Normal file
View File

@@ -0,0 +1,82 @@
// npm plumbing for `omniroute plugin install|remove|update` (#21056).
//
// Plugins are installed into a private npm prefix (`~/.omniroute/plugins`), which is
// the same directory `discoverPlugins()` scans — a global `npm install -g` landed in
// `$(npm root -g)`, a place discovery never looked at.
import { spawnSync } from "node:child_process";
import { homedir } from "node:os";
import { isAbsolute, join, resolve } from "node:path";
import { npmBin, npmExecInvocation, npmExecOptions } from "./npm-exec.mjs";
import { escapeWindowsShellArg } from "./utils/winShellArgs.mjs";
const LITERAL_TOKEN = /^[A-Za-z0-9@._/:=+-]+$/;
const UNSAFE_CHARS = /[\0\r\n]/;
const WINDOWS_DRIVE_RE = /^[A-Za-z]:[\\/]/;
/** Where plugins are installed (an npm `--prefix`); `node_modules/` lives below it. */
export function getPluginPrefix(home = homedir()) {
return join(home, ".omniroute", "plugins");
}
/** True when the user passed a path / file: spec rather than a registry name. */
export function isLocalPluginSpec(name) {
return (
name === "." ||
name === ".." ||
name.startsWith("./") ||
name.startsWith("../") ||
name.startsWith(".\\") ||
name.startsWith("..\\") ||
name.startsWith("/") ||
name.startsWith("~/") ||
name.startsWith("file:") ||
WINDOWS_DRIVE_RE.test(name) ||
name.startsWith("\\\\")
);
}
/** Spec handed to npm: absolute path for local installs, `omniroute-cmd-<name>` otherwise. */
export function resolvePluginSpec(name, cwd = process.cwd(), home = homedir()) {
if (!isLocalPluginSpec(name)) {
return name.startsWith("omniroute-cmd-") || name.startsWith("@")
? name
: `omniroute-cmd-${name}`;
}
if (name.startsWith("file:")) return name;
if (name.startsWith("~/")) return join(home, name.slice(2));
if (isAbsolute(name) || WINDOWS_DRIVE_RE.test(name) || name.startsWith("\\\\")) return name;
return resolve(cwd, name);
}
/**
* Build `[file, args, options]` for spawnSync. Tokens that are not plain literals are
* validated (no NUL/newline, no leading "-") and, on win32, escaped before joining
* (Hard Rule #13).
*/
export function buildPluginNpmInvocation(args, platform = process.platform) {
const isBun = Boolean(process.versions.bun);
const cmdArgs = isBun && args[0] === "install" ? ["add", ...args.slice(1)] : args;
const bin = npmBin(platform);
const opts = npmExecOptions(platform, { stdio: "inherit" });
cmdArgs.forEach((token, i) => {
if (
typeof token !== "string" ||
UNSAFE_CHARS.test(token) ||
(i > 0 && token.startsWith("-") && !LITERAL_TOKEN.test(token))
) {
throw new Error(`Refusing unsafe npm argument ${JSON.stringify(token)}`);
}
});
if (platform !== "win32") return npmExecInvocation(platform, bin, cmdArgs, opts);
const line = [bin, ...cmdArgs.map((t) => (LITERAL_TOKEN.test(t) ? t : escapeWindowsShellArg(t)))];
return [line.join(" "), [], opts];
}
export function runPluginNpm(args, platform = process.platform) {
const [file, fileArgs, opts] = buildPluginNpmInvocation(args, platform);
const res = spawnSync(file, fileArgs, opts);
if (res.error) throw res.error;
if (typeof res.status === "number" && res.status !== 0) {
throw new Error(`${file.split(" ")[0]} exited with code ${res.status}`);
}
}

View File

@@ -1,4 +1,4 @@
import { readdirSync, existsSync, readFileSync } from "node:fs";
import { readdirSync, existsSync, readFileSync, statSync } from "node:fs";
import { join } from "node:path";
import { homedir } from "node:os";
import { pathToFileURL } from "node:url";
@@ -6,24 +6,51 @@ import { pathToFileURL } from "node:url";
const PLUGIN_PREFIX_RE = /^(@[^/]+\/)?omniroute-cmd-/;
function getPluginDirs() {
return [join(homedir(), ".omniroute", "plugins"), process.env.OMNIROUTE_PLUGIN_PATH].filter(
Boolean
);
const prefix = join(homedir(), ".omniroute", "plugins");
// `omniroute plugin install` uses `prefix` as an npm --prefix, so packages land in
// `<prefix>/node_modules` (#21056).
return [prefix, join(prefix, "node_modules"), process.env.OMNIROUTE_PLUGIN_PATH].filter(Boolean);
}
function isDir(path) {
try {
return statSync(path).isDirectory(); // follows symlinks (npm links local installs)
} catch {
return false;
}
}
function listCandidates(dir) {
const out = [];
for (const entry of readdirSync(dir, { withFileTypes: true })) {
if (entry.name.startsWith(".")) continue;
const full = join(dir, entry.name);
if (!isDir(full)) continue;
if (entry.name.startsWith("@")) {
try {
for (const sub of readdirSync(full)) out.push(join(full, sub));
} catch {
// ignore unreadable scope dir
}
} else {
out.push(full);
}
}
return out;
}
export async function discoverPlugins() {
const found = [];
for (const dir of getPluginDirs()) {
if (!existsSync(dir)) continue;
let entries;
let candidates;
try {
entries = readdirSync(dir, { withFileTypes: true });
candidates = listCandidates(dir);
} catch {
continue;
}
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const pkgPath = join(dir, entry.name, "package.json");
for (const candidate of candidates) {
const pkgPath = join(candidate, "package.json");
if (!existsSync(pkgPath)) continue;
let pkg;
try {
@@ -32,11 +59,12 @@ export async function discoverPlugins() {
continue;
}
if (!pkg.name || !PLUGIN_PREFIX_RE.test(pkg.name)) continue;
if (found.some((f) => f.name === pkg.name)) continue;
found.push({
name: pkg.name,
version: pkg.version || "0.0.0",
description: pkg.description || "",
dir: join(dir, entry.name),
dir: candidate,
pkg,
});
}
@@ -67,6 +95,12 @@ export function buildPluginContext(opts = {}) {
};
}
// Startup entry (#21056): `--version`/`-v` stays fast and never imports plugin code.
export async function loadCliPlugins(program, argv = process.argv, env = process.env) {
if (argv.slice(2).some((a) => a === "--version" || a === "-v")) return 0;
return loadPlugins(program, { baseUrl: env.OMNIROUTE_BASE_URL, apiKey: env.OMNIROUTE_API_KEY });
}
export async function loadPlugins(program, ctx = {}) {
const plugins = await discoverPlugins();
for (const p of plugins) {

View File

@@ -449,6 +449,10 @@ try {
pathToFileURL(join(ROOT, "bin", "cli", "program.mjs")).href
);
const program = createProgram();
const { loadCliPlugins } = await import(
pathToFileURL(join(ROOT, "bin", "cli", "plugins.mjs")).href
);
await loadCliPlugins(program);
await program.parseAsync(process.argv);
} catch (err) {
if (err?.exitCode !== undefined) process.exit(err.exitCode);

View File

@@ -0,0 +1 @@
- fix(cli): CLI plugins are now loaded at startup, `plugin install` uses the directory discovery scans (and `.`/local paths, npm.cmd on Windows), scaffold range matches the host version (#21056)

View File

@@ -45,7 +45,7 @@ omniroute-cmd-myplugin/
"version": "0.1.0",
"type": "module",
"main": "index.mjs",
"engines": { "omniroute": ">=4.0.0" },
"engines": { "omniroute": ">=3.8.0" },
"keywords": ["omniroute-plugin", "omniroute-cmd"]
}
```
@@ -57,7 +57,7 @@ export const meta = {
name: "myplugin",
version: "0.1.0",
description: "My plugin for OmniRoute",
omnirouteApi: ">=4.0.0",
omnirouteApi: ">=3.8.0",
};
export function register(program, ctx) {
@@ -94,8 +94,11 @@ The `ctx` object passed to `register(program, ctx)`:
Plugins are discovered from:
1. `~/.omniroute/plugins/<name>/` — user-local installs
2. `OMNIROUTE_PLUGIN_PATH` env var — custom directory
1. `~/.omniroute/plugins/node_modules/<name>/` — where `omniroute plugin install` puts packages (an npm `--prefix`, not `npm -g`)
2. `~/.omniroute/plugins/<name>/` — hand-copied plugin directories
3. `OMNIROUTE_PLUGIN_PATH` env var — custom directory
Symlinked directories (what npm creates for `plugin install ./dir`) are followed.
Both are **CLI-only**. The server-side plugin runtime (the marketplace/`plugin.json`
plugins that run inside the proxy) has its own scanner with its own override,

View File

@@ -0,0 +1,152 @@
// tests/unit/repro-21056.test.ts (written in the probe worktree, now removed; copy kept in the session scratchpad)
import test from "node:test";
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import {
chmodSync,
mkdirSync,
mkdtempSync,
readFileSync,
writeFileSync,
existsSync,
} from "node:fs";
import { join, dirname } from "node:path";
import { tmpdir } from "node:os";
import { fileURLToPath } from "node:url";
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
const BIN = join(ROOT, "bin", "omniroute.mjs");
function makePlugin(parent: string, name = "omniroute-cmd-hello", cmd = "hello-plugin") {
const dir = join(parent, name);
mkdirSync(dir, { recursive: true });
writeFileSync(
join(dir, "package.json"),
JSON.stringify({ name, version: "1.0.0", type: "module", main: "index.mjs" })
);
writeFileSync(
join(dir, "index.mjs"),
`export function register(program){ program.command("${cmd}").description("fixture").action(()=>console.log("RAN")); }\n`
);
return dir;
}
function cli(args: string[], env: Record<string, string>) {
return spawnSync(process.execPath, [BIN, ...args], {
env: { ...process.env, OMNIROUTE_NO_UPDATE_NOTIFIER: "1", ...env },
encoding: "utf8",
timeout: 90_000,
});
}
test("#21056-1: a discovered plugin's command shows up in --help (loadPlugins wired in)", () => {
const sandbox = mkdtempSync(join(tmpdir(), "repro-21056-a-"));
const plugDir = join(sandbox, "plug");
makePlugin(plugDir);
const env = {
HOME: join(sandbox, "home"),
USERPROFILE: join(sandbox, "home"),
DATA_DIR: join(sandbox, "data"),
OMNIROUTE_PLUGIN_PATH: plugDir,
};
const list = cli(["plugin", "list", "--output", "json"], env);
assert.match(list.stdout, /omniroute-cmd-hello/, "precondition: discovery finds the fixture");
const help = cli(["--help"], env);
assert.match(help.stdout, /hello-plugin/, "plugin command must be registered in --help");
});
test("#21056-1b: nothing under bin/ invokes loadPlugins()", () => {
const grep = spawnSync("git", ["grep", "-n", "loadPlugins(", "--", "bin"], {
cwd: ROOT,
encoding: "utf8",
});
const callers = grep.stdout
.split("\n")
.filter((l) => l && !l.includes("export async function loadPlugins"));
assert.ok(callers.length > 0, "expected at least one caller of loadPlugins in bin/, got none");
});
test("#21056-2: `plugin install .` / `plugin install ./x` hand npm the right spec, and use a location discovery scans", () => {
const sandbox = mkdtempSync(join(tmpdir(), "repro-21056-b-"));
const fakeBin = join(sandbox, "bin");
mkdirSync(fakeBin);
const log = join(sandbox, "npm-argv.txt");
writeFileSync(join(fakeBin, "npm"), `#!/bin/sh\necho "$@" >> "${log}"\nexit 0\n`);
chmodSync(join(fakeBin, "npm"), 0o755);
const env = {
HOME: join(sandbox, "home"),
USERPROFILE: join(sandbox, "home"),
DATA_DIR: join(sandbox, "data"),
PATH: `${fakeBin}:${process.env.PATH}`,
};
cli(["plugin", "install", ".", "--yes"], env);
cli(["plugin", "install", "./local-plugin", "--yes"], env);
const argv = existsSync(log) ? readFileSync(log, "utf8").trim().split("\n") : [];
console.log("npm argv recorded:", JSON.stringify(argv));
assert.equal(argv.length, 2);
assert.doesNotMatch(
argv[0],
/omniroute-cmd-\./,
"`install .` must not become package omniroute-cmd-."
);
assert.doesNotMatch(
argv[1],
/(^| )-g( |$)/,
"install uses -g, a location discoverPlugins() never scans"
);
assert.match(argv[1], /--prefix \S*\.omniroute\/plugins /);
});
test("#21056-2b: a plugin installed with the CLI's own npm --prefix is found by `plugin list` (symlink too)", () => {
const sandbox = mkdtempSync(join(tmpdir(), "repro-21056-c-"));
const src = makePlugin(join(sandbox, "src"), "omniroute-cmd-glob", "glob-cmd");
const home = join(sandbox, "home");
const env = { HOME: home, USERPROFILE: home, DATA_DIR: join(sandbox, "data") };
const prefix = join(home, ".omniroute", "plugins");
mkdirSync(prefix, { recursive: true });
const inst = spawnSync(
"npm",
["install", "--prefix", prefix, src, "--offline", "--no-audit", "--no-fund"],
{ env: { ...process.env, ...env }, encoding: "utf8", timeout: 60_000 }
);
assert.equal(inst.status, 0, inst.stderr);
const list = cli(["plugin", "list", "--output", "json"], env);
assert.match(list.stdout, /omniroute-cmd-glob/);
const help = cli(["--help"], env);
assert.match(help.stdout, /glob-cmd/);
});
test("#21056-2c: spec resolution and win32 invocation", async () => {
const m = await import("../../bin/cli/pluginNpm.mjs");
assert.equal(m.isLocalPluginSpec("."), true);
assert.equal(m.isLocalPluginSpec("C:\\x\\p"), true);
assert.equal(m.isLocalPluginSpec("stripe"), false);
assert.equal(m.resolvePluginSpec("stripe"), "omniroute-cmd-stripe");
assert.equal(m.resolvePluginSpec(".", "/a/b"), "/a/b");
const [file, args, opts] = m.buildPluginNpmInvocation(
["install", "--prefix", "C:\\Users\\a b\\.omniroute\\plugins", "omniroute-cmd-x"],
"win32"
);
assert.match(file, /^npm\.cmd install --prefix \^+"C:/);
assert.deepEqual(args, []);
assert.equal(opts.shell, true);
assert.throws(() => m.buildPluginNpmInvocation(["install", "a\nb"], "win32"));
});
test("#21056-3: plugin.mjs spawns npm via the win32-aware helper and surfaces the real error", () => {
const src = readFileSync(join(ROOT, "bin/cli/commands/plugin.mjs"), "utf8");
assert.match(readFileSync(join(ROOT, "bin/cli/pluginNpm.mjs"), "utf8"), /npm-exec\.mjs/);
assert.doesNotMatch(src, /spawnSync\(pm, cmdArgs, \{ stdio: "inherit", shell: false \}\)/);
assert.doesNotMatch(src, /catch \{\s*process\.stderr\.write\(`✗ Failed to install/);
});
test("#21056-4: scaffold does not require a 4.0.0 host that no release satisfies", () => {
const pkg = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8"));
const src = readFileSync(join(ROOT, "bin/cli/commands/plugin.mjs"), "utf8");
const major = Number(String(pkg.version).split(".")[0]);
const m = [...src.matchAll(/>=(\d+)\.0\.0/g)].map((x) => Number(x[1]));
void 0;
assert.ok(
m.every((x) => x <= major),
`scaffold requires >=${m.join(",")}.0.0 but CLI is ${pkg.version}`
);
});