Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(cli): add stable machine-readable error codes to all errors (#2562)

Joey5c59aa2e3f97
diff --git a/packages/cli/README.md b/packages/cli/README.md
index f33fff16f8..0dd7e8a229 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -68,7 +68,7 @@ Options:
These flags work with any command:
-- `--json` — Output as typed JSON envelope: `{ type, data }`
+- `--json` — Output as typed JSON envelope: `{ type, data }` (errors: `{ error, code, suggestions? }`)
- `--detail <level>` — Detail level for list views, increasing in size: `brief` (names only, default for `--list`) < `compact` (names + 1-line descriptions) < `full` (full docs per entry). Single-item views default to `full`.
- `--zh` — Output docs in Chinese Simplified
- `--dense` — Compressed format (token-efficient, useful for AI agents)
@@ -87,10 +87,81 @@ Errors:
```json
{
"error": "No component named \"Buttn\"",
+ "code": "ERR_UNKNOWN_COMPONENT",
"suggestions": [{"name": "Button", "reason": "similar name"}]
}
```
+The `code` field is a **stable, machine-readable identifier**. Branch on it —
+never on the human-readable `error` string, which changes freely as we improve
+wording. Every error envelope carries a `code` (falling back to `ERR_UNKNOWN`
+when no more specific code applies). The same `code` is exposed on thrown
+`XDSError` instances from the programmatic API, so both surfaces agree.
+
+Codes are **append-only**: once shipped, a code's meaning never changes and a
+code is never removed. New error conditions get new codes.
+
+```typescript
+import {isError} from '@xds/cli/json';
+
+const result = parseResponse(raw);
+if (isError(result)) {
+ switch (result.code) {
+ case 'ERR_UNKNOWN_COMPONENT':
+ // suggest the closest match
+ break;
+ case 'ERR_CORE_NOT_FOUND':
+ // prompt the user to install @xds/core
+ break;
+ default:
+ console.error(result.error);
+ }
+}
+```
+
+### Error codes
+
+| Code | Meaning |
+| --- | --- |
+| `ERR_UNKNOWN` | Generic fallback for any error without a more specific code. |
+| `ERR_UNKNOWN_COMMAND` | A top-level command name was not recognized (e.g. `xds bogus`). |
+| `ERR_UNKNOWN_SUBCOMMAND` | A subcommand under a group was not recognized (e.g. `xds theme bogus`). |
+| `ERR_INVALID_OPTION` | An unknown flag was passed, or `--json` was used on a command that doesn't support it. |
+| `ERR_INVALID_ARGUMENT` | An option/argument value was rejected, or required flags were missing. |
+| `ERR_MISSING_ARGUMENT` | A required positional argument was omitted (e.g. `xds theme build` with no file). |
+| `ERR_INVALID_LANG` | `--lang` was given a value outside its choices (`en`, `zh`, `dense`). |
+| `ERR_INVALID_DETAIL` | `--detail` was given a value outside its choices (`full`, `compact`, `brief`). |
+| `ERR_NODE_VERSION` | The running Node.js version is below the supported minimum. |
+| `ERR_CORE_NOT_FOUND` | `@xds/core` could not be located (not installed / not in a monorepo). |
+| `ERR_UNKNOWN_COMPONENT` | No component matched the requested name. |
+| `ERR_UNKNOWN_HOOK` | No hook matched the requested name. |
+| `ERR_UNKNOWN_TOPIC` | No docs topic matched the requested name. |
+| `ERR_UNKNOWN_SECTION` | A docs topic exists but the requested section within it does not. |
+| `ERR_UNKNOWN_CATEGORY` | A `--category` filter value did not match any known category. |
+| `ERR_UNKNOWN_TEMPLATE` | No template matched the requested name. |
+| `ERR_UNKNOWN_PACKAGE` | No package matched the requested name (discover). |
+| `ERR_UNKNOWN_AGENT` | An unrecognized `--agent` value was passed (agent docs / init). |
+| `ERR_UNKNOWN_FEATURE` | An unrecognized `--features` value was passed to `init`. |
+| `ERR_UNKNOWN_CODEMOD` | A `--codemod` value did not match any registered codemod (upgrade). |
+| `ERR_NOT_FOUND` | A discover/lookup query matched nothing in any package. |
+| `ERR_NO_DOC` | A component exists but has no typed `.doc.mjs` file. |
+| `ERR_NO_SHOWCASE` | No showcase exists for the requested component. |
+| `ERR_NO_SOURCE` | No source file could be located for the component/template. |
+| `ERR_INVALID_DOC` | A component's docs failed validation (malformed `.doc.mjs`). |
+| `ERR_FILE_NOT_FOUND` | A required input file did not exist. |
+| `ERR_FILE_EXISTS` | Refused to overwrite an existing file in non-interactive mode. |
+| `ERR_PATH_TRAVERSAL` | A path escaped its allowed root, or a name contained traversal markers. |
+| `ERR_WRITE_FAILED` | Writing output files failed (and was rolled back). |
+| `ERR_THEME_INVALID` | A theme definition was missing a required property (e.g. `name`). |
+| `ERR_THEME_LOAD` | A theme file could not be loaded / parsed into a `defineTheme` result. |
+| `ERR_TEMPLATE_CONFIG` | `template.get` is not configured in `xds.config.mjs` (fetch-by-id). |
+| `ERR_TEMPLATE_GET` | A configured `template.get` threw or returned an invalid value. |
+| `ERR_VERSION_DETECT` | The current `@xds/core` version could not be detected. |
+| `ERR_INVALID_VERSION` | A `--from`/`--to` value was not a valid semver string. |
+| `ERR_DEP_MISSING` | A required external dependency (e.g. jscodeshift) is missing. |
+| `ERR_GH_CLI` | GitHub CLI (`gh`) is not installed or not authenticated. |
+| `ERR_GAP_REPORT_FAILED` | Filing a gap report failed (disabled, or the integration errored). |
+
## Programmatic API
The same logic that powers `xds --json` is available as importable, type-safe functions:
@@ -115,11 +186,12 @@ principles.data.title; // 'XDS Principles'
const useMediaQuery = await hook('useMediaQuery');
useMediaQuery.data.params; // typed as HookParamDoc[]
-// Errors throw XDSError with optional .suggestions
+// Errors throw XDSError with a stable .code and optional .suggestions
try {
await component('Buttn');
} catch (e) {
e.message; // 'No component named "Buttn"'
+ e.code; // 'ERR_UNKNOWN_COMPONENT' (stable; branch on this)
e.suggestions; // [{ name: 'Button', reason: 'similar name' }]
}
```
diff --git a/packages/cli/bin/xds.mjs b/packages/cli/bin/xds.mjs
index 1be8c1b129..450f63c71d 100644
--- a/packages/cli/bin/xds.mjs
+++ b/packages/cli/bin/xds.mjs
@@ -18,7 +18,22 @@ import {
} from '../src/lib/node-version.mjs';
if (!isNodeVersionSupported(process.versions.node)) {
- console.error(unsupportedNodeMessage(process.versions.node));
+ const msg = unsupportedNodeMessage(process.versions.node);
+ // Honor the --json contract even at this pre-import gate. We can't import
+ // json.mjs here (it transitively loads styleText, the very thing this gate
+ // protects against), so emit a minimal hand-rolled envelope. The shape and
+ // the stable `code` (ERR_NODE_VERSION) match error-codes.mjs.
+ if (process.argv.slice(2).includes('--json')) {
+ console.log(
+ JSON.stringify(
+ {apiVersion: 1, error: msg, code: 'ERR_NODE_VERSION'},
+ null,
+ 2,
+ ),
+ );
+ } else {
+ console.error(msg);
+ }
process.exit(1);
}
diff --git a/packages/cli/src/api/component.mjs b/packages/cli/src/api/component.mjs
index 19d195a973..39026fc676 100644
--- a/packages/cli/src/api/component.mjs
+++ b/packages/cli/src/api/component.mjs
@@ -8,6 +8,7 @@
*/
import * as fs from 'node:fs';
+import {ERROR_CODES} from '../lib/error-codes.mjs';
import {findCoreDir, discoverExternalPackages} from '../utils/paths.mjs';
import {
discoverComponents,
@@ -76,7 +77,7 @@ export async function component(name, options = {}) {
const coreDir = findCoreDir(cwd);
if (!coreDir) {
- throw new XDSError('Could not find @xds/core package');
+ throw new XDSError('Could not find @xds/core package', undefined, ERROR_CODES.ERR_CORE_NOT_FOUND);
}
// ── List mode ──────────────────────────────────────────────────
@@ -92,6 +93,7 @@ export async function component(name, options = {}) {
throw new XDSError(
`Unknown category "${category}"`,
Object.keys(components).map(k => ({name: k, reason: 'valid category'})),
+ ERROR_CODES.ERR_UNKNOWN_CATEGORY,
);
}
@@ -217,13 +219,13 @@ export async function component(name, options = {}) {
if (packageScope) {
const ext = resolveExternalPackage(packageScope, cwd);
if (!ext) {
- throw new XDSError(`External package "${packageScope}" not found`);
+ throw new XDSError(`External package "${packageScope}" not found`, undefined, ERROR_CODES.ERR_UNKNOWN_PACKAGE);
}
if (showcase) {
const match = await findShowcase(dirName, cwd, {package: packageScope});
if (!match) {
- throw new XDSError(`No showcase found for "${name}" in package "${packageScope}"`);
+ throw new XDSError(`No showcase found for "${name}" in package "${packageScope}"`, undefined, ERROR_CODES.ERR_NO_SHOWCASE);
}
return {
type: 'component.detail.showcase',
@@ -245,13 +247,13 @@ export async function component(name, options = {}) {
}
return {type: 'component.detail', data: docs};
}
- throw new XDSError(`No component "${name}" in package "${packageScope}"`);
+ throw new XDSError(`No component "${name}" in package "${packageScope}"`, undefined, ERROR_CODES.ERR_UNKNOWN_COMPONENT);
}
if (source) {
const sourcePath = findComponentSource(coreDir, dirName);
if (!sourcePath) {
- throw new XDSError(`Source for "${name}" not found`);
+ throw new XDSError(`Source for "${name}" not found`, undefined, ERROR_CODES.ERR_NO_SOURCE);
}
return {type: 'component.detail.source', data: {component: dirName, source: fs.readFileSync(sourcePath, 'utf-8')}};
}
@@ -259,7 +261,7 @@ export async function component(name, options = {}) {
if (showcase) {
const match = await findShowcase(dirName, cwd);
if (!match) {
- throw new XDSError(`No showcase found for "${name}"`);
+ throw new XDSError(`No showcase found for "${name}"`, undefined, ERROR_CODES.ERR_NO_SHOWCASE);
}
return {
type: 'component.detail.showcase',
@@ -307,15 +309,16 @@ export async function component(name, options = {}) {
throw new XDSError(
`No component named "${name}"`,
candidates.map(c => ({name: c.name, reason: c.reason})),
+ ERROR_CODES.ERR_UNKNOWN_COMPONENT,
);
}
} else {
- throw new XDSError(`No component named "${name}"`);
+ throw new XDSError(`No component named "${name}"`, undefined, ERROR_CODES.ERR_UNKNOWN_COMPONENT);
}
}
if (!readmePath || !readmePath.endsWith('.doc.mjs')) {
- throw new XDSError(`No .doc.mjs found for "${resolvedName}". The component needs a typed doc file.`);
+ throw new XDSError(`No .doc.mjs found for "${resolvedName}". The component needs a typed doc file.`, undefined, ERROR_CODES.ERR_NO_DOC);
}
const docs = await loadDocs(readmePath, {zh, dense, lang});
diff --git a/packages/cli/src/api/discover.mjs b/packages/cli/src/api/discover.mjs
index 5f096db04b..a4bce6a2ea 100644
--- a/packages/cli/src/api/discover.mjs
+++ b/packages/cli/src/api/discover.mjs
@@ -9,6 +9,7 @@ import {scanAllPackages, findComponentInPackages} from '../lib/package-scanner.m
import {loadDocs} from '../lib/component-loader.mjs';
import {levenshteinDistance} from '../lib/string-utils.mjs';
import {XDSError} from './error.mjs';
+import {ERROR_CODES} from '../lib/error-codes.mjs';
function validateDocs(docs) {
if (!docs || typeof docs !== 'object') return 'docs export is missing or not an object';
@@ -68,6 +69,7 @@ export async function discover(query, options = {}) {
throw new XDSError(
`Package "${query}" not found`,
packages.map(p => ({name: p.name, reason: 'available package'})),
+ ERROR_CODES.ERR_UNKNOWN_PACKAGE,
);
}
return {type: 'discover.detail', data: toEntry(pkg)};
@@ -117,15 +119,16 @@ export async function discover(query, options = {}) {
throw new XDSError(
`"${query}" not found`,
fuzzyMatches.map(m => ({name: m.pkg.name + '/' + m.comp, reason: 'similar name'})),
+ ERROR_CODES.ERR_NOT_FOUND,
);
}
- throw new XDSError(`"${query}" not found in any package`);
+ throw new XDSError(`"${query}" not found in any package`, undefined, ERROR_CODES.ERR_NOT_FOUND);
}
async function resolveComponentDocs(packages, compName, pkgName, {lang, zh}) {
const pkg = packages.find(p => p.name === pkgName);
- if (!pkg) throw new XDSError(`Package "${pkgName}" not found`);
+ if (!pkg) throw new XDSError(`Package "${pkgName}" not found`, undefined, ERROR_CODES.ERR_UNKNOWN_PACKAGE);
const result = findComponentInPackages([pkg], compName);
if (!result) {
@@ -142,6 +145,7 @@ async function resolveComponentDocs(packages, compName, pkgName, {lang, zh}) {
throw new XDSError(
`Component "${compName}" not found in ${pkgName}`,
suggestions.map(s => ({name: s, reason: 'similar name'})),
+ ERROR_CODES.ERR_UNKNOWN_COMPONENT,
);
}
@@ -153,9 +157,9 @@ async function loadAndValidate(result, {lang, zh}) {
try {
docs = await loadDocs(result.docPath, {zh, lang});
} catch (e) {
- throw new XDSError(`Failed to load docs for ${result.componentName}: ${e.message}`);
+ throw new XDSError(`Failed to load docs for ${result.componentName}: ${e.message}`, undefined, ERROR_CODES.ERR_INVALID_DOC);
}
const err = validateDocs(docs);
- if (err) throw new XDSError(`Invalid docs for ${result.componentName}: ${err}`);
+ if (err) throw new XDSError(`Invalid docs for ${result.componentName}: ${err}`, undefined, ERROR_CODES.ERR_INVALID_DOC);
return {type: 'discover.detail.doc', data: docs};
}
diff --git a/packages/cli/src/api/docs.mjs b/packages/cli/src/api/docs.mjs
index 2e66dd095f..abb73338a1 100644
--- a/packages/cli/src/api/docs.mjs
+++ b/packages/cli/src/api/docs.mjs
@@ -9,6 +9,7 @@ import * as path from 'node:path';
import {pathToFileURL} from 'node:url';
import {CLI_ROOT} from '../utils/paths.mjs';
import {XDSError} from './error.mjs';
+import {ERROR_CODES} from '../lib/error-codes.mjs';
const DOCS_DIR = path.join(CLI_ROOT, 'docs');
@@ -138,6 +139,7 @@ export async function docs(topic, section, options = {}) {
throw new XDSError(
`Unknown topic "${topic}"`,
Object.keys(topics).map(t => ({name: t, reason: 'available topic'})),
+ ERROR_CODES.ERR_UNKNOWN_TOPIC,
);
}
@@ -150,6 +152,7 @@ export async function docs(topic, section, options = {}) {
throw new XDSError(
`Section "${section}" not found in "${topic}"`,
docsData.sections.map(s => ({name: s.title, reason: 'available section'})),
+ ERROR_CODES.ERR_UNKNOWN_SECTION,
);
}
return {type: 'docs.detail.section', data: match};
diff --git a/packages/cli/src/api/error.mjs b/packages/cli/src/api/error.mjs
index 6e687e6c91..fa59f6fa3a 100644
--- a/packages/cli/src/api/error.mjs
+++ b/packages/cli/src/api/error.mjs
@@ -2,19 +2,37 @@
/**
* @file API error class — carries structured error info matching CLIError shape.
+ *
+ * `XDSError` is what the API layer throws. Alongside the human-readable
+ * message and optional `suggestions`, it carries a stable machine-readable
+ * `code` (see ../lib/error-codes.mjs). When the CLI catches an XDSError and
+ * routes it through `cliError`, it propagates `e.code` so the JSON error
+ * envelope's `code` field matches the API contract exactly. The code defaults
+ * to `ERR_UNKNOWN` so older throw sites still produce a valid envelope.
*/
+import {ERROR_CODES} from '../lib/error-codes.mjs';
+
export class XDSError extends Error {
/** @type {Array<{name: string, reason: string}> | undefined} */
suggestions;
+ /**
+ * Stable, machine-readable error code (error-codes.mjs). Consumers branch
+ * on this, never on the message text.
+ * @type {string}
+ */
+ code;
+
/**
* @param {string} message
* @param {Array<{name: string, reason: string}>} [suggestions]
+ * @param {string} [code] - Stable error code. Defaults to ERR_UNKNOWN.
*/
- constructor(message, suggestions) {
+ constructor(message, suggestions, code) {
super(message);
this.name = 'XDSError';
+ this.code = code || ERROR_CODES.ERR_UNKNOWN;
if (suggestions?.length) this.suggestions = suggestions;
}
}
diff --git a/packages/cli/src/api/hook.mjs b/packages/cli/src/api/hook.mjs
index 0a4c75c75e..cad428d69f 100644
--- a/packages/cli/src/api/hook.mjs
+++ b/packages/cli/src/api/hook.mjs
@@ -12,6 +12,7 @@ import {discoverHooks, findHookDoc, getAllHookNames} from '../lib/hook-discovery
import {loadDocs} from '../lib/component-loader.mjs';
import {levenshteinDistance} from '../lib/string-utils.mjs';
import {XDSError} from './error.mjs';
+import {ERROR_CODES} from '../lib/error-codes.mjs';
/**
* @param {string} [name]
@@ -45,7 +46,7 @@ export async function hook(name, options = {}) {
const coreDir = findCoreDir(cwd);
if (!coreDir) {
- throw new XDSError('Could not find @xds/core package');
+ throw new XDSError('Could not find @xds/core package', undefined, ERROR_CODES.ERR_CORE_NOT_FOUND);
}
// ── List mode ──────────────────────────────────────────────────
@@ -61,6 +62,7 @@ export async function hook(name, options = {}) {
throw new XDSError(
`Unknown category "${category}"`,
Object.keys(hooks).map(k => ({name: k, reason: 'valid category'})),
+ ERROR_CODES.ERR_UNKNOWN_CATEGORY,
);
}
@@ -180,6 +182,7 @@ export async function hook(name, options = {}) {
throw new XDSError(
`No hook named "${name}"`,
suggestions,
+ ERROR_CODES.ERR_UNKNOWN_HOOK,
);
}
diff --git a/packages/cli/src/api/template.mjs b/packages/cli/src/api/template.mjs
index 62075d5dec..3b62c4e469 100644
--- a/packages/cli/src/api/template.mjs
+++ b/packages/cli/src/api/template.mjs
@@ -9,6 +9,7 @@ import * as path from 'node:path';
import {CLI_ROOT, discoverExternalPackages} from '../utils/paths.mjs';
import {assertWithin, isFilePathArg, PathSafetyError} from '../utils/path-safety.mjs';
import {XDSError} from './error.mjs';
+import {ERROR_CODES} from '../lib/error-codes.mjs';
import {loadConfig} from '../lib/config.mjs';
const TEMPLATES_DIR = path.join(CLI_ROOT, 'templates');
@@ -347,6 +348,8 @@ export async function getTemplateById(id, options = {}) {
" get: async (id) => { /* return template source string */ },\n" +
' },\n' +
' };',
+ undefined,
+ ERROR_CODES.ERR_TEMPLATE_CONFIG,
);
}
@@ -355,24 +358,30 @@ export async function getTemplateById(id, options = {}) {
source = await getter(id);
} catch (err) {
const detail = err instanceof Error ? err.message : String(err);
- throw new XDSError(`template.get("${id}") threw an error: ${detail}`);
+ throw new XDSError(`template.get("${id}") threw an error: ${detail}`, undefined, ERROR_CODES.ERR_TEMPLATE_GET);
}
if (source == null) {
throw new XDSError(
`template.get("${id}") returned ${source} — no template found for that ID`,
+ undefined,
+ ERROR_CODES.ERR_TEMPLATE_GET,
);
}
if (typeof source !== 'string') {
throw new XDSError(
`template.get("${id}") must return a string, got ${typeof source}`,
+ undefined,
+ ERROR_CODES.ERR_TEMPLATE_GET,
);
}
if (source.trim() === '') {
throw new XDSError(
`template.get("${id}") returned an empty string`,
+ undefined,
+ ERROR_CODES.ERR_TEMPLATE_GET,
);
}
@@ -414,6 +423,7 @@ export async function template(name, options = {}) {
throw new XDSError(
`Unknown template "${name}"`,
templates.map(t => ({name: t.dirName, reason: `${t.type} template`})),
+ ERROR_CODES.ERR_UNKNOWN_TEMPLATE,
);
}
@@ -422,10 +432,11 @@ export async function template(name, options = {}) {
throw new XDSError(
'Specify a template name for --skeleton',
templates.map(t => ({name: t.dirName, reason: `${t.type} template`})),
+ ERROR_CODES.ERR_UNKNOWN_TEMPLATE,
);
}
if (!fs.existsSync(match.filePath)) {
- throw new XDSError(`No source file found for template "${name}"`);
+ throw new XDSError(`No source file found for template "${name}"`, undefined, ERROR_CODES.ERR_NO_SOURCE);
}
const src = fs.readFileSync(match.filePath, 'utf-8');
return {
@@ -440,7 +451,7 @@ export async function template(name, options = {}) {
}
if (!fs.existsSync(match.filePath)) {
- throw new XDSError(`No source file found for template "${name}"`);
+ throw new XDSError(`No source file found for template "${name}"`, undefined, ERROR_CODES.ERR_NO_SOURCE);
}
if (show || !targetPath) {
@@ -467,7 +478,7 @@ export async function template(name, options = {}) {
});
} catch (err) {
if (err instanceof PathSafetyError) {
- throw new XDSError(err.message);
+ throw new XDSError(err.message, undefined, ERROR_CODES.ERR_PATH_TRAVERSAL);
}
throw err;
}
diff --git a/packages/cli/src/commands/agent-docs.mjs b/packages/cli/src/commands/agent-docs.mjs
index ef90ffd884..823f721a35 100644
--- a/packages/cli/src/commands/agent-docs.mjs
+++ b/packages/cli/src/commands/agent-docs.mjs
@@ -26,6 +26,7 @@ import {discoverComponents} from '../lib/component-discovery.mjs';
import {discoverHooks} from '../lib/hook-discovery.mjs';
import {humanLog} from '../lib/json.mjs';
import {cliError} from '../lib/cli-error.mjs';
+import {ERROR_CODES} from '../lib/error-codes.mjs';
const AGENTS_MD = 'AGENTS.md';
const CLAUDE_MD = 'CLAUDE.md';
@@ -432,7 +433,7 @@ export function registerAgentDocs(program) {
// Validate --agent
if (options.agent && !VALID_AGENTS.includes(options.agent)) {
- cliError(`Unknown agent "${options.agent}". Valid: ${VALID_AGENTS.join(', ')}`);
+ cliError(`Unknown agent "${options.agent}". Valid: ${VALID_AGENTS.join(', ')}`, {code: ERROR_CODES.ERR_UNKNOWN_AGENT});
return;
}
@@ -455,7 +456,7 @@ export function registerAgentDocs(program) {
});
} catch (err) {
if (err instanceof PathSafetyError) {
- cliError(err.message);
+ cliError(err.message, {code: ERROR_CODES.ERR_PATH_TRAVERSAL});
return;
}
throw err;
diff --git a/packages/cli/src/commands/build-theme.mjs b/packages/cli/src/commands/build-theme.mjs
index eef12075b8..77ac1075db 100644
--- a/packages/cli/src/commands/build-theme.mjs
+++ b/packages/cli/src/commands/build-theme.mjs
@@ -20,6 +20,7 @@ import {getRunPrefix} from '../utils/package-manager.mjs';
import {sanitizeName, PathSafetyError} from '../utils/path-safety.mjs';
import {jsonOut, jsonError, humanLog} from '../lib/json.mjs';
import {cliError} from '../lib/cli-error.mjs';
+import {ERROR_CODES} from '../lib/error-codes.mjs';
// Import shared theme processing from core — ensures build and runtime
// use the same logic for typography.scale expansion, prose, and component rules.
@@ -986,7 +987,7 @@ export function registerTheme(program) {
const unknown = String(extras[0]);
const known = (theme.commands || []).map((c) => c.name());
const suggestions = known.map((name) => ({name, reason: 'available subcommand'}));
- cliError(`unknown subcommand 'theme ${unknown}'`, {suggestions});
+ cliError(`unknown subcommand 'theme ${unknown}'`, {suggestions, code: ERROR_CODES.ERR_UNKNOWN_SUBCOMMAND});
return;
}
// Bare `xds theme` — show the subcommand list. Exit 0 (help is success).
@@ -1003,7 +1004,7 @@ export function registerTheme(program) {
const json = program.opts().json || false;
if (!fs.existsSync(filePath)) {
- cliError(`File not found: ${filePath}`);
+ cliError(`File not found: ${filePath}`, {code: ERROR_CODES.ERR_FILE_NOT_FOUND});
return;
}
@@ -1014,12 +1015,12 @@ export function registerTheme(program) {
try {
themeDef = await extractThemeDefinition(filePath);
} catch (e) {
- cliError(e.message);
+ cliError(e.message, {code: ERROR_CODES.ERR_THEME_LOAD});
return;
}
if (!themeDef.name) {
- cliError('Theme must have a name property.');
+ cliError('Theme must have a name property.', {code: ERROR_CODES.ERR_THEME_INVALID});
return;
}
@@ -1031,7 +1032,7 @@ export function registerTheme(program) {
sanitizeName(themeDef.name, {label: 'theme name'});
} catch (err) {
if (err instanceof PathSafetyError) {
- cliError(err.message);
+ cliError(err.message, {code: ERROR_CODES.ERR_PATH_TRAVERSAL});
return;
}
throw err;
@@ -1207,7 +1208,7 @@ export function registerTheme(program) {
try { fs.rmSync(s.tmp, {force: true}); } catch { /* best-effort */ }
}
const msg = `Failed to write theme outputs: ${err.message}`;
- cliError(msg);
+ cliError(msg, {code: ERROR_CODES.ERR_WRITE_FAILED});
return;
}
diff --git a/packages/cli/src/commands/component/index.mjs b/packages/cli/src/commands/component/index.mjs
index 0f6423033d..a19e460fbf 100644
--- a/packages/cli/src/commands/component/index.mjs
+++ b/packages/cli/src/commands/component/index.mjs
@@ -25,6 +25,7 @@ import {resolveTheme} from '../../lib/resolve-theme.mjs';
import {getRunPrefix} from '../../utils/package-manager.mjs';
import {jsonOut, jsonError, humanLog} from '../../lib/json.mjs';
import {cliError} from '../../lib/cli-error.mjs';
+import {ERROR_CODES} from '../../lib/error-codes.mjs';
import {component as componentApi} from '../../api/component.mjs';
import {findRelatedBlocks} from '../../api/template.mjs';
@@ -54,7 +55,7 @@ export function registerComponent(program) {
const validDetails = ['full', 'compact', 'brief'];
if (!validDetails.includes(detail)) {
- cliError(`Invalid --detail value "${detail}". Valid levels: ${validDetails.join(', ')}`);
+ cliError(`Invalid --detail value "${detail}". Valid levels: ${validDetails.join(', ')}`, {code: ERROR_CODES.ERR_INVALID_DETAIL});
return;
}
@@ -73,7 +74,7 @@ export function registerComponent(program) {
lang, zh, dense,
});
} catch (e) {
- cliError(e.message, {suggestions: e.suggestions});
+ cliError(e.message, {suggestions: e.suggestions, code: e.code});
return;
}
diff --git a/packages/cli/src/commands/discover.mjs b/packages/cli/src/commands/discover.mjs
index 8f3b984d5f..1f96ce2afa 100644
--- a/packages/cli/src/commands/discover.mjs
+++ b/packages/cli/src/commands/discover.mjs
@@ -32,7 +32,7 @@ export function registerDiscover(program) {
try {
result = await discoverApi(query, {components: options.components, lang, zh});
} catch (e) {
- cliError(e.message, {suggestions: e.suggestions});
+ cliError(e.message, {suggestions: e.suggestions, code: e.code});
return;
}
diff --git a/packages/cli/src/commands/docs.mjs b/packages/cli/src/commands/docs.mjs
index 82343b2120..b35522c2ef 100644
--- a/packages/cli/src/commands/docs.mjs
+++ b/packages/cli/src/commands/docs.mjs
@@ -116,7 +116,7 @@ export function registerDocs(program) {
} catch (e) {
// docs API throws structured errors with {name, reason} suggestions —
// pass them through untouched so the CLI envelope matches the API.
- cliError(e.message, {suggestions: e.suggestions || []});
+ cliError(e.message, {suggestions: e.suggestions || [], code: e.code});
return;
}
diff --git a/packages/cli/src/commands/gap-report.mjs b/packages/cli/src/commands/gap-report.mjs
index df81da48da..722e9b42ce 100644
--- a/packages/cli/src/commands/gap-report.mjs
+++ b/packages/cli/src/commands/gap-report.mjs
@@ -22,6 +22,7 @@ import {
import {getRunPrefix} from '../utils/package-manager.mjs';
import {jsonOut, jsonError, humanLog} from '../lib/json.mjs';
import {cliError} from '../lib/cli-error.mjs';
+import {ERROR_CODES} from '../lib/error-codes.mjs';
/**
* Decide whether we're in a context safe to actually file a report.
@@ -253,7 +254,7 @@ export function registerGapReport(program) {
const config = loadGapReportConfig();
if (!config.enabled) {
- if (json) return jsonError('Gap reporting is disabled');
+ if (json) return jsonError('Gap reporting is disabled', undefined, ERROR_CODES.ERR_GAP_REPORT_FAILED);
humanLog(
`Gap reporting is disabled (XDS_GAP_REPORT=off or xds.config.mjs).\n` +
`Run \`${getRunPrefix()} xds gap-report setup\` to configure.`,
@@ -274,7 +275,7 @@ export function registerGapReport(program) {
'GitHub CLI (gh) is not installed or not authenticated. ' +
'Install it from https://cli.github.com and run `gh auth login`. ' +
`Or run \`${getRunPrefix()} xds gap-report setup\` to configure a custom command.`;
- cliError(msg);
+ cliError(msg, {code: ERROR_CODES.ERR_GH_CLI});
return;
}
@@ -289,6 +290,7 @@ export function registerGapReport(program) {
if (!validCategory) {
cliError(
`Invalid category "${options.category}". Valid: ${GAP_CATEGORIES.map(c => c.value).join(', ')}`,
+ {code: ERROR_CODES.ERR_UNKNOWN_CATEGORY},
);
return;
}
@@ -341,7 +343,7 @@ export function registerGapReport(program) {
humanLog('\nGap reporting is disabled via configuration.\n');
}
} catch (err) {
- cliError(`Filing gap report failed: ${err.message}`);
+ cliError(`Filing gap report failed: ${err.message}`, {code: ERROR_CODES.ERR_GAP_REPORT_FAILED});
return;
}
return;
@@ -353,6 +355,8 @@ export function registerGapReport(program) {
return jsonError(
'gap-report --json requires --component, --category, and --reason. ' +
'Run with --list-categories to see valid categories.',
+ undefined,
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
);
}
diff --git a/packages/cli/src/commands/hook/index.mjs b/packages/cli/src/commands/hook/index.mjs
index 5d9a32ec3f..9d9e929618 100644
--- a/packages/cli/src/commands/hook/index.mjs
+++ b/packages/cli/src/commands/hook/index.mjs
@@ -18,6 +18,7 @@ import {
import {getRunPrefix} from '../../utils/package-manager.mjs';
import {jsonOut, jsonError, humanLog} from '../../lib/json.mjs';
import {cliError} from '../../lib/cli-error.mjs';
+import {ERROR_CODES} from '../../lib/error-codes.mjs';
import {hook as hookApi} from '../../api/hook.mjs';
import {findRelatedBlocks} from '../../api/template.mjs';
@@ -41,7 +42,7 @@ export function registerHook(program) {
const validDetails = ['full', 'compact', 'brief'];
if (!validDetails.includes(detail)) {
- cliError(`Invalid --detail value "${detail}". Valid levels: ${validDetails.join(', ')}`);
+ cliError(`Invalid --detail value "${detail}". Valid levels: ${validDetails.join(', ')}`, {code: ERROR_CODES.ERR_INVALID_DETAIL});
return;
}
@@ -56,7 +57,7 @@ export function registerHook(program) {
lang, zh,
});
} catch (e) {
- cliError(e.message, {suggestions: e.suggestions});
+ cliError(e.message, {suggestions: e.suggestions, code: e.code});
return;
}
diff --git a/packages/cli/src/commands/init.mjs b/packages/cli/src/commands/init.mjs
index c98f7817c0..d0f1622055 100644
--- a/packages/cli/src/commands/init.mjs
+++ b/packages/cli/src/commands/init.mjs
@@ -23,6 +23,7 @@ import {installAgentDocs, removeAgentDocs} from './agent-docs.mjs';
import {listTemplates} from './template.mjs';
import {humanLog} from '../lib/json.mjs';
import {cliError} from '../lib/cli-error.mjs';
+import {ERROR_CODES} from '../lib/error-codes.mjs';
import {requireInteractive} from '../utils/interactive.mjs';
const VALID_FEATURES = ['agents', 'theme', 'template'];
@@ -104,7 +105,7 @@ async function runTemplate(targetDir, {interactive = true, templateName} = {}) {
}
if (!templates.includes(templateName)) {
- cliError(`Unknown template "${templateName}". Available: ${templates.join(', ')}`);
+ cliError(`Unknown template "${templateName}". Available: ${templates.join(', ')}`, {code: ERROR_CODES.ERR_UNKNOWN_TEMPLATE});
return;
}
@@ -178,7 +179,7 @@ export function registerInit(program) {
const invalid = features.filter(f => !VALID_FEATURES.includes(f));
if (invalid.length > 0) {
- cliError(`Unknown features: ${invalid.join(', ')}. Valid features: ${VALID_FEATURES.join(', ')}`);
+ cliError(`Unknown features: ${invalid.join(', ')}. Valid features: ${VALID_FEATURES.join(', ')}`, {code: ERROR_CODES.ERR_UNKNOWN_FEATURE});
return;
}
diff --git a/packages/cli/src/commands/swizzle.mjs b/packages/cli/src/commands/swizzle.mjs
index 8139d666c7..2534e0220e 100644
--- a/packages/cli/src/commands/swizzle.mjs
+++ b/packages/cli/src/commands/swizzle.mjs
@@ -19,6 +19,7 @@ import {assertWithin, PathSafetyError, isNonInteractive} from '../utils/path-saf
import {isInteractive} from '../utils/interactive.mjs';
import {jsonOut, jsonError, humanLog} from '../lib/json.mjs';
import {cliError} from '../lib/cli-error.mjs';
+import {ERROR_CODES} from '../lib/error-codes.mjs';
import {
buildGapReportPreview,
checkGhCli,
@@ -88,6 +89,7 @@ export function registerSwizzle(program) {
if (!coreDir) {
cliError(
'Could not find @xds/core package. Make sure you are inside the design system monorepo or have @xds/core installed.',
+ {code: ERROR_CODES.ERR_CORE_NOT_FOUND},
);
return;
}
@@ -112,7 +114,7 @@ export function registerSwizzle(program) {
if (!fs.existsSync(componentDir)) {
cliError(
`Component "${component}" not found.`,
- {suggestions: components.slice(0, 10).map((n) => ({name: n}))},
+ {suggestions: components.slice(0, 10).map((n) => ({name: n})), code: ERROR_CODES.ERR_UNKNOWN_COMPONENT},
);
return;
}
@@ -126,7 +128,7 @@ export function registerSwizzle(program) {
});
} catch (err) {
if (err instanceof PathSafetyError) {
- cliError(err.message);
+ cliError(err.message, {code: ERROR_CODES.ERR_PATH_TRAVERSAL});
return;
}
throw err;
@@ -151,7 +153,7 @@ export function registerSwizzle(program) {
const msg =
`Refusing to overwrite ${existingFiles.length} existing file(s) in ${relOutputForMsg}/. ` +
`Re-run with --overwrite (or -f) to replace them.`;
- cliError(msg);
+ cliError(msg, {code: ERROR_CODES.ERR_FILE_EXISTS});
return;
}
const confirmed = isCancel(
diff --git a/packages/cli/src/commands/template.mjs b/packages/cli/src/commands/template.mjs
index 15f35523d4..6830e28048 100644
--- a/packages/cli/src/commands/template.mjs
+++ b/packages/cli/src/commands/template.mjs
@@ -11,6 +11,7 @@ import {CLI_ROOT} from '../utils/paths.mjs';
import {isNonInteractive} from '../utils/path-safety.mjs';
import {jsonOut, jsonError, humanLog} from '../lib/json.mjs';
import {cliError} from '../lib/cli-error.mjs';
+import {ERROR_CODES} from '../lib/error-codes.mjs';
import {template as templateApi, getTemplateById} from '../api/template.mjs';
export {discoverTemplates, listTemplates, getTemplateById} from '../api/template.mjs';
@@ -50,7 +51,7 @@ export function registerTemplate(program) {
const msg =
`Refusing to overwrite existing file ${rel}. ` +
`Re-run with --overwrite (or -f) to replace it.`;
- cliError(msg);
+ cliError(msg, {code: ERROR_CODES.ERR_FILE_EXISTS});
return;
}
const confirmed = isCancel(
@@ -78,7 +79,7 @@ export function registerTemplate(program) {
} catch (e) {
// template API throws structured errors with {name, reason} suggestions —
// pass them through untouched so the CLI envelope matches the API.
- cliError(e.message, {suggestions: e.suggestions || []});
+ cliError(e.message, {suggestions: e.suggestions || [], code: e.code});
return;
}
@@ -143,7 +144,7 @@ export function registerTemplate(program) {
try {
result = await getTemplateById(options.id, {cwd: process.cwd()});
} catch (e) {
- cliError(e.message, {suggestions: e.suggestions});
+ cliError(e.message, {suggestions: e.suggestions, code: e.code});
return;
}
diff --git a/packages/cli/src/commands/upgrade.mjs b/packages/cli/src/commands/upgrade.mjs
index 612efc2410..4af23db54e 100644
--- a/packages/cli/src/commands/upgrade.mjs
+++ b/packages/cli/src/commands/upgrade.mjs
@@ -39,6 +39,7 @@ import {installAgentDocs, discoverAgentDocs} from './agent-docs.mjs';
import {detectPackageManager, getRunPrefix} from '../utils/package-manager.mjs';
import {isValidSemver, semverGte} from '../utils/semver.mjs';
import {jsonOut, jsonError} from '../lib/json.mjs';
+import {ERROR_CODES} from '../lib/error-codes.mjs';
/**
* Detect the installed @xds/core version from the consumer's package.json.
@@ -160,7 +161,7 @@ export function registerUpgrade(program) {
// and just emit "no codemods available").
if (options.to !== undefined && !isValidSemver(options.to)) {
const msg = `Invalid --to value: "${options.to}". Expected a semver string like 0.0.10.`;
- if (json) return jsonError(msg);
+ if (json) return jsonError(msg, undefined, ERROR_CODES.ERR_INVALID_VERSION);
p.log.error(msg);
p.outro('Aborted');
process.exitCode = 1;
@@ -168,7 +169,7 @@ export function registerUpgrade(program) {
}
if (options.from !== undefined && !isValidSemver(options.from)) {
const msg = `Invalid --from value: "${options.from}". Expected a semver string like 0.0.5.`;
- if (json) return jsonError(msg);
+ if (json) return jsonError(msg, undefined, ERROR_CODES.ERR_INVALID_VERSION);
p.log.error(msg);
p.outro('Aborted');
process.exitCode = 1;
@@ -208,7 +209,7 @@ export function registerUpgrade(program) {
const currentVersion = options.from ?? detectCurrentVersion();
if (!currentVersion && !skipVersionCheck) {
const msg = 'Could not detect @xds/core version. Make sure package.json is in the current directory, or use --from <version>.';
- if (json) return jsonError(msg);
+ if (json) return jsonError(msg, undefined, ERROR_CODES.ERR_VERSION_DETECT);
p.log.error(msg);
p.outro('Aborted');
process.exitCode = 1;
@@ -273,7 +274,7 @@ export function registerUpgrade(program) {
if (totalTransforms === 0 && totalOptional === 0) {
const msg = `Codemod "${options.codemod}" not found. Use --list to see available codemods.`;
- if (json) return jsonError(msg);
+ if (json) return jsonError(msg, undefined, ERROR_CODES.ERR_UNKNOWN_CODEMOD);
p.log.error(msg);
p.outro('Aborted');
process.exitCode = 1;
@@ -317,7 +318,7 @@ export function registerUpgrade(program) {
// Ensure jscodeshift is available
const ready = await ensureJscodeshift({installDeps: options.installDeps, silent: json});
if (!ready) {
- if (json) return jsonError('jscodeshift is required but could not be installed.');
+ if (json) return jsonError('jscodeshift is required but could not be installed.', undefined, ERROR_CODES.ERR_DEP_MISSING);
p.outro('Aborted');
process.exitCode = 1;
return;
diff --git a/packages/cli/src/index.mjs b/packages/cli/src/index.mjs
index c3b8ee8c04..179a694bb2 100644
--- a/packages/cli/src/index.mjs
+++ b/packages/cli/src/index.mjs
@@ -15,6 +15,7 @@ import {checkForUpdate} from './utils/update-check.mjs';
import {getRunPrefix} from './utils/package-manager.mjs';
import {API_VERSION, setJsonMode} from './lib/json.mjs';
import {cliError} from './lib/cli-error.mjs';
+import {ERROR_CODES} from './lib/error-codes.mjs';
import {levenshteinDistance} from './lib/string-utils.mjs';
import {installJsonShim} from './lib/json-shim.mjs';
@@ -105,7 +106,7 @@ program
const suggestions = close.length > 0
? close
: known.map((name) => ({name, reason: 'available command'}));
- cliError(`unknown command '${unknown}'`, {suggestions});
+ cliError(`unknown command '${unknown}'`, {suggestions, code: ERROR_CODES.ERR_UNKNOWN_COMMAND});
return;
}
@@ -172,6 +173,7 @@ program.hook('preAction', (thisCommand, actionCommand) => {
console.log(JSON.stringify({
apiVersion: API_VERSION,
error: `JSON output is not supported for the '${fullName}' command`,
+ code: ERROR_CODES.ERR_INVALID_OPTION,
}, null, 2));
process.exit(1);
});
diff --git a/packages/cli/src/lib/cli-error.mjs b/packages/cli/src/lib/cli-error.mjs
index 3817d14eb9..7bd138e578 100644
--- a/packages/cli/src/lib/cli-error.mjs
+++ b/packages/cli/src/lib/cli-error.mjs
@@ -39,12 +39,19 @@
*
* The JSON envelope shape MUST match the contract from the json.mjs module:
*
- * { apiVersion: 1, error: <string>, suggestions?: [{name, reason}, ...] }
+ * { apiVersion: 1, error: <string>, code: <string>, suggestions?: [...] }
+ *
+ * The `code` is a stable, machine-readable identifier (see error-codes.mjs).
+ * It is the field AI agents and CI scripts should branch on — never the
+ * human-readable `error` string, which changes freely. Human output stays
+ * clean: the code is omitted from the printed "Error: …" line and surfaces
+ * only in the JSON envelope.
*
* NEVER add ad-hoc fields. NEVER vary the shape. Consumers depend on it.
*/
import {isJsonMode, jsonError as _jsonError, humanWarn} from './json.mjs';
+import {ERROR_CODES} from './error-codes.mjs';
/**
* Suggestion object — matches the shape used by API errors and the JSON
@@ -55,6 +62,11 @@ import {isJsonMode, jsonError as _jsonError, humanWarn} from './json.mjs';
/**
* Options for {@link cliError}.
* @typedef {object} CliErrorOptions
+ * @property {string} [code] - Stable machine-readable error code from
+ * error-codes.mjs (e.g. ERR_UNKNOWN_COMPONENT). Emitted as the `code`
+ * field of the JSON envelope. Defaults to ERR_UNKNOWN when omitted.
+ * This is the field machine consumers branch on; the human `error`
+ * string may change at any time.
* @property {Suggestion[]} [suggestions] - Optional "did you mean…" list.
* Printed under the error message in human mode and serialized as the
* `suggestions` field in JSON mode.
@@ -84,11 +96,14 @@ import {isJsonMode, jsonError as _jsonError, humanWarn} from './json.mjs';
*/
export function cliError(message, options = {}) {
const {suggestions, exitCode = 1, hard = true} = options;
+ const code = options.code || ERROR_CODES.ERR_UNKNOWN;
if (isJsonMode()) {
// jsonError emits the envelope on stdout and calls process.exit(1).
// We don't honor a custom exitCode in JSON mode — the contract is exit 1.
- _jsonError(message, suggestions);
+ // The stable `code` is carried into the envelope; the human-facing
+ // branch below intentionally omits it to keep stderr clean.
+ _jsonError(message, suggestions, code);
// Unreachable, but keeps the type-checker honest.
return /** @type {never} */ (undefined);
}
diff --git a/packages/cli/src/lib/error-codes.mjs b/packages/cli/src/lib/error-codes.mjs
new file mode 100644
index 0000000000..f6fe2984db
--- /dev/null
+++ b/packages/cli/src/lib/error-codes.mjs
@@ -0,0 +1,197 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file XDS CLI — stable machine-readable error codes.
+ *
+ * ## Why codes exist
+ *
+ * The JSON error envelope (see json.mjs) carries a human-readable `error`
+ * string. That string is for people. It changes whenever we improve the
+ * wording, add detail, or localize. AI agents and CI scripts that consume
+ * `xds --json` must NOT branch on prose — string-matching "No component
+ * named X" is brittle and silently breaks the moment we reword it.
+ *
+ * The `code` field is the stable contract. Every error — whether raised by a
+ * command, the API layer (`XDSError`), or Commander's own parse machinery —
+ * carries one of the identifiers below. Codes are append-only: once shipped,
+ * a code's meaning never changes and the code is never removed. The message
+ * may change freely; the code never does.
+ *
+ * ## Naming
+ *
+ * `ERR_<SUBJECT>[_<QUALIFIER>]`, SCREAMING_SNAKE_CASE, always prefixed
+ * `ERR_`. Group by subject (component, hook, docs, template, theme, …).
+ *
+ * ## Usage
+ *
+ * import {ERROR_CODES} from './error-codes.mjs';
+ * cliError('No component named "Buton"', {code: ERROR_CODES.ERR_UNKNOWN_COMPONENT});
+ * throw new XDSError('No component named "Buton"', suggestions, ERROR_CODES.ERR_UNKNOWN_COMPONENT);
+ *
+ * Consumers read `envelope.code` and compare against the published list in
+ * packages/cli/README.md.
+ */
+
+/**
+ * Stable error-code string union. Append-only.
+ *
+ * @typedef {(
+ * | 'ERR_UNKNOWN'
+ * | 'ERR_UNKNOWN_COMMAND'
+ * | 'ERR_UNKNOWN_SUBCOMMAND'
+ * | 'ERR_INVALID_OPTION'
+ * | 'ERR_INVALID_ARGUMENT'
+ * | 'ERR_MISSING_ARGUMENT'
+ * | 'ERR_INVALID_LANG'
+ * | 'ERR_INVALID_DETAIL'
+ * | 'ERR_NODE_VERSION'
+ * | 'ERR_CORE_NOT_FOUND'
+ * | 'ERR_UNKNOWN_COMPONENT'
+ * | 'ERR_UNKNOWN_HOOK'
+ * | 'ERR_UNKNOWN_TOPIC'
+ * | 'ERR_UNKNOWN_SECTION'
+ * | 'ERR_UNKNOWN_CATEGORY'
+ * | 'ERR_UNKNOWN_TEMPLATE'
+ * | 'ERR_UNKNOWN_PACKAGE'
+ * | 'ERR_UNKNOWN_AGENT'
+ * | 'ERR_UNKNOWN_FEATURE'
+ * | 'ERR_UNKNOWN_CODEMOD'
+ * | 'ERR_NOT_FOUND'
+ * | 'ERR_NO_DOC'
+ * | 'ERR_NO_SHOWCASE'
+ * | 'ERR_NO_SOURCE'
+ * | 'ERR_INVALID_DOC'
+ * | 'ERR_FILE_NOT_FOUND'
+ * | 'ERR_FILE_EXISTS'
+ * | 'ERR_PATH_TRAVERSAL'
+ * | 'ERR_WRITE_FAILED'
+ * | 'ERR_THEME_INVALID'
+ * | 'ERR_THEME_LOAD'
+ * | 'ERR_TEMPLATE_CONFIG'
+ * | 'ERR_TEMPLATE_GET'
+ * | 'ERR_VERSION_DETECT'
+ * | 'ERR_INVALID_VERSION'
+ * | 'ERR_DEP_MISSING'
+ * | 'ERR_GH_CLI'
+ * | 'ERR_GAP_REPORT_FAILED'
+ * )} ErrorCode
+ */
+
+/**
+ * The complete, frozen set of XDS CLI error codes. Append-only.
+ * @type {Readonly<Record<ErrorCode, ErrorCode>>}
+ */
+export const ERROR_CODES = Object.freeze({
+ // ── Generic ──────────────────────────────────────────────────────
+ /** Fallback for any error without a more specific code. */
+ ERR_UNKNOWN: 'ERR_UNKNOWN',
+
+ // ── CLI parsing / dispatch (Commander + bare invocation) ─────────
+ /** A top-level command name was not recognized (e.g. `xds bogus`). */
+ ERR_UNKNOWN_COMMAND: 'ERR_UNKNOWN_COMMAND',
+ /** A subcommand under a command group was not recognized (e.g. `xds theme bogus`). */
+ ERR_UNKNOWN_SUBCOMMAND: 'ERR_UNKNOWN_SUBCOMMAND',
+ /** An unknown flag/option was passed (Commander `unknownOption`). */
+ ERR_INVALID_OPTION: 'ERR_INVALID_OPTION',
+ /** An option/argument had a value Commander's parser rejected. */
+ ERR_INVALID_ARGUMENT: 'ERR_INVALID_ARGUMENT',
+ /** A required positional argument was omitted (Commander `missingArgument`). */
+ ERR_MISSING_ARGUMENT: 'ERR_MISSING_ARGUMENT',
+ /** `--lang` was given a value outside its choices (en, zh, dense). */
+ ERR_INVALID_LANG: 'ERR_INVALID_LANG',
+ /** `--detail` was given a value outside its choices (full, compact, brief). */
+ ERR_INVALID_DETAIL: 'ERR_INVALID_DETAIL',
+
+ // ── Environment / runtime ────────────────────────────────────────
+ /** The running Node.js version is below the supported minimum. */
+ ERR_NODE_VERSION: 'ERR_NODE_VERSION',
+ /** `@xds/core` could not be located (not installed / not in a monorepo). */
+ ERR_CORE_NOT_FOUND: 'ERR_CORE_NOT_FOUND',
+
+ // ── "Unknown <subject>" lookups ──────────────────────────────────
+ /** No component matched the requested name. */
+ ERR_UNKNOWN_COMPONENT: 'ERR_UNKNOWN_COMPONENT',
+ /** No hook matched the requested name. */
+ ERR_UNKNOWN_HOOK: 'ERR_UNKNOWN_HOOK',
+ /** No docs topic matched the requested name. */
+ ERR_UNKNOWN_TOPIC: 'ERR_UNKNOWN_TOPIC',
+ /** A docs topic exists but the requested section within it does not. */
+ ERR_UNKNOWN_SECTION: 'ERR_UNKNOWN_SECTION',
+ /** A `--category` filter value did not match any known category. */
+ ERR_UNKNOWN_CATEGORY: 'ERR_UNKNOWN_CATEGORY',
+ /** No template matched the requested name. */
+ ERR_UNKNOWN_TEMPLATE: 'ERR_UNKNOWN_TEMPLATE',
+ /** No package matched the requested name (discover). */
+ ERR_UNKNOWN_PACKAGE: 'ERR_UNKNOWN_PACKAGE',
+ /** An unrecognized `--agent` value was passed to agent-docs/init. */
+ ERR_UNKNOWN_AGENT: 'ERR_UNKNOWN_AGENT',
+ /** An unrecognized `--features` value was passed to init. */
+ ERR_UNKNOWN_FEATURE: 'ERR_UNKNOWN_FEATURE',
+ /** A `--codemod` value did not match any registered codemod (upgrade). */
+ ERR_UNKNOWN_CODEMOD: 'ERR_UNKNOWN_CODEMOD',
+ /** A generic discover/lookup query matched nothing in any package. */
+ ERR_NOT_FOUND: 'ERR_NOT_FOUND',
+
+ // ── Resource shape problems (subject exists, artifact missing) ───
+ /** A component exists but has no typed `.doc.mjs` file. */
+ ERR_NO_DOC: 'ERR_NO_DOC',
+ /** No showcase exists for the requested component. */
+ ERR_NO_SHOWCASE: 'ERR_NO_SHOWCASE',
+ /** No source file could be located for the requested component/template. */
+ ERR_NO_SOURCE: 'ERR_NO_SOURCE',
+ /** A component's docs failed validation (malformed `.doc.mjs`). */
+ ERR_INVALID_DOC: 'ERR_INVALID_DOC',
+
+ // ── Filesystem ───────────────────────────────────────────────────
+ /** A required input file did not exist. */
+ ERR_FILE_NOT_FOUND: 'ERR_FILE_NOT_FOUND',
+ /** Refused to overwrite an existing file in non-interactive mode. */
+ ERR_FILE_EXISTS: 'ERR_FILE_EXISTS',
+ /** A path escaped its allowed root, or a name contained traversal markers. */
+ ERR_PATH_TRAVERSAL: 'ERR_PATH_TRAVERSAL',
+ /** Writing output files failed (and was rolled back). */
+ ERR_WRITE_FAILED: 'ERR_WRITE_FAILED',
+
+ // ── Theme build ──────────────────────────────────────────────────
+ /** A theme definition was missing a required property (e.g. `name`). */
+ ERR_THEME_INVALID: 'ERR_THEME_INVALID',
+ /** A theme file could not be loaded / parsed into a defineTheme result. */
+ ERR_THEME_LOAD: 'ERR_THEME_LOAD',
+
+ // ── Template config ──────────────────────────────────────────────
+ /** `template.get` is not configured in xds.config.mjs (fetch-by-id). */
+ ERR_TEMPLATE_CONFIG: 'ERR_TEMPLATE_CONFIG',
+ /** A configured `template.get` threw or returned an invalid value. */
+ ERR_TEMPLATE_GET: 'ERR_TEMPLATE_GET',
+
+ // ── Upgrade ──────────────────────────────────────────────────────
+ /** The current `@xds/core` version could not be detected. */
+ ERR_VERSION_DETECT: 'ERR_VERSION_DETECT',
+ /** A `--from`/`--to` value was not a valid semver string. */
+ ERR_INVALID_VERSION: 'ERR_INVALID_VERSION',
+ /** A required external dependency (e.g. jscodeshift) is missing. */
+ ERR_DEP_MISSING: 'ERR_DEP_MISSING',
+
+ // ── Gap report ───────────────────────────────────────────────────
+ /** GitHub CLI (`gh`) is not installed or not authenticated. */
+ ERR_GH_CLI: 'ERR_GH_CLI',
+ /** Filing a gap report failed at the command/integration boundary. */
+ ERR_GAP_REPORT_FAILED: 'ERR_GAP_REPORT_FAILED',
+});
+
+/**
+ * Type guard: is `value` one of the known error codes?
+ * @param {unknown} value
+ * @returns {value is ErrorCode}
+ */
+export function isErrorCode(value) {
+ return typeof value === 'string' && Object.hasOwn(ERROR_CODES, value);
+}
+
+/**
+ * All error code string values, sorted. Handy for tests and tooling.
+ * @returns {string[]}
+ */
+export function allErrorCodes() {
+ return Object.values(ERROR_CODES).sort();
+}
diff --git a/packages/cli/src/lib/error-codes.test.mjs b/packages/cli/src/lib/error-codes.test.mjs
new file mode 100644
index 0000000000..277f42738a
--- /dev/null
+++ b/packages/cli/src/lib/error-codes.test.mjs
@@ -0,0 +1,152 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Tests for the stable error-code contract.
+ *
+ * Two layers:
+ *
+ * 1. Unit — the taxonomy itself: every code is a non-empty, unique,
+ * stable string; the object is frozen; helpers behave.
+ *
+ * 2. End-to-end — spawn the CLI as a subprocess and assert that
+ * representative error paths emit the right `code` in their JSON
+ * envelope. Spawning is the only way to exercise Commander hooks,
+ * the json-shim, and the bin error boundary together.
+ */
+
+import {describe, it, expect} from 'vitest';
+import {spawnSync} from 'node:child_process';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {ERROR_CODES, isErrorCode, allErrorCodes} from './error-codes.mjs';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const CLI_BIN = path.resolve(__dirname, '../../bin/xds.mjs');
+
+function runCli(args, {cwd} = {}) {
+ const res = spawnSync('node', [CLI_BIN, ...args], {
+ cwd: cwd || process.cwd(),
+ encoding: 'utf-8',
+ timeout: 20_000,
+ });
+ return {
+ status: res.status,
+ stdout: res.stdout || '',
+ stderr: res.stderr || '',
+ };
+}
+
+/** Parse the JSON envelope from stdout. Throws if stdout isn't clean JSON. */
+function envelope(stdout) {
+ return JSON.parse(stdout);
+}
+
+describe('error-codes taxonomy', () => {
+ it('every code is a non-empty string', () => {
+ for (const [key, value] of Object.entries(ERROR_CODES)) {
+ expect(typeof value).toBe('string');
+ expect(value.length).toBeGreaterThan(0);
+ // Key and value must match — the object is a string enum.
+ expect(value).toBe(key);
+ }
+ });
+
+ it('every code follows the ERR_ naming convention', () => {
+ for (const value of Object.values(ERROR_CODES)) {
+ expect(value).toMatch(/^ERR_[A-Z0-9_]+$/);
+ }
+ });
+
+ it('all codes are unique', () => {
+ const values = Object.values(ERROR_CODES);
+ expect(new Set(values).size).toBe(values.length);
+ });
+
+ it('includes the generic fallback', () => {
+ expect(ERROR_CODES.ERR_UNKNOWN).toBe('ERR_UNKNOWN');
+ });
+
+ it('the taxonomy object is frozen (codes are stable, append-only)', () => {
+ expect(Object.isFrozen(ERROR_CODES)).toBe(true);
+ expect(() => {
+ // @ts-expect-error - intentional mutation attempt
+ ERROR_CODES.ERR_NEW = 'ERR_NEW';
+ }).toThrow();
+ expect(ERROR_CODES.ERR_NEW).toBeUndefined();
+ });
+
+ it('isErrorCode recognizes known codes and rejects others', () => {
+ expect(isErrorCode('ERR_UNKNOWN_COMPONENT')).toBe(true);
+ expect(isErrorCode('ERR_UNKNOWN')).toBe(true);
+ expect(isErrorCode('ERR_NOT_A_REAL_CODE')).toBe(false);
+ expect(isErrorCode('')).toBe(false);
+ expect(isErrorCode(42)).toBe(false);
+ expect(isErrorCode(undefined)).toBe(false);
+ });
+
+ it('allErrorCodes returns the sorted, complete set', () => {
+ const codes = allErrorCodes();
+ expect(codes.length).toBe(Object.keys(ERROR_CODES).length);
+ expect(codes).toEqual([...codes].sort());
+ expect(codes).toContain('ERR_UNKNOWN');
+ expect(codes).toContain('ERR_UNKNOWN_COMPONENT');
+ });
+});
+
+describe('error codes: end-to-end JSON envelopes', () => {
+ const cases = [
+ {name: 'unknown component', args: ['component', 'Bogus', '--json'], code: 'ERR_UNKNOWN_COMPONENT'},
+ {name: 'unknown hook', args: ['hook', 'bogusHook', '--json'], code: 'ERR_UNKNOWN_HOOK'},
+ {name: 'unknown topic', args: ['docs', 'bogusTopic', '--json'], code: 'ERR_UNKNOWN_TOPIC'},
+ {name: 'unknown template', args: ['template', 'bogusTemplate', '--json'], code: 'ERR_UNKNOWN_TEMPLATE'},
+ {name: 'unknown command', args: ['bogus-cmd', '--json'], code: 'ERR_UNKNOWN_COMMAND'},
+ {name: 'invalid --lang', args: ['docs', 'color', '--lang', 'fr', '--json'], code: 'ERR_INVALID_LANG'},
+ {name: 'invalid --detail', args: ['docs', 'color', '--detail', 'bogus', '--json'], code: 'ERR_INVALID_DETAIL'},
+ {name: 'unknown option', args: ['component', 'Button', '--bogus-flag', '--json'], code: 'ERR_INVALID_OPTION'},
+ {name: 'missing argument', args: ['theme', 'build', '--json'], code: 'ERR_MISSING_ARGUMENT'},
+ // `theme` is not on the --json allowlist, so --json on any theme subcommand
+ // is rejected at the preAction gate with a stable invalid-option code.
+ {name: 'json not supported', args: ['theme', 'bogus-sub', '--json'], code: 'ERR_INVALID_OPTION'},
+ ];
+
+ for (const {name, args, code} of cases) {
+ it(`${name} → ${code}`, () => {
+ const {status, stdout} = runCli(args);
+ expect(status).toBe(1);
+ const env = envelope(stdout);
+ expect(env).toHaveProperty('apiVersion');
+ expect(env).toHaveProperty('error');
+ expect(env.code).toBe(code);
+ // The code must be a recognized member of the taxonomy.
+ expect(isErrorCode(env.code)).toBe(true);
+ });
+ }
+
+ it('every error envelope carries a code (even unmatched paths fall back to ERR_UNKNOWN)', () => {
+ const {stdout} = runCli(['component', 'Bogus', '--json']);
+ const env = envelope(stdout);
+ expect(typeof env.code).toBe('string');
+ expect(env.code.length).toBeGreaterThan(0);
+ });
+});
+
+describe('error codes: human mode stays clean', () => {
+ it('the code is NOT printed in the human-facing error line', () => {
+ const {status, stderr, stdout} = runCli(['component', 'Bogus']);
+ expect(status).toBe(1);
+ // Human output goes to stderr and must not leak the machine code.
+ expect(stderr).toContain('No component named');
+ expect(stderr).not.toContain('ERR_UNKNOWN_COMPONENT');
+ expect(stdout).not.toContain('ERR_UNKNOWN_COMPONENT');
+ });
+
+ it('unknown subcommand exits 1 in human mode (code carried internally)', () => {
+ // `theme` is not JSON-capable, so this path is human-only; we assert the
+ // failure surfaces with exit 1 and a helpful message. The stable
+ // ERR_UNKNOWN_SUBCOMMAND code rides along on the cliError call.
+ const {status, stderr} = runCli(['theme', 'bogus-sub']);
+ expect(status).toBe(1);
+ expect(stderr).toContain("unknown subcommand 'theme bogus-sub'");
+ expect(stderr).not.toContain('ERR_UNKNOWN_SUBCOMMAND');
+ });
+});
diff --git a/packages/cli/src/lib/json-contract.test.mjs b/packages/cli/src/lib/json-contract.test.mjs
index 5a4ed89691..55d3f5dc65 100644
--- a/packages/cli/src/lib/json-contract.test.mjs
+++ b/packages/cli/src/lib/json-contract.test.mjs
@@ -66,11 +66,33 @@ describe('json envelope shape', () => {
expect(env.data).toEqual([]);
});
- it('toErrorEnvelope produces { apiVersion, error } from string or Error', () => {
- expect(toErrorEnvelope('boom')).toEqual({apiVersion: API_VERSION, error: 'boom'});
+ it('toErrorEnvelope produces { apiVersion, error, code } from string or Error', () => {
+ expect(toErrorEnvelope('boom')).toEqual({
+ apiVersion: API_VERSION,
+ error: 'boom',
+ code: 'ERR_UNKNOWN',
+ });
expect(toErrorEnvelope(new Error('kaboom'))).toEqual({
apiVersion: API_VERSION,
error: 'kaboom',
+ code: 'ERR_UNKNOWN',
+ });
+ });
+
+ it('toErrorEnvelope honors an explicit code argument', () => {
+ expect(toErrorEnvelope('boom', undefined, 'ERR_UNKNOWN_COMPONENT')).toEqual({
+ apiVersion: API_VERSION,
+ error: 'boom',
+ code: 'ERR_UNKNOWN_COMPONENT',
+ });
+ });
+
+ it('toErrorEnvelope reads a code carried on a thrown Error', () => {
+ const err = Object.assign(new Error('kaboom'), {code: 'ERR_NO_DOC'});
+ expect(toErrorEnvelope(err)).toEqual({
+ apiVersion: API_VERSION,
+ error: 'kaboom',
+ code: 'ERR_NO_DOC',
});
});
diff --git a/packages/cli/src/lib/json-shim.mjs b/packages/cli/src/lib/json-shim.mjs
index 423300f4fe..e17d003d7d 100644
--- a/packages/cli/src/lib/json-shim.mjs
+++ b/packages/cli/src/lib/json-shim.mjs
@@ -37,6 +37,7 @@
*/
import {API_VERSION, isJsonMode, toErrorEnvelope} from './json.mjs';
+import {ERROR_CODES} from './error-codes.mjs';
/**
* Cheap argv check used before preAction has had a chance to engage
@@ -102,14 +103,50 @@ export function buildHelpEnvelope(cmd) {
*
* @param {string} message
* @param {Array<{name: string, reason: string}>} [suggestions]
+ * @param {string} [code] - Stable machine-readable error code (error-codes.mjs).
*/
-function emitJsonError(message, suggestions) {
+function emitJsonError(message, suggestions, code) {
if (process.__xdsJsonHandled) return;
process.__xdsJsonHandled = true;
- const env = toErrorEnvelope(message, suggestions);
+ const env = toErrorEnvelope(message, suggestions, code);
process.stdout.write(`${JSON.stringify(env, null, 2)}\n`);
}
+/**
+ * Map a Commander parse-error code (and its message) to a stable XDS error
+ * code. Commander's own codes are stable enough, but they aren't part of our
+ * documented contract — so we translate them into the `ERR_*` taxonomy.
+ *
+ * The `--lang` / `--detail` choice violations both arrive as
+ * `commander.invalidArgument`; we disambiguate on the option name in the
+ * message so consumers get the precise ERR_INVALID_LANG / ERR_INVALID_DETAIL.
+ *
+ * @param {string} commanderCode - e.g. 'commander.unknownOption'
+ * @param {string} message
+ * @returns {string}
+ */
+function commanderCodeToErrorCode(commanderCode, message) {
+ switch (commanderCode) {
+ case 'commander.unknownCommand':
+ return ERROR_CODES.ERR_UNKNOWN_COMMAND;
+ case 'commander.unknownOption':
+ return ERROR_CODES.ERR_INVALID_OPTION;
+ case 'commander.missingArgument':
+ case 'commander.missingMandatoryOptionValue':
+ return ERROR_CODES.ERR_MISSING_ARGUMENT;
+ case 'commander.excessArguments':
+ return ERROR_CODES.ERR_INVALID_ARGUMENT;
+ case 'commander.invalidArgument':
+ case 'commander.invalidOptionArgument': {
+ if (/--lang\b/.test(message)) return ERROR_CODES.ERR_INVALID_LANG;
+ if (/--detail\b/.test(message)) return ERROR_CODES.ERR_INVALID_DETAIL;
+ return ERROR_CODES.ERR_INVALID_ARGUMENT;
+ }
+ default:
+ return ERROR_CODES.ERR_UNKNOWN;
+ }
+}
+
/**
* Install the shim on a Commander program. Idempotent — safe to call
* once at program-construction time.
@@ -274,7 +311,7 @@ export function handleCommanderError(err) {
// Strip Commander's "error: " prefix — the envelope key is `error`
// already, doubled "error" is noise.
const cleaned = message.replace(/^error:\s*/i, '');
- emitJsonError(cleaned);
+ emitJsonError(cleaned, undefined, commanderCodeToErrorCode(code, cleaned));
} else {
// Non-JSON mode: Commander already wrote the "error: ..." line
// to stderr via configureOutput.writeErr before throwing the
diff --git a/packages/cli/src/lib/json.mjs b/packages/cli/src/lib/json.mjs
index 1c1d5ed7fd..b723c099a4 100644
--- a/packages/cli/src/lib/json.mjs
+++ b/packages/cli/src/lib/json.mjs
@@ -7,7 +7,11 @@
* The contract has four guarantees, enforced here and in index.mjs:
*
* 1. EVERY emission in --json mode is a single valid JSON envelope.
- * Success: { apiVersion, type, data } Error: { apiVersion, error, suggestions? }
+ * Success: { apiVersion, type, data }
+ * Error: { apiVersion, error, code, suggestions? }
+ * The `code` is a stable, machine-readable identifier (see
+ * error-codes.mjs). Consumers should branch on `code`, never on the
+ * human-readable `error` string.
* 2. Commands that don't support --json are rejected BEFORE any side
* effect (preAction gate in index.mjs).
* 3. Human-facing chatter is suppressed in --json mode (see humanLog /
@@ -24,6 +28,8 @@
* Version of the JSON envelope contract. Bump on breaking shape changes so
* consumers can negotiate. Exposed on every envelope as `apiVersion`.
*/
+import {ERROR_CODES} from './error-codes.mjs';
+
export const API_VERSION = 1;
/**
@@ -99,15 +105,30 @@ export function jsonOut(type, data, meta) {
* Build a structured error envelope without emitting it. Used by the bin
* error boundary to convert an uncaught throw into the contract's error
* shape.
+ *
+ * The `code` is resolved in priority order: an explicit `code` argument,
+ * then a `code` property carried on a thrown Error/XDSError, then the
+ * generic `ERR_UNKNOWN` fallback. It always appears on the envelope so
+ * consumers can branch on it unconditionally.
+ *
* @param {unknown} err
* @param {Array<{name: string, reason: string}>} [suggestions]
- * @returns {{apiVersion: number, error: string, suggestions?: Array<{name: string, reason: string}>}}
+ * @param {string} [code] - Explicit stable error code. Overrides any code
+ * carried on a thrown Error.
+ * @returns {{apiVersion: number, error: string, code: string, suggestions?: Array<{name: string, reason: string}>}}
*/
-export function toErrorEnvelope(err, suggestions) {
+export function toErrorEnvelope(err, suggestions, code) {
const message =
err instanceof Error ? err.message : typeof err === 'string' ? err : String(err);
+ const resolvedCode =
+ code ||
+ (err && typeof err === 'object' &&
+ typeof (/** @type {any} */ (err).code) === 'string'
+ ? /** @type {any} */ (err).code
+ : undefined) ||
+ ERROR_CODES.ERR_UNKNOWN;
/** @type {any} */
- const env = {apiVersion: API_VERSION, error: message};
+ const env = {apiVersion: API_VERSION, error: message, code: resolvedCode};
if (suggestions?.length) env.suggestions = suggestions;
return env;
}
@@ -116,10 +137,11 @@ export function toErrorEnvelope(err, suggestions) {
* Output a structured JSON error and exit.
* @param {string} message
* @param {Array<{name: string, reason: string}>} [suggestions]
+ * @param {string} [code] - Stable machine-readable error code (error-codes.mjs).
*/
-export function jsonError(message, suggestions) {
+export function jsonError(message, suggestions, code) {
process.__xdsJsonHandled = true;
- const err = toErrorEnvelope(message, suggestions);
+ const err = toErrorEnvelope(message, suggestions, code);
console.log(JSON.stringify(err, null, 2));
process.exit(1);
}
diff --git a/packages/cli/src/types/api.d.ts b/packages/cli/src/types/api.d.ts
index c7779ece56..f2e5b587fc 100644
--- a/packages/cli/src/types/api.d.ts
+++ b/packages/cli/src/types/api.d.ts
@@ -42,13 +42,17 @@ import type {
HookDetailParamsResponse,
} from './hook';
import type {SearchResponse, SearchDomain} from './search';
+import type {ErrorCode} from './error-codes';
-/** Structured API error with optional suggestions. */
+/** Structured API error with a stable machine-readable code. */
export declare class XDSError extends Error {
+ /** Stable error code; consumers branch on this, never the message. */
+ code: ErrorCode;
suggestions?: Array<{name: string; reason: string}>;
constructor(
message: string,
suggestions?: Array<{name: string; reason: string}>,
+ code?: ErrorCode,
);
}
diff --git a/packages/cli/src/types/base.d.ts b/packages/cli/src/types/base.d.ts
index f7e95736f7..e4018ec49b 100644
--- a/packages/cli/src/types/base.d.ts
+++ b/packages/cli/src/types/base.d.ts
@@ -49,16 +49,24 @@ import type {
GapReportFileResponse,
} from './gap-report';
import type {SearchResponse} from './search';
+import type {ErrorCode} from './error-codes';
-/** Structured error. Check `'error' in result` to discriminate. */
+/**
+ * Structured error. Check `'error' in result` to discriminate.
+ *
+ * Branch on `code` (a stable machine-readable identifier), never on the
+ * human-readable `error` string, which changes freely.
+ */
export interface CLIError {
error: string;
+ code: ErrorCode;
suggestions?: Array<{name: string; reason: string}>;
}
/** Returned by the fallback hook for commands without --json support. */
export interface CLIUnsupportedError {
error: `JSON output is not supported for the '${string}' command`;
+ code: ErrorCode;
}
/** Wrap any response type to include possible error shapes. */
@@ -124,6 +132,7 @@ export function jsonOut<T extends CLIResponseType>(
export function jsonError(
message: string,
suggestions?: Array<{name: string; reason: string}>,
+ code?: ErrorCode,
): never;
/** Parse raw CLI output (string or object) into typed result. */
diff --git a/packages/cli/src/types/error-codes.d.ts b/packages/cli/src/types/error-codes.d.ts
new file mode 100644
index 0000000000..285222092a
--- /dev/null
+++ b/packages/cli/src/types/error-codes.d.ts
@@ -0,0 +1,58 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Stable, machine-readable error codes carried on every CLI error envelope
+ * and every thrown XDSError. Consumers should branch on these — never on the
+ * human-readable `error` string, which can change at any time.
+ *
+ * Append-only: a code's meaning never changes and codes are never removed.
+ * See packages/cli/README.md for the documented contract and meanings.
+ */
+export type ErrorCode =
+ | 'ERR_UNKNOWN'
+ | 'ERR_UNKNOWN_COMMAND'
+ | 'ERR_UNKNOWN_SUBCOMMAND'
+ | 'ERR_INVALID_OPTION'
+ | 'ERR_INVALID_ARGUMENT'
+ | 'ERR_MISSING_ARGUMENT'
+ | 'ERR_INVALID_LANG'
+ | 'ERR_INVALID_DETAIL'
+ | 'ERR_NODE_VERSION'
+ | 'ERR_CORE_NOT_FOUND'
+ | 'ERR_UNKNOWN_COMPONENT'
+ | 'ERR_UNKNOWN_HOOK'
+ | 'ERR_UNKNOWN_TOPIC'
+ | 'ERR_UNKNOWN_SECTION'
+ | 'ERR_UNKNOWN_CATEGORY'
+ | 'ERR_UNKNOWN_TEMPLATE'
+ | 'ERR_UNKNOWN_PACKAGE'
+ | 'ERR_UNKNOWN_AGENT'
+ | 'ERR_UNKNOWN_FEATURE'
+ | 'ERR_UNKNOWN_CODEMOD'
+ | 'ERR_NOT_FOUND'
+ | 'ERR_NO_DOC'
+ | 'ERR_NO_SHOWCASE'
+ | 'ERR_NO_SOURCE'
+ | 'ERR_INVALID_DOC'
+ | 'ERR_FILE_NOT_FOUND'
+ | 'ERR_FILE_EXISTS'
+ | 'ERR_PATH_TRAVERSAL'
+ | 'ERR_WRITE_FAILED'
+ | 'ERR_THEME_INVALID'
+ | 'ERR_THEME_LOAD'
+ | 'ERR_TEMPLATE_CONFIG'
+ | 'ERR_TEMPLATE_GET'
+ | 'ERR_VERSION_DETECT'
+ | 'ERR_INVALID_VERSION'
+ | 'ERR_DEP_MISSING'
+ | 'ERR_GH_CLI'
+ | 'ERR_GAP_REPORT_FAILED';
+
+/** The frozen runtime map of all error codes (keys === values). */
+export declare const ERROR_CODES: Readonly<Record<ErrorCode, ErrorCode>>;
+
+/** Type guard: is `value` a known error code? */
+export declare function isErrorCode(value: unknown): value is ErrorCode;
+
+/** All error code string values, sorted. */
+export declare function allErrorCodes(): ErrorCode[];
diff --git a/packages/cli/src/types/index.d.ts b/packages/cli/src/types/index.d.ts
index 8ac76d040d..42834750c9 100644
--- a/packages/cli/src/types/index.d.ts
+++ b/packages/cli/src/types/index.d.ts
@@ -11,3 +11,4 @@ export * from './theme';
export * from './gap-report';
export * from './upgrade';
export * from './search';
+export * from './error-codes';