Skip to content

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

TypeScript

feat(cli/api): add template() to @xds/cli/api (#1224)

Joey75f9ce92edf4
diff --git a/.github/scripts/api-cli-parity-test.mjs b/.github/scripts/api-cli-parity-test.mjs
index deed580dc2..0645f38dcd 100644
--- a/.github/scripts/api-cli-parity-test.mjs
+++ b/.github/scripts/api-cli-parity-test.mjs
@@ -125,10 +125,15 @@ for (const topic of allTopics) {
add('docs nonexistent', ['docs', 'nonexistent_xyz'],
() => apiCall(api.docs, 'nonexistent_xyz'));
-// Other commands — probe with safe read-only args
+// Template — uses API
+add('template --list', ['template', '--list'],
+ () => apiCall(api.template));
+add('template nonexistent', ['template', 'nonexistent99'],
+ () => apiCall(api.template, 'nonexistent99'));
+
+// Other commands — probe with safe read-only args (no API yet)
const otherCommands = [
['swizzle', '--list'],
- ['template', '--list'],
['gap-report', '--list-categories'],
['upgrade', '--list'],
];
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 97d8df4f66..3594c6ae3e 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -115,9 +115,17 @@ Every response has a `type` string that uniquely identifies it:
## Adding a new command
+### Does it need an API function?
+
+**Yes** if the command returns data that consumers might want programmatically — component docs, template source, lists, search results. Put the logic in `src/api/`, export from `@xds/cli/api`, and make the CLI handler a thin wrapper.
+
+**No** if the command is purely interactive or only makes sense in a terminal — `init` (interactive prompts), `gap-report setup` (config wizard). These can live entirely in `src/commands/`.
+
+**Rule of thumb:** if it supports `--json`, it should have an API function. The parity test (`api-cli-parity-test.mjs`) will flag any `--json` type that doesn't have API coverage.
+
### 1. Write the API function
-Add a file in `src/api/` with the core logic. It returns `{ type, data }` on success and throws `XDSError` on failure:
+Add a file in `src/api/` with all the logic. It returns `{ type, data }` on success and throws `XDSError` on failure. The CLI handler should have zero logic — just arg parsing and text formatting:
```javascript
// src/api/my-command.mjs
@@ -137,9 +145,15 @@ export async function myCommand(name, options = {}) {
}
```
+Export it from `src/api/index.mjs`:
+
+```javascript
+export {myCommand} from './my-command.mjs';
+```
+
### 2. Create the CLI wrapper
-Add a thin wrapper in `src/commands/` that parses args, calls the API, and formats output:
+The CLI handler just parses args, calls the API function, and formats the result. No business logic here:
```javascript
// src/commands/my-command.mjs
@@ -168,7 +182,7 @@ export function registerMyCommand(program) {
}
```
-### 2. Define response types
+### 3. Define response types
Create `src/types/my-command.d.ts`:
@@ -220,9 +234,63 @@ export type CLIAnyResponse =
| MyCommandDetailResponse;
```
-### 4. That's it
+### 5. That's it
+
+If you skip the type steps, the command still works — the global fallback hook returns a clean `CLIUnsupportedError` when someone passes `--json`. No crashes, no broken output.
+
+---
+
+## Playbook — common changes
+
+### Adding a prop to a component
+
+Nothing to do in the CLI. Props come from `.doc.mjs` files in `packages/core/src/`. The CLI reads them at runtime. If the `.doc.mjs` is updated, the CLI and API automatically reflect the change.
+
+### Adding a new component
+
+1. Create the component in `packages/core/src/{Name}/`
+2. Add a `{Name}.doc.mjs` in the same directory (or add to the parent's `.doc.mjs` if it's a sub-component)
+3. Done — the CLI auto-discovers it, the API auto-discovers it, the parity test auto-discovers it
+
+If the component has no `.doc.mjs`, `xds component {Name}` returns a clean error and CI's smoke test skips it.
+
+### Adding a new doc topic
+
+1. Add `{topic}.doc.mjs` in `packages/cli/docs/`
+2. Done — auto-discovered by `xds docs` and the `docs()` API function
+
+### Adding a new template
+
+1. Add a directory in `packages/cli/templates/{name}/` with a `page.tsx`
+2. Optionally add `template.doc.mjs` for metadata (name, description, isReady)
+3. Done — auto-discovered by `xds template --list` and the `template()` API function
+
+### Adding a new option to an existing API function
+
+1. Add the option to the API function in `src/api/{command}.mjs`
+2. Pass it through from the CLI handler in `src/commands/{command}.mjs`
+3. Update the types in `src/types/api.d.ts` (add to the options interface)
+4. If it produces a new response type, also update `src/types/{command}.d.ts` and `src/types/base.d.ts`
+
+### Adding a new response type (e.g. `component.detail.variants`)
+
+1. Add the logic in `src/api/{command}.mjs` — return `{type: 'component.detail.variants', data: ...}`
+2. Add a TypeScript interface in `src/types/{command}.d.ts`
+3. Add it to `CLIAnyResponse` in `src/types/base.d.ts`
+4. Add it to the result union in `src/types/api.d.ts`
+5. The parity test will auto-detect the new type and verify API=CLI
+
+### Renaming or removing a response type
+
+This is a breaking change for `@xds/cli/api` consumers. Bump the version.
+
+### What CI catches automatically
-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.
+- **New component without docs** → smoke test skips it with a message (not a failure)
+- **New CLI `--json` type without API coverage** → parity test flags it as a coverage gap
+- **API and CLI returning different data** → parity test fails with both payloads shown
+- **Invalid JSON envelope shape** → json smoke test fails
+- **Type mismatches** → `tsconfig.json-api.json` typecheck fails
---
@@ -278,21 +346,22 @@ Both paths run identical code. The CLI handler just adds argument parsing and ou
```
src/
api/ # Programmatic API (exported as @xds/cli/api)
- index.mjs # barrel: component, docs, discover, XDSError
+ index.mjs # barrel: component, docs, discover, template, XDSError
component.mjs # component(name?, opts?) → { type, data }
docs.mjs # docs(topic?, section?, opts?) → { type, data }
discover.mjs # discover(query?, opts?) → { type, data }
+ template.mjs # template(name?, opts?) → { type, data }
error.mjs # XDSError class (carries .suggestions)
commands/ # CLI wrappers (thin: parse args → call API → format output)
- component/index.mjs # registerComponent(program) — calls api/component.mjs
- docs.mjs # registerDocs(program) — calls api/docs.mjs
- discover.mjs # registerDiscover(program) — calls api/discover.mjs
- template.mjs # side-effect command (copies files)
- swizzle.mjs # side-effect command (copies + rewrites)
- build-theme.mjs # side-effect command (compiles theme)
- upgrade.mjs # side-effect command (runs codemods)
- gap-report.mjs # side-effect command (files issues)
- init.mjs # interactive only (no --json)
+ component/index.mjs # calls api/component.mjs
+ docs.mjs # calls api/docs.mjs
+ discover.mjs # calls api/discover.mjs
+ template.mjs # calls api/template.mjs
+ swizzle.mjs # CLI-only (side-effect: copies + rewrites imports)
+ build-theme.mjs # CLI-only (side-effect: compiles theme to CSS)
+ upgrade.mjs # CLI-only (side-effect: runs codemods)
+ gap-report.mjs # CLI-only (side-effect: files GitHub issues)
+ init.mjs # CLI-only (interactive prompts)
lib/
json.mjs # jsonOut(type, data), jsonError(msg) — internal
parse.mjs # parseResponse, isError, assertResponse — consumer
diff --git a/packages/cli/src/api/index.mjs b/packages/cli/src/api/index.mjs
index f32f6bdd27..d3c88ff003 100644
--- a/packages/cli/src/api/index.mjs
+++ b/packages/cli/src/api/index.mjs
@@ -17,4 +17,5 @@
export {component} from './component.mjs';
export {docs} from './docs.mjs';
export {discover} from './discover.mjs';
+export {template} from './template.mjs';
export {XDSError} from './error.mjs';
diff --git a/packages/cli/src/api/template.mjs b/packages/cli/src/api/template.mjs
new file mode 100644
index 0000000000..7c8e1029bd
--- /dev/null
+++ b/packages/cli/src/api/template.mjs
@@ -0,0 +1,272 @@
+/**
+ * @file Programmatic API for the template command.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {CLI_ROOT} from '../utils/paths.mjs';
+import {XDSError} from './error.mjs';
+
+const TEMPLATES_DIR = path.join(CLI_ROOT, 'templates');
+
+async function loadTemplateDoc(templateDir) {
+ const docPath = path.join(templateDir, 'template.doc.mjs');
+ if (!fs.existsSync(docPath)) return null;
+ const docModule = await import(`file://${docPath}`);
+ return docModule.doc;
+}
+
+export {discoverAll as discoverTemplates};
+
+export function listTemplates() {
+ if (!fs.existsSync(TEMPLATES_DIR)) return [];
+ return fs
+ .readdirSync(TEMPLATES_DIR, {withFileTypes: true})
+ .filter(e => e.isDirectory())
+ .map(e => e.name)
+ .sort();
+}
+
+async function discoverAll() {
+ if (!fs.existsSync(TEMPLATES_DIR)) return [];
+ const dirs = fs
+ .readdirSync(TEMPLATES_DIR, {withFileTypes: true})
+ .filter(e => e.isDirectory())
+ .sort((a, b) => a.name.localeCompare(b.name));
+
+ const templates = [];
+ for (const dir of dirs) {
+ const doc = await loadTemplateDoc(path.join(TEMPLATES_DIR, dir.name));
+ templates.push({
+ dirName: dir.name,
+ name: doc?.name || dir.name,
+ description: doc?.description || '',
+ isReady: doc?.isReady ?? true,
+ });
+ }
+ return templates;
+}
+
+const UBIQUITOUS = new Set([
+ 'Text', 'Heading', 'Button', 'HStack', 'VStack', 'Link',
+ 'StackItem', 'Icon',
+]);
+
+function extractComponents(pagePath) {
+ const src = fs.readFileSync(pagePath, 'utf-8');
+ return [...new Set(
+ (src.match(/XDS[A-Z]\w+/g) || [])
+ .map(n => n.replace(/^XDS/, ''))
+ .filter(n => !['Theme', 'ThemeProvider'].includes(n))
+ .filter(n => !UBIQUITOUS.has(n))
+ .map(n => n.replace(/(Item|Section|Header|Content|Footer|Panel|Heading|CollapseButton|Column|Sortable|Selection|Group|Source)$/, ''))
+ .filter(Boolean),
+ )].sort();
+}
+
+const STRUCTURAL = new Set([
+ 'AppShell', 'Layout', 'LayoutHeader', 'LayoutContent', 'LayoutPanel',
+ 'LayoutFooter', 'Card', 'Section', 'Grid', 'GridSpan', 'List',
+ 'Table', 'TabList', 'Toolbar', 'SideNav', 'TopNav', 'Dialog',
+ 'FormLayout', 'Center',
+]);
+
+function extractSkeleton(source) {
+ const lines = source.split('\n');
+ const out = [];
+ let depth = 0;
+ let capturing = false;
+ let inDefaultExport = false;
+ const MAX_LINES = 35;
+ const depthStack = [];
+
+ for (let i = 0; i < lines.length; i++) {
+ const t = lines[i].trim();
+
+ if (t.match(/^export\s+default\s+function/)) { inDefaultExport = true; continue; }
+ if (inDefaultExport && t.match(/^return\s*\(/)) { capturing = true; continue; }
+ if (!capturing) continue;
+ if (out.length >= MAX_LINES) {
+ if (!out[out.length - 1]?.includes('...')) out.push(' '.repeat(depth) + '...');
+ continue;
+ }
+
+ const openMatch = t.match(/^<(XDS\w+)/);
+ if (openMatch && !t.startsWith('</')) {
+ const comp = openMatch[1].replace(/^XDS/, '');
+ let tagText = '';
+ for (let j = i; j < Math.min(i + 12, lines.length); j++) {
+ tagText += ' ' + lines[j];
+ if (lines[j].includes('>')) break;
+ }
+
+ const props = [];
+ const propRegex = /\b(padding|contentPadding|gap|rowGap|columnGap|columns|minChildWidth|hasDivider|defaultHasDividers|variant|density|role|height|width|maxWidth)\s*[=]\s*\{?\s*['"]?([^}'"\s,/>]+)/g;
+ let m;
+ while ((m = propRegex.exec(tagText)) !== null) {
+ const val = m[2];
+ if (val === 'true') props.push(m[1]);
+ else if (/^\d+$/.test(val)) props.push(`${m[1]}={${val}}`);
+ else props.push(`${m[1]}="${val}"`);
+ }
+
+ const hasSpatialProps = props.length > 0;
+ const propStr = hasSpatialProps ? ' ' + props.join(' ') : '';
+ const isVStack = comp === 'VStack' || comp === 'HStack';
+ const isSelfClosing = tagText.match(new RegExp('<' + openMatch[1] + '[^>]*/>', 's'));
+
+ if (isVStack && !hasSpatialProps) continue;
+
+ if (isSelfClosing) {
+ out.push(' '.repeat(depth) + `<${comp}${propStr} />`);
+ } else if (STRUCTURAL.has(comp) || (isVStack && hasSpatialProps)) {
+ out.push(' '.repeat(depth) + `<${comp}${propStr}>`);
+ depthStack.push(comp);
+ depth++;
+ } else {
+ out.push(' '.repeat(depth) + `<${comp}${propStr} />`);
+ }
+ continue;
+ }
+
+ const closeMatch = t.match(/^<\/(XDS\w+)>/);
+ if (closeMatch) {
+ const comp = closeMatch[1].replace(/^XDS/, '');
+ if (depthStack.length > 0 && depthStack[depthStack.length - 1] === comp) {
+ depthStack.pop();
+ depth = Math.max(0, depth - 1);
+ out.push(' '.repeat(depth) + `</${comp}>`);
+ }
+ continue;
+ }
+
+ const slotMatch = t.match(/^(header|content|footer|start|end|sideNav|topNav)\s*=\s*\{/);
+ if (slotMatch) {
+ out.push(' '.repeat(depth) + `/* ${slotMatch[1]}: */`);
+ continue;
+ }
+
+ if (t.startsWith('<div') && (t.includes('padding') || t.includes('maxWidth') || t.includes('gap:'))) {
+ const styleProps = [];
+ const divText = lines.slice(i, Math.min(i + 5, lines.length)).join(' ');
+ const pp = divText.match(/padding[^:]*:\s*['"]?([^'"},)]+)/);
+ const mw = divText.match(/maxWidth:\s*(\d+)/);
+ const gp = divText.match(/gap:\s*(\d+)/);
+ const mg = divText.match(/margin:\s*['"]([^'"]+)['"]/);
+ const mi = divText.match(/marginInline:\s*['"]([^'"]+)['"]/);
+ if (pp) styleProps.push(`padding: ${pp[1].trim()}`);
+ if (mw) styleProps.push(`maxWidth: ${mw[1]}`);
+ if (gp) styleProps.push(`gap: ${gp[1]}`);
+ if (mg) styleProps.push(`margin: ${mg[1]}`);
+ if (mi) styleProps.push(`marginInline: ${mi[1]}`);
+ if (styleProps.length > 0) {
+ out.push(' '.repeat(depth) + `/* div: ${styleProps.join(', ')} */`);
+ }
+ }
+ }
+
+ return out.filter(l => l.trim()).join('\n');
+}
+
+/**
+ * @param {string} [name]
+ * @param {object} [options]
+ * @param {string} [options.targetPath]
+ * @param {boolean} [options.list]
+ * @param {boolean} [options.skeleton]
+ * @param {boolean} [options.show]
+ * @param {string} [options.cwd]
+ * @returns {Promise<{type: string, data: unknown}>}
+ */
+export async function template(name, options = {}) {
+ const {list = false, skeleton = false, show = false, targetPath, cwd = process.cwd()} = options;
+ const templates = await discoverAll();
+ const templateNames = templates.map(t => t.dirName);
+
+ if (list || (!name && !skeleton)) {
+ return {
+ type: 'template.list',
+ data: templates.map(t => ({
+ name: t.dirName,
+ description: t.description,
+ isReady: t.isReady,
+ })),
+ };
+ }
+
+ if (name && !templateNames.includes(name)) {
+ throw new XDSError(
+ `Unknown template "${name}"`,
+ templateNames.map(n => ({name: n, reason: 'available template'})),
+ );
+ }
+
+ if (skeleton) {
+ if (!name) {
+ throw new XDSError(
+ 'Specify a template name for --skeleton',
+ templateNames.map(n => ({name: n, reason: 'available template'})),
+ );
+ }
+ const pagePath = path.join(TEMPLATES_DIR, name, 'page.tsx');
+ if (!fs.existsSync(pagePath)) {
+ throw new XDSError(`No page.tsx found for template "${name}"`);
+ }
+ const src = fs.readFileSync(pagePath, 'utf-8');
+ const doc = await loadTemplateDoc(path.join(TEMPLATES_DIR, name));
+ return {
+ type: 'template.skeleton',
+ data: {
+ template: name,
+ description: doc?.description || '',
+ components: extractComponents(pagePath),
+ skeleton: extractSkeleton(src),
+ },
+ };
+ }
+
+ const templateDir = path.join(TEMPLATES_DIR, name);
+ const doc = await loadTemplateDoc(templateDir);
+
+ // Show mode: return file contents without writing to disk
+ if (show || !targetPath) {
+ const files = fs.readdirSync(templateDir);
+ const fileContents = {};
+ for (const file of files) {
+ if (file === 'template.doc.mjs') continue;
+ const srcPath = path.join(templateDir, file);
+ if (!fs.statSync(srcPath).isFile()) continue;
+ fileContents[file] = fs.readFileSync(srcPath, 'utf-8');
+ }
+ return {
+ type: 'template.show',
+ data: {
+ template: name,
+ description: doc?.description || '',
+ components: extractComponents(path.join(templateDir, 'page.tsx')),
+ files: fileContents,
+ },
+ };
+ }
+
+ // Copy mode: write files to disk
+ const outputDir = path.resolve(cwd, targetPath);
+ fs.mkdirSync(outputDir, {recursive: true});
+
+ const files = fs.readdirSync(templateDir);
+ let copied = 0;
+
+ for (const file of files) {
+ if (file === 'template.doc.mjs') continue;
+ const srcPath = path.join(templateDir, file);
+ if (!fs.statSync(srcPath).isFile()) continue;
+ fs.copyFileSync(srcPath, path.join(outputDir, file));
+ copied++;
+ }
+
+ const relOutput = path.relative(cwd, outputDir);
+ return {
+ type: 'template.copy',
+ data: {template: name, outputDir: relOutput, filesCopied: copied},
+ };
+}
diff --git a/packages/cli/src/commands/template.mjs b/packages/cli/src/commands/template.mjs
index 1e89706487..57a109689f 100644
--- a/packages/cli/src/commands/template.mjs
+++ b/packages/cli/src/commands/template.mjs
@@ -1,321 +1,77 @@
/**
- * @file template command — Inject page templates
- *
- * Copies template files from packages/cli/templates/{name}/ to a target path.
- * Template metadata comes from template.doc.mjs files (TemplateDoc type).
- * Templates without a doc file fall back to directory name only.
- *
- * --list: Show all templates with component compositions
- * --skeleton: Show layout skeleton with spatial annotations (padding, gap)
+ * @file template command — thin CLI wrapper around api/template.mjs
*/
-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';
+import {template as templateApi} from '../api/template.mjs';
-// ── Template discovery ───────────────────────────────────────────────
-
-async function loadTemplateDoc(templateDir) {
- const docPath = path.join(templateDir, 'template.doc.mjs');
- if (!fs.existsSync(docPath)) return null;
- const docModule = await import(`file://${docPath}`);
- return docModule.doc;
-}
-
-export async function discoverTemplates() {
- const templatesDir = path.join(CLI_ROOT, 'templates');
- if (!fs.existsSync(templatesDir)) return [];
-
- const dirs = fs
- .readdirSync(templatesDir, {withFileTypes: true})
- .filter(e => e.isDirectory())
- .sort((a, b) => a.name.localeCompare(b.name));
-
- const templates = [];
- for (const dir of dirs) {
- const doc = await loadTemplateDoc(path.join(templatesDir, dir.name));
- templates.push({
- dirName: dir.name,
- name: doc?.name || dir.name,
- description: doc?.description || '',
- isReady: doc?.isReady ?? true,
- });
- }
- return templates;
-}
-
-export function listTemplates() {
- const templatesDir = path.join(CLI_ROOT, 'templates');
- if (!fs.existsSync(templatesDir)) return [];
- return fs
- .readdirSync(templatesDir, {withFileTypes: true})
- .filter(e => e.isDirectory())
- .map(e => e.name)
- .sort();
-}
-
-// ── Component extraction ─────────────────────────────────────────────
-
-/**
- * Extract distinguishing XDS component names from a template's page.tsx.
- * Filters out ubiquitous components (Text, Button, HStack, etc.) to show
- * only the structural components that define the template's composition.
- */
-function extractComponents(pagePath) {
- const src = fs.readFileSync(pagePath, 'utf-8');
- const UBIQUITOUS = new Set([
- 'Text', 'Heading', 'Button', 'HStack', 'VStack', 'Link',
- 'StackItem', 'Icon',
- ]);
- return [...new Set(
- (src.match(/XDS[A-Z]\w+/g) || [])
- .map(n => n.replace(/^XDS/, ''))
- .filter(n => !['Theme', 'ThemeProvider'].includes(n))
- .filter(n => !UBIQUITOUS.has(n))
- .map(n => n.replace(/(Item|Section|Header|Content|Footer|Panel|Heading|CollapseButton|Column|Sortable|Selection|Group|Source)$/, ''))
- .filter(Boolean),
- )].sort();
-}
-
-// ── Skeleton extraction ──────────────────────────────────────────────
-
-/**
- * Extract a layout skeleton from template source code.
- * Shows the XDS component nesting tree with spatial props
- * (padding, gap, contentPadding, hasDivider, maxWidth, etc.).
- *
- * Structural components (Layout, AppShell, Card, Grid, Section, List, Table,
- * TabList, Toolbar) are always shown with full nesting. Leaf content
- * components (Text, Heading, Button, Badge, etc.) are collapsed to single
- * lines to keep the skeleton focused on spatial structure.
- */
-function extractSkeleton(source) {
- const lines = source.split('\n');
- const out = [];
- let depth = 0;
- let capturing = false;
- let inDefaultExport = false;
- const MAX_LINES = 35;
-
- const STRUCTURAL = new Set([
- 'AppShell', 'Layout', 'LayoutHeader', 'LayoutContent', 'LayoutPanel',
- 'LayoutFooter', 'Card', 'Section', 'Grid', 'GridSpan', 'List',
- 'Table', 'TabList', 'Toolbar', 'SideNav', 'TopNav', 'Dialog',
- 'FormLayout', 'Center',
- ]);
-
- const depthStack = [];
-
- for (let i = 0; i < lines.length; i++) {
- const t = lines[i].trim();
-
- if (t.match(/^export\s+default\s+function/)) {
- inDefaultExport = true;
- continue;
- }
- if (inDefaultExport && t.match(/^return\s*\(/)) {
- capturing = true;
- continue;
- }
- if (!capturing) continue;
- if (out.length >= MAX_LINES) {
- if (!out[out.length - 1]?.includes('...')) out.push(' '.repeat(depth) + '...');
- continue;
- }
-
- // XDS opening tag
- const openMatch = t.match(/^<(XDS\w+)/);
- if (openMatch && !t.startsWith('</')) {
- const comp = openMatch[1].replace(/^XDS/, '');
- const isStructural = STRUCTURAL.has(comp);
-
- // Gather spatial props
- let tagText = '';
- for (let j = i; j < Math.min(i + 12, lines.length); j++) {
- tagText += ' ' + lines[j];
- if (lines[j].includes('>')) break;
- }
-
- const props = [];
- const propRegex = /\b(padding|contentPadding|gap|rowGap|columnGap|columns|minChildWidth|hasDivider|defaultHasDividers|variant|density|role|height|width|maxWidth)\s*[=]\s*\{?\s*['"]?([^}'"\s,/>]+)/g;
- let m;
- while ((m = propRegex.exec(tagText)) !== null) {
- const val = m[2];
- if (val === 'true') props.push(m[1]);
- else if (/^\d+$/.test(val)) props.push(`${m[1]}={${val}}`);
- else props.push(`${m[1]}="${val}"`);
- }
-
- const hasSpatialProps = props.length > 0;
- const propStr = hasSpatialProps ? ' ' + props.join(' ') : '';
- const isVStack = comp === 'VStack' || comp === 'HStack';
- const isSelfClosing = tagText.match(new RegExp('<' + openMatch[1] + '[^>]*/>', 's'));
-
- // VStack/HStack: only show if they have gap props
- if (isVStack && !hasSpatialProps) continue;
-
- if (isSelfClosing) {
- out.push(' '.repeat(depth) + `<${comp}${propStr} />`);
- } else if (isStructural || (isVStack && hasSpatialProps)) {
- out.push(' '.repeat(depth) + `<${comp}${propStr}>`);
- depthStack.push(comp);
- depth++;
- } else {
- out.push(' '.repeat(depth) + `<${comp}${propStr} />`);
- }
- continue;
- }
-
- // Closing tag
- const closeMatch = t.match(/^<\/(XDS\w+)>/);
- if (closeMatch) {
- const comp = closeMatch[1].replace(/^XDS/, '');
- if (depthStack.length > 0 && depthStack[depthStack.length - 1] === comp) {
- depthStack.pop();
- depth = Math.max(0, depth - 1);
- out.push(' '.repeat(depth) + `</${comp}>`);
- }
- continue;
- }
-
- // Slot props
- const slotMatch = t.match(/^(header|content|footer|start|end|sideNav|topNav)\s*=\s*\{/);
- if (slotMatch) {
- out.push(' '.repeat(depth) + `/* ${slotMatch[1]}: */`);
- continue;
- }
-
- // Wrapper divs with spatial styles
- if (t.startsWith('<div') && (t.includes('padding') || t.includes('maxWidth') || t.includes('gap:'))) {
- const styleProps = [];
- const divText = lines.slice(i, Math.min(i + 5, lines.length)).join(' ');
- const pp = divText.match(/padding[^:]*:\s*['"]?([^'"},)]+)/);
- const mw = divText.match(/maxWidth:\s*(\d+)/);
- const gp = divText.match(/gap:\s*(\d+)/);
- const mg = divText.match(/margin:\s*['"]([^'"]+)['"]/);
- const mi = divText.match(/marginInline:\s*['"]([^'"]+)['"]/);
- if (pp) styleProps.push(`padding: ${pp[1].trim()}`);
- if (mw) styleProps.push(`maxWidth: ${mw[1]}`);
- if (gp) styleProps.push(`gap: ${gp[1]}`);
- if (mg) styleProps.push(`margin: ${mg[1]}`);
- if (mi) styleProps.push(`marginInline: ${mi[1]}`);
- if (styleProps.length > 0) {
- out.push(' '.repeat(depth) + `/* div: ${styleProps.join(', ')} */`);
- }
- }
- }
-
- return out.filter(l => l.trim()).join('\n');
-}
-
-// ── Command ──────────────────────────────────────────────────────────
+export {discoverTemplates, listTemplates} from '../api/template.mjs';
export function registerTemplate(program) {
program
.command('template [name] [path]')
.description('Inject a page template')
.option('--list', 'List available templates with component compositions')
- .option(
- '--skeleton',
- 'Show layout skeleton with spatial annotations (padding, gap, nesting)',
- )
+ .option('--skeleton', 'Show layout skeleton with spatial annotations (padding, gap, nesting)')
.action(async (name, targetPath, options) => {
- const templatesDir = path.join(CLI_ROOT, 'templates');
- const templates = await discoverTemplates();
- const templateNames = templates.map(t => t.dirName);
const json = program.opts().json || false;
- if (options.list || (!name && !options.skeleton)) {
- if (json) {
- return jsonOut('template.list', templates.map(t => ({
- name: t.dirName,
- description: t.description,
- isReady: t.isReady,
- })));
+ let result;
+ try {
+ result = await templateApi(name, {
+ list: options.list,
+ skeleton: options.skeleton,
+ targetPath,
+ cwd: process.cwd(),
+ });
+ } catch (e) {
+ if (json) return jsonError(e.message, e.suggestions);
+ console.error(`Error: ${e.message}`);
+ if (e.suggestions?.length) {
+ console.error(`Available: ${e.suggestions.map(s => s.name).join(', ')}`);
}
- console.log('\nAvailable templates:\n');
- for (const t of templates) {
- const status = t.isReady ? '' : ' (WIP)';
- const pagePath = path.join(templatesDir, t.dirName, 'page.tsx');
- const comps = fs.existsSync(pagePath)
- ? extractComponents(pagePath)
- : [];
- const compStr =
- comps.length > 0 ? ` [${comps.join(', ')}]` : '';
-
- console.log(` ${t.dirName}${status}`);
- if (t.description) console.log(` ${t.description}`);
- if (compStr) console.log(` ${compStr}`);
- }
- console.log('\nUsage:');
- console.log(' xds template <name> [target-path] Scaffold page');
- console.log(
- ' xds template <name> --skeleton Layout reference\n',
- );
- return;
- }
-
- 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);
}
- // --skeleton: show layout skeleton for a specific template
- if (options.skeleton) {
- if (!name) {
- console.error(
- 'Error: Specify a template name. Usage: xds template <name> --skeleton',
- );
- console.error(`Available: ${templateNames.join(', ')}`);
- process.exit(1);
+ if (json) return jsonOut(result.type, result.data);
+
+ switch (result.type) {
+ case 'template.list': {
+ console.log('\nAvailable templates:\n');
+ for (const t of result.data) {
+ const status = t.isReady ? '' : ' (WIP)';
+ console.log(` ${t.name}${status}`);
+ if (t.description) console.log(` ${t.description}`);
+ }
+ console.log('\nUsage:');
+ console.log(' xds template <name> [target-path] Scaffold page');
+ console.log(' xds template <name> --skeleton Layout reference\n');
+ break;
}
- const pagePath = path.join(templatesDir, name, 'page.tsx');
- if (!fs.existsSync(pagePath)) {
- console.error(`Error: No page.tsx found for template "${name}".`);
- process.exit(1);
+ 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('');
+ break;
}
- const src = fs.readFileSync(pagePath, 'utf-8');
- const skeleton = extractSkeleton(src);
- const comps = extractComponents(pagePath);
-
- const doc = await loadTemplateDoc(path.join(templatesDir, name));
- const desc = doc?.description || '';
-
- console.log(`\n# ${name}${desc ? ' — ' + desc : ''}`);
- console.log(`# Components: ${comps.join(', ')}\n`);
- console.log(skeleton);
- console.log('');
- return;
- }
-
- // Default: scaffold the template
- const outputDir = path.resolve(
- process.cwd(),
- targetPath || `./src/pages/${name}`,
- );
- const templateDir = path.join(templatesDir, name);
-
- fs.mkdirSync(outputDir, {recursive: true});
-
- const files = fs.readdirSync(templateDir);
- let copied = 0;
+ case 'template.show': {
+ for (const [filename, content] of Object.entries(result.data.files)) {
+ console.log(`// ${filename}`);
+ console.log(content);
+ }
+ break;
+ }
- for (const file of files) {
- if (file === 'template.doc.mjs') continue;
- const srcPath = path.join(templateDir, file);
- const stat = fs.statSync(srcPath);
- if (!stat.isFile()) continue;
- fs.copyFileSync(srcPath, path.join(outputDir, file));
- copied++;
+ case 'template.copy': {
+ console.log(`\n✓ Copied ${result.data.filesCopied} template files to ${result.data.outputDir}/\n`);
+ break;
+ }
}
-
- 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/types/api.d.ts b/packages/cli/src/types/api.d.ts
index 0b8cd7b44d..b3eb4afff0 100644
--- a/packages/cli/src/types/api.d.ts
+++ b/packages/cli/src/types/api.d.ts
@@ -23,6 +23,7 @@ import type {
DiscoverDetailDocResponse,
DiscoverSearchResponse,
} from './discover';
+import type {TemplateListResponse, TemplateCopyResponse} from './template';
/** Structured API error with optional suggestions. */
export declare class XDSError extends Error {
@@ -96,3 +97,18 @@ export declare function discover(
query?: string,
options?: DiscoverOptions,
): Promise<DiscoverResult>;
+
+// ── Template ─────────────────────────────────────────────────────────
+
+export interface TemplateOptions {
+ list?: boolean;
+ targetPath?: string;
+ cwd?: string;
+}
+
+type TemplateResult = TemplateListResponse | TemplateCopyResponse;
+
+export declare function template(
+ name?: string,
+ options?: TemplateOptions,
+): Promise<TemplateResult>;