Skip to content

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

TypeScript

feat(cli): add type-safe --json output to all CLI commands (#1157)

Joey50ed56fa50d7
diff --git a/.github/scripts/cli-json-smoke-test.mjs b/.github/scripts/cli-json-smoke-test.mjs
new file mode 100644
index 0000000000..95dbaba0ec
--- /dev/null
+++ b/.github/scripts/cli-json-smoke-test.mjs
@@ -0,0 +1,226 @@
+#!/usr/bin/env node
+/**
+ * CLI JSON smoke test — validates --json output for every supported command.
+ *
+ * Auto-discovers components and doc topics (same as cli-smoke-test.mjs)
+ * then runs every command with --json and validates:
+ * 1. Output is valid JSON
+ * 2. Success responses have `type` (string) and `data` fields
+ * 3. Error responses have `error` (string) field
+ * 4. `type` values follow the dot-separated naming pattern
+ * 5. Envelope shape is consistent across all commands
+ *
+ * No hardcoded type allowlist — validates shape, not specific strings.
+ * The .d.ts type declarations are the source of truth for valid types.
+ *
+ * Usage: node .github/scripts/cli-json-smoke-test.mjs
+ */
+
+import {spawnSync} from 'node:child_process';
+import {fileURLToPath} from 'node:url';
+import * as path from 'node:path';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const ROOT = path.resolve(__dirname, '../..');
+const CLI = path.join(ROOT, 'packages/cli/bin/xds.mjs');
+
+let passed = 0;
+let failed = 0;
+const failures = [];
+const seenTypes = new Set();
+
+function run(args) {
+ const result = spawnSync(process.execPath, [CLI, ...args], {
+ cwd: ROOT,
+ encoding: 'utf8',
+ timeout: 30_000,
+ });
+ return {
+ stdout: result.stdout ?? '',
+ stderr: result.stderr ?? '',
+ status: result.status ?? 1,
+ };
+}
+
+function runJson(args) {
+ return run(['--json', ...args]);
+}
+
+function checkJson(label, args, {expectError = false, expectType = null} = {}) {
+ const {stdout, status} = runJson(args);
+
+ let parsed;
+ try {
+ parsed = JSON.parse(stdout);
+ } catch {
+ console.log(` FAIL ${label} (invalid JSON)`);
+ if (stdout.trim()) console.log(` ${stdout.trim().split('\n')[0].slice(0, 80)}`);
+ failures.push({label, reason: 'invalid JSON'});
+ failed++;
+ return;
+ }
+
+ if (expectError) {
+ if (!parsed.error) {
+ console.log(` FAIL ${label} (expected error, got type="${parsed.type}")`);
+ failures.push({label, reason: 'expected error response'});
+ failed++;
+ return;
+ }
+ if (typeof parsed.error !== 'string') {
+ console.log(` FAIL ${label} (error field is not a string)`);
+ failures.push({label, reason: 'error field not a string'});
+ failed++;
+ return;
+ }
+ console.log(` ok ${label} (error: "${parsed.error.slice(0, 60)}")`);
+ passed++;
+ return;
+ }
+
+ // Error responses
+ if (parsed.error) {
+ if (typeof parsed.error !== 'string') {
+ console.log(` FAIL ${label} (error field is not a string)`);
+ failures.push({label, reason: 'error field not a string'});
+ failed++;
+ return;
+ }
+ if (status !== 1) {
+ console.log(` FAIL ${label} (error without exit code 1)`);
+ failures.push({label, reason: 'error without exit code 1'});
+ failed++;
+ return;
+ }
+ console.log(` ok ${label} (error: "${parsed.error.slice(0, 60)}")`);
+ passed++;
+ return;
+ }
+
+ // Success responses must have type + data
+ if (typeof parsed.type !== 'string') {
+ console.log(` FAIL ${label} (missing or non-string type field)`);
+ failures.push({label, reason: 'missing type field'});
+ failed++;
+ return;
+ }
+
+ if (!('data' in parsed)) {
+ console.log(` FAIL ${label} (missing data field)`);
+ failures.push({label, reason: 'missing data field'});
+ failed++;
+ return;
+ }
+
+ // Type discriminators must follow the dot-separated pattern
+ if (!/^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)*$/.test(parsed.type)) {
+ console.log(` FAIL ${label} (type "${parsed.type}" doesn't match naming pattern)`);
+ failures.push({label, reason: `invalid type format "${parsed.type}"`});
+ failed++;
+ return;
+ }
+
+ // Envelope should only have type + data keys (no extra fields)
+ const extraKeys = Object.keys(parsed).filter(k => k !== 'type' && k !== 'data');
+ if (extraKeys.length > 0) {
+ console.log(` FAIL ${label} (extra fields in envelope: ${extraKeys.join(', ')})`);
+ failures.push({label, reason: `extra envelope fields: ${extraKeys.join(', ')}`});
+ failed++;
+ return;
+ }
+
+ if (expectType && parsed.type !== expectType) {
+ console.log(` FAIL ${label} (expected type "${expectType}", got "${parsed.type}")`);
+ failures.push({label, reason: `expected type "${expectType}"`});
+ failed++;
+ return;
+ }
+
+ seenTypes.add(parsed.type);
+ console.log(` ok ${label} (type: ${parsed.type})`);
+ passed++;
+}
+
+// ---------------------------------------------------------------------------
+// 1. Auto-discover components from xds component --list (text mode)
+// ---------------------------------------------------------------------------
+const listResult = run(['component', '--list']);
+const componentNames = listResult.stdout
+ .split('\n')
+ .filter(line => /^\s+[A-Z]/.test(line))
+ .map(line => line.trim());
+
+console.log(`\ndiscovered ${componentNames.length} components`);
+
+// Pick a sample component for detail tests
+const sampleComponent = componentNames.includes('Button') ? 'Button' : componentNames[0];
+
+// ---------------------------------------------------------------------------
+// 2. Auto-discover doc topics from xds docs (text mode)
+// ---------------------------------------------------------------------------
+const docsResult = run(['docs']);
+const docTopics = docsResult.stdout
+ .split('\n')
+ .filter(line => /^\s{2}\w+\s{2,}/.test(line))
+ .map(line => line.trim().split(/\s{2,}/)[0]);
+
+console.log(`discovered ${docTopics.length} doc topics: ${docTopics.join(', ')}`);
+
+// ---------------------------------------------------------------------------
+// 3. Run all checks
+// ---------------------------------------------------------------------------
+
+// ── Component ────────────────────────────────────────────────────────
+console.log('\ncomponent --json');
+checkJson('component --list', ['component', '--list'], {expectType: 'component.list'});
+
+// Pick a sample category from the JSON output
+const catResult = runJson(['component', '--list']);
+try {
+ const catData = JSON.parse(catResult.stdout);
+ const firstCategory = Object.keys(catData.data)[0];
+ if (firstCategory) {
+ checkJson(`component --category ${firstCategory}`, ['component', '--category', firstCategory], {expectType: 'component.list'});
+ }
+} catch { /* skip if parse fails */ }
+
+if (sampleComponent) {
+ checkJson(`component ${sampleComponent}`, ['component', sampleComponent], {expectType: 'component.detail'});
+ checkJson(`component ${sampleComponent} --props`, ['component', sampleComponent, '--props'], {expectType: 'component.detail.props'});
+ checkJson(`component ${sampleComponent} --source`, ['component', sampleComponent, '--source'], {expectType: 'component.detail.source'});
+}
+checkJson('component (not found)', ['component', 'NotARealComponentName99'], {expectError: true});
+
+// ── Docs ─────────────────────────────────────────────────────────────
+console.log('\ndocs --json');
+checkJson('docs (list)', ['docs'], {expectType: 'docs.list'});
+if (docTopics.length > 0) {
+ checkJson(`docs ${docTopics[0]}`, ['docs', docTopics[0]], {expectType: 'docs.detail'});
+}
+checkJson('docs (not found)', ['docs', 'nonexistent_topic_xyz'], {expectError: true});
+
+// ── Template ─────────────────────────────────────────────────────────
+console.log('\ntemplate --json');
+checkJson('template --list', ['template', '--list'], {expectType: 'template.list'});
+checkJson('template (not found)', ['template', 'nonexistent_template_xyz'], {expectError: true});
+
+// ── Swizzle ──────────────────────────────────────────────────────────
+console.log('\nswizzle --json');
+checkJson('swizzle --list', ['swizzle', '--list'], {expectType: 'swizzle.list'});
+checkJson('swizzle (not found)', ['swizzle', 'NonexistentComponent99'], {expectError: true});
+
+// ── Gap report ───────────────────────────────────────────────────────
+console.log('\ngap-report --json');
+checkJson('gap-report --list-categories', ['gap-report', '--list-categories'], {expectType: 'gap-report.categories'});
+
+// ── Summary ──────────────────────────────────────────────────────────
+console.log(`\n${passed + failed} checks: ${passed} passed, ${failed} failed`);
+console.log(`types seen: ${[...seenTypes].sort().join(', ')}`);
+
+if (failed > 0) {
+ console.log('\nFailed:');
+ for (const f of failures) {
+ console.log(` - ${f.label}: ${f.reason}`);
+ }
+ process.exit(1);
+}
diff --git a/.github/workflows/cli-smoke-test.yml b/.github/workflows/cli-smoke-test.yml
index 8e44365f26..9f31331101 100644
--- a/.github/workflows/cli-smoke-test.yml
+++ b/.github/workflows/cli-smoke-test.yml
@@ -29,3 +29,9 @@ jobs:
- name: CLI smoke test
run: node .github/scripts/cli-smoke-test.mjs
+
+ - name: Typecheck JSON API types
+ run: cd packages/cli && yarn typecheck:json-api
+
+ - name: CLI --json smoke test
+ run: node .github/scripts/cli-json-smoke-test.mjs
diff --git a/packages/cli/README.md b/packages/cli/README.md
new file mode 100644
index 0000000000..e6c1752088
--- /dev/null
+++ b/packages/cli/README.md
@@ -0,0 +1,258 @@
+# @xds/cli
+
+XDS design system CLI -- components, themes, and tooling.
+
+```bash
+npx xds --help
+npx xds component Button
+npx xds docs tokens
+npx xds template --list
+```
+
+## JSON API
+
+Every command supports `--json` for machine-readable output. Responses are typed envelopes:
+
+```json
+{"type": "component.detail", "data": {"name": "Button", ...}}
+```
+
+Errors:
+
+```json
+{
+ "error": "No component named \"Buttn\"",
+ "suggestions": [{"name": "Button", "reason": "similar name"}]
+}
+```
+
+### Consumer utilities
+
+```typescript
+import {parseResponse, isError, assertResponse} from '@xds/cli/json';
+import type {ComponentDetailResponse, CLIResult} from '@xds/cli/json';
+
+const result = parseResponse(stdout);
+if (isError(result)) {
+ console.error(result.error);
+} else {
+ switch (result.type) {
+ case 'component.detail':
+ result.data.name; // TypeScript: ComponentDoc
+ break;
+ }
+}
+
+// Or assert directly (throws on error/mismatch):
+const detail = assertResponse(stdout, 'component.detail');
+detail.data.name; // already narrowed
+```
+
+### Type discriminators
+
+Every response has a `type` string that uniquely identifies it:
+
+| Command | Type | Response |
+| ----------------------------------------- | ------------------------- | ------------------------------- |
+| `xds --json component [--list]` | `component.list` | `ComponentListResponse` |
+| `xds --json component --detail brief` | `component.brief` | `ComponentBriefResponse` |
+| `xds --json component <name>` | `component.detail` | `ComponentDetailResponse` |
+| `xds --json component <name> --props` | `component.detail.props` | `ComponentDetailPropsResponse` |
+| `xds --json component <name> --source` | `component.detail.source` | `ComponentDetailSourceResponse` |
+| `xds --json discover` | `discover.list` | `DiscoverListResponse` |
+| `xds --json discover @scope/name` | `discover.detail` | `DiscoverDetailResponse` |
+| `xds --json discover @scope/name/Comp` | `discover.detail.doc` | `DiscoverDetailDocResponse` |
+| `xds --json discover <search>` | `discover.search` | `DiscoverSearchResponse` |
+| `xds --json docs` | `docs.list` | `DocsListResponse` |
+| `xds --json docs <topic>` | `docs.detail` | `DocsDetailResponse` |
+| `xds --json docs <topic> <section>` | `docs.detail.section` | `DocsDetailSectionResponse` |
+| `xds --json template [--list]` | `template.list` | `TemplateListResponse` |
+| `xds --json template <name> [path]` | `template.copy` | `TemplateCopyResponse` |
+| `xds --json swizzle [--list]` | `swizzle.list` | `SwizzleListResponse` |
+| `xds --json swizzle <component>` | `swizzle.copy` | `SwizzleCopyResponse` |
+| `xds --json theme build <file>` | `theme.build` | `ThemeBuildResponse` |
+| `xds --json upgrade --list` | `upgrade.list` | `UpgradeListResponse` |
+| `xds --json upgrade [--apply]` | `upgrade.run` | `UpgradeRunResponse` |
+| `xds --json gap-report --list-categories` | `gap-report.categories` | `GapReportCategoriesResponse` |
+| `xds --json gap-report --component X ...` | `gap-report.file` | `GapReportFileResponse` |
+| legacy README.md fallback | `markdown` | `CLIMarkdownResponse` |
+| any error | -- | `CLIError` |
+| unsupported command | -- | `CLIUnsupportedError` |
+
+---
+
+## Adding a new command
+
+### 1. Create the command
+
+Add a file in `src/commands/` and register it in `src/index.mjs`:
+
+```javascript
+// src/commands/my-command.mjs
+import {jsonOut, jsonError} from '../lib/json.mjs';
+
+export function registerMyCommand(program) {
+ program
+ .command('my-command [name]')
+ .description('Does something')
+ .action(async (name, options) => {
+ const json = program.opts().json || false;
+
+ // ... your logic ...
+
+ if (json) return jsonOut('my-command.list', data);
+ console.log(textOutput);
+ });
+}
+```
+
+### 2. Define response types
+
+Create `src/types/my-command.d.ts`:
+
+```typescript
+/**
+ * My-command JSON responses.
+ *
+ * Invocation -> type discriminator
+ * ------------------------------------------------------------------
+ * xds --json my-command -> my-command.list
+ * xds --json my-command <name> -> my-command.detail
+ * (not found) -> CLIError
+ */
+
+/** xds --json my-command */
+export interface MyCommandListResponse {
+ type: 'my-command.list';
+ data: MyCommandListEntry[];
+}
+
+export interface MyCommandListEntry {
+ name: string;
+ description: string;
+}
+
+/** xds --json my-command <name> */
+export interface MyCommandDetailResponse {
+ type: 'my-command.detail';
+ data: {name: string; content: string};
+}
+```
+
+### 3. Wire it up
+
+Add to `src/types/index.d.ts`:
+
+```typescript
+export * from './my-command';
+```
+
+Add to `CLIAnyResponse` in `src/types/base.d.ts`:
+
+```typescript
+import type { MyCommandListResponse, MyCommandDetailResponse } from './my-command';
+
+export type CLIAnyResponse =
+ | ...existing types...
+ | MyCommandListResponse
+ | MyCommandDetailResponse;
+```
+
+### 4. That's it
+
+If you skip steps 2-3, the command still works -- the global fallback hook returns a clean `CLIUnsupportedError` when someone passes `--json`. No crashes, no broken output.
+
+---
+
+## Naming conventions
+
+### Response types: `{Command}{Mode}{SubMode?}Response`
+
+| Part | Rule | Examples |
+| ------- | ----------------------- | --------------------------------------------------------------------------------- |
+| Command | PascalCase command name | `Component`, `Discover`, `ThemeBuild` |
+| Mode | What the response IS | `List`, `Brief`, `Detail`, `Search`, `Copy`, `Build`, `Run`, `Categories`, `File` |
+| SubMode | Narrower view of Mode | `Props`, `Source`, `Doc`, `Section` |
+| Suffix | Always `Response` | |
+
+### Entry types: `{Command}{What}Entry`
+
+Sub-objects in arrays. No `Response` suffix.
+
+### Type discriminators: dot-separated lowercase
+
+```
+{command}.{mode} -> component.list
+{command}.{mode}.{submode} -> component.detail.props
+```
+
+### How flags compose
+
+`--json` is an output format, not a mode. All other flags still work:
+
+- `--json + --category X` filters the same response type (no new type needed)
+- `--json + --lang zh` applies translation before dumping
+- `--json + --props` narrows to `component.detail.props` (sub-mode)
+- `--json + --source` narrows to `component.detail.source` (sub-mode)
+
+---
+
+## Architecture
+
+```
+src/
+ index.mjs # Commander setup, --json flag, fallback hook
+ lib/
+ json.mjs # jsonOut(type, data), jsonError(msg) -- internal
+ parse.mjs # parseResponse, isError, assertResponse -- consumer
+ types/
+ base.d.ts # CLIError, CLIResult<T>, CLIAnyResponse, CLIResponseType
+ component.d.ts # ComponentListResponse, ComponentDetailResponse, ...
+ discover.d.ts # DiscoverListResponse, ...
+ docs.d.ts # DocsListResponse, ...
+ template.d.ts # TemplateListResponse, TemplateCopyResponse
+ swizzle.d.ts # SwizzleListResponse, SwizzleCopyResponse
+ theme.d.ts # ThemeBuildResponse
+ upgrade.d.ts # UpgradeListResponse, UpgradeRunResponse
+ gap-report.d.ts # GapReportCategoriesResponse, GapReportFileResponse
+ index.d.ts # barrel re-export
+ commands/
+ component/index.mjs # uses jsonOut('component.list', ...) etc.
+ discover.mjs
+ docs.mjs
+ template.mjs
+ swizzle.mjs
+ build-theme.mjs
+ upgrade.mjs
+ gap-report.mjs
+ init.mjs # no --json (interactive only, fallback hook handles it)
+```
+
+### How the fallback hook works
+
+1. Command runs normally
+2. If it called `jsonOut()` or `jsonError()`, `process.__xdsJsonHandled` is `true` -> done
+3. If not, the `postAction` hook fires and outputs `CLIUnsupportedError`
+4. New commands that don't know about `--json` automatically get a clean error
+
+### CI enforcement
+
+- `tsconfig.json-api.json` typechecks `json.mjs` and `parse.mjs` against the `.d.ts` declarations
+- `.github/scripts/cli-json-smoke-test.mjs` validates every `--json` command outputs valid JSON with correct envelope shape
+- Both run in the `cli-smoke-test.yml` workflow on every PR
+
+### Suppressing stdout for --json
+
+When `--json` is active, human-readable output must not contaminate stdout:
+
+```javascript
+// Simple commands: guard console.log
+if (!json) console.log(`✓ Done`);
+
+// Clack-based commands: skip Clack calls
+if (!json) p.intro('Welcome');
+if (!json) p.log.step('Running...');
+
+// Side-effect commands: still run the work, just suppress output
+// and collect results into a receipt object
+```
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 5c5b37a3ec..bbea541ca8 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -6,6 +6,13 @@
"bin": {
"xds": "./bin/xds.mjs"
},
+ "exports": {
+ ".": "./bin/xds.mjs",
+ "./json": {
+ "types": "./src/types/index.d.ts",
+ "import": "./src/lib/parse.mjs"
+ }
+ },
"files": [
"bin",
"src",
@@ -14,7 +21,8 @@
],
"scripts": {
"xds": "node bin/xds.mjs",
- "typecheck:template-docs": "tsc --project tsconfig.template-docs.json"
+ "typecheck:template-docs": "tsc --project tsconfig.template-docs.json",
+ "typecheck:json-api": "tsc --project tsconfig.json-api.json"
},
"dependencies": {
"@clack/prompts": "^0.9.1",
diff --git a/packages/cli/src/commands/build-theme.mjs b/packages/cli/src/commands/build-theme.mjs
index 1a1c714cc9..16381dcc71 100644
--- a/packages/cli/src/commands/build-theme.mjs
+++ b/packages/cli/src/commands/build-theme.mjs
@@ -15,6 +15,7 @@ import * as path from 'node:path';
import {createRequire} from 'node:module';
import {pathToFileURL, fileURLToPath} from 'node:url';
import {getRunPrefix} from '../utils/package-manager.mjs';
+import {jsonOut, jsonError} 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.
@@ -741,32 +742,38 @@ export function registerTheme(program) {
.option('--no-prose', 'Skip prose mappings (h1, p, code, hr, etc.)')
.action(async (file, options) => {
const filePath = path.resolve(process.cwd(), file);
+ const json = program.opts().json || false;
if (!fs.existsSync(filePath)) {
+ if (json) return jsonError('File not found: ' + filePath);
console.error(`Error: File not found: ${filePath}`);
process.exit(1);
}
- console.log(`\nBuilding theme from ${path.relative(process.cwd(), filePath)}...`);
+ if (!json) console.log(`\nBuilding theme from ${path.relative(process.cwd(), filePath)}...`);
// Extract theme definition
let themeDef;
try {
themeDef = await extractThemeDefinition(filePath);
} catch (e) {
+ if (json) return jsonError(e.message);
console.error(`Error: ${e.message}`);
process.exit(1);
}
if (!themeDef.name) {
+ if (json) return jsonError('Theme must have a name property.');
console.error('Error: Theme must have a name property.');
process.exit(1);
}
// Validate component overrides
const warnings = validateComponentOverrides(themeDef);
+ const warningMessages = [];
for (const w of warnings) {
- console.warn(` ⚠ ${w}`);
+ warningMessages.push(w);
+ if (!json) console.warn(` ⚠ ${w}`);
}
// Generate CSS using the shared generateThemeRules from core.
@@ -791,7 +798,7 @@ export function registerTheme(program) {
if (_generateThemeRulesSplit) {
const {component, prose} = _generateThemeRulesSplit(resolvedTheme);
if (component.length === 0 && prose.length === 0) {
- console.log('No overrides found — nothing to build.');
+ if (!json) console.log('No overrides found — nothing to build.');
return;
}
const cssParts = [];
@@ -811,7 +818,7 @@ export function registerTheme(program) {
} else {
const rules = _generateThemeRules(resolvedTheme);
if (rules.length === 0) {
- console.log('No overrides found — nothing to build.');
+ if (!json) console.log('No overrides found — nothing to build.');
return;
}
const inner = rules.join('\n\n');
@@ -829,7 +836,7 @@ export function registerTheme(program) {
const mainCss = generateCSS(themeDef);
if (mainCss) scopeBlocks.push(mainCss);
if (scopeBlocks.length === 0) {
- console.log('No overrides found — nothing to build.');
+ if (!json) console.log('No overrides found — nothing to build.');
return;
}
const joined = scopeBlocks.join('\n\n');
@@ -852,9 +859,11 @@ export function registerTheme(program) {
const componentCount = themeDef.components ? Object.keys(themeDef.components).length : 0;
const size = (Buffer.byteLength(css) / 1024).toFixed(1);
- console.log(`\n✓ ${path.relative(process.cwd(), outPath)}`);
- console.log(` ${tokenCount} token overrides, ${componentCount} component overrides`);
- console.log(` ${size} KB`);
+ if (!json) {
+ console.log(`\n✓ ${path.relative(process.cwd(), outPath)}`);
+ console.log(` ${tokenCount} token overrides, ${componentCount} component overrides`);
+ console.log(` ${size} KB`);
+ }
// Always generate JS module + types alongside CSS
const outDir = path.dirname(outPath);
@@ -869,17 +878,36 @@ export function registerTheme(program) {
fs.writeFileSync(jsPath, generateBuiltModule(themeDef, iconImportPath));
fs.writeFileSync(dtsPath, generateBuiltTypes(themeDef));
- console.log(`✓ ${path.relative(process.cwd(), jsPath)}`);
- console.log(`✓ ${path.relative(process.cwd(), dtsPath)}`);
+ if (!json) {
+ console.log(`✓ ${path.relative(process.cwd(), jsPath)}`);
+ console.log(`✓ ${path.relative(process.cwd(), dtsPath)}`);
+ }
// Generate type augmentation .d.ts if theme has custom prop values
const augmentationSource = resolvedTheme || themeDef;
const variantDecl = await generateVariantDeclarationsAsync(augmentationSource);
+ let variantDtsPath;
if (variantDecl) {
- const variantDtsPath = path.join(outDir, `${baseName}.variants.d.ts`);
+ variantDtsPath = path.join(outDir, `${baseName}.variants.d.ts`);
fs.writeFileSync(variantDtsPath, variantDecl);
const augCount = (variantDecl.match(/': true;/g) || []).length;
- console.log(`✓ ${path.relative(process.cwd(), variantDtsPath)} (${augCount} type augmentations)`);
+ if (!json) console.log(`✓ ${path.relative(process.cwd(), variantDtsPath)} (${augCount} type augmentations)`);
+ }
+
+ if (json) {
+ return jsonOut('theme.build', {
+ name: themeDef.name,
+ tokenCount,
+ componentCount,
+ sizeKB: parseFloat(size),
+ outputs: {
+ css: path.relative(process.cwd(), outPath),
+ js: path.relative(process.cwd(), jsPath),
+ dts: path.relative(process.cwd(), dtsPath),
+ ...(variantDecl ? {variantsDts: path.relative(process.cwd(), variantDtsPath)} : {}),
+ },
+ warnings: warningMessages,
+ });
}
// Print install instructions
diff --git a/packages/cli/src/commands/component/index.mjs b/packages/cli/src/commands/component/index.mjs
index 814b319827..c7b98b3dfe 100644
--- a/packages/cli/src/commands/component/index.mjs
+++ b/packages/cli/src/commands/component/index.mjs
@@ -33,6 +33,7 @@ import {
import {findClosestComponents, searchComponents} from '../../lib/string-utils.mjs';
import {resolveTheme} from '../../lib/resolve-theme.mjs';
import {getRunPrefix} from '../../utils/package-manager.mjs';
+import {jsonOut, jsonError} from '../../lib/json.mjs';
export function registerComponent(program) {
program
@@ -49,15 +50,18 @@ export function registerComponent(program) {
const dense = program.opts().dense || false;
const lang = program.opts().lang || null;
const detail = program.opts().detail || 'full';
+ const json = program.opts().json || false;
const validDetails = ['full', 'compact', 'brief'];
if (!validDetails.includes(detail)) {
+ if (json) return jsonError(`Invalid --detail value "${detail}". Valid levels: ${validDetails.join(', ')}`);
console.error(`Error: Invalid --detail value "${detail}".`);
console.error(`Valid levels: ${validDetails.join(', ')}`);
process.exit(1);
}
if (!coreDir) {
+ if (json) return jsonError('Could not find @xds/core package');
console.error(
'Error: Could not find @xds/core package.\n' +
'Make sure you are inside the XDS monorepo or have @xds/core installed.',
@@ -77,6 +81,7 @@ export function registerComponent(program) {
([key]) => key.toLowerCase() === cat.toLowerCase(),
);
if (!match) {
+ if (json) return jsonError(`Unknown category "${cat}"`, Object.keys(components).map(k => ({name: k, reason: 'valid category'})));
console.error(`Error: Unknown category "${cat}".`);
console.error(
`Available categories: ${Object.keys(components).join(', ')}`,
@@ -84,8 +89,26 @@ export function registerComponent(program) {
process.exit(1);
}
+ if (json && detail === 'brief') {
+ const entries = [];
+ for (const comp of match[1]) {
+ const readme = findComponentReadme(coreDir, comp);
+ if (readme && readme.endsWith('.doc.mjs')) {
+ try {
+ const docs = await loadDocs(readme, {zh, lang});
+ entries.push({name: comp, description: docs.description, import: resolveImportPath(coreDir, comp)});
+ } catch {
+ entries.push({name: comp, description: '', import: resolveImportPath(coreDir, comp)});
+ }
+ } else {
+ entries.push({name: comp, description: '', import: resolveImportPath(coreDir, comp)});
+ }
+ }
+ return jsonOut('component.brief', {[match[0]]: entries});
+ }
+ if (json) return jsonOut('component.list', {[match[0]]: match[1]});
+
if (detail === 'brief') {
- // Brief list: name + one-line description for each component
for (const comp of match[1]) {
const readme = findComponentReadme(coreDir, comp);
if (readme && readme.endsWith('.doc.mjs')) {
@@ -111,8 +134,39 @@ export function registerComponent(program) {
}
// --list or no name: show all components
+ if (json && detail === 'brief') {
+ /** @type {Record<string, Array<import('../../types/component').ComponentBriefEntry>>} */
+ const result = {};
+ for (const [category, comps] of Object.entries(components)) {
+ result[category] = [];
+ for (const comp of comps) {
+ const readme = findComponentReadme(coreDir, comp);
+ if (readme && readme.endsWith('.doc.mjs')) {
+ try {
+ const docs = await loadDocs(readme, {zh, lang});
+ result[category].push({name: comp, description: docs.description, import: resolveImportPath(coreDir, comp)});
+ } catch {
+ result[category].push({name: comp, description: '', import: resolveImportPath(coreDir, comp)});
+ }
+ } else {
+ result[category].push({name: comp, description: '', import: resolveImportPath(coreDir, comp)});
+ }
+ }
+ }
+ return jsonOut('component.brief', result);
+ }
+ if (json) {
+ const externals = discoverExternalPackages(process.cwd());
+ for (const ext of externals) {
+ const extComps = discoverExternalComponents(ext.docsDir);
+ if (extComps.length > 0) {
+ components[`${ext.category} (${ext.name})`] = extComps;
+ }
+ }
+ return jsonOut('component.list', components);
+ }
+
if (detail === 'brief') {
- // Brief list: brief summaries of ALL components
console.log(await formatBriefAll(coreDir, {zh, lang, themeData}));
} else {
console.log('');
@@ -123,7 +177,6 @@ export function registerComponent(program) {
}
console.log('');
}
- // Show external packages
const externals = discoverExternalPackages(process.cwd());
for (const ext of externals) {
const extComponents = discoverExternalComponents(ext.docsDir);
@@ -148,10 +201,12 @@ export function registerComponent(program) {
if (options.source) {
const sourcePath = findComponentSource(coreDir, dirName);
if (!sourcePath) {
+ if (json) return jsonError(`Source for "${name}" not found`);
console.error(`Error: Source for "${name}" not found.`);
process.exit(1);
}
const source = fs.readFileSync(sourcePath, 'utf-8');
+ if (json) return jsonOut('component.detail.source', {component: dirName, source});
console.log(source);
return;
}
@@ -185,19 +240,17 @@ export function registerComponent(program) {
const gap = topScore - secondScore;
if (topScore >= 90 && topTied.length === 1 && gap >= 20) {
- // Crystal clear single winner: show docs directly
resolvedName = topTied[0].name;
readmePath = findComponentReadme(coreDir, resolvedName);
- if (readmePath && topScore < 100) {
+ if (readmePath && topScore < 100 && !json) {
console.log(`Showing results for ${resolvedName} (matched ${topTied[0].reason})\n`);
}
} else {
- // Multiple strong matches or ambiguous: show options
- // Include everything within 20 points of the top, min 2, max 5
const threshold = Math.max(topScore - 20, 1);
const candidates = results.filter(r => r.score >= threshold).slice(0, 5);
if (candidates.length < 2) candidates.push(...results.slice(candidates.length, 2));
+ if (json) return jsonError(`No component named "${name}"`, candidates.map(c => ({name: c.name, reason: c.reason})));
console.error(`No component named "${name}". Did you mean:\n`);
for (const match of candidates) {
console.error(` ${match.name} (${match.reason})`);
@@ -206,6 +259,7 @@ export function registerComponent(program) {
process.exit(1);
}
} else {
+ if (json) return jsonError(`No component named "${name}"`);
console.error(`No component named "${name}".`);
console.error(`Run \`${run} xds component --list\` to see available components.`);
process.exit(1);
@@ -215,6 +269,13 @@ export function registerComponent(program) {
if (readmePath.endsWith('.doc.mjs')) {
const docs = await loadDocs(readmePath, {zh, dense, lang});
const importHint = fromExternal ? fromExternal.name : resolveImportPath(coreDir, resolvedName);
+ if (json) {
+ if (options.props) {
+ const props = docs.props || (docs.components ? docs.components.flatMap(c => c.props || []) : []);
+ return jsonOut('component.detail.props', props);
+ }
+ return jsonOut('component.detail', docs);
+ }
if (options.props) {
console.log(formatProps(docs, resolvedName));
} else if (detail === 'brief') {
@@ -227,6 +288,7 @@ export function registerComponent(program) {
} else {
// Legacy path for README.md files
const content = fs.readFileSync(readmePath, 'utf-8');
+ if (json) return jsonOut('markdown', {name: resolvedName, format: 'markdown', content});
if (options.props) {
console.log(extractProps(content, resolvedName));
} else if (detail === 'brief') {
diff --git a/packages/cli/src/commands/discover.mjs b/packages/cli/src/commands/discover.mjs
index d98b023150..5e18f746ab 100644
--- a/packages/cli/src/commands/discover.mjs
+++ b/packages/cli/src/commands/discover.mjs
@@ -13,6 +13,7 @@ import {scanAllPackages, findComponentInPackages} from '../lib/package-scanner.m
import {loadDocs} from '../lib/component-loader.mjs';
import {formatFull, formatBrief, formatCompact} from '../lib/component-format.mjs';
import {levenshteinDistance} from '../lib/string-utils.mjs';
+import {jsonOut, jsonError} from '../lib/json.mjs';
export function registerDiscover(program) {
program
@@ -22,8 +23,13 @@ export function registerDiscover(program) {
.action(async (query, options) => {
const config = await loadConfig();
const detail = program.opts().detail || 'full';
+ const json = program.opts().json || false;
+
+ /** @param {object} pkg */
+ const toEntry = (pkg) => ({name: pkg.name, category: pkg.category, components: pkg.components});
if (config.packages.length === 0) {
+ if (json) return jsonOut('discover.list', []);
console.log('');
console.log('No package directories configured.');
console.log('');
@@ -39,6 +45,7 @@ export function registerDiscover(program) {
const packages = scanAllPackages(config.packages);
if (packages.length === 0) {
+ if (json) return jsonOut('discover.list', []);
console.log('');
console.log('No external XDS packages found.');
console.log('');
@@ -54,24 +61,22 @@ export function registerDiscover(program) {
return;
}
- // No query: list all packages
if (!query) {
+ if (json) return jsonOut('discover.list', packages.map(toEntry));
printPackageList(packages, options.components);
return;
}
- // Starts with @: package navigation
if (query.startsWith('@')) {
const slashIdx = query.indexOf('/', query.indexOf('/') + 1);
if (slashIdx > 0) {
- // @scope/name/Component
const pkgName = query.slice(0, slashIdx);
const compName = query.slice(slashIdx + 1);
- await showComponentDocs(packages, compName, pkgName, program, detail);
+ await showComponentDocs(packages, compName, pkgName, program, detail, json);
} else {
- // @scope/name — list that package
const pkg = packages.find(p => p.name === query);
if (!pkg) {
+ if (json) return jsonError('Package "' + query + '" not found', packages.map(p => ({name: p.name, reason: 'available package'})));
console.error('Package "' + query + '" not found.');
console.error('');
console.error('Available packages:');
@@ -80,13 +85,13 @@ export function registerDiscover(program) {
}
process.exit(1);
}
+ if (json) return jsonOut('discover.detail', toEntry(pkg));
printSinglePackage(pkg);
}
return;
}
- // No @: search across all packages
- await searchComponents(packages, query, program, detail);
+ await searchComponents(packages, query, program, detail, json);
});
}
@@ -133,22 +138,23 @@ function printSinglePackage(pkg) {
console.log('');
}
-async function showComponentDocs(packages, compName, pkgName, program, detail) {
+async function showComponentDocs(packages, compName, pkgName, program, detail, json) {
const pkg = packages.find(p => p.name === pkgName);
if (!pkg) {
+ if (json) return jsonError('Package "' + pkgName + '" not found');
console.error('Package "' + pkgName + '" not found.');
process.exit(1);
}
const result = findComponentInPackages([pkg], compName);
if (!result) {
- // Substring match first, then fuzzy
const substringHits = pkg.components.filter(
c => c.toLowerCase().includes(compName.toLowerCase()),
);
const suggestions = substringHits.length > 0
? substringHits
: fuzzyMatch(compName, pkg.components);
+ if (json) return jsonError('Component "' + compName + '" not found in ' + pkgName, suggestions.map(s => ({name: s, reason: 'similar name'})));
if (suggestions.length > 0) {
console.error('Component "' + compName + '" not found in ' + pkgName + '.');
console.error('');
@@ -164,22 +170,22 @@ async function showComponentDocs(packages, compName, pkgName, program, detail) {
process.exit(1);
}
- await renderDocs(result, program, detail);
+ await renderDocs(result, program, detail, json);
}
-async function searchComponents(packages, query, program, detail) {
+async function searchComponents(packages, query, program, detail, json) {
const lower = query.toLowerCase();
- // Exact match first
const exact = findComponentInPackages(packages, query);
if (exact) {
- console.log('Found: ' + exact.pkg.name + '/' + exact.componentName);
- console.log('');
- await renderDocs(exact, program, detail);
+ if (!json) {
+ console.log('Found: ' + exact.pkg.name + '/' + exact.componentName);
+ console.log('');
+ }
+ await renderDocs(exact, program, detail, json);
return;
}
- // Substring match
const substringMatches = [];
for (const pkg of packages) {
for (const comp of pkg.components) {
@@ -193,14 +199,17 @@ async function searchComponents(packages, query, program, detail) {
const match = substringMatches[0];
const result = findComponentInPackages([match.pkg], match.comp);
if (result) {
- console.log('Found: ' + match.pkg.name + '/' + match.comp);
- console.log('');
- await renderDocs(result, program, detail);
+ if (!json) {
+ console.log('Found: ' + match.pkg.name + '/' + match.comp);
+ console.log('');
+ }
+ await renderDocs(result, program, detail, json);
return;
}
}
if (substringMatches.length > 1) {
+ if (json) return jsonOut('discover.search', {query, matches: substringMatches.map(m => ({package: m.pkg.name, component: m.comp}))});
console.log('');
console.log('Found ' + substringMatches.length + ' matches for "' + query + '":');
console.log('');
@@ -211,7 +220,6 @@ async function searchComponents(packages, query, program, detail) {
return;
}
- // Fuzzy match across all packages
const allComponents = [];
for (const pkg of packages) {
for (const comp of pkg.components) {
@@ -228,12 +236,14 @@ async function searchComponents(packages, query, program, detail) {
.slice(0, 5);
if (fuzzyMatches.length > 0) {
+ if (json) return jsonError('"' + query + '" not found', fuzzyMatches.map(m => ({name: m.pkg.name + '/' + m.comp, reason: 'similar name'})));
console.error('"' + query + '" not found. Did you mean?');
console.error('');
for (const m of fuzzyMatches) {
console.error(' xds discover ' + m.pkg.name + '/' + m.comp);
}
} else {
+ if (json) return jsonError('"' + query + '" not found in any package');
console.error('"' + query + '" not found in any package.');
console.error('');
console.error('Run xds discover to see available packages.');
@@ -265,13 +275,14 @@ function validateDocs(docs) {
return null;
}
-async function renderDocs(result, program, detail) {
+async function renderDocs(result, program, detail, json) {
let docs;
try {
const zh = program.opts().zh || false;
const lang = program.opts().lang || null;
docs = await loadDocs(result.docPath, {zh, lang});
} catch (e) {
+ if (json) return jsonError('Failed to load docs for ' + result.componentName + ': ' + e.message);
console.error('Failed to load docs for ' + result.componentName + ': ' + e.message);
console.error('File: ' + result.docPath);
process.exit(1);
@@ -279,11 +290,14 @@ async function renderDocs(result, program, detail) {
const validationError = validateDocs(docs);
if (validationError) {
+ if (json) return jsonError('Invalid docs for ' + result.componentName + ': ' + validationError);
console.error('Invalid docs for ' + result.componentName + ': ' + validationError);
console.error('File: ' + result.docPath);
process.exit(1);
}
+ if (json) return jsonOut('discover.detail.doc', docs);
+
if (detail === 'brief') {
console.log(formatBrief(docs, result.componentName, result.pkg.name + '/' + result.componentName));
} else if (detail === 'compact') {
diff --git a/packages/cli/src/commands/docs.mjs b/packages/cli/src/commands/docs.mjs
index aaf0ff737b..541cef861b 100644
--- a/packages/cli/src/commands/docs.mjs
+++ b/packages/cli/src/commands/docs.mjs
@@ -15,6 +15,7 @@ import * as path from 'node:path';
import {pathToFileURL} from 'node:url';
import {CLI_ROOT} from '../utils/paths.mjs';
import {getRunPrefix} from '../utils/package-manager.mjs';
+import {jsonOut, jsonError} from '../lib/json.mjs';
const DOCS_DIR = path.join(CLI_ROOT, 'docs');
@@ -192,9 +193,23 @@ export function registerDocs(program) {
const zh = program.opts().zh || false;
const dense = program.opts().dense || false;
const detail = program.opts().detail || 'full';
+ const json = program.opts().json || false;
const effectiveLang = lang || (dense ? 'dense' : zh ? 'zh' : null);
if (!topic) {
+ if (json) {
+ /** @type {Array<import('../types/docs').DocsListEntry>} */
+ const entries = [];
+ for (const [name, docPath] of Object.entries(topics)) {
+ try {
+ const mod = await import(pathToFileURL(docPath).href);
+ entries.push({topic: name, description: mod.docs.description});
+ } catch {
+ entries.push({topic: name, description: ''});
+ }
+ }
+ return jsonOut('docs.list', entries);
+ }
console.log('\nAvailable docs:\n');
for (const [name, docPath] of Object.entries(topics)) {
try {
@@ -212,13 +227,15 @@ export function registerDocs(program) {
const normalized = topic.toLowerCase();
if (!topics[normalized]) {
- // Fallback: try legacy .md file
const mdPath = path.join(DOCS_DIR, `${normalized}.md`);
if (fs.existsSync(mdPath)) {
- console.log(fs.readFileSync(mdPath, 'utf-8'));
+ const content = fs.readFileSync(mdPath, 'utf-8');
+ if (json) return jsonOut('markdown', {name: normalized, format: 'markdown', content});
+ console.log(content);
return;
}
+ if (json) return jsonError(`Unknown topic "${topic}"`, Object.keys(topics).map(t => ({name: t, reason: 'available topic'})));
console.error(`Error: Unknown topic "${topic}".`);
console.error(`Available topics: ${Object.keys(topics).join(', ')}`);
process.exit(1);
@@ -232,16 +249,19 @@ export function registerDocs(program) {
s => s.title.toLowerCase().includes(normalizedSection),
);
if (!match) {
+ if (json) return jsonError(`Section "${section}" not found in "${topic}"`, docs.sections.map(s => ({name: s.title, reason: 'available section'})));
console.error(`Error: Section "${section}" not found in "${topic}".`);
console.error(
`Available sections: ${docs.sections.map(s => s.title).join(', ')}`,
);
process.exit(1);
}
+ if (json) return jsonOut('docs.detail.section', match);
console.log(formatSection(match, detail));
return;
}
+ if (json) return jsonOut('docs.detail', docs);
console.log(formatReferenceFull(docs, detail));
});
}
diff --git a/packages/cli/src/commands/gap-report.mjs b/packages/cli/src/commands/gap-report.mjs
index 51df7774b7..f52c68eda5 100644
--- a/packages/cli/src/commands/gap-report.mjs
+++ b/packages/cli/src/commands/gap-report.mjs
@@ -17,6 +17,7 @@ import {
GAP_CATEGORIES,
} from '../utils/github.mjs';
import {getRunPrefix} from '../utils/package-manager.mjs';
+import {jsonOut, jsonError} from '../lib/json.mjs';
function isCancel(value) {
if (p.isCancel(value)) {
@@ -170,9 +171,21 @@ export function registerGapReport(program) {
.option('--component <name>', 'Component name')
.option('--category <category>', 'Gap category')
.option('--reason <reason>', 'What capability was missing')
+ .option('--list-categories', 'List valid gap categories')
.action(async options => {
+ const json = program.opts().json || false;
+
+ 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}`);
+ }
+ return;
+ }
+
const config = loadGapReportConfig();
if (!config.enabled) {
+ if (json) return jsonError('Gap reporting is disabled');
console.log(
`Gap reporting is disabled. Run \`${getRunPrefix()} xds gap-report setup\` to configure.`,
);
@@ -197,6 +210,10 @@ export function registerGapReport(program) {
c => c.value === options.category,
);
if (!validCategory) {
+ if (json)
+ return jsonError(
+ `Invalid category "${options.category}". Valid: ${GAP_CATEGORIES.map(c => c.value).join(', ')}`,
+ );
console.error(
`Error: Invalid category "${options.category}".\n` +
`Valid categories: ${GAP_CATEGORIES.map(c => c.value).join(', ')}`,
@@ -211,12 +228,18 @@ export function registerGapReport(program) {
intention: options.reason,
source: 'cli',
});
+ if (json)
+ return jsonOut('gap-report.file', {
+ filed: !!url,
+ url: url || null,
+ });
if (url) {
console.log(`\n✓ Gap report filed: ${url}\n`);
} else {
console.log('\nGap reporting is disabled via configuration.\n');
}
} catch (err) {
+ if (json) return jsonError(err.message);
console.error(`Error filing gap report: ${err.message}`);
process.exit(1);
}
diff --git a/packages/cli/src/commands/swizzle.mjs b/packages/cli/src/commands/swizzle.mjs
index 64c40e01ad..ad6f466404 100644
--- a/packages/cli/src/commands/swizzle.mjs
+++ b/packages/cli/src/commands/swizzle.mjs
@@ -13,6 +13,7 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import * as p from '@clack/prompts';
import {findCoreDir, listComponents} from '../utils/paths.mjs';
+import {jsonOut, jsonError} from '../lib/json.mjs';
import {
checkGhCli,
createGapReport,
@@ -63,8 +64,10 @@ export function registerSwizzle(program) {
.option('--no-report', 'Suppress the interactive gap report prompt')
.action(async (component, options) => {
const coreDir = findCoreDir(process.cwd());
+ const json = program.opts().json || false;
if (!coreDir) {
+ if (json) return jsonError('Could not find @xds/core package');
console.error(
'Error: Could not find @xds/core package.\n' +
'Make sure you are inside the XDS monorepo or have @xds/core installed.',
@@ -75,6 +78,7 @@ export function registerSwizzle(program) {
const components = listComponents(coreDir);
if (options.list || !component) {
+ if (json) return jsonOut('swizzle.list', components);
console.log('\nAvailable components:\n');
for (const name of components) {
console.log(` ${name}`);
@@ -85,11 +89,11 @@ export function registerSwizzle(program) {
return;
}
- // Normalize component name — strip XDS prefix for directory lookup
const dirName = component.replace(/^XDS/, '');
const componentDir = path.join(coreDir, 'src', dirName);
if (!fs.existsSync(componentDir)) {
+ if (json) return jsonError(`Component "${component}" not found`, components.slice(0, 5).map(n => ({name: n, reason: 'available component'})));
console.error(`Error: Component "${component}" not found.`);
console.error(`Available: ${components.join(', ')}`);
process.exit(1);
@@ -122,45 +126,44 @@ export function registerSwizzle(program) {
}
const relOutput = path.relative(process.cwd(), outputDir);
- 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');
+ const copiedFiles = files.filter(f => !f.includes('.test.') && f !== 'README.md' && fs.statSync(path.join(componentDir, f)).isFile());
// --- Gap reporting ---
const gapConfig = loadGapReportConfig();
+ let gapReportUrl = null;
- // Programmatic gap mode (for LLMs using --gap flag)
if (options.gap) {
- if (!gapConfig.enabled) {
- console.log('Gap reporting is disabled via configuration.');
- return;
- }
- if (!gapConfig.command && !checkGhCli()) {
- console.log(
- 'Skipping gap report: gh CLI not available. Install from https://cli.github.com',
- );
- return;
- }
-
- const category = options.gapCategory || 'other';
- try {
- const url = createGapReport({
- component: dirName,
- category,
- intention: options.gap,
- source: 'llm-auto',
- });
- if (url) {
- console.log(`✓ Gap report filed: ${url}\n`);
+ if (gapConfig.enabled && (gapConfig.command || checkGhCli())) {
+ const category = options.gapCategory || 'other';
+ try {
+ gapReportUrl = createGapReport({
+ component: dirName,
+ category,
+ intention: options.gap,
+ source: 'llm-auto',
+ });
+ } catch (err) {
+ if (!json) console.error(`Warning: Could not file gap report: ${err.message}`);
}
- } catch (err) {
- console.error(`Warning: Could not file gap report: ${err.message}`);
}
+
+ if (json) return jsonOut('swizzle.copy', {component: dirName, outputDir: relOutput, filesCopied: copied, files: copiedFiles.map(f => f), gapReport: gapReportUrl});
+ 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');
+ if (gapReportUrl) console.log(`✓ Gap report filed: ${gapReportUrl}\n`);
+ else if (!gapConfig.enabled) console.log('Gap reporting is disabled via configuration.');
+ else if (!gapConfig.command && !checkGhCli()) console.log('Skipping gap report: gh CLI not available.');
return;
}
- // Skip interactive prompt if --no-report or gap reporting disabled
+ 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');
+
if (!options.report || !gapConfig.enabled) {
return;
}
diff --git a/packages/cli/src/commands/template.mjs b/packages/cli/src/commands/template.mjs
index 0ef192123d..1e89706487 100644
--- a/packages/cli/src/commands/template.mjs
+++ b/packages/cli/src/commands/template.mjs
@@ -12,6 +12,7 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
import {CLI_ROOT} from '../utils/paths.mjs';
+import {jsonOut, jsonError} from '../lib/json.mjs';
// ── Template discovery ───────────────────────────────────────────────
@@ -223,9 +224,16 @@ export function registerTemplate(program) {
const templatesDir = path.join(CLI_ROOT, 'templates');
const templates = await discoverTemplates();
const templateNames = templates.map(t => t.dirName);
+ const json = program.opts().json || false;
- // --list: show all templates with compositions
if (options.list || (!name && !options.skeleton)) {
+ if (json) {
+ return jsonOut('template.list', templates.map(t => ({
+ name: t.dirName,
+ description: t.description,
+ isReady: t.isReady,
+ })));
+ }
console.log('\nAvailable templates:\n');
for (const t of templates) {
const status = t.isReady ? '' : ' (WIP)';
@@ -248,8 +256,8 @@ export function registerTemplate(program) {
return;
}
- // Validate template name
if (name && !templateNames.includes(name)) {
+ if (json) return jsonError(`Unknown template "${name}"`, templateNames.map(n => ({name: n, reason: 'available template'})));
console.error(`Error: Unknown template "${name}".`);
console.error(`Available: ${templateNames.join(', ')}`);
process.exit(1);
@@ -307,6 +315,7 @@ export function registerTemplate(program) {
}
const relOutput = path.relative(process.cwd(), outputDir);
+ if (json) return jsonOut('template.copy', {template: name, outputDir: relOutput, filesCopied: copied});
console.log(`\n✓ Copied ${copied} template files to ${relOutput}/\n`);
});
}
diff --git a/packages/cli/src/commands/upgrade.mjs b/packages/cli/src/commands/upgrade.mjs
index c7ff790ed6..3916cd1af2 100644
--- a/packages/cli/src/commands/upgrade.mjs
+++ b/packages/cli/src/commands/upgrade.mjs
@@ -35,6 +35,7 @@ import {
import {runCodemods} from '../codemods/runner.mjs';
import {installAgentDocs, discoverAgentDocs} from './agent-docs.mjs';
import {detectPackageManager, getRunPrefix} from '../utils/package-manager.mjs';
+import {jsonOut, jsonError} from '../lib/json.mjs';
/**
* Detect the installed @xds/core version from the consumer's package.json.
@@ -142,11 +143,24 @@ export function registerUpgrade(program) {
.option('--install-deps', 'Auto-install jscodeshift without prompting', false)
.option('--list', 'List available codemods', false)
.action(async (options) => {
- p.intro('XDS Upgrade');
+ const json = program.opts().json || false;
+ if (!json) p.intro('XDS Upgrade');
if (options.list) {
+ const codemods = [];
+ for (const version of versions) {
+ const manifests = await getTransformsBetween('0.0.0', version);
+ for (const {transforms} of manifests) {
+ for (const {name, meta} of transforms) {
+ codemods.push({name, title: meta.title, version, pr: meta.pr});
+ }
+ }
+ }
+ if (json) return jsonOut('upgrade.list', codemods.map(({name, title, version}) => ({name, title, version})));
p.log.step('Available codemods:');
- await listCodemods();
+ for (const {name, title, pr} of codemods) {
+ p.log.info(` ${name} — ${title} (${pr})`);
+ }
p.outro('Done');
return;
}
@@ -158,9 +172,9 @@ export function registerUpgrade(program) {
// Detect current version (--from overrides package.json)
const currentVersion = options.from ?? detectCurrentVersion();
if (!currentVersion && !skipVersionCheck) {
- p.log.error(
- 'Could not detect @xds/core version. Make sure package.json is in the current directory, or use --from <version>.',
- );
+ 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);
+ p.log.error(msg);
p.outro('Aborted');
process.exitCode = 1;
return;
@@ -169,13 +183,17 @@ export function registerUpgrade(program) {
const targetVersion = options.to;
if (!skipVersionCheck) {
- p.log.info(`Current version: ${currentVersion}`);
- p.log.info(`Target version: ${targetVersion}`);
+ if (!json) {
+ p.log.info(`Current version: ${currentVersion}`);
+ p.log.info(`Target version: ${targetVersion}`);
+ }
if (!options.force && currentVersion >= 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');
+ 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');
+ }
return;
}
}
@@ -187,8 +205,10 @@ export function registerUpgrade(program) {
);
if (versionManifests.length === 0) {
- p.log.success('No codemods available for this version range.');
- p.outro('Done');
+ if (!json) {
+ p.log.success('No codemods available for this version range.');
+ p.outro('Done');
+ }
return;
}
@@ -203,31 +223,36 @@ export function registerUpgrade(program) {
}
if (totalTransforms === 0) {
- p.log.error(
- `Codemod "${options.codemod}" not found. Use --list to see available codemods.`,
- );
+ const msg = `Codemod "${options.codemod}" not found. Use --list to see available codemods.`;
+ if (json) return jsonError(msg);
+ p.log.error(msg);
p.outro('Aborted');
process.exitCode = 1;
return;
}
- p.log.step(
- `${totalTransforms} codemod${totalTransforms === 1 ? '' : 's'} to run${options.apply ? '' : ' (dry run)'}`,
- );
+ if (!json) {
+ p.log.step(
+ `${totalTransforms} codemod${totalTransforms === 1 ? '' : 's'} to run${options.apply ? '' : ' (dry run)'}`,
+ );
+ }
+
+ const receipt = {from: currentVersion, to: targetVersion, codemods: totalTransforms, depsUpdated: [], agentDocsRefreshed: false};
// Bump @xds/* deps and install before running codemods
if (options.apply && !skipVersionCheck) {
const result = bumpXdsDeps(targetVersion);
if (result && result.bumped.length > 0) {
- p.log.info(`Bumped ${result.bumped.join(', ')} → ${targetVersion}`);
+ receipt.depsUpdated = result.bumped;
+ if (!json) p.log.info(`Bumped ${result.bumped.join(', ')} → ${targetVersion}`);
const installCmd = getInstallCommand();
- p.log.step(`Running ${installCmd}...`);
+ if (!json) p.log.step(`Running ${installCmd}...`);
try {
execSync(installCmd, {stdio: 'inherit', cwd: process.cwd()});
- p.log.success('Dependencies installed.');
+ if (!json) p.log.success('Dependencies installed.');
} catch {
- p.log.warn('Install failed — codemods will still run against existing code.');
+ if (!json) p.log.warn('Install failed — codemods will still run against existing code.');
}
}
}
@@ -235,6 +260,7 @@ export function registerUpgrade(program) {
// Ensure jscodeshift is available
const ready = await ensureJscodeshift({installDeps: options.installDeps});
if (!ready) {
+ if (json) return jsonError('jscodeshift is required but could not be installed.');
p.outro('Aborted');
process.exitCode = 1;
return;
@@ -254,14 +280,18 @@ export function registerUpgrade(program) {
if (existingDocs.length > 0) {
try {
const written = installAgentDocs(process.cwd());
- p.log.success(`Agent docs updated: ${written.join(', ')}`);
+ receipt.agentDocsRefreshed = true;
+ if (!json) p.log.success(`Agent docs updated: ${written.join(', ')}`);
} catch {
- p.log.warn(
- `Could not update agent docs. Run \`${getRunPrefix()} xds agent-docs\` to update manually.`,
- );
+ if (!json) {
+ p.log.warn(
+ `Could not update agent docs. Run \`${getRunPrefix()} xds agent-docs\` to update manually.`,
+ );
+ }
}
}
+ if (json) 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 648df5919d..538fb38b72 100644
--- a/packages/cli/src/index.mjs
+++ b/packages/cli/src/index.mjs
@@ -27,18 +27,41 @@ 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 })')
.addHelpCommand('help', 'Show all commands')
.action(() => {
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.
+ */
+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);
+ }
+});
+
/**
* Post-action hook: print update hint after any command output.
* Only fires for commands that produce output agents read (component, docs, etc.).
- * Uses the FYI format validated by vibe testing — never triggers injection defenses.
+ * Suppressed when --json is active to avoid contaminating stdout.
*/
const UPDATE_HINT_COMMANDS = new Set(['component', 'docs', 'doctor']);
program.hook('postAction', (thisCommand, actionCommand) => {
+ if (program.opts().json) return;
try {
if (UPDATE_HINT_COMMANDS.has(actionCommand.name())) {
const hint = checkForUpdate();
diff --git a/packages/cli/src/lib/json.mjs b/packages/cli/src/lib/json.mjs
new file mode 100644
index 0000000000..918c41ada8
--- /dev/null
+++ b/packages/cli/src/lib/json.mjs
@@ -0,0 +1,38 @@
+/**
+ * @file Internal JSON output helpers for CLI commands.
+ *
+ * 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.
+ *
+ * Consumer-facing utilities (parseResponse, isError, assertResponse)
+ * live in parse.mjs and are exported via @xds/cli/json.
+ */
+
+/**
+ * Output a typed JSON response envelope and mark as handled.
+ * Type safety enforced via declaration in types/base.d.ts —
+ * data must match the declared shape for the given type discriminator.
+ * @template {import('../types/base').CLIResponseType} T
+ * @param {T} type
+ * @param {import('../types/base').CLIResponseDataMap[T]} data
+ * @returns {void}
+ */
+export function jsonOut(type, data) {
+ process.__xdsJsonHandled = true;
+ console.log(JSON.stringify({type, data}, null, 2));
+}
+
+/**
+ * Output a structured JSON error and exit.
+ * @param {string} message
+ * @param {Array<{name: string, reason: string}>} [suggestions]
+ */
+export function jsonError(message, suggestions) {
+ process.__xdsJsonHandled = true;
+ /** @type {import('../types/base').CLIError} */
+ const err = {error: message};
+ if (suggestions?.length) err.suggestions = suggestions;
+ console.log(JSON.stringify(err, null, 2));
+ process.exit(1);
+}
diff --git a/packages/cli/src/lib/parse.mjs b/packages/cli/src/lib/parse.mjs
new file mode 100644
index 0000000000..2f9b483842
--- /dev/null
+++ b/packages/cli/src/lib/parse.mjs
@@ -0,0 +1,41 @@
+/**
+ * @file Consumer utilities for parsing XDS CLI JSON output.
+ *
+ * Exported via `@xds/cli/json`:
+ * import { parseResponse, isError, assertResponse } from '@xds/cli/json';
+ */
+
+/**
+ * Parse raw CLI output into a typed result.
+ * Consumer types are declared in types/base.d.ts — this is the runtime implementation.
+ * @param {unknown} raw
+ */
+export function parseResponse(raw) {
+ return typeof raw === 'string' ? JSON.parse(raw) : raw;
+}
+
+/**
+ * Type guard: returns true if result is a CLI error.
+ * @param {unknown} result
+ * @returns {boolean}
+ */
+export function isError(result) {
+ return result != null && typeof result === 'object' && 'error' in result;
+}
+
+/**
+ * Assert a specific response type. Throws on error or type mismatch.
+ * Consumer types are declared in types/base.d.ts — this is the runtime implementation.
+ * @param {unknown} raw
+ * @param {string} expectedType
+ */
+export function assertResponse(raw, expectedType) {
+ const result = parseResponse(raw);
+ if (isError(result)) throw new Error(/** @type {any} */ (result).error);
+ if (/** @type {any} */ (result).type !== expectedType) {
+ throw new Error(
+ `Expected type "${expectedType}", got "${/** @type {any} */ (result).type}"`,
+ );
+ }
+ return result;
+}
diff --git a/packages/cli/src/types/base.d.ts b/packages/cli/src/types/base.d.ts
new file mode 100644
index 0000000000..d527e833ec
--- /dev/null
+++ b/packages/cli/src/types/base.d.ts
@@ -0,0 +1,132 @@
+/**
+ * Shared types for the XDS CLI JSON API.
+ *
+ * CLIError and CLIUnsupportedError are the two error shapes.
+ * CLIMarkdownResponse is the shared fallback for legacy .md files.
+ * CLIAnyResponse is the union of all success response types.
+ * CLIResult<T> wraps any response with possible errors.
+ */
+
+import type {
+ ComponentListResponse,
+ ComponentBriefResponse,
+ ComponentDetailResponse,
+ ComponentDetailPropsResponse,
+ ComponentDetailSourceResponse,
+} from './component';
+import type {
+ DiscoverListResponse,
+ DiscoverDetailResponse,
+ DiscoverDetailDocResponse,
+ DiscoverSearchResponse,
+} from './discover';
+import type {
+ DocsListResponse,
+ DocsDetailResponse,
+ DocsDetailSectionResponse,
+} from './docs';
+import type {TemplateListResponse, TemplateCopyResponse} from './template';
+import type {SwizzleListResponse, SwizzleCopyResponse} from './swizzle';
+import type {ThemeBuildResponse} from './theme';
+import type {UpgradeListResponse, UpgradeRunResponse} from './upgrade';
+import type {
+ GapReportCategoriesResponse,
+ GapReportFileResponse,
+} from './gap-report';
+
+/** Structured error. Check `'error' in result` to discriminate. */
+export interface CLIError {
+ error: string;
+ 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`;
+}
+
+/** Legacy markdown fallback envelope. */
+export interface CLIMarkdownResponse {
+ type: 'markdown';
+ data: {name: string; format: 'markdown'; content: string};
+}
+
+/** Wrap any response type to include possible error shapes. */
+export type CLIResult<T> = T | CLIError | CLIUnsupportedError;
+
+/** Union of all possible success response types. */
+export type CLIAnyResponse =
+ | ComponentListResponse
+ | ComponentBriefResponse
+ | ComponentDetailResponse
+ | ComponentDetailPropsResponse
+ | ComponentDetailSourceResponse
+ | DiscoverListResponse
+ | DiscoverDetailResponse
+ | DiscoverDetailDocResponse
+ | DiscoverSearchResponse
+ | DocsListResponse
+ | DocsDetailResponse
+ | DocsDetailSectionResponse
+ | TemplateListResponse
+ | TemplateCopyResponse
+ | SwizzleListResponse
+ | SwizzleCopyResponse
+ | ThemeBuildResponse
+ | UpgradeListResponse
+ | UpgradeRunResponse
+ | GapReportCategoriesResponse
+ | GapReportFileResponse
+ | CLIMarkdownResponse;
+
+/** Union of all type discriminator string literals. */
+export type CLIResponseType = CLIAnyResponse['type'];
+
+/**
+ * Map from type discriminator to the data shape for that response.
+ * Used by jsonOut to enforce type-safe data payloads.
+ */
+export type CLIResponseDataMap = {
+ [R in CLIAnyResponse as R['type']]: R['data'];
+};
+
+/**
+ * Output a typed JSON response envelope. The data parameter is
+ * constrained to match the declared shape for the given type discriminator.
+ */
+export function jsonOut<T extends CLIResponseType>(
+ type: T,
+ data: CLIResponseDataMap[T],
+): void;
+
+/**
+ * Output a structured JSON error and exit.
+ */
+export function jsonError(
+ message: string,
+ suggestions?: Array<{name: string; reason: string}>,
+): never;
+
+/** Parse raw CLI output (string or object) into typed result. */
+export function parseResponse(
+ raw: unknown,
+): CLIAnyResponse | CLIError | CLIUnsupportedError;
+
+/** Type guard: returns true if result is an error. */
+export function isError(
+ result: unknown,
+): result is CLIError | CLIUnsupportedError;
+
+/** Assert a specific response type. Throws on error or type mismatch. */
+export function assertResponse<T extends CLIResponseType>(
+ raw: unknown,
+ type: T,
+): Extract<CLIAnyResponse, {type: T}>;
+
+declare global {
+ namespace NodeJS {
+ interface Process {
+ __xdsJsonHandled?: boolean;
+ }
+ }
+}
diff --git a/packages/cli/src/types/component.d.ts b/packages/cli/src/types/component.d.ts
new file mode 100644
index 0000000000..90ae5efa23
--- /dev/null
+++ b/packages/cli/src/types/component.d.ts
@@ -0,0 +1,53 @@
+/**
+ * Component command JSON responses.
+ *
+ * Invocation -> type discriminator
+ * ------------------------------------------------------------------
+ * xds --json component -> component.list
+ * xds --json component --list -> component.list
+ * xds --json component --category Form -> component.list (filtered)
+ * xds --json component --detail brief -> component.brief
+ * xds --json component Button -> component.detail
+ * xds --json component Button --props -> component.detail.props
+ * xds --json component Button --source -> component.detail.source
+ * xds --json component Button (legacy .md) -> markdown (CLIMarkdownResponse)
+ * (not found) -> CLIError
+ */
+
+import type {ComponentDoc, PropDoc} from '../../../core/src/docs-types';
+
+/** xds --json component [--list] [--category X] */
+export interface ComponentListResponse {
+ type: 'component.list';
+ data: Record<string, string[]>;
+}
+
+/** xds --json component --detail brief [--category X] */
+export interface ComponentBriefResponse {
+ type: 'component.brief';
+ data: Record<string, ComponentBriefEntry[]>;
+}
+
+export interface ComponentBriefEntry {
+ name: string;
+ description: string;
+ import: string;
+}
+
+/** xds --json component <name> */
+export interface ComponentDetailResponse {
+ type: 'component.detail';
+ data: ComponentDoc;
+}
+
+/** xds --json component <name> --props */
+export interface ComponentDetailPropsResponse {
+ type: 'component.detail.props';
+ data: PropDoc[];
+}
+
+/** xds --json component <name> --source */
+export interface ComponentDetailSourceResponse {
+ type: 'component.detail.source';
+ data: {component: string; source: string};
+}
diff --git a/packages/cli/src/types/discover.d.ts b/packages/cli/src/types/discover.d.ts
new file mode 100644
index 0000000000..6b780410da
--- /dev/null
+++ b/packages/cli/src/types/discover.d.ts
@@ -0,0 +1,49 @@
+/**
+ * Discover command JSON responses.
+ *
+ * Invocation -> type discriminator
+ * ------------------------------------------------------------------
+ * xds --json discover -> discover.list
+ * xds --json discover @scope/name -> discover.detail
+ * xds --json discover @scope/name/Component -> discover.detail.doc
+ * xds --json discover <searchterm> (1 match) -> discover.detail.doc
+ * xds --json discover <searchterm> (N matches) -> discover.search
+ * (not found) -> CLIError
+ */
+
+import type {ComponentDoc} from '../../../core/src/docs-types';
+
+/** xds --json discover */
+export interface DiscoverListResponse {
+ type: 'discover.list';
+ data: DiscoverListEntry[];
+}
+
+export interface DiscoverListEntry {
+ name: string;
+ category: string;
+ components: string[];
+}
+
+/** xds --json discover @scope/name */
+export interface DiscoverDetailResponse {
+ type: 'discover.detail';
+ data: DiscoverListEntry;
+}
+
+/** xds --json discover @scope/name/Component */
+export interface DiscoverDetailDocResponse {
+ type: 'discover.detail.doc';
+ data: ComponentDoc;
+}
+
+/** xds --json discover <searchterm> (multiple matches) */
+export interface DiscoverSearchResponse {
+ type: 'discover.search';
+ data: {query: string; matches: DiscoverSearchEntry[]};
+}
+
+export interface DiscoverSearchEntry {
+ package: string;
+ component: string;
+}
diff --git a/packages/cli/src/types/docs.d.ts b/packages/cli/src/types/docs.d.ts
new file mode 100644
index 0000000000..d1478adaa1
--- /dev/null
+++ b/packages/cli/src/types/docs.d.ts
@@ -0,0 +1,39 @@
+/**
+ * Docs command JSON responses.
+ *
+ * Invocation -> type discriminator
+ * ------------------------------------------------------------------
+ * xds --json docs -> docs.list
+ * xds --json docs <topic> -> docs.detail
+ * xds --json docs <topic> <section> -> docs.detail.section
+ * xds --json docs <topic> (legacy .md) -> markdown (CLIMarkdownResponse)
+ * (unknown topic/section) -> CLIError
+ */
+
+import type {
+ ReferenceDoc,
+ ReferenceSection,
+} from '../../../core/src/docs-types';
+
+/** xds --json docs */
+export interface DocsListResponse {
+ type: 'docs.list';
+ data: DocsListEntry[];
+}
+
+export interface DocsListEntry {
+ topic: string;
+ description: string;
+}
+
+/** xds --json docs <topic> */
+export interface DocsDetailResponse {
+ type: 'docs.detail';
+ data: ReferenceDoc;
+}
+
+/** xds --json docs <topic> <section> */
+export interface DocsDetailSectionResponse {
+ type: 'docs.detail.section';
+ data: ReferenceSection;
+}
diff --git a/packages/cli/src/types/gap-report.d.ts b/packages/cli/src/types/gap-report.d.ts
new file mode 100644
index 0000000000..276cb3c7ac
--- /dev/null
+++ b/packages/cli/src/types/gap-report.d.ts
@@ -0,0 +1,27 @@
+/**
+ * Gap-report command JSON responses.
+ *
+ * Invocation -> type discriminator
+ * ------------------------------------------------------------------
+ * xds --json gap-report --list-categories -> gap-report.categories
+ * xds --json gap-report --component X --category Y --reason Z -> gap-report.file
+ * (invalid category) -> CLIError
+ * (interactive mode) -> CLIUnsupportedError (fallback)
+ */
+
+/** xds --json gap-report --list-categories */
+export interface GapReportCategoriesResponse {
+ type: 'gap-report.categories';
+ data: GapReportCategoryEntry[];
+}
+
+export interface GapReportCategoryEntry {
+ value: string;
+ label: string;
+}
+
+/** xds --json gap-report --component X --category Y --reason Z */
+export interface GapReportFileResponse {
+ type: 'gap-report.file';
+ data: {filed: boolean; url: string | null};
+}
diff --git a/packages/cli/src/types/index.d.ts b/packages/cli/src/types/index.d.ts
new file mode 100644
index 0000000000..ef62ec54bd
--- /dev/null
+++ b/packages/cli/src/types/index.d.ts
@@ -0,0 +1,9 @@
+export * from './base';
+export * from './component';
+export * from './discover';
+export * from './docs';
+export * from './template';
+export * from './swizzle';
+export * from './theme';
+export * from './gap-report';
+export * from './upgrade';
diff --git a/packages/cli/src/types/swizzle.d.ts b/packages/cli/src/types/swizzle.d.ts
new file mode 100644
index 0000000000..8cc4f49ab9
--- /dev/null
+++ b/packages/cli/src/types/swizzle.d.ts
@@ -0,0 +1,28 @@
+/**
+ * Swizzle command JSON responses.
+ *
+ * Invocation -> type discriminator
+ * ------------------------------------------------------------------
+ * xds --json swizzle [--list] -> swizzle.list
+ * xds --json swizzle <component> -> swizzle.copy
+ * xds --json swizzle <component> --gap "x" -> swizzle.copy (with gapReport)
+ * (not found) -> CLIError
+ */
+
+/** xds --json swizzle [--list] */
+export interface SwizzleListResponse {
+ type: 'swizzle.list';
+ data: string[];
+}
+
+/** xds --json swizzle <component> */
+export interface SwizzleCopyResponse {
+ type: 'swizzle.copy';
+ data: {
+ component: string;
+ outputDir: string;
+ filesCopied: number;
+ files: string[];
+ gapReport?: string | null;
+ };
+}
diff --git a/packages/cli/src/types/template.d.ts b/packages/cli/src/types/template.d.ts
new file mode 100644
index 0000000000..30155cab06
--- /dev/null
+++ b/packages/cli/src/types/template.d.ts
@@ -0,0 +1,27 @@
+/**
+ * Template command JSON responses.
+ *
+ * Invocation -> type discriminator
+ * ------------------------------------------------------------------
+ * xds --json template [--list] -> template.list
+ * xds --json template <name> [path] -> template.copy
+ * (unknown template) -> CLIError
+ */
+
+/** xds --json template [--list] */
+export interface TemplateListResponse {
+ type: 'template.list';
+ data: TemplateListEntry[];
+}
+
+export interface TemplateListEntry {
+ name: string;
+ description: string;
+ isReady: boolean;
+}
+
+/** xds --json template <name> [path] */
+export interface TemplateCopyResponse {
+ type: 'template.copy';
+ data: {template: string; outputDir: string; filesCopied: number};
+}
diff --git a/packages/cli/src/types/theme.d.ts b/packages/cli/src/types/theme.d.ts
new file mode 100644
index 0000000000..74c346edb5
--- /dev/null
+++ b/packages/cli/src/types/theme.d.ts
@@ -0,0 +1,21 @@
+/**
+ * Theme build command JSON responses.
+ *
+ * Invocation -> type discriminator
+ * ------------------------------------------------------------------
+ * xds --json theme build <file> -> theme.build
+ * (file not found / parse error) -> CLIError
+ */
+
+/** xds --json theme build <file> */
+export interface ThemeBuildResponse {
+ type: 'theme.build';
+ data: {
+ name: string;
+ tokenCount: number;
+ componentCount: number;
+ sizeKB: number;
+ outputs: {css: string; js: string; dts: string; variantsDts?: string};
+ warnings: string[];
+ };
+}
diff --git a/packages/cli/src/types/upgrade.d.ts b/packages/cli/src/types/upgrade.d.ts
new file mode 100644
index 0000000000..ddda0a9242
--- /dev/null
+++ b/packages/cli/src/types/upgrade.d.ts
@@ -0,0 +1,33 @@
+/**
+ * Upgrade command JSON responses.
+ *
+ * Invocation -> type discriminator
+ * ------------------------------------------------------------------
+ * xds --json upgrade --list -> upgrade.list
+ * xds --json upgrade [--apply] -> upgrade.run
+ * (version detection failure) -> CLIError
+ */
+
+/** xds --json upgrade --list */
+export interface UpgradeListResponse {
+ type: 'upgrade.list';
+ data: UpgradeListEntry[];
+}
+
+export interface UpgradeListEntry {
+ name: string;
+ title: string;
+ version: string;
+}
+
+/** xds --json upgrade [--apply] */
+export interface UpgradeRunResponse {
+ type: 'upgrade.run';
+ data: {
+ from: string;
+ to: string;
+ codemods: number;
+ depsUpdated: string[];
+ agentDocsRefreshed: boolean;
+ };
+}
diff --git a/packages/cli/tsconfig.json-api.json b/packages/cli/tsconfig.json-api.json
new file mode 100644
index 0000000000..eb395b7e15
--- /dev/null
+++ b/packages/cli/tsconfig.json-api.json
@@ -0,0 +1,16 @@
+{
+ "extends": "../../tsconfig.json",
+ "compilerOptions": {
+ "rootDir": "../..",
+ "allowJs": true,
+ "checkJs": true,
+ "noEmit": true,
+ "types": ["node"]
+ },
+ "include": [
+ "src/types/**/*.d.ts",
+ "src/lib/json.mjs",
+ "src/lib/parse.mjs",
+ "../core/src/docs-types.ts"
+ ]
+}