An open source design system that's fully customizable and agent ready
TypeScript
feat(docsite): build-time data extraction with tests (#1944)
Cindy Zhang759e0405c6a3
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 9ef9fa1a30..4533f93bf4 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -63,6 +63,9 @@ jobs:- run: yarn test+ - name: Docsite data extraction tests+ run: yarn workspace @xds/docsite generate && yarn workspace @xds/docsite test+# Build storybook + analyze components (parallel with test)# Uploads storybook preview and analysis artifacts for downstream jobsbuild:diff --git a/apps/docsite/.gitignore b/apps/docsite/.gitignoreindex 9fb346fb7d..0b1fda90cc 100644--- a/apps/docsite/.gitignore+++ b/apps/docsite/.gitignore@@ -1,2 +1,5 @@.nextnext-env.d.ts++# Auto-generated by scripts/generate-data.mjs+src/generated/diff --git a/apps/docsite/package.json b/apps/docsite/package.jsonindex 2fd70c01e6..4ffa6a4425 100644--- a/apps/docsite/package.json+++ b/apps/docsite/package.json@@ -3,14 +3,23 @@"version": "0.0.1","private": true,"scripts": {+ "generate": "node scripts/generate-data.mjs",+ "predev": "node scripts/generate-data.mjs","dev": "next dev",+ "prebuild": "node scripts/generate-data.mjs","build": "next build",- "start": "next start"+ "start": "next start",+ "test": "vitest run",+ "test:watch": "vitest"},"dependencies": {"@stylexjs/stylex": "^0.18.3",+ "@xds/cli": "*","@xds/core": "*",+ "@xds/theme-daily": "*","@xds/theme-default": "*",+ "@xds/theme-matcha": "*",+ "@xds/theme-neutral": "*","next": "^15.5.15","react": "^19.2.5","react-dom": "^19.2.5"@@ -23,7 +32,8 @@"@types/react": "^19.2.14","@types/react-dom": "^19.2.3","typescript": "^6.0.3",- "autoprefixer": "^10.4.0"+ "autoprefixer": "^10.4.0",+ "vitest": "^3.2.1"},"browserslist": ["last 1 Chrome version"diff --git a/apps/docsite/scripts/generate-data.mjs b/apps/docsite/scripts/generate-data.mjsnew file mode 100644index 0000000000..e7735248db--- /dev/null+++ b/apps/docsite/scripts/generate-data.mjs@@ -0,0 +1,465 @@+#!/usr/bin/env node++/**+ * @file generate-data.mjs+ *+ * Build-time data extraction for the XDS docsite.+ * Reads package.json, .doc.mjs, templates, and markdown files across the+ * monorepo and generates typed TypeScript registries in src/generated/.+ *+ * Run: node scripts/generate-data.mjs+ *+ * Generates:+ * - packageRegistry.ts — metadata for every distributable package+ * - componentRegistry.ts — component listings per package (from .doc.mjs)+ * - blockRegistry.ts — showcases + example blocks from CLI templates+ * - templateRegistry.ts — page-level templates from CLI templates+ * - docsRegistry.ts — long-form documentation topics from CLI docs/+ */++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 DOCSITE_ROOT = path.resolve(__dirname, '..');+const REPO_ROOT = path.resolve(DOCSITE_ROOT, '..', '..');+const OUT_DIR = path.join(DOCSITE_ROOT, 'src', 'generated');+const CLI_ROOT = path.join(REPO_ROOT, 'packages', 'cli');++fs.mkdirSync(OUT_DIR, {recursive: true});++// ── Helpers ────────────────────────────────────────────────────────────++function writeRegistry(filename, content) {+ const outPath = path.join(OUT_DIR, filename);+ fs.writeFileSync(outPath, content, 'utf-8');+ console.log(` wrote ${path.relative(REPO_ROOT, outPath)}`);+}++/** Extract group/description/hidden from .doc.mjs via regex (no dynamic import) */+const GROUP_RE = /(?:^|\n) {0,4}group:\s*['"]([^'"]+)['"]/;+const DESC_RE = /description:\s*\n?\s*['"`]([^'"`]{0,200})['"`]/;+const HIDDEN_RE = /(?:^|\n) {0,4}hidden:\s*true/;+const NAME_RE = /(?:^|\n) {0,4}name:\s*['"]([^'"]+)['"]/;+const KEYWORDS_RE = /keywords:\s*\[([^\]]*)\]/;++function readDocMeta(docPath) {+ try {+ const content = fs.readFileSync(docPath, 'utf-8');+ const groupMatch = GROUP_RE.exec(content);+ const descMatch = DESC_RE.exec(content);+ const nameMatch = NAME_RE.exec(content);+ const hidden = HIDDEN_RE.test(content);+ const kwMatch = KEYWORDS_RE.exec(content);+ const keywords = kwMatch+ ? [...kwMatch[1].matchAll(/['"]([^'"]+)['"]/g)].map(m => m[1])+ : [];+ return {+ group: groupMatch?.[1] ?? null,+ description: descMatch?.[1] ?? '',+ name: nameMatch?.[1] ?? null,+ hidden,+ keywords,+ };+ } catch {+ return {group: null, description: '', name: null, hidden: false, keywords: []};+ }+}++function findDocFilesRecursive(dir) {+ const results = [];+ if (!fs.existsSync(dir)) return results;+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ results.push(...findDocFilesRecursive(full));+ } else if (entry.name.endsWith('.doc.mjs')) {+ results.push(full);+ }+ }+ return results;+}++// ── Package discovery ──────────────────────────────────────────────────++/**+ * Auto-discover packages from the monorepo workspace globs.+ * Reads the root package.json "workspaces" field and expands globs.+ * Skips apps/* and internal/* — only surfaces packages/*.+ */+function discoverPackageDirs() {+ const rootPkg = JSON.parse(fs.readFileSync(path.join(REPO_ROOT, 'package.json'), 'utf-8'));+ const workspaces = rootPkg.workspaces || [];+ const dirs = [];++ for (const pattern of workspaces) {+ // Only include packages/*, not apps/* or internal/*+ if (!pattern.startsWith('packages')) continue;++ // Expand glob: packages/* or packages/themes/*+ const base = pattern.replace('/*', '');+ const baseDir = path.join(REPO_ROOT, base);+ if (!fs.existsSync(baseDir)) continue;++ for (const entry of fs.readdirSync(baseDir, {withFileTypes: true})) {+ if (!entry.isDirectory()) continue;+ const pkgJsonPath = path.join(baseDir, entry.name, 'package.json');+ if (fs.existsSync(pkgJsonPath)) {+ dirs.push(path.join(base, entry.name));+ }+ }+ }++ return dirs.sort();+}++// ── 1. Package Registry ────────────────────────────────────────────────++function generatePackageRegistry() {+ console.log('Generating package registry...');++ const packageDirs = discoverPackageDirs();++ const packages = packageDirs+ .map(dir => {+ const pkgPath = path.join(REPO_ROOT, dir, 'package.json');+ const raw = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));++ // Skip private packages+ if (raw.private === true) return null;++ const hasReadme = fs.existsSync(path.join(REPO_ROOT, dir, 'README.md'));+ const hasChangelog = fs.existsSync(path.join(REPO_ROOT, dir, 'CHANGELOG.md'));+ return {+ name: raw.name,+ displayName: raw.displayName || raw.name.replace('@xds/', '').replace('theme-', 'Theme: ').replace(/^\w/, c => c.toUpperCase()),+ version: raw.version,+ description: raw.description || '',+ packagePath: dir,+ hasReadme,+ hasChangelog,+ };+ })+ .filter(Boolean)+ .sort((a, b) => a.name.localeCompare(b.name));++ const content = `// Auto-generated by scripts/generate-data.mjs — do not edit++export interface PackageMeta {+ name: string;+ displayName: string;+ version: string;+ description: string;+ packagePath: string;+ hasReadme: boolean;+ hasChangelog: boolean;+}++export const packages: PackageMeta[] = ${JSON.stringify(packages, null, 2)};+`;+ writeRegistry('packageRegistry.ts', content);+ return packages;+}++// ── 2. Component Registry ──────────────────────────────────────────────++function generateComponentRegistry() {+ console.log('Generating component registry...');++ // Auto-discover component packages: any package with a src/ dir containing+ // subdirectories that have .doc.mjs files.+ const packageDirs = discoverPackageDirs();+ const componentPackages = [];++ for (const dir of packageDirs) {+ const srcDir = path.join(REPO_ROOT, dir, 'src');+ if (!fs.existsSync(srcDir)) continue;+ const pkgJson = JSON.parse(fs.readFileSync(path.join(REPO_ROOT, dir, 'package.json'), 'utf-8'));+ // Check if any file anywhere under src/ is a .doc.mjs+ const allDocFiles = findDocFilesRecursive(srcDir);+ if (allDocFiles.length > 0) {+ componentPackages.push({name: pkgJson.name, srcDir});+ }+ }++ // Only skip dirs that never contain doc files+ const SKIP_DIRS = new Set(['utils', '__tests__', 'node_modules']);+ const allComponents = {};+ let totalCount = 0;++ for (const pkg of componentPackages) {+ if (!fs.existsSync(pkg.srcDir)) continue;+ const components = [];++ for (const entry of fs.readdirSync(pkg.srcDir, {withFileTypes: true})) {+ if (!entry.isDirectory() || SKIP_DIRS.has(entry.name)) continue;++ const dirPath = path.join(pkg.srcDir, entry.name);++ // Collect ALL .doc.mjs files in this directory (not just the first)+ const docFiles = fs.readdirSync(dirPath).filter(f => f.endsWith('.doc.mjs'));+ if (docFiles.length === 0) continue;++ for (const docFileName of docFiles) {+ const docFile = path.join(dirPath, docFileName);+ const meta = readDocMeta(docFile);++ // Use docs.name as the canonical name, fall back to filename stem+ const fileNameStem = docFileName.replace('.doc.mjs', '').replace(/^XDS/, '');+ const name = meta.name || fileNameStem;++ components.push({+ name,+ directory: entry.name,+ group: meta.group,+ description: meta.description,+ keywords: meta.keywords,+ hidden: meta.hidden,+ });+ }+ }++ components.sort((a, b) => a.name.localeCompare(b.name));+ if (components.length > 0) {+ allComponents[pkg.name] = components;+ totalCount += components.length;+ }+ }++ const content = `// Auto-generated by scripts/generate-data.mjs — do not edit++export interface ComponentEntry {+ /** Canonical name from docs.name (e.g. 'Button', 'useClickableContainer') */+ name: string;+ /** Source directory containing this component (e.g. 'Button', 'hooks') */+ directory: string;+ /** Sidebar group from docs.group (e.g. 'Actions', 'Chat') */+ group: string | null;+ /** Short description (first ~200 chars of docs.usage.description) */+ description: string;+ /** Search keywords from docs.keywords */+ keywords: string[];+ /** Whether this component is marked hidden in its doc */+ hidden: boolean;+}++export const components: Record<string, ComponentEntry[]> = ${JSON.stringify(allComponents, null, 2)};++export const componentCount = ${totalCount};+`;+ writeRegistry('componentRegistry.ts', content);+ return {allComponents, totalCount};+}++// ── 3. Block Registry ──────────────────────────────────────────────────++async function generateBlockRegistry() {+ console.log('Generating block registry...');++ const BLOCKS_DIR = path.join(CLI_ROOT, 'templates', 'blocks');+ const docFiles = findDocFilesRecursive(BLOCKS_DIR);+ const blocks = [];++ for (const docPath of docFiles) {+ const basename = path.basename(docPath, '.doc.mjs');+ const tsxPath = path.join(path.dirname(docPath), basename + '.tsx');+ if (!fs.existsSync(tsxPath)) continue;++ const meta = readDocMeta(docPath);+ const relCategory = path.relative(BLOCKS_DIR, path.dirname(docPath));++ // Read isShowcase, aspectRatio, componentsUsed from the doc file+ let isShowcase = false;+ let aspectRatio = 1;+ let componentsUsed = [];+ try {+ const content = fs.readFileSync(docPath, 'utf-8');+ isShowcase = /isShowcase:\s*true/.test(content);+ const arMatch = content.match(/aspectRatio:\s*([\d.]+)\s*\/\s*([\d.]+)/);+ const arSingle = content.match(/aspectRatio:\s*([\d.]+)(?!\s*\/)/);+ if (arMatch) {+ aspectRatio = parseFloat(arMatch[1]) / parseFloat(arMatch[2]);+ } else if (arSingle) {+ aspectRatio = parseFloat(arSingle[1]);+ }+ const cuMatch = content.match(/componentsUsed:\s*\[([^\]]*)\]/);+ if (cuMatch) {+ componentsUsed = [...cuMatch[1].matchAll(/['"]([^'"]+)['"]/g)].map(m => m[1]);+ }+ } catch { /* ignore */ }++ blocks.push({+ dirName: basename,+ name: meta.name || basename,+ description: meta.description,+ isShowcase,+ aspectRatio,+ componentsUsed,+ category: relCategory,+ });+ }++ blocks.sort((a, b) => a.name.localeCompare(b.name));++ const showcaseCount = blocks.filter(b => b.isShowcase).length;++ const content = `// Auto-generated by scripts/generate-data.mjs — do not edit++export interface BlockEntry {+ dirName: string;+ name: string;+ description: string;+ isShowcase: boolean;+ aspectRatio: number;+ componentsUsed: string[];+ /** Category path, e.g. 'components/Button' */+ category: string;+}++export const blocks: BlockEntry[] = ${JSON.stringify(blocks, null, 2)};++export const blockCount = ${blocks.length};+export const showcaseCount = ${showcaseCount};+`;+ writeRegistry('blockRegistry.ts', content);+ return {blocks, blockCount: blocks.length, showcaseCount};+}++// ── 4. Template Registry ───────────────────────────────────────────────++async function generateTemplateRegistry() {+ console.log('Generating template registry...');++ const PAGES_DIR = path.join(CLI_ROOT, 'templates', 'pages');+ if (!fs.existsSync(PAGES_DIR)) {+ writeRegistry('templateRegistry.ts', `// Auto-generated — no templates found\nexport const templates = [];\nexport const templateCount = 0;\n`);+ return {templates: [], templateCount: 0};+ }++ const templates = [];+ const dirs = fs.readdirSync(PAGES_DIR, {withFileTypes: true}).filter(e => e.isDirectory());++ for (const dir of dirs) {+ const docPath = path.join(PAGES_DIR, dir.name, 'template.doc.mjs');+ if (!fs.existsSync(docPath)) continue;+ const pagePath = path.join(PAGES_DIR, dir.name, 'page.tsx');+ if (!fs.existsSync(pagePath)) continue;++ let doc;+ try {+ const mod = await import(fileURLToPath(new URL(`file://${docPath}`)).replace(/\\/g, '/'));+ doc = mod.doc;+ } catch {+ const meta = readDocMeta(docPath);+ doc = {name: meta.name || dir.name, description: meta.description, isReady: true};+ }++ templates.push({+ slug: dir.name,+ name: doc.name || dir.name,+ description: doc.description || '',+ isReady: doc.isReady ?? true,+ });+ }++ templates.sort((a, b) => a.name.localeCompare(b.name));++ const content = `// Auto-generated by scripts/generate-data.mjs — do not edit++export interface TemplateEntry {+ slug: string;+ name: string;+ description: string;+ isReady: boolean;+}++export const templates: TemplateEntry[] = ${JSON.stringify(templates, null, 2)};++export const templateCount = ${templates.length};+`;+ writeRegistry('templateRegistry.ts', content);+ return {templates, templateCount: templates.length};+}++// ── 5. Docs Registry ──────────────────────────────────────────────────++async function generateDocsRegistry() {+ console.log('Generating docs registry...');++ const DOCS_DIR = path.join(CLI_ROOT, 'docs');+ if (!fs.existsSync(DOCS_DIR)) {+ writeRegistry('docsRegistry.ts', `// Auto-generated — no docs found\nexport const docTopics = [];\nexport const docsCount = 0;\n`);+ return {docTopics: [], docsCount: 0};+ }++ const docTopics = [];++ for (const file of fs.readdirSync(DOCS_DIR)) {+ const match = file.match(/^([\w-]+)\.doc\.mjs$/);+ if (!match) continue;+ // Skip translations+ if (file.includes('.doc.zh.') || file.includes('.doc.dense.')) continue;++ const topic = match[1];+ const docPath = path.join(DOCS_DIR, file);++ let title = '';+ let description = '';+ try {+ const mod = await import(`file://${docPath}`);+ title = mod.docs?.title || '';+ description = mod.docs?.description || '';+ } catch {+ const meta = readDocMeta(docPath);+ description = meta.description;+ }++ docTopics.push({topic, title: title || topic, description});+ }++ docTopics.sort((a, b) => a.topic.localeCompare(b.topic));++ const content = `// Auto-generated by scripts/generate-data.mjs — do not edit++export interface DocTopic {+ /** URL-friendly slug derived from filename (e.g. 'getting-started') */+ topic: string;+ /** Display title from docs.title (e.g. 'Getting Started') */+ title: string;+ /** Short description */+ description: string;+}++export const docTopics: DocTopic[] = ${JSON.stringify(docTopics, null, 2)};++export const docsCount = ${docTopics.length};+`;+ writeRegistry('docsRegistry.ts', content);+ return {docTopics, docsCount: docTopics.length};+}++// ── Main ───────────────────────────────────────────────────────────────++async function main() {+ console.log('Generating docsite data...\n');++ const packages = generatePackageRegistry();+ const {totalCount: componentCount} = generateComponentRegistry();+ const {blockCount, showcaseCount} = await generateBlockRegistry();+ const {templateCount} = await generateTemplateRegistry();+ const {docsCount} = await generateDocsRegistry();++ console.log(`\nSummary:`);+ console.log(` ${packages.length} packages`);+ console.log(` ${componentCount} components`);+ console.log(` ${blockCount} blocks (${showcaseCount} showcases)`);+ console.log(` ${templateCount} templates`);+ console.log(` ${docsCount} doc topics`);+ console.log('Done.');+}++main().catch(err => {+ console.error(err);+ process.exit(1);+});diff --git a/apps/docsite/src/__tests__/data-extraction.test.ts b/apps/docsite/src/__tests__/data-extraction.test.tsnew file mode 100644index 0000000000..e8cdc2d14a--- /dev/null+++ b/apps/docsite/src/__tests__/data-extraction.test.ts@@ -0,0 +1,275 @@+/**+ * @file Data extraction tests for the docsite.+ *+ * Validates that the generated registries contain expected data.+ * Run: yarn workspace @xds/docsite test+ */++import {describe, it, expect} from 'vitest';+import {packages} from '../generated/packageRegistry';+import {components, componentCount} from '../generated/componentRegistry';+import {blocks, blockCount, showcaseCount} from '../generated/blockRegistry';+import {templates, templateCount} from '../generated/templateRegistry';+import {docTopics, docsCount} from '../generated/docsRegistry';++// ── Package Registry ───────────────────────────────────────────────────++describe('packageRegistry', () => {+ it('discovers all published packages (private packages excluded)', () => {+ const names = packages.map(p => p.name);+ expect(names).toContain('@xds/core');+ expect(names).toContain('@xds/cli');+ expect(names).toContain('@xds/theme-default');+ expect(names).toContain('@xds/theme-neutral');+ // Private packages should not appear+ expect(names).not.toContain('@xds/lab');+ expect(names).not.toContain('@xds/build');+ expect(names).not.toContain('@xds/theme-brutalist');+ expect(packages.length).toBeGreaterThanOrEqual(5);+ });++ it('each package has required fields', () => {+ for (const pkg of packages) {+ expect(pkg.name).toBeTruthy();+ expect(pkg.displayName).toBeTruthy();+ expect(pkg.version).toMatch(/^\d+\.\d+\.\d+/);+ expect(pkg.packagePath).toBeTruthy();+ expect(typeof pkg.hasReadme).toBe('boolean');+ expect(typeof pkg.hasChangelog).toBe('boolean');+ }+ });++ it('no duplicate package names', () => {+ const names = packages.map(p => p.name);+ expect(new Set(names).size).toBe(names.length);+ });+});++// ── Component Registry ─────────────────────────────────────────────────++describe('componentRegistry', () => {+ it('discovers components in @xds/core', () => {+ expect(components['@xds/core']).toBeDefined();+ expect(components['@xds/core'].length).toBeGreaterThan(50);+ });++ it('component count matches sum of all packages', () => {+ const sum = Object.values(components).reduce(+ (acc, list) => acc + list.length,+ 0,+ );+ expect(componentCount).toBe(sum);+ });++ it('components are scoped to their package', () => {+ for (const [pkgName, comps] of Object.entries(components)) {+ expect(pkgName).toMatch(/^@xds\//);+ expect(Array.isArray(comps)).toBe(true);+ for (const comp of comps) {+ expect(comp.name).toBeTruthy();+ expect(typeof comp.description).toBe('string');+ expect(typeof comp.directory).toBe('string');+ }+ }+ });++ it('known components are present', () => {+ const coreNames = components['@xds/core'].map(c => c.name);+ expect(coreNames).toContain('Button');+ expect(coreNames).toContain('Text');+ expect(coreNames).toContain('Card');+ expect(coreNames).toContain('Table');+ });++ it('name comes from docs.name, not directory name', () => {+ const core = components['@xds/core'];+ // CodeBlock dir has file XDSCodeBlock.doc.mjs with docs.name = 'CodeBlock'+ const codeBlock = core.find(c => c.name === 'CodeBlock');+ expect(codeBlock).toBeDefined();+ expect(codeBlock?.directory).toBe('CodeBlock');++ // hooks dir has multiple docs with names like 'useClickableContainer'+ const hookComponent = core.find(c => c.name === 'useClickableContainer');+ expect(hookComponent).toBeDefined();+ expect(hookComponent?.directory).toBe('hooks');+ });++ it('discovers hooks (not skipped)', () => {+ const core = components['@xds/core'];+ const hooks = core.filter(c => c.directory === 'hooks');+ expect(hooks.length).toBeGreaterThan(8);+ // Verify names are the hook names, not 'hooks'+ for (const hook of hooks) {+ expect(hook.name).toMatch(/^use[A-Z]/);+ }+ });++ it('discovers theme utilities (not skipped)', () => {+ const core = components['@xds/core'];+ const themeUtils = core.filter(c => c.directory === 'theme');+ expect(themeUtils.length).toBeGreaterThanOrEqual(2);+ const names = themeUtils.map(c => c.name);+ expect(names).toContain('MediaTheme');+ });++ it('discovers multiple docs per directory (Chat has multiple)', () => {+ const core = components['@xds/core'];+ const chatComponents = core.filter(c => c.directory === 'Chat');+ // Chat dir has ChatDictationButton (hidden) + ChatToolCalls (visible) + main Chat doc+ expect(chatComponents.length).toBeGreaterThanOrEqual(2);+ });++ it('hidden components are included with hidden flag', () => {+ const core = components['@xds/core'];+ const names = core.map(c => c.name);+ // All components should be present regardless of hidden flag+ expect(names).toContain('ChatDictationButton');+ expect(names).toContain('NavMenuItem');+ // Currently no components are hidden+ const hiddenCount = core.filter(c => c.hidden).length;+ expect(hiddenCount).toBe(0);+ });++ it('components have group assignments', () => {+ const withGroups = components['@xds/core'].filter(c => c.group !== null);+ expect(withGroups.length).toBeGreaterThan(+ components['@xds/core'].length * 0.3,+ );+ });++ it('no duplicate component names within a package', () => {+ for (const [, comps] of Object.entries(components)) {+ const names = comps.map(c => c.name);+ expect(new Set(names).size).toBe(names.length);+ }+ });+});++// ── Block Registry ─────────────────────────────────────────────────────++describe('blockRegistry', () => {+ it('discovers blocks', () => {+ expect(blockCount).toBeGreaterThan(100);+ expect(blocks.length).toBe(blockCount);+ });++ it('has showcases', () => {+ expect(showcaseCount).toBeGreaterThan(20);+ const actualShowcases = blocks.filter(b => b.isShowcase);+ expect(actualShowcases.length).toBe(showcaseCount);+ });++ it('blocks have required fields', () => {+ for (const block of blocks) {+ expect(block.dirName).toBeTruthy();+ expect(block.name).toBeTruthy();+ expect(typeof block.isShowcase).toBe('boolean');+ expect(typeof block.aspectRatio).toBe('number');+ expect(block.aspectRatio).toBeGreaterThan(0);+ expect(block.aspectRatio).not.toBeNaN();+ expect(Array.isArray(block.componentsUsed)).toBe(true);+ expect(block.category).toBeDefined();+ }+ });++ it('aspect ratios are parsed correctly (no eval)', () => {+ // 16/9 should parse to ~1.777+ const wideBlocks = blocks.filter(+ b => Math.abs(b.aspectRatio - 16 / 9) < 0.01,+ );+ expect(wideBlocks.length).toBeGreaterThan(0);+ // 4/3 should parse to ~1.333+ const standardBlocks = blocks.filter(+ b => Math.abs(b.aspectRatio - 4 / 3) < 0.01,+ );+ expect(standardBlocks.length).toBeGreaterThan(0);+ });++ it('blocks are scoped by category (component directory)', () => {+ const categories = new Set(blocks.map(b => b.category));+ expect(categories.size).toBeGreaterThan(10);+ });++ it('showcase for Button exists', () => {+ const buttonShowcase = blocks.find(+ b => b.isShowcase && b.category.includes('Button'),+ );+ expect(buttonShowcase).toBeDefined();+ });++ it('componentsUsed links blocks to components', () => {+ const blocksWithComponents = blocks.filter(+ b => b.componentsUsed.length > 0,+ );+ expect(blocksWithComponents.length).toBeGreaterThan(blocks.length * 0.5);+ });+});++// ── Template Registry ──────────────────────────────────────────────────++describe('templateRegistry', () => {+ it('discovers page templates', () => {+ expect(templateCount).toBeGreaterThan(10);+ expect(templates.length).toBe(templateCount);+ });++ it('templates have required fields', () => {+ for (const t of templates) {+ expect(t.slug).toBeTruthy();+ expect(t.name).toBeTruthy();+ expect(typeof t.description).toBe('string');+ expect(typeof t.isReady).toBe('boolean');+ }+ });++ it('known templates are present', () => {+ const slugs = templates.map(t => t.slug);+ expect(slugs).toContain('dashboard');+ expect(slugs).toContain('settings');+ });++ it('no duplicate template slugs', () => {+ const slugs = templates.map(t => t.slug);+ expect(new Set(slugs).size).toBe(slugs.length);+ });+});++// ── Docs Registry ──────────────────────────────────────────────────────++describe('docsRegistry', () => {+ it('discovers doc topics', () => {+ expect(docsCount).toBeGreaterThan(5);+ expect(docTopics.length).toBe(docsCount);+ });++ it('doc topics have required fields including title', () => {+ for (const d of docTopics) {+ expect(d.topic).toBeTruthy();+ expect(d.title).toBeTruthy();+ expect(typeof d.description).toBe('string');+ }+ });++ it('title differs from slug (human-readable)', () => {+ const gettingStarted = docTopics.find(d => d.topic === 'getting-started');+ expect(gettingStarted).toBeDefined();+ expect(gettingStarted?.title).toBe('Getting Started');++ const theme = docTopics.find(d => d.topic === 'theme');+ expect(theme).toBeDefined();+ expect(theme?.title).toBe('Theme System');+ });++ it('known topics are present', () => {+ const topics = docTopics.map(d => d.topic);+ expect(topics).toContain('getting-started');+ expect(topics).toContain('tokens');+ expect(topics).toContain('spacing');+ expect(topics).toContain('color');+ });++ it('no duplicate topics', () => {+ const topics = docTopics.map(d => d.topic);+ expect(new Set(topics).size).toBe(topics.length);+ });+});diff --git a/apps/docsite/src/app/page.tsx b/apps/docsite/src/app/page.tsxindex 82343b302e..01b00ee821 100644--- a/apps/docsite/src/app/page.tsx+++ b/apps/docsite/src/app/page.tsx@@ -1,9 +1,9 @@-'use client';-import * as stylex from '@stylexjs/stylex';-import {XDSVStack} from '@xds/core/Layout';-import {XDSText, XDSHeading} from '@xds/core/Text';-import {XDSButton} from '@xds/core/Button';+import {packages} from '../generated/packageRegistry';+import {components, componentCount} from '../generated/componentRegistry';+import {blockCount, showcaseCount} from '../generated/blockRegistry';+import {templateCount} from '../generated/templateRegistry';+import {docsCount} from '../generated/docsRegistry';const styles = stylex.create({main: {@@ -13,20 +13,122 @@ const styles = stylex.create({minHeight: '100vh',padding: '2rem',},+ container: {+ maxWidth: 640,+ width: '100%',+ },+ heading: {+ fontSize: '2.5rem',+ fontWeight: 700,+ marginBottom: '0.5rem',+ },+ subtitle: {+ fontSize: '1.125rem',+ opacity: 0.7,+ marginBottom: '2rem',+ },+ grid: {+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))',+ gap: '1rem',+ marginBottom: '2rem',+ },+ stat: {+ padding: '1rem',+ borderRadius: 8,+ border: '1px solid var(--color-border)',+ textAlign: 'center' as const,+ },+ statNumber: {+ fontSize: '2rem',+ fontWeight: 700,+ lineHeight: 1,+ },+ statLabel: {+ fontSize: '0.75rem',+ opacity: 0.6,+ marginTop: '0.25rem',+ },+ section: {+ marginBottom: '1.5rem',+ },+ sectionHeading: {+ fontSize: '0.875rem',+ fontWeight: 600,+ opacity: 0.5,+ textTransform: 'uppercase' as const,+ letterSpacing: '0.05em',+ marginBottom: '0.5rem',+ },+ packageList: {+ display: 'flex',+ flexWrap: 'wrap' as const,+ gap: '0.5rem',+ },+ chip: {+ fontSize: '0.8125rem',+ padding: '0.25rem 0.75rem',+ borderRadius: 999,+ border: '1px solid var(--color-border)',+ },});+const themeCount = packages.filter(p => p.name.includes('theme-')).length;+const componentPackages = Object.keys(components);+export default function Home() {return (<main {...stylex.props(styles.main)}>- <XDSVStack gap={6} hAlign="center">- <XDSVStack gap={2} hAlign="center">- <XDSHeading level={1}>XDS</XDSHeading>- <XDSText type="body" color="secondary">- A design system for building internal tools and products.- </XDSText>- </XDSVStack>- <XDSButton label="Get Started" variant="primary" />- </XDSVStack>+ <div {...stylex.props(styles.container)}>+ <h1 {...stylex.props(styles.heading)}>XDS</h1>+ <p {...stylex.props(styles.subtitle)}>+ A design system for building internal tools and products.+ </p>++ <div {...stylex.props(styles.grid)}>+ <Stat n={componentCount} label="Components" />+ <Stat n={blockCount} label="Blocks" />+ <Stat n={showcaseCount} label="Showcases" />+ <Stat n={templateCount} label="Templates" />+ <Stat n={themeCount} label="Themes" />+ <Stat n={docsCount} label="Doc Topics" />+ <Stat n={packages.length} label="Packages" />+ <Stat n={componentPackages.length} label="Component Pkgs" />+ </div>++ <div {...stylex.props(styles.section)}>+ <div {...stylex.props(styles.sectionHeading)}>Packages</div>+ <div {...stylex.props(styles.packageList)}>+ {packages.map(p => (+ <span key={p.name} {...stylex.props(styles.chip)}>+ {p.name} <span style={{opacity: 0.5}}>v{p.version}</span>+ </span>+ ))}+ </div>+ </div>++ <div {...stylex.props(styles.section)}>+ <div {...stylex.props(styles.sectionHeading)}>+ Components by Package+ </div>+ <div {...stylex.props(styles.packageList)}>+ {componentPackages.map(pkg => (+ <span key={pkg} {...stylex.props(styles.chip)}>+ {pkg.replace('@xds/', '')} ({components[pkg].length})+ </span>+ ))}+ </div>+ </div>+ </div></main>);}++function Stat({n, label}: {n: number; label: string}) {+ return (+ <div {...stylex.props(styles.stat)}>+ <div {...stylex.props(styles.statNumber)}>{n}</div>+ <div {...stylex.props(styles.statLabel)}>{label}</div>+ </div>+ );+}diff --git a/apps/docsite/vitest.config.ts b/apps/docsite/vitest.config.tsnew file mode 100644index 0000000000..9586925e24--- /dev/null+++ b/apps/docsite/vitest.config.ts@@ -0,0 +1,7 @@+import {defineConfig} from 'vitest/config';++export default defineConfig({+ test: {+ include: ['src/__tests__/**/*.test.ts'],+ },+});diff --git a/eslint.config.js b/eslint.config.jsindex 869a178022..e6eb144df7 100644--- a/eslint.config.js+++ b/eslint.config.js@@ -36,6 +36,7 @@ export default tseslint.config("apps/example-nextjs/next-env.d.ts","apps/example-nextjs-source/*.js","apps/docsite/*.js",+ "apps/docsite/scripts/**","apps/sandbox/*.js","packages/build/**",],diff --git a/packages/core/src/Chat/ChatDictationButton.doc.mjs b/packages/core/src/Chat/ChatDictationButton.doc.mjsindex a4942121bc..7fbbd3c599 100644--- a/packages/core/src/Chat/ChatDictationButton.doc.mjs+++ b/packages/core/src/Chat/ChatDictationButton.doc.mjs@@ -3,7 +3,7 @@export const docs = {name: 'ChatDictationButton',group: 'Chat',- hidden: true,+ hidden: false,keywords: ['dictation', 'microphone', 'voice', 'speech', 'recording', 'stt', 'speech-to-text', 'voice-input', 'mic'],diff --git a/packages/core/src/NavIcon/NavIcon.doc.mjs b/packages/core/src/NavIcon/NavIcon.doc.mjsindex b1891ed7cd..abd8b67741 100644--- a/packages/core/src/NavIcon/NavIcon.doc.mjs+++ b/packages/core/src/NavIcon/NavIcon.doc.mjs@@ -2,7 +2,7 @@export const docs = {name: 'NavIcon',- hidden: true,+ hidden: false,keywords: ["navicon","iconbutton","toolbar icon","appbar icon","nav button"],props: [{diff --git a/packages/core/src/NavMenu/NavMenu.doc.mjs b/packages/core/src/NavMenu/NavMenu.doc.mjsindex 6495e40cb6..18c2242624 100644--- a/packages/core/src/NavMenu/NavMenu.doc.mjs+++ b/packages/core/src/NavMenu/NavMenu.doc.mjs@@ -1,8 +1,8 @@/** @type {import('../docs-types').ComponentDoc} */export const docs = {- name: 'NavMenu',- hidden: true,+ name: 'NavMenuItem',+ hidden: false,keywords: ['nav', 'menu', 'navigation', 'menu-item'],usage: {description: 'Menu item used within navigation components like SideNav and TopNav.',