An open source design system that's fully customizable and agent ready
TypeScript
feat: consolidate build plugins into @xds/build (#1447)
Cindy Zhangfc5e62fa80c9
diff --git a/apps/example-nextjs-source/README.md b/apps/example-nextjs-source/README.mdnew file mode 100644index 0000000000..4d26626831--- /dev/null+++ b/apps/example-nextjs-source/README.md@@ -0,0 +1,155 @@+# XDS Example — Next.js (Source Build)++Reference application for compiling **@xds/core** from raw TypeScript + StyleX source alongside product code. Uses `@xds/build` for independent CSS layer separation.++## Why source build?++| | Source build | Dist build |+| ------------- | --------------------------------------------- | ---------------------------- |+| CSS output | Only styles for components you import (~22KB) | All component styles (~77KB) |+| Layer control | Full: reset < xds-base < xds-theme < product | Basic: import order |+| Build time | Slower (compiles XDS source through Babel) | Fast (pre-built CSS) |+| Setup | More config (babel + postcss + next.config) | Minimal (CSS imports) |++## How it works++`@xds/build` provides two plugins that work together:++1. **`@xds/build/babel`** — wraps the StyleX babel plugin, routing XDS library files to `xds` class prefix and product files to default `x` prefix+2. **`@xds/build/postcss`** — compiles StyleX CSS in two passes with different prefixes, wrapping each in its own `@layer`++This creates completely independent class namespaces:++- `.xds78zum5 { display: flex }` in `@layer xds-base`+- `.x78zum5 { display: flex }` in `@layer product`++Theme sits between them in `@layer xds-theme`, so:++- Theme overrides library defaults ✓+- Product overrides theme when needed ✓+- No `!important` needed ✓++## Setup++### 1. Install++```bash+npm install @stylexjs/stylex @xds/core @xds/theme-default next react react-dom+npm install -D @xds/build @stylexjs/babel-plugin @babel/core autoprefixer typescript+```++### 2. babel.config.js++```js+const path = require('path');++module.exports = {+ presets: ['next/babel'],+ plugins: [+ [+ '@xds/build/babel',+ {+ dev: process.env.NODE_ENV !== 'production',+ runtimeInjection: false,+ enableInlinedConditionalMerge: true,+ treeshakeCompensation: true,+ aliases: {+ '@xds/core/*': [path.join(__dirname, 'node_modules/@xds/core/*')],+ '@xds/core': [path.join(__dirname, 'node_modules/@xds/core')],+ },+ unstable_moduleResolution: {type: 'commonJS'},+ },+ ],+ ],+};+```++### 3. postcss.config.js++```js+const path = require('path');++module.exports = {+ plugins: {+ '@xds/build/postcss': {+ appDir: 'src',+ babelPlugins: [+ [+ '@stylexjs/babel-plugin',+ {+ dev: process.env.NODE_ENV !== 'production',+ runtimeInjection: false,+ enableInlinedConditionalMerge: true,+ treeshakeCompensation: true,+ aliases: {+ '@xds/core/*': [path.join(__dirname, 'node_modules/@xds/core/*')],+ '@xds/core': [path.join(__dirname, 'node_modules/@xds/core')],+ },+ unstable_moduleResolution: {type: 'commonJS'},+ },+ ],+ ],+ },+ autoprefixer: {},+ },+};+```++### 4. next.config.mjs++```js+const nextConfig = {+ transpilePackages: ['@xds/core', '@xds/theme-default'],+ webpack: config => {+ config.resolve.conditionNames = ['source', 'import', 'require', 'default'];+ return config;+ },+};++export default nextConfig;+```++### 5. CSS files++`src/app/layers.css` — must be a separate file (webpack hoists `@import` content):++```css+@layer reset, xds-base, xds-theme, product;+```++`src/app/globals.css`:++```css+@import './layers.css';+@import '@xds/core/reset.css';+@import '@xds/theme-default/theme.css';++@stylex;+```++## Layer Demo++This example includes a visual demo showing:++1. **xds-base** — default XDS component styles+2. **xds-theme** — theme overrides (secondary button background)+3. **product** — app overrides (pill shape, green background, full-width)+4. **Class prefix verification** — XDS components use `xds` prefix, product uses `x`++Open devtools → CSS layers panel to see the separation.++## Gotchas++| Issue | Symptom | Fix |+| ------------------------ | -------------------------------------- | ------------------------------------------------------------------ |+| Missing `conditionNames` | XDS resolves to dist (no `xds` prefix) | Add `['source', 'import', 'require', 'default']` to webpack config |+| Missing `aliases` | `defineVars` resolution fails | Add aliases for `@xds/core` and `@xds/core/*` |+| `layers.css` inline | Layer order ignored | Keep as separate file (webpack hoists `@import`) |+| Missing `browserslist` | `light-dark()` gets lowered | Add `["last 1 Chrome version"]` |++## Related++- [Plain dist example](../example-nextjs/) — simplest setup+- [Dist + Tailwind](../example-nextjs-tailwind/) — Tailwind for layout+- [Dist + StyleX](../example-nextjs-stylex/) — StyleX for product only+- [`@xds/build`](../../packages/build/) — the build plugin sourcediff --git a/apps/example-nextjs-source/babel.config.js b/apps/example-nextjs-source/babel.config.jsindex 5e5a440054..71fed55f68 100644--- a/apps/example-nextjs-source/babel.config.js+++ b/apps/example-nextjs-source/babel.config.js@@ -1,27 +1,3 @@-/* global module, process, __dirname, require */-// eslint-disable-next-line @typescript-eslint/no-require-imports-const path = require('path');--const dev = process.env.NODE_ENV !== 'production';--module.exports = {- presets: ['next/babel'],- plugins: [- [- '@stylexjs/babel-plugin',- {- dev,- runtimeInjection: false,- enableInlinedConditionalMerge: true,- treeshakeCompensation: true,- aliases: {- '@xds/core/*': [path.join(__dirname, 'node_modules/@xds/core/*')],- '@xds/core': [path.join(__dirname, 'node_modules/@xds/core')],- },- unstable_moduleResolution: {- type: 'commonJS',- },- },- ],- ],-};+/* global module, __dirname */+const {babel} = require('@xds/build');+module.exports = babel(__dirname);diff --git a/apps/example-nextjs-source/next.config.mjs b/apps/example-nextjs-source/next.config.mjsindex c616176c79..9149ce3b9a 100644--- a/apps/example-nextjs-source/next.config.mjs+++ b/apps/example-nextjs-source/next.config.mjs@@ -1,6 +1,2 @@-/** @type {import('next').NextConfig} */-const nextConfig = {- transpilePackages: ['@xds/core', '@xds/theme-default'],-};--export default nextConfig;+import {withXDS} from '@xds/build/next';+export default withXDS({});diff --git a/apps/example-nextjs-source/package.json b/apps/example-nextjs-source/package.jsonindex 28c4d7775e..6ba27ac649 100644--- a/apps/example-nextjs-source/package.json+++ b/apps/example-nextjs-source/package.json@@ -24,7 +24,7 @@"@types/react-dom": "^19.2.3","autoprefixer": "^10.4.0","typescript": "^5.7.0",- "@xds/postcss-plugin": "*"+ "@xds/build": "*"},"browserslist": ["last 1 Chrome version"diff --git a/apps/example-nextjs-source/postcss.config.js b/apps/example-nextjs-source/postcss.config.jsindex 5d19c6ed63..dce384a833 100644--- a/apps/example-nextjs-source/postcss.config.js+++ b/apps/example-nextjs-source/postcss.config.js@@ -1,13 +1,3 @@-/* global module, require */-// eslint-disable-next-line @typescript-eslint/no-require-imports-const babelConfig = require('./babel.config');--module.exports = {- plugins: {- '@xds/postcss-plugin': {- appDir: 'src',- babelPlugins: babelConfig.plugins,- },- autoprefixer: {},- },-};+/* global module, __dirname */+const {postcss} = require('@xds/build');+module.exports = postcss(__dirname);diff --git a/apps/example-nextjs-source/src/app/page.tsx b/apps/example-nextjs-source/src/app/page.tsxindex 05e55a96e8..c64c517a09 100644--- a/apps/example-nextjs-source/src/app/page.tsx+++ b/apps/example-nextjs-source/src/app/page.tsx@@ -8,6 +8,8 @@ import {XDSText, XDSHeading} from '@xds/core/Text';import {XDSTextInput} from '@xds/core/TextInput';import {XDSBadge} from '@xds/core/Badge';import {XDSDivider} from '@xds/core';+import {XDSCard} from '@xds/core/Card';+import {XDSSwitch} from '@xds/core/Switch';const styles = stylex.create({main: {@@ -21,12 +23,6 @@ const styles = stylex.create({maxWidth: 640,width: '100%',},- card: {- borderRadius: 8,- border: '1px solid var(--color-border)',- padding: '1rem',- backgroundColor: 'var(--color-background-body)',- },layerDemo: {padding: '1.5rem',borderRadius: 12,@@ -42,10 +38,25 @@ const styles = stylex.create({backgroundColor: 'mediumseagreen',color: 'white',},+ card: {+ borderRadius: 8,+ border: '1px solid var(--color-border)',+ padding: '1rem',+ backgroundColor: 'var(--color-background-body)',+ },+ prefixDemo: {+ fontFamily: 'monospace',+ fontSize: '0.75rem',+ padding: '0.5rem',+ backgroundColor: 'var(--color-background-muted)',+ borderRadius: 6,+ overflowX: 'auto',+ },});export default function Home() {const [email, setEmail] = useState('');+ const [toggle, setToggle] = useState(false);return (<main {...stylex.props(styles.main)}>@@ -58,9 +69,13 @@ export default function Home() {<XDSText type="body" weight="bold">@xds/core</XDSText>{' '}- from raw TypeScript + StyleX source. Both XDS component styles and- product styles are compiled together at build time — fully- tree-shaken, zero unused CSS.+ from raw TypeScript + StyleX source. The{' '}+ <XDSText type="body" weight="bold">+ @xds/build+ </XDSText>{' '}+ package provides a babel plugin and PostCSS plugin that compile+ library and product code with separate class name prefixes,+ enabling independent CSS layers.</XDSText></XDSVStack>@@ -70,113 +85,115 @@ export default function Home() {<XDSVStack gap={3}><XDSHeading level={2}>Layer Demo</XDSHeading><XDSText type="body" color="secondary">- Product StyleX styles override XDS component defaults via CSS- layer ordering. No <code>!important</code> needed — the{' '}- <code>product</code> layer sits above <code>xds-base</code> in the- cascade.+ Four CSS layers in strict order. Product styles override theme,+ theme overrides base, all without <code>!important</code>.</XDSText><div {...stylex.props(styles.layerDemo)}>- <XDSVStack gap={3}>+ <XDSVStack gap={4}>+ {/* Base layer */}<XDSVStack gap={1}><XDSText type="supporting" weight="bold">- Default XDS buttons (xds-base layer)+ 1. xds-base — default component styles</XDSText><XDSHStack gap={3} vAlign="center">- <XDSButton label="Default" variant="primary" />- <XDSButton label="Default" variant="secondary" />+ <XDSButton label="Primary" variant="primary" />+ <XDSButton label="Secondary" variant="secondary" />+ <XDSButton label="Ghost" variant="ghost" /></XDSHStack></XDSVStack>+ {/* Theme layer */}<XDSVStack gap={1}><XDSText type="supporting" weight="bold">- Product-styled buttons (product layer overrides)+ 2. xds-theme — theme overrides base+ </XDSText>+ <XDSText type="supporting" color="secondary">+ The secondary button background comes from the theme layer,+ overriding the base default.</XDSText><XDSHStack gap={3} vAlign="center">- <XDSButton- label="Pill shape"- variant="primary"- xstyle={styles.customButton}- />- <XDSButton- label="Pill shape"- variant="secondary"- xstyle={styles.customButton}- />+ <XDSButton label="Theme color" variant="secondary" />+ <XDSBadge variant="info" label="Themed" />+ <XDSBadge variant="success" label="Themed" /></XDSHStack></XDSVStack>+ {/* Product layer overrides */}<XDSVStack gap={1}><XDSText type="supporting" weight="bold">- Three-layer cascade: base → theme → product+ 3. product — product overrides theme</XDSText><XDSText type="supporting" color="secondary">- The secondary button's background goes through three layers:- XDS base sets the default, the theme overrides it with a- brand tint, and product code overrides again with green.+ Product styles use a different class prefix (x vs xds) so+ they don't collide with library classes in the base layer.</XDSText><XDSHStack gap={3} vAlign="center">- <XDSButton label="Theme color" variant="secondary" /><XDSButton- label="Product override"+ label="Pill shape"+ variant="primary"+ xstyle={styles.customButton}+ />+ <XDSButton+ label="Green override"variant="secondary"xstyle={styles.brandSecondary}/></XDSHStack></XDSVStack>- <XDSVStack gap={1}>- <XDSText type="supporting" weight="bold">- Full-width product override- </XDSText>- <XDSButton- label="Full width button"- variant="primary"- xstyle={styles.wideButton}- />- </XDSVStack>+ {/* Full width */}+ <XDSButton+ label="Full width product override"+ variant="primary"+ xstyle={styles.wideButton}+ /></XDSVStack></div></XDSVStack><XDSDivider />- {/* Standard components */}- <XDSVStack gap={3}>- <XDSHeading level={2}>Components</XDSHeading>- <XDSHStack gap={3} vAlign="center">- <XDSButton label="Primary" variant="primary" />- <XDSButton label="Secondary" variant="secondary" />- <XDSButton label="Ghost" variant="ghost" />- </XDSHStack>- </XDSVStack>-- <XDSDivider />-+ {/* Class prefix verification */}<XDSVStack gap={3}>- <XDSHeading level={2}>Badges</XDSHeading>- <XDSHStack gap={3} vAlign="center">- <XDSBadge variant="info" label="Info" />- <XDSBadge variant="success" label="Success" />- <XDSBadge variant="warning" label="Warning" />- <XDSBadge variant="error" label="Error" />- </XDSHStack>+ <XDSHeading level={2}>Class Prefix Verification</XDSHeading>+ <XDSText type="body" color="secondary">+ Inspect these elements in devtools. XDS library classes start with{' '}+ <code>xds</code>, product classes start with <code>x</code>.+ </XDSText>+ <XDSCard padding={4}>+ <XDSVStack gap={2}>+ <XDSText type="supporting" weight="bold">+ This card is an XDS component → xds-prefixed classes+ </XDSText>+ <div {...stylex.props(styles.prefixDemo)}>+ This div uses product StyleX → x-prefixed classes+ </div>+ </XDSVStack>+ </XDSCard></XDSVStack><XDSDivider />+ {/* Form components */}<XDSVStack gap={3}>- <XDSHeading level={2}>Text Input</XDSHeading>+ <XDSHeading level={2}>Form Components</XDSHeading><XDSTextInputlabel="Email address"placeholder="[email protected]"value={email}onChange={setEmail}/>+ <XDSSwitch+ label="Enable notifications"+ isSelected={toggle}+ onChange={setToggle}+ /></XDSVStack><XDSDivider />+ {/* Typography */}<XDSVStack gap={3}><XDSHeading level={2}>Typography</XDSHeading><XDSText type="large" weight="bold">@@ -190,16 +207,26 @@ export default function Home() {<XDSDivider />+ {/* How it works */}<XDSVStack gap={3}>- <XDSHeading level={2}>Source Build</XDSHeading>+ <XDSHeading level={2}>How It Works</XDSHeading><div {...stylex.props(styles.card)}>- <XDSText type="body">- Open devtools → inspect the CSS. You'll see separate{' '}- <code>@layer xds-base</code> and <code>@layer product</code>{' '}- blocks. The layer order{' '}- <code>reset < xds-base < xds-theme < product</code>{' '}- ensures product styles always win without specificity hacks.- </XDSText>+ <XDSVStack gap={2}>+ <XDSText type="body">+ <code>@xds/build/babel</code> wraps the StyleX babel plugin+ and routes files to two internal instances with different{' '}+ <code>classNamePrefix</code> values based on file path.+ </XDSText>+ <XDSText type="body">+ <code>@xds/build/postcss</code> does the same for CSS+ extraction, placing each group in its own <code>@layer</code>{' '}+ block.+ </XDSText>+ <XDSText type="body">+ Open devtools → CSS layers panel to see:{' '}+ <code>reset < xds-base < xds-theme < product</code>+ </XDSText>+ </XDSVStack></div></XDSVStack></XDSVStack>diff --git a/eslint.config.js b/eslint.config.jsindex 686d4c81cc..3b7dcabef1 100644--- a/eslint.config.js+++ b/eslint.config.js@@ -36,7 +36,7 @@ export default tseslint.config("apps/example-nextjs/next-env.d.ts","apps/example-nextjs-source/*.js","apps/sandbox/*.js",- "packages/postcss-plugin/**",+ "packages/build/**","packages/vite-plugin/**",],},diff --git a/packages/build/README.md b/packages/build/README.mdnew file mode 100644index 0000000000..aea91774a5--- /dev/null+++ b/packages/build/README.md@@ -0,0 +1,247 @@+# @xds/build++Build plugins for XDS source builds. Provides babel, PostCSS, and Vite integrations that compile XDS library and product code with separate class name prefixes, enabling independent CSS layers:++```+reset < xds-base (library, xds prefix) < xds-theme < product (app, x prefix)+```++## Why?++StyleX generates atomic CSS — same declaration = same class name. Without separate prefixes, library and product classes collide and can't be placed in independent CSS layers, which breaks theme overrides.++`@xds/build` solves this by:++1. Compiling XDS library code with `xds` prefix (`.xds78zum5`)+2. Compiling product code with default `x` prefix (`.x78zum5`)+3. Placing each group in its own CSS `@layer`++## Packages++| Export | Purpose | Platform |+| -------------------- | --------------------------------------------- | --------------------------- |+| `@xds/build/babel` | Babel plugin — splits class prefixes per file | Next.js, any babel pipeline |+| `@xds/build/postcss` | PostCSS plugin — compiles + splits CSS layers | Next.js |+| `@xds/build/vite` | Vite plugin — wraps unplugin + splits layers | Vite, Storybook |++## Install++```bash+npm install -D @xds/build @stylexjs/babel-plugin @babel/core+```++For Vite, also install:++```bash+npm install -D @stylexjs/unplugin+```++---++## Next.js Setup++### 1. babel.config.js++```js+const path = require('path');++module.exports = {+ presets: ['next/babel'],+ plugins: [+ [+ '@xds/build/babel',+ {+ dev: process.env.NODE_ENV !== 'production',+ runtimeInjection: false,+ treeshakeCompensation: true,+ enableInlinedConditionalMerge: true,+ aliases: {+ '@xds/core/*': [path.join(__dirname, 'node_modules/@xds/core/*')],+ '@xds/core': [path.join(__dirname, 'node_modules/@xds/core')],+ },+ unstable_moduleResolution: {type: 'commonJS'},+ },+ ],+ ],+};+```++### 2. postcss.config.js++```js+const path = require('path');++module.exports = {+ plugins: {+ '@xds/build/postcss': {+ appDir: 'src',+ babelPlugins: [+ [+ '@stylexjs/babel-plugin',+ {+ dev: process.env.NODE_ENV !== 'production',+ runtimeInjection: false,+ treeshakeCompensation: true,+ enableInlinedConditionalMerge: true,+ aliases: {+ '@xds/core/*': [path.join(__dirname, 'node_modules/@xds/core/*')],+ '@xds/core': [path.join(__dirname, 'node_modules/@xds/core')],+ },+ unstable_moduleResolution: {type: 'commonJS'},+ },+ ],+ ],+ },+ },+};+```++### 3. next.config.mjs++```js+const nextConfig = {+ transpilePackages: ['@xds/core', '@xds/theme-default'],+ webpack: config => {+ // Resolve to source TypeScript instead of dist+ config.resolve.conditionNames = ['source', 'import', 'require', 'default'];+ return config;+ },+};++export default nextConfig;+```++### 4. CSS files++`src/app/layers.css`:++```css+@layer reset, xds-base, xds-theme, product;+```++`src/app/globals.css`:++```css+@import './layers.css';+@import '@xds/core/reset.css';+@import '@xds/theme-default/theme.css';++@stylex;+```++> `layers.css` must be a separate file because webpack hoists `@import` content above inline CSS.++### 5. Browserslist++```json+{+ "browserslist": ["last 1 Chrome version"]+}+```++---++## Vite Setup++```ts+import {xdsStylex} from '@xds/build/vite';+import react from '@vitejs/plugin-react';++export default defineConfig({+ plugins: [+ ...xdsStylex({+ stylexOptions: {+ dev: process.env.NODE_ENV === 'development',+ runtimeInjection: false,+ treeshakeCompensation: true,+ unstable_moduleResolution: {+ type: 'commonJS',+ rootDir: __dirname,+ },+ },+ }),+ react(),+ ],+ resolve: {+ alias: {+ '@xds/core': path.resolve(__dirname, 'node_modules/@xds/core/src'),+ },+ },+ optimizeDeps: {+ exclude: ['@xds/core', '@xds/theme-default'],+ },+});+```++---++## How it works++### Babel plugin (`@xds/build/babel`)++Wraps `@stylexjs/babel-plugin` with two internal instances — one with `classNamePrefix: 'xds'` for library files, one with default `'x'` for product files. Routes each file to the correct instance based on its path.++Library patterns (configurable):++- `packages/core/`+- `packages/themes/`+- `node_modules/@xds/`++### PostCSS plugin (`@xds/build/postcss`)++Compiles StyleX from both library and product source files in two separate passes with different prefixes. Wraps the results in named `@layer` blocks:++- Library rules → `@layer xds-base`+- Product rules → `@layer product`++### Vite plugin (`@xds/build/vite`)++Wraps `@stylexjs/unplugin` and intercepts the dev CSS endpoint (`/virtual:stylex.css`). Partitions the collected rules by file path and serves split-layer CSS.++---++## Advanced Options++### Babel plugin++```js+[+ '@xds/build/babel',+ {+ // Patterns to identify library files (default shown)+ libraryPatterns: [+ 'packages/core/',+ 'packages/themes/',+ 'node_modules/@xds/',+ ],++ // Class name prefix for library styles (default: 'xds')+ libraryPrefix: 'xds',++ // Class name prefix for product styles (default: 'x')+ classNamePrefix: 'x',++ // ... all @stylexjs/babel-plugin options+ },+];+```++### PostCSS plugin++```js+'@xds/build/postcss': {+ appDir: 'src', // Your app source directory+ babelPlugins: [...], // StyleX babel plugin config+ libraryPrefix: 'xds', // Prefix for library CSS (default: 'xds')+ extraInclude: [...], // Additional glob patterns+ layers: { // Layer names (defaults shown)+ library: 'xds-base',+ product: 'product',+ },+}+```++## Related++- [example-nextjs-source](../../apps/example-nextjs-source/) — Full Next.js source build example+- [`@stylexjs/babel-plugin`](https://github.com/facebook/stylex) — The underlying StyleX compilerdiff --git a/packages/build/package.json b/packages/build/package.jsonnew file mode 100644index 0000000000..8cca348190--- /dev/null+++ b/packages/build/package.json@@ -0,0 +1,44 @@+{+ "name": "@xds/build",+ "version": "0.0.1",+ "description": "Build plugins for XDS source builds — babel, PostCSS, and Vite integrations",+ "license": "MIT",+ "main": "./src/config.js",+ "exports": {+ ".": "./src/config.js",+ "./babel": "./src/babel.js",+ "./postcss": "./src/index.js",+ "./vite": "./src/vite.ts",+ "./next": "./src/next.js"+ },+ "files": [+ "src"+ ],+ "keywords": [+ "xds",+ "postcss",+ "stylex",+ "css-layers",+ "design-system"+ ],+ "peerDependencies": {+ "@stylexjs/babel-plugin": ">=0.18.0",+ "@babel/core": ">=7.0.0",+ "@stylexjs/unplugin": ">=0.18.0",+ "vite": ">=5.0.0"+ },+ "dependencies": {+ "fast-glob": "^3.3.0",+ "glob-parent": "^6.0.0",+ "is-glob": "^4.0.0"+ },+ "peerDependenciesMeta": {+ "@stylexjs/unplugin": {+ "optional": true+ },+ "vite": {+ "optional": true+ }+ },+ "private": true+}diff --git a/packages/build/src/babel.js b/packages/build/src/babel.jsnew file mode 100644index 0000000000..7d1d1654fa--- /dev/null+++ b/packages/build/src/babel.js@@ -0,0 +1,104 @@+"use strict";++/**+ * @xds/build/babel+ *+ * Babel plugin that delegates to @stylexjs/babel-plugin with a+ * different classNamePrefix for XDS library files vs product files.+ *+ * Library files get 'xds' prefix (.xds78zum5), product files get 'x' (.x78zum5).+ */++const XDS_LIBRARY_PATTERNS = [+ 'packages/core/',+ 'packages/themes/',+ 'packages/lab/',+ 'node_modules/@xds/',+];++module.exports = function xdsBabelPlugin(api, options) {+ const stylexPlugin = require('@stylexjs/babel-plugin');++ const {+ libraryPatterns = XDS_LIBRARY_PATTERNS,+ libraryPrefix = 'xds',+ classNamePrefix = 'x',+ ...stylexOptions+ } = options;++ // Build the two sets of options — only classNamePrefix differs+ const libraryOpts = {...stylexOptions, classNamePrefix: libraryPrefix};+ const productOpts = {...stylexOptions, classNamePrefix};++ // Create two plugin instances+ const libraryPlugin = stylexPlugin(api, libraryOpts);+ const productPlugin = stylexPlugin(api, productOpts);++ function getPluginAndOpts(filename) {+ const isLibrary = libraryPatterns.some(p => filename.includes(p));+ return isLibrary+ ? {plugin: libraryPlugin, opts: libraryOpts}+ : {plugin: productPlugin, opts: productOpts};+ }++ // Helper: call a visitor function with overridden state.opts+ function callVisitor(visitor, key, path, state) {+ const {plugin, opts} = getPluginAndOpts(state.filename || '');+ const v = plugin.visitor[key];+ if (!v) return;++ // Override state.opts so StyleX reads the correct classNamePrefix+ const originalOpts = state.opts;+ state.opts = opts;++ try {+ if (typeof v === 'function') {+ v.call(this, path, state);+ } else if (typeof v === 'object') {+ // enter/exit form — should not happen at top level for stylex+ // but handle it anyway+ if (visitor === 'enter' && v.enter) v.enter.call(this, path, state);+ if (visitor === 'exit' && v.exit) v.exit.call(this, path, state);+ }+ } finally {+ state.opts = originalOpts;+ }+ }++ // Get all visitor keys+ const allKeys = new Set([+ ...Object.keys(libraryPlugin.visitor || {}),+ ...Object.keys(productPlugin.visitor || {}),+ ]);++ const visitor = {};++ for (const key of allKeys) {+ const sample = libraryPlugin.visitor[key] || productPlugin.visitor[key];++ if (typeof sample === 'object' && (sample.enter || sample.exit)) {+ // enter/exit form (Program uses this)+ visitor[key] = {};+ if (sample.enter) {+ visitor[key].enter = function(path, state) {+ callVisitor.call(this, 'enter', key, path, state);+ };+ }+ if (sample.exit) {+ visitor[key].exit = function(path, state) {+ callVisitor.call(this, 'exit', key, path, state);+ };+ }+ } else {+ // Simple function visitor+ visitor[key] = function(path, state) {+ callVisitor.call(this, 'enter', key, path, state);+ };+ }+ }++ return {+ name: 'xds-babel-plugin',+ visitor,+ };+};diff --git a/packages/build/src/config.js b/packages/build/src/config.jsnew file mode 100644index 0000000000..5092630f0a--- /dev/null+++ b/packages/build/src/config.js@@ -0,0 +1,89 @@+"use strict";++/**+ * @xds/build+ *+ * Unified build configuration for XDS source builds.+ *+ * Usage:+ * // babel.config.js+ * const {babel} = require('@xds/build');+ * module.exports = babel(__dirname);+ *+ * // postcss.config.js+ * const {postcss} = require('@xds/build');+ * module.exports = postcss(__dirname);+ */++const path = require('node:path');++/**+ * Resolve XDS package aliases from a root directory.+ * Handles both npm installs (node_modules/@xds/core) and+ * monorepo layouts (packages/core).+ */+function resolveAliases(rootDir) {+ const coreDir = path.join(rootDir, 'node_modules/@xds/core');+ return {+ '@xds/core/*': [path.join(coreDir, '*')],+ '@xds/core': [coreDir],+ };+}++/**+ * Build shared StyleX babel plugin options from a root directory.+ */+function stylexOptions(rootDir, overrides = {}) {+ return {+ dev: process.env.NODE_ENV !== 'production',+ runtimeInjection: false,+ enableInlinedConditionalMerge: true,+ treeshakeCompensation: true,+ aliases: resolveAliases(rootDir),+ unstable_moduleResolution: {+ type: 'commonJS',+ },+ ...overrides,+ };+}++/**+ * Generate a complete babel.config.js for XDS source builds.+ *+ * @param {string} rootDir — __dirname of the project root+ * @param {object} [overrides] — extra StyleX options to merge+ * @returns {object} babel config object+ */+function babel(rootDir, overrides = {}) {+ return {+ presets: ['next/babel'],+ plugins: [+ [require.resolve('./babel.js'), stylexOptions(rootDir, overrides)],+ ],+ };+}++/**+ * Generate a complete postcss.config.js for XDS source builds.+ *+ * @param {string} rootDir — __dirname of the project root+ * @param {object} [overrides] — extra options (appDir, extraInclude, etc.)+ * @returns {object} postcss config object+ */+function postcss(rootDir, overrides = {}) {+ const {appDir = 'src', extraInclude = [], ...rest} = overrides;+ return {+ plugins: {+ [require.resolve('./index.js')]: {+ appDir,+ babelPlugins: [+ ['@stylexjs/babel-plugin', stylexOptions(rootDir, rest)],+ ],+ extraInclude,+ },+ autoprefixer: {},+ },+ };+}++module.exports = {babel, postcss, stylexOptions, resolveAliases};diff --git a/packages/postcss-plugin/src/index.js b/packages/build/src/index.jssimilarity index 70%rename from packages/postcss-plugin/src/index.jsrename to packages/build/src/index.jsindex d4cd8b5367..fcbc7e4b55 100644--- a/packages/postcss-plugin/src/index.js+++ b/packages/build/src/index.js@@ -4,23 +4,13 @@* @xds/postcss-plugin** PostCSS plugin for XDS source builds. Compiles StyleX from both- * XDS library source and product code, then splits the output into- * separate named CSS layers:+ * XDS library source and product code in two separate passes with+ * different class name prefixes, then outputs them in separate layers:*- * reset < xds-base (library styles) < xds-theme < product (app styles)+ * reset < xds-base (library, prefix: 'xds') < xds-theme < product (prefix: 'x')*- * Usage:- * // postcss.config.js- * const babelConfig = require('./babel.config');- *- * module.exports = {- * plugins: {- * '@xds/postcss-plugin': {- * appDir: 'src',- * babelPlugins: babelConfig.plugins,- * },- * },- * };+ * The separate prefixes ensure atomic classes don't collide between+ * layers, which would break theme overrides.*/const path = require('node:path');@@ -34,9 +24,8 @@ const globParent = require('glob-parent');const PLUGIN_NAME = '@xds/postcss-plugin';-// XDS-specific defaults — the user shouldn't need to specify theseconst XDS_LIBRARY_GLOB = 'node_modules/@xds/**/*.{ts,tsx}';-const XDS_LIBRARY_PATTERN = 'node_modules/@xds/';+const XDS_LIBRARY_PATTERNS = ['node_modules/@xds/', 'packages/core/', 'packages/themes/'];const STYLEX_IMPORT_SOURCE = '@stylexjs/stylex';function parseDependency(fileOrGlob, cwd) {@@ -57,39 +46,45 @@ function parseDependency(fileOrGlob, cwd) {};}+/**+ * Clone a babel plugins array, overriding the classNamePrefix on the+ * StyleX babel plugin entry.+ */+function withClassNamePrefix(plugins, prefix) {+ return plugins.map(p => {+ if (!Array.isArray(p)) return p;+ const [pluginPath, opts] = p;+ // Match @stylexjs/babel-plugin by name+ const name = typeof pluginPath === 'string' ? pluginPath : '';+ if (name.includes('@stylexjs/babel-plugin') || name.includes('stylex')) {+ return [pluginPath, {...opts, classNamePrefix: prefix}];+ }+ return p;+ });+}+function createPlugin() {const isDev = process.env.NODE_ENV === 'development';- // Persists across rebuilds for watch mode- const styleXRulesMap = new Map();+ // Separate rule maps for library and product+ const libraryRulesMap = new Map();+ const productRulesMap = new Map();const fileModifiedMap = new Map();const plugin = ({cwd = process.cwd(),-- // --- User-facing options ----- // Directory containing your app source (default: 'src')appDir = 'src',-- // StyleX babel plugins from your babel.config.jsbabelPlugins = [],-- // Layer names (override if you need different names)layers = {library: 'xds-base',product: 'product',},-- // --- Advanced options (rarely needed) ----- // Additional include globs beyond appDir and @xds packages+ // Class name prefix for library styles (product keeps default 'x')+ libraryPrefix = 'xds',extraInclude = [],-- // Exclude globs+ libraryPatterns = XDS_LIBRARY_PATTERNS,exclude = [],}) => {- // Build the include list: app code + all @xds packagesconst include = [`${appDir}/**/*.{js,jsx,ts,tsx}`,XDS_LIBRARY_GLOB,@@ -98,13 +93,17 @@ function createPlugin() {const excludeWithDefaults = ['**/*.d.ts', '**/*.flow', ...exclude];- // Build babel config from the user's plugins- const babelConfig = {+ // Two babel configs — different classNamePrefix+ const libraryBabelConfig = {+ babelrc: false,+ parserOpts: {plugins: ['typescript', 'jsx']},+ plugins: withClassNamePrefix(babelPlugins, libraryPrefix),+ };++ const productBabelConfig = {babelrc: false,- parserOpts: {- plugins: ['typescript', 'jsx'],- },- plugins: babelPlugins,+ parserOpts: {plugins: ['typescript', 'jsx']},+ plugins: babelPlugins, // keeps default 'x' prefix};let shouldSkipTransformError = false;@@ -115,7 +114,6 @@ function createPlugin() {async function (root, result) {const fileName = result.opts.from;- // Find @stylex at-rulelet styleXAtRule = null;root.walkAtRules((atRule) => {if (atRule.name === 'stylex' && !atRule.params) {@@ -153,11 +151,13 @@ function createPlugin() {for (const f of fileModifiedMap.keys()) {if (!files.has(f)) {fileModifiedMap.delete(f);- styleXRulesMap.delete(f);+ libraryRulesMap.delete(f);+ productRulesMap.delete(f);}}- // Transform changed files+ // Partition files into library vs product, then compile+ // each group with its own babel config (different prefix)const transforms = [];for (const filePath of files) {const mtimeMs = fs.existsSync(filePath)@@ -172,21 +172,23 @@ function createPlugin() {fileModifiedMap.set(filePath, mtimeMs);const contents = fs.readFileSync(filePath, 'utf-8');-- // Quick check: does this file import stylex?if (!contents.includes(STYLEX_IMPORT_SOURCE)) continue;+ const isLibrary = libraryPatterns.some(p => filePath.includes(p));+ const config = isLibrary ? libraryBabelConfig : productBabelConfig;+ const rulesMap = isLibrary ? libraryRulesMap : productRulesMap;+transforms.push(babel.transformAsync(contents, {filename: filePath,caller: {name: PLUGIN_NAME, platform: 'web', isDev},- ...babelConfig,+ ...config,}).then(({metadata}) => {const stylex = metadata?.stylex;if (stylex != null && stylex.length > 0) {- styleXRulesMap.set(filePath, stylex);+ rulesMap.set(filePath, stylex);}}).catch((error) => {@@ -202,16 +204,9 @@ function createPlugin() {}await Promise.all(transforms);- // Partition rules by source path- const libraryRules = [];- const productRules = [];- for (const [filePath, rules] of styleXRulesMap.entries()) {- if (filePath.includes(XDS_LIBRARY_PATTERN)) {- libraryRules.push(...rules);- } else {- productRules.push(...rules);- }- }+ // Collect rules from each map+ const libraryRules = Array.from(libraryRulesMap.values()).flat();+ const productRules = Array.from(productRulesMap.values()).flat();// Process each group separatelyconst libraryCss = libraryRules.lengthdiff --git a/packages/build/src/next.js b/packages/build/src/next.jsnew file mode 100644index 0000000000..347f3ae29f--- /dev/null+++ b/packages/build/src/next.js@@ -0,0 +1,58 @@+"use strict";++/**+ * @xds/build/next+ *+ * Next.js configuration helper for XDS source builds.+ *+ * Usage in next.config.mjs:+ * import {withXDS} from '@xds/build/next';+ * export default withXDS({+ * // your normal next config+ * });+ */++/**+ * Wraps a Next.js config to enable XDS source builds.+ * - Adds transpilePackages for @xds/* packages+ * - Sets conditionNames to resolve source exports+ */+function withXDS(nextConfig = {}) {+ const xdsPackages = [+ '@xds/core',+ '@xds/theme-default',+ '@xds/theme-neutral',+ '@xds/theme-brutalist',+ '@xds/theme-meta',+ '@xds/theme-whatsapp',+ '@xds/theme-daily',+ '@xds/lab',+ ];++ const existingTranspile = nextConfig.transpilePackages || [];+ const merged = Array.from(new Set([...existingTranspile, ...xdsPackages]));++ const existingWebpack = nextConfig.webpack;++ return {+ ...nextConfig,+ transpilePackages: merged,+ webpack: (config, context) => {+ // Resolve to source exports+ config.resolve.conditionNames = [+ 'source',+ 'import',+ 'require',+ 'default',+ ];++ // Call user's webpack config if provided+ if (existingWebpack) {+ return existingWebpack(config, context);+ }+ return config;+ },+ };+}++module.exports = {withXDS};diff --git a/packages/build/src/vite.ts b/packages/build/src/vite.tsnew file mode 100644index 0000000000..2a04cefe61--- /dev/null+++ b/packages/build/src/vite.ts@@ -0,0 +1,165 @@+import type {Plugin} from 'vite';+import stylexBabelPlugin from '@stylexjs/babel-plugin';+import stylex from '@stylexjs/unplugin';++const XDS_LIBRARY_PATTERN = 'node_modules/@xds/';+const STYLEX_CSS_PATH = '/virtual:stylex.css';++export interface XDSVitePluginOptions {+ /**+ * Options passed to @stylexjs/unplugin.+ * See https://stylexjs.com/docs/api/configuration/babel-plugin/+ */+ stylexOptions: Parameters<typeof stylex.vite>[0];++ /**+ * Pattern to identify XDS library files vs product files.+ * @default 'node_modules/@xds/'+ */+ libraryPattern?: string;++ /**+ * CSS layer names for the split output.+ */+ layers?: {+ /** Layer name for XDS library styles @default 'xds-base' */+ library?: string;+ /** Layer name for product styles @default 'product' */+ product?: string;+ };+}++/**+ * Vite plugin for XDS source builds.+ *+ * Wraps @stylexjs/unplugin to compile StyleX from both XDS library source+ * and product code, then splits the CSS output into separate named layers:+ *+ * reset < xds-base (library) < xds-theme < product (app)+ *+ * Usage:+ * import {xdsStylex} from '@xds/vite-plugin';+ *+ * export default defineConfig({+ * plugins: [+ * ...xdsStylex({+ * stylexOptions: {+ * dev: process.env.NODE_ENV === 'development',+ * unstable_moduleResolution: { type: 'commonJS', rootDir: __dirname },+ * },+ * }),+ * react(),+ * ],+ * });+ */+export function xdsStylex(options: XDSVitePluginOptions): Plugin[] {+ const {+ stylexOptions,+ libraryPattern = XDS_LIBRARY_PATTERN,+ layers = {},+ } = options;++ const libraryLayer = layers.library ?? 'xds-base';+ const productLayer = layers.product ?? 'product';++ // Create the base StyleX unplugin with layers enabled+ const basePlugin = stylex.vite({+ ...stylexOptions,+ useCSSLayers: true,+ });++ // Layer order declaration plugin+ const layerOrderPlugin: Plugin = {+ name: 'xds-css-layer-order',+ transformIndexHtml() {+ return [+ {+ tag: 'style',+ children: `@layer reset, ${libraryLayer}, xds-theme, ${productLayer};`,+ injectTo: 'head-prepend',+ },+ ];+ },+ };++ // Split-layer interceptor plugin+ const splitLayerPlugin: Plugin = {+ name: 'xds-split-layers',+ configureServer(server) {+ let stylexPlugin: any = null;++ // Return a function so it runs AFTER all configureServer hooks+ return () => {+ // Find the stylex plugin+ for (const p of server.config.plugins.flat()) {+ if ((p as any)?.__stylexGetSharedStore) {+ stylexPlugin = p;+ break;+ }+ }++ // Prepend our middleware so it runs BEFORE the unplugin's+ server.middlewares.stack.unshift({+ route: '',+ handle: (req: any, res: any, next: any) => {+ if (!req.url?.startsWith(STYLEX_CSS_PATH)) {+ return next();+ }++ if (!stylexPlugin) {+ res.statusCode = 200;+ res.setHeader('Content-Type', 'text/css');+ res.end('');+ return;+ }++ const shared = stylexPlugin.__stylexGetSharedStore?.();+ const rulesById = shared?.rulesById;++ if (!rulesById || rulesById.size === 0) {+ res.statusCode = 200;+ res.setHeader('Content-Type', 'text/css');+ res.end('');+ return;+ }++ const libraryRules: any[] = [];+ const productRules: any[] = [];++ for (const [filePath, rules] of rulesById.entries()) {+ if (filePath.includes(libraryPattern)) {+ libraryRules.push(...rules);+ } else {+ productRules.push(...rules);+ }+ }++ const libraryCss = libraryRules.length+ ? stylexBabelPlugin.processStylexRules(libraryRules, {+ useLayers: true,+ })+ : '';+ const productCss = productRules.length+ ? stylexBabelPlugin.processStylexRules(productRules, {+ useLayers: true,+ })+ : '';++ const parts: string[] = [];+ if (libraryCss)+ parts.push(`@layer ${libraryLayer} {\n${libraryCss}\n}`);+ if (productCss)+ parts.push(`@layer ${productLayer} {\n${productCss}\n}`);++ res.statusCode = 200;+ res.setHeader('Content-Type', 'text/css');+ res.setHeader('Cache-Control', 'no-store');+ res.end(parts.join('\n\n'));+ },+ });+ };+ },+ };++ return [layerOrderPlugin, basePlugin, splitLayerPlugin];+}diff --git a/packages/postcss-plugin/README.md b/packages/postcss-plugin/README.mddeleted file mode 100644index ba0b416451..0000000000--- a/packages/postcss-plugin/README.md+++ /dev/null@@ -1,112 +0,0 @@-# @xds/postcss-plugin--PostCSS plugin for XDS source builds. Compiles StyleX from both XDS library source and product code, then splits the output into separate CSS layers.--## Install--```bash-npm install -D @xds/postcss-plugin @stylexjs/babel-plugin @babel/core-```--## Usage--```js-// babel.config.js-const path = require('path');--module.exports = {- presets: ['next/babel'],- plugins: [- [- '@stylexjs/babel-plugin',- {- dev: process.env.NODE_ENV !== 'production',- runtimeInjection: false,- enableInlinedConditionalMerge: true,- treeshakeCompensation: true,- aliases: {- '@xds/core/*': [path.join(__dirname, 'node_modules/@xds/core/*')],- '@xds/core': [path.join(__dirname, 'node_modules/@xds/core')],- },- unstable_moduleResolution: {type: 'commonJS'},- },- ],- ],-};-```--```js-// postcss.config.js-const babelConfig = require('./babel.config');--module.exports = {- plugins: {- '@xds/postcss-plugin': {- appDir: 'src',- babelPlugins: babelConfig.plugins,- },- },-};-```--```css-/* globals.css */-@import './layers.css';-@import '@xds/core/reset.css';-@import '@xds/theme-default/theme.css';--@stylex;-```--```css-/* layers.css */-@layer reset, xds-base, xds-theme, product;-```--## What it does--The plugin scans both your app source and `node_modules/@xds/` for StyleX usage. It compiles everything in a single pass using the Babel plugin, then partitions the resulting CSS rules by file path:--- Rules from `node_modules/@xds/` → `@layer xds-base`-- Rules from your app source → `@layer product`--### Layer ordering--```-reset < xds-base < xds-theme < product-```--Product styles always win over XDS defaults without `!important`.--## Options--```ts-{- /** Directory containing your app source (default: 'src') */- appDir?: string;-- /** StyleX babel plugins from your babel.config.js */- babelPlugins?: any[];-- /** Layer names (override if needed) */- layers?: {- library?: string; // default: 'xds-base'- product?: string; // default: 'product'- };-- /** Additional include globs beyond appDir and @xds packages */- extraInclude?: string[];-- /** Exclude globs */- exclude?: string[];-}-```--## Why a separate `layers.css` file?--The `@layer` order declaration must appear before any layer content in the CSS output. In Next.js, webpack hoists `@import` content above inline CSS in the same file, so an inline `@layer` statement in `globals.css` would appear _after_ `reset.css` and `theme.css` content. A separate `layers.css` file imported first ensures correct ordering.--## Related--- [`@xds/vite-plugin`](../vite-plugin/) — Vite plugin for source builds-- [example-nextjs-source](../../apps/example-nextjs-source/) — Full Next.js source build examplediff --git a/packages/postcss-plugin/package.json b/packages/postcss-plugin/package.jsondeleted file mode 100644index f08028a24d..0000000000--- a/packages/postcss-plugin/package.json+++ /dev/null@@ -1,29 +0,0 @@-{- "name": "@xds/postcss-plugin",- "version": "0.0.1",- "description": "PostCSS plugin for XDS source builds — splits StyleX output into library and product CSS layers",- "license": "MIT",- "main": "src/index.js",- "exports": {- ".": "./src/index.js"- },- "files": [- "src"- ],- "keywords": [- "xds",- "postcss",- "stylex",- "css-layers",- "design-system"- ],- "peerDependencies": {- "@stylexjs/babel-plugin": ">=0.18.0",- "@babel/core": ">=7.0.0"- },- "dependencies": {- "fast-glob": "^3.3.0",- "glob-parent": "^6.0.0",- "is-glob": "^4.0.0"- }-}