Skip to content

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

TypeScript

feat(core): expose StyleX data token variables (#6832)

Cindy Zhang01fb22f931c7
diff --git a/.changeset/data-vars-stylex-source.md b/.changeset/data-vars-stylex-source.md
new file mode 100644
index 0000000000..b5b54f4b3a
--- /dev/null
+++ b/.changeset/data-vars-stylex-source.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feature] Export the canonical 56-token StyleX `dataVars` group for CSS-capable data visualization consumers.
+
+@cixzhang
diff --git a/package.json b/package.json
index 4819814cb3..b1f7b38461 100644
--- a/package.json
+++ b/package.json
@@ -13,7 +13,7 @@
"test:a11y-contract": "playwright test --config playwright.config.ts --project chromium",
"test:docsite-browser": "playwright test --config apps/docsite/playwright.config.ts",
"check:package-boundaries": "node scripts/check-package-boundaries.js",
- "check:repo": "pnpm check:visual-owner && pnpm check:sync && pnpm check:knowledge && pnpm check:package-boundaries && pnpm check:changesets && pnpm check:demo-media && pnpm check:executable-bits && pnpm check:cli-structure && pnpm check:use-client && pnpm check:portable-scripts && pnpm check:i18n-runtime && pnpm check:i18n-catalog && pnpm check:cldr-weekdays && pnpm check:fixtures && pnpm check:setup-contract",
+ "check:repo": "pnpm check:visual-owner && pnpm check:sync && pnpm check:data-tokens && pnpm check:token-docs && pnpm check:knowledge && pnpm check:package-boundaries && pnpm check:changesets && pnpm check:demo-media && pnpm check:executable-bits && pnpm check:cli-structure && pnpm check:use-client && pnpm check:portable-scripts && pnpm check:i18n-runtime && pnpm check:i18n-catalog && pnpm check:cldr-weekdays && pnpm check:fixtures && pnpm check:setup-contract",
"check:visual-owner": "node scripts/check-visual-workflow-owner.mjs",
"check:fixtures": "node internal/vibe-tests/scripts/fixture-suite.mjs verify",
"generate:cldr-weekdays": "node scripts/generate-cldr-weekdays.mjs",
@@ -29,6 +29,10 @@
"check:i18n-runtime": "node scripts/generate-i18n-runtime.mjs --check",
"check:i18n-catalog": "node scripts/check-i18n-catalog.mjs",
"check:sync": "node scripts/check-sync.js",
+ "generate:data-tokens": "node scripts/generate-data-tokens.mjs",
+ "check:data-tokens": "node scripts/generate-data-tokens.mjs --check",
+ "generate:token-docs": "node scripts/generate-token-docs.mjs",
+ "check:token-docs": "node scripts/generate-token-docs.mjs --check",
"check:use-client": "node scripts/check-use-client.mjs",
"lint": "pnpm check:repo && eslint . --cache",
"lint:strict": "pnpm check:repo && ASTRYX_STRICT_LINT=1 eslint . --cache",
diff --git a/packages/cli/assets/docs/tokens.doc.mjs b/packages/cli/assets/docs/tokens.doc.mjs
index 6b98fb7ad2..ef5bfe56ec 100644
--- a/packages/cli/assets/docs/tokens.doc.mjs
+++ b/packages/cli/assets/docs/tokens.doc.mjs
@@ -2,7 +2,7 @@
// AUTO-GENERATED — do not edit manually.
// Source: packages/core/src/theme/tokens.stylex.ts,
-// domainTokens/dataTokens.ts, and syntax/tokens.ts
+// dataTokens.stylex.ts, and syntax/tokens.ts
// Run: node scripts/generate-token-docs.mjs
// Total: 258 tokens across 15 categories.
@@ -439,7 +439,7 @@ export const docs = {
"content": [
{
"type": "prose",
- "text": "Colors for charts and graphs: one categorical accent per series, a neutral for labels and reference lines, and sequential ramps from 5 (darkest) to 1 (lightest) for ordered scales and heatmaps."
+ "text": "Colors for charts and graphs: one categorical accent per series, a neutral for labels and reference lines, and sequential ramps from 5 (darkest) to 1 (lightest) for ordered scales and heatmaps. Import their public StyleX variables from @astryxdesign/core/theme/dataTokens.stylex."
},
{
"type": "table",
@@ -1479,7 +1479,7 @@ export const docs = {
"type": "code",
"lang": "tsx",
"label": "Using token imports",
- "code": "import * as stylex from '@stylexjs/stylex';\nimport {colorVars, spacingVars, sizeVars, radiusVars} from '@astryxdesign/core/theme/tokens.stylex';\n\nconst styles = stylex.create({\n card: {\n padding: spacingVars['--spacing-4'],\n backgroundColor: colorVars['--color-background-surface'],\n borderRadius: radiusVars['--radius-container'],\n },\n button: {\n height: sizeVars['--size-element-md'],\n },\n});"
+ "code": "import * as stylex from '@stylexjs/stylex';\nimport {colorVars, spacingVars, sizeVars, radiusVars} from '@astryxdesign/core/theme/tokens.stylex';\nimport {dataVars} from '@astryxdesign/core/theme/dataTokens.stylex';\n\nconst styles = stylex.create({\n card: {\n padding: spacingVars['--spacing-4'],\n backgroundColor: colorVars['--color-background-surface'],\n borderRadius: radiusVars['--radius-container'],\n },\n series: {\n color: dataVars['--color-data-categorical-blue'],\n },\n button: {\n height: sizeVars['--size-element-md'],\n },\n});"
},
{
"type": "prose",
diff --git a/packages/core/package.json b/packages/core/package.json
index da63735166..b8b0bbe83b 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -71,6 +71,11 @@
"types": "./dist/theme/tokens.stylex.d.ts",
"default": "./dist/theme/tokens.stylex.js"
},
+ "./theme/dataTokens.stylex": {
+ "source": "./src/theme/dataTokens.stylex.ts",
+ "types": "./dist/theme/dataTokens.stylex.d.ts",
+ "default": "./dist/theme/dataTokens.stylex.js"
+ },
"./theme/syntax": {
"source": "./src/theme/syntax/index.ts",
"types": "./dist/theme/syntax/index.d.ts",
diff --git a/packages/core/src/theme/dataTokens.stylex.ts b/packages/core/src/theme/dataTokens.stylex.ts
new file mode 100644
index 0000000000..608e745223
--- /dev/null
+++ b/packages/core/src/theme/dataTokens.stylex.ts
@@ -0,0 +1,90 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file dataTokens.stylex.ts
+ * @input None (canonical data-color token definitions)
+ * @output dataVars, DataTokenName
+ * @position Public StyleX data-token source; generates the plain JS compatibility view
+ *
+ * This is the single source of truth for Astryx data-color names and defaults.
+ * Run `pnpm generate:data-tokens` after editing the static defaults object.
+ */
+
+import * as stylex from '@stylexjs/stylex';
+
+const dataTokenDefaults = {
+ // Categorical palette
+ '--color-data-categorical-blue': 'light-dark(#0171E3, #0171E3)',
+ '--color-data-categorical-orange': 'light-dark(#EB6E00, #EB6E00)',
+ '--color-data-categorical-purple': 'light-dark(#6B1EFD, #6B1EFD)',
+ '--color-data-categorical-green': 'light-dark(#0B991F, #0B991F)',
+ '--color-data-categorical-pink': 'light-dark(#F351C0, #F351C0)',
+ '--color-data-categorical-cyan': 'light-dark(#0171A4, #0171A4)',
+ '--color-data-categorical-red': 'light-dark(#F5394F, #F5394F)',
+ '--color-data-categorical-teal': 'light-dark(#08A3A3, #08A3A3)',
+ '--color-data-categorical-brown': 'light-dark(#965E03, #965E03)',
+ '--color-data-categorical-indigo': 'light-dark(#6F8AFF, #6F8AFF)',
+
+ // Neutral
+ '--color-data-neutral': 'light-dark(#8494A3, #8C939B)',
+
+ // Sequential ramps (5 = darkest, 1 = lightest)
+ '--color-data-blue-5': 'light-dark(#02165E, #02165E)',
+ '--color-data-blue-4': 'light-dark(#004CBC, #004CBC)',
+ '--color-data-blue-3': 'light-dark(#2694FE, #2694FE)',
+ '--color-data-blue-2': 'light-dark(#78BEFF, #78BEFF)',
+ '--color-data-blue-1': 'light-dark(#DBECFF, #DBECFF)',
+
+ '--color-data-shamrock-5': 'light-dark(#0B603D, #0B603D)',
+ '--color-data-shamrock-4': 'light-dark(#138546, #138546)',
+ '--color-data-shamrock-3': 'light-dark(#24BB5E, #24BB5E)',
+ '--color-data-shamrock-2': 'light-dark(#8EF7AA, #8EF7AA)',
+ '--color-data-shamrock-1': 'light-dark(#D6FEE4, #D6FEE4)',
+
+ '--color-data-orange-5': 'light-dark(#A13F04, #A13F04)',
+ '--color-data-orange-4': 'light-dark(#D66100, #D66100)',
+ '--color-data-orange-3': 'light-dark(#FD9537, #FD9537)',
+ '--color-data-orange-2': 'light-dark(#FDB876, #FDB876)',
+ '--color-data-orange-1': 'light-dark(#FFE6CF, #FFE6CF)',
+
+ '--color-data-pink-5': 'light-dark(#8E1073, #8E1073)',
+ '--color-data-pink-4': 'light-dark(#D123A1, #D123A1)',
+ '--color-data-pink-3': 'light-dark(#F989D3, #F989D3)',
+ '--color-data-pink-2': 'light-dark(#FEADE3, #FEADE3)',
+ '--color-data-pink-1': 'light-dark(#FCE3F4, #FCE3F4)',
+
+ '--color-data-purple-5': 'light-dark(#3E0697, #3E0697)',
+ '--color-data-purple-4': 'light-dark(#6B1EFD, #6B1EFD)',
+ '--color-data-purple-3': 'light-dark(#9081FF, #9081FF)',
+ '--color-data-purple-2': 'light-dark(#B3B0FE, #B3B0FE)',
+ '--color-data-purple-1': 'light-dark(#E8E8FB, #E8E8FB)',
+
+ '--color-data-red-5': 'light-dark(#9D0519, #9D0519)',
+ '--color-data-red-4': 'light-dark(#D31130, #D31130)',
+ '--color-data-red-3': 'light-dark(#FB7D87, #FB7D87)',
+ '--color-data-red-2': 'light-dark(#FFB2B8, #FFB2B8)',
+ '--color-data-red-1': 'light-dark(#FEE4E6, #FEE4E6)',
+
+ '--color-data-teal-5': 'light-dark(#08767D, #08767D)',
+ '--color-data-teal-4': 'light-dark(#0C9293, #0C9293)',
+ '--color-data-teal-3': 'light-dark(#0DB7AF, #0DB7AF)',
+ '--color-data-teal-2': 'light-dark(#6CE6D8, #6CE6D8)',
+ '--color-data-teal-1': 'light-dark(#D7FCF8, #D7FCF8)',
+
+ '--color-data-yellow-5': 'light-dark(#8A5001, #8A5001)',
+ '--color-data-yellow-4': 'light-dark(#D69804, #D69804)',
+ '--color-data-yellow-3': 'light-dark(#FBCE03, #FBCE03)',
+ '--color-data-yellow-2': 'light-dark(#FCEC85, #FCEC85)',
+ '--color-data-yellow-1': 'light-dark(#FDF6BA, #FDF6BA)',
+
+ '--color-data-gray-5': 'light-dark(#25363F, #333338)',
+ '--color-data-gray-4': 'light-dark(#5D6C7B, #666A72)',
+ '--color-data-gray-3': 'light-dark(#AFB9C4, #B2B8BE)',
+ '--color-data-gray-2': 'light-dark(#CCD3DB, #D0D3D6)',
+ '--color-data-gray-1': 'light-dark(#F1F4F7, #F2F4F6)',
+} as const;
+
+/** Public StyleX data-color variables. The complete 56-token group is atomic. */
+export const dataVars = stylex.defineVars(dataTokenDefaults);
+
+export type DataTokenName = keyof typeof dataTokenDefaults;
diff --git a/packages/core/src/theme/domainTokens/dataTokens.ts b/packages/core/src/theme/domainTokens/dataTokens.ts
index 935a5bdb37..befea9561a 100644
--- a/packages/core/src/theme/domainTokens/dataTokens.ts
+++ b/packages/core/src/theme/domainTokens/dataTokens.ts
@@ -2,95 +2,65 @@
/**
* @file dataTokens.ts
- * @input None (pure token definitions)
+ * @input dataTokens.stylex.ts (generated; do not edit)
* @output dataTokenDefaults, DataTokenName
- * @position Domain token sub-module; re-exported from domainTokens/index.ts
+ * @position Plain compatibility view for theme validation and JavaScript token resolution
*
- * Data visualization tokens. Used by chart and graph components to maintain
- * consistent, theme-aware color palettes across all data vis surfaces.
- *
- * Token structure:
- * - Categorical: one accent per category (use for distinct series/dimensions)
- * - Neutral: a single neutral tone (use for labels, reference lines, empty states)
- * - Sequential ramps (color-5 → color-1): darkest → lightest within a hue.
- * Use for ordered/quantitative scales, heatmaps, choropleth maps.
+ * Run `pnpm generate:data-tokens` after editing the canonical StyleX source.
*/
export const dataTokenDefaults = {
- // --- Categorical palette (single accent color per category) ---
- '--color-data-categorical-blue': 'light-dark(#0171E3, #0171E3)',
+ '--color-data-categorical-blue': 'light-dark(#0171E3, #0171E3)',
'--color-data-categorical-orange': 'light-dark(#EB6E00, #EB6E00)',
'--color-data-categorical-purple': 'light-dark(#6B1EFD, #6B1EFD)',
- '--color-data-categorical-green': 'light-dark(#0B991F, #0B991F)',
- '--color-data-categorical-pink': 'light-dark(#F351C0, #F351C0)',
- '--color-data-categorical-cyan': 'light-dark(#0171A4, #0171A4)',
- '--color-data-categorical-red': 'light-dark(#F5394F, #F5394F)',
- '--color-data-categorical-teal': 'light-dark(#08A3A3, #08A3A3)',
- '--color-data-categorical-brown': 'light-dark(#965E03, #965E03)',
+ '--color-data-categorical-green': 'light-dark(#0B991F, #0B991F)',
+ '--color-data-categorical-pink': 'light-dark(#F351C0, #F351C0)',
+ '--color-data-categorical-cyan': 'light-dark(#0171A4, #0171A4)',
+ '--color-data-categorical-red': 'light-dark(#F5394F, #F5394F)',
+ '--color-data-categorical-teal': 'light-dark(#08A3A3, #08A3A3)',
+ '--color-data-categorical-brown': 'light-dark(#965E03, #965E03)',
'--color-data-categorical-indigo': 'light-dark(#6F8AFF, #6F8AFF)',
-
- // --- Neutral ---
'--color-data-neutral': 'light-dark(#8494A3, #8C939B)',
-
- // --- Sequential ramps (5 = darkest, 1 = lightest) ---
-
- // Blue
'--color-data-blue-5': 'light-dark(#02165E, #02165E)',
'--color-data-blue-4': 'light-dark(#004CBC, #004CBC)',
'--color-data-blue-3': 'light-dark(#2694FE, #2694FE)',
'--color-data-blue-2': 'light-dark(#78BEFF, #78BEFF)',
'--color-data-blue-1': 'light-dark(#DBECFF, #DBECFF)',
-
- // Shamrock
'--color-data-shamrock-5': 'light-dark(#0B603D, #0B603D)',
'--color-data-shamrock-4': 'light-dark(#138546, #138546)',
'--color-data-shamrock-3': 'light-dark(#24BB5E, #24BB5E)',
'--color-data-shamrock-2': 'light-dark(#8EF7AA, #8EF7AA)',
'--color-data-shamrock-1': 'light-dark(#D6FEE4, #D6FEE4)',
-
- // Orange
'--color-data-orange-5': 'light-dark(#A13F04, #A13F04)',
'--color-data-orange-4': 'light-dark(#D66100, #D66100)',
'--color-data-orange-3': 'light-dark(#FD9537, #FD9537)',
'--color-data-orange-2': 'light-dark(#FDB876, #FDB876)',
'--color-data-orange-1': 'light-dark(#FFE6CF, #FFE6CF)',
-
- // Pink
'--color-data-pink-5': 'light-dark(#8E1073, #8E1073)',
'--color-data-pink-4': 'light-dark(#D123A1, #D123A1)',
'--color-data-pink-3': 'light-dark(#F989D3, #F989D3)',
'--color-data-pink-2': 'light-dark(#FEADE3, #FEADE3)',
'--color-data-pink-1': 'light-dark(#FCE3F4, #FCE3F4)',
-
- // Purple
'--color-data-purple-5': 'light-dark(#3E0697, #3E0697)',
'--color-data-purple-4': 'light-dark(#6B1EFD, #6B1EFD)',
'--color-data-purple-3': 'light-dark(#9081FF, #9081FF)',
'--color-data-purple-2': 'light-dark(#B3B0FE, #B3B0FE)',
'--color-data-purple-1': 'light-dark(#E8E8FB, #E8E8FB)',
-
- // Red
'--color-data-red-5': 'light-dark(#9D0519, #9D0519)',
'--color-data-red-4': 'light-dark(#D31130, #D31130)',
'--color-data-red-3': 'light-dark(#FB7D87, #FB7D87)',
'--color-data-red-2': 'light-dark(#FFB2B8, #FFB2B8)',
'--color-data-red-1': 'light-dark(#FEE4E6, #FEE4E6)',
-
- // Teal
'--color-data-teal-5': 'light-dark(#08767D, #08767D)',
'--color-data-teal-4': 'light-dark(#0C9293, #0C9293)',
'--color-data-teal-3': 'light-dark(#0DB7AF, #0DB7AF)',
'--color-data-teal-2': 'light-dark(#6CE6D8, #6CE6D8)',
'--color-data-teal-1': 'light-dark(#D7FCF8, #D7FCF8)',
-
- // Yellow
'--color-data-yellow-5': 'light-dark(#8A5001, #8A5001)',
'--color-data-yellow-4': 'light-dark(#D69804, #D69804)',
'--color-data-yellow-3': 'light-dark(#FBCE03, #FBCE03)',
'--color-data-yellow-2': 'light-dark(#FCEC85, #FCEC85)',
'--color-data-yellow-1': 'light-dark(#FDF6BA, #FDF6BA)',
-
- // Gray
'--color-data-gray-5': 'light-dark(#25363F, #333338)',
'--color-data-gray-4': 'light-dark(#5D6C7B, #666A72)',
'--color-data-gray-3': 'light-dark(#AFB9C4, #B2B8BE)',
diff --git a/scripts/build-css.graph.test.mjs b/scripts/build-css.graph.test.mjs
new file mode 100644
index 0000000000..1e6c2d2c50
--- /dev/null
+++ b/scripts/build-css.graph.test.mjs
@@ -0,0 +1,130 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import stylexBabelPlugin from '@stylexjs/babel-plugin';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import {afterEach, describe, expect, it} from 'vitest';
+import {collectStyleXCSS} from './build-css.mjs';
+
+const temporaryRoots = [];
+
+afterEach(async () => {
+ await Promise.all(
+ temporaryRoots
+ .splice(0)
+ .map(root => fs.rm(root, {recursive: true, force: true})),
+ );
+});
+
+async function fixture() {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'astryx-stylex-graph-'));
+ temporaryRoots.push(root);
+ const src = path.join(root, 'consumer');
+ const external = path.join(root, 'external');
+ await fs.mkdir(src, {recursive: true});
+ await fs.mkdir(external, {recursive: true});
+ return {root, src, external};
+}
+
+describe('build-css dependency extraction', () => {
+ it('emits a referenced cross-package variable group and omits an unused group', async () => {
+ const {src, external} = await fixture();
+ await fs.writeFile(
+ path.join(src, 'Consumer.ts'),
+ `import {usedVars} from '@probe/used.stylex';\nexport const color = usedVars['--probe-used-a'];\n`,
+ );
+ await fs.writeFile(
+ path.join(external, 'used.stylex.ts'),
+ `import * as stylex from '@stylexjs/stylex';\nexport const usedVars = stylex.defineVars({'--probe-used-a': 'red', '--probe-used-b': 'blue'});\n`,
+ );
+ await fs.writeFile(
+ path.join(external, 'unused.stylex.ts'),
+ `import * as stylex from '@stylexjs/stylex';\nexport const unusedVars = stylex.defineVars({'--probe-unused': 'green'});\n`,
+ );
+
+ const rules = await collectStyleXCSS({
+ src,
+ aliases: {'@probe/*': [path.join(external, '*')]},
+ });
+ const css = stylexBabelPlugin.processStylexRules(rules, false);
+
+ expect(css).toContain('--probe-used-a:red');
+ expect(css).toContain('--probe-used-b:blue');
+ expect(css).not.toContain('--probe-unused');
+ });
+
+ it('emits no variable group when no source entry imports one', async () => {
+ const {src, external} = await fixture();
+ await fs.writeFile(
+ path.join(src, 'Consumer.ts'),
+ 'export const value = 1;\n',
+ );
+ await fs.writeFile(
+ path.join(external, 'unused.stylex.ts'),
+ `import * as stylex from '@stylexjs/stylex';\nexport const unusedVars = stylex.defineVars({'--probe-unused': 'green'});\n`,
+ );
+
+ const rules = await collectStyleXCSS({
+ src,
+ aliases: {'@probe/*': [path.join(external, '*')]},
+ });
+
+ expect(rules).toEqual([]);
+ });
+
+ it('ignores type-only imports and re-exports', async () => {
+ const {src, external} = await fixture();
+ await fs.writeFile(
+ path.join(src, 'Consumer.ts'),
+ `import type {ProbeToken} from '@probe/types.stylex';\nexport type {ProbeToken as ExportedProbeToken} from '@probe/types.stylex';\nexport type ConsumerToken = ProbeToken;\n`,
+ );
+ await fs.writeFile(
+ path.join(src, 'InlineTypeConsumer.ts'),
+ `import {type ProbeToken} from '@probe/types.stylex';\nexport type InlineConsumerToken = ProbeToken;\n`,
+ );
+ await fs.writeFile(
+ path.join(external, 'types.stylex.ts'),
+ `import * as stylex from '@stylexjs/stylex';\nexport const typeVars = stylex.defineVars({'--probe-type-only': 'green'});\nexport type ProbeToken = keyof typeof typeVars;\n`,
+ );
+
+ const rules = await collectStyleXCSS({
+ src,
+ aliases: {'@probe/*': [path.join(external, '*')]},
+ });
+
+ expect(rules).toEqual([]);
+ });
+
+ it('leaves a variable group to the provider stylesheet that already emits it', async () => {
+ const {root, src, external} = await fixture();
+ const provider = path.join(root, 'provider');
+ await fs.mkdir(provider, {recursive: true});
+ await fs.writeFile(
+ path.join(provider, 'Component.ts'),
+ `import {sharedVars} from '../external/shared.stylex';\nexport const color = sharedVars['--probe-shared'];\n`,
+ );
+ await fs.writeFile(
+ path.join(src, 'Consumer.ts'),
+ `import {sharedVars} from '@probe/shared.stylex';\nimport {dataVars} from '@probe/data.stylex';\nexport const colors = [sharedVars['--probe-shared'], dataVars['--probe-data']];\n`,
+ );
+ await fs.writeFile(
+ path.join(external, 'shared.stylex.ts'),
+ `import * as stylex from '@stylexjs/stylex';\nexport const sharedVars = stylex.defineVars({'--probe-shared': 'red'});\n`,
+ );
+ await fs.writeFile(
+ path.join(external, 'data.stylex.ts'),
+ `import * as stylex from '@stylexjs/stylex';\nexport const dataVars = stylex.defineVars({'--probe-data': 'blue'});\n`,
+ );
+
+ const rules = await collectStyleXCSS({
+ src,
+ aliases: {'@probe/*': [path.join(external, '*')]},
+ provider: {src: provider, aliases: {}},
+ });
+ const css = stylexBabelPlugin.processStylexRules(rules, false);
+
+ expect(css).toContain('--probe-data:blue');
+ expect(css).not.toContain('--probe-shared');
+ });
+});
diff --git a/scripts/build-css.mjs b/scripts/build-css.mjs
index 4c69edc3c1..fd9aa55c9e 100644
--- a/scripts/build-css.mjs
+++ b/scripts/build-css.mjs
@@ -51,6 +51,9 @@ const TARGETS = {
'@astryxdesign/core/*': [path.join(ROOT, 'packages/core/src/*')],
'@astryxdesign/core': [path.join(ROOT, 'packages/core/src')],
},
+ // astryx.css always loads with this stylesheet, so a Core variable group
+ // it already declares is not repeated here.
+ provider: 'core',
},
charts: {
src: path.resolve(ROOT, 'packages/charts/src'),
@@ -64,6 +67,9 @@ const TARGETS = {
'@astryxdesign/core/*': [path.join(ROOT, 'packages/core/src/*')],
'@astryxdesign/core': [path.join(ROOT, 'packages/core/src')],
},
+ // astryx.css always loads with this stylesheet, so a Core variable group
+ // it already declares is not repeated here.
+ provider: 'core',
},
richtext: {
src: path.resolve(ROOT, 'packages/richtext/src'),
@@ -77,6 +83,9 @@ const TARGETS = {
'@astryxdesign/core/*': [path.join(ROOT, 'packages/core/src/*')],
'@astryxdesign/core': [path.join(ROOT, 'packages/core/src')],
},
+ // astryx.css always loads with this stylesheet, so a Core variable group
+ // it already declares is not repeated here.
+ provider: 'core',
},
};
@@ -90,23 +99,162 @@ function parseTarget() {
);
process.exit(1);
}
- return {name, ...target};
+ return {
+ name,
+ ...target,
+ provider: target.provider ? TARGETS[target.provider] : undefined,
+ };
}
-async function collectStyleXCSS(target) {
+function staticStyleXImports(source) {
+ const specifiers = [];
+ const pattern =
+ /\b(?:import|export)\s+([^'";]*?\sfrom\s*)?['"]([^'"]+\.stylex)['"]/g;
+ for (const match of source.matchAll(pattern)) {
+ const clause = (match[1] ?? '').replace(/\s+from\s*$/, '').trim();
+ if (/^type(?:\s|\*|\{)/.test(clause)) {
+ continue;
+ }
+
+ // TypeScript also permits `import {type Foo}` and
+ // `export {type Foo}`. Keep a mixed list when any runtime binding remains,
+ // but do not make an all-type list retain a variable module.
+ const named = /^\{([^}]*)\}$/.exec(clause);
+ if (
+ named &&
+ named[1]
+ .split(',')
+ .map(specifier => specifier.trim())
+ .filter(Boolean)
+ .every(specifier => /^type\b/.test(specifier))
+ ) {
+ continue;
+ }
+
+ specifiers.push(match[2]);
+ }
+ return specifiers;
+}
+
+async function firstExistingModule(basePath) {
+ const candidates = [
+ basePath,
+ `${basePath}.ts`,
+ `${basePath}.tsx`,
+ `${basePath}.js`,
+ `${basePath}.mjs`,
+ path.join(basePath, 'index.ts'),
+ path.join(basePath, 'index.tsx'),
+ ];
+ for (const candidate of candidates) {
+ try {
+ const stat = await fs.stat(candidate);
+ if (stat.isFile()) {
+ return candidate;
+ }
+ } catch {
+ // Try the next supported source spelling.
+ }
+ }
+ return null;
+}
+
+async function resolveStyleXImport(specifier, importer, aliases) {
+ if (specifier.startsWith('.')) {
+ return firstExistingModule(path.resolve(path.dirname(importer), specifier));
+ }
+
+ for (const [pattern, replacements] of Object.entries(aliases)) {
+ const wildcard = pattern.indexOf('*');
+ const prefix = wildcard === -1 ? pattern : pattern.slice(0, wildcard);
+ const suffix = wildcard === -1 ? '' : pattern.slice(wildcard + 1);
+ if (!specifier.startsWith(prefix) || !specifier.endsWith(suffix)) {
+ continue;
+ }
+ const matched = specifier.slice(
+ prefix.length,
+ suffix ? -suffix.length : undefined,
+ );
+ for (const replacement of replacements) {
+ const candidate = replacement.replace('*', matched);
+ const resolved = await firstExistingModule(candidate);
+ if (resolved) {
+ return resolved;
+ }
+ }
+ }
+ return null;
+}
+
+const STYLEX_MODULE = /\.stylex\.[cm]?[jt]sx?$/;
+
+/**
+ * Walks a package from its all-component entry set through static `.stylex`
+ * imports. Non-StyleX source files are the entries; a variable module joins
+ * only when a reachable file imports it, so a public defineVars module stays
+ * absent from packages that never consume it. Modules in `provided` are left
+ * to the stylesheet that already emits them.
+ */
+async function reachableSourceFiles(target, provided = new Set()) {
const files = await glob('**/*.{ts,tsx}', {
cwd: target.src,
absolute: true,
ignore: ['**/*.test.*', '**/*.d.ts', '**/node_modules/**'],
});
- console.log(`Processing ${files.length} source files...`);
+ const queue = files.filter(file => !STYLEX_MODULE.test(file));
+ const reachable = new Map();
- const allRules = [];
+ while (queue.length > 0) {
+ const file = queue.shift();
+ if (reachable.has(file)) {
+ continue;
+ }
- for (const file of files) {
const code = await fs.readFile(file, 'utf8');
+ reachable.set(file, code);
+ for (const specifier of staticStyleXImports(code)) {
+ const dependency = await resolveStyleXImport(
+ specifier,
+ file,
+ target.aliases,
+ );
+ if (!dependency) {
+ throw new Error(
+ `Could not resolve StyleX dependency "${specifier}" from ${path.relative(ROOT, file)}`,
+ );
+ }
+ if (!provided.has(dependency)) {
+ queue.push(dependency);
+ }
+ }
+ }
+ return reachable;
+}
+/**
+ * The variable modules a provider package's own stylesheet emits. A satellite
+ * package that imports one of them relies on that stylesheet instead of
+ * declaring the same group a second time.
+ */
+async function providedStyleXModules(provider) {
+ if (!provider) {
+ return new Set();
+ }
+ const reachable = await reachableSourceFiles(provider);
+ return new Set(
+ [...reachable.keys()].filter(file => STYLEX_MODULE.test(file)),
+ );
+}
+
+export async function collectStyleXCSS(target) {
+ const provided = await providedStyleXModules(target.provider);
+ const reachable = await reachableSourceFiles(target, provided);
+ const allRules = [];
+
+ console.log(`Processing ${reachable.size} reachable source files...`);
+
+ for (const [file, code] of reachable) {
if (!code.includes('@stylexjs/stylex')) {
continue;
}
@@ -141,14 +289,16 @@ async function collectStyleXCSS(target) {
allRules.push(...result.metadata.stylex);
}
} catch (err) {
- console.warn(
- ` Warning: Could not process ${path.relative(ROOT, file)}: ${err.message}`,
+ throw new Error(
+ `Could not process ${path.relative(ROOT, file)}: ${err.message}`,
+ {cause: err},
);
}
}
- console.log(`Collected ${allRules.length} StyleX rules`);
-
+ console.log(
+ `Collected ${allRules.length} StyleX rules from ${reachable.size} reachable files`,
+ );
return allRules;
}
@@ -171,10 +321,14 @@ async function main() {
.map(line => ' ' + line)
.join('\n')}\n}\n`;
await fs.writeFile(outPath, combinedFileContents, 'utf8');
- console.log(`${target.outFile}: ${(combinedCSS.length / 1024).toFixed(1)} KB`);
+ console.log(
+ `${target.outFile}: ${(combinedCSS.length / 1024).toFixed(1)} KB`,
+ );
}
-main().catch(err => {
- console.error(err);
- process.exit(1);
-});
+if (fileURLToPath(import.meta.url) === process.argv[1]) {
+ main().catch(err => {
+ console.error(err);
+ process.exit(1);
+ });
+}
diff --git a/scripts/generate-data-tokens.mjs b/scripts/generate-data-tokens.mjs
new file mode 100644
index 0000000000..1185091a55
--- /dev/null
+++ b/scripts/generate-data-tokens.mjs
@@ -0,0 +1,86 @@
+#!/usr/bin/env node
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file generate-data-tokens.mjs
+ * @input packages/core/src/theme/dataTokens.stylex.ts
+ * @output packages/core/src/theme/domainTokens/dataTokens.ts
+ * @position Keeps the non-StyleX token-resolution view derived from the public StyleX source
+ *
+ * Usage:
+ * node scripts/generate-data-tokens.mjs
+ * node scripts/generate-data-tokens.mjs --check
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {fileURLToPath} from 'node:url';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const SOURCE = path.join(ROOT, 'packages/core/src/theme/dataTokens.stylex.ts');
+const OUTPUT = path.join(
+ ROOT,
+ 'packages/core/src/theme/domainTokens/dataTokens.ts',
+);
+
+export function parseDataTokenDefaults(source) {
+ const block = source.match(
+ /const dataTokenDefaults\s*=\s*\{([\s\S]*?)\}\s*as const;/,
+ );
+ if (!block) {
+ throw new Error('Could not find the static dataTokenDefaults object');
+ }
+
+ const entries = [];
+ const seen = new Set();
+ const entryPattern = /'(--color-data-[^']+)'\s*:\s*'([^']+)'/g;
+ for (const match of block[1].matchAll(entryPattern)) {
+ const [, name, value] = match;
+ if (seen.has(name)) {
+ throw new Error(`Duplicate data token: ${name}`);
+ }
+ seen.add(name);
+ entries.push([name, value]);
+ }
+
+ if (entries.length !== 56) {
+ throw new Error(`Expected 56 data tokens, found ${entries.length}`);
+ }
+ return entries;
+}
+
+export function renderDataTokenDefaults(entries) {
+ const declarations = entries
+ .map(([name, value]) => ` '${name}': '${value}',`)
+ .join('\n');
+
+ return `// Copyright (c) Meta Platforms, Inc. and affiliates.\n\n/**\n * @file dataTokens.ts\n * @input dataTokens.stylex.ts (generated; do not edit)\n * @output dataTokenDefaults, DataTokenName\n * @position Plain compatibility view for theme validation and JavaScript token resolution\n *\n * Run \`pnpm generate:data-tokens\` after editing the canonical StyleX source.\n */\n\nexport const dataTokenDefaults = {\n${declarations}\n} as const;\n\nexport type DataTokenName = keyof typeof dataTokenDefaults;\n`;
+}
+
+export function generateDataTokenDefaults() {
+ return renderDataTokenDefaults(
+ parseDataTokenDefaults(fs.readFileSync(SOURCE, 'utf8')),
+ );
+}
+
+function main() {
+ const expected = generateDataTokenDefaults();
+ if (process.argv.includes('--check')) {
+ const actual = fs.existsSync(OUTPUT) ? fs.readFileSync(OUTPUT, 'utf8') : '';
+ if (actual !== expected) {
+ console.error(
+ 'Data token compatibility view is stale. Run `pnpm generate:data-tokens`.',
+ );
+ process.exit(1);
+ }
+ console.log('Data token compatibility view is in sync.');
+ return;
+ }
+
+ fs.writeFileSync(OUTPUT, expected);
+ console.log(`Generated ${path.relative(ROOT, OUTPUT)}.`);
+}
+
+if (fileURLToPath(import.meta.url) === process.argv[1]) {
+ main();
+}
diff --git a/scripts/generate-data-tokens.test.mjs b/scripts/generate-data-tokens.test.mjs
new file mode 100644
index 0000000000..6377ed3608
--- /dev/null
+++ b/scripts/generate-data-tokens.test.mjs
@@ -0,0 +1,47 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {describe, expect, it} from 'vitest';
+import {
+ generateDataTokenDefaults,
+ parseDataTokenDefaults,
+} from './generate-data-tokens.mjs';
+
+describe('generate-data-tokens', () => {
+ it('requires one complete 56-token canonical object', () => {
+ const source = `const dataTokenDefaults = {\n${Array.from(
+ {length: 56},
+ (_, index) =>
+ ` '--color-data-probe-${index}': 'light-dark(#000, #fff)',`,
+ ).join('\n')}\n} as const;`;
+
+ expect(parseDataTokenDefaults(source)).toHaveLength(56);
+ expect(() =>
+ parseDataTokenDefaults(
+ source.replace(
+ " '--color-data-probe-55': 'light-dark(#000, #fff)',\n",
+ '',
+ ),
+ ),
+ ).toThrow('Expected 56 data tokens, found 55');
+ });
+
+ it('keeps the checked-in compatibility view in sync', () => {
+ const root = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '..',
+ );
+ const output = fs.readFileSync(
+ path.join(root, 'packages/core/src/theme/domainTokens/dataTokens.ts'),
+ 'utf8',
+ );
+ const generated = generateDataTokenDefaults();
+
+ expect(output).toBe(generated);
+ expect(generated).toContain(
+ "'--color-data-categorical-green': 'light-dark(#0B991F, #0B991F)'",
+ );
+ });
+});
diff --git a/scripts/generate-token-docs.mjs b/scripts/generate-token-docs.mjs
index f67b24caf2..dede8510d6 100644
--- a/scripts/generate-token-docs.mjs
+++ b/scripts/generate-token-docs.mjs
@@ -24,7 +24,7 @@ const ROOT = resolve(__dirname, '..');
const TOKENS_SRC = resolve(ROOT, 'packages/core/src/theme/tokens.stylex.ts');
const DATA_TOKENS_SRC = resolve(
ROOT,
- 'packages/core/src/theme/domainTokens/dataTokens.ts',
+ 'packages/core/src/theme/dataTokens.stylex.ts',
);
const SYNTAX_TOKENS_SRC = resolve(
ROOT,
@@ -53,9 +53,9 @@ function sourceText(file) {
*/
function extractDefaults(name, file = TOKENS_SRC) {
const src = sourceText(file);
- // Match: `export const <name> = {` ... `} as const;`
+ // Match: `[export] const <name> = {` ... `} as const;`
const re = new RegExp(
- `export const ${name}\\s*=\\s*\\{([^}]+(?:\\{[^}]*\\}[^}]*)*)\\}\\s*as const`,
+ `(?:export\\s+)?const ${name}\\s*=\\s*\\{([^}]+(?:\\{[^}]*\\}[^}]*)*)\\}\\s*as const`,
's',
);
const m = src.match(re);
@@ -113,7 +113,7 @@ const groups = [
file: DATA_TOKENS_SRC,
title: 'Data Visualization Tokens',
description:
- 'Colors for charts and graphs: one categorical accent per series, a neutral for labels and reference lines, and sequential ramps from 5 (darkest) to 1 (lightest) for ordered scales and heatmaps.',
+ 'Colors for charts and graphs: one categorical accent per series, a neutral for labels and reference lines, and sequential ramps from 5 (darkest) to 1 (lightest) for ordered scales and heatmaps. Import their public StyleX variables from @astryxdesign/core/theme/dataTokens.stylex.',
headers: ['Token', 'Light', 'Dark'],
formatRow: lightDarkRow,
},
@@ -278,6 +278,7 @@ sections.push({
label: 'Using token imports',
code: `import * as stylex from '@stylexjs/stylex';
import {colorVars, spacingVars, sizeVars, radiusVars} from '@astryxdesign/core/theme/tokens.stylex';
+import {dataVars} from '@astryxdesign/core/theme/dataTokens.stylex';
const styles = stylex.create({
card: {
@@ -285,6 +286,9 @@ const styles = stylex.create({
backgroundColor: colorVars['--color-background-surface'],
borderRadius: radiusVars['--radius-container'],
},
+ series: {
+ color: dataVars['--color-data-categorical-blue'],
+ },
button: {
height: sizeVars['--size-element-md'],
},
@@ -314,7 +318,7 @@ const output = `\
// AUTO-GENERATED — do not edit manually.
// Source: packages/core/src/theme/tokens.stylex.ts,
-// domainTokens/dataTokens.ts, and syntax/tokens.ts
+// dataTokens.stylex.ts, and syntax/tokens.ts
// Run: node scripts/generate-token-docs.mjs
// Total: ${totalTokens} tokens across ${groups.length} categories.
diff --git a/scripts/sync-exports.js b/scripts/sync-exports.js
index b91cea4617..d6dc099b72 100644
--- a/scripts/sync-exports.js
+++ b/scripts/sync-exports.js
@@ -82,6 +82,11 @@ const STATIC_EXPORTS = {
types: './dist/theme/tokens.stylex.d.ts',
default: './dist/theme/tokens.stylex.js',
},
+ './theme/dataTokens.stylex': {
+ source: './src/theme/dataTokens.stylex.ts',
+ types: './dist/theme/dataTokens.stylex.d.ts',
+ default: './dist/theme/dataTokens.stylex.js',
+ },
'./theme/syntax': {
source: './src/theme/syntax/index.ts',
types: './dist/theme/syntax/index.d.ts',