An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): a parse error prints the Astryx error format in text mode (#6624)
Joey9143f0319079
diff --git a/.changeset/cli-parse-error-astryx-format.md b/.changeset/cli-parse-error-astryx-format.mdnew file mode 100644index 0000000000..82625a5e83--- /dev/null+++ b/.changeset/cli-parse-error-astryx-format.md@@ -0,0 +1,19 @@+---+'@astryxdesign/cli': patch+---++[fix] A parse error prints the Astryx error format in text mode.++`astryx theme list --lang zh-Hans` printed Commander's own line —+`error: option '--lang <locale>' argument 'zh-Hans' is invalid…` — while every+other CLI error prints `Error: …`. `--json` was already correct+(`ERR_INVALID_LANG`), so the two modes agreed only on the exit code.++Commander writes that line before any Astryx code runs, so the JSON shim — the+one place that already sees every parse failure — now suppresses it and writes+the Astryx line itself, from the same message, for both modes. Every parse+failure is covered: unknown option, unknown command, missing argument, and an+invalid value for a global option. `--help` and `--version` are untouched and+still exit 0.++@josephfarinadiff --git a/packages/cli/clients/cli/lib/json-shim.mjs b/packages/cli/clients/cli/lib/json-shim.mjsindex 006f1a8dbb..22dba4aa8b 100644--- a/packages/cli/clients/cli/lib/json-shim.mjs+++ b/packages/cli/clients/cli/lib/json-shim.mjs@@ -33,10 +33,12 @@* shows help because the invocation failed (`help <unknown>`, or a* command group with no subcommand), which exits 1.*- * Non-JSON behavior is preserved exactly: every code path that printed- * to stderr before still prints to stderr. Commander writes its- * "error: ..." line via configureOutput.writeErr, which we pass- * through verbatim outside of --json mode.+ * Commander writes its own "error: ..." line via configureOutput.writeErr.+ * The shim drops that line in both modes. Under --json the error envelope+ * replaces it; in text mode `handleCommanderError` writes the Astryx line+ * instead (`Error: <message>`, the same message the envelope carries), so+ * a parse failure reads like every other CLI error. Other stderr output,+ * such as help printed as the failure report, still passes through.*/import {API_VERSION, isJsonMode, toErrorEnvelope} from '../../../foundation/response/json.mjs';@@ -249,11 +251,20 @@ function applyShimRecursively(cmd) {});cmd.configureOutput({writeOut: (str) => process.stdout.write(str),+ // Commander's own "error: ..." line never reaches the user. Under --json a+ // consumer parsing both streams must not see it alongside the envelope;+ // in text mode it is Commander's format, not Astryx's, so an invalid+ // global option (`--lang zh-Hans`) printed `error: option '--lang+ // <locale>' argument 'zh-Hans' is invalid…` where every other CLI error+ // prints `Error: …`. handleCommanderError writes the Astryx line below,+ // for both modes, from the same message.+ //+ // ONLY that line. Commander also writes HELP through this channel when it+ // shows help because the invocation failed (a command group with no+ // subcommand), and that output is still wanted in text mode.writeErr: (str) => {- // Suppress Commander's "error: ..." stderr line when --json is- // active, so a JSON consumer parsing both streams doesn't see- // it alongside the envelope. Non-JSON callers are unaffected.if (jsonActive()) return;+ if (/^error:\s/i.test(str)) return;process.stderr.write(str);},});@@ -432,16 +443,15 @@ export function handleCommanderError(err) {code: commanderCodeToErrorCode(code, message),});- // Real error paths.+ // Real error paths. Strip Commander's "error: " prefix once: in the envelope+ // the key is already `error`, and in text mode the Astryx prefix replaces it.+ const cleaned = message.replace(/^error:\s*/i, '');if (jsonActive()) {- // Strip Commander's "error: " prefix — the envelope key is `error`- // already, doubled "error" is noise.- const cleaned = message.replace(/^error:\s*/i, '');emitJsonError(cleaned, undefined, commanderCodeToErrorCode(code, cleaned));} else {- // Non-JSON mode: Commander already wrote the "error: ..." line- // to stderr via configureOutput.writeErr before throwing the- // CommanderError. Nothing to do — exit with the original code.+ // Commander's own line was suppressed above, so a parse failure reads the+ // same as every other CLI error — the `Error: …` line cliError prints.+ process.stderr.write(`Error: ${cleaned}\n`);}process.exit(exitCode || 1);}diff --git a/packages/cli/clients/cli/lib/parse-error-format.test.mjs b/packages/cli/clients/cli/lib/parse-error-format.test.mjsnew file mode 100644index 0000000000..43db063d94--- /dev/null+++ b/packages/cli/clients/cli/lib/parse-error-format.test.mjs@@ -0,0 +1,81 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file A parse failure reads like every other Astryx error in text mode.+ *+ * `astryx theme list --lang zh-Hans` printed Commander's own line —+ * `error: option '--lang <locale>' argument 'zh-Hans' is invalid…` — while+ * every other CLI error prints `Error: …`. `--json` was already correct+ * (ERR_INVALID_LANG), so text and JSON disagreed on everything except the exit+ * code. Commander writes that line before any Astryx code runs, so the shim is+ * the only place that can speak for it.+ */++import {describe, it, expect} from 'vitest';+import {Command} from 'commander';+import {runCli} from '../../../test-utils/run-cli.mjs';+import {installJsonShim} from './json-shim.mjs';++describe('a parse error prints the Astryx error format', () => {+ it.each([+ ['invalid --lang value', ['theme', 'list', '--lang', 'zh-Hans'], 'ERR_INVALID_LANG'],+ ['invalid --detail value', ['theme', 'list', '--detail', 'nope'], 'ERR_INVALID_DETAIL'],+ ['unknown option', ['component', '--bogus-flag'], 'ERR_INVALID_OPTION'],+ ['missing argument', ['theme', 'build'], 'ERR_MISSING_ARGUMENT'],+ ])('%s', async (_label, args, code) => {+ const human = await runCli(args);++ expect(human.status).toBe(1);+ expect(human.stderr).toContain('Error: ');+ // Commander's own lowercase line must not reach the user.+ expect(human.stderr).not.toMatch(/(^|\n)error: /);++ // --json is unchanged, and the two modes agree on the exit code.+ const json = await runCli(['--json', ...args]);+ expect(json.status).toBe(human.status);+ expect(JSON.parse(json.stdout).code).toBe(code);+ expect(json.stderr).toBe('');+ });++ it('carries Commander\'s explanation, not just a generic line', async () => {+ const {stderr} = await runCli(['theme', 'list', '--lang', 'zh-Hans']);+ expect(stderr).toContain("'zh-Hans' is invalid");+ expect(stderr).toContain('en, zh, dense');+ });++ it('leaves --help and --version at exit 0 with nothing on stderr', async () => {+ for (const args of [['--help'], ['theme', '--help']]) {+ const r = await runCli(args);+ expect(r.status).toBe(0);+ expect(r.stderr).toBe('');+ }+ });++ // Commander writes help through the same stderr channel when it shows help+ // BECAUSE the invocation failed, so suppressing that channel wholesale would+ // have taken the help with it. Driven on a throwaway program rather than a+ // real command, so the guard outlives whichever command happens to have a+ // subcommand group today.+ it('still lets help reach stderr when help IS the failure report', () => {+ const program = new Command('probe');+ const group = program.command('group');+ group.command('leaf').action(() => {});+ installJsonShim(program);++ /** @type {string[]} */+ const written = [];+ const original = process.stderr.write;+ // @ts-expect-error test double for the write signature+ process.stderr.write = str => {+ written.push(String(str));+ return true;+ };+ try {+ group.outputHelp({error: true});+ } finally {+ process.stderr.write = original;+ }++ expect(written.join('')).toMatch(/Usage: probe group/);+ });+});diff --git a/packages/cli/test-utils/run-cli.mjs b/packages/cli/test-utils/run-cli.mjsindex 0c0635ead5..d632ca331b 100644--- a/packages/cli/test-utils/run-cli.mjs+++ b/packages/cli/test-utils/run-cli.mjs@@ -120,7 +120,7 @@ export async function runCli(args, cwdOrOpts) {// CommanderError from exitOverride() (parse error / --help / --version).// Mirror bin/astryx.mjs's error boundary: route it through the JSON shim// so --json consumers get a valid envelope (with the mapped ERR_ code)- // and non-JSON callers keep Commander's stderr line. handleCommanderError+ // and non-JSON callers get the Astryx `Error: …` line. handleCommanderError// calls process.exit, which our trap re-raises as an ExitSignal.try {handleCommanderError(e);