Skip to content

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

TypeScript

feat(cli): JSON-is-always-JSON contract — apiVersion, stdout discipline, error boundary (#2467)

Joeye653d90206fc
diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md
index a18ee853c4..15fcab01c8 100644
--- a/packages/cli/CHANGELOG.md
+++ b/packages/cli/CHANGELOG.md
@@ -1,5 +1,18 @@
# @xds/cli
+# Unreleased
+
+#### Fixes
+
+- **`--json` contract enforcement** — Commands that don't support `--json` now reject the flag in a `preAction` hook _before_ running any side effects. Previously `xds init --json` would create files (e.g. `.claude/CLAUDE.md`) and _then_ emit the unsupported-output error, leaving partial state behind.
+- **`--json` envelope shape documented** — Success responses are `{ type, data }`. Error responses are `{ error, suggestions? }`. The `--json` help text now describes both.
+- **`xds --version --json`** — Now emits `{ type: 'version', data: { version } }` instead of plain text.
+- **`xds --json` (no subcommand)** — Now emits `{ type: 'help', data: { commands, jsonSupported, ... } }` instead of human help text.
+- **`xds upgrade --json`** — The "already up to date" path now emits `{ type: 'upgrade.status', data: { status: 'up_to_date', ... } }`. The "no codemods in version range" path emits `{ type: 'upgrade.status', data: { status: 'no_codemods', ... } }`. The codemod runner is now silent under `--json` so prompts and progress lines no longer corrupt stdout.
+- **`xds discover --json`** — When no packages are configured, the response now includes `meta: { configured: false }` so consumers can distinguish "configured but empty" from "not configured".
+- **`xds gap-report --json`** — Without `--component`/`--category`/`--reason`, returns a structured error instead of starting an interactive prompt. The "gh CLI missing" path also emits a JSON error.
+- **`xds theme --json`** — The `theme` parent command (without a subcommand) now rejects `--json` cleanly. `theme build --json` continues to work.
+
# 0.0.14
#### Codemods
@@ -25,7 +38,6 @@
- **DropdownMenu inline data types** — Inline into items prop docs (#2027)
- **Parent hook docs** to their component in docsite (#2022)
-
---
# 0.0.13
@@ -188,6 +200,7 @@ npx xds upgrade --apply --to 0.0.6
#### Codemods
12 codemods for the v0.0.2 breaking changes:
+
- `rename-selector-items-to-options` — Selector `items` → `options`
- `unify-visibility-to-onOpenChange` — Visibility callbacks → `onOpenChange`
- `unify-uncontrolled-to-defaultX` — Uncontrolled state → defaultX pattern
diff --git a/packages/cli/bin/xds.mjs b/packages/cli/bin/xds.mjs
index d2e69dfc6a..977a198744 100755
--- a/packages/cli/bin/xds.mjs
+++ b/packages/cli/bin/xds.mjs
@@ -2,5 +2,41 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import {program} from '../src/index.mjs';
+import {isJsonMode, toErrorEnvelope} from '../src/lib/json.mjs';
-program.parse();
+/**
+ * Top-level error boundary (contract guarantee #4): an uncaught throw must
+ * never reach a --json consumer as a raw stack trace. If we're in JSON mode,
+ * convert it to the contract's error envelope on stdout and exit 1; otherwise
+ * preserve the normal human-facing behavior.
+ *
+ * We detect JSON mode two ways: the global flag (set once root options are
+ * parsed) and a raw argv check, since a throw can occur during parsing/command
+ * load — before the preAction hook engages the flag.
+ */
+function inJsonMode() {
+ return isJsonMode() || process.argv.slice(2).includes('--json');
+}
+
+function handleFatal(err) {
+ if (inJsonMode()) {
+ // Only emit if a command didn't already produce an envelope.
+ if (!process.__xdsJsonHandled) {
+ process.__xdsJsonHandled = true;
+ console.log(JSON.stringify(toErrorEnvelope(err), null, 2));
+ }
+ process.exit(1);
+ }
+ // Human mode: preserve Commander/Node default-ish behavior.
+ console.error(err instanceof Error ? err.stack || err.message : String(err));
+ process.exit(1);
+}
+
+process.on('unhandledRejection', handleFatal);
+process.on('uncaughtException', handleFatal);
+
+try {
+ await program.parseAsync(process.argv);
+} catch (err) {
+ handleFatal(err);
+}
diff --git a/packages/cli/src/api/discover.mjs b/packages/cli/src/api/discover.mjs
index f7cf49b56d..5f096db04b 100644
--- a/packages/cli/src/api/discover.mjs
+++ b/packages/cli/src/api/discover.mjs
@@ -41,13 +41,13 @@ export async function discover(query, options = {}) {
});
if (config.packages.length === 0) {
- return {type: 'discover.list', data: []};
+ return {type: 'discover.list', data: [], meta: {configured: false}};
}
const packages = scanAllPackages(config.packages);
if (packages.length === 0) {
- return {type: 'discover.list', data: []};
+ return {type: 'discover.list', data: [], meta: {configured: true}};
}
if (!query) {
diff --git a/packages/cli/src/codemods/ensure-jscodeshift.mjs b/packages/cli/src/codemods/ensure-jscodeshift.mjs
index f84f399235..7a9734c773 100644
--- a/packages/cli/src/codemods/ensure-jscodeshift.mjs
+++ b/packages/cli/src/codemods/ensure-jscodeshift.mjs
@@ -18,24 +18,28 @@ import {detectPackageManager} from '../utils/package-manager.mjs';
/**
* @param {object} [options]
* @param {boolean} [options.installDeps] - Auto-install without prompting
+ * @param {boolean} [options.silent] - Suppress human-facing output (for --json)
*/
-export async function ensureJscodeshift({installDeps = false} = {}) {
+export async function ensureJscodeshift({installDeps = false, silent = false} = {}) {
+ const log = silent
+ ? {warn() {}, error() {}, step() {}, success() {}}
+ : p.log;
try {
await import('jscodeshift');
return true;
} catch {
- p.log.warn('jscodeshift is required for codemods but not installed.');
+ log.warn('jscodeshift is required for codemods but not installed.');
const isInteractive = process.stdout.isTTY && !process.env.CI;
if (installDeps) {
// Explicit opt-in — install without prompting
- return installJscodeshift();
+ return installJscodeshift(silent);
}
- if (!isInteractive) {
- // Non-interactive environment — fail fast with a helpful message
- p.log.error(
+ if (!isInteractive || silent) {
+ // Non-interactive environment (or --json) — fail fast with a helpful message
+ log.error(
'Cannot run codemods without jscodeshift. ' +
'Use --install-deps to auto-install in non-interactive environments.',
);
@@ -51,12 +55,15 @@ export async function ensureJscodeshift({installDeps = false} = {}) {
p.log.error('Cannot run codemods without jscodeshift.');
return false;
}
- return installJscodeshift();
+ return installJscodeshift(silent);
}
}
/** @returns {boolean} */
-function installJscodeshift() {
+function installJscodeshift(silent = false) {
+ const log = silent
+ ? {step() {}, success() {}, error() {}}
+ : p.log;
const pm = detectPackageManager();
const cmds = {
yarn: 'yarn add --dev jscodeshift',
@@ -68,12 +75,12 @@ function installJscodeshift() {
const cmd = cmds[pm] || cmds.npm;
try {
- p.log.step(`Installing jscodeshift via ${pm}...`);
+ log.step(`Installing jscodeshift via ${pm}...`);
execSync(cmd, {stdio: 'pipe'});
- p.log.success('jscodeshift installed.');
+ log.success('jscodeshift installed.');
return true;
} catch (err) {
- p.log.error(`Failed to install jscodeshift: ${err.message}`);
+ log.error(`Failed to install jscodeshift: ${err.message}`);
return false;
}
}
diff --git a/packages/cli/src/codemods/runner.mjs b/packages/cli/src/codemods/runner.mjs
index a8c8aca67a..ff4e4ee9a8 100644
--- a/packages/cli/src/codemods/runner.mjs
+++ b/packages/cli/src/codemods/runner.mjs
@@ -12,6 +12,7 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import * as p from '@clack/prompts';
import {getRunPrefix} from '../utils/package-manager.mjs';
+import {humanLog} from '../lib/json.mjs';
// Known corruption patterns that indicate a broken transform.
// Each entry: [regex, human-readable description]
@@ -77,8 +78,9 @@ function findSourceFiles(dir) {
* Tries prettier, then biome. Silently skips if none found.
*
* @param {string[]} files - Absolute paths to files that were modified
+ * @param {boolean} [silent] - Suppress human-facing output
*/
-async function formatChangedFiles(files) {
+async function formatChangedFiles(files, silent = false) {
if (files.length === 0) return;
const {execSync} = await import('node:child_process');
@@ -93,7 +95,7 @@ async function formatChangedFiles(files) {
for (const {name, cmd} of formatters) {
try {
execSync(cmd, {stdio: 'pipe', timeout: 30000});
- p.log.info(`Formatted ${files.length} file${files.length === 1 ? '' : 's'} with ${name}`);
+ if (!silent) p.log.info(`Formatted ${files.length} file${files.length === 1 ? '' : 's'} with ${name}`);
return;
} catch {
// Formatter not available or failed — try next
@@ -149,24 +151,32 @@ export function validateOutput(result, source, j) {
* @param {boolean} options.apply - Write changes to disk
* @param {string} options.path - Source directory to scan
* @param {string|undefined} options.codemod - Run only this specific transform
+ * @param {boolean} [options.silent] - Suppress all human-facing output (for --json)
*/
-export async function runCodemods(versionManifests, {apply, path: srcPath, codemod}) {
+export async function runCodemods(versionManifests, {apply, path: srcPath, codemod, silent = false}) {
+ // No-op stub object so silent mode skips clack stdout entirely without
+ // littering the body with `if (!silent)` guards.
+ const log = silent
+ ? {step() {}, info() {}, success() {}, warn() {}, error() {}, message() {}}
+ : p.log;
+ const writeBlank = () => { if (!silent) humanLog(''); };
+
const resolvedPath = path.resolve(srcPath);
if (!fs.existsSync(resolvedPath)) {
- p.log.error(`Source path not found: ${resolvedPath}`);
- return;
+ log.error(`Source path not found: ${resolvedPath}`);
+ return {ok: false, reason: 'source_path_missing', resolvedPath};
}
- p.log.step(`Scanning ${resolvedPath} for source files...`);
+ log.step(`Scanning ${resolvedPath} for source files...`);
const files = findSourceFiles(resolvedPath);
if (files.length === 0) {
- p.log.warn('No source files found.');
- return;
+ log.warn('No source files found.');
+ return {ok: true, totalFilesChanged: 0, totalTransformsApplied: 0, errors: [], writtenFiles: [], skippedOptional: []};
}
- p.log.info(`Found ${files.length} source file${files.length === 1 ? '' : 's'}`);
+ log.info(`Found ${files.length} source file${files.length === 1 ? '' : 's'}`);
// Dynamically import jscodeshift
const jscodeshift = (await import('jscodeshift')).default;
@@ -179,7 +189,7 @@ export async function runCodemods(versionManifests, {apply, path: srcPath, codem
const skippedOptional = [];
for (const {version, transforms} of versionManifests) {
- p.log.step(`Applying v${version} codemods...`);
+ log.step(`Applying v${version} codemods...`);
for (const transformEntry of transforms) {
// Filter by codemod name if specified
@@ -193,7 +203,7 @@ export async function runCodemods(versionManifests, {apply, path: srcPath, codem
continue;
}
- p.log.info(` ${meta.title}`);
+ log.info(` ${meta.title}`);
let filesChanged = 0;
@@ -223,7 +233,7 @@ export async function runCodemods(versionManifests, {apply, path: srcPath, codem
const validation = validateOutput(result, source, j);
if (!validation.valid) {
totalValidationBlocked++;
- p.log.error(` ✗ ${relativePath} — ${validation.reason}`);
+ log.error(` ✗ ${relativePath} — ${validation.reason}`);
errors.push({file: relativePath, codemod: name, error: validation.reason});
continue;
}
@@ -235,80 +245,80 @@ export async function runCodemods(versionManifests, {apply, path: srcPath, codem
if (apply) {
fs.writeFileSync(filePath, result, 'utf-8');
writtenFiles.push(filePath);
- p.log.success(` ✓ ${relativePath}`);
+ log.success(` ✓ ${relativePath}`);
} else {
- p.log.warn(` ~ ${relativePath} (would change)`);
+ log.warn(` ~ ${relativePath} (would change)`);
}
}
} catch (err) {
- p.log.error(` ✗ ${relativePath} — ${err.message}`);
+ log.error(` ✗ ${relativePath} — ${err.message}`);
errors.push({file: relativePath, codemod: name, error: err.message});
}
}
if (filesChanged > 0) {
const verb = apply ? 'Updated' : 'Would update';
- p.log.info(` ${verb} ${filesChanged} file${filesChanged === 1 ? '' : 's'}`);
+ log.info(` ${verb} ${filesChanged} file${filesChanged === 1 ? '' : 's'}`);
}
}
}
// Summary
- console.log('');
+ writeBlank();
if (errors.length > 0) {
- p.log.error(
+ log.error(
`${errors.length} error${errors.length === 1 ? '' : 's'} during codemods:`,
);
for (const {file, codemod: cm, error} of errors) {
- p.log.error(` ${cm} → ${file}: ${error}`);
+ log.error(` ${cm} → ${file}: ${error}`);
}
}
// Post-codemod formatting: run the project's formatter on changed files
// so codemods don't introduce style drift (jscodeshift may change quotes, etc.)
if (apply && writtenFiles.length > 0) {
- await formatChangedFiles(writtenFiles);
+ await formatChangedFiles(writtenFiles, silent);
}
if (totalValidationBlocked > 0) {
- p.log.warn(
+ log.warn(
`${totalValidationBlocked} file${totalValidationBlocked === 1 ? ' was' : 's were'} blocked by validation — no changes written to ${totalValidationBlocked === 1 ? 'that file' : 'those files'}.`,
);
- p.log.info(
+ log.info(
'This means a codemod produced invalid output. Please report this as a bug.',
);
}
if (totalFilesChanged === 0 && errors.length === 0) {
- p.log.success('No changes needed — your code is already up to date!');
+ log.success('No changes needed — your code is already up to date!');
} else if (apply) {
- p.log.success(
+ log.success(
`Done! Applied ${totalTransformsApplied} change${totalTransformsApplied === 1 ? '' : 's'} across ${totalFilesChanged} file${totalFilesChanged === 1 ? '' : 's'}.`,
);
if (errors.length > 0) {
- p.log.warn('Some files had errors — review them manually.');
+ log.warn('Some files had errors — review them manually.');
}
- p.log.info('Run your type checker and tests to verify the changes.');
+ log.info('Run your type checker and tests to verify the changes.');
} else {
- p.log.warn(
+ log.warn(
`Found ${totalTransformsApplied} change${totalTransformsApplied === 1 ? '' : 's'} across ${totalFilesChanged} file${totalFilesChanged === 1 ? '' : 's'}.`,
);
- p.log.info('Run with --apply to write changes to disk.');
+ log.info('Run with --apply to write changes to disk.');
}
// Report skipped optional codemods so the user knows they exist
if (skippedOptional.length > 0) {
- console.log('');
- p.log.message(
+ writeBlank();
+ log.message(
`${skippedOptional.length} optional codemod${skippedOptional.length === 1 ? '' : 's'} available:`,
);
for (const {name, meta} of skippedOptional) {
- p.log.info(` ${name} — ${meta.title}`);
+ log.info(` ${name} — ${meta.title}`);
if (meta.description) {
- p.log.info(` ${meta.description}`);
+ log.info(` ${meta.description}`);
}
- p.log.info(` Run: xds upgrade --codemod ${name} --path <dir> --apply`);
+ log.info(` Run: xds upgrade --codemod ${name} --path <dir> --apply`);
}
}
diff --git a/packages/cli/src/commands/agent-docs.mjs b/packages/cli/src/commands/agent-docs.mjs
index 823622fafd..1ee1a9c4f5 100644
--- a/packages/cli/src/commands/agent-docs.mjs
+++ b/packages/cli/src/commands/agent-docs.mjs
@@ -23,6 +23,7 @@ import {findCoreDir, CLI_ROOT} from '../utils/paths.mjs';
import {getRunPrefix} from '../utils/package-manager.mjs';
import {discoverComponents} from '../lib/component-discovery.mjs';
import {discoverHooks} from '../lib/hook-discovery.mjs';
+import {humanLog} from '../lib/json.mjs';
const AGENTS_MD = 'AGENTS.md';
const CLAUDE_MD = 'CLAUDE.md';
@@ -303,9 +304,9 @@ export function removeAgentDocs(targetDir) {
const deleteIfEmpty = p === AGENTS_MD || p === CLAUDE_DIR_MD;
if (removeXdsBlock(filePath, {deleteIfEmpty})) {
if (!fs.existsSync(filePath)) {
- console.log(`✓ Removed empty ${p}`);
+ humanLog(`✓ Removed empty ${p}`);
} else {
- console.log(`✓ Removed XDS section from ${p}`);
+ humanLog(`✓ Removed XDS section from ${p}`);
}
}
}
@@ -415,9 +416,9 @@ export function registerAgentDocs(program) {
const lang = program.opts().lang || null;
if (options.remove) {
- console.log('\n🗑️ Removing XDS agent docs...\n');
+ humanLog('\n🗑️ Removing XDS agent docs...\n');
removeAgentDocs(targetDir);
- console.log('\n✅ XDS agent docs removed.\n');
+ humanLog('\n✅ XDS agent docs removed.\n');
return;
}
@@ -428,7 +429,7 @@ export function registerAgentDocs(program) {
return;
}
- console.log(`\n📚 Installing XDS agent docs (v${version})...\n`);
+ humanLog(`\n📚 Installing XDS agent docs (v${version})...\n`);
// Collect explicit paths from --agent-docs-path (commander parses variadic as array or single)
const explicitPaths = options.agentDocsPath
@@ -448,10 +449,10 @@ export function registerAgentDocs(program) {
const run = `${runPrefix} xds`;
for (const t of targets) {
- console.log(`✓ ${t}`);
+ humanLog(`✓ ${t}`);
}
- console.log(`
+ humanLog(`
✅ XDS agent docs installed!
Your AI coding agent will now:
diff --git a/packages/cli/src/commands/build-theme.mjs b/packages/cli/src/commands/build-theme.mjs
index 1710efffc8..cdb123232d 100644
--- a/packages/cli/src/commands/build-theme.mjs
+++ b/packages/cli/src/commands/build-theme.mjs
@@ -18,7 +18,7 @@ import {createRequire} from 'node:module';
import {pathToFileURL, fileURLToPath} from 'node:url';
import {createJiti} from 'jiti';
import {getRunPrefix} from '../utils/package-manager.mjs';
-import {jsonOut, jsonError} from '../lib/json.mjs';
+import {jsonOut, jsonError, humanLog} from '../lib/json.mjs';
// Import shared theme processing from core — ensures build and runtime
// use the same logic for typography.scale expansion, prose, and component rules.
@@ -973,7 +973,14 @@ function validatePrivateVars(themeDef) {
export function registerTheme(program) {
const theme = program
.command('theme')
- .description('Theme tools — build, export, and manage XDS themes');
+ .description('Theme tools — build, export, and manage XDS themes')
+ .action(() => {
+ // Parent group has no default behaviour. When invoked without a
+ // subcommand, the preAction hook (in index.mjs) will reject --json
+ // because 'theme' (parent) is not on the JSON_SUPPORTED allowlist —
+ // only 'theme build' is. For the human path, fall through to help.
+ theme.help();
+ });
theme
.command('build <file>')
@@ -990,7 +997,7 @@ export function registerTheme(program) {
process.exit(1);
}
- if (!json) console.log(`\nBuilding theme from ${path.relative(process.cwd(), filePath)}...`);
+ if (!json) humanLog(`\nBuilding theme from ${path.relative(process.cwd(), filePath)}...`);
// Extract theme definition
let themeDef;
@@ -1097,7 +1104,7 @@ export function registerTheme(program) {
const mainCss = generateCSS(themeDef);
if (mainCss) scopeBlocks.push(mainCss);
if (scopeBlocks.length === 0) {
- if (!json) console.log('No overrides found — nothing to build.');
+ if (!json) humanLog('No overrides found — nothing to build.');
return;
}
const joined = scopeBlocks.join('\n\n');
@@ -1126,9 +1133,9 @@ export function registerTheme(program) {
const size = (Buffer.byteLength(css) / 1024).toFixed(1);
if (!json) {
- console.log(`\n✓ ${path.relative(process.cwd(), outPath)}`);
- console.log(` ${tokenCount} token overrides, ${componentCount} component overrides`);
- console.log(` ${size} KB`);
+ humanLog(`\n✓ ${path.relative(process.cwd(), outPath)}`);
+ humanLog(` ${tokenCount} token overrides, ${componentCount} component overrides`);
+ humanLog(` ${size} KB`);
}
// Always generate JS module + types alongside CSS
@@ -1144,8 +1151,8 @@ export function registerTheme(program) {
fs.writeFileSync(dtsPath, generatedHeader(sourceRelative, 'ts', buildCommand) + generateBuiltTypes(themeDef, iconInfo));
if (!json) {
- console.log(`✓ ${path.relative(process.cwd(), jsPath)}`);
- console.log(`✓ ${path.relative(process.cwd(), dtsPath)}`);
+ humanLog(`✓ ${path.relative(process.cwd(), jsPath)}`);
+ humanLog(`✓ ${path.relative(process.cwd(), dtsPath)}`);
}
// Generate type augmentation .d.ts if theme has custom prop values
@@ -1156,7 +1163,7 @@ export function registerTheme(program) {
variantDtsPath = path.join(outDir, `${baseName}.variants.d.ts`);
fs.writeFileSync(variantDtsPath, generatedHeader(sourceRelative, 'ts', buildCommand) + variantDecl);
const augCount = (variantDecl.match(/': true;/g) || []).length;
- if (!json) console.log(`✓ ${path.relative(process.cwd(), variantDtsPath)} (${augCount} type augmentations)`);
+ if (!json) humanLog(`✓ ${path.relative(process.cwd(), variantDtsPath)} (${augCount} type augmentations)`);
}
if (json) {
@@ -1178,7 +1185,7 @@ export function registerTheme(program) {
// Print install instructions
const relDir = path.relative(process.cwd(), outDir);
const exportName = `${toIdentifier(baseName)}Theme`;
- console.log(`
+ humanLog(`
Install in your app:
import { ${exportName} } from './${relDir}/${baseName}';
@@ -1200,12 +1207,12 @@ Or with a <link> tag:
// Print font declaration warnings (derived from typography roles)
if (resolvedTheme && resolvedTheme.fonts && resolvedTheme.fonts.length > 0) {
- console.log(`\n⚠ Theme "${themeDef.name}" requires fonts not included in the build:`);
+ humanLog(`\n⚠ Theme "${themeDef.name}" requires fonts not included in the build:`);
for (const font of resolvedTheme.fonts) {
- console.log(` ${font.family} — add to your document <head>:`);
- console.log(` <link rel="stylesheet" href="${font.url}" />`);
+ humanLog(` ${font.family} — add to your document <head>:`);
+ humanLog(` <link rel="stylesheet" href="${font.url}" />`);
}
- console.log('');
+ humanLog('');
}
});
}
diff --git a/packages/cli/src/commands/component/index.mjs b/packages/cli/src/commands/component/index.mjs
index 89771221bc..e4cb0c1bea 100644
--- a/packages/cli/src/commands/component/index.mjs
+++ b/packages/cli/src/commands/component/index.mjs
@@ -23,7 +23,7 @@ import {
} from '../../lib/component-format.mjs';
import {resolveTheme} from '../../lib/resolve-theme.mjs';
import {getRunPrefix} from '../../utils/package-manager.mjs';
-import {jsonOut, jsonError} from '../../lib/json.mjs';
+import {jsonOut, jsonError, humanLog} from '../../lib/json.mjs';
import {component as componentApi} from '../../api/component.mjs';
import {findRelatedBlocks} from '../../api/template.mjs';
@@ -90,34 +90,34 @@ export function registerComponent(program) {
case 'component.list': {
if (options.category) {
const [cat, comps] = Object.entries(result.data)[0];
- console.log(`\n${cat}:`);
- for (const comp of comps) console.log(` ${comp}`);
- console.log('');
+ humanLog(`\n${cat}:`);
+ for (const comp of comps) humanLog(` ${comp}`);
+ humanLog('');
} else {
- console.log('');
+ humanLog('');
for (const [key, comps] of Object.entries(result.data)) {
const isUngrouped = comps.length === 1 && comps[0] === key;
if (isUngrouped) {
- console.log(key);
+ humanLog(key);
} else {
- console.log(key);
- for (const comp of comps) console.log(` ${comp}`);
+ humanLog(key);
+ for (const comp of comps) humanLog(` ${comp}`);
}
}
- console.log('');
- console.log(`Usage: ${run} xds component <name>`);
- console.log('');
+ humanLog('');
+ humanLog(`Usage: ${run} xds component <name>`);
+ humanLog('');
}
break;
}
case 'component.brief': {
if (options.category || options.list || !name) {
- console.log(await formatBriefAll(coreDir, {zh, lang, themeData}));
+ humanLog(await formatBriefAll(coreDir, {zh, lang, themeData}));
} else {
const resolvedName = (name || '').replace(/^XDS/, '');
const importHint = resolveImportPath(coreDir, resolvedName);
- console.log(formatBrief(result.data, resolvedName, importHint, {themeData}));
+ humanLog(formatBrief(result.data, resolvedName, importHint, {themeData}));
}
break;
}
@@ -126,66 +126,66 @@ export function registerComponent(program) {
if (detail === 'brief') {
const resolvedName = (name || '').replace(/^XDS/, '');
const importHint = resolveImportPath(coreDir, resolvedName);
- console.log(formatBrief(result.data, resolvedName, importHint, {themeData}));
+ humanLog(formatBrief(result.data, resolvedName, importHint, {themeData}));
} else if (detail === 'compact') {
const resolvedName = (name || '').replace(/^XDS/, '');
const importHint = resolveImportPath(coreDir, resolvedName);
- console.log(formatCompact(result.data, resolvedName, importHint));
+ humanLog(formatCompact(result.data, resolvedName, importHint));
} else {
- console.log(formatFull(result.data, {themeData}));
+ humanLog(formatFull(result.data, {themeData}));
}
const compName = (name || '').replace(/^XDS/, '');
const related = await findRelatedBlocks(compName);
if (related.length > 0) {
- console.log('\nRelated block templates:\n');
+ humanLog('\nRelated block templates:\n');
for (const b of related) {
- console.log(` ${b.dirName}`);
- if (b.description) console.log(` ${b.description}`);
+ humanLog(` ${b.dirName}`);
+ if (b.description) humanLog(` ${b.description}`);
}
- console.log('');
+ humanLog('');
}
break;
}
case 'component.detail.props': {
const resolvedName = (name || '').replace(/^XDS/, '');
- console.log(formatProps({props: result.data}, resolvedName));
+ humanLog(formatProps({props: result.data}, resolvedName));
break;
}
case 'component.detail.source': {
- console.log(result.data.source);
+ humanLog(result.data.source);
break;
}
case 'component.detail.showcase': {
- console.log(result.data.source);
+ humanLog(result.data.source);
break;
}
case 'component.detail.blocks': {
const {showcase, examples, related} = result.data;
if (showcase) {
- console.log(`\nShowcase: ${showcase.displayName}`);
- if (showcase.description) console.log(` ${showcase.description}`);
+ humanLog(`\nShowcase: ${showcase.displayName}`);
+ if (showcase.description) humanLog(` ${showcase.description}`);
}
if (examples.length > 0) {
- console.log('\nExamples:\n');
+ humanLog('\nExamples:\n');
for (const b of examples) {
- console.log(` ${b.name}`);
- if (b.description) console.log(` ${b.description}`);
+ humanLog(` ${b.name}`);
+ if (b.description) humanLog(` ${b.description}`);
}
}
if (related.length > 0) {
- console.log(`\nRelated: ${related.length} blocks that use ${result.data.component}\n`);
+ humanLog(`\nRelated: ${related.length} blocks that use ${result.data.component}\n`);
for (const b of related) {
- console.log(` ${b.name}`);
+ humanLog(` ${b.name}`);
}
}
if (!showcase && examples.length === 0 && related.length === 0) {
- console.log(`\nNo blocks found for ${result.data.component}`);
+ humanLog(`\nNo blocks found for ${result.data.component}`);
}
- console.log('');
+ humanLog('');
break;
}
}
diff --git a/packages/cli/src/commands/discover.mjs b/packages/cli/src/commands/discover.mjs
index ad84db9789..ebdb8d551d 100644
--- a/packages/cli/src/commands/discover.mjs
+++ b/packages/cli/src/commands/discover.mjs
@@ -13,7 +13,7 @@
import {loadConfig} from '../lib/config.mjs';
import {scanAllPackages} from '../lib/package-scanner.mjs';
import {formatFull, formatBrief, formatCompact} from '../lib/component-format.mjs';
-import {jsonOut, jsonError} from '../lib/json.mjs';
+import {jsonOut, jsonError, humanLog} from '../lib/json.mjs';
import {discover as discoverApi} from '../api/discover.mjs';
export function registerDiscover(program) {
@@ -42,102 +42,107 @@ export function registerDiscover(program) {
process.exit(1);
}
- if (json) return jsonOut(result.type, result.data);
+ if (json) {
+ // Forward optional meta (e.g. configured flag for discover.list) as a
+ // sibling of data via jsonOut, so the envelope still carries
+ // apiVersion and goes through the single sanctioned emit path.
+ return jsonOut(result.type, result.data, result.meta);
+ }
switch (result.type) {
case 'discover.list': {
if (result.data.length === 0) {
const config = await loadConfig();
- console.log('');
+ humanLog('');
if (config.packages.length === 0) {
- console.log('No package directories configured.');
- console.log('');
- console.log('Add a packages field to xds.config.mjs:');
- console.log('');
- console.log(' export default {');
- console.log(" packages: ['/path/to/your/libs'],");
- console.log(' };');
+ humanLog('No package directories configured.');
+ humanLog('');
+ humanLog('Add a packages field to xds.config.mjs:');
+ humanLog('');
+ humanLog(' export default {');
+ humanLog(" packages: ['/path/to/your/libs'],");
+ humanLog(' };');
} else {
- console.log('No external XDS packages found.');
- console.log('');
- console.log('Packages opt in by adding an "xds" field to package.json:');
- console.log('');
- console.log(' {');
- console.log(' "xds": {');
- console.log(' "docs": "./src",');
- console.log(' "category": "Common"');
- console.log(' }');
- console.log(' }');
+ humanLog('No external XDS packages found.');
+ humanLog('');
+ humanLog('Packages opt in by adding an "xds" field to package.json:');
+ humanLog('');
+ humanLog(' {');
+ humanLog(' "xds": {');
+ humanLog(' "docs": "./src",');
+ humanLog(' "category": "Common"');
+ humanLog(' }');
+ humanLog(' }');
}
- console.log('');
+ humanLog('');
} else {
- console.log('');
+ humanLog('');
for (const pkg of result.data) {
const count = pkg.components.length;
const label = count === 1 ? 'component' : 'components';
const heading = pkg.displayName
? pkg.displayName + ' ' + pkg.name + ' (' + count + ' ' + label + ')'
: pkg.name + ' (' + count + ' ' + label + ')';
- console.log(heading);
- if (pkg.description) console.log(' ' + pkg.description);
+ humanLog(heading);
+ if (pkg.description) humanLog(' ' + pkg.description);
if (options.components) {
- for (const comp of pkg.components) console.log(' ' + comp);
+ for (const comp of pkg.components) humanLog(' ' + comp);
} else {
const maxShow = 10;
const shown = pkg.components.slice(0, maxShow);
const remaining = count - maxShow;
const list = shown.join(', ');
- console.log(remaining > 0 ? ' ' + list + ', +' + remaining + ' more' : ' ' + list);
+ humanLog(remaining > 0 ? ' ' + list + ', +' + remaining + ' more' : ' ' + list);
}
- console.log('');
+ humanLog('');
}
- console.log('Usage:');
- console.log(' xds discover <package> Browse a package');
- console.log(' xds discover <package>/Component View component docs');
- console.log(' xds discover <search> Search all packages');
- console.log('');
+ humanLog('Usage:');
+ humanLog(' xds discover <package> Browse a package');
+ humanLog(' xds discover <package>/Component View component docs');
+ humanLog(' xds discover <search> Search all packages');
+ humanLog('');
}
break;
}
case 'discover.detail': {
- console.log('');
+ humanLog('');
const d = result.data;
const detailHeading = d.displayName
? d.displayName + ' ' + d.name + ' (' + d.components.length + ' components)'
: d.name + ' (' + d.components.length + ' components)';
- console.log(detailHeading);
- if (d.description) console.log(' ' + d.description);
- console.log('');
- for (const comp of result.data.components) console.log(' ' + comp);
- console.log('');
- console.log('Usage: xds discover ' + result.data.name + '/<ComponentName>');
- console.log('');
+ humanLog(detailHeading);
+ if (d.description) humanLog(' ' + d.description);
+ humanLog('');
+ for (const comp of result.data.components) humanLog(' ' + comp);
+ humanLog('');
+ humanLog('Usage: xds discover ' + result.data.name + '/<ComponentName>');
+ humanLog('');
break;
}
case 'discover.detail.doc': {
const docs = result.data;
if (detail === 'brief') {
- console.log(formatBrief(docs, docs.name, ''));
+ humanLog(formatBrief(docs, docs.name, ''));
} else if (detail === 'compact') {
- console.log(formatCompact(docs, docs.name, ''));
+ humanLog(formatCompact(docs, docs.name, ''));
} else {
- console.log(formatFull(docs));
+ humanLog(formatFull(docs));
}
- console.log('');
+ humanLog('');
break;
}
case 'discover.search': {
- console.log('');
- console.log('Found ' + result.data.matches.length + ' matches for "' + result.data.query + '":');
- console.log('');
+ humanLog('');
+ humanLog('Found ' + result.data.matches.length + ' matches for "' + result.data.query + '":');
+ humanLog('');
for (const m of result.data.matches) {
- console.log(' xds discover ' + m.package + '/' + m.component);
+ humanLog(' xds discover ' + m.package + '/' + m.component);
}
- console.log('');
+ humanLog('');
break;
}
}
diff --git a/packages/cli/src/commands/docs.mjs b/packages/cli/src/commands/docs.mjs
index 4c6d625de6..476d034569 100644
--- a/packages/cli/src/commands/docs.mjs
+++ b/packages/cli/src/commands/docs.mjs
@@ -13,7 +13,7 @@
*/
import {getRunPrefix} from '../utils/package-manager.mjs';
-import {jsonOut, jsonError} from '../lib/json.mjs';
+import {jsonOut, jsonError, humanLog} from '../lib/json.mjs';
import {docs as docsApi} from '../api/docs.mjs';
// ─── Formatting ──────────────────────────────────────────────────────────────
@@ -125,22 +125,22 @@ export function registerDocs(program) {
switch (result.type) {
case 'docs.list': {
- console.log('\nAvailable docs:\n');
+ humanLog('\nAvailable docs:\n');
for (const entry of result.data) {
- console.log(` ${entry.topic.padEnd(14)} ${entry.description}`);
+ humanLog(` ${entry.topic.padEnd(14)} ${entry.description}`);
}
- console.log(`\nUsage: ${run} xds docs <topic>`);
- console.log(` ${run} xds docs <topic> <section>\n`);
+ humanLog(`\nUsage: ${run} xds docs <topic>`);
+ humanLog(` ${run} xds docs <topic> <section>\n`);
break;
}
case 'docs.detail': {
- console.log(formatReferenceFull(result.data, detail));
+ humanLog(formatReferenceFull(result.data, detail));
break;
}
case 'docs.detail.section': {
- console.log(formatSection(result.data, detail));
+ humanLog(formatSection(result.data, detail));
break;
}
}
diff --git a/packages/cli/src/commands/gap-report.mjs b/packages/cli/src/commands/gap-report.mjs
index 7b25fbeb36..d47c4c1a87 100644
--- a/packages/cli/src/commands/gap-report.mjs
+++ b/packages/cli/src/commands/gap-report.mjs
@@ -20,7 +20,7 @@ import {
GAP_CATEGORIES,
} from '../utils/github.mjs';
import {getRunPrefix} from '../utils/package-manager.mjs';
-import {jsonOut, jsonError} from '../lib/json.mjs';
+import {jsonOut, jsonError, humanLog} from '../lib/json.mjs';
/**
* Decide whether we're in a context safe to actually file a report.
@@ -245,7 +245,7 @@ export function registerGapReport(program) {
if (options.listCategories) {
if (json) return jsonOut('gap-report.categories', GAP_CATEGORIES);
for (const cat of GAP_CATEGORIES) {
- console.log(` ${cat.value.padEnd(20)} ${cat.label}`);
+ humanLog(` ${cat.value.padEnd(20)} ${cat.label}`);
}
return;
}
@@ -253,7 +253,7 @@ export function registerGapReport(program) {
const config = loadGapReportConfig();
if (!config.enabled) {
if (json) return jsonError('Gap reporting is disabled');
- console.log(
+ humanLog(
`Gap reporting is disabled (XDS_GAP_REPORT=off or xds.config.mjs).\n` +
`Run \`${getRunPrefix()} xds gap-report setup\` to configure.`,
);
@@ -321,8 +321,8 @@ export function registerGapReport(program) {
'Default is dry-run in non-interactive contexts.',
});
}
- console.log(formatPreview(preview));
- console.log(
+ humanLog(formatPreview(preview));
+ humanLog(
'\n[dry-run] Nothing was filed. Re-run with --commit to file this report.',
);
return;
@@ -341,9 +341,9 @@ export function registerGapReport(program) {
url: url || null,
});
if (url) {
- console.log(`\n✓ Gap report filed: ${url}\n`);
+ humanLog(`\n✓ Gap report filed: ${url}\n`);
} else {
- console.log('\nGap reporting is disabled via configuration.\n');
+ humanLog('\nGap reporting is disabled via configuration.\n');
}
} catch (err) {
if (json) return jsonError(err.message);
@@ -353,6 +353,15 @@ export function registerGapReport(program) {
return;
}
+ // --json without --component/--category/--reason can't go interactive —
+ // emit a structured error explaining the required flags.
+ if (json) {
+ return jsonError(
+ 'gap-report --json requires --component, --category, and --reason. ' +
+ 'Run with --list-categories to see valid categories.',
+ );
+ }
+
// Interactive mode
p.intro('Report an XDS gap');
diff --git a/packages/cli/src/commands/hook/index.mjs b/packages/cli/src/commands/hook/index.mjs
index 49d095755a..870597389d 100644
--- a/packages/cli/src/commands/hook/index.mjs
+++ b/packages/cli/src/commands/hook/index.mjs
@@ -17,7 +17,7 @@ import {
formatHookParams,
} from '../../lib/hook-format.mjs';
import {getRunPrefix} from '../../utils/package-manager.mjs';
-import {jsonOut, jsonError} from '../../lib/json.mjs';
+import {jsonOut, jsonError, humanLog} from '../../lib/json.mjs';
import {hook as hookApi} from '../../api/hook.mjs';
import {findRelatedBlocks} from '../../api/template.mjs';
@@ -74,39 +74,39 @@ export function registerHook(program) {
case 'hook.list': {
if (options.category) {
const [cat, hookNames] = Object.entries(result.data)[0];
- console.log(`\n${cat}:`);
- for (const h of hookNames) console.log(` ${h}`);
- console.log('');
+ humanLog(`\n${cat}:`);
+ for (const h of hookNames) humanLog(` ${h}`);
+ humanLog('');
} else {
- console.log('');
+ humanLog('');
for (const [category, hookNames] of Object.entries(result.data)) {
- console.log(category);
- for (const h of hookNames) console.log(` ${h}`);
+ humanLog(category);
+ for (const h of hookNames) humanLog(` ${h}`);
}
- console.log('');
- console.log(`Usage: ${run} xds hook <name>`);
- console.log('');
+ humanLog('');
+ humanLog(`Usage: ${run} xds hook <name>`);
+ humanLog('');
}
break;
}
case 'hook.brief': {
if (options.category || options.list || !name) {
- console.log(await formatHookBriefAll(coreDir));
+ humanLog(await formatHookBriefAll(coreDir));
} else {
- console.log(formatHookBrief(result.data));
+ humanLog(formatHookBrief(result.data));
}
break;
}
case 'hook.detail': {
if (detail === 'brief') {
- console.log(formatHookBrief(result.data));
+ humanLog(formatHookBrief(result.data));
} else if (detail === 'compact') {
const importPath = result.data.importPath || '@xds/core/hooks';
- console.log(formatHookCompact(result.data, importPath));
+ humanLog(formatHookCompact(result.data, importPath));
} else {
- console.log(formatHookFull(result.data));
+ humanLog(formatHookFull(result.data));
}
// Show related block templates from relatedComponents
const relatedComps = result.data.relatedComponents || [];
@@ -120,18 +120,18 @@ export function registerHook(program) {
}
}
if (allBlocks.length > 0) {
- console.log('\nRelated block templates:\n');
+ humanLog('\nRelated block templates:\n');
for (const b of allBlocks) {
- console.log(` ${b.dirName}`);
- if (b.description) console.log(` ${b.description}`);
+ humanLog(` ${b.dirName}`);
+ if (b.description) humanLog(` ${b.description}`);
}
- console.log('');
+ humanLog('');
}
break;
}
case 'hook.detail.params': {
- console.log(formatHookParams({params: result.data, name: name}));
+ humanLog(formatHookParams({params: result.data, name: name}));
break;
}
}
diff --git a/packages/cli/src/commands/init.mjs b/packages/cli/src/commands/init.mjs
index 6836322a05..00d2a5631e 100644
--- a/packages/cli/src/commands/init.mjs
+++ b/packages/cli/src/commands/init.mjs
@@ -20,6 +20,7 @@ import {CLI_ROOT} from '../utils/paths.mjs';
import {getRunPrefix} from '../utils/package-manager.mjs';
import {installAgentDocs, removeAgentDocs} from './agent-docs.mjs';
import {listTemplates} from './template.mjs';
+import {humanLog} from '../lib/json.mjs';
import {requireInteractive} from '../utils/interactive.mjs';
const VALID_FEATURES = ['agents', 'theme', 'template'];
@@ -47,7 +48,7 @@ function runAgents(targetDir, {interactive = true, agent, agentDocsPath} = {}) {
if (interactive) {
p.log.success(`AI agent docs installed → ${summary}`);
} else {
- console.log(`✓ AI agent docs installed → ${summary}`);
+ humanLog(`✓ AI agent docs installed → ${summary}`);
}
} catch {
const msg = `Could not install agent docs. Try again with \`${run} xds init --features agents\`.`;
@@ -63,7 +64,7 @@ function runAgents(targetDir, {interactive = true, agent, agentDocsPath} = {}) {
async function runTheme({interactive = true} = {}) {
if (!interactive) {
- console.log(`✓ Theme scaffolding requires interactive mode. Run \`${run} xds theme\` instead.`);
+ humanLog(`✓ Theme scaffolding requires interactive mode. Run \`${run} xds theme\` instead.`);
return;
}
@@ -83,7 +84,7 @@ async function runTemplate(targetDir, {interactive = true, templateName} = {}) {
if (!interactive) {
if (!templateName) {
- console.log(`✓ Available templates: ${templates.join(', ')}. Use ${run} xds template <name> [path].`);
+ humanLog(`✓ Available templates: ${templates.join(', ')}. Use ${run} xds template <name> [path].`);
return;
}
@@ -96,7 +97,7 @@ async function runTemplate(targetDir, {interactive = true, templateName} = {}) {
const srcPath = path.join(CLI_ROOT, 'templates', 'pages', templateName, 'page.tsx');
fs.mkdirSync(outputDir, {recursive: true});
fs.copyFileSync(srcPath, path.join(outputDir, 'page.tsx'));
- console.log(`✓ Template created at ${path.relative(targetDir, outputDir)}/page.tsx`);
+ humanLog(`✓ Template created at ${path.relative(targetDir, outputDir)}/page.tsx`);
return;
}
@@ -150,7 +151,7 @@ export function registerInit(program) {
// Remove mode
if (options.removeAgents) {
removeAgentDocs(targetDir);
- console.log('✓ AI agent docs removed.');
+ humanLog('✓ AI agent docs removed.');
return;
}
@@ -226,13 +227,13 @@ export function registerInit(program) {
// Outro
p.outro('XDS initialized!');
- console.log('');
- console.log(' Next steps:');
- console.log(" 1. Import components: import { XDSButton } from '@xds/core'");
- console.log(' 2. Optionally add a theme:');
- console.log(" import { defaultTheme } from '@xds/theme/default'");
- console.log(' <XDSTheme theme={defaultTheme}>...</XDSTheme>');
- console.log(` 3. ${run} xds --help for all commands`);
- console.log('');
+ humanLog('');
+ humanLog(' Next steps:');
+ humanLog(" 1. Import components: import { XDSButton } from '@xds/core'");
+ humanLog(' 2. Optionally add a theme:');
+ humanLog(" import { defaultTheme } from '@xds/theme/default'");
+ humanLog(' <XDSTheme theme={defaultTheme}>...</XDSTheme>');
+ humanLog(` 3. ${run} xds --help for all commands`);
+ humanLog('');
});
}
diff --git a/packages/cli/src/commands/json-contract.test.mjs b/packages/cli/src/commands/json-contract.test.mjs
new file mode 100644
index 0000000000..84e2ee8eaf
--- /dev/null
+++ b/packages/cli/src/commands/json-contract.test.mjs
@@ -0,0 +1,216 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Integration tests for the global --json contract.
+ *
+ * These tests spawn the CLI as a subprocess (the only way to exercise
+ * Commander hooks end-to-end) in a tmp directory, then assert:
+ *
+ * 1. Commands NOT on the JSON_SUPPORTED allowlist reject --json BEFORE
+ * running any side effects (no files written, exit 1, valid JSON
+ * error envelope on stdout).
+ *
+ * 2. Commands ON the allowlist emit valid JSON envelopes for their
+ * common code paths (success and error).
+ *
+ * 3. The --version --json variant emits a structured envelope.
+ *
+ * Spawning a real subprocess (vs. importing program.mjs) is essential
+ * because Commander's preAction hooks and process.exit calls only fire
+ * during a real .parse() against argv.
+ */
+
+import {describe, it, expect, beforeEach, afterEach} from 'vitest';
+import {spawnSync} from 'node:child_process';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {fileURLToPath} from 'node:url';
+
+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 || '',
+ };
+}
+
+function parseJson(stdout) {
+ // CLI emits a single JSON document. If anything else snuck onto stdout
+ // (clack output, console.log strings, etc.) JSON.parse will throw —
+ // which is exactly the failure mode we want to catch in tests.
+ return JSON.parse(stdout);
+}
+
+let tmpDir;
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'xds-json-contract-'));
+});
+
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe('--json contract: rejects before side effects', () => {
+ it('xds init --json --features agents does not write .claude/CLAUDE.md', () => {
+ const before = fs.readdirSync(tmpDir);
+ expect(before).toEqual([]);
+
+ const {status, stdout} = runCli(['init', '--json', '--features', 'agents'], {cwd: tmpDir});
+
+ // 1. Exit code must be non-zero.
+ expect(status).toBe(1);
+
+ // 2. Stdout must be valid JSON with an error envelope.
+ const parsed = parseJson(stdout);
+ expect(parsed).toHaveProperty('error');
+ expect(parsed.error).toMatch(/json/i);
+ expect(parsed.error).toMatch(/init/i);
+
+ // 3. CRITICAL — no filesystem mutation took place.
+ const after = fs.readdirSync(tmpDir);
+ expect(after).toEqual([]);
+ expect(fs.existsSync(path.join(tmpDir, '.claude'))).toBe(false);
+ expect(fs.existsSync(path.join(tmpDir, '.claude/CLAUDE.md'))).toBe(false);
+ expect(fs.existsSync(path.join(tmpDir, 'AGENTS.md'))).toBe(false);
+ });
+
+ it('xds init --json --all does not write any files', () => {
+ const {status, stdout} = runCli(['init', '--json', '--all'], {cwd: tmpDir});
+ expect(status).toBe(1);
+ parseJson(stdout); // valid JSON
+ expect(fs.readdirSync(tmpDir)).toEqual([]);
+ });
+
+ it('xds gap-report setup --json rejects before prompting', () => {
+ const {status, stdout} = runCli(['gap-report', 'setup', '--json'], {cwd: tmpDir});
+ expect(status).toBe(1);
+ const parsed = parseJson(stdout);
+ expect(parsed.error).toMatch(/gap-report setup/);
+ // No xds.config.mjs written.
+ expect(fs.existsSync(path.join(tmpDir, 'xds.config.mjs'))).toBe(false);
+ });
+
+ it('xds theme --json (parent, no subcommand) rejects without printing help', () => {
+ const {status, stdout, stderr} = runCli(['theme', '--json'], {cwd: tmpDir});
+ expect(status).toBe(1);
+ const parsed = parseJson(stdout);
+ expect(parsed.error).toMatch(/theme/);
+ // Human help text would mention "Usage:" — must NOT appear on stdout.
+ expect(stdout).not.toMatch(/Usage:/);
+ expect(stderr).not.toMatch(/Usage:/);
+ });
+
+ it('xds postinstall --json rejects (hidden command not on allowlist)', () => {
+ const {status, stdout} = runCli(['postinstall', '--json'], {cwd: tmpDir});
+ expect(status).toBe(1);
+ const parsed = parseJson(stdout);
+ expect(parsed).toHaveProperty('error');
+ });
+
+ it('error envelope is { error, suggestions? } — never { type, data }', () => {
+ const {stdout} = runCli(['init', '--json'], {cwd: tmpDir});
+ const parsed = parseJson(stdout);
+ expect(parsed).toHaveProperty('error');
+ expect(parsed).not.toHaveProperty('type');
+ expect(parsed).not.toHaveProperty('data');
+ });
+});
+
+describe('--json contract: supported commands emit valid envelopes', () => {
+ it('xds --version --json emits { type: "version", data: { version } }', () => {
+ const {status, stdout} = runCli(['--version', '--json']);
+ expect(status).toBe(0);
+ const parsed = parseJson(stdout);
+ expect(parsed.type).toBe('version');
+ expect(parsed.data).toHaveProperty('version');
+ expect(typeof parsed.data.version).toBe('string');
+ });
+
+ it('xds --json (no subcommand) emits a help envelope', () => {
+ const {status, stdout} = runCli(['--json']);
+ expect(status).toBe(0);
+ const parsed = parseJson(stdout);
+ expect(parsed.type).toBe('help');
+ expect(Array.isArray(parsed.data.commands)).toBe(true);
+ expect(Array.isArray(parsed.data.jsonSupported)).toBe(true);
+ });
+
+ it('xds gap-report --json --list-categories returns a typed envelope', () => {
+ const {status, stdout} = runCli(['gap-report', '--json', '--list-categories'], {cwd: tmpDir});
+ expect(status).toBe(0);
+ const parsed = parseJson(stdout);
+ expect(parsed.type).toBe('gap-report.categories');
+ expect(Array.isArray(parsed.data)).toBe(true);
+ });
+
+ it('xds gap-report --json without required flags emits a structured error (no clack)', () => {
+ // Configure gap-report so it doesn't error on "disabled" — we want to
+ // hit the "interactive prompt would start" branch.
+ fs.writeFileSync(
+ path.join(tmpDir, 'xds.config.mjs'),
+ 'export default { gapReport: { command: "true" } };\n',
+ );
+ const {status, stdout} = runCli(['gap-report', '--json'], {cwd: tmpDir});
+ expect(status).toBe(1);
+ const parsed = parseJson(stdout);
+ expect(parsed.error).toMatch(/component/i);
+ // Must not contain clack-rendered prompt characters.
+ expect(stdout).not.toMatch(/Which component/);
+ });
+
+ it('xds upgrade --json --list returns the codemod list', () => {
+ const {status, stdout} = runCli(['upgrade', '--json', '--list'], {cwd: tmpDir});
+ expect(status).toBe(0);
+ const parsed = parseJson(stdout);
+ expect(parsed.type).toBe('upgrade.list');
+ expect(Array.isArray(parsed.data)).toBe(true);
+ });
+
+ it('xds upgrade --json (already up to date) emits upgrade.status', () => {
+ // Force a no-op range: from > to.
+ const {status, stdout} = runCli(
+ ['upgrade', '--json', '--from', '99.0.0', '--to', '0.0.1'],
+ {cwd: tmpDir},
+ );
+ expect(status).toBe(0);
+ const parsed = parseJson(stdout);
+ expect(parsed.type).toBe('upgrade.status');
+ expect(parsed.data.status).toBe('up_to_date');
+ expect(parsed.data.from).toBe('99.0.0');
+ expect(parsed.data.to).toBe('0.0.1');
+ });
+
+ it('xds discover --json (no config) includes meta.configured=false', () => {
+ const {status, stdout} = runCli(['discover', '--json'], {cwd: tmpDir});
+ expect(status).toBe(0);
+ const parsed = parseJson(stdout);
+ expect(parsed.type).toBe('discover.list');
+ expect(parsed.data).toEqual([]);
+ expect(parsed.meta).toEqual({configured: false});
+ });
+
+ it('xds template --json emits a typed envelope', () => {
+ const {status, stdout} = runCli(['template', '--json'], {cwd: tmpDir});
+ expect(status).toBe(0);
+ const parsed = parseJson(stdout);
+ expect(parsed.type).toBe('template.list');
+ expect(Array.isArray(parsed.data)).toBe(true);
+ });
+
+ it('xds docs --json emits a typed envelope', () => {
+ const {status, stdout} = runCli(['docs', '--json'], {cwd: tmpDir});
+ expect(status).toBe(0);
+ const parsed = parseJson(stdout);
+ expect(parsed.type).toMatch(/^docs\./);
+ });
+});
diff --git a/packages/cli/src/commands/swizzle.mjs b/packages/cli/src/commands/swizzle.mjs
index 8942772bfd..3944ae3257 100644
--- a/packages/cli/src/commands/swizzle.mjs
+++ b/packages/cli/src/commands/swizzle.mjs
@@ -16,7 +16,7 @@ import * as path from 'node:path';
import * as p from '@clack/prompts';
import {findCoreDir, listComponents} from '../utils/paths.mjs';
import {isInteractive} from '../utils/interactive.mjs';
-import {jsonOut, jsonError} from '../lib/json.mjs';
+import {jsonOut, jsonError, humanLog} from '../lib/json.mjs';
import {
buildGapReportPreview,
checkGhCli,
@@ -95,13 +95,13 @@ export function registerSwizzle(program) {
if (options.list || !component) {
if (json) return jsonOut('swizzle.list', components);
- console.log('\nAvailable components:\n');
+ humanLog('\nAvailable components:\n');
for (const name of components) {
- console.log(` ${name}`);
+ humanLog(` ${name}`);
}
- console.log(`\nUsage: xds swizzle <component>\n`);
- console.log('Example: xds swizzle Button');
- console.log(' xds swizzle XDSButton (XDS prefix also works)\n');
+ humanLog(`\nUsage: xds swizzle <component>\n`);
+ humanLog('Example: xds swizzle Button');
+ humanLog(' xds swizzle XDSButton (XDS prefix also works)\n');
return;
}
@@ -204,36 +204,36 @@ export function registerSwizzle(program) {
gapReportDryRun: gapDryRunPreview,
gapReportSuppressed: reportingSuppressed || !gapConfig.enabled,
});
- console.log(`\n✓ Copied ${copied} files to ${relOutput}/\n`);
- console.log('Relative imports have been rewritten to use @xds/core.');
- console.log('You can now customize the component source freely.\n');
+ humanLog(`\n✓ Copied ${copied} files to ${relOutput}/\n`);
+ humanLog('Relative imports have been rewritten to use @xds/core.');
+ humanLog('You can now customize the component source freely.\n');
if (gapReportUrl) {
- console.log(`✓ Gap report filed: ${gapReportUrl}\n`);
+ humanLog(`✓ Gap report filed: ${gapReportUrl}\n`);
} else if (gapDryRunPreview) {
- console.log(formatPreview(buildGapReportPreview({
+ humanLog(formatPreview(buildGapReportPreview({
component: dirName,
category: options.gapCategory || 'other',
intention: options.gap,
source: 'llm-auto',
})));
- console.log(
+ humanLog(
'\n[dry-run] No gap report was filed. Re-run with --commit to file.',
);
} else if (reportingSuppressed) {
- console.log('Gap reporting suppressed by --no-report.');
+ humanLog('Gap reporting suppressed by --no-report.');
} else if (!gapConfig.enabled) {
- console.log('Gap reporting is disabled via configuration.');
+ humanLog('Gap reporting is disabled via configuration.');
} else if (!gapConfig.command && !checkGhCli()) {
- console.log('Skipping gap report: gh CLI not available.');
+ humanLog('Skipping gap report: gh CLI not available.');
}
return;
}
if (json) return jsonOut('swizzle.copy', {component: dirName, outputDir: relOutput, filesCopied: copied, files: copiedFiles.map(f => f)});
- console.log(`\n✓ Copied ${copied} files to ${relOutput}/\n`);
- console.log('Relative imports have been rewritten to use @xds/core.');
- console.log('You can now customize the component source freely.\n');
+ humanLog(`\n✓ Copied ${copied} files to ${relOutput}/\n`);
+ humanLog('Relative imports have been rewritten to use @xds/core.');
+ humanLog('You can now customize the component source freely.\n');
if (reportingSuppressed || !gapConfig.enabled) {
return;
@@ -316,7 +316,7 @@ export function registerSwizzle(program) {
);
if (!confirmFile) {
- console.log('Cancelled — nothing was filed.');
+ humanLog('Cancelled — nothing was filed.');
return;
}
@@ -326,7 +326,7 @@ export function registerSwizzle(program) {
try {
const url = createGapReport(previewArgs);
s.stop('Gap report filed');
- console.log(`✓ ${url}\n`);
+ humanLog(`✓ ${url}\n`);
} catch (err) {
s.stop('Failed to file gap report');
console.error(`Warning: Could not file gap report: ${err.message}`);
diff --git a/packages/cli/src/commands/template.mjs b/packages/cli/src/commands/template.mjs
index 28f1ceabdd..e71e5be344 100644
--- a/packages/cli/src/commands/template.mjs
+++ b/packages/cli/src/commands/template.mjs
@@ -6,7 +6,7 @@
import * as path from 'node:path';
import {CLI_ROOT} from '../utils/paths.mjs';
-import {jsonOut, jsonError} from '../lib/json.mjs';
+import {jsonOut, jsonError, humanLog} from '../lib/json.mjs';
import {template as templateApi, getTemplateById} from '../api/template.mjs';
export {discoverTemplates, listTemplates, getTemplateById} from '../api/template.mjs';
@@ -46,44 +46,44 @@ export function registerTemplate(program) {
const pages = result.data.filter(t => t.type === 'page');
const blocks = result.data.filter(t => t.type === 'block');
if (pages.length > 0) {
- console.log('\nPage Templates:\n');
+ humanLog('\nPage Templates:\n');
for (const t of pages) {
const status = t.isReady ? '' : ' (WIP)';
- console.log(` ${t.name}${status}`);
- if (t.description) console.log(` ${t.description}`);
+ humanLog(` ${t.name}${status}`);
+ if (t.description) humanLog(` ${t.description}`);
}
}
if (blocks.length > 0) {
- console.log('\nBlock Templates:\n');
+ humanLog('\nBlock Templates:\n');
for (const t of blocks) {
const status = t.isReady ? '' : ' (WIP)';
- console.log(` ${t.name}${status}`);
- if (t.description) console.log(` ${t.description}`);
+ humanLog(` ${t.name}${status}`);
+ if (t.description) humanLog(` ${t.description}`);
}
}
- console.log('\nUsage:');
- console.log(' xds template <name> [target-path] Scaffold page or block');
- console.log(' xds template <name> --skeleton Layout reference');
- console.log(' xds template --list --type block List only blocks\n');
+ humanLog('\nUsage:');
+ humanLog(' xds template <name> [target-path] Scaffold page or block');
+ humanLog(' xds template <name> --skeleton Layout reference');
+ humanLog(' xds template --list --type block List only blocks\n');
break;
}
case 'template.skeleton': {
const {template: tName, description, components, skeleton} = result.data;
- console.log(`\n# ${tName}${description ? ' — ' + description : ''}`);
- console.log(`# Components: ${components.join(', ')}\n`);
- console.log(skeleton);
- console.log('');
+ humanLog(`\n# ${tName}${description ? ' — ' + description : ''}`);
+ humanLog(`# Components: ${components.join(', ')}\n`);
+ humanLog(skeleton);
+ humanLog('');
break;
}
case 'template.show': {
- console.log(result.data.source);
+ humanLog(result.data.source);
break;
}
case 'template.copy': {
- console.log(`\n✓ Copied template to ${result.data.outputDir}/${result.data.fileName}\n`);
+ humanLog(`\n✓ Copied template to ${result.data.outputDir}/${result.data.fileName}\n`);
break;
}
}
@@ -107,6 +107,6 @@ export function registerTemplate(program) {
if (json) return jsonOut(result.type, result.data);
- console.log(result.data.source);
+ humanLog(result.data.source);
});
}
diff --git a/packages/cli/src/commands/upgrade.mjs b/packages/cli/src/commands/upgrade.mjs
index 142b42e3a0..4373cf94dd 100644
--- a/packages/cli/src/commands/upgrade.mjs
+++ b/packages/cli/src/commands/upgrade.mjs
@@ -224,11 +224,16 @@ export function registerUpgrade(program) {
}
if (!options.force && semverGte(currentVersion, targetVersion)) {
- if (!json) {
- p.log.success('Already up to date — no codemods to run.');
- p.log.info('Use --force to run codemods anyway, or --from <version> to specify the previous version.');
- p.outro('Done');
+ if (json) {
+ return jsonOut('upgrade.status', {
+ status: 'up_to_date',
+ from: currentVersion,
+ to: targetVersion,
+ });
}
+ p.log.success('Already up to date — no codemods to run.');
+ p.log.info('Use --force to run codemods anyway, or --from <version> to specify the previous version.');
+ p.outro('Done');
return;
}
}
@@ -240,10 +245,15 @@ export function registerUpgrade(program) {
);
if (versionManifests.length === 0) {
- if (!json) {
- p.log.success('No codemods available for this version range.');
- p.outro('Done');
+ if (json) {
+ return jsonOut('upgrade.status', {
+ status: 'no_codemods',
+ from: skipVersionCheck ? null : currentVersion,
+ to: targetVersion,
+ });
}
+ p.log.success('No codemods available for this version range.');
+ p.outro('Done');
return;
}
@@ -305,7 +315,7 @@ export function registerUpgrade(program) {
}
// Ensure jscodeshift is available
- const ready = await ensureJscodeshift({installDeps: options.installDeps});
+ const ready = await ensureJscodeshift({installDeps: options.installDeps, silent: json});
if (!ready) {
if (json) return jsonError('jscodeshift is required but could not be installed.');
p.outro('Aborted');
@@ -314,10 +324,11 @@ export function registerUpgrade(program) {
}
// Run codemods
- await runCodemods(versionManifests, {
+ const codemodResult = await runCodemods(versionManifests, {
apply: options.apply,
path: options.path,
codemod: options.codemod,
+ silent: json,
});
// Refresh agent docs if any exist (AGENTS.md, CLAUDE.md, .claude/CLAUDE.md, etc.)
@@ -340,7 +351,14 @@ export function registerUpgrade(program) {
}
}
- if (json) return jsonOut('upgrade.run', receipt);
+ if (json) {
+ if (codemodResult && typeof codemodResult === 'object') {
+ receipt.filesChanged = codemodResult.totalFilesChanged ?? 0;
+ receipt.transformsApplied = codemodResult.totalTransformsApplied ?? 0;
+ receipt.errors = codemodResult.errors ?? [];
+ }
+ return jsonOut('upgrade.run', receipt);
+ }
p.outro(options.apply ? 'Upgrade complete' : 'Dry run complete');
});
}
diff --git a/packages/cli/src/index.mjs b/packages/cli/src/index.mjs
index 659c51665e..ef4c04037c 100644
--- a/packages/cli/src/index.mjs
+++ b/packages/cli/src/index.mjs
@@ -13,14 +13,50 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import {checkForUpdate} from './utils/update-check.mjs';
import {getRunPrefix} from './utils/package-manager.mjs';
+import {API_VERSION, setJsonMode} from './lib/json.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Read version from package.json so it stays in sync
const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf-8'));
+// Intercept `xds --version --json` (or `-V --json`) before Commander processes
+// the version flag and exits. Commander's built-in version handler prints the
+// raw version string and calls process.exit, bypassing our hooks — so the
+// only correct place to JSON-ify it is here.
+const _argv = process.argv.slice(2);
+if (
+ (_argv.includes('--version') || _argv.includes('-V')) &&
+ _argv.includes('--json')
+) {
+ process.__xdsJsonHandled = true;
+ console.log(JSON.stringify({apiVersion: API_VERSION, type: 'version', data: {version: pkg.version}}, null, 2));
+ process.exit(0);
+}
+
export const program = new Command();
+/**
+ * Allowlist of fully-qualified command names that natively support --json.
+ * Subcommands are listed by their full path (parent + leaf), e.g. "theme build".
+ *
+ * Commands NOT in this set will be rejected by the preAction hook below
+ * BEFORE any side effects can run. This protects users from partial state
+ * (e.g. files written, then --json error printed) on commands that don't
+ * yet support structured output.
+ */
+export const JSON_SUPPORTED = new Set([
+ 'component',
+ 'docs',
+ 'discover',
+ 'swizzle',
+ 'template',
+ 'hook',
+ 'theme build',
+ 'gap-report',
+ 'upgrade',
+]);
+
program
.name('xds')
.description('XDS design system CLI — components, themes, and tooling')
@@ -29,31 +65,94 @@ program
.option('--dense', 'Output docs in compressed dense format (token-efficient)')
.option('--lang <locale>', 'Output docs in specified language/format (en, zh, dense)')
.option('--detail <level>', 'Output detail level (full, compact, brief)', 'full')
- .option('--json', 'Output as typed JSON (envelope: { type, data })')
+ .option(
+ '--json',
+ 'Output as typed JSON. Success envelope: { type, data }. Error envelope: { error, suggestions? }.',
+ )
.addHelpCommand('help', 'Show all commands')
.action(() => {
+ // `xds` (no subcommand) — print help, or emit a JSON envelope when --json.
+ if (program.opts().json) {
+ // Emit a JSON help envelope. Treat the bare invocation as supported.
+ process.__xdsJsonHandled = true;
+ console.log(JSON.stringify({
+ apiVersion: API_VERSION,
+ type: 'help',
+ data: {
+ name: 'xds',
+ version: pkg.version,
+ commands: [
+ 'component', 'docs', 'discover', 'swizzle', 'template',
+ 'hook', 'theme', 'gap-report', 'upgrade', 'init',
+ ],
+ jsonSupported: [...JSON_SUPPORTED].sort(),
+ },
+ }, null, 2));
+ return;
+ }
program.help();
});
/**
- * Fallback hook: if --json was requested but the command didn't call
- * jsonOut/jsonError, return a structured "not supported" error.
- * Registered BEFORE the update-check hook so it fires first.
+ * Compute the fully qualified command name, e.g. "theme build" or "gap-report".
+ * @param {import('commander').Command} actionCommand
+ * @returns {string}
*/
-program.hook('postAction', (thisCommand, actionCommand) => {
- if (program.opts().json && !process.__xdsJsonHandled) {
- const parts = [];
- let cmd = actionCommand;
- while (cmd && cmd !== program) {
- parts.unshift(cmd.name());
- cmd = cmd.parent;
- }
- const fullName = parts.join(' ');
- console.log(JSON.stringify({
- error: `JSON output is not supported for the '${fullName}' command`,
- }, null, 2));
- process.exit(1);
+function fullCommandName(actionCommand) {
+ const parts = [];
+ let cmd = actionCommand;
+ while (cmd && cmd !== program) {
+ parts.unshift(cmd.name());
+ cmd = cmd.parent;
}
+ return parts.join(' ');
+}
+
+/**
+ * Pre-action hook: gate --json BEFORE any command body runs.
+ *
+ * If --json is set on a command that is not on the JSON_SUPPORTED allowlist,
+ * emit a structured error envelope and exit 1 — without running the command's
+ * action (so no filesystem mutations, no clack prompts, no spawned processes).
+ *
+ * This is the single source of truth for "command does not support --json".
+ * Individual commands should NOT re-check this; they may assume that if their
+ * action runs with --json, they are responsible for emitting an envelope on
+ * every code path.
+ */
+program.hook('preAction', (thisCommand, actionCommand) => {
+ if (!program.opts().json) return;
+ // Engage global JSON mode so humanLog()/humanWarn() across commands become
+ // no-ops — stdout now carries only the JSON envelope.
+ setJsonMode(true);
+ // The root program's own action (no subcommand) is handled directly in
+ // its action handler — let it through. fullCommandName is '' there.
+ if (actionCommand === program) return;
+ const fullName = fullCommandName(actionCommand);
+ if (JSON_SUPPORTED.has(fullName)) return;
+ process.__xdsJsonHandled = true;
+ console.log(JSON.stringify({
+ apiVersion: API_VERSION,
+ error: `JSON output is not supported for the '${fullName}' command`,
+ }, null, 2));
+ process.exit(1);
+});
+
+/**
+ * Belt-and-suspenders postAction: if a "supported" command somehow forgot
+ * to emit a JSON envelope on a code path, surface that as a structured error
+ * rather than silent stdout corruption. This should never fire in practice;
+ * if it does, it's a bug in the command implementation.
+ */
+program.hook('postAction', (thisCommand, actionCommand) => {
+ if (!program.opts().json) return;
+ if (process.__xdsJsonHandled) return;
+ const fullName = fullCommandName(actionCommand);
+ console.log(JSON.stringify({
+ apiVersion: API_VERSION,
+ error: `Internal: '${fullName}' completed without emitting a JSON envelope`,
+ }, null, 2));
+ process.exit(1);
});
/**
diff --git a/packages/cli/src/lib/json-contract.test.mjs b/packages/cli/src/lib/json-contract.test.mjs
new file mode 100644
index 0000000000..5a4ed89691
--- /dev/null
+++ b/packages/cli/src/lib/json-contract.test.mjs
@@ -0,0 +1,146 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Unit + subprocess tests for the "JSON is always JSON" contract.
+ *
+ * Guarantees under test:
+ * 1. Every JSON envelope carries apiVersion (success and error).
+ * 2. humanLog/humanWarn are suppressed in JSON mode (stdout discipline).
+ * 3. jsonOut supports optional meta as a sibling of data.
+ * 4. An uncaught throw in --json mode becomes a JSON error envelope
+ * (the bin error boundary), never a raw stack trace.
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {spawnSync} from 'node:child_process';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {
+ API_VERSION,
+ jsonOut,
+ jsonError,
+ toErrorEnvelope,
+ setJsonMode,
+ isJsonMode,
+ humanLog,
+ humanWarn,
+} from './json.mjs';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const CLI = path.resolve(__dirname, '..', '..', 'bin', 'xds.mjs');
+
+function runCli(args) {
+ return spawnSync(process.execPath, [CLI, ...args], {
+ encoding: 'utf8',
+ timeout: 20_000,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: {...process.env, FORCE_COLOR: '0', CI: ''},
+ });
+}
+
+describe('json envelope shape', () => {
+ let logs;
+ beforeEach(() => {
+ logs = [];
+ vi.spyOn(console, 'log').mockImplementation((...a) => logs.push(a.join(' ')));
+ setJsonMode(false);
+ });
+ afterEach(() => {
+ vi.restoreAllMocks();
+ setJsonMode(false);
+ });
+
+ it('jsonOut stamps apiVersion + type + data', () => {
+ jsonOut('docs.list', [{name: 'Button'}]);
+ const env = JSON.parse(logs[0]);
+ expect(env.apiVersion).toBe(API_VERSION);
+ expect(env.type).toBe('docs.list');
+ expect(env.data).toEqual([{name: 'Button'}]);
+ expect('meta' in env).toBe(false);
+ });
+
+ it('jsonOut attaches optional meta as a sibling of data', () => {
+ jsonOut('discover.list', [], {configured: false});
+ const env = JSON.parse(logs[0]);
+ expect(env.meta).toEqual({configured: false});
+ expect(env.data).toEqual([]);
+ });
+
+ it('toErrorEnvelope produces { apiVersion, error } from string or Error', () => {
+ expect(toErrorEnvelope('boom')).toEqual({apiVersion: API_VERSION, error: 'boom'});
+ expect(toErrorEnvelope(new Error('kaboom'))).toEqual({
+ apiVersion: API_VERSION,
+ error: 'kaboom',
+ });
+ });
+
+ it('toErrorEnvelope includes suggestions when present', () => {
+ const env = toErrorEnvelope('x', [{name: 'Button', reason: 'close match'}]);
+ expect(env.suggestions).toEqual([{name: 'Button', reason: 'close match'}]);
+ });
+});
+
+describe('stdout discipline (humanLog / humanWarn)', () => {
+ let logs, errs;
+ beforeEach(() => {
+ logs = [];
+ errs = [];
+ vi.spyOn(console, 'log').mockImplementation((...a) => logs.push(a.join(' ')));
+ vi.spyOn(console, 'error').mockImplementation((...a) => errs.push(a.join(' ')));
+ });
+ afterEach(() => {
+ vi.restoreAllMocks();
+ setJsonMode(false);
+ });
+
+ it('humanLog prints when NOT in json mode', () => {
+ setJsonMode(false);
+ expect(isJsonMode()).toBe(false);
+ humanLog('hello');
+ expect(logs).toEqual(['hello']);
+ });
+
+ it('humanLog is a no-op in json mode', () => {
+ setJsonMode(true);
+ expect(isJsonMode()).toBe(true);
+ humanLog('should not appear');
+ expect(logs).toEqual([]);
+ });
+
+ it('humanWarn is a no-op in json mode', () => {
+ setJsonMode(true);
+ humanWarn('warning');
+ expect(errs).toEqual([]);
+ });
+});
+
+describe('contract: every --json emission is valid JSON with apiVersion', () => {
+ it('xds --version --json', () => {
+ const r = runCli(['--version', '--json']);
+ const env = JSON.parse(r.stdout);
+ expect(env.apiVersion).toBe(API_VERSION);
+ expect(env.type).toBe('version');
+ });
+
+ it('xds --json (bare) help envelope', () => {
+ const r = runCli(['--json']);
+ const env = JSON.parse(r.stdout);
+ expect(env.apiVersion).toBe(API_VERSION);
+ expect(env.type).toBe('help');
+ });
+
+ it('unsupported command error envelope carries apiVersion', () => {
+ const r = runCli(['init', '--json', '--all']);
+ const env = JSON.parse(r.stdout);
+ expect(env.apiVersion).toBe(API_VERSION);
+ expect(env.error).toMatch(/init/);
+ });
+
+ it('supported command (discover) emits clean JSON, no human chatter leak', () => {
+ const r = runCli(['discover', '--json']);
+ // Whole stdout must parse — nothing printed before/after the envelope.
+ const env = JSON.parse(r.stdout);
+ expect(env.apiVersion).toBe(API_VERSION);
+ expect(env.type).toBe('discover.list');
+ });
+});
diff --git a/packages/cli/src/lib/json.mjs b/packages/cli/src/lib/json.mjs
index f64e07ecae..1c1d5ed7fd 100644
--- a/packages/cli/src/lib/json.mjs
+++ b/packages/cli/src/lib/json.mjs
@@ -1,16 +1,81 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file Internal JSON output helpers for CLI commands.
+ * @file Internal JSON output helpers and the CLI's "JSON is always JSON"
+ * contract.
*
- * Commands call jsonOut(type, data) for success and jsonError(msg) for errors.
- * Both set process.__xdsJsonHandled so the global fallback hook knows
- * the command handled --json itself.
+ * The contract has four guarantees, enforced here and in index.mjs:
*
- * Consumer-facing utilities (parseResponse, isError, assertResponse)
+ * 1. EVERY emission in --json mode is a single valid JSON envelope.
+ * Success: { apiVersion, type, data } Error: { apiVersion, error, suggestions? }
+ * 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 /
+ * setJsonMode) so it can never corrupt stdout.
+ * 4. Uncaught throws in --json mode become a JSON error envelope, never a
+ * raw stack trace (see toErrorEnvelope / the bin error boundary).
+ *
+ * Commands call jsonOut(type, data) for success and jsonError(msg) for
+ * errors. Consumer-facing utilities (parseResponse, isError, assertResponse)
* live in parse.mjs and are exported via @xds/cli/json.
*/
+/**
+ * Version of the JSON envelope contract. Bump on breaking shape changes so
+ * consumers can negotiate. Exposed on every envelope as `apiVersion`.
+ */
+export const API_VERSION = 1;
+
+/**
+ * Process-wide flag: are we emitting machine-readable JSON? Set once, early,
+ * from the parsed --json option (see setJsonMode in index.mjs). Read by
+ * humanLog() so human output is suppressed without every call site having to
+ * thread a `json` boolean.
+ *
+ * @type {boolean}
+ */
+let _jsonMode = false;
+
+/**
+ * Enable/disable JSON mode globally. Called once from index.mjs as soon as
+ * the root options are known (preAction), before any command body runs.
+ * @param {boolean} on
+ */
+export function setJsonMode(on) {
+ _jsonMode = Boolean(on);
+}
+
+/** @returns {boolean} */
+export function isJsonMode() {
+ return _jsonMode;
+}
+
+/**
+ * Human-facing output that is automatically suppressed in --json mode.
+ *
+ * This is the stdout-discipline primitive: instead of scattering
+ * `if (!json) console.log(...)` across commands (easy to forget, and one
+ * miss corrupts the JSON), route all human chatter through humanLog. In JSON
+ * mode it is a no-op, guaranteeing stdout carries only the JSON envelope.
+ *
+ * @param {...unknown} args
+ */
+export function humanLog(...args) {
+ if (_jsonMode) return;
+ console.log(...args);
+}
+
+/**
+ * Human-facing stderr (warnings, hints). Also suppressed in JSON mode so a
+ * stray warning can't interleave with piped output. Use jsonError for real
+ * errors that must reach a JSON consumer.
+ * @param {...unknown} args
+ */
+export function humanWarn(...args) {
+ if (_jsonMode) return;
+ console.error(...args);
+}
+
/**
* Output a typed JSON response envelope and mark as handled.
* Type safety enforced via declaration in types/base.d.ts —
@@ -18,11 +83,33 @@
* @template {import('../types/base').CLIResponseType} T
* @param {T} type
* @param {import('../types/base').CLIResponseDataMap[T]} data
+ * @param {Record<string, unknown>} [meta] - Optional sidecar metadata (e.g.
+ * {configured: false}). Emitted as a sibling of data, never merged into it.
* @returns {void}
*/
-export function jsonOut(type, data) {
+export function jsonOut(type, data, meta) {
process.__xdsJsonHandled = true;
- console.log(JSON.stringify({type, data}, null, 2));
+ /** @type {any} */
+ const envelope = {apiVersion: API_VERSION, type, data};
+ if (meta !== undefined) envelope.meta = meta;
+ console.log(JSON.stringify(envelope, null, 2));
+}
+
+/**
+ * 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.
+ * @param {unknown} err
+ * @param {Array<{name: string, reason: string}>} [suggestions]
+ * @returns {{apiVersion: number, error: string, suggestions?: Array<{name: string, reason: string}>}}
+ */
+export function toErrorEnvelope(err, suggestions) {
+ const message =
+ err instanceof Error ? err.message : typeof err === 'string' ? err : String(err);
+ /** @type {any} */
+ const env = {apiVersion: API_VERSION, error: message};
+ if (suggestions?.length) env.suggestions = suggestions;
+ return env;
}
/**
@@ -32,9 +119,7 @@ export function jsonOut(type, data) {
*/
export function jsonError(message, suggestions) {
process.__xdsJsonHandled = true;
- /** @type {import('../types/base').CLIError} */
- const err = {error: message};
- if (suggestions?.length) err.suggestions = suggestions;
+ const err = toErrorEnvelope(message, suggestions);
console.log(JSON.stringify(err, null, 2));
process.exit(1);
}