An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): validate theme targets from docs (#4644)
Cindy Zhanga714ba94c9d2
diff --git a/.changeset/theme-target-docs.md b/.changeset/theme-target-docs.mdnew file mode 100644index 0000000000..50af611333--- /dev/null+++ b/.changeset/theme-target-docs.md@@ -0,0 +1,6 @@+---+'@astryxdesign/cli': patch+---++[fix] theme build: validate component override keys from documented theming targets so subtargets like Chat bubbles and SideNav items no longer warn as unknown.+@cixzhangdiff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjsindex 61679d17d4..5f397eec64 100644--- a/packages/cli/api/theme/build/build.mjs+++ b/packages/cli/api/theme/build/build.mjs@@ -30,6 +30,7 @@ import {import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';import {AstryxError} from '../../error.mjs';import {logger} from '../../logger.mjs';+import {loadComponentDoc} from '../../../foundation/discovery/component-loader.mjs';// Import shared theme processing from core. `astryx theme build` MUST produce the// exact same CSS as the `<Theme>` runtime, so it has exactly one generation@@ -596,105 +597,94 @@ ${iconType}export declare const ${toIdentifier(themeDef.name)}Theme: DefinedThem`;}-// =============================================================================-// Component validation-// =============================================================================-/**- * Known Astryx component names and their visual props.- * Used to warn on typos in defineTheme component overrides.+ * Load known theme target keys and visual props from core component docs.+ * Returns null when docs are unavailable so validation can skip unknown-key+ * warnings rather than guessing from a second registry.*- * CONTRACT: every key must equal the stable class token the component- * actually renders — the `<name>` in core's `themeProps('<name>')` /- * `stableClassName('<name>')` calls. Theme CSS selectors are derived- * verbatim from these keys (`.astryx-<key>`), so a key that diverges from- * the rendered class validates cleanly but emits a dead rule that matches- * nothing in the DOM (#4109: `textinput` emitted `.astryx-textinput` while- * TextInput renders `astryx-text-input`).- *- * The prop lists mirror the visual props each component passes to- * `themeProps()` (also documented as `theming.targets[].visualProps` in the- * component's doc.mjs) — the axes that render as variant classes and- * data attributes.- *- * `layer` has no rendered `astryx-layer` class or doc target; it is a- * layout/anchor concept unrelated to #4109 and is intentionally kept (see the- * `allowedWithoutTarget` allowlist in build-theme.registry.test.mjs).- *- * @type {Record<string, string[]>}+ * @returns {Promise<Record<string, string[]> | null>}*/-const KNOWN_COMPONENTS = {- 'app-shell': ['variant'],- 'aspect-ratio': ['shape'],- avatar: ['size'],- badge: ['variant', 'color'],- banner: ['container', 'status'],- breadcrumbs: ['variant'],- button: ['variant', 'size'],- calendar: [],- card: ['variant'],- center: [],- 'checkbox-input': ['size'],- collapsible: [],- 'date-input': ['size', 'status'],- dialog: ['variant', 'position'],- divider: ['variant', 'orientation'],- 'dropdown-menu': [],- 'empty-state': [],- field: [],- 'form-layout': ['direction'],- grid: ['align'],- heading: ['level'],- icon: ['size', 'color'],- kbd: [],- layer: [],- layout: [],- link: ['color'],- list: ['type', 'density'],- 'mobile-nav': ['side'],- 'more-menu': [],- navicon: [],- 'number-input': ['size', 'status'],- pagination: ['variant'],- progressbar: ['variant', 'size'],- 'radio-list': ['orientation', 'size'],- section: ['variant'],- selector: ['type', 'size', 'color'],- 'side-nav': ['mode'],- skeleton: [],- slider: ['orientation'],- spinner: ['size'],- stack: [],- statusdot: ['variant', 'size'],- switch: [],- 'tab-list': ['size'],- table: [],- text: ['type', 'color'],- 'text-input': ['size', 'status'],- textarea: [],- 'time-input': ['size', 'status'],- token: ['color'],- tokenizer: [],- 'top-nav': [],- typeahead: ['type', 'size', 'color'],-};+async function loadKnownComponents() {+ const coreRoot = resolveCoreRoot();+ const coreSrc = coreRoot ? path.join(coreRoot, 'src') : null;+ if (!coreSrc || !fs.existsSync(coreSrc)) return null;++ /** @type {Record<string, string[]>} */+ const targets = {};++ /** @param {string} dir */+ async function scan(dir) {+ const entries = fs.readdirSync(dir, {withFileTypes: true});+ for (const entry of entries) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ if (entry.name === 'node_modules' || entry.name === '__tests__') continue;+ await scan(full);+ continue;+ }+ if (!entry.name.endsWith('.doc.mjs')) continue;++ /** @type {any} */+ let doc;+ try {+ doc = await loadComponentDoc(full);+ } catch {+ continue;+ }++ for (const target of doc?.theming?.targets || []) {+ const className = target?.className;+ if (typeof className !== 'string') continue;+ const key = className.replace(/^astryx-/, '');+ if (!key) continue;+ const props = Array.isArray(target.visualProps)+ ? target.visualProps.filter((/** @type {unknown} */ p) => typeof p === 'string')+ : [];+ targets[key] = [...new Set([...(targets[key] || []), ...props])];+ }+ }+ }++ await scan(coreSrc);+ return Object.keys(targets).length > 0 ? targets : null;+}++/** @type {Record<string, string[]> | null | undefined} */+let knownComponentsCache;++/**+ * @returns {Promise<Record<string, string[]> | null>}+ */+async function getKnownComponents() {+ if (knownComponentsCache === undefined) {+ knownComponentsCache = await loadKnownComponents();+ }+ return knownComponentsCache;+}++// =============================================================================+// Component validation+// =============================================================================/*** Validate component overrides in a theme definition.* Warns on unknown component names and unknown prop names.* Returns array of warning strings.* @param {{components?: Record<string, Record<string, unknown>>}} themeDef- * @returns {string[]}+ * @returns {Promise<string[]>}*/-function validateComponentOverrides(themeDef) {+async function validateComponentOverrides(themeDef) {/** @type {string[]} */const warnings = [];if (!themeDef.components) return warnings;+ const knownComponents = await getKnownComponents();+ if (knownComponents == null) return warnings;+for (const [component, rules] of Object.entries(themeDef.components)) {// Check component name- if (!(component in KNOWN_COMPONENTS)) {- const similar = Object.keys(KNOWN_COMPONENTS)+ if (!(component in knownComponents)) {+ const similar = Object.keys(knownComponents).filter((k) => {if (k.includes(component) || component.includes(k)) return true;// Levenshtein distance 1-2 for short names@@ -719,7 +709,7 @@ function validateComponentOverrides(themeDef) {}// Check prop names in prop:value keys- const knownProps = KNOWN_COMPONENTS[component];+ const knownProps = knownComponents[component];for (const key of Object.keys(rules)) {if (key === 'base') continue;@@ -823,7 +813,7 @@ export async function themeBuild(file, options = {}, {cwd = process.cwd()} = {})}// Validate component overrides- const warnings = validateComponentOverrides(themeDef);+ const warnings = await validateComponentOverrides(themeDef);const warningMessages = [];for (const w of warnings) {warningMessages.push(w);diff --git a/packages/cli/clients/cli/commands/build-theme.registry.test.mjs b/packages/cli/clients/cli/commands/build-theme.registry.test.mjsindex 5b71fd96c8..5162874eae 100644--- a/packages/cli/clients/cli/commands/build-theme.registry.test.mjs+++ b/packages/cli/clients/cli/commands/build-theme.registry.test.mjs@@ -1,28 +1,13 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file Regression test for issue #4109: theme-build component-override keys- * must match the class names components actually render.+ * @file Regression tests for theme-build component-override keys.** `astryx theme build` emits a component override as a `.astryx-<key>` rule,* where `<key>` is the theme's `components` key passed through verbatim- * (generateThemeRules re-adds the `astryx-` prefix). The CLI's KNOWN_COMPONENTS- * registry is what the validator accepts and what its "Did you mean?" hints- * point authors toward — so every registry key MUST correspond to a class a- * component really renders, or the emitted rule is a dead selector that- * silently does nothing.- *- * The registry had de-hyphenated keys for every multi-word component- * (`textinput`, `dateinput`, `numberinput`, `timeinput`, `appshell`,- * `aspectratio`, `checkboxinput`, `dropdownmenu`, `formlayout`, `mobilenav`,- * `moremenu`, `radiolist`, `sidenav`, `tablist`, `topnav`), while the- * components render the hyphenated class (`astryx-text-input`, etc.). Authors- * following the registry shipped dead `.astryx-textinput` rules.- *- * Source of truth = the class the component renders, captured in each- * component's `{Name}.doc.mjs` `theming.targets[].className` (itself guarded- * against the real `themeProps()`/`stableClassName()` call sites by- * packages/core/src/theme/themingTargets.test.ts).+ * (generateThemeRules re-adds the `astryx-` prefix). The validator reads the+ * same documented theming targets that component docs expose, so the docs must+ * stay aligned with the classes components actually render.*/import {describe, it, expect, beforeAll} from 'vitest';@@ -35,28 +20,6 @@ import {runCli} from '../../../test-utils/run-cli.mjs';const HERE = path.dirname(fileURLToPath(import.meta.url));const CORE_SRC = path.resolve(HERE, '../../../../core/src');-const BUILD_THEME_SRC = path.resolve(HERE, '../../../api/theme/build/build.mjs');--/**- * Extract the KNOWN_COMPONENTS registry keys from the build-theme source.- * Reading the source (rather than importing the un-exported constant) keeps- * this test decoupled from the module's private surface.- */-function knownComponentKeys() {- const src = fs.readFileSync(BUILD_THEME_SRC, 'utf8');- const start = src.indexOf('const KNOWN_COMPONENTS = {');- expect(start).toBeGreaterThan(-1);- const end = src.indexOf('};', start);- const block = src.slice(start, end);- const keys = new Set();- const re = /^\s*'?([a-z][a-z0-9-]*)'?\s*:/gm;- let m;- while ((m = re.exec(block)) !== null) {- keys.add(m[1]);- }- return keys;-}-/*** The set of real override keys: every `theming.targets[].className` across the* component docs, with the `astryx-` prefix stripped. This is the canonical@@ -115,42 +78,11 @@ function renderedClassLiterals() {return classes;}-describe('theme-build KNOWN_COMPONENTS registry (#4109)', () => {- // `layer` is a layout/anchor concept with no rendered `astryx-layer`- // class or doc target; it predates and is unrelated to #4109.- const allowedWithoutTarget = new Set(['layer']);-- it('every registry key is a class documented as a theming target', () => {- const known = knownComponentKeys();- const real = realOverrideKeys();-- const dead = [...known].filter(- k => !real.has(k) && !allowedWithoutTarget.has(k),- );- expect(dead).toEqual([]);- });-- it('every registry key is a class a component actually renders (themeProps literal)', () => {- // Validate the registry against the TRUE source of truth — the literal- // passed to themeProps()/stableClassName() in the component source — not- // just the hand-authored doc targets. This catches a de-hyphenated key- // even if the docs were (wrongly) kept in agreement with it.- const known = knownComponentKeys();- const rendered = renderedClassLiterals();-- const dead = [...known].filter(- k => !rendered.has(k) && !allowedWithoutTarget.has(k),- );- expect(dead).toEqual([]);- });-+describe('theme-build documented target validation', () => {it('every documented theming target is backed by a real themeProps literal', () => {- // Guards the two "sources of truth" against drift: a component whose- // themeProps() arg and doc target className disagree would be a latent bug- // that the registry checks above could not catch (they'd validate against- // whichever side happened to match). `theming.targets[].className` is- // hand-authored; themeProps()/stableClassName() literals are what actually- // renders — they must agree.+ // Guards against a component whose doc target className and rendered+ // themeProps()/stableClassName() literal disagree. The docs are what theme+ // build validates against; the literals are what actually matches the DOM.const targets = realOverrideKeys();const rendered = renderedClassLiterals();@@ -166,6 +98,32 @@ describe('theme build emits a live TextInput selector (#4109)', () => {tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-4109-'));}, 200_000);+ it('accepts documented subtargets from component docs', async () => {+ const themeFile = path.join(tmpDir, 'subtargets.mjs');+ const outFile = path.join(tmpDir, 'subtargets.css');+ fs.writeFileSync(+ themeFile,+ `export default {\n` ++ ` name: 'subtargets-4109',\n` ++ ` tokens: {},\n` ++ ` components: {\n` ++ ` 'side-nav-item': { base: { borderRadius: '12px' } },\n` ++ ` 'chat-composer': { base: { padding: '10px' } },\n` ++ ` 'chat-message-bubble': { 'variant:ghost': { borderRadius: '18px' } },\n` ++ ` },\n` ++ `};\n`,+ );++ const result = await runCli(['theme', 'build', themeFile, '-o', outFile]);+ const css = fs.readFileSync(outFile, 'utf8');++ expect(result.status).toBe(0);+ expect(result.stderr).not.toContain('Unknown component');+ expect(css).toContain('.astryx-side-nav-item');+ expect(css).toContain('.astryx-chat-composer');+ expect(css).toContain('.astryx-chat-message-bubble.ghost');+ });+it('emits .astryx-text-input (the rendered class), not the dead .astryx-textinput', async () => {const themeFile = path.join(tmpDir, 'theme.mjs');const outFile = path.join(tmpDir, 'theme.css');