@wordpress/theme-build-tools 1.0.0 → 1.1.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/README.md CHANGED
@@ -40,6 +40,8 @@ These rules validate design token usage in CSS. Enable them in your Stylelint co
40
40
 
41
41
  Reports references to unknown `--wpds-*` tokens.
42
42
 
43
+ The rule checks CSS `var()` references. It ignores token-like text in strings and URLs.
44
+
43
45
  ### `plugin-wpds/no-setting-wpds-custom-properties`
44
46
 
45
47
  Reports definitions or overrides in the `--wpds-*` namespace.
@@ -63,6 +65,8 @@ The build plugins inject generated fallbacks into bare `var(--wpds-*)` reference
63
65
 
64
66
  Existing fallbacks are unchanged. An unknown token in a bare reference in transformed values fails the build.
65
67
 
68
+ The PostCSS plugin leaves token-like text in CSS strings and URLs unchanged.
69
+
66
70
  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
71
 
68
72
  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.
@@ -23,6 +23,14 @@
23
23
  export declare function addFallbackToVar(cssValue: string, tokenFallbacks: Record<string, string>, { escapeQuotes }?: {
24
24
  escapeQuotes?: boolean;
25
25
  }): string;
26
+ /**
27
+ * Replace bare `var(--wpds-*)` references in a parsed CSS value.
28
+ *
29
+ * @param {string} cssValue A CSS declaration value.
30
+ * @param {Record<string, string>} tokenFallbacks Map of CSS variable names to fallback expressions.
31
+ * @return {string} The value with fallbacks injected.
32
+ */
33
+ export declare function addFallbackToVarInCSS(cssValue: string, tokenFallbacks: Record<string, string>): string;
26
34
  /**
27
35
  * Get the fallback for a design token.
28
36
  *
@@ -31,6 +31,13 @@ export declare function addFallbackToVar(cssValue: string, options?: {
31
31
  * `@wordpress/theme` is installed. The plugins do nothing without them.
32
32
  */
33
33
  export declare const hasTokenFallbacks: boolean;
34
+ /**
35
+ * Replace bare design token references in a parsed CSS declaration value.
36
+ *
37
+ * @param {string} cssValue A CSS declaration value.
38
+ * @return {string} The value with fallbacks injected.
39
+ */
40
+ export declare function addFallbackToVarInCSS(cssValue: string): string;
34
41
  /**
35
42
  * Get the generated fallback for a design token.
36
43
  *
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Parse the custom property references in CSS `var()` functions.
3
+ *
4
+ * String, URL, and comment contents are not treated as CSS functions.
5
+ *
6
+ * @param {string} value A CSS declaration value.
7
+ * @return {{ parsed: import('postcss-value-parser').ParsedValue, references: Array<{ name: string, sourceIndex: number, fallbackSeparator: import('postcss-value-parser').DivNode | undefined, node: import('postcss-value-parser').FunctionNode }> }} The parsed value and its custom property references.
8
+ */
9
+ export declare function parseCSSVariableReferences(value: string): {
10
+ parsed: import('postcss-value-parser').ParsedValue;
11
+ references: Array<{
12
+ name: string;
13
+ sourceIndex: number;
14
+ fallbackSeparator: import('postcss-value-parser').DivNode | undefined;
15
+ node: import('postcss-value-parser').FunctionNode;
16
+ }>;
17
+ };
18
+ //# sourceMappingURL=parse-css-variables.d.mts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wordpress/theme-build-tools",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Build plugins and Stylelint rules for the WordPress Design System design tokens.",
5
5
  "author": "The WordPress Contributors",
6
6
  "license": "GPL-2.0-or-later",
@@ -74,22 +74,24 @@
74
74
  "@babel/types": "^7.29.7",
75
75
  "@jridgewell/remapping": "^2.3.5",
76
76
  "@jridgewell/trace-mapping": "^0.3.31",
77
- "magic-string": "^0.30.21"
77
+ "magic-string": "^0.30.21",
78
+ "postcss-value-parser": "^4.2.0"
78
79
  },
79
80
  "devDependencies": {
80
81
  "@types/node": "^24.13.3",
81
- "@wordpress/theme": "^4.0.0",
82
+ "@wordpress/theme": "^5.0.0",
82
83
  "@wordpress/validation-tools": "file:../../tools/validation",
83
84
  "esbuild": "^0.27.2",
84
85
  "lightningcss": "^1.33.0",
85
- "postcss": "^8.4.38",
86
+ "postcss": "^8.5.33",
87
+ "postcss-scss": "^4.0.9",
86
88
  "source-map": "^0.6.1",
87
89
  "stylelint": "^17.14.1",
88
- "vite": "^8.3.5",
89
- "vitest": "^5.0.5"
90
+ "vite": "^8.3.8",
91
+ "vitest": "^5.1.0"
90
92
  },
91
93
  "peerDependencies": {
92
- "@wordpress/theme": "^3.0.0 || ^4.0.0",
94
+ "@wordpress/theme": "^3.0.0 || ^4.0.0 || ^5.0.0",
93
95
  "esbuild": ">=0.27.2 <1.0.0",
94
96
  "lightningcss": ">=1.33.0 <2.0.0",
95
97
  "postcss": "^8.0.0",
@@ -122,5 +124,5 @@
122
124
  "scripts": {
123
125
  "lint:package-contents": "wp-validate-package-contents . --disallow-path test"
124
126
  },
125
- "gitHead": "9b70363b9f93cff0583a1f3153738d383cf5a49e"
127
+ "gitHead": "1000cdf1dffd5b5e69f75cc4360aa76db8252264"
126
128
  }
@@ -1,3 +1,6 @@
1
+ import valueParser from 'postcss-value-parser';
2
+ import { parseCSSVariableReferences } from './parse-css-variables.mjs';
3
+
1
4
  /**
2
5
  * Replace bare `var(--wpds-*)` references in a CSS value string with
3
6
  * `var(--wpds-*, <fallback>)` using the provided token fallback map.
@@ -36,6 +39,35 @@ export function addFallbackToVar(
36
39
  );
37
40
  }
38
41
 
42
+ /**
43
+ * Replace bare `var(--wpds-*)` references in a parsed CSS value.
44
+ *
45
+ * @param {string} cssValue A CSS declaration value.
46
+ * @param {Record<string, string>} tokenFallbacks Map of CSS variable names to fallback expressions.
47
+ * @return {string} The value with fallbacks injected.
48
+ */
49
+ export function addFallbackToVarInCSS( cssValue, tokenFallbacks ) {
50
+ if ( ! cssValue.includes( '--wpds-' ) && ! cssValue.includes( '\\' ) ) {
51
+ return cssValue;
52
+ }
53
+
54
+ const { parsed, references } = parseCSSVariableReferences( cssValue );
55
+
56
+ for ( const reference of references ) {
57
+ if (
58
+ ! reference.name.startsWith( '--wpds-' ) ||
59
+ reference.fallbackSeparator
60
+ ) {
61
+ continue;
62
+ }
63
+
64
+ const fallback = getTokenFallback( reference.name, tokenFallbacks );
65
+ reference.node.nodes.push( ...valueParser( `, ${ fallback }` ).nodes );
66
+ }
67
+
68
+ return parsed.toString();
69
+ }
70
+
39
71
  /**
40
72
  * Get the fallback for a design token.
41
73
  *
@@ -1,6 +1,7 @@
1
1
  import { tokenFallbacks } from '../lib/theme-tokens.mjs';
2
2
  import {
3
3
  addFallbackToVar as _addFallbackToVar,
4
+ addFallbackToVarInCSS as _addFallbackToVarInCSS,
4
5
  getTokenFallback as _getTokenFallback,
5
6
  } from './add-fallback-to-var.mjs';
6
7
 
@@ -42,6 +43,19 @@ export function addFallbackToVar( cssValue, options ) {
42
43
  */
43
44
  export const hasTokenFallbacks = tokenFallbacks !== undefined;
44
45
 
46
+ /**
47
+ * Replace bare design token references in a parsed CSS declaration value.
48
+ *
49
+ * @param {string} cssValue A CSS declaration value.
50
+ * @return {string} The value with fallbacks injected.
51
+ */
52
+ export function addFallbackToVarInCSS( cssValue ) {
53
+ if ( ! tokenFallbacks ) {
54
+ return cssValue;
55
+ }
56
+ return _addFallbackToVarInCSS( cssValue, tokenFallbacks );
57
+ }
58
+
45
59
  /**
46
60
  * Get the generated fallback for a design token.
47
61
  *
@@ -0,0 +1,106 @@
1
+ import valueParser from 'postcss-value-parser';
2
+
3
+ const identifierPattern = String.raw`(?:[\w\u0080-\uFFFF-]|\\(?:[\da-f]{1,6}(?:\r\n|[ \t\n\r\f])?|[^\n\r\f]))+`;
4
+ const identifierStart = new RegExp( `^${ identifierPattern }`, 'i' );
5
+ const identifiers = new RegExp( identifierPattern, 'gi' );
6
+
7
+ /**
8
+ * Decode CSS escapes without changing the source nodes used for serialization.
9
+ *
10
+ * @param {string} identifier A CSS identifier's source spelling.
11
+ * @return {string} The decoded identifier.
12
+ */
13
+ function decodeIdentifier( identifier ) {
14
+ return identifier.replace(
15
+ /\\(?:([\da-f]{1,6})(?:\r\n|[ \t\n\r\f])?|([^\n\r\f]))/gi,
16
+ ( match, hex, character ) => {
17
+ if ( ! hex ) {
18
+ return character;
19
+ }
20
+ const codePoint = parseInt( hex, 16 );
21
+ return codePoint === 0 ||
22
+ codePoint > 0x10ffff ||
23
+ ( codePoint >= 0xd800 && codePoint <= 0xdfff )
24
+ ? '\uFFFD'
25
+ : String.fromCodePoint( codePoint );
26
+ }
27
+ );
28
+ }
29
+
30
+ /**
31
+ * @param {import('postcss-value-parser').Node} node A parsed value node.
32
+ * @return {node is import('postcss-value-parser').DivNode} Whether the node separates a fallback value.
33
+ */
34
+ function isFallbackSeparator( node ) {
35
+ return node.type === 'div' && node.value === ',';
36
+ }
37
+
38
+ /**
39
+ * Parse the custom property references in CSS `var()` functions.
40
+ *
41
+ * String, URL, and comment contents are not treated as CSS functions.
42
+ *
43
+ * @param {string} value A CSS declaration value.
44
+ * @return {{ parsed: import('postcss-value-parser').ParsedValue, references: Array<{ name: string, sourceIndex: number, fallbackSeparator: import('postcss-value-parser').DivNode | undefined, node: import('postcss-value-parser').FunctionNode }> }} The parsed value and its custom property references.
45
+ */
46
+ export function parseCSSVariableReferences( value ) {
47
+ const parsed = valueParser( value );
48
+ /** @type {Map<number, number>} */
49
+ const variableFunctionStarts = new Map();
50
+ // Hexadecimal escapes can split function names across value-parser nodes.
51
+ // Scan once to locate their complete source spelling.
52
+ for ( const identifier of value.matchAll( identifiers ) ) {
53
+ const end = identifier.index + identifier[ 0 ].length;
54
+ const prefix = value[ identifier.index - 1 ];
55
+ if (
56
+ prefix !== '#' &&
57
+ prefix !== '@' &&
58
+ value[ end ] === '(' &&
59
+ decodeIdentifier( identifier[ 0 ] ).toLowerCase() === 'var'
60
+ ) {
61
+ variableFunctionStarts.set( end, identifier.index );
62
+ }
63
+ }
64
+ /** @type {Array<{ name: string, sourceIndex: number, fallbackSeparator: import('postcss-value-parser').DivNode | undefined, node: import('postcss-value-parser').FunctionNode }>} */
65
+ const references = [];
66
+
67
+ parsed.walk( ( node ) => {
68
+ if ( node.type !== 'function' ) {
69
+ return;
70
+ }
71
+
72
+ const sourceIndex = variableFunctionStarts.get(
73
+ node.sourceIndex + node.value.length
74
+ );
75
+ if ( sourceIndex === undefined ) {
76
+ return;
77
+ }
78
+
79
+ const nameNode = node.nodes.find(
80
+ ( child ) => child.type !== 'space' && child.type !== 'comment'
81
+ );
82
+
83
+ if ( nameNode?.type !== 'word' ) {
84
+ return;
85
+ }
86
+
87
+ // A hexadecimal escape's terminating whitespace can split an identifier
88
+ // across value-parser nodes. Read the whole identifier from its source.
89
+ const spelling = value
90
+ .slice( nameNode.sourceIndex )
91
+ .match( identifierStart )?.[ 0 ];
92
+ const name = decodeIdentifier( spelling ?? '' );
93
+ if ( ! name.startsWith( '--' ) ) {
94
+ return;
95
+ }
96
+
97
+ references.push( {
98
+ name,
99
+ sourceIndex,
100
+ fallbackSeparator: node.nodes.find( isFallbackSeparator ),
101
+ node,
102
+ } );
103
+ } );
104
+
105
+ return { parsed, references };
106
+ }
@@ -1,11 +1,11 @@
1
- import { addFallbackToVar } from './ds-token-fallbacks.mjs';
1
+ import { addFallbackToVarInCSS } from './ds-token-fallbacks.mjs';
2
2
 
3
3
  /** @type {import('postcss').PluginCreator<never>} */
4
4
  const plugin = () => ( {
5
5
  postcssPlugin: 'postcss-ds-token-fallbacks',
6
6
  /** @param {import('postcss').Declaration} decl */
7
7
  Declaration( decl ) {
8
- const updated = addFallbackToVar( decl.value );
8
+ const updated = addFallbackToVarInCSS( decl.value );
9
9
  if ( updated !== decl.value ) {
10
10
  decl.value = updated;
11
11
  }
@@ -1,4 +1,5 @@
1
1
  import stylelint from 'stylelint';
2
+ import { parseCSSVariableReferences } from '../postcss-plugins/parse-css-variables.mjs';
2
3
 
3
4
  const {
4
5
  createPlugin,
@@ -7,12 +8,6 @@ const {
7
8
 
8
9
  const ruleName = 'plugin-wpds/no-token-fallback-values';
9
10
 
10
- /**
11
- * Matches `var(--wpds-<name>,` — the comma signals a fallback value.
12
- * Captures the token name (e.g. `--wpds-color-foreground-content-neutral`).
13
- */
14
- const varWithFallbackRegex = /var\(\s*(--wpds-[\w-]+)\s*,/g;
15
-
16
11
  const messages = ruleMessages( ruleName, {
17
12
  rejected: ( tokenName ) =>
18
13
  `Do not add a fallback value for Design System token '${ tokenName }'. Fallbacks should be injected automatically at build time (see @wordpress/theme-build-tools package README).`,
@@ -31,15 +26,51 @@ const ruleFunction = ( primary ) => {
31
26
  }
32
27
 
33
28
  root.walkDecls( ( ruleNode ) => {
34
- const { value } = ruleNode;
29
+ if (
30
+ ! ruleNode.value.includes( '--wpds-' ) &&
31
+ ! ruleNode.value.includes( '\\' )
32
+ ) {
33
+ return;
34
+ }
35
+
36
+ const declaration = ruleNode.toString();
37
+ const references =
38
+ parseCSSVariableReferences( declaration ).references;
39
+ let { line, column } = ruleNode.rangeBy( { index: 0 } ).start;
40
+ let offset = 0;
41
+
42
+ // SCSS serialization adds closing delimiters to line comments. Those
43
+ // change offsets, but not line/column positions on subsequent lines.
44
+ // References are visited in source order, so advance one shared cursor.
45
+ /** @param {number} index Offset in the serialized declaration. */
46
+ const getPosition = ( index ) => {
47
+ while ( offset < index ) {
48
+ if ( declaration[ offset++ ] === '\n' ) {
49
+ line++;
50
+ column = 1;
51
+ } else {
52
+ column++;
53
+ }
54
+ }
55
+ return { line, column };
56
+ };
57
+
58
+ for ( const reference of references ) {
59
+ if (
60
+ ! reference.name.startsWith( '--wpds-' ) ||
61
+ ! reference.fallbackSeparator
62
+ ) {
63
+ continue;
64
+ }
35
65
 
36
- let match;
37
- varWithFallbackRegex.lastIndex = 0;
38
- while ( ( match = varWithFallbackRegex.exec( value ) ) !== null ) {
39
66
  report( {
40
- message: messages.rejected( match[ 1 ] ),
67
+ message: messages.rejected( reference.name ),
41
68
  node: ruleNode,
42
- word: match[ 0 ],
69
+ start: getPosition( reference.sourceIndex ),
70
+ end: getPosition(
71
+ reference.fallbackSeparator.sourceEndIndex -
72
+ reference.fallbackSeparator.after.length
73
+ ),
43
74
  result,
44
75
  ruleName,
45
76
  } );
@@ -1,43 +1,10 @@
1
1
  import stylelint from 'stylelint';
2
2
  import { tokenList } from '../lib/theme-tokens.mjs';
3
+ import { parseCSSVariableReferences } from '../postcss-plugins/parse-css-variables.mjs';
3
4
 
4
5
  const DS_TOKEN_PREFIX = 'wpds-';
5
6
 
6
- /**
7
- * Extracts all unique CSS custom properties (variables) from a given CSS value string,
8
- * including those in fallback positions, optionally filtering by a specific prefix.
9
- *
10
- * @param {string} value - The CSS value string to search for variables.
11
- * @param {string} [prefix=''] - Optional prefix to filter variables (e.g., 'wpds-').
12
- * @return {Set<string>} A Set of unique matched CSS variable names (e.g., Set { '--wpds-token' }).
13
- *
14
- * @example
15
- * extractCSSVariables(
16
- * 'border: 1px solid var(--wpds-border-radius-sm, var(--wpds-border-radius-md)); ' +
17
- * 'color: var(--wpds-color-foreground-content-neutral, black); ' +
18
- * 'background: var(--unrelated-bg);',
19
- * 'wpds'
20
- * );
21
- * // → Set { '--wpds-border-radius-sm', '--wpds-border-radius-md', '--wpds-color-foreground-content-neutral' }
22
- */
23
- function extractCSSVariables( value, prefix = '' ) {
24
- const regex = /--[\w-]+/g;
25
- /** @type {Set<string>} */
26
- const variables = new Set();
27
-
28
- let match;
29
- while ( ( match = regex.exec( value ) ) !== null ) {
30
- const variableName = match[ 0 ];
31
- if ( variableName.startsWith( `--${ prefix }` ) ) {
32
- variables.add( variableName );
33
- }
34
- }
35
-
36
- return variables;
37
- }
38
-
39
7
  const knownTokens = new Set( tokenList ?? [] );
40
- const wpdsTokensRegex = new RegExp( `[^\\w]--${ DS_TOKEN_PREFIX }`, 'i' );
41
8
 
42
9
  const {
43
10
  createPlugin,
@@ -66,16 +33,19 @@ const ruleFunction = ( primary ) => {
66
33
 
67
34
  root.walkDecls( ( ruleNode ) => {
68
35
  const { value } = ruleNode;
69
- // Early match for WPDS tokens to avoid unnecessary processing.
70
- if ( wpdsTokensRegex.test( value ) ) {
71
- const usedTokens = extractCSSVariables(
72
- value,
73
- DS_TOKEN_PREFIX
74
- );
36
+ if (
37
+ value.includes( `--${ DS_TOKEN_PREFIX }` ) ||
38
+ value.includes( '\\' )
39
+ ) {
40
+ const { references } = parseCSSVariableReferences( value );
75
41
  const unknownTokens = new Set(
76
- [ ...usedTokens ].filter(
77
- ( token ) => ! knownTokens.has( token )
78
- )
42
+ references
43
+ .map( ( reference ) => reference.name )
44
+ .filter(
45
+ ( name ) =>
46
+ name.startsWith( `--${ DS_TOKEN_PREFIX }` ) &&
47
+ ! knownTokens.has( name )
48
+ )
79
49
  );
80
50
 
81
51
  if ( unknownTokens.size > 0 ) {