@wordpress/build 0.25.0 → 0.27.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.
@@ -1,26 +1,61 @@
1
1
  import { createHash } from 'node:crypto';
2
+ import path from 'node:path';
2
3
  import cssnano from 'cssnano';
3
4
  import postcss from 'postcss';
4
5
  import postcssModules from 'postcss-modules';
6
+ import dsTokenFallbacks from '@wordpress/theme-build-tools/postcss-plugins/postcss-ds-token-fallbacks';
5
7
 
6
- /** @type {import('postcss').AcceptedPlugin | undefined} */
7
- let dsTokenFallbacks;
8
- try {
9
- const { default: postcssPlugin } =
10
- await import( '@wordpress/theme/postcss-plugins/postcss-ds-token-fallbacks' );
11
- dsTokenFallbacks = postcssPlugin;
12
- } catch {
13
- // @wordpress/theme is optional; skip token fallbacks if not available.
14
- }
15
8
  export { dsTokenFallbacks };
16
9
 
10
+ /**
11
+ * Create a CSS module class name generator whose names change whenever the
12
+ * CSS that defines them changes.
13
+ *
14
+ * `postcss-modules-scope` calls the generator with the source of the file that
15
+ * defines each class, including files reached through `composes`. That source
16
+ * has not been through the earlier plugins yet, so they are applied before
17
+ * hashing. This way, a changed token fallback also renames the classes that
18
+ * use it.
19
+ *
20
+ * @param {import('postcss').AcceptedPlugin[]} plugins Plugins that run before `postcss-modules`.
21
+ * @return {(name: string, filename: string, css: string) => string} Class name generator.
22
+ */
23
+ function createScopedNameGenerator( plugins ) {
24
+ const processor = postcss( plugins );
25
+ /** @type {Map<string, string>} */
26
+ const processedSources = new Map();
27
+
28
+ return ( name, filename, css ) => {
29
+ let processedCss = processedSources.get( css );
30
+ if ( processedCss === undefined ) {
31
+ processedCss = processor.process( css, { from: filename } ).css;
32
+ processedSources.set( css, processedCss );
33
+ }
34
+
35
+ // Hash a relative path so that names do not depend on the checkout location.
36
+ const hash = createHash( 'sha1' )
37
+ .update(
38
+ path.relative( process.cwd(), filename ).replaceAll( '\\', '/' )
39
+ )
40
+ .update( '\0' )
41
+ .update( processedCss )
42
+ .update( '\0' )
43
+ .update( name )
44
+ .digest( 'hex' )
45
+ .slice( 0, 16 );
46
+
47
+ // A class name cannot start with a digit.
48
+ return `${ /^\d/.test( hash ) ? '_' : '' }${ hash }__${ name }`;
49
+ };
50
+ }
51
+
17
52
  /**
18
53
  * Compile CSS into the JavaScript module emitted by wp-build.
19
54
  *
20
55
  * @param {Object} options
21
56
  * @param {boolean} [options.cssModules=false] Whether to emit CSS Module exports.
22
57
  * @param {boolean} [options.minify=true] Whether to minify the CSS.
23
- * @return {Function} esbuild-sass-plugin transform callback.
58
+ * @return {Function} Transform of compiled CSS into a JavaScript module.
24
59
  */
25
60
  export function compileInlineStyle( {
26
61
  cssModules = false,
@@ -35,11 +70,12 @@ export function compileInlineStyle( {
35
70
  return async function styleType( cssText, _dirname, filePath ) {
36
71
  let moduleExports = null;
37
72
 
38
- const plugins = dsTokenFallbacks ? [ dsTokenFallbacks ] : [];
73
+ /** @type {import('postcss').AcceptedPlugin[]} */
74
+ const plugins = [ dsTokenFallbacks ];
39
75
  if ( cssModules ) {
40
76
  plugins.push(
41
77
  postcssModules( {
42
- generateScopedName: '[contenthash]__[local]',
78
+ generateScopedName: createScopedNameGenerator( plugins ),
43
79
  getJSON: ( _, json ) => {
44
80
  moduleExports = json;
45
81
  },
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Dependency graph utilities for WordPress packages.
3
3
  *
4
- * This module provides functions to analyze dependencies between @wordpress/* packages
4
+ * This module provides functions to analyze dependencies between `@wordpress/*` packages
5
5
  * and determine the correct build order using topological sorting.
6
6
  */
7
7
 
@@ -66,7 +66,7 @@ function findPackageRoot( startDir ) {
66
66
  * and external dependencies in pnpm/yarn/npm workspaces.
67
67
  *
68
68
  * @param {string} fullPackageName The full package name (e.g., '@wordpress/blocks').
69
- * @param {string|null} resolveDir Optional directory context for resolution (from esbuild).
69
+ * @param {string|null} resolveDir Optional directory context for resolution (the importer's directory).
70
70
  * @return {PackageJson|null} Package.json object or null if not found.
71
71
  */
72
72
  export function getPackageInfo( fullPackageName, resolveDir = null ) {
@@ -90,7 +90,7 @@ export function getPackageInfo( fullPackageName, resolveDir = null ) {
90
90
  } catch ( error ) {
91
91
  // Treat a genuine resolution miss (package not installed, or it doesn't
92
92
  // expose its package.json) as `null` so callers can fall through to
93
- // esbuild's own resolution. Rethrow anything unexpected so real errors
93
+ // the bundler's own resolution. Rethrow anything unexpected so real errors
94
94
  // (invalid specifiers, resolver bugs) aren't silently swallowed.
95
95
  const code = /** @type {NodeJS.ErrnoException} */ ( error ).code;
96
96
  if (
@@ -34,6 +34,11 @@ export async function getPhpReplacements( rootDir, baseUrlExpression ) {
34
34
  /**
35
35
  * Apply template replacements to a template string.
36
36
  *
37
+ * In the Gutenberg repository, the PHP templates are statically analyzed with
38
+ * a sample value for each placeholder, in `tools/phpstan/src/WpBuildTemplateParser.php`.
39
+ * When a placeholder is added, or what one expands to changes shape, update
40
+ * its sample value there too.
41
+ *
37
42
  * @param {string} template Template string with placeholders.
38
43
  * @param {Record<string, string>} replacements Replacements object (e.g. {'{{PREFIX}}': 'gutenberg'}).
39
44
  * @return {string} Template with replacements applied.
@@ -148,7 +148,7 @@ export function generateContentEntryPoint( files ) {
148
148
  const lines = [];
149
149
 
150
150
  /*
151
- * Import the full file name rather than relying on esbuild extending an
151
+ * Import the full file name rather than relying on the bundler extending an
152
152
  * extensionless path: that resolution never tries `.mts` or `.cts`.
153
153
  */
154
154
  if ( files.stage ) {
@@ -0,0 +1,41 @@
1
+ import { readFile } from 'fs/promises';
2
+ import { initAsyncCompiler } from 'sass-embedded';
3
+
4
+ /** @type {Promise<import('sass-embedded').AsyncCompiler> | undefined} */
5
+ let compilerPromise;
6
+
7
+ /**
8
+ * Stop the shared Sass compiler, if it was started. Its process keeps Node
9
+ * running until it is stopped.
10
+ *
11
+ * @return {Promise<void>}
12
+ */
13
+ export async function disposeSassCompiler() {
14
+ if ( ! compilerPromise ) {
15
+ return;
16
+ }
17
+ const compiler = await compilerPromise;
18
+ compilerPromise = undefined;
19
+ await compiler.dispose();
20
+ }
21
+
22
+ /**
23
+ * Compile a stylesheet to CSS. Plain CSS files are returned as they are.
24
+ *
25
+ * @param {string} filePath Absolute path of the stylesheet.
26
+ * @param {import('sass-embedded').Options<'async'>} sassOptions Sass options.
27
+ * @return {Promise<string>} The CSS.
28
+ */
29
+ export async function compileStylesheet( filePath, sassOptions ) {
30
+ if ( filePath.endsWith( '.css' ) ) {
31
+ return readFile( filePath, 'utf8' );
32
+ }
33
+
34
+ compilerPromise ??= initAsyncCompiler();
35
+ const compiler = await compilerPromise;
36
+ const { css } = await compiler.compileAsync( filePath, {
37
+ ...sassOptions,
38
+ sourceMap: false,
39
+ } );
40
+ return css;
41
+ }
@@ -52,6 +52,11 @@ export function getAllWidgets( rootDir ) {
52
52
  * @property {'high'|'medium'|'low'} [relevance] How prominently a host surfaces the attribute.
53
53
  */
54
54
 
55
+ /**
56
+ * @typedef {Object} WidgetExampleMetadata
57
+ * @property {Record<string, unknown>} [attributes] Attribute values hosts preview the widget with, and apply to a new instance.
58
+ */
59
+
55
60
  /**
56
61
  * @typedef {Object} WidgetMetadata
57
62
  * @property {string} name Widget namespaced identifier.
@@ -61,6 +66,7 @@ export function getAllWidgets( rootDir ) {
61
66
  * @property {string} [icon] Registered icon name (`collection/icon-name`).
62
67
  * @property {WidgetActionMetadata[]} [actions] Declarative actions the widget exposes.
63
68
  * @property {WidgetAttributeMetadata[]} [attributes] Attribute schema, the JSON-expressible subset of a DataViews `Field`.
69
+ * @property {WidgetExampleMetadata} [example] Structured example: `attributes` as plain JSON values.
64
70
  * @property {string} [category] Grouping category.
65
71
  * @property {'framed' | 'content-bleed' | 'full-bleed'} [presentation] Authoring intent about how the widget wants to render.
66
72
  * @property {string[]} [keywords] Search aliases used to match the widget.
@@ -104,7 +110,7 @@ export function getWidgetMetadata( rootDir, widgetName ) {
104
110
 
105
111
  /**
106
112
  * Supported source extensions for widget entry files, in priority order.
107
- * Must stay aligned with SOURCE_EXTENSIONS in build.mjs.
113
+ * Must stay aligned with SOURCE_EXTENSIONS in source-files.mjs.
108
114
  */
109
115
  const WIDGET_EXTENSIONS = [
110
116
  'tsx',