An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): add `theme build --check` to verify generated theme outputs (#4565)
Cindy Zhang9fa085c4a110
diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjsindex 11d2a82467..53b715b6a9 100644--- a/packages/cli/api/theme/build/build.mjs+++ b/packages/cli/api/theme/build/build.mjs@@ -16,6 +16,14 @@* a stable code). Human progress is emitted through the shared `logger`* (silent by default), so the CLI keeps its exact output while a programmatic* caller stays quiet.+ *+ * With `{check: true}`, it compiles the same outputs in memory but writes+ * nothing: it compares each generated file against what is on disk (ignoring+ * only the volatile `@generated` `Command:` line) and returns a+ * `theme.build.check` receipt listing any stale or missing outputs. This is+ * the CI guard for committed, generated theme CSS: the source of truth is+ * `<theme>.ts`, and `theme build --check` fails when the committed+ * `<theme>.css`/`.js`/`.d.ts` no longer match it.*/import * as fs from 'node:fs';@@ -23,6 +31,7 @@ import * as path from 'node:path';import {pathToFileURL, fileURLToPath} from 'node:url';import {createJiti} from 'jiti';import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';+import {CLI_ROOT, findCoreDir} from '../../../foundation/fs/paths.mjs';import {sanitizeName,PathSafetyError,@@ -57,14 +66,47 @@ try {_coreImportError = e;}+/**+ * Read a package's `version` from a resolved directory. Returns `'unknown'`+ * when it can't be read so the header always has a value.+ * @param {string|null} dir+ * @returns {string}+ */+function readPkgVersion(dir) {+ if (!dir) return 'unknown';+ try {+ const pkg = JSON.parse(+ fs.readFileSync(path.join(dir, 'package.json'), 'utf-8'),+ );+ return pkg?.version ?? 'unknown';+ } catch {+ return 'unknown';+ }+}++/**+ * Resolve the CLI and core package versions recorded in generated headers.+ * These are stable (unlike a timestamp): identical inputs produce byte-identical+ * output, so rebuilds don't churn git and `theme build --check` stays a pure+ * content-drift signal.+ * @param {string} cwd - Consumer cwd, used to locate the installed core.+ * @returns {{cli: string, core: string}}+ */+function resolveToolVersions(cwd) {+ return {+ cli: readPkgVersion(CLI_ROOT),+ core: readPkgVersion(findCoreDir(cwd)),+ };+}+/*** Build a @generated attribution header for generated files.* @param {string} sourceFile - Relative path to the source theme file* @param {'css'|'js'|'ts'} lang - File language (determines comment syntax)* @param {string} [command] - The full CLI command used to generate this file+ * @param {{cli: string, core: string}} [versions] - CLI/core versions used to build*/-function generatedHeader(sourceFile, lang = 'js', command) {- const timestamp = new Date().toISOString();+function generatedHeader(sourceFile, lang = 'js', command, versions) {const body = [`@generated by \`astryx theme build\` — do not edit manually.`,`Source: ${sourceFile}`,@@ -72,13 +114,37 @@ function generatedHeader(sourceFile, lang = 'js', command) {if (command) {body.push(`Command: ${command}`);}- body.push(`Generated: ${timestamp}`);+ if (versions) {+ body.push(`CLI: @astryxdesign/cli@${versions.cli}`);+ body.push(`Core: @astryxdesign/core@${versions.core}`);+ }if (lang === 'css') {return `/*\n * ${body.join('\n * ')}\n */\n\n`;}return `/**\n * ${body.join('\n * ')}\n */\n\n`;}+/**+ * Normalize generated file content for staleness comparison by dropping the+ * volatile `Command:` line of the `@generated` header (it embeds the+ * invocation, e.g. an explicit --out). Everything else — including the rest of+ * the header and all real content — is compared verbatim. Used only by+ * `--check`: a differing command must NOT report a file as stale, but any real+ * content drift must. The `CLI:`/`Core:` provenance lines are deterministic+ * for a given toolchain, so they compare verbatim like real content.+ * @param {string} content+ * @returns {string}+ */+function normalizeForCompare(content) {+ return content+ .split('\n')+ .filter(line => {+ const t = line.replace(/^\s*\*?\s?/, '');+ return !t.startsWith('Command:');+ })+ .join('\n');+}+/*** Convert a theme name to a valid JS identifier.* e.g. 'default-minimal' → 'defaultMinimal', 'ocean' → 'ocean'@@ -86,7 +152,10 @@ function generatedHeader(sourceFile, lang = 'js', command) {* @returns {string}*/function toIdentifier(name) {- return name.replace(/-([a-z])/g, (/** @type {string} */ _, /** @type {string} */ c) => c.toUpperCase());+ return name.replace(+ /-([a-z])/g,+ (/** @type {string} */ _, /** @type {string} */ c) => c.toUpperCase(),+ );}/**@@ -115,98 +184,13 @@ export function importSpecifier(relDir, base) {function toPascalCase(name) {return name.split('-')- .map((/** @type {string} */ part) => part.charAt(0).toUpperCase() + part.slice(1))+ .map(+ (/** @type {string} */ part) =>+ part.charAt(0).toUpperCase() + part.slice(1),+ ).join('');}-/** @type {Map<string, {moduleName: string, interfacePrefix: string}>} */-const _augmentationTargetCache = new Map();--/**- * Resolve a theme component key (the rendered class without `astryx-`) to the- * public core subpath and component-name prefix that own its augmentable prop- * maps. Subtargets such as `avatar-status-dot` are documented in their parent- * component docs and augment the parent's public module (`Avatar`), while some- * rendered class keys are intentionally unhyphenated (`progressbar`,- * `statusdot`) and need the exported component casing from docs, not naive- * PascalCase.- *- * @param {string} componentName- * @returns {Promise<{moduleName: string, interfacePrefix: string}>}- */-async function resolveAugmentationTarget(componentName) {- if (_augmentationTargetCache.has(componentName)) {- return /** @type {{moduleName: string, interfacePrefix: string}} */ (_augmentationTargetCache.get(componentName));- }-- const fallback = {- moduleName: toPascalCase(componentName),- interfacePrefix: toPascalCase(componentName),- };-- const coreRoot = resolveCoreRoot();- const coreSrc = coreRoot ? path.join(coreRoot, 'src') : null;- if (!coreSrc || !fs.existsSync(coreSrc)) {- _augmentationTargetCache.set(componentName, fallback);- return fallback;- }-- /** @type {Array<{moduleName: string, interfacePrefix: string}>} */- const matches = [];-- /** @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;- }-- const matchesTarget = (doc?.theming?.targets || []).some(- (/** @type {any} */ target) =>- typeof target?.className === 'string' &&- target.className.replace(/^astryx-/, '') === componentName,- );- if (!matchesTarget) continue;-- const sourceDir = path.basename(path.dirname(full));- const moduleName = doc?.name && typeof doc.name === 'string'- ? doc.name- : sourceDir;- const interfacePrefix = (doc?.components || [])- .map((/** @type {any} */ comp) => comp?.name)- .find((/** @type {unknown} */ name) =>- typeof name === 'string' &&- name.toLowerCase().replace(/[^a-z]/g, '') ===- componentName.toLowerCase().replace(/[^a-z]/g, ''),- ) || moduleName;-- matches.push({moduleName, interfacePrefix});- }- }-- await scan(coreSrc);- const normalizedComponent = componentName.toLowerCase().replace(/[^a-z]/g, '');- const result =- matches.find(m => m.moduleName.toLowerCase().replace(/[^a-z]/g, '') === normalizedComponent) ||- matches[0] ||- fallback;- _augmentationTargetCache.set(componentName, result);- return result;-}-/*** Load known built-in values for a component's visual props from its .doc.mjs file.* Parses the type string (e.g. "'info' | 'warning' | 'error' | 'success'") to extract values.@@ -223,7 +207,8 @@ async function loadKnownValues(componentName) {// 'dropdown-menu' → 'DropdownMenu'). Theme keys use the rendered class// token, which hyphenates multi-word names, so strip non-letters from BOTH// sides before comparing.- const dirs = fs.readdirSync(coreSrc, { withFileTypes: true })+ const dirs = fs+ .readdirSync(coreSrc, {withFileTypes: true}).filter(d => d.isDirectory()).map(d => d.name);const target = componentName.toLowerCase().replace(/[^a-z]/g, '');@@ -267,7 +252,9 @@ async function loadKnownValues(componentName) {// Parse union type: "'info' | 'warning' | 'error' | 'success'" → ['info', 'warning', 'error', 'success']const matches = prop.type.match(/'([^']+)'/g);if (matches) {- result[prop.name] = matches.map((/** @type {string} */ m) => m.replace(/'/g, ''));+ result[prop.name] = matches.map((/** @type {string} */ m) =>+ m.replace(/'/g, ''),+ );}}return result;@@ -343,6 +330,113 @@ function readComponentDeclarations(pascalName) {return contents;}++/** @type {Map<string, Array<{moduleName: string, interfacePrefix: string}>>} */+const _augmentationTargetCache = new Map();++/**+ * Resolve a rendered theme class token (the key without `astryx-`) to candidate+ * public core subpaths and interface prefixes that may own its augmentable prop+ * maps. Some tokens are subtargets documented by a parent component+ * (`avatar-status-dot` augments `@astryxdesign/core/Avatar`), and some stable+ * class tokens intentionally omit word separators (`progressbar`, `statusdot`)+ * while the public API keeps `ProgressBar`/`StatusDot` casing. Component docs+ * are the source of truth for the target token → owning component relationship.+ *+ * @param {string} componentName+ * @returns {Promise<Array<{moduleName: string, interfacePrefix: string}>>}+ */+async function resolveAugmentationTargetCandidates(componentName) {+ if (_augmentationTargetCache.has(componentName)) {+ return /** @type {Array<{moduleName: string, interfacePrefix: string}>} */ (+ _augmentationTargetCache.get(componentName)+ );+ }++ const fallback = [+ {+ moduleName: toPascalCase(componentName),+ interfacePrefix: toPascalCase(componentName),+ },+ ];++ const coreRoot = resolveCoreRoot();+ const coreSrc = coreRoot ? path.join(coreRoot, 'src') : null;+ if (!coreSrc || !fs.existsSync(coreSrc)) {+ _augmentationTargetCache.set(componentName, fallback);+ return fallback;+ }++ /** @type {Array<{moduleName: string, interfacePrefix: string}>} */+ const matches = [];+ /** @type {Set<string>} */+ const seen = new Set();++ /**+ * @param {string} moduleName+ * @param {string} interfacePrefix+ */+ function addCandidate(moduleName, interfacePrefix) {+ const key = `${moduleName}:${interfacePrefix}`;+ if (seen.has(key)) return;+ seen.add(key);+ matches.push({moduleName, interfacePrefix});+ }++ /** @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;+ }++ const matchesTarget = (doc?.theming?.targets || []).some(+ (/** @type {any} */ target) =>+ typeof target?.className === 'string' &&+ target.className.replace(/^astryx-/, '') === componentName,+ );+ if (!matchesTarget) continue;++ const moduleName =+ typeof doc?.name === 'string' && doc.name+ ? doc.name+ : path.basename(path.dirname(full));++ // Try the exact rendered token first for documented subtargets such as+ // avatar-status-dot → AvatarStatusDotVariantMap, then the owning public+ // component name for unhyphenated public casings such as progressbar →+ // ProgressBarVariantMap/statusdot → StatusDotVariantMap.+ addCandidate(moduleName, toPascalCase(componentName));+ addCandidate(moduleName, moduleName);+ if (Array.isArray(doc?.components)) {+ for (const comp of doc.components) {+ if (typeof comp?.name === 'string') {+ addCandidate(moduleName, comp.name);+ }+ }+ }+ }+ }++ await scan(coreSrc);+ const resolved = matches.length > 0 ? matches : fallback;+ _augmentationTargetCache.set(componentName, resolved);+ return resolved;+}+/*** Determine whether `@astryxdesign/core/<Component>` exports an interface named* `interfaceName` that can be augmented via module augmentation.@@ -358,8 +452,12 @@ function readComponentDeclarations(pascalName) {function componentHasAugmentableInterface(pascalName, interfaceName) {const decl = readComponentDeclarations(pascalName);if (!decl) return false;- // Word-boundary match so `ButtonVariantMap` doesn't match `XButtonVariantMap`.- const re = new RegExp(`\\b${interfaceName}\\b`);+ // Require an actual interface declaration in this public subpath, not just a+ // type re-export. Module augmentation only widens consumers that import the+ // module where the interface is declared; augmenting a barrel that re-exports+ // the type (e.g. Field re-exporting FieldStatusVariantMap) creates a dead+ // sibling interface for consumers of the real FieldStatus subpath.+ const re = new RegExp(String.raw`\binterface\s+${interfaceName}\b`);return re.test(decl);}@@ -408,15 +506,16 @@ async function generateVariantDeclarationsAsync(themeDef) {if (knownForProp && knownForProp.includes(value)) continue;if (!customValues[component]) customValues[component] = {};- if (!customValues[component][prop]) customValues[component][prop] = new Set();+ if (!customValues[component][prop])+ customValues[component][prop] = new Set();customValues[component][prop].add(value);}}}// Check if we found any custom values- const hasCustom = Object.values(customValues).some(- props => Object.values(props).some(values => values.size > 0)+ const hasCustom = Object.values(customValues).some(props =>+ Object.values(props).some(values => values.size > 0),);if (!hasCustom) return null;@@ -426,17 +525,24 @@ async function generateVariantDeclarationsAsync(themeDef) {for (const [prop, values] of Object.entries(props)) {if (values.size === 0) continue;- const {moduleName, interfacePrefix} = await resolveAugmentationTarget(component);const propPascal = prop.charAt(0).toUpperCase() + prop.slice(1);- const modulePath = `@astryxdesign/core/${moduleName}`;- const interfaceName = `${interfacePrefix}${propPascal}Map`;+ const target = (await resolveAugmentationTargetCandidates(component)).find(+ candidate =>+ componentHasAugmentableInterface(+ candidate.moduleName,+ `${candidate.interfacePrefix}${propPascal}Map`,+ ),+ );// Only augment interfaces that actually exist as an extension point in// core. Props backed by closed literal-union types (e.g. Button `size`,// Heading `type`/`level`) have no `*Map` interface — a `declare module`// block against a non-existent interface just creates a new, unused// interface and never extends the component's prop union, so skip it.- if (!componentHasAugmentableInterface(moduleName, interfaceName)) continue;+ if (!target) continue;++ const modulePath = `@astryxdesign/core/${target.moduleName}`;+ const interfaceName = `${target.interfacePrefix}${propPascal}Map`;sections.push(`declare module '${modulePath}' {`);sections.push(` interface ${interfaceName} {`);@@ -474,7 +580,8 @@ function resolveTokenValue(value) {// Theme @scope selector helpers. Keep the `astryx` literal in sync with// packages/core/src/naming.ts (NAMESPACE) and generateThemeRules.ts.// Theme scopes to data-astryx-theme; the static build path must match.-const themeScopeStart = (/** @type {string} */ name) => `[data-astryx-theme="${name}"]`;+const themeScopeStart = (/** @type {string} */ name) =>+ `[data-astryx-theme="${name}"]`;const THEME_SCOPE_TO = `[data-astryx-theme]`;/**@@ -501,7 +608,7 @@ async function importThemeModule(filePath) {throw new Error(`Could not find a defineTheme() result in ${filePath}.\n` +- `Expected an export like: export const myTheme = defineTheme({ name: '...', tokens: {...} })`,+ `Expected an export like: export const myTheme = defineTheme({ name: '...', tokens: {...} })`,);}@@ -535,7 +642,7 @@ async function extractThemeDefinition(filePath) {const je = /** @type {Error} */ (jitiError);throw new Error(`Failed to load theme from ${filePath}: ${je.message}\n` +- `Make sure all imports in the theme file are resolvable.`,+ `Make sure all imports in the theme file are resolvable.`,);}}@@ -556,25 +663,27 @@ function extractThemeDefinitionLegacy(filePath) {if (!defaultMatch) {throw new Error(`Could not find defineTheme() call or default export in ${filePath}.\n` +- `Expected: defineTheme({ name: '...', tokens: {...} })`,+ `Expected: defineTheme({ name: '...', tokens: {...} })`,);}-+return eval(`(${defaultMatch[1]})`);}let objStr = defineMatch[1];objStr = objStr.replace(/\s+as\s+const/g, '');- objStr = objStr.replace(/icons:\s*[a-zA-Z_][a-zA-Z0-9_]*/g, 'icons: undefined');+ objStr = objStr.replace(+ /icons:\s*[a-zA-Z_][a-zA-Z0-9_]*/g,+ 'icons: undefined',+ );try {-return eval(`(${objStr})`);} catch (e) {const err = /** @type {Error} */ (e);throw new Error(`Failed to parse theme definition in ${filePath}: ${err.message}\n` +- `Make sure the defineTheme() argument is a plain object literal.`,+ `Make sure the defineTheme() argument is a plain object literal.`,{cause: e},);}@@ -625,9 +734,7 @@ function generateBuiltModule(themeDef, iconInfo) {? `import { ${iconInfo.exportName} } from '${iconInfo.importPath}';\n`: '';const iconsField = iconInfo ? ` icons: ${iconInfo.exportName},` : '';- const iconReExport = iconInfo- ? `\nexport { ${iconInfo.exportName} };\n`- : '';+ const iconReExport = iconInfo ? `\nexport { ${iconInfo.exportName} };\n` : '';// Resolve token values — tuples become light-dark() strings/** @type {Record<string, unknown>} */@@ -685,6 +792,10 @@ ${iconType}export declare const ${toIdentifier(themeDef.name)}Theme: DefinedThem`;}+// =============================================================================+// Component validation+// =============================================================================+/*** Load known theme target keys and visual props from core component docs.* Returns null when docs are unavailable so validation can skip unknown-key@@ -750,10 +861,6 @@ async function getKnownComponents() {return knownComponentsCache;}-// =============================================================================-// Component validation-// =============================================================================-/*** Validate component overrides in a theme definition.* Warns on unknown component names and unknown prop names.@@ -773,7 +880,7 @@ async function validateComponentOverrides(themeDef) {// Check component nameif (!(component in knownComponents)) {const similar = Object.keys(knownComponents)- .filter((k) => {+ .filter(k => {if (k.includes(component) || component.includes(k)) return true;// Levenshtein distance 1-2 for short namesif (Math.abs(k.length - component.length) <= 2) {@@ -791,7 +898,8 @@ async function validateComponentOverrides(themeDef) {return false;}).slice(0, 3);- const hint = similar.length > 0 ? ` Did you mean: ${similar.join(', ')}?` : '';+ const hint =+ similar.length > 0 ? ` Did you mean: ${similar.join(', ')}?` : '';warnings.push(`Unknown component "${component}".${hint}`);continue;}@@ -842,8 +950,8 @@ function validatePrivateVars(themeDef) {if (typeof prop === 'string' && prop.startsWith('--_')) {errors.push(`Component "${component}" (${key}) sets private var "${prop}". ` +- `Private vars (--_*) are internal — use standard CSS properties ` +- `(e.g. borderRadius, padding) instead. The pipeline expands them automatically.`,+ `Private vars (--_*) are internal — use standard CSS properties ` ++ `(e.g. borderRadius, padding) instead. The pipeline expands them automatically.`,);}}@@ -861,15 +969,23 @@ function validatePrivateVars(themeDef) {* `logger` (silent by default).** @param {string} file - Theme file path, resolved against `cwd`.- * @param {{out?: string}} [options] - `out` overrides the output CSS path.+ * @param {{out?: string, check?: boolean}} [options] - `out` overrides the output CSS path; `check` compares against on-disk outputs instead of writing.* @param {{cwd?: string}} [ctx]- * @returns {Promise<import('../theme.type.mjs').ThemeBuildResponse | null>}+ * @returns {Promise<import('../theme.type.mjs').ThemeBuildResponse | import('../theme.type.mjs').ThemeBuildCheckResponse | null>}*/-export async function themeBuild(file, options = {}, {cwd = process.cwd()} = {}) {+export async function themeBuild(+ file,+ options = {},+ {cwd = process.cwd()} = {},+) {const filePath = path.resolve(cwd, file);if (!fs.existsSync(filePath)) {- throw new AstryxError(`File not found: ${filePath}`, undefined, ERROR_CODES.ERR_FILE_NOT_FOUND);+ throw new AstryxError(+ `File not found: ${filePath}`,+ undefined,+ ERROR_CODES.ERR_FILE_NOT_FOUND,+ );}logger.log(`\nBuilding theme from ${path.relative(cwd, filePath)}...`);@@ -884,7 +1000,11 @@ export async function themeBuild(file, options = {}, {cwd = process.cwd()} = {})}if (!themeDef.name) {- throw new AstryxError('Theme must have a name property.', undefined, ERROR_CODES.ERR_THEME_INVALID);+ throw new AstryxError(+ 'Theme must have a name property.',+ undefined,+ ERROR_CODES.ERR_THEME_INVALID,+ );}// Path-safety: the theme name is used to derive output filenames@@ -895,7 +1015,11 @@ export async function themeBuild(file, options = {}, {cwd = process.cwd()} = {})sanitizeName(themeDef.name, {label: 'theme name'});} catch (err) {if (err instanceof PathSafetyError) {- throw new AstryxError(err.message, undefined, ERROR_CODES.ERR_PATH_TRAVERSAL);+ throw new AstryxError(+ err.message,+ undefined,+ ERROR_CODES.ERR_PATH_TRAVERSAL,+ );}throw err;}@@ -915,7 +1039,9 @@ export async function themeBuild(file, options = {}, {cwd = process.cwd()} = {})logger.error(` ✗ ${e}`);}if (privateVarErrors.length > 0) {- logger.error(`\n ${privateVarErrors.length} private var error(s). Use standard CSS properties instead.`);+ logger.error(+ `\n ${privateVarErrors.length} private var error(s). Use standard CSS properties instead.`,+ );}// Generate CSS via core's shared generator — the SINGLE source of truth.@@ -928,7 +1054,9 @@ export async function themeBuild(file, options = {}, {cwd = process.cwd()} = {})'built, resolvable @astryxdesign/core so it emits the same CSS as the ' +'runtime <Theme>. Build @astryxdesign/core first (e.g. `pnpm -F @astryxdesign/core ' +'build`)' +- (_coreImportError ? `.\n Import error: ${_coreImportError.message}` : '.'),+ (_coreImportError+ ? `.\n Import error: ${_coreImportError.message}`+ : '.'),undefined,ERROR_CODES.ERR_CORE_NOT_FOUND,);@@ -995,6 +1123,9 @@ export async function themeBuild(file, options = {}, {cwd = process.cwd()} = {})// Source path relative to cwd — used in @generated headersconst sourceRelative = path.relative(cwd, filePath);const buildCommand = `astryx theme build ${sourceRelative}${options.out ? ' --out ' + path.relative(cwd, path.resolve(cwd, options.out)) : ''}`;+ // Stable provenance recorded in @generated headers — versions, not a+ // timestamp, so identical inputs produce byte-identical output.+ const versions = resolveToolVersions(cwd);// Derive the default CSS name from the theme name so .css/.js/.d.ts// share one scheme; an explicit --out still wins.@@ -1004,8 +1135,12 @@ export async function themeBuild(file, options = {}, {cwd = process.cwd()} = {}): path.join(path.dirname(filePath), `${baseName}.css`);const displayTheme = resolvedTheme || themeDef;- const tokenCount = displayTheme.tokens ? Object.keys(displayTheme.tokens).length : 0;- const componentCount = displayTheme.components ? Object.keys(displayTheme.components).length : 0;+ const tokenCount = displayTheme.tokens+ ? Object.keys(displayTheme.tokens).length+ : 0;+ const componentCount = displayTheme.components+ ? Object.keys(displayTheme.components).length+ : 0;const size = (Buffer.byteLength(css) / 1024).toFixed(1);// Compute all output paths up front so we can validate them as a@@ -1022,22 +1157,29 @@ export async function themeBuild(file, options = {}, {cwd = process.cwd()} = {})// Type augmentation .d.ts if theme has custom prop values. Computed// before the main .d.ts so the latter can reference it (see below).const augmentationSource = resolvedTheme || themeDef;- const variantDecl = await generateVariantDeclarationsAsync(augmentationSource);+ const variantDecl =+ await generateVariantDeclarationsAsync(augmentationSource);const variantsFileName = variantDecl ? `${baseName}.variants.d.ts` : null;const variantDtsPath =variantDecl && variantsFileName? path.join(outDir, variantsFileName): null;const variantContent = variantDecl- ? generatedHeader(sourceRelative, 'ts', buildCommand) + variantDecl+ ? generatedHeader(sourceRelative, 'ts', buildCommand, versions) ++ variantDecl: null;// Generate all file contents in memory first. The main .d.ts references// the variants file (when present) via a triple-slash directive so// importing the theme also loads the custom-variant augmentations.- const cssContent = generatedHeader(sourceRelative, 'css', buildCommand) + css;- const jsContent = generatedHeader(sourceRelative, 'js', buildCommand) + generateBuiltModule(resolvedTheme || themeDef, iconInfo);- const dtsContent = generatedHeader(sourceRelative, 'ts', buildCommand) + generateBuiltTypes(themeDef, iconInfo, variantsFileName);+ const cssContent =+ generatedHeader(sourceRelative, 'css', buildCommand, versions) + css;+ const jsContent =+ generatedHeader(sourceRelative, 'js', buildCommand, versions) ++ generateBuiltModule(resolvedTheme || themeDef, iconInfo);+ const dtsContent =+ generatedHeader(sourceRelative, 'ts', buildCommand, versions) ++ generateBuiltTypes(themeDef, iconInfo, variantsFileName);// Atomic-ish write: stage every file as `<dest>.tmp`, then rename// each into place. If any stage step fails we clean up partials and@@ -1052,6 +1194,49 @@ export async function themeBuild(file, options = {}, {cwd = process.cwd()} = {})writes.push({dest: variantDtsPath, content: variantContent});}+ // Check mode: compare generated content against what's on disk instead of+ // writing. A file is "stale" if it's missing or its content differs once the+ // volatile @generated `Command:` line is ignored. Returns a+ // receipt listing stale/missing outputs so callers (CI) can fail on drift.+ if (options.check) {+ /** @type {Array<{path: string, reason: 'missing' | 'outdated'}>} */+ const stale = [];+ for (const w of writes) {+ const rel = path.relative(cwd, w.dest);+ if (!fs.existsSync(w.dest)) {+ stale.push({path: rel, reason: 'missing'});+ continue;+ }+ const onDisk = fs.readFileSync(w.dest, 'utf8');+ if (normalizeForCompare(onDisk) !== normalizeForCompare(w.content)) {+ stale.push({path: rel, reason: 'outdated'});+ }+ }+ const upToDate = stale.length === 0;+ if (upToDate) {+ logger.log(`\n✓ Theme outputs are up to date with ${sourceRelative}.`);+ } else {+ logger.error(+ `\n✗ ${stale.length} theme output(s) are out of date with ${sourceRelative}:`,+ );+ for (const s of stale) {+ logger.error(+ ` ${s.reason === 'missing' ? 'missing' : 'stale'}: ${s.path}`,+ );+ }+ logger.error(`\n Rebuild with: ${buildCommand}`);+ }+ return {+ type: 'theme.build.check',+ data: {+ name: themeDef.name,+ upToDate,+ stale,+ checked: writes.map(w => path.relative(cwd, w.dest)),+ },+ };+ }+fs.mkdirSync(outDir, {recursive: true});/** @type {Array<{tmp: string, dest: string}>} */const staged = [];@@ -1067,20 +1252,28 @@ export async function themeBuild(file, options = {}, {cwd = process.cwd()} = {})} catch (err) {// Roll back any temp files we managed to create.for (const s of staged) {- try { fs.rmSync(s.tmp, {force: true}); } catch { /* best-effort */ }+ try {+ fs.rmSync(s.tmp, {force: true});+ } catch {+ /* best-effort */+ }}const msg = `Failed to write theme outputs: ${/** @type {Error} */ (err).message}`;throw new AstryxError(msg, undefined, ERROR_CODES.ERR_WRITE_FAILED);}logger.log(`\n✓ ${path.relative(cwd, outPath)}`);- logger.log(` ${tokenCount} token overrides, ${componentCount} component overrides`);+ logger.log(+ ` ${tokenCount} token overrides, ${componentCount} component overrides`,+ );logger.log(` ${size} KB`);logger.log(`✓ ${path.relative(cwd, jsPath)}`);logger.log(`✓ ${path.relative(cwd, dtsPath)}`);if (variantDtsPath && variantDecl) {const augCount = (variantDecl.match(/': true;/g) || []).length;- logger.log(`✓ ${path.relative(cwd, variantDtsPath)} (${augCount} type augmentations)`);+ logger.log(+ `✓ ${path.relative(cwd, variantDtsPath)} (${augCount} type augmentations)`,+ );}const relOutDir = path.relative(cwd, outDir) || '.';@@ -1110,7 +1303,9 @@ Or with a <link> tag:// Print font declaration warnings (derived from typography roles)if (resolvedTheme && resolvedTheme.fonts && resolvedTheme.fonts.length > 0) {- logger.log(`\n⚠ Theme "${themeDef.name}" requires fonts not included in the build:`);+ logger.log(+ `\n⚠ Theme "${themeDef.name}" requires fonts not included in the build:`,+ );for (const font of resolvedTheme.fonts) {logger.log(` ${font.family} — add to your document <head>:`);logger.log(` <link rel="stylesheet" href="${font.url}" />`);@@ -1129,7 +1324,9 @@ Or with a <link> tag:css: path.relative(cwd, outPath),js: path.relative(cwd, jsPath),dts: path.relative(cwd, dtsPath),- ...(variantDecl && variantDtsPath ? {variantsDts: path.relative(cwd, variantDtsPath)} : {}),+ ...(variantDecl && variantDtsPath+ ? {variantsDts: path.relative(cwd, variantDtsPath)}+ : {}),},warnings: warningMessages,},diff --git a/packages/cli/api/theme/build/build.test.mjs b/packages/cli/api/theme/build/build.test.mjsindex e1795a0a01..1d27f7895d 100644--- a/packages/cli/api/theme/build/build.test.mjs+++ b/packages/cli/api/theme/build/build.test.mjs@@ -78,9 +78,9 @@ describe('themeBuild() — receipt', () => {result?.data.outputs.js,result?.data.outputs.dts,]) {- expect(fs.existsSync(path.join(tmpDir, /** @type {string} */ (rel)))).toBe(- true,- );+ expect(+ fs.existsSync(path.join(tmpDir, /** @type {string} */ (rel))),+ ).toBe(true);}});@@ -134,3 +134,91 @@ describe('themeBuild() — nothing to build', () => {expect(fs.readdirSync(tmpDir)).toEqual(['empty.mjs']);});});++describe('themeBuild() — check mode', () => {+ it('reports upToDate with no stale files and writes nothing when outputs match the source', async () => {+ const themeFile = path.join(tmpDir, 'chk.mjs');+ fs.writeFileSync(+ themeFile,+ `export default { name: 'chk', tokens: { '--color-bg': '#0a0a0a' } };\n`,+ );++ // Build once for real to produce the committed outputs.+ await themeBuild('chk.mjs', {}, {cwd: tmpDir});+ const before = fs.readFileSync(path.join(tmpDir, 'chk.css'), 'utf8');++ const result = await themeBuild('chk.mjs', {check: true}, {cwd: tmpDir});++ expect(result?.type).toBe('theme.build.check');+ expect(result?.data.upToDate).toBe(true);+ expect(result?.data.stale).toEqual([]);+ expect(result?.data.checked).toContain('chk.css');+ // Check mode must not rewrite the file.+ expect(fs.readFileSync(path.join(tmpDir, 'chk.css'), 'utf8')).toBe(before);+ });++ it('flags a stale output when the committed CSS content drifts from the source', async () => {+ const themeFile = path.join(tmpDir, 'drift.mjs');+ fs.writeFileSync(+ themeFile,+ `export default { name: 'drift', tokens: { '--color-bg': '#0a0a0a' } };\n`,+ );+ await themeBuild('drift.mjs', {}, {cwd: tmpDir});++ // Tamper with the committed CSS (real content change, not just the header).+ const cssPath = path.join(tmpDir, 'drift.css');+ fs.writeFileSync(+ cssPath,+ fs.readFileSync(cssPath, 'utf8') + '\n.injected{}\n',+ );++ const result = await themeBuild('drift.mjs', {check: true}, {cwd: tmpDir});++ expect(result?.data.upToDate).toBe(false);+ expect(+ result?.data.stale.some(+ s => s.path === 'drift.css' && s.reason === 'outdated',+ ),+ ).toBe(true);+ });++ it('flags a missing output', async () => {+ const themeFile = path.join(tmpDir, 'gone.mjs');+ fs.writeFileSync(+ themeFile,+ `export default { name: 'gone', tokens: { '--color-bg': '#0a0a0a' } };\n`,+ );+ await themeBuild('gone.mjs', {}, {cwd: tmpDir});+ fs.rmSync(path.join(tmpDir, 'gone.css'));++ const result = await themeBuild('gone.mjs', {check: true}, {cwd: tmpDir});++ expect(result?.data.upToDate).toBe(false);+ expect(+ result?.data.stale.some(+ s => s.path === 'gone.css' && s.reason === 'missing',+ ),+ ).toBe(true);+ });++ it('ignores volatile @generated header lines (a differing timestamp is NOT stale)', async () => {+ const themeFile = path.join(tmpDir, 'stamp.mjs');+ fs.writeFileSync(+ themeFile,+ `export default { name: 'stamp', tokens: { '--color-bg': '#0a0a0a' } };\n`,+ );+ await themeBuild('stamp.mjs', {}, {cwd: tmpDir});++ // Rewrite ONLY the Generated: timestamp line in the committed CSS.+ const cssPath = path.join(tmpDir, 'stamp.css');+ const tampered = fs+ .readFileSync(cssPath, 'utf8')+ .replace(/Generated: .*/, 'Generated: 1999-01-01T00:00:00.000Z');+ fs.writeFileSync(cssPath, tampered);++ const result = await themeBuild('stamp.mjs', {check: true}, {cwd: tmpDir});++ expect(result?.data.upToDate).toBe(true);+ expect(result?.data.stale).toEqual([]);+ });+});diff --git a/packages/cli/api/theme/theme.type.mjs b/packages/cli/api/theme/theme.type.mjsindex 5a079e7f81..eafc74446f 100644--- a/packages/cli/api/theme/theme.type.mjs+++ b/packages/cli/api/theme/theme.type.mjs@@ -9,6 +9,7 @@* Invocation -> type discriminator* ------------------------------------------------------------------* xds --json theme build <file> -> theme.build+ * xds --json theme build <file> --check -> theme.build.check* xds --json theme list -> theme.list* xds --json theme add <slug> -> theme.add* (file not found / parse error) -> CLIError@@ -23,6 +24,13 @@* @property {{name: string, tokenCount: number, componentCount: number, sizeKB: number, outputs: {css: string, js: string, dts: string, variantsDts?: string}, warnings: string[]}} data*/+/**+ * xds --json theme build <file> --check+ * @typedef {object} ThemeBuildCheckResponse+ * @property {'theme.build.check'} type+ * @property {{name: string, upToDate: boolean, stale: Array<{path: string, reason: 'missing' | 'outdated'}>, checked: string[]}} data+ */+/*** A single theme entry as surfaced by `theme list`.* @typedef {object} ThemeListEntrydiff --git a/packages/cli/clients/cli/commands/build-theme.mjs b/packages/cli/clients/cli/commands/build-theme.mjsindex 9669f6d607..ca3f37b356 100644--- a/packages/cli/clients/cli/commands/build-theme.mjs+++ b/packages/cli/clients/cli/commands/build-theme.mjs@@ -137,21 +137,32 @@ export function registerTheme(program) {const theme = program.command('theme').description('Theme tools — build, export, and manage themes')- .action((/** @type {unknown} */ options, /** @type {import('commander').Command} */ cmd) => {- // Parent group has no default behaviour. If the user passed an- // unknown subcommand (e.g. `astryx theme bogus`), Commander hands it to- // us as a positional in cmd.args — exit 1 with a clear error.- const extras = (cmd && cmd.args) || [];- if (extras.length > 0) {- const unknown = String(extras[0]);- const known = (theme.commands || []).map((c) => c.name());- const suggestions = known.map((name) => ({name, reason: 'available subcommand'}));- cliError(`unknown subcommand 'theme ${unknown}'`, {suggestions, code: ERROR_CODES.ERR_UNKNOWN_SUBCOMMAND});- return;- }- // Bare `astryx theme` — show the subcommand list. Exit 0 (help is success).- theme.help();- });+ .action(+ (+ /** @type {unknown} */ options,+ /** @type {import('commander').Command} */ cmd,+ ) => {+ // Parent group has no default behaviour. If the user passed an+ // unknown subcommand (e.g. `astryx theme bogus`), Commander hands it to+ // us as a positional in cmd.args — exit 1 with a clear error.+ const extras = (cmd && cmd.args) || [];+ if (extras.length > 0) {+ const unknown = String(extras[0]);+ const known = (theme.commands || []).map(c => c.name());+ const suggestions = known.map(name => ({+ name,+ reason: 'available subcommand',+ }));+ cliError(`unknown subcommand 'theme ${unknown}'`, {+ suggestions,+ code: ERROR_CODES.ERR_UNKNOWN_SUBCOMMAND,+ });+ return;+ }+ // Bare `astryx theme` — show the subcommand list. Exit 0 (help is success).+ theme.help();+ },+ );theme.command('build <file>')@@ -161,42 +172,78 @@ export function registerTheme(program) {'-w, --watch','Rebuild automatically when the theme file changes (Ctrl-C to stop)',)- .action(async (/** @type {string} */ file, /** @type {{out?: string, watch?: boolean}} */ options) => {- const filePath = path.resolve(process.cwd(), file);- const json = program.opts().json || false;+ .option(+ '-c, --check',+ 'Verify the committed outputs match the source without writing; exit non-zero if stale',+ )+ .action(+ async (+ /** @type {string} */ file,+ /** @type {{out?: string, watch?: boolean, check?: boolean}} */ options,+ ) => {+ const filePath = path.resolve(process.cwd(), file);+ const json = program.opts().json || false;- if (!fs.existsSync(filePath)) {- cliError(`File not found: ${filePath}`, {code: ERROR_CODES.ERR_FILE_NOT_FOUND});- return;- }+ if (!fs.existsSync(filePath)) {+ cliError(`File not found: ${filePath}`, {+ code: ERROR_CODES.ERR_FILE_NOT_FOUND,+ });+ return;+ }- // Watch mode: run an initial build, then rebuild on every change to the- // theme file. Watch is a human-interactive, long-running mode — it is not- // supported in --json (machine) mode, which expects a single envelope.- if (options.watch) {- if (json) {- cliError('--watch is not supported with --json', {+ // --check and --watch are mutually exclusive: check is a one-shot,+ // exit-coded verification; watch is a long-running rebuild loop.+ if (options.check && options.watch) {+ cliError('--check cannot be combined with --watch', {code: ERROR_CODES.ERR_THEME_INVALID,});return;}- await runThemeBuildWatch(file, filePath, options);- return;- }- // Non-watch: delegate to the API compiler. Enable human output unless in- // --json mode (log → stdout via humanLog, warn/error → stderr). The- // "Building theme from" line, the ✓/warning lines, and the install- // instructions are all emitted from inside themeBuild via the shared logger.- logger.setSilent(json);- try {- const result = await themeBuild(file, {out: options.out}, {cwd: process.cwd()});- if (json && result) jsonOut(result);- } catch (e) {- const err = /** @type {import('../../../api/error.mjs').AstryxError} */ (e);- cliError(err.message, {suggestions: err.suggestions, code: err.code});- }- });+ // Watch mode: run an initial build, then rebuild on every change to the+ // theme file. Watch is a human-interactive, long-running mode — it is not+ // supported in --json (machine) mode, which expects a single envelope.+ if (options.watch) {+ if (json) {+ cliError('--watch is not supported with --json', {+ code: ERROR_CODES.ERR_THEME_INVALID,+ });+ return;+ }+ await runThemeBuildWatch(file, filePath, options);+ return;+ }++ // Non-watch: delegate to the API compiler. Enable human output unless in+ // --json mode (log → stdout via humanLog, warn/error → stderr). The+ // "Building theme from" line, the ✓/warning lines, and the install+ // instructions are all emitted from inside themeBuild via the shared logger.+ logger.setSilent(json);+ try {+ const result = await themeBuild(+ file,+ {out: options.out, check: options.check},+ {cwd: process.cwd()},+ );+ if (json && result) jsonOut(result);+ // In --check mode a stale/missing output is a failure: exit non-zero+ // (after emitting the receipt) so CI can gate on it. The receipt is+ // already printed above (shared logger or --json envelope).+ if (+ options.check &&+ result &&+ result.type === 'theme.build.check' &&+ !result.data.upToDate+ ) {+ process.exitCode = 1;+ }+ } catch (e) {+ const err =+ /** @type {import('../../../api/error.mjs').AstryxError} */ (e);+ cliError(err.message, {suggestions: err.suggestions, code: err.code});+ }+ },+ );theme.command('list')@@ -208,8 +255,12 @@ export function registerTheme(program) {try {result = themeList();} catch (e) {- const err = /** @type {import('../../../api/error.mjs').AstryxError} */ (e);- cliError(err.message, {suggestions: err.suggestions || [], code: err.code});+ const err =+ /** @type {import('../../../api/error.mjs').AstryxError} */ (e);+ cliError(err.message, {+ suggestions: err.suggestions || [],+ code: err.code,+ });return;}@@ -227,7 +278,9 @@ export function registerTheme(program) {if (t.description) humanLog(` ${t.description}`);}humanLog('\nUsage:');- humanLog(` ${getCliInvocation()} theme add <slug> [target-path] Scaffold a theme file you own\n`);+ humanLog(+ ` ${getCliInvocation()} theme add <slug> [target-path] Scaffold a theme file you own\n`,+ );});theme@@ -235,56 +288,67 @@ export function registerTheme(program) {.description('Scaffold a theme into your project as editable source').option('-f, --overwrite', 'Overwrite existing files without prompting').option('--list', 'List available themes')- .action(async (/** @type {string | undefined} */ slug, /** @type {string | undefined} */ targetPath, /** @type {{list?: boolean, overwrite?: boolean}} */ options) => {- const json = program.opts().json || false;+ .action(+ async (+ /** @type {string | undefined} */ slug,+ /** @type {string | undefined} */ targetPath,+ /** @type {{list?: boolean, overwrite?: boolean}} */ options,+ ) => {+ const json = program.opts().json || false;- // The CLI is non-interactive: never prompt to confirm an overwrite.- // Existing files require an explicit --overwrite; otherwise themeAdd's- // ERR_FILE_EXISTS guard rejects the write. `--list` (or a bare `theme add`- // with no slug) is the list affordance — route it to the list leaf.- /** @type {import('../../../api/theme/theme.type.mjs').ThemeListResponse | import('../../../api/theme/theme.type.mjs').ThemeAddResponse} */- let result;- try {- result =- options.list || !slug- ? themeList()- : await themeAdd(slug, {- targetPath,- overwrite: options.overwrite,- cwd: process.cwd(),- });- } catch (e) {- const err = /** @type {import('../../../api/error.mjs').AstryxError} */ (e);- cliError(err.message, {suggestions: err.suggestions || [], code: err.code});- return;- }+ // The CLI is non-interactive: never prompt to confirm an overwrite.+ // Existing files require an explicit --overwrite; otherwise themeAdd's+ // ERR_FILE_EXISTS guard rejects the write. `--list` (or a bare `theme add`+ // with no slug) is the list affordance — route it to the list leaf.+ /** @type {import('../../../api/theme/theme.type.mjs').ThemeListResponse | import('../../../api/theme/theme.type.mjs').ThemeAddResponse} */+ let result;+ try {+ result =+ options.list || !slug+ ? themeList()+ : await themeAdd(slug, {+ targetPath,+ overwrite: options.overwrite,+ cwd: process.cwd(),+ });+ } catch (e) {+ const err =+ /** @type {import('../../../api/error.mjs').AstryxError} */ (e);+ cliError(err.message, {+ suggestions: err.suggestions || [],+ code: err.code,+ });+ return;+ }- if (json) return jsonOut(result);+ if (json) return jsonOut(result);- if (result.type === 'theme.list') {- const themes = result.data;- humanLog('\nThemes:\n');- for (const t of themes) {- const tag = t.maintained ? ' (maintained)' : '';- humanLog(` ${t.slug}${tag}`);- if (t.description) humanLog(` ${t.description}`);+ if (result.type === 'theme.list') {+ const themes = result.data;+ humanLog('\nThemes:\n');+ for (const t of themes) {+ const tag = t.maintained ? ' (maintained)' : '';+ humanLog(` ${t.slug}${tag}`);+ if (t.description) humanLog(` ${t.description}`);+ }+ humanLog('\nUsage:');+ humanLog(+ ` ${getCliInvocation()} theme add <slug> [target-path] Scaffold a theme file you own\n`,+ );+ return;}- humanLog('\nUsage:');- humanLog(` ${getCliInvocation()} theme add <slug> [target-path] Scaffold a theme file you own\n`);- return;- }- // theme.add — print where files landed + how to use the theme.- const {displayName, outputDir, entry, exportName, files} = result.data;- humanLog(`\n✓ Added ${displayName} theme to ${outputDir}/`);- for (const f of files) {- humanLog(` ${outputDir}/${f}`);- }- const entryModule = importSpecifier(- outputDir,- entry.replace(/\.tsx?$/, ''),- );- humanLog(`+ // theme.add — print where files landed + how to use the theme.+ const {displayName, outputDir, entry, exportName, files} = result.data;+ humanLog(`\n✓ Added ${displayName} theme to ${outputDir}/`);+ for (const f of files) {+ humanLog(` ${outputDir}/${f}`);+ }+ const entryModule = importSpecifier(+ outputDir,+ entry.replace(/\.tsx?$/, ''),+ );+ humanLog(`Use it in your app (import path is relative to a file in src/ — adjust if yours lives elsewhere):import { ${exportName} } from '${entryModule}';@@ -295,5 +359,6 @@ Use it in your app (import path is relative to a file in src/ — adjust if yourThis is your copy of the ${displayName} theme — edit ${entry} to make it your own.`);- });+ },+ );}diff --git a/packages/cli/clients/cli/lib/manifest.mjs b/packages/cli/clients/cli/lib/manifest.mjsindex 2b3767bf00..b7a35df4c8 100644--- a/packages/cli/clients/cli/lib/manifest.mjs+++ b/packages/cli/clients/cli/lib/manifest.mjs@@ -56,7 +56,12 @@ export const RESPONSE_TYPES = {],docs: ['docs.list', 'docs.detail', 'docs.detail.section'],blog: ['blog.list', 'blog.detail'],- discover: ['discover.list', 'discover.detail', 'discover.detail.doc', 'discover.search'],+ discover: [+ 'discover.list',+ 'discover.detail',+ 'discover.detail.doc',+ 'discover.search',+ ],search: ['search'],build: ['build.help', 'build.kit'],swizzle: ['swizzle.list', 'swizzle.copy'],@@ -67,7 +72,7 @@ export const RESPONSE_TYPES = {'template.copy',],hook: ['hook.list', 'hook.detail', 'hook.detail.params'],- 'theme build': ['theme.build'],+ 'theme build': ['theme.build', 'theme.build.check'],'theme list': ['theme.list'],'theme add': ['theme.list', 'theme.add'],upgrade: ['upgrade.list', 'upgrade.status', 'upgrade.run'],@@ -84,17 +89,30 @@ export const RESPONSE_TYPES = {* @type {Record<string, string[]>}*/const EXAMPLES = {- component: ['astryx component', 'astryx component XDSButton', 'astryx component XDSButton --props --json'],+ component: [+ 'astryx component',+ 'astryx component XDSButton',+ 'astryx component XDSButton --props --json',+ ],docs: ['astryx docs', 'astryx docs spacing --json'],discover: ['astryx discover --json'],- search: ['astryx search modal --json', 'astryx search button --type component --json'],+ search: [+ 'astryx search modal --json',+ 'astryx search button --type component --json',+ ],build: ['astryx build', 'astryx build "analytics dashboard" --json'],swizzle: ['astryx swizzle XDSButton'],template: ['astryx template --json', 'astryx template dashboard ./src/app'],hook: ['astryx hook', 'astryx hook useToggle --json'],- 'theme build': ['astryx theme build ./src/themes/ocean.ts --out ./dist/ocean.css'],+ 'theme build': [+ 'astryx theme build ./src/themes/ocean.ts --out ./dist/ocean.css',+ 'astryx theme build ./src/themes/ocean.ts --check',+ ],'theme list': ['astryx theme list --json'],- 'theme add': ['astryx theme add matcha', 'astryx theme add matcha ./src/themes/matcha'],+ 'theme add': [+ 'astryx theme add matcha',+ 'astryx theme add matcha ./src/themes/matcha',+ ],upgrade: ['astryx upgrade --json'],manifest: ['astryx manifest --json', 'astryx --json'],doctor: ['astryx doctor', 'astryx doctor --json'],@@ -103,7 +121,9 @@ const EXAMPLES = {'astryx validate-integration @acme/widgets --json',],init: ['astryx init'],- 'layout expand': [`astryx layout expand 'V[g6] > C{card-callout}*4' ./src/Page.tsx`],+ 'layout expand': [+ `astryx layout expand 'V[g6] > C{card-callout}*4' ./src/Page.tsx`,+ ],'layout check': [`astryx layout check 'A[cp6] > L > LC > S[p6]' --json`],'layout grammar': ['astryx layout grammar'],};@@ -182,14 +202,19 @@ function describeCommand(cmd, root, jsonSupported) {// `_hidden` is a Commander internal not present on its public types.if (!name || /** @type {any} */ (cmd)._hidden || name === 'help') return null;- const subcommands = /** @type {object[]} */ ((cmd.commands || [])- .map((sub) => describeCommand(sub, root, jsonSupported))- .filter(Boolean));+ const subcommands = /** @type {object[]} */ (+ (cmd.commands || [])+ .map(sub => describeCommand(sub, root, jsonSupported))+ .filter(Boolean)+ );// `registeredArguments` is Commander 12's public-ish accessor; `_args` is the// older internal. Cast through any to read whichever exists.- const args =- /** @type {any[]} */ (/** @type {any} */ (cmd).registeredArguments || /** @type {any} */ (cmd)._args || []);+ const args = /** @type {any[]} */ (+ /** @type {any} */ (cmd).registeredArguments ||+ /** @type {any} */ (cmd)._args ||+ []+ );/** @type {any} */const entry = {@@ -234,7 +259,7 @@ function describeGlobalOptions(program) {const opts = (program.options || []).map(describeOption);// Commander registers a built-in --version flag; if for some reason it// isn't present in program.options, surface it so the manifest is complete.- if (!opts.some((o) => /(^|[\s,])--version\b/.test(o.flag))) {+ if (!opts.some(o => /(^|[\s,])--version\b/.test(o.flag))) {opts.push({flag: '-V, --version',description: 'Output the version number',@@ -257,10 +282,11 @@ export function buildManifest(program, opts = {}) {const jsonSupported = opts.jsonSupported || new Set();const version = opts.version || /** @type {any} */ (program)._version || '';- const commands = /** @type {any[]} */ ((program.commands || [])- .map((cmd) => describeCommand(cmd, program, jsonSupported))- .filter(Boolean))- .sort((a, b) => a.name.localeCompare(b.name));+ const commands = /** @type {any[]} */ (+ (program.commands || [])+ .map(cmd => describeCommand(cmd, program, jsonSupported))+ .filter(Boolean)+ ).sort((a, b) => a.name.localeCompare(b.name));return {name: 'astryx',