An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): package-scoped component resolution and grouped external discovery (#1919)
Cindy Zhang78a40450517d
diff --git a/packages/cli/src/api/component.mjs b/packages/cli/src/api/component.mjsindex d2a8ea9a49..15b7e17b2a 100644--- a/packages/cli/src/api/component.mjs+++ b/packages/cli/src/api/component.mjs@@ -10,6 +10,7 @@ import {findCoreDir, discoverExternalPackages} from '../utils/paths.mjs';import {discoverComponents,discoverExternalComponents,+ discoverExternalComponentsGrouped,findComponentReadme,findComponentSource,findExternalComponentDoc,@@ -20,12 +21,24 @@ import {searchComponents} from '../lib/string-utils.mjs';import {XDSError} from './error.mjs';import {findShowcase, findRelatedBlocks} from './template.mjs';+/**+ * Resolve an external package by name from the discovered externals list.+ * @param {string} packageName - e.g. '@xds/core'+ * @param {string} cwd+ * @returns {{ name: string, category: string, docsDir: string } | null}+ */+function resolveExternalPackage(packageName, cwd) {+ const externals = discoverExternalPackages(cwd);+ return externals.find(ext => ext.name === packageName) ?? null;+}+/*** @param {string} [name]* @param {object} [options]* @param {string} [options.cwd]* @param {boolean} [options.list]* @param {string} [options.category]+ * @param {string} [options.package] - Scope to a specific external package (e.g. '@xds/core')* @param {boolean} [options.props]* @param {boolean} [options.source]* @param {boolean} [options.showcase]@@ -41,6 +54,7 @@ export async function component(name, options = {}) {cwd = process.cwd(),list = false,category,+ package: packageScope,props = false,source = false,showcase = false,@@ -93,7 +107,7 @@ export async function component(name, options = {}) {return {type: 'component.list', data: {[match[0]]: match[1]}};}- // All components+ // All components — merge core + external packages with grouped subcategoriesif (detail === 'brief') {/** @type {Record<string, Array<import('../types/component').ComponentBriefEntry>>} */const result = {};@@ -118,9 +132,26 @@ export async function component(name, options = {}) {const externals = discoverExternalPackages(cwd);for (const ext of externals) {- const extComps = discoverExternalComponents(ext.docsDir);- if (extComps.length > 0) {- components[`${ext.category} (${ext.name})`] = extComps;+ const grouped = discoverExternalComponentsGrouped(ext.docsDir);+ const groupKeys = Object.keys(grouped);+ if (groupKeys.length === 0) continue;++ // If the package has subcategories (groups), emit each as a separate key.+ // If no groups exist, fall back to the flat list under one key.+ const hasGroups = groupKeys.some(+ k => grouped[k].length > 1 || grouped[k][0] !== k,+ );++ if (hasGroups) {+ for (const [group, members] of Object.entries(grouped)) {+ components[`${group} (${ext.name})`] = members;+ }+ } else {+ // All ungrouped — single flat list under the package category+ const allComps = Object.values(grouped).flat().sort();+ if (allComps.length > 0) {+ components[`${ext.category} (${ext.name})`] = allComps;+ }}}return {type: 'component.list', data: components};@@ -130,6 +161,28 @@ export async function component(name, options = {}) {const dirName = name.replace(/^XDS/, '');+ // When scoped to a specific package, search that package first.+ // This is critical for components that exist in both core and an external+ // package (e.g. AppShell, Button, SideNav) — the package scope ensures+ // the external package's docs are returned, not core's.+ if (packageScope) {+ const ext = resolveExternalPackage(packageScope, cwd);+ if (!ext) {+ throw new XDSError(`External package "${packageScope}" not found`);+ }+ const extDocPath = findExternalComponentDoc(ext.docsDir, dirName);+ if (extDocPath && extDocPath.endsWith('.doc.mjs')) {+ const docs = await loadDocs(extDocPath, {zh, dense, lang});++ if (props) {+ const p = docs.props || (docs.components ? docs.components.flatMap(c => c.props || []) : []);+ return {type: 'component.detail.props', data: p};+ }+ return {type: 'component.detail', data: docs};+ }+ throw new XDSError(`No component "${name}" in package "${packageScope}"`);+ }+if (source) {const sourcePath = findComponentSource(coreDir, dirName);if (!sourcePath) {diff --git a/packages/cli/src/commands/component-package.test.mjs b/packages/cli/src/commands/component-package.test.mjsnew file mode 100644index 0000000000..47c441b37d--- /dev/null+++ b/packages/cli/src/commands/component-package.test.mjs@@ -0,0 +1,95 @@+import {describe, it, expect, beforeEach, afterEach} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import * as os from 'node:os';+import {component} from '../api/component.mjs';++// These tests create a minimal monorepo fixture with:+// - packages/core (symlinked to real @xds/core for loadDocs compatibility)+// - node_modules/@test/ext with a Button + Employee component (external package)+//+// This tests the --package option for disambiguating overlapping component names.++let tmpDir;++function createFixture() {+ // Symlink real core package so loadDocs (dynamic import) works with Vite+ const realCoreDir = path.resolve(import.meta.dirname, '..', '..', '..', 'core');+ const coreDir = path.join(tmpDir, 'packages', 'core');+ fs.mkdirSync(path.dirname(coreDir), {recursive: true});+ fs.symlinkSync(realCoreDir, coreDir);++ // External package with Button (different docs) + Employee (unique)+ const extDir = path.join(tmpDir, 'node_modules', '@test', 'ext');+ const extSrc = path.join(extDir, 'src');+ fs.mkdirSync(path.join(extSrc, 'Button'), {recursive: true});+ fs.mkdirSync(path.join(extSrc, 'Employee'), {recursive: true});+ fs.writeFileSync(path.join(extDir, 'package.json'), JSON.stringify({+ name: '@test/ext',+ xds: {docs: './src', category: 'Common'},+ }));+ fs.writeFileSync(path.join(extSrc, 'Button', 'Button.doc.mjs'), `+export const docs = {+ name: 'XDSCommonButton',+ usage: { description: 'Common button with platform features.' },+ props: [{ name: 'label', type: 'string', description: 'Button label' }, { name: 'isLoading', type: 'boolean', description: 'Shows spinner' }],+};+`);+ fs.writeFileSync(path.join(extSrc, 'Employee', 'Employee.doc.mjs'), `+export const docs = {+ name: 'XDSCommonEmployee',+ usage: { description: 'Employee profile component.' },+ props: [{ name: 'employeeId', type: 'string', description: 'Employee FBID' }],+};+`);+}++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'xds-pkg-test-'));+ createFixture();+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('component() with --package option', () => {+ it('returns external package docs when --package is specified', async () => {+ const result = await component('Button', {cwd: tmpDir, package: '@test/ext'});+ expect(result.type).toBe('component.detail');+ expect(result.data.name).toBe('XDSCommonButton');+ expect(result.data.usage.description).toContain('platform features');+ });++ it('returns core docs when no --package is specified (default behavior)', async () => {+ const result = await component('Button', {cwd: tmpDir});+ expect(result.type).toBe('component.detail');+ // Core's Button doc has name 'Button', not 'XDSCommonButton'+ expect(result.data.name).toBe('Button');+ });++ it('resolves unique external components without --package', async () => {+ const result = await component('Employee', {cwd: tmpDir});+ expect(result.type).toBe('component.detail');+ expect(result.data.name).toBe('XDSCommonEmployee');+ });++ it('returns props for package-scoped component', async () => {+ const result = await component('Button', {cwd: tmpDir, package: '@test/ext', props: true});+ expect(result.type).toBe('component.detail.props');+ expect(result.data).toHaveLength(2);+ expect(result.data.some(p => p.name === 'isLoading')).toBe(true);+ });++ it('throws for unknown package name', async () => {+ await expect(+ component('Button', {cwd: tmpDir, package: '@test/nonexistent'}),+ ).rejects.toThrow('not found');+ });++ it('throws for component not in the specified package', async () => {+ await expect(+ component('Avatar', {cwd: tmpDir, package: '@test/ext'}),+ ).rejects.toThrow('No component "Avatar" in package');+ });+});diff --git a/packages/cli/src/commands/component.test.mjs b/packages/cli/src/commands/component.test.mjsindex a5b2f5a9f9..58be11c381 100644--- a/packages/cli/src/commands/component.test.mjs+++ b/packages/cli/src/commands/component.test.mjs@@ -5,6 +5,7 @@ import * as os from 'node:os';import {discoverComponents,discoverExternalComponents,+ discoverExternalComponentsGrouped,findExternalComponentDoc,findComponentReadme,findComponentSource,@@ -335,6 +336,79 @@ describe('discoverExternalComponents', () => {});});+describe('discoverExternalComponentsGrouped', () => {+ it('reads group: from doc files and groups components', () => {+ const docsDir = path.join(tmpDir, 'src');++ // AppShell with group+ const shellDir = path.join(docsDir, 'AppShell');+ fs.mkdirSync(shellDir, {recursive: true});+ fs.writeFileSync(path.join(shellDir, 'AppShell.doc.mjs'),+ "export const docs = {\n name: 'AppShell',\n group: 'App Chrome',\n};");++ // SideNav with same group+ const navDir = path.join(docsDir, 'SideNav');+ fs.mkdirSync(navDir, {recursive: true});+ fs.writeFileSync(path.join(navDir, 'SideNav.doc.mjs'),+ "export const docs = {\n name: 'SideNav',\n group: 'App Chrome',\n};");++ // Diff with no group+ const diffDir = path.join(docsDir, 'Diff');+ fs.mkdirSync(diffDir, {recursive: true});+ fs.writeFileSync(path.join(diffDir, 'Diff.doc.mjs'),+ "export const docs = {\n name: 'Diff',\n};");++ const result = discoverExternalComponentsGrouped(docsDir);+ expect(result).toEqual({+ 'App Chrome': ['AppShell', 'SideNav'],+ 'Diff': ['Diff'],+ });+ });++ it('returns empty object for nonexistent directory', () => {+ const result = discoverExternalComponentsGrouped(path.join(tmpDir, 'nope'));+ expect(result).toEqual({});+ });++ it('skips hidden components', () => {+ const docsDir = path.join(tmpDir, 'src');+ const compDir = path.join(docsDir, 'Internal');+ fs.mkdirSync(compDir, {recursive: true});+ fs.writeFileSync(path.join(compDir, 'Internal.doc.mjs'),+ "export const docs = {\n name: 'Internal',\n hidden: true,\n};");++ fs.writeFileSync(path.join(docsDir, 'Visible.doc.mjs'),+ "export const docs = {\n name: 'Visible',\n};");++ const result = discoverExternalComponentsGrouped(docsDir);+ expect(result).toEqual({'Visible': ['Visible']});+ });++ it('sorts groups and ungrouped alphabetically', () => {+ const docsDir = path.join(tmpDir, 'src');++ const zDir = path.join(docsDir, 'Zebra');+ fs.mkdirSync(zDir, {recursive: true});+ fs.writeFileSync(path.join(zDir, 'Zebra.doc.mjs'),+ "export const docs = {\n name: 'Zebra',\n group: 'Animals',\n};");++ const aDir = path.join(docsDir, 'Alpha');+ fs.mkdirSync(aDir, {recursive: true});+ fs.writeFileSync(path.join(aDir, 'Alpha.doc.mjs'),+ "export const docs = {\n name: 'Alpha',\n};");++ const bDir = path.join(docsDir, 'Bear');+ fs.mkdirSync(bDir, {recursive: true});+ fs.writeFileSync(path.join(bDir, 'Bear.doc.mjs'),+ "export const docs = {\n name: 'Bear',\n group: 'Animals',\n};");++ const result = discoverExternalComponentsGrouped(docsDir);+ const keys = Object.keys(result);+ expect(keys).toEqual(['Alpha', 'Animals']);+ expect(result['Animals']).toEqual(['Bear', 'Zebra']);+ });+});+describe('findExternalComponentDoc', () => {it('finds a doc file by component name', () => {const docsDir = path.join(tmpDir, 'src');diff --git a/packages/cli/src/commands/component/index.mjs b/packages/cli/src/commands/component/index.mjsindex 1f92c6dd5a..5b58d9720c 100644--- a/packages/cli/src/commands/component/index.mjs+++ b/packages/cli/src/commands/component/index.mjs@@ -35,6 +35,7 @@ export function registerComponent(program) {.option('--source', 'Print component source code').option('--showcase', 'Print showcase source code').option('--blocks', 'List example blocks: showcase, examples, and related')+ .option('--package <name>', 'Scope lookup to an external package (e.g. @xds/core)').action(async (name, options) => {const run = getRunPrefix();const zh = program.opts().zh || false;@@ -57,6 +58,7 @@ export function registerComponent(program) {cwd: process.cwd(),list: options.list,category: options.category,+ package: options.package,props: options.props,source: options.source,showcase: options.showcase,@@ -191,7 +193,7 @@ export function registerComponent(program) {// Re-export lib functions for backward compatibility// (agent-docs.mjs, tests, and generate-skill-doc.sh import from here)-export {discoverComponents, discoverExternalComponents, findComponentReadme, findComponentSource, findExternalComponentDoc, resolveImportPath} from '../../lib/component-discovery.mjs';+export {discoverComponents, discoverExternalComponents, discoverExternalComponentsGrouped, findComponentReadme, findComponentSource, findExternalComponentDoc, resolveImportPath} from '../../lib/component-discovery.mjs';export {discoverExternalPackages} from '../../utils/paths.mjs';export {loadDocs} from '../../lib/component-loader.mjs';export {formatFull, formatCompact, formatBrief, formatProps, formatBriefAll} from '../../lib/component-format.mjs';diff --git a/packages/cli/src/lib/component-discovery.mjs b/packages/cli/src/lib/component-discovery.mjsindex 8e1d8ed6b8..0cd2437076 100644--- a/packages/cli/src/lib/component-discovery.mjs+++ b/packages/cli/src/lib/component-discovery.mjs@@ -285,7 +285,9 @@ export function resolveImportPath(coreDir, componentName) {/*** Discover components from an external package's docs directory.- * Scans for *.doc.mjs files and returns their names.+ * Scans for *.doc.mjs files and returns their names as a flat array.+ *+ * @deprecated Use discoverExternalComponentsGrouped for group-aware discovery.*/export function discoverExternalComponents(docsDir) {if (!fs.existsSync(docsDir)) return [];@@ -308,6 +310,77 @@ export function discoverExternalComponents(docsDir) {return components.sort();}+/**+ * Discover components from an external package's docs directory,+ * reading `group:` fields from each .doc.mjs for subcategories.+ *+ * Returns a Record<string, string[]> matching the shape of discoverComponents():+ * - Grouped components: `{ 'App Chrome': ['AppShell', 'SideNav', 'TopNav'] }`+ * - Ungrouped components: `{ 'Diff': ['Diff'] }`+ */+export function discoverExternalComponentsGrouped(docsDir) {+ if (!fs.existsSync(docsDir)) return {};++ /** @type {Map<string, string|null>} componentName → group */+ const componentGroups = new Map();++ function scanDir(dirPath) {+ const entries = fs.readdirSync(dirPath, {withFileTypes: true});+ for (const entry of entries) {+ if (entry.name === 'node_modules' || entry.name === '__tests__') continue;+ const fullPath = path.join(dirPath, entry.name);+ if (entry.isDirectory()) {+ scanDir(fullPath);+ } else if (entry.name.endsWith('.doc.mjs')) {+ const name = entry.name.replace('.doc.mjs', '');+ const {group, hidden} = readDocMeta(fullPath);+ if (!hidden) {+ componentGroups.set(name, group);+ }+ }+ }+ }++ scanDir(docsDir);++ // Build grouped result (same algorithm as discoverComponents)+ /** @type {Map<string, string[]>} */+ const groups = new Map();+ /** @type {string[]} */+ const ungrouped = [];++ for (const [name, group] of componentGroups) {+ if (group) {+ if (!groups.has(group)) groups.set(group, []);+ groups.get(group).push(name);+ } else {+ ungrouped.push(name);+ }+ }++ for (const members of groups.values()) {+ members.sort();+ }++ /** @type {Array<{key: string, values: string[]}>} */+ const entries = [];+ for (const [groupName, members] of groups) {+ entries.push({key: groupName, values: members});+ }+ for (const name of ungrouped) {+ entries.push({key: name, values: [name]});+ }+ entries.sort((a, b) => a.key.localeCompare(b.key));++ /** @type {Record<string, string[]>} */+ const ordered = {};+ for (const {key, values} of entries) {+ ordered[key] = values;+ }++ return ordered;+}+/*** Find a component's doc file in an external package's docs directory.* Returns the path to {Name}.doc.mjs or null.