2010-10-19 18:25:42 +00:00
|
|
|
<?php
|
|
|
|
|
/**
|
|
|
|
|
* This program is free software; you can redistribute it and/or modify
|
|
|
|
|
* it under the terms of the GNU General Public License as published by
|
|
|
|
|
* the Free Software Foundation; either version 2 of the License, or
|
|
|
|
|
* (at your option) any later version.
|
|
|
|
|
*
|
|
|
|
|
* This program is distributed in the hope that it will be useful,
|
|
|
|
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
|
* GNU General Public License for more details.
|
|
|
|
|
*
|
|
|
|
|
* You should have received a copy of the GNU General Public License along
|
|
|
|
|
* with this program; if not, write to the Free Software Foundation, Inc.,
|
|
|
|
|
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
|
|
|
|
* http://www.gnu.org/copyleft/gpl.html
|
|
|
|
|
*
|
|
|
|
|
* @file
|
|
|
|
|
* @author Trevor Parscal
|
|
|
|
|
* @author Roan Kattouw
|
|
|
|
|
*/
|
|
|
|
|
|
2019-12-15 19:11:40 +00:00
|
|
|
use MediaWiki\Languages\LanguageFallback;
|
|
|
|
|
use MediaWiki\MediaWikiServices;
|
2021-02-18 04:38:29 +00:00
|
|
|
use Wikimedia\Minify\CSSMin;
|
2019-12-15 19:11:40 +00:00
|
|
|
|
2010-10-19 18:25:42 +00:00
|
|
|
/**
|
2019-09-14 04:32:54 +00:00
|
|
|
* Module based on local JavaScript/CSS files.
|
2019-06-19 22:44:39 +00:00
|
|
|
*
|
|
|
|
|
* The following public methods can query the database:
|
|
|
|
|
*
|
|
|
|
|
* - getDefinitionSummary / … / ResourceLoaderModule::getFileDependencies.
|
|
|
|
|
* - getVersionHash / getDefinitionSummary / … / ResourceLoaderModule::getFileDependencies.
|
|
|
|
|
* - getStyles / ResourceLoaderModule::saveFileDependencies.
|
2019-09-14 04:32:54 +00:00
|
|
|
*
|
|
|
|
|
* @ingroup ResourceLoader
|
2020-03-25 23:05:54 +00:00
|
|
|
* @see $wgResourceModules
|
2019-09-14 04:32:54 +00:00
|
|
|
* @since 1.17
|
2010-10-19 18:25:42 +00:00
|
|
|
*/
|
|
|
|
|
class ResourceLoaderFileModule extends ResourceLoaderModule {
|
2014-04-20 21:33:05 +00:00
|
|
|
/** @var string Local base path, see __construct() */
|
2010-10-27 22:22:10 +00:00
|
|
|
protected $localBasePath = '';
|
2014-05-10 08:39:37 +00:00
|
|
|
|
2014-04-20 21:33:05 +00:00
|
|
|
/** @var string Remote base path, see __construct() */
|
2010-10-27 22:22:10 +00:00
|
|
|
protected $remoteBasePath = '';
|
2014-05-10 08:39:37 +00:00
|
|
|
|
2014-10-10 00:07:14 +00:00
|
|
|
/** @var array Saves a list of the templates named by the modules. */
|
2016-02-17 09:09:32 +00:00
|
|
|
protected $templates = [];
|
2014-10-10 00:07:14 +00:00
|
|
|
|
2010-10-20 20:43:30 +00:00
|
|
|
/**
|
2014-04-20 21:33:05 +00:00
|
|
|
* @var array List of paths to JavaScript files to always include
|
2012-02-01 17:05:15 +00:00
|
|
|
* @par Usage:
|
|
|
|
|
* @code
|
2016-08-13 01:10:40 +00:00
|
|
|
* [ [file-path], [file-path], ... ]
|
2012-02-01 17:05:15 +00:00
|
|
|
* @endcode
|
2010-10-20 20:43:30 +00:00
|
|
|
*/
|
2016-02-17 09:09:32 +00:00
|
|
|
protected $scripts = [];
|
2014-05-10 08:39:37 +00:00
|
|
|
|
2010-10-20 20:43:30 +00:00
|
|
|
/**
|
2014-04-20 21:33:05 +00:00
|
|
|
* @var array List of JavaScript files to include when using a specific language
|
2012-02-01 17:05:15 +00:00
|
|
|
* @par Usage:
|
|
|
|
|
* @code
|
2016-08-13 01:10:40 +00:00
|
|
|
* [ [language-code] => [ [file-path], [file-path], ... ], ... ]
|
2012-02-01 17:05:15 +00:00
|
|
|
* @endcode
|
2010-10-20 20:43:30 +00:00
|
|
|
*/
|
2016-02-17 09:09:32 +00:00
|
|
|
protected $languageScripts = [];
|
2014-05-10 08:39:37 +00:00
|
|
|
|
2010-10-20 20:43:30 +00:00
|
|
|
/**
|
2014-04-20 21:33:05 +00:00
|
|
|
* @var array List of JavaScript files to include when using a specific skin
|
2012-02-01 17:05:15 +00:00
|
|
|
* @par Usage:
|
|
|
|
|
* @code
|
2016-08-13 01:10:40 +00:00
|
|
|
* [ [skin-name] => [ [file-path], [file-path], ... ], ... ]
|
2012-02-01 17:05:15 +00:00
|
|
|
* @endcode
|
2010-10-20 20:43:30 +00:00
|
|
|
*/
|
2016-02-17 09:09:32 +00:00
|
|
|
protected $skinScripts = [];
|
2014-05-10 08:39:37 +00:00
|
|
|
|
2010-10-20 20:43:30 +00:00
|
|
|
/**
|
2014-04-20 21:33:05 +00:00
|
|
|
* @var array List of paths to JavaScript files to include in debug mode
|
2012-02-01 17:05:15 +00:00
|
|
|
* @par Usage:
|
|
|
|
|
* @code
|
2016-08-13 01:10:40 +00:00
|
|
|
* [ [skin-name] => [ [file-path], [file-path], ... ], ... ]
|
2012-02-01 17:05:15 +00:00
|
|
|
* @endcode
|
2010-10-20 20:43:30 +00:00
|
|
|
*/
|
2016-02-17 09:09:32 +00:00
|
|
|
protected $debugScripts = [];
|
2014-05-10 08:39:37 +00:00
|
|
|
|
2010-10-20 20:43:30 +00:00
|
|
|
/**
|
2014-04-20 21:33:05 +00:00
|
|
|
* @var array List of paths to CSS files to always include
|
2012-02-01 17:05:15 +00:00
|
|
|
* @par Usage:
|
|
|
|
|
* @code
|
2016-08-13 01:10:40 +00:00
|
|
|
* [ [file-path], [file-path], ... ]
|
2012-02-01 17:05:15 +00:00
|
|
|
* @endcode
|
2010-10-20 20:43:30 +00:00
|
|
|
*/
|
2016-02-17 09:09:32 +00:00
|
|
|
protected $styles = [];
|
2014-05-10 08:39:37 +00:00
|
|
|
|
2010-10-20 20:43:30 +00:00
|
|
|
/**
|
2014-04-20 21:33:05 +00:00
|
|
|
* @var array List of paths to CSS files to include when using specific skins
|
2012-02-01 17:05:15 +00:00
|
|
|
* @par Usage:
|
|
|
|
|
* @code
|
2016-08-13 01:10:40 +00:00
|
|
|
* [ [file-path], [file-path], ... ]
|
2012-02-01 17:05:15 +00:00
|
|
|
* @endcode
|
2010-10-20 20:43:30 +00:00
|
|
|
*/
|
2016-02-17 09:09:32 +00:00
|
|
|
protected $skinStyles = [];
|
2014-05-10 08:39:37 +00:00
|
|
|
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
/**
|
|
|
|
|
* @var array List of packaged files to make available through require()
|
|
|
|
|
* @par Usage:
|
|
|
|
|
* @code
|
2019-10-24 15:12:20 +00:00
|
|
|
* [ [file-path-or-object], [file-path-or-object], ... ]
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
* @endcode
|
|
|
|
|
*/
|
|
|
|
|
protected $packageFiles = null;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @var array Expanded versions of $packageFiles, lazy-computed by expandPackageFiles();
|
|
|
|
|
* keyed by context hash
|
|
|
|
|
*/
|
|
|
|
|
private $expandedPackageFiles = [];
|
|
|
|
|
|
2020-02-04 01:42:03 +00:00
|
|
|
/**
|
|
|
|
|
* @var array Further expanded versions of $expandedPackageFiles, lazy-computed by
|
|
|
|
|
* getPackageFiles(); keyed by context hash
|
|
|
|
|
*/
|
|
|
|
|
private $fullyExpandedPackageFiles = [];
|
|
|
|
|
|
2010-10-20 20:43:30 +00:00
|
|
|
/**
|
2014-04-20 21:33:05 +00:00
|
|
|
* @var array List of modules this module depends on
|
2012-02-01 17:05:15 +00:00
|
|
|
* @par Usage:
|
|
|
|
|
* @code
|
2016-08-13 01:10:40 +00:00
|
|
|
* [ [file-path], [file-path], ... ]
|
2012-02-01 17:05:15 +00:00
|
|
|
* @endcode
|
2010-10-20 20:43:30 +00:00
|
|
|
*/
|
2016-02-17 09:09:32 +00:00
|
|
|
protected $dependencies = [];
|
2014-05-10 08:39:37 +00:00
|
|
|
|
2014-04-30 21:06:51 +00:00
|
|
|
/**
|
|
|
|
|
* @var string File name containing the body of the skip function
|
|
|
|
|
*/
|
|
|
|
|
protected $skipFunction = null;
|
|
|
|
|
|
2010-10-20 20:43:30 +00:00
|
|
|
/**
|
2014-04-20 21:33:05 +00:00
|
|
|
* @var array List of message keys used by this module
|
2012-02-01 17:05:15 +00:00
|
|
|
* @par Usage:
|
|
|
|
|
* @code
|
2016-08-13 01:10:40 +00:00
|
|
|
* [ [message-key], [message-key], ... ]
|
2012-02-01 17:05:15 +00:00
|
|
|
* @endcode
|
2010-10-20 20:43:30 +00:00
|
|
|
*/
|
2016-02-17 09:09:32 +00:00
|
|
|
protected $messages = [];
|
2014-05-10 08:39:37 +00:00
|
|
|
|
2014-04-20 21:33:05 +00:00
|
|
|
/** @var string Name of group to load this module in */
|
2010-10-19 22:48:52 +00:00
|
|
|
protected $group;
|
2014-05-10 08:39:37 +00:00
|
|
|
|
2014-04-20 21:33:05 +00:00
|
|
|
/** @var bool Link to raw files in debug mode */
|
2010-10-21 01:03:46 +00:00
|
|
|
protected $debugRaw = true;
|
2014-05-10 08:39:37 +00:00
|
|
|
|
2020-10-28 10:01:33 +00:00
|
|
|
/** @var string[] */
|
2016-02-17 09:09:32 +00:00
|
|
|
protected $targets = [ 'desktop' ];
|
2012-10-11 22:37:59 +00:00
|
|
|
|
2016-10-18 19:04:40 +00:00
|
|
|
/** @var bool Whether CSSJanus flipping should be skipped for this module */
|
|
|
|
|
protected $noflip = false;
|
|
|
|
|
|
2021-01-23 07:33:38 +00:00
|
|
|
/** @var bool Whether this module requires the client to support ES6 */
|
|
|
|
|
protected $es6 = false;
|
|
|
|
|
|
Support LESS stylesheets in ResourceLoader
This patch adds support for the LESS stylesheet language to ResourceLoader.
LESS is a stylesheet language that compiles into CSS. The patch includes
lessphp, a LESS compiler implemented in PHP. The rationale for choosing LESS is
explained in a MediaWiki RFC which accompanies this patch, available at
<https://www.mediawiki.org/wiki/Requests_for_comment/LESS>.
LESS support is provided for ResourceLoader file modules. It is triggered by
the presence of the '.less' extension in stylesheet filenames. LESS files are
compiled by lessc, and the resultant CSS is subjected to the standard set of
transformations (CSSJanus & CSSMin). The immediate result of LESS compilation
is encoded as an array, which includes the list of LESS files that were
compiled and their mtimes. This array is cached. Cache invalidation is
performed by comparing the cached mtimes with the mtimes of the files on disk.
If the compiler itself throws an exception, ResourceLoader constructs a
compilation result which consists of the error message encoded as a CSS
comment. Failed compilation results are cached too, but with an expiration time
of five minutes. The expiration time is required because the full list of
referenced files is not known.
Three configuration variables configure the global environment for LESS
modules: $wgResourceLoaderLESSVars, $wgResourceLoaderLESSFunctions, and
$wgResourceLoaderLESSImportPaths. $wgResourceLoaderLESSVars maps variable names
to CSS values, specified as strings. Variables declared in this array are
available in all LESS files. $wgResourceLoaderLESSFunctions is similar, except
it maps custom function names to PHP callables. These functions can be called
from within LESS to transform values. Read more about custom functions at
<http://leafo.net/lessphp/docs/#custom_functions>. Finally,
$wgResourceLoaderLESSImportPaths specifies file system paths in addition to the
current module's path where the LESS compiler should look up files referenced
in @import statements.
The issue of handling of /* @embed */ and /* @noflip */ annotations is left
unresolved. Earlier versions of this patch included an @embed analog
implemented as a LESS custom function, but there was enough ambiguity about
whether the strategy it took was optimal to merit discussing it in a separate,
follow-up patch.
Bug: 40964
Change-Id: Id052a04dd2f76a1f4aef39fbd454bd67f5fd282f
2013-08-11 16:40:20 +00:00
|
|
|
/**
|
2014-04-20 21:33:05 +00:00
|
|
|
* @var bool Whether getStyleURLsForDebug should return raw file paths,
|
Support LESS stylesheets in ResourceLoader
This patch adds support for the LESS stylesheet language to ResourceLoader.
LESS is a stylesheet language that compiles into CSS. The patch includes
lessphp, a LESS compiler implemented in PHP. The rationale for choosing LESS is
explained in a MediaWiki RFC which accompanies this patch, available at
<https://www.mediawiki.org/wiki/Requests_for_comment/LESS>.
LESS support is provided for ResourceLoader file modules. It is triggered by
the presence of the '.less' extension in stylesheet filenames. LESS files are
compiled by lessc, and the resultant CSS is subjected to the standard set of
transformations (CSSJanus & CSSMin). The immediate result of LESS compilation
is encoded as an array, which includes the list of LESS files that were
compiled and their mtimes. This array is cached. Cache invalidation is
performed by comparing the cached mtimes with the mtimes of the files on disk.
If the compiler itself throws an exception, ResourceLoader constructs a
compilation result which consists of the error message encoded as a CSS
comment. Failed compilation results are cached too, but with an expiration time
of five minutes. The expiration time is required because the full list of
referenced files is not known.
Three configuration variables configure the global environment for LESS
modules: $wgResourceLoaderLESSVars, $wgResourceLoaderLESSFunctions, and
$wgResourceLoaderLESSImportPaths. $wgResourceLoaderLESSVars maps variable names
to CSS values, specified as strings. Variables declared in this array are
available in all LESS files. $wgResourceLoaderLESSFunctions is similar, except
it maps custom function names to PHP callables. These functions can be called
from within LESS to transform values. Read more about custom functions at
<http://leafo.net/lessphp/docs/#custom_functions>. Finally,
$wgResourceLoaderLESSImportPaths specifies file system paths in addition to the
current module's path where the LESS compiler should look up files referenced
in @import statements.
The issue of handling of /* @embed */ and /* @noflip */ annotations is left
unresolved. Earlier versions of this patch included an @embed analog
implemented as a LESS custom function, but there was enough ambiguity about
whether the strategy it took was optimal to merit discussing it in a separate,
follow-up patch.
Bug: 40964
Change-Id: Id052a04dd2f76a1f4aef39fbd454bd67f5fd282f
2013-08-11 16:40:20 +00:00
|
|
|
* or return load.php urls
|
|
|
|
|
*/
|
|
|
|
|
protected $hasGeneratedStyles = false;
|
|
|
|
|
|
2010-10-27 19:59:10 +00:00
|
|
|
/**
|
2014-04-20 21:33:05 +00:00
|
|
|
* @var array Place where readStyleFile() tracks file dependencies
|
2012-02-01 17:05:15 +00:00
|
|
|
* @par Usage:
|
|
|
|
|
* @code
|
2016-08-13 01:10:40 +00:00
|
|
|
* [ [file-path], [file-path], ... ]
|
2012-02-01 17:05:15 +00:00
|
|
|
* @endcode
|
2010-10-27 19:59:10 +00:00
|
|
|
*/
|
2016-02-17 09:09:32 +00:00
|
|
|
protected $localFileRefs = [];
|
2010-10-19 18:25:42 +00:00
|
|
|
|
2015-09-03 21:30:36 +00:00
|
|
|
/**
|
|
|
|
|
* @var array Place where readStyleFile() tracks file dependencies for non-existent files.
|
|
|
|
|
* Used in tests to detect missing dependencies.
|
|
|
|
|
*/
|
2016-02-17 09:09:32 +00:00
|
|
|
protected $missingLocalFileRefs = [];
|
2015-09-03 21:30:36 +00:00
|
|
|
|
2020-02-04 01:42:03 +00:00
|
|
|
/**
|
2020-06-14 18:40:02 +00:00
|
|
|
* @var VueComponentParser|null Lazy-created by getVueComponentParser()
|
2020-02-04 01:42:03 +00:00
|
|
|
*/
|
|
|
|
|
protected $vueComponentParser = null;
|
|
|
|
|
|
2010-10-19 18:25:42 +00:00
|
|
|
/**
|
2010-10-20 00:22:25 +00:00
|
|
|
* Constructs a new module from an options array.
|
2011-06-17 16:05:05 +00:00
|
|
|
*
|
2020-03-25 23:05:54 +00:00
|
|
|
* @param array $options See $wgResourceModules for the available options.
|
2018-06-26 21:14:43 +00:00
|
|
|
* @param string|null $localBasePath Base path to prepend to all local paths in $options.
|
|
|
|
|
* Defaults to $IP
|
|
|
|
|
* @param string|null $remoteBasePath Base path to prepend to all remote paths in $options.
|
|
|
|
|
* Defaults to $wgResourceBasePath
|
2015-03-30 16:51:10 +00:00
|
|
|
* @throws InvalidArgumentException
|
2020-03-25 23:05:54 +00:00
|
|
|
* @see $wgResourceModules
|
2010-10-19 18:25:42 +00:00
|
|
|
*/
|
2014-06-26 14:29:31 +00:00
|
|
|
public function __construct(
|
2019-10-05 07:38:41 +00:00
|
|
|
array $options = [],
|
2014-06-26 14:29:31 +00:00
|
|
|
$localBasePath = null,
|
2013-04-02 20:28:40 +00:00
|
|
|
$remoteBasePath = null
|
|
|
|
|
) {
|
2014-10-10 00:07:14 +00:00
|
|
|
// Flag to decide whether to automagically add the mediawiki.template module
|
|
|
|
|
$hasTemplates = false;
|
2014-06-26 14:29:31 +00:00
|
|
|
// localBasePath and remoteBasePath both have unbelievably long fallback chains
|
|
|
|
|
// and need to be handled separately.
|
|
|
|
|
list( $this->localBasePath, $this->remoteBasePath ) =
|
|
|
|
|
self::extractBasePaths( $options, $localBasePath, $remoteBasePath );
|
2014-06-01 17:25:11 +00:00
|
|
|
|
2014-06-26 14:29:31 +00:00
|
|
|
// Extract, validate and normalise remaining options
|
2010-10-19 20:59:23 +00:00
|
|
|
foreach ( $options as $member => $option ) {
|
|
|
|
|
switch ( $member ) {
|
|
|
|
|
// Lists of file paths
|
2010-10-19 18:25:42 +00:00
|
|
|
case 'scripts':
|
|
|
|
|
case 'debugScripts':
|
|
|
|
|
case 'styles':
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
case 'packageFiles':
|
2017-03-17 02:14:05 +00:00
|
|
|
$this->{$member} = is_array( $option ) ? $option : [ $option ];
|
2010-10-19 20:59:23 +00:00
|
|
|
break;
|
2014-10-10 00:07:14 +00:00
|
|
|
case 'templates':
|
|
|
|
|
$hasTemplates = true;
|
2017-03-17 02:14:05 +00:00
|
|
|
$this->{$member} = is_array( $option ) ? $option : [ $option ];
|
2014-10-10 00:07:14 +00:00
|
|
|
break;
|
2010-10-19 20:59:23 +00:00
|
|
|
// Collated lists of file paths
|
|
|
|
|
case 'languageScripts':
|
|
|
|
|
case 'skinScripts':
|
2010-10-19 18:25:42 +00:00
|
|
|
case 'skinStyles':
|
2010-10-21 22:34:26 +00:00
|
|
|
if ( !is_array( $option ) ) {
|
2015-03-30 16:51:10 +00:00
|
|
|
throw new InvalidArgumentException(
|
2011-06-17 16:05:05 +00:00
|
|
|
"Invalid collated file path list error. " .
|
2010-11-05 06:53:14 +00:00
|
|
|
"'$option' given, array expected."
|
2010-10-21 22:34:26 +00:00
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
foreach ( $option as $key => $value ) {
|
|
|
|
|
if ( !is_string( $key ) ) {
|
2015-03-30 16:51:10 +00:00
|
|
|
throw new InvalidArgumentException(
|
2011-06-17 16:05:05 +00:00
|
|
|
"Invalid collated file path list key error. " .
|
2010-11-05 06:53:14 +00:00
|
|
|
"'$key' given, string expected."
|
2010-10-21 22:34:26 +00:00
|
|
|
);
|
|
|
|
|
}
|
2017-03-17 02:14:05 +00:00
|
|
|
$this->{$member}[$key] = is_array( $value ) ? $value : [ $value ];
|
2010-10-19 18:25:42 +00:00
|
|
|
}
|
2010-10-21 22:34:26 +00:00
|
|
|
break;
|
2016-07-14 22:09:06 +00:00
|
|
|
case 'deprecated':
|
|
|
|
|
$this->deprecated = $option;
|
|
|
|
|
break;
|
2010-10-19 20:59:23 +00:00
|
|
|
// Lists of strings
|
2010-10-19 18:25:42 +00:00
|
|
|
case 'dependencies':
|
|
|
|
|
case 'messages':
|
2012-10-11 22:37:59 +00:00
|
|
|
case 'targets':
|
2013-10-18 13:34:50 +00:00
|
|
|
// Normalise
|
|
|
|
|
$option = array_values( array_unique( (array)$option ) );
|
|
|
|
|
sort( $option );
|
|
|
|
|
|
|
|
|
|
$this->{$member} = $option;
|
2010-10-19 18:25:42 +00:00
|
|
|
break;
|
2010-10-19 20:59:23 +00:00
|
|
|
// Single strings
|
2015-05-25 14:04:57 +00:00
|
|
|
case 'group':
|
2014-04-30 21:06:51 +00:00
|
|
|
case 'skipFunction':
|
2013-04-02 20:28:40 +00:00
|
|
|
$this->{$member} = (string)$option;
|
2010-10-21 01:03:46 +00:00
|
|
|
break;
|
|
|
|
|
// Single booleans
|
|
|
|
|
case 'debugRaw':
|
2016-10-18 19:04:40 +00:00
|
|
|
case 'noflip':
|
2021-01-23 07:33:38 +00:00
|
|
|
case 'es6':
|
2013-04-02 20:28:40 +00:00
|
|
|
$this->{$member} = (bool)$option;
|
2010-10-19 18:25:42 +00:00
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
if ( isset( $options['scripts'] ) && isset( $options['packageFiles'] ) ) {
|
|
|
|
|
throw new InvalidArgumentException( "A module may not set both 'scripts' and 'packageFiles'" );
|
|
|
|
|
}
|
2020-06-09 13:21:06 +00:00
|
|
|
if ( isset( $options['packageFiles'] ) && isset( $options['skinScripts'] ) ) {
|
2020-06-11 22:22:21 +00:00
|
|
|
throw new InvalidArgumentException( "Options 'skinScripts' and 'packageFiles' cannot be used together." );
|
2020-06-09 13:21:06 +00:00
|
|
|
}
|
2014-10-10 00:07:14 +00:00
|
|
|
if ( $hasTemplates ) {
|
|
|
|
|
$this->dependencies[] = 'mediawiki.template';
|
2014-12-17 20:30:54 +00:00
|
|
|
// Ensure relevant template compiler module gets loaded
|
|
|
|
|
foreach ( $this->templates as $alias => $templatePath ) {
|
|
|
|
|
if ( is_int( $alias ) ) {
|
2017-03-17 02:14:05 +00:00
|
|
|
$alias = $this->getPath( $templatePath );
|
2014-12-17 20:30:54 +00:00
|
|
|
}
|
|
|
|
|
$suffix = explode( '.', $alias );
|
|
|
|
|
$suffix = end( $suffix );
|
|
|
|
|
$compilerModule = 'mediawiki.template.' . $suffix;
|
|
|
|
|
if ( $suffix !== 'html' && !in_array( $compilerModule, $this->dependencies ) ) {
|
|
|
|
|
$this->dependencies[] = $compilerModule;
|
|
|
|
|
}
|
|
|
|
|
}
|
2014-10-10 00:07:14 +00:00
|
|
|
}
|
2014-06-26 14:29:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Extract a pair of local and remote base paths from module definition information.
|
|
|
|
|
* Implementation note: the amount of global state used in this function is staggering.
|
|
|
|
|
*
|
|
|
|
|
* @param array $options Module definition
|
2018-06-26 21:14:43 +00:00
|
|
|
* @param string|null $localBasePath Path to use if not provided in module definition. Defaults
|
2014-06-26 14:29:31 +00:00
|
|
|
* to $IP
|
2018-06-26 21:14:43 +00:00
|
|
|
* @param string|null $remoteBasePath Path to use if not provided in module definition. Defaults
|
2014-09-17 23:12:53 +00:00
|
|
|
* to $wgResourceBasePath
|
2020-10-28 10:01:33 +00:00
|
|
|
* @return string[] [ localBasePath, remoteBasePath ]
|
2014-06-26 14:29:31 +00:00
|
|
|
*/
|
|
|
|
|
public static function extractBasePaths(
|
2019-10-05 07:38:41 +00:00
|
|
|
array $options = [],
|
2014-06-26 14:29:31 +00:00
|
|
|
$localBasePath = null,
|
|
|
|
|
$remoteBasePath = null
|
|
|
|
|
) {
|
2014-09-17 23:12:53 +00:00
|
|
|
global $IP, $wgResourceBasePath;
|
2014-06-26 14:29:31 +00:00
|
|
|
|
|
|
|
|
// The different ways these checks are done, and their ordering, look very silly,
|
|
|
|
|
// but were preserved for backwards-compatibility just in case. Tread lightly.
|
|
|
|
|
|
2014-09-25 01:11:39 +00:00
|
|
|
if ( $localBasePath === null ) {
|
|
|
|
|
$localBasePath = $IP;
|
|
|
|
|
}
|
2014-08-07 10:27:36 +00:00
|
|
|
if ( $remoteBasePath === null ) {
|
2014-09-17 23:12:53 +00:00
|
|
|
$remoteBasePath = $wgResourceBasePath;
|
2014-06-26 14:29:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if ( isset( $options['remoteExtPath'] ) ) {
|
|
|
|
|
global $wgExtensionAssetsPath;
|
|
|
|
|
$remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if ( isset( $options['remoteSkinPath'] ) ) {
|
|
|
|
|
global $wgStylePath;
|
|
|
|
|
$remoteBasePath = $wgStylePath . '/' . $options['remoteSkinPath'];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if ( array_key_exists( 'localBasePath', $options ) ) {
|
|
|
|
|
$localBasePath = (string)$options['localBasePath'];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if ( array_key_exists( 'remoteBasePath', $options ) ) {
|
|
|
|
|
$remoteBasePath = (string)$options['remoteBasePath'];
|
|
|
|
|
}
|
|
|
|
|
|
resourceloader: Remove wfExpandUrl() coupling from CSSMin
There are three cases in CSSMin::remap where performs path
resolution.
1. Absolute local path URLs to full URL.
Example: url(/static/foo.png), url(/w/index.php?…), etc.
These previously used wfExpandUrl(), which got the server
name and protocol directly from $wgServer.
We will now use the $remote parameter to get this information
instead, which is generally set to something like
https://wiki/w/resources/foo, and thus naturally contains
the server name and protocol.
The resolution is powered by the Net_URL2 library, allowing
this to work outside Mediawiki as well.
Some tests needed to change because they were calling CSSMin::remap
with an incomplete $remote dummy values like "/" or "/w, because
the test author (past me) was trying to be clever by not supplying
it, knowing MW would ignore it. Now that it is consistently used,
like normal calls from ResourceLoader would, the expected values
will always be based on http://localhost/w, instead of sometimes
the competing $wgServer value of `https://expand.example`.
2. Relative local path to full URL
Example: url(foo.png), url(../foo.png), url(bar/foo.png)
These were already using $remote. The only change is that
they now use Net_URL2 library instead of blind string
concatenation. One of the benefits of this is that we will
no longer need to call wfRemoveDotSegments() to get rid
of things like double slashes or redundant "../" sequences.
Previously, thing like "foo//bar" or "foo/../bar" were cleaned
up only due to wfRemoveDotSegments(). This is now naturally
handled by Net_URL2.
3. Remote URLs
Example: url(http://example.org/bar.png), url(//example.org/bar.png)
This is generally not used in source code, but gadgets may use this,
e.g. for upload.wikimedia.org or cross-wiki imports.
Other changes:
* One test case used spaces within the URL string in CSS, which the
net_url2 library represents with percent-encoding instead.
Same thing either way.
Bug: T88914
Change-Id: Ibef70cc934c0ee8260a244c51bca9fb88c1c0d88
2020-09-11 21:35:37 +00:00
|
|
|
if ( $remoteBasePath === '' ) {
|
|
|
|
|
// If MediaWiki is installed at the document root (not recommended),
|
|
|
|
|
// then wgScriptPath is set to the empty string by the installer to
|
|
|
|
|
// ensure safe concatenating of file paths (avoid "/" + "/foo" being "//foo").
|
|
|
|
|
// However, this also means the path itself can be an invalid URI path,
|
|
|
|
|
// as those must start with a slash. Within ResourceLoader, we will not
|
|
|
|
|
// do such primitive/unsafe slash concatenation and use URI resolution
|
|
|
|
|
// instead, so beyond this point, to avoid fatal errors in CSSMin::resolveUrl(),
|
|
|
|
|
// do a best-effort support for docroot installs by casting this to a slash.
|
|
|
|
|
$remoteBasePath = '/';
|
|
|
|
|
}
|
|
|
|
|
|
2016-02-17 09:09:32 +00:00
|
|
|
return [ $localBasePath, $remoteBasePath ];
|
2010-10-19 18:25:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
2010-10-20 00:22:25 +00:00
|
|
|
* Gets all scripts for a given context concatenated together.
|
2011-06-17 16:05:05 +00:00
|
|
|
*
|
2013-09-13 04:50:45 +00:00
|
|
|
* @param ResourceLoaderContext $context Context in which to generate script
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
* @return string|array JavaScript code for $context, or package files data structure
|
2010-10-19 18:25:42 +00:00
|
|
|
*/
|
2010-10-19 22:48:52 +00:00
|
|
|
public function getScript( ResourceLoaderContext $context ) {
|
2019-09-09 15:50:13 +00:00
|
|
|
$deprecationScript = $this->getDeprecationInformation( $context );
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
if ( $this->packageFiles !== null ) {
|
|
|
|
|
$packageFiles = $this->getPackageFiles( $context );
|
2020-02-04 01:42:03 +00:00
|
|
|
foreach ( $packageFiles['files'] as &$file ) {
|
|
|
|
|
if ( $file['type'] === 'script+style' ) {
|
|
|
|
|
$file['content'] = $file['content']['script'];
|
|
|
|
|
$file['type'] = 'script';
|
|
|
|
|
}
|
|
|
|
|
}
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
if ( $deprecationScript ) {
|
2019-04-06 12:48:39 +00:00
|
|
|
$mainFile =& $packageFiles['files'][$packageFiles['main']];
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
$mainFile['content'] = $deprecationScript . $mainFile['content'];
|
|
|
|
|
}
|
|
|
|
|
return $packageFiles;
|
|
|
|
|
}
|
|
|
|
|
|
2011-05-14 12:15:58 +00:00
|
|
|
$files = $this->getScriptFiles( $context );
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
return $deprecationScript . $this->readScriptFiles( $files );
|
2010-10-19 18:25:42 +00:00
|
|
|
}
|
2011-10-14 08:06:54 +00:00
|
|
|
|
|
|
|
|
/**
|
2013-09-13 04:50:45 +00:00
|
|
|
* @param ResourceLoaderContext $context
|
2020-10-28 10:01:33 +00:00
|
|
|
* @return string[]
|
2011-10-14 08:06:54 +00:00
|
|
|
*/
|
Fix the fixme on r88053: dependency handling was broken in debug mode in certain cases. More specifically, if A is a file module that depends on B, B is a wiki module that depends on C and C is a file module, the loading order is CBA (correct) in production mode but was BCA (wrong) in debug mode. Fixed this by URL-ifying scripts and styles for those modules in debug mode, as I said to on CR. What this means is that the initial debug=true request for a module will now always return arrays of URLs, never the JS or CSS itself. This was already the case for file modules (which returned arrays of URLs to the raw files), but not for other modules (which returned the JS and CSS itself). So for non-file modules, load.php?modules=foo&debug=true now returns some JS that instructs the loader to fetch the module's JS from load.php?modules=foo&debug=true&only=scripts and the CSS from ...&only=styles .
* Removed the magic behavior where ResourceLoaderModule::getScripts() and getStyles() could return an array of URLs where the documentation said they should return a JS/CSS string. Because I didn't restructure the calling code too much, the old magical behavior should still work.
* Instead, move this behavior to getScriptURLsForDebug() and getStyleURLsForDebug(). The default implementation constructs a single URL for a load.php request for the module with debug=true&only=scripts (or styles). The URL building code duplicates some things from OutputPage::makeResourceLoaderLink(), I'll clean that up later. ResourceLoaderFileModule overrides this method to return URLs to the raw files, using code that I removed from getScripts()/getStyles()
* Add ResourceLoaderModule::supportsURLLoading(), which returns true by default but may return false to indicate that a module does not support loading via a URL. This is needed to respect $this->debugRaw in ResourceLoaderFileModule (set to true for jquery and mediawiki), and obviously for the startup module as well, because we get bootstrapping problems otherwise (can't call mw.loader.implement() when the code for mw.loader isn't loaded yet)
2011-09-13 17:13:53 +00:00
|
|
|
public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
|
resourceloader: Fix debug mode for RL-to-RL cross-wiki module loads
The native "foreign module source" feature, as used by the GlobalCssJs
extension, did not work correctly in debug mode as the urls returned
by the remote wiki were formatted as "/w/load.php...", which would
be interpreted by the browser relative to the host document, instead
of relative to the parent script.
For example:
1. Page view on en.wikipedia.org.
2. Script call to
meta.wikimedia.org/w/load.php?debug=true&modules=ext.globalCssJs.user&user
This URL is formatted by getScriptURLsForDebug on en.wikipedia.org,
when building the article HTML. It knows the modules is on Meta, and
formats it as such.
So far so good.
3. meta.wikimedia.org responds with an array of urls for sub resources.
That array contained URLs like "/w/load.php...only=scripts".
These were formatted by getScriptURLsForDebug running on Meta,
no longer with a reason to make it a Meta-Wiki URL as it isn't
perceived as cross-wiki. It is indistinguishable from debugging
a Meta-Wiki page view from its perspective.
This patch affects scenario 3 by always expanding it relative to the
current-request's wgServer. We still only do this in debug mode. There
is not yet a need to do this in non-debug mode, and if there was we'd
likely want to find a way to avoid it in the common case to keep
embedded URLs short.
The ResourceLoader::expandUrl() method is similar to the one in
Wikimedia\Minify\CSSMin.
Test Plan:
* view-source:http://mw.localhost:8080/w/load.php?debug=1&modules=site
For Module base class.
Before, the array entries were relative. After, they are full.
* view-source:http://mw.localhost:8080/w/load.php?debug=1&modules=jquery
For FileModule.
Before, the array entries were relative. After, they are full.
* view-source:http://mw.localhost:8080/wiki/Main_Page?debug=true
Unchanged.
* view-source:http://mw.localhost:8080/wiki/Main_Page
Unchanged.
Bug: T255367
Change-Id: I83919744b2677c7fb52b84089ecc60b89957d32a
2021-08-25 02:36:25 +00:00
|
|
|
$rl = $context->getResourceLoader();
|
|
|
|
|
$config = $this->getConfig();
|
|
|
|
|
$server = $config->get( 'Server' );
|
|
|
|
|
|
2016-02-17 09:09:32 +00:00
|
|
|
$urls = [];
|
Fix the fixme on r88053: dependency handling was broken in debug mode in certain cases. More specifically, if A is a file module that depends on B, B is a wiki module that depends on C and C is a file module, the loading order is CBA (correct) in production mode but was BCA (wrong) in debug mode. Fixed this by URL-ifying scripts and styles for those modules in debug mode, as I said to on CR. What this means is that the initial debug=true request for a module will now always return arrays of URLs, never the JS or CSS itself. This was already the case for file modules (which returned arrays of URLs to the raw files), but not for other modules (which returned the JS and CSS itself). So for non-file modules, load.php?modules=foo&debug=true now returns some JS that instructs the loader to fetch the module's JS from load.php?modules=foo&debug=true&only=scripts and the CSS from ...&only=styles .
* Removed the magic behavior where ResourceLoaderModule::getScripts() and getStyles() could return an array of URLs where the documentation said they should return a JS/CSS string. Because I didn't restructure the calling code too much, the old magical behavior should still work.
* Instead, move this behavior to getScriptURLsForDebug() and getStyleURLsForDebug(). The default implementation constructs a single URL for a load.php request for the module with debug=true&only=scripts (or styles). The URL building code duplicates some things from OutputPage::makeResourceLoaderLink(), I'll clean that up later. ResourceLoaderFileModule overrides this method to return URLs to the raw files, using code that I removed from getScripts()/getStyles()
* Add ResourceLoaderModule::supportsURLLoading(), which returns true by default but may return false to indicate that a module does not support loading via a URL. This is needed to respect $this->debugRaw in ResourceLoaderFileModule (set to true for jquery and mediawiki), and obviously for the startup module as well, because we get bootstrapping problems otherwise (can't call mw.loader.implement() when the code for mw.loader isn't loaded yet)
2011-09-13 17:13:53 +00:00
|
|
|
foreach ( $this->getScriptFiles( $context ) as $file ) {
|
resourceloader: Fix debug mode for RL-to-RL cross-wiki module loads
The native "foreign module source" feature, as used by the GlobalCssJs
extension, did not work correctly in debug mode as the urls returned
by the remote wiki were formatted as "/w/load.php...", which would
be interpreted by the browser relative to the host document, instead
of relative to the parent script.
For example:
1. Page view on en.wikipedia.org.
2. Script call to
meta.wikimedia.org/w/load.php?debug=true&modules=ext.globalCssJs.user&user
This URL is formatted by getScriptURLsForDebug on en.wikipedia.org,
when building the article HTML. It knows the modules is on Meta, and
formats it as such.
So far so good.
3. meta.wikimedia.org responds with an array of urls for sub resources.
That array contained URLs like "/w/load.php...only=scripts".
These were formatted by getScriptURLsForDebug running on Meta,
no longer with a reason to make it a Meta-Wiki URL as it isn't
perceived as cross-wiki. It is indistinguishable from debugging
a Meta-Wiki page view from its perspective.
This patch affects scenario 3 by always expanding it relative to the
current-request's wgServer. We still only do this in debug mode. There
is not yet a need to do this in non-debug mode, and if there was we'd
likely want to find a way to avoid it in the common case to keep
embedded URLs short.
The ResourceLoader::expandUrl() method is similar to the one in
Wikimedia\Minify\CSSMin.
Test Plan:
* view-source:http://mw.localhost:8080/w/load.php?debug=1&modules=site
For Module base class.
Before, the array entries were relative. After, they are full.
* view-source:http://mw.localhost:8080/w/load.php?debug=1&modules=jquery
For FileModule.
Before, the array entries were relative. After, they are full.
* view-source:http://mw.localhost:8080/wiki/Main_Page?debug=true
Unchanged.
* view-source:http://mw.localhost:8080/wiki/Main_Page
Unchanged.
Bug: T255367
Change-Id: I83919744b2677c7fb52b84089ecc60b89957d32a
2021-08-25 02:36:25 +00:00
|
|
|
$url = OutputPage::transformResourcePath( $config, $this->getRemotePath( $file ) );
|
|
|
|
|
// Expand debug URL in case we are another wiki's module source (T255367)
|
|
|
|
|
$url = $rl->expandUrl( $server, $url );
|
|
|
|
|
$urls[] = $url;
|
Fix the fixme on r88053: dependency handling was broken in debug mode in certain cases. More specifically, if A is a file module that depends on B, B is a wiki module that depends on C and C is a file module, the loading order is CBA (correct) in production mode but was BCA (wrong) in debug mode. Fixed this by URL-ifying scripts and styles for those modules in debug mode, as I said to on CR. What this means is that the initial debug=true request for a module will now always return arrays of URLs, never the JS or CSS itself. This was already the case for file modules (which returned arrays of URLs to the raw files), but not for other modules (which returned the JS and CSS itself). So for non-file modules, load.php?modules=foo&debug=true now returns some JS that instructs the loader to fetch the module's JS from load.php?modules=foo&debug=true&only=scripts and the CSS from ...&only=styles .
* Removed the magic behavior where ResourceLoaderModule::getScripts() and getStyles() could return an array of URLs where the documentation said they should return a JS/CSS string. Because I didn't restructure the calling code too much, the old magical behavior should still work.
* Instead, move this behavior to getScriptURLsForDebug() and getStyleURLsForDebug(). The default implementation constructs a single URL for a load.php request for the module with debug=true&only=scripts (or styles). The URL building code duplicates some things from OutputPage::makeResourceLoaderLink(), I'll clean that up later. ResourceLoaderFileModule overrides this method to return URLs to the raw files, using code that I removed from getScripts()/getStyles()
* Add ResourceLoaderModule::supportsURLLoading(), which returns true by default but may return false to indicate that a module does not support loading via a URL. This is needed to respect $this->debugRaw in ResourceLoaderFileModule (set to true for jquery and mediawiki), and obviously for the startup module as well, because we get bootstrapping problems otherwise (can't call mw.loader.implement() when the code for mw.loader isn't loaded yet)
2011-09-13 17:13:53 +00:00
|
|
|
}
|
|
|
|
|
return $urls;
|
|
|
|
|
}
|
|
|
|
|
|
2011-10-14 08:06:54 +00:00
|
|
|
/**
|
|
|
|
|
* @return bool
|
|
|
|
|
*/
|
Fix the fixme on r88053: dependency handling was broken in debug mode in certain cases. More specifically, if A is a file module that depends on B, B is a wiki module that depends on C and C is a file module, the loading order is CBA (correct) in production mode but was BCA (wrong) in debug mode. Fixed this by URL-ifying scripts and styles for those modules in debug mode, as I said to on CR. What this means is that the initial debug=true request for a module will now always return arrays of URLs, never the JS or CSS itself. This was already the case for file modules (which returned arrays of URLs to the raw files), but not for other modules (which returned the JS and CSS itself). So for non-file modules, load.php?modules=foo&debug=true now returns some JS that instructs the loader to fetch the module's JS from load.php?modules=foo&debug=true&only=scripts and the CSS from ...&only=styles .
* Removed the magic behavior where ResourceLoaderModule::getScripts() and getStyles() could return an array of URLs where the documentation said they should return a JS/CSS string. Because I didn't restructure the calling code too much, the old magical behavior should still work.
* Instead, move this behavior to getScriptURLsForDebug() and getStyleURLsForDebug(). The default implementation constructs a single URL for a load.php request for the module with debug=true&only=scripts (or styles). The URL building code duplicates some things from OutputPage::makeResourceLoaderLink(), I'll clean that up later. ResourceLoaderFileModule overrides this method to return URLs to the raw files, using code that I removed from getScripts()/getStyles()
* Add ResourceLoaderModule::supportsURLLoading(), which returns true by default but may return false to indicate that a module does not support loading via a URL. This is needed to respect $this->debugRaw in ResourceLoaderFileModule (set to true for jquery and mediawiki), and obviously for the startup module as well, because we get bootstrapping problems otherwise (can't call mw.loader.implement() when the code for mw.loader isn't loaded yet)
2011-09-13 17:13:53 +00:00
|
|
|
public function supportsURLLoading() {
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
// If package files are involved, don't support URL loading, because that breaks
|
|
|
|
|
// scoped require() functions
|
|
|
|
|
return $this->debugRaw && !$this->packageFiles;
|
Fix the fixme on r88053: dependency handling was broken in debug mode in certain cases. More specifically, if A is a file module that depends on B, B is a wiki module that depends on C and C is a file module, the loading order is CBA (correct) in production mode but was BCA (wrong) in debug mode. Fixed this by URL-ifying scripts and styles for those modules in debug mode, as I said to on CR. What this means is that the initial debug=true request for a module will now always return arrays of URLs, never the JS or CSS itself. This was already the case for file modules (which returned arrays of URLs to the raw files), but not for other modules (which returned the JS and CSS itself). So for non-file modules, load.php?modules=foo&debug=true now returns some JS that instructs the loader to fetch the module's JS from load.php?modules=foo&debug=true&only=scripts and the CSS from ...&only=styles .
* Removed the magic behavior where ResourceLoaderModule::getScripts() and getStyles() could return an array of URLs where the documentation said they should return a JS/CSS string. Because I didn't restructure the calling code too much, the old magical behavior should still work.
* Instead, move this behavior to getScriptURLsForDebug() and getStyleURLsForDebug(). The default implementation constructs a single URL for a load.php request for the module with debug=true&only=scripts (or styles). The URL building code duplicates some things from OutputPage::makeResourceLoaderLink(), I'll clean that up later. ResourceLoaderFileModule overrides this method to return URLs to the raw files, using code that I removed from getScripts()/getStyles()
* Add ResourceLoaderModule::supportsURLLoading(), which returns true by default but may return false to indicate that a module does not support loading via a URL. This is needed to respect $this->debugRaw in ResourceLoaderFileModule (set to true for jquery and mediawiki), and obviously for the startup module as well, because we get bootstrapping problems otherwise (can't call mw.loader.implement() when the code for mw.loader isn't loaded yet)
2011-09-13 17:13:53 +00:00
|
|
|
}
|
2010-10-19 18:25:42 +00:00
|
|
|
|
|
|
|
|
/**
|
2014-06-04 19:30:14 +00:00
|
|
|
* Get all styles for a given context.
|
2011-06-17 16:05:05 +00:00
|
|
|
*
|
2014-06-04 19:30:14 +00:00
|
|
|
* @param ResourceLoaderContext $context
|
2020-10-28 10:01:33 +00:00
|
|
|
* @return string[] CSS code for $context as an associative array mapping media type to CSS text.
|
2010-10-19 18:25:42 +00:00
|
|
|
*/
|
|
|
|
|
public function getStyles( ResourceLoaderContext $context ) {
|
2011-05-14 12:15:58 +00:00
|
|
|
$styles = $this->readStyleFiles(
|
|
|
|
|
$this->getStyleFiles( $context ),
|
2014-08-20 13:13:43 +00:00
|
|
|
$context
|
2010-12-16 19:31:48 +00:00
|
|
|
);
|
2019-06-29 04:50:31 +00:00
|
|
|
|
2020-02-04 01:42:03 +00:00
|
|
|
if ( $this->packageFiles !== null ) {
|
|
|
|
|
$packageFiles = $this->getPackageFiles( $context );
|
|
|
|
|
foreach ( $packageFiles['files'] as $fileName => $file ) {
|
|
|
|
|
if ( $file['type'] === 'script+style' ) {
|
|
|
|
|
$style = $this->processStyle(
|
|
|
|
|
$file['content']['style'],
|
|
|
|
|
$file['content']['styleLang'],
|
|
|
|
|
$fileName,
|
|
|
|
|
$context
|
|
|
|
|
);
|
|
|
|
|
$styles['all'] = ( $styles['all'] ?? '' ) . "\n" . $style;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-06-29 04:50:31 +00:00
|
|
|
// Track indirect file dependencies so that ResourceLoaderStartUpModule can check for
|
|
|
|
|
// on-disk file changes to any of this files without having to recompute the file list
|
2015-09-30 00:15:57 +00:00
|
|
|
$this->saveFileDependencies( $context, $this->localFileRefs );
|
2015-09-17 22:14:46 +00:00
|
|
|
|
2010-10-19 18:25:42 +00:00
|
|
|
return $styles;
|
|
|
|
|
}
|
|
|
|
|
|
2011-10-14 08:06:54 +00:00
|
|
|
/**
|
2013-09-13 04:50:45 +00:00
|
|
|
* @param ResourceLoaderContext $context
|
2020-10-28 10:01:33 +00:00
|
|
|
* @return string[][]
|
2011-10-14 08:06:54 +00:00
|
|
|
*/
|
Fix the fixme on r88053: dependency handling was broken in debug mode in certain cases. More specifically, if A is a file module that depends on B, B is a wiki module that depends on C and C is a file module, the loading order is CBA (correct) in production mode but was BCA (wrong) in debug mode. Fixed this by URL-ifying scripts and styles for those modules in debug mode, as I said to on CR. What this means is that the initial debug=true request for a module will now always return arrays of URLs, never the JS or CSS itself. This was already the case for file modules (which returned arrays of URLs to the raw files), but not for other modules (which returned the JS and CSS itself). So for non-file modules, load.php?modules=foo&debug=true now returns some JS that instructs the loader to fetch the module's JS from load.php?modules=foo&debug=true&only=scripts and the CSS from ...&only=styles .
* Removed the magic behavior where ResourceLoaderModule::getScripts() and getStyles() could return an array of URLs where the documentation said they should return a JS/CSS string. Because I didn't restructure the calling code too much, the old magical behavior should still work.
* Instead, move this behavior to getScriptURLsForDebug() and getStyleURLsForDebug(). The default implementation constructs a single URL for a load.php request for the module with debug=true&only=scripts (or styles). The URL building code duplicates some things from OutputPage::makeResourceLoaderLink(), I'll clean that up later. ResourceLoaderFileModule overrides this method to return URLs to the raw files, using code that I removed from getScripts()/getStyles()
* Add ResourceLoaderModule::supportsURLLoading(), which returns true by default but may return false to indicate that a module does not support loading via a URL. This is needed to respect $this->debugRaw in ResourceLoaderFileModule (set to true for jquery and mediawiki), and obviously for the startup module as well, because we get bootstrapping problems otherwise (can't call mw.loader.implement() when the code for mw.loader isn't loaded yet)
2011-09-13 17:13:53 +00:00
|
|
|
public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
|
Support LESS stylesheets in ResourceLoader
This patch adds support for the LESS stylesheet language to ResourceLoader.
LESS is a stylesheet language that compiles into CSS. The patch includes
lessphp, a LESS compiler implemented in PHP. The rationale for choosing LESS is
explained in a MediaWiki RFC which accompanies this patch, available at
<https://www.mediawiki.org/wiki/Requests_for_comment/LESS>.
LESS support is provided for ResourceLoader file modules. It is triggered by
the presence of the '.less' extension in stylesheet filenames. LESS files are
compiled by lessc, and the resultant CSS is subjected to the standard set of
transformations (CSSJanus & CSSMin). The immediate result of LESS compilation
is encoded as an array, which includes the list of LESS files that were
compiled and their mtimes. This array is cached. Cache invalidation is
performed by comparing the cached mtimes with the mtimes of the files on disk.
If the compiler itself throws an exception, ResourceLoader constructs a
compilation result which consists of the error message encoded as a CSS
comment. Failed compilation results are cached too, but with an expiration time
of five minutes. The expiration time is required because the full list of
referenced files is not known.
Three configuration variables configure the global environment for LESS
modules: $wgResourceLoaderLESSVars, $wgResourceLoaderLESSFunctions, and
$wgResourceLoaderLESSImportPaths. $wgResourceLoaderLESSVars maps variable names
to CSS values, specified as strings. Variables declared in this array are
available in all LESS files. $wgResourceLoaderLESSFunctions is similar, except
it maps custom function names to PHP callables. These functions can be called
from within LESS to transform values. Read more about custom functions at
<http://leafo.net/lessphp/docs/#custom_functions>. Finally,
$wgResourceLoaderLESSImportPaths specifies file system paths in addition to the
current module's path where the LESS compiler should look up files referenced
in @import statements.
The issue of handling of /* @embed */ and /* @noflip */ annotations is left
unresolved. Earlier versions of this patch included an @embed analog
implemented as a LESS custom function, but there was enough ambiguity about
whether the strategy it took was optimal to merit discussing it in a separate,
follow-up patch.
Bug: 40964
Change-Id: Id052a04dd2f76a1f4aef39fbd454bd67f5fd282f
2013-08-11 16:40:20 +00:00
|
|
|
if ( $this->hasGeneratedStyles ) {
|
|
|
|
|
// Do the default behaviour of returning a url back to load.php
|
|
|
|
|
// but with only=styles.
|
|
|
|
|
return parent::getStyleURLsForDebug( $context );
|
|
|
|
|
}
|
|
|
|
|
// Our module consists entirely of real css files,
|
|
|
|
|
// in debug mode we can load those directly.
|
2016-02-17 09:09:32 +00:00
|
|
|
$urls = [];
|
Fix the fixme on r88053: dependency handling was broken in debug mode in certain cases. More specifically, if A is a file module that depends on B, B is a wiki module that depends on C and C is a file module, the loading order is CBA (correct) in production mode but was BCA (wrong) in debug mode. Fixed this by URL-ifying scripts and styles for those modules in debug mode, as I said to on CR. What this means is that the initial debug=true request for a module will now always return arrays of URLs, never the JS or CSS itself. This was already the case for file modules (which returned arrays of URLs to the raw files), but not for other modules (which returned the JS and CSS itself). So for non-file modules, load.php?modules=foo&debug=true now returns some JS that instructs the loader to fetch the module's JS from load.php?modules=foo&debug=true&only=scripts and the CSS from ...&only=styles .
* Removed the magic behavior where ResourceLoaderModule::getScripts() and getStyles() could return an array of URLs where the documentation said they should return a JS/CSS string. Because I didn't restructure the calling code too much, the old magical behavior should still work.
* Instead, move this behavior to getScriptURLsForDebug() and getStyleURLsForDebug(). The default implementation constructs a single URL for a load.php request for the module with debug=true&only=scripts (or styles). The URL building code duplicates some things from OutputPage::makeResourceLoaderLink(), I'll clean that up later. ResourceLoaderFileModule overrides this method to return URLs to the raw files, using code that I removed from getScripts()/getStyles()
* Add ResourceLoaderModule::supportsURLLoading(), which returns true by default but may return false to indicate that a module does not support loading via a URL. This is needed to respect $this->debugRaw in ResourceLoaderFileModule (set to true for jquery and mediawiki), and obviously for the startup module as well, because we get bootstrapping problems otherwise (can't call mw.loader.implement() when the code for mw.loader isn't loaded yet)
2011-09-13 17:13:53 +00:00
|
|
|
foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
|
2016-02-17 09:09:32 +00:00
|
|
|
$urls[$mediaType] = [];
|
Fix the fixme on r88053: dependency handling was broken in debug mode in certain cases. More specifically, if A is a file module that depends on B, B is a wiki module that depends on C and C is a file module, the loading order is CBA (correct) in production mode but was BCA (wrong) in debug mode. Fixed this by URL-ifying scripts and styles for those modules in debug mode, as I said to on CR. What this means is that the initial debug=true request for a module will now always return arrays of URLs, never the JS or CSS itself. This was already the case for file modules (which returned arrays of URLs to the raw files), but not for other modules (which returned the JS and CSS itself). So for non-file modules, load.php?modules=foo&debug=true now returns some JS that instructs the loader to fetch the module's JS from load.php?modules=foo&debug=true&only=scripts and the CSS from ...&only=styles .
* Removed the magic behavior where ResourceLoaderModule::getScripts() and getStyles() could return an array of URLs where the documentation said they should return a JS/CSS string. Because I didn't restructure the calling code too much, the old magical behavior should still work.
* Instead, move this behavior to getScriptURLsForDebug() and getStyleURLsForDebug(). The default implementation constructs a single URL for a load.php request for the module with debug=true&only=scripts (or styles). The URL building code duplicates some things from OutputPage::makeResourceLoaderLink(), I'll clean that up later. ResourceLoaderFileModule overrides this method to return URLs to the raw files, using code that I removed from getScripts()/getStyles()
* Add ResourceLoaderModule::supportsURLLoading(), which returns true by default but may return false to indicate that a module does not support loading via a URL. This is needed to respect $this->debugRaw in ResourceLoaderFileModule (set to true for jquery and mediawiki), and obviously for the startup module as well, because we get bootstrapping problems otherwise (can't call mw.loader.implement() when the code for mw.loader isn't loaded yet)
2011-09-13 17:13:53 +00:00
|
|
|
foreach ( $list as $file ) {
|
2016-02-12 23:33:45 +00:00
|
|
|
$urls[$mediaType][] = OutputPage::transformResourcePath(
|
|
|
|
|
$this->getConfig(),
|
|
|
|
|
$this->getRemotePath( $file )
|
|
|
|
|
);
|
Fix the fixme on r88053: dependency handling was broken in debug mode in certain cases. More specifically, if A is a file module that depends on B, B is a wiki module that depends on C and C is a file module, the loading order is CBA (correct) in production mode but was BCA (wrong) in debug mode. Fixed this by URL-ifying scripts and styles for those modules in debug mode, as I said to on CR. What this means is that the initial debug=true request for a module will now always return arrays of URLs, never the JS or CSS itself. This was already the case for file modules (which returned arrays of URLs to the raw files), but not for other modules (which returned the JS and CSS itself). So for non-file modules, load.php?modules=foo&debug=true now returns some JS that instructs the loader to fetch the module's JS from load.php?modules=foo&debug=true&only=scripts and the CSS from ...&only=styles .
* Removed the magic behavior where ResourceLoaderModule::getScripts() and getStyles() could return an array of URLs where the documentation said they should return a JS/CSS string. Because I didn't restructure the calling code too much, the old magical behavior should still work.
* Instead, move this behavior to getScriptURLsForDebug() and getStyleURLsForDebug(). The default implementation constructs a single URL for a load.php request for the module with debug=true&only=scripts (or styles). The URL building code duplicates some things from OutputPage::makeResourceLoaderLink(), I'll clean that up later. ResourceLoaderFileModule overrides this method to return URLs to the raw files, using code that I removed from getScripts()/getStyles()
* Add ResourceLoaderModule::supportsURLLoading(), which returns true by default but may return false to indicate that a module does not support loading via a URL. This is needed to respect $this->debugRaw in ResourceLoaderFileModule (set to true for jquery and mediawiki), and obviously for the startup module as well, because we get bootstrapping problems otherwise (can't call mw.loader.implement() when the code for mw.loader isn't loaded yet)
2011-09-13 17:13:53 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return $urls;
|
|
|
|
|
}
|
|
|
|
|
|
2010-10-19 22:48:52 +00:00
|
|
|
/**
|
2010-10-20 00:22:25 +00:00
|
|
|
* Gets list of message keys used by this module.
|
2011-06-17 16:05:05 +00:00
|
|
|
*
|
2020-10-28 10:01:33 +00:00
|
|
|
* @return string[] List of message keys
|
2010-10-19 22:48:52 +00:00
|
|
|
*/
|
2010-10-19 18:25:42 +00:00
|
|
|
public function getMessages() {
|
|
|
|
|
return $this->messages;
|
|
|
|
|
}
|
|
|
|
|
|
2010-10-19 22:48:52 +00:00
|
|
|
/**
|
2010-10-20 00:22:25 +00:00
|
|
|
* Gets the name of the group this module should be loaded in.
|
2011-06-17 16:05:05 +00:00
|
|
|
*
|
2014-04-20 21:33:05 +00:00
|
|
|
* @return string Group name
|
2010-10-19 22:48:52 +00:00
|
|
|
*/
|
2010-10-19 18:25:42 +00:00
|
|
|
public function getGroup() {
|
|
|
|
|
return $this->group;
|
|
|
|
|
}
|
2011-05-21 17:45:20 +00:00
|
|
|
|
2010-10-19 22:48:52 +00:00
|
|
|
/**
|
2010-10-20 00:22:25 +00:00
|
|
|
* Gets list of names of modules this module depends on.
|
2015-12-09 17:20:41 +00:00
|
|
|
* @param ResourceLoaderContext|null $context
|
2020-10-28 10:01:33 +00:00
|
|
|
* @return string[] List of module names
|
2010-10-19 22:48:52 +00:00
|
|
|
*/
|
2015-04-08 21:34:08 +00:00
|
|
|
public function getDependencies( ResourceLoaderContext $context = null ) {
|
2010-10-19 18:25:42 +00:00
|
|
|
return $this->dependencies;
|
|
|
|
|
}
|
|
|
|
|
|
2020-03-11 19:52:52 +00:00
|
|
|
/**
|
|
|
|
|
* Helper method for getting a file.
|
|
|
|
|
*
|
|
|
|
|
* @param string $localPath The path to the resource to load
|
|
|
|
|
* @param string $type The type of resource being loaded (for error reporting only)
|
|
|
|
|
* @throws RuntimeException If the supplied path is not found, or not a path
|
|
|
|
|
* @return string
|
|
|
|
|
*/
|
|
|
|
|
private function getFileContents( $localPath, $type ) {
|
2020-03-11 22:34:16 +00:00
|
|
|
if ( !is_file( $localPath ) ) {
|
|
|
|
|
throw new RuntimeException(
|
|
|
|
|
__METHOD__ . ": $type file not found, or is not a file: \"$localPath\""
|
|
|
|
|
);
|
2020-03-11 19:52:52 +00:00
|
|
|
}
|
|
|
|
|
return $this->stripBom( file_get_contents( $localPath ) );
|
|
|
|
|
}
|
|
|
|
|
|
2014-04-30 21:06:51 +00:00
|
|
|
/**
|
2014-12-24 13:49:20 +00:00
|
|
|
* @return null|string
|
2020-03-11 19:52:52 +00:00
|
|
|
* @throws RuntimeException If the file doesn't exist
|
2014-04-30 21:06:51 +00:00
|
|
|
*/
|
|
|
|
|
public function getSkipFunction() {
|
|
|
|
|
if ( !$this->skipFunction ) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
$localPath = $this->getLocalPath( $this->skipFunction );
|
2020-03-11 19:52:52 +00:00
|
|
|
return $this->getFileContents( $localPath, 'skip function' );
|
2014-04-30 21:06:51 +00:00
|
|
|
}
|
|
|
|
|
|
2021-01-23 07:33:38 +00:00
|
|
|
public function requiresES6() {
|
|
|
|
|
return $this->es6;
|
|
|
|
|
}
|
|
|
|
|
|
resourceloader: Enable module content version for data modules
This greatly simplifies logic required to compute module versions.
It also makes it significantly less error-prone.
Since f37cee996e, we support hashes as versions (instead of timestamps).
This means we can build a hash of the content directly, instead of compiling a
large array with all values that may influence the module content somehow.
Benefits:
* Remove all methods and logic related to querying database and disk for
timestamps, revision numbers, definition summaries, cache epochs, and more.
* No longer needlessly invalidate cache as a result of no-op changes to
implementation datails. Due to inclusion of absolute file paths in the
definition summary, cache was always invalidated when moving wikis to newer
MediaWiki branches; even if the module observed no actual changes.
* When changes are reverted within a certain period of time, old caches can now
be re-used. The module would produce the same version hash as before.
Previously when a change was deployed and then reverted, all web clients (even
those that never saw the bad version) would have re-fetch modules because the
version increased.
Updated unit tests to account for the change in version. New default version of
empty test modules is: "mvgTPvXh". For the record, this comes from the base64
encoding of the SHA1 digest of the JSON serialised form of the module content:
> $str = '{"scripts":"","styles":{"css":[]},"messagesBlob":"{}"}';
> echo base64_encode(sha1($str, true));
> FEb3+VuiUm/fOMfod1bjw/te+AQ=
Enabled content versioning for the data modules in MediaWiki core:
* EditToolbarModule
* JqueryMsgModule
* LanguageDataModule
* LanguageNamesModule
* SpecialCharacterDataModule
* UserCSSPrefsModule
* UserDefaultsModule
* UserOptionsModule
The FileModule and base class explicitly disable it for now and keep their
current behaviour of using the definition summary. We may remove it later, but
that requires more performance testing first.
Explicitly disable it in the WikiModule class to avoid breakage when the
default changes.
Ref T98087.
Change-Id: I782df43c50dfcfb7d7592f744e13a3a0430b0dc6
2015-06-02 17:27:23 +00:00
|
|
|
/**
|
|
|
|
|
* Disable module content versioning.
|
|
|
|
|
*
|
|
|
|
|
* This class uses getDefinitionSummary() instead, to avoid filesystem overhead
|
|
|
|
|
* involved with building the full module content inside a startup request.
|
|
|
|
|
*
|
|
|
|
|
* @return bool
|
|
|
|
|
*/
|
|
|
|
|
public function enableModuleContentVersion() {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
2010-10-19 18:25:42 +00:00
|
|
|
/**
|
2018-06-26 01:52:40 +00:00
|
|
|
* Helper method for getDefinitionSummary.
|
2011-06-17 16:05:05 +00:00
|
|
|
*
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
* @param ResourceLoaderContext $context
|
resourceloader: Use FileContentsHasher batching in FileModule::getFileHashes
Instead of hashing each file separately, hash them in a batch.
Previous research on this area of code has identified the suppressing
and restoring of warnings to have a measurable cost, which is why
this was optimised in 3621ad0f82f8b6b. However, we never really made
use if it (aisde from the 2:1 change in that commit itself), because
we always call it with a single item, turn it into an array, do the
hash and then merge it again.
Instead, we now let it handle a single module's set of files all
at once. Given that this no longer exposes an array of hashes,
also update the (private) signature of getFileHashes to reflect this.
This means all file modules will have their version bumped during the
next MediaWiki release. In general this happens for most releases
and weekly branches already (due to localisation update, general
maintenance, linting changes, and other internal changes). But,
noting here for future reference as this might not be obvious from
the diff.
Change-Id: I4e141a0f5a5c1c1972e2ba33d4b7be6e64ed6ab6
2019-12-15 19:35:20 +00:00
|
|
|
* @return string
|
2010-10-19 18:25:42 +00:00
|
|
|
*/
|
2018-06-26 01:52:40 +00:00
|
|
|
private function getFileHashes( ResourceLoaderContext $context ) {
|
2016-02-17 09:09:32 +00:00
|
|
|
$files = [];
|
2011-06-17 16:05:05 +00:00
|
|
|
|
2021-08-25 21:46:00 +00:00
|
|
|
$styleFiles = $this->getStyleFiles( $context );
|
|
|
|
|
foreach ( $styleFiles as $paths ) {
|
|
|
|
|
$files = array_merge( $files, $paths );
|
2010-10-19 18:25:42 +00:00
|
|
|
}
|
2011-06-17 16:05:05 +00:00
|
|
|
|
2019-12-15 19:11:40 +00:00
|
|
|
// Extract file paths for package files
|
|
|
|
|
// Optimisation: Use foreach() and isset() instead of array_map/array_filter.
|
|
|
|
|
// This is a hot code path, called by StartupModule for thousands of modules.
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
$expandedPackageFiles = $this->expandPackageFiles( $context );
|
2019-12-15 19:11:40 +00:00
|
|
|
$packageFiles = [];
|
|
|
|
|
if ( $expandedPackageFiles ) {
|
|
|
|
|
foreach ( $expandedPackageFiles['files'] as $fileInfo ) {
|
|
|
|
|
if ( isset( $fileInfo['filePath'] ) ) {
|
|
|
|
|
$packageFiles[] = $fileInfo['filePath'];
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
|
2019-12-15 19:11:40 +00:00
|
|
|
// Merge all the file paths we were able discover directly from the module definition.
|
|
|
|
|
// This is the master list of direct-dependent files for this module.
|
2010-10-19 18:25:42 +00:00
|
|
|
$files = array_merge(
|
2010-10-19 23:47:56 +00:00
|
|
|
$files,
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
$packageFiles,
|
2010-10-19 18:25:42 +00:00
|
|
|
$this->scripts,
|
2014-10-10 00:07:14 +00:00
|
|
|
$this->templates,
|
2016-02-17 09:09:32 +00:00
|
|
|
$context->getDebug() ? $this->debugScripts : [],
|
2014-08-29 17:13:21 +00:00
|
|
|
$this->getLanguageScripts( $context->getLanguage() ),
|
2015-10-19 23:04:23 +00:00
|
|
|
self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
|
2010-10-19 18:25:42 +00:00
|
|
|
);
|
2014-04-30 21:06:51 +00:00
|
|
|
if ( $this->skipFunction ) {
|
|
|
|
|
$files[] = $this->skipFunction;
|
|
|
|
|
}
|
2019-12-15 19:11:40 +00:00
|
|
|
|
|
|
|
|
// Expand these local paths into absolute file paths
|
2016-02-17 09:09:32 +00:00
|
|
|
$files = array_map( [ $this, 'getLocalPath' ], $files );
|
2019-12-15 19:11:40 +00:00
|
|
|
|
|
|
|
|
// Add any lazily discovered file dependencies from previous module builds.
|
|
|
|
|
// These are added last because they are already absolute file paths.
|
2015-09-30 00:15:57 +00:00
|
|
|
$files = array_merge( $files, $this->getFileDependencies( $context ) );
|
2019-12-15 19:11:40 +00:00
|
|
|
|
|
|
|
|
// Filter out any duplicates. Typically introduced by getFileDependencies() which
|
2020-02-04 22:44:14 +00:00
|
|
|
// may lazily re-discover a master file.
|
2019-12-15 19:11:40 +00:00
|
|
|
$files = array_unique( $files );
|
|
|
|
|
|
resourceloader: Use FileContentsHasher batching in FileModule::getFileHashes
Instead of hashing each file separately, hash them in a batch.
Previous research on this area of code has identified the suppressing
and restoring of warnings to have a measurable cost, which is why
this was optimised in 3621ad0f82f8b6b. However, we never really made
use if it (aisde from the 2:1 change in that commit itself), because
we always call it with a single item, turn it into an array, do the
hash and then merge it again.
Instead, we now let it handle a single module's set of files all
at once. Given that this no longer exposes an array of hashes,
also update the (private) signature of getFileHashes to reflect this.
This means all file modules will have their version bumped during the
next MediaWiki release. In general this happens for most releases
and weekly branches already (due to localisation update, general
maintenance, linting changes, and other internal changes). But,
noting here for future reference as this might not be obvious from
the diff.
Change-Id: I4e141a0f5a5c1c1972e2ba33d4b7be6e64ed6ab6
2019-12-15 19:35:20 +00:00
|
|
|
// Don't return array keys or any other form of file path here, only the hashes.
|
|
|
|
|
// Including file paths would needlessly cause global cache invalidation when files
|
|
|
|
|
// move on disk or if e.g. the MediaWiki directory name changes.
|
|
|
|
|
// Anything where order is significant is already detected by the definition summary.
|
|
|
|
|
return FileContentsHasher::getFileContentsHash( $files );
|
2010-10-19 18:25:42 +00:00
|
|
|
}
|
|
|
|
|
|
2013-10-18 13:34:50 +00:00
|
|
|
/**
|
|
|
|
|
* Get the definition summary for this module.
|
|
|
|
|
*
|
2014-08-14 19:34:55 +00:00
|
|
|
* @param ResourceLoaderContext $context
|
2014-04-20 21:33:05 +00:00
|
|
|
* @return array
|
2013-10-18 13:34:50 +00:00
|
|
|
*/
|
|
|
|
|
public function getDefinitionSummary( ResourceLoaderContext $context ) {
|
2015-03-23 03:56:35 +00:00
|
|
|
$summary = parent::getDefinitionSummary( $context );
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
|
2016-02-17 09:09:32 +00:00
|
|
|
$options = [];
|
|
|
|
|
foreach ( [
|
2015-08-23 12:34:33 +00:00
|
|
|
// The following properties are omitted because they don't affect the module reponse:
|
|
|
|
|
// - localBasePath (Per T104950; Changes when absolute directory name changes. If
|
|
|
|
|
// this affects 'scripts' and other file paths, getFileHashes accounts for that.)
|
|
|
|
|
// - remoteBasePath (Per T104950)
|
|
|
|
|
// - dependencies (provided via startup module)
|
|
|
|
|
// - targets
|
|
|
|
|
// - group (provided via startup module)
|
2013-10-18 13:34:50 +00:00
|
|
|
'scripts',
|
|
|
|
|
'debugScripts',
|
|
|
|
|
'styles',
|
|
|
|
|
'languageScripts',
|
|
|
|
|
'skinScripts',
|
|
|
|
|
'skinStyles',
|
|
|
|
|
'messages',
|
2014-10-10 00:07:14 +00:00
|
|
|
'templates',
|
2014-04-30 21:06:51 +00:00
|
|
|
'skipFunction',
|
2013-10-18 13:34:50 +00:00
|
|
|
'debugRaw',
|
2016-02-17 09:09:32 +00:00
|
|
|
] as $member ) {
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
$options[$member] = $this->{$member};
|
2019-06-12 13:35:59 +00:00
|
|
|
}
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
|
2019-06-12 00:57:17 +00:00
|
|
|
$packageFiles = $this->expandPackageFiles( $context );
|
|
|
|
|
if ( $packageFiles ) {
|
|
|
|
|
// Extract the minimum needed:
|
|
|
|
|
// - The 'main' pointer (included as-is).
|
2020-02-23 22:39:52 +00:00
|
|
|
// - The 'files' array, simplified to only which files exist (the keys of
|
2019-06-12 00:57:17 +00:00
|
|
|
// this array), and something that represents their non-file content.
|
|
|
|
|
// For packaged files that reflect files directly from disk, the
|
resourceloader: Use FileContentsHasher batching in FileModule::getFileHashes
Instead of hashing each file separately, hash them in a batch.
Previous research on this area of code has identified the suppressing
and restoring of warnings to have a measurable cost, which is why
this was optimised in 3621ad0f82f8b6b. However, we never really made
use if it (aisde from the 2:1 change in that commit itself), because
we always call it with a single item, turn it into an array, do the
hash and then merge it again.
Instead, we now let it handle a single module's set of files all
at once. Given that this no longer exposes an array of hashes,
also update the (private) signature of getFileHashes to reflect this.
This means all file modules will have their version bumped during the
next MediaWiki release. In general this happens for most releases
and weekly branches already (due to localisation update, general
maintenance, linting changes, and other internal changes). But,
noting here for future reference as this might not be obvious from
the diff.
Change-Id: I4e141a0f5a5c1c1972e2ba33d4b7be6e64ed6ab6
2019-12-15 19:35:20 +00:00
|
|
|
// 'getFileHashes' method tracks their content already.
|
|
|
|
|
// It is important that the keys of the $packageFiles['files'] array
|
|
|
|
|
// are preserved, as they do affect the module output.
|
2021-02-10 22:31:02 +00:00
|
|
|
$packageFiles['files'] = array_map( static function ( $fileInfo ) {
|
2019-06-12 00:57:17 +00:00
|
|
|
return $fileInfo['definitionSummary'] ?? ( $fileInfo['content'] ?? null );
|
|
|
|
|
}, $packageFiles['files'] );
|
|
|
|
|
}
|
|
|
|
|
|
2016-02-17 09:09:32 +00:00
|
|
|
$summary[] = [
|
resourceloader: Replace timestamp system with version hashing
Modules now track their version via getVersionHash() instead of getModifiedTime().
== Background ==
While some resources have observeable timestamps (e.g. files stored on disk),
many other resources do not. E.g. config variables, and module definitions.
For static file modules, one can e.g. revert one of more files in a module to a
previous version and not affect the max timestamp.
Wiki modules include pages only if they exist. The user module supports common.js
and skin.js. By default neither exists. If a user has both, and then the
less-recently modified one is deleted, the max-timestamp remains unchanged.
For client-side caching, batch requests use "Math.max" on the relevant timestamps.
Again, if a module changes but another module is more recent (e.g. out-of-order
deployment, or out-of-order discovery), the change would not result in a cache miss.
More scenarios can be found in the associated Phabricator tasks.
== Version hash ==
Previously we virtually mapped these variables to a timestamp by storing the current
time alongside a hash of the value in ObjectCache. Considering the number of
possible request contexts (wikis * modules * users * skins * languages) this doesn't
work well. It results in needless cache invalidation when the first time observation
is purged due to LRU algorithms. It also has other minor bugs leading to fewer
cache hits.
All modules automatically get the benefits of version hashing with this change.
The old getDefinitionMtime() and getHashMtime() have been replaced with dummies
that return 1. These functions are often called from getModifiedTime() in subclasses.
For backward-compatibility, their respective values (definition summary and hash)
are now included in getVersionHash directly.
As examples, the following modules have been updated to use getVersionHash directly.
Other modules still work fine and can be updated later.
* ResourceLoaderFileModule
* ResourceLoaderEditToolbarModule
* ResourceLoaderStartUpModule
* ResourceLoaderWikiModule
The presence of hashes in place of timestamps increases the startup module size on
a default MediaWiki install from 4.4k to 5.8k (after gzip and minification).
== ETag ==
Since timestamps are no longer tracked, we need a different way to implement caching
for cache proxies (e.g. Varnish) and web browsers. Previously we used the
Last-Modified header (in combination with Cache-Control and Expires).
Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match).
Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default.
They instruct browsers to allow usage of partial Range requests. Since our responses
are dynamically generated, we need to use the Weak version of ETag.
While this sounds bad, it's no different than Last-Modified. As reassured by
RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the
specified behaviour behind Last-Modified follows the same "Weak" caching logic as
Entity tags. It's just that entity tags are capable of a stricter mode (whereas
Last-Modified is inherently weak).
== File cache ==
If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache
load.php responses. While the blind TTL handling (during the allowed expiry period)
is still maxage/timestamp based, tryRespondNotModified() now requires the caller to
know the expected ETag.
For this to work, the FileCache handling had to be moved from the top of
ResoureLoader::respond() to after the expected ETag is computed.
This also allows us to remove the duplicate tryRespondNotModified() handling since
that's is already handled by ResourceLoader::respond() meanwhile.
== Misc ==
* Remove redundant modifiedTime cache in ResourceLoaderFileModule.
* Change bugzilla references to Phabricator.
* Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this
logic was duplicated in each place the modified timestamp was used.
* It's easy to forget calling the parent class in getDefinitionSummary().
Previously this method only tracked 'class' by default. As such, various
extensions hardcoded that one value instead of calling the parent and extending
the array. To better prevent this in the future, getVersionHash() now asserts
that the '_cacheEpoch' property made it through.
* tests: Don't use getDefinitionSummary() as an API.
Fix ResourceLoaderWikiModuleTest to call getPages properly.
* In tests, the default timestamp used to be 1388534400000 (which is the unix time
of 20140101000000; the unit tests' CacheEpoch). The new version hash of these
modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of:
'{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}'
* Add sha1.js library for client-side hash generation.
Compared various different implementations for code size (after minfication/gzip),
and speed (when used for short hexidecimal strings).
https://jsperf.com/sha1-implementations
- CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k)
http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js
Chrome: 45k, Firefox: 89k, Safari: 92k
- jsSHA <https://github.com/Caligatio/jsSHA>
https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k)
Chrome: 65k, Firefox: 53k, Safari: 69k
- phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k)
https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js
Chrome: 200k, Firefox: 280k, Safari: 78k
Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous,
only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate
code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being
needed in the module loader, we'd have to load the fallback regardless. Considering
this is not used in a critical path for performance, it's not worth shipping two
implementations for this optimisation.
May also resolve:
* T44094
* T90411
* T94810
Bug: T94074
Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
|
|
|
'options' => $options,
|
2019-06-12 00:57:17 +00:00
|
|
|
'packageFiles' => $packageFiles,
|
2015-07-09 18:30:53 +00:00
|
|
|
'fileHashes' => $this->getFileHashes( $context ),
|
2015-11-13 00:04:12 +00:00
|
|
|
'messageBlob' => $this->getMessageBlob( $context ),
|
2016-02-17 09:09:32 +00:00
|
|
|
];
|
2017-07-27 01:53:37 +00:00
|
|
|
|
|
|
|
|
$lessVars = $this->getLessVars( $context );
|
|
|
|
|
if ( $lessVars ) {
|
|
|
|
|
$summary[] = [ 'lessVars' => $lessVars ];
|
|
|
|
|
}
|
|
|
|
|
|
2013-10-18 13:34:50 +00:00
|
|
|
return $summary;
|
|
|
|
|
}
|
|
|
|
|
|
2020-02-04 01:42:03 +00:00
|
|
|
/**
|
|
|
|
|
* @return VueComponentParser
|
|
|
|
|
*/
|
|
|
|
|
protected function getVueComponentParser() {
|
|
|
|
|
if ( $this->vueComponentParser === null ) {
|
|
|
|
|
$this->vueComponentParser = new VueComponentParser;
|
|
|
|
|
}
|
|
|
|
|
return $this->vueComponentParser;
|
|
|
|
|
}
|
|
|
|
|
|
2017-03-17 02:14:05 +00:00
|
|
|
/**
|
|
|
|
|
* @param string|ResourceLoaderFilePath $path
|
|
|
|
|
* @return string
|
|
|
|
|
*/
|
|
|
|
|
protected function getPath( $path ) {
|
|
|
|
|
if ( $path instanceof ResourceLoaderFilePath ) {
|
|
|
|
|
return $path->getPath();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return $path;
|
|
|
|
|
}
|
|
|
|
|
|
2011-05-21 17:45:20 +00:00
|
|
|
/**
|
2014-06-26 14:29:31 +00:00
|
|
|
* @param string|ResourceLoaderFilePath $path
|
2011-05-21 17:45:20 +00:00
|
|
|
* @return string
|
|
|
|
|
*/
|
2010-10-27 22:22:10 +00:00
|
|
|
protected function getLocalPath( $path ) {
|
2014-06-26 14:29:31 +00:00
|
|
|
if ( $path instanceof ResourceLoaderFilePath ) {
|
|
|
|
|
return $path->getLocalPath();
|
|
|
|
|
}
|
|
|
|
|
|
2010-10-27 22:22:10 +00:00
|
|
|
return "{$this->localBasePath}/$path";
|
|
|
|
|
}
|
2011-05-21 17:45:20 +00:00
|
|
|
|
|
|
|
|
/**
|
2014-06-26 14:29:31 +00:00
|
|
|
* @param string|ResourceLoaderFilePath $path
|
2011-05-21 17:45:20 +00:00
|
|
|
* @return string
|
|
|
|
|
*/
|
2010-10-27 22:22:10 +00:00
|
|
|
protected function getRemotePath( $path ) {
|
2014-06-26 14:29:31 +00:00
|
|
|
if ( $path instanceof ResourceLoaderFilePath ) {
|
|
|
|
|
return $path->getRemotePath();
|
|
|
|
|
}
|
|
|
|
|
|
2021-02-24 01:13:22 +00:00
|
|
|
if ( $this->remoteBasePath === '/' ) {
|
|
|
|
|
return "/$path";
|
|
|
|
|
} else {
|
|
|
|
|
return "{$this->remoteBasePath}/$path";
|
|
|
|
|
}
|
2010-10-19 20:59:23 +00:00
|
|
|
}
|
|
|
|
|
|
Support LESS stylesheets in ResourceLoader
This patch adds support for the LESS stylesheet language to ResourceLoader.
LESS is a stylesheet language that compiles into CSS. The patch includes
lessphp, a LESS compiler implemented in PHP. The rationale for choosing LESS is
explained in a MediaWiki RFC which accompanies this patch, available at
<https://www.mediawiki.org/wiki/Requests_for_comment/LESS>.
LESS support is provided for ResourceLoader file modules. It is triggered by
the presence of the '.less' extension in stylesheet filenames. LESS files are
compiled by lessc, and the resultant CSS is subjected to the standard set of
transformations (CSSJanus & CSSMin). The immediate result of LESS compilation
is encoded as an array, which includes the list of LESS files that were
compiled and their mtimes. This array is cached. Cache invalidation is
performed by comparing the cached mtimes with the mtimes of the files on disk.
If the compiler itself throws an exception, ResourceLoader constructs a
compilation result which consists of the error message encoded as a CSS
comment. Failed compilation results are cached too, but with an expiration time
of five minutes. The expiration time is required because the full list of
referenced files is not known.
Three configuration variables configure the global environment for LESS
modules: $wgResourceLoaderLESSVars, $wgResourceLoaderLESSFunctions, and
$wgResourceLoaderLESSImportPaths. $wgResourceLoaderLESSVars maps variable names
to CSS values, specified as strings. Variables declared in this array are
available in all LESS files. $wgResourceLoaderLESSFunctions is similar, except
it maps custom function names to PHP callables. These functions can be called
from within LESS to transform values. Read more about custom functions at
<http://leafo.net/lessphp/docs/#custom_functions>. Finally,
$wgResourceLoaderLESSImportPaths specifies file system paths in addition to the
current module's path where the LESS compiler should look up files referenced
in @import statements.
The issue of handling of /* @embed */ and /* @noflip */ annotations is left
unresolved. Earlier versions of this patch included an @embed analog
implemented as a LESS custom function, but there was enough ambiguity about
whether the strategy it took was optimal to merit discussing it in a separate,
follow-up patch.
Bug: 40964
Change-Id: Id052a04dd2f76a1f4aef39fbd454bd67f5fd282f
2013-08-11 16:40:20 +00:00
|
|
|
/**
|
|
|
|
|
* Infer the stylesheet language from a stylesheet file path.
|
|
|
|
|
*
|
2013-09-27 09:32:41 +00:00
|
|
|
* @since 1.22
|
Support LESS stylesheets in ResourceLoader
This patch adds support for the LESS stylesheet language to ResourceLoader.
LESS is a stylesheet language that compiles into CSS. The patch includes
lessphp, a LESS compiler implemented in PHP. The rationale for choosing LESS is
explained in a MediaWiki RFC which accompanies this patch, available at
<https://www.mediawiki.org/wiki/Requests_for_comment/LESS>.
LESS support is provided for ResourceLoader file modules. It is triggered by
the presence of the '.less' extension in stylesheet filenames. LESS files are
compiled by lessc, and the resultant CSS is subjected to the standard set of
transformations (CSSJanus & CSSMin). The immediate result of LESS compilation
is encoded as an array, which includes the list of LESS files that were
compiled and their mtimes. This array is cached. Cache invalidation is
performed by comparing the cached mtimes with the mtimes of the files on disk.
If the compiler itself throws an exception, ResourceLoader constructs a
compilation result which consists of the error message encoded as a CSS
comment. Failed compilation results are cached too, but with an expiration time
of five minutes. The expiration time is required because the full list of
referenced files is not known.
Three configuration variables configure the global environment for LESS
modules: $wgResourceLoaderLESSVars, $wgResourceLoaderLESSFunctions, and
$wgResourceLoaderLESSImportPaths. $wgResourceLoaderLESSVars maps variable names
to CSS values, specified as strings. Variables declared in this array are
available in all LESS files. $wgResourceLoaderLESSFunctions is similar, except
it maps custom function names to PHP callables. These functions can be called
from within LESS to transform values. Read more about custom functions at
<http://leafo.net/lessphp/docs/#custom_functions>. Finally,
$wgResourceLoaderLESSImportPaths specifies file system paths in addition to the
current module's path where the LESS compiler should look up files referenced
in @import statements.
The issue of handling of /* @embed */ and /* @noflip */ annotations is left
unresolved. Earlier versions of this patch included an @embed analog
implemented as a LESS custom function, but there was enough ambiguity about
whether the strategy it took was optimal to merit discussing it in a separate,
follow-up patch.
Bug: 40964
Change-Id: Id052a04dd2f76a1f4aef39fbd454bd67f5fd282f
2013-08-11 16:40:20 +00:00
|
|
|
* @param string $path
|
2014-04-20 21:33:05 +00:00
|
|
|
* @return string The stylesheet language name
|
Support LESS stylesheets in ResourceLoader
This patch adds support for the LESS stylesheet language to ResourceLoader.
LESS is a stylesheet language that compiles into CSS. The patch includes
lessphp, a LESS compiler implemented in PHP. The rationale for choosing LESS is
explained in a MediaWiki RFC which accompanies this patch, available at
<https://www.mediawiki.org/wiki/Requests_for_comment/LESS>.
LESS support is provided for ResourceLoader file modules. It is triggered by
the presence of the '.less' extension in stylesheet filenames. LESS files are
compiled by lessc, and the resultant CSS is subjected to the standard set of
transformations (CSSJanus & CSSMin). The immediate result of LESS compilation
is encoded as an array, which includes the list of LESS files that were
compiled and their mtimes. This array is cached. Cache invalidation is
performed by comparing the cached mtimes with the mtimes of the files on disk.
If the compiler itself throws an exception, ResourceLoader constructs a
compilation result which consists of the error message encoded as a CSS
comment. Failed compilation results are cached too, but with an expiration time
of five minutes. The expiration time is required because the full list of
referenced files is not known.
Three configuration variables configure the global environment for LESS
modules: $wgResourceLoaderLESSVars, $wgResourceLoaderLESSFunctions, and
$wgResourceLoaderLESSImportPaths. $wgResourceLoaderLESSVars maps variable names
to CSS values, specified as strings. Variables declared in this array are
available in all LESS files. $wgResourceLoaderLESSFunctions is similar, except
it maps custom function names to PHP callables. These functions can be called
from within LESS to transform values. Read more about custom functions at
<http://leafo.net/lessphp/docs/#custom_functions>. Finally,
$wgResourceLoaderLESSImportPaths specifies file system paths in addition to the
current module's path where the LESS compiler should look up files referenced
in @import statements.
The issue of handling of /* @embed */ and /* @noflip */ annotations is left
unresolved. Earlier versions of this patch included an @embed analog
implemented as a LESS custom function, but there was enough ambiguity about
whether the strategy it took was optimal to merit discussing it in a separate,
follow-up patch.
Bug: 40964
Change-Id: Id052a04dd2f76a1f4aef39fbd454bd67f5fd282f
2013-08-11 16:40:20 +00:00
|
|
|
*/
|
2013-09-28 07:40:03 +00:00
|
|
|
public function getStyleSheetLang( $path ) {
|
Support LESS stylesheets in ResourceLoader
This patch adds support for the LESS stylesheet language to ResourceLoader.
LESS is a stylesheet language that compiles into CSS. The patch includes
lessphp, a LESS compiler implemented in PHP. The rationale for choosing LESS is
explained in a MediaWiki RFC which accompanies this patch, available at
<https://www.mediawiki.org/wiki/Requests_for_comment/LESS>.
LESS support is provided for ResourceLoader file modules. It is triggered by
the presence of the '.less' extension in stylesheet filenames. LESS files are
compiled by lessc, and the resultant CSS is subjected to the standard set of
transformations (CSSJanus & CSSMin). The immediate result of LESS compilation
is encoded as an array, which includes the list of LESS files that were
compiled and their mtimes. This array is cached. Cache invalidation is
performed by comparing the cached mtimes with the mtimes of the files on disk.
If the compiler itself throws an exception, ResourceLoader constructs a
compilation result which consists of the error message encoded as a CSS
comment. Failed compilation results are cached too, but with an expiration time
of five minutes. The expiration time is required because the full list of
referenced files is not known.
Three configuration variables configure the global environment for LESS
modules: $wgResourceLoaderLESSVars, $wgResourceLoaderLESSFunctions, and
$wgResourceLoaderLESSImportPaths. $wgResourceLoaderLESSVars maps variable names
to CSS values, specified as strings. Variables declared in this array are
available in all LESS files. $wgResourceLoaderLESSFunctions is similar, except
it maps custom function names to PHP callables. These functions can be called
from within LESS to transform values. Read more about custom functions at
<http://leafo.net/lessphp/docs/#custom_functions>. Finally,
$wgResourceLoaderLESSImportPaths specifies file system paths in addition to the
current module's path where the LESS compiler should look up files referenced
in @import statements.
The issue of handling of /* @embed */ and /* @noflip */ annotations is left
unresolved. Earlier versions of this patch included an @embed analog
implemented as a LESS custom function, but there was enough ambiguity about
whether the strategy it took was optimal to merit discussing it in a separate,
follow-up patch.
Bug: 40964
Change-Id: Id052a04dd2f76a1f4aef39fbd454bd67f5fd282f
2013-08-11 16:40:20 +00:00
|
|
|
return preg_match( '/\.less$/i', $path ) ? 'less' : 'css';
|
|
|
|
|
}
|
|
|
|
|
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
/**
|
|
|
|
|
* Infer the file type from a package file path.
|
|
|
|
|
* @param string $path
|
2020-02-04 01:42:03 +00:00
|
|
|
* @return string 'script', 'script-vue', or 'data'
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
*/
|
|
|
|
|
public static function getPackageFileType( $path ) {
|
|
|
|
|
if ( preg_match( '/\.json$/i', $path ) ) {
|
|
|
|
|
return 'data';
|
|
|
|
|
}
|
2020-02-04 01:42:03 +00:00
|
|
|
if ( preg_match( '/\.vue$/i', $path ) ) {
|
|
|
|
|
return 'script-vue';
|
|
|
|
|
}
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
return 'script';
|
|
|
|
|
}
|
|
|
|
|
|
2010-10-19 20:59:23 +00:00
|
|
|
/**
|
2010-10-20 00:22:25 +00:00
|
|
|
* Collates file paths by option (where provided).
|
2011-06-17 16:05:05 +00:00
|
|
|
*
|
2013-03-11 17:15:01 +00:00
|
|
|
* @param array $list List of file paths in any combination of index/path
|
2010-11-05 06:53:14 +00:00
|
|
|
* or path/options pairs
|
2014-04-20 21:33:05 +00:00
|
|
|
* @param string $option Option name
|
|
|
|
|
* @param mixed $default Default value if the option isn't set
|
2020-10-28 10:01:33 +00:00
|
|
|
* @return string[][] List of file paths, collated by $option
|
2010-10-19 20:59:23 +00:00
|
|
|
*/
|
|
|
|
|
protected static function collateFilePathListByOption( array $list, $option, $default ) {
|
2016-02-17 09:09:32 +00:00
|
|
|
$collatedFiles = [];
|
2020-06-15 10:46:22 +00:00
|
|
|
foreach ( $list as $key => $value ) {
|
2010-10-19 20:59:23 +00:00
|
|
|
if ( is_int( $key ) ) {
|
|
|
|
|
// File name as the value
|
|
|
|
|
if ( !isset( $collatedFiles[$default] ) ) {
|
2016-02-17 09:09:32 +00:00
|
|
|
$collatedFiles[$default] = [];
|
2010-10-19 20:59:23 +00:00
|
|
|
}
|
|
|
|
|
$collatedFiles[$default][] = $value;
|
2011-06-17 16:05:05 +00:00
|
|
|
} elseif ( is_array( $value ) ) {
|
2010-10-19 20:59:23 +00:00
|
|
|
// File name as the key, options array as the value
|
2017-10-06 22:17:58 +00:00
|
|
|
$optionValue = $value[$option] ?? $default;
|
2010-10-20 20:43:30 +00:00
|
|
|
if ( !isset( $collatedFiles[$optionValue] ) ) {
|
2016-02-17 09:09:32 +00:00
|
|
|
$collatedFiles[$optionValue] = [];
|
2010-10-19 20:59:23 +00:00
|
|
|
}
|
2010-10-20 20:43:30 +00:00
|
|
|
$collatedFiles[$optionValue][] = $key;
|
2010-10-19 20:59:23 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return $collatedFiles;
|
|
|
|
|
}
|
|
|
|
|
|
2010-10-19 18:25:42 +00:00
|
|
|
/**
|
2014-06-04 19:30:14 +00:00
|
|
|
* Get a list of element that match a key, optionally using a fallback key.
|
2011-06-17 16:05:05 +00:00
|
|
|
*
|
2020-10-28 10:01:33 +00:00
|
|
|
* @param array[] $list List of lists to select from
|
|
|
|
|
* @param string $key Key to look for in $list
|
2018-06-26 21:14:43 +00:00
|
|
|
* @param string|null $fallback Key to look for in $list if $key doesn't exist
|
2020-10-28 10:01:33 +00:00
|
|
|
* @return array List of elements from $list which matched $key or $fallback,
|
2014-06-04 19:30:14 +00:00
|
|
|
* or an empty list in case of no match
|
2010-10-19 18:25:42 +00:00
|
|
|
*/
|
2010-10-20 20:56:33 +00:00
|
|
|
protected static function tryForKey( array $list, $key, $fallback = null ) {
|
2010-10-19 22:48:52 +00:00
|
|
|
if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
|
2010-10-20 20:56:33 +00:00
|
|
|
return $list[$key];
|
2011-06-17 16:05:05 +00:00
|
|
|
} elseif ( is_string( $fallback )
|
|
|
|
|
&& isset( $list[$fallback] )
|
2013-12-01 20:39:00 +00:00
|
|
|
&& is_array( $list[$fallback] )
|
|
|
|
|
) {
|
2010-10-20 20:56:33 +00:00
|
|
|
return $list[$fallback];
|
2010-10-19 22:48:52 +00:00
|
|
|
}
|
2016-02-17 09:09:32 +00:00
|
|
|
return [];
|
2010-10-19 18:25:42 +00:00
|
|
|
}
|
|
|
|
|
|
2011-05-14 12:15:58 +00:00
|
|
|
/**
|
2018-06-26 01:52:40 +00:00
|
|
|
* Get a list of script file paths for this module, in order of proper execution.
|
2011-06-17 16:05:05 +00:00
|
|
|
*
|
2013-09-13 04:50:45 +00:00
|
|
|
* @param ResourceLoaderContext $context
|
2020-10-28 10:01:33 +00:00
|
|
|
* @return string[] List of file paths
|
2011-05-14 12:15:58 +00:00
|
|
|
*/
|
2018-06-26 01:52:40 +00:00
|
|
|
private function getScriptFiles( ResourceLoaderContext $context ) {
|
2011-05-14 12:15:58 +00:00
|
|
|
$files = array_merge(
|
|
|
|
|
$this->scripts,
|
2014-08-29 17:13:21 +00:00
|
|
|
$this->getLanguageScripts( $context->getLanguage() ),
|
2011-05-14 12:15:58 +00:00
|
|
|
self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
|
|
|
|
|
);
|
|
|
|
|
if ( $context->getDebug() ) {
|
|
|
|
|
$files = array_merge( $files, $this->debugScripts );
|
|
|
|
|
}
|
2012-10-21 21:06:00 +00:00
|
|
|
|
2014-06-26 14:29:31 +00:00
|
|
|
return array_unique( $files, SORT_REGULAR );
|
2011-05-14 12:15:58 +00:00
|
|
|
}
|
|
|
|
|
|
2014-08-29 17:13:21 +00:00
|
|
|
/**
|
|
|
|
|
* Get the set of language scripts for the given language,
|
|
|
|
|
* possibly using a fallback language.
|
|
|
|
|
*
|
|
|
|
|
* @param string $lang
|
2020-10-28 10:01:33 +00:00
|
|
|
* @return string[]
|
2014-08-29 17:13:21 +00:00
|
|
|
*/
|
|
|
|
|
private function getLanguageScripts( $lang ) {
|
|
|
|
|
$scripts = self::tryForKey( $this->languageScripts, $lang );
|
|
|
|
|
if ( $scripts ) {
|
|
|
|
|
return $scripts;
|
|
|
|
|
}
|
2019-12-15 19:11:40 +00:00
|
|
|
$fallbacks = MediaWikiServices::getInstance()->getLanguageFallback()
|
|
|
|
|
->getAll( $lang, LanguageFallback::MESSAGES );
|
2014-08-29 17:13:21 +00:00
|
|
|
foreach ( $fallbacks as $lang ) {
|
|
|
|
|
$scripts = self::tryForKey( $this->languageScripts, $lang );
|
|
|
|
|
if ( $scripts ) {
|
|
|
|
|
return $scripts;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2016-02-17 09:09:32 +00:00
|
|
|
return [];
|
2014-08-29 17:13:21 +00:00
|
|
|
}
|
|
|
|
|
|
2021-08-11 18:53:15 +00:00
|
|
|
public function setSkinStylesOverride( array $moduleSkinStyles ): void {
|
|
|
|
|
$moduleName = $this->getName();
|
|
|
|
|
foreach ( $moduleSkinStyles as $skinName => $overrides ) {
|
|
|
|
|
// If a module provides overrides for a skin, and that skin also provides overrides
|
|
|
|
|
// for the same module, then the module has precedence.
|
|
|
|
|
if ( isset( $this->skinStyles[$skinName] ) ) {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// If $moduleName in ResourceModuleSkinStyles is preceded with a '+', the defined style
|
|
|
|
|
// files will be added to 'default' skinStyles, otherwise 'default' will be ignored.
|
|
|
|
|
if ( isset( $overrides[$moduleName] ) ) {
|
|
|
|
|
$paths = (array)$overrides[$moduleName];
|
|
|
|
|
$styleFiles = [];
|
|
|
|
|
} elseif ( isset( $overrides['+' . $moduleName] ) ) {
|
|
|
|
|
$paths = (array)$overrides['+' . $moduleName];
|
|
|
|
|
$styleFiles = isset( $this->skinStyles['default'] ) ?
|
|
|
|
|
(array)$this->skinStyles['default'] :
|
|
|
|
|
[];
|
|
|
|
|
} else {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Add new file paths, remapping them to refer to our directories and not use settings
|
|
|
|
|
// from the module we're modifying, which come from the base definition.
|
|
|
|
|
list( $localBasePath, $remoteBasePath ) = self::extractBasePaths( $overrides );
|
|
|
|
|
|
|
|
|
|
foreach ( $paths as $path ) {
|
|
|
|
|
$styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$this->skinStyles[$skinName] = $styleFiles;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2011-05-14 12:15:58 +00:00
|
|
|
/**
|
2014-06-04 19:30:14 +00:00
|
|
|
* Get a list of file paths for all styles in this module, in order of proper inclusion.
|
2011-06-17 16:05:05 +00:00
|
|
|
*
|
2021-04-14 21:52:37 +00:00
|
|
|
* @internal Exposed only for use by structure phpunit tests.
|
2013-09-13 04:50:45 +00:00
|
|
|
* @param ResourceLoaderContext $context
|
2020-10-28 10:01:33 +00:00
|
|
|
* @return string[][] List of file paths
|
2011-05-14 12:15:58 +00:00
|
|
|
*/
|
2014-06-04 19:30:14 +00:00
|
|
|
public function getStyleFiles( ResourceLoaderContext $context ) {
|
2011-05-14 12:15:58 +00:00
|
|
|
return array_merge_recursive(
|
|
|
|
|
self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
|
|
|
|
|
self::collateFilePathListByOption(
|
2014-02-28 19:23:11 +00:00
|
|
|
self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
|
|
|
|
|
'media',
|
|
|
|
|
'all'
|
2011-05-14 12:15:58 +00:00
|
|
|
)
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2013-09-28 07:40:03 +00:00
|
|
|
/**
|
2014-04-01 14:28:46 +00:00
|
|
|
* Gets a list of file paths for all skin styles in the module used by
|
|
|
|
|
* the skin.
|
|
|
|
|
*
|
|
|
|
|
* @param string $skinName The name of the skin
|
|
|
|
|
* @return array A list of file paths collated by media type
|
|
|
|
|
*/
|
|
|
|
|
protected function getSkinStyleFiles( $skinName ) {
|
|
|
|
|
return self::collateFilePathListByOption(
|
|
|
|
|
self::tryForKey( $this->skinStyles, $skinName ),
|
|
|
|
|
'media',
|
|
|
|
|
'all'
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Gets a list of file paths for all skin style files in the module,
|
|
|
|
|
* for all available skins.
|
|
|
|
|
*
|
|
|
|
|
* @return array A list of file paths collated by media type
|
|
|
|
|
*/
|
|
|
|
|
protected function getAllSkinStyleFiles() {
|
2020-08-18 00:11:09 +00:00
|
|
|
$skinFactory = MediaWikiServices::getInstance()->getSkinFactory();
|
2016-02-17 09:09:32 +00:00
|
|
|
$styleFiles = [];
|
2020-08-18 00:11:09 +00:00
|
|
|
|
2021-08-08 13:30:16 +00:00
|
|
|
$internalSkinNames = array_keys( $skinFactory->getInstalledSkins() );
|
2014-04-01 14:28:46 +00:00
|
|
|
$internalSkinNames[] = 'default';
|
|
|
|
|
|
|
|
|
|
foreach ( $internalSkinNames as $internalSkinName ) {
|
|
|
|
|
$styleFiles = array_merge_recursive(
|
|
|
|
|
$styleFiles,
|
|
|
|
|
$this->getSkinStyleFiles( $internalSkinName )
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return $styleFiles;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Returns all style files and all skin style files used by this module.
|
|
|
|
|
*
|
2013-09-28 07:40:03 +00:00
|
|
|
* @return array
|
|
|
|
|
*/
|
|
|
|
|
public function getAllStyleFiles() {
|
2014-04-01 14:28:46 +00:00
|
|
|
$collatedStyleFiles = array_merge_recursive(
|
|
|
|
|
self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
|
|
|
|
|
$this->getAllSkinStyleFiles()
|
|
|
|
|
);
|
|
|
|
|
|
2016-02-17 09:09:32 +00:00
|
|
|
$result = [];
|
2014-04-01 14:28:46 +00:00
|
|
|
|
|
|
|
|
foreach ( $collatedStyleFiles as $media => $styleFiles ) {
|
|
|
|
|
foreach ( $styleFiles as $styleFile ) {
|
|
|
|
|
$result[] = $this->getLocalPath( $styleFile );
|
2013-09-28 07:40:03 +00:00
|
|
|
}
|
|
|
|
|
}
|
2014-04-01 14:28:46 +00:00
|
|
|
|
|
|
|
|
return $result;
|
2013-09-28 07:40:03 +00:00
|
|
|
}
|
|
|
|
|
|
2010-10-19 18:25:42 +00:00
|
|
|
/**
|
2018-06-26 01:52:40 +00:00
|
|
|
* Get the contents of a list of JavaScript files. Helper for getScript().
|
2011-06-17 16:05:05 +00:00
|
|
|
*
|
2020-10-28 10:01:33 +00:00
|
|
|
* @param string[] $scripts List of file paths to scripts to read, remap and concetenate
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
* @return string Concatenated JavaScript data from $scripts
|
2020-03-11 19:52:52 +00:00
|
|
|
* @throws RuntimeException
|
2010-10-19 18:25:42 +00:00
|
|
|
*/
|
2018-06-26 01:52:40 +00:00
|
|
|
private function readScriptFiles( array $scripts ) {
|
2010-10-19 22:48:52 +00:00
|
|
|
if ( empty( $scripts ) ) {
|
2010-10-19 18:25:42 +00:00
|
|
|
return '';
|
|
|
|
|
}
|
2010-11-05 06:53:14 +00:00
|
|
|
$js = '';
|
2014-06-26 14:29:31 +00:00
|
|
|
foreach ( array_unique( $scripts, SORT_REGULAR ) as $fileName ) {
|
2010-11-05 06:53:14 +00:00
|
|
|
$localPath = $this->getLocalPath( $fileName );
|
2020-03-11 19:52:52 +00:00
|
|
|
$contents = $this->getFileContents( $localPath, 'script' );
|
2019-07-27 09:26:58 +00:00
|
|
|
$js .= ResourceLoader::ensureNewline( $contents );
|
2010-11-05 06:53:14 +00:00
|
|
|
}
|
|
|
|
|
return $js;
|
2010-10-19 18:25:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
2018-06-26 01:52:40 +00:00
|
|
|
* Get the contents of a list of CSS files.
|
|
|
|
|
*
|
2019-02-16 23:30:46 +00:00
|
|
|
* @internal This is considered a private method. Exposed for internal use by WebInstallerOutput.
|
2018-06-26 01:52:40 +00:00
|
|
|
* @param array $styles Map of media type to file paths to read, remap, and concatenate
|
2019-02-16 23:30:46 +00:00
|
|
|
* @param ResourceLoaderContext $context
|
2020-10-28 10:01:33 +00:00
|
|
|
* @return string[] List of concatenated and remapped CSS data from $styles,
|
2010-11-05 06:53:14 +00:00
|
|
|
* keyed by media type
|
2020-03-11 19:52:52 +00:00
|
|
|
* @throws RuntimeException
|
2010-10-19 18:25:42 +00:00
|
|
|
*/
|
2020-02-04 22:44:14 +00:00
|
|
|
public function readStyleFiles( array $styles, ResourceLoaderContext $context ) {
|
2019-02-16 23:30:46 +00:00
|
|
|
if ( !$styles ) {
|
2016-02-17 09:09:32 +00:00
|
|
|
return [];
|
2010-10-19 18:25:42 +00:00
|
|
|
}
|
|
|
|
|
foreach ( $styles as $media => $files ) {
|
2014-06-26 14:29:31 +00:00
|
|
|
$uniqueFiles = array_unique( $files, SORT_REGULAR );
|
2016-02-17 09:09:32 +00:00
|
|
|
$styleFiles = [];
|
2014-01-30 18:39:51 +00:00
|
|
|
foreach ( $uniqueFiles as $file ) {
|
2020-02-04 22:44:14 +00:00
|
|
|
$styleFiles[] = $this->readStyleFile( $file, $context );
|
2014-01-30 18:39:51 +00:00
|
|
|
}
|
|
|
|
|
$styles[$media] = implode( "\n", $styleFiles );
|
2010-10-19 18:25:42 +00:00
|
|
|
}
|
|
|
|
|
return $styles;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
2020-02-04 22:44:14 +00:00
|
|
|
* Read and process a style file. Reads a file from disk and runs it through processStyle().
|
2011-06-17 16:05:05 +00:00
|
|
|
*
|
2010-10-19 22:48:52 +00:00
|
|
|
* This method can be used as a callback for array_map()
|
2011-06-17 16:05:05 +00:00
|
|
|
*
|
2020-02-04 22:44:14 +00:00
|
|
|
* @internal
|
2013-03-11 17:15:01 +00:00
|
|
|
* @param string $path File path of style file to read
|
2015-09-25 17:57:35 +00:00
|
|
|
* @param ResourceLoaderContext $context
|
2014-04-20 21:33:05 +00:00
|
|
|
* @return string CSS data in script file
|
2019-12-01 01:58:30 +00:00
|
|
|
* @throws RuntimeException If the file doesn't exist
|
2010-10-19 18:25:42 +00:00
|
|
|
*/
|
2020-02-04 22:44:14 +00:00
|
|
|
protected function readStyleFile( $path, ResourceLoaderContext $context ) {
|
2010-11-05 06:53:14 +00:00
|
|
|
$localPath = $this->getLocalPath( $path );
|
2020-03-11 19:52:52 +00:00
|
|
|
$style = $this->getFileContents( $localPath, 'style' );
|
2020-02-04 22:44:14 +00:00
|
|
|
$styleLang = $this->getStyleSheetLang( $localPath );
|
|
|
|
|
|
|
|
|
|
return $this->processStyle( $style, $styleLang, $path, $context );
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Process a CSS/LESS string.
|
|
|
|
|
*
|
|
|
|
|
* This method performs the following processing steps:
|
|
|
|
|
* - LESS compilation (if $styleLang = 'less')
|
|
|
|
|
* - RTL flipping with CSSJanus (if getFlip() returns true)
|
|
|
|
|
* - Registration of references to local files in $localFileRefs and $missingLocalFileRefs
|
|
|
|
|
* - URL remapping and data URI embedding
|
|
|
|
|
*
|
|
|
|
|
* @internal
|
|
|
|
|
* @param string $style CSS/LESS string
|
|
|
|
|
* @param string $styleLang Language of $style ('css' or 'less')
|
|
|
|
|
* @param string $path File path where the CSS/LESS lives, used for resolving relative file paths
|
|
|
|
|
* @param ResourceLoaderContext $context
|
|
|
|
|
* @return string Processed CSS
|
|
|
|
|
*/
|
|
|
|
|
protected function processStyle( $style, $styleLang, $path, ResourceLoaderContext $context ) {
|
|
|
|
|
$localPath = $this->getLocalPath( $path );
|
|
|
|
|
$remotePath = $this->getRemotePath( $path );
|
|
|
|
|
|
|
|
|
|
if ( $styleLang === 'less' ) {
|
|
|
|
|
$style = $this->compileLessString( $style, $localPath, $context );
|
Support LESS stylesheets in ResourceLoader
This patch adds support for the LESS stylesheet language to ResourceLoader.
LESS is a stylesheet language that compiles into CSS. The patch includes
lessphp, a LESS compiler implemented in PHP. The rationale for choosing LESS is
explained in a MediaWiki RFC which accompanies this patch, available at
<https://www.mediawiki.org/wiki/Requests_for_comment/LESS>.
LESS support is provided for ResourceLoader file modules. It is triggered by
the presence of the '.less' extension in stylesheet filenames. LESS files are
compiled by lessc, and the resultant CSS is subjected to the standard set of
transformations (CSSJanus & CSSMin). The immediate result of LESS compilation
is encoded as an array, which includes the list of LESS files that were
compiled and their mtimes. This array is cached. Cache invalidation is
performed by comparing the cached mtimes with the mtimes of the files on disk.
If the compiler itself throws an exception, ResourceLoader constructs a
compilation result which consists of the error message encoded as a CSS
comment. Failed compilation results are cached too, but with an expiration time
of five minutes. The expiration time is required because the full list of
referenced files is not known.
Three configuration variables configure the global environment for LESS
modules: $wgResourceLoaderLESSVars, $wgResourceLoaderLESSFunctions, and
$wgResourceLoaderLESSImportPaths. $wgResourceLoaderLESSVars maps variable names
to CSS values, specified as strings. Variables declared in this array are
available in all LESS files. $wgResourceLoaderLESSFunctions is similar, except
it maps custom function names to PHP callables. These functions can be called
from within LESS to transform values. Read more about custom functions at
<http://leafo.net/lessphp/docs/#custom_functions>. Finally,
$wgResourceLoaderLESSImportPaths specifies file system paths in addition to the
current module's path where the LESS compiler should look up files referenced
in @import statements.
The issue of handling of /* @embed */ and /* @noflip */ annotations is left
unresolved. Earlier versions of this patch included an @embed analog
implemented as a LESS custom function, but there was enough ambiguity about
whether the strategy it took was optimal to merit discussing it in a separate,
follow-up patch.
Bug: 40964
Change-Id: Id052a04dd2f76a1f4aef39fbd454bd67f5fd282f
2013-08-11 16:40:20 +00:00
|
|
|
$this->hasGeneratedStyles = true;
|
|
|
|
|
}
|
|
|
|
|
|
2020-02-04 22:44:14 +00:00
|
|
|
if ( $this->getFlip( $context ) ) {
|
|
|
|
|
$style = CSSJanus::transform(
|
|
|
|
|
$style,
|
|
|
|
|
/* $swapLtrRtlInURL = */ true,
|
|
|
|
|
/* $swapLeftRightInURL = */ false
|
|
|
|
|
);
|
2010-12-16 19:31:48 +00:00
|
|
|
}
|
2020-02-04 22:44:14 +00:00
|
|
|
|
2014-06-26 14:29:31 +00:00
|
|
|
$localDir = dirname( $localPath );
|
|
|
|
|
$remoteDir = dirname( $remotePath );
|
2010-10-27 19:59:10 +00:00
|
|
|
// Get and register local file references
|
2016-03-03 00:16:13 +00:00
|
|
|
$localFileRefs = CSSMin::getLocalFileReferences( $style, $localDir );
|
2015-09-03 21:30:36 +00:00
|
|
|
foreach ( $localFileRefs as $file ) {
|
|
|
|
|
if ( file_exists( $file ) ) {
|
|
|
|
|
$this->localFileRefs[] = $file;
|
|
|
|
|
} else {
|
|
|
|
|
$this->missingLocalFileRefs[] = $file;
|
|
|
|
|
}
|
|
|
|
|
}
|
2016-03-02 23:55:28 +00:00
|
|
|
// Don't cache this call. remap() ensures data URIs embeds are up to date,
|
|
|
|
|
// and urls contain correct content hashes in their query string. (T128668)
|
|
|
|
|
return CSSMin::remap( $style, $localDir, $remoteDir, true );
|
2010-10-19 18:25:42 +00:00
|
|
|
}
|
2011-10-14 08:06:54 +00:00
|
|
|
|
2011-03-25 11:15:40 +00:00
|
|
|
/**
|
|
|
|
|
* Get whether CSS for this module should be flipped
|
2013-09-13 04:50:45 +00:00
|
|
|
* @param ResourceLoaderContext $context
|
2011-03-25 11:15:40 +00:00
|
|
|
* @return bool
|
|
|
|
|
*/
|
2019-09-27 04:43:44 +00:00
|
|
|
public function getFlip( ResourceLoaderContext $context ) {
|
2016-10-18 19:04:40 +00:00
|
|
|
return $context->getDirection() === 'rtl' && !$this->noflip;
|
2011-03-25 11:15:40 +00:00
|
|
|
}
|
2012-10-11 22:37:59 +00:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
|
|
|
|
|
*
|
2020-10-28 10:01:33 +00:00
|
|
|
* @return string[]
|
2012-10-11 22:37:59 +00:00
|
|
|
*/
|
|
|
|
|
public function getTargets() {
|
|
|
|
|
return $this->targets;
|
|
|
|
|
}
|
|
|
|
|
|
2016-05-10 19:00:44 +00:00
|
|
|
/**
|
|
|
|
|
* Get the module's load type.
|
|
|
|
|
*
|
|
|
|
|
* @since 1.28
|
|
|
|
|
* @return string
|
|
|
|
|
*/
|
|
|
|
|
public function getType() {
|
|
|
|
|
$canBeStylesOnly = !(
|
|
|
|
|
// All options except 'styles', 'skinStyles' and 'debugRaw'
|
|
|
|
|
$this->scripts
|
|
|
|
|
|| $this->debugScripts
|
|
|
|
|
|| $this->templates
|
|
|
|
|
|| $this->languageScripts
|
|
|
|
|
|| $this->skinScripts
|
|
|
|
|
|| $this->dependencies
|
|
|
|
|
|| $this->messages
|
|
|
|
|
|| $this->skipFunction
|
2019-08-07 10:04:24 +00:00
|
|
|
|| $this->packageFiles
|
2016-05-10 19:00:44 +00:00
|
|
|
);
|
|
|
|
|
return $canBeStylesOnly ? self::LOAD_STYLES : self::LOAD_GENERAL;
|
|
|
|
|
}
|
|
|
|
|
|
Support LESS stylesheets in ResourceLoader
This patch adds support for the LESS stylesheet language to ResourceLoader.
LESS is a stylesheet language that compiles into CSS. The patch includes
lessphp, a LESS compiler implemented in PHP. The rationale for choosing LESS is
explained in a MediaWiki RFC which accompanies this patch, available at
<https://www.mediawiki.org/wiki/Requests_for_comment/LESS>.
LESS support is provided for ResourceLoader file modules. It is triggered by
the presence of the '.less' extension in stylesheet filenames. LESS files are
compiled by lessc, and the resultant CSS is subjected to the standard set of
transformations (CSSJanus & CSSMin). The immediate result of LESS compilation
is encoded as an array, which includes the list of LESS files that were
compiled and their mtimes. This array is cached. Cache invalidation is
performed by comparing the cached mtimes with the mtimes of the files on disk.
If the compiler itself throws an exception, ResourceLoader constructs a
compilation result which consists of the error message encoded as a CSS
comment. Failed compilation results are cached too, but with an expiration time
of five minutes. The expiration time is required because the full list of
referenced files is not known.
Three configuration variables configure the global environment for LESS
modules: $wgResourceLoaderLESSVars, $wgResourceLoaderLESSFunctions, and
$wgResourceLoaderLESSImportPaths. $wgResourceLoaderLESSVars maps variable names
to CSS values, specified as strings. Variables declared in this array are
available in all LESS files. $wgResourceLoaderLESSFunctions is similar, except
it maps custom function names to PHP callables. These functions can be called
from within LESS to transform values. Read more about custom functions at
<http://leafo.net/lessphp/docs/#custom_functions>. Finally,
$wgResourceLoaderLESSImportPaths specifies file system paths in addition to the
current module's path where the LESS compiler should look up files referenced
in @import statements.
The issue of handling of /* @embed */ and /* @noflip */ annotations is left
unresolved. Earlier versions of this patch included an @embed analog
implemented as a LESS custom function, but there was enough ambiguity about
whether the strategy it took was optimal to merit discussing it in a separate,
follow-up patch.
Bug: 40964
Change-Id: Id052a04dd2f76a1f4aef39fbd454bd67f5fd282f
2013-08-11 16:40:20 +00:00
|
|
|
/**
|
2020-02-04 22:44:14 +00:00
|
|
|
* @deprecated since 1.35 Use compileLessString() instead
|
|
|
|
|
* @param string $fileName
|
|
|
|
|
* @param ResourceLoaderContext $context
|
|
|
|
|
* @return string
|
|
|
|
|
* @codeCoverageIgnore
|
|
|
|
|
*/
|
|
|
|
|
protected function compileLessFile( $fileName, ResourceLoaderContext $context ) {
|
|
|
|
|
wfDeprecated( __METHOD__, '1.35' );
|
2020-03-11 19:52:52 +00:00
|
|
|
|
|
|
|
|
$style = $this->getFileContents( $fileName, 'LESS' );
|
2020-02-04 22:44:14 +00:00
|
|
|
return $this->compileLessString( $style, $fileName, $context );
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Compile a LESS string into CSS.
|
Support LESS stylesheets in ResourceLoader
This patch adds support for the LESS stylesheet language to ResourceLoader.
LESS is a stylesheet language that compiles into CSS. The patch includes
lessphp, a LESS compiler implemented in PHP. The rationale for choosing LESS is
explained in a MediaWiki RFC which accompanies this patch, available at
<https://www.mediawiki.org/wiki/Requests_for_comment/LESS>.
LESS support is provided for ResourceLoader file modules. It is triggered by
the presence of the '.less' extension in stylesheet filenames. LESS files are
compiled by lessc, and the resultant CSS is subjected to the standard set of
transformations (CSSJanus & CSSMin). The immediate result of LESS compilation
is encoded as an array, which includes the list of LESS files that were
compiled and their mtimes. This array is cached. Cache invalidation is
performed by comparing the cached mtimes with the mtimes of the files on disk.
If the compiler itself throws an exception, ResourceLoader constructs a
compilation result which consists of the error message encoded as a CSS
comment. Failed compilation results are cached too, but with an expiration time
of five minutes. The expiration time is required because the full list of
referenced files is not known.
Three configuration variables configure the global environment for LESS
modules: $wgResourceLoaderLESSVars, $wgResourceLoaderLESSFunctions, and
$wgResourceLoaderLESSImportPaths. $wgResourceLoaderLESSVars maps variable names
to CSS values, specified as strings. Variables declared in this array are
available in all LESS files. $wgResourceLoaderLESSFunctions is similar, except
it maps custom function names to PHP callables. These functions can be called
from within LESS to transform values. Read more about custom functions at
<http://leafo.net/lessphp/docs/#custom_functions>. Finally,
$wgResourceLoaderLESSImportPaths specifies file system paths in addition to the
current module's path where the LESS compiler should look up files referenced
in @import statements.
The issue of handling of /* @embed */ and /* @noflip */ annotations is left
unresolved. Earlier versions of this patch included an @embed analog
implemented as a LESS custom function, but there was enough ambiguity about
whether the strategy it took was optimal to merit discussing it in a separate,
follow-up patch.
Bug: 40964
Change-Id: Id052a04dd2f76a1f4aef39fbd454bd67f5fd282f
2013-08-11 16:40:20 +00:00
|
|
|
*
|
2014-08-20 18:26:46 +00:00
|
|
|
* Keeps track of all used files and adds them to localFileRefs.
|
Support LESS stylesheets in ResourceLoader
This patch adds support for the LESS stylesheet language to ResourceLoader.
LESS is a stylesheet language that compiles into CSS. The patch includes
lessphp, a LESS compiler implemented in PHP. The rationale for choosing LESS is
explained in a MediaWiki RFC which accompanies this patch, available at
<https://www.mediawiki.org/wiki/Requests_for_comment/LESS>.
LESS support is provided for ResourceLoader file modules. It is triggered by
the presence of the '.less' extension in stylesheet filenames. LESS files are
compiled by lessc, and the resultant CSS is subjected to the standard set of
transformations (CSSJanus & CSSMin). The immediate result of LESS compilation
is encoded as an array, which includes the list of LESS files that were
compiled and their mtimes. This array is cached. Cache invalidation is
performed by comparing the cached mtimes with the mtimes of the files on disk.
If the compiler itself throws an exception, ResourceLoader constructs a
compilation result which consists of the error message encoded as a CSS
comment. Failed compilation results are cached too, but with an expiration time
of five minutes. The expiration time is required because the full list of
referenced files is not known.
Three configuration variables configure the global environment for LESS
modules: $wgResourceLoaderLESSVars, $wgResourceLoaderLESSFunctions, and
$wgResourceLoaderLESSImportPaths. $wgResourceLoaderLESSVars maps variable names
to CSS values, specified as strings. Variables declared in this array are
available in all LESS files. $wgResourceLoaderLESSFunctions is similar, except
it maps custom function names to PHP callables. These functions can be called
from within LESS to transform values. Read more about custom functions at
<http://leafo.net/lessphp/docs/#custom_functions>. Finally,
$wgResourceLoaderLESSImportPaths specifies file system paths in addition to the
current module's path where the LESS compiler should look up files referenced
in @import statements.
The issue of handling of /* @embed */ and /* @noflip */ annotations is left
unresolved. Earlier versions of this patch included an @embed analog
implemented as a LESS custom function, but there was enough ambiguity about
whether the strategy it took was optimal to merit discussing it in a separate,
follow-up patch.
Bug: 40964
Change-Id: Id052a04dd2f76a1f4aef39fbd454bd67f5fd282f
2013-08-11 16:40:20 +00:00
|
|
|
*
|
2020-02-04 22:44:14 +00:00
|
|
|
* @since 1.35
|
2015-09-10 22:22:13 +00:00
|
|
|
* @throws Exception If less.php encounters a parse error
|
2020-02-04 22:44:14 +00:00
|
|
|
* @param string $style LESS source to compile
|
2020-07-14 22:37:26 +00:00
|
|
|
* @param string $stylePath File path of LESS source, used for resolving relative file paths
|
2015-09-25 17:57:35 +00:00
|
|
|
* @param ResourceLoaderContext $context Context in which to generate script
|
2014-04-20 21:33:05 +00:00
|
|
|
* @return string CSS source
|
Support LESS stylesheets in ResourceLoader
This patch adds support for the LESS stylesheet language to ResourceLoader.
LESS is a stylesheet language that compiles into CSS. The patch includes
lessphp, a LESS compiler implemented in PHP. The rationale for choosing LESS is
explained in a MediaWiki RFC which accompanies this patch, available at
<https://www.mediawiki.org/wiki/Requests_for_comment/LESS>.
LESS support is provided for ResourceLoader file modules. It is triggered by
the presence of the '.less' extension in stylesheet filenames. LESS files are
compiled by lessc, and the resultant CSS is subjected to the standard set of
transformations (CSSJanus & CSSMin). The immediate result of LESS compilation
is encoded as an array, which includes the list of LESS files that were
compiled and their mtimes. This array is cached. Cache invalidation is
performed by comparing the cached mtimes with the mtimes of the files on disk.
If the compiler itself throws an exception, ResourceLoader constructs a
compilation result which consists of the error message encoded as a CSS
comment. Failed compilation results are cached too, but with an expiration time
of five minutes. The expiration time is required because the full list of
referenced files is not known.
Three configuration variables configure the global environment for LESS
modules: $wgResourceLoaderLESSVars, $wgResourceLoaderLESSFunctions, and
$wgResourceLoaderLESSImportPaths. $wgResourceLoaderLESSVars maps variable names
to CSS values, specified as strings. Variables declared in this array are
available in all LESS files. $wgResourceLoaderLESSFunctions is similar, except
it maps custom function names to PHP callables. These functions can be called
from within LESS to transform values. Read more about custom functions at
<http://leafo.net/lessphp/docs/#custom_functions>. Finally,
$wgResourceLoaderLESSImportPaths specifies file system paths in addition to the
current module's path where the LESS compiler should look up files referenced
in @import statements.
The issue of handling of /* @embed */ and /* @noflip */ annotations is left
unresolved. Earlier versions of this patch included an @embed analog
implemented as a LESS custom function, but there was enough ambiguity about
whether the strategy it took was optimal to merit discussing it in a separate,
follow-up patch.
Bug: 40964
Change-Id: Id052a04dd2f76a1f4aef39fbd454bd67f5fd282f
2013-08-11 16:40:20 +00:00
|
|
|
*/
|
2020-07-14 22:37:26 +00:00
|
|
|
protected function compileLessString( $style, $stylePath, ResourceLoaderContext $context ) {
|
2015-09-23 07:47:40 +00:00
|
|
|
static $cache;
|
2020-07-14 22:37:26 +00:00
|
|
|
// @TODO: dependency injection
|
2015-09-23 07:47:40 +00:00
|
|
|
if ( !$cache ) {
|
2015-10-31 18:42:48 +00:00
|
|
|
$cache = ObjectCache::getLocalServerInstance( CACHE_ANYTHING );
|
2015-09-23 07:47:40 +00:00
|
|
|
}
|
|
|
|
|
|
2018-05-20 18:32:57 +00:00
|
|
|
$skinName = $context->getSkin();
|
|
|
|
|
$skinImportPaths = ExtensionRegistry::getInstance()->getAttribute( 'SkinLessImportPaths' );
|
|
|
|
|
$importDirs = [];
|
|
|
|
|
if ( isset( $skinImportPaths[ $skinName ] ) ) {
|
|
|
|
|
$importDirs[] = $skinImportPaths[ $skinName ];
|
|
|
|
|
}
|
|
|
|
|
|
2018-08-09 15:09:56 +00:00
|
|
|
$vars = $this->getLessVars( $context );
|
2020-02-04 22:44:14 +00:00
|
|
|
// Construct a cache key from a hash of the LESS source, and a hash digest
|
2015-09-23 07:47:40 +00:00
|
|
|
// of the LESS variables used for compilation.
|
2015-09-25 17:57:35 +00:00
|
|
|
ksort( $vars );
|
2018-05-20 18:32:57 +00:00
|
|
|
$compilerParams = [
|
|
|
|
|
'vars' => $vars,
|
|
|
|
|
'importDirs' => $importDirs,
|
|
|
|
|
];
|
2020-07-14 22:37:26 +00:00
|
|
|
$key = $cache->makeGlobalKey(
|
|
|
|
|
'resourceloader-less',
|
|
|
|
|
'v1',
|
|
|
|
|
hash( 'md4', $style ),
|
2018-05-20 18:32:57 +00:00
|
|
|
hash( 'md4', serialize( $compilerParams ) )
|
2020-07-14 22:37:26 +00:00
|
|
|
);
|
2015-09-23 07:47:40 +00:00
|
|
|
|
2020-07-14 22:37:26 +00:00
|
|
|
// If we got a cached value, we have to validate it by getting a checksum of all the
|
|
|
|
|
// files that were loaded by the parser and ensuring it matches the cached entry's.
|
|
|
|
|
$data = $cache->get( $key );
|
|
|
|
|
if (
|
|
|
|
|
!$data ||
|
|
|
|
|
$data['hash'] !== FileContentsHasher::getFileContentsHash( $data['files'] )
|
|
|
|
|
) {
|
2018-05-20 18:32:57 +00:00
|
|
|
$compiler = $context->getResourceLoader()->getLessCompiler( $vars, $importDirs );
|
|
|
|
|
|
2020-07-14 22:37:26 +00:00
|
|
|
$css = $compiler->parse( $style, $stylePath )->getCss();
|
|
|
|
|
// T253055: store the implicit dependency paths in a form relative to any install
|
|
|
|
|
// path so that multiple version of the application can share the cache for identical
|
|
|
|
|
// less stylesheets. This also avoids churn during application updates.
|
|
|
|
|
$files = $compiler->AllParsedFiles();
|
|
|
|
|
$data = [
|
|
|
|
|
'css' => $css,
|
|
|
|
|
'files' => ResourceLoaderModule::getRelativePaths( $files ),
|
|
|
|
|
'hash' => FileContentsHasher::getFileContentsHash( $files )
|
|
|
|
|
];
|
|
|
|
|
$cache->set( $key, $data, $cache::TTL_DAY );
|
|
|
|
|
}
|
2015-09-23 07:47:40 +00:00
|
|
|
|
2020-07-14 22:37:26 +00:00
|
|
|
foreach ( ResourceLoaderModule::expandRelativePaths( $data['files'] ) as $path ) {
|
|
|
|
|
$this->localFileRefs[] = $path;
|
|
|
|
|
}
|
2015-09-23 07:47:40 +00:00
|
|
|
|
2020-07-14 22:37:26 +00:00
|
|
|
return $data['css'];
|
Support LESS stylesheets in ResourceLoader
This patch adds support for the LESS stylesheet language to ResourceLoader.
LESS is a stylesheet language that compiles into CSS. The patch includes
lessphp, a LESS compiler implemented in PHP. The rationale for choosing LESS is
explained in a MediaWiki RFC which accompanies this patch, available at
<https://www.mediawiki.org/wiki/Requests_for_comment/LESS>.
LESS support is provided for ResourceLoader file modules. It is triggered by
the presence of the '.less' extension in stylesheet filenames. LESS files are
compiled by lessc, and the resultant CSS is subjected to the standard set of
transformations (CSSJanus & CSSMin). The immediate result of LESS compilation
is encoded as an array, which includes the list of LESS files that were
compiled and their mtimes. This array is cached. Cache invalidation is
performed by comparing the cached mtimes with the mtimes of the files on disk.
If the compiler itself throws an exception, ResourceLoader constructs a
compilation result which consists of the error message encoded as a CSS
comment. Failed compilation results are cached too, but with an expiration time
of five minutes. The expiration time is required because the full list of
referenced files is not known.
Three configuration variables configure the global environment for LESS
modules: $wgResourceLoaderLESSVars, $wgResourceLoaderLESSFunctions, and
$wgResourceLoaderLESSImportPaths. $wgResourceLoaderLESSVars maps variable names
to CSS values, specified as strings. Variables declared in this array are
available in all LESS files. $wgResourceLoaderLESSFunctions is similar, except
it maps custom function names to PHP callables. These functions can be called
from within LESS to transform values. Read more about custom functions at
<http://leafo.net/lessphp/docs/#custom_functions>. Finally,
$wgResourceLoaderLESSImportPaths specifies file system paths in addition to the
current module's path where the LESS compiler should look up files referenced
in @import statements.
The issue of handling of /* @embed */ and /* @noflip */ annotations is left
unresolved. Earlier versions of this patch included an @embed analog
implemented as a LESS custom function, but there was enough ambiguity about
whether the strategy it took was optimal to merit discussing it in a separate,
follow-up patch.
Bug: 40964
Change-Id: Id052a04dd2f76a1f4aef39fbd454bd67f5fd282f
2013-08-11 16:40:20 +00:00
|
|
|
}
|
2014-08-20 13:13:43 +00:00
|
|
|
|
2014-10-10 00:07:14 +00:00
|
|
|
/**
|
|
|
|
|
* Takes named templates by the module and returns an array mapping.
|
2017-07-01 00:31:56 +00:00
|
|
|
* @return array Templates mapping template alias to content
|
2019-12-01 01:58:30 +00:00
|
|
|
* @throws RuntimeException If a file doesn't exist
|
2014-10-10 00:07:14 +00:00
|
|
|
*/
|
|
|
|
|
public function getTemplates() {
|
2016-02-17 09:09:32 +00:00
|
|
|
$templates = [];
|
2014-10-10 00:07:14 +00:00
|
|
|
|
|
|
|
|
foreach ( $this->templates as $alias => $templatePath ) {
|
|
|
|
|
// Alias is optional
|
|
|
|
|
if ( is_int( $alias ) ) {
|
2017-03-17 02:14:05 +00:00
|
|
|
$alias = $this->getPath( $templatePath );
|
2014-10-10 00:07:14 +00:00
|
|
|
}
|
|
|
|
|
$localPath = $this->getLocalPath( $templatePath );
|
2020-03-11 19:52:52 +00:00
|
|
|
$content = $this->getFileContents( $localPath, 'template' );
|
|
|
|
|
|
2019-12-01 01:58:30 +00:00
|
|
|
$templates[$alias] = $this->stripBom( $content );
|
2014-10-10 00:07:14 +00:00
|
|
|
}
|
|
|
|
|
return $templates;
|
|
|
|
|
}
|
2016-05-11 11:53:59 +00:00
|
|
|
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
/**
|
2019-06-12 00:57:17 +00:00
|
|
|
* Internal helper for use by getPackageFiles(), getFileHashes() and getDefinitionSummary().
|
|
|
|
|
*
|
|
|
|
|
* This expands the 'packageFiles' definition into something that's (almost) the right format
|
|
|
|
|
* for getPackageFiles() to return. It expands shorthands, resolves config vars, and handles
|
|
|
|
|
* summarising any non-file data for getVersionHash(). For file-based data, getFileHashes()
|
|
|
|
|
* handles it instead, which also ends up in getDefinitionSummary().
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
*
|
2019-06-12 00:57:17 +00:00
|
|
|
* What it does not do is reading the actual contents of any specified files, nor invoking
|
|
|
|
|
* the computation callbacks. Those things are done by getPackageFiles() instead to improve
|
|
|
|
|
* backend performance by only doing this work when the module response is needed, and not
|
|
|
|
|
* when merely computing the version hash for StartupModule, or when checking
|
|
|
|
|
* If-None-Match headers for a HTTP 304 response.
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
*
|
|
|
|
|
* @param ResourceLoaderContext $context
|
|
|
|
|
* @return array|null
|
2019-10-12 14:13:38 +00:00
|
|
|
* @phan-return array{main:string,files:string[][]}|null
|
2019-12-01 01:58:30 +00:00
|
|
|
* @throws LogicException If the 'packageFiles' definition is invalid.
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
*/
|
|
|
|
|
private function expandPackageFiles( ResourceLoaderContext $context ) {
|
|
|
|
|
$hash = $context->getHash();
|
|
|
|
|
if ( isset( $this->expandedPackageFiles[$hash] ) ) {
|
|
|
|
|
return $this->expandedPackageFiles[$hash];
|
|
|
|
|
}
|
|
|
|
|
if ( $this->packageFiles === null ) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
$expandedFiles = [];
|
|
|
|
|
$mainFile = null;
|
|
|
|
|
|
2019-12-01 01:58:30 +00:00
|
|
|
foreach ( $this->packageFiles as $key => $fileInfo ) {
|
resourceloader: Change 'packageFiles' format to be JSON-compatible
The module definition format for 'packageFiles', as initially designed,
mixes sequential and associative arrays. This works in PHP, but not in
JSON. To make the format JSON compatible, use a 'name' key instead of
using the key in the main array.
Leave backwards compatibility in place so that extensions using the old
format can be migrated. This will be removed in the next commit.
Before:
'packageFiles' => [
'script.js',
'script2.js',
'config.json' => [ 'config' => [ 'Foo', 'Bar' ] ],
'data.json' => [ 'callback' => function () { ... } ],
],
After:
'packageFiles' => [
'script.js',
'script2.js',
[ 'name' => 'config.json', 'config' => [ 'Foo', 'Bar' ] ],
[ 'name' => 'data.json', 'callback' => function () { ... } ],
],
This can then be written in extension.json as:
"packageFiles": [
"script.js",
"script2.js",
[ "name": "config.json", "config": [ "Foo", "Bar" ] ],
[ "name": "data.json", "callback: [ "MyExtHooks", "getData" ] ]
]
Change-Id: Ic566a1cd7efd075c380bc50ba0cc2c329a2041d7
2019-02-22 01:26:23 +00:00
|
|
|
if ( is_string( $fileInfo ) ) {
|
|
|
|
|
$fileInfo = [ 'name' => $fileInfo, 'file' => $fileInfo ];
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
}
|
2019-12-01 01:58:30 +00:00
|
|
|
if ( !isset( $fileInfo['name'] ) ) {
|
|
|
|
|
$msg = "Missing 'name' key in package file info for module '{$this->getName()}'," .
|
|
|
|
|
" offset '{$key}'.";
|
|
|
|
|
$this->getLogger()->error( $msg );
|
|
|
|
|
throw new LogicException( $msg );
|
|
|
|
|
}
|
|
|
|
|
$fileName = $fileInfo['name'];
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
|
|
|
|
|
// Infer type from alias if needed
|
2019-12-01 01:58:30 +00:00
|
|
|
$type = $fileInfo['type'] ?? self::getPackageFileType( $fileName );
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
$expanded = [ 'type' => $type ];
|
|
|
|
|
if ( !empty( $fileInfo['main'] ) ) {
|
2019-12-01 01:58:30 +00:00
|
|
|
$mainFile = $fileName;
|
2020-02-04 01:42:03 +00:00
|
|
|
if ( $type !== 'script' && $type !== 'script-vue' ) {
|
2019-12-01 01:58:30 +00:00
|
|
|
$msg = "Main file in package must be of type 'script', module " .
|
|
|
|
|
"'{$this->getName()}', main file '{$mainFile}' is '{$type}'.";
|
|
|
|
|
$this->getLogger()->error( $msg );
|
|
|
|
|
throw new LogicException( $msg );
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-06-12 00:57:17 +00:00
|
|
|
// Perform expansions (except 'file' and 'callback'), creating one of these keys:
|
|
|
|
|
// - 'content': literal value.
|
|
|
|
|
// - 'filePath': content to be read from a file.
|
|
|
|
|
// - 'callback': content computed by a callable.
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
if ( isset( $fileInfo['content'] ) ) {
|
|
|
|
|
$expanded['content'] = $fileInfo['content'];
|
|
|
|
|
} elseif ( isset( $fileInfo['file'] ) ) {
|
|
|
|
|
$expanded['filePath'] = $fileInfo['file'];
|
|
|
|
|
} elseif ( isset( $fileInfo['callback'] ) ) {
|
2019-10-18 18:27:30 +00:00
|
|
|
// If no extra parameter for the callback is given, use null.
|
|
|
|
|
$expanded['callbackParam'] = $fileInfo['callbackParam'] ?? null;
|
|
|
|
|
|
2019-06-12 00:57:17 +00:00
|
|
|
if ( !is_callable( $fileInfo['callback'] ) ) {
|
2019-12-01 01:58:30 +00:00
|
|
|
$msg = "Invalid 'callback' for module '{$this->getName()}', file '{$fileName}'.";
|
|
|
|
|
$this->getLogger()->error( $msg );
|
|
|
|
|
throw new LogicException( $msg );
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
}
|
2019-06-12 00:57:17 +00:00
|
|
|
if ( isset( $fileInfo['versionCallback'] ) ) {
|
|
|
|
|
if ( !is_callable( $fileInfo['versionCallback'] ) ) {
|
2019-12-01 01:58:30 +00:00
|
|
|
throw new LogicException( "Invalid 'versionCallback' for "
|
|
|
|
|
. "module '{$this->getName()}', file '{$fileName}'."
|
|
|
|
|
);
|
2019-06-12 00:57:17 +00:00
|
|
|
}
|
2019-10-18 18:27:30 +00:00
|
|
|
|
|
|
|
|
// Execute the versionCallback with the same arguments that
|
|
|
|
|
// would be given to the callback
|
2020-02-23 22:39:52 +00:00
|
|
|
$callbackResult = ( $fileInfo['versionCallback'] )(
|
2019-10-18 18:27:30 +00:00
|
|
|
$context,
|
|
|
|
|
$this->getConfig(),
|
|
|
|
|
$expanded['callbackParam']
|
|
|
|
|
);
|
2020-02-23 22:39:52 +00:00
|
|
|
if ( $callbackResult instanceof ResourceLoaderFilePath ) {
|
|
|
|
|
$expanded['filePath'] = $callbackResult->getPath();
|
|
|
|
|
} else {
|
|
|
|
|
$expanded['definitionSummary'] = $callbackResult;
|
|
|
|
|
}
|
2019-06-12 00:57:17 +00:00
|
|
|
// Don't invoke 'callback' here as it may be expensive (T223260).
|
|
|
|
|
$expanded['callback'] = $fileInfo['callback'];
|
|
|
|
|
} else {
|
2019-10-18 18:27:30 +00:00
|
|
|
// Else go ahead invoke callback with its arguments.
|
2019-12-11 22:08:31 +00:00
|
|
|
$callbackResult = ( $fileInfo['callback'] )(
|
2019-10-18 18:27:30 +00:00
|
|
|
$context,
|
|
|
|
|
$this->getConfig(),
|
|
|
|
|
$expanded['callbackParam']
|
|
|
|
|
);
|
2019-12-11 22:08:31 +00:00
|
|
|
if ( $callbackResult instanceof ResourceLoaderFilePath ) {
|
|
|
|
|
$expanded['filePath'] = $callbackResult->getPath();
|
|
|
|
|
} else {
|
|
|
|
|
$expanded['content'] = $callbackResult;
|
|
|
|
|
}
|
2019-06-12 00:57:17 +00:00
|
|
|
}
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
} elseif ( isset( $fileInfo['config'] ) ) {
|
|
|
|
|
if ( $type !== 'data' ) {
|
2019-12-01 01:58:30 +00:00
|
|
|
$msg = "Key 'config' only valid for data files. "
|
|
|
|
|
. " Module '{$this->getName()}', file '{$fileName}' is '{$type}'.";
|
|
|
|
|
$this->getLogger()->error( $msg );
|
|
|
|
|
throw new LogicException( $msg );
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
}
|
|
|
|
|
$expandedConfig = [];
|
2021-09-03 22:28:20 +00:00
|
|
|
foreach ( $fileInfo['config'] as $configKey => $var ) {
|
|
|
|
|
$expandedConfig[ is_numeric( $configKey ) ? $var : $configKey ] = $this->getConfig()->get( $var );
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
}
|
|
|
|
|
$expanded['content'] = $expandedConfig;
|
|
|
|
|
} elseif ( !empty( $fileInfo['main'] ) ) {
|
resourceloader: Change 'packageFiles' format to be JSON-compatible
The module definition format for 'packageFiles', as initially designed,
mixes sequential and associative arrays. This works in PHP, but not in
JSON. To make the format JSON compatible, use a 'name' key instead of
using the key in the main array.
Leave backwards compatibility in place so that extensions using the old
format can be migrated. This will be removed in the next commit.
Before:
'packageFiles' => [
'script.js',
'script2.js',
'config.json' => [ 'config' => [ 'Foo', 'Bar' ] ],
'data.json' => [ 'callback' => function () { ... } ],
],
After:
'packageFiles' => [
'script.js',
'script2.js',
[ 'name' => 'config.json', 'config' => [ 'Foo', 'Bar' ] ],
[ 'name' => 'data.json', 'callback' => function () { ... } ],
],
This can then be written in extension.json as:
"packageFiles": [
"script.js",
"script2.js",
[ "name": "config.json", "config": [ "Foo", "Bar" ] ],
[ "name": "data.json", "callback: [ "MyExtHooks", "getData" ] ]
]
Change-Id: Ic566a1cd7efd075c380bc50ba0cc2c329a2041d7
2019-02-22 01:26:23 +00:00
|
|
|
// [ 'name' => 'foo.js', 'main' => true ] is shorthand
|
2019-12-01 01:58:30 +00:00
|
|
|
$expanded['filePath'] = $fileName;
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
} else {
|
2019-12-01 01:58:30 +00:00
|
|
|
$msg = "Incomplete definition for module '{$this->getName()}', file '{$fileName}'. "
|
|
|
|
|
. "One of 'file', 'content', 'callback', or 'config' must be set.";
|
|
|
|
|
$this->getLogger()->error( $msg );
|
|
|
|
|
throw new LogicException( $msg );
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
}
|
|
|
|
|
|
2019-12-01 01:58:30 +00:00
|
|
|
$expandedFiles[$fileName] = $expanded;
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if ( $expandedFiles && $mainFile === null ) {
|
|
|
|
|
// The first package file that is a script is the main file
|
2019-12-01 01:58:30 +00:00
|
|
|
foreach ( $expandedFiles as $path => $file ) {
|
2020-02-04 01:42:03 +00:00
|
|
|
if ( $file['type'] === 'script' || $file['type'] === 'script-vue' ) {
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
$mainFile = $path;
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$result = [
|
|
|
|
|
'main' => $mainFile,
|
|
|
|
|
'files' => $expandedFiles
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
$this->expandedPackageFiles[$hash] = $result;
|
|
|
|
|
return $result;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
2021-04-10 08:52:52 +00:00
|
|
|
* Resolves the package files definition and generates the content of each package file.
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
* @param ResourceLoaderContext $context
|
|
|
|
|
* @return array Package files data structure, see ResourceLoaderModule::getScript()
|
2020-02-04 01:42:03 +00:00
|
|
|
* @throws RuntimeException If a file doesn't exist, or parsing a .vue file fails
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
*/
|
|
|
|
|
public function getPackageFiles( ResourceLoaderContext $context ) {
|
|
|
|
|
if ( $this->packageFiles === null ) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
2020-02-04 01:42:03 +00:00
|
|
|
$hash = $context->getHash();
|
|
|
|
|
if ( isset( $this->fullyExpandedPackageFiles[ $hash ] ) ) {
|
|
|
|
|
return $this->fullyExpandedPackageFiles[ $hash ];
|
|
|
|
|
}
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
$expandedPackageFiles = $this->expandPackageFiles( $context );
|
|
|
|
|
|
|
|
|
|
// Expand file contents
|
2020-02-04 01:42:03 +00:00
|
|
|
foreach ( $expandedPackageFiles['files'] as $fileName => &$fileInfo ) {
|
2019-06-12 00:57:17 +00:00
|
|
|
// Turn any 'filePath' or 'callback' key into actual 'content',
|
2019-12-11 22:08:31 +00:00
|
|
|
// and remove the key after that. The callback could return a
|
|
|
|
|
// ResourceLoaderFilePath object; if that happens, fall through
|
|
|
|
|
// to the 'filePath' handling.
|
|
|
|
|
if ( isset( $fileInfo['callback'] ) ) {
|
|
|
|
|
$callbackResult = ( $fileInfo['callback'] )(
|
|
|
|
|
$context,
|
|
|
|
|
$this->getConfig(),
|
|
|
|
|
$fileInfo['callbackParam']
|
|
|
|
|
);
|
|
|
|
|
if ( $callbackResult instanceof ResourceLoaderFilePath ) {
|
|
|
|
|
// Fall through to the filePath handling code below
|
|
|
|
|
$fileInfo['filePath'] = $callbackResult->getPath();
|
|
|
|
|
} else {
|
|
|
|
|
$fileInfo['content'] = $callbackResult;
|
|
|
|
|
}
|
|
|
|
|
unset( $fileInfo['callback'] );
|
|
|
|
|
}
|
2020-02-23 22:39:52 +00:00
|
|
|
// Only interpret 'filePath' if 'content' hasn't been set already.
|
|
|
|
|
// This can happen if 'versionCallback' provided 'filePath',
|
|
|
|
|
// while 'callback' provides 'content'. In that case both are set
|
|
|
|
|
// at this point. The 'filePath' from 'versionCallback' in that case is
|
|
|
|
|
// only to inform getDefinitionSummary().
|
|
|
|
|
if ( !isset( $fileInfo['content'] ) && isset( $fileInfo['filePath'] ) ) {
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
$localPath = $this->getLocalPath( $fileInfo['filePath'] );
|
2020-03-11 19:52:52 +00:00
|
|
|
$content = $this->getFileContents( $localPath, 'package' );
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
if ( $fileInfo['type'] === 'data' ) {
|
|
|
|
|
$content = json_decode( $content );
|
|
|
|
|
}
|
|
|
|
|
$fileInfo['content'] = $content;
|
|
|
|
|
unset( $fileInfo['filePath'] );
|
|
|
|
|
}
|
2020-02-04 01:42:03 +00:00
|
|
|
if ( $fileInfo['type'] === 'script-vue' ) {
|
|
|
|
|
try {
|
2020-05-22 23:10:50 +00:00
|
|
|
$parsedComponent = $this->getVueComponentParser()->parse(
|
|
|
|
|
$fileInfo['content'],
|
|
|
|
|
[ 'minifyTemplate' => !$context->getDebug() ]
|
|
|
|
|
);
|
2020-02-04 01:42:03 +00:00
|
|
|
} catch ( Exception $e ) {
|
|
|
|
|
$msg = "Error parsing file '$fileName' in module '{$this->getName()}': " .
|
|
|
|
|
$e->getMessage();
|
|
|
|
|
$this->getLogger()->error( $msg );
|
|
|
|
|
throw new RuntimeException( $msg );
|
|
|
|
|
}
|
2020-05-22 23:10:50 +00:00
|
|
|
$encodedTemplate = json_encode( $parsedComponent['template'] );
|
2020-02-04 01:42:03 +00:00
|
|
|
if ( $context->getDebug() ) {
|
|
|
|
|
// Replace \n (backslash-n) with space + backslash-newline in debug mode
|
|
|
|
|
// We only replace \n if not preceded by a backslash, to avoid breaking '\\n'
|
|
|
|
|
$encodedTemplate = preg_replace( '/(?<!\\\\)\\\\n/', " \\\n", $encodedTemplate );
|
|
|
|
|
// Expand \t to real tabs in debug mode
|
|
|
|
|
$encodedTemplate = strtr( $encodedTemplate, [ "\\t" => "\t" ] );
|
|
|
|
|
}
|
|
|
|
|
$fileInfo['content'] = [
|
|
|
|
|
'script' => $parsedComponent['script'] .
|
|
|
|
|
";\nmodule.exports.template = $encodedTemplate;",
|
|
|
|
|
'style' => $parsedComponent['style'] ?? '',
|
|
|
|
|
'styleLang' => $parsedComponent['styleLang'] ?? 'css'
|
|
|
|
|
];
|
|
|
|
|
$fileInfo['type'] = 'script+style';
|
|
|
|
|
}
|
2019-06-12 00:57:17 +00:00
|
|
|
|
2019-10-18 18:27:30 +00:00
|
|
|
// Not needed for client response, exists for use by getDefinitionSummary().
|
2019-06-12 00:57:17 +00:00
|
|
|
unset( $fileInfo['definitionSummary'] );
|
2019-10-18 18:27:30 +00:00
|
|
|
// Not needed for client response, used by callbacks only.
|
|
|
|
|
unset( $fileInfo['callbackParam'] );
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
}
|
|
|
|
|
|
2020-02-04 01:42:03 +00:00
|
|
|
$this->fullyExpandedPackageFiles[ $hash ] = $expandedPackageFiles;
|
ResourceLoader: Add support for packageFiles
Package files are files that are part of a module, but are not
immediately executed when the module executes. Instead, they are
lazy-excecuted when require() is called on them. Package files can be
scripts (JS) or data (JSON), and can be real files on the file system,
or virtual files generated by a callback.
Using virtual data files, server-side data and config variables can be
bundled with a module. Support for file-based require() allows us to
import npm modules into ResourceLoader more easily.
The require function passed to each script execution context, which was
previously a reference to the global mw.loader.require() function, is
changed to one that is scoped to the module and the file being executed.
This is needed to support relative paths: require( '../foo.js' ) can
mean a different file depending on the path of the calling file.
The results of require()ing each file (i.e. the value of module.exports
after executing it) are stored, and calling require() on the same file a
second time won't execute it again, but will return the stored value.
Miscellaneous changes:
- Add XmlJsCode::encodeObject(), which combines an associative array of
XmlJsCode objects into one larger XmlJsCode object. This is needed for
encoding the packageFiles parameter in mw.loader.implement() calls.
Bug: T133462
Change-Id: I78cc86e626de0720397718cd2bed8ed279579112
2018-11-03 00:53:17 +00:00
|
|
|
return $expandedPackageFiles;
|
|
|
|
|
}
|
|
|
|
|
|
2016-05-11 11:53:59 +00:00
|
|
|
/**
|
|
|
|
|
* Takes an input string and removes the UTF-8 BOM character if present
|
|
|
|
|
*
|
|
|
|
|
* We need to remove these after reading a file, because we concatenate our files and
|
|
|
|
|
* the BOM character is not valid in the middle of a string.
|
|
|
|
|
* We already assume UTF-8 everywhere, so this should be safe.
|
|
|
|
|
*
|
2017-07-01 00:31:56 +00:00
|
|
|
* @param string $input
|
2021-06-29 11:24:37 +00:00
|
|
|
* @return string Input minus the initial BOM char
|
2016-05-11 11:53:59 +00:00
|
|
|
*/
|
|
|
|
|
protected function stripBom( $input ) {
|
|
|
|
|
if ( substr_compare( "\xef\xbb\xbf", $input, 0, 3 ) === 0 ) {
|
|
|
|
|
return substr( $input, 3 );
|
|
|
|
|
}
|
|
|
|
|
return $input;
|
|
|
|
|
}
|
2010-10-19 18:25:42 +00:00
|
|
|
}
|