Skip to content

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

TypeScript

build(css): a package stylesheet inlines the constants it reads from its provider (#8339)

Christopher Chedeau513459a92d01
diff --git a/scripts/build-css.graph.test.mjs b/scripts/build-css.graph.test.mjs
index 9c5ead6897..f01899ceec 100644
--- a/scripts/build-css.graph.test.mjs
+++ b/scripts/build-css.graph.test.mjs
@@ -124,6 +124,41 @@ describe('build-css dependency extraction', () => {
expect(standaloneCSS).toBe(providerCSS);
});
+ it("inlines a provider's defineConsts value, without emitting the provider's module", async () => {
+ // Lab reading a core motion constant as a value (a fade's duration): the
+ // constants module belongs to the provider's stylesheet, but a constant is
+ // inlined where it is read. (At-rule keys stay literal: StyleX gives an
+ // imported constant key a different priority than the literal at-rule.)
+ const {root, src} = await fixture();
+ const provider = path.join(root, 'provider');
+ await fs.mkdir(provider, {recursive: true});
+ await fs.writeFile(
+ path.join(provider, 'motion.stylex.ts'),
+ `import * as stylex from '@stylexjs/stylex';\nexport const motion = stylex.defineConsts({fade: '200ms'});\nexport const tones = stylex.defineVars({'--probe-tone': 'green'});\n`,
+ );
+ await fs.writeFile(
+ path.join(provider, 'Panel.ts'),
+ `import * as stylex from '@stylexjs/stylex';\nimport {motion, tones} from './motion.stylex';\nexport const styles = stylex.create({panel: {color: tones['--probe-tone'], transitionDuration: motion.fade}});\n`,
+ );
+ await fs.writeFile(
+ path.join(src, 'Consumer.ts'),
+ `import * as stylex from '@stylexjs/stylex';\nimport {motion} from '@probe/motion.stylex';\nexport const styles = stylex.create({row: {transitionProperty: 'opacity', transitionDuration: motion.fade}});\n`,
+ );
+ const providerTarget = {src: provider, aliases: {}};
+ const css = stylexBabelPlugin.processStylexRules(
+ await collectStyleXCSS({
+ src,
+ aliases: {'@probe/*': [path.join(provider, '*')]},
+ provider: providerTarget,
+ }),
+ false,
+ );
+ expect(css).toMatch(/transition-duration:\s*(200ms|\.2s)/);
+ expect(undefinedStyleXVariables(css)).toEqual([]);
+ // The provider's variable group stays in the provider's stylesheet.
+ expect(css).not.toContain('--probe-tone');
+ });
+
it('fails closed when an explicit distribution entry is missing', async () => {
const {src} = await fixture();
await expect(
diff --git a/scripts/build-css.mjs b/scripts/build-css.mjs
index 237deed10e..6be7c276f0 100644
--- a/scripts/build-css.mjs
+++ b/scripts/build-css.mjs
@@ -201,9 +201,14 @@ const STYLEX_MODULE = /\.stylex\.[cm]?[jt]sx?$/;
* imports. Non-StyleX source files and explicitly retained distribution modules
* are the entries; other variable modules join only through reachable imports.
* This keeps source-like graphs selective without omitting Core's public dist
- * defaults. Modules in `provided` are left to the stylesheet that emits them.
+ * defaults. Modules in `provided` are left to the stylesheet that emits them;
+ * the ones this package imports are added to `providedImports`.
*/
-async function reachableSourceFiles(target, provided = new Set()) {
+async function reachableSourceFiles(
+ target,
+ provided = new Set(),
+ providedImports = new Set(),
+) {
const files = await glob('**/*.{ts,tsx}', {
cwd: target.src,
absolute: true,
@@ -239,6 +244,8 @@ async function reachableSourceFiles(target, provided = new Set()) {
}
if (!provided.has(dependency)) {
queue.push(dependency);
+ } else {
+ providedImports.add(dependency);
}
}
}
@@ -260,9 +267,20 @@ async function providedStyleXModules(provider) {
);
}
+/** A `defineConsts` value as StyleX collects it: a rule with `constKey`/`constVal`. */
+function isConstantRule(rule) {
+ const body = Array.isArray(rule) ? rule[1] : undefined;
+ return body?.constKey != null && body?.constVal != null;
+}
+
export async function collectStyleXCSS(target) {
const provided = await providedStyleXModules(target.provider);
- const reachable = await reachableSourceFiles(target, provided);
+ const providedImports = new Set();
+ const reachable = await reachableSourceFiles(
+ target,
+ provided,
+ providedImports,
+ );
const allRules = [];
console.log(`Processing ${reachable.size} reachable source files...`);
@@ -271,40 +289,22 @@ export async function collectStyleXCSS(target) {
if (!code.includes('@stylexjs/stylex')) {
continue;
}
+ allRules.push(...(await compileStyleX(file, code, target)));
+ }
- 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: target.aliases,
- unstable_moduleResolution:
- stylexResolution.stylexModuleResolution,
- },
- ],
- ],
- });
-
- if (result?.metadata?.stylex?.length) {
- allRules.push(...result.metadata.stylex);
- }
- } catch (err) {
- throw new Error(
- `Could not process ${path.relative(ROOT, file)}: ${err.message}`,
- {cause: err},
- );
- }
+ // A constant read from a provider's module as a value (lab reading a core
+ // motion duration) compiles to a placeholder that only the constant's own
+ // rule resolves, and a constant is inlined where it is read; at-rule keys
+ // stay literal. So the constants of
+ // every provided module this package imports join its rules (they emit no
+ // CSS); the module's variables stay in the provider's stylesheet.
+ for (const file of providedImports) {
+ const rules = await compileStyleX(
+ file,
+ await fs.readFile(file, 'utf8'),
+ target,
+ );
+ allRules.push(...rules.filter(isConstantRule));
}
console.log(
@@ -313,6 +313,40 @@ export async function collectStyleXCSS(target) {
return allRules;
}
+/** One file's StyleX rules, compiled as every package stylesheet compiles them. */
+async function compileStyleX(file, code, target) {
+ 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: target.aliases,
+ unstable_moduleResolution: stylexResolution.stylexModuleResolution,
+ },
+ ],
+ ],
+ });
+
+ return result?.metadata?.stylex ?? [];
+ } catch (err) {
+ throw new Error(
+ `Could not process ${path.relative(ROOT, file)}: ${err.message}`,
+ {cause: err},
+ );
+ }
+}
+
/**
* The cascade-layer order every Astryx stylesheet registers before its own
* rules (spec:AST-080 FR3), the same line theme output carries