@wordpress/build 0.26.0 → 0.28.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/lib/build.mjs CHANGED
@@ -3,17 +3,16 @@ import { readFile, writeFile, copyFile, mkdir, unlink } from 'fs/promises';
3
3
  import path from 'path';
4
4
  import { createRequire as createNodeRequire } from 'node:module';
5
5
  import { parseArgs } from 'node:util';
6
- import esbuild from 'esbuild';
7
6
  import glob from 'fast-glob';
8
7
  import chokidar from 'chokidar';
9
8
  import browserslistToEsbuild from 'browserslist-to-esbuild';
10
- import { sassPlugin } from 'esbuild-sass-plugin';
11
9
  import postcss from 'postcss';
12
10
  import autoprefixer from 'autoprefixer';
13
11
  import rtlcss from 'rtlcss';
14
12
  import cssnano from 'cssnano';
15
13
  import { camelCase } from 'change-case';
16
14
  import { NodePackageImporter } from 'sass-embedded';
15
+ import createDsTokenFallbacksPlugin from '@wordpress/theme-build-tools/vite-plugins/vite-ds-token-fallbacks';
17
16
  import {
18
17
  groupByDepth,
19
18
  findScriptsToRebundle,
@@ -24,7 +23,12 @@ import {
24
23
  getPhpReplacements,
25
24
  renderTemplateToString,
26
25
  } from './php-generator.mjs';
27
- import { getPackageInfo, getPackageInfoFromFile } from './package-utils.mjs';
26
+ import {
27
+ boolConfigVal,
28
+ getPackageInfo,
29
+ getPackageInfoFromFile,
30
+ } from './package-utils.mjs';
31
+ import { copyPackageFile, getCopyFiles } from './copy-files.mjs';
28
32
  import { getBrowserslistQueries } from './browserslist.mjs';
29
33
  import { getSourceFileGlob, isTestSourceFile } from './source-files.mjs';
30
34
  import { createWordpressExternalsPlugin } from './wordpress-externals-plugin.mjs';
@@ -48,6 +52,12 @@ import {
48
52
  compileInlineStyle,
49
53
  dsTokenFallbacks,
50
54
  } from './compile-inline-style.mjs';
55
+ import { compileStylesheet, disposeSassCompiler } from './sass-compiler.mjs';
56
+ import {
57
+ buildWithConcurrency,
58
+ getDefaultBuildConcurrency,
59
+ setBuildConcurrency,
60
+ } from './build-concurrency.mjs';
51
61
 
52
62
  /**
53
63
  * Resolve the ESBuild target from the project's Browserslist config.
@@ -57,24 +67,15 @@ import {
57
67
  function getEsbuildTarget() {
58
68
  return browserslistToEsbuild( getBrowserslistQueries() );
59
69
  }
60
- // Optional dependency: @wordpress/theme provides a plugin that injects fallback
61
- // values for design system tokens in JavaScript. Fails gracefully when the
62
- // package is not installed (it is an optional peerDependency).
63
- let dsTokenFallbacksJs;
64
- try {
65
- const { default: esbuildPlugin } =
66
- await import( '@wordpress/theme/esbuild-plugins/esbuild-ds-token-fallbacks' );
67
- dsTokenFallbacksJs = esbuildPlugin;
68
- } catch {
69
- // @wordpress/theme is optional; skip token fallbacks if not available.
70
- }
70
+ // The Vite-only `enforce` property is not a Rolldown plugin property.
71
+ const { enforce, ...dsTokenFallbacksJs } = createDsTokenFallbacksPlugin();
71
72
 
72
73
  const ROOT_DIR = process.cwd();
73
74
  const PACKAGES_DIR = path.join( ROOT_DIR, 'packages' );
74
75
  const BUILD_DIR = path.join( ROOT_DIR, 'build' );
75
76
 
76
77
  /**
77
- * esbuild loaders for non-JS imports. SVG files are inlined as `data:` URIs.
78
+ * Module types for non-JS imports. SVG files are inlined as `data:` URIs.
78
79
  */
79
80
  const LOADER_CONFIG = { '.svg': 'dataurl' };
80
81
  const ASSET_EXTENSIONS = 'json';
@@ -114,20 +115,6 @@ const PAGES = WP_PLUGIN_CONFIG.pages || [];
114
115
  // enforce this themselves.
115
116
  const DEFAULT_PAGE_CAPABILITY = 'manage_options';
116
117
 
117
- /**
118
- * Interprets a configuration value as a boolean, where `"true"` and `"1"`
119
- * are considered true while all other values are false.
120
- *
121
- * @param {string|undefined} value The configuration value to interpret.
122
- * @return {boolean|undefined} Boolean interpretation of the given configuration value, or undefined if not set.
123
- */
124
- const boolConfigVal = ( value ) => {
125
- if ( value === undefined ) {
126
- return undefined;
127
- }
128
- return [ 'true', '1' ].includes( value.toLowerCase() );
129
- };
130
-
131
118
  const baseDefine = {
132
119
  'globalThis.IS_GUTENBERG_PLUGIN': JSON.stringify(
133
120
  boolConfigVal( process.env.IS_GUTENBERG_PLUGIN ) ??
@@ -142,8 +129,41 @@ const baseDefine = {
142
129
  false
143
130
  ),
144
131
  };
145
- // Keep esbuild's module condition when enabling development exports.
146
- const developmentConditions = [ 'development', 'module' ];
132
+ // Rolldown's default conditions lack esbuild's module condition.
133
+ const defaultConditions = [ 'module', 'browser', 'default' ];
134
+ const developmentConditions = [ 'development', ...defaultConditions ];
135
+ /*
136
+ * The `jsx` option overrides the tsconfig's `jsx`, which is `preserve` for the
137
+ * type checker.
138
+ */
139
+ const JSX_OPTIONS = { runtime: 'automatic', importSource: 'react' };
140
+ const BASE_CHECKS = {
141
+ configurationFieldConflict: false,
142
+ // Don't warn about directives like 'use client' in bundled dependencies.
143
+ moduleLevelDirective: false,
144
+ };
145
+ // Rolldown's `__toESM` gives namespace imports a `default` unless the module has
146
+ // its own, even when flagged `__esModule`. Follow the flag alone, like esbuild.
147
+ const TO_ESM_OWN_DEFAULT_CHECK = ' || !__hasOwnProp.call(mod, "default")';
148
+ const esModuleInteropPlugin = {
149
+ name: 'es-module-interop',
150
+ renderChunk( code ) {
151
+ if ( ! code.includes( 'var __toESM = ' ) ) {
152
+ return null;
153
+ }
154
+ if ( ! code.includes( TO_ESM_OWN_DEFAULT_CHECK ) ) {
155
+ throw new Error( 'Unexpected Rolldown `__toESM` helper.' );
156
+ }
157
+ // A same-length replacement keeps the source map valid.
158
+ return {
159
+ code: code.replace(
160
+ TO_ESM_OWN_DEFAULT_CHECK,
161
+ ' '.repeat( TO_ESM_OWN_DEFAULT_CHECK.length )
162
+ ),
163
+ map: null,
164
+ };
165
+ },
166
+ };
147
167
  const getDefine = ( scriptDebug ) => ( {
148
168
  ...baseDefine,
149
169
  'globalThis.SCRIPT_DEBUG': JSON.stringify( scriptDebug ),
@@ -177,11 +197,9 @@ const STYLE_RUNTIME_ENTRY = path.join(
177
197
  function styleRuntimeAliasPlugin() {
178
198
  return {
179
199
  name: 'style-runtime-alias',
180
- setup( build ) {
181
- build.onResolve(
182
- { filter: /^@wordpress\/style-runtime$/ },
183
- () => ( { path: STYLE_RUNTIME_ENTRY } )
184
- );
200
+ resolveId: {
201
+ filter: { id: /^@wordpress\/style-runtime$/ },
202
+ handler: () => STYLE_RUNTIME_ENTRY,
185
203
  },
186
204
  };
187
205
  }
@@ -210,16 +228,41 @@ function getSassOptions( workingDir ) {
210
228
  };
211
229
  }
212
230
 
213
- function inlineStyle( contents ) {
214
- // The `contents` is already a JS code created by `compileInlineStyle`.
215
- return contents;
231
+ /**
232
+ * Plugin compiling stylesheets with Sass into JS code, created by `transform`
233
+ * from the CSS.
234
+ *
235
+ * @param {Object} options Plugin options, along with the Sass options.
236
+ * @param {RegExp} options.filter Stylesheets to compile.
237
+ * @param {(css: string, resolveDir: string, filePath: string) => Promise<string>} options.transform Transforms the CSS into JS code.
238
+ * @return {import('rolldown').Plugin} Rolldown plugin.
239
+ */
240
+ function sassPlugin( { filter, transform, ...sassOptions } ) {
241
+ // Files transpiled on their own share the plugin, and often a stylesheet.
242
+ const cache = new Map();
243
+ const compile = async ( id ) => {
244
+ const css = await compileStylesheet( id, sassOptions );
245
+ return transform( css, path.dirname( id ), id );
246
+ };
247
+ return {
248
+ name: 'sass',
249
+ load: {
250
+ filter: { id: filter },
251
+ async handler( id ) {
252
+ if ( ! cache.has( id ) ) {
253
+ cache.set( id, compile( id ) );
254
+ }
255
+ return { code: await cache.get( id ), moduleType: 'js' };
256
+ },
257
+ },
258
+ };
216
259
  }
217
260
 
218
261
  /**
219
262
  * Create style bundling plugins with the given working directory.
220
263
  *
221
264
  * @param {string} workingDir - The directory where we're working (for NodePackageImporter).
222
- * @return {object[]} Array of esbuild plugins for handling CSS/SCSS.
265
+ * @return {import('rolldown').Plugin[]} Array of Rolldown plugins for handling CSS/SCSS.
223
266
  */
224
267
  function createStyleBundlingPlugins( workingDir ) {
225
268
  const sassOptions = getSassOptions( workingDir );
@@ -227,21 +270,15 @@ function createStyleBundlingPlugins( workingDir ) {
227
270
  styleRuntimeAliasPlugin(),
228
271
  // Handle CSS modules (.module.css and .module.scss)
229
272
  sassPlugin( {
230
- embedded: true,
231
- sourceMap: false,
232
273
  filter: /\.module\.(css|scss)$/,
233
274
  transform: compileInlineStyle( { cssModules: true } ),
234
- type: inlineStyle,
235
275
  ...sassOptions,
236
276
  } ),
237
277
  // Handle regular CSS/SCSS files
238
278
  // Note: .module.css and .module.scss already handled by plugin above
239
279
  sassPlugin( {
240
- embedded: true,
241
- sourceMap: false,
242
280
  filter: /\.(css|scss)$/,
243
281
  transform: compileInlineStyle(),
244
- type: inlineStyle,
245
282
  ...sassOptions,
246
283
  } ),
247
284
  ];
@@ -303,6 +340,8 @@ function binaryEncode( data ) {
303
340
  return Buffer.from( out ).toString( 'utf8' );
304
341
  }
305
342
 
343
+ const WASM_INLINE_PREFIX = '\0wasm-inline:';
344
+
306
345
  /**
307
346
  * Plugin to inline WASM files into the bundle.
308
347
  *
@@ -311,55 +350,53 @@ function binaryEncode( data ) {
311
350
  * embedded using a compact UTF-8 encoding (rather than base64) so it compresses
312
351
  * well, and is decoded back to a `Uint8Array` at runtime.
313
352
  *
314
- * @return {Object} esbuild plugin.
353
+ * @type {import('rolldown').Plugin}
315
354
  */
316
355
  const wasmInlinePlugin = {
317
356
  name: 'wasm-inline',
318
- setup( build ) {
319
- // Resolve .wasm imports from node_modules.
320
- build.onResolve( { filter: /\.wasm$/ }, async ( args ) => {
321
- // Handle imports like 'wasm-vips/vips.wasm'.
322
- if ( ! args.path.startsWith( '.' ) ) {
323
- const { createRequire } = await import( 'module' );
324
- const require = createRequire( args.resolveDir + '/index.js' );
325
- try {
326
- const resolved = require.resolve( args.path );
327
- return {
328
- path: normalizePath(
329
- path.relative( ROOT_DIR, resolved )
330
- ),
331
- namespace: 'wasm-inline',
332
- pluginData: { resolvedPath: resolved },
333
- };
334
- } catch {
335
- // If resolution fails, let other plugins handle it.
336
- return null;
337
- }
357
+ // Resolve .wasm imports from node_modules, like 'wasm-vips/vips.wasm'.
358
+ resolveId: {
359
+ filter: { id: /^[^.].*\.wasm$/ },
360
+ handler( source, importer ) {
361
+ const require = createNodeRequire(
362
+ importer ?? path.join( ROOT_DIR, 'index.js' )
363
+ );
364
+ try {
365
+ // A path relative to the root keeps the checkout path out of
366
+ // the source map.
367
+ return (
368
+ WASM_INLINE_PREFIX +
369
+ normalizePath(
370
+ path.relative( ROOT_DIR, require.resolve( source ) )
371
+ )
372
+ );
373
+ } catch {
374
+ // If resolution fails, let other plugins handle it.
375
+ return null;
338
376
  }
339
- return null;
340
- } );
377
+ },
378
+ },
341
379
 
342
- // Load WASM files, embed them as a compact UTF-8 string, and decode
343
- // back to a Uint8Array at runtime.
344
- build.onLoad(
345
- { filter: /.*/, namespace: 'wasm-inline' },
346
- async ( args ) => {
347
- const wasmBuffer = await readFile(
348
- args.pluginData.resolvedPath
349
- );
350
- const encoded = binaryEncode( wasmBuffer );
380
+ // Load WASM files, embed them as a compact UTF-8 string, and decode
381
+ // back to a Uint8Array at runtime.
382
+ load: {
383
+ filter: { id: /^\0wasm-inline:/ },
384
+ async handler( id ) {
385
+ const wasmBuffer = await readFile(
386
+ path.join( ROOT_DIR, id.slice( WASM_INLINE_PREFIX.length ) )
387
+ );
388
+ const encoded = binaryEncode( wasmBuffer );
351
389
 
352
- return {
353
- contents: `const s = ${ encoded };
390
+ return {
391
+ code: `const s = ${ encoded };
354
392
  const bytes = new Uint8Array( s.length );
355
393
  for ( let i = 0; i < s.length; i++ ) {
356
394
  bytes[ i ] = s.charCodeAt( i );
357
395
  }
358
396
  export default bytes;`,
359
- loader: 'js',
360
- };
361
- }
362
- );
397
+ moduleType: 'js',
398
+ };
399
+ },
363
400
  },
364
401
  };
365
402
 
@@ -373,104 +410,41 @@ function normalizePath( p ) {
373
410
  return p.replace( /\\/g, '/' );
374
411
  }
375
412
 
376
- function transformPhpContent( content, transforms ) {
377
- const {
378
- functionPrefix = '',
379
- classSuffix = '',
380
- prefixFunctions = [],
381
- suffixClasses = [],
382
- addActionPriority,
383
- } = transforms;
384
-
385
- content = content.toString();
386
-
387
- /*
388
- * Transforms are used to modify PHP files that are committed to version
389
- * control in their wordpress-develop state (`wp_` function prefixes, `WP_`
390
- * class prefixes, etc.). When building for WordPress Core, it's not
391
- * necessary to perform these steps.
392
- */
393
- if (
394
- boolConfigVal( process.env.IS_WORDPRESS_CORE ) ??
395
- boolConfigVal( process.env.npm_package_config_IS_WORDPRESS_CORE )
396
- ) {
397
- return content;
398
- }
399
-
400
- if ( prefixFunctions.length ) {
401
- content = content.replace(
402
- new RegExp( prefixFunctions.join( '|' ), 'g' ),
403
- ( match ) => `${ functionPrefix }${ match.replace( /^wp_/, '' ) }`
404
- );
405
- }
406
-
407
- if ( suffixClasses.length ) {
408
- content = content.replace(
409
- new RegExp( suffixClasses.join( '|' ), 'g' ),
410
- ( match ) => `${ match }${ classSuffix }`
411
- );
412
- }
413
-
414
- if ( functionPrefix ) {
415
- content = Array.from(
416
- content.matchAll( /^\s*function ([^\(]+)/gm )
417
- ).reduce( ( result, [ , functionName ] ) => {
418
- return result.replace(
419
- new RegExp( functionName + '(?![a-zA-Z0-9_])', 'g' ),
420
- ( match ) => functionPrefix + match.replace( /^wp_/, '' )
421
- );
422
- }, content );
423
- }
424
-
425
- if ( addActionPriority ) {
426
- content = content.replace(
427
- /(add_action\(\s*'init',\s*'gutenberg_register_block_[^']+'(?!,))/,
428
- `$1, ${ addActionPriority }`
429
- );
430
- }
431
-
432
- return content;
433
- }
434
-
435
413
  /**
436
414
  * Plugin to handle moment-timezone aliases.
437
415
  * Redirects moment-timezone imports to use pre-built bundles with limited data.
438
416
  *
439
- * @return {Object} esbuild plugin.
417
+ * @return {import('rolldown').Plugin} Rolldown plugin.
440
418
  */
441
419
  function momentTimezoneAliasPlugin() {
442
420
  return {
443
421
  name: 'moment-timezone-alias',
444
- setup( build ) {
445
- // Alias path that esbuild will resolve
446
- const aliasPath =
447
- 'moment-timezone/builds/moment-timezone-with-data-1970-2030.js';
448
-
449
- // Redirect main moment-timezone files to pre-built bundle
450
- build.onResolve(
451
- { filter: /^moment-timezone\/moment-timezone\.js$/ },
452
- ( { importer, resolveDir, kind } ) =>
453
- build.resolve( aliasPath, {
454
- importer,
455
- resolveDir,
422
+ resolveId: {
423
+ filter: { id: /^(moment-timezone\/moment-timezone\.js|\.\/)$/ },
424
+ handler( source, importer, { kind } ) {
425
+ // Alias path that Rolldown will resolve
426
+ const aliasPath =
427
+ 'moment-timezone/builds/moment-timezone-with-data-1970-2030.js';
428
+
429
+ // Redirect main moment-timezone files to pre-built bundle
430
+ if ( source === 'moment-timezone/moment-timezone.js' ) {
431
+ return this.resolve( aliasPath, importer, {
456
432
  kind,
457
- } )
458
- );
433
+ skipSelf: true,
434
+ } );
435
+ }
459
436
 
460
- // Intercept the require('./') call inside moment-timezone-utils
461
- // and redirect it to the pre-built bundle.
462
- build.onResolve(
463
- { filter: /^\.\/$/ },
464
- ( { importer, resolveDir, kind } ) => {
465
- if ( importer.includes( 'moment-timezone-utils' ) ) {
466
- return build.resolve( aliasPath, {
467
- importer,
468
- resolveDir,
469
- kind,
470
- } );
471
- }
437
+ // Intercept the require('./') call inside moment-timezone-utils
438
+ // and redirect it to the pre-built bundle.
439
+ if ( importer?.includes( 'moment-timezone-utils' ) ) {
440
+ return this.resolve( aliasPath, importer, {
441
+ kind,
442
+ skipSelf: true,
443
+ } );
472
444
  }
473
- );
445
+
446
+ return null;
447
+ },
474
448
  },
475
449
  };
476
450
  }
@@ -515,7 +489,48 @@ function resolveEntryPoint( packageDir, packageJson ) {
515
489
  }
516
490
 
517
491
  /**
518
- * Bundle a package for WordPress using esbuild.
492
+ * Rolldown plugin that exposes a classic script's exports on the global,
493
+ * e.g. `window.wp.blocks`.
494
+ *
495
+ * Its `outro` runs at the end of the bundle's function, whose `exports`
496
+ * parameter holds the entry's exports as data properties. A CommonJS entry's
497
+ * `module.exports` is its default export.
498
+ *
499
+ * @param {string} scriptGlobal Global variable name, e.g. `wp`.
500
+ * @param {string} globalMember Member of the global variable, e.g. `blocks`.
501
+ * @param {boolean} exposeDefault Whether to expose the default export instead of the exports.
502
+ * @return {import('rolldown').Plugin} Rolldown plugin.
503
+ */
504
+ function scriptGlobalPlugin( scriptGlobal, globalMember, exposeDefault ) {
505
+ return {
506
+ name: 'script-global',
507
+ outro( chunk ) {
508
+ if ( ! chunk.isEntry ) {
509
+ return '';
510
+ }
511
+ const assign = ( value ) =>
512
+ `(window.${ scriptGlobal } ||= {}).${ globalMember } = ${ value };`;
513
+ // The bundle's function has no `exports` parameter without exports.
514
+ if ( chunk.exports.length === 0 ) {
515
+ return assign( 'undefined' );
516
+ }
517
+ const { inputFormat } = this.getModuleInfo( chunk.facadeModuleId );
518
+ if (
519
+ ( exposeDefault || inputFormat === 'cjs' ) &&
520
+ chunk.exports.includes( 'default' )
521
+ ) {
522
+ return assign( 'exports.default' );
523
+ }
524
+ return [
525
+ "Object.defineProperty(exports, '__esModule', { value: true });",
526
+ assign( 'exports' ),
527
+ ].join( '\n' );
528
+ },
529
+ };
530
+ }
531
+
532
+ /**
533
+ * Bundle a package for WordPress using Rolldown.
519
534
  *
520
535
  * @param {string} packageName Package name.
521
536
  * @param {Object} options Optional bundling options.
@@ -551,60 +566,57 @@ async function bundlePackage( packageName, options = {} ) {
551
566
  );
552
567
  const shouldExposeGlobal = matchesNamespace && scriptGlobal !== false;
553
568
 
554
- const globalName = shouldExposeGlobal
555
- ? `${ scriptGlobal }.${ camelCase( packageName ) }`
556
- : undefined;
557
-
558
569
  const baseConfig = {
559
- entryPoints: [ entryPoint ],
560
- bundle: true,
561
- loader: LOADER_CONFIG,
562
- sourcemap: true,
563
- format: 'iife',
564
- target,
570
+ input: entryPoint,
571
+ moduleTypes: LOADER_CONFIG,
565
572
  platform: 'browser',
566
- globalName,
573
+ checks: {
574
+ ...BASE_CHECKS,
575
+ // The script global plugin exposes the exports, not `output.name`.
576
+ missingNameOptionForIifeExport: false,
577
+ },
567
578
  };
568
579
 
569
- /*
570
- * Wrap the bundle in an IIFE so the `'use strict'` directive esbuild emits for the
571
- * (strict) ES module output stays at the function level. Left at the top of the
572
- * file it is a *file-level* directive, which — because load-scripts.php
573
- * concatenates raw file contents — forces strict mode onto any sloppy-mode script
574
- * bundled after it, throwing on e.g. implicit globals. Wrapping confines the
575
- * directive to this bundle. See https://core.trac.wordpress.org/ticket/65515.
576
- */
577
- baseConfig.banner = { js: '(function() {' };
578
-
579
- /*
580
- * esbuild's `globalName` assigns onto a locally-declared `var` root (using a
581
- * `window.…` global name would emit `var window`, shadowing the real global), so
582
- * that assignment is trapped inside the wrapper. Re-expose it on the real global
583
- * object in the footer, then close the IIFE.
584
- */
585
- let footerJs = '';
586
- if ( shouldExposeGlobal ) {
587
- const globalMember = camelCase( packageName );
588
- // For packages with default exports, expose the default, not the namespace.
589
- if ( packageJson.wpScriptDefaultExport ) {
590
- footerJs += `if (typeof ${ globalName } === 'object' && ${ globalName }.default) { ${ globalName } = ${ globalName }.default; }\n`;
591
- }
592
- footerJs += `(window.${ scriptGlobal } ||= {}).${ globalMember } = ${ scriptGlobal }.${ globalMember };\n`;
593
- }
594
- footerJs += '})();';
595
- baseConfig.footer = { js: footerJs };
580
+ const baseOutput = {
581
+ sourcemap: true,
582
+ format: 'iife',
583
+ codeSplitting: false,
584
+ exports: 'named',
585
+ /*
586
+ * Keep the `'use strict'` directive for the (strict) ES module code inside
587
+ * the bundle's function. Left at the top of the file it is a *file-level*
588
+ * directive, which — because load-scripts.php concatenates raw file
589
+ * contents — forces strict mode onto any sloppy-mode script bundled after
590
+ * it, throwing on e.g. implicit globals.
591
+ * See https://core.trac.wordpress.org/ticket/65515.
592
+ */
593
+ strict: false,
594
+ intro: '"use strict";',
595
+ // The script global plugin adds it, only when there are exports.
596
+ esModule: false,
597
+ generatedCode: { symbols: false },
598
+ };
596
599
 
597
600
  const baseBundlePlugins = [
598
601
  momentTimezoneAliasPlugin(),
599
602
  styleRuntimeAliasPlugin(),
603
+ shouldExposeGlobal &&
604
+ scriptGlobalPlugin(
605
+ scriptGlobal,
606
+ camelCase( packageName ),
607
+ !! packageJson.wpScriptDefaultExport
608
+ ),
600
609
  ];
601
610
 
602
611
  builds.push(
603
- esbuild.build( {
612
+ buildWithConcurrency( {
604
613
  ...baseConfig,
605
- outfile: path.join( outputDir, 'index.min.js' ),
606
- minify: true,
607
- define: getDefine( false ),
614
+ transform: {
615
+ target,
616
+ define: getDefine( false ),
617
+ jsx: JSX_OPTIONS,
618
+ },
619
+ resolve: { conditionNames: defaultConditions },
608
620
  plugins: [
609
621
  ...baseBundlePlugins,
610
622
  wordpressExternalsPlugin(
@@ -614,13 +626,20 @@ async function bundlePackage( packageName, options = {} ) {
614
626
  true // Generate asset file for minified build
615
627
  ),
616
628
  ],
629
+ output: {
630
+ ...baseOutput,
631
+ file: path.join( outputDir, 'index.min.js' ),
632
+ minify: true,
633
+ },
617
634
  } ),
618
- esbuild.build( {
635
+ buildWithConcurrency( {
619
636
  ...baseConfig,
620
- outfile: path.join( outputDir, 'index.js' ),
621
- minify: false,
622
- define: getDefine( true ),
623
- conditions: developmentConditions,
637
+ transform: {
638
+ target,
639
+ define: getDefine( true ),
640
+ jsx: JSX_OPTIONS,
641
+ },
642
+ resolve: { conditionNames: developmentConditions },
624
643
  plugins: [
625
644
  ...baseBundlePlugins,
626
645
  wordpressExternalsPlugin(
@@ -630,6 +649,11 @@ async function bundlePackage( packageName, options = {} ) {
630
649
  false // Skip asset file for non-minified build
631
650
  ),
632
651
  ],
652
+ output: {
653
+ ...baseOutput,
654
+ file: path.join( outputDir, 'index.js' ),
655
+ minify: false,
656
+ },
633
657
  } )
634
658
  );
635
659
 
@@ -671,24 +695,17 @@ async function bundlePackage( packageName, options = {} ) {
671
695
  );
672
696
 
673
697
  builds.push(
674
- esbuild.build( {
675
- loader: LOADER_CONFIG,
676
- entryPoints: [ entryPoint ],
677
- outfile: path.join(
678
- rootBuildModuleDir,
679
- `${ fileName }.min.js`
680
- ),
681
- bundle: true,
682
- // Emit UTF-8 so binary-encoded inlined WASM (e.g. the vips
683
- // worker) stays compact; ASCII output would escape high
684
- // bytes as \uXXXX and defeat the compression.
685
- charset: 'utf8',
686
- sourcemap: ! isWasmWorker,
687
- format: 'esm',
688
- target,
698
+ buildWithConcurrency( {
699
+ moduleTypes: LOADER_CONFIG,
700
+ checks: BASE_CHECKS,
701
+ input: entryPoint,
689
702
  platform: 'browser',
690
- minify: true,
691
- define: getDefine( false ),
703
+ transform: {
704
+ target,
705
+ define: getDefine( false ),
706
+ jsx: JSX_OPTIONS,
707
+ },
708
+ resolve: { conditionNames: defaultConditions },
692
709
  plugins: [
693
710
  styleRuntimeAliasPlugin(),
694
711
  wordpressExternalsPlugin(
@@ -698,27 +715,32 @@ async function bundlePackage( packageName, options = {} ) {
698
715
  true // Generate asset file for minified build
699
716
  ),
700
717
  ],
718
+ output: {
719
+ file: path.join(
720
+ rootBuildModuleDir,
721
+ `${ fileName }.min.js`
722
+ ),
723
+ codeSplitting: false,
724
+ sourcemap: ! isWasmWorker,
725
+ format: 'esm',
726
+ minify: true,
727
+ },
701
728
  } )
702
729
  );
703
730
 
704
731
  if ( ! isWasmWorker ) {
705
732
  builds.push(
706
- esbuild.build( {
707
- loader: LOADER_CONFIG,
708
- entryPoints: [ entryPoint ],
709
- outfile: path.join(
710
- rootBuildModuleDir,
711
- `${ fileName }.js`
712
- ),
713
- bundle: true,
714
- charset: 'utf8',
715
- sourcemap: true,
716
- format: 'esm',
717
- target,
733
+ buildWithConcurrency( {
734
+ moduleTypes: LOADER_CONFIG,
735
+ checks: BASE_CHECKS,
736
+ input: entryPoint,
718
737
  platform: 'browser',
719
- minify: false,
720
- define: getDefine( true ),
721
- conditions: developmentConditions,
738
+ transform: {
739
+ target,
740
+ define: getDefine( true ),
741
+ jsx: JSX_OPTIONS,
742
+ },
743
+ resolve: { conditionNames: developmentConditions },
722
744
  plugins: [
723
745
  styleRuntimeAliasPlugin(),
724
746
  wordpressExternalsPlugin(
@@ -728,6 +750,16 @@ async function bundlePackage( packageName, options = {} ) {
728
750
  false // Skip asset file for non-minified build
729
751
  ),
730
752
  ],
753
+ output: {
754
+ file: path.join(
755
+ rootBuildModuleDir,
756
+ `${ fileName }.js`
757
+ ),
758
+ codeSplitting: false,
759
+ sourcemap: true,
760
+ format: 'esm',
761
+ minify: false,
762
+ },
731
763
  } )
732
764
  );
733
765
  }
@@ -801,76 +833,15 @@ async function bundlePackage( packageName, options = {} ) {
801
833
  }
802
834
  }
803
835
 
804
- if ( packageJson.wpCopyFiles ) {
805
- const { files, transforms = {} } = packageJson.wpCopyFiles;
806
- const packageSourceDir = path.join( packageDir, 'src' );
807
- const outputDir = path.join( BUILD_DIR, 'scripts', packageName );
808
-
809
- for ( const filePattern of files ) {
810
- const matchedFiles = await glob(
811
- normalizePath( path.join( packageDir, filePattern ) )
812
- );
813
-
814
- for ( const sourceFile of matchedFiles ) {
815
- const relativePath = path.relative(
816
- packageSourceDir,
817
- sourceFile
818
- );
819
- const destPath = path.join( outputDir, relativePath );
820
- const destDir = path.dirname( destPath );
821
-
822
- if ( sourceFile.endsWith( '.php' ) && transforms.php ) {
823
- builds.push(
824
- ( async () => {
825
- let finalPath = destPath;
826
- let finalDir = destDir;
827
-
828
- const content = await readFile(
829
- sourceFile,
830
- 'utf8'
831
- );
832
- const transformed = transformPhpContent(
833
- content,
834
- transforms.php
835
- );
836
-
837
- if ( transforms.php.filenameSuffix ) {
838
- const ext = path.extname( destPath );
839
- const base = path.basename( destPath, ext );
840
- finalPath = path.join(
841
- destDir,
842
- `${ base }${ transforms.php.filenameSuffix }${ ext }`
843
- );
844
- }
845
-
846
- // Check if we should flatten index.php files
847
- if (
848
- transforms.php.flattenIndexFiles &&
849
- path.basename( sourceFile ) === 'index.php'
850
- ) {
851
- // Flatten: button/index.php → button.php
852
- const parentDir = path.dirname( finalPath );
853
- const blockName = path.basename( parentDir );
854
- finalPath = path.join(
855
- path.dirname( parentDir ),
856
- `${ blockName }.php`
857
- );
858
- finalDir = path.dirname( finalPath );
859
- }
860
-
861
- await mkdir( finalDir, { recursive: true } );
862
- await writeFile( finalPath, transformed );
863
- } )()
864
- );
865
- } else {
866
- builds.push(
867
- mkdir( destDir, { recursive: true } ).then( () =>
868
- copyFile( sourceFile, destPath )
869
- )
870
- );
871
- }
872
- }
873
- }
836
+ for ( const sourceFile of await getCopyFiles( packageDir, packageJson ) ) {
837
+ builds.push(
838
+ copyPackageFile(
839
+ sourceFile,
840
+ packageDir,
841
+ path.join( BUILD_DIR, 'scripts', packageName ),
842
+ packageJson
843
+ )
844
+ );
874
845
  }
875
846
 
876
847
  if ( builds.length === 0 ) {
@@ -1316,7 +1287,8 @@ async function transpilePackage( packageName ) {
1316
1287
 
1317
1288
  const srcFiles = await glob( getSourceFileGlob( 'src/**/*' ), {
1318
1289
  cwd: packageDir,
1319
- ignore: IGNORE_PATTERNS,
1290
+ // Declaration files have no code to transpile.
1291
+ ignore: [ ...IGNORE_PATTERNS, '**/*.d.{ts,mts,cts}' ],
1320
1292
  absolute: true,
1321
1293
  } );
1322
1294
 
@@ -1344,73 +1316,50 @@ async function transpilePackage( packageName ) {
1344
1316
  */
1345
1317
  const externalizeJsImportsPlugin = {
1346
1318
  name: 'externalize-js-imports',
1347
- setup( build ) {
1348
- // Externalize all imports except styles and SVGs
1349
- build.onResolve( { filter: /.*/ }, async ( args ) => {
1350
- // Skip recursive calls.
1351
- if ( args.pluginData?.__fromExternalize ) {
1352
- return null;
1353
- }
1319
+ async resolveId( source, importer, extraOptions ) {
1320
+ // Skip entry points
1321
+ if ( extraOptions.isEntry || ! importer ) {
1322
+ return null;
1323
+ }
1354
1324
 
1355
- // Skip entry points
1356
- if ( args.kind === 'entry-point' ) {
1357
- return null;
1358
- }
1325
+ // Let CSS/SCSS files be processed by the style plugin
1326
+ if ( source.match( /\.(css|scss)$/ ) ) {
1327
+ return null;
1328
+ }
1359
1329
 
1360
- // Let CSS/SCSS files be processed by sassPlugin
1361
- if ( args.path.match( /\.(css|scss)$/ ) ) {
1362
- return null;
1363
- }
1330
+ // Let SVG files be inlined by the `dataurl` module type.
1331
+ if ( source.endsWith( '.svg' ) ) {
1332
+ return null;
1333
+ }
1334
+
1335
+ // Fully resolve local dependencies without file extension.
1336
+ // The output's `paths` replace the extension with the target extension.
1337
+ if ( source.startsWith( '.' ) ) {
1338
+ const resolved = await this.resolve( source, importer, {
1339
+ kind: extraOptions.kind,
1340
+ skipSelf: true,
1341
+ } );
1364
1342
 
1365
- // Let SVG files be inlined by the `dataurl` loader.
1366
- if ( args.path.endsWith( '.svg' ) ) {
1343
+ if ( ! resolved ) {
1367
1344
  return null;
1368
1345
  }
1369
1346
 
1370
- // Fully resolve local dependencies without file extension
1371
- // and replace the extension with the target extension.
1372
- if ( args.path.startsWith( '.' ) ) {
1373
- const resolved = await build.resolve( args.path, {
1374
- namespace: args.namespace,
1375
- importer: args.importer,
1376
- kind: args.kind,
1377
- resolveDir: args.resolveDir,
1378
- with: args.with,
1379
- pluginData: {
1380
- ...args.pluginData,
1381
- __fromExternalize: true,
1382
- },
1383
- } );
1384
-
1385
- if ( resolved.errors.length > 0 ) {
1386
- return resolved;
1387
- }
1388
-
1389
- // Relativize path: make it relative to resolveDir with leading ./
1390
- let relativePath = normalizePath(
1391
- path.relative( args.resolveDir, resolved.path )
1392
- );
1393
- if ( ! relativePath.startsWith( '.' ) ) {
1394
- relativePath = './' + relativePath;
1395
- }
1396
-
1397
- // Replace extension: make sure that file extension is always `.mjs` or `.cjs`.
1398
- const newExt =
1399
- build.initialOptions.format === 'cjs' ? '.cjs' : '.mjs';
1400
- relativePath = relativePath.replace(
1401
- /\.[cm]?[jt]sx?$/,
1402
- newExt
1403
- );
1404
-
1405
- return {
1406
- path: relativePath,
1407
- external: true,
1408
- };
1347
+ // Relativize path: make it relative to the importer with leading ./
1348
+ let relativePath = normalizePath(
1349
+ path.relative( path.dirname( importer ), resolved.id )
1350
+ );
1351
+ if ( ! relativePath.startsWith( '.' ) ) {
1352
+ relativePath = './' + relativePath;
1409
1353
  }
1410
1354
 
1411
- // Externalize everything else (keep imports as-is)
1412
- return { path: args.path, external: true };
1413
- } );
1355
+ return {
1356
+ id: relativePath,
1357
+ external: true,
1358
+ };
1359
+ }
1360
+
1361
+ // Externalize everything else (keep imports as-is)
1362
+ return { id: source, external: true };
1414
1363
  },
1415
1364
  };
1416
1365
  const plugins = [
@@ -1422,27 +1371,49 @@ async function transpilePackage( packageName ) {
1422
1371
  externalizeJsImportsPlugin,
1423
1372
  ].filter( Boolean );
1424
1373
 
1374
+ /*
1375
+ * Name each entry after its path in `src`, so the output mirrors it. Each
1376
+ * file is built on its own, so the modules it bundles (styles, the style
1377
+ * runtime, SVGs) are inlined into it instead of moved to shared chunks,
1378
+ * which would also reorder their side effects.
1379
+ */
1380
+ const entryPoints = srcFiles.map( ( file ) => ( {
1381
+ [ normalizePath( path.relative( srcDir, file ) ).replace(
1382
+ /\.[^./]+$/,
1383
+ ''
1384
+ ) ]: file,
1385
+ } ) );
1386
+
1387
+ // Make sure that file extension is always `.mjs` or `.cjs`.
1388
+ const replaceExtension = ( extension ) => ( id ) =>
1389
+ id.startsWith( '.' ) ? id.replace( /\.[cm]?[jt]sx?$/, extension ) : id;
1390
+
1425
1391
  if ( packageJson.main ) {
1426
- builds.push(
1427
- esbuild.build( {
1428
- loader: LOADER_CONFIG,
1429
- entryPoints: srcFiles,
1430
- outdir: buildDir,
1431
- outbase: srcDir,
1432
- outExtension: { '.js': '.cjs' },
1433
- bundle: true,
1434
- // Emit UTF-8 so binary-encoded inlined WASM stays compact
1435
- // (ASCII output would escape high bytes as \uXXXX).
1436
- charset: 'utf8',
1437
- platform: 'node',
1438
- format: 'cjs',
1439
- sourcemap: true,
1440
- target,
1441
- jsx: 'automatic',
1442
- jsxImportSource: 'react',
1443
- plugins,
1444
- } )
1445
- );
1392
+ for ( const input of entryPoints ) {
1393
+ builds.push(
1394
+ buildWithConcurrency( {
1395
+ moduleTypes: LOADER_CONFIG,
1396
+ checks: BASE_CHECKS,
1397
+ input,
1398
+ platform: 'node',
1399
+ transform: { target, jsx: JSX_OPTIONS },
1400
+ // Every import is kept, as the imported files are transpiled on their own.
1401
+ treeshake: { moduleSideEffects: true },
1402
+ plugins: [ ...plugins, esModuleInteropPlugin ],
1403
+ output: {
1404
+ dir: buildDir,
1405
+ entryFileNames: '[name].cjs',
1406
+ codeSplitting: false,
1407
+ paths: replaceExtension( '.cjs' ),
1408
+ format: 'cjs',
1409
+ esModule: true,
1410
+ strict: true,
1411
+ exports: 'named',
1412
+ sourcemap: true,
1413
+ },
1414
+ } )
1415
+ );
1416
+ }
1446
1417
 
1447
1418
  for ( const assetFile of assetFiles ) {
1448
1419
  const relativePath = path.relative( srcDir, assetFile );
@@ -1457,26 +1428,28 @@ async function transpilePackage( packageName ) {
1457
1428
  }
1458
1429
 
1459
1430
  if ( packageJson.module ) {
1460
- builds.push(
1461
- esbuild.build( {
1462
- loader: LOADER_CONFIG,
1463
- entryPoints: srcFiles,
1464
- outdir: buildModuleDir,
1465
- outbase: srcDir,
1466
- outExtension: { '.js': '.mjs' },
1467
- bundle: true,
1468
- // Emit UTF-8 so binary-encoded inlined WASM stays compact
1469
- // (ASCII output would escape high bytes as \uXXXX).
1470
- charset: 'utf8',
1471
- platform: 'neutral',
1472
- format: 'esm',
1473
- sourcemap: true,
1474
- target,
1475
- jsx: 'automatic',
1476
- jsxImportSource: 'react',
1477
- plugins,
1478
- } )
1479
- );
1431
+ for ( const input of entryPoints ) {
1432
+ builds.push(
1433
+ buildWithConcurrency( {
1434
+ moduleTypes: LOADER_CONFIG,
1435
+ checks: BASE_CHECKS,
1436
+ input,
1437
+ platform: 'neutral',
1438
+ transform: { target, jsx: JSX_OPTIONS },
1439
+ // Every import is kept, as the imported files are transpiled on their own.
1440
+ treeshake: { moduleSideEffects: true },
1441
+ plugins,
1442
+ output: {
1443
+ dir: buildModuleDir,
1444
+ entryFileNames: '[name].mjs',
1445
+ codeSplitting: false,
1446
+ paths: replaceExtension( '.mjs' ),
1447
+ format: 'esm',
1448
+ sourcemap: true,
1449
+ },
1450
+ } )
1451
+ );
1452
+ }
1480
1453
 
1481
1454
  for ( const jsonFile of assetFiles ) {
1482
1455
  const relativePath = path.relative( srcDir, jsonFile );
@@ -1566,56 +1539,36 @@ async function compileStyles( packageName ) {
1566
1539
 
1567
1540
  await mkdir( outputDir, { recursive: true } );
1568
1541
 
1569
- await esbuild.build( {
1570
- entryPoints: [ styleEntryPath ],
1571
- outdir: outputDir,
1572
- bundle: true,
1573
- write: false,
1574
- loader: {
1575
- '.scss': 'css',
1576
- },
1577
- plugins: [
1578
- sassPlugin( {
1579
- embedded: true,
1580
- ...getSassOptions( packageDir ),
1581
- async transform( source ) {
1582
- const ltrResult = await postcss(
1583
- [
1584
- dsTokenFallbacks,
1585
- autoprefixer( {
1586
- grid: true,
1587
- overrideBrowserslist:
1588
- getBrowserslistQueries(),
1589
- } ),
1590
- ].filter( Boolean )
1591
- ).process( source, { from: undefined } );
1592
-
1593
- const rtlResult = await postcss( [
1594
- rtlcss(),
1595
- ] ).process( ltrResult.css, { from: undefined } );
1596
-
1597
- await Promise.all( [
1598
- writeFile(
1599
- path.join(
1600
- outputDir,
1601
- `${ entryName }.css`
1602
- ),
1603
- ltrResult.css
1604
- ),
1605
- writeFile(
1606
- path.join(
1607
- outputDir,
1608
- `${ entryName }-rtl.css`
1609
- ),
1610
- rtlResult.css
1611
- ),
1612
- ] );
1613
-
1614
- return '';
1615
- },
1542
+ const source = await compileStylesheet(
1543
+ styleEntryPath,
1544
+ getSassOptions( packageDir )
1545
+ );
1546
+
1547
+ const ltrResult = await postcss(
1548
+ [
1549
+ dsTokenFallbacks,
1550
+ autoprefixer( {
1551
+ grid: true,
1552
+ overrideBrowserslist: getBrowserslistQueries(),
1616
1553
  } ),
1617
- ],
1618
- } );
1554
+ ].filter( Boolean )
1555
+ ).process( source, { from: undefined } );
1556
+
1557
+ const rtlResult = await postcss( [ rtlcss() ] ).process(
1558
+ ltrResult.css,
1559
+ { from: undefined }
1560
+ );
1561
+
1562
+ await Promise.all( [
1563
+ writeFile(
1564
+ path.join( outputDir, `${ entryName }.css` ),
1565
+ ltrResult.css
1566
+ ),
1567
+ writeFile(
1568
+ path.join( outputDir, `${ entryName }-rtl.css` ),
1569
+ rtlResult.css
1570
+ ),
1571
+ ] );
1619
1572
  } )
1620
1573
  );
1621
1574
 
@@ -1702,15 +1655,16 @@ async function buildRoute( routeName ) {
1702
1655
  if ( routeEntryPoints.length > 0 ) {
1703
1656
  // Build both minified and non-minified versions in parallel
1704
1657
  await Promise.all( [
1705
- esbuild.build( {
1706
- loader: LOADER_CONFIG,
1707
- entryPoints: routeEntryPoints,
1708
- outfile: path.join( outputDir, 'route.min.js' ),
1709
- bundle: true,
1710
- format: 'esm',
1711
- target: getEsbuildTarget(),
1712
- minify: true,
1713
- define: getDefine( false ),
1658
+ buildWithConcurrency( {
1659
+ moduleTypes: LOADER_CONFIG,
1660
+ checks: BASE_CHECKS,
1661
+ input: routeEntryPoints,
1662
+ transform: {
1663
+ target: getEsbuildTarget(),
1664
+ define: getDefine( false ),
1665
+ jsx: JSX_OPTIONS,
1666
+ },
1667
+ resolve: { conditionNames: defaultConditions },
1714
1668
  plugins: [
1715
1669
  styleRuntimeAliasPlugin(),
1716
1670
  wordpressExternalsPlugin(
@@ -1720,17 +1674,23 @@ async function buildRoute( routeName ) {
1720
1674
  true // Generate asset file for minified build
1721
1675
  ),
1722
1676
  ],
1677
+ output: {
1678
+ file: path.join( outputDir, 'route.min.js' ),
1679
+ format: 'esm',
1680
+ minify: true,
1681
+ codeSplitting: false,
1682
+ },
1723
1683
  } ),
1724
- esbuild.build( {
1725
- loader: LOADER_CONFIG,
1726
- entryPoints: routeEntryPoints,
1727
- outfile: path.join( outputDir, 'route.js' ),
1728
- bundle: true,
1729
- format: 'esm',
1730
- target: getEsbuildTarget(),
1731
- minify: false,
1732
- define: getDefine( true ),
1733
- conditions: developmentConditions,
1684
+ buildWithConcurrency( {
1685
+ moduleTypes: LOADER_CONFIG,
1686
+ checks: BASE_CHECKS,
1687
+ input: routeEntryPoints,
1688
+ transform: {
1689
+ target: getEsbuildTarget(),
1690
+ define: getDefine( true ),
1691
+ jsx: JSX_OPTIONS,
1692
+ },
1693
+ resolve: { conditionNames: developmentConditions },
1734
1694
  plugins: [
1735
1695
  styleRuntimeAliasPlugin(),
1736
1696
  wordpressExternalsPlugin(
@@ -1740,6 +1700,12 @@ async function buildRoute( routeName ) {
1740
1700
  false // Skip asset file for non-minified build
1741
1701
  ),
1742
1702
  ],
1703
+ output: {
1704
+ file: path.join( outputDir, 'route.js' ),
1705
+ format: 'esm',
1706
+ minify: false,
1707
+ codeSplitting: false,
1708
+ },
1743
1709
  } ),
1744
1710
  ] );
1745
1711
  }
@@ -1756,15 +1722,16 @@ async function buildRoute( routeName ) {
1756
1722
 
1757
1723
  // Build both minified and non-minified versions in parallel
1758
1724
  await Promise.all( [
1759
- esbuild.build( {
1760
- loader: LOADER_CONFIG,
1761
- entryPoints: [ tempEntryPath ],
1762
- outfile: path.join( outputDir, 'content.min.js' ),
1763
- bundle: true,
1764
- format: 'esm',
1765
- target: getEsbuildTarget(),
1766
- minify: true,
1767
- define: getDefine( false ),
1725
+ buildWithConcurrency( {
1726
+ moduleTypes: LOADER_CONFIG,
1727
+ checks: BASE_CHECKS,
1728
+ input: [ tempEntryPath ],
1729
+ transform: {
1730
+ target: getEsbuildTarget(),
1731
+ define: getDefine( false ),
1732
+ jsx: JSX_OPTIONS,
1733
+ },
1734
+ resolve: { conditionNames: defaultConditions },
1768
1735
  plugins: [
1769
1736
  ...createStyleBundlingPlugins( routeDir ),
1770
1737
  wordpressExternalsPlugin(
@@ -1774,17 +1741,23 @@ async function buildRoute( routeName ) {
1774
1741
  true // Generate asset file for minified build
1775
1742
  ),
1776
1743
  ],
1744
+ output: {
1745
+ file: path.join( outputDir, 'content.min.js' ),
1746
+ format: 'esm',
1747
+ minify: true,
1748
+ codeSplitting: false,
1749
+ },
1777
1750
  } ),
1778
- esbuild.build( {
1779
- loader: LOADER_CONFIG,
1780
- entryPoints: [ tempEntryPath ],
1781
- outfile: path.join( outputDir, 'content.js' ),
1782
- bundle: true,
1783
- format: 'esm',
1784
- target: getEsbuildTarget(),
1785
- minify: false,
1786
- define: getDefine( true ),
1787
- conditions: developmentConditions,
1751
+ buildWithConcurrency( {
1752
+ moduleTypes: LOADER_CONFIG,
1753
+ checks: BASE_CHECKS,
1754
+ input: [ tempEntryPath ],
1755
+ transform: {
1756
+ target: getEsbuildTarget(),
1757
+ define: getDefine( true ),
1758
+ jsx: JSX_OPTIONS,
1759
+ },
1760
+ resolve: { conditionNames: developmentConditions },
1788
1761
  plugins: [
1789
1762
  ...createStyleBundlingPlugins( routeDir ),
1790
1763
  wordpressExternalsPlugin(
@@ -1794,6 +1767,12 @@ async function buildRoute( routeName ) {
1794
1767
  false // Skip asset file for non-minified build
1795
1768
  ),
1796
1769
  ],
1770
+ output: {
1771
+ file: path.join( outputDir, 'content.js' ),
1772
+ format: 'esm',
1773
+ minify: false,
1774
+ codeSplitting: false,
1775
+ },
1797
1776
  } ),
1798
1777
  ] );
1799
1778
 
@@ -1869,15 +1848,16 @@ async function buildWidget( widgetName ) {
1869
1848
  if ( renderEntryPoints.length > 0 ) {
1870
1849
  // Build both minified and non-minified versions in parallel
1871
1850
  await Promise.all( [
1872
- esbuild.build( {
1873
- loader: LOADER_CONFIG,
1874
- entryPoints: renderEntryPoints,
1875
- outfile: path.join( outputDir, 'render.min.js' ),
1876
- bundle: true,
1877
- format: 'esm',
1878
- target: getEsbuildTarget(),
1879
- minify: true,
1880
- define: getDefine( false ),
1851
+ buildWithConcurrency( {
1852
+ moduleTypes: LOADER_CONFIG,
1853
+ checks: BASE_CHECKS,
1854
+ input: renderEntryPoints,
1855
+ transform: {
1856
+ target: getEsbuildTarget(),
1857
+ define: getDefine( false ),
1858
+ jsx: JSX_OPTIONS,
1859
+ },
1860
+ resolve: { conditionNames: defaultConditions },
1881
1861
  plugins: [
1882
1862
  ...createStyleBundlingPlugins( widgetDir ),
1883
1863
  wordpressExternalsPlugin(
@@ -1887,17 +1867,23 @@ async function buildWidget( widgetName ) {
1887
1867
  true // Generate asset file for minified build
1888
1868
  ),
1889
1869
  ],
1870
+ output: {
1871
+ file: path.join( outputDir, 'render.min.js' ),
1872
+ format: 'esm',
1873
+ minify: true,
1874
+ codeSplitting: false,
1875
+ },
1890
1876
  } ),
1891
- esbuild.build( {
1892
- loader: LOADER_CONFIG,
1893
- entryPoints: renderEntryPoints,
1894
- outfile: path.join( outputDir, 'render.js' ),
1895
- bundle: true,
1896
- format: 'esm',
1897
- target: getEsbuildTarget(),
1898
- minify: false,
1899
- define: getDefine( true ),
1900
- conditions: developmentConditions,
1877
+ buildWithConcurrency( {
1878
+ moduleTypes: LOADER_CONFIG,
1879
+ checks: BASE_CHECKS,
1880
+ input: renderEntryPoints,
1881
+ transform: {
1882
+ target: getEsbuildTarget(),
1883
+ define: getDefine( true ),
1884
+ jsx: JSX_OPTIONS,
1885
+ },
1886
+ resolve: { conditionNames: developmentConditions },
1901
1887
  plugins: [
1902
1888
  ...createStyleBundlingPlugins( widgetDir ),
1903
1889
  wordpressExternalsPlugin(
@@ -1907,6 +1893,12 @@ async function buildWidget( widgetName ) {
1907
1893
  false // Skip asset file for non-minified build
1908
1894
  ),
1909
1895
  ],
1896
+ output: {
1897
+ file: path.join( outputDir, 'render.js' ),
1898
+ format: 'esm',
1899
+ minify: false,
1900
+ codeSplitting: false,
1901
+ },
1910
1902
  } ),
1911
1903
  ] );
1912
1904
  }
@@ -1922,15 +1914,16 @@ async function buildWidget( widgetName ) {
1922
1914
  if ( widgetEntryPoints.length > 0 ) {
1923
1915
  // Build both minified and non-minified versions in parallel
1924
1916
  await Promise.all( [
1925
- esbuild.build( {
1926
- loader: LOADER_CONFIG,
1927
- entryPoints: widgetEntryPoints,
1928
- outfile: path.join( outputDir, 'widget.min.js' ),
1929
- bundle: true,
1930
- format: 'esm',
1931
- target: getEsbuildTarget(),
1932
- minify: true,
1933
- define: getDefine( false ),
1917
+ buildWithConcurrency( {
1918
+ moduleTypes: LOADER_CONFIG,
1919
+ checks: BASE_CHECKS,
1920
+ input: widgetEntryPoints,
1921
+ transform: {
1922
+ target: getEsbuildTarget(),
1923
+ define: getDefine( false ),
1924
+ jsx: JSX_OPTIONS,
1925
+ },
1926
+ resolve: { conditionNames: defaultConditions },
1934
1927
  plugins: [
1935
1928
  styleRuntimeAliasPlugin(),
1936
1929
  wordpressExternalsPlugin(
@@ -1940,17 +1933,23 @@ async function buildWidget( widgetName ) {
1940
1933
  true // Generate asset file for minified build
1941
1934
  ),
1942
1935
  ],
1936
+ output: {
1937
+ file: path.join( outputDir, 'widget.min.js' ),
1938
+ format: 'esm',
1939
+ minify: true,
1940
+ codeSplitting: false,
1941
+ },
1943
1942
  } ),
1944
- esbuild.build( {
1945
- loader: LOADER_CONFIG,
1946
- entryPoints: widgetEntryPoints,
1947
- outfile: path.join( outputDir, 'widget.js' ),
1948
- bundle: true,
1949
- format: 'esm',
1950
- target: getEsbuildTarget(),
1951
- minify: false,
1952
- define: getDefine( true ),
1953
- conditions: developmentConditions,
1943
+ buildWithConcurrency( {
1944
+ moduleTypes: LOADER_CONFIG,
1945
+ checks: BASE_CHECKS,
1946
+ input: widgetEntryPoints,
1947
+ transform: {
1948
+ target: getEsbuildTarget(),
1949
+ define: getDefine( true ),
1950
+ jsx: JSX_OPTIONS,
1951
+ },
1952
+ resolve: { conditionNames: developmentConditions },
1954
1953
  plugins: [
1955
1954
  styleRuntimeAliasPlugin(),
1956
1955
  wordpressExternalsPlugin(
@@ -1960,6 +1959,12 @@ async function buildWidget( widgetName ) {
1960
1959
  false // Skip asset file for non-minified build
1961
1960
  ),
1962
1961
  ],
1962
+ output: {
1963
+ file: path.join( outputDir, 'widget.js' ),
1964
+ format: 'esm',
1965
+ minify: false,
1966
+ codeSplitting: false,
1967
+ },
1963
1968
  } ),
1964
1969
  ] );
1965
1970
  }
@@ -2001,7 +2006,7 @@ async function buildAllWidgets() {
2001
2006
  * Discover all widgets and collect their registry-facing data.
2002
2007
  * Widgets without a valid widget.json are skipped.
2003
2008
  *
2004
- * @return {Array<{ name: string, dirName: string, title: string | null, description: string | null, help: import('./widget-utils.mjs').WidgetHelpMetadata | null, icon: string | null, actions: import('./widget-utils.mjs').WidgetActionMetadata[] | null, attributes: import('./widget-utils.mjs').WidgetAttributeMetadata[] | null, hasRender: boolean, hasWidget: boolean, presentation: string | null, category: string | null, keywords: string[] | null, textdomain: string | null }>} Array of widget objects.
2009
+ * @return {Array<{ name: string, dirName: string, title: string | null, description: string | null, help: import('./widget-utils.mjs').WidgetHelpMetadata | null, icon: string | null, actions: import('./widget-utils.mjs').WidgetActionMetadata[] | null, attributes: import('./widget-utils.mjs').WidgetAttributeMetadata[] | null, example: import('./widget-utils.mjs').WidgetExampleMetadata | null, hasRender: boolean, hasWidget: boolean, presentation: string | null, category: string | null, keywords: string[] | null, textdomain: string | null }>} Array of widget objects.
2005
2010
  */
2006
2011
  function collectWidgets() {
2007
2012
  return getAllWidgets( ROOT_DIR ).flatMap( ( widgetName ) => {
@@ -2026,6 +2031,7 @@ function collectWidgets() {
2026
2031
  icon: metadata.icon ?? null,
2027
2032
  actions: metadata.actions ?? null,
2028
2033
  attributes: metadata.attributes ?? null,
2034
+ example: metadata.example ?? null,
2029
2035
  hasRender: widgetFiles.hasRender,
2030
2036
  hasWidget: widgetFiles.hasWidget,
2031
2037
  presentation: metadata.presentation ?? null,
@@ -2236,6 +2242,29 @@ function toPhpAttributesLiteral( attributes ) {
2236
2242
  return `array( ${ entries.join( ', ' ) } )`;
2237
2243
  }
2238
2244
 
2245
+ /**
2246
+ * Format a widget's example as a PHP array literal: `attributes` copied as
2247
+ * declared, with the registration gate constraining the values. Returns the
2248
+ * PHP literal `null` unless `example` carries a non-empty `attributes`
2249
+ * object.
2250
+ *
2251
+ * @param {import('./widget-utils.mjs').WidgetExampleMetadata|null|undefined} example Source value.
2252
+ * @return {string} PHP array literal, or `null`.
2253
+ */
2254
+ function toPhpExampleLiteral( example ) {
2255
+ const attributes = example?.attributes;
2256
+ if (
2257
+ ! attributes ||
2258
+ typeof attributes !== 'object' ||
2259
+ Array.isArray( attributes ) ||
2260
+ Object.keys( attributes ).length === 0
2261
+ ) {
2262
+ return 'null';
2263
+ }
2264
+
2265
+ return toPhpValueLiteral( { attributes } );
2266
+ }
2267
+
2239
2268
  /**
2240
2269
  * Generate global widget registry file.
2241
2270
  * Creates a single registry with all widgets including file availability.
@@ -2264,6 +2293,7 @@ async function generateWidgetRegistry( widgets, replacements ) {
2264
2293
  const iconStr = toPhpStringLiteral( widget.icon );
2265
2294
  const actionsStr = toPhpActionsLiteral( widget.actions );
2266
2295
  const attributesStr = toPhpAttributesLiteral( widget.attributes );
2296
+ const exampleStr = toPhpExampleLiteral( widget.example );
2267
2297
  const keywordsStr = toPhpStringArrayLiteral( widget.keywords );
2268
2298
  const textdomainStr = toPhpStringLiteral( widget.textdomain );
2269
2299
  return `\tarray(
@@ -2275,6 +2305,7 @@ async function generateWidgetRegistry( widgets, replacements ) {
2275
2305
  'icon' => ${ iconStr },
2276
2306
  'actions' => ${ actionsStr },
2277
2307
  'attributes' => ${ attributesStr },
2308
+ 'example' => ${ exampleStr },
2278
2309
  'has_render' => ${ hasRenderStr },
2279
2310
  'has_widget' => ${ hasWidgetStr },
2280
2311
  'presentation' => ${ presentationStr },
@@ -2561,6 +2592,7 @@ async function watchMode() {
2561
2592
  * Rebuild a package and any affected scripts/modules.
2562
2593
  *
2563
2594
  * @param {string} packageName Package to rebuild (short name).
2595
+ * @return {Promise<boolean>} Whether the package itself was rebuilt.
2564
2596
  */
2565
2597
  async function rebuildPackage( packageName ) {
2566
2598
  try {
@@ -2617,8 +2649,10 @@ async function watchMode() {
2617
2649
  );
2618
2650
  }
2619
2651
  }
2652
+ return true;
2620
2653
  } catch ( error ) {
2621
2654
  console.log( `❌ ${ packageName } - Error: ${ error.message }` );
2655
+ return false;
2622
2656
  }
2623
2657
  }
2624
2658
 
@@ -2640,6 +2674,58 @@ async function watchMode() {
2640
2674
  }
2641
2675
  }
2642
2676
 
2677
+ /**
2678
+ * Copy a changed PHP file to the build, without rebuilding its package.
2679
+ *
2680
+ * @param {string} filename Absolute path of the PHP file.
2681
+ */
2682
+ async function recopyPhpFile( filename ) {
2683
+ const packageName = getPackageName( filename );
2684
+ const relativePath = path.relative( PACKAGES_DIR, filename );
2685
+ try {
2686
+ const startTime = Date.now();
2687
+ await copyPackageFile(
2688
+ filename,
2689
+ path.join( PACKAGES_DIR, packageName ),
2690
+ path.join( BUILD_DIR, 'scripts', packageName ),
2691
+ fullToPackageJson.get( shortToFull.get( packageName ) )
2692
+ );
2693
+ const copyTime = Date.now() - startTime;
2694
+ console.log( `✅ ${ relativePath } (copied) (${ copyTime }ms)` );
2695
+ } catch ( error ) {
2696
+ // The file was removed since; its removal rebuilds the package.
2697
+ if ( error.code === 'ENOENT' ) {
2698
+ return;
2699
+ }
2700
+ console.log( `❌ ${ relativePath } - Error: ${ error.message }` );
2701
+ }
2702
+ }
2703
+
2704
+ /*
2705
+ * The PHP files each package copies to the build with `wpCopyFiles`, by
2706
+ * package name. Only the build's copy of such a file depends on it, so a
2707
+ * change to it needs the file copied again, not its package rebuilt.
2708
+ */
2709
+ const copiedPhpFiles = new Map();
2710
+
2711
+ /**
2712
+ * Find the PHP files a package copies to the build with `wpCopyFiles`.
2713
+ *
2714
+ * @param {string} packageName Package name (short name).
2715
+ */
2716
+ async function updateCopiedPhpFiles( packageName ) {
2717
+ const copyFiles = await getCopyFiles(
2718
+ path.join( PACKAGES_DIR, packageName ),
2719
+ fullToPackageJson.get( shortToFull.get( packageName ) )
2720
+ );
2721
+ copiedPhpFiles.set(
2722
+ packageName,
2723
+ new Set( copyFiles.filter( ( file ) => file.endsWith( '.php' ) ) )
2724
+ );
2725
+ }
2726
+
2727
+ await Promise.all( PACKAGES.map( updateCopiedPhpFiles ) );
2728
+
2643
2729
  async function processNextRebuild() {
2644
2730
  if ( needsRebuild.size === 0 ) {
2645
2731
  isRebuilding = false;
@@ -2649,6 +2735,9 @@ async function watchMode() {
2649
2735
  const itemsToRebuild = Array.from( needsRebuild );
2650
2736
  needsRebuild.clear();
2651
2737
 
2738
+ const phpFilesToCopy = [];
2739
+ const rebuiltPackages = new Set();
2740
+
2652
2741
  for ( const item of itemsToRebuild ) {
2653
2742
  // Check if it's a route (prefixed with 'route:')
2654
2743
  if ( item.startsWith( 'route:' ) ) {
@@ -2657,8 +2746,17 @@ async function watchMode() {
2657
2746
  } else if ( item.startsWith( 'widget:' ) ) {
2658
2747
  const widgetDirName = item.slice( 7 ); // Remove 'widget:' prefix
2659
2748
  await rebuildWidget( widgetDirName );
2660
- } else {
2661
- await rebuildPackage( item );
2749
+ } else if ( item.startsWith( 'php:' ) ) {
2750
+ phpFilesToCopy.push( item.slice( 4 ) ); // Remove 'php:' prefix
2751
+ } else if ( await rebuildPackage( item ) ) {
2752
+ rebuiltPackages.add( item );
2753
+ }
2754
+ }
2755
+
2756
+ // Copy the PHP files last, unless a rebuild of their package did.
2757
+ for ( const file of phpFilesToCopy ) {
2758
+ if ( ! rebuiltPackages.has( getPackageName( file ) ) ) {
2759
+ await recopyPhpFile( file );
2662
2760
  }
2663
2761
  }
2664
2762
 
@@ -2700,7 +2798,7 @@ async function watchMode() {
2700
2798
  console.error( '❌ Watcher error:', error );
2701
2799
  } );
2702
2800
 
2703
- const handleFileChange = async ( filename ) => {
2801
+ const handleFileChange = async ( filename, event ) => {
2704
2802
  if ( ! isPackageSourceFile( filename ) ) {
2705
2803
  return;
2706
2804
  }
@@ -2710,19 +2808,47 @@ async function watchMode() {
2710
2808
  return;
2711
2809
  }
2712
2810
 
2811
+ /*
2812
+ * A changed PHP file only needs copying again. An added or removed
2813
+ * one still rebuilds its package, which copies all of its files.
2814
+ */
2815
+ const file = normalizePath( path.resolve( filename ) );
2816
+ const item =
2817
+ event === 'change' && copiedPhpFiles.get( packageName )?.has( file )
2818
+ ? `php:${ file }`
2819
+ : packageName;
2820
+
2821
+ /*
2822
+ * Find the package's copied PHP files again when one may have been
2823
+ * added or removed. Until that finishes, a change to an added file
2824
+ * rebuilds the package, which copies it too.
2825
+ */
2826
+ if ( event !== 'change' && file.endsWith( '.php' ) ) {
2827
+ updateCopiedPhpFiles( packageName ).catch( ( error ) => {
2828
+ console.log(
2829
+ `❌ ${ packageName } - Error finding copied PHP files: ${ error.message }`
2830
+ );
2831
+ } );
2832
+ }
2833
+
2834
+ // Queue the item, so that it is not written while a rebuild is running.
2713
2835
  if ( isRebuilding ) {
2714
- needsRebuild.add( packageName );
2836
+ needsRebuild.add( item );
2715
2837
  return;
2716
2838
  }
2717
2839
 
2718
2840
  isRebuilding = true;
2719
- await rebuildPackage( packageName );
2841
+ needsRebuild.add( item );
2720
2842
  await processNextRebuild();
2721
2843
  };
2722
2844
 
2723
- watcher.on( 'change', handleFileChange );
2724
- watcher.on( 'add', handleFileChange );
2725
- watcher.on( 'unlink', handleFileChange );
2845
+ watcher.on( 'change', ( filename ) =>
2846
+ handleFileChange( filename, 'change' )
2847
+ );
2848
+ watcher.on( 'add', ( filename ) => handleFileChange( filename, 'add' ) );
2849
+ watcher.on( 'unlink', ( filename ) =>
2850
+ handleFileChange( filename, 'unlink' )
2851
+ );
2726
2852
 
2727
2853
  // Watch route files if routes exist
2728
2854
  if ( allRoutes.length > 0 ) {
@@ -2865,12 +2991,17 @@ async function main() {
2865
2991
  } );
2866
2992
 
2867
2993
  const baseUrlExpression = values[ 'base-url' ];
2994
+ const buildConcurrency = getDefaultBuildConcurrency();
2995
+ setBuildConcurrency( buildConcurrency );
2996
+ console.log( `⚙️ Using build concurrency: ${ buildConcurrency }\n` );
2868
2997
 
2869
2998
  await buildAll( baseUrlExpression );
2870
2999
 
2871
3000
  if ( values.watch ) {
2872
3001
  console.log( '\n👀 Watching for changes...\n' );
2873
3002
  await watchMode();
3003
+ } else {
3004
+ await disposeSassCompiler();
2874
3005
  }
2875
3006
  }
2876
3007