2 * Base library for MediaWiki.
4 * Exposed globally as `mw`, with `mediaWiki` as alias.
7 * @alternateClassName mediaWiki
10 /* global $VARS, $CODE */
15 var mw
, StringSet
, log
,
16 hasOwn
= Object
.prototype.hasOwnProperty
,
20 * FNV132 hash function
22 * This function implements the 32-bit version of FNV-1.
23 * It is equivalent to hash( 'fnv132', ... ) in PHP, except
24 * its output is base 36 rather than hex.
25 * See <https://en.wikipedia.org/wiki/FNV_hash_function>
28 * @param {string} str String to hash
29 * @return {string} hash as an seven-character base 36 string
31 function fnv132( str
) {
32 /* eslint-disable no-bitwise */
33 var hash
= 0x811C9DC5,
36 for ( i
= 0; i
< str
.length
; i
++ ) {
37 hash
+= ( hash
<< 1 ) + ( hash
<< 4 ) + ( hash
<< 7 ) + ( hash
<< 8 ) + ( hash
<< 24 );
38 hash
^= str
.charCodeAt( i
);
41 hash
= ( hash
>>> 0 ).toString( 36 );
42 while ( hash
.length
< 7 ) {
47 /* eslint-enable no-bitwise */
50 function defineFallbacks() {
51 // <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set>
56 StringSet
= window
.Set
|| function StringSet() {
57 var set = Object
.create( null );
58 this.add = function ( value
) {
61 this.has = function ( value
) {
68 * Alias property to the global object.
75 * @param {Mixed} value
77 function setGlobalMapValue( map
, key
, value
) {
78 map
.values
[ key
] = value
;
83 // Deprecation notice for mw.config globals (T58550, T72470)
84 map
=== mw
.config
&& 'Use mw.config instead.'
89 * Log a message to window.console, if possible.
91 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
92 * also in production mode). Gets console references in each invocation instead of caching the
93 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
96 * @param {string} topic Stream name passed by mw.track
97 * @param {Object} data Data passed by mw.track
98 * @param {Error} [data.exception]
99 * @param {string} data.source Error source
100 * @param {string} [data.module] Name of module which caused the error
102 function logError( topic
, data
) {
105 source
= data
.source
,
106 module
= data
.module
,
107 console
= window
.console
;
109 if ( console
&& console
.log
) {
110 msg
= ( e
? 'Exception' : 'Error' ) + ' in ' + source
;
112 msg
+= ' in module ' + module
;
114 msg
+= ( e
? ':' : '.' );
117 // If we have an exception object, log it to the warning channel to trigger
118 // proper stacktraces in browsers that support it.
119 if ( e
&& console
.warn
) {
126 * Create an object that can be read from or written to via methods that allow
127 * interaction both with single and multiple properties at once.
133 * @param {boolean} [global=false] Whether to synchronise =values to the global
134 * window object (for backwards-compatibility with mw.config; T72470). Values are
135 * copied in one direction only. Changes to globals do not reflect in the map.
137 function Map( global
) {
138 this.values
= Object
.create( null );
139 if ( global
=== true ) {
140 // Override #set to also set the global variable
141 this.set = function ( selection
, value
) {
143 if ( arguments
.length
> 1 ) {
144 if ( typeof selection
!== 'string' ) {
147 setGlobalMapValue( this, selection
, value
);
150 if ( typeof selection
=== 'object' ) {
151 for ( s
in selection
) {
152 setGlobalMapValue( this, s
, selection
[ s
] );
165 * Get the value of one or more keys.
167 * If called with no arguments, all values are returned.
169 * @param {string|Array} [selection] Key or array of keys to retrieve values for.
170 * @param {Mixed} [fallback=null] Value for keys that don't exist.
171 * @return {Mixed|Object|null} If selection was a string, returns the value,
172 * If selection was an array, returns an object of key/values.
173 * If no selection is passed, a new object with all key/values is returned.
175 get: function ( selection
, fallback
) {
177 fallback
= arguments
.length
> 1 ? fallback
: null;
179 if ( Array
.isArray( selection
) ) {
181 for ( i
= 0; i
< selection
.length
; i
++ ) {
182 if ( typeof selection
[ i
] === 'string' ) {
183 results
[ selection
[ i
] ] = selection
[ i
] in this.values
?
184 this.values
[ selection
[ i
] ] :
191 if ( typeof selection
=== 'string' ) {
192 return selection
in this.values
?
193 this.values
[ selection
] :
197 if ( selection
=== undefined ) {
199 for ( i
in this.values
) {
200 results
[ i
] = this.values
[ i
];
205 // Invalid selection key
210 * Set one or more key/value pairs.
212 * @param {string|Object} selection Key to set value for, or object mapping keys to values
213 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
214 * @return {boolean} True on success, false on failure
216 set: function ( selection
, value
) {
218 // Use `arguments.length` because `undefined` is also a valid value.
219 if ( arguments
.length
> 1 ) {
220 if ( typeof selection
!== 'string' ) {
223 this.values
[ selection
] = value
;
226 if ( typeof selection
=== 'object' ) {
227 for ( s
in selection
) {
228 this.values
[ s
] = selection
[ s
];
236 * Check if one or more keys exist.
238 * @param {Mixed} selection Key or array of keys to check
239 * @return {boolean} True if the key(s) exist
241 exists: function ( selection
) {
243 if ( Array
.isArray( selection
) ) {
244 for ( i
= 0; i
< selection
.length
; i
++ ) {
245 if ( typeof selection
[ i
] !== 'string' || !( selection
[ i
] in this.values
) ) {
251 return typeof selection
=== 'string' && selection
in this.values
;
257 log
= ( function () {
259 * Write a verbose message to the browser's console in debug mode.
261 * This method is mainly intended for verbose logging. It is a no-op in production mode.
262 * In ResourceLoader debug mode, it will use the browser's console if available, with
263 * fallback to creating a console interface in the DOM and logging messages there.
265 * See {@link mw.log} for other logging methods.
268 * @param {...string} msg Messages to output to console.
270 var log = function () {},
271 console
= window
.console
;
273 // Note: Keep list of methods in sync with restoration in mediawiki.log.js
274 // when adding or removing mw.log methods below!
277 * Collection of methods to help log messages to the console.
284 * Write a message to the browser console's warning channel.
286 * This method is a no-op in browsers that don't implement the Console API.
288 * @param {...string} msg Messages to output to console
290 log
.warn
= console
&& console
.warn
?
291 Function
.prototype.bind
.call( console
.warn
, console
) :
295 * Write a message to the browser console's error channel.
297 * Most browsers also print a stacktrace when calling this method if the
298 * argument is an Error object.
300 * This method is a no-op in browsers that don't implement the Console API.
303 * @param {...Mixed} msg Messages to output to console
305 log
.error
= console
&& console
.error
?
306 Function
.prototype.bind
.call( console
.error
, console
) :
310 * Create a property on a host object that, when accessed, will produce
311 * a deprecation warning in the console.
313 * @param {Object} obj Host object of deprecated property
314 * @param {string} key Name of property to create in `obj`
315 * @param {Mixed} val The value this property should return when accessed
316 * @param {string} [msg] Optional text to include in the deprecation message
317 * @param {string} [logName] Name for the feature for logging and tracking
318 * purposes. Except for properties of the window object, tracking is only
319 * enabled if logName is set.
321 log
.deprecate = function ( obj
, key
, val
, msg
, logName
) {
323 function maybeLog() {
324 var name
= logName
|| key
,
325 trace
= new Error().stack
;
327 stacks
= new StringSet();
329 if ( !stacks
.has( trace
) ) {
331 if ( logName
|| obj
=== window
) {
332 mw
.track( 'mw.deprecate', name
);
335 'Use of "' + name
+ '" is deprecated.' + ( msg
? ( ' ' + msg
) : '' )
339 // Support: Safari 5.0
340 // Throws "not supported on DOM Objects" for Node or Element objects (incl. document)
341 // Safari 4.0 doesn't have this method, and it was fixed in Safari 5.1.
343 Object
.defineProperty( obj
, key
, {
350 set: function ( newVal
) {
367 redefineFallbacksForTest: function () {
368 if ( !window
.QUnit
) {
369 throw new Error( 'Reset not allowed outside unit tests' );
375 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
377 * On browsers that implement the Navigation Timing API, this function will produce
378 * floating-point values with microsecond precision that are guaranteed to be monotonic.
379 * On all other browsers, it will fall back to using `Date`.
381 * @return {number} Current time
384 // Optimisation: Define the shortcut on first call, not at module definition.
385 var perf
= window
.performance
,
386 navStart
= perf
&& perf
.timing
&& perf
.timing
.navigationStart
;
388 // Define the relevant shortcut
389 mw
.now
= navStart
&& typeof perf
.now
=== 'function' ?
390 function () { return navStart
+ perf
.now(); } :
397 * List of all analytic events emitted so far.
402 trackQueue
: trackQueue
,
404 track: function ( topic
, data
) {
405 trackQueue
.push( { topic
: topic
, timeStamp
: mw
.now(), data
: data
} );
406 // The base module extends this method to fire events here
410 * Track an early error event via mw.track and send it to the window console.
413 * @param {string} topic Topic name
414 * @param {Object} data Data describing the event, encoded as an object; see mw#logError
416 trackError: function ( topic
, data
) {
417 mw
.track( topic
, data
);
418 logError( topic
, data
);
421 // Expose Map constructor
425 * Map of configuration values.
427 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
430 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
431 * global `window` object.
433 * @property {mw.Map} config
435 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
439 * Empty object for third-party libraries, for cases where you don't
440 * want to add a new global, or the global is bad and needs containment
448 * Access container for deprecated functionality that can be moved from
449 * from their legacy location and attached to this object (e.g. a global
450 * function that is deprecated and as stop-gap can be exposed through here).
452 * This was reserved for future use but never ended up being used.
454 * @deprecated since 1.22 Let deprecated identifiers keep their original name
455 * and use mw.log#deprecate to create an access container for tracking.
461 * Store for messages.
468 * Store for templates associated with a module.
472 templates
: new Map(),
478 * Client for ResourceLoader server end point.
480 * This client is in charge of maintaining the module registry and state
481 * machine, initiating network (batch) requests for loading modules, as
482 * well as dependency resolution and execution of source code.
484 * For more information, refer to
485 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
490 loader
: ( function () {
493 * Fired via mw.track on various resource loading errors.
495 * @event resourceloader_exception
496 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
497 * object, but in theory module code could manually throw something else, and that
498 * might also end up here.
499 * @param {string} [module] Name of the module which caused the error. Omitted if the
500 * error is not module-related or the module cannot be easily identified due to
502 * @param {string} source Source of the error. Possible values:
504 * - style: stylesheet error (only affects old IE where a special style loading method
506 * - load-callback: exception thrown by user callback
507 * - module-execute: exception thrown by module code
508 * - resolve: failed to sort dependencies for a module in mw.loader.load
509 * - store-eval: could not evaluate module code cached in localStorage
510 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
511 * - store-localstorage-json: JSON conversion error in mw.loader.store
512 * - store-localstorage-update: localStorage conversion error in mw.loader.store.
516 * Fired via mw.track on resource loading error conditions.
518 * @event resourceloader_assert
519 * @param {string} source Source of the error. Possible values:
521 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
522 * bug; see <https://phabricator.wikimedia.org/T59567> for details
526 * Mapping of registered modules.
528 * See #implement and #execute for exact details on support for script, style and messages.
534 * // From mw.loader.register()
535 * 'version': '########' (hash)
536 * 'dependencies': ['required.foo', 'bar.also', ...]
537 * 'group': 'somegroup', (or) null
538 * 'source': 'local', (or) 'anotherwiki'
539 * 'skip': 'return !!window.Example', (or) null
540 * 'module': export Object
542 * // Set from execute() or mw.loader.state()
543 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
545 * // Optionally added at run-time by mw.loader.implement()
547 * 'script': closure, array of urls, or string
548 * 'style': { ... } (see #execute)
549 * 'messages': { 'key': 'value', ... }
556 * The module is known to the system but not yet required.
557 * Meta data is registered via mw.loader#register. Calls to that method are
558 * generated server-side by the startup module.
560 * The module was required through mw.loader (either directly or as dependency of
561 * another module). The client will fetch module contents from the server.
562 * The contents are then stashed in the registry via mw.loader#implement.
564 * The module has been loaded from the server and stashed via mw.loader#implement.
565 * Once the module has no more dependencies in-flight, the module will be executed,
566 * controlled via #requestPropagation and #doPropagation.
568 * The module is being executed.
570 * The module has been successfully executed.
572 * The module (or one of its dependencies) produced an error during execution.
574 * The module was registered client-side and requested, but the server denied knowledge
575 * of the module's existence.
580 var registry
= Object
.create( null ),
581 // Mapping of sources, keyed by source-id, values are strings.
586 // 'sourceId': 'http://example.org/w/load.php'
589 sources
= Object
.create( null ),
591 // For queueModuleScript()
592 handlingPendingRequests
= false,
593 pendingRequests
= [],
595 // List of modules to be loaded
599 * List of callback jobs waiting for modules to be ready.
601 * Jobs are created by #enqueue() and run by #doPropagation().
602 * Typically when a job is created for a module, the job's dependencies contain
603 * both the required module and all its recursive dependencies.
608 * 'dependencies': [ module names ],
609 * 'ready': Function callback
610 * 'error': Function callback
613 * @property {Object[]} jobs
618 // For #requestPropagation() and #doPropagation()
619 willPropagate
= false,
624 * @property {Array} baseModules
626 baseModules
= $VARS
.baseModules
,
629 * For #addEmbeddedCSS() and #addLink()
632 * @property {HTMLElement|null} marker
634 marker
= document
.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' ),
636 // For #addEmbeddedCSS()
638 rAF
= window
.requestAnimationFrame
|| setTimeout
;
641 * Create a new style element and add it to the DOM.
644 * @param {string} text CSS text
645 * @param {Node|null} [nextNode] The element where the style tag
646 * should be inserted before
647 * @return {HTMLElement} Reference to the created style element
649 function newStyleTag( text
, nextNode
) {
650 var el
= document
.createElement( 'style' );
651 el
.appendChild( document
.createTextNode( text
) );
652 if ( nextNode
&& nextNode
.parentNode
) {
653 nextNode
.parentNode
.insertBefore( el
, nextNode
);
655 document
.head
.appendChild( el
);
662 * @param {Object} cssBuffer
664 function flushCssBuffer( cssBuffer
) {
666 // Mark this object as inactive now so that further calls to addEmbeddedCSS() from
667 // the callbacks go to a new buffer instead of this one (T105973)
668 cssBuffer
.active
= false;
669 newStyleTag( cssBuffer
.cssText
, marker
);
670 for ( i
= 0; i
< cssBuffer
.callbacks
.length
; i
++ ) {
671 cssBuffer
.callbacks
[ i
]();
676 * Add a bit of CSS text to the current browser page.
678 * The creation and insertion of the `<style>` element is debounced for two reasons:
680 * - Performing the insertion before the next paint round via requestAnimationFrame
681 * avoids forced or wasted style recomputations, which are expensive in browsers.
682 * - Reduce how often new stylesheets are inserted by letting additional calls to this
683 * function accumulate into a buffer for at least one JavaScript tick. Modules are
684 * received from the server in batches, which means there is likely going to be many
685 * calls to this function in a row within the same tick / the same call stack.
689 * @param {string} cssText CSS text to be added in a `<style>` tag.
690 * @param {Function} callback Called after the insertion has occurred
692 function addEmbeddedCSS( cssText
, callback
) {
693 // Create a buffer if:
694 // - We don't have one yet.
695 // - The previous one is closed.
696 // - The next CSS chunk syntactically needs to be at the start of a stylesheet (T37562).
697 if ( !nextCssBuffer
|| nextCssBuffer
.active
=== false || cssText
.slice( 0, '@import'.length
) === '@import' ) {
705 // Linebreak for somewhat distinguishable sections
706 nextCssBuffer
.cssText
+= '\n' + cssText
;
707 nextCssBuffer
.callbacks
.push( callback
);
709 if ( nextCssBuffer
.active
=== null ) {
710 nextCssBuffer
.active
= true;
711 // The flushCssBuffer callback has its parameter bound by reference, which means
712 // 1) We can still extend the buffer from our object reference after this point.
713 // 2) We can safely re-assign the variable (not the object) to start a new buffer.
714 rAF( flushCssBuffer
.bind( null, nextCssBuffer
) );
720 * @param {Array} modules List of module names
721 * @return {string} Hash of concatenated version hashes.
723 function getCombinedVersion( modules
) {
724 var hashes
= modules
.reduce( function ( result
, module
) {
725 return result
+ registry
[ module
].version
;
727 return fnv132( hashes
);
731 * Determine whether all dependencies are in state 'ready', which means we may
732 * execute the module or job now.
735 * @param {Array} modules Names of modules to be checked
736 * @return {boolean} True if all modules are in state 'ready', false otherwise
738 function allReady( modules
) {
740 for ( i
= 0; i
< modules
.length
; i
++ ) {
741 if ( mw
.loader
.getState( modules
[ i
] ) !== 'ready' ) {
749 * Determine whether all direct and base dependencies are in state 'ready'
752 * @param {string} module Name of the module to be checked
753 * @return {boolean} True if all direct/base dependencies are in state 'ready'; false otherwise
755 function allWithImplicitReady( module
) {
756 return allReady( registry
[ module
].dependencies
) &&
757 ( baseModules
.indexOf( module
) !== -1 || allReady( baseModules
) );
761 * Determine whether all dependencies are in state 'ready', which means we may
762 * execute the module or job now.
765 * @param {Array} modules Names of modules to be checked
766 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
768 function anyFailed( modules
) {
770 for ( i
= 0; i
< modules
.length
; i
++ ) {
771 state
= mw
.loader
.getState( modules
[ i
] );
772 if ( state
=== 'error' || state
=== 'missing' ) {
780 * Handle propagation of module state changes and reactions to them.
782 * - When a module reaches a failure state, this should be propagated to
783 * modules that depend on the failed module.
784 * - When a module reaches a final state, pending job callbacks for the
785 * module from mw.loader.using() should be called.
786 * - When a module reaches the 'ready' state from #execute(), consider
787 * executing dependant modules now having their dependencies satisfied.
788 * - When a module reaches the 'loaded' state from mw.loader.implement,
789 * consider executing it, if it has no unsatisfied dependencies.
793 function doPropagation() {
794 var errorModule
, baseModuleError
, module
, i
, failed
, job
,
797 // Keep going until the last iteration performed no actions.
799 didPropagate
= false;
801 // Stage 1: Propagate failures
802 while ( errorModules
.length
) {
803 errorModule
= errorModules
.shift();
804 baseModuleError
= baseModules
.indexOf( errorModule
) !== -1;
805 for ( module
in registry
) {
806 if ( registry
[ module
].state
!== 'error' && registry
[ module
].state
!== 'missing' ) {
807 if ( baseModuleError
&& baseModules
.indexOf( module
) === -1 ) {
808 // Propate error from base module to all regular (non-base) modules
809 registry
[ module
].state
= 'error';
811 } else if ( registry
[ module
].dependencies
.indexOf( errorModule
) !== -1 ) {
812 // Propagate error from dependency to depending module
813 registry
[ module
].state
= 'error';
814 // .. and propagate it further
815 errorModules
.push( module
);
822 // Stage 2: Execute 'loaded' modules with no unsatisfied dependencies
823 for ( module
in registry
) {
824 if ( registry
[ module
].state
=== 'loaded' && allWithImplicitReady( module
) ) {
825 // Recursively execute all dependent modules that were already loaded
826 // (waiting for execution) and no longer have unsatisfied dependencies.
827 // Base modules may have dependencies amongst eachother to ensure correct
828 // execution order. Regular modules wait for all base modules.
829 // eslint-disable-next-line no-use-before-define
835 // Stage 3: Invoke job callbacks that are no longer blocked
836 for ( i
= 0; i
< jobs
.length
; i
++ ) {
838 failed
= anyFailed( job
.dependencies
);
839 if ( failed
|| allReady( job
.dependencies
) ) {
843 if ( failed
&& job
.error
) {
844 job
.error( new Error( 'Module has failed dependencies' ), job
.dependencies
);
845 } else if ( !failed
&& job
.ready
) {
849 // A user-defined callback raised an exception.
850 // Swallow it to protect our state machine!
851 mw
.trackError( 'resourceloader.exception', {
853 source
: 'load-callback'
859 } while ( didPropagate
);
861 willPropagate
= false;
865 * Request a (debounced) call to doPropagation().
869 function requestPropagation() {
870 if ( willPropagate
) {
871 // Already scheduled, or, we're already in a doPropagation stack.
874 willPropagate
= true;
875 // Yield for two reasons:
876 // * Allow successive calls to mw.loader.implement() from the same
877 // load.php response, or from the same asyncEval() to be in the
878 // propagation batch.
879 // * Allow the browser to breathe between the reception of
880 // module source code and the execution of it.
882 // Use a high priority because the user may be waiting for interactions
883 // to start being possible. But, first provide a moment (up to 'timeout')
884 // for native input event handling (e.g. scrolling/typing/clicking).
885 mw
.requestIdleCallback( doPropagation
, { timeout
: 1 } );
889 * Update a module's state in the registry and make sure any neccesary
890 * propagation will occur. See #doPropagation for more about propagation.
891 * See #registry for more about how states are used.
894 * @param {string} module
895 * @param {string} state
897 function setAndPropagate( module
, state
) {
898 registry
[ module
].state
= state
;
899 if ( state
=== 'loaded' || state
=== 'ready' || state
=== 'error' || state
=== 'missing' ) {
900 if ( state
=== 'ready' ) {
901 // Queue to later be synced to the local module store.
902 mw
.loader
.store
.add( module
);
903 } else if ( state
=== 'error' || state
=== 'missing' ) {
904 errorModules
.push( module
);
906 requestPropagation();
911 * Resolve dependencies and detect circular references.
914 * @param {string} module Name of the top-level module whose dependencies shall be
915 * resolved and sorted.
916 * @param {Array} resolved Returns a topological sort of the given module and its
917 * dependencies, such that later modules depend on earlier modules. The array
918 * contains the module names. If the array contains already some module names,
919 * this function appends its result to the pre-existing array.
920 * @param {StringSet} [unresolved] Used to track the current dependency
921 * chain, and to report loops in the dependency graph.
922 * @throws {Error} If any unregistered module or a dependency loop is encountered
924 function sortDependencies( module
, resolved
, unresolved
) {
927 if ( !( module
in registry
) ) {
928 throw new Error( 'Unknown dependency: ' + module
);
931 if ( registry
[ module
].skip
!== null ) {
932 // eslint-disable-next-line no-new-func
933 skip
= new Function( registry
[ module
].skip
);
934 registry
[ module
].skip
= null;
936 registry
[ module
].skipped
= true;
937 registry
[ module
].dependencies
= [];
938 setAndPropagate( module
, 'ready' );
943 if ( resolved
.indexOf( module
) !== -1 ) {
944 // Module already resolved; nothing to do
947 // Create unresolved if not passed in
949 unresolved
= new StringSet();
953 if ( baseModules
.indexOf( module
) === -1 ) {
954 baseModules
.forEach( function ( baseModule
) {
955 if ( resolved
.indexOf( baseModule
) === -1 ) {
956 resolved
.push( baseModule
);
961 // Tracks down dependencies
962 deps
= registry
[ module
].dependencies
;
963 unresolved
.add( module
);
964 for ( i
= 0; i
< deps
.length
; i
++ ) {
965 if ( resolved
.indexOf( deps
[ i
] ) === -1 ) {
966 if ( unresolved
.has( deps
[ i
] ) ) {
968 'Circular reference detected: ' + module
+ ' -> ' + deps
[ i
]
972 sortDependencies( deps
[ i
], resolved
, unresolved
);
975 resolved
.push( module
);
979 * Get names of module that a module depends on, in their proper dependency order.
982 * @param {string[]} modules Array of string module names
983 * @return {Array} List of dependencies, including 'module'.
984 * @throws {Error} If an unregistered module or a dependency loop is encountered
986 function resolve( modules
) {
987 var i
, resolved
= [];
988 for ( i
= 0; i
< modules
.length
; i
++ ) {
989 sortDependencies( modules
[ i
], resolved
);
995 * Like #resolve(), except it will silently ignore modules that
996 * are missing or have missing dependencies.
999 * @param {string[]} modules Array of string module names
1000 * @return {Array} List of dependencies.
1002 function resolveStubbornly( modules
) {
1003 var i
, saved
, resolved
= [];
1004 for ( i
= 0; i
< modules
.length
; i
++ ) {
1005 saved
= resolved
.slice();
1007 sortDependencies( modules
[ i
], resolved
);
1009 // This module is unknown or has unknown dependencies.
1010 // Undo any incomplete resolutions made and keep going.
1012 mw
.trackError( 'resourceloader.exception', {
1022 * Resolve a relative file path.
1024 * For example, resolveRelativePath( '../foo.js', 'resources/src/bar/bar.js' )
1025 * returns 'resources/src/foo.js'.
1027 * @param {string} relativePath Relative file path, starting with ./ or ../
1028 * @param {string} basePath Path of the file (not directory) relativePath is relative to
1029 * @return {string|null} Resolved path, or null if relativePath does not start with ./ or ../
1031 function resolveRelativePath( relativePath
, basePath
) {
1032 var prefixes
, prefix
, baseDirParts
,
1033 relParts
= relativePath
.match( /^((?:\.\.?\/)+)(.*)$/ );
1039 baseDirParts
= basePath
.split( '/' );
1040 // basePath looks like 'foo/bar/baz.js', so baseDirParts looks like [ 'foo', 'bar, 'baz.js' ]
1041 // Remove the file component at the end, so that we are left with only the directory path
1044 prefixes
= relParts
[ 1 ].split( '/' );
1045 // relParts[ 1 ] looks like '../../', so prefixes looks like [ '..', '..', '' ]
1046 // Remove the empty element at the end
1049 // For every ../ in the path prefix, remove one directory level from baseDirParts
1050 while ( ( prefix
= prefixes
.pop() ) !== undefined ) {
1051 if ( prefix
=== '..' ) {
1056 // If there's anything left of the base path, prepend it to the file path
1057 return ( baseDirParts
.length
? baseDirParts
.join( '/' ) + '/' : '' ) + relParts
[ 2 ];
1061 * Make a require() function scoped to a package file
1063 * @param {Object} moduleObj Module object from the registry
1064 * @param {string} basePath Path of the file this is scoped to. Used for relative paths.
1065 * @return {Function}
1067 function makeRequireFunction( moduleObj
, basePath
) {
1068 return function require( moduleName
) {
1069 var fileName
, fileContent
, result
, moduleParam
,
1070 scriptFiles
= moduleObj
.script
.files
;
1071 fileName
= resolveRelativePath( moduleName
, basePath
);
1072 if ( fileName
=== null ) {
1073 // Not a relative path, so it's a module name
1074 return mw
.loader
.require( moduleName
);
1077 if ( !hasOwn
.call( scriptFiles
, fileName
) ) {
1078 throw new Error( 'Cannot require() undefined file ' + fileName
);
1080 if ( hasOwn
.call( moduleObj
.packageExports
, fileName
) ) {
1081 // File has already been executed, return the cached result
1082 return moduleObj
.packageExports
[ fileName
];
1085 fileContent
= scriptFiles
[ fileName
];
1086 if ( typeof fileContent
=== 'function' ) {
1087 moduleParam
= { exports
: {} };
1088 fileContent( makeRequireFunction( moduleObj
, fileName
), moduleParam
);
1089 result
= moduleParam
.exports
;
1091 // fileContent is raw data, just pass it through
1092 result
= fileContent
;
1094 moduleObj
.packageExports
[ fileName
] = result
;
1100 * Load and execute a script.
1103 * @param {string} src URL to script, will be used as the src attribute in the script tag
1104 * @param {Function} [callback] Callback to run after request resolution
1106 function addScript( src
, callback
) {
1107 var script
= document
.createElement( 'script' );
1109 script
.onload
= script
.onerror = function () {
1110 if ( script
.parentNode
) {
1111 script
.parentNode
.removeChild( script
);
1119 document
.head
.appendChild( script
);
1123 * Queue the loading and execution of a script for a particular module.
1125 * This does for debug mode what runScript() does for production.
1128 * @param {string} src URL of the script
1129 * @param {string} moduleName Name of currently executing module
1130 * @param {Function} callback Callback to run after addScript() resolution
1132 function queueModuleScript( src
, moduleName
, callback
) {
1133 pendingRequests
.push( function () {
1134 // Keep in sync with execute()/runScript().
1135 if ( moduleName
!== 'jquery' ) {
1136 window
.require
= mw
.loader
.require
;
1137 window
.module
= registry
[ moduleName
].module
;
1139 addScript( src
, function () {
1140 // 'module.exports' should not persist after the file is executed to
1141 // avoid leakage to unrelated code. 'require' should be kept, however,
1142 // as asynchronous access to 'require' is allowed and expected. (T144879)
1143 delete window
.module
;
1145 // Start the next one (if any)
1146 if ( pendingRequests
[ 0 ] ) {
1147 pendingRequests
.shift()();
1149 handlingPendingRequests
= false;
1153 if ( !handlingPendingRequests
&& pendingRequests
[ 0 ] ) {
1154 handlingPendingRequests
= true;
1155 pendingRequests
.shift()();
1160 * Utility function for execute()
1163 * @param {string} [media] Media attribute
1164 * @param {string} url URL
1166 function addLink( media
, url
) {
1167 var el
= document
.createElement( 'link' );
1169 el
.rel
= 'stylesheet';
1170 if ( media
&& media
!== 'all' ) {
1173 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1174 // see #addEmbeddedCSS, T33676, T43331, and T49277 for details.
1177 if ( marker
&& marker
.parentNode
) {
1178 marker
.parentNode
.insertBefore( el
, marker
);
1180 document
.head
.appendChild( el
);
1186 * @param {string} code JavaScript code
1188 function domEval( code
) {
1189 var script
= document
.createElement( 'script' );
1190 if ( mw
.config
.get( 'wgCSPNonce' ) !== false ) {
1191 script
.nonce
= mw
.config
.get( 'wgCSPNonce' );
1194 document
.head
.appendChild( script
);
1195 script
.parentNode
.removeChild( script
);
1199 * Add one or more modules to the module load queue.
1204 * @param {string[]} dependencies Array of module names in the registry
1205 * @param {Function} [ready] Callback to execute when all dependencies are ready
1206 * @param {Function} [error] Callback to execute when any dependency fails
1208 function enqueue( dependencies
, ready
, error
) {
1209 if ( allReady( dependencies
) ) {
1210 // Run ready immediately
1211 if ( ready
!== undefined ) {
1217 if ( anyFailed( dependencies
) ) {
1218 if ( error
!== undefined ) {
1219 // Execute error immediately if any dependencies have errors
1221 new Error( 'One or more dependencies failed to load' ),
1228 // Not all dependencies are ready, add to the load queue...
1230 // Add ready and error callbacks if they were given
1231 if ( ready
!== undefined || error
!== undefined ) {
1233 // Narrow down the list to modules that are worth waiting for
1234 dependencies
: dependencies
.filter( function ( module
) {
1235 var state
= registry
[ module
].state
;
1236 return state
=== 'registered' || state
=== 'loaded' || state
=== 'loading' || state
=== 'executing';
1243 dependencies
.forEach( function ( module
) {
1244 // Only queue modules that are still in the initial 'registered' state
1245 // (not ones already loading, ready or error).
1246 if ( registry
[ module
].state
=== 'registered' && queue
.indexOf( module
) === -1 ) {
1247 // Private modules must be embedded in the page. Don't bother queuing
1248 // these as the server will deny them anyway (T101806).
1249 if ( registry
[ module
].group
=== 'private' ) {
1250 setAndPropagate( module
, 'error' );
1253 queue
.push( module
);
1261 * Executes a loaded module, making it ready to use
1264 * @param {string} module Module name to execute
1266 function execute( module
) {
1267 var key
, value
, media
, i
, urls
, cssHandle
, siteDeps
, siteDepErr
, runScript
,
1270 if ( registry
[ module
].state
!== 'loaded' ) {
1271 throw new Error( 'Module in state "' + registry
[ module
].state
+ '" may not be executed: ' + module
);
1274 registry
[ module
].state
= 'executing';
1275 $CODE
.profileExecuteStart();
1277 runScript = function () {
1278 var script
, markModuleReady
, nestedAddScript
, mainScript
;
1280 $CODE
.profileScriptStart();
1281 script
= registry
[ module
].script
;
1282 markModuleReady = function () {
1283 $CODE
.profileScriptEnd();
1284 setAndPropagate( module
, 'ready' );
1286 nestedAddScript = function ( arr
, callback
, i
) {
1287 // Recursively call queueModuleScript() in its own callback
1288 // for each element of arr.
1289 if ( i
>= arr
.length
) {
1290 // We're at the end of the array
1295 queueModuleScript( arr
[ i
], module
, function () {
1296 nestedAddScript( arr
, callback
, i
+ 1 );
1301 if ( Array
.isArray( script
) ) {
1302 nestedAddScript( script
, markModuleReady
, 0 );
1304 typeof script
=== 'function' || (
1305 typeof script
=== 'object' &&
1309 if ( typeof script
=== 'function' ) {
1310 // Keep in sync with queueModuleScript() for debug mode
1311 if ( module
=== 'jquery' ) {
1312 // This is a special case for when 'jquery' itself is being loaded.
1313 // - The standard jquery.js distribution does not set `window.jQuery`
1314 // in CommonJS-compatible environments (Node.js, AMD, RequireJS, etc.).
1315 // - MediaWiki's 'jquery' module also bundles jquery.migrate.js, which
1316 // in a CommonJS-compatible environment, will use require('jquery'),
1317 // but that can't work when we're still inside that module.
1320 // Pass jQuery twice so that the signature of the closure which wraps
1321 // the script can bind both '$' and 'jQuery'.
1322 script( window
.$, window
.$, mw
.loader
.require
, registry
[ module
].module
);
1325 mainScript
= script
.files
[ script
.main
];
1326 if ( typeof mainScript
!== 'function' ) {
1327 throw new Error( 'Main script file ' + script
.main
+ ' in module ' + module
+
1328 'must be of type function, is of type ' + typeof mainScript
);
1330 // jQuery parameters are not passed for multi-file modules
1332 makeRequireFunction( registry
[ module
], script
.main
),
1333 registry
[ module
].module
1337 } else if ( typeof script
=== 'string' ) {
1338 // Site and user modules are legacy scripts that run in the global scope.
1339 // This is transported as a string instead of a function to avoid needing
1340 // to use string manipulation to undo the function wrapper.
1345 // Module without script
1349 // Use mw.track instead of mw.log because these errors are common in production mode
1350 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1351 setAndPropagate( module
, 'error' );
1352 $CODE
.profileScriptEnd();
1353 mw
.trackError( 'resourceloader.exception', {
1356 source
: 'module-execute'
1361 // Add localizations to message system
1362 if ( registry
[ module
].messages
) {
1363 mw
.messages
.set( registry
[ module
].messages
);
1366 // Initialise templates
1367 if ( registry
[ module
].templates
) {
1368 mw
.templates
.set( module
, registry
[ module
].templates
);
1371 // Adding of stylesheets is asynchronous via addEmbeddedCSS().
1372 // The below function uses a counting semaphore to make sure we don't call
1373 // runScript() until after this module's stylesheets have been inserted
1375 cssHandle = function () {
1376 // Increase semaphore, when creating a callback for addEmbeddedCSS.
1378 return function () {
1380 // Decrease semaphore, when said callback is invoked.
1382 if ( cssPending
=== 0 ) {
1384 // This callback is exposed to addEmbeddedCSS, which is outside the execute()
1385 // function and is not concerned with state-machine integrity. In turn,
1386 // addEmbeddedCSS() actually exposes stuff further into the browser (rAF).
1387 // If increment and decrement callbacks happen in the wrong order, or start
1388 // again afterwards, then this branch could be reached multiple times.
1389 // To protect the integrity of the state-machine, prevent that from happening
1390 // by making runScript() cannot be called more than once. We store a private
1391 // reference when we first reach this branch, then deference the original, and
1392 // call our reference to it.
1393 runScriptCopy
= runScript
;
1394 runScript
= undefined;
1400 // Process styles (see also mw.loader.implement)
1401 // * back-compat: { <media>: css }
1402 // * back-compat: { <media>: [url, ..] }
1403 // * { "css": [css, ..] }
1404 // * { "url": { <media>: [url, ..] } }
1405 if ( registry
[ module
].style
) {
1406 for ( key
in registry
[ module
].style
) {
1407 value
= registry
[ module
].style
[ key
];
1410 if ( key
!== 'url' && key
!== 'css' ) {
1411 // Backwards compatibility, key is a media-type
1412 if ( typeof value
=== 'string' ) {
1413 // back-compat: { <media>: css }
1414 // Ignore 'media' because it isn't supported (nor was it used).
1415 // Strings are pre-wrapped in "@media". The media-type was just ""
1416 // (because it had to be set to something).
1417 // This is one of the reasons why this format is no longer used.
1418 addEmbeddedCSS( value
, cssHandle() );
1420 // back-compat: { <media>: [url, ..] }
1426 // Array of css strings in key 'css',
1427 // or back-compat array of urls from media-type
1428 if ( Array
.isArray( value
) ) {
1429 for ( i
= 0; i
< value
.length
; i
++ ) {
1430 if ( key
=== 'bc-url' ) {
1431 // back-compat: { <media>: [url, ..] }
1432 addLink( media
, value
[ i
] );
1433 } else if ( key
=== 'css' ) {
1434 // { "css": [css, ..] }
1435 addEmbeddedCSS( value
[ i
], cssHandle() );
1438 // Not an array, but a regular object
1439 // Array of urls inside media-type key
1440 } else if ( typeof value
=== 'object' ) {
1441 // { "url": { <media>: [url, ..] } }
1442 for ( media
in value
) {
1443 urls
= value
[ media
];
1444 for ( i
= 0; i
< urls
.length
; i
++ ) {
1445 addLink( media
, urls
[ i
] );
1452 // End profiling of execute()-self before we call runScript(),
1453 // which we want to measure separately without overlap.
1454 $CODE
.profileExecuteEnd();
1456 if ( module
=== 'user' ) {
1457 // Implicit dependency on the site module. Not a real dependency because it should
1458 // run after 'site' regardless of whether it succeeds or fails.
1459 // Note: This is a simplified version of mw.loader.using(), inlined here because
1460 // mw.loader.using() is part of mediawiki.base (depends on jQuery; T192623).
1462 siteDeps
= resolve( [ 'site' ] );
1467 if ( siteDepErr
=== undefined ) {
1468 enqueue( siteDeps
, runScript
, runScript
);
1470 } else if ( cssPending
=== 0 ) {
1471 // Regular module without styles
1474 // else: runScript will get called via cssHandle()
1477 function sortQuery( o
) {
1486 for ( key
= 0; key
< a
.length
; key
++ ) {
1487 sorted
[ a
[ key
] ] = o
[ a
[ key
] ];
1493 * Converts a module map of the form `{ foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }`
1494 * to a query string of the form `foo.bar,baz|bar.baz,quux`.
1496 * See `ResourceLoader::makePackedModulesString()` in PHP, of which this is a port.
1497 * On the server, unpacking is done by `ResourceLoaderContext::expandModuleNames()`.
1499 * Note: This is only half of the logic, the other half has to be in #batchRequest(),
1500 * because its implementation needs to keep track of potential string size in order
1501 * to decide when to split the requests due to url size.
1504 * @param {Object} moduleMap Module map
1506 * @return {string} return.str Module query string
1507 * @return {Array} return.list List of module names in matching order
1509 function buildModulesString( moduleMap
) {
1514 function restore( suffix
) {
1518 for ( prefix
in moduleMap
) {
1519 p
= prefix
=== '' ? '' : prefix
+ '.';
1520 str
.push( p
+ moduleMap
[ prefix
].join( ',' ) );
1521 list
.push
.apply( list
, moduleMap
[ prefix
].map( restore
) );
1524 str
: str
.join( '|' ),
1530 * Resolve indexed dependencies.
1532 * ResourceLoader uses an optimisation to save space which replaces module names in
1533 * dependency lists with the index of that module within the array of module
1534 * registration data if it exists. The benefit is a significant reduction in the data
1535 * size of the startup module. This function changes those dependency lists back to
1536 * arrays of strings.
1539 * @param {Array} modules Modules array
1541 function resolveIndexedDependencies( modules
) {
1543 function resolveIndex( dep
) {
1544 return typeof dep
=== 'number' ? modules
[ dep
][ 0 ] : dep
;
1546 for ( i
= 0; i
< modules
.length
; i
++ ) {
1547 deps
= modules
[ i
][ 2 ];
1549 for ( j
= 0; j
< deps
.length
; j
++ ) {
1550 deps
[ j
] = resolveIndex( deps
[ j
] );
1558 * @param {Object} params Map of parameter names to values
1561 function makeQueryString( params
) {
1562 return Object
.keys( params
).map( function ( key
) {
1563 return encodeURIComponent( key
) + '=' + encodeURIComponent( params
[ key
] );
1568 * Create network requests for a batch of modules.
1570 * This is an internal method for #work(). This must not be called directly
1571 * unless the modules are already registered, and no request is in progress,
1572 * and the module state has already been set to `loading`.
1575 * @param {string[]} batch
1577 function batchRequest( batch
) {
1578 var reqBase
, splits
, maxQueryLength
, b
, bSource
, bGroup
,
1579 source
, group
, i
, modules
, sourceLoadScript
,
1580 currReqBase
, currReqBaseLength
, moduleMap
, currReqModules
, l
,
1581 lastDotIndex
, prefix
, suffix
, bytesAdded
;
1584 * Start the currently drafted request to the server.
1588 function doRequest() {
1589 // Optimisation: Inherit (Object.create), not copy ($.extend)
1590 var query
= Object
.create( currReqBase
),
1591 packed
= buildModulesString( moduleMap
);
1592 query
.modules
= packed
.str
;
1593 // The packing logic can change the effective order, even if the input was
1594 // sorted. As such, the call to getCombinedVersion() must use this
1595 // effective order, instead of currReqModules, as otherwise the combined
1596 // version will not match the hash expected by the server based on
1597 // combining versions from the module query string in-order. (T188076)
1598 query
.version
= getCombinedVersion( packed
.list
);
1599 query
= sortQuery( query
);
1600 addScript( sourceLoadScript
+ '?' + makeQueryString( query
) );
1603 if ( !batch
.length
) {
1607 // Always order modules alphabetically to help reduce cache
1608 // misses for otherwise identical content.
1611 // Query parameters common to all requests
1613 skin
: mw
.config
.get( 'skin' ),
1614 lang
: mw
.config
.get( 'wgUserLanguage' ),
1615 debug
: mw
.config
.get( 'debug' )
1617 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1619 // Split module list by source and by group.
1620 splits
= Object
.create( null );
1621 for ( b
= 0; b
< batch
.length
; b
++ ) {
1622 bSource
= registry
[ batch
[ b
] ].source
;
1623 bGroup
= registry
[ batch
[ b
] ].group
;
1624 if ( !splits
[ bSource
] ) {
1625 splits
[ bSource
] = Object
.create( null );
1627 if ( !splits
[ bSource
][ bGroup
] ) {
1628 splits
[ bSource
][ bGroup
] = [];
1630 splits
[ bSource
][ bGroup
].push( batch
[ b
] );
1633 for ( source
in splits
) {
1634 sourceLoadScript
= sources
[ source
];
1636 for ( group
in splits
[ source
] ) {
1638 // Cache access to currently selected list of
1639 // modules for this group from this source.
1640 modules
= splits
[ source
][ group
];
1642 // Query parameters common to requests for this module group
1643 // Optimisation: Inherit (Object.create), not copy ($.extend)
1644 currReqBase
= Object
.create( reqBase
);
1645 // User modules require a user name in the query string.
1646 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1647 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1650 // In addition to currReqBase, doRequest() will also add 'modules' and 'version'.
1651 // > '&modules='.length === 9
1652 // > '&version=1234567'.length === 16
1654 currReqBaseLength
= makeQueryString( currReqBase
).length
+ 25;
1656 // We may need to split up the request to honor the query string length limit,
1657 // so build it piece by piece.
1658 l
= currReqBaseLength
;
1659 moduleMap
= Object
.create( null ); // { prefix: [ suffixes ] }
1660 currReqModules
= [];
1662 for ( i
= 0; i
< modules
.length
; i
++ ) {
1663 // Determine how many bytes this module would add to the query string
1664 lastDotIndex
= modules
[ i
].lastIndexOf( '.' );
1665 // If lastDotIndex is -1, substr() returns an empty string
1666 prefix
= modules
[ i
].substr( 0, lastDotIndex
);
1667 suffix
= modules
[ i
].slice( lastDotIndex
+ 1 );
1668 bytesAdded
= moduleMap
[ prefix
] ?
1669 suffix
.length
+ 3 : // '%2C'.length == 3
1670 modules
[ i
].length
+ 3; // '%7C'.length == 3
1672 // If the url would become too long, create a new one, but don't create empty requests
1673 if ( maxQueryLength
> 0 && currReqModules
.length
&& l
+ bytesAdded
> maxQueryLength
) {
1674 // Dispatch what we've got...
1676 // .. and start again.
1677 l
= currReqBaseLength
;
1678 moduleMap
= Object
.create( null );
1679 currReqModules
= [];
1681 mw
.track( 'resourceloader.splitRequest', { maxQueryLength
: maxQueryLength
} );
1683 if ( !moduleMap
[ prefix
] ) {
1684 moduleMap
[ prefix
] = [];
1687 moduleMap
[ prefix
].push( suffix
);
1688 currReqModules
.push( modules
[ i
] );
1690 // If there's anything left in moduleMap, request that too
1691 if ( currReqModules
.length
) {
1700 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1701 * form of calls to mw.loader#implement().
1702 * @param {Function} cb Callback in case of failure
1703 * @param {Error} cb.err
1705 function asyncEval( implementations
, cb
) {
1706 if ( !implementations
.length
) {
1709 mw
.requestIdleCallback( function () {
1711 domEval( implementations
.join( ';' ) );
1719 * Make a versioned key for a specific module.
1722 * @param {string} module Module name
1723 * @return {string|null} Module key in format '`[name]@[version]`',
1724 * or null if the module does not exist
1726 function getModuleKey( module
) {
1727 return module
in registry
? ( module
+ '@' + registry
[ module
].version
) : null;
1732 * @param {string} key Module name or '`[name]@[version]`'
1735 function splitModuleKey( key
) {
1736 var index
= key
.indexOf( '@' );
1737 if ( index
=== -1 ) {
1744 name
: key
.slice( 0, index
),
1745 version
: key
.slice( index
+ 1 )
1751 * @param {string} module
1752 * @param {string|number} [version]
1753 * @param {string[]} [dependencies]
1754 * @param {string} [group]
1755 * @param {string} [source]
1756 * @param {string} [skip]
1758 function registerOne( module
, version
, dependencies
, group
, source
, skip
) {
1759 if ( module
in registry
) {
1760 throw new Error( 'module already registered: ' + module
);
1762 registry
[ module
] = {
1763 // Exposed to execute() for mw.loader.implement() closures.
1764 // Import happens via require().
1768 // module.export objects for each package file inside this module
1770 version
: String( version
|| '' ),
1771 dependencies
: dependencies
|| [],
1772 group
: typeof group
=== 'string' ? group
: null,
1773 source
: typeof source
=== 'string' ? source
: 'local',
1774 state
: 'registered',
1775 skip
: typeof skip
=== 'string' ? skip
: null
1779 /* Public Members */
1782 * The module registry is exposed as an aid for debugging and inspecting page
1783 * state; it is not a public interface for modifying the registry.
1789 moduleRegistry
: registry
,
1792 * @inheritdoc #newStyleTag
1795 addStyleTag
: newStyleTag
,
1802 * Start loading of all queued module dependencies.
1807 var q
, batch
, implementations
, sourceModules
;
1811 // Appends a list of modules from the queue to the batch
1812 for ( q
= 0; q
< queue
.length
; q
++ ) {
1813 // Only load modules which are registered
1814 if ( queue
[ q
] in registry
&& registry
[ queue
[ q
] ].state
=== 'registered' ) {
1815 // Prevent duplicate entries
1816 if ( batch
.indexOf( queue
[ q
] ) === -1 ) {
1817 batch
.push( queue
[ q
] );
1818 // Mark registered modules as loading
1819 registry
[ queue
[ q
] ].state
= 'loading';
1824 // Now that the queue has been processed into a batch, clear the queue.
1825 // This MUST happen before we initiate any eval or network request. Otherwise,
1826 // it is possible for a cached script to instantly trigger the same work queue
1827 // again; all before we've cleared it causing each request to include modules
1828 // which are already loaded.
1831 if ( !batch
.length
) {
1835 mw
.loader
.store
.init();
1836 if ( mw
.loader
.store
.enabled
) {
1837 implementations
= [];
1839 batch
= batch
.filter( function ( module
) {
1840 var implementation
= mw
.loader
.store
.get( module
);
1841 if ( implementation
) {
1842 implementations
.push( implementation
);
1843 sourceModules
.push( module
);
1848 asyncEval( implementations
, function ( err
) {
1850 // Not good, the cached mw.loader.implement calls failed! This should
1851 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1852 // Depending on how corrupt the string is, it is likely that some
1853 // modules' implement() succeeded while the ones after the error will
1854 // never run and leave their modules in the 'loading' state forever.
1855 mw
.loader
.store
.stats
.failed
++;
1857 // Since this is an error not caused by an individual module but by
1858 // something that infected the implement call itself, don't take any
1859 // risks and clear everything in this cache.
1860 mw
.loader
.store
.clear();
1862 mw
.trackError( 'resourceloader.exception', {
1864 source
: 'store-eval'
1866 // Re-add the failed ones that are still pending back to the batch
1867 failed
= sourceModules
.filter( function ( module
) {
1868 return registry
[ module
].state
=== 'loading';
1870 batchRequest( failed
);
1874 batchRequest( batch
);
1878 * Register a source.
1880 * The #work() method will use this information to split up requests by source.
1882 * mw.loader.addSource( { mediawikiwiki: 'https://www.mediawiki.org/w/load.php' } );
1885 * @param {Object} ids An object mapping ids to load.php end point urls
1886 * @throws {Error} If source id is already registered
1888 addSource: function ( ids
) {
1891 if ( id
in sources
) {
1892 throw new Error( 'source already registered: ' + id
);
1894 sources
[ id
] = ids
[ id
];
1899 * Register a module, letting the system know about it and its properties.
1901 * The startup module calls this method.
1903 * When using multiple module registration by passing an array, dependencies that
1904 * are specified as references to modules within the array will be resolved before
1905 * the modules are registered.
1907 * @param {string|Array} modules Module name or array of arrays, each containing
1908 * a list of arguments compatible with this method
1909 * @param {string|number} [version] Module version hash (falls backs to empty string)
1910 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1911 * @param {string[]} [dependencies] Array of module names on which this module depends.
1912 * @param {string} [group=null] Group which the module is in
1913 * @param {string} [source='local'] Name of the source
1914 * @param {string} [skip=null] Script body of the skip function
1916 register: function ( modules
) {
1918 if ( typeof modules
=== 'object' ) {
1919 resolveIndexedDependencies( modules
);
1920 // Optimisation: Up to 55% faster.
1921 // Typically called only once, and with a batch.
1922 // See <https://gist.github.com/Krinkle/f06fdb3de62824c6c16f02a0e6ce0e66>
1923 // Benchmarks taught us that the code for adding an object to `registry`
1924 // should actually be inline, or in a simple function that does no
1925 // arguments manipulation, and isn't also the caller itself.
1926 // JS semantics make it hard to optimise recursion to a different
1927 // signature of itself.
1928 for ( i
= 0; i
< modules
.length
; i
++ ) {
1929 registerOne
.apply( null, modules
[ i
] );
1932 registerOne
.apply( null, arguments
);
1937 * Implement a module given the components that make up the module.
1939 * When #load() or #using() requests one or more modules, the server
1940 * response contain calls to this function.
1942 * @param {string} module Name of module and current module version. Formatted
1943 * as '`[name]@[version]`". This version should match the requested version
1944 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1945 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1946 * @param {Function|Array|string|Object} [script] Module code. This can be a function,
1947 * a list of URLs to load via `<script src>`, a string for `$.globalEval()`, or an
1948 * object like {"files": {"foo.js":function, "bar.js": function, ...}, "main": "foo.js"}.
1949 * If an object is provided, the main file will be executed immediately, and the other
1950 * files will only be executed if loaded via require(). If a function or string is
1951 * provided, it will be executed/evaluated immediately. If an array is provided, all
1952 * URLs in the array will be loaded immediately, and executed as soon as they arrive.
1953 * @param {Object} [style] Should follow one of the following patterns:
1955 * { "css": [css, ..] }
1956 * { "url": { <media>: [url, ..] } }
1958 * And for backwards compatibility (needs to be supported forever due to caching):
1961 * { <media>: [url, ..] }
1963 * The reason css strings are not concatenated anymore is T33676. We now check
1964 * whether it's safe to extend the stylesheet.
1967 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1968 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1970 implement: function ( module
, script
, style
, messages
, templates
) {
1971 var split
= splitModuleKey( module
),
1973 version
= split
.version
;
1974 // Automatically register module
1975 if ( !( name
in registry
) ) {
1976 mw
.loader
.register( name
);
1978 // Check for duplicate implementation
1979 if ( registry
[ name
].script
!== undefined ) {
1980 throw new Error( 'module already implemented: ' + name
);
1983 // Without this reset, if there is a version mismatch between the
1984 // requested and received module version, then mw.loader.store would
1985 // cache the response under the requested key. Thus poisoning the cache
1986 // indefinitely with a stale value. (T117587)
1987 registry
[ name
].version
= version
;
1989 // Attach components
1990 registry
[ name
].script
= script
|| null;
1991 registry
[ name
].style
= style
|| null;
1992 registry
[ name
].messages
= messages
|| null;
1993 registry
[ name
].templates
= templates
|| null;
1994 // The module may already have been marked as erroneous
1995 if ( registry
[ name
].state
!== 'error' && registry
[ name
].state
!== 'missing' ) {
1996 setAndPropagate( name
, 'loaded' );
2001 * Load an external script or one or more modules.
2003 * This method takes a list of unrelated modules. Use cases:
2005 * - A web page will be composed of many different widgets. These widgets independently
2006 * queue their ResourceLoader modules (`OutputPage::addModules()`). If any of them
2007 * have problems, or are no longer known (e.g. cached HTML), the other modules
2008 * should still be loaded.
2009 * - This method is used for preloading, which must not throw. Later code that
2010 * calls #using() will handle the error.
2012 * @param {string|Array} modules Either the name of a module, array of modules,
2013 * or a URL of an external script or style
2014 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
2015 * external script or style; acceptable values are "text/css" and
2016 * "text/javascript"; if no type is provided, text/javascript is assumed.
2018 load: function ( modules
, type
) {
2021 // Allow calling with a url or single dependency as a string
2022 if ( typeof modules
=== 'string' ) {
2023 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
2024 if ( /^(https?:)?\/?\//.test( modules
) ) {
2025 if ( type
=== 'text/css' ) {
2026 l
= document
.createElement( 'link' );
2027 l
.rel
= 'stylesheet';
2029 document
.head
.appendChild( l
);
2032 if ( type
=== 'text/javascript' || type
=== undefined ) {
2033 addScript( modules
);
2037 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
2039 // Called with single module
2040 modules
= [ modules
];
2043 // Filter out top-level modules that are unknown or failed to load before.
2044 filtered
= modules
.filter( function ( module
) {
2045 var state
= mw
.loader
.getState( module
);
2046 return state
!== 'error' && state
!== 'missing';
2048 // Resolve remaining list using the known dependency tree.
2049 // This also filters out modules with unknown dependencies. (T36853)
2050 filtered
= resolveStubbornly( filtered
);
2051 // Some modules are not yet ready, add to module load queue.
2052 enqueue( filtered
, undefined, undefined );
2056 * Change the state of one or more modules.
2058 * @param {Object} states Object of module name/state pairs
2060 state: function ( states
) {
2062 for ( module
in states
) {
2063 state
= states
[ module
];
2064 if ( !( module
in registry
) ) {
2065 mw
.loader
.register( module
);
2067 setAndPropagate( module
, state
);
2072 * Get the version of a module.
2074 * @param {string} module Name of module
2075 * @return {string|null} The version, or null if the module (or its version) is not
2078 getVersion: function ( module
) {
2079 return module
in registry
? registry
[ module
].version
: null;
2083 * Get the state of a module.
2085 * @param {string} module Name of module
2086 * @return {string|null} The state, or null if the module (or its state) is not
2089 getState: function ( module
) {
2090 return module
in registry
? registry
[ module
].state
: null;
2094 * Get the names of all registered modules.
2098 getModuleNames: function () {
2099 return Object
.keys( registry
);
2103 * Get the exported value of a module.
2105 * This static method is publicly exposed for debugging purposes
2106 * only and must not be used in production code. In production code,
2107 * please use the dynamically provided `require()` function instead.
2109 * In case of lazy-loaded modules via mw.loader#using(), the returned
2110 * Promise provides the function, see #using() for examples.
2114 * @param {string} moduleName Module name
2115 * @return {Mixed} Exported value
2117 require: function ( moduleName
) {
2118 var state
= mw
.loader
.getState( moduleName
);
2120 // Only ready modules can be required
2121 if ( state
!== 'ready' ) {
2122 // Module may've forgotten to declare a dependency
2123 throw new Error( 'Module "' + moduleName
+ '" is not loaded.' );
2126 return registry
[ moduleName
].module
.exports
;
2130 * On browsers that implement the localStorage API, the module store serves as a
2131 * smart complement to the browser cache. Unlike the browser cache, the module store
2132 * can slice a concatenated response from ResourceLoader into its constituent
2133 * modules and cache each of them separately, using each module's versioning scheme
2134 * to determine when the cache should be invalidated.
2138 * @class mw.loader.store
2141 // Whether the store is in use on this page.
2144 // Modules whose string representation exceeds 100 kB are
2145 // ineligible for storage. See bug T66721.
2146 MODULE_SIZE_MAX
: 100 * 1000,
2148 // The contents of the store, mapping '[name]@[version]' keys
2149 // to module implementations.
2152 // Names of modules to be stored during the next update.
2153 // See add() and update().
2157 stats
: { hits
: 0, misses
: 0, expired
: 0, failed
: 0 },
2160 * Construct a JSON-serializable object representing the content of the store.
2162 * @return {Object} Module store contents.
2164 toJSON: function () {
2165 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
2169 * Get the localStorage key for the entire module store. The key references
2170 * $wgDBname to prevent clashes between wikis which share a common host.
2172 * @return {string} localStorage item key
2174 getStoreKey: function () {
2175 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
2179 * Get a key on which to vary the module cache.
2181 * @return {string} String of concatenated vary conditions.
2183 getVary: function () {
2184 return mw
.config
.get( 'skin' ) + ':' +
2185 mw
.config
.get( 'wgResourceLoaderStorageVersion' ) + ':' +
2186 mw
.config
.get( 'wgUserLanguage' );
2190 * Initialize the store.
2192 * Retrieves store from localStorage and (if successfully retrieved) decoding
2193 * the stored JSON value to a plain object.
2195 * The try / catch block is used for JSON & localStorage feature detection.
2196 * See the in-line documentation for Modernizr's localStorage feature detection
2197 * code for a full account of why we need a try / catch:
2198 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2203 if ( this.enabled
!== null ) {
2209 // Disabled because localStorage quotas are tight and (in Firefox's case)
2210 // shared by multiple origins.
2211 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2212 /Firefox/.test( navigator
.userAgent
) ||
2214 // Disabled by configuration.
2215 !mw
.config
.get( 'wgResourceLoaderStorageEnabled' )
2217 // Clear any previous store to free up space. (T66721)
2219 this.enabled
= false;
2222 if ( mw
.config
.get( 'debug' ) ) {
2223 // Disable module store in debug mode
2224 this.enabled
= false;
2229 // This a string we stored, or `null` if the key does not (yet) exist.
2230 raw
= localStorage
.getItem( this.getStoreKey() );
2231 // If we get here, localStorage is available; mark enabled
2232 this.enabled
= true;
2233 // If null, JSON.parse() will cast to string and re-parse, still null.
2234 data
= JSON
.parse( raw
);
2235 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== this.getVary() ) {
2236 this.items
= data
.items
;
2240 mw
.trackError( 'resourceloader.exception', {
2242 source
: 'store-localstorage-init'
2246 // If we get here, one of four things happened:
2248 // 1. localStorage did not contain our store key.
2249 // This means `raw` is `null`, and we're on a fresh page view (cold cache).
2250 // The store was enabled, and `items` starts fresh.
2252 // 2. localStorage contained parseable data under our store key,
2253 // but it's not applicable to our current context (see getVary).
2254 // The store was enabled, and `items` starts fresh.
2256 // 3. JSON.parse threw (localStorage contained corrupt data).
2257 // This means `raw` contains a string.
2258 // The store was enabled, and `items` starts fresh.
2260 // 4. localStorage threw (disabled or otherwise unavailable).
2261 // This means `raw` was never assigned.
2262 // We will disable the store below.
2263 if ( raw
=== undefined ) {
2264 // localStorage failed; disable store
2265 this.enabled
= false;
2270 * Retrieve a module from the store and update cache hit stats.
2272 * @param {string} module Module name
2273 * @return {string|boolean} Module implementation or false if unavailable
2275 get: function ( module
) {
2278 if ( !this.enabled
) {
2282 key
= getModuleKey( module
);
2283 if ( key
in this.items
) {
2285 return this.items
[ key
];
2287 this.stats
.misses
++;
2292 * Queue the name of a module that the next update should consider storing.
2295 * @param {string} module Module name
2297 add: function ( module
) {
2298 if ( !this.enabled
) {
2301 this.queue
.push( module
);
2302 this.requestUpdate();
2306 * Add the contents of the named module to the in-memory store.
2308 * This method does not guarantee that the module will be stored.
2309 * Inspection of the module's meta data and size will ultimately decide that.
2311 * This method is considered internal to mw.loader.store and must only
2312 * be called if the store is enabled.
2315 * @param {string} module Module name
2317 set: function ( module
) {
2320 descriptor
= mw
.loader
.moduleRegistry
[ module
];
2322 key
= getModuleKey( module
);
2325 // Already stored a copy of this exact version
2326 key
in this.items
||
2327 // Module failed to load
2329 descriptor
.state
!== 'ready' ||
2330 // Unversioned, private, or site-/user-specific
2331 !descriptor
.version
||
2332 descriptor
.group
=== 'private' ||
2333 descriptor
.group
=== 'user' ||
2334 // Partial descriptor
2335 // (e.g. skipped module, or style module with state=ready)
2336 [ descriptor
.script
, descriptor
.style
, descriptor
.messages
,
2337 descriptor
.templates
].indexOf( undefined ) !== -1
2344 if ( typeof descriptor
.script
=== 'function' ) {
2345 encodedScript
= String( descriptor
.script
);
2347 // Plain object: an object that is not null and is not an array
2348 typeof descriptor
.script
=== 'object' &&
2349 descriptor
.script
&&
2350 !Array
.isArray( descriptor
.script
)
2352 encodedScript
= '{' +
2353 '"main":' + JSON
.stringify( descriptor
.script
.main
) + ',' +
2355 Object
.keys( descriptor
.script
.files
).map( function ( key
) {
2356 var value
= descriptor
.script
.files
[ key
];
2357 return JSON
.stringify( key
) + ':' +
2358 ( typeof value
=== 'function' ? value
: JSON
.stringify( value
) );
2362 encodedScript
= JSON
.stringify( descriptor
.script
);
2365 JSON
.stringify( key
),
2367 JSON
.stringify( descriptor
.style
),
2368 JSON
.stringify( descriptor
.messages
),
2369 JSON
.stringify( descriptor
.templates
)
2372 mw
.trackError( 'resourceloader.exception', {
2374 source
: 'store-localstorage-json'
2379 src
= 'mw.loader.implement(' + args
.join( ',' ) + ');';
2380 if ( src
.length
> this.MODULE_SIZE_MAX
) {
2383 this.items
[ key
] = src
;
2387 * Iterate through the module store, removing any item that does not correspond
2388 * (in name and version) to an item in the module registry.
2390 prune: function () {
2393 for ( key
in this.items
) {
2394 module
= key
.slice( 0, key
.indexOf( '@' ) );
2395 if ( getModuleKey( module
) !== key
) {
2396 this.stats
.expired
++;
2397 delete this.items
[ key
];
2398 } else if ( this.items
[ key
].length
> this.MODULE_SIZE_MAX
) {
2399 // This value predates the enforcement of a size limit on cached modules.
2400 delete this.items
[ key
];
2406 * Clear the entire module store right now.
2408 clear: function () {
2411 localStorage
.removeItem( this.getStoreKey() );
2416 * Request a sync of the in-memory store back to persisted localStorage.
2418 * This function debounces updates. The debouncing logic should account
2419 * for the following factors:
2421 * - Writing to localStorage is an expensive operation that must not happen
2422 * during the critical path of initialising and executing module code.
2423 * Instead, it should happen at a later time after modules have been given
2424 * time and priority to do their thing first.
2426 * - This method is called from mw.loader.store.add(), which will be called
2427 * hundreds of times on a typical page, including within the same call-stack
2428 * and eventloop-tick. This is because responses from load.php happen in
2429 * batches. As such, we want to allow all modules from the same load.php
2430 * response to be written to disk with a single flush, not many.
2432 * - Repeatedly deleting and creating timers is non-trivial.
2434 * - localStorage is shared by all pages from the same origin, if multiple
2435 * pages are loaded with different module sets, the possibility exists that
2436 * modules saved by one page will be clobbered by another. The impact of
2437 * this is minor, it merely causes a less efficient cache use, and the
2438 * problem would be corrected by subsequent page views.
2440 * This method is considered internal to mw.loader.store and must only
2441 * be called if the store is enabled.
2446 requestUpdate
: ( function () {
2447 var hasPendingWrites
= false;
2449 function flushWrites() {
2452 // Remove anything from the in-memory store that came from previous page
2453 // loads that no longer corresponds with current module names and versions.
2454 mw
.loader
.store
.prune();
2455 // Process queued module names, serialise their contents to the in-memory store.
2456 while ( mw
.loader
.store
.queue
.length
) {
2457 mw
.loader
.store
.set( mw
.loader
.store
.queue
.shift() );
2460 key
= mw
.loader
.store
.getStoreKey();
2462 // Replacing the content of the module store might fail if the new
2463 // contents would exceed the browser's localStorage size limit. To
2464 // avoid clogging the browser with stale data, always remove the old
2465 // value before attempting to set the new one.
2466 localStorage
.removeItem( key
);
2467 data
= JSON
.stringify( mw
.loader
.store
);
2468 localStorage
.setItem( key
, data
);
2470 mw
.trackError( 'resourceloader.exception', {
2472 source
: 'store-localstorage-update'
2476 // Let the next call to requestUpdate() create a new timer.
2477 hasPendingWrites
= false;
2480 function onTimeout() {
2481 // Defer the actual write via requestIdleCallback
2482 mw
.requestIdleCallback( flushWrites
);
2485 return function () {
2486 // On the first call to requestUpdate(), create a timer that
2487 // waits at least two seconds, then calls onTimeout.
2488 // The main purpose is to allow the current batch of load.php
2489 // responses to complete before we do anything. This batch can
2490 // trigger many hundreds of calls to requestUpdate().
2491 if ( !hasPendingWrites
) {
2492 hasPendingWrites
= true;
2493 setTimeout( onTimeout
, 2000 );
2501 // Skeleton user object, extended by the 'mediawiki.user' module.
2508 * @property {mw.Map}
2512 * @property {mw.Map}
2517 // OOUI widgets specific to MediaWiki
2522 // Attach to window and globally alias
2523 window
.mw
= window
.mediaWiki
= mw
;