Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Script Modules: Implement script interoperability #6239

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 20 additions & 1 deletion src/wp-includes/class-wp-script-modules.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,10 @@ public function register( string $id, string $src, array $deps = array(), $versi
}
$dependencies[] = array(
'id' => $dependency['id'],
'import' => isset( $dependency['import'] ) && 'dynamic' === $dependency['import'] ? 'dynamic' : 'static',
'import' => isset( $dependency['import'] ) &&
'dynamic' === $dependency['import'] ||
'wp-script' === $dependency['import']
? $dependency['import'] : 'static',
);
} elseif ( is_string( $dependency ) ) {
$dependencies[] = array(
Expand Down Expand Up @@ -195,6 +198,13 @@ public function print_enqueued_script_modules() {
'id' => $id . '-js-module',
)
);

foreach ( $script_module['dependencies'] as $dependency ) {
if ( 'wp-script' !== $dependency['import'] ) {
continue;
}
wp_enqueue_script( $dependency['id'] );
}
}
}

Expand Down Expand Up @@ -250,6 +260,15 @@ public function print_import_map() {
'id' => 'wp-importmap',
)
);

foreach ( $import_map['imports'] as $id => $_ ) {
foreach ( $this->registered[ $id ]['dependencies'] as $dependency ) {
if ( 'wp-script' !== $dependency['import'] ) {
continue;
}
wp_enqueue_script( $dependency['id'] );
}
}
}
}

Expand Down
59 changes: 59 additions & 0 deletions src/wp-includes/script-modules.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,3 +123,62 @@ function wp_dequeue_script_module( string $id ) {
function wp_deregister_script_module( string $id ) {
wp_script_modules()->deregister( $id );
}

/**
* Registers all the WordPress packages scripts proxy modules.
*
* @since 6.6.0
*
* @param WP_Scripts $scripts WP_Scripts object.
*/
function wp_register_package_scripts_proxy_modules() {
$suffix = defined( 'WP_RUN_CORE_TESTS' ) ? '.min' : wp_scripts_get_suffix();

/*
* Expects multidimensional array like:
*
* 'a11y-esm.js' => array('dependencies' => array(...), 'version' => '...'),
* 'annotations-esm.js' => array('dependencies' => array(...), 'version' => '...'),
* 'api-fetch-esm.js' => array(...
*/
$assets = include ABSPATH . WPINC . "/assets/script-loader-packages-proxy-modules{$suffix}.php";

foreach ( $assets as $file_name => $package_data ) {
$basename = str_replace( $suffix . '-esm-proxy.js', '', basename( $file_name ) );
$id = '@wordpress/' . $basename;
$path = "/wp-includes/js/dist/{$file_name}";

if ( ! empty( $package_data['dependencies'] ) ) {
$dependencies = $package_data['dependencies'];
} else {
$dependencies = array();
}

wp_register_script_module( $id, $path, $dependencies, $package_data['version'] );
}

/*
* Expects multidimensional array like:
*
* 'a11y-esm.js' => array('dependencies' => array(...), 'version' => '...'),
* 'annotations-esm.js' => array('dependencies' => array(...), 'version' => '...'),
* 'api-fetch-esm.js' => array(...
*/
$assets = include ABSPATH . WPINC . "/assets/script-loader-packages-esm{$suffix}.php";

foreach ( $assets as $file_name => $package_data ) {
$basename = str_replace( $suffix . '-esm.js', '', basename( $file_name ) );
$id = '@wordpress-esm/' . $basename;
$path = "/wp-includes/js/dist/{$file_name}";

if ( ! empty( $package_data['dependencies'] ) ) {
$dependencies = $package_data['dependencies'];
} else {
$dependencies = array();
}

wp_register_script_module( $id, $path, $dependencies, $package_data['version'] );
}
}

add_action( 'init', 'wp_register_package_scripts_proxy_modules' );
205 changes: 205 additions & 0 deletions tools/webpack/packages-proxy-module-gen-plugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
/**
* External dependencies
*/
const path = require( 'path' );
const webpack = require( 'webpack' );
const json2php = require( 'json2php' );

const { createHash } = webpack.util;
const { RawSource } = webpack.sources;

class WpScriptsPackageProxyModuleWebpackPlugin {
/**
* @param {{ combinedOutputFile: string }} options
*/
constructor( options ) {
if ( ! options || ! Object.hasOwn( options, 'combinedOutputFile' ) ) {
throw new Error( 'Must provide combinedOutputFile option' );
}

this.options = options;
}

/**
* @param {any} asset Asset Data
* @return {string} Stringified asset data suitable for output
*/
stringify( asset ) {
return `<?php return ${ json2php(
JSON.parse( JSON.stringify( asset ) )
) };\n`;
}

/** @type {webpack.WebpackPluginInstance['apply']} */
apply( compiler ) {
if ( compiler.options.output?.module ) {
throw new Error(
`${ this.constructor.name } is not compatible with a module build.`
);
}

compiler.hooks.thisCompilation.tap(
this.constructor.name,
( compilation ) => {
compilation.hooks.processAssets.tap(
{
name: this.constructor.name,
stage: compiler.webpack.Compilation
.PROCESS_ASSETS_STAGE_ANALYSE,
},
() => this.addAssets( compilation )
);
}
);
}

/** @param {webpack.Compilation} compilation */
addAssets( compilation ) {
const { combinedOutputFile } = this.options;

const combinedAssetsData = {};

// Accumulate all entrypoint chunks, some of them shared
const entrypointChunks = new Set();

/**
* @type Map<string, {exportsInfo: ReturnType<webpack.ModuleGraph['getExportInfo']>, libOpts: {name:string[];type:string}}>
*/
const entrypointProxyInfo = new Map();

for ( const entrypoint of compilation.entrypoints.values() ) {
for ( const chunk of entrypoint.chunks ) {
entrypointChunks.add( chunk );
}

const library = entrypoint.options.library;
if ( ! library || ! Array.isArray( library.name ) ) {
continue;
}

if (
1 !==
compilation.chunkGraph.getNumberOfEntryModules(
entrypoint.getEntrypointChunk()
)
) {
continue;
}

/** @type {webpack.Module} */
const entryModule = compilation.chunkGraph
.getChunkEntryModulesIterable( entrypoint.getEntrypointChunk() )
.next().value;

const exportsInfo =
compilation.moduleGraph.getExportsInfo( entryModule );

if ( Array.isArray( exportsInfo.getProvidedExports() ) ) {
entrypointProxyInfo.set( entrypoint.options.name, {
exportsInfo,
libOpts: library,
} );
}
}

// Process each entrypoint chunk independently
for ( const chunk of entrypointChunks ) {
const chunkFiles = Array.from( chunk.files );

const jsExtensionRegExp = this.useModules ? /\.m?js$/i : /\.js$/i;

const chunkJSFile = chunkFiles.find( ( f ) =>
jsExtensionRegExp.test( f )
);
if ( ! chunkJSFile ) {
// There's no JS file in this chunk, no work for us. Typically a `style.css` from cache group.
continue;
}

// Go through the assets and hash the sources. We can't just use
// `chunk.contentHash` because that's not updated when
// assets are minified. In practice the hash is updated by
// `RealContentHashPlugin` after minification, but it only modifies
// already-produced asset filenames and the updated hash is not
// available to plugins.
const { hashFunction, hashDigest, hashDigestLength } =
compilation.outputOptions;

if ( entrypointProxyInfo.has( chunk.name ) ) {
const { exportsInfo, libOpts } = entrypointProxyInfo.get(
chunk.name
);
const generatedProxyModuleFilename = compilation
.getPath( '[file]', {
filename: chunkJSFile,
} )
.replace( /\.m?js$/i, '-esm-proxy.js' );
const libraryPath = libOpts.name.map(
( n ) => `[${ JSON.stringify( n ) }]`
);

// let sourceString = `if ( 'undefined' === typeof ${
// libOpts.type
// }?.${ libraryPath.join(
// '?.'
// ) } ) {\n\tthrow new Error( 'Undefined dependency: ${
// libOpts.type
// }${ libraryPath.join( '' ) }' );\n}\n`;

let sourceString = `const __library__ = ${
libOpts.type
}?.${ libraryPath.join(
'?.'
) } ?? await import( '@wordpress-esm/${ chunk.name }' )${
'' //libOpts.export === 'default' ? '.default' : ''
};\n`;

console.log( {
n: chunk.name,
es: exportsInfo.getProvidedExports(),
} );
for ( const exportName of exportsInfo.getProvidedExports() ) {
if ( exportName === 'default' ) {
sourceString += `export default __library__.default;\n`;
} else {
sourceString += `export const ${ exportName } = __library__.${ exportName };\n`;
}
}

const contentHash = createHash( hashFunction );
contentHash.update( sourceString );

compilation.assets[ generatedProxyModuleFilename ] =
new RawSource( sourceString );

chunk.files.add( generatedProxyModuleFilename );

const assetData = {
dependencies: [
// { id: `wp-${ chunk.name }`, import: 'wp-script' },
{
id: `@wordpress-esm/${ chunk.name }`,
import: 'dynamic',
},
],
version: contentHash
.digest( hashDigest )
.slice( 0, hashDigestLength ),
};
combinedAssetsData[ generatedProxyModuleFilename ] = assetData;
}
}

const outputFolder = compilation.outputOptions.path;

const assetsFilePath = path.resolve( outputFolder, combinedOutputFile );
const assetsFilename = path.relative( outputFolder, assetsFilePath );

// Add source into compilation for webpack to output.
compilation.assets[ assetsFilename ] = new RawSource(
this.stringify( combinedAssetsData )
);
}
}

module.exports = WpScriptsPackageProxyModuleWebpackPlugin;
Loading
Loading