@wordpress/build 0.23.1-next.v.202608281122.0 → 0.24.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
@@ -1,7 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { readFile, writeFile, copyFile, mkdir, unlink } from 'fs/promises';
3
3
  import path from 'path';
4
- import { createHash } from 'node:crypto';
5
4
  import { createRequire as createNodeRequire } from 'node:module';
6
5
  import { parseArgs } from 'node:util';
7
6
  import esbuild from 'esbuild';
@@ -10,7 +9,6 @@ import chokidar from 'chokidar';
10
9
  import browserslistToEsbuild from 'browserslist-to-esbuild';
11
10
  import { sassPlugin } from 'esbuild-sass-plugin';
12
11
  import postcss from 'postcss';
13
- import postcssModules from 'postcss-modules';
14
12
  import autoprefixer from 'autoprefixer';
15
13
  import rtlcss from 'rtlcss';
16
14
  import cssnano from 'cssnano';
@@ -28,6 +26,7 @@ import {
28
26
  renderTemplateToString,
29
27
  } from './php-generator.mjs';
30
28
  import { getPackageInfo, getPackageInfoFromFile } from './package-utils.mjs';
29
+ import { getBrowserslistQueries } from './browserslist.mjs';
31
30
  import { getSourceFileGlob, isTestSourceFile } from './source-files.mjs';
32
31
  import { createWordpressExternalsPlugin } from './wordpress-externals-plugin.mjs';
33
32
  import {
@@ -46,20 +45,26 @@ import {
46
45
  buildWorkers,
47
46
  generateWorkerCode,
48
47
  } from './worker-build.mjs';
48
+ import {
49
+ compileInlineStyle,
50
+ dsTokenFallbacks,
51
+ } from './compile-inline-style.mjs';
49
52
 
50
- // Optional dependency: @wordpress/theme provides plugins that inject fallback
51
- // values for design system tokens. Fails gracefully when the package is not
52
- // installed (it is an optional peerDependency).
53
- let dsTokenFallbacks;
53
+ /**
54
+ * Resolve the ESBuild target from the project's Browserslist config.
55
+ *
56
+ * @return {string[]} ESBuild target strings.
57
+ */
58
+ function getEsbuildTarget() {
59
+ return browserslistToEsbuild( getBrowserslistQueries() );
60
+ }
61
+ // Optional dependency: @wordpress/theme provides a plugin that injects fallback
62
+ // values for design system tokens in JavaScript. Fails gracefully when the
63
+ // package is not installed (it is an optional peerDependency).
54
64
  let dsTokenFallbacksJs;
55
65
  try {
56
- const { default: postcssPlugin } = await import(
57
- '@wordpress/theme/postcss-plugins/postcss-ds-token-fallbacks'
58
- );
59
- const { default: esbuildPlugin } = await import(
60
- '@wordpress/theme/esbuild-plugins/esbuild-ds-token-fallbacks'
61
- );
62
- dsTokenFallbacks = postcssPlugin;
66
+ const { default: esbuildPlugin } =
67
+ await import( '@wordpress/theme/esbuild-plugins/esbuild-ds-token-fallbacks' );
63
68
  dsTokenFallbacksJs = esbuildPlugin;
64
69
  } catch {
65
70
  // @wordpress/theme is optional; skip token fallbacks if not available.
@@ -101,6 +106,11 @@ const HANDLE_PREFIX = WP_PLUGIN_CONFIG.handlePrefix || PACKAGE_NAMESPACE;
101
106
  const EXTERNAL_NAMESPACES = WP_PLUGIN_CONFIG.externalNamespaces || {};
102
107
  const PAGES = WP_PLUGIN_CONFIG.pages || [];
103
108
 
109
+ // Capability required to view a generated page when the page config does not
110
+ // declare one. Pages rendering outside the menu page callback flow must
111
+ // enforce this themselves.
112
+ const DEFAULT_PAGE_CAPABILITY = 'manage_options';
113
+
104
114
  /**
105
115
  * Interprets a configuration value as a boolean, where `"true"` and `"1"`
106
116
  * are considered true while all other values are false.
@@ -195,66 +205,6 @@ function getSassOptions( workingDir ) {
195
205
  };
196
206
  }
197
207
 
198
- function compileInlineStyle( { cssModules = false, minify = true } = {} ) {
199
- return async function styleType( cssText, _dirname, filePath ) {
200
- let moduleExports = null;
201
-
202
- // Transform the code: token fallbacks, CSS modules and minification.
203
- const plugins = [
204
- dsTokenFallbacks,
205
- cssModules &&
206
- postcssModules( {
207
- generateScopedName: '[contenthash]__[local]',
208
- getJSON: ( _, json ) => {
209
- moduleExports = json;
210
- },
211
- } ),
212
- minify &&
213
- cssnano( {
214
- preset: [
215
- 'default',
216
- { discardComments: { removeAll: true } },
217
- ],
218
- } ),
219
- ].filter( Boolean );
220
-
221
- const { css } = await postcss( plugins ).process( cssText, {
222
- from: filePath,
223
- map: false,
224
- } );
225
-
226
- // Hash the transformed CSS so that the dedup key reflects the actual
227
- // injected content, including mangled CSS module class names.
228
- const hash = createHash( 'sha1' )
229
- .update( css )
230
- .digest( 'hex' )
231
- .slice( 0, 10 );
232
-
233
- // Skip automatic style injection in Node-based test environments, where DOM
234
- // implementations do not reliably support modern CSS features like @layer.
235
- let cssModule = cssModules
236
- ? `import { registerStyle } from '@wordpress/style-runtime';
237
- if (typeof process === 'undefined' || process.env.NODE_ENV !== 'test') {
238
- registerStyle("${ hash }", ${ JSON.stringify( css ) });
239
- }
240
- `
241
- : `if (typeof document !== 'undefined' && process.env.NODE_ENV !== 'test' && !document.head.querySelector("style[data-wp-hash='${ hash }']")) {
242
- const style = document.createElement("style");
243
- style.setAttribute("data-wp-hash", "${ hash }");
244
- style.appendChild(document.createTextNode(${ JSON.stringify( css ) }));
245
- document.head.appendChild(style);
246
- }
247
- `;
248
-
249
- // The CSS modules transform produces an `exports` object with class name mappings.
250
- if ( moduleExports ) {
251
- const exportsString = JSON.stringify( moduleExports );
252
- cssModule += `export default ${ exportsString };\n`;
253
- }
254
- return cssModule;
255
- };
256
- }
257
-
258
208
  function inlineStyle( contents ) {
259
209
  // The `contents` is already a JS code created by `compileInlineStyle`.
260
210
  return contents;
@@ -587,7 +537,7 @@ async function bundlePackage( packageName, options = {} ) {
587
537
  if ( packageJson.wpScript ) {
588
538
  const entryPoint = resolveEntryPoint( packageDir, packageJson );
589
539
  const outputDir = path.join( BUILD_DIR, 'scripts', packageName );
590
- const target = browserslistToEsbuild();
540
+ const target = getEsbuildTarget();
591
541
 
592
542
  // Check if package matches the namespace and should expose a global
593
543
  const packageFullName = packageJson.name;
@@ -684,7 +634,7 @@ async function bundlePackage( packageName, options = {} ) {
684
634
  }
685
635
 
686
636
  if ( packageJson.wpScriptModuleExports ) {
687
- const target = browserslistToEsbuild();
637
+ const target = getEsbuildTarget();
688
638
  const rootBuildModuleDir = path.join(
689
639
  BUILD_DIR,
690
640
  'modules',
@@ -1287,6 +1237,7 @@ async function generatePagesPhp( pageData, replacements ) {
1287
1237
  '{{PREFIX}}': prefixUnderscore,
1288
1238
  '{{INIT_MODULES_PHP_ARRAY}}': initModulesPhp,
1289
1239
  '{{INIT_MODULES_JSON}}': JSON.stringify( page.initModules ),
1240
+ '{{CAPABILITY}}': page.capability || DEFAULT_PAGE_CAPABILITY,
1290
1241
  };
1291
1242
 
1292
1243
  // Generate both page.php and page-wp-admin.php
@@ -1368,7 +1319,7 @@ async function transpilePackage( packageName ) {
1368
1319
  const buildDir = path.join( packageDir, 'build' );
1369
1320
  const buildModuleDir = path.join( packageDir, 'build-module' );
1370
1321
  const srcDir = path.join( packageDir, 'src' );
1371
- const target = browserslistToEsbuild();
1322
+ const target = getEsbuildTarget();
1372
1323
 
1373
1324
  const builds = [];
1374
1325
 
@@ -1381,7 +1332,7 @@ async function transpilePackage( packageName ) {
1381
1332
  // Ideally we should remove this exception and move away from emotion.
1382
1333
  const needsEmotionPlugin = packageName === 'components';
1383
1334
  const emotionPlugin = babel( {
1384
- filter: /\.[jt]sx?$/,
1335
+ filter: /\.[cm]?[jt]sx?$/,
1385
1336
  config: {
1386
1337
  plugins: [ styleRuntimeRequire.resolve( '@emotion/babel-plugin' ) ],
1387
1338
  },
@@ -1436,7 +1387,10 @@ async function transpilePackage( packageName ) {
1436
1387
  // Replace extension: make sure that file extension is always `.mjs` or `.cjs`.
1437
1388
  const newExt =
1438
1389
  build.initialOptions.format === 'cjs' ? '.cjs' : '.mjs';
1439
- relativePath = relativePath.replace( /\.[jt]sx?$/, newExt );
1390
+ relativePath = relativePath.replace(
1391
+ /\.[cm]?[jt]sx?$/,
1392
+ newExt
1393
+ );
1440
1394
 
1441
1395
  return {
1442
1396
  path: relativePath,
@@ -1480,7 +1434,6 @@ async function transpilePackage( packageName ) {
1480
1434
  target,
1481
1435
  jsx: 'automatic',
1482
1436
  jsxImportSource: 'react',
1483
- loader: { '.js': 'jsx' },
1484
1437
  plugins,
1485
1438
  } )
1486
1439
  );
@@ -1514,7 +1467,6 @@ async function transpilePackage( packageName ) {
1514
1467
  target,
1515
1468
  jsx: 'automatic',
1516
1469
  jsxImportSource: 'react',
1517
- loader: { '.js': 'jsx' },
1518
1470
  plugins,
1519
1471
  } )
1520
1472
  );
@@ -1623,7 +1575,11 @@ async function compileStyles( packageName ) {
1623
1575
  const ltrResult = await postcss(
1624
1576
  [
1625
1577
  dsTokenFallbacks,
1626
- autoprefixer( { grid: true } ),
1578
+ autoprefixer( {
1579
+ grid: true,
1580
+ overrideBrowserslist:
1581
+ getBrowserslistQueries(),
1582
+ } ),
1627
1583
  ].filter( Boolean )
1628
1584
  ).process( source, { from: undefined } );
1629
1585
 
@@ -1744,7 +1700,7 @@ async function buildRoute( routeName ) {
1744
1700
  outfile: path.join( outputDir, 'route.min.js' ),
1745
1701
  bundle: true,
1746
1702
  format: 'esm',
1747
- target: browserslistToEsbuild(),
1703
+ target: getEsbuildTarget(),
1748
1704
  minify: true,
1749
1705
  define: getDefine( false ),
1750
1706
  plugins: [
@@ -1762,7 +1718,7 @@ async function buildRoute( routeName ) {
1762
1718
  outfile: path.join( outputDir, 'route.js' ),
1763
1719
  bundle: true,
1764
1720
  format: 'esm',
1765
- target: browserslistToEsbuild(),
1721
+ target: getEsbuildTarget(),
1766
1722
  minify: false,
1767
1723
  define: getDefine( true ),
1768
1724
  plugins: [
@@ -1795,7 +1751,7 @@ async function buildRoute( routeName ) {
1795
1751
  outfile: path.join( outputDir, 'content.min.js' ),
1796
1752
  bundle: true,
1797
1753
  format: 'esm',
1798
- target: browserslistToEsbuild(),
1754
+ target: getEsbuildTarget(),
1799
1755
  minify: true,
1800
1756
  define: getDefine( false ),
1801
1757
  plugins: [
@@ -1813,7 +1769,7 @@ async function buildRoute( routeName ) {
1813
1769
  outfile: path.join( outputDir, 'content.js' ),
1814
1770
  bundle: true,
1815
1771
  format: 'esm',
1816
- target: browserslistToEsbuild(),
1772
+ target: getEsbuildTarget(),
1817
1773
  minify: false,
1818
1774
  define: getDefine( true ),
1819
1775
  plugins: [
@@ -1859,7 +1815,7 @@ async function buildRoutes( experimentalPageIds = new Set() ) {
1859
1815
  return metadata.pages.some(
1860
1816
  ( page ) => ! experimentalPageIds.has( page )
1861
1817
  );
1862
- } );
1818
+ } );
1863
1819
 
1864
1820
  if ( routes.length === 0 ) {
1865
1821
  console.log( ' No routes found, skipping.\n' );
@@ -1869,9 +1825,7 @@ async function buildRoutes( experimentalPageIds = new Set() ) {
1869
1825
  await Promise.all(
1870
1826
  routes.map( async ( routeName ) => {
1871
1827
  const buildTime = await buildRoute( routeName );
1872
- console.log(
1873
- ` ✔ Built route ${ routeName } (${ buildTime }ms)`
1874
- );
1828
+ console.log( ` ✔ Built route ${ routeName } (${ buildTime }ms)` );
1875
1829
  } )
1876
1830
  );
1877
1831
  }
@@ -1907,7 +1861,7 @@ async function buildWidget( widgetName ) {
1907
1861
  outfile: path.join( outputDir, 'render.min.js' ),
1908
1862
  bundle: true,
1909
1863
  format: 'esm',
1910
- target: browserslistToEsbuild(),
1864
+ target: getEsbuildTarget(),
1911
1865
  minify: true,
1912
1866
  define: getDefine( false ),
1913
1867
  plugins: [
@@ -1925,7 +1879,7 @@ async function buildWidget( widgetName ) {
1925
1879
  outfile: path.join( outputDir, 'render.js' ),
1926
1880
  bundle: true,
1927
1881
  format: 'esm',
1928
- target: browserslistToEsbuild(),
1882
+ target: getEsbuildTarget(),
1929
1883
  minify: false,
1930
1884
  define: getDefine( true ),
1931
1885
  plugins: [
@@ -1957,7 +1911,7 @@ async function buildWidget( widgetName ) {
1957
1911
  outfile: path.join( outputDir, 'widget.min.js' ),
1958
1912
  bundle: true,
1959
1913
  format: 'esm',
1960
- target: browserslistToEsbuild(),
1914
+ target: getEsbuildTarget(),
1961
1915
  minify: true,
1962
1916
  define: getDefine( false ),
1963
1917
  plugins: [
@@ -1975,7 +1929,7 @@ async function buildWidget( widgetName ) {
1975
1929
  outfile: path.join( outputDir, 'widget.js' ),
1976
1930
  bundle: true,
1977
1931
  format: 'esm',
1978
- target: browserslistToEsbuild(),
1932
+ target: getEsbuildTarget(),
1979
1933
  minify: false,
1980
1934
  define: getDefine( true ),
1981
1935
  plugins: [
@@ -2028,7 +1982,7 @@ async function buildAllWidgets() {
2028
1982
  * Discover all widgets and collect their registry-facing data.
2029
1983
  * Widgets without a valid widget.json are skipped.
2030
1984
  *
2031
- * @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, hasRender: boolean, hasWidget: boolean, presentation: string | null, category: string | null, keywords: string[] | null, textdomain: string | null }>} Array of widget objects.
1985
+ * @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.
2032
1986
  */
2033
1987
  function collectWidgets() {
2034
1988
  return getAllWidgets( ROOT_DIR ).flatMap( ( widgetName ) => {
@@ -2052,6 +2006,7 @@ function collectWidgets() {
2052
2006
  help: metadata.help ?? null,
2053
2007
  icon: metadata.icon ?? null,
2054
2008
  actions: metadata.actions ?? null,
2009
+ attributes: metadata.attributes ?? null,
2055
2010
  hasRender: widgetFiles.hasRender,
2056
2011
  hasWidget: widgetFiles.hasWidget,
2057
2012
  presentation: metadata.presentation ?? null,
@@ -2157,10 +2112,10 @@ function toPhpActionsLiteral( actions ) {
2157
2112
  typeof action.download === 'boolean'
2158
2113
  ? `'download' => ${
2159
2114
  action.download ? 'true' : 'false'
2160
- }`
2115
+ }`
2161
2116
  : `'download' => ${ toPhpStringLiteral(
2162
2117
  action.download
2163
- ) }`
2118
+ ) }`
2164
2119
  );
2165
2120
  }
2166
2121
 
@@ -2194,6 +2149,74 @@ function toPhpActionsLiteral( actions ) {
2194
2149
  return `array( ${ entries.join( ', ' ) } )`;
2195
2150
  }
2196
2151
 
2152
+ /**
2153
+ * Format any JSON value as a PHP literal: scalars as-is, lists as
2154
+ * `array( ... )`, objects as `array( 'key' => ... )`. Non-finite numbers
2155
+ * and unsupported values become `null`.
2156
+ *
2157
+ * @param {unknown} value Source value.
2158
+ * @return {string} PHP literal.
2159
+ */
2160
+ function toPhpValueLiteral( value ) {
2161
+ if ( value === null || value === undefined ) {
2162
+ return 'null';
2163
+ }
2164
+ if ( typeof value === 'boolean' ) {
2165
+ return value ? 'true' : 'false';
2166
+ }
2167
+ if ( typeof value === 'number' ) {
2168
+ return Number.isFinite( value ) ? String( value ) : 'null';
2169
+ }
2170
+ if ( typeof value === 'string' ) {
2171
+ const escaped = value.replace( /\\/g, '\\\\' ).replace( /'/g, "\\'" );
2172
+ return `'${ escaped }'`;
2173
+ }
2174
+ if ( Array.isArray( value ) ) {
2175
+ return `array( ${ value.map( toPhpValueLiteral ).join( ', ' ) } )`;
2176
+ }
2177
+ if ( typeof value === 'object' ) {
2178
+ const entries = Object.entries( value ).map(
2179
+ ( [ key, entry ] ) =>
2180
+ `${ toPhpValueLiteral( key ) } => ${ toPhpValueLiteral(
2181
+ entry
2182
+ ) }`
2183
+ );
2184
+ return `array( ${ entries.join( ', ' ) } )`;
2185
+ }
2186
+ return 'null';
2187
+ }
2188
+
2189
+ /**
2190
+ * Format a widget's attribute schema as a PHP array literal. Returns the
2191
+ * PHP literal `null` when there are no valid entries; entries without a
2192
+ * string `id` are dropped. Everything else is copied as declared; the
2193
+ * registration gate constrains the shape.
2194
+ *
2195
+ * @param {import('./widget-utils.mjs').WidgetAttributeMetadata[]|null|undefined} attributes Source value.
2196
+ * @return {string} PHP array literal, or `null`.
2197
+ */
2198
+ function toPhpAttributesLiteral( attributes ) {
2199
+ if ( ! Array.isArray( attributes ) ) {
2200
+ return 'null';
2201
+ }
2202
+
2203
+ const entries = attributes
2204
+ .filter(
2205
+ ( attribute ) =>
2206
+ attribute &&
2207
+ typeof attribute === 'object' &&
2208
+ typeof attribute.id === 'string' &&
2209
+ attribute.id !== ''
2210
+ )
2211
+ .map( toPhpValueLiteral );
2212
+
2213
+ if ( entries.length === 0 ) {
2214
+ return 'null';
2215
+ }
2216
+
2217
+ return `array( ${ entries.join( ', ' ) } )`;
2218
+ }
2219
+
2197
2220
  /**
2198
2221
  * Generate global widget registry file.
2199
2222
  * Creates a single registry with all widgets including file availability.
@@ -2221,6 +2244,7 @@ async function generateWidgetRegistry( widgets, replacements ) {
2221
2244
  const helpStr = toPhpHelpLiteral( widget.help );
2222
2245
  const iconStr = toPhpStringLiteral( widget.icon );
2223
2246
  const actionsStr = toPhpActionsLiteral( widget.actions );
2247
+ const attributesStr = toPhpAttributesLiteral( widget.attributes );
2224
2248
  const keywordsStr = toPhpStringArrayLiteral( widget.keywords );
2225
2249
  const textdomainStr = toPhpStringLiteral( widget.textdomain );
2226
2250
  return `\tarray(
@@ -2231,6 +2255,7 @@ async function generateWidgetRegistry( widgets, replacements ) {
2231
2255
  'help' => ${ helpStr },
2232
2256
  'icon' => ${ iconStr },
2233
2257
  'actions' => ${ actionsStr },
2258
+ 'attributes' => ${ attributesStr },
2234
2259
  'has_render' => ${ hasRenderStr },
2235
2260
  'has_widget' => ${ hasWidgetStr },
2236
2261
  'presentation' => ${ presentationStr },
@@ -2341,13 +2366,19 @@ async function buildAll( baseUrlExpression ) {
2341
2366
  // Normalize PAGES config to support both string and object formats
2342
2367
  const normalizedPages = PAGES.map( ( page ) => {
2343
2368
  if ( typeof page === 'string' ) {
2344
- return { id: page, init: [], title: undefined };
2369
+ return {
2370
+ id: page,
2371
+ init: [],
2372
+ title: undefined,
2373
+ capability: DEFAULT_PAGE_CAPABILITY,
2374
+ };
2345
2375
  }
2346
2376
  return {
2347
2377
  id: page.id,
2348
2378
  init: page.init || [],
2349
2379
  title: page.title || undefined,
2350
2380
  experimental: page.experimental || false,
2381
+ capability: page.capability || DEFAULT_PAGE_CAPABILITY,
2351
2382
  };
2352
2383
  } );
2353
2384
 
@@ -2365,7 +2396,7 @@ async function buildAll( baseUrlExpression ) {
2365
2396
  normalizedPages
2366
2397
  .filter( ( page ) => page.experimental )
2367
2398
  .map( ( page ) => page.id )
2368
- )
2399
+ )
2369
2400
  : new Set();
2370
2401
  await buildRoutes( experimentalPageIds );
2371
2402
 
@@ -2415,6 +2446,7 @@ async function buildAll( baseUrlExpression ) {
2415
2446
  routes: pageRoutes,
2416
2447
  initModules: page.init,
2417
2448
  title: page.title,
2449
+ capability: page.capability,
2418
2450
  };
2419
2451
  } );
2420
2452
 
@@ -2451,9 +2483,7 @@ async function buildAll( baseUrlExpression ) {
2451
2483
  if ( pageData.length > 0 ) {
2452
2484
  console.log( ' ✔ Generated build/pages.php' );
2453
2485
  for ( const page of pageData ) {
2454
- console.log(
2455
- ` ✔ Generated build/pages/${ page.slug }/page.php`
2456
- );
2486
+ console.log( ` ✔ Generated build/pages/${ page.slug }/page.php` );
2457
2487
  console.log(
2458
2488
  ` ✔ Generated build/pages/${ page.slug }/page-wp-admin.php`
2459
2489
  );
@@ -2804,10 +2834,10 @@ async function main() {
2804
2834
  'base-url': {
2805
2835
  type: 'string',
2806
2836
  default:
2807
- boolConfigVal( process.env.IS_WORDPRESS_CORE ) ??
2837
+ ( boolConfigVal( process.env.IS_WORDPRESS_CORE ) ??
2808
2838
  boolConfigVal(
2809
2839
  process.env.npm_package_config_IS_WORDPRESS_CORE
2810
- )
2840
+ ) )
2811
2841
  ? "includes_url( 'build/' )"
2812
2842
  : 'plugin_dir_url( __FILE__ )',
2813
2843
  },
@@ -0,0 +1,98 @@
1
+ import { createHash } from 'node:crypto';
2
+ import cssnano from 'cssnano';
3
+ import postcss from 'postcss';
4
+ import postcssModules from 'postcss-modules';
5
+
6
+ /** @type {import('postcss').AcceptedPlugin | undefined} */
7
+ let dsTokenFallbacks;
8
+ try {
9
+ const { default: postcssPlugin } =
10
+ await import( '@wordpress/theme/postcss-plugins/postcss-ds-token-fallbacks' );
11
+ dsTokenFallbacks = postcssPlugin;
12
+ } catch {
13
+ // @wordpress/theme is optional; skip token fallbacks if not available.
14
+ }
15
+ export { dsTokenFallbacks };
16
+
17
+ /**
18
+ * Compile CSS into the JavaScript module emitted by wp-build.
19
+ *
20
+ * @param {Object} options
21
+ * @param {boolean} [options.cssModules=false] Whether to emit CSS Module exports.
22
+ * @param {boolean} [options.minify=true] Whether to minify the CSS.
23
+ * @return {Function} esbuild-sass-plugin transform callback.
24
+ */
25
+ export function compileInlineStyle( {
26
+ cssModules = false,
27
+ minify = true,
28
+ } = {} ) {
29
+ /**
30
+ * @param {string} cssText CSS source to compile.
31
+ * @param {string} _dirname Directory containing the source file.
32
+ * @param {string} filePath Source file path.
33
+ * @return {Promise<string>} Compiled JavaScript module.
34
+ */
35
+ return async function styleType( cssText, _dirname, filePath ) {
36
+ let moduleExports = null;
37
+
38
+ const plugins = dsTokenFallbacks ? [ dsTokenFallbacks ] : [];
39
+ if ( cssModules ) {
40
+ plugins.push(
41
+ postcssModules( {
42
+ generateScopedName: '[contenthash]__[local]',
43
+ getJSON: ( _, json ) => {
44
+ moduleExports = json;
45
+ },
46
+ } )
47
+ );
48
+ }
49
+ if ( minify ) {
50
+ plugins.push(
51
+ cssnano( {
52
+ preset: [
53
+ 'default',
54
+ { discardComments: { removeAll: true } },
55
+ ],
56
+ } )
57
+ );
58
+ }
59
+
60
+ const { css } = await postcss( plugins ).process( cssText, {
61
+ from: filePath,
62
+ map: false,
63
+ } );
64
+
65
+ // Hash the transformed CSS so that the dedup key reflects the actual
66
+ // injected content, including mangled CSS module class names.
67
+ const hash = createHash( 'sha1' )
68
+ .update( css )
69
+ .digest( 'hex' )
70
+ .slice( 0, 10 );
71
+ const shouldInjectStyle =
72
+ `typeof process === 'undefined' || ` +
73
+ `process.env.NODE_ENV !== 'test'`;
74
+
75
+ // Skip automatic style injection in Node-based test environments, where DOM
76
+ // implementations do not reliably support modern CSS features like @layer.
77
+ let cssModule = cssModules
78
+ ? `import { registerStyle } from '@wordpress/style-runtime';
79
+ if (${ shouldInjectStyle }) {
80
+ registerStyle("${ hash }", ${ JSON.stringify( css ) });
81
+ }
82
+ `
83
+ : `if (typeof document !== 'undefined' && (${ shouldInjectStyle }) && !document.head.querySelector("style[data-wp-hash='${ hash }']")) {
84
+ const style = document.createElement("style");
85
+ style.setAttribute("data-wp-hash", "${ hash }");
86
+ style.appendChild(document.createTextNode(${ JSON.stringify( css ) }));
87
+ document.head.appendChild(style);
88
+ }
89
+ `;
90
+
91
+ // The CSS modules transform produces an `exports` object with class name mappings.
92
+ if ( moduleExports ) {
93
+ const exportsString = JSON.stringify( moduleExports );
94
+ cssModule += `export default ${ exportsString };\n`;
95
+ }
96
+ return cssModule;
97
+ };
98
+ }
@@ -63,44 +63,69 @@ export function getRouteMetadata( rootDir, routeName ) {
63
63
  };
64
64
  }
65
65
 
66
+ /**
67
+ * Source extensions for route entry files, in priority order.
68
+ * Must stay aligned with SOURCE_EXTENSIONS in source-files.mjs.
69
+ */
70
+ const ROUTE_EXTENSIONS = [
71
+ 'tsx',
72
+ 'ts',
73
+ 'mts',
74
+ 'cts',
75
+ 'jsx',
76
+ 'js',
77
+ 'mjs',
78
+ 'cjs',
79
+ ];
80
+
66
81
  /**
67
82
  * @typedef {Object} RouteFiles
68
- * @property {boolean} hasRoute Whether route file exists.
69
- * @property {boolean} hasStage Whether stage file exists.
70
- * @property {boolean} hasInspector Whether inspector file exists.
71
- * @property {boolean} hasCanvas Whether canvas file exists.
72
- * @property {boolean} hasStyle Whether style file exists.
83
+ * @property {boolean} hasRoute Whether route file exists.
84
+ * @property {boolean} hasStage Whether stage file exists.
85
+ * @property {boolean} hasInspector Whether inspector file exists.
86
+ * @property {boolean} hasCanvas Whether canvas file exists.
87
+ * @property {boolean} hasStyle Whether style file exists.
88
+ * @property {string|null} stage Stage file name, extension included.
89
+ * @property {string|null} inspector Inspector file name, extension included.
90
+ * @property {string|null} canvas Canvas file name, extension included.
73
91
  */
74
92
 
75
93
  /**
76
94
  * Check if a route has specific files.
77
95
  *
78
96
  * @param {string} routeDirectory Route directory path.
79
- * @return {RouteFiles} Object with boolean flags for route files.
97
+ * @return {RouteFiles} Object with flags and file names for route files.
80
98
  */
81
99
  export function getRouteFiles( routeDirectory ) {
82
- const extensions = [ 'tsx', 'ts', 'jsx', 'js' ];
100
+ /** @type {RouteFiles} */
83
101
  const files = {
84
102
  hasRoute: false,
85
103
  hasStage: false,
86
104
  hasInspector: false,
87
105
  hasCanvas: false,
88
106
  hasStyle: false,
107
+ stage: null,
108
+ inspector: null,
109
+ canvas: null,
89
110
  };
90
111
 
91
112
  const entries = readdirSync( routeDirectory );
92
113
 
93
- for ( const ext of extensions ) {
114
+ // The extension list is ordered, so the first match wins.
115
+ for ( const ext of ROUTE_EXTENSIONS ) {
94
116
  if ( entries.includes( `route.${ ext }` ) ) {
95
117
  files.hasRoute = true;
96
118
  }
97
- if ( entries.includes( `stage.${ ext }` ) ) {
119
+ if ( ! files.stage && entries.includes( `stage.${ ext }` ) ) {
120
+ files.stage = `stage.${ ext }`;
98
121
  files.hasStage = true;
99
122
  }
100
- if ( entries.includes( `inspector.${ ext }` ) ) {
123
+ if ( ! files.inspector && entries.includes( `inspector.${ ext }` ) ) {
124
+ files.inspector = `inspector.${ ext }`;
101
125
  files.hasInspector = true;
102
126
  }
103
- if ( entries.includes( `canvas.${ ext }` ) ) {
127
+ if ( ! files.canvas && entries.includes( `canvas.${ ext }` ) ) {
128
+ files.canvas = `canvas.${ ext }`;
104
129
  files.hasCanvas = true;
105
130
  }
106
131
  }
@@ -122,16 +147,20 @@ export function getRouteFiles( routeDirectory ) {
122
147
  export function generateContentEntryPoint( files ) {
123
148
  const lines = [];
124
149
 
125
- if ( files.hasStage ) {
126
- lines.push( "export { stage } from './stage';" );
150
+ /*
151
+ * Import the full file name rather than relying on esbuild extending an
152
+ * extensionless path: that resolution never tries `.mts` or `.cts`.
153
+ */
154
+ if ( files.stage ) {
155
+ lines.push( `export { stage } from './${ files.stage }';` );
127
156
  }
128
157
 
129
- if ( files.hasInspector ) {
130
- lines.push( "export { inspector } from './inspector';" );
158
+ if ( files.inspector ) {
159
+ lines.push( `export { inspector } from './${ files.inspector }';` );
131
160
  }
132
161
 
133
- if ( files.hasCanvas ) {
134
- lines.push( "export { canvas } from './canvas';" );
162
+ if ( files.canvas ) {
163
+ lines.push( `export { canvas } from './${ files.canvas }';` );
135
164
  }
136
165
 
137
166
  // If no components exist, export empty object