An open source design system that's fully customizable and agent ready
TypeScript
feat: pre-compiled CSS dist with @layer xds (#451)
Cindy Zhangcd551b9ce2ef
diff --git a/packages/core/package.json b/packages/core/package.jsonindex 22e22108ae..c03893ae97 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -351,7 +351,8 @@"types": "./dist/utils/index.d.ts","import": "./dist/utils/index.mjs","require": "./dist/utils/index.js"- }+ },+ "./xds.css": "./dist/xds.css"},"files": ["dist",@@ -364,7 +365,9 @@"dev": "tsup --watch","test": "vitest run --root ../..","test:watch": "vitest --root ../..",- "lint": "eslint src"+ "lint": "eslint src",+ "build:css": "node ../../scripts/build-css.mjs",+ "postbuild": "yarn build:css"},"peerDependencies": {"react": ">=19.0.0",@@ -383,4 +386,4 @@"dependencies": {"@stylexjs/stylex": "^0.17.4"}-}+}\ No newline at end of filediff --git a/packages/core/src/reset.css b/packages/core/src/reset.cssindex fbf33320c4..0aaf441432 100644--- a/packages/core/src/reset.css+++ b/packages/core/src/reset.css@@ -21,9 +21,11 @@* 2. Combine with theme and typography:* import '@xds/core/reset.css'; // @layer reset — clean slate* import '@xds/core/typography.css'; // @layer typography — prose styles- * // XDS components handle their own styles+ * import '@xds/core/xds.css'; // @layer xds — component styles+ * import '@xds/theme-default/theme.css'; // @layer xds.theme — theme overrides*- * Layer order: reset → typography → components+ * Layer order: reset → typography → xds → xds.theme+ * Consumer styles (unlayered) always override all XDS layers.* The reset has the lowest priority and can be overridden by any other layer.** Similar to:diff --git a/packages/themes/default/package.json b/packages/themes/default/package.jsonindex 51290b4e81..9b33bf6f68 100644--- a/packages/themes/default/package.json+++ b/packages/themes/default/package.json@@ -13,7 +13,8 @@"types": "./dist/index.d.ts","import": "./dist/index.mjs","require": "./dist/index.js"- }+ },+ "./theme.css": "./dist/theme.css"},"files": ["dist",@@ -21,7 +22,9 @@],"scripts": {"build": "tsup",- "dev": "tsup --watch"+ "dev": "tsup --watch",+ "build:css": "node ../../../scripts/build-theme-css.mjs packages/themes/default",+ "postbuild": "yarn build:css"},"dependencies": {"@heroicons/react": "^2.2.0"@@ -39,4 +42,4 @@"esbuild-plugin-babel": "^0.2.3","tsup": "^8.3.0"}-}+}\ No newline at end of filediff --git a/packages/themes/neutral/package.json b/packages/themes/neutral/package.jsonindex e796946485..752fe151e5 100644--- a/packages/themes/neutral/package.json+++ b/packages/themes/neutral/package.json@@ -13,7 +13,8 @@"types": "./dist/index.d.ts","import": "./dist/index.mjs","require": "./dist/index.js"- }+ },+ "./theme.css": "./dist/theme.css"},"files": ["dist",@@ -21,7 +22,9 @@],"scripts": {"build": "tsup",- "dev": "tsup --watch"+ "dev": "tsup --watch",+ "build:css": "node ../../../scripts/build-theme-css.mjs packages/themes/neutral",+ "postbuild": "yarn build:css"},"dependencies": {"lucide-react": "^0.575.0"@@ -39,4 +42,4 @@"esbuild-plugin-babel": "^0.2.3","tsup": "^8.3.0"}-}+}\ No newline at end of filediff --git a/scripts/build-css.mjs b/scripts/build-css.mjsnew file mode 100644index 0000000000..3f7c3eb005--- /dev/null+++ b/scripts/build-css.mjs@@ -0,0 +1,128 @@+/**+ * @file build-css.mjs+ * Post-build script that extracts StyleX CSS from compiled source files+ * and outputs a single xds.css wrapped in @layer xds.+ *+ * Usage: node scripts/build-css.mjs+ *+ * This script:+ * 1. Runs Babel with the StyleX plugin over all source files+ * 2. Collects the CSS rules StyleX generates+ * 3. Wraps them in @layer xds { ... }+ * 4. Writes to packages/core/dist/xds.css+ *+ * The resulting CSS file can be imported by consumers who don't have+ * StyleX in their build pipeline:+ *+ * import '@xds/core/xds.css';+ */++import {transformAsync} from '@babel/core';+import stylexBabelPlugin from '@stylexjs/babel-plugin';+import fs from 'fs/promises';+import path from 'path';+import {fileURLToPath} from 'url';+import {glob} from 'glob';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const ROOT = path.resolve(__dirname, '..');+const CORE_SRC = path.resolve(ROOT, 'packages/core/src');+const CORE_DIST = path.resolve(ROOT, 'packages/core/dist');++async function collectStyleXCSS() {+ // Find all TypeScript/TSX source files+ const files = await glob('**/*.{ts,tsx}', {+ cwd: CORE_SRC,+ absolute: true,+ ignore: ['**/*.test.*', '**/*.d.ts', '**/node_modules/**'],+ });++ console.log(`Processing ${files.length} source files...`);++ const allRules = [];++ for (const file of files) {+ const code = await fs.readFile(file, 'utf8');++ // Skip files that don't use stylex+ if (!code.includes('@stylexjs/stylex')) {+ continue;+ }++ try {+ const result = await transformAsync(code, {+ babelrc: false,+ filename: file,+ presets: [+ ['@babel/preset-typescript', {isTSX: true, allExtensions: true}],+ ['@babel/preset-react', {runtime: 'automatic'}],+ ],+ plugins: [+ [+ stylexBabelPlugin,+ {+ dev: false,+ runtimeInjection: false,+ genConditionalClasses: true,+ treeshakeCompensation: true,+ unstable_moduleResolution: {+ type: 'commonJS',+ rootDir: ROOT,+ },+ },+ ],+ ],+ });++ if (result?.metadata?.stylex) {+ allRules.push(...result.metadata.stylex);+ }+ } catch (err) {+ console.warn(` Warning: Could not process ${path.relative(ROOT, file)}: ${err.message}`);+ }+ }++ console.log(`Collected ${allRules.length} StyleX rules`);++ if (allRules.length === 0) {+ console.warn('No StyleX rules found!');+ return '';+ }++ // Use StyleX's built-in CSS processor to sort and dedupe rules+ const css = stylexBabelPlugin.processStylexRules(allRules, false);++ // Wrap in @layer xds+ const layeredCSS = `/* XDS Pre-compiled StyleX CSS */+/* This file is auto-generated. Do not edit manually. */+/* Consumer styles (unlayered) always override these styles. */++@layer xds {+${css.split('\n').map(line => ' ' + line).join('\n')}+}+`;++ return layeredCSS;+}++async function main() {+ const css = await collectStyleXCSS();++ if (!css) {+ console.error('Failed to collect CSS');+ process.exit(1);+ }++ // Ensure dist directory exists+ await fs.mkdir(CORE_DIST, {recursive: true});++ const outPath = path.resolve(CORE_DIST, 'xds.css');+ await fs.writeFile(outPath, css, 'utf8');+ console.log(`\nWritten to ${path.relative(ROOT, outPath)}`);+ console.log(`Size: ${(css.length / 1024).toFixed(1)} KB`);+}++main().catch(err => {+ console.error(err);+ process.exit(1);+});diff --git a/scripts/build-theme-css.mjs b/scripts/build-theme-css.mjsnew file mode 100644index 0000000000..37fc4df735--- /dev/null+++ b/scripts/build-theme-css.mjs@@ -0,0 +1,118 @@+/**+ * @file build-theme-css.mjs+ * Post-build script that extracts StyleX CSS from theme packages+ * and outputs theme.css files.+ *+ * Usage: node scripts/build-theme-css.mjs <theme-dir>+ * Example: node scripts/build-theme-css.mjs packages/themes/default+ */++import {transformAsync} from '@babel/core';+import stylexBabelPlugin from '@stylexjs/babel-plugin';+import fs from 'fs/promises';+import path from 'path';+import {fileURLToPath} from 'url';+import {glob} from 'glob';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const ROOT = path.resolve(__dirname, '..');++const themeDir = process.argv[2];+if (!themeDir) {+ console.error('Usage: node scripts/build-theme-css.mjs <theme-dir>');+ process.exit(1);+}++const THEME_SRC = path.resolve(ROOT, themeDir, 'src');+const THEME_DIST = path.resolve(ROOT, themeDir, 'dist');++async function collectThemeCSS() {+ const files = await glob('**/*.{ts,tsx}', {+ cwd: THEME_SRC,+ absolute: true,+ ignore: ['**/*.test.*', '**/*.d.ts'],+ });++ console.log(`Processing ${files.length} theme files from ${themeDir}...`);++ const allRules = [];++ for (const file of files) {+ const code = await fs.readFile(file, 'utf8');+ if (!code.includes('@stylexjs/stylex')) continue;++ try {+ const result = await transformAsync(code, {+ babelrc: false,+ filename: file,+ presets: [+ ['@babel/preset-typescript', {isTSX: true, allExtensions: true}],+ ['@babel/preset-react', {runtime: 'automatic'}],+ ],+ plugins: [+ [+ stylexBabelPlugin,+ {+ dev: false,+ runtimeInjection: false,+ genConditionalClasses: true,+ treeshakeCompensation: true,+ aliases: {+ '@xds/core/*': [path.join(ROOT, 'packages/core/src/*')],+ },+ unstable_moduleResolution: {+ type: 'commonJS',+ rootDir: ROOT,+ },+ },+ ],+ ],+ });++ if (result?.metadata?.stylex) {+ allRules.push(...result.metadata.stylex);+ }+ } catch (err) {+ console.warn(` Warning: ${path.relative(ROOT, file)}: ${err.message}`);+ }+ }++ console.log(`Collected ${allRules.length} StyleX rules`);++ if (allRules.length === 0) {+ console.warn('No StyleX rules found in theme!');+ return '';+ }++ const css = stylexBabelPlugin.processStylexRules(allRules, false);+ const themeName = path.basename(themeDir);++ const layeredCSS = `/* XDS Theme: ${themeName} — Pre-compiled StyleX CSS */+/* This file is auto-generated. Do not edit manually. */++@layer xds.theme {+${css.split('\n').map(line => ' ' + line).join('\n')}+}+`;++ return layeredCSS;+}++async function main() {+ const css = await collectThemeCSS();+ if (!css) {+ console.error('Failed to collect theme CSS');+ process.exit(1);+ }++ await fs.mkdir(THEME_DIST, {recursive: true});+ const outPath = path.resolve(THEME_DIST, 'theme.css');+ await fs.writeFile(outPath, css, 'utf8');+ console.log(`Written to ${path.relative(ROOT, outPath)}`);+ console.log(`Size: ${(css.length / 1024).toFixed(1)} KB`);+}++main().catch(err => {+ console.error(err);+ process.exit(1);+});