An open source design system that's fully customizable and agent ready
TypeScript
feat(build): build Astryx from source under Turbopack (#7754)
Christopher Chedeau653624f84b4d
diff --git a/.changeset/build-next-turbopack-source.md b/.changeset/build-next-turbopack-source.mdnew file mode 100644index 0000000000..cc066a2c18--- /dev/null+++ b/.changeset/build-next-turbopack-source.md@@ -0,0 +1,7 @@+---+'@astryxdesign/build': patch+---++[feat] `withAstryx()` builds Astryx from source under Turbopack instead of refusing to. It points each package's documented entry points at their source (Core, Lab, Charts and Rich Text), compiles that source with the settings the prebuilt stylesheets use, and keeps the app's own Turbopack rules off it. The new PostCSS plugin `@astryxdesign/build/next/postcss` replaces an `@astryx;` rule with each source-built package's prebuilt stylesheet, compiled from that source: the same rules and selectors, in the same order, inside `@layer astryx-base`. To set it up, list `@astryxdesign/build/next/postcss` in the app's PostCSS config and put one `@astryx;` rule in the app's global stylesheet (option `cwd`, the app root, defaults to the working directory). Under Turbopack, the webpack setup's `@astryxdesign/build/postcss` refuses to run beside `withAstryx()`, since its rules never match the classes Turbopack renders. In this source build, an installed Astryx package with a malformed `package.json` fails the build instead of being left out. The webpack setup is unchanged: it builds Core and Lab from source, and Rich Text and Charts keep their prebuilt stylesheets there.++@vjeuxdiff --git a/docs/specs/AST-080-package-stylesheets/spec.md b/docs/specs/AST-080-package-stylesheets/spec.mdindex dedd032d05..384b9944ca 100644--- a/docs/specs/AST-080-package-stylesheets/spec.md+++ b/docs/specs/AST-080-package-stylesheets/spec.md@@ -20,6 +20,25 @@ affects_consumer_docs: [styling-overview, getting-started, migration-setup]<!-- Describe the system, not the project: present tense, what it does. No proposals, history, pull requests, or research in the record; see docs/contributing/spec-writing.md and report its rubric results in the pull request. -->+<!-- path-applicability:v1 -->++```json+{+ "paths": [+ "packages/build/src/next.js",+ "packages/build/src/next-postcss.js",+ "packages/build/src/source-stylesheet.js",+ "packages/build/src/turbopack-loader.js",+ "packages/build/src/next.turbopack.test.mjs",+ "packages/build/src/source-stylesheet.test.mjs",+ "packages/build/scripts/turbopack-speed.mjs",+ "packages/build/__fixtures__/next-app.mjs",+ "packages/build/__fixtures__/next-turbopack/src/app/globals.css",+ "packages/build/__fixtures__/next-turbopack/src/app/page.tsx"+ ]+}+```+## IntentA product that uses Astryx loads prebuilt stylesheets: `@astryxdesign/core/astryx.css`,@@ -181,6 +200,11 @@ first.(FR7). Product CSS, including the product's own StyleX output, staysunlayered and wins over every Astryx rule in any chunk or load order. Anon-Core block relies on Core's variables and keyframes as under FR2.+ - **Stylesheet entry (Turbopack).** The product lists the PostCSS plugin+ `@astryxdesign/build/next/postcss` in its PostCSS config and puts one+ `@astryx;` rule in its global stylesheet. Under Turbopack, the plugin MUST+ replace that rule with every source-built package's block, in package+ order.- **Fast path (Turbopack goal, known gap).** The goal is that Astryx modulescompile inside Turbopack's native pipeline: no `turbopack.rules`JavaScript loader, no Babel, and no PostCSS step compiles an Astryx module,@@ -231,12 +255,20 @@ first.page; and nothing makes a Core source build carry the Core definitions thatprebuilt `lab.css` relies on. Conforming changes the class names and layers itemits for its current users.-- `withAstryx()` does not yet meet FR9 (implementation gaps): it refuses- Turbopack builds; under webpack it source-builds Core and Lab, while Rich Text- and Charts stay on their prebuilt stylesheets; and a source build emits no- order registration in its own output (FR7), relying on `reset.css`, the theme,- or the product's line. No fixture checks FR9 and no speed figures are- reported. Rich Text and Charts already publish `source` export conditions.+- Under Turbopack, `withAstryx()` source-builds Core, Lab, Rich Text, and+ Charts; each compiled block begins with the FR3 order registration (FR7), and+ the build fails when the product imports the prebuilt stylesheet of a package+ it compiles. `@astryxdesign/build/next/postcss` replaces the app+ stylesheet's `@astryx;` marker with those blocks, compiling each package's+ modules a second time with Babel and the StyleX plugin, as the loader does.+ A Next.js fixture checks FR9 under Turbopack, and a script in+ `@astryxdesign/build` measures the speed figures.+- Under webpack, `withAstryx()` does not yet meet FR9 (implementation gaps): it+ source-builds Core and Lab with the `@astryxdesign/build` setup above, while+ Rich Text and Charts stay on their prebuilt stylesheets, and that source build+ emits no order registration in its own output (FR7), relying on `reset.css`,+ the theme, or the product's line. Closing these gaps changes existing webpack+ output.- Under Turbopack no maintained StyleX compiler runs in the native pipeline, sothe FR9 fast path is a goal with a known gap: the Turbopack route compilesAstryx modules through a JavaScript loader running Babel and the StyleX Babeldiff --git a/package.json b/package.jsonindex ed5cef9868..9acfca80d1 100644--- a/package.json+++ b/package.json@@ -27,7 +27,7 @@"test:ui": "vitest run --project ui --exclude packages/core/src/Markdown/Markdown.fr23.perf.test.ts","test:ui:isolated": "vitest run --project ui packages/core/src/Markdown/Markdown.fr23.perf.test.ts --no-file-parallelism","test:node": "vitest run --project node",- "test:build": "vitest run packages/build/src/packed-consumer.test.mjs --project node --maxWorkers=1 && pnpm -F @astryxdesign/build build && node .github/scripts/theme-layer-cascade.js && ASTRYX_STYLEX_BROWSER=1 vitest run scripts/stylex-module-resolution.browser.test.mjs --project node --maxWorkers=1",+ "test:build": "vitest run packages/build/src/packed-consumer.test.mjs --project node --maxWorkers=1 && pnpm -F @astryxdesign/build build && node .github/scripts/theme-layer-cascade.js && ASTRYX_STYLEX_BROWSER=1 vitest run scripts/stylex-module-resolution.browser.test.mjs --project node --maxWorkers=1 && ASTRYX_TURBOPACK_E2E=1 vitest run packages/build/src/next.turbopack.test.mjs --project node --maxWorkers=1","test:theme-family": "pnpm -F @astryxdesign/core build && pnpm -F @astryxdesign/sandbox generate:theme-family && node .github/scripts/theme-family-cascade.js","test:a11y-contract": "playwright test --config playwright.config.ts --project chromium","test:a11y-contract:pr": "node .github/scripts/a11y-pr-contracts.mjs",diff --git a/packages/build/README.md b/packages/build/README.mdindex 752061d5eb..0f4f5b9701 100644--- a/packages/build/README.md+++ b/packages/build/README.md@@ -1,16 +1,18 @@# @astryxdesign/build-Build plugins for Astryx source builds. Provides babel, PostCSS, and Vite integrations that compile Astryx library and product code with separate class name prefixes, which enables independent CSS layers:+Build plugins for Astryx source builds. In the webpack and Vite setups, its babel, PostCSS, and Vite integrations compile Astryx library and product code with separate class name prefixes, which enables independent CSS layers:```reset < astryx-base (library, astryx prefix) < astryx-theme < product (app, x prefix)```+Under Turbopack, `withAstryx()` and `@astryxdesign/build/next/postcss` compile Astryx the way its prebuilt stylesheets are compiled: the same class names, in `@layer astryx-base`.+## 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.-`@astryxdesign/build` solves this by:+In the webpack and Vite setups, `@astryxdesign/build` solves this by:1. Compiling Astryx library code with `astryx` prefix (`.astryx78zum5`)2. Compiling product code with default `x` prefix (`.x78zum5`)@@ -19,11 +21,13 @@ StyleX generates atomic CSS: same declaration = same class name. Without separat## Packages-| Export | Purpose | Platform |-| ----------------------------- | -------------------------------------------- | --------------------------- |-| `@astryxdesign/build/babel` | Babel plugin: splits class prefixes per file | Next.js, any babel pipeline |-| `@astryxdesign/build/postcss` | PostCSS plugin: compiles + splits CSS layers | Next.js |-| `@astryxdesign/build/vite` | Vite plugin: wraps unplugin + splits layers | Vite, Storybook |+| Export | Purpose | Platform |+| ---------------------------------- | -------------------------------------------- | ---------------------------- |+| `@astryxdesign/build/babel` | Babel plugin: splits class prefixes per file | Next.js, any babel pipeline |+| `@astryxdesign/build/postcss` | PostCSS plugin: compiles + splits CSS layers | Next.js (webpack) |+| `@astryxdesign/build/next` | `withAstryx()`: the Next.js config helper | Next.js (webpack, Turbopack) |+| `@astryxdesign/build/next/postcss` | PostCSS plugin: `@astryx;` | Next.js (Turbopack) |+| `@astryxdesign/build/vite` | Vite plugin: wraps unplugin + splits layers | Vite, Storybook |## Install@@ -39,28 +43,49 @@ npm install -D @stylexjs/unplugin----## Next.js Setup--> **Requires the webpack bundler.** Every step below configures resolution through-> `nextConfig.webpack`, and Turbopack never calls that hook. Under Turbopack the app-> resolves `@astryxdesign/*` to `dist` while the PostCSS pass compiles the library from-> `source` — the two emit disjoint class names, so the build succeeds and the page-> renders unstyled with nothing logged.->-> Next.js 16 selects Turbopack by default, so name the bundler explicitly:->-> ```bash-> next dev --webpack-> next build --webpack-> ```->-> `withAstryx()` throws when it sees `TURBOPACK` set rather than letting that through.-> Next 16 also rejects a `webpack` config with no `turbopack` config on its own when no-> bundler flag is given.->-> If you would rather not pin the bundler, take the pre-built package instead: import-> `@astryxdesign/core/astryx.css` and skip the babel and PostCSS setup entirely. See-> [example-nextjs](../../apps/example-nextjs/).+## Next.js Setup (Turbopack)++Under Turbopack, the default bundler since Next.js 16, `withAstryx()` compiles the+Astryx modules your app imports from source as the prebuilt stylesheets are compiled,+and `@astryxdesign/build/next/postcss` emits each source-built package's prebuilt+stylesheet from that source: the same rules and selectors, in the same order, inside+`@layer astryx-base`. Installed and workspace-linked packages both work; Astryx needs+no Babel config.++1. `next.config.mjs`, around your config and its own `turbopack.rules`:++ ```js+ import {withAstryx} from '@astryxdesign/build/next';+ export default withAstryx({/* your Next.js config */});+ ```++2. `postcss.config.js`, beside any plugin your app already uses:++ ```js+ module.exports = {plugins: {'@astryxdesign/build/next/postcss': {}}};+ ```++3. Your global stylesheet, with `@astryx;` in place of `astryx.css`, `lab.css`, `charts.css` and `richtext.css` (every installed package with a prebuilt stylesheet builds from source, so import none of them: the build fails on one):++ ```css+ @import '@astryxdesign/core/reset.css';+ @import '@astryxdesign/theme-neutral/theme.css';++ @astryx;+ ```++ Each package's rules start with the `reset, astryx-base, astryx-theme` layer+ order, as `reset.css` and the theme do, so the order holds in any chunk order+ without a line of your own.++Your own Turbopack rules are kept off Astryx source. Your Babel config file is not,+and Babel's `ignore` cannot exclude Astryx: to keep it off, set+`experimental.turbopackUseBuiltinBabel: false` and run `babel-loader` from a+`turbopack.rules` entry, which `withAstryx()` keeps off Astryx source like any rule.++## Next.js Setup (webpack)++These steps run under `next dev --webpack` and `next build --webpack`.### 1. babel.config.jsdiff --git a/packages/build/__fixtures__/next-app.mjs b/packages/build/__fixtures__/next-app.mjsnew file mode 100644index 0000000000..8173f1a788--- /dev/null+++ b/packages/build/__fixtures__/next-app.mjs@@ -0,0 +1,198 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file next-app.mjs+ * @input __fixtures__/next-turbopack and the workspace packages+ * @output Scratch copies of the Next.js fixture app, and helpers to build and+ * serve one. Core is linked, and a registry's layout installs the others.+ * @position Shared by the Turbopack end-to-end test (src/next.turbopack.test.mjs)+ * and the speed figures (scripts/turbopack-speed.mjs)+ */++import {spawn} from 'node:child_process';+import * as fs from 'node:fs';+import * as net from 'node:net';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';++export const packageDir = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '..',+);+export const repoRoot = path.resolve(packageDir, '../..');+export const env = {+ ...process.env,+ NEXT_TELEMETRY_DISABLED: '1',+ TURBOPACK: undefined,+ NODE_PATH: undefined,+};++export const nextBin = dir => path.join(dir, 'node_modules/next/dist/bin/next');++function symlink(target, name, into) {+ const at = path.join(into, 'node_modules', name);+ fs.mkdirSync(path.dirname(at), {recursive: true});+ fs.symlinkSync(target, at, 'junction');+}++/** Copy a package's published files, as a registry install lays them out. */+function install(name, to) {+ const from = path.join(repoRoot, 'packages', name);+ const {files} = JSON.parse(fs.readFileSync(`${from}/package.json`, 'utf8'));+ for (const entry of ['package.json', ...files]) {+ if (!fs.existsSync(path.join(from, entry))) continue;+ fs.cpSync(path.join(from, entry), path.join(to, entry), {+ recursive: true,+ filter: file => !/[\\/]__tests__$|\.test\.tsx?$/.test(file),+ });+ }+}++/** Each package's prebuilt stylesheet, under its `dist`. */+export const PREBUILT = {+ core: 'astryx.css',+ lab: 'lab.css',+ charts: 'charts.css',+ richtext: 'richtext.css',+};++/** The dependencies a package resolves from its own directory. */+const DEPENDENCIES = {+ core: ['intl-messageformat'],+ lab: ['d3-array', 'd3-scale', 'd3-shape'],+ charts: ['d3-array', 'd3-scale', 'd3-shape'],+ richtext: [+ 'lexical',+ ...[+ 'code',+ 'extension',+ 'headless',+ 'html',+ 'link',+ 'list',+ 'markdown',+ 'react',+ 'rich-text',+ 'selection',+ 'table',+ 'utils',+ ].map(name => `@lexical/${name}`),+ ],+};++/**+ * A scratch copy of the fixture app, in `dir`, with Core linked and `packages`+ * installed. It deletes every installed prebuilt package stylesheet, except+ * those of `keepPrebuilt`. A stand-in rule replaces one the copy lacks.+ */+export function scratchApp({+ packages = ['lab', 'charts', 'richtext'],+ keepPrebuilt = [],+} = {}) {+ // Inside the repository (an ignored scratch directory), so Turbopack's+ // workspace root covers the linked package's real path.+ const dir = fs.mkdtempSync(path.join(packageDir, '.astryx-next-turbopack-'));+ const app = path.join(dir, 'app');+ fs.cpSync(path.join(packageDir, '__fixtures__/next-turbopack'), app, {+ recursive: true,+ });+ const dependencies = {+ [packageDir]: ['next', '@babel/core', '@stylexjs/babel-plugin'],+ [repoRoot]: ['react', 'react-dom', 'typescript', '@types/react'],+ };+ dependencies[packageDir].push('@stylexjs/postcss-plugin', '@stylexjs/stylex');+ dependencies[repoRoot].push('@types/node');+ for (const [from, names] of Object.entries(dependencies)) {+ for (const name of names) {+ symlink(+ fs.realpathSync(path.join(from, 'node_modules', name)),+ name,+ app,+ );+ }+ }+ symlink(packageDir, '@astryxdesign/build', app);+ // Core linked from a workspace (`file:`, `pnpm link`, a monorepo package),+ // the others as registry installs: real directories under node_modules.+ const installed = {core: path.join(dir, 'core')};+ for (const name of packages) {+ installed[name] = path.join(app, 'node_modules/@astryxdesign', name);+ }+ for (const [name, to] of Object.entries(installed)) {+ install(name, to);+ for (const dependency of DEPENDENCIES[name]) {+ const from = `${repoRoot}/packages/${name}/node_modules/${dependency}`;+ symlink(fs.realpathSync(from), dependency, to);+ }+ const sheet = path.join(to, 'dist', PREBUILT[name]);+ if (!keepPrebuilt.includes(name)) {+ fs.rmSync(sheet, {force: true});+ } else if (!fs.existsSync(sheet)) {+ fs.mkdirSync(path.dirname(sheet), {recursive: true});+ fs.writeFileSync(sheet, '.x1{color:red}\n');+ }+ }+ symlink(installed.core, '@astryxdesign/core', app);+ return {dir, app, installed};+}++/**+ * The page a just-started `next` server serves at `origin`. It waits out only+ * "not listening yet", up to `timeout`. Its first answer must be the page.+ * Every other outcome fails and names the command.+ */+async function servedPage(origin, child, command, timeout = 300_000) {+ const deadline = Date.now() + timeout;+ for (;;) {+ if (child.exitCode != null || child.signalCode != null) {+ throw new Error(+ `${command} exited (${child.exitCode ?? child.signalCode}) before listening on ${origin}`,+ );+ }+ const response = await fetch(origin).catch(error => {+ if (error.cause?.code === 'ECONNREFUSED') return null;+ throw error;+ });+ if (response != null) {+ if (!response.ok) {+ throw new Error(+ `${command} answered ${origin} with ${response.status}`,+ );+ }+ return response.text();+ }+ if (Date.now() >= deadline) {+ throw new Error(+ `${command} never listened on ${origin} within ${timeout / 1000} s`,+ );+ }+ await new Promise(resolve => setTimeout(resolve, 250));+ }+}++/**+ * Run `next <command>` in `dir` on a free port until `use(origin, page)`+ * settles, `page` being the first page it serves.+ */+export async function serving(dir, command, use) {+ const port = await new Promise(resolve => {+ const server = net.createServer().listen(0, () => {+ const {port: free} = server.address();+ server.close(() => resolve(free));+ });+ });+ const args = [nextBin(dir), command, '-p', String(port)];+ const child = spawn(process.execPath, args, {+ cwd: dir,+ env,+ detached: true,+ stdio: 'ignore',+ });+ try {+ const origin = `http://localhost:${port}`;+ const label = `${[process.execPath, ...args].join(' ')} (in ${dir})`;+ return await use(origin, await servedPage(origin, child, label));+ } finally {+ process.kill(-child.pid, 'SIGKILL');+ }+}diff --git a/packages/build/__fixtures__/next-turbopack/app-loader.cjs b/packages/build/__fixtures__/next-turbopack/app-loader.cjsnew file mode 100644index 0000000000..d361de5e57--- /dev/null+++ b/packages/build/__fixtures__/next-turbopack/app-loader.cjs@@ -0,0 +1,27 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++// Stands in for the app's own loaders. It logs each file it runs on and+// refuses Astryx source. Given the app's StyleX options, it compiles StyleX.++const fs = require('fs');+const babel = require('@babel/core');+const ASTRYX = /[\\/](node_modules[\\/]@astryxdesign|core)[\\/]/;++module.exports = function appLoader(source) {+ const {name, ...stylex} = this.getOptions();+ if (ASTRYX.test(this.resourcePath)) {+ throw new Error(`An app rule reached Astryx source: ${this.resourcePath}`);+ }+ fs.appendFileSync('rules.log', `${name} ${this.resourcePath}\n`);+ if (name !== 'stylex') return source;+ const callback = this.async();+ babel+ .transformAsync(source, {+ filename: this.resourcePath,+ babelrc: false,+ configFile: false,+ parserOpts: {plugins: ['typescript', 'jsx']},+ plugins: [['@stylexjs/babel-plugin', stylex]],+ })+ .then(result => callback(null, result.code), callback);+};diff --git a/packages/build/__fixtures__/next-turbopack/app-stylex.cjs b/packages/build/__fixtures__/next-turbopack/app-stylex.cjsnew file mode 100644index 0000000000..230455bcf6--- /dev/null+++ b/packages/build/__fixtures__/next-turbopack/app-stylex.cjs@@ -0,0 +1,8 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++// The app's own StyleX options, with a class-name prefix of its own.+module.exports = {+ classNamePrefix: 'p',+ runtimeInjection: false,+ unstable_moduleResolution: {type: 'commonJS'},+};diff --git a/packages/build/__fixtures__/next-turbopack/babel.config.js b/packages/build/__fixtures__/next-turbopack/babel.config.jsnew file mode 100644index 0000000000..0dfa493e97--- /dev/null+++ b/packages/build/__fixtures__/next-turbopack/babel.config.js@@ -0,0 +1,6 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++module.exports = {+ presets: ['next/babel'],+ plugins: [['@stylexjs/babel-plugin', require('./app-stylex.cjs')]],+};diff --git a/packages/build/__fixtures__/next-turbopack/next.config.mjs b/packages/build/__fixtures__/next-turbopack/next.config.mjsnew file mode 100644index 0000000000..b28aa01e2a--- /dev/null+++ b/packages/build/__fixtures__/next-turbopack/next.config.mjs@@ -0,0 +1,25 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++// An app with its own StyleX setup three ways. It has a Babel config, a+// `*.tsx` rule list that also matches Astryx source, and StyleX's PostCSS+// plugin.+import {createRequire} from 'node:module';+import {withAstryx} from '@astryxdesign/build/next';++const require = createRequire(import.meta.url);+const loader = require.resolve('./app-loader.cjs');+const stylex = {name: 'stylex', ...require('./app-stylex.cjs')};++// Bare loaders mixed with a rule object, each logging where it runs.+const rules = {+ '*.tsx': [+ {loader, options: {name: 'a'}},+ {loaders: [{loader, options: stylex}], as: '*'},+ {loader, options: {name: 'b'}},+ ],+};++export default withAstryx({+ typescript: {ignoreBuildErrors: true},+ turbopack: {rules},+});diff --git a/packages/build/__fixtures__/next-turbopack/package.json b/packages/build/__fixtures__/next-turbopack/package.jsonnew file mode 100644index 0000000000..9f87f03ee8--- /dev/null+++ b/packages/build/__fixtures__/next-turbopack/package.json@@ -0,0 +1,4 @@+{+ "name": "astryx-next-turbopack-fixture",+ "private": true+}diff --git a/packages/build/__fixtures__/next-turbopack/postcss.config.js b/packages/build/__fixtures__/next-turbopack/postcss.config.jsnew file mode 100644index 0000000000..10b87b42ef--- /dev/null+++ b/packages/build/__fixtures__/next-turbopack/postcss.config.js@@ -0,0 +1,17 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++module.exports = {+ plugins: {+ // Astryx, compiled from the source the app reaches (`@astryx;`).+ '@astryxdesign/build/next/postcss': {},+ // The app's own StyleX (`@stylex;`).+ '@stylexjs/postcss-plugin': {+ include: ['src/**/*.tsx'],+ babelConfig: {+ babelrc: false,+ parserOpts: {plugins: ['typescript', 'jsx']},+ plugins: [['@stylexjs/babel-plugin', require('./app-stylex.cjs')]],+ },+ },+ },+};diff --git a/packages/build/__fixtures__/next-turbopack/src/app/globals.css b/packages/build/__fixtures__/next-turbopack/src/app/globals.cssnew file mode 100644index 0000000000..b34e97b6db--- /dev/null+++ b/packages/build/__fixtures__/next-turbopack/src/app/globals.css@@ -0,0 +1,25 @@+/* Copyright (c) Meta Platforms, Inc. and affiliates. */++/* No layer-order line of the app's own. Core's reset.css and each block that+ `@astryx;` emits register it. */+@import '@astryxdesign/core/reset.css';++@astryx;+@stylex;++/* The product's own classes over a base rule of each package. */+.product-core {+ background-color: rgb(255, 0, 255);+}++.product-lab {+ flex-direction: row;+}++.product-richtext {+ position: static;+}++.product-charts {+ width: 50px;+}diff --git a/packages/build/__fixtures__/next-turbopack/src/app/layout.tsx b/packages/build/__fixtures__/next-turbopack/src/app/layout.tsxnew file mode 100644index 0000000000..fce1ea3b4c--- /dev/null+++ b/packages/build/__fixtures__/next-turbopack/src/app/layout.tsx@@ -0,0 +1,11 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import './globals.css';++export default function RootLayout({children}: {children: React.ReactNode}) {+ return (+ <html lang="en">+ <body>{children}</body>+ </html>+ );+}diff --git a/packages/build/__fixtures__/next-turbopack/src/app/modules.tsx b/packages/build/__fixtures__/next-turbopack/src/app/modules.tsxnew file mode 100644index 0000000000..827e806f41--- /dev/null+++ b/packages/build/__fixtures__/next-turbopack/src/app/modules.tsx@@ -0,0 +1,89 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++// The module packages, built from source beside Core. Per package, it renders+// a base instance, one under the product's StyleX and one under its class+// (globals.css). Each sits in a `data-probe` wrapper.+import * as stylex from '@stylexjs/stylex';+import {Chart, bar} from '@astryxdesign/charts';+import {RichTextView} from '@astryxdesign/richtext';++const styles = stylex.create({+ richtext: {position: 'static'},+ charts: {width: 50},+});++const value = JSON.stringify({+ root: {+ type: 'root',+ version: 1,+ direction: null,+ format: '',+ indent: 0,+ children: [+ {+ type: 'paragraph',+ version: 1,+ direction: null,+ format: '',+ indent: 0,+ children: [+ {+ type: 'text',+ version: 1,+ detail: 0,+ format: 0,+ mode: 'normal',+ style: '',+ text: 'Notes',+ },+ ],+ },+ ],+ },+});++const data = [+ {month: 'Jan', revenue: 3},+ {month: 'Feb', revenue: 5},+];+const series = [bar('revenue', {label: 'Revenue'})];++function Revenue(props: {xstyle?: stylex.StyleXStyles; className?: string}) {+ return (+ <Chart+ data={data}+ xKey="month"+ series={series}+ title="Revenue"+ height={120}+ {...props}+ />+ );+}++export function Modules() {+ return (+ <>+ <div data-probe="richtext-base">+ <RichTextView value={value} />+ </div>+ <div data-probe="richtext-stylex">+ <RichTextView value={value} xstyle={styles.richtext} />+ </div>+ <div data-probe="richtext-class">+ <RichTextView value={value} className="product-richtext" />+ </div>+ <div data-probe="charts-base" style={{width: 300}}>+ <Revenue />+ </div>+ <div data-probe="charts-stylex" style={{width: 300}}>+ <Revenue xstyle={styles.charts} />+ </div>+ <div data-probe="charts-class" style={{width: 300}}>+ <Revenue className="product-charts" />+ </div>+ </>+ );+}diff --git a/packages/build/__fixtures__/next-turbopack/src/app/page.tsx b/packages/build/__fixtures__/next-turbopack/src/app/page.tsxnew file mode 100644index 0000000000..7e4a9c2690--- /dev/null+++ b/packages/build/__fixtures__/next-turbopack/src/app/page.tsx@@ -0,0 +1,41 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import * as stylex from '@stylexjs/stylex';+import {Button, Text} from '@astryxdesign/core';+import {Stat} from '@astryxdesign/lab';+import {Modules} from './modules';++// Per package, a base instance, one under the product's StyleX and one under+// its class (globals.css). Each sits in a `data-probe` wrapper.+const styles = stylex.create({+ card: {padding: 13, borderWidth: 3},+ core: {backgroundColor: 'rgb(255, 0, 255)'},+ lab: {flexDirection: 'row'},+});++export default function Page() {+ return (+ <main id="card" {...stylex.props(styles.card)}>+ <Text>Hello</Text>+ <div data-probe="core-base">+ <Button label="Delete" variant="destructive" />+ </div>+ <div data-probe="core-stylex">+ <Button label="Delete" variant="destructive" xstyle={styles.core} />+ </div>+ <div data-probe="core-class">+ <Button label="Delete" variant="destructive" className="product-core" />+ </div>+ <div data-probe="lab-base">+ <Stat label="Requests" value="1.2M" />+ </div>+ <div data-probe="lab-stylex">+ <Stat label="Requests" value="1.2M" xstyle={styles.lab} />+ </div>+ <div data-probe="lab-class">+ <Stat label="Requests" value="1.2M" className="product-lab" />+ </div>+ <Modules />+ </main>+ );+}diff --git a/packages/build/api-report.md b/packages/build/api-report.mdindex 8ce53df175..04d193f18b 100644--- a/packages/build/api-report.md+++ b/packages/build/api-report.md@@ -27,7 +27,17 @@ module.exports### Functions```text-function withAstryx: (nextConfig?: {}) => { transpilePackages: any[]; webpack: (config: any, context: any) => any }+function withAstryx: (nextConfig?: {}) => { transpilePackages: any[]; turbopack: {} } | { transpilePackages: any[]; webpack: (config: any, context: any) => any }+```++## `./next/postcss`++### Values++```text+module.exports+ (call): (options?: { cwd?: string | undefined } | undefined) => { postcssPlugin: string; Once(root: any, { result }: { result: any }): Promise<void> }+ postcss: boolean```## `./postcss`diff --git a/packages/build/package.json b/packages/build/package.jsonindex 756336e0d9..05b0c1b038 100644--- a/packages/build/package.json+++ b/packages/build/package.json@@ -29,7 +29,8 @@"types": "./dist/vite.d.ts","import": "./dist/vite.mjs"},- "./next": "./src/next.js"+ "./next": "./src/next.js",+ "./next/postcss": "./src/next-postcss.js"},"files": ["src",@@ -68,8 +69,11 @@"lightningcss": "^1.32.0"},"devDependencies": {+ "@stylexjs/postcss-plugin": "catalog:",+ "@stylexjs/stylex": "catalog:","enhanced-resolve": "^5.21.6",- "esbuild": "catalog:"+ "esbuild": "catalog:",+ "next": "16.3.6"},"peerDependenciesMeta": {"@stylexjs/unplugin": {diff --git a/packages/build/scripts/turbopack-speed.mjs b/packages/build/scripts/turbopack-speed.mjsnew file mode 100644index 0000000000..7e9918d605--- /dev/null+++ b/packages/build/scripts/turbopack-speed.mjs@@ -0,0 +1,247 @@+#!/usr/bin/env node+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file turbopack-speed.mjs+ * @input The fixture app (__fixtures__/next-app.mjs) and built Core, Lab,+ * Charts and Rich Text packages (their `dist`, for the prebuilt app).+ * @output The Turbopack speed figures for the fixture app, from source and on+ * the prebuilt stylesheets. Each is the median of `--runs` runs (default 5):+ * `next build`, a `next dev` cold start and a hot update, against the budget.+ * It also counts the files the Astryx loader compiles in one source build.+ * It reports the budget and does not enforce it while the loader route runs.+ * @position Run by hand on every change to @astryxdesign/build:+ * node packages/build/scripts/turbopack-speed.mjs [--runs 5]+ */++import {execFileSync} from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {+ PREBUILT,+ env,+ nextBin,+ packageDir,+ repoRoot,+ scratchApp,+ serving,+} from '../__fixtures__/next-app.mjs';++const runsFlag = process.argv.indexOf('--runs');+const runs = runsFlag > 0 ? Number(process.argv[runsFlag + 1]) : 5;+if (!Number.isInteger(runs) || runs < 1) {+ throw new Error('--runs takes a positive whole number');+}++/** The speed budget: how much slower than the prebuilt app each figure may be. */+const BUDGET = {build: 0.2, cold: 0.15, hot: 0.1};+const LABELS = {+ build: '`next build`',+ cold: '`next dev` cold start',+ hot: 'hot update',+};++const dirs = [];++/** Rewrite a file of a scratch app; the edit must change it. */+function edit(file, transform) {+ const source = fs.readFileSync(file, 'utf8');+ const next = transform(source);+ if (next === source) throw new Error(`nothing to edit in ${file}`);+ fs.writeFileSync(file, next);+}++/** The fixture app as `withAstryx()` builds it, from source. */+function sourceApp() {+ const made = scratchApp();+ dirs.push(made.dir);+ return made.app;+}++/**+ * The same app on the prebuilt stylesheets, with no `withAstryx()` and no+ * `@astryx` plugin. Each package's stylesheet replaces `@astryx;`, and each+ * package resolves to its `dist`.+ */+function prebuiltApp() {+ for (const [name, sheet] of Object.entries(PREBUILT)) {+ for (const file of [`dist/${sheet}`, 'dist/index.js']) {+ if (!fs.existsSync(path.join(repoRoot, 'packages', name, file))) {+ throw new Error(+ `packages/${name}/${file} is missing: build the package first ` ++ `(pnpm -F @astryxdesign/${name} build)`,+ );+ }+ }+ }+ const made = scratchApp({keepPrebuilt: Object.keys(PREBUILT)});+ dirs.push(made.dir);+ edit(path.join(made.app, 'next.config.mjs'), source =>+ source+ .replace("import {withAstryx} from '@astryxdesign/build/next';\n", '')+ .replace('export default withAstryx({', 'export default ({'),+ );+ edit(path.join(made.app, 'postcss.config.js'), source =>+ source.replace(+ /\n\s*\/\/ Astryx, compiled from[^\n]*\n\s*'@astryxdesign\/build\/next\/postcss': \{\},/,+ '',+ ),+ );+ edit(path.join(made.app, 'src/app/globals.css'), source =>+ source.replace(+ '@astryx;',+ Object.entries(PREBUILT)+ .map(([name, sheet]) => `@import '@astryxdesign/${name}/${sheet}';`)+ .join('\n'),+ ),+ );+ return made.app;+}++/**+ * A source app whose `withAstryx()` loader logs each file it compiles, so one+ * build counts the Astryx loader's runs. Kept apart from the timed apps.+ */+function countingApp() {+ const app = sourceApp();+ const log = path.join(app, 'astryx-loader.log');+ const loader = path.join(packageDir, 'src/turbopack-loader.js');+ fs.writeFileSync(+ path.join(app, 'counting-loader.cjs'),+ [+ "const fs = require('fs');",+ `const loader = require(${JSON.stringify(loader)});`,+ 'module.exports = function countingLoader(...args) {',+ ` fs.appendFileSync(${JSON.stringify(log)}, this.resourcePath + '\\n');`,+ ' return loader.apply(this, args);',+ '};',+ '',+ ].join('\n'),+ );+ edit(path.join(app, 'next.config.mjs'), source =>+ source+ .replace('export default withAstryx({', 'const config = withAstryx({')+ .concat(+ [+ "const counting = require.resolve('./counting-loader.cjs');",+ "for (const rule of [config.turbopack.rules['*.{ts,tsx}']].flat()) {",+ ' for (const entry of rule.loaders ?? []) {',+ ' if (entry.loader?.endsWith(`turbopack-loader.js`)) entry.loader = counting;',+ ' }',+ '}',+ 'export default config;',+ '',+ ].join('\n'),+ ),+ );+ return {app, log};+}++function clean(app) {+ fs.rmSync(path.join(app, '.next'), {recursive: true, force: true});+}++function build(app) {+ execFileSync(process.execPath, [nextBin(app), 'build'], {+ cwd: app,+ env,+ stdio: 'ignore',+ });+}++/** `next build` from a clean output directory, in milliseconds. */+function timeBuild(app) {+ clean(app);+ const start = performance.now();+ build(app);+ return performance.now() - start;+}++/** `next dev` from a clean output directory until it serves the page. */+async function timeColdStart(app) {+ clean(app);+ const start = performance.now();+ return serving(app, 'dev', () => performance.now() - start);+}++/** Edits of the page in a running `next dev`, each until it serves the edit. */+async function timeHotUpdates(app) {+ const page = path.join(app, 'src/app/page.tsx');+ const original = fs.readFileSync(page, 'utf8');+ return serving(app, 'dev', async origin => {+ const times = [];+ for (let run = 1; run <= runs; run += 1) {+ const marker = `Hello ${run}`;+ edit(page, () =>+ original.replace('<Text>Hello</Text>', `<Text>${marker}</Text>`),+ );+ const start = performance.now();+ const deadline = start + 120_000;+ while (!(await (await fetch(origin)).text()).includes(marker)) {+ if (performance.now() > deadline) {+ throw new Error(`next dev never served "${marker}" within 120 s`);+ }+ await new Promise(resolve => setTimeout(resolve, 50));+ }+ times.push(performance.now() - start);+ }+ fs.writeFileSync(page, original);+ return times;+ });+}++async function measure(app) {+ const figures = {build: [], cold: [], hot: []};+ for (let run = 1; run <= runs; run += 1) {+ figures.build.push(timeBuild(app));+ figures.cold.push(await timeColdStart(app));+ }+ figures.hot = await timeHotUpdates(app);+ return figures;+}++const median = values => {+ const sorted = [...values].sort((a, b) => a - b);+ const middle = Math.floor(sorted.length / 2);+ return sorted.length % 2+ ? sorted[middle]+ : (sorted[middle - 1] + sorted[middle]) / 2;+};+const seconds = ms => `${(ms / 1000).toFixed(2)} s`;++try {+ const prebuilt = await measure(prebuiltApp());+ const source = await measure(sourceApp());+ const {app, log} = countingApp();+ build(app);+ const compiled = fs.readFileSync(log, 'utf8').trim().split('\n');++ const lines = [+ `Turbopack speed, median of ${runs} runs (spec:AST-080 FR9; reported, not enforced, while the loader route is in use):`,+ '',+ '| Figure | Prebuilt stylesheets | From source | Change | Budget |',+ '| --- | --- | --- | --- | --- |',+ ];+ for (const figure of Object.keys(BUDGET)) {+ const before = median(prebuilt[figure]);+ const after = median(source[figure]);+ const change = (after - before) / before;+ lines.push(+ `| ${LABELS[figure]} | ${seconds(before)} | ${seconds(after)} | ` ++ `${change >= 0 ? '+' : ''}${(change * 100).toFixed(0)}% | ` ++ `+${BUDGET[figure] * 100}% ${change <= BUDGET[figure] ? 'within' : 'over'} |`,+ );+ }+ lines.push(+ '',+ `Astryx loader runs in one source \`next build\`: ${compiled.length} ` ++ `(${new Set(compiled).size} Astryx files).`,+ '',+ `Runs (ms): ${JSON.stringify({prebuilt, source}, (key, value) =>+ typeof value === 'number' ? Math.round(value) : value,+ )}`,+ );+ console.log(lines.join('\n'));+} finally {+ for (const dir of dirs) fs.rmSync(dir, {recursive: true, force: true});+}diff --git a/packages/build/src/index.js b/packages/build/src/index.jsindex fc8f9c2cf2..4484d9b05e 100644--- a/packages/build/src/index.js+++ b/packages/build/src/index.js@@ -178,6 +178,15 @@ function createPlugin() {postcssPlugin: PLUGIN_NAME,plugins: [async function (root, result) {+ if (process.env.TURBOPACK && process.env.ASTRYX_BUILD_TURBOPACK) {+ throw new Error(+ 'withAstryx() under Turbopack cannot run beside @astryxdesign/build/postcss, ' ++ "the webpack setup's PostCSS plugin: its rules never match the classes " ++ 'Turbopack renders, so every Astryx component would be unstyled. Use ' ++ "'@astryxdesign/build/next/postcss' and `@astryx;` (see the " ++ '@astryxdesign/build README), or build with `next build --webpack`.',+ );+ }const fileName = result.opts.from;let styleXAtRule = null;diff --git a/packages/build/src/next-postcss.js b/packages/build/src/next-postcss.jsnew file mode 100644index 0000000000..d53897ed1a--- /dev/null+++ b/packages/build/src/next-postcss.js@@ -0,0 +1,106 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use strict';++/**+ * @astryxdesign/build/next/postcss: for a Next.js app that builds Astryx from+ * source with `withAstryx()` under Turbopack. It replaces an `@astryx;` rule+ * with every rule of the source-built packages, as their prebuilt stylesheets+ * print them. It fails on a source-built package's prebuilt stylesheet, since+ * its rules would load twice, the second copy outside the source build.+ */++const fs = require('fs');+const path = require('path');+const {+ PREBUILT_STYLESHEETS,+ prebuiltStylesheet,+ sourcePackages,+ sourceStylesheet,+} = require('./source-stylesheet');++const PLUGIN_NAME = '@astryxdesign/build/next/postcss';++const PREBUILT_NAMES = new Set(+ Object.values(PREBUILT_STYLESHEETS).map(file => path.basename(file)),+);++/**+ * Fail when `from` is the prebuilt stylesheet of a package the app builds from+ * source. Its rules would load twice. The second copy would sit outside the+ * source build.+ */+function refusePrebuilt(from, cwd) {+ if (!from || !PREBUILT_NAMES.has(path.basename(from))) return;+ const file = fs.realpathSync.native(from);+ for (const pkg of sourcePackages(cwd)) {+ const prebuilt = prebuiltStylesheet(pkg);+ if (+ prebuilt != null &&+ fs.existsSync(prebuilt) &&+ fs.realpathSync.native(prebuilt) === file+ ) {+ throw new Error(+ `[${PLUGIN_NAME}] ${pkg.name} is built from source, so its prebuilt ` ++ `stylesheet ${pkg.name}/${path.basename(prebuilt)} must not load: ` ++ 'remove its import. `@astryx;` emits its rules (see "Next.js ' ++ 'Setup (Turbopack)" in the @astryxdesign/build README).',+ );+ }+ }+}++/**+ * The PostCSS plugin. List it in the app's PostCSS config, and put one+ * `@astryx;` rule in the app's global stylesheet.+ *+ * @param {{cwd?: string}} [options] `cwd` is the app root (default:+ * `process.cwd()`).+ */+function astryxSourcePlugin(options = {}) {+ const {cwd = process.cwd()} = options;+ return {+ postcssPlugin: PLUGIN_NAME,+ async Once(root, {result}) {+ refusePrebuilt(result.opts.from, cwd);+ const markers = [];+ root.walkAtRules('astryx', rule => {+ if (!rule.params) markers.push(rule);+ });+ if (markers.length === 0) {+ return;+ }+ if (markers.length > 1) {+ throw markers[1].error(+ 'Only one @astryx rule is allowed per stylesheet.',+ );+ }+ const {css, packages} = await sourceStylesheet({cwd});+ if (packages.length === 0) {+ throw markers[0].error(+ 'No Astryx package with `source` entries is installed, so there is ' ++ 'nothing to compile. Install @astryxdesign/core, or import ' ++ "'@astryxdesign/core/astryx.css' instead of using @astryx.",+ );+ }+ // The host PostCSS parses the replacement, so this plugin needs no copy+ // of PostCSS of its own.+ if (css) markers[0].replaceWith(css);+ else markers[0].remove();+ // Turbopack caches this stylesheet, persistently by default. The plugin+ // reports each package's source directory as a dependency, so a change+ // there runs it again.+ for (const {srcDir} of packages) {+ result.messages.push({+ type: 'dir-dependency',+ plugin: PLUGIN_NAME,+ parent: result.opts.from,+ dir: fs.realpathSync.native(srcDir),+ glob: '**/*.{ts,tsx}',+ });+ }+ },+ };+}++module.exports = Object.assign(astryxSourcePlugin, {postcss: true});diff --git a/packages/build/src/next.js b/packages/build/src/next.jsindex ddf70d1c92..0245639db5 100644--- a/packages/build/src/next.js+++ b/packages/build/src/next.js@@ -5,7 +5,8 @@/*** @astryxdesign/build/next*- * Next.js configuration helper for Astryx source builds.+ * Next.js configuration helper for Astryx source builds, under webpack or+ * Turbopack.** Usage in next.config.mjs:* import {withAstryx} from '@astryxdesign/build/next';@@ -16,59 +17,19 @@const fs = require('fs');const path = require('path');+const {fileURLToPath} = require('url');+const {+ ASTRYX_PACKAGES,+ SOURCE_PACKAGES,+ findPackageDir,+ sourcePackages,+ stylexOptions,+} = require('./source-stylesheet');const ASTRYX_MODULE = /[\\/]node_modules[\\/]@astryxdesign[\\/]/;const escapeRegExp = text => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');--/**- * Every alias this helper installs lives in `nextConfig.webpack`, and Turbopack- * never calls that hook. So `withAstryx()` under Turbopack reinstates exactly- * the failure the aliases exist to prevent: the app resolves the library- * through `default` to dist, whose runtime class names are disjoint from the- * CSS the PostCSS pass compiles out of source, and the build succeeds with an- * unstyled page and nothing logged.- *- * There is no configuration in which the combination does what the author- * intended, so this refuses rather than warning — an unstyled production deploy- * costs more than a failed build. Next sets `TURBOPACK` for both- * `next dev --turbopack` and `next build --turbopack`, in the parent process- * and in each build worker.- */-function assertWebpack() {- if (!process.env.TURBOPACK) {- return;- }- throw new Error(- 'withAstryx() requires the webpack bundler: it configures resolution ' +- 'through nextConfig.webpack, which Turbopack does not call, so the app ' +- 'would resolve @astryxdesign/* to dist while the CSS is compiled from ' +- 'source and render unstyled.\n' +- 'Run the source build with `next build --webpack` / `next dev --webpack`, ' +- 'or drop withAstryx() and consume the pre-built package instead — import ' +- "'@astryxdesign/core/astryx.css' and skip the babel and PostCSS setup.",- );-}--/**- * Locate an installed package's directory by walking `node_modules` up from- * the app, the way Node resolves a bare specifier. Returns null when the- * package is not installed.- */-function findPackageDir(name, from) {- let dir = path.resolve(from);- for (;;) {- const candidate = path.join(dir, 'node_modules', name);- if (fs.existsSync(path.join(candidate, 'package.json'))) {- return candidate;- }- const parent = path.dirname(dir);- if (parent === dir) {- return null;- }- dir = parent;- }-}+const TURBOPACK_LOADER = require.resolve('./turbopack-loader.js');/*** Match a wildcard alias key such as `@astryxdesign/*` against a request. The@@ -240,23 +201,148 @@ function aliasCoversAstryx(alias, packages) {return Object.keys(alias).some(key => covers(key, false));}+const posix = file => file.split(path.sep).join('/');+const sourceRegExp = tails =>+ new RegExp(`(^|/)(${[...new Set(tails)].map(escapeRegExp).join('|')})/`);++/**+ * How a package's source path ends in the resolved, root-relative paths that+ * Turbopack matches rules against. For a workspace link, the tail starts at the+ * app's closest ancestor that holds the package, such as `packages/core/src`.+ * For an installed package, it is the path in `node_modules`.+ */+function sourceTails(pkg, cwd) {+ const real = fs.realpathSync(pkg.srcDir);+ let base = fs.realpathSync(cwd);+ while (path.relative(base, real).startsWith('..')) base = path.dirname(base);+ return [+ `node_modules/${pkg.name}/${posix(path.relative(pkg.dir, pkg.srcDir))}`,+ posix(path.relative(base, real)),+ ];+}++/**+ * Keep a caller's rule off Astryx source. Turbopack runs every rule whose glob+ * matches. So a caller rule such as `*.tsx` with its own StyleX setup could+ * compile Astryx again, with other class names. Next.js makes each bare loader+ * in a list a rule of its own, run in list order. Wrapping each loader in place+ * keeps that order on the app's files.+ */+function keepOffAstryx(collection, astryxSource) {+ const exclude = rule => ({+ ...rule,+ condition:+ rule.condition == null+ ? {not: astryxSource}+ : {all: [{not: astryxSource}, rule.condition]},+ });+ const isLoader = item => typeof item === 'string' || 'loader' in item;+ return Array.isArray(collection)+ ? collection.map(item => exclude(isLoader(item) ? {loaders: [item]} : item))+ : exclude(collection);+}++const ASTRYX_RULE = '*.{ts,tsx}';+const NEXT_CONFIG = /^next\.config(\.compiled)?\.[cm]?[jt]s$/;++/**+ * The project directory. Webpack's hook receives it as `context.dir`. A+ * Turbopack config receives no such value. Next.js loads the config file from+ * the project directory and keeps the working directory (`next build <dir>`).+ * So the project is that file's directory, found on the call stack. A working+ * directory inside it wins. The app can import a config from an ancestor, and+ * Next.js then runs in the app.+ */+function projectDir() {+ const {prepareStackTrace, stackTraceLimit} = Error;+ Object.assign(Error, {prepareStackTrace: (_, sites) => sites});+ Error.stackTraceLimit = Infinity;+ const sites = new Error().stack;+ Object.assign(Error, {prepareStackTrace, stackTraceLimit});+ const config = sites+ .map(site => site.getFileName() ?? '')+ .map(file => (file.startsWith('file:') ? fileURLToPath(file) : file))+ .find(file => NEXT_CONFIG.test(path.basename(file)));+ const [cwd, dir] = [process.cwd(), config && path.dirname(config)];+ return dir && !`${cwd}${path.sep}`.startsWith(`${dir}${path.sep}`)+ ? dir+ : cwd;+}++/**+ * The Turbopack half. Turbopack never calls `nextConfig.webpack`, so this+ * configures Turbopack directly. `resolveAlias` points each documented entry+ * point at its `source` file, unless the caller aliased it. Turbopack matches+ * alias keys exactly and resolves targets from the project directory. A rule+ * per package compiles its source with the prebuilt stylesheets' StyleX+ * options. Every caller rule stays off that source.+ */+function turbopackConfig(turbopack = {}, cwd) {+ const packages = sourcePackages(cwd);+ if (packages.length === 0) {+ return turbopack;+ }+ const callerAlias = turbopack.resolveAlias || {};+ const claimed = Object.keys(callerAlias)+ .filter(key => key.includes('*'))+ .map(wildcardPattern);+ const resolveAlias = {};+ for (const {entries} of packages) {+ for (const [request, file] of entries) {+ if (request in callerAlias || claimed.some(p => p.test(request))) {+ continue;+ }+ const target = posix(path.relative(cwd, file));+ resolveAlias[request] = target.startsWith('../') ? target : `./${target}`;+ }+ }+ Object.assign(resolveAlias, callerAlias);++ const tails = packages.map(pkg => sourceTails(pkg, cwd));+ const astryxSource = {path: sourceRegExp(tails.flat())};+ const rules = {};+ for (const [glob, collection] of Object.entries(turbopack.rules || {})) {+ rules[glob] = keepOffAstryx(collection, astryxSource);+ }+ rules[ASTRYX_RULE] = [+ ...[rules[ASTRYX_RULE] ?? []].flat(),+ ...packages.map((pkg, i) => ({+ condition: {path: sourceRegExp(tails[i])},+ loaders: [+ {loader: TURBOPACK_LOADER, options: stylexOptions(pkg, packages)},+ ],+ as: '*',+ })),+ ];+ return {...turbopack, resolveAlias, rules};+}+/*** Wraps a Next.js config to enable Astryx source builds.* - Adds transpilePackages for @astryxdesign/* packages- * - Sets conditionNames to resolve source exports+ * - webpack: sets conditionNames and aliases to resolve source exports+ * - Turbopack: see `turbopackConfig()`*/function withAstryx(nextConfig = {}) {- assertWebpack();-- const astryxPackages = [- '@astryxdesign/core',- '@astryxdesign/theme-neutral',- '@astryxdesign/lab',- ];+ const astryxPackages = ASTRYX_PACKAGES;const existingTranspile = nextConfig.transpilePackages || [];const merged = Array.from(new Set([...existingTranspile, ...astryxPackages]));+ // Next sets TURBOPACK whenever it bundles with Turbopack (its default since+ // Next 16) and leaves it unset under `--webpack`.+ if (process.env.TURBOPACK) {+ // The webpack setup's PostCSS plugin reads this and refuses to run.+ process.env.ASTRYX_BUILD_TURBOPACK = '1';+ return {+ ...nextConfig,+ transpilePackages: Array.from(+ new Set([...existingTranspile, ...SOURCE_PACKAGES]),+ ),+ turbopack: turbopackConfig(nextConfig.turbopack, projectDir()),+ };+ }+const existingWebpack = nextConfig.webpack;return {diff --git a/packages/build/src/next.test.mjs b/packages/build/src/next.test.mjsindex 8a7f323910..5f66851ca9 100644--- a/packages/build/src/next.test.mjs+++ b/packages/build/src/next.test.mjs@@ -22,6 +22,7 @@ import {createRequire} from 'node:module';const require = createRequire(import.meta.url);const {withAstryx} = require('./next.js');+const {configSchema} = require('next/dist/server/config-schema');const {ResolverFactory, CachedInputFileSystem} = require('enhanced-resolve');let appDir;@@ -376,36 +377,241 @@ describe('withAstryx', () => {expect(config.marker).toBe(true);expect(config.resolve.alias['@astryxdesign/core$']).toBeDefined();});++ it('transpiles only Core and Lab under webpack: Rich Text and Charts keep their prebuilt stylesheets', () => {+ const {transpilePackages} = withAstryx({transpilePackages: ['other']});+ expect(transpilePackages).toEqual([+ 'other',+ '@astryxdesign/core',+ '@astryxdesign/theme-neutral',+ '@astryxdesign/lab',+ ]);+ });});-describe('withAstryx bundler guard', () => {+describe('withAstryx under Turbopack', () => {+ const ASTRYX_FILE = 'node_modules/@astryxdesign/core/src/Button/Button.tsx';++ beforeEach(() => {+ process.env.TURBOPACK = '1';+ vi.spyOn(process, 'cwd').mockReturnValue(appDir);+ });+afterEach(() => {delete process.env.TURBOPACK;+ delete process.env.ASTRYX_BUILD_TURBOPACK;vi.restoreAllMocks();});- it('refuses to build a config under Turbopack', () => {- process.env.TURBOPACK = '1';- expect(() => withAstryx()).toThrow(/requires the webpack bundler/);+ /** Whether a rule's condition admits a project-relative path. */+ function admits(condition, file) {+ if (condition == null) return true;+ if (condition === 'foreign') return file.includes('node_modules/');+ if (condition.not) return !admits(condition.not, file);+ if (condition.all) return condition.all.every(c => admits(c, file));+ if (condition.path instanceof RegExp) return condition.path.test(file);+ return true;+ }++ it('routes each source entry point through a project-relative alias', () => {+ const {resolveAlias} = withAstryx().turbopack;+ expect(resolveAlias).toEqual({+ '@astryxdesign/core': './node_modules/@astryxdesign/core/src/index.ts',+ '@astryxdesign/core/AlertDialog':+ './node_modules/@astryxdesign/core/src/AlertDialog/index.ts',+ });});- it('names both ways out in the message', () => {- process.env.TURBOPACK = '1';- // The two supported routes: keep the source build and pick webpack, or drop- // the source build entirely and consume the pre-built package.- expect(() => withAstryx()).toThrow(/--webpack/);- expect(() => withAstryx()).toThrow(/astryx\.css/);+ it('lets a caller alias win, exact or wildcard', () => {+ const resolveAlias = {+ '@astryxdesign/core': './mine.ts',+ '@astryxdesign/core/*': './ours/*',+ };+ const config = withAstryx({turbopack: {resolveAlias}});+ expect(config.turbopack.resolveAlias).toEqual(resolveAlias);+ });++ it('compiles Astryx source with the prebuilt stylesheet options', () => {+ const [rule] = withAstryx().turbopack.rules['*.{ts,tsx}'];+ expect(admits(rule.condition, ASTRYX_FILE)).toBe(true);+ expect(admits(rule.condition, 'src/app/page.tsx')).toBe(false);+ expect(rule.as).toBe('*');+ expect(rule.loaders).toHaveLength(1);+ const [{loader, options}] = rule.loaders;+ expect(loader).toBe(require.resolve('./turbopack-loader.js'));+ expect(options).toMatchObject({+ dev: false,+ runtimeInjection: false,+ genConditionalClasses: true,+ treeshakeCompensation: true,+ });+ // StyleX's default `x` prefix, the one the prebuilt stylesheets use.+ expect(options.classNamePrefix).toBeUndefined();+ // Turbopack only passes serializable loader options.+ expect(JSON.parse(JSON.stringify(options))).toEqual(options);+ });++ it('keeps every caller rule off Astryx source, in every rule shape', () => {+ const appLoader = {loader: 'app-babel-loader', options: {prefix: 'p'}};+ const config = withAstryx({+ turbopack: {+ rules: {+ '*.tsx': {loaders: [appLoader], as: '*'},+ '*.ts': {loaders: [appLoader], condition: {not: 'foreign'}},+ '*.mdx': ['a', {loaders: [appLoader]}, {type: 'raw'}, {loader: 'b'}],+ '*.svg': ['@svgr/webpack', 'svgo-loader'],+ '*.{ts,tsx}': {loaders: [appLoader]},+ },+ },+ });+ expect(configSchema.safeParse(config).success).toBe(true);+ const {rules} = config.turbopack;+ // Next.js makes each bare loader a rule of its own, run in list order.+ expect(rules['*.mdx'].map(r => r.loaders?.[0] ?? r.type)).toEqual([+ 'a',+ appLoader,+ 'raw',+ {loader: 'b'},+ ]);+ expect(rules['*.svg'].map(rule => rule.loaders)).toEqual([+ ['@svgr/webpack'],+ ['svgo-loader'],+ ]);+ // A caller rule under the key Astryx uses keeps its place, ahead of ours.+ const [shared, ours] = rules['*.{ts,tsx}'];+ expect(ours.loaders[0].loader).toBe(+ require.resolve('./turbopack-loader.js'),+ );+ const callerRules = [+ shared,+ rules['*.tsx'],+ rules['*.ts'],+ ...rules['*.mdx'],+ ...rules['*.svg'],+ ];+ for (const rule of callerRules) {+ expect(admits(rule.condition, ASTRYX_FILE)).toBe(false);+ expect(admits(rule.condition, 'src/app/page.tsx')).toBe(true);+ }+ expect(rules['*.tsx']).toMatchObject({loaders: [appLoader], as: '*'});+ expect(rules['*.ts'].condition.all).toContainEqual({not: 'foreign'});});- it('refuses before touching the caller config', () => {- process.env.TURBOPACK = '1';- const webpack = vi.fn();- expect(() => withAstryx({webpack})).toThrow();- expect(webpack).not.toHaveBeenCalled();+ it('matches a workspace-linked package where it really lives', () => {+ // Turbopack matches resolved paths, relative to a root that holds both.+ const workspace = fs.realpathSync(+ fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-linked-')),+ );+ const core = path.join(workspace, 'packages/core');+ const web = path.join(workspace, 'apps/web');+ fs.mkdirSync(path.join(core, 'src'), {recursive: true});+ fs.writeFileSync(path.join(core, 'src/index.ts'), '');+ fs.writeFileSync(+ path.join(core, 'package.json'),+ JSON.stringify({exports: {'.': {source: './src/index.ts'}}}),+ );+ fs.mkdirSync(path.join(web, 'node_modules/@astryxdesign'), {+ recursive: true,+ });+ fs.symlinkSync(core, path.join(web, 'node_modules/@astryxdesign/core'));+ process.cwd.mockReturnValue(web);+ try {+ const {rules} = withAstryx({+ turbopack: {rules: {'*.tsx': ['app-loader']}},+ }).turbopack;+ const [astryx] = rules['*.{ts,tsx}'];+ for (const file of [+ 'packages/core/src/A.tsx',+ 'x/packages/core/src/A.tsx',+ ]) {+ expect(admits(astryx.condition, file)).toBe(true);+ expect(admits(rules['*.tsx'][0].condition, file)).toBe(false);+ }+ expect(admits(astryx.condition, 'apps/web/src/page.tsx')).toBe(false);+ } finally {+ fs.rmSync(workspace, {recursive: true, force: true});+ }+ });++ it("makes the webpack setup's PostCSS plugin refuse to run beside it", async () => {+ const [run] = require('./index.js')({cwd: appDir}).plugins;+ const css = () => run({walkAtRules() {}}, {opts: {}});+ // Alone under Turbopack it runs, as on main.+ await expect(css()).resolves.toBeUndefined();+ withAstryx();+ await expect(css()).rejects.toThrow(/next\/postcss/);+ // Under webpack Next.js leaves TURBOPACK unset.+ delete process.env.TURBOPACK;+ await expect(css()).resolves.toBeUndefined();+ });++ it('finds the project from its next.config when run from elsewhere', () => {+ // `next build <dir>` loads <dir>/next.config.js and keeps the caller's cwd.+ process.cwd.mockReturnValue(path.dirname(appDir));+ const config = path.join(appDir, 'next.config.js');+ const helper = JSON.stringify(require.resolve('./next.js'));+ fs.writeFileSync(+ config,+ `module.exports = require(${helper}).withAstryx();`,+ );+ try {+ expect(require(config).turbopack.resolveAlias).toHaveProperty(+ '@astryxdesign/core',+ './node_modules/@astryxdesign/core/src/index.ts',+ );+ } finally {+ fs.rmSync(config);+ }});- it('builds normally when Turbopack is not in play', () => {- expect(() => withAstryx()).not.toThrow();+ it('keeps the working directory when the config it loads sits above it', () => {+ // A config the app imports from an ancestor, such as a shared one in a+ // monorepo. Next.js runs in the app, which holds the packages.+ const workspace = fs.realpathSync(+ fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-shared-')),+ );+ const app = path.join(workspace, 'app');+ fs.cpSync(+ path.join(appDir, 'node_modules'),+ path.join(app, 'node_modules'),+ {+ recursive: true,+ },+ );+ const config = path.join(workspace, 'next.config.js');+ const helper = JSON.stringify(require.resolve('./next.js'));+ fs.writeFileSync(+ config,+ `module.exports = require(${helper}).withAstryx();`,+ );+ process.cwd.mockReturnValue(app);+ try {+ expect(require(config).turbopack.resolveAlias).toHaveProperty(+ '@astryxdesign/core',+ './node_modules/@astryxdesign/core/src/index.ts',+ );+ } finally {+ fs.rmSync(workspace, {recursive: true, force: true});+ }+ });++ it('transpiles every package with a prebuilt stylesheet and installs no webpack hook', () => {+ const config = withAstryx({transpilePackages: ['other']});+ expect(config.transpilePackages).toEqual([+ 'other',+ '@astryxdesign/core',+ '@astryxdesign/theme-neutral',+ '@astryxdesign/lab',+ '@astryxdesign/charts',+ '@astryxdesign/richtext',+ ]);+ expect(config.webpack).toBeUndefined();+ });++ it('leaves the turbopack config alone when no package ships source', () => {+ process.cwd.mockReturnValue(os.tmpdir());+ const turbopack = {rules: {'*.svg': ['@svgr/webpack']}};+ expect(withAstryx({turbopack}).turbopack).toBe(turbopack);});});diff --git a/packages/build/src/next.turbopack.test.mjs b/packages/build/src/next.turbopack.test.mjsnew file mode 100644index 0000000000..edfa6a229a--- /dev/null+++ b/packages/build/src/next.turbopack.test.mjs@@ -0,0 +1,451 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file next.turbopack.test.mjs+ * @input ASTRYX_TURBOPACK_E2E=1, installed Chromium, and+ * __fixtures__/next-turbopack, an app with its own StyleX setup.+ * @output Builds the app from source under Turbopack, with Core linked and+ * Lab, Charts and Rich Text installed. Checks each package's cascade in+ * Chromium, served and under `next dev`.+ * @position The Turbopack check of @astryxdesign/build. `pnpm test:build` runs+ * it, and the default suite skips it.+ */++import {execFileSync} from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {chromium} from 'playwright';+import {afterAll, beforeAll, describe, expect, it} from 'vitest';+import {+ PREBUILT,+ env,+ nextBin,+ scratchApp,+ serving,+} from '../__fixtures__/next-app.mjs';++let root, app, html, css, ruleLog;+/** Scratch folders not yet removed: each goes once its last reader is done. */+const roots = new Set();++/** A scratch fixture app; `unscratch()` removes it once it has been read. */+function scratch(options) {+ const made = scratchApp(options);+ roots.add(made.dir);+ return made;+}++/**+ * Remove a scratch folder inside the budget of the case or hook that read it+ * last. A folder holds thousands of files; Core alone has about 4,600.+ * Removing every folder at once in `afterAll` can pass its time bound on a+ * loaded machine.+ */+function unscratch(dir) {+ fs.rmSync(dir, {recursive: true, force: true});+ roots.delete(dir);+}++/** The page a build rendered, and its stylesheets. */+function built(dir) {+ const page = fs.readFileSync(+ path.join(dir, '.next/server/app/index.html'),+ 'utf8',+ );+ const chunks = path.join(dir, '.next/static/chunks');+ const sheets = fs+ .readdirSync(chunks)+ .filter(file => file.endsWith('.css'))+ .map(file => fs.readFileSync(path.join(chunks, file), 'utf8'));+ return {page, css: sheets.join('\n')};+}++/**+ * The rendered class lists. They hold the stable `astryx-*` hooks and the+ * compiled classes on Astryx elements. Overridden elements also carry the+ * product's own StyleX and class. The app's own element carries the app's+ * classes.+ */+function classLists(page) {+ const lists = [...page.matchAll(/<\w+([^>]*?) class="([^"]*)"/g)].map(+ ([, attrs, classes]) => ({attrs, classes: classes.split(/\s+/)}),+ );+ const isHook = name => name.startsWith('astryx-');+ const onAstryx = lists+ .filter(list => list.classes.some(isHook))+ .flatMap(list => list.classes.filter(name => name && !isHook(name)));+ return {+ hooks: lists.flatMap(list => list.classes.filter(isHook)),+ astryx: onAstryx.filter(name => /^x[a-z0-9]+$/.test(name)),+ product: [...new Set(onAstryx.filter(name => !/^x/.test(name)))],+ app: lists+ .filter(list => list.attrs.includes('id="card"'))+ .flatMap(list => list.classes),+ };+}++/** Astryx and app classes alike render with the classes their rules use. */+function expectStyled(page, stylesheet) {+ const {hooks, astryx, product, app: own} = classLists(page);+ expect(hooks).toEqual(+ expect.arrayContaining(['astryx-button', 'astryx-stat']),+ );+ expect(astryx.length).toBeGreaterThan(20);+ expect(own.length).toBeGreaterThan(0);+ // On the overridden Button and Stat: the product's StyleX and its classes.+ expect(product.filter(name => /^p[a-z0-9]+$/.test(name))).toHaveLength(2);+ expect(product.filter(name => !/^p[a-z0-9]+$/.test(name)).sort()).toEqual([+ 'product-core',+ 'product-lab',+ ]);+ for (const name of own) expect(name).toMatch(/^p[a-z0-9]+$/);+ for (const name of [...astryx, ...product, ...own]) {+ expect(stylesheet, name).toContain(`.${name}`);+ }+}++/**+ * Per package, a property its base rule sets on the probed element. Each entry+ * gives that property's value from the base rule, a theme and the product. The+ * product's StyleX is in page.tsx and modules.tsx, and its classes are in+ * globals.css. Core's property is the destructive Button's `--color-error`.+ */+const PROBES = {+ core: {+ property: 'background-color',+ base: 'rgb(227, 25, 59)',+ theme: 'rgb(0, 120, 255)',+ product: 'rgb(255, 0, 255)',+ },+ lab: {+ property: 'flex-direction',+ base: 'column',+ theme: 'row-reverse',+ product: 'row',+ },+ richtext: {+ property: 'position',+ base: 'relative',+ theme: 'sticky',+ product: 'static',+ },+ charts: {property: 'width', base: '300px', theme: '40px', product: '50px'},+};++// A theme stylesheet registers the layer order itself.+const THEME = [+ '@layer reset, astryx-base, astryx-theme;',+ '@layer astryx-theme {',+ ...Object.entries(PROBES).map(+ ([name, {property, theme}]) =>+ ` [data-probe^="${name}-"] > * { ${property}: ${theme}; }`,+ ),+ '}',+].join('\n');++/**+ * Every probe's value, by its `data-probe` name, once the page's transitions+ * have run. A stylesheet added to a loaded page starts Button's+ * `background-color` transition. A read at once gets the old value.+ */+async function readProbes(tab) {+ await tab.evaluate(() =>+ Promise.all(+ document+ .getAnimations()+ .filter(animation => animation instanceof CSSTransition)+ .map(animation => animation.finished),+ ),+ );+ return tab.$$eval(+ '[data-probe]',+ (wrappers, probes) =>+ Object.fromEntries(+ wrappers.map(wrapper => {+ const {property} = probes[wrapper.dataset.probe.split('-')[0]];+ const style = getComputedStyle(wrapper.firstElementChild);+ return [wrapper.dataset.probe, style.getPropertyValue(property)];+ }),+ ),+ PROBES,+ );+}++/** What each probe reads: the base or, with a theme, the theme's value under+ * the product's class and StyleX rule. */+function expected(themed) {+ return Object.fromEntries(+ Object.entries(PROBES).flatMap(([name, probe]) => [+ [`${name}-base`, themed ? probe.theme : probe.base],+ [`${name}-stylex`, probe.product],+ [`${name}-class`, probe.product],+ ]),+ );+}++/**+ * Replace the page's stylesheet chunks with copies in reverse order. Return the+ * cascade layers that each reversed chunk holds, in the new order.+ */+function reverseChunks() {+ const chunks = [...document.styleSheets].map(sheet => [...sheet.cssRules]);+ for (const node of document.querySelectorAll(+ 'link[rel="stylesheet"], style',+ )) {+ node.remove();+ }+ for (const rules of [...chunks].reverse()) {+ const style = document.createElement('style');+ style.textContent = rules.map(rule => rule.cssText).join('\n');+ document.head.append(style);+ }+ return chunks+ .reverse()+ .map(rules =>+ rules+ .filter(rule => rule instanceof CSSLayerBlockRule)+ .map(rule => rule.name),+ );+}++/**+ * Checks the page served at `origin`, per package. The product's class and+ * StyleX rule beat the base rule. A theme beats the base in either load order.+ * With `reversed`, the same holds with the page's stylesheet chunks reversed.+ */+async function expectCascade(origin, {reversed}) {+ const browser = await chromium.launch();+ try {+ const tab = await browser.newPage();+ const load = () => tab.goto(origin, {waitUntil: 'load'});+ await load();+ // Present first: every probe, each package's three.+ expect(Object.keys(await readProbes(tab)).sort()).toEqual(+ Object.keys(expected(false)).sort(),+ );+ expect(await readProbes(tab)).toEqual(expected(false));+ await tab.addStyleTag({content: THEME});+ expect(await readProbes(tab)).toEqual(expected(true));+ await load();+ await tab.evaluate(theme => {+ const style = document.createElement('style');+ style.textContent = theme;+ document.head.prepend(style);+ }, THEME);+ expect(await readProbes(tab)).toEqual(expected(true));+ if (!reversed) return;+ await load();+ // Present first. Core's reset.css and Astryx's blocks load as separate+ // chunks. One of the two load orders puts the blocks first. There, only+ // each block's own order line keeps the reset below them.+ const layers = await tab.evaluate(reverseChunks);+ const reset = layers.findIndex(chunk => chunk.includes('reset'));+ const base = layers.findIndex(chunk => chunk.includes('astryx-base'));+ expect(reset).toBeGreaterThanOrEqual(0);+ expect(base).toBeGreaterThanOrEqual(0);+ expect(reset).not.toBe(base);+ expect(await readProbes(tab)).toEqual(expected(false));+ await tab.addStyleTag({content: THEME});+ expect(await readProbes(tab)).toEqual(expected(true));+ } finally {+ await browser.close();+ }+}++// Real Next.js builds, servers and Chromium take minutes on every core, so the+// default suite skips them. ASTRYX_TURBOPACK_E2E=1 runs them with Chromium, as+// `pnpm test:build` does on the Build package's CI runner.+describe.runIf(process.env.ASTRYX_TURBOPACK_E2E === '1')(+ 'Turbopack end to end (ASTRYX_TURBOPACK_E2E=1)',+ () => {+ let installed;++ beforeAll(() => {+ ({app, installed} = scratch());+ root = path.dirname(app);+ // From the parent, as `next build <dir>` runs; the servers below run in the app.+ execFileSync(process.execPath, [nextBin(app), 'build', 'app'], {+ cwd: root,+ env,+ });+ ruleLog = fs.readFileSync(path.join(app, 'rules.log'), 'utf8');+ ({page: html, css} = built(app));+ }, 600_000);++ // Only a case that failed, or was filtered out, before removing its+ // folder leaves one here.+ afterAll(() => {+ for (const dir of roots) unscratch(dir);+ });++ describe('withAstryx() under Turbopack', () => {+ it('builds Core linked and Lab, Charts and Rich Text installed, with the prebuilt class names', () => {+ expectStyled(html, css);+ });++ it('builds with every installed prebuilt package stylesheet deleted', () => {+ // Present first: each package is installed with its source entry.+ for (const [name, dir] of Object.entries(installed)) {+ expect(fs.existsSync(path.join(dir, 'src/index.ts')), name).toBe(+ true,+ );+ expect(+ fs.existsSync(path.join(dir, 'dist', PREBUILT[name])),+ name,+ ).toBe(false);+ }+ expect(Object.keys(installed).sort()).toEqual(+ Object.keys(PREBUILT).sort(),+ );+ });++ it("runs the app's mixed rule list in order, on the app's files only", () => {+ // The app loader also throws on Astryx source, failing the build.+ const runs = [...ruleLog.matchAll(/^(\S+) (.*)$/gm)];+ const page = path.join(app, 'src/app/page.tsx');+ const names = runs+ .filter(([, , file]) => file === page)+ .map(run => run[1]);+ expect([...new Set(names)]).toEqual(['a', 'stylex', 'b']);+ expect(runs.every(run => run[2].startsWith(path.dirname(page)))).toBe(+ true,+ );+ });++ it('emits Astryx rules in astryx-base layers, without a priority layer', () => {+ expect(css).toContain('@layer astryx-base');+ expect(css).not.toMatch(/@layer priority|\.astryx[a-z0-9]{5,}/);+ });++ it('keeps the product and a theme over each package base in the built app', async () => {+ await serving(app, 'start', origin =>+ expectCascade(origin, {reversed: true}),+ );+ }, 300_000);++ it('serves the same in next dev', async () => {+ try {+ await serving(app, 'dev', async (origin, page) => {+ const hrefs = [...page.matchAll(/href="([^"]+\.css[^"]*)"/g)];+ const sheets = await Promise.all(+ hrefs.map(async ([, href]) =>+ (await fetch(origin + href)).text(),+ ),+ );+ expectStyled(page, sheets.join('\n'));+ // `next dev` serves Core's reset.css and Astryx's blocks in one+ // stylesheet, and its own rules fix their order. Only the built+ // app's separate chunks can load in reverse.+ await expectCascade(origin, {reversed: false});+ });+ } finally {+ // The app's last reader: the cases above read it, in this order.+ unscratch(root);+ }+ }, 600_000);+ });++ describe("withAstryx() under Turbopack, importing a source-built package's prebuilt stylesheet", () => {+ const reset = "@import '@astryxdesign/core/reset.css';\n";+ const prebuilt = "import '@astryxdesign/core/astryx.css';\n";+ for (const [where, layoutImport, globals] of [+ [+ "from the app's stylesheet",+ '',+ `${reset}@import '@astryxdesign/core/astryx.css';\n@astryx;\n`,+ ],+ ['from a component', prebuilt, `${reset}@astryx;\n`],+ ]) {+ it(`fails the build instead of taking rules from it, imported ${where}`, () => {+ const {dir, app: imports} = scratch({+ packages: [],+ keepPrebuilt: ['core'],+ });+ fs.writeFileSync(+ path.join(imports, 'src/app/page.tsx'),+ "import {Text} from '@astryxdesign/core';\nexport default function Page() {\n return <Text>Hello</Text>;\n}\n",+ );+ const layout = path.join(imports, 'src/app/layout.tsx');+ fs.writeFileSync(+ layout,+ fs+ .readFileSync(layout, 'utf8')+ .replace(+ "import './globals.css';",+ `${layoutImport}import './globals.css';`,+ ),+ );+ fs.writeFileSync(path.join(imports, 'src/app/globals.css'), globals);+ let failure;+ try {+ execFileSync(process.execPath, [nextBin(imports), 'build'], {+ cwd: imports,+ env,+ stdio: 'pipe',+ });+ } catch (error) {+ failure = `${error.stdout}${error.stderr}`;+ } finally {+ unscratch(dir);+ }+ expect(failure).toMatch(+ /@astryxdesign\/core is built from source[\s\S]*astryx\.css/,+ );+ }, 600_000);+ }+ });++ describe('withAstryx() under Turbopack, with Core alone', () => {+ let page, sheet;++ beforeAll(() => {+ const {dir, app: coreOnly} = scratch({packages: []});+ // An app reading a Core data colour as plain CSS, as dist dataVars compile.+ fs.writeFileSync(+ path.join(coreOnly, 'src/app/page.tsx'),+ [+ "import * as stylex from '@stylexjs/stylex';",+ "import {Text} from '@astryxdesign/core';",+ "const styles = stylex.create({swatch: {height: 8, backgroundColor: 'var(--color-data-categorical-blue)'}});",+ 'export default function Page() {',+ ' return <main><Text>Hello</Text><div id="swatch" {...stylex.props(styles.swatch)} /></main>;',+ '}',+ '',+ ].join('\n'),+ );+ try {+ execFileSync(process.execPath, [nextBin(coreOnly), 'build'], {+ cwd: coreOnly,+ env,+ });+ ({page, css: sheet} = built(coreOnly));+ } finally {+ // The cases below read the page and stylesheet from memory.+ unscratch(dir);+ }+ }, 600_000);++ it("declares Core's data-colour defaults, as astryx.css does", () => {+ expect(sheet).toMatch(/--color-data-categorical-blue:/);+ });++ it('colours a swatch that reads one', async () => {+ const body = page.replace(/<link[^>]*>|<script[\s\S]*?<\/script>/g, '');+ const browser = await chromium.launch();+ try {+ const tab = await browser.newPage();+ await tab.setContent(+ body.replace('</head>', `<style>${sheet}</style></head>`),+ );+ expect(+ await tab.$eval('#swatch', swatch =>+ getComputedStyle(swatch).getPropertyValue('background-color'),+ ),+ ).toBe('rgb(1, 113, 227)');+ } finally {+ await browser.close();+ }+ });+ });+ },+);diff --git a/packages/build/src/source-stylesheet.js b/packages/build/src/source-stylesheet.jsnew file mode 100644index 0000000000..ce765fd705--- /dev/null+++ b/packages/build/src/source-stylesheet.js@@ -0,0 +1,424 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use strict';++/**+ * @astryxdesign/build: source stylesheets. A source build of a package's+ * modules prints its prebuilt stylesheet's rules, selectors and order. It+ * prints them in one `@layer astryx-base` after the layer order.+ * `stylexOptions()` holds the options the prebuilt stylesheets use+ * (scripts/build-css.mjs), `packageModules()` the module set, and+ * `renderPackage()` prints it. The bundler compiles the same modules with the+ * same options (turbopack-loader.js), so rendered class names match the rules.+ */++const fs = require('node:fs');+const path = require('node:path');+const {globSync} = require('fast-glob');++// Loaded on first use: next.js reads this file's package helpers on the+// webpack path too, which must not start requiring the compiler.+const babel = () => require('@babel/core');+const stylexBabelPlugin = () => require('@stylexjs/babel-plugin');++/** The packages the webpack setup of withAstryx() transpiles from source.+ * Rich Text and Charts keep their prebuilt stylesheets there. */+const ASTRYX_PACKAGES = [+ '@astryxdesign/core',+ '@astryxdesign/theme-neutral',+ '@astryxdesign/lab',+];++/** The packages a Turbopack source build compiles when they ship `source`+ * entries. They are every package with a prebuilt stylesheet, in the order+ * their blocks print. Theme packages ship none and keep their stylesheet. */+const SOURCE_PACKAGES = [+ ...ASTRYX_PACKAGES,+ '@astryxdesign/charts',+ '@astryxdesign/richtext',+];++const CORE = '@astryxdesign/core';+const STYLEX_MODULE = /\.stylex\.[cm]?[jt]sx?$/;++/**+ * Each package's prebuilt stylesheet export: the file a source build replaces,+ * and never takes a rule from.+ */+const PREBUILT_STYLESHEETS = {+ [CORE]: './astryx.css',+ '@astryxdesign/lab': './lab.css',+ '@astryxdesign/charts': './charts.css',+ '@astryxdesign/richtext': './richtext.css',+};++/**+ * Variable modules a prebuilt stylesheet compiles though none of the package's+ * modules imports them: scripts/build-css.mjs's `stylexEntries`. Core's public+ * `dataVars` entry is one, since an app reads its defaults as plain `var()`+ * references. The parity test, whose reference comes from that script's own+ * targets, fails if this list drifts from it.+ */+const STYLEX_ENTRIES = {[CORE]: ['theme/dataTokens.stylex.ts']};++/**+ * Locate an installed package's directory by walking `node_modules` up from+ * `from`, the way Node resolves a bare specifier. Null when not installed.+ */+function findPackageDir(name, from) {+ let dir = path.resolve(from);+ for (;;) {+ const candidate = path.join(dir, 'node_modules', name);+ if (fs.existsSync(path.join(candidate, 'package.json'))) {+ return candidate;+ }+ const parent = path.dirname(dir);+ if (parent === dir) {+ return null;+ }+ dir = parent;+ }+}++function readManifest(dir) {+ return JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));+}++/**+ * The installed packages a source build compiles, in `SOURCE_PACKAGES`+ * order, each with its exact `source` entries (request → file). A package's+ * source directory is the one its root entry lives in.+ */+function sourcePackages(from) {+ const packages = [];+ for (const name of SOURCE_PACKAGES) {+ const dir = findPackageDir(name, from);+ const exports = dir && readManifest(dir)?.exports;+ if (exports == null || typeof exports !== 'object') {+ continue;+ }+ const entries = new Map();+ for (const [key, value] of Object.entries(exports)) {+ if (typeof value?.source === 'string' && !key.includes('*')) {+ const request = key === '.' ? name : `${name}/${key.slice(2)}`;+ entries.set(request, path.resolve(dir, value.source));+ }+ }+ if (entries.has(name)) {+ packages.push({+ name,+ dir,+ srcDir: path.dirname(entries.get(name)),+ entries,+ });+ }+ }+ return packages;+}++/**+ * The file an installed package's prebuilt stylesheet export names, or null+ * when the package has none.+ */+function prebuiltStylesheet(pkg) {+ const key = PREBUILT_STYLESHEETS[pkg.name];+ const target = key && readManifest(pkg.dir).exports?.[key];+ const file = typeof target === 'string' ? target : target?.default;+ return typeof file === 'string' ? path.resolve(pkg.dir, file) : null;+}++/**+ * The StyleX options the prebuilt stylesheets are compiled with: the default+ * `x` class-name prefix, no development class names and StyleX's default+ * property validation. Plain JSON, since Turbopack passes only serializable+ * loader options: `pluginOptions()` adds the resolution's functions.+ */+function stylexOptions(pkg, packages) {+ const core = packages.find(candidate => candidate.name === CORE);+ return {+ dev: false,+ runtimeInjection: false,+ genConditionalClasses: true,+ treeshakeCompensation: true,+ aliases:+ pkg.name === CORE || core == null+ ? {}+ : {+ '@astryxdesign/core/*': [path.join(core.srcDir, '*')],+ '@astryxdesign/core': [core.srcDir],+ },+ unstable_moduleResolution: {type: 'custom', rootDir: pkg.dir},+ };+}++// Resolution failures that mean an import cannot be found from its importer.+const UNRESOLVED = new Set([+ 'MODULE_NOT_FOUND',+ 'ERR_PACKAGE_PATH_NOT_EXPORTED',+]);++/**+ * StyleX's options for `stylexOptions()`. They resolve `.stylex` imports as the+ * prebuilt build does (scripts/stylex-module-resolution.cjs). A request into a+ * source-built package names its `source` entry or `src/<subpath>`, never the+ * `dist` file Node finds. So a marker, constant or hashed variable keeps the+ * name its own package gives it. Names follow StyleX's rule,+ * `<package name>:<path inside it>`, so Core's names do not change.+ */+function pluginOptions(options) {+ const {rootDir} = options.unstable_moduleResolution;+ let packages;+ const owner = request =>+ (packages ??= sourcePackages(rootDir)).find(({name}) =>+ request.startsWith(`${name}/`),+ );+ const filePathResolver = (request, importer, aliases) => {+ const pkg = !request.startsWith('.') && owner(request);+ if (pkg) {+ const subpath = request.slice(pkg.name.length + 1);+ return (+ pkg.entries.get(request) ?? firstFile([path.join(pkg.srcDir, subpath)])+ );+ }+ const local = resolveStyleXImport(request, importer, aliases);+ if (local != null) return local;+ try {+ return require.resolve(request, {paths: [path.dirname(importer)]});+ } catch (error) {+ // An import the importer cannot resolve reads as "not a theme file", as+ // in StyleX's own resolvers. Any other error, such as a broken+ // package.json, throws.+ if (UNRESOLVED.has(error.code)) return null;+ throw error;+ }+ };+ const getCanonicalFilePath = file => {+ let dir = path.dirname(file);+ while (!fs.existsSync(path.join(dir, 'package.json'))) {+ if (dir === path.parse(dir).root) return path.relative(rootDir, file);+ dir = path.dirname(dir);+ }+ return `${readManifest(dir).name}:${path.relative(dir, file)}`;+ };+ return {+ ...options,+ unstable_moduleResolution: {+ type: 'custom',+ filePathResolver,+ getCanonicalFilePath,+ },+ };+}++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();+ const named = /^\{([^}]*)\}$/.exec(clause);+ const typeOnly =+ /^type(?:\s|\*|\{)/.test(clause) ||+ (named != null &&+ named[1]+ .split(',')+ .map(specifier => specifier.trim())+ .filter(Boolean)+ .every(specifier => /^type\b/.test(specifier)));+ if (!typeOnly) {+ specifiers.push(match[2]);+ }+ }+ return specifiers;+}++const SUFFIXES = ['', '.ts', '.tsx', '.js', '.mjs', '/index.ts', '/index.tsx'];++/** The first file named by a base and a suffix, in order. */+function firstFile(bases, suffixes = SUFFIXES) {+ for (const file of bases.flatMap(base => suffixes.map(s => base + s))) {+ if (fs.statSync(file, {throwIfNoEntry: false})?.isFile()) return file;+ }+ return null;+}++function resolveStyleXImport(specifier, importer, aliases) {+ if (specifier.startsWith('.')) {+ return firstFile([path.resolve(path.dirname(importer), specifier)]);+ }+ for (const [pattern, targets] of Object.entries(aliases)) {+ // A key without `*` matches only itself, as in StyleX's own aliases.+ if (!pattern.includes('*') && specifier !== pattern) continue;+ const [prefix, suffix = ''] = pattern.split('*');+ if (specifier.startsWith(prefix) && specifier.endsWith(suffix)) {+ const matched = specifier.slice(+ prefix.length,+ specifier.length - suffix.length,+ );+ const found = targets+ .map(target => firstFile([target.replace('*', matched)]))+ .find(Boolean);+ if (found) return found;+ }+ }+ return null;+}++/**+ * The modules a package's prebuilt stylesheet is compiled from, walked as+ * scripts/build-css.mjs walks them. That is every source file except tests and+ * `.stylex` modules, plus the package's `STYLEX_ENTRIES`. The walk adds the+ * variable modules they import, minus those a provider's stylesheet already+ * emits. It adds the provided modules the package imports to `imported`. The+ * parity test in source-stylesheet.test.mjs fails if this drifts from+ * scripts/build-css.mjs.+ */+function packageModules(+ pkg,+ packages,+ provided = new Set(),+ imported = new Set(),+) {+ const {aliases} = stylexOptions(pkg, packages);+ const queue = [+ ...globSync('**/*.{ts,tsx}', {+ cwd: pkg.srcDir,+ absolute: true,+ ignore: ['**/*.test.*', '**/*.d.ts', '**/node_modules/**'],+ })+ .map(file => path.normalize(file))+ .filter(file => !STYLEX_MODULE.test(file)),+ // A version older than an entry has none of it to print.+ ...(STYLEX_ENTRIES[pkg.name] ?? [])+ .map(entry => path.join(pkg.srcDir, entry))+ .filter(file => fs.existsSync(file)),+ ].filter(file => !provided.has(file));+ const modules = new Set();+ while (queue.length > 0) {+ const file = queue.shift();+ if (modules.has(file)) continue;+ modules.add(file);+ for (const specifier of staticStyleXImports(+ fs.readFileSync(file, 'utf8'),+ )) {+ const dependency = resolveStyleXImport(specifier, file, aliases);+ if (dependency == null) {+ throw new Error(+ `[@astryxdesign/build] Cannot resolve "${specifier}" from ${file}`,+ );+ }+ if (!provided.has(dependency)) queue.push(dependency);+ else imported.add(dependency);+ }+ }+ return modules;+}++/** A `defineConsts` value, as StyleX collects it: no CSS of its own. */+const isConstant = rule =>+ rule[1]?.constKey != null && rule[1]?.constVal != null;++/**+ * Every rule of a package's prebuilt stylesheet, collected as+ * scripts/build-css.mjs collects them. That is its modules' rules, plus the+ * constants it reads from a provider's modules. Those constants resolve where+ * they are read.+ */+async function packageRules(pkg, packages, provided) {+ const options = stylexOptions(pkg, packages);+ const imported = new Set();+ const modules = packageModules(pkg, packages, provided, imported);+ const rules = [];+ for (const file of modules) {+ rules.push(...(await compileRules(file, options)));+ }+ for (const file of imported) {+ rules.push(...(await compileRules(file, options)).filter(isConstant));+ }+ return {modules, rules};+}++const compiled = new Map();++function stamp(file) {+ const stat = fs.statSync(file);+ return `${stat.mtimeMs}:${stat.size}`;+}++/** One module's StyleX rules, cached on its modification stamp. */+async function compileRules(file, options) {+ const key = `${stamp(file)}:${JSON.stringify(options)}`;+ if (compiled.get(file)?.key === key) {+ return compiled.get(file).rules;+ }+ const code = fs.readFileSync(file, 'utf8');+ let rules = [];+ if (code.includes('@stylexjs/stylex')) {+ const result = await babel().transformAsync(code, {+ filename: file,+ babelrc: false,+ configFile: false,+ code: false,+ parserOpts: {plugins: ['typescript', 'jsx']},+ plugins: [[stylexBabelPlugin(), pluginOptions(options)]],+ });+ rules = result?.metadata?.stylex ?? [];+ }+ compiled.set(file, {key, rules});+ return rules;+}++/**+ * The cascade-layer order every Astryx stylesheet registers before its rules,+ * the line scripts/build-css.mjs writes into each prebuilt stylesheet.+ */+const LAYER_ORDER = '@layer reset, astryx-base, astryx-theme;';++/**+ * Print a package's rules as its prebuilt stylesheet prints them. Print the+ * layer order, then StyleX's output inside one `@layer astryx-base`. Print+ * nothing when there are no rules. Each block carries the order, so the order+ * holds whichever block or chunk loads first. The product needs no line of its+ * own.+ */+function renderPackage(rules) {+ const css = stylexBabelPlugin().processStylexRules(rules, false);+ if (!css.trim()) return '';+ return `${LAYER_ORDER}\n\n@layer astryx-base {\n${css.replace(/^/gm, ' ')}\n}\n`;+}++/**+ * The stylesheet a source build emits. It holds every rule of each+ * source-built package, as its prebuilt stylesheet prints them, one block per+ * package in package order. Another package's block leaves out the Core+ * variable modules that Core's block carries, as prebuilt `lab.css` does.+ */+async function sourceStylesheet({cwd}) {+ const packages = sourcePackages(cwd);+ const blocks = [];+ let provided = new Set();+ for (const pkg of packages) {+ const {modules, rules} = await packageRules(pkg, packages, provided);+ if (pkg.name === CORE) {+ provided = new Set([...modules].filter(file => STYLEX_MODULE.test(file)));+ }+ blocks.push(renderPackage(rules));+ }+ return {css: blocks.filter(Boolean).join('\n'), packages};+}++module.exports = {+ ASTRYX_PACKAGES,+ SOURCE_PACKAGES,+ PREBUILT_STYLESHEETS,+ prebuiltStylesheet,+ findPackageDir,+ sourcePackages,+ stylexOptions,+ pluginOptions,+ packageModules,+ compileRules,+ renderPackage,+ resolveStyleXImport,+ sourceStylesheet,+};diff --git a/packages/build/src/source-stylesheet.test.mjs b/packages/build/src/source-stylesheet.test.mjsnew file mode 100644index 0000000000..d93a33d0ac--- /dev/null+++ b/packages/build/src/source-stylesheet.test.mjs@@ -0,0 +1,342 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file source-stylesheet.test.mjs+ * @input The real Core and Lab source, their prebuilt stylesheets as+ * scripts/build-css.mjs builds them, and a synthetic Astryx-shaped package.+ * @output Proves a source build of every module prints each prebuilt+ * stylesheet byte for byte. Proves the Turbopack loader compiles a component+ * to classes that stylesheet styles. Covers the `@astryx` PostCSS plugin.+ * @position Unit and parity tests for the Turbopack half of @astryxdesign/build+ */++import {afterAll, beforeAll, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {createRequire} from 'node:module';+import {fileURLToPath, pathToFileURL} from 'node:url';++const require = createRequire(import.meta.url);+const {+ compileRules,+ pluginOptions,+ resolveStyleXImport,+ sourcePackages,+ sourceStylesheet,+ stylexOptions,+} = require('./source-stylesheet.js');+const astryxPostcss = require('./next-postcss.js');+const turbopackLoader = require('./turbopack-loader.js');+const {processStylexRules} = require('@stylexjs/babel-plugin');++const repoRoot = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '../../..',+);+const roots = [];++function tempDir() {+ const dir = fs.realpathSync(+ fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-source-')),+ );+ roots.push(dir);+ return dir;+}++function writeFiles(root, files) {+ for (const [file, content] of Object.entries(files)) {+ fs.mkdirSync(path.dirname(path.join(root, file)), {recursive: true});+ fs.writeFileSync(path.join(root, file), content);+ }+}++afterAll(() => {+ for (const dir of roots) fs.rmSync(dir, {recursive: true, force: true});+});++describe('a source build against the prebuilt stylesheets', () => {+ let app;+ let buildCss;++ /** A package's prebuilt stylesheet, built from scripts/build-css.mjs's targets. */+ async function prebuilt(name) {+ const {TARGETS} = buildCss;+ const {provider} = TARGETS[name];+ const rules = await buildCss.collectStyleXCSS({+ ...TARGETS[name],+ provider: provider && TARGETS[provider],+ });+ const sheet = buildCss.composePackageStylesheet(+ '',+ processStylexRules(rules, false),+ );+ // Everything after the banner: the layer order, then the rules.+ return sheet.slice(sheet.indexOf(buildCss.ASTRYX_LAYER_ORDER));+ }++ beforeAll(async () => {+ app = tempDir();+ fs.mkdirSync(path.join(app, 'node_modules/@astryxdesign'), {+ recursive: true,+ });+ for (const name of ['core', 'lab', 'charts', 'richtext']) {+ fs.symlinkSync(+ path.join(repoRoot, 'packages', name),+ path.join(app, 'node_modules/@astryxdesign', name),+ 'junction',+ );+ }+ buildCss = await import(+ pathToFileURL(path.join(repoRoot, 'scripts/build-css.mjs')).href+ );+ });++ it('prints every module of each package as its prebuilt stylesheet prints them: astryx.css, lab.css, charts.css and richtext.css', async () => {+ const {css} = await sourceStylesheet({cwd: app});+ const sheets = [];+ for (const name of ['core', 'lab', 'charts', 'richtext']) {+ sheets.push(await prebuilt(name));+ }+ // Present first. Each package prints rules of its own, after the layer+ // order its block begins with.+ for (const sheet of sheets) {+ expect(sheet).toMatch(+ /^@layer reset, astryx-base, astryx-theme;\n\n@layer astryx-base \{\n\s+\S/,+ );+ }+ expect(css).toBe(sheets.join('\n'));+ }, 360_000);++ it('compiles a component in the Turbopack loader to classes astryx.css styles', async () => {+ const packages = sourcePackages(app);+ const core = packages.find(({name}) => name === '@astryxdesign/core');+ const file = path.join(core.srcDir, 'Button/Button.tsx');+ const code = await new Promise((resolve, reject) => {+ turbopackLoader.call(+ {+ resourcePath: file,+ getOptions: () => stylexOptions(core, packages),+ async: () => (error, result) =>+ error ? reject(error) : resolve(result),+ },+ fs.readFileSync(file, 'utf8'),+ );+ });+ // Each compiled style maps a property key to the classes it applies.+ const classes = [+ ...code.matchAll(/\bk[A-Za-z0-9]{4,}:\s*"([^"]+)"/g),+ ].flatMap(([, names]) => names.split(/\s+/));+ expect(classes.length).toBeGreaterThan(20);+ const astryxCss = fs.readFileSync(+ path.join(repoRoot, 'packages/core/dist/astryx.css'),+ 'utf8',+ );+ for (const name of new Set(classes)) {+ expect(astryxCss, name).toContain(`.${name}`);+ }+ });+});++describe('reading packages and resolving imports', () => {+ it('matches an alias key without a wildcard only exactly', () => {+ const dir = fs.realpathSync(+ fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-alias-')),+ );+ try {+ const index = path.join(dir, 'index.ts');+ fs.writeFileSync(index, '');+ const aliases = {'@astryxdesign/core': [index]};+ const importer = path.join(dir, 'a.ts');+ expect(resolveStyleXImport('@astryxdesign/core', importer, aliases)).toBe(+ index,+ );+ expect(+ resolveStyleXImport('@astryxdesign/core-x/a.stylex', importer, aliases),+ ).toBeNull();+ } finally {+ fs.rmSync(dir, {recursive: true, force: true});+ }+ });++ it('fails on a broken package.json instead of leaving its package out', () => {+ const app = tempDir();+ writeFiles(app, {+ 'src/page.tsx': '',+ 'node_modules/broken/package.json': '{',+ });+ const {filePathResolver} = pluginOptions({+ unstable_moduleResolution: {rootDir: app},+ }).unstable_moduleResolution;+ const importer = path.join(app, 'src/page.tsx');+ // Only an import nothing can resolve reads as unresolved.+ expect(filePathResolver('missing/tokens.stylex', importer, {})).toBeNull();+ expect(() =>+ filePathResolver('broken/tokens.stylex', importer, {}),+ ).toThrow(/Invalid package config/);+ writeFiles(app, {'node_modules/@astryxdesign/core/package.json': '{'});+ expect(() => sourcePackages(app)).toThrow(SyntaxError);+ });+});++describe('the @astryx PostCSS plugin', () => {+ /** Run the plugin over a root holding `count` bare `@astryx` rules. */+ async function run(cwd, count = 1) {+ const result = {opts: {from: path.join(cwd, 'a.css')}, messages: []};+ const rules = Array.from({length: count}, () => ({+ params: '',+ replaceWith(css) {+ this.css = css;+ },+ error: message => new Error(message),+ }));+ const root = {walkAtRules: (_, visit) => rules.forEach(visit)};+ await astryxPostcss({cwd}).Once(root, {result});+ return {css: rules[0].css, messages: result.messages};+ }++ it('replaces @astryx with every compiled rule', async () => {+ const app = tempDir();+ writeFiles(app, {+ 'node_modules/@astryxdesign/core/package.json': JSON.stringify({+ name: '@astryxdesign/core',+ exports: {'.': {source: './src/index.ts'}},+ }),+ 'node_modules/@astryxdesign/core/src/index.ts':+ "import * as stylex from '@stylexjs/stylex';\nconst s = stylex.create({root: {color: 'red'}});\nexport const Box = () => stylex.props(s.root);",+ });+ const {css, messages} = await run(app);+ // The layer order first, so the block keeps it wherever it loads.+ expect(css).toMatch(+ /^@layer reset, astryx-base, astryx-theme;\n\n@layer astryx-base \{\n {2}\.x[a-z0-9]+\{color:red\}/,+ );+ // It depends on the package's source, never on an app file.+ expect(messages).toEqual([+ expect.objectContaining({+ type: 'dir-dependency',+ dir: path.join(app, 'node_modules/@astryxdesign/core/src'),+ glob: '**/*.{ts,tsx}',+ }),+ ]);+ await expect(run(app, 2)).rejects.toThrow(/Only one @astryx/);+ });++ it('fails when no Astryx package ships source', async () => {+ await expect(run(tempDir())).rejects.toThrow(/No Astryx package/);+ });++ it("fails on a source-built package's prebuilt stylesheet instead of taking its rules", async () => {+ const app = tempDir();+ const manifest = (name, exports) => JSON.stringify({name, exports});+ writeFiles(app, {+ 'node_modules/@astryxdesign/core/package.json': manifest(+ '@astryxdesign/core',+ {+ '.': {source: './src/index.ts'},+ './astryx.css': {default: './dist/astryx.css'},+ },+ ),+ 'node_modules/@astryxdesign/core/src/index.ts': 'export {};',+ 'node_modules/@astryxdesign/core/dist/astryx.css': '.x1{color:red}',+ // Installed without `source` entries, so not built from source.+ 'node_modules/@astryxdesign/lab/package.json': manifest(+ '@astryxdesign/lab',+ {'.': './dist/index.js', './lab.css': './dist/lab.css'},+ ),+ 'node_modules/@astryxdesign/lab/dist/lab.css': '.x2{color:blue}',+ });+ const plugin = astryxPostcss({cwd: app});+ const process = from =>+ plugin.Once({walkAtRules() {}}, {result: {opts: {from}, messages: []}});+ await expect(+ process(+ path.join(app, 'node_modules/@astryxdesign/core/dist/astryx.css'),+ ),+ ).rejects.toThrow(+ /@astryxdesign\/core is built from source[\s\S]*@astryxdesign\/core\/astryx\.css/,+ );+ // Present first, then absent: the same check passes other stylesheets.+ await expect(process(path.join(app, 'a.css'))).resolves.toBeUndefined();+ await expect(+ process(path.join(app, 'node_modules/@astryxdesign/lab/dist/lab.css')),+ ).resolves.toBeUndefined();+ });+});++describe('a source build across packages', () => {+ it("names another package's use of a Core marker as Core does, with Core's dist installed", async () => {+ const app = tempDir();+ const core = 'node_modules/@astryxdesign/core';+ const marker =+ "import * as stylex from '@stylexjs/stylex';\nexport const scope = stylex.defineMarker();";+ const hover = from =>+ `import * as stylex from '@stylexjs/stylex';\nimport {scope} from '${from}';\nconst s = stylex.create({root: {color: {default: 'red', [stylex.when.ancestor(':hover', scope)]: 'blue'}}});\nexport const Box = () => stylex.props(s.root);`;+ writeFiles(app, {+ [`${core}/package.json`]: JSON.stringify({+ name: '@astryxdesign/core',+ exports: {+ '.': {source: './src/index.ts', default: './dist/index.js'},+ './scope.stylex': {+ source: './src/scope.stylex.ts',+ default: './dist/scope.stylex.js',+ },+ },+ }),+ [`${core}/src/scope.stylex.ts`]: marker,+ // Published Core ships its build, where Node resolves the request.+ [`${core}/dist/scope.stylex.js`]: marker,+ [`${core}/src/index.ts`]: hover('./scope.stylex'),+ 'node_modules/@astryxdesign/lab/package.json': JSON.stringify({+ name: '@astryxdesign/lab',+ exports: {'.': {source: './src/index.ts'}},+ }),+ 'node_modules/@astryxdesign/lab/src/index.ts': hover(+ '@astryxdesign/core/scope.stylex',+ ),+ });+ const packages = sourcePackages(app);+ const markers = [];+ for (const pkg of packages) {+ const rules = await compileRules(+ path.join(pkg.srcDir, 'index.ts'),+ stylexOptions(pkg, packages),+ );+ markers.push(+ rules.map(([, {ltr}]) => /\.(x\w+):hover/.exec(ltr)?.[1]).find(Boolean),+ );+ }+ // Lab names the marker after Core's source, as scripts/build-css.mjs does.+ expect(markers).toEqual([expect.any(String), markers[0]]);+ });++ it('resolves the constants another package reads from Core, as lab.css does', async () => {+ const app = tempDir();+ const core = 'node_modules/@astryxdesign/core';+ const reads = (from, property) =>+ `import * as stylex from '@stylexjs/stylex';\nimport {motion} from '${from}';\nconst s = stylex.create({root: {${property}: motion.fast}});\nexport const Box = () => stylex.props(s.root);`;+ writeFiles(app, {+ [`${core}/package.json`]: JSON.stringify({+ name: '@astryxdesign/core',+ exports: {+ '.': {source: './src/index.ts'},+ './motion.stylex': {source: './src/motion.stylex.ts'},+ },+ }),+ [`${core}/src/motion.stylex.ts`]:+ "import * as stylex from '@stylexjs/stylex';\nexport const motion = stylex.defineConsts({fast: '120ms'});",+ [`${core}/src/index.ts`]: reads('./motion.stylex', 'transitionDuration'),+ 'node_modules/@astryxdesign/lab/package.json': JSON.stringify({+ name: '@astryxdesign/lab',+ exports: {'.': {source: './src/index.ts'}},+ }),+ 'node_modules/@astryxdesign/lab/src/index.ts': reads(+ '@astryxdesign/core/motion.stylex',+ 'animationDuration',+ ),+ });+ const {css} = await sourceStylesheet({cwd: app});+ // Core's block resolves the constant where Core reads it; Lab's block too.+ expect(css).toMatch(/transition-duration:120ms/);+ expect(css).toMatch(/animation-duration:120ms/);+ });+});diff --git a/packages/build/src/turbopack-loader.js b/packages/build/src/turbopack-loader.jsnew file mode 100644index 0000000000..82fe888304--- /dev/null+++ b/packages/build/src/turbopack-loader.js@@ -0,0 +1,33 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use strict';++/**+ * Turbopack loader for Astryx package source, installed by `withAstryx()`. It+ * compiles each module's StyleX with the prebuilt stylesheets' options+ * (source-stylesheet.js `stylexOptions`). So a component renders the class+ * names that `@astryxdesign/build/next/postcss` emits rules for. Turbopack+ * compiles the TypeScript and JSX.+ */++const babel = require('@babel/core');+const stylexBabelPlugin = require('@stylexjs/babel-plugin');+const {pluginOptions} = require('./source-stylesheet');++module.exports = function astryxTurbopackLoader(source) {+ const callback = this.async();+ if (!source.includes('@stylexjs/stylex')) {+ callback(null, source);+ return;+ }+ babel+ .transformAsync(source, {+ filename: this.resourcePath,+ babelrc: false,+ configFile: false,+ sourceMaps: true,+ parserOpts: {plugins: ['typescript', 'jsx']},+ plugins: [[stylexBabelPlugin, pluginOptions(this.getOptions())]],+ })+ .then(result => callback(null, result.code, result.map), callback);+};diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 33c7540280..4aa0a5d255 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -729,12 +729,21 @@ importers:specifier: 'catalog:'version: 8.1.3(@types/[email protected])([email protected])([email protected])([email protected])([email protected])devDependencies:+ '@stylexjs/postcss-plugin':+ specifier: 'catalog:'+ version: 0.19.0+ '@stylexjs/stylex':+ specifier: 'catalog:'+ version: 0.19.0enhanced-resolve:specifier: ^5.21.6version: 5.21.6esbuild:specifier: '>=0.28.1'version: 0.28.1+ next:+ specifier: 16.3.6+ version: 16.3.6(@babel/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])packages/charts:dependencies:diff --git a/scripts/build-css.mjs b/scripts/build-css.mjsindex 99369aa37b..45102dc824 100644--- a/scripts/build-css.mjs+++ b/scripts/build-css.mjs@@ -37,7 +37,7 @@ const ROOT = path.resolve(__dirname, '..');// Per-package build targets. Each entry defines where source lives, where the// stylesheet is written, and any StyleX module-resolution aliases needed for// cross-package theme-token imports (lab consumes @astryxdesign/core tokens).-const TARGETS = {+export const TARGETS = {core: {src: path.resolve(ROOT, 'packages/core/src'),dist: path.resolve(ROOT, 'packages/core/dist'),