@wordpress/build 0.26.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.
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,
@@ -48,6 +47,12 @@ import {
48
47
  compileInlineStyle,
49
48
  dsTokenFallbacks,
50
49
  } from './compile-inline-style.mjs';
50
+ import { compileStylesheet, disposeSassCompiler } from './sass-compiler.mjs';
51
+ import {
52
+ buildWithConcurrency,
53
+ getDefaultBuildConcurrency,
54
+ setBuildConcurrency,
55
+ } from './build-concurrency.mjs';
51
56
 
52
57
  /**
53
58
  * Resolve the ESBuild target from the project's Browserslist config.
@@ -57,24 +62,15 @@ import {
57
62
  function getEsbuildTarget() {
58
63
  return browserslistToEsbuild( getBrowserslistQueries() );
59
64
  }
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
- }
65
+ // The Vite-only `enforce` property is not a Rolldown plugin property.
66
+ const { enforce, ...dsTokenFallbacksJs } = createDsTokenFallbacksPlugin();
71
67
 
72
68
  const ROOT_DIR = process.cwd();
73
69
  const PACKAGES_DIR = path.join( ROOT_DIR, 'packages' );
74
70
  const BUILD_DIR = path.join( ROOT_DIR, 'build' );
75
71
 
76
72
  /**
77
- * esbuild loaders for non-JS imports. SVG files are inlined as `data:` URIs.
73
+ * Module types for non-JS imports. SVG files are inlined as `data:` URIs.
78
74
  */
79
75
  const LOADER_CONFIG = { '.svg': 'dataurl' };
80
76
  const ASSET_EXTENSIONS = 'json';
@@ -142,8 +138,41 @@ const baseDefine = {
142
138
  false
143
139
  ),
144
140
  };
145
- // Keep esbuild's module condition when enabling development exports.
146
- const developmentConditions = [ 'development', 'module' ];
141
+ // Rolldown's default conditions lack esbuild's module condition.
142
+ const defaultConditions = [ 'module', 'browser', 'default' ];
143
+ const developmentConditions = [ 'development', ...defaultConditions ];
144
+ /*
145
+ * The `jsx` option overrides the tsconfig's `jsx`, which is `preserve` for the
146
+ * type checker.
147
+ */
148
+ const JSX_OPTIONS = { runtime: 'automatic', importSource: 'react' };
149
+ const BASE_CHECKS = {
150
+ configurationFieldConflict: false,
151
+ // Don't warn about directives like 'use client' in bundled dependencies.
152
+ moduleLevelDirective: false,
153
+ };
154
+ // Rolldown's `__toESM` gives namespace imports a `default` unless the module has
155
+ // its own, even when flagged `__esModule`. Follow the flag alone, like esbuild.
156
+ const TO_ESM_OWN_DEFAULT_CHECK = ' || !__hasOwnProp.call(mod, "default")';
157
+ const esModuleInteropPlugin = {
158
+ name: 'es-module-interop',
159
+ renderChunk( code ) {
160
+ if ( ! code.includes( 'var __toESM = ' ) ) {
161
+ return null;
162
+ }
163
+ if ( ! code.includes( TO_ESM_OWN_DEFAULT_CHECK ) ) {
164
+ throw new Error( 'Unexpected Rolldown `__toESM` helper.' );
165
+ }
166
+ // A same-length replacement keeps the source map valid.
167
+ return {
168
+ code: code.replace(
169
+ TO_ESM_OWN_DEFAULT_CHECK,
170
+ ' '.repeat( TO_ESM_OWN_DEFAULT_CHECK.length )
171
+ ),
172
+ map: null,
173
+ };
174
+ },
175
+ };
147
176
  const getDefine = ( scriptDebug ) => ( {
148
177
  ...baseDefine,
149
178
  'globalThis.SCRIPT_DEBUG': JSON.stringify( scriptDebug ),
@@ -177,11 +206,9 @@ const STYLE_RUNTIME_ENTRY = path.join(
177
206
  function styleRuntimeAliasPlugin() {
178
207
  return {
179
208
  name: 'style-runtime-alias',
180
- setup( build ) {
181
- build.onResolve(
182
- { filter: /^@wordpress\/style-runtime$/ },
183
- () => ( { path: STYLE_RUNTIME_ENTRY } )
184
- );
209
+ resolveId: {
210
+ filter: { id: /^@wordpress\/style-runtime$/ },
211
+ handler: () => STYLE_RUNTIME_ENTRY,
185
212
  },
186
213
  };
187
214
  }
@@ -210,16 +237,41 @@ function getSassOptions( workingDir ) {
210
237
  };
211
238
  }
212
239
 
213
- function inlineStyle( contents ) {
214
- // The `contents` is already a JS code created by `compileInlineStyle`.
215
- return contents;
240
+ /**
241
+ * Plugin compiling stylesheets with Sass into JS code, created by `transform`
242
+ * from the CSS.
243
+ *
244
+ * @param {Object} options Plugin options, along with the Sass options.
245
+ * @param {RegExp} options.filter Stylesheets to compile.
246
+ * @param {(css: string, resolveDir: string, filePath: string) => Promise<string>} options.transform Transforms the CSS into JS code.
247
+ * @return {import('rolldown').Plugin} Rolldown plugin.
248
+ */
249
+ function sassPlugin( { filter, transform, ...sassOptions } ) {
250
+ // Files transpiled on their own share the plugin, and often a stylesheet.
251
+ const cache = new Map();
252
+ const compile = async ( id ) => {
253
+ const css = await compileStylesheet( id, sassOptions );
254
+ return transform( css, path.dirname( id ), id );
255
+ };
256
+ return {
257
+ name: 'sass',
258
+ load: {
259
+ filter: { id: filter },
260
+ async handler( id ) {
261
+ if ( ! cache.has( id ) ) {
262
+ cache.set( id, compile( id ) );
263
+ }
264
+ return { code: await cache.get( id ), moduleType: 'js' };
265
+ },
266
+ },
267
+ };
216
268
  }
217
269
 
218
270
  /**
219
271
  * Create style bundling plugins with the given working directory.
220
272
  *
221
273
  * @param {string} workingDir - The directory where we're working (for NodePackageImporter).
222
- * @return {object[]} Array of esbuild plugins for handling CSS/SCSS.
274
+ * @return {import('rolldown').Plugin[]} Array of Rolldown plugins for handling CSS/SCSS.
223
275
  */
224
276
  function createStyleBundlingPlugins( workingDir ) {
225
277
  const sassOptions = getSassOptions( workingDir );
@@ -227,21 +279,15 @@ function createStyleBundlingPlugins( workingDir ) {
227
279
  styleRuntimeAliasPlugin(),
228
280
  // Handle CSS modules (.module.css and .module.scss)
229
281
  sassPlugin( {
230
- embedded: true,
231
- sourceMap: false,
232
282
  filter: /\.module\.(css|scss)$/,
233
283
  transform: compileInlineStyle( { cssModules: true } ),
234
- type: inlineStyle,
235
284
  ...sassOptions,
236
285
  } ),
237
286
  // Handle regular CSS/SCSS files
238
287
  // Note: .module.css and .module.scss already handled by plugin above
239
288
  sassPlugin( {
240
- embedded: true,
241
- sourceMap: false,
242
289
  filter: /\.(css|scss)$/,
243
290
  transform: compileInlineStyle(),
244
- type: inlineStyle,
245
291
  ...sassOptions,
246
292
  } ),
247
293
  ];
@@ -303,6 +349,8 @@ function binaryEncode( data ) {
303
349
  return Buffer.from( out ).toString( 'utf8' );
304
350
  }
305
351
 
352
+ const WASM_INLINE_PREFIX = '\0wasm-inline:';
353
+
306
354
  /**
307
355
  * Plugin to inline WASM files into the bundle.
308
356
  *
@@ -311,55 +359,53 @@ function binaryEncode( data ) {
311
359
  * embedded using a compact UTF-8 encoding (rather than base64) so it compresses
312
360
  * well, and is decoded back to a `Uint8Array` at runtime.
313
361
  *
314
- * @return {Object} esbuild plugin.
362
+ * @type {import('rolldown').Plugin}
315
363
  */
316
364
  const wasmInlinePlugin = {
317
365
  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
- }
366
+ // Resolve .wasm imports from node_modules, like 'wasm-vips/vips.wasm'.
367
+ resolveId: {
368
+ filter: { id: /^[^.].*\.wasm$/ },
369
+ handler( source, importer ) {
370
+ const require = createNodeRequire(
371
+ importer ?? path.join( ROOT_DIR, 'index.js' )
372
+ );
373
+ try {
374
+ // A path relative to the root keeps the checkout path out of
375
+ // the source map.
376
+ return (
377
+ WASM_INLINE_PREFIX +
378
+ normalizePath(
379
+ path.relative( ROOT_DIR, require.resolve( source ) )
380
+ )
381
+ );
382
+ } catch {
383
+ // If resolution fails, let other plugins handle it.
384
+ return null;
338
385
  }
339
- return null;
340
- } );
386
+ },
387
+ },
341
388
 
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 );
389
+ // Load WASM files, embed them as a compact UTF-8 string, and decode
390
+ // back to a Uint8Array at runtime.
391
+ load: {
392
+ filter: { id: /^\0wasm-inline:/ },
393
+ async handler( id ) {
394
+ const wasmBuffer = await readFile(
395
+ path.join( ROOT_DIR, id.slice( WASM_INLINE_PREFIX.length ) )
396
+ );
397
+ const encoded = binaryEncode( wasmBuffer );
351
398
 
352
- return {
353
- contents: `const s = ${ encoded };
399
+ return {
400
+ code: `const s = ${ encoded };
354
401
  const bytes = new Uint8Array( s.length );
355
402
  for ( let i = 0; i < s.length; i++ ) {
356
403
  bytes[ i ] = s.charCodeAt( i );
357
404
  }
358
405
  export default bytes;`,
359
- loader: 'js',
360
- };
361
- }
362
- );
406
+ moduleType: 'js',
407
+ };
408
+ },
363
409
  },
364
410
  };
365
411
 
@@ -436,41 +482,37 @@ function transformPhpContent( content, transforms ) {
436
482
  * Plugin to handle moment-timezone aliases.
437
483
  * Redirects moment-timezone imports to use pre-built bundles with limited data.
438
484
  *
439
- * @return {Object} esbuild plugin.
485
+ * @return {import('rolldown').Plugin} Rolldown plugin.
440
486
  */
441
487
  function momentTimezoneAliasPlugin() {
442
488
  return {
443
489
  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,
490
+ resolveId: {
491
+ filter: { id: /^(moment-timezone\/moment-timezone\.js|\.\/)$/ },
492
+ handler( source, importer, { kind } ) {
493
+ // Alias path that Rolldown will resolve
494
+ const aliasPath =
495
+ 'moment-timezone/builds/moment-timezone-with-data-1970-2030.js';
496
+
497
+ // Redirect main moment-timezone files to pre-built bundle
498
+ if ( source === 'moment-timezone/moment-timezone.js' ) {
499
+ return this.resolve( aliasPath, importer, {
456
500
  kind,
457
- } )
458
- );
501
+ skipSelf: true,
502
+ } );
503
+ }
459
504
 
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
- }
505
+ // Intercept the require('./') call inside moment-timezone-utils
506
+ // and redirect it to the pre-built bundle.
507
+ if ( importer?.includes( 'moment-timezone-utils' ) ) {
508
+ return this.resolve( aliasPath, importer, {
509
+ kind,
510
+ skipSelf: true,
511
+ } );
472
512
  }
473
- );
513
+
514
+ return null;
515
+ },
474
516
  },
475
517
  };
476
518
  }
@@ -515,7 +557,48 @@ function resolveEntryPoint( packageDir, packageJson ) {
515
557
  }
516
558
 
517
559
  /**
518
- * Bundle a package for WordPress using esbuild.
560
+ * Rolldown plugin that exposes a classic script's exports on the global,
561
+ * e.g. `window.wp.blocks`.
562
+ *
563
+ * Its `outro` runs at the end of the bundle's function, whose `exports`
564
+ * parameter holds the entry's exports as data properties. A CommonJS entry's
565
+ * `module.exports` is its default export.
566
+ *
567
+ * @param {string} scriptGlobal Global variable name, e.g. `wp`.
568
+ * @param {string} globalMember Member of the global variable, e.g. `blocks`.
569
+ * @param {boolean} exposeDefault Whether to expose the default export instead of the exports.
570
+ * @return {import('rolldown').Plugin} Rolldown plugin.
571
+ */
572
+ function scriptGlobalPlugin( scriptGlobal, globalMember, exposeDefault ) {
573
+ return {
574
+ name: 'script-global',
575
+ outro( chunk ) {
576
+ if ( ! chunk.isEntry ) {
577
+ return '';
578
+ }
579
+ const assign = ( value ) =>
580
+ `(window.${ scriptGlobal } ||= {}).${ globalMember } = ${ value };`;
581
+ // The bundle's function has no `exports` parameter without exports.
582
+ if ( chunk.exports.length === 0 ) {
583
+ return assign( 'undefined' );
584
+ }
585
+ const { inputFormat } = this.getModuleInfo( chunk.facadeModuleId );
586
+ if (
587
+ ( exposeDefault || inputFormat === 'cjs' ) &&
588
+ chunk.exports.includes( 'default' )
589
+ ) {
590
+ return assign( 'exports.default' );
591
+ }
592
+ return [
593
+ "Object.defineProperty(exports, '__esModule', { value: true });",
594
+ assign( 'exports' ),
595
+ ].join( '\n' );
596
+ },
597
+ };
598
+ }
599
+
600
+ /**
601
+ * Bundle a package for WordPress using Rolldown.
519
602
  *
520
603
  * @param {string} packageName Package name.
521
604
  * @param {Object} options Optional bundling options.
@@ -551,60 +634,57 @@ async function bundlePackage( packageName, options = {} ) {
551
634
  );
552
635
  const shouldExposeGlobal = matchesNamespace && scriptGlobal !== false;
553
636
 
554
- const globalName = shouldExposeGlobal
555
- ? `${ scriptGlobal }.${ camelCase( packageName ) }`
556
- : undefined;
557
-
558
637
  const baseConfig = {
559
- entryPoints: [ entryPoint ],
560
- bundle: true,
561
- loader: LOADER_CONFIG,
562
- sourcemap: true,
563
- format: 'iife',
564
- target,
638
+ input: entryPoint,
639
+ moduleTypes: LOADER_CONFIG,
565
640
  platform: 'browser',
566
- globalName,
641
+ checks: {
642
+ ...BASE_CHECKS,
643
+ // The script global plugin exposes the exports, not `output.name`.
644
+ missingNameOptionForIifeExport: false,
645
+ },
567
646
  };
568
647
 
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 };
648
+ const baseOutput = {
649
+ sourcemap: true,
650
+ format: 'iife',
651
+ codeSplitting: false,
652
+ exports: 'named',
653
+ /*
654
+ * Keep the `'use strict'` directive for the (strict) ES module code inside
655
+ * the bundle's function. Left at the top of the file it is a *file-level*
656
+ * directive, which — because load-scripts.php concatenates raw file
657
+ * contents — forces strict mode onto any sloppy-mode script bundled after
658
+ * it, throwing on e.g. implicit globals.
659
+ * See https://core.trac.wordpress.org/ticket/65515.
660
+ */
661
+ strict: false,
662
+ intro: '"use strict";',
663
+ // The script global plugin adds it, only when there are exports.
664
+ esModule: false,
665
+ generatedCode: { symbols: false },
666
+ };
596
667
 
597
668
  const baseBundlePlugins = [
598
669
  momentTimezoneAliasPlugin(),
599
670
  styleRuntimeAliasPlugin(),
671
+ shouldExposeGlobal &&
672
+ scriptGlobalPlugin(
673
+ scriptGlobal,
674
+ camelCase( packageName ),
675
+ !! packageJson.wpScriptDefaultExport
676
+ ),
600
677
  ];
601
678
 
602
679
  builds.push(
603
- esbuild.build( {
680
+ buildWithConcurrency( {
604
681
  ...baseConfig,
605
- outfile: path.join( outputDir, 'index.min.js' ),
606
- minify: true,
607
- define: getDefine( false ),
682
+ transform: {
683
+ target,
684
+ define: getDefine( false ),
685
+ jsx: JSX_OPTIONS,
686
+ },
687
+ resolve: { conditionNames: defaultConditions },
608
688
  plugins: [
609
689
  ...baseBundlePlugins,
610
690
  wordpressExternalsPlugin(
@@ -614,13 +694,20 @@ async function bundlePackage( packageName, options = {} ) {
614
694
  true // Generate asset file for minified build
615
695
  ),
616
696
  ],
697
+ output: {
698
+ ...baseOutput,
699
+ file: path.join( outputDir, 'index.min.js' ),
700
+ minify: true,
701
+ },
617
702
  } ),
618
- esbuild.build( {
703
+ buildWithConcurrency( {
619
704
  ...baseConfig,
620
- outfile: path.join( outputDir, 'index.js' ),
621
- minify: false,
622
- define: getDefine( true ),
623
- conditions: developmentConditions,
705
+ transform: {
706
+ target,
707
+ define: getDefine( true ),
708
+ jsx: JSX_OPTIONS,
709
+ },
710
+ resolve: { conditionNames: developmentConditions },
624
711
  plugins: [
625
712
  ...baseBundlePlugins,
626
713
  wordpressExternalsPlugin(
@@ -630,6 +717,11 @@ async function bundlePackage( packageName, options = {} ) {
630
717
  false // Skip asset file for non-minified build
631
718
  ),
632
719
  ],
720
+ output: {
721
+ ...baseOutput,
722
+ file: path.join( outputDir, 'index.js' ),
723
+ minify: false,
724
+ },
633
725
  } )
634
726
  );
635
727
 
@@ -671,24 +763,17 @@ async function bundlePackage( packageName, options = {} ) {
671
763
  );
672
764
 
673
765
  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,
766
+ buildWithConcurrency( {
767
+ moduleTypes: LOADER_CONFIG,
768
+ checks: BASE_CHECKS,
769
+ input: entryPoint,
689
770
  platform: 'browser',
690
- minify: true,
691
- define: getDefine( false ),
771
+ transform: {
772
+ target,
773
+ define: getDefine( false ),
774
+ jsx: JSX_OPTIONS,
775
+ },
776
+ resolve: { conditionNames: defaultConditions },
692
777
  plugins: [
693
778
  styleRuntimeAliasPlugin(),
694
779
  wordpressExternalsPlugin(
@@ -698,27 +783,32 @@ async function bundlePackage( packageName, options = {} ) {
698
783
  true // Generate asset file for minified build
699
784
  ),
700
785
  ],
786
+ output: {
787
+ file: path.join(
788
+ rootBuildModuleDir,
789
+ `${ fileName }.min.js`
790
+ ),
791
+ codeSplitting: false,
792
+ sourcemap: ! isWasmWorker,
793
+ format: 'esm',
794
+ minify: true,
795
+ },
701
796
  } )
702
797
  );
703
798
 
704
799
  if ( ! isWasmWorker ) {
705
800
  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,
801
+ buildWithConcurrency( {
802
+ moduleTypes: LOADER_CONFIG,
803
+ checks: BASE_CHECKS,
804
+ input: entryPoint,
718
805
  platform: 'browser',
719
- minify: false,
720
- define: getDefine( true ),
721
- conditions: developmentConditions,
806
+ transform: {
807
+ target,
808
+ define: getDefine( true ),
809
+ jsx: JSX_OPTIONS,
810
+ },
811
+ resolve: { conditionNames: developmentConditions },
722
812
  plugins: [
723
813
  styleRuntimeAliasPlugin(),
724
814
  wordpressExternalsPlugin(
@@ -728,6 +818,16 @@ async function bundlePackage( packageName, options = {} ) {
728
818
  false // Skip asset file for non-minified build
729
819
  ),
730
820
  ],
821
+ output: {
822
+ file: path.join(
823
+ rootBuildModuleDir,
824
+ `${ fileName }.js`
825
+ ),
826
+ codeSplitting: false,
827
+ sourcemap: true,
828
+ format: 'esm',
829
+ minify: false,
830
+ },
731
831
  } )
732
832
  );
733
833
  }
@@ -1316,7 +1416,8 @@ async function transpilePackage( packageName ) {
1316
1416
 
1317
1417
  const srcFiles = await glob( getSourceFileGlob( 'src/**/*' ), {
1318
1418
  cwd: packageDir,
1319
- ignore: IGNORE_PATTERNS,
1419
+ // Declaration files have no code to transpile.
1420
+ ignore: [ ...IGNORE_PATTERNS, '**/*.d.{ts,mts,cts}' ],
1320
1421
  absolute: true,
1321
1422
  } );
1322
1423
 
@@ -1344,73 +1445,50 @@ async function transpilePackage( packageName ) {
1344
1445
  */
1345
1446
  const externalizeJsImportsPlugin = {
1346
1447
  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
- }
1448
+ async resolveId( source, importer, extraOptions ) {
1449
+ // Skip entry points
1450
+ if ( extraOptions.isEntry || ! importer ) {
1451
+ return null;
1452
+ }
1354
1453
 
1355
- // Skip entry points
1356
- if ( args.kind === 'entry-point' ) {
1357
- return null;
1358
- }
1454
+ // Let CSS/SCSS files be processed by the style plugin
1455
+ if ( source.match( /\.(css|scss)$/ ) ) {
1456
+ return null;
1457
+ }
1359
1458
 
1360
- // Let CSS/SCSS files be processed by sassPlugin
1361
- if ( args.path.match( /\.(css|scss)$/ ) ) {
1362
- return null;
1363
- }
1459
+ // Let SVG files be inlined by the `dataurl` module type.
1460
+ if ( source.endsWith( '.svg' ) ) {
1461
+ return null;
1462
+ }
1463
+
1464
+ // Fully resolve local dependencies without file extension.
1465
+ // The output's `paths` replace the extension with the target extension.
1466
+ if ( source.startsWith( '.' ) ) {
1467
+ const resolved = await this.resolve( source, importer, {
1468
+ kind: extraOptions.kind,
1469
+ skipSelf: true,
1470
+ } );
1364
1471
 
1365
- // Let SVG files be inlined by the `dataurl` loader.
1366
- if ( args.path.endsWith( '.svg' ) ) {
1472
+ if ( ! resolved ) {
1367
1473
  return null;
1368
1474
  }
1369
1475
 
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
- };
1476
+ // Relativize path: make it relative to the importer with leading ./
1477
+ let relativePath = normalizePath(
1478
+ path.relative( path.dirname( importer ), resolved.id )
1479
+ );
1480
+ if ( ! relativePath.startsWith( '.' ) ) {
1481
+ relativePath = './' + relativePath;
1409
1482
  }
1410
1483
 
1411
- // Externalize everything else (keep imports as-is)
1412
- return { path: args.path, external: true };
1413
- } );
1484
+ return {
1485
+ id: relativePath,
1486
+ external: true,
1487
+ };
1488
+ }
1489
+
1490
+ // Externalize everything else (keep imports as-is)
1491
+ return { id: source, external: true };
1414
1492
  },
1415
1493
  };
1416
1494
  const plugins = [
@@ -1422,27 +1500,49 @@ async function transpilePackage( packageName ) {
1422
1500
  externalizeJsImportsPlugin,
1423
1501
  ].filter( Boolean );
1424
1502
 
1503
+ /*
1504
+ * Name each entry after its path in `src`, so the output mirrors it. Each
1505
+ * file is built on its own, so the modules it bundles (styles, the style
1506
+ * runtime, SVGs) are inlined into it instead of moved to shared chunks,
1507
+ * which would also reorder their side effects.
1508
+ */
1509
+ const entryPoints = srcFiles.map( ( file ) => ( {
1510
+ [ normalizePath( path.relative( srcDir, file ) ).replace(
1511
+ /\.[^./]+$/,
1512
+ ''
1513
+ ) ]: file,
1514
+ } ) );
1515
+
1516
+ // Make sure that file extension is always `.mjs` or `.cjs`.
1517
+ const replaceExtension = ( extension ) => ( id ) =>
1518
+ id.startsWith( '.' ) ? id.replace( /\.[cm]?[jt]sx?$/, extension ) : id;
1519
+
1425
1520
  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
- );
1521
+ for ( const input of entryPoints ) {
1522
+ builds.push(
1523
+ buildWithConcurrency( {
1524
+ moduleTypes: LOADER_CONFIG,
1525
+ checks: BASE_CHECKS,
1526
+ input,
1527
+ platform: 'node',
1528
+ transform: { target, jsx: JSX_OPTIONS },
1529
+ // Every import is kept, as the imported files are transpiled on their own.
1530
+ treeshake: { moduleSideEffects: true },
1531
+ plugins: [ ...plugins, esModuleInteropPlugin ],
1532
+ output: {
1533
+ dir: buildDir,
1534
+ entryFileNames: '[name].cjs',
1535
+ codeSplitting: false,
1536
+ paths: replaceExtension( '.cjs' ),
1537
+ format: 'cjs',
1538
+ esModule: true,
1539
+ strict: true,
1540
+ exports: 'named',
1541
+ sourcemap: true,
1542
+ },
1543
+ } )
1544
+ );
1545
+ }
1446
1546
 
1447
1547
  for ( const assetFile of assetFiles ) {
1448
1548
  const relativePath = path.relative( srcDir, assetFile );
@@ -1457,26 +1557,28 @@ async function transpilePackage( packageName ) {
1457
1557
  }
1458
1558
 
1459
1559
  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
- );
1560
+ for ( const input of entryPoints ) {
1561
+ builds.push(
1562
+ buildWithConcurrency( {
1563
+ moduleTypes: LOADER_CONFIG,
1564
+ checks: BASE_CHECKS,
1565
+ input,
1566
+ platform: 'neutral',
1567
+ transform: { target, jsx: JSX_OPTIONS },
1568
+ // Every import is kept, as the imported files are transpiled on their own.
1569
+ treeshake: { moduleSideEffects: true },
1570
+ plugins,
1571
+ output: {
1572
+ dir: buildModuleDir,
1573
+ entryFileNames: '[name].mjs',
1574
+ codeSplitting: false,
1575
+ paths: replaceExtension( '.mjs' ),
1576
+ format: 'esm',
1577
+ sourcemap: true,
1578
+ },
1579
+ } )
1580
+ );
1581
+ }
1480
1582
 
1481
1583
  for ( const jsonFile of assetFiles ) {
1482
1584
  const relativePath = path.relative( srcDir, jsonFile );
@@ -1566,56 +1668,36 @@ async function compileStyles( packageName ) {
1566
1668
 
1567
1669
  await mkdir( outputDir, { recursive: true } );
1568
1670
 
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
- },
1671
+ const source = await compileStylesheet(
1672
+ styleEntryPath,
1673
+ getSassOptions( packageDir )
1674
+ );
1675
+
1676
+ const ltrResult = await postcss(
1677
+ [
1678
+ dsTokenFallbacks,
1679
+ autoprefixer( {
1680
+ grid: true,
1681
+ overrideBrowserslist: getBrowserslistQueries(),
1616
1682
  } ),
1617
- ],
1618
- } );
1683
+ ].filter( Boolean )
1684
+ ).process( source, { from: undefined } );
1685
+
1686
+ const rtlResult = await postcss( [ rtlcss() ] ).process(
1687
+ ltrResult.css,
1688
+ { from: undefined }
1689
+ );
1690
+
1691
+ await Promise.all( [
1692
+ writeFile(
1693
+ path.join( outputDir, `${ entryName }.css` ),
1694
+ ltrResult.css
1695
+ ),
1696
+ writeFile(
1697
+ path.join( outputDir, `${ entryName }-rtl.css` ),
1698
+ rtlResult.css
1699
+ ),
1700
+ ] );
1619
1701
  } )
1620
1702
  );
1621
1703
 
@@ -1702,15 +1784,16 @@ async function buildRoute( routeName ) {
1702
1784
  if ( routeEntryPoints.length > 0 ) {
1703
1785
  // Build both minified and non-minified versions in parallel
1704
1786
  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 ),
1787
+ buildWithConcurrency( {
1788
+ moduleTypes: LOADER_CONFIG,
1789
+ checks: BASE_CHECKS,
1790
+ input: routeEntryPoints,
1791
+ transform: {
1792
+ target: getEsbuildTarget(),
1793
+ define: getDefine( false ),
1794
+ jsx: JSX_OPTIONS,
1795
+ },
1796
+ resolve: { conditionNames: defaultConditions },
1714
1797
  plugins: [
1715
1798
  styleRuntimeAliasPlugin(),
1716
1799
  wordpressExternalsPlugin(
@@ -1720,17 +1803,23 @@ async function buildRoute( routeName ) {
1720
1803
  true // Generate asset file for minified build
1721
1804
  ),
1722
1805
  ],
1806
+ output: {
1807
+ file: path.join( outputDir, 'route.min.js' ),
1808
+ format: 'esm',
1809
+ minify: true,
1810
+ codeSplitting: false,
1811
+ },
1723
1812
  } ),
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,
1813
+ buildWithConcurrency( {
1814
+ moduleTypes: LOADER_CONFIG,
1815
+ checks: BASE_CHECKS,
1816
+ input: routeEntryPoints,
1817
+ transform: {
1818
+ target: getEsbuildTarget(),
1819
+ define: getDefine( true ),
1820
+ jsx: JSX_OPTIONS,
1821
+ },
1822
+ resolve: { conditionNames: developmentConditions },
1734
1823
  plugins: [
1735
1824
  styleRuntimeAliasPlugin(),
1736
1825
  wordpressExternalsPlugin(
@@ -1740,6 +1829,12 @@ async function buildRoute( routeName ) {
1740
1829
  false // Skip asset file for non-minified build
1741
1830
  ),
1742
1831
  ],
1832
+ output: {
1833
+ file: path.join( outputDir, 'route.js' ),
1834
+ format: 'esm',
1835
+ minify: false,
1836
+ codeSplitting: false,
1837
+ },
1743
1838
  } ),
1744
1839
  ] );
1745
1840
  }
@@ -1756,15 +1851,16 @@ async function buildRoute( routeName ) {
1756
1851
 
1757
1852
  // Build both minified and non-minified versions in parallel
1758
1853
  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 ),
1854
+ buildWithConcurrency( {
1855
+ moduleTypes: LOADER_CONFIG,
1856
+ checks: BASE_CHECKS,
1857
+ input: [ tempEntryPath ],
1858
+ transform: {
1859
+ target: getEsbuildTarget(),
1860
+ define: getDefine( false ),
1861
+ jsx: JSX_OPTIONS,
1862
+ },
1863
+ resolve: { conditionNames: defaultConditions },
1768
1864
  plugins: [
1769
1865
  ...createStyleBundlingPlugins( routeDir ),
1770
1866
  wordpressExternalsPlugin(
@@ -1774,17 +1870,23 @@ async function buildRoute( routeName ) {
1774
1870
  true // Generate asset file for minified build
1775
1871
  ),
1776
1872
  ],
1873
+ output: {
1874
+ file: path.join( outputDir, 'content.min.js' ),
1875
+ format: 'esm',
1876
+ minify: true,
1877
+ codeSplitting: false,
1878
+ },
1777
1879
  } ),
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,
1880
+ buildWithConcurrency( {
1881
+ moduleTypes: LOADER_CONFIG,
1882
+ checks: BASE_CHECKS,
1883
+ input: [ tempEntryPath ],
1884
+ transform: {
1885
+ target: getEsbuildTarget(),
1886
+ define: getDefine( true ),
1887
+ jsx: JSX_OPTIONS,
1888
+ },
1889
+ resolve: { conditionNames: developmentConditions },
1788
1890
  plugins: [
1789
1891
  ...createStyleBundlingPlugins( routeDir ),
1790
1892
  wordpressExternalsPlugin(
@@ -1794,6 +1896,12 @@ async function buildRoute( routeName ) {
1794
1896
  false // Skip asset file for non-minified build
1795
1897
  ),
1796
1898
  ],
1899
+ output: {
1900
+ file: path.join( outputDir, 'content.js' ),
1901
+ format: 'esm',
1902
+ minify: false,
1903
+ codeSplitting: false,
1904
+ },
1797
1905
  } ),
1798
1906
  ] );
1799
1907
 
@@ -1869,15 +1977,16 @@ async function buildWidget( widgetName ) {
1869
1977
  if ( renderEntryPoints.length > 0 ) {
1870
1978
  // Build both minified and non-minified versions in parallel
1871
1979
  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 ),
1980
+ buildWithConcurrency( {
1981
+ moduleTypes: LOADER_CONFIG,
1982
+ checks: BASE_CHECKS,
1983
+ input: renderEntryPoints,
1984
+ transform: {
1985
+ target: getEsbuildTarget(),
1986
+ define: getDefine( false ),
1987
+ jsx: JSX_OPTIONS,
1988
+ },
1989
+ resolve: { conditionNames: defaultConditions },
1881
1990
  plugins: [
1882
1991
  ...createStyleBundlingPlugins( widgetDir ),
1883
1992
  wordpressExternalsPlugin(
@@ -1887,17 +1996,23 @@ async function buildWidget( widgetName ) {
1887
1996
  true // Generate asset file for minified build
1888
1997
  ),
1889
1998
  ],
1999
+ output: {
2000
+ file: path.join( outputDir, 'render.min.js' ),
2001
+ format: 'esm',
2002
+ minify: true,
2003
+ codeSplitting: false,
2004
+ },
1890
2005
  } ),
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,
2006
+ buildWithConcurrency( {
2007
+ moduleTypes: LOADER_CONFIG,
2008
+ checks: BASE_CHECKS,
2009
+ input: renderEntryPoints,
2010
+ transform: {
2011
+ target: getEsbuildTarget(),
2012
+ define: getDefine( true ),
2013
+ jsx: JSX_OPTIONS,
2014
+ },
2015
+ resolve: { conditionNames: developmentConditions },
1901
2016
  plugins: [
1902
2017
  ...createStyleBundlingPlugins( widgetDir ),
1903
2018
  wordpressExternalsPlugin(
@@ -1907,6 +2022,12 @@ async function buildWidget( widgetName ) {
1907
2022
  false // Skip asset file for non-minified build
1908
2023
  ),
1909
2024
  ],
2025
+ output: {
2026
+ file: path.join( outputDir, 'render.js' ),
2027
+ format: 'esm',
2028
+ minify: false,
2029
+ codeSplitting: false,
2030
+ },
1910
2031
  } ),
1911
2032
  ] );
1912
2033
  }
@@ -1922,15 +2043,16 @@ async function buildWidget( widgetName ) {
1922
2043
  if ( widgetEntryPoints.length > 0 ) {
1923
2044
  // Build both minified and non-minified versions in parallel
1924
2045
  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 ),
2046
+ buildWithConcurrency( {
2047
+ moduleTypes: LOADER_CONFIG,
2048
+ checks: BASE_CHECKS,
2049
+ input: widgetEntryPoints,
2050
+ transform: {
2051
+ target: getEsbuildTarget(),
2052
+ define: getDefine( false ),
2053
+ jsx: JSX_OPTIONS,
2054
+ },
2055
+ resolve: { conditionNames: defaultConditions },
1934
2056
  plugins: [
1935
2057
  styleRuntimeAliasPlugin(),
1936
2058
  wordpressExternalsPlugin(
@@ -1940,17 +2062,23 @@ async function buildWidget( widgetName ) {
1940
2062
  true // Generate asset file for minified build
1941
2063
  ),
1942
2064
  ],
2065
+ output: {
2066
+ file: path.join( outputDir, 'widget.min.js' ),
2067
+ format: 'esm',
2068
+ minify: true,
2069
+ codeSplitting: false,
2070
+ },
1943
2071
  } ),
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,
2072
+ buildWithConcurrency( {
2073
+ moduleTypes: LOADER_CONFIG,
2074
+ checks: BASE_CHECKS,
2075
+ input: widgetEntryPoints,
2076
+ transform: {
2077
+ target: getEsbuildTarget(),
2078
+ define: getDefine( true ),
2079
+ jsx: JSX_OPTIONS,
2080
+ },
2081
+ resolve: { conditionNames: developmentConditions },
1954
2082
  plugins: [
1955
2083
  styleRuntimeAliasPlugin(),
1956
2084
  wordpressExternalsPlugin(
@@ -1960,6 +2088,12 @@ async function buildWidget( widgetName ) {
1960
2088
  false // Skip asset file for non-minified build
1961
2089
  ),
1962
2090
  ],
2091
+ output: {
2092
+ file: path.join( outputDir, 'widget.js' ),
2093
+ format: 'esm',
2094
+ minify: false,
2095
+ codeSplitting: false,
2096
+ },
1963
2097
  } ),
1964
2098
  ] );
1965
2099
  }
@@ -2001,7 +2135,7 @@ async function buildAllWidgets() {
2001
2135
  * Discover all widgets and collect their registry-facing data.
2002
2136
  * Widgets without a valid widget.json are skipped.
2003
2137
  *
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.
2138
+ * @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
2139
  */
2006
2140
  function collectWidgets() {
2007
2141
  return getAllWidgets( ROOT_DIR ).flatMap( ( widgetName ) => {
@@ -2026,6 +2160,7 @@ function collectWidgets() {
2026
2160
  icon: metadata.icon ?? null,
2027
2161
  actions: metadata.actions ?? null,
2028
2162
  attributes: metadata.attributes ?? null,
2163
+ example: metadata.example ?? null,
2029
2164
  hasRender: widgetFiles.hasRender,
2030
2165
  hasWidget: widgetFiles.hasWidget,
2031
2166
  presentation: metadata.presentation ?? null,
@@ -2236,6 +2371,29 @@ function toPhpAttributesLiteral( attributes ) {
2236
2371
  return `array( ${ entries.join( ', ' ) } )`;
2237
2372
  }
2238
2373
 
2374
+ /**
2375
+ * Format a widget's example as a PHP array literal: `attributes` copied as
2376
+ * declared, with the registration gate constraining the values. Returns the
2377
+ * PHP literal `null` unless `example` carries a non-empty `attributes`
2378
+ * object.
2379
+ *
2380
+ * @param {import('./widget-utils.mjs').WidgetExampleMetadata|null|undefined} example Source value.
2381
+ * @return {string} PHP array literal, or `null`.
2382
+ */
2383
+ function toPhpExampleLiteral( example ) {
2384
+ const attributes = example?.attributes;
2385
+ if (
2386
+ ! attributes ||
2387
+ typeof attributes !== 'object' ||
2388
+ Array.isArray( attributes ) ||
2389
+ Object.keys( attributes ).length === 0
2390
+ ) {
2391
+ return 'null';
2392
+ }
2393
+
2394
+ return toPhpValueLiteral( { attributes } );
2395
+ }
2396
+
2239
2397
  /**
2240
2398
  * Generate global widget registry file.
2241
2399
  * Creates a single registry with all widgets including file availability.
@@ -2264,6 +2422,7 @@ async function generateWidgetRegistry( widgets, replacements ) {
2264
2422
  const iconStr = toPhpStringLiteral( widget.icon );
2265
2423
  const actionsStr = toPhpActionsLiteral( widget.actions );
2266
2424
  const attributesStr = toPhpAttributesLiteral( widget.attributes );
2425
+ const exampleStr = toPhpExampleLiteral( widget.example );
2267
2426
  const keywordsStr = toPhpStringArrayLiteral( widget.keywords );
2268
2427
  const textdomainStr = toPhpStringLiteral( widget.textdomain );
2269
2428
  return `\tarray(
@@ -2275,6 +2434,7 @@ async function generateWidgetRegistry( widgets, replacements ) {
2275
2434
  'icon' => ${ iconStr },
2276
2435
  'actions' => ${ actionsStr },
2277
2436
  'attributes' => ${ attributesStr },
2437
+ 'example' => ${ exampleStr },
2278
2438
  'has_render' => ${ hasRenderStr },
2279
2439
  'has_widget' => ${ hasWidgetStr },
2280
2440
  'presentation' => ${ presentationStr },
@@ -2865,12 +3025,17 @@ async function main() {
2865
3025
  } );
2866
3026
 
2867
3027
  const baseUrlExpression = values[ 'base-url' ];
3028
+ const buildConcurrency = getDefaultBuildConcurrency();
3029
+ setBuildConcurrency( buildConcurrency );
3030
+ console.log( `⚙️ Using build concurrency: ${ buildConcurrency }\n` );
2868
3031
 
2869
3032
  await buildAll( baseUrlExpression );
2870
3033
 
2871
3034
  if ( values.watch ) {
2872
3035
  console.log( '\n👀 Watching for changes...\n' );
2873
3036
  await watchMode();
3037
+ } else {
3038
+ await disposeSassCompiler();
2874
3039
  }
2875
3040
  }
2876
3041