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