An open source design system that's fully customizable and agent ready
TypeScript
feat(docs): add README structure validation for CLI brief extractor (#350)
Cindy Zhangadf0f33c6634
diff --git a/docs/COMPONENT_README_GUIDE.md b/docs/COMPONENT_README_GUIDE.mdnew file mode 100644index 0000000000..5b16e89eec--- /dev/null+++ b/docs/COMPONENT_README_GUIDE.md@@ -0,0 +1,212 @@+# Component README Structure Guide++## Why This Matters++The XDS CLI's `extractBrief` function parses component READMEs to generate+LLM-friendly documentation. This documentation powers:++- **`xds component --brief-all`** — compact docs that LLMs use to discover and+ correctly use XDS components+- **Vibe tests** — automated evaluations of how well LLMs can build UIs with XDS+- **Developer experience** — `xds component <name>` shows formatted docs in the terminal++When a README doesn't follow the expected structure, the brief extractor can't+find props or examples. This means LLMs miss critical API details — for example,+`XDSText.type` (which controls the semantic HTML element) was invisible to LLMs+because the Text README used `### XDSText / XDSHeading` instead of separate+`### XDSText` and `### XDSHeading` sections.++## Validation++Run the validation script to check all READMEs:++```bash+yarn validate-readmes+```++This runs automatically in CI to catch issues before merge.++## Required Structure++### Single-Component Directories++For directories with one `XDS*.tsx` file (e.g., `Button/`, `Card/`, `Spinner/`):++```markdown+# ComponentName++Brief description of what the component does.++## Usage++\`\`\`tsx+import { XDSComponent } from '@xds/core/Component';++<XDSComponent variant="primary" />+\`\`\`++## Props++| Prop | Type | Default | Description |+| ------------ | ---------------------------- | ------------- | --------------------- |+| \`variant\` | \`'primary' \| 'secondary'\` | \`'primary'\` | Visual style |+| \`size\` | \`'sm' \| 'md' \| 'lg'\` | \`'md'\` | Size of the component |+| \`children\` | \`ReactNode\` | — | Content |+```++**Requirements:**++- A `## Props` section+- A markdown table inside `## Props` with at least one `| \`propName\`` row++### Multi-Component Directories++For directories with multiple `XDS*.tsx` files (e.g., `Text/`, `Stack/`, `Dialog/`):++```markdown+# ComponentGroup++Brief description of the component group.++### XDSComponentA++Description of ComponentA.++\`\`\`tsx+import { XDSComponentA } from '@xds/core/ComponentGroup';++<XDSComponentA requiredProp="value">Content</XDSComponentA>+\`\`\`++| Prop | Type | Default | Description |+| ---------------- | --------------------- | ------- | ---------------------- |+| \`requiredProp\` | \`'a' \| 'b' \| 'c'\` | — | Description (required) |+| \`children\` | \`ReactNode\` | — | Content |++### XDSComponentB++Description of ComponentB.++\`\`\`tsx+<XDSComponentB prop="value" />+\`\`\`++| Prop | Type | Default | Description |+| -------- | ---------- | ------- | ----------- |+| \`prop\` | \`string\` | — | Description |+```++**Requirements for each component:**++- A `### XDSComponentName` heading (exact match — no slashes, no extra text)+- A markdown props table within that section+- At least one `\`\`\`tsx`or`\`\`\`jsx`code block with`<XDS` JSX usage++## Common Mistakes++### ❌ Combined headings++```markdown+### XDSText / XDSHeading+```++The extractor looks for exact `### XDSText` and `### XDSHeading` matches.+Combined headings are invisible to it.++**Fix:** Split into separate sections:++```markdown+### XDSText++...props table and example...++### XDSHeading++...props table and example...+```++### ❌ Props table outside the component section++```markdown+### XDSDialog++Description of Dialog.++## Props++| Prop | Type | Default | Description |+```++The `## Props` heading breaks out of the `### XDSDialog` section (it's a+higher-level heading). The extractor can't associate the table with the component.++**Fix:** Put the table directly under the `###` heading without a separate+`## Props` section:++```markdown+### XDSDialog++Description of Dialog.++| Prop | Type | Default | Description |+```++### ❌ Missing code example++```markdown+### XDSButton++| Prop | Type | Default | Description |+| ----------- | ---------- | ------- | ------------ |+| \`variant\` | \`string\` | — | Visual style |+```++The extractor needs at least one code example to show LLMs how the component+is used.++**Fix:** Add a code block before or after the props table:++```markdown+### XDSButton++\`\`\`tsx+<XDSButton variant="primary" onClick={handleClick}>Save</XDSButton>+\`\`\`++| Prop | Type | Default | Description |+```++### ❌ Code example without XDS JSX++```markdown+\`\`\`tsx+const items = data.map(item => <li>{item.name}</li>);+\`\`\`+```++The extractor looks for `<XDS` in code blocks to find component usage examples.++**Fix:** Include actual component JSX:++```markdown+\`\`\`tsx+<XDSList>+{data.map(item => (+<XDSListItem key={item.id}>{item.name}</XDSListItem>+))}+</XDSList>+\`\`\`+```++## CLI Warnings++When running `xds component --brief` or `--brief-all`, the CLI will print+warnings to stderr if it can't extract complete information:++```+⚠️ No props found for XDSText. Ensure README has a '### XDSText' section with a props table.+⚠️ No code example found for XDSText.+```++These warnings help you identify and fix README structure issues during+development without polluting the brief output itself.diff --git a/package.json b/package.jsonindex 8eddf402db..9df40f4a01 100644--- a/package.json+++ b/package.json@@ -25,6 +25,7 @@"docs": "yarn workspace @xds/docs dev","sync:exports": "node scripts/sync-exports.js","sync:exports:check": "node scripts/sync-exports.js --check",+ "validate-readmes": "node scripts/validate-readmes.mjs","package:source": "node scripts/package-source.js","changeset": "changeset","version-packages": "changeset version",diff --git a/packages/cli/src/commands/component.mjs b/packages/cli/src/commands/component.mjsindex 76f09522f6..7db0037e90 100644--- a/packages/cli/src/commands/component.mjs+++ b/packages/cli/src/commands/component.mjs@@ -596,6 +596,16 @@ export function extractBrief(content, componentName, importHint) {output.push(` ${example}`);}+ // Warn on stderr when extraction is incomplete (doesn't pollute brief output)+ if (props.length === 0) {+ console.warn(+ `⚠️ No props found for ${displayName}. Ensure README has a '### ${displayName}' section with a props table.`,+ );+ }+ if (!example) {+ console.warn(`⚠️ No code example found for ${displayName}.`);+ }+return output.join('\n') + '\n';}diff --git a/scripts/validate-readmes.mjs b/scripts/validate-readmes.mjsnew file mode 100644index 0000000000..af8455c050--- /dev/null+++ b/scripts/validate-readmes.mjs@@ -0,0 +1,205 @@+#!/usr/bin/env node++/**+ * @file Validate component README structure for CLI brief extractor compatibility.+ *+ * The XDS CLI's `extractBrief` function parses READMEs to generate LLM-friendly+ * docs. It expects a specific structure:+ *+ * - Multi-component directories: `### XDSComponentName` subsection per component,+ * each with a props table and code example.+ * - Single-component directories: `## Props` section with a table.+ *+ * This script scans all packages/core/src/* directories and reports any READMEs+ * that don't follow the expected structure.+ *+ * Usage: node scripts/validate-readmes.mjs+ * Exit code: 0 if all pass, 1 if any issues found.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const ROOT = path.resolve(__dirname, '..');+const SRC_DIR = path.join(ROOT, 'packages', 'core', 'src');+const SKIP_DIRS = new Set(['hooks', 'utils', 'theme', '__tests__', 'node_modules']);++/**+ * Find all XDS*.tsx component files in a directory (non-recursive),+ * excluding test files and Context files.+ */+function findComponentFiles(dirPath) {+ if (!fs.existsSync(dirPath)) return [];+ return fs+ .readdirSync(dirPath)+ .filter(+ f =>+ /^XDS[A-Z]\w+\.tsx$/.test(f) &&+ !f.includes('.test') &&+ !f.includes('Context'),+ )+ .map(f => f.replace(/\.tsx$/, ''));+}++/**+ * Extract the content of a ### heading section from markdown lines.+ * Returns all lines from the heading until the next ### (or end of file).+ */+function extractSection(lines, heading) {+ const headingRe = new RegExp(`^###\\s+${escapeRegex(heading)}\\s*$`);+ let inSection = false;+ const sectionLines = [];++ for (const line of lines) {+ if (headingRe.test(line)) {+ inSection = true;+ continue;+ }+ if (inSection && /^###\s+/.test(line)) {+ break;+ }+ if (inSection) {+ sectionLines.push(line);+ }+ }++ return inSection ? sectionLines : null;+}++/**+ * Check if lines contain a markdown props table.+ * Looks for at least one row like `| \`propName\` |`+ */+function hasPropsTable(lines) {+ return lines.some(line => /^\|\s*`[a-zA-Z]/.test(line));+}++/**+ * Check if lines contain a code example with <XDS JSX.+ * Looks for ```tsx or ```jsx blocks containing <XDS.+ */+function hasCodeExample(lines) {+ let inCode = false;+ for (const line of lines) {+ if (/^```(?:tsx|jsx)/.test(line)) {+ inCode = true;+ continue;+ }+ if (inCode && line.startsWith('```')) {+ inCode = false;+ continue;+ }+ if (inCode && line.includes('<XDS')) {+ return true;+ }+ }+ return false;+}++function escapeRegex(str) {+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}++function validate() {+ const issues = [];+ const entries = fs.readdirSync(SRC_DIR, {withFileTypes: true});++ for (const entry of entries) {+ if (!entry.isDirectory() || SKIP_DIRS.has(entry.name)) continue;++ const dirPath = path.join(SRC_DIR, entry.name);+ const components = findComponentFiles(dirPath);+ if (components.length === 0) continue;++ const readmePath = path.join(dirPath, 'README.md');+ const relReadme = path.relative(ROOT, readmePath);++ if (!fs.existsSync(readmePath)) {+ issues.push(`${relReadme}: README.md is missing.`);+ continue;+ }++ const content = fs.readFileSync(readmePath, 'utf-8');+ const lines = content.split('\n');+ const isMultiComponent = components.length > 1;++ if (isMultiComponent) {+ // Multi-component: each component needs ### XDSComponentName+ for (const comp of components) {+ const section = extractSection(lines, comp);++ if (!section) {+ issues.push(+ `${relReadme}: Missing section \`### ${comp}\`. ` ++ `Each component needs its own ### heading for the CLI brief extractor to work.`,+ );+ continue;+ }++ if (!hasPropsTable(section)) {+ issues.push(+ `${relReadme}: Section \`### ${comp}\` has no props table. ` ++ `Add a markdown table with | Prop | Type | Default | Description | columns.`,+ );+ }++ if (!hasCodeExample(section)) {+ issues.push(+ `${relReadme}: Section \`### ${comp}\` has no code example. ` ++ `Add a \`\`\`tsx block with <XDS JSX usage.`,+ );+ }+ }+ } else {+ // Single-component: needs ## Props with a table+ const hasPropsSection = /^## Props/m.test(content);++ if (!hasPropsSection) {+ issues.push(+ `${relReadme}: Missing \`## Props\` section. ` ++ `Single-component READMEs need a ## Props heading with a props table.`,+ );+ } else {+ // Extract the ## Props section content+ let inProps = false;+ const propsLines = [];+ for (const line of lines) {+ if (/^## Props/.test(line)) {+ inProps = true;+ continue;+ }+ if (inProps && /^## /.test(line)) break;+ if (inProps) propsLines.push(line);+ }++ if (!hasPropsTable(propsLines)) {+ issues.push(+ `${relReadme}: \`## Props\` section has no props table. ` ++ `Add a markdown table with | Prop | Type | Default | Description | columns.`,+ );+ }+ }+ }+ }++ return issues;+}++// Run validation+const issues = validate();++if (issues.length > 0) {+ console.error(`\n❌ Found ${issues.length} README structure issue(s):\n`);+ for (const issue of issues) {+ console.error(` • ${issue}`);+ }+ console.error(+ `\nSee docs/COMPONENT_README_GUIDE.md for the expected structure.\n`,+ );+ process.exit(1);+} else {+ console.log('\n✅ All component READMEs follow the expected structure.\n');+ process.exit(0);+}