Skip to content

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

TypeScript

fix(theme): restore Markdown prose typography after unprefix (#2964)

Cindy Zhang9328bcf1b8e1
diff --git a/.changeset/markdown-docsite-theme-css.md b/.changeset/markdown-docsite-theme-css.md
new file mode 100644
index 0000000000..ecbd1ff0b8
--- /dev/null
+++ b/.changeset/markdown-docsite-theme-css.md
@@ -0,0 +1,16 @@
+---
+'@xds/core': patch
+'@xds/cli': patch
+---
+
+Fix built theme CSS regression introduced by the XDS-prefix migration that broke Markdown typography in the docsite (headings lost their block margins).
+
+Root cause: the generated compat-alias barrels self-re-export from `'.'`, and the Babel ESM build left that as a bare `from '.'` (a directory import Node ESM rejects). `xds theme build` could no longer import `@xds/core/theme` and silently fell back to a duplicated, in-CLI CSS generator — which emitted bare `h1/p { margin: 0; ... }` prose defaults into `@layer xds-theme` (the highest XDS layer). Those out-ranked the Markdown component's own StyleX block-spacing (in `@layer xds-base`), collapsing heading/paragraph margins.
+
+Fixes:
+
+- The Babel extension plugin rewrites compat self-re-exports (`'.'` / `'..'`) to `./index.js` / `../index.js`, so `@xds/core/theme` imports cleanly.
+- `xds theme build` now has a single CSS generation path — `@xds/core`'s generator, the same one the `<Theme>` runtime uses. The duplicated in-CLI generator (`generateCSS` / `generateProseCSS` / local `parseStyleKey` / `expandContainerPadding`) is removed, and a failed `@xds/core/theme` import is now a hard build error (`ERR_CORE_NOT_FOUND`) instead of a silent fallback. This guarantees the CLI and runtime can never emit divergent CSS.
+- The `theme build --no-prose` flag is removed. The runtime always emits prose element defaults, so allowing the build to omit them was another way for the CLI output to diverge from runtime. Prose defaults now always ship, in `@layer reset`.
+- Prose paragraph defaults use `--font-family-body` (was `--font-family-heading`).
+- Theme component pseudo-class selectors now apply to both `astryx-*` and legacy `xds-*` classes.
diff --git a/packages/cli/src/commands/build-theme.import-path.test.mjs b/packages/cli/src/commands/build-theme.import-path.test.mjs
index 6812824c4e..63e225a2fb 100644
--- a/packages/cli/src/commands/build-theme.import-path.test.mjs
+++ b/packages/cli/src/commands/build-theme.import-path.test.mjs
@@ -12,7 +12,7 @@
* regressions in the opposite direction.
*/
-import {describe, it, expect, beforeEach, afterEach} from 'vitest';
+import {describe, it, expect, beforeAll, beforeEach, afterEach} from 'vitest';
import {execFileSync} from 'node:child_process';
import * as fs from 'node:fs';
import * as path from 'node:path';
@@ -21,6 +21,11 @@ import {fileURLToPath} from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const CLI_BIN = path.resolve(__dirname, '../../bin/xds.mjs');
+const REPO_ROOT = path.resolve(__dirname, '../../../..');
+const CORE_THEME_ENTRY = path.join(
+ REPO_ROOT,
+ 'packages/core/dist/theme/index.js',
+);
function runCli(args, cwd) {
try {
@@ -50,6 +55,19 @@ function writeTheme(dir, name) {
return file;
}
+// `xds theme build` imports the compiled @xds/core/theme entry (there is no
+// in-CLI fallback generator). Build core once if it isn't already present so
+// the suite works in any CI job, regardless of job ordering.
+beforeAll(() => {
+ if (!fs.existsSync(CORE_THEME_ENTRY)) {
+ execFileSync('pnpm', ['-F', '@xds/core', 'build'], {
+ cwd: REPO_ROOT,
+ stdio: 'pipe',
+ timeout: 180_000,
+ });
+ }
+}, 200_000);
+
let tmpDir;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'xds-build-theme-import-path-'));
diff --git a/packages/cli/src/commands/build-theme.mjs b/packages/cli/src/commands/build-theme.mjs
index fe24043389..db5b4dbd75 100644
--- a/packages/cli/src/commands/build-theme.mjs
+++ b/packages/cli/src/commands/build-theme.mjs
@@ -22,25 +22,27 @@ import {jsonOut, humanLog} from '../lib/json.mjs';
import {cliError} from '../lib/cli-error.mjs';
import {ERROR_CODES} from '../lib/error-codes.mjs';
-// Import shared theme processing from core — ensures build and runtime
-// use the same logic for typography.scale expansion, prose, and component rules.
-// When available, these imports supersede all local fallback implementations
-// (parsePadding, expandContainerPadding, parseStyleKey, generateCSS, generateProseCSS).
+// Import shared theme processing from core. `xds theme build` MUST produce the
+// exact same CSS as the `<Theme>` runtime, so it has exactly one generation
+// path: core's generator. There is no in-CLI fallback implementation — if this
+// import fails, the build fails (see the ERR_CORE_NOT_FOUND guard in the theme
+// action). A built, resolvable `@xds/core` is a hard requirement.
let _defineTheme = null;
-let _generateThemeRules = null;
let _generateThemeRulesSplit = null;
let _generateOnMediaCSS = null;
+let _coreImportError = null;
try {
const coreTheme = await import('@xds/core/theme');
_defineTheme = coreTheme.defineTheme;
- _generateThemeRules = coreTheme.generateThemeRules;
_generateThemeRulesSplit = coreTheme.generateThemeRulesSplit;
_generateOnMediaCSS = coreTheme.generateOnMediaCSS;
-} catch (_e) {
- // Silent fallback. The theme command surfaces a clear error if it's actually
- // invoked without core being available; emitting a stderr warning at module-
- // load time would leak into every other command's output and break the
- // clean-stderr contract under --json (and breaks tests that assert it).
+} catch (e) {
+ // Capture the reason so the theme action can surface a precise, actionable
+ // error. We don't throw here: this module is imported eagerly by the CLI
+ // entrypoint for every command, and a throw at load time would break
+ // unrelated commands (the entry wraps loads in try/catch and degrades the
+ // command to a stub). The hard failure happens when `theme build` runs.
+ _coreImportError = e;
}
/**
@@ -65,13 +67,6 @@ function generatedHeader(sourceFile, lang = 'js', command) {
return `/**\n * ${body.join('\n * ')}\n */\n\n`;
}
-/**
- * Convert camelCase CSS property to kebab-case
- */
-function toKebabCase(str) {
- return str.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);
-}
-
/**
* Convert a theme name to a valid JS identifier.
* e.g. 'default-minimal' → 'defaultMinimal', 'ocean' → 'ocean'
@@ -162,7 +157,6 @@ async function getKnownValues(componentName) {
return _knownValuesCache.get(componentName);
}
-
/**
* Generate TypeScript declaration content with module augmentation for custom
* component prop values found in the theme's `components` keys. Reads known
@@ -248,100 +242,6 @@ function resolveTokenValue(value) {
return value;
}
-/**
- * Parse a component style key into the legacy class selector suffix used by
- * built theme CSS today.
- * - `base` → ''
- * - `variant:secondary` → '.secondary'
- * - `level:1` → '.level-1' (digits get prefixed)
- * - `variant:destructive+size:sm` → '.destructive.sm'
- *
- * Runtime components also emit matching data-* prop reflections via xdsThemeProps()
- * (`data-variant="secondary"`, `data-level="1"`, etc.) for the data-attribute
- * selector migration. Keep the class output here until the generator migrates.
- *
- * <!-- SYNC: packages/core/src/utils/parseStyleKey.ts -->
- * <!-- SYNC: packages/core/src/utils/xdsThemeProps.ts -->
- * The digit-prefix and value-to-class logic must match across all three files.
- */
-
-// =============================================================================
-// Container padding mapping
-//
-// LEGACY FALLBACK: The functions below (parsePadding, expandContainerPadding,
-// parseStyleKey, generateCSS, generateProseCSS) duplicate logic from
-// @xds/core/theme (packages/core/src/theme/generateThemeRules.ts).
-//
-// When @xds/core is built, the CLI imports and uses the shared implementation
-// from core (see _generateThemeRules / _generateThemeRulesSplit at top of file).
-// These local copies exist only as a fallback for when core hasn't been built yet
-// (e.g., first-time bootstrap or CI environments where core builds after CLI).
-//
-// TODO: Remove this fallback once the monorepo build order guarantees core
-// is always available before CLI runs. Track in issue backlog.
-// =============================================================================
-
-const CONTAINER_COMPONENTS = new Set(['card', 'section', 'dialog']);
-const PADDING_PROPS = new Set([
- 'padding', 'paddingBlock', 'paddingInline',
- 'paddingBlockStart', 'paddingBlockEnd',
- 'paddingInlineStart', 'paddingInlineEnd',
-]);
-
-function parsePadding(props) {
- const result = {};
- for (const [prop, value] of props) {
- switch (prop) {
- case 'padding': {
- const parts = value.trim().split(/\s+/);
- if (parts.length === 1) {
- result.blockStart = parts[0];
- result.blockEnd = parts[0];
- result.inline = parts[0];
- } else if (parts.length === 2) {
- result.blockStart = parts[0];
- result.blockEnd = parts[0];
- result.inline = parts[1];
- } else if (parts.length >= 3) {
- result.blockStart = parts[0];
- result.inline = parts[1];
- result.blockEnd = parts[2];
- }
- break;
- }
- case 'paddingBlock': {
- const parts = value.trim().split(/\s+/);
- result.blockStart = parts[0];
- result.blockEnd = parts[1] ?? parts[0];
- break;
- }
- case 'paddingInline': {
- const parts = value.trim().split(/\s+/);
- if (parts.length === 1) {
- result.inline = parts[0];
- } else {
- result.inlineStart = parts[0];
- result.inlineEnd = parts[1];
- }
- break;
- }
- case 'paddingBlockStart':
- result.blockStart = value;
- break;
- case 'paddingBlockEnd':
- result.blockEnd = value;
- break;
- case 'paddingInlineStart':
- result.inlineStart = value;
- break;
- case 'paddingInlineEnd':
- result.inlineEnd = value;
- break;
- }
- }
- return result;
-}
-
// Dual-prefix theme @scope selector helpers (XDS-prefix migration
// P2380608025). Keep the `astryx` literal in sync with
// packages/core/src/naming.ts (NAMESPACE) and generateThemeRules.ts.
@@ -350,265 +250,6 @@ function parsePadding(props) {
const themeScopeStart = name =>
`[data-astryx-theme="${name}"], [data-xds-theme="${name}"]`;
const THEME_SCOPE_TO = `[data-astryx-theme], [data-xds-theme]`;
-const componentClassSelector = (component, suffix) =>
- `.astryx-${component}${suffix}, .xds-${component}${suffix}`;
-
-function expandContainerPadding(component, parsed) {
- // Emit the rebranded --astryx-<component>-padding tokens. The component reads
- // them via an inverted fallback (var(--xds-*, var(--astryx-*, default))) so a
- // legacy --xds-* override still wins during compat (XDS-prefix migration
- // P2380608025). Keep the `astryx` literal in sync with packages/core/src/naming.ts
- // (NAMESPACE) and the primary path in generateThemeRules.ts.
- const prefix = `--astryx-${component}-padding`;
- const tokens = [];
-
- // Resolve effective inline values (inlineStart/End override inline)
- const effectiveInlineStart = parsed.inlineStart ?? parsed.inline;
- const effectiveInlineEnd = parsed.inlineEnd ?? parsed.inline;
- const inlineSymmetric =
- effectiveInlineStart != null &&
- effectiveInlineEnd != null &&
- effectiveInlineStart === effectiveInlineEnd;
-
- // If all sides are the same, emit the shorthand token only
- const allSame =
- inlineSymmetric &&
- parsed.blockStart != null &&
- parsed.blockEnd != null &&
- effectiveInlineStart === parsed.blockStart &&
- parsed.blockStart === parsed.blockEnd;
-
- if (allSame) {
- tokens.push([prefix, effectiveInlineStart]);
- return tokens;
- }
-
- // Directional tokens
- if (parsed.inlineStart != null || parsed.inlineEnd != null) {
- // Asymmetric inline — emit start and end separately
- if (effectiveInlineStart != null) {
- tokens.push([`${prefix}-inline-start`, effectiveInlineStart]);
- }
- if (effectiveInlineEnd != null) {
- tokens.push([`${prefix}-inline-end`, effectiveInlineEnd]);
- }
- } else if (parsed.inline != null) {
- tokens.push([`${prefix}-inline`, parsed.inline]);
- }
- if (parsed.blockStart != null) {
- tokens.push([`${prefix}-block-start`, parsed.blockStart]);
- }
- if (parsed.blockEnd != null) {
- tokens.push([`${prefix}-block-end`, parsed.blockEnd]);
- }
- return tokens;
-}
-
-function parseStyleKey(key) {
- if (key === 'base') return '';
- return key
- .split('+')
- .map(part => {
- const [prop, value] = part.split(':');
- // Bare state name (no colon) — e.g. 'checked', 'disabled', 'selected'
- if (value === undefined) {
- return `.${prop}`;
- }
- if (/^\d/.test(value)) {
- return `.${prop}-${value}`;
- }
- return `.${value}`;
- })
- .join('');
-}
-
-/**
- * Maps component style keys to HTML elements for prose co-selection.
- *
- * When a theme overrides a prose-related component, the HTML element
- * counterpart should get the same styles. This map defines which
- * HTML elements correspond to which component + style key.
- *
- * 'base' overrides apply to all HTML counterparts.
- * Variant-specific overrides only apply to matching elements.
- */
-const PROSE_COMPONENT_MAP = {
- heading: {
- base: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'],
- },
- text: {
- base: ['p', 'small'],
- 'type:code': ['code', 'pre'],
- 'type:supporting': ['small'],
- },
- kbd: {
- base: ['kbd'],
- },
- link: {
- base: ['a'],
- },
- divider: {
- base: ['hr'],
- },
-};
-
-/**
- * Generate CSS from a theme definition object.
- * @deprecated Legacy fallback — see generateThemeRules.ts in @xds/core.
- *
- * When prose is enabled, component overrides for prose-related components
- * (heading, text, kbd, link, divider) co-select their HTML element
- * counterparts so raw markup inherits the theme's component styling.
- */
-function generateCSS(themeDef, {prose = true} = {}) {
- const parts = [];
- const scopeSelector = themeScopeStart(themeDef.name);
-
- // Token overrides — applied to the scope root
- if (themeDef.tokens && Object.keys(themeDef.tokens).length > 0) {
- const declarations = Object.entries(themeDef.tokens)
- .map(([prop, value]) => ` ${prop}: ${resolveTokenValue(value)};`)
- .join('\n');
- parts.push(` :scope {\n${declarations}\n }`);
- }
-
- // Component overrides
- if (themeDef.components) {
- for (const [component, rules] of Object.entries(themeDef.components)) {
- for (const [key, styles] of Object.entries(rules)) {
- const entries = Object.entries(styles);
- if (entries.length > 0) {
- const suffix = parseStyleKey(key);
-
- // Separate regular properties from pseudo-class overrides
- const props = [];
- const pseudos = [];
-
- for (const [prop, value] of entries) {
- if (prop.startsWith(':') && typeof value === 'object') {
- pseudos.push([prop, value]);
- } else {
- props.push([prop, value]);
- }
- }
-
- // Build selector — co-select HTML elements for prose-related components
- const xdsSelector = componentClassSelector(component, suffix);
- let baseSelector = ` ${xdsSelector}`;
-
- if (prose) {
- const htmlElements = PROSE_COMPONENT_MAP[component]?.[key];
- if (htmlElements) {
- const htmlSelector = htmlElements.map(el => ` ${el}`).join(',\n');
- baseSelector = ` ${xdsSelector},\n${htmlSelector}`;
- }
- }
-
- // Container padding mapping
- let finalProps = props;
- if (CONTAINER_COMPONENTS.has(component)) {
- const paddingProps = props.filter(([p]) => PADDING_PROPS.has(p));
- if (paddingProps.length > 0) {
- const nonPaddingProps = props.filter(([p]) => !PADDING_PROPS.has(p));
- const parsed = parsePadding(paddingProps);
- const containerTokens = expandContainerPadding(component, parsed);
- finalProps = [...nonPaddingProps, ...containerTokens];
- }
- }
-
- // Emit base rule
- if (finalProps.length > 0) {
- const declarations = finalProps
- .map(([prop, value]) => ` ${toKebabCase(prop)}: ${value};`)
- .join('\n');
- parts.push(`${baseSelector} {\n${declarations}\n }`);
- }
-
- // Emit pseudo-class rules
- for (const [pseudo, pseudoStyles] of pseudos) {
- const pseudoEntries = Object.entries(pseudoStyles);
- if (pseudoEntries.length > 0) {
- const declarations = pseudoEntries
- .map(([prop, value]) => ` ${toKebabCase(prop)}: ${value};`)
- .join('\n');
- // Pseudo-class rules only on xds selector, not prose co-selection
- parts.push(
- ` ${xdsSelector}${pseudo} {\n${declarations}\n }`,
- );
- }
- }
- }
- }
- }
- }
-
- if (parts.length === 0) return '';
-
- const inner = parts.join('\n\n');
- return `@scope (${scopeSelector}) to (${THEME_SCOPE_TO}) {\n${inner}\n}`;
-}
-
-// =============================================================================
-// Prose CSS generation
-// =============================================================================
-
-/**
- * Generate prose CSS — aliases raw HTML elements to XDS component classes.
- *
- * The actual styles live in xds.base (component CSS). Prose just says
- * "inside this theme, an <h1> should look like .xds-heading.level-1".
- * This is done via CSS @extend-like pattern: each HTML element inherits
- * the same class as its XDS counterpart.
- */
-function generateProseCSS(themeDef) {
- const scopeSelector = themeScopeStart(themeDef.name);
-
- // Each mapping becomes: h1 { /* same styles as .xds-heading.level-1 */ }
- // Since we can't @extend in plain CSS, we use the component's CSS custom
- // properties which are already set by xds.base. The prose elements just
- // need the same structural styles (font-family, margin reset, etc.)
- // that the base heading/text components apply.
- //
- // For now, we co-select: the component overrides in generateCSS already
- // target .xds-button, .xds-card, etc. Prose adds the HTML element as
- // an additional selector for component overrides that have an HTML equivalent.
- // CSS @extend isn't widely supported yet. Instead, generate rules that
- // reference the same token-based custom properties the components use.
- // This is a thin layer — just structural resets + token references.
- const parts = [];
-
- // Heading resets — all heading elements get the base heading treatment
- parts.push(` :is(h1, h2, h3, h4, h5, h6) {\n font-family: var(--font-family-heading);\n font-weight: var(--font-weight-semibold);\n color: var(--color-text-primary);\n margin: 0;\n }`);
-
- // Per-level heading sizes
- const headingSizes = {
- h1: {fontSize: 'var(--font-size-2xl)', lineHeight: '1.2'},
- h2: {fontSize: 'var(--font-size-xl)', lineHeight: '1.333'},
- h3: {fontSize: 'var(--font-size-lg)', lineHeight: '1.25'},
- h4: {fontSize: 'var(--font-size-base)', lineHeight: 'var(--leading-base)'},
- h5: {fontSize: 'var(--font-size-base)', lineHeight: 'var(--leading-base)'},
- h6: {fontSize: 'var(--font-size-xs)', lineHeight: '1.333'},
- };
-
- for (const [el, styles] of Object.entries(headingSizes)) {
- const declarations = Object.entries(styles)
- .map(([prop, value]) => ` ${toKebabCase(prop)}: ${value};`)
- .join('\n');
- parts.push(` ${el} {\n${declarations}\n }`);
- }
-
- // Text element resets
- parts.push(` p {\n font-family: var(--font-family-heading);\n color: var(--color-text-primary);\n margin: 0;\n font-size: var(--font-size-base);\n line-height: var(--leading-base);\n }`);
-
- parts.push(` small {\n font-size: var(--font-size-xs);\n line-height: 1.333;\n color: var(--color-text-secondary);\n }`);
-
- parts.push(` code, pre {\n font-family: var(--font-family-code);\n font-size: var(--font-size-base);\n line-height: var(--leading-base);\n }`);
-
- parts.push(` hr {\n border: none;\n border-top: 1px solid var(--color-border);\n margin: 0;\n }`);
-
- const inner = parts.join('\n\n');
- return `@scope (${scopeSelector}) to (${THEME_SCOPE_TO}) {\n${inner}\n}`;
-}
/**
* Import a theme module using jiti and find the defineTheme() result.
@@ -966,7 +607,6 @@ export function registerTheme(program) {
.command('build <file>')
.description('Compile a defineTheme file to CSS + JS')
.option('-o, --out <path>', 'Output CSS file path')
- .option('--no-prose', 'Skip prose mappings (h1, p, code, hr, etc.)')
.action(async (file, options) => {
const filePath = path.resolve(process.cwd(), file);
const json = program.opts().json || false;
@@ -1024,13 +664,27 @@ export function registerTheme(program) {
console.error(`\n ${privateVarErrors.length} private var error(s). Use standard CSS properties instead.`);
}
- // Generate CSS using the shared generateThemeRules from core.
- // This ensures build and runtime produce identical rule sets.
+ // Generate CSS via core's shared generator — the SINGLE source of truth.
+ // `xds theme build` and the `<Theme>` runtime MUST emit identical CSS, so
+ // there is exactly one generation path: @xds/core/theme. If core could not
+ // be imported, fail hard rather than silently producing divergent output.
+ if (!_defineTheme || !_generateThemeRulesSplit) {
+ cliError(
+ 'Could not load @xds/core/theme — `xds theme build` requires a ' +
+ 'built, resolvable @xds/core so it emits the same CSS as the ' +
+ 'runtime <Theme>. Build @xds/core first (e.g. `pnpm -F @xds/core ' +
+ 'build`)' +
+ (_coreImportError ? `.\n Import error: ${_coreImportError.message}` : '.'),
+ {code: ERROR_CODES.ERR_CORE_NOT_FOUND},
+ );
+ }
+
let css;
let resolvedTheme;
- if (_defineTheme && _generateThemeRules) {
+ {
// jiti returns an already-resolved theme; legacy eval returns raw input.
- const isAlreadyResolved = !themeDef.typography && !themeDef.motion && !themeDef.radius;
+ const isAlreadyResolved =
+ !themeDef.typography && !themeDef.motion && !themeDef.radius;
if (isAlreadyResolved) {
resolvedTheme = themeDef;
} else {
@@ -1046,65 +700,40 @@ export function registerTheme(program) {
const scopeSelector = themeScopeStart(themeDef.name);
const scopeTo = THEME_SCOPE_TO;
- if (_generateThemeRulesSplit) {
- const {component, prose} = _generateThemeRulesSplit(resolvedTheme);
- const cssParts = [];
- if (options.prose !== false && prose.length > 0) {
- const proseInner = prose.join('\n\n');
- cssParts.push(`@layer reset {\n@scope (${scopeSelector}) to (${scopeTo}) {\n${proseInner}\n}\n}`);
- }
- if (component.length > 0) {
- const componentInner = component.join('\n\n');
- const componentScope = `@scope (${scopeSelector}) to (${scopeTo}) {\n${componentInner}\n}`;
- const colorSchemeDecl = componentScope.includes('light-dark(')
- ? ' :root { color-scheme: light dark; }\n\n'
- : '';
- cssParts.push(`@layer xds-theme {\n${colorSchemeDecl}${componentScope}\n}`);
- }
- // On-media rules (XDSMediaTheme dark/light surface overrides)
- if (_generateOnMediaCSS) {
- const onMediaCss = _generateOnMediaCSS(resolvedTheme);
- if (onMediaCss) {
- cssParts.push(`@layer xds-theme {\n${onMediaCss}\n}`);
- }
- }
- css = cssParts.join('\n\n') + '\n';
- } else {
- const rules = _generateThemeRules(resolvedTheme);
- if (rules.length > 0) {
- const inner = rules.join('\n\n');
- const scopeBlock = `@scope (${scopeSelector}) to (${scopeTo}) {\n${inner}\n}`;
- const colorSchemeDecl = scopeBlock.includes('light-dark(')
- ? ' :root { color-scheme: light dark; }\n\n'
- : '';
- css = `@layer xds-theme {\n${colorSchemeDecl}${scopeBlock}\n}\n`;
- // On-media rules (legacy path)
- if (_generateOnMediaCSS) {
- const onMediaCss = _generateOnMediaCSS(resolvedTheme);
- if (onMediaCss) {
- css += `\n@layer xds-theme {\n${onMediaCss}\n}\n`;
- }
- }
- }
+ const {component, prose} = _generateThemeRulesSplit(resolvedTheme);
+ const cssParts = [];
+ // Prose element defaults always ship — the `<Theme>` runtime
+ // (generateThemeCSS) always emits them, so the build must too, or the
+ // CLI output would diverge from runtime. They go in @layer reset
+ // (zero-specificity :where()) so component/Markdown StyleX always wins.
+ if (prose.length > 0) {
+ const proseInner = prose.join('\n\n');
+ cssParts.push(
+ `@layer reset {\n@scope (${scopeSelector}) to (${scopeTo}) {\n${proseInner}\n}\n}`,
+ );
}
- } else {
- // Legacy fallback when core isn't built yet
- const scopeBlocks = [];
- if (options.prose !== false) {
- const proseCss = generateProseCSS(themeDef);
- if (proseCss) scopeBlocks.push(proseCss);
+ if (component.length > 0) {
+ const componentInner = component.join('\n\n');
+ const componentScope = `@scope (${scopeSelector}) to (${scopeTo}) {\n${componentInner}\n}`;
+ const colorSchemeDecl = componentScope.includes('light-dark(')
+ ? ' :root { color-scheme: light dark; }\n\n'
+ : '';
+ cssParts.push(
+ `@layer xds-theme {\n${colorSchemeDecl}${componentScope}\n}`,
+ );
+ }
+ // On-media rules (MediaTheme dark/light surface overrides)
+ if (_generateOnMediaCSS) {
+ const onMediaCss = _generateOnMediaCSS(resolvedTheme);
+ if (onMediaCss) {
+ cssParts.push(`@layer xds-theme {\n${onMediaCss}\n}`);
+ }
}
- const mainCss = generateCSS(themeDef);
- if (mainCss) scopeBlocks.push(mainCss);
- if (scopeBlocks.length === 0) {
+ if (cssParts.length === 0) {
if (!json) humanLog('No overrides found — nothing to build.');
return;
}
- const joined = scopeBlocks.join('\n\n');
- const colorSchemeDecl = joined.includes('light-dark(')
- ? ' :root { color-scheme: light dark; }\n\n'
- : '';
- css = `@layer xds-theme {\n${colorSchemeDecl}${joined}\n}\n`;
+ css = cssParts.join('\n\n') + '\n';
}
// Source path relative to cwd — used in @generated headers
diff --git a/packages/cli/src/commands/build-theme.no-prose.test.mjs b/packages/cli/src/commands/build-theme.no-prose.test.mjs
deleted file mode 100644
index ffd09febbb..0000000000
--- a/packages/cli/src/commands/build-theme.no-prose.test.mjs
+++ /dev/null
@@ -1,111 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file Regression test for `xds theme build --no-prose`.
- *
- * Covers:
- * - Default build emits the `@layer reset` block with prose mappings
- * (h1, p, code, hr, …) so unstyled HTML inherits XDS typography.
- * - `--no-prose` skips that block entirely. Useful when a project ships
- * its own typography (Tailwind prose, CMS prose styles, etc.) and
- * wants only the component layer.
- */
-
-import {describe, it, expect, beforeEach, afterEach} from 'vitest';
-import {execFileSync} from 'node:child_process';
-import * as fs from 'node:fs';
-import * as path from 'node:path';
-import * as os from 'node:os';
-import {fileURLToPath} from 'node:url';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const CLI_BIN = path.resolve(__dirname, '../../bin/xds.mjs');
-
-function runCli(args, cwd) {
- try {
- const out = execFileSync('node', [CLI_BIN, ...args], {
- cwd,
- encoding: 'utf-8',
- stdio: ['ignore', 'pipe', 'pipe'],
- env: {...process.env, FORCE_COLOR: '0'},
- });
- return {code: 0, stdout: out, stderr: ''};
- } catch (e) {
- return {
- code: e.status ?? 1,
- stdout: e.stdout?.toString() ?? '',
- stderr: e.stderr?.toString() ?? '',
- };
- }
-}
-
-function writeTheme(dir, name) {
- fs.mkdirSync(dir, {recursive: true});
- // The CLI writes <basename>.css next to the source file, so use the
- // theme name as the filename for unambiguous fixtures.
- const file = path.join(dir, `${name}.mjs`);
- fs.writeFileSync(
- file,
- `export default { name: ${JSON.stringify(name)}, tokens: { '--color-bg': '#fff' } };\n`,
- );
- return file;
-}
-
-let tmpDir;
-beforeEach(() => {
- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'xds-build-theme-no-prose-'));
-});
-afterEach(() => {
- fs.rmSync(tmpDir, {recursive: true, force: true});
-});
-
-describe('theme build --no-prose', () => {
- it('emits prose mappings by default', () => {
- const project = path.join(tmpDir, 'project');
- const themesDir = path.join(project, 'themes');
- const themeFile = writeTheme(themesDir, 'with-prose');
-
- const result = runCli(
- ['theme', 'build', path.relative(project, themeFile)],
- project,
- );
-
- expect(result.code).toBe(0);
-
- const cssPath = path.join(themesDir, 'with-prose.css');
- expect(fs.existsSync(cssPath)).toBe(true);
- const css = fs.readFileSync(cssPath, 'utf-8');
-
- // Prose markers — at least one heading reset and the reset layer
- // should be present in the default build.
- const hasProse =
- /h1\s*,\s*h2/.test(css) ||
- /:is\(h1, h2/.test(css) ||
- /@layer reset/.test(css);
- expect(hasProse).toBe(true);
- });
-
- it('omits prose mappings when --no-prose is passed', () => {
- const project = path.join(tmpDir, 'project');
- const themesDir = path.join(project, 'themes');
- const themeFile = writeTheme(themesDir, 'no-prose');
-
- const result = runCli(
- ['theme', 'build', path.relative(project, themeFile), '--no-prose'],
- project,
- );
-
- expect(result.code).toBe(0);
-
- const cssPath = path.join(themesDir, 'no-prose.css');
- expect(fs.existsSync(cssPath)).toBe(true);
- const css = fs.readFileSync(cssPath, 'utf-8');
-
- // None of the prose markers should appear when --no-prose is set.
- expect(css).not.toMatch(/@layer reset/);
- expect(css).not.toMatch(/:is\(h1, h2, h3/);
- expect(css).not.toMatch(/^\s*h1\s*\{/m);
- expect(css).not.toMatch(/^\s*p\s*\{/m);
- expect(css).not.toMatch(/^\s*hr\s*\{/m);
- });
-});
diff --git a/packages/cli/src/commands/build-theme.prose.test.mjs b/packages/cli/src/commands/build-theme.prose.test.mjs
new file mode 100644
index 0000000000..9abfc22011
--- /dev/null
+++ b/packages/cli/src/commands/build-theme.prose.test.mjs
@@ -0,0 +1,135 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Regression test for prose output of `xds theme build`.
+ *
+ * `xds theme build` has a single CSS-generation path — @xds/core's generator,
+ * the same one the <Theme> runtime uses (generateThemeCSS). It always emits
+ * prose element defaults (h1–h6, p, small, code, hr) so unstyled HTML inherits
+ * the theme's typography, exactly like the runtime. There is intentionally no
+ * way to omit them (the old `--no-prose` flag was removed: it let the build
+ * emit something the runtime never would, breaking the build⇄runtime parity).
+ *
+ * Covers:
+ * - prose defaults ship in `@layer reset` (zero-specificity :where()), NOT
+ * `@layer xds-theme`, so component/Markdown StyleX always wins;
+ * - no raw element margins are emitted (reset.css zeroes them and the
+ * components own block spacing — see the docsite Markdown regression);
+ * - paragraphs use the body font, not the heading font.
+ *
+ * Building `xds theme build` requires a compiled @xds/core (there is no in-CLI
+ * fallback generator), so this suite builds core once in beforeAll — mirroring
+ * scripts/build-css.test.mjs — to stay self-sufficient regardless of CI job
+ * ordering.
+ */
+
+import {describe, it, expect, beforeAll, beforeEach, afterEach} from 'vitest';
+import {execFileSync} from 'node:child_process';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {fileURLToPath} from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const CLI_BIN = path.resolve(__dirname, '../../bin/xds.mjs');
+const REPO_ROOT = path.resolve(__dirname, '../../../..');
+const CORE_THEME_ENTRY = path.join(
+ REPO_ROOT,
+ 'packages/core/dist/theme/index.js',
+);
+
+function runCli(args, cwd) {
+ try {
+ const out = execFileSync('node', [CLI_BIN, ...args], {
+ cwd,
+ encoding: 'utf-8',
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: {...process.env, FORCE_COLOR: '0'},
+ });
+ return {code: 0, stdout: out, stderr: ''};
+ } catch (e) {
+ return {
+ code: e.status ?? 1,
+ stdout: e.stdout?.toString() ?? '',
+ stderr: e.stderr?.toString() ?? '',
+ };
+ }
+}
+
+function writeTheme(dir, name) {
+ fs.mkdirSync(dir, {recursive: true});
+ // The CLI writes <basename>.css next to the source file, so use the
+ // theme name as the filename for unambiguous fixtures.
+ const file = path.join(dir, `${name}.mjs`);
+ fs.writeFileSync(
+ file,
+ `export default { name: ${JSON.stringify(name)}, tokens: { '--color-bg': '#fff' } };\n`,
+ );
+ return file;
+}
+
+// `xds theme build` imports the compiled @xds/core/theme entry. Build core
+// once if it isn't already present so the suite works in any CI job.
+beforeAll(() => {
+ if (!fs.existsSync(CORE_THEME_ENTRY)) {
+ execFileSync('pnpm', ['-F', '@xds/core', 'build'], {
+ cwd: REPO_ROOT,
+ stdio: 'pipe',
+ timeout: 180_000,
+ });
+ }
+}, 200_000);
+
+let tmpDir;
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'xds-build-theme-prose-'));
+});
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe('theme build prose output', () => {
+ it('always emits prose mappings in @layer reset', () => {
+ const project = path.join(tmpDir, 'project');
+ const themesDir = path.join(project, 'themes');
+ const themeFile = writeTheme(themesDir, 'with-prose');
+
+ const result = runCli(
+ ['theme', 'build', path.relative(project, themeFile)],
+ project,
+ );
+
+ expect(result.code).toBe(0);
+
+ const cssPath = path.join(themesDir, 'with-prose.css');
+ expect(fs.existsSync(cssPath)).toBe(true);
+ const css = fs.readFileSync(cssPath, 'utf-8');
+
+ // Prose defaults are zero-specificity :where() rules in @layer reset,
+ // NOT @layer xds-theme, so Markdown/component StyleX always wins.
+ expect(css).toMatch(/@layer reset/);
+ expect(css).toMatch(/:where\(h1, h2, h3, h4, h5, h6\)/);
+ // Paragraphs use the body font (regression: they used the heading font).
+ expect(css).toMatch(/:where\(p\)[^}]*font-family: var\(--font-family-body\)/);
+ // No raw element margins — reset.css + component StyleX own spacing.
+ const proseBlock = css.slice(
+ css.indexOf('@layer reset'),
+ css.indexOf('@layer xds-theme'),
+ );
+ expect(proseBlock).not.toMatch(/margin/);
+
+ // Layer placement: prose (reset) must come before component overrides
+ // (xds-theme) so the cascade resolves correctly.
+ const resetIndex = css.indexOf('@layer reset');
+ const themeIndex = css.indexOf('@layer xds-theme');
+ expect(resetIndex).toBeGreaterThanOrEqual(0);
+ expect(themeIndex).toBeGreaterThan(resetIndex);
+ expect(css.indexOf(':where(p)')).toBeLessThan(themeIndex);
+ });
+
+ it('has no --no-prose flag (prose is non-optional)', () => {
+ const result = runCli(['theme', 'build', '--help'], process.cwd());
+ // The flag was removed; build always emits prose to match the runtime.
+ expect(result.stdout + result.stderr).not.toContain('--no-prose');
+ });
+});
diff --git a/packages/core/babel-plugin-add-extensions.cjs b/packages/core/babel-plugin-add-extensions.cjs
index 666d75d2e6..9e652e966e 100644
--- a/packages/core/babel-plugin-add-extensions.cjs
+++ b/packages/core/babel-plugin-add-extensions.cjs
@@ -26,6 +26,19 @@ module.exports = function addExtensions() {
const source = path.node.source;
if (!source) return;
const value = source.value;
+
+ // Compat alias barrels self-re-export from `'.'` in source. Node ESM
+ // does not support directory imports in built output, so make the self
+ // reference explicit (`./index.js`) during compilation.
+ if (value === '.') {
+ source.value = './index.js';
+ return;
+ }
+ if (value === '..') {
+ source.value = '../index.js';
+ return;
+ }
+
if (!value.startsWith('./') && !value.startsWith('../')) return;
if (SKIP.test(value)) return;
diff --git a/packages/core/src/theme/generateThemeRules.test.ts b/packages/core/src/theme/generateThemeRules.test.ts
index ba9517351a..842f693061 100644
--- a/packages/core/src/theme/generateThemeRules.test.ts
+++ b/packages/core/src/theme/generateThemeRules.test.ts
@@ -124,6 +124,25 @@ describe('generateThemeRules', () => {
expect(buttonRule).toContain('light-dark(rgba(5, 54, 89, 0.1)');
});
+ it('applies pseudo-class suffixes to both compat selector prefixes', () => {
+ const pseudoTheme = defineTheme({
+ name: 'pseudo-compat',
+ components: {
+ button: {
+ base: {
+ ':hover': {color: 'red'},
+ },
+ },
+ },
+ });
+ const pseudoRules = generateThemeRules(pseudoTheme);
+ expect(
+ pseudoRules.some(rule =>
+ rule.includes('.astryx-button:hover, .xds-button:hover'),
+ ),
+ ).toBe(true);
+ });
+
// --- Prose rules ---
it('includes prose heading rules with computed values', () => {
@@ -134,6 +153,12 @@ describe('generateThemeRules', () => {
// Prose rules use val() helper which resolves to the token value (now a var ref)
expect(h1Rule).toContain('var(--font-size-2xl)');
expect(h1Rule).toContain('var(--font-weight-semibold)');
+ // Prose defaults intentionally carry NO block margins: reset.css zeroes
+ // raw element margins and the Markdown/Heading components own their spacing
+ // via StyleX (@layer xds-base). Emitting margins here would re-introduce
+ // the regression where prose defaults fought component spacing.
+ expect(h1Rule).not.toContain('margin-block-start');
+ expect(h1Rule).not.toContain('margin-block-end');
});
it('includes prose p rule with computed values', () => {
@@ -142,7 +167,10 @@ describe('generateThemeRules', () => {
);
expect(pRule).toBeDefined();
expect(pRule).toContain('var(--font-size-base)');
+ expect(pRule).toContain('font-family: var(--font-family-body)');
expect(pRule).toContain('var(--color-text-primary)');
+ // No margins on the prose paragraph default (see heading rule note).
+ expect(pRule).not.toContain('margin-block-start');
});
it('includes prose small, code, hr rules', () => {
@@ -209,7 +237,6 @@ describe('generateThemeRules with weight overrides', () => {
});
});
-
// =============================================================================
// Derived var expansion
// =============================================================================
@@ -344,7 +371,6 @@ describe('derived var expansion', () => {
});
});
-
describe('brutalist-style derived expansion', () => {
it('button borderRadius emits --_button-radius for pill shape', () => {
const theme = defineTheme({
diff --git a/packages/core/src/theme/generateThemeRules.ts b/packages/core/src/theme/generateThemeRules.ts
index 64c82d6df8..b98c1965fa 100644
--- a/packages/core/src/theme/generateThemeRules.ts
+++ b/packages/core/src/theme/generateThemeRules.ts
@@ -55,6 +55,35 @@ function componentClassSelector(component: string, suffix: string): string {
return `.${classPrefix}-${component}${suffix}, .${legacyClassPrefix}-${component}${suffix}`;
}
+/**
+ * Append a pseudo-class to every selector in a comma-separated selector list.
+ *
+ * The compat selector helpers emit lists such as
+ * `.astryx-button.secondary, .xds-button.secondary`. CSS does not distribute a
+ * trailing pseudo over selector lists, so `${list}:hover` only targets the
+ * final legacy selector. Keep pseudo rules dual-prefix by rewriting each item.
+ */
+function appendPseudoToSelectorList(selector: string, pseudo: string): string {
+ const parts: string[] = [];
+ let depth = 0;
+ let start = 0;
+
+ for (let i = 0; i < selector.length; i++) {
+ const char = selector[i];
+ if (char === '(') {
+ depth++;
+ } else if (char === ')') {
+ depth = Math.max(0, depth - 1);
+ } else if (char === ',' && depth === 0) {
+ parts.push(selector.slice(start, i).trim());
+ start = i + 1;
+ }
+ }
+ parts.push(selector.slice(start).trim());
+
+ return parts.map(part => `${part}${pseudo}`).join(', ');
+}
+
// =============================================================================
// Types
// =============================================================================
@@ -381,7 +410,9 @@ function generateComponentRules(
const declarations = pseudoEntries
.map(([prop, value]) => ` ${toKebabCase(prop)}: ${value};`)
.join('\n');
- parts.push(` ${baseSelector}${pseudo} {\n${declarations}\n }`);
+ parts.push(
+ ` ${appendPseudoToSelectorList(baseSelector, pseudo)} {\n${declarations}\n }`,
+ );
}
}
}
@@ -413,7 +444,7 @@ function generateProseRules(
}
parts.push(` :where(p) {
- font-family: var(--font-family-heading);
+ font-family: var(--font-family-body);
font-size: ${val('--text-body-size')};
font-weight: ${val('--text-body-weight')};
line-height: ${val('--text-body-leading')};
@@ -575,7 +606,9 @@ export function generateOnMediaCSS(theme: DefinedTheme): string {
const declarations = pseudoEntries
.map(([prop, value]) => ` ${toKebabCase(prop)}: ${value};`)
.join('\n');
- parts.push(` ${baseSelector}${pseudo} {\n${declarations}\n }`);
+ parts.push(
+ ` ${appendPseudoToSelectorList(baseSelector, pseudo)} {\n${declarations}\n }`,
+ );
}
}
}
diff --git a/packages/core/src/theme/onMediaTokens.test.ts b/packages/core/src/theme/onMediaTokens.test.ts
index 835affefeb..5acf6b5f37 100644
--- a/packages/core/src/theme/onMediaTokens.test.ts
+++ b/packages/core/src/theme/onMediaTokens.test.ts
@@ -194,7 +194,9 @@ describe('generateOnMediaCSS', () => {
},
});
const css = generateOnMediaCSS(theme);
- expect(css).toContain(':is(.astryx-button, .xds-button):hover');
+ expect(css).toContain(
+ ':is([data-astryx-media="dark"], [data-xds-media="dark"]) :is(.astryx-button, .xds-button):hover',
+ );
expect(css).toContain('color: rgba(255,255,255,0.8)');
});
});
diff --git a/packages/core/src/utils/parseStyleKey.ts b/packages/core/src/utils/parseStyleKey.ts
index 484e5acaf1..95d2626868 100644
--- a/packages/core/src/utils/parseStyleKey.ts
+++ b/packages/core/src/utils/parseStyleKey.ts
@@ -6,7 +6,6 @@
* Used by both defineTheme (CSS generation) and components (class name rendering)
* to ensure the same convention is applied consistently.
*
- * <!-- SYNC: packages/cli/src/commands/build-theme.mjs (parseStyleKey) -->
* <!-- SYNC: packages/core/src/utils/xdsThemeProps.ts -->
*
* Emits the legacy class-selector suffix used by defineTheme/component override
diff --git a/packages/core/src/utils/xdsThemeProps.ts b/packages/core/src/utils/xdsThemeProps.ts
index 7fc91e6f51..24852e4401 100644
--- a/packages/core/src/utils/xdsThemeProps.ts
+++ b/packages/core/src/utils/xdsThemeProps.ts
@@ -4,10 +4,7 @@ import {stableClassName, legacyStableClassName} from '../naming';
export type ClassValue = string | number | undefined | null;
export type ClassProps = Record<string, ClassValue>;
-export type ThemeDataAttributes = Record<
- `data-${string}`,
- string | undefined
->;
+export type ThemeDataAttributes = Record<`data-${string}`, string | undefined>;
export type ThemeProps = {className: string} & ThemeDataAttributes;
function toDataAttributeName(prop: string): `data-${string}` {
@@ -32,7 +29,6 @@ function classTokenForPropValue(prop: string, value: string): string {
* (`packages/core/src/naming.ts`) so the prefix migration flips in one place.
*
* <!-- SYNC: packages/core/src/naming.ts (namespace prefix source of truth) -->
- * <!-- SYNC: packages/cli/src/commands/build-theme.mjs (parseStyleKey + selector generation) -->
* <!-- SYNC: packages/core/src/utils/parseStyleKey.ts -->
*
* Values starting with a digit get prefixed with the prop name since
@@ -59,7 +55,10 @@ function dualClassName(component: string, props?: ClassProps): string {
// Dual-emit both the new (astryx-*) and legacy (xds-*) base class so existing
// consumer CSS selectors keep matching during the compat window. The new
// prefix is listed first; legacy stays until the final cutover (P10).
- const classes = [stableClassName(component), legacyStableClassName(component)];
+ const classes = [
+ stableClassName(component),
+ legacyStableClassName(component),
+ ];
if (props) {
for (const [prop, value] of Object.entries(props)) {