@astryxdesign/build 0.7.6 → 0.7.7-canary.36f8ea1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +54 -29
- package/package.json +7 -3
- package/src/index.js +9 -0
- package/src/next-postcss.js +106 -0
- package/src/next.js +144 -58
- package/src/source-stylesheet.js +424 -0
- package/src/turbopack-loader.js +33 -0
package/README.md
CHANGED
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
# @astryxdesign/build
|
|
2
2
|
|
|
3
|
-
Build plugins for Astryx source builds.
|
|
3
|
+
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:
|
|
4
4
|
|
|
5
5
|
```
|
|
6
6
|
reset < astryx-base (library, astryx prefix) < astryx-theme < product (app, x prefix)
|
|
7
7
|
```
|
|
8
8
|
|
|
9
|
+
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`.
|
|
10
|
+
|
|
9
11
|
## Why?
|
|
10
12
|
|
|
11
13
|
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.
|
|
12
14
|
|
|
13
|
-
`@astryxdesign/build` solves this by:
|
|
15
|
+
In the webpack and Vite setups, `@astryxdesign/build` solves this by:
|
|
14
16
|
|
|
15
17
|
1. Compiling Astryx library code with `astryx` prefix (`.astryx78zum5`)
|
|
16
18
|
2. Compiling product code with default `x` prefix (`.x78zum5`)
|
|
@@ -19,11 +21,13 @@ StyleX generates atomic CSS: same declaration = same class name. Without separat
|
|
|
19
21
|
|
|
20
22
|
## Packages
|
|
21
23
|
|
|
22
|
-
| Export
|
|
23
|
-
|
|
|
24
|
-
| `@astryxdesign/build/babel`
|
|
25
|
-
| `@astryxdesign/build/postcss`
|
|
26
|
-
| `@astryxdesign/build/
|
|
24
|
+
| Export | Purpose | Platform |
|
|
25
|
+
| ---------------------------------- | -------------------------------------------- | ---------------------------- |
|
|
26
|
+
| `@astryxdesign/build/babel` | Babel plugin: splits class prefixes per file | Next.js, any babel pipeline |
|
|
27
|
+
| `@astryxdesign/build/postcss` | PostCSS plugin: compiles + splits CSS layers | Next.js (webpack) |
|
|
28
|
+
| `@astryxdesign/build/next` | `withAstryx()`: the Next.js config helper | Next.js (webpack, Turbopack) |
|
|
29
|
+
| `@astryxdesign/build/next/postcss` | PostCSS plugin: `@astryx;` | Next.js (Turbopack) |
|
|
30
|
+
| `@astryxdesign/build/vite` | Vite plugin: wraps unplugin + splits layers | Vite, Storybook |
|
|
27
31
|
|
|
28
32
|
## Install
|
|
29
33
|
|
|
@@ -39,28 +43,49 @@ npm install -D @stylexjs/unplugin
|
|
|
39
43
|
|
|
40
44
|
---
|
|
41
45
|
|
|
42
|
-
## Next.js Setup
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
46
|
+
## Next.js Setup (Turbopack)
|
|
47
|
+
|
|
48
|
+
Under Turbopack, the default bundler since Next.js 16, `withAstryx()` compiles the
|
|
49
|
+
Astryx modules your app imports from source as the prebuilt stylesheets are compiled,
|
|
50
|
+
and `@astryxdesign/build/next/postcss` emits each source-built package's prebuilt
|
|
51
|
+
stylesheet from that source: the same rules and selectors, in the same order, inside
|
|
52
|
+
`@layer astryx-base`. Installed and workspace-linked packages both work; Astryx needs
|
|
53
|
+
no Babel config.
|
|
54
|
+
|
|
55
|
+
1. `next.config.mjs`, around your config and its own `turbopack.rules`:
|
|
56
|
+
|
|
57
|
+
```js
|
|
58
|
+
import {withAstryx} from '@astryxdesign/build/next';
|
|
59
|
+
export default withAstryx({/* your Next.js config */});
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
2. `postcss.config.js`, beside any plugin your app already uses:
|
|
63
|
+
|
|
64
|
+
```js
|
|
65
|
+
module.exports = {plugins: {'@astryxdesign/build/next/postcss': {}}};
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
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):
|
|
69
|
+
|
|
70
|
+
```css
|
|
71
|
+
@import '@astryxdesign/core/reset.css';
|
|
72
|
+
@import '@astryxdesign/theme-neutral/theme.css';
|
|
73
|
+
|
|
74
|
+
@astryx;
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Each package's rules start with the `reset, astryx-base, astryx-theme` layer
|
|
78
|
+
order, as `reset.css` and the theme do, so the order holds in any chunk order
|
|
79
|
+
without a line of your own.
|
|
80
|
+
|
|
81
|
+
Your own Turbopack rules are kept off Astryx source. Your Babel config file is not,
|
|
82
|
+
and Babel's `ignore` cannot exclude Astryx: to keep it off, set
|
|
83
|
+
`experimental.turbopackUseBuiltinBabel: false` and run `babel-loader` from a
|
|
84
|
+
`turbopack.rules` entry, which `withAstryx()` keeps off Astryx source like any rule.
|
|
85
|
+
|
|
86
|
+
## Next.js Setup (webpack)
|
|
87
|
+
|
|
88
|
+
These steps run under `next dev --webpack` and `next build --webpack`.
|
|
64
89
|
|
|
65
90
|
### 1. babel.config.js
|
|
66
91
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astryxdesign/build",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.7-canary.36f8ea1",
|
|
4
4
|
"description": "Build plugins for Astryx source builds — babel, PostCSS, and Vite integrations",
|
|
5
5
|
"author": "Meta Open Source",
|
|
6
6
|
"license": "MIT",
|
|
@@ -29,7 +29,8 @@
|
|
|
29
29
|
"types": "./dist/vite.d.ts",
|
|
30
30
|
"import": "./dist/vite.mjs"
|
|
31
31
|
},
|
|
32
|
-
"./next": "./src/next.js"
|
|
32
|
+
"./next": "./src/next.js",
|
|
33
|
+
"./next/postcss": "./src/next-postcss.js"
|
|
33
34
|
},
|
|
34
35
|
"files": [
|
|
35
36
|
"src",
|
|
@@ -63,8 +64,11 @@
|
|
|
63
64
|
"lightningcss": "^1.32.0"
|
|
64
65
|
},
|
|
65
66
|
"devDependencies": {
|
|
67
|
+
"@stylexjs/postcss-plugin": "^0.19.0",
|
|
68
|
+
"@stylexjs/stylex": "^0.19.0",
|
|
66
69
|
"enhanced-resolve": "^5.21.6",
|
|
67
|
-
"esbuild": "^0.28.1"
|
|
70
|
+
"esbuild": "^0.28.1",
|
|
71
|
+
"next": "16.3.6"
|
|
68
72
|
},
|
|
69
73
|
"peerDependenciesMeta": {
|
|
70
74
|
"@stylexjs/unplugin": {
|
package/src/index.js
CHANGED
|
@@ -178,6 +178,15 @@ function createPlugin() {
|
|
|
178
178
|
postcssPlugin: PLUGIN_NAME,
|
|
179
179
|
plugins: [
|
|
180
180
|
async function (root, result) {
|
|
181
|
+
if (process.env.TURBOPACK && process.env.ASTRYX_BUILD_TURBOPACK) {
|
|
182
|
+
throw new Error(
|
|
183
|
+
'withAstryx() under Turbopack cannot run beside @astryxdesign/build/postcss, ' +
|
|
184
|
+
"the webpack setup's PostCSS plugin: its rules never match the classes " +
|
|
185
|
+
'Turbopack renders, so every Astryx component would be unstyled. Use ' +
|
|
186
|
+
"'@astryxdesign/build/next/postcss' and `@astryx;` (see the " +
|
|
187
|
+
'@astryxdesign/build README), or build with `next build --webpack`.',
|
|
188
|
+
);
|
|
189
|
+
}
|
|
181
190
|
const fileName = result.opts.from;
|
|
182
191
|
|
|
183
192
|
let styleXAtRule = null;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
2
|
+
|
|
3
|
+
'use strict';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* @astryxdesign/build/next/postcss: for a Next.js app that builds Astryx from
|
|
7
|
+
* source with `withAstryx()` under Turbopack. It replaces an `@astryx;` rule
|
|
8
|
+
* with every rule of the source-built packages, as their prebuilt stylesheets
|
|
9
|
+
* print them. It fails on a source-built package's prebuilt stylesheet, since
|
|
10
|
+
* its rules would load twice, the second copy outside the source build.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const fs = require('fs');
|
|
14
|
+
const path = require('path');
|
|
15
|
+
const {
|
|
16
|
+
PREBUILT_STYLESHEETS,
|
|
17
|
+
prebuiltStylesheet,
|
|
18
|
+
sourcePackages,
|
|
19
|
+
sourceStylesheet,
|
|
20
|
+
} = require('./source-stylesheet');
|
|
21
|
+
|
|
22
|
+
const PLUGIN_NAME = '@astryxdesign/build/next/postcss';
|
|
23
|
+
|
|
24
|
+
const PREBUILT_NAMES = new Set(
|
|
25
|
+
Object.values(PREBUILT_STYLESHEETS).map(file => path.basename(file)),
|
|
26
|
+
);
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Fail when `from` is the prebuilt stylesheet of a package the app builds from
|
|
30
|
+
* source. Its rules would load twice. The second copy would sit outside the
|
|
31
|
+
* source build.
|
|
32
|
+
*/
|
|
33
|
+
function refusePrebuilt(from, cwd) {
|
|
34
|
+
if (!from || !PREBUILT_NAMES.has(path.basename(from))) return;
|
|
35
|
+
const file = fs.realpathSync.native(from);
|
|
36
|
+
for (const pkg of sourcePackages(cwd)) {
|
|
37
|
+
const prebuilt = prebuiltStylesheet(pkg);
|
|
38
|
+
if (
|
|
39
|
+
prebuilt != null &&
|
|
40
|
+
fs.existsSync(prebuilt) &&
|
|
41
|
+
fs.realpathSync.native(prebuilt) === file
|
|
42
|
+
) {
|
|
43
|
+
throw new Error(
|
|
44
|
+
`[${PLUGIN_NAME}] ${pkg.name} is built from source, so its prebuilt ` +
|
|
45
|
+
`stylesheet ${pkg.name}/${path.basename(prebuilt)} must not load: ` +
|
|
46
|
+
'remove its import. `@astryx;` emits its rules (see "Next.js ' +
|
|
47
|
+
'Setup (Turbopack)" in the @astryxdesign/build README).',
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The PostCSS plugin. List it in the app's PostCSS config, and put one
|
|
55
|
+
* `@astryx;` rule in the app's global stylesheet.
|
|
56
|
+
*
|
|
57
|
+
* @param {{cwd?: string}} [options] `cwd` is the app root (default:
|
|
58
|
+
* `process.cwd()`).
|
|
59
|
+
*/
|
|
60
|
+
function astryxSourcePlugin(options = {}) {
|
|
61
|
+
const {cwd = process.cwd()} = options;
|
|
62
|
+
return {
|
|
63
|
+
postcssPlugin: PLUGIN_NAME,
|
|
64
|
+
async Once(root, {result}) {
|
|
65
|
+
refusePrebuilt(result.opts.from, cwd);
|
|
66
|
+
const markers = [];
|
|
67
|
+
root.walkAtRules('astryx', rule => {
|
|
68
|
+
if (!rule.params) markers.push(rule);
|
|
69
|
+
});
|
|
70
|
+
if (markers.length === 0) {
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
if (markers.length > 1) {
|
|
74
|
+
throw markers[1].error(
|
|
75
|
+
'Only one @astryx rule is allowed per stylesheet.',
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
const {css, packages} = await sourceStylesheet({cwd});
|
|
79
|
+
if (packages.length === 0) {
|
|
80
|
+
throw markers[0].error(
|
|
81
|
+
'No Astryx package with `source` entries is installed, so there is ' +
|
|
82
|
+
'nothing to compile. Install @astryxdesign/core, or import ' +
|
|
83
|
+
"'@astryxdesign/core/astryx.css' instead of using @astryx.",
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
// The host PostCSS parses the replacement, so this plugin needs no copy
|
|
87
|
+
// of PostCSS of its own.
|
|
88
|
+
if (css) markers[0].replaceWith(css);
|
|
89
|
+
else markers[0].remove();
|
|
90
|
+
// Turbopack caches this stylesheet, persistently by default. The plugin
|
|
91
|
+
// reports each package's source directory as a dependency, so a change
|
|
92
|
+
// there runs it again.
|
|
93
|
+
for (const {srcDir} of packages) {
|
|
94
|
+
result.messages.push({
|
|
95
|
+
type: 'dir-dependency',
|
|
96
|
+
plugin: PLUGIN_NAME,
|
|
97
|
+
parent: result.opts.from,
|
|
98
|
+
dir: fs.realpathSync.native(srcDir),
|
|
99
|
+
glob: '**/*.{ts,tsx}',
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
module.exports = Object.assign(astryxSourcePlugin, {postcss: true});
|
package/src/next.js
CHANGED
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
/**
|
|
6
6
|
* @astryxdesign/build/next
|
|
7
7
|
*
|
|
8
|
-
* Next.js configuration helper for Astryx source builds
|
|
8
|
+
* Next.js configuration helper for Astryx source builds, under webpack or
|
|
9
|
+
* Turbopack.
|
|
9
10
|
*
|
|
10
11
|
* Usage in next.config.mjs:
|
|
11
12
|
* import {withAstryx} from '@astryxdesign/build/next';
|
|
@@ -16,59 +17,19 @@
|
|
|
16
17
|
|
|
17
18
|
const fs = require('fs');
|
|
18
19
|
const path = require('path');
|
|
20
|
+
const {fileURLToPath} = require('url');
|
|
21
|
+
const {
|
|
22
|
+
ASTRYX_PACKAGES,
|
|
23
|
+
SOURCE_PACKAGES,
|
|
24
|
+
findPackageDir,
|
|
25
|
+
sourcePackages,
|
|
26
|
+
stylexOptions,
|
|
27
|
+
} = require('./source-stylesheet');
|
|
19
28
|
|
|
20
29
|
const ASTRYX_MODULE = /[\\/]node_modules[\\/]@astryxdesign[\\/]/;
|
|
21
30
|
|
|
22
31
|
const escapeRegExp = text => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* Every alias this helper installs lives in `nextConfig.webpack`, and Turbopack
|
|
26
|
-
* never calls that hook. So `withAstryx()` under Turbopack reinstates exactly
|
|
27
|
-
* the failure the aliases exist to prevent: the app resolves the library
|
|
28
|
-
* through `default` to dist, whose runtime class names are disjoint from the
|
|
29
|
-
* CSS the PostCSS pass compiles out of source, and the build succeeds with an
|
|
30
|
-
* unstyled page and nothing logged.
|
|
31
|
-
*
|
|
32
|
-
* There is no configuration in which the combination does what the author
|
|
33
|
-
* intended, so this refuses rather than warning — an unstyled production deploy
|
|
34
|
-
* costs more than a failed build. Next sets `TURBOPACK` for both
|
|
35
|
-
* `next dev --turbopack` and `next build --turbopack`, in the parent process
|
|
36
|
-
* and in each build worker.
|
|
37
|
-
*/
|
|
38
|
-
function assertWebpack() {
|
|
39
|
-
if (!process.env.TURBOPACK) {
|
|
40
|
-
return;
|
|
41
|
-
}
|
|
42
|
-
throw new Error(
|
|
43
|
-
'withAstryx() requires the webpack bundler: it configures resolution ' +
|
|
44
|
-
'through nextConfig.webpack, which Turbopack does not call, so the app ' +
|
|
45
|
-
'would resolve @astryxdesign/* to dist while the CSS is compiled from ' +
|
|
46
|
-
'source and render unstyled.\n' +
|
|
47
|
-
'Run the source build with `next build --webpack` / `next dev --webpack`, ' +
|
|
48
|
-
'or drop withAstryx() and consume the pre-built package instead — import ' +
|
|
49
|
-
"'@astryxdesign/core/astryx.css' and skip the babel and PostCSS setup.",
|
|
50
|
-
);
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* Locate an installed package's directory by walking `node_modules` up from
|
|
55
|
-
* the app, the way Node resolves a bare specifier. Returns null when the
|
|
56
|
-
* package is not installed.
|
|
57
|
-
*/
|
|
58
|
-
function findPackageDir(name, from) {
|
|
59
|
-
let dir = path.resolve(from);
|
|
60
|
-
for (;;) {
|
|
61
|
-
const candidate = path.join(dir, 'node_modules', name);
|
|
62
|
-
if (fs.existsSync(path.join(candidate, 'package.json'))) {
|
|
63
|
-
return candidate;
|
|
64
|
-
}
|
|
65
|
-
const parent = path.dirname(dir);
|
|
66
|
-
if (parent === dir) {
|
|
67
|
-
return null;
|
|
68
|
-
}
|
|
69
|
-
dir = parent;
|
|
70
|
-
}
|
|
71
|
-
}
|
|
32
|
+
const TURBOPACK_LOADER = require.resolve('./turbopack-loader.js');
|
|
72
33
|
|
|
73
34
|
/**
|
|
74
35
|
* Match a wildcard alias key such as `@astryxdesign/*` against a request. The
|
|
@@ -240,23 +201,148 @@ function aliasCoversAstryx(alias, packages) {
|
|
|
240
201
|
return Object.keys(alias).some(key => covers(key, false));
|
|
241
202
|
}
|
|
242
203
|
|
|
204
|
+
const posix = file => file.split(path.sep).join('/');
|
|
205
|
+
const sourceRegExp = tails =>
|
|
206
|
+
new RegExp(`(^|/)(${[...new Set(tails)].map(escapeRegExp).join('|')})/`);
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* How a package's source path ends in the resolved, root-relative paths that
|
|
210
|
+
* Turbopack matches rules against. For a workspace link, the tail starts at the
|
|
211
|
+
* app's closest ancestor that holds the package, such as `packages/core/src`.
|
|
212
|
+
* For an installed package, it is the path in `node_modules`.
|
|
213
|
+
*/
|
|
214
|
+
function sourceTails(pkg, cwd) {
|
|
215
|
+
const real = fs.realpathSync(pkg.srcDir);
|
|
216
|
+
let base = fs.realpathSync(cwd);
|
|
217
|
+
while (path.relative(base, real).startsWith('..')) base = path.dirname(base);
|
|
218
|
+
return [
|
|
219
|
+
`node_modules/${pkg.name}/${posix(path.relative(pkg.dir, pkg.srcDir))}`,
|
|
220
|
+
posix(path.relative(base, real)),
|
|
221
|
+
];
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Keep a caller's rule off Astryx source. Turbopack runs every rule whose glob
|
|
226
|
+
* matches. So a caller rule such as `*.tsx` with its own StyleX setup could
|
|
227
|
+
* compile Astryx again, with other class names. Next.js makes each bare loader
|
|
228
|
+
* in a list a rule of its own, run in list order. Wrapping each loader in place
|
|
229
|
+
* keeps that order on the app's files.
|
|
230
|
+
*/
|
|
231
|
+
function keepOffAstryx(collection, astryxSource) {
|
|
232
|
+
const exclude = rule => ({
|
|
233
|
+
...rule,
|
|
234
|
+
condition:
|
|
235
|
+
rule.condition == null
|
|
236
|
+
? {not: astryxSource}
|
|
237
|
+
: {all: [{not: astryxSource}, rule.condition]},
|
|
238
|
+
});
|
|
239
|
+
const isLoader = item => typeof item === 'string' || 'loader' in item;
|
|
240
|
+
return Array.isArray(collection)
|
|
241
|
+
? collection.map(item => exclude(isLoader(item) ? {loaders: [item]} : item))
|
|
242
|
+
: exclude(collection);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const ASTRYX_RULE = '*.{ts,tsx}';
|
|
246
|
+
const NEXT_CONFIG = /^next\.config(\.compiled)?\.[cm]?[jt]s$/;
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* The project directory. Webpack's hook receives it as `context.dir`. A
|
|
250
|
+
* Turbopack config receives no such value. Next.js loads the config file from
|
|
251
|
+
* the project directory and keeps the working directory (`next build <dir>`).
|
|
252
|
+
* So the project is that file's directory, found on the call stack. A working
|
|
253
|
+
* directory inside it wins. The app can import a config from an ancestor, and
|
|
254
|
+
* Next.js then runs in the app.
|
|
255
|
+
*/
|
|
256
|
+
function projectDir() {
|
|
257
|
+
const {prepareStackTrace, stackTraceLimit} = Error;
|
|
258
|
+
Object.assign(Error, {prepareStackTrace: (_, sites) => sites});
|
|
259
|
+
Error.stackTraceLimit = Infinity;
|
|
260
|
+
const sites = new Error().stack;
|
|
261
|
+
Object.assign(Error, {prepareStackTrace, stackTraceLimit});
|
|
262
|
+
const config = sites
|
|
263
|
+
.map(site => site.getFileName() ?? '')
|
|
264
|
+
.map(file => (file.startsWith('file:') ? fileURLToPath(file) : file))
|
|
265
|
+
.find(file => NEXT_CONFIG.test(path.basename(file)));
|
|
266
|
+
const [cwd, dir] = [process.cwd(), config && path.dirname(config)];
|
|
267
|
+
return dir && !`${cwd}${path.sep}`.startsWith(`${dir}${path.sep}`)
|
|
268
|
+
? dir
|
|
269
|
+
: cwd;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* The Turbopack half. Turbopack never calls `nextConfig.webpack`, so this
|
|
274
|
+
* configures Turbopack directly. `resolveAlias` points each documented entry
|
|
275
|
+
* point at its `source` file, unless the caller aliased it. Turbopack matches
|
|
276
|
+
* alias keys exactly and resolves targets from the project directory. A rule
|
|
277
|
+
* per package compiles its source with the prebuilt stylesheets' StyleX
|
|
278
|
+
* options. Every caller rule stays off that source.
|
|
279
|
+
*/
|
|
280
|
+
function turbopackConfig(turbopack = {}, cwd) {
|
|
281
|
+
const packages = sourcePackages(cwd);
|
|
282
|
+
if (packages.length === 0) {
|
|
283
|
+
return turbopack;
|
|
284
|
+
}
|
|
285
|
+
const callerAlias = turbopack.resolveAlias || {};
|
|
286
|
+
const claimed = Object.keys(callerAlias)
|
|
287
|
+
.filter(key => key.includes('*'))
|
|
288
|
+
.map(wildcardPattern);
|
|
289
|
+
const resolveAlias = {};
|
|
290
|
+
for (const {entries} of packages) {
|
|
291
|
+
for (const [request, file] of entries) {
|
|
292
|
+
if (request in callerAlias || claimed.some(p => p.test(request))) {
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
const target = posix(path.relative(cwd, file));
|
|
296
|
+
resolveAlias[request] = target.startsWith('../') ? target : `./${target}`;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
Object.assign(resolveAlias, callerAlias);
|
|
300
|
+
|
|
301
|
+
const tails = packages.map(pkg => sourceTails(pkg, cwd));
|
|
302
|
+
const astryxSource = {path: sourceRegExp(tails.flat())};
|
|
303
|
+
const rules = {};
|
|
304
|
+
for (const [glob, collection] of Object.entries(turbopack.rules || {})) {
|
|
305
|
+
rules[glob] = keepOffAstryx(collection, astryxSource);
|
|
306
|
+
}
|
|
307
|
+
rules[ASTRYX_RULE] = [
|
|
308
|
+
...[rules[ASTRYX_RULE] ?? []].flat(),
|
|
309
|
+
...packages.map((pkg, i) => ({
|
|
310
|
+
condition: {path: sourceRegExp(tails[i])},
|
|
311
|
+
loaders: [
|
|
312
|
+
{loader: TURBOPACK_LOADER, options: stylexOptions(pkg, packages)},
|
|
313
|
+
],
|
|
314
|
+
as: '*',
|
|
315
|
+
})),
|
|
316
|
+
];
|
|
317
|
+
return {...turbopack, resolveAlias, rules};
|
|
318
|
+
}
|
|
319
|
+
|
|
243
320
|
/**
|
|
244
321
|
* Wraps a Next.js config to enable Astryx source builds.
|
|
245
322
|
* - Adds transpilePackages for @astryxdesign/* packages
|
|
246
|
-
* -
|
|
323
|
+
* - webpack: sets conditionNames and aliases to resolve source exports
|
|
324
|
+
* - Turbopack: see `turbopackConfig()`
|
|
247
325
|
*/
|
|
248
326
|
function withAstryx(nextConfig = {}) {
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
const astryxPackages = [
|
|
252
|
-
'@astryxdesign/core',
|
|
253
|
-
'@astryxdesign/theme-neutral',
|
|
254
|
-
'@astryxdesign/lab',
|
|
255
|
-
];
|
|
327
|
+
const astryxPackages = ASTRYX_PACKAGES;
|
|
256
328
|
|
|
257
329
|
const existingTranspile = nextConfig.transpilePackages || [];
|
|
258
330
|
const merged = Array.from(new Set([...existingTranspile, ...astryxPackages]));
|
|
259
331
|
|
|
332
|
+
// Next sets TURBOPACK whenever it bundles with Turbopack (its default since
|
|
333
|
+
// Next 16) and leaves it unset under `--webpack`.
|
|
334
|
+
if (process.env.TURBOPACK) {
|
|
335
|
+
// The webpack setup's PostCSS plugin reads this and refuses to run.
|
|
336
|
+
process.env.ASTRYX_BUILD_TURBOPACK = '1';
|
|
337
|
+
return {
|
|
338
|
+
...nextConfig,
|
|
339
|
+
transpilePackages: Array.from(
|
|
340
|
+
new Set([...existingTranspile, ...SOURCE_PACKAGES]),
|
|
341
|
+
),
|
|
342
|
+
turbopack: turbopackConfig(nextConfig.turbopack, projectDir()),
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
|
|
260
346
|
const existingWebpack = nextConfig.webpack;
|
|
261
347
|
|
|
262
348
|
return {
|
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
// Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
2
|
+
|
|
3
|
+
'use strict';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* @astryxdesign/build: source stylesheets. A source build of a package's
|
|
7
|
+
* modules prints its prebuilt stylesheet's rules, selectors and order. It
|
|
8
|
+
* prints them in one `@layer astryx-base` after the layer order.
|
|
9
|
+
* `stylexOptions()` holds the options the prebuilt stylesheets use
|
|
10
|
+
* (scripts/build-css.mjs), `packageModules()` the module set, and
|
|
11
|
+
* `renderPackage()` prints it. The bundler compiles the same modules with the
|
|
12
|
+
* same options (turbopack-loader.js), so rendered class names match the rules.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const fs = require('node:fs');
|
|
16
|
+
const path = require('node:path');
|
|
17
|
+
const {globSync} = require('fast-glob');
|
|
18
|
+
|
|
19
|
+
// Loaded on first use: next.js reads this file's package helpers on the
|
|
20
|
+
// webpack path too, which must not start requiring the compiler.
|
|
21
|
+
const babel = () => require('@babel/core');
|
|
22
|
+
const stylexBabelPlugin = () => require('@stylexjs/babel-plugin');
|
|
23
|
+
|
|
24
|
+
/** The packages the webpack setup of withAstryx() transpiles from source.
|
|
25
|
+
* Rich Text and Charts keep their prebuilt stylesheets there. */
|
|
26
|
+
const ASTRYX_PACKAGES = [
|
|
27
|
+
'@astryxdesign/core',
|
|
28
|
+
'@astryxdesign/theme-neutral',
|
|
29
|
+
'@astryxdesign/lab',
|
|
30
|
+
];
|
|
31
|
+
|
|
32
|
+
/** The packages a Turbopack source build compiles when they ship `source`
|
|
33
|
+
* entries. They are every package with a prebuilt stylesheet, in the order
|
|
34
|
+
* their blocks print. Theme packages ship none and keep their stylesheet. */
|
|
35
|
+
const SOURCE_PACKAGES = [
|
|
36
|
+
...ASTRYX_PACKAGES,
|
|
37
|
+
'@astryxdesign/charts',
|
|
38
|
+
'@astryxdesign/richtext',
|
|
39
|
+
];
|
|
40
|
+
|
|
41
|
+
const CORE = '@astryxdesign/core';
|
|
42
|
+
const STYLEX_MODULE = /\.stylex\.[cm]?[jt]sx?$/;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Each package's prebuilt stylesheet export: the file a source build replaces,
|
|
46
|
+
* and never takes a rule from.
|
|
47
|
+
*/
|
|
48
|
+
const PREBUILT_STYLESHEETS = {
|
|
49
|
+
[CORE]: './astryx.css',
|
|
50
|
+
'@astryxdesign/lab': './lab.css',
|
|
51
|
+
'@astryxdesign/charts': './charts.css',
|
|
52
|
+
'@astryxdesign/richtext': './richtext.css',
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Variable modules a prebuilt stylesheet compiles though none of the package's
|
|
57
|
+
* modules imports them: scripts/build-css.mjs's `stylexEntries`. Core's public
|
|
58
|
+
* `dataVars` entry is one, since an app reads its defaults as plain `var()`
|
|
59
|
+
* references. The parity test, whose reference comes from that script's own
|
|
60
|
+
* targets, fails if this list drifts from it.
|
|
61
|
+
*/
|
|
62
|
+
const STYLEX_ENTRIES = {[CORE]: ['theme/dataTokens.stylex.ts']};
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Locate an installed package's directory by walking `node_modules` up from
|
|
66
|
+
* `from`, the way Node resolves a bare specifier. Null when not installed.
|
|
67
|
+
*/
|
|
68
|
+
function findPackageDir(name, from) {
|
|
69
|
+
let dir = path.resolve(from);
|
|
70
|
+
for (;;) {
|
|
71
|
+
const candidate = path.join(dir, 'node_modules', name);
|
|
72
|
+
if (fs.existsSync(path.join(candidate, 'package.json'))) {
|
|
73
|
+
return candidate;
|
|
74
|
+
}
|
|
75
|
+
const parent = path.dirname(dir);
|
|
76
|
+
if (parent === dir) {
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
dir = parent;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function readManifest(dir) {
|
|
84
|
+
return JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The installed packages a source build compiles, in `SOURCE_PACKAGES`
|
|
89
|
+
* order, each with its exact `source` entries (request → file). A package's
|
|
90
|
+
* source directory is the one its root entry lives in.
|
|
91
|
+
*/
|
|
92
|
+
function sourcePackages(from) {
|
|
93
|
+
const packages = [];
|
|
94
|
+
for (const name of SOURCE_PACKAGES) {
|
|
95
|
+
const dir = findPackageDir(name, from);
|
|
96
|
+
const exports = dir && readManifest(dir)?.exports;
|
|
97
|
+
if (exports == null || typeof exports !== 'object') {
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
const entries = new Map();
|
|
101
|
+
for (const [key, value] of Object.entries(exports)) {
|
|
102
|
+
if (typeof value?.source === 'string' && !key.includes('*')) {
|
|
103
|
+
const request = key === '.' ? name : `${name}/${key.slice(2)}`;
|
|
104
|
+
entries.set(request, path.resolve(dir, value.source));
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
if (entries.has(name)) {
|
|
108
|
+
packages.push({
|
|
109
|
+
name,
|
|
110
|
+
dir,
|
|
111
|
+
srcDir: path.dirname(entries.get(name)),
|
|
112
|
+
entries,
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return packages;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* The file an installed package's prebuilt stylesheet export names, or null
|
|
121
|
+
* when the package has none.
|
|
122
|
+
*/
|
|
123
|
+
function prebuiltStylesheet(pkg) {
|
|
124
|
+
const key = PREBUILT_STYLESHEETS[pkg.name];
|
|
125
|
+
const target = key && readManifest(pkg.dir).exports?.[key];
|
|
126
|
+
const file = typeof target === 'string' ? target : target?.default;
|
|
127
|
+
return typeof file === 'string' ? path.resolve(pkg.dir, file) : null;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* The StyleX options the prebuilt stylesheets are compiled with: the default
|
|
132
|
+
* `x` class-name prefix, no development class names and StyleX's default
|
|
133
|
+
* property validation. Plain JSON, since Turbopack passes only serializable
|
|
134
|
+
* loader options: `pluginOptions()` adds the resolution's functions.
|
|
135
|
+
*/
|
|
136
|
+
function stylexOptions(pkg, packages) {
|
|
137
|
+
const core = packages.find(candidate => candidate.name === CORE);
|
|
138
|
+
return {
|
|
139
|
+
dev: false,
|
|
140
|
+
runtimeInjection: false,
|
|
141
|
+
genConditionalClasses: true,
|
|
142
|
+
treeshakeCompensation: true,
|
|
143
|
+
aliases:
|
|
144
|
+
pkg.name === CORE || core == null
|
|
145
|
+
? {}
|
|
146
|
+
: {
|
|
147
|
+
'@astryxdesign/core/*': [path.join(core.srcDir, '*')],
|
|
148
|
+
'@astryxdesign/core': [core.srcDir],
|
|
149
|
+
},
|
|
150
|
+
unstable_moduleResolution: {type: 'custom', rootDir: pkg.dir},
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// Resolution failures that mean an import cannot be found from its importer.
|
|
155
|
+
const UNRESOLVED = new Set([
|
|
156
|
+
'MODULE_NOT_FOUND',
|
|
157
|
+
'ERR_PACKAGE_PATH_NOT_EXPORTED',
|
|
158
|
+
]);
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* StyleX's options for `stylexOptions()`. They resolve `.stylex` imports as the
|
|
162
|
+
* prebuilt build does (scripts/stylex-module-resolution.cjs). A request into a
|
|
163
|
+
* source-built package names its `source` entry or `src/<subpath>`, never the
|
|
164
|
+
* `dist` file Node finds. So a marker, constant or hashed variable keeps the
|
|
165
|
+
* name its own package gives it. Names follow StyleX's rule,
|
|
166
|
+
* `<package name>:<path inside it>`, so Core's names do not change.
|
|
167
|
+
*/
|
|
168
|
+
function pluginOptions(options) {
|
|
169
|
+
const {rootDir} = options.unstable_moduleResolution;
|
|
170
|
+
let packages;
|
|
171
|
+
const owner = request =>
|
|
172
|
+
(packages ??= sourcePackages(rootDir)).find(({name}) =>
|
|
173
|
+
request.startsWith(`${name}/`),
|
|
174
|
+
);
|
|
175
|
+
const filePathResolver = (request, importer, aliases) => {
|
|
176
|
+
const pkg = !request.startsWith('.') && owner(request);
|
|
177
|
+
if (pkg) {
|
|
178
|
+
const subpath = request.slice(pkg.name.length + 1);
|
|
179
|
+
return (
|
|
180
|
+
pkg.entries.get(request) ?? firstFile([path.join(pkg.srcDir, subpath)])
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
const local = resolveStyleXImport(request, importer, aliases);
|
|
184
|
+
if (local != null) return local;
|
|
185
|
+
try {
|
|
186
|
+
return require.resolve(request, {paths: [path.dirname(importer)]});
|
|
187
|
+
} catch (error) {
|
|
188
|
+
// An import the importer cannot resolve reads as "not a theme file", as
|
|
189
|
+
// in StyleX's own resolvers. Any other error, such as a broken
|
|
190
|
+
// package.json, throws.
|
|
191
|
+
if (UNRESOLVED.has(error.code)) return null;
|
|
192
|
+
throw error;
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
const getCanonicalFilePath = file => {
|
|
196
|
+
let dir = path.dirname(file);
|
|
197
|
+
while (!fs.existsSync(path.join(dir, 'package.json'))) {
|
|
198
|
+
if (dir === path.parse(dir).root) return path.relative(rootDir, file);
|
|
199
|
+
dir = path.dirname(dir);
|
|
200
|
+
}
|
|
201
|
+
return `${readManifest(dir).name}:${path.relative(dir, file)}`;
|
|
202
|
+
};
|
|
203
|
+
return {
|
|
204
|
+
...options,
|
|
205
|
+
unstable_moduleResolution: {
|
|
206
|
+
type: 'custom',
|
|
207
|
+
filePathResolver,
|
|
208
|
+
getCanonicalFilePath,
|
|
209
|
+
},
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function staticStyleXImports(source) {
|
|
214
|
+
const specifiers = [];
|
|
215
|
+
const pattern =
|
|
216
|
+
/\b(?:import|export)\s+([^'";]*?\sfrom\s*)?['"]([^'"]+\.stylex)['"]/g;
|
|
217
|
+
for (const match of source.matchAll(pattern)) {
|
|
218
|
+
const clause = (match[1] ?? '').replace(/\s+from\s*$/, '').trim();
|
|
219
|
+
const named = /^\{([^}]*)\}$/.exec(clause);
|
|
220
|
+
const typeOnly =
|
|
221
|
+
/^type(?:\s|\*|\{)/.test(clause) ||
|
|
222
|
+
(named != null &&
|
|
223
|
+
named[1]
|
|
224
|
+
.split(',')
|
|
225
|
+
.map(specifier => specifier.trim())
|
|
226
|
+
.filter(Boolean)
|
|
227
|
+
.every(specifier => /^type\b/.test(specifier)));
|
|
228
|
+
if (!typeOnly) {
|
|
229
|
+
specifiers.push(match[2]);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return specifiers;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const SUFFIXES = ['', '.ts', '.tsx', '.js', '.mjs', '/index.ts', '/index.tsx'];
|
|
236
|
+
|
|
237
|
+
/** The first file named by a base and a suffix, in order. */
|
|
238
|
+
function firstFile(bases, suffixes = SUFFIXES) {
|
|
239
|
+
for (const file of bases.flatMap(base => suffixes.map(s => base + s))) {
|
|
240
|
+
if (fs.statSync(file, {throwIfNoEntry: false})?.isFile()) return file;
|
|
241
|
+
}
|
|
242
|
+
return null;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function resolveStyleXImport(specifier, importer, aliases) {
|
|
246
|
+
if (specifier.startsWith('.')) {
|
|
247
|
+
return firstFile([path.resolve(path.dirname(importer), specifier)]);
|
|
248
|
+
}
|
|
249
|
+
for (const [pattern, targets] of Object.entries(aliases)) {
|
|
250
|
+
// A key without `*` matches only itself, as in StyleX's own aliases.
|
|
251
|
+
if (!pattern.includes('*') && specifier !== pattern) continue;
|
|
252
|
+
const [prefix, suffix = ''] = pattern.split('*');
|
|
253
|
+
if (specifier.startsWith(prefix) && specifier.endsWith(suffix)) {
|
|
254
|
+
const matched = specifier.slice(
|
|
255
|
+
prefix.length,
|
|
256
|
+
specifier.length - suffix.length,
|
|
257
|
+
);
|
|
258
|
+
const found = targets
|
|
259
|
+
.map(target => firstFile([target.replace('*', matched)]))
|
|
260
|
+
.find(Boolean);
|
|
261
|
+
if (found) return found;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
return null;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* The modules a package's prebuilt stylesheet is compiled from, walked as
|
|
269
|
+
* scripts/build-css.mjs walks them. That is every source file except tests and
|
|
270
|
+
* `.stylex` modules, plus the package's `STYLEX_ENTRIES`. The walk adds the
|
|
271
|
+
* variable modules they import, minus those a provider's stylesheet already
|
|
272
|
+
* emits. It adds the provided modules the package imports to `imported`. The
|
|
273
|
+
* parity test in source-stylesheet.test.mjs fails if this drifts from
|
|
274
|
+
* scripts/build-css.mjs.
|
|
275
|
+
*/
|
|
276
|
+
function packageModules(
|
|
277
|
+
pkg,
|
|
278
|
+
packages,
|
|
279
|
+
provided = new Set(),
|
|
280
|
+
imported = new Set(),
|
|
281
|
+
) {
|
|
282
|
+
const {aliases} = stylexOptions(pkg, packages);
|
|
283
|
+
const queue = [
|
|
284
|
+
...globSync('**/*.{ts,tsx}', {
|
|
285
|
+
cwd: pkg.srcDir,
|
|
286
|
+
absolute: true,
|
|
287
|
+
ignore: ['**/*.test.*', '**/*.d.ts', '**/node_modules/**'],
|
|
288
|
+
})
|
|
289
|
+
.map(file => path.normalize(file))
|
|
290
|
+
.filter(file => !STYLEX_MODULE.test(file)),
|
|
291
|
+
// A version older than an entry has none of it to print.
|
|
292
|
+
...(STYLEX_ENTRIES[pkg.name] ?? [])
|
|
293
|
+
.map(entry => path.join(pkg.srcDir, entry))
|
|
294
|
+
.filter(file => fs.existsSync(file)),
|
|
295
|
+
].filter(file => !provided.has(file));
|
|
296
|
+
const modules = new Set();
|
|
297
|
+
while (queue.length > 0) {
|
|
298
|
+
const file = queue.shift();
|
|
299
|
+
if (modules.has(file)) continue;
|
|
300
|
+
modules.add(file);
|
|
301
|
+
for (const specifier of staticStyleXImports(
|
|
302
|
+
fs.readFileSync(file, 'utf8'),
|
|
303
|
+
)) {
|
|
304
|
+
const dependency = resolveStyleXImport(specifier, file, aliases);
|
|
305
|
+
if (dependency == null) {
|
|
306
|
+
throw new Error(
|
|
307
|
+
`[@astryxdesign/build] Cannot resolve "${specifier}" from ${file}`,
|
|
308
|
+
);
|
|
309
|
+
}
|
|
310
|
+
if (!provided.has(dependency)) queue.push(dependency);
|
|
311
|
+
else imported.add(dependency);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return modules;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** A `defineConsts` value, as StyleX collects it: no CSS of its own. */
|
|
318
|
+
const isConstant = rule =>
|
|
319
|
+
rule[1]?.constKey != null && rule[1]?.constVal != null;
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Every rule of a package's prebuilt stylesheet, collected as
|
|
323
|
+
* scripts/build-css.mjs collects them. That is its modules' rules, plus the
|
|
324
|
+
* constants it reads from a provider's modules. Those constants resolve where
|
|
325
|
+
* they are read.
|
|
326
|
+
*/
|
|
327
|
+
async function packageRules(pkg, packages, provided) {
|
|
328
|
+
const options = stylexOptions(pkg, packages);
|
|
329
|
+
const imported = new Set();
|
|
330
|
+
const modules = packageModules(pkg, packages, provided, imported);
|
|
331
|
+
const rules = [];
|
|
332
|
+
for (const file of modules) {
|
|
333
|
+
rules.push(...(await compileRules(file, options)));
|
|
334
|
+
}
|
|
335
|
+
for (const file of imported) {
|
|
336
|
+
rules.push(...(await compileRules(file, options)).filter(isConstant));
|
|
337
|
+
}
|
|
338
|
+
return {modules, rules};
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
const compiled = new Map();
|
|
342
|
+
|
|
343
|
+
function stamp(file) {
|
|
344
|
+
const stat = fs.statSync(file);
|
|
345
|
+
return `${stat.mtimeMs}:${stat.size}`;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** One module's StyleX rules, cached on its modification stamp. */
|
|
349
|
+
async function compileRules(file, options) {
|
|
350
|
+
const key = `${stamp(file)}:${JSON.stringify(options)}`;
|
|
351
|
+
if (compiled.get(file)?.key === key) {
|
|
352
|
+
return compiled.get(file).rules;
|
|
353
|
+
}
|
|
354
|
+
const code = fs.readFileSync(file, 'utf8');
|
|
355
|
+
let rules = [];
|
|
356
|
+
if (code.includes('@stylexjs/stylex')) {
|
|
357
|
+
const result = await babel().transformAsync(code, {
|
|
358
|
+
filename: file,
|
|
359
|
+
babelrc: false,
|
|
360
|
+
configFile: false,
|
|
361
|
+
code: false,
|
|
362
|
+
parserOpts: {plugins: ['typescript', 'jsx']},
|
|
363
|
+
plugins: [[stylexBabelPlugin(), pluginOptions(options)]],
|
|
364
|
+
});
|
|
365
|
+
rules = result?.metadata?.stylex ?? [];
|
|
366
|
+
}
|
|
367
|
+
compiled.set(file, {key, rules});
|
|
368
|
+
return rules;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* The cascade-layer order every Astryx stylesheet registers before its rules,
|
|
373
|
+
* the line scripts/build-css.mjs writes into each prebuilt stylesheet.
|
|
374
|
+
*/
|
|
375
|
+
const LAYER_ORDER = '@layer reset, astryx-base, astryx-theme;';
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* Print a package's rules as its prebuilt stylesheet prints them. Print the
|
|
379
|
+
* layer order, then StyleX's output inside one `@layer astryx-base`. Print
|
|
380
|
+
* nothing when there are no rules. Each block carries the order, so the order
|
|
381
|
+
* holds whichever block or chunk loads first. The product needs no line of its
|
|
382
|
+
* own.
|
|
383
|
+
*/
|
|
384
|
+
function renderPackage(rules) {
|
|
385
|
+
const css = stylexBabelPlugin().processStylexRules(rules, false);
|
|
386
|
+
if (!css.trim()) return '';
|
|
387
|
+
return `${LAYER_ORDER}\n\n@layer astryx-base {\n${css.replace(/^/gm, ' ')}\n}\n`;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* The stylesheet a source build emits. It holds every rule of each
|
|
392
|
+
* source-built package, as its prebuilt stylesheet prints them, one block per
|
|
393
|
+
* package in package order. Another package's block leaves out the Core
|
|
394
|
+
* variable modules that Core's block carries, as prebuilt `lab.css` does.
|
|
395
|
+
*/
|
|
396
|
+
async function sourceStylesheet({cwd}) {
|
|
397
|
+
const packages = sourcePackages(cwd);
|
|
398
|
+
const blocks = [];
|
|
399
|
+
let provided = new Set();
|
|
400
|
+
for (const pkg of packages) {
|
|
401
|
+
const {modules, rules} = await packageRules(pkg, packages, provided);
|
|
402
|
+
if (pkg.name === CORE) {
|
|
403
|
+
provided = new Set([...modules].filter(file => STYLEX_MODULE.test(file)));
|
|
404
|
+
}
|
|
405
|
+
blocks.push(renderPackage(rules));
|
|
406
|
+
}
|
|
407
|
+
return {css: blocks.filter(Boolean).join('\n'), packages};
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
module.exports = {
|
|
411
|
+
ASTRYX_PACKAGES,
|
|
412
|
+
SOURCE_PACKAGES,
|
|
413
|
+
PREBUILT_STYLESHEETS,
|
|
414
|
+
prebuiltStylesheet,
|
|
415
|
+
findPackageDir,
|
|
416
|
+
sourcePackages,
|
|
417
|
+
stylexOptions,
|
|
418
|
+
pluginOptions,
|
|
419
|
+
packageModules,
|
|
420
|
+
compileRules,
|
|
421
|
+
renderPackage,
|
|
422
|
+
resolveStyleXImport,
|
|
423
|
+
sourceStylesheet,
|
|
424
|
+
};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
2
|
+
|
|
3
|
+
'use strict';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Turbopack loader for Astryx package source, installed by `withAstryx()`. It
|
|
7
|
+
* compiles each module's StyleX with the prebuilt stylesheets' options
|
|
8
|
+
* (source-stylesheet.js `stylexOptions`). So a component renders the class
|
|
9
|
+
* names that `@astryxdesign/build/next/postcss` emits rules for. Turbopack
|
|
10
|
+
* compiles the TypeScript and JSX.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const babel = require('@babel/core');
|
|
14
|
+
const stylexBabelPlugin = require('@stylexjs/babel-plugin');
|
|
15
|
+
const {pluginOptions} = require('./source-stylesheet');
|
|
16
|
+
|
|
17
|
+
module.exports = function astryxTurbopackLoader(source) {
|
|
18
|
+
const callback = this.async();
|
|
19
|
+
if (!source.includes('@stylexjs/stylex')) {
|
|
20
|
+
callback(null, source);
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
babel
|
|
24
|
+
.transformAsync(source, {
|
|
25
|
+
filename: this.resourcePath,
|
|
26
|
+
babelrc: false,
|
|
27
|
+
configFile: false,
|
|
28
|
+
sourceMaps: true,
|
|
29
|
+
parserOpts: {plugins: ['typescript', 'jsx']},
|
|
30
|
+
plugins: [[stylexBabelPlugin, pluginOptions(this.getOptions())]],
|
|
31
|
+
})
|
|
32
|
+
.then(result => callback(null, result.code, result.map), callback);
|
|
33
|
+
};
|