@wordpress/theme-build-tools 0.0.0-stage → 1.0.0
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/LICENSE.md +788 -0
- package/README.md +133 -2
- package/build-types/esbuild-plugins/esbuild-ds-token-fallbacks.d.mts +12 -0
- package/build-types/js-plugins/transform-ds-token-fallbacks.d.mts +14 -0
- package/build-types/lib/theme-tokens.d.mts +28 -0
- package/build-types/lightningcss-plugins/lightningcss-ds-token-fallbacks.d.mts +13 -0
- package/build-types/postcss-plugins/add-fallback-to-var.d.mts +38 -0
- package/build-types/postcss-plugins/ds-token-fallbacks.d.mts +41 -0
- package/build-types/postcss-plugins/postcss-ds-token-fallbacks.d.mts +4 -0
- package/build-types/stylelint-plugins/no-setting-wpds-custom-properties.d.mts +5 -0
- package/build-types/stylelint-plugins/no-token-fallback-values.d.mts +5 -0
- package/build-types/stylelint-plugins/no-unknown-ds-tokens.d.mts +5 -0
- package/build-types/vite-plugins/vite-ds-token-fallbacks.d.mts +12 -0
- package/esbuild-plugins/esbuild-ds-token-fallbacks.mjs +130 -0
- package/js-plugins/transform-ds-token-fallbacks.mjs +211 -0
- package/lib/theme-tokens.mjs +58 -0
- package/lightningcss-plugins/lightningcss-ds-token-fallbacks.mjs +89 -0
- package/package.json +125 -5
- package/postcss-plugins/add-fallback-to-var.mjs +65 -0
- package/postcss-plugins/ds-token-fallbacks.mjs +53 -0
- package/postcss-plugins/postcss-ds-token-fallbacks.mjs +17 -0
- package/stylelint-plugins/no-setting-wpds-custom-properties.mjs +45 -0
- package/stylelint-plugins/no-token-fallback-values.mjs +55 -0
- package/stylelint-plugins/no-unknown-ds-tokens.mjs +102 -0
- package/vite-plugins/vite-ds-token-fallbacks.mjs +33 -0
package/README.md
CHANGED
|
@@ -1,3 +1,134 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Theme Build Tools
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Build plugins and Stylelint plugins for the WordPress Design System design tokens provided by [`@wordpress/theme`](https://github.com/WordPress/gutenberg/tree/HEAD/packages/theme/README.md).
|
|
4
|
+
|
|
5
|
+
- The [Stylelint plugins](#stylelint-plugins) validate `--wpds-*` design token usage in CSS.
|
|
6
|
+
- The [build plugins](#build-plugins) inject the generated fallback values into `var(--wpds-*)` references, for PostCSS, Lightning CSS, esbuild, and Vite.
|
|
7
|
+
|
|
8
|
+
The token names and fallback values come from the `@wordpress/theme` package, which is an optional peer dependency, so they match the design tokens stylesheet of the version you installed. If `@wordpress/theme` is not installed, the plugins do nothing: the build plugins leave `var(--wpds-*)` references unchanged, and `no-unknown-ds-tokens` reports nothing.
|
|
9
|
+
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm install @wordpress/theme-build-tools @wordpress/theme --save-dev
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Install the tool you use the plugins with (`stylelint`, `postcss`, `lightningcss`, `esbuild`, or `vite`) as well; they are optional peer dependencies.
|
|
17
|
+
|
|
18
|
+
The package's entrypoints are ESM-only and require Node.js `>=22.13.0`. Use `import` syntax from ESM or TypeScript configuration files.
|
|
19
|
+
|
|
20
|
+
## Stylelint Plugins
|
|
21
|
+
|
|
22
|
+
These rules validate design token usage in CSS. Enable them in your Stylelint configuration:
|
|
23
|
+
|
|
24
|
+
```json
|
|
25
|
+
{
|
|
26
|
+
"plugins": [
|
|
27
|
+
"@wordpress/theme-build-tools/stylelint-plugins/no-unknown-ds-tokens",
|
|
28
|
+
"@wordpress/theme-build-tools/stylelint-plugins/no-setting-wpds-custom-properties",
|
|
29
|
+
"@wordpress/theme-build-tools/stylelint-plugins/no-token-fallback-values"
|
|
30
|
+
],
|
|
31
|
+
"rules": {
|
|
32
|
+
"plugin-wpds/no-unknown-ds-tokens": true,
|
|
33
|
+
"plugin-wpds/no-setting-wpds-custom-properties": true,
|
|
34
|
+
"plugin-wpds/no-token-fallback-values": true
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### `plugin-wpds/no-unknown-ds-tokens`
|
|
40
|
+
|
|
41
|
+
Reports references to unknown `--wpds-*` tokens.
|
|
42
|
+
|
|
43
|
+
### `plugin-wpds/no-setting-wpds-custom-properties`
|
|
44
|
+
|
|
45
|
+
Reports definitions or overrides in the `--wpds-*` namespace.
|
|
46
|
+
|
|
47
|
+
### `plugin-wpds/no-token-fallback-values`
|
|
48
|
+
|
|
49
|
+
Reports manual fallbacks that can drift from the generated values.
|
|
50
|
+
|
|
51
|
+
## Build Plugins
|
|
52
|
+
|
|
53
|
+
The build plugins inject generated fallbacks into bare `var(--wpds-*)` references so components still render when the design tokens stylesheet is unavailable. For example, `var(--wpds-color-foreground-content-neutral)` becomes `var(--wpds-color-foreground-content-neutral, #1e1e1e)`.
|
|
54
|
+
|
|
55
|
+
`@wordpress/build` already applies these plugins automatically. You only need to configure them manually for custom build setups.
|
|
56
|
+
|
|
57
|
+
| Export | Tool | Scope |
|
|
58
|
+
| ----------------------------------------------------------------------- | ------------- | ----- |
|
|
59
|
+
| `@wordpress/theme-build-tools/postcss-plugins/postcss-ds-token-fallbacks` | PostCSS | CSS |
|
|
60
|
+
| `@wordpress/theme-build-tools/lightningcss-plugins/lightningcss-ds-token-fallbacks` | Lightning CSS | CSS |
|
|
61
|
+
| `@wordpress/theme-build-tools/esbuild-plugins/esbuild-ds-token-fallbacks` | esbuild | JS/TS |
|
|
62
|
+
| `@wordpress/theme-build-tools/vite-plugins/vite-ds-token-fallbacks` | Vite | JS/TS |
|
|
63
|
+
|
|
64
|
+
Existing fallbacks are unchanged. An unknown token in a bare reference in transformed values fails the build.
|
|
65
|
+
|
|
66
|
+
The JavaScript plugins treat token references in string values, JSX attribute values, and static template parts as CSS. This includes tagged templates such as `String.raw`. They leave comments, regular expressions, property names, module paths, JSX text, and TypeScript types unchanged. Token names assembled across template expressions are not resolved. As before, a token reference in a runtime message string is also treated as CSS.
|
|
67
|
+
|
|
68
|
+
Files the JavaScript parser cannot read are left unchanged for the downstream compiler. To add fallbacks in Vite files that use custom syntax, configure the syntax-stripping plugin with `enforce: 'pre'` and list it before the token fallback plugin.
|
|
69
|
+
|
|
70
|
+
Both JavaScript plugins preserve source maps. The Vite plugin runs before JavaScript and TypeScript compilation and supports module IDs with query strings. It skips `?raw` and `?url` imports so their exported file contents and URLs stay unchanged.
|
|
71
|
+
|
|
72
|
+
### PostCSS
|
|
73
|
+
|
|
74
|
+
```js
|
|
75
|
+
// postcss.config.mjs
|
|
76
|
+
import dsTokenFallbacks from '@wordpress/theme-build-tools/postcss-plugins/postcss-ds-token-fallbacks';
|
|
77
|
+
|
|
78
|
+
export default {
|
|
79
|
+
plugins: [ dsTokenFallbacks ],
|
|
80
|
+
};
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### Lightning CSS
|
|
84
|
+
|
|
85
|
+
```js
|
|
86
|
+
import { transform, composeVisitors } from 'lightningcss';
|
|
87
|
+
import dsTokenFallbacks from '@wordpress/theme-build-tools/lightningcss-plugins/lightningcss-ds-token-fallbacks';
|
|
88
|
+
|
|
89
|
+
const { code } = transform( {
|
|
90
|
+
filename: 'styles.css',
|
|
91
|
+
code: Buffer.from( css ),
|
|
92
|
+
visitor: composeVisitors( [ dsTokenFallbacks ] ),
|
|
93
|
+
} );
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
The visitor preserves CSS Modules [`from global`](https://lightningcss.dev/css-modules.html#local-css-variables) references such as `var(--wpds-dimension-gap-sm from global)` when it adds a fallback. Custom properties inside generated fallbacks, including `--wp-admin-*` variables, also remain global so admin overrides still apply.
|
|
97
|
+
|
|
98
|
+
### esbuild
|
|
99
|
+
|
|
100
|
+
```js
|
|
101
|
+
import dsTokenFallbacks from '@wordpress/theme-build-tools/esbuild-plugins/esbuild-ds-token-fallbacks';
|
|
102
|
+
|
|
103
|
+
await esbuild.build( {
|
|
104
|
+
plugins: [ dsTokenFallbacks ],
|
|
105
|
+
// …
|
|
106
|
+
} );
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### Vite
|
|
110
|
+
|
|
111
|
+
The Vite setup uses both the Vite plugin (for JS/TS) and the PostCSS plugin (for CSS):
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
// vite.config.ts
|
|
115
|
+
import dsTokenFallbacks from '@wordpress/theme-build-tools/postcss-plugins/postcss-ds-token-fallbacks';
|
|
116
|
+
import dsTokenFallbacksJs from '@wordpress/theme-build-tools/vite-plugins/vite-ds-token-fallbacks';
|
|
117
|
+
|
|
118
|
+
export default defineConfig( {
|
|
119
|
+
plugins: [ dsTokenFallbacksJs() ],
|
|
120
|
+
css: {
|
|
121
|
+
postcss: {
|
|
122
|
+
plugins: [ dsTokenFallbacks ],
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
} );
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
## Contributing to this package
|
|
129
|
+
|
|
130
|
+
This is an individual package that's part of the Gutenberg project. The project is organized as a monorepo. It's made up of multiple self-contained software packages, each with a specific purpose. The packages in this monorepo are published to [npm](https://www.npmjs.com/) and used by [WordPress](https://make.wordpress.org/core/) as well as other software projects.
|
|
131
|
+
|
|
132
|
+
To find out more about contributing to this package or Gutenberg as a whole, please read the project's main [contributor guide](https://github.com/WordPress/gutenberg/tree/HEAD/CONTRIBUTING.md).
|
|
133
|
+
|
|
134
|
+
<br /><br /><p align="center"><img src="https://s.w.org/style/images/codeispoetry.png?1" alt="Code is Poetry." /></p>
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* esbuild plugin that injects design-system token fallbacks into JS/TS files.
|
|
3
|
+
*
|
|
4
|
+
* Replaces bare `var(--wpds-*)` references in string literals with
|
|
5
|
+
* `var(--wpds-*, <fallback>)` so components render correctly without
|
|
6
|
+
* a ThemeProvider. Does nothing when `@wordpress/theme` is not installed.
|
|
7
|
+
*
|
|
8
|
+
* @type {import('esbuild').Plugin}
|
|
9
|
+
*/
|
|
10
|
+
declare const plugin: import('esbuild').Plugin;
|
|
11
|
+
export default plugin;
|
|
12
|
+
//# sourceMappingURL=esbuild-ds-token-fallbacks.d.mts.map
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Inject fallbacks into JavaScript values without rewriting other source text.
|
|
3
|
+
* The caller is responsible for composing the returned source map.
|
|
4
|
+
*
|
|
5
|
+
* @param {string} source JavaScript or TypeScript source.
|
|
6
|
+
* @param {string} filename Source filename, without a query string.
|
|
7
|
+
* @return {{ code: string, map: import('magic-string').SourceMap, sourceMappingURL: string | undefined } | null} Transformation, or null when unchanged, unparseable, or `@wordpress/theme` is not installed.
|
|
8
|
+
*/
|
|
9
|
+
export declare function transformDsTokenFallbacks(source: string, filename: string): {
|
|
10
|
+
code: string;
|
|
11
|
+
map: import('magic-string').SourceMap;
|
|
12
|
+
sourceMappingURL: string | undefined;
|
|
13
|
+
} | null;
|
|
14
|
+
//# sourceMappingURL=transform-ds-token-fallbacks.d.mts.map
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Token data from the installed `@wordpress/theme`.
|
|
3
|
+
*
|
|
4
|
+
* The plugins do nothing when `@wordpress/theme` cannot be loaded.
|
|
5
|
+
*/
|
|
6
|
+
export type DesignTokensModule = {
|
|
7
|
+
/**
|
|
8
|
+
* Token metadata, keyed by CSS custom property name.
|
|
9
|
+
*/
|
|
10
|
+
tokens: Record<string, {
|
|
11
|
+
fallback: string;
|
|
12
|
+
}>;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Map of design token names to their generated fallback values, or
|
|
16
|
+
* `undefined` when `@wordpress/theme` is unavailable.
|
|
17
|
+
*
|
|
18
|
+
* @type {Record<string, string> | undefined}
|
|
19
|
+
*/
|
|
20
|
+
export declare const tokenFallbacks: Record<string, string> | undefined;
|
|
21
|
+
/**
|
|
22
|
+
* List of design token names, or `undefined` when `@wordpress/theme` is
|
|
23
|
+
* unavailable.
|
|
24
|
+
*
|
|
25
|
+
* @type {string[] | undefined}
|
|
26
|
+
*/
|
|
27
|
+
export declare const tokenList: string[] | undefined;
|
|
28
|
+
//# sourceMappingURL=theme-tokens.d.mts.map
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lightning CSS visitor that injects design-system token fallbacks into CSS.
|
|
3
|
+
*
|
|
4
|
+
* Replaces bare `var(--wpds-*)` references with `var(--wpds-*, <fallback>)`.
|
|
5
|
+
*
|
|
6
|
+
* Existing fallbacks are left untouched. Unknown tokens throw. Does nothing
|
|
7
|
+
* when `@wordpress/theme` is not installed.
|
|
8
|
+
*
|
|
9
|
+
* @type {import('lightningcss').Visitor<never>}
|
|
10
|
+
*/
|
|
11
|
+
declare const plugin: import('lightningcss').Visitor<never>;
|
|
12
|
+
export default plugin;
|
|
13
|
+
//# sourceMappingURL=lightningcss-ds-token-fallbacks.d.mts.map
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Replace bare `var(--wpds-*)` references in a CSS value string with
|
|
3
|
+
* `var(--wpds-*, <fallback>)` using the provided token fallback map.
|
|
4
|
+
*
|
|
5
|
+
* Existing fallbacks (i.e. `var()` calls that already contain a comma)
|
|
6
|
+
* are left untouched, making the function safe to run multiple times
|
|
7
|
+
* (idempotent).
|
|
8
|
+
*
|
|
9
|
+
* This is the generic, reusable implementation that takes the fallback
|
|
10
|
+
* map as an argument. For the variant prebound with the package's
|
|
11
|
+
* generated token fallback map, see `./ds-token-fallbacks.mjs`.
|
|
12
|
+
*
|
|
13
|
+
* @param {string} cssValue A CSS declaration value.
|
|
14
|
+
* @param {Record<string, string>} tokenFallbacks Map of CSS variable names to their fallback expressions.
|
|
15
|
+
* @param {Object} [options] Options.
|
|
16
|
+
* @param {boolean} [options.escapeQuotes] When true, escape `"` and `'` in fallback values.
|
|
17
|
+
* Use this when the input is JS/TS source so that
|
|
18
|
+
* injected quotes don't break string literals. JS
|
|
19
|
+
* will unescape them at parse time, so the browser's
|
|
20
|
+
* CSS engine still sees the correct value.
|
|
21
|
+
* @return {string} The value with fallbacks injected.
|
|
22
|
+
*/
|
|
23
|
+
export declare function addFallbackToVar(cssValue: string, tokenFallbacks: Record<string, string>, { escapeQuotes }?: {
|
|
24
|
+
escapeQuotes?: boolean;
|
|
25
|
+
}): string;
|
|
26
|
+
/**
|
|
27
|
+
* Get the fallback for a design token.
|
|
28
|
+
*
|
|
29
|
+
* @param {string} tokenName CSS variable name.
|
|
30
|
+
* @param {Record<string, string>} tokenFallbacks Map of CSS variable names to fallback expressions.
|
|
31
|
+
* @param {Object} [options] Options.
|
|
32
|
+
* @param {boolean} [options.escapeQuotes] Whether to escape quotes in the fallback.
|
|
33
|
+
* @return {string} The token fallback.
|
|
34
|
+
*/
|
|
35
|
+
export declare function getTokenFallback(tokenName: string, tokenFallbacks: Record<string, string>, { escapeQuotes }?: {
|
|
36
|
+
escapeQuotes?: boolean;
|
|
37
|
+
}): string;
|
|
38
|
+
//# sourceMappingURL=add-fallback-to-var.d.mts.map
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Replace bare `var(--wpds-*)` references in a CSS value string with
|
|
3
|
+
* `var(--wpds-*, <fallback>)` using the package's generated token
|
|
4
|
+
* fallback map.
|
|
5
|
+
*
|
|
6
|
+
* Existing fallbacks (i.e. var() calls that already contain a comma) are
|
|
7
|
+
* left untouched, making the function safe to run multiple times.
|
|
8
|
+
*
|
|
9
|
+
* This is a thin wrapper around the generic `addFallbackToVar` helper in
|
|
10
|
+
* `./add-fallback-to-var.mjs`, prebound to the package's token fallback
|
|
11
|
+
* map. Update the regex/replacement logic in that file, not here.
|
|
12
|
+
*
|
|
13
|
+
* Returns the value unchanged when `@wordpress/theme` is not installed.
|
|
14
|
+
*
|
|
15
|
+
* @param {string} cssValue A CSS declaration value.
|
|
16
|
+
* @param {Object} [options] Options.
|
|
17
|
+
* @param {boolean} [options.escapeQuotes] When true, escape `"` and `'` in
|
|
18
|
+
* fallback values. Use this when the
|
|
19
|
+
* input is JS/TS source so that
|
|
20
|
+
* injected quotes don't break string
|
|
21
|
+
* literals. JS will unescape them at
|
|
22
|
+
* parse time, so the browser's CSS
|
|
23
|
+
* engine still sees the correct value.
|
|
24
|
+
* @return {string} The value with fallbacks injected.
|
|
25
|
+
*/
|
|
26
|
+
export declare function addFallbackToVar(cssValue: string, options?: {
|
|
27
|
+
escapeQuotes?: boolean;
|
|
28
|
+
}): string;
|
|
29
|
+
/**
|
|
30
|
+
* Whether design token fallbacks are available, i.e. whether
|
|
31
|
+
* `@wordpress/theme` is installed. The plugins do nothing without them.
|
|
32
|
+
*/
|
|
33
|
+
export declare const hasTokenFallbacks: boolean;
|
|
34
|
+
/**
|
|
35
|
+
* Get the generated fallback for a design token.
|
|
36
|
+
*
|
|
37
|
+
* @param {string} tokenName CSS variable name.
|
|
38
|
+
* @return {string} The token fallback.
|
|
39
|
+
*/
|
|
40
|
+
export declare function getTokenFallback(tokenName: string): string;
|
|
41
|
+
//# sourceMappingURL=ds-token-fallbacks.d.mts.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Vite plugin that injects design-system token fallbacks into JS/TS files.
|
|
3
|
+
*
|
|
4
|
+
* Replaces bare `var(--wpds-*)` references in string literals with
|
|
5
|
+
* `var(--wpds-*, <fallback>)` so components render correctly without
|
|
6
|
+
* a ThemeProvider. Does nothing when `@wordpress/theme` is not installed.
|
|
7
|
+
*
|
|
8
|
+
* @type {() => import('vite').Plugin}
|
|
9
|
+
*/
|
|
10
|
+
declare const plugin: () => import('vite').Plugin;
|
|
11
|
+
export default plugin;
|
|
12
|
+
//# sourceMappingURL=vite-ds-token-fallbacks.d.mts.map
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { readFile } from 'fs/promises';
|
|
2
|
+
import { fileURLToPath, pathToFileURL } from 'url';
|
|
3
|
+
import remapping from '@jridgewell/remapping';
|
|
4
|
+
import { AnyMap } from '@jridgewell/trace-mapping';
|
|
5
|
+
import { transformDsTokenFallbacks } from '../js-plugins/transform-ds-token-fallbacks.mjs';
|
|
6
|
+
import { hasTokenFallbacks } from '../postcss-plugins/ds-token-fallbacks.mjs';
|
|
7
|
+
|
|
8
|
+
/** @type {Record<string, import('esbuild').Loader>} */
|
|
9
|
+
const LOADER_MAP = {
|
|
10
|
+
'.js': 'jsx',
|
|
11
|
+
'.jsx': 'jsx',
|
|
12
|
+
'.ts': 'ts',
|
|
13
|
+
'.tsx': 'tsx',
|
|
14
|
+
'.mjs': 'jsx',
|
|
15
|
+
'.mts': 'ts',
|
|
16
|
+
'.cjs': 'jsx',
|
|
17
|
+
'.cts': 'ts',
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* esbuild plugin that injects design-system token fallbacks into JS/TS files.
|
|
22
|
+
*
|
|
23
|
+
* Replaces bare `var(--wpds-*)` references in string literals with
|
|
24
|
+
* `var(--wpds-*, <fallback>)` so components render correctly without
|
|
25
|
+
* a ThemeProvider. Does nothing when `@wordpress/theme` is not installed.
|
|
26
|
+
*
|
|
27
|
+
* @type {import('esbuild').Plugin}
|
|
28
|
+
*/
|
|
29
|
+
const plugin = {
|
|
30
|
+
name: 'ds-token-fallbacks-js',
|
|
31
|
+
setup( build ) {
|
|
32
|
+
if ( ! hasTokenFallbacks ) {
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
build.onLoad(
|
|
37
|
+
{ filter: /\.[mc]?[jt]sx?$/, namespace: 'file' },
|
|
38
|
+
async ( args ) => {
|
|
39
|
+
// Skip node_modules.
|
|
40
|
+
if ( args.path.includes( 'node_modules' ) ) {
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const source = await readFile( args.path, 'utf8' );
|
|
45
|
+
|
|
46
|
+
if ( ! source.includes( '--wpds-' ) ) {
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const ext = args.path.match( /(\.[^.]+)$/ )?.[ 1 ] || '.js';
|
|
51
|
+
const result = transformDsTokenFallbacks( source, args.path );
|
|
52
|
+
if ( ! result ) {
|
|
53
|
+
return {
|
|
54
|
+
contents: source,
|
|
55
|
+
loader: LOADER_MAP[ ext ] || 'jsx',
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
let sourceMap = result.map.toUrl();
|
|
59
|
+
/** @type {string[]} */
|
|
60
|
+
const watchFiles = [];
|
|
61
|
+
/** @type {import('esbuild').PartialMessage[]} */
|
|
62
|
+
const warnings = [];
|
|
63
|
+
if ( result.sourceMappingURL ) {
|
|
64
|
+
try {
|
|
65
|
+
const url = new URL(
|
|
66
|
+
result.sourceMappingURL,
|
|
67
|
+
pathToFileURL( args.path )
|
|
68
|
+
);
|
|
69
|
+
/** @type {string | undefined} */
|
|
70
|
+
let inputMap;
|
|
71
|
+
let mapPath = args.path;
|
|
72
|
+
if ( url.protocol === 'data:' ) {
|
|
73
|
+
const comma = url.href.indexOf( ',' );
|
|
74
|
+
const data = decodeURIComponent(
|
|
75
|
+
url.href.slice( comma + 1 )
|
|
76
|
+
);
|
|
77
|
+
inputMap = url.href
|
|
78
|
+
.slice( 0, comma )
|
|
79
|
+
.endsWith( ';base64' )
|
|
80
|
+
? Buffer.from( data, 'base64' ).toString(
|
|
81
|
+
'utf8'
|
|
82
|
+
)
|
|
83
|
+
: data;
|
|
84
|
+
} else if ( url.protocol === 'file:' ) {
|
|
85
|
+
mapPath = fileURLToPath( url );
|
|
86
|
+
watchFiles.push( mapPath );
|
|
87
|
+
inputMap = await readFile( url, 'utf8' );
|
|
88
|
+
}
|
|
89
|
+
// Like esbuild, do not fetch remote source-map URLs.
|
|
90
|
+
if ( inputMap !== undefined ) {
|
|
91
|
+
const map = remapping(
|
|
92
|
+
[
|
|
93
|
+
result.map.toString(),
|
|
94
|
+
new AnyMap(
|
|
95
|
+
inputMap,
|
|
96
|
+
pathToFileURL( mapPath ).href
|
|
97
|
+
),
|
|
98
|
+
],
|
|
99
|
+
() => null
|
|
100
|
+
);
|
|
101
|
+
sourceMap = `data:application/json;base64,${ Buffer.from( map.toString() ).toString( 'base64' ) }`;
|
|
102
|
+
}
|
|
103
|
+
} catch ( error ) {
|
|
104
|
+
// esbuild ignores missing maps and warns for malformed maps.
|
|
105
|
+
if ( ! (
|
|
106
|
+
error &&
|
|
107
|
+
typeof error === 'object' &&
|
|
108
|
+
'code' in error &&
|
|
109
|
+
error.code === 'ENOENT'
|
|
110
|
+
) ) {
|
|
111
|
+
warnings.push( {
|
|
112
|
+
text: `Could not load the input source map: ${ error instanceof Error ? error.message : String( error ) }`,
|
|
113
|
+
detail: error,
|
|
114
|
+
} );
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return {
|
|
120
|
+
contents: `${ result.code }\n//# sourceMappingURL=${ sourceMap }`,
|
|
121
|
+
loader: LOADER_MAP[ ext ] || 'jsx',
|
|
122
|
+
watchFiles,
|
|
123
|
+
warnings,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
);
|
|
127
|
+
},
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
export default plugin;
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import { parse } from '@babel/parser';
|
|
2
|
+
import { isTSType, traverse } from '@babel/types';
|
|
3
|
+
import MagicString from 'magic-string';
|
|
4
|
+
import {
|
|
5
|
+
addFallbackToVar,
|
|
6
|
+
hasTokenFallbacks,
|
|
7
|
+
} from '../postcss-plugins/ds-token-fallbacks.mjs';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Whether an ancestor makes a literal part of a name, module path, or type.
|
|
11
|
+
*
|
|
12
|
+
* @param {import('@babel/types').TraversalAncestors} ancestors Ancestors.
|
|
13
|
+
* @return {boolean} Whether to leave the literal alone.
|
|
14
|
+
*/
|
|
15
|
+
function isNonValue( ancestors ) {
|
|
16
|
+
return ancestors.some( ( { node, key } ) => {
|
|
17
|
+
if ( isTSType( node ) ) {
|
|
18
|
+
return true;
|
|
19
|
+
}
|
|
20
|
+
if (
|
|
21
|
+
[
|
|
22
|
+
'source',
|
|
23
|
+
'key',
|
|
24
|
+
'property',
|
|
25
|
+
'imported',
|
|
26
|
+
'exported',
|
|
27
|
+
'local',
|
|
28
|
+
].includes( key )
|
|
29
|
+
) {
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
return (
|
|
33
|
+
node.type === 'ImportAttribute' ||
|
|
34
|
+
( ( node.type === 'TSModuleDeclaration' ||
|
|
35
|
+
node.type === 'TSEnumMember' ) &&
|
|
36
|
+
key === 'id' ) ||
|
|
37
|
+
node.type === 'TSExternalModuleReference' ||
|
|
38
|
+
node.type === 'ImportExpression' ||
|
|
39
|
+
( node.type === 'CallExpression' &&
|
|
40
|
+
( node.callee.type === 'Import' ||
|
|
41
|
+
( node.callee.type === 'Identifier' &&
|
|
42
|
+
node.callee.name === 'require' ) ) )
|
|
43
|
+
);
|
|
44
|
+
} );
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Inject fallbacks into JavaScript values without rewriting other source text.
|
|
49
|
+
* The caller is responsible for composing the returned source map.
|
|
50
|
+
*
|
|
51
|
+
* @param {string} source JavaScript or TypeScript source.
|
|
52
|
+
* @param {string} filename Source filename, without a query string.
|
|
53
|
+
* @return {{ code: string, map: import('magic-string').SourceMap, sourceMappingURL: string | undefined } | null} Transformation, or null when unchanged, unparseable, or `@wordpress/theme` is not installed.
|
|
54
|
+
*/
|
|
55
|
+
export function transformDsTokenFallbacks( source, filename ) {
|
|
56
|
+
if ( ! hasTokenFallbacks || ! source.includes( '--wpds-' ) ) {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const isTypeScript = /\.[mc]?tsx?$/.test( filename );
|
|
61
|
+
/** @type {import('@babel/parser').ParserOptions} */
|
|
62
|
+
const options = {
|
|
63
|
+
sourceType: 'unambiguous',
|
|
64
|
+
allowReturnOutsideFunction: true,
|
|
65
|
+
allowAwaitOutsideFunction: true,
|
|
66
|
+
allowUndeclaredExports: true,
|
|
67
|
+
attachComment: false,
|
|
68
|
+
errorRecovery: true,
|
|
69
|
+
plugins: [
|
|
70
|
+
...( isTypeScript
|
|
71
|
+
? [ /** @type {const} */ ( 'typescript' ) ]
|
|
72
|
+
: [] ),
|
|
73
|
+
...( /\.[mc]?ts$/.test( filename )
|
|
74
|
+
? []
|
|
75
|
+
: [ /** @type {const} */ ( 'jsx' ) ] ),
|
|
76
|
+
'decorators',
|
|
77
|
+
'decoratorAutoAccessors',
|
|
78
|
+
'deprecatedImportAssert',
|
|
79
|
+
'sourcePhaseImports',
|
|
80
|
+
'deferredImportEvaluation',
|
|
81
|
+
],
|
|
82
|
+
};
|
|
83
|
+
let parserSource = source;
|
|
84
|
+
/** @type {ReturnType<typeof parse>} */
|
|
85
|
+
let ast;
|
|
86
|
+
for (;;) {
|
|
87
|
+
try {
|
|
88
|
+
ast = parse( parserSource, options );
|
|
89
|
+
// Unambiguous parsing can retain module errors in a valid script.
|
|
90
|
+
if ( ast.program.sourceType === 'script' && ast.errors?.length ) {
|
|
91
|
+
ast = parse( parserSource, {
|
|
92
|
+
...options,
|
|
93
|
+
sourceType: 'script',
|
|
94
|
+
} );
|
|
95
|
+
}
|
|
96
|
+
break;
|
|
97
|
+
} catch ( error ) {
|
|
98
|
+
const parseError =
|
|
99
|
+
/** @type {import('@babel/parser').ParseError} */ ( error );
|
|
100
|
+
if ( parseError.code !== 'BABEL_PARSER_SYNTAX_ERROR' ) {
|
|
101
|
+
throw error;
|
|
102
|
+
}
|
|
103
|
+
if (
|
|
104
|
+
! isTypeScript ||
|
|
105
|
+
! [ 'UnexpectedLeadingDecorator', 'UnexpectedToken' ].includes(
|
|
106
|
+
parseError.reasonCode
|
|
107
|
+
) ||
|
|
108
|
+
! Number.isInteger( parseError.pos ) ||
|
|
109
|
+
parserSource[ parseError.pos ] !== '!'
|
|
110
|
+
) {
|
|
111
|
+
// A later compiler plugin may understand syntax Babel does not.
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
// Babel's decorator grammar rejects TypeScript non-null assertions.
|
|
115
|
+
// Mask only the rejected token for parsing, preserving source offsets.
|
|
116
|
+
// The downstream compiler still receives the original assertion.
|
|
117
|
+
parserSource =
|
|
118
|
+
parserSource.slice( 0, parseError.pos ) +
|
|
119
|
+
' ' +
|
|
120
|
+
parserSource.slice( parseError.pos + 1 );
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
// Babel's standard decorators grammar reports parameter decorators even
|
|
124
|
+
// in TypeScript. Leave that one check to the compiler's tsconfig settings.
|
|
125
|
+
for ( const error of ast.errors ?? [] ) {
|
|
126
|
+
if (
|
|
127
|
+
! isTypeScript ||
|
|
128
|
+
error.reasonCode !== 'UnsupportedParameterDecorator'
|
|
129
|
+
) {
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
const output = new MagicString( source );
|
|
134
|
+
|
|
135
|
+
traverse( ast, ( node, ancestors ) => {
|
|
136
|
+
if (
|
|
137
|
+
( node.type !== 'StringLiteral' &&
|
|
138
|
+
node.type !== 'TemplateElement' ) ||
|
|
139
|
+
typeof node.start !== 'number' ||
|
|
140
|
+
typeof node.end !== 'number' ||
|
|
141
|
+
isNonValue( ancestors )
|
|
142
|
+
) {
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if ( node.type === 'StringLiteral' ) {
|
|
147
|
+
const value = addFallbackToVar( node.value );
|
|
148
|
+
if ( value === node.value ) {
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
// Keep JSX literals as literals: JSX compilers can normalize their
|
|
152
|
+
// whitespace differently from JavaScript expression values.
|
|
153
|
+
const isAttribute =
|
|
154
|
+
ancestors.at( -1 )?.node.type === 'JSXAttribute';
|
|
155
|
+
output.overwrite(
|
|
156
|
+
node.start,
|
|
157
|
+
node.end,
|
|
158
|
+
isAttribute
|
|
159
|
+
? `"${ value.replaceAll( '&', '&' ).replaceAll( '"', '"' ) }"`
|
|
160
|
+
: JSON.stringify( value )
|
|
161
|
+
);
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// Tags can observe raw text, including String.raw and CSS-in-JS tags.
|
|
166
|
+
// Preserve their existing escapes and insert the CSS fallback verbatim.
|
|
167
|
+
const tagged =
|
|
168
|
+
ancestors.at( -2 )?.node.type === 'TaggedTemplateExpression';
|
|
169
|
+
const original = tagged ? node.value.raw : node.value.cooked;
|
|
170
|
+
if ( typeof original !== 'string' ) {
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
const value = addFallbackToVar( original );
|
|
174
|
+
if ( value !== original ) {
|
|
175
|
+
output.overwrite(
|
|
176
|
+
node.start,
|
|
177
|
+
node.end,
|
|
178
|
+
tagged
|
|
179
|
+
? value
|
|
180
|
+
: JSON.stringify( value )
|
|
181
|
+
.slice( 1, -1 )
|
|
182
|
+
.replaceAll( '\\"', '"' )
|
|
183
|
+
.replaceAll( '`', '\\`' )
|
|
184
|
+
.replaceAll( '${', '\\${' )
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
} );
|
|
188
|
+
|
|
189
|
+
if ( ! output.hasChanged() ) {
|
|
190
|
+
return null;
|
|
191
|
+
}
|
|
192
|
+
// Read actual comments, not directive-shaped text inside strings/templates.
|
|
193
|
+
let sourceMappingURL;
|
|
194
|
+
for ( const comment of ast.comments ?? [] ) {
|
|
195
|
+
const match = /^[#@]\s*sourceMappingURL=(\S+)\s*$/.exec(
|
|
196
|
+
comment.value
|
|
197
|
+
);
|
|
198
|
+
if ( match ) {
|
|
199
|
+
sourceMappingURL = match[ 1 ];
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return {
|
|
203
|
+
code: output.toString(),
|
|
204
|
+
sourceMappingURL,
|
|
205
|
+
map: output.generateMap( {
|
|
206
|
+
source: filename,
|
|
207
|
+
includeContent: true,
|
|
208
|
+
hires: true,
|
|
209
|
+
} ),
|
|
210
|
+
};
|
|
211
|
+
}
|