PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 16.3
Jetpack – WP Security, Backup, Speed, & Growth v16.3
16.3 16.3-beta 16.3-a.5 16.3-a.7 16.3-a.3 16.3-a.1 16.2 16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 All 508 releases
jetpack / jetpack_vendor / automattic / jetpack-wp-build-polyfills / src / class-wp-build-polyfills.php

class-wp-build-polyfills.php in Jetpack – WP Security, Backup, Speed, & Growth 16.3, at jetpack_vendor/automattic/jetpack-wp-build-polyfills/src/class-wp-build-polyfills.php

396 lines 14.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Polyfill registration for Core packages not available or incomplete in older WordPress versions.
4 *
5 * On WordPress 7.0 at the default threshold, only wp-private-apis and wp-rich-text replace Core's
6 * copies; every other polyfill fills in what Core lacks, or replaces a Gutenberg copy too old to use.
7 *
8 * @package automattic/jetpack-wp-build-polyfills
9 */
10
11 namespace Automattic\Jetpack\WP_Build_Polyfills;
12
13 /**
14 * Registers polyfill scripts and modules for WordPress Core packages.
15 */
16 class WP_Build_Polyfills {
17
18 /**
19 * Available polyfill handles for classic scripts.
20 */
21 const SCRIPT_HANDLES = array( 'wp-notices', 'wp-private-apis', 'wp-rich-text', 'wp-theme', 'wp-views' );
22
23 /**
24 * Available polyfill module IDs.
25 */
26 const MODULE_IDS = array( '@wordpress/boot', '@wordpress/route', '@wordpress/a11y', '@wordpress/widget-primitives' );
27
28 /**
29 * Polyfills that only work when another polyfill is registered alongside them.
30 *
31 * These bundles call `__dangerousOptInToUnstableAPIsOnlyForCoreModules()` at
32 * module scope, which throws unless the `wp-private-apis` implementation that
33 * actually loads allowlists their package name. WP 7.0's allowlist omits
34 * `@wordpress/views` and `@wordpress/compose` (bundled into the rich-text
35 * polyfill), so requesting either polyfill without `wp-private-apis` blanks
36 * the page. It does allow `@wordpress/theme`, and WP 7.0 registers `wp-theme`
37 * itself, so the theme polyfill never loads there.
38 *
39 * The `wp-private-apis` script dependency in each `.asset.php` is not enough
40 * on its own — it makes WordPress enqueue the *handle*, which resolves to
41 * Core's incomplete implementation unless the polyfill was requested too.
42 *
43 * @var array<string, string[]>
44 */
45 const SCRIPT_DEPENDENCIES = array(
46 'wp-rich-text' => array( 'wp-private-apis' ),
47 'wp-theme' => array( 'wp-private-apis' ),
48 'wp-views' => array( 'wp-private-apis' ),
49 );
50
51 /**
52 * Minimum Gutenberg plugin version known to ship a private-apis allowlist
53 * that includes the dashboard packages used by this package's current build.
54 */
55 const GUTENBERG_PRIVATE_APIS_MIN_VERSION = '23.5.0';
56
57 /**
58 * Minimum Gutenberg plugin version whose rich-text ships all the privateApis
59 * keys dashboard packages unlock (useRichText, KeyboardShortcutContext,
60 * InputEventContext, shortcutsListener, inputEventsListener). They were
61 * completed by Gutenberg PR #78471, first released in 23.6.0 — verified
62 * against the released builds: 23.5.0 lacks three of the five keys.
63 */
64 const GUTENBERG_RICH_TEXT_MIN_VERSION = '23.6.0';
65
66 /**
67 * Minimum Gutenberg plugin version whose widget-primitives script module ships the
68 * `WidgetHostProvider` / `useWidgetHost` seam that widget-dashboard >= 0.6.0 imports at
69 * module scope (Gutenberg PR #81740, first released in 23.9.0).
70 */
71 const GUTENBERG_WIDGET_PRIMITIVES_MIN_VERSION = '23.9.0';
72
73 /**
74 * Tracks which polyfills have been requested and by which consumers.
75 *
76 * Keys are polyfill handles/module IDs, values are arrays of consumer names.
77 *
78 * @var array<string, string[]>
79 */
80 private static $requested = array();
81
82 /**
83 * Whether registration has already run, or been hooked to wp_default_scripts.
84 *
85 * @var bool
86 */
87 private static $hooked = false;
88
89 /**
90 * The WordPress version below which force-replacements are applied.
91 * When multiple consumers call register() with different thresholds,
92 * the highest threshold wins (most conservative approach).
93 *
94 * @var string
95 */
96 private static $wp_version_threshold = '7.0';
97
98 /**
99 * Overrides the build directory. Test seam, null in production.
100 *
101 * @var string|null
102 */
103 private static $build_dir_override = null;
104
105 /**
106 * Register polyfill scripts and modules.
107 *
108 * Call this early (e.g. during plugin load) — it hooks into wp_default_scripts
109 * at priority 20 so Core (default) and Gutenberg (priority 10) register first.
110 *
111 * When multiple consumers call this method with different thresholds, the
112 * highest threshold wins (most conservative — polyfills active on more versions).
113 *
114 * Polyfills listed in SCRIPT_DEPENDENCIES pull in their companion polyfill
115 * automatically, so consumers cannot request a combination that throws at
116 * load time. Those companions show up in get_consumers() under the
117 * requesting consumer's name.
118 *
119 * Every call also arms WP_Build_Admin_Frame for the request, which keeps the boot
120 * single-page layout in step with the wp-admin frame on every wp-build page.
121 *
122 * @param string $consumer A unique identifier for the consumer (e.g. plugin slug).
123 * @param string[] $polyfills List of polyfill handles/module IDs to register.
124 * Use class constants SCRIPT_HANDLES and MODULE_IDS for reference.
125 * @param string $wp_version_threshold The WordPress version below which force-replacements
126 * are applied. Defaults to '7.0'.
127 */
128 public static function register( $consumer, $polyfills, $wp_version_threshold = '7.0' ) {
129 WP_Build_Admin_Frame::register();
130
131 $added = array();
132 foreach ( $polyfills as $handle ) {
133 if ( ! in_array( $handle, self::SCRIPT_HANDLES, true ) && ! in_array( $handle, self::MODULE_IDS, true ) ) {
134 continue;
135 }
136
137 $required = array_merge( array( $handle ), self::SCRIPT_DEPENDENCIES[ $handle ] ?? array() );
138
139 foreach ( $required as $required_handle ) {
140 if ( ! isset( self::$requested[ $required_handle ] ) ) {
141 self::$requested[ $required_handle ] = array();
142 $added[] = $required_handle;
143 }
144 if ( ! in_array( $consumer, self::$requested[ $required_handle ], true ) ) {
145 self::$requested[ $required_handle ][] = $consumer;
146 }
147 }
148 }
149
150 $raised = version_compare( $wp_version_threshold, self::$wp_version_threshold, '>' );
151 if ( $raised ) {
152 self::$wp_version_threshold = $wp_version_threshold;
153 }
154
155 $package_root = dirname( __DIR__ );
156 $build_dir = self::$build_dir_override ?? $package_root . '/build';
157 $base_file = $package_root . '/composer.json';
158
159 if ( self::$hooked ) {
160 // Registration already ran, so apply this call's new polyfills and raised threshold to it.
161 if ( ( $raised || $added ) && did_action( 'wp_default_scripts' ) ) {
162 self::register_scripts( wp_scripts(), $build_dir, $base_file, self::$wp_version_threshold );
163 self::register_modules( $build_dir, $base_file, $added );
164 }
165 return;
166 }
167 self::$hooked = true;
168
169 // `wp_default_scripts` fires when `wp_scripts()` creates the WP_Scripts singleton, and again on
170 // `init` if it was created before then. Once it has fired (common on admin requests by
171 // `admin_menu`), a hook added now may never run, so register synchronously instead.
172 if ( did_action( 'wp_default_scripts' ) ) {
173 self::register_scripts( wp_scripts(), $build_dir, $base_file, self::$wp_version_threshold );
174 self::register_modules( $build_dir, $base_file );
175 return;
176 }
177
178 add_action(
179 'wp_default_scripts',
180 function ( $scripts ) use ( $build_dir, $base_file ) {
181 self::register_scripts( $scripts, $build_dir, $base_file, self::$wp_version_threshold );
182 self::register_modules( $build_dir, $base_file );
183 },
184 20
185 );
186 }
187
188 /**
189 * Get the map of requested polyfills and their consumers.
190 *
191 * @return array<string, string[]> Keys are polyfill handles/module IDs, values are consumer names.
192 */
193 public static function get_consumers() {
194 return self::$requested;
195 }
196
197 /**
198 * Register polyfill classic scripts.
199 *
200 * @param \WP_Scripts $scripts The WP_Scripts instance.
201 * @param string $build_dir Absolute path to the build directory.
202 * @param string $base_file File path for plugins_url() computation.
203 * @param string $wp_version_threshold WP version below which force-replacements apply.
204 */
205 private static function register_scripts( $scripts, $build_dir, $base_file, $wp_version_threshold ) {
206 // Force-replace only when Core's bundled scripts are incomplete and
207 // Gutenberg cannot be trusted to provide a compatible implementation.
208 $gutenberg_version = defined( 'GUTENBERG_VERSION' ) ? GUTENBERG_VERSION : null;
209
210 $polyfills = array(
211 'wp-notices' => array(
212 'path' => 'notices',
213 'force_threshold' => '7.0',
214 // WP 7.0 ships the SnackbarNotices and InlineNotices exports
215 // @wordpress/boot depends on, so on a supported site this forces only
216 // when a consumer raises the threshold, and never with Gutenberg active.
217 ),
218 'wp-private-apis' => array(
219 'path' => 'private-apis',
220 'force_threshold' => '7.1',
221 'gutenberg_min_version' => self::GUTENBERG_PRIVATE_APIS_MIN_VERSION,
222 // WP 7.0's private-apis allowlist rejects newer dashboard packages
223 // such as @wordpress/views and @wordpress/widget-dashboard. Active
224 // Gutenberg is only a safe substitute once its private-apis
225 // allowlist includes those dashboard packages too.
226 ),
227 'wp-rich-text' => array(
228 'path' => 'rich-text',
229 'force_threshold' => '7.1',
230 'gutenberg_min_version' => self::GUTENBERG_RICH_TEXT_MIN_VERSION,
231 // WP 7.0 ships a rich-text that locks only `useRichText` into
232 // `privateApis`, so current dashboard dependencies that unlock more
233 // keys at module scope (e.g. @wordpress/dataviews >= 17.2 dataform
234 // controls) get undefined and the page blanks. Older Gutenberg is
235 // not a safe substitute either — see the constant's doc.
236 ),
237 'wp-theme' => array(
238 'path' => 'theme',
239 ),
240 'wp-views' => array(
241 'path' => 'views',
242 ),
243 );
244
245 foreach ( $polyfills as $handle => $data ) {
246 if ( ! isset( self::$requested[ $handle ] ) ) {
247 continue;
248 }
249
250 $asset_file = $build_dir . '/scripts/' . $data['path'] . '/index.asset.php';
251
252 if ( ! file_exists( $asset_file ) ) {
253 continue;
254 }
255
256 $src = plugins_url( 'build/scripts/' . $data['path'] . '/index.js', $base_file );
257
258 // Already ours from an earlier register() call; replacing it would drop anything attached since.
259 $registered = $scripts->query( $handle, 'registered' );
260 if ( $registered && $src === $registered->src ) {
261 continue;
262 }
263
264 $force_threshold = $data['force_threshold'] ?? null;
265 if ( null !== $force_threshold && version_compare( $wp_version_threshold, $force_threshold, '>' ) ) {
266 $force_threshold = $wp_version_threshold;
267 }
268
269 $force = null !== $force_threshold
270 && ! self::is_gutenberg_version_safe( $data['gutenberg_min_version'] ?? null, $gutenberg_version )
271 && version_compare( $GLOBALS['wp_version'] ?? '0', $force_threshold, '<' );
272
273 if ( ! $force && $scripts->query( $handle, 'registered' ) ) {
274 continue;
275 }
276
277 // Deregister first when forcing replacement of an existing registration.
278 // `remove()` drops everything Core set up alongside the src — notably
279 // `$args` (Core registers package scripts with `1`, i.e. in the footer)
280 // and the registered translations. Both are restored after `add()` so
281 // the replacement is a drop-in for the registration it displaces.
282 $replaced = null;
283 if ( $force && $scripts->query( $handle, 'registered' ) ) {
284 $replaced = $scripts->registered[ $handle ];
285 $scripts->remove( $handle );
286 }
287
288 $asset = require $asset_file;
289
290 $scripts->add(
291 $handle,
292 $src,
293 $asset['dependencies'],
294 $asset['version'],
295 // Match Core's `wp_default_packages_scripts()`, which registers every
296 // `wp-*` package script in the footer.
297 null !== $replaced ? $replaced->args : 1
298 );
299
300 if ( null !== $replaced && null !== $replaced->textdomain ) {
301 $scripts->set_translations( $handle, $replaced->textdomain, $replaced->translations_path );
302 } elseif ( in_array( 'wp-i18n', $asset['dependencies'], true ) ) {
303 // Same rule Core applies when registering its own package scripts.
304 // Translations resolve via `{locale}-{handle}.json`, which is keyed
305 // by handle, so the polyfill's own src path does not break the lookup.
306 $scripts->set_translations( $handle );
307 }
308 }
309 }
310
311 /**
312 * Check whether the active Gutenberg plugin can satisfy a forced script.
313 *
314 * @param string|null $minimum_version Minimum Gutenberg version required for the script, or null when any active Gutenberg is sufficient.
315 * @param string|null $gutenberg_version Active Gutenberg version, or null when Gutenberg is inactive.
316 * @return bool True when Gutenberg is active and new enough.
317 */
318 private static function is_gutenberg_version_safe( $minimum_version, $gutenberg_version ) {
319 if ( null === $gutenberg_version ) {
320 return false;
321 }
322
323 if ( null === $minimum_version ) {
324 return true;
325 }
326
327 return version_compare( $gutenberg_version, $minimum_version, '>=' );
328 }
329
330 /**
331 * Register polyfill script modules.
332 *
333 * Calls to wp_register_script_module() silently ignore duplicate registrations (first wins), so an
334 * already registered module is left alone unless the active Gutenberg's copy is known to be
335 * too old for this package's current build, in which case it is replaced.
336 *
337 * @param string $build_dir Absolute path to the build directory.
338 * @param string $base_file File path for plugins_url() computation.
339 * @param string[]|null $module_ids Only these requested module IDs, or null for all of them.
340 */
341 private static function register_modules( $build_dir, $base_file, $module_ids = null ) {
342 if ( ! function_exists( 'wp_register_script_module' ) ) {
343 return;
344 }
345
346 $gutenberg_version = defined( 'GUTENBERG_VERSION' ) ? GUTENBERG_VERSION : null;
347
348 $modules = array(
349 'boot' => array(),
350 'route' => array(),
351 'a11y' => array(),
352 'widget-primitives' => array(
353 // Gutenberg re-registers Core's script modules with its own copies, and
354 // older ones lack exports widget-dashboard imports at module scope. The
355 // replacement only adds exports, so Gutenberg's own consumers keep working.
356 'gutenberg_min_version' => self::GUTENBERG_WIDGET_PRIMITIVES_MIN_VERSION,
357 ),
358 );
359
360 foreach ( $modules as $name => $data ) {
361 $module_id = '@wordpress/' . $name;
362
363 if ( ! isset( self::$requested[ $module_id ] ) ) {
364 continue;
365 }
366
367 if ( null !== $module_ids && ! in_array( $module_id, $module_ids, true ) ) {
368 continue;
369 }
370
371 $asset_file = $build_dir . '/modules/' . $name . '/index.asset.php';
372
373 if ( ! file_exists( $asset_file ) ) {
374 continue;
375 }
376
377 $asset = require $asset_file;
378
379 if (
380 isset( $data['gutenberg_min_version'] )
381 && null !== $gutenberg_version
382 && ! self::is_gutenberg_version_safe( $data['gutenberg_min_version'], $gutenberg_version )
383 ) {
384 wp_deregister_script_module( $module_id );
385 }
386
387 wp_register_script_module(
388 $module_id,
389 plugins_url( 'build/modules/' . $name . '/index.js', $base_file ),
390 $asset['module_dependencies'] ?? array(),
391 $asset['version']
392 );
393 }
394 }
395 }
396