Make WordPress Core

Changeset 58579


Ignore:
Timestamp:
06/26/2024 01:19:47 PM (2 years ago)
Author:
Bernhard Reiter
Message:

Script Modules: Add new API to embed server data in HTML.

Add a new filter script_module_data_{$module_id} to associate data
with a Script Module. For example:

add_filter(
        'script_module_data_MyScriptModuleID',
        function ( array $data ): array {
                $data['script-needs-this-data'] = 'ok';
                return $data;
        }
);

If the Script Module is included in the page, enqueued or as a
dependency, the associated data will be JSON-encoded and embedded in the
HTML in a <script type="application/json"> tag with an ID of the form
wp-script-module-data-{$module_id} allowing the Script Module to
access the data on the client.

See the original proposal: ​https://make.wordpress.org/core/2024/05/06/proposal-server-to-client-data-sharing-for-script-modules/

Developed in ​https://github.com/WordPress/wordpress-develop/pull/6682.

Props jonsurrell, cbravobernal, westonruter, gziolo, bernhard-reiter, youknowriad, sergiomdgomes, czapla.
Fixes #61510. See #60647.

Location:
trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/class-wp-script-modules.php

    r58126 r58579  
    183183                add_action( 'admin_print_footer_scripts', array( $this, 'print_enqueued_script_modules' ) );
    184184                add_action( 'admin_print_footer_scripts', array( $this, 'print_script_module_preloads' ) );
     185
     186                add_action( 'wp_footer', array( $this, 'print_script_module_data' ) );
     187                add_action( 'admin_print_footer_scripts', array( $this, 'print_script_module_data' ) );
    185188        }
    186189
    … …  
    364367                return $src;
    365368        }
     369
     370        /**
     371         * Print data associated with Script Modules.
     372         *
     373         * The data will be embedded in the page HTML and can be read by Script Modules on page load.
     374         *
     375         * @since 6.7.0
     376         *
     377         * Data can be associated with a Script Module via the
     378         * {@see "script_module_data_{$module_id}"} filter.
     379         *
     380         * The data for a Script Module will be serialized as JSON in a script tag with an ID of the
     381         * form `wp-script-module-data-{$module_id}`.
     382         */
     383        public function print_script_module_data(): void {
     384                $modules = array();
     385                foreach ( array_keys( $this->get_marked_for_enqueue() ) as $id ) {
     386                        $modules[ $id ] = true;
     387                }
     388                foreach ( array_keys( $this->get_import_map()['imports'] ) as $id ) {
     389                        $modules[ $id ] = true;
     390                }
     391
     392                foreach ( array_keys( $modules ) as $module_id ) {
     393                        /**
     394                         * Filters data associated with a given Script Module.
     395                         *
     396                         * Script Modules may require data that is required for initialization or is essential
     397                         * to have immediately available on page load. These are suitable use cases for
     398                         * this data.
     399                         *
     400                         * The dynamic portion of the hook name, `$module_id`, refers to the Script Module ID
     401                         * that the data is associated with.
     402                         *
     403                         * This is best suited to pass essential data that must be available to the module for
     404                         * initialization or immediately on page load. It does not replace the REST API or
     405                         * fetching data from the client.
     406                         *
     407                         * @example
     408                         *   add_filter(
     409                         *     'script_module_data_MyScriptModuleID',
     410                         *     function ( array $data ): array {
     411                         *       $data['script-needs-this-data'] = 'ok';
     412                         *       return $data;
     413                         *     }
     414                         *   );
     415                         *
     416                         * If the filter returns no data (an empty array), nothing will be embedded in the page.
     417                         *
     418                         * The data for a given Script Module, if provided, will be JSON serialized in a script
     419                         * tag with an ID of the form `wp-script-module-data-{$module_id}`.
     420                         *
     421                         * The data can be read on the client with a pattern like this:
     422                         *
     423                         * @example
     424                         *   const dataContainer = document.getElementById( 'wp-script-module-data-MyScriptModuleID' );
     425                         *   let data = {};
     426                         *   if ( dataContainer ) {
     427                         *     try {
     428                         *       data = JSON.parse( dataContainer.textContent );
     429                         *     } catch {}
     430                         *   }
     431                         *   initMyScriptModuleWithData( data );
     432                         *
     433                         * @since 6.7.0
     434                         *
     435                         * @param array $data The data associated with the Script Module.
     436                         */
     437                        $data = apply_filters( "script_module_data_{$module_id}", array() );
     438
     439                        if ( is_array( $data ) && array() !== $data ) {
     440                                /*
     441                                 * This data will be printed as JSON inside a script tag like this:
     442                                 *   <script type="application/json"></script>
     443                                 *
     444                                 * A script tag must be closed by a sequence beginning with `</`. It's impossible to
     445                                 * close a script tag without using `<`. We ensure that `<` is escaped and `/` can
     446                                 * remain unescaped, so `</script>` will be printed as `\u003C/script\u00E3`.
     447                                 *
     448                                 *   - JSON_HEX_TAG: All < and > are converted to \u003C and \u003E.
     449                                 *   - JSON_UNESCAPED_SLASHES: Don't escape /.
     450                                 *
     451                                 * If the page will use UTF-8 encoding, it's safe to print unescaped unicode:
     452                                 *
     453                                 *   - JSON_UNESCAPED_UNICODE: Encode multibyte Unicode characters literally (instead of as `\uXXXX`).
     454                                 *   - JSON_UNESCAPED_LINE_TERMINATORS: The line terminators are kept unescaped when
     455                                 *     JSON_UNESCAPED_UNICODE is supplied. It uses the same behaviour as it was
     456                                 *     before PHP 7.1 without this constant. Available as of PHP 7.1.0.
     457                                 *
     458                                 * The JSON specification requires encoding in UTF-8, so if the generated HTML page
     459                                 * is not encoded in UTF-8 then it's not safe to include those literals. They must
     460                                 * be escaped to avoid encoding issues.
     461                                 *
     462                                 * @see https://www.rfc-editor.org/rfc/rfc8259.html for details on encoding requirements.
     463                                 * @see https://www.php.net/manual/en/json.constants.php for details on these constants.
     464                                 * @see https://html.spec.whatwg.org/#script-data-state for details on script tag parsing.
     465                                 */
     466                                $json_encode_flags = JSON_HEX_TAG | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_LINE_TERMINATORS;
     467                                if ( ! is_utf8_charset() ) {
     468                                        $json_encode_flags = JSON_HEX_TAG | JSON_UNESCAPED_SLASHES;
     469                                }
     470
     471                                wp_print_inline_script_tag(
     472                                        wp_json_encode(
     473                                                $data,
     474                                                $json_encode_flags
     475                                        ),
     476                                        array(
     477                                                'type' => 'application/json',
     478                                                'id'   => "wp-script-module-data-{$module_id}",
     479                                        )
     480                                );
     481                        }
     482                }
     483        }
    366484}
  • trunk/tests/phpunit/tests/script-modules/wpScriptModules.php

    r58420 r58579  
    733733                $this->assertSame( 'wp-load-polyfill-importmap', $id );
    734734        }
     735
     736        /**
     737         * @ticket 61510
     738         */
     739        public function test_print_script_module_data_prints_enqueued_module_data() {
     740                $this->script_modules->enqueue( '@test/module', '/example.js' );
     741                add_action(
     742                        'script_module_data_@test/module',
     743                        function ( $data ) {
     744                                $data['foo'] = 'bar';
     745                                return $data;
     746                        }
     747                );
     748
     749                $actual = get_echo( array( $this->script_modules, 'print_script_module_data' ) );
     750
     751                $expected = <<<HTML
     752<script type="application/json" id="wp-script-module-data-@test/module">
     753{"foo":"bar"}
     754</script>
     755
     756HTML;
     757                $this->assertSame( $expected, $actual );
     758        }
     759
     760        /**
     761         * @ticket 61510
     762         */
     763        public function test_print_script_module_data_prints_dependency_module_data() {
     764                $this->script_modules->register( '@test/dependency', '/dependency.js' );
     765                $this->script_modules->enqueue( '@test/module', '/example.js', array( '@test/dependency' ) );
     766                add_action(
     767                        'script_module_data_@test/dependency',
     768                        function ( $data ) {
     769                                $data['foo'] = 'bar';
     770                                return $data;
     771                        }
     772                );
     773
     774                $actual = get_echo( array( $this->script_modules, 'print_script_module_data' ) );
     775
     776                $expected = <<<HTML
     777<script type="application/json" id="wp-script-module-data-@test/dependency">
     778{"foo":"bar"}
     779</script>
     780
     781HTML;
     782                $this->assertSame( $expected, $actual );
     783        }
     784
     785        /**
     786         * @ticket 61510
     787         */
     788        public function test_print_script_module_data_does_not_print_nondependency_module_data() {
     789                $this->script_modules->register( '@test/other', '/dependency.js' );
     790                $this->script_modules->enqueue( '@test/module', '/example.js' );
     791                add_action(
     792                        'script_module_data_@test/other',
     793                        function ( $data ) {
     794                                $data['foo'] = 'bar';
     795                                return $data;
     796                        }
     797                );
     798
     799                $actual = get_echo( array( $this->script_modules, 'print_script_module_data' ) );
     800
     801                $this->assertSame( '', $actual );
     802        }
     803
     804        /**
     805         * @ticket 61510
     806         */
     807        public function test_print_script_module_data_does_not_print_empty_data() {
     808                $this->script_modules->enqueue( '@test/module', '/example.js' );
     809                add_action(
     810                        'script_module_data_@test/module',
     811                        function ( $data ) {
     812                                return $data;
     813                        }
     814                );
     815
     816                $actual = get_echo( array( $this->script_modules, 'print_script_module_data' ) );
     817
     818                $this->assertSame( '', $actual );
     819        }
     820
     821        /**
     822         * @ticket 61510
     823         *
     824         * @dataProvider data_special_chars_script_encoding
     825         * @param string $input    Raw input string.
     826         * @param string $expected Expected output string.
     827         * @param string $charset  Blog charset option.
     828         */
     829        public function test_print_script_module_data_encoding( $input, $expected, $charset ) {
     830                add_filter(
     831                        'pre_option_blog_charset',
     832                        function () use ( $charset ) {
     833                                return $charset;
     834                        }
     835                );
     836
     837                $this->script_modules->enqueue( '@test/module', '/example.js' );
     838                add_action(
     839                        'script_module_data_@test/module',
     840                        function ( $data ) use ( $input ) {
     841                                $data[''] = $input;
     842                                return $data;
     843                        }
     844                );
     845
     846                $actual = get_echo( array( $this->script_modules, 'print_script_module_data' ) );
     847
     848                $expected = <<<HTML
     849<script type="application/json" id="wp-script-module-data-@test/module">
     850{"":"{$expected}"}
     851</script>
     852
     853HTML;
     854
     855                $this->assertSame( $expected, $actual );
     856        }
     857
     858        /**
     859         * Data provider.
     860         *
     861         * @return array
     862         */
     863        public static function data_special_chars_script_encoding(): array {
     864                return array(
     865                        // UTF-8
     866                        'Solidus'                                => array( '/', '/', 'UTF-8' ),
     867                        'Double quote'                           => array( '"', '\\"', 'UTF-8' ),
     868                        'Single quote'                           => array( '\'', '\'', 'UTF-8' ),
     869                        'Less than'                              => array( '<', '\u003C', 'UTF-8' ),
     870                        'Greater than'                           => array( '>', '\u003E', 'UTF-8' ),
     871                        'Ampersand'                              => array( '&', '&', 'UTF-8' ),
     872                        'Newline'                                => array( "\n", "\\n", 'UTF-8' ),
     873                        'Tab'                                    => array( "\t", "\\t", 'UTF-8' ),
     874                        'Form feed'                              => array( "\f", "\\f", 'UTF-8' ),
     875                        'Carriage return'                        => array( "\r", "\\r", 'UTF-8' ),
     876                        'Line separator'                         => array( "\u{2028}", "\u{2028}", 'UTF-8' ),
     877                        'Paragraph separator'                    => array( "\u{2029}", "\u{2029}", 'UTF-8' ),
     878
     879                        /*
     880                         * The following is the Flag of England emoji
     881                         * PHP: "\u{1F3F4}\u{E0067}\u{E0062}\u{E0065}\u{E006E}\u{E0067}\u{E007F}"
     882                         */
     883                        'Flag of england'                        => array( '🏴󠁧󠁢󠁥󠁮󠁧󠁿', '🏴󠁧󠁢󠁥󠁮󠁧󠁿', 'UTF-8' ),
     884                        'Malicious script closer'                => array( '</script>', '\u003C/script\u003E', 'UTF-8' ),
     885                        'Entity-encoded malicious script closer' => array( '&lt;/script&gt;', '&lt;/script&gt;', 'UTF-8' ),
     886
     887                        // Non UTF-8
     888                        'Solidus'                                => array( '/', '/', 'iso-8859-1' ),
     889                        'Less than'                              => array( '<', '\u003C', 'iso-8859-1' ),
     890                        'Greater than'                           => array( '>', '\u003E', 'iso-8859-1' ),
     891                        'Ampersand'                              => array( '&', '&', 'iso-8859-1' ),
     892                        'Newline'                                => array( "\n", "\\n", 'iso-8859-1' ),
     893                        'Tab'                                    => array( "\t", "\\t", 'iso-8859-1' ),
     894                        'Form feed'                              => array( "\f", "\\f", 'iso-8859-1' ),
     895                        'Carriage return'                        => array( "\r", "\\r", 'iso-8859-1' ),
     896                        'Line separator'                         => array( "\u{2028}", "\u2028", 'iso-8859-1' ),
     897                        'Paragraph separator'                    => array( "\u{2029}", "\u2029", 'iso-8859-1' ),
     898                        /*
     899                         * The following is the Flag of England emoji
     900                         * PHP: "\u{1F3F4}\u{E0067}\u{E0062}\u{E0065}\u{E006E}\u{E0067}\u{E007F}"
     901                         */
     902                        'Flag of england'                        => array( '🏴󠁧󠁢󠁥󠁮󠁧󠁿', "\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc65\udb40\udc6e\udb40\udc67\udb40\udc7f", 'iso-8859-1' ),
     903                        'Malicious script closer'                => array( '</script>', '\u003C/script\u003E', 'iso-8859-1' ),
     904                        'Entity-encoded malicious script closer' => array( '&lt;/script&gt;', '&lt;/script&gt;', 'iso-8859-1' ),
     905
     906                );
     907        }
     908
     909        /**
     910         * @ticket 61510
     911         *
     912         * @dataProvider data_invalid_script_module_data
     913         * @param mixed $data Data to return in filter.
     914         */
     915        public function test_print_script_module_data_does_not_print_invalid_data( $data ) {
     916                $this->script_modules->enqueue( '@test/module', '/example.js' );
     917                add_action(
     918                        'script_module_data_@test/module',
     919                        function ( $_ ) use ( $data ) {
     920                                return $data;
     921                        }
     922                );
     923
     924                $actual = get_echo( array( $this->script_modules, 'print_script_module_data' ) );
     925
     926                $this->assertSame( '', $actual );
     927        }
     928
     929        /**
     930         * Data provider.
     931         *
     932         * @return array
     933         */
     934        public static function data_invalid_script_module_data(): array {
     935                return array(
     936                        'null'     => array( null ),
     937                        'stdClass' => array( new stdClass() ),
     938                        'number 1' => array( 1 ),
     939                        'string'   => array( 'string' ),
     940                );
     941        }
    735942}
Note: See TracChangeset for help on using the changeset viewer.