Skip to content

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

TypeScript

feat(docs): surface @example JSDoc blocks in docs.mjs (#1817)

Cindy Zhang7ed653db2d06
diff --git a/internal/vibe-tests/README.md b/internal/vibe-tests/README.md
index 3e051599d0..15435df8fa 100644
--- a/internal/vibe-tests/README.md
+++ b/internal/vibe-tests/README.md
@@ -103,8 +103,7 @@ Before any test run, review the generated task prompts:
```bash
# Generate an iteration without running it
-node internal/vibe-tests/src/setup-iteration.mjs --sample 3 --target xds
-node internal/vibe-tests/src/setup-iteration.mjs --sample 3 --target baseline
+node internal/vibe-tests/src/setup-nightly.mjs --sample 3
# Read the task files and compare:
# - Are the prompts identical (same task text)?
@@ -133,7 +132,6 @@ These are intentional and documented — they slightly favor baseline, making XD
internal/vibe-tests/
├── test-sets/ # Prompt batteries (JSON)
├── src/ # Runner scripts and evaluation
-│ ├── setup-iteration.mjs # Single-target iteration setup
│ ├── setup-nightly.mjs # 4-target nightly setup
│ ├── universal-eval.ts # Static analysis scoring (5 dimensions)
│ ├── universal-aggregate.ts # Score aggregation
diff --git a/internal/vibe-tests/src/setup-iteration.mjs b/internal/vibe-tests/src/setup-iteration.mjs
deleted file mode 100644
index 7f73fe12e8..0000000000
--- a/internal/vibe-tests/src/setup-iteration.mjs
+++ /dev/null
@@ -1,254 +0,0 @@
-#!/usr/bin/env node
-/**
- * @file setup-iteration.mjs
- *
- * Sets up a vibe test iteration where XDS sub-agents use the CLI for doc retrieval.
- * Generates task manifests with instructions to run `npx xds component <Name>`
- * on the MacBook CLI node before generating code.
- *
- * Usage:
- * node internal/vibe-tests/src/setup-iteration.mjs --sample 10 --target xds
- * node internal/vibe-tests/src/setup-iteration.mjs --sample 10 --target xds-tailwind
- * node internal/vibe-tests/src/setup-iteration.mjs --sample 10 --target baseline
- * node internal/vibe-tests/src/setup-iteration.mjs --sample 10 --target html
- * node internal/vibe-tests/src/setup-iteration.mjs --sample 10 --target xds --prompts cwm-1,dd-2,fwc-6
- */
-
-import * as fs from 'node:fs';
-import * as path from 'node:path';
-import * as crypto from 'node:crypto';
-import { fileURLToPath } from 'node:url';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const VIBE_DIR = path.resolve(__dirname, '..');
-const RESULTS_DIR = path.join(VIBE_DIR, 'results');
-
-// ── Helpers ──────────────────────────────────────────────────────────
-
-function generateId() {
- return crypto.randomBytes(4).toString('hex');
-}
-
-function timestamp() {
- return new Date().toISOString();
-}
-
-function ensureDir(dir) {
- fs.mkdirSync(dir, { recursive: true });
-}
-
-function loadTestSet() {
- const testSetDir = path.join(VIBE_DIR, 'test-sets');
- const files = fs.readdirSync(testSetDir).filter(f => f.endsWith('.json'));
- const prompts = [];
- for (const file of files) {
- const data = JSON.parse(fs.readFileSync(path.join(testSetDir, file), 'utf-8'));
- if (Array.isArray(data)) {
- prompts.push(...data);
- } else if (data.prompts) {
- prompts.push(...data.prompts);
- }
- }
- return prompts;
-}
-
-function samplePrompts(prompts, n) {
- if (!n || n >= prompts.length) return prompts;
- const byCategory = {};
- for (const p of prompts) {
- if (!byCategory[p.category]) byCategory[p.category] = [];
- byCategory[p.category].push(p);
- }
- const categories = Object.keys(byCategory);
- const perCategory = Math.max(1, Math.floor(n / categories.length));
- const sampled = [];
- for (const cat of categories) {
- const shuffled = byCategory[cat].sort(() => Math.random() - 0.5);
- sampled.push(...shuffled.slice(0, perCategory));
- }
- while (sampled.length < n) {
- const remaining = prompts.filter(p => !sampled.includes(p));
- if (remaining.length === 0) break;
- sampled.push(remaining[Math.floor(Math.random() * remaining.length)]);
- }
- return sampled.slice(0, n);
-}
-
-// ── Task prompt templates ────────────────────────────────────────────
-
-function generateXdsTaskPrompt(prompt, iterDir) {
- return `You are generating React/TSX code using the XDS design system.
-
-Read the package README at ${path.resolve(VIBE_DIR, '../../packages/core/README.md')} for how to look up
-component docs. Use what you find there to discover the components you need.
-
-## Task
-
-${prompt.prompt}
-
-## Output
-
-Write the TSX code to: ${path.join(iterDir, 'results', `${prompt.id}.tsx`)}
-Write metadata to: ${path.join(iterDir, 'results', `${prompt.id}.json`)}
-
-Metadata: {"completedAt": "<ISO timestamp>", "docsRead": [<component names you looked up>]}
-Write ONLY valid TSX. No markdown fences, no explanation.`;
-}
-
-function generateBaselineTaskPrompt(prompt, iterDir) {
- return `You are generating React/TSX code using shadcn/ui components with Tailwind CSS.
-
-Read the README at ${path.join(VIBE_DIR, '.baseline', 'README.md')} for component guidance.
-The actual component sources are in ${path.join(VIBE_DIR, '.baseline', 'components', 'ui')}/.
-
-## Task
-
-${prompt.prompt}
-
-## Output
-
-Write the TSX code to: ${path.join(iterDir, 'results', `${prompt.id}.tsx`)}
-Write metadata to: ${path.join(iterDir, 'results', `${prompt.id}.json`)}
-
-Metadata: {"completedAt": "<ISO timestamp>", "docsRead": [<docs you read>]}
-Write ONLY valid TSX. No markdown fences, no explanation.`;
-}
-
-function generateXdsTailwindTaskPrompt(prompt, iterDir) {
- return `You are generating React/TSX code using the XDS design system with Tailwind CSS.
-
-Read the package README at ${path.resolve(VIBE_DIR, '../../packages/core/README.md')} for how to look up
-component docs. Use what you find there to discover the components you need.
-
-## Task
-
-${prompt.prompt}
-
-## Output
-
-Write the TSX code to: ${path.join(iterDir, 'results', `${prompt.id}.tsx`)}
-Write metadata to: ${path.join(iterDir, 'results', `${prompt.id}.json`)}
-
-Metadata: {"completedAt": "<ISO timestamp>", "docsRead": [<component names you looked up>]}
-Write ONLY valid TSX. No markdown fences, no explanation.`;
-}
-
-function generateHtmlTaskPrompt(prompt, iterDir) {
- return `You are generating React/TSX code using ONLY plain HTML elements and inline CSS.
-Do NOT use any component library. Use standard HTML elements (div, button, input, etc.)
-with inline styles or a styles object.
-
-## Task
-
-${prompt.prompt}
-
-## Output
-
-Write the TSX code to: ${path.join(iterDir, 'results', `${prompt.id}.tsx`)}
-Write metadata to: ${path.join(iterDir, 'results', `${prompt.id}.json`)}
-
-Metadata: {"completedAt": "<ISO timestamp>", "docsRead": []}
-Write ONLY valid TSX. No markdown fences, no explanation.`;
-}
-
-// ── Main ─────────────────────────────────────────────────────────────
-
-const args = process.argv.slice(2);
-const sampleIdx = args.indexOf('--sample');
-const sample = sampleIdx !== -1 ? parseInt(args[sampleIdx + 1]) : 10;
-const targetIdx = args.indexOf('--target');
-const target = targetIdx !== -1 ? args[targetIdx + 1] : 'xds';
-const promptsIdx = args.indexOf('--prompts');
-const promptFilter = promptsIdx !== -1 ? args[promptsIdx + 1].split(',') : null;
-
-console.log(`\n🧪 Setup Vibe Test Iteration`);
-console.log(` Target: ${target}, Sample: ${sample}`);
-if (target === 'xds') console.log(` Mode: CLI-retrieval (MacBook)\n`);
-else if (target === 'xds-tailwind') console.log(` Mode: CLI-retrieval + Tailwind (MacBook)\n`);
-else console.log(` Mode: ${target === 'baseline' ? 'baseline-docs' : 'no docs'}\n`);
-
-// 1. Load and filter/sample prompts
-const allPrompts = loadTestSet();
-let prompts;
-if (promptFilter) {
- prompts = allPrompts.filter(p => promptFilter.includes(p.id));
- console.log(`📋 Using ${prompts.length} specified prompts`);
-} else {
- prompts = samplePrompts(allPrompts, sample);
- console.log(`📋 Sampled ${prompts.length} prompts from ${allPrompts.length} total`);
-}
-
-// 2. Create iteration
-const iterationId = generateId();
-const iterDir = path.join(RESULTS_DIR, iterationId);
-ensureDir(iterDir);
-ensureDir(path.join(iterDir, 'results'));
-ensureDir(path.join(iterDir, 'tasks'));
-
-// 3. Generate manifest + task files
-const manifest = {
- iterationId,
- createdAt: timestamp(),
- config: {
- target,
- persona: 'naive',
- holdout: false,
- degradation: false,
- cliRetrieval: target === 'xds' || target === 'xds-tailwind',
- },
- prompts: prompts.map(p => ({
- id: p.id,
- category: p.category,
- prompt: p.prompt,
- expectedComponents: p.expectedComponents,
- status: 'pending',
- })),
-};
-
-fs.writeFileSync(path.join(iterDir, 'manifest.json'), JSON.stringify(manifest, null, 2));
-
-const generateTaskPrompt = target === 'xds' ? generateXdsTaskPrompt
- : target === 'xds-tailwind' ? generateXdsTailwindTaskPrompt
- : target === 'baseline' ? generateBaselineTaskPrompt
- : generateHtmlTaskPrompt;
-
-for (const prompt of prompts) {
- const taskPrompt = generateTaskPrompt(prompt, iterDir);
-
- const task = {
- promptId: prompt.id,
- category: prompt.category,
- prompt: prompt.prompt,
- expectedComponents: prompt.expectedComponents,
- target,
- persona: 'naive',
- taskPrompt,
- createdAt: timestamp(),
- };
-
- fs.writeFileSync(
- path.join(iterDir, 'tasks', `${prompt.id}.json`),
- JSON.stringify(task, null, 2)
- );
-}
-
-// 4. Output
-console.log(`\n✅ Iteration ${iterationId} ready`);
-console.log(` Dir: ${iterDir}`);
-console.log(` ${prompts.length} tasks created`);
-console.log(` Prompt IDs: ${prompts.map(p => p.id).join(',')}\n`);
-
-if (target === 'xds' || target === 'xds-tailwind') {
- console.log(`## Sub-agent spawn pattern (${target} with CLI retrieval):\n`);
- console.log(`Each agent needs: node "cli:MacBook-Pro-2" for CLI, workspace for file I/O\n`);
-} else if (target === 'baseline') {
- console.log(`## Sub-agent spawn pattern (baseline):\n`);
- console.log(`Agents read .baseline-docs/ and AGENTS.baseline.md\n`);
-} else {
- console.log(`## Sub-agent spawn pattern (HTML):\n`);
- console.log(`Agents use plain HTML/CSS — no design system docs\n`);
-}
-
-for (const prompt of prompts) {
- console.log(` Task: ${iterDir}/tasks/${prompt.id}.json`);
-}
diff --git a/packages/core/docs.mjs b/packages/core/docs.mjs
index b18ab5929c..bea5ce68ec 100644
--- a/packages/core/docs.mjs
+++ b/packages/core/docs.mjs
@@ -105,6 +105,32 @@ async function loadDoc(docPath) {
return mod.docs;
}
+// ── Example extraction ───────────────────────────────────────────────
+
+function extractExamples(docPath) {
+ const dir = path.dirname(docPath);
+ const examples = [];
+ try {
+ for (const file of fs.readdirSync(dir)) {
+ if (!file.endsWith('.tsx') || file.includes('.test')) continue;
+ const content = fs.readFileSync(path.join(dir, file), 'utf-8');
+ const regex = /@example\s*\n\s*\*\s*```[\w]*\n([\s\S]*?)```/g;
+ let match;
+ while ((match = regex.exec(content)) !== null) {
+ const code = match[1]
+ .split('\n')
+ .map(line => line.replace(/^\s*\*\s?/, ''))
+ .join('\n')
+ .trim();
+ if (code.includes('declare module')) continue;
+ if (code.includes('stylex.create') && !code.includes('XDS')) continue;
+ if (code.length > 0) examples.push(code);
+ }
+ }
+ } catch {}
+ return examples;
+}
+
// ── Formatting ───────────────────────────────────────────────────────
function formatPropsTable(props) {
@@ -118,11 +144,22 @@ function formatPropsTable(props) {
return lines.join('\n');
}
-function formatFull(docs) {
+function formatFull(docs, docPath) {
const s = [];
s.push(`# ${docs.name}\n`);
s.push((docs.usage?.description || '') + '\n');
+ // Examples from @example JSDoc blocks in component source
+ if (docPath) {
+ const examples = extractExamples(docPath);
+ if (examples.length) {
+ s.push('## Example\n');
+ s.push('```tsx');
+ s.push(examples.join('\n\n'));
+ s.push('```\n');
+ }
+ }
+
if (docs.usage?.anatomy?.length) {
s.push('## Anatomy\n');
s.push('| Element | Required | Description |');
@@ -225,7 +262,7 @@ if (isList) {
process.exit(1);
}
const docs = await loadDoc(docPath);
- console.log(formatFull(docs));
+ console.log(formatFull(docs, docPath));
} else {
console.log('Usage:');
console.log(' node docs.mjs <ComponentName> Show full component docs');