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
,
19 * FNV132 hash function
21 * This function implements the 32-bit version of FNV-1.
22 * It is equivalent to hash( 'fnv132', ... ) in PHP, except
23 * its output is base 36 rather than hex.
24 * See <https://en.wikipedia.org/wiki/FNV_hash_function>
27 * @param {string} str String to hash
28 * @return {string} hash as an seven-character base 36 string
30 function fnv132( str
) {
31 /* eslint-disable no-bitwise */
32 var hash
= 0x811C9DC5,
35 for ( i
= 0; i
< str
.length
; i
++ ) {
36 hash
+= ( hash
<< 1 ) + ( hash
<< 4 ) + ( hash
<< 7 ) + ( hash
<< 8 ) + ( hash
<< 24 );
37 hash
^= str
.charCodeAt( i
);
40 hash
= ( hash
>>> 0 ).toString( 36 );
41 while ( hash
.length
< 7 ) {
46 /* eslint-enable no-bitwise */
49 function defineFallbacks() {
50 // <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set>
55 StringSet
= window
.Set
|| function StringSet() {
56 var set = Object
.create( null );
57 this.add = function ( value
) {
60 this.has = function ( value
) {
67 * Alias property to the global object.
74 * @param {Mixed} value
76 function setGlobalMapValue( map
, key
, value
) {
77 map
.values
[ key
] = value
;
82 // Deprecation notice for mw.config globals (T58550, T72470)
83 map
=== mw
.config
&& 'Use mw.config instead.'
88 * Log a message to window.console, if possible.
90 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
91 * also in production mode). Gets console references in each invocation instead of caching the
92 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
95 * @param {string} topic Stream name passed by mw.track
96 * @param {Object} data Data passed by mw.track
97 * @param {Error} [data.exception]
98 * @param {string} data.source Error source
99 * @param {string} [data.module] Name of module which caused the error
101 function logError( topic
, data
) {
104 source
= data
.source
,
105 module
= data
.module
,
106 console
= window
.console
;
108 if ( console
&& console
.log
) {
109 msg
= ( e
? 'Exception' : 'Error' ) + ' in ' + source
;
111 msg
+= ' in module ' + module
;
113 msg
+= ( e
? ':' : '.' );
116 // If we have an exception object, log it to the warning channel to trigger
117 // proper stacktraces in browsers that support it.
118 if ( e
&& console
.warn
) {
125 * Create an object that can be read from or written to via methods that allow
126 * interaction both with single and multiple properties at once.
132 * @param {boolean} [global=false] Whether to synchronise =values to the global
133 * window object (for backwards-compatibility with mw.config; T72470). Values are
134 * copied in one direction only. Changes to globals do not reflect in the map.
136 function Map( global
) {
137 this.values
= Object
.create( null );
138 if ( global
=== true ) {
139 // Override #set to also set the global variable
140 this.set = function ( selection
, value
) {
142 if ( arguments
.length
> 1 ) {
143 if ( typeof selection
!== 'string' ) {
146 setGlobalMapValue( this, selection
, value
);
149 if ( typeof selection
=== 'object' ) {
150 for ( s
in selection
) {
151 setGlobalMapValue( this, s
, selection
[ s
] );
164 * Get the value of one or more keys.
166 * If called with no arguments, all values are returned.
168 * @param {string|Array} [selection] Key or array of keys to retrieve values for.
169 * @param {Mixed} [fallback=null] Value for keys that don't exist.
170 * @return {Mixed|Object|null} If selection was a string, returns the value,
171 * If selection was an array, returns an object of key/values.
172 * If no selection is passed, a new object with all key/values is returned.
174 get: function ( selection
, fallback
) {
176 fallback
= arguments
.length
> 1 ? fallback
: null;
178 if ( Array
.isArray( selection
) ) {
180 for ( i
= 0; i
< selection
.length
; i
++ ) {
181 if ( typeof selection
[ i
] === 'string' ) {
182 results
[ selection
[ i
] ] = selection
[ i
] in this.values
?
183 this.values
[ selection
[ i
] ] :
190 if ( typeof selection
=== 'string' ) {
191 return selection
in this.values
?
192 this.values
[ selection
] :
196 if ( selection
=== undefined ) {
198 for ( i
in this.values
) {
199 results
[ i
] = this.values
[ i
];
204 // Invalid selection key
209 * Set one or more key/value pairs.
211 * @param {string|Object} selection Key to set value for, or object mapping keys to values
212 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
213 * @return {boolean} True on success, false on failure
215 set: function ( selection
, value
) {
217 // Use `arguments.length` because `undefined` is also a valid value.
218 if ( arguments
.length
> 1 ) {
219 if ( typeof selection
!== 'string' ) {
222 this.values
[ selection
] = value
;
225 if ( typeof selection
=== 'object' ) {
226 for ( s
in selection
) {
227 this.values
[ s
] = selection
[ s
];
235 * Check if one or more keys exist.
237 * @param {Mixed} selection Key or array of keys to check
238 * @return {boolean} True if the key(s) exist
240 exists: function ( selection
) {
242 if ( Array
.isArray( selection
) ) {
243 for ( i
= 0; i
< selection
.length
; i
++ ) {
244 if ( typeof selection
[ i
] !== 'string' || !( selection
[ i
] in this.values
) ) {
250 return typeof selection
=== 'string' && selection
in this.values
;
256 log
= ( function () {
258 * Write a verbose message to the browser's console in debug mode.
260 * This method is mainly intended for verbose logging. It is a no-op in production mode.
261 * In ResourceLoader debug mode, it will use the browser's console if available, with
262 * fallback to creating a console interface in the DOM and logging messages there.
264 * See {@link mw.log} for other logging methods.
267 * @param {...string} msg Messages to output to console.
269 var log = function () {},
270 console
= window
.console
;
272 // Note: Keep list of methods in sync with restoration in mediawiki.log.js
273 // when adding or removing mw.log methods below!
276 * Collection of methods to help log messages to the console.
283 * Write a message to the browser console's warning channel.
285 * This method is a no-op in browsers that don't implement the Console API.
287 * @param {...string} msg Messages to output to console
289 log
.warn
= console
&& console
.warn
?
290 Function
.prototype.bind
.call( console
.warn
, console
) :
294 * Write a message to the browser console's error channel.
296 * Most browsers also print a stacktrace when calling this method if the
297 * argument is an Error object.
299 * This method is a no-op in browsers that don't implement the Console API.
302 * @param {...Mixed} msg Messages to output to console
304 log
.error
= console
&& console
.error
?
305 Function
.prototype.bind
.call( console
.error
, console
) :
309 * Create a property on a host object that, when accessed, will produce
310 * a deprecation warning in the console.
312 * @param {Object} obj Host object of deprecated property
313 * @param {string} key Name of property to create in `obj`
314 * @param {Mixed} val The value this property should return when accessed
315 * @param {string} [msg] Optional text to include in the deprecation message
316 * @param {string} [logName=key] Optional custom name for the feature.
317 * This is used instead of `key` in the message and `mw.deprecate` tracking.
319 log
.deprecate = function ( obj
, key
, val
, msg
, logName
) {
321 function maybeLog() {
323 trace
= new Error().stack
;
325 stacks
= new StringSet();
327 if ( !stacks
.has( trace
) ) {
329 name
= logName
|| key
;
330 mw
.track( 'mw.deprecate', name
);
332 'Use of "' + name
+ '" is deprecated.' + ( msg
? ( ' ' + msg
) : '' )
336 // Support: Safari 5.0
337 // Throws "not supported on DOM Objects" for Node or Element objects (incl. document)
338 // Safari 4.0 doesn't have this method, and it was fixed in Safari 5.1.
340 Object
.defineProperty( obj
, key
, {
347 set: function ( newVal
) {
364 redefineFallbacksForTest: function () {
365 if ( !window
.QUnit
) {
366 throw new Error( 'Reset not allowed outside unit tests' );
372 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
374 * On browsers that implement the Navigation Timing API, this function will produce
375 * floating-point values with microsecond precision that are guaranteed to be monotonic.
376 * On all other browsers, it will fall back to using `Date`.
378 * @return {number} Current time
381 // Optimisation: Define the shortcut on first call, not at module definition.
382 var perf
= window
.performance
,
383 navStart
= perf
&& perf
.timing
&& perf
.timing
.navigationStart
;
385 // Define the relevant shortcut
386 mw
.now
= navStart
&& typeof perf
.now
=== 'function' ?
387 function () { return navStart
+ perf
.now(); } :
394 * List of all analytic events emitted so far.
399 trackQueue
: trackQueue
,
401 track: function ( topic
, data
) {
402 trackQueue
.push( { topic
: topic
, timeStamp
: mw
.now(), data
: data
} );
403 // The base module extends this method to fire events here
407 * Track an early error event via mw.track and send it to the window console.
410 * @param {string} topic Topic name
411 * @param {Object} data Data describing the event, encoded as an object; see mw#logError
413 trackError: function ( topic
, data
) {
414 mw
.track( topic
, data
);
415 logError( topic
, data
);
418 // Expose Map constructor
422 * Map of configuration values.
424 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
427 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
428 * global `window` object.
430 * @property {mw.Map} config
432 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
436 * Empty object for third-party libraries, for cases where you don't
437 * want to add a new global, or the global is bad and needs containment
445 * Access container for deprecated functionality that can be moved from
446 * from their legacy location and attached to this object (e.g. a global
447 * function that is deprecated and as stop-gap can be exposed through here).
449 * This was reserved for future use but never ended up being used.
451 * @deprecated since 1.22 Let deprecated identifiers keep their original name
452 * and use mw.log#deprecate to create an access container for tracking.
458 * Store for messages.
465 * Store for templates associated with a module.
469 templates
: new Map(),
475 * Client for ResourceLoader server end point.
477 * This client is in charge of maintaining the module registry and state
478 * machine, initiating network (batch) requests for loading modules, as
479 * well as dependency resolution and execution of source code.
481 * For more information, refer to
482 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
487 loader
: ( function () {
490 * Fired via mw.track on various resource loading errors.
492 * @event resourceloader_exception
493 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
494 * object, but in theory module code could manually throw something else, and that
495 * might also end up here.
496 * @param {string} [module] Name of the module which caused the error. Omitted if the
497 * error is not module-related or the module cannot be easily identified due to
499 * @param {string} source Source of the error. Possible values:
501 * - style: stylesheet error (only affects old IE where a special style loading method
503 * - load-callback: exception thrown by user callback
504 * - module-execute: exception thrown by module code
505 * - resolve: failed to sort dependencies for a module in mw.loader.load
506 * - store-eval: could not evaluate module code cached in localStorage
507 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
508 * - store-localstorage-json: JSON conversion error in mw.loader.store
509 * - store-localstorage-update: localStorage conversion error in mw.loader.store.
513 * Fired via mw.track on resource loading error conditions.
515 * @event resourceloader_assert
516 * @param {string} source Source of the error. Possible values:
518 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
519 * bug; see <https://phabricator.wikimedia.org/T59567> for details
523 * Mapping of registered modules.
525 * See #implement and #execute for exact details on support for script, style and messages.
531 * // From mw.loader.register()
532 * 'version': '########' (hash)
533 * 'dependencies': ['required.foo', 'bar.also', ...]
534 * 'group': 'somegroup', (or) null
535 * 'source': 'local', (or) 'anotherwiki'
536 * 'skip': 'return !!window.Example', (or) null
537 * 'module': export Object
539 * // Set from execute() or mw.loader.state()
540 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
542 * // Optionally added at run-time by mw.loader.implement()
544 * 'script': closure, array of urls, or string
545 * 'style': { ... } (see #execute)
546 * 'messages': { 'key': 'value', ... }
553 * The module is known to the system but not yet required.
554 * Meta data is registered via mw.loader#register. Calls to that method are
555 * generated server-side by the startup module.
557 * The module was required through mw.loader (either directly or as dependency of
558 * another module). The client will fetch module contents from the server.
559 * The contents are then stashed in the registry via mw.loader#implement.
561 * The module has been loaded from the server and stashed via mw.loader#implement.
562 * Once the module has no more dependencies in-flight, the module will be executed,
563 * controlled via #requestPropagation and #doPropagation.
565 * The module is being executed.
567 * The module has been successfully executed.
569 * The module (or one of its dependencies) produced an error during execution.
571 * The module was registered client-side and requested, but the server denied knowledge
572 * of the module's existence.
577 var registry
= Object
.create( null ),
578 // Mapping of sources, keyed by source-id, values are strings.
583 // 'sourceId': 'http://example.org/w/load.php'
586 sources
= Object
.create( null ),
588 // For queueModuleScript()
589 handlingPendingRequests
= false,
590 pendingRequests
= [],
592 // List of modules to be loaded
596 * List of callback jobs waiting for modules to be ready.
598 * Jobs are created by #enqueue() and run by #doPropagation().
599 * Typically when a job is created for a module, the job's dependencies contain
600 * both the required module and all its recursive dependencies.
605 * 'dependencies': [ module names ],
606 * 'ready': Function callback
607 * 'error': Function callback
610 * @property {Object[]} jobs
615 // For #requestPropagation() and #doPropagation()
616 willPropagate
= false,
621 * @property {Array} baseModules
623 baseModules
= $VARS
.baseModules
,
626 * For #addEmbeddedCSS() and #addLink()
629 * @property {HTMLElement|null} marker
631 marker
= document
.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' ),
633 // For #addEmbeddedCSS()
635 rAF
= window
.requestAnimationFrame
|| setTimeout
;
638 * Create a new style element and add it to the DOM.
641 * @param {string} text CSS text
642 * @param {Node|null} [nextNode] The element where the style tag
643 * should be inserted before
644 * @return {HTMLElement} Reference to the created style element
646 function newStyleTag( text
, nextNode
) {
647 var el
= document
.createElement( 'style' );
648 el
.appendChild( document
.createTextNode( text
) );
649 if ( nextNode
&& nextNode
.parentNode
) {
650 nextNode
.parentNode
.insertBefore( el
, nextNode
);
652 document
.head
.appendChild( el
);
659 * @param {Object} cssBuffer
661 function flushCssBuffer( cssBuffer
) {
663 // Mark this object as inactive now so that further calls to addEmbeddedCSS() from
664 // the callbacks go to a new buffer instead of this one (T105973)
665 cssBuffer
.active
= false;
666 newStyleTag( cssBuffer
.cssText
, marker
);
667 for ( i
= 0; i
< cssBuffer
.callbacks
.length
; i
++ ) {
668 cssBuffer
.callbacks
[ i
]();
673 * Add a bit of CSS text to the current browser page.
675 * The creation and insertion of the `<style>` element is debounced for two reasons:
677 * - Performing the insertion before the next paint round via requestAnimationFrame
678 * avoids forced or wasted style recomputations, which are expensive in browsers.
679 * - Reduce how often new stylesheets are inserted by letting additional calls to this
680 * function accumulate into a buffer for at least one JavaScript tick. Modules are
681 * received from the server in batches, which means there is likely going to be many
682 * calls to this function in a row within the same tick / the same call stack.
686 * @param {string} cssText CSS text to be added in a `<style>` tag.
687 * @param {Function} callback Called after the insertion has occurred
689 function addEmbeddedCSS( cssText
, callback
) {
690 // Create a buffer if:
691 // - We don't have one yet.
692 // - The previous one is closed.
693 // - The next CSS chunk syntactically needs to be at the start of a stylesheet (T37562).
694 if ( !nextCssBuffer
|| nextCssBuffer
.active
=== false || cssText
.slice( 0, '@import'.length
) === '@import' ) {
702 // Linebreak for somewhat distinguishable sections
703 nextCssBuffer
.cssText
+= '\n' + cssText
;
704 nextCssBuffer
.callbacks
.push( callback
);
706 if ( nextCssBuffer
.active
=== null ) {
707 nextCssBuffer
.active
= true;
708 // The flushCssBuffer callback has its parameter bound by reference, which means
709 // 1) We can still extend the buffer from our object reference after this point.
710 // 2) We can safely re-assign the variable (not the object) to start a new buffer.
711 rAF( flushCssBuffer
.bind( null, nextCssBuffer
) );
717 * @param {Array} modules List of module names
718 * @return {string} Hash of concatenated version hashes.
720 function getCombinedVersion( modules
) {
721 var hashes
= modules
.reduce( function ( result
, module
) {
722 return result
+ registry
[ module
].version
;
724 return fnv132( hashes
);
728 * Determine whether all dependencies are in state 'ready', which means we may
729 * execute the module or job now.
732 * @param {Array} modules Names of modules to be checked
733 * @return {boolean} True if all modules are in state 'ready', false otherwise
735 function allReady( modules
) {
737 for ( i
= 0; i
< modules
.length
; i
++ ) {
738 if ( mw
.loader
.getState( modules
[ i
] ) !== 'ready' ) {
746 * Determine whether all direct and base dependencies are in state 'ready'
749 * @param {string} module Name of the module to be checked
750 * @return {boolean} True if all direct/base dependencies are in state 'ready'; false otherwise
752 function allWithImplicitReady( module
) {
753 return allReady( registry
[ module
].dependencies
) &&
754 ( baseModules
.indexOf( module
) !== -1 || allReady( baseModules
) );
758 * Determine whether all dependencies are in state 'ready', which means we may
759 * execute the module or job now.
762 * @param {Array} modules Names of modules to be checked
763 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
765 function anyFailed( modules
) {
767 for ( i
= 0; i
< modules
.length
; i
++ ) {
768 state
= mw
.loader
.getState( modules
[ i
] );
769 if ( state
=== 'error' || state
=== 'missing' ) {
777 * Handle propagation of module state changes and reactions to them.
779 * - When a module reaches a failure state, this should be propagated to
780 * modules that depend on the failed module.
781 * - When a module reaches a final state, pending job callbacks for the
782 * module from mw.loader.using() should be called.
783 * - When a module reaches the 'ready' state from #execute(), consider
784 * executing dependant modules now having their dependencies satisfied.
785 * - When a module reaches the 'loaded' state from mw.loader.implement,
786 * consider executing it, if it has no unsatisfied dependencies.
790 function doPropagation() {
791 var errorModule
, baseModuleError
, module
, i
, failed
, job
,
794 // Keep going until the last iteration performed no actions.
796 didPropagate
= false;
798 // Stage 1: Propagate failures
799 while ( errorModules
.length
) {
800 errorModule
= errorModules
.shift();
801 baseModuleError
= baseModules
.indexOf( errorModule
) !== -1;
802 for ( module
in registry
) {
803 if ( registry
[ module
].state
!== 'error' && registry
[ module
].state
!== 'missing' ) {
804 if ( baseModuleError
&& baseModules
.indexOf( module
) === -1 ) {
805 // Propate error from base module to all regular (non-base) modules
806 registry
[ module
].state
= 'error';
808 } else if ( registry
[ module
].dependencies
.indexOf( errorModule
) !== -1 ) {
809 // Propagate error from dependency to depending module
810 registry
[ module
].state
= 'error';
811 // .. and propagate it further
812 errorModules
.push( module
);
819 // Stage 2: Execute 'loaded' modules with no unsatisfied dependencies
820 for ( module
in registry
) {
821 if ( registry
[ module
].state
=== 'loaded' && allWithImplicitReady( module
) ) {
822 // Recursively execute all dependent modules that were already loaded
823 // (waiting for execution) and no longer have unsatisfied dependencies.
824 // Base modules may have dependencies amongst eachother to ensure correct
825 // execution order. Regular modules wait for all base modules.
826 // eslint-disable-next-line no-use-before-define
832 // Stage 3: Invoke job callbacks that are no longer blocked
833 for ( i
= 0; i
< jobs
.length
; i
++ ) {
835 failed
= anyFailed( job
.dependencies
);
836 if ( failed
|| allReady( job
.dependencies
) ) {
840 if ( failed
&& job
.error
) {
841 job
.error( new Error( 'Module has failed dependencies' ), job
.dependencies
);
842 } else if ( !failed
&& job
.ready
) {
846 // A user-defined callback raised an exception.
847 // Swallow it to protect our state machine!
848 mw
.trackError( 'resourceloader.exception', {
850 source
: 'load-callback'
856 } while ( didPropagate
);
858 willPropagate
= false;
862 * Request a (debounced) call to doPropagation().
866 function requestPropagation() {
867 if ( willPropagate
) {
868 // Already scheduled, or, we're already in a doPropagation stack.
871 willPropagate
= true;
872 // Yield for two reasons:
873 // * Allow successive calls to mw.loader.implement() from the same
874 // load.php response, or from the same asyncEval() to be in the
875 // propagation batch.
876 // * Allow the browser to breathe between the reception of
877 // module source code and the execution of it.
879 // Use a high priority because the user may be waiting for interactions
880 // to start being possible. But, first provide a moment (up to 'timeout')
881 // for native input event handling (e.g. scrolling/typing/clicking).
882 mw
.requestIdleCallback( doPropagation
, { timeout
: 1 } );
886 * Update a module's state in the registry and make sure any neccesary
887 * propagation will occur. See #doPropagation for more about propagation.
888 * See #registry for more about how states are used.
891 * @param {string} module
892 * @param {string} state
894 function setAndPropagate( module
, state
) {
895 registry
[ module
].state
= state
;
896 if ( state
=== 'loaded' || state
=== 'ready' || state
=== 'error' || state
=== 'missing' ) {
897 if ( state
=== 'ready' ) {
898 // Queue to later be synced to the local module store.
899 mw
.loader
.store
.add( module
);
900 } else if ( state
=== 'error' || state
=== 'missing' ) {
901 errorModules
.push( module
);
903 requestPropagation();
908 * Resolve dependencies and detect circular references.
911 * @param {string} module Name of the top-level module whose dependencies shall be
912 * resolved and sorted.
913 * @param {Array} resolved Returns a topological sort of the given module and its
914 * dependencies, such that later modules depend on earlier modules. The array
915 * contains the module names. If the array contains already some module names,
916 * this function appends its result to the pre-existing array.
917 * @param {StringSet} [unresolved] Used to track the current dependency
918 * chain, and to report loops in the dependency graph.
919 * @throws {Error} If any unregistered module or a dependency loop is encountered
921 function sortDependencies( module
, resolved
, unresolved
) {
924 if ( !( module
in registry
) ) {
925 throw new Error( 'Unknown dependency: ' + module
);
928 if ( registry
[ module
].skip
!== null ) {
929 // eslint-disable-next-line no-new-func
930 skip
= new Function( registry
[ module
].skip
);
931 registry
[ module
].skip
= null;
933 registry
[ module
].skipped
= true;
934 registry
[ module
].dependencies
= [];
935 setAndPropagate( module
, 'ready' );
940 if ( resolved
.indexOf( module
) !== -1 ) {
941 // Module already resolved; nothing to do
944 // Create unresolved if not passed in
946 unresolved
= new StringSet();
950 if ( baseModules
.indexOf( module
) === -1 ) {
951 baseModules
.forEach( function ( baseModule
) {
952 if ( resolved
.indexOf( baseModule
) === -1 ) {
953 resolved
.push( baseModule
);
958 // Tracks down dependencies
959 deps
= registry
[ module
].dependencies
;
960 unresolved
.add( module
);
961 for ( i
= 0; i
< deps
.length
; i
++ ) {
962 if ( resolved
.indexOf( deps
[ i
] ) === -1 ) {
963 if ( unresolved
.has( deps
[ i
] ) ) {
965 'Circular reference detected: ' + module
+ ' -> ' + deps
[ i
]
969 sortDependencies( deps
[ i
], resolved
, unresolved
);
972 resolved
.push( module
);
976 * Get names of module that a module depends on, in their proper dependency order.
979 * @param {string[]} modules Array of string module names
980 * @return {Array} List of dependencies, including 'module'.
981 * @throws {Error} If an unregistered module or a dependency loop is encountered
983 function resolve( modules
) {
984 var i
, resolved
= [];
985 for ( i
= 0; i
< modules
.length
; i
++ ) {
986 sortDependencies( modules
[ i
], resolved
);
992 * Like #resolve(), except it will silently ignore modules that
993 * are missing or have missing dependencies.
996 * @param {string[]} modules Array of string module names
997 * @return {Array} List of dependencies.
999 function resolveStubbornly( modules
) {
1000 var i
, saved
, resolved
= [];
1001 for ( i
= 0; i
< modules
.length
; i
++ ) {
1002 saved
= resolved
.slice();
1004 sortDependencies( modules
[ i
], resolved
);
1006 // This module is unknown or has unknown dependencies.
1007 // Undo any incomplete resolutions made and keep going.
1009 mw
.trackError( 'resourceloader.exception', {
1019 * Load and execute a script.
1022 * @param {string} src URL to script, will be used as the src attribute in the script tag
1023 * @param {Function} [callback] Callback to run after request resolution
1025 function addScript( src
, callback
) {
1026 var script
= document
.createElement( 'script' );
1028 script
.onload
= script
.onerror = function () {
1029 if ( script
.parentNode
) {
1030 script
.parentNode
.removeChild( script
);
1038 document
.head
.appendChild( script
);
1042 * Queue the loading and execution of a script for a particular module.
1044 * This does for debug mode what runScript() does for production.
1047 * @param {string} src URL of the script
1048 * @param {string} moduleName Name of currently executing module
1049 * @param {Function} callback Callback to run after addScript() resolution
1051 function queueModuleScript( src
, moduleName
, callback
) {
1052 pendingRequests
.push( function () {
1053 // Keep in sync with execute()/runScript().
1054 if ( moduleName
!== 'jquery' ) {
1055 window
.require
= mw
.loader
.require
;
1056 window
.module
= registry
[ moduleName
].module
;
1058 addScript( src
, function () {
1059 // 'module.exports' should not persist after the file is executed to
1060 // avoid leakage to unrelated code. 'require' should be kept, however,
1061 // as asynchronous access to 'require' is allowed and expected. (T144879)
1062 delete window
.module
;
1064 // Start the next one (if any)
1065 if ( pendingRequests
[ 0 ] ) {
1066 pendingRequests
.shift()();
1068 handlingPendingRequests
= false;
1072 if ( !handlingPendingRequests
&& pendingRequests
[ 0 ] ) {
1073 handlingPendingRequests
= true;
1074 pendingRequests
.shift()();
1079 * Utility function for execute()
1082 * @param {string} [media] Media attribute
1083 * @param {string} url URL
1085 function addLink( media
, url
) {
1086 var el
= document
.createElement( 'link' );
1088 el
.rel
= 'stylesheet';
1089 if ( media
&& media
!== 'all' ) {
1092 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1093 // see #addEmbeddedCSS, T33676, T43331, and T49277 for details.
1096 if ( marker
&& marker
.parentNode
) {
1097 marker
.parentNode
.insertBefore( el
, marker
);
1099 document
.head
.appendChild( el
);
1105 * @param {string} code JavaScript code
1107 function domEval( code
) {
1108 var script
= document
.createElement( 'script' );
1109 if ( mw
.config
.get( 'wgCSPNonce' ) !== false ) {
1110 script
.nonce
= mw
.config
.get( 'wgCSPNonce' );
1113 document
.head
.appendChild( script
);
1114 script
.parentNode
.removeChild( script
);
1118 * Add one or more modules to the module load queue.
1123 * @param {string[]} dependencies Array of module names in the registry
1124 * @param {Function} [ready] Callback to execute when all dependencies are ready
1125 * @param {Function} [error] Callback to execute when any dependency fails
1127 function enqueue( dependencies
, ready
, error
) {
1128 if ( allReady( dependencies
) ) {
1129 // Run ready immediately
1130 if ( ready
!== undefined ) {
1136 if ( anyFailed( dependencies
) ) {
1137 if ( error
!== undefined ) {
1138 // Execute error immediately if any dependencies have errors
1140 new Error( 'One or more dependencies failed to load' ),
1147 // Not all dependencies are ready, add to the load queue...
1149 // Add ready and error callbacks if they were given
1150 if ( ready
!== undefined || error
!== undefined ) {
1152 // Narrow down the list to modules that are worth waiting for
1153 dependencies
: dependencies
.filter( function ( module
) {
1154 var state
= registry
[ module
].state
;
1155 return state
=== 'registered' || state
=== 'loaded' || state
=== 'loading' || state
=== 'executing';
1162 dependencies
.forEach( function ( module
) {
1163 // Only queue modules that are still in the initial 'registered' state
1164 // (not ones already loading, ready or error).
1165 if ( registry
[ module
].state
=== 'registered' && queue
.indexOf( module
) === -1 ) {
1166 // Private modules must be embedded in the page. Don't bother queuing
1167 // these as the server will deny them anyway (T101806).
1168 if ( registry
[ module
].group
=== 'private' ) {
1169 setAndPropagate( module
, 'error' );
1172 queue
.push( module
);
1180 * Executes a loaded module, making it ready to use
1183 * @param {string} module Module name to execute
1185 function execute( module
) {
1186 var key
, value
, media
, i
, urls
, cssHandle
, siteDeps
, siteDepErr
, runScript
,
1189 if ( registry
[ module
].state
!== 'loaded' ) {
1190 throw new Error( 'Module in state "' + registry
[ module
].state
+ '" may not be executed: ' + module
);
1193 registry
[ module
].state
= 'executing';
1194 $CODE
.profileExecuteStart();
1196 runScript = function () {
1197 var script
, markModuleReady
, nestedAddScript
;
1199 $CODE
.profileScriptStart();
1200 script
= registry
[ module
].script
;
1201 markModuleReady = function () {
1202 $CODE
.profileScriptEnd();
1203 setAndPropagate( module
, 'ready' );
1205 nestedAddScript = function ( arr
, callback
, i
) {
1206 // Recursively call queueModuleScript() in its own callback
1207 // for each element of arr.
1208 if ( i
>= arr
.length
) {
1209 // We're at the end of the array
1214 queueModuleScript( arr
[ i
], module
, function () {
1215 nestedAddScript( arr
, callback
, i
+ 1 );
1220 if ( Array
.isArray( script
) ) {
1221 nestedAddScript( script
, markModuleReady
, 0 );
1222 } else if ( typeof script
=== 'function' ) {
1223 // Keep in sync with queueModuleScript() for debug mode
1224 if ( module
=== 'jquery' ) {
1225 // This is a special case for when 'jquery' itself is being loaded.
1226 // - The standard jquery.js distribution does not set `window.jQuery`
1227 // in CommonJS-compatible environments (Node.js, AMD, RequireJS, etc.).
1228 // - MediaWiki's 'jquery' module also bundles jquery.migrate.js, which
1229 // in a CommonJS-compatible environment, will use require('jquery'),
1230 // but that can't work when we're still inside that module.
1233 // Pass jQuery twice so that the signature of the closure which wraps
1234 // the script can bind both '$' and 'jQuery'.
1235 script( window
.$, window
.$, mw
.loader
.require
, registry
[ module
].module
);
1239 } else if ( typeof script
=== 'string' ) {
1240 // Site and user modules are legacy scripts that run in the global scope.
1241 // This is transported as a string instead of a function to avoid needing
1242 // to use string manipulation to undo the function wrapper.
1247 // Module without script
1251 // Use mw.track instead of mw.log because these errors are common in production mode
1252 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1253 setAndPropagate( module
, 'error' );
1254 $CODE
.profileScriptEnd();
1255 mw
.trackError( 'resourceloader.exception', {
1258 source
: 'module-execute'
1263 // Add localizations to message system
1264 if ( registry
[ module
].messages
) {
1265 mw
.messages
.set( registry
[ module
].messages
);
1268 // Initialise templates
1269 if ( registry
[ module
].templates
) {
1270 mw
.templates
.set( module
, registry
[ module
].templates
);
1273 // Adding of stylesheets is asynchronous via addEmbeddedCSS().
1274 // The below function uses a counting semaphore to make sure we don't call
1275 // runScript() until after this module's stylesheets have been inserted
1277 cssHandle = function () {
1278 // Increase semaphore, when creating a callback for addEmbeddedCSS.
1280 return function () {
1282 // Decrease semaphore, when said callback is invoked.
1284 if ( cssPending
=== 0 ) {
1286 // This callback is exposed to addEmbeddedCSS, which is outside the execute()
1287 // function and is not concerned with state-machine integrity. In turn,
1288 // addEmbeddedCSS() actually exposes stuff further into the browser (rAF).
1289 // If increment and decrement callbacks happen in the wrong order, or start
1290 // again afterwards, then this branch could be reached multiple times.
1291 // To protect the integrity of the state-machine, prevent that from happening
1292 // by making runScript() cannot be called more than once. We store a private
1293 // reference when we first reach this branch, then deference the original, and
1294 // call our reference to it.
1295 runScriptCopy
= runScript
;
1296 runScript
= undefined;
1302 // Process styles (see also mw.loader.implement)
1303 // * back-compat: { <media>: css }
1304 // * back-compat: { <media>: [url, ..] }
1305 // * { "css": [css, ..] }
1306 // * { "url": { <media>: [url, ..] } }
1307 if ( registry
[ module
].style
) {
1308 for ( key
in registry
[ module
].style
) {
1309 value
= registry
[ module
].style
[ key
];
1312 if ( key
!== 'url' && key
!== 'css' ) {
1313 // Backwards compatibility, key is a media-type
1314 if ( typeof value
=== 'string' ) {
1315 // back-compat: { <media>: css }
1316 // Ignore 'media' because it isn't supported (nor was it used).
1317 // Strings are pre-wrapped in "@media". The media-type was just ""
1318 // (because it had to be set to something).
1319 // This is one of the reasons why this format is no longer used.
1320 addEmbeddedCSS( value
, cssHandle() );
1322 // back-compat: { <media>: [url, ..] }
1328 // Array of css strings in key 'css',
1329 // or back-compat array of urls from media-type
1330 if ( Array
.isArray( value
) ) {
1331 for ( i
= 0; i
< value
.length
; i
++ ) {
1332 if ( key
=== 'bc-url' ) {
1333 // back-compat: { <media>: [url, ..] }
1334 addLink( media
, value
[ i
] );
1335 } else if ( key
=== 'css' ) {
1336 // { "css": [css, ..] }
1337 addEmbeddedCSS( value
[ i
], cssHandle() );
1340 // Not an array, but a regular object
1341 // Array of urls inside media-type key
1342 } else if ( typeof value
=== 'object' ) {
1343 // { "url": { <media>: [url, ..] } }
1344 for ( media
in value
) {
1345 urls
= value
[ media
];
1346 for ( i
= 0; i
< urls
.length
; i
++ ) {
1347 addLink( media
, urls
[ i
] );
1354 // End profiling of execute()-self before we call runScript(),
1355 // which we want to measure separately without overlap.
1356 $CODE
.profileExecuteEnd();
1358 if ( module
=== 'user' ) {
1359 // Implicit dependency on the site module. Not a real dependency because it should
1360 // run after 'site' regardless of whether it succeeds or fails.
1361 // Note: This is a simplified version of mw.loader.using(), inlined here because
1362 // mw.loader.using() is part of mediawiki.base (depends on jQuery; T192623).
1364 siteDeps
= resolve( [ 'site' ] );
1369 if ( siteDepErr
=== undefined ) {
1370 enqueue( siteDeps
, runScript
, runScript
);
1372 } else if ( cssPending
=== 0 ) {
1373 // Regular module without styles
1376 // else: runScript will get called via cssHandle()
1379 function sortQuery( o
) {
1388 for ( key
= 0; key
< a
.length
; key
++ ) {
1389 sorted
[ a
[ key
] ] = o
[ a
[ key
] ];
1395 * Converts a module map of the form `{ foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }`
1396 * to a query string of the form `foo.bar,baz|bar.baz,quux`.
1398 * See `ResourceLoader::makePackedModulesString()` in PHP, of which this is a port.
1399 * On the server, unpacking is done by `ResourceLoaderContext::expandModuleNames()`.
1401 * Note: This is only half of the logic, the other half has to be in #batchRequest(),
1402 * because its implementation needs to keep track of potential string size in order
1403 * to decide when to split the requests due to url size.
1406 * @param {Object} moduleMap Module map
1408 * @return {string} return.str Module query string
1409 * @return {Array} return.list List of module names in matching order
1411 function buildModulesString( moduleMap
) {
1416 function restore( suffix
) {
1420 for ( prefix
in moduleMap
) {
1421 p
= prefix
=== '' ? '' : prefix
+ '.';
1422 str
.push( p
+ moduleMap
[ prefix
].join( ',' ) );
1423 list
.push
.apply( list
, moduleMap
[ prefix
].map( restore
) );
1426 str
: str
.join( '|' ),
1432 * Resolve indexed dependencies.
1434 * ResourceLoader uses an optimisation to save space which replaces module names in
1435 * dependency lists with the index of that module within the array of module
1436 * registration data if it exists. The benefit is a significant reduction in the data
1437 * size of the startup module. This function changes those dependency lists back to
1438 * arrays of strings.
1441 * @param {Array} modules Modules array
1443 function resolveIndexedDependencies( modules
) {
1445 function resolveIndex( dep
) {
1446 return typeof dep
=== 'number' ? modules
[ dep
][ 0 ] : dep
;
1448 for ( i
= 0; i
< modules
.length
; i
++ ) {
1449 deps
= modules
[ i
][ 2 ];
1451 for ( j
= 0; j
< deps
.length
; j
++ ) {
1452 deps
[ j
] = resolveIndex( deps
[ j
] );
1460 * @param {Object} params Map of parameter names to values
1463 function makeQueryString( params
) {
1464 return Object
.keys( params
).map( function ( key
) {
1465 return encodeURIComponent( key
) + '=' + encodeURIComponent( params
[ key
] );
1470 * Create network requests for a batch of modules.
1472 * This is an internal method for #work(). This must not be called directly
1473 * unless the modules are already registered, and no request is in progress,
1474 * and the module state has already been set to `loading`.
1477 * @param {string[]} batch
1479 function batchRequest( batch
) {
1480 var reqBase
, splits
, maxQueryLength
, b
, bSource
, bGroup
,
1481 source
, group
, i
, modules
, sourceLoadScript
,
1482 currReqBase
, currReqBaseLength
, moduleMap
, currReqModules
, l
,
1483 lastDotIndex
, prefix
, suffix
, bytesAdded
;
1486 * Start the currently drafted request to the server.
1490 function doRequest() {
1491 // Optimisation: Inherit (Object.create), not copy ($.extend)
1492 var query
= Object
.create( currReqBase
),
1493 packed
= buildModulesString( moduleMap
);
1494 query
.modules
= packed
.str
;
1495 // The packing logic can change the effective order, even if the input was
1496 // sorted. As such, the call to getCombinedVersion() must use this
1497 // effective order, instead of currReqModules, as otherwise the combined
1498 // version will not match the hash expected by the server based on
1499 // combining versions from the module query string in-order. (T188076)
1500 query
.version
= getCombinedVersion( packed
.list
);
1501 query
= sortQuery( query
);
1502 addScript( sourceLoadScript
+ '?' + makeQueryString( query
) );
1505 if ( !batch
.length
) {
1509 // Always order modules alphabetically to help reduce cache
1510 // misses for otherwise identical content.
1513 // Query parameters common to all requests
1515 skin
: mw
.config
.get( 'skin' ),
1516 lang
: mw
.config
.get( 'wgUserLanguage' ),
1517 debug
: mw
.config
.get( 'debug' )
1519 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1521 // Split module list by source and by group.
1522 splits
= Object
.create( null );
1523 for ( b
= 0; b
< batch
.length
; b
++ ) {
1524 bSource
= registry
[ batch
[ b
] ].source
;
1525 bGroup
= registry
[ batch
[ b
] ].group
;
1526 if ( !splits
[ bSource
] ) {
1527 splits
[ bSource
] = Object
.create( null );
1529 if ( !splits
[ bSource
][ bGroup
] ) {
1530 splits
[ bSource
][ bGroup
] = [];
1532 splits
[ bSource
][ bGroup
].push( batch
[ b
] );
1535 for ( source
in splits
) {
1536 sourceLoadScript
= sources
[ source
];
1538 for ( group
in splits
[ source
] ) {
1540 // Cache access to currently selected list of
1541 // modules for this group from this source.
1542 modules
= splits
[ source
][ group
];
1544 // Query parameters common to requests for this module group
1545 // Optimisation: Inherit (Object.create), not copy ($.extend)
1546 currReqBase
= Object
.create( reqBase
);
1547 // User modules require a user name in the query string.
1548 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1549 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1552 // In addition to currReqBase, doRequest() will also add 'modules' and 'version'.
1553 // > '&modules='.length === 9
1554 // > '&version=1234567'.length === 16
1556 currReqBaseLength
= makeQueryString( currReqBase
).length
+ 25;
1558 // We may need to split up the request to honor the query string length limit,
1559 // so build it piece by piece.
1560 l
= currReqBaseLength
;
1561 moduleMap
= Object
.create( null ); // { prefix: [ suffixes ] }
1562 currReqModules
= [];
1564 for ( i
= 0; i
< modules
.length
; i
++ ) {
1565 // Determine how many bytes this module would add to the query string
1566 lastDotIndex
= modules
[ i
].lastIndexOf( '.' );
1567 // If lastDotIndex is -1, substr() returns an empty string
1568 prefix
= modules
[ i
].substr( 0, lastDotIndex
);
1569 suffix
= modules
[ i
].slice( lastDotIndex
+ 1 );
1570 bytesAdded
= moduleMap
[ prefix
] ?
1571 suffix
.length
+ 3 : // '%2C'.length == 3
1572 modules
[ i
].length
+ 3; // '%7C'.length == 3
1574 // If the url would become too long, create a new one, but don't create empty requests
1575 if ( maxQueryLength
> 0 && currReqModules
.length
&& l
+ bytesAdded
> maxQueryLength
) {
1576 // Dispatch what we've got...
1578 // .. and start again.
1579 l
= currReqBaseLength
;
1580 moduleMap
= Object
.create( null );
1581 currReqModules
= [];
1583 mw
.track( 'resourceloader.splitRequest', { maxQueryLength
: maxQueryLength
} );
1585 if ( !moduleMap
[ prefix
] ) {
1586 moduleMap
[ prefix
] = [];
1589 moduleMap
[ prefix
].push( suffix
);
1590 currReqModules
.push( modules
[ i
] );
1592 // If there's anything left in moduleMap, request that too
1593 if ( currReqModules
.length
) {
1602 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1603 * form of calls to mw.loader#implement().
1604 * @param {Function} cb Callback in case of failure
1605 * @param {Error} cb.err
1607 function asyncEval( implementations
, cb
) {
1608 if ( !implementations
.length
) {
1611 mw
.requestIdleCallback( function () {
1613 domEval( implementations
.join( ';' ) );
1621 * Make a versioned key for a specific module.
1624 * @param {string} module Module name
1625 * @return {string|null} Module key in format '`[name]@[version]`',
1626 * or null if the module does not exist
1628 function getModuleKey( module
) {
1629 return module
in registry
? ( module
+ '@' + registry
[ module
].version
) : null;
1634 * @param {string} key Module name or '`[name]@[version]`'
1637 function splitModuleKey( key
) {
1638 var index
= key
.indexOf( '@' );
1639 if ( index
=== -1 ) {
1646 name
: key
.slice( 0, index
),
1647 version
: key
.slice( index
+ 1 )
1653 * @param {string} module
1654 * @param {string|number} [version]
1655 * @param {string[]} [dependencies]
1656 * @param {string} [group]
1657 * @param {string} [source]
1658 * @param {string} [skip]
1660 function registerOne( module
, version
, dependencies
, group
, source
, skip
) {
1661 if ( module
in registry
) {
1662 throw new Error( 'module already registered: ' + module
);
1664 registry
[ module
] = {
1665 // Exposed to execute() for mw.loader.implement() closures.
1666 // Import happens via require().
1670 version
: String( version
|| '' ),
1671 dependencies
: dependencies
|| [],
1672 group
: typeof group
=== 'string' ? group
: null,
1673 source
: typeof source
=== 'string' ? source
: 'local',
1674 state
: 'registered',
1675 skip
: typeof skip
=== 'string' ? skip
: null
1679 /* Public Members */
1682 * The module registry is exposed as an aid for debugging and inspecting page
1683 * state; it is not a public interface for modifying the registry.
1689 moduleRegistry
: registry
,
1692 * @inheritdoc #newStyleTag
1695 addStyleTag
: newStyleTag
,
1702 * Start loading of all queued module dependencies.
1707 var q
, batch
, implementations
, sourceModules
;
1711 // Appends a list of modules from the queue to the batch
1712 for ( q
= 0; q
< queue
.length
; q
++ ) {
1713 // Only load modules which are registered
1714 if ( queue
[ q
] in registry
&& registry
[ queue
[ q
] ].state
=== 'registered' ) {
1715 // Prevent duplicate entries
1716 if ( batch
.indexOf( queue
[ q
] ) === -1 ) {
1717 batch
.push( queue
[ q
] );
1718 // Mark registered modules as loading
1719 registry
[ queue
[ q
] ].state
= 'loading';
1724 // Now that the queue has been processed into a batch, clear the queue.
1725 // This MUST happen before we initiate any eval or network request. Otherwise,
1726 // it is possible for a cached script to instantly trigger the same work queue
1727 // again; all before we've cleared it causing each request to include modules
1728 // which are already loaded.
1731 if ( !batch
.length
) {
1735 mw
.loader
.store
.init();
1736 if ( mw
.loader
.store
.enabled
) {
1737 implementations
= [];
1739 batch
= batch
.filter( function ( module
) {
1740 var implementation
= mw
.loader
.store
.get( module
);
1741 if ( implementation
) {
1742 implementations
.push( implementation
);
1743 sourceModules
.push( module
);
1748 asyncEval( implementations
, function ( err
) {
1750 // Not good, the cached mw.loader.implement calls failed! This should
1751 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1752 // Depending on how corrupt the string is, it is likely that some
1753 // modules' implement() succeeded while the ones after the error will
1754 // never run and leave their modules in the 'loading' state forever.
1755 mw
.loader
.store
.stats
.failed
++;
1757 // Since this is an error not caused by an individual module but by
1758 // something that infected the implement call itself, don't take any
1759 // risks and clear everything in this cache.
1760 mw
.loader
.store
.clear();
1762 mw
.trackError( 'resourceloader.exception', {
1764 source
: 'store-eval'
1766 // Re-add the failed ones that are still pending back to the batch
1767 failed
= sourceModules
.filter( function ( module
) {
1768 return registry
[ module
].state
=== 'loading';
1770 batchRequest( failed
);
1774 batchRequest( batch
);
1778 * Register a source.
1780 * The #work() method will use this information to split up requests by source.
1782 * mw.loader.addSource( { mediawikiwiki: 'https://www.mediawiki.org/w/load.php' } );
1785 * @param {Object} ids An object mapping ids to load.php end point urls
1786 * @throws {Error} If source id is already registered
1788 addSource: function ( ids
) {
1791 if ( id
in sources
) {
1792 throw new Error( 'source already registered: ' + id
);
1794 sources
[ id
] = ids
[ id
];
1799 * Register a module, letting the system know about it and its properties.
1801 * The startup module calls this method.
1803 * When using multiple module registration by passing an array, dependencies that
1804 * are specified as references to modules within the array will be resolved before
1805 * the modules are registered.
1807 * @param {string|Array} modules Module name or array of arrays, each containing
1808 * a list of arguments compatible with this method
1809 * @param {string|number} [version] Module version hash (falls backs to empty string)
1810 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1811 * @param {string[]} [dependencies] Array of module names on which this module depends.
1812 * @param {string} [group=null] Group which the module is in
1813 * @param {string} [source='local'] Name of the source
1814 * @param {string} [skip=null] Script body of the skip function
1816 register: function ( modules
) {
1818 if ( typeof modules
=== 'object' ) {
1819 resolveIndexedDependencies( modules
);
1820 // Optimisation: Up to 55% faster.
1821 // Typically called only once, and with a batch.
1822 // See <https://gist.github.com/Krinkle/f06fdb3de62824c6c16f02a0e6ce0e66>
1823 // Benchmarks taught us that the code for adding an object to `registry`
1824 // should actually be inline, or in a simple function that does no
1825 // arguments manipulation, and isn't also the caller itself.
1826 // JS semantics make it hard to optimise recursion to a different
1827 // signature of itself.
1828 for ( i
= 0; i
< modules
.length
; i
++ ) {
1829 registerOne
.apply( null, modules
[ i
] );
1832 registerOne
.apply( null, arguments
);
1837 * Implement a module given the components that make up the module.
1839 * When #load() or #using() requests one or more modules, the server
1840 * response contain calls to this function.
1842 * @param {string} module Name of module and current module version. Formatted
1843 * as '`[name]@[version]`". This version should match the requested version
1844 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1845 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1846 * @param {Function|Array|string} [script] Function with module code, list of URLs
1847 * to load via `<script src>`, or string of module code for `$.globalEval()`.
1848 * @param {Object} [style] Should follow one of the following patterns:
1850 * { "css": [css, ..] }
1851 * { "url": { <media>: [url, ..] } }
1853 * And for backwards compatibility (needs to be supported forever due to caching):
1856 * { <media>: [url, ..] }
1858 * The reason css strings are not concatenated anymore is T33676. We now check
1859 * whether it's safe to extend the stylesheet.
1862 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1863 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1865 implement: function ( module
, script
, style
, messages
, templates
) {
1866 var split
= splitModuleKey( module
),
1868 version
= split
.version
;
1869 // Automatically register module
1870 if ( !( name
in registry
) ) {
1871 mw
.loader
.register( name
);
1873 // Check for duplicate implementation
1874 if ( registry
[ name
].script
!== undefined ) {
1875 throw new Error( 'module already implemented: ' + name
);
1878 // Without this reset, if there is a version mismatch between the
1879 // requested and received module version, then mw.loader.store would
1880 // cache the response under the requested key. Thus poisoning the cache
1881 // indefinitely with a stale value. (T117587)
1882 registry
[ name
].version
= version
;
1884 // Attach components
1885 registry
[ name
].script
= script
|| null;
1886 registry
[ name
].style
= style
|| null;
1887 registry
[ name
].messages
= messages
|| null;
1888 registry
[ name
].templates
= templates
|| null;
1889 // The module may already have been marked as erroneous
1890 if ( registry
[ name
].state
!== 'error' && registry
[ name
].state
!== 'missing' ) {
1891 setAndPropagate( name
, 'loaded' );
1896 * Load an external script or one or more modules.
1898 * This method takes a list of unrelated modules. Use cases:
1900 * - A web page will be composed of many different widgets. These widgets independently
1901 * queue their ResourceLoader modules (`OutputPage::addModules()`). If any of them
1902 * have problems, or are no longer known (e.g. cached HTML), the other modules
1903 * should still be loaded.
1904 * - This method is used for preloading, which must not throw. Later code that
1905 * calls #using() will handle the error.
1907 * @param {string|Array} modules Either the name of a module, array of modules,
1908 * or a URL of an external script or style
1909 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
1910 * external script or style; acceptable values are "text/css" and
1911 * "text/javascript"; if no type is provided, text/javascript is assumed.
1913 load: function ( modules
, type
) {
1916 // Allow calling with a url or single dependency as a string
1917 if ( typeof modules
=== 'string' ) {
1918 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
1919 if ( /^(https?:)?\/?\//.test( modules
) ) {
1920 if ( type
=== 'text/css' ) {
1921 l
= document
.createElement( 'link' );
1922 l
.rel
= 'stylesheet';
1924 document
.head
.appendChild( l
);
1927 if ( type
=== 'text/javascript' || type
=== undefined ) {
1928 addScript( modules
);
1932 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
1934 // Called with single module
1935 modules
= [ modules
];
1938 // Filter out top-level modules that are unknown or failed to load before.
1939 filtered
= modules
.filter( function ( module
) {
1940 var state
= mw
.loader
.getState( module
);
1941 return state
!== 'error' && state
!== 'missing';
1943 // Resolve remaining list using the known dependency tree.
1944 // This also filters out modules with unknown dependencies. (T36853)
1945 filtered
= resolveStubbornly( filtered
);
1946 // Some modules are not yet ready, add to module load queue.
1947 enqueue( filtered
, undefined, undefined );
1951 * Change the state of one or more modules.
1953 * @param {Object} states Object of module name/state pairs
1955 state: function ( states
) {
1957 for ( module
in states
) {
1958 state
= states
[ module
];
1959 if ( !( module
in registry
) ) {
1960 mw
.loader
.register( module
);
1962 setAndPropagate( module
, state
);
1967 * Get the version of a module.
1969 * @param {string} module Name of module
1970 * @return {string|null} The version, or null if the module (or its version) is not
1973 getVersion: function ( module
) {
1974 return module
in registry
? registry
[ module
].version
: null;
1978 * Get the state of a module.
1980 * @param {string} module Name of module
1981 * @return {string|null} The state, or null if the module (or its state) is not
1984 getState: function ( module
) {
1985 return module
in registry
? registry
[ module
].state
: null;
1989 * Get the names of all registered modules.
1993 getModuleNames: function () {
1994 return Object
.keys( registry
);
1998 * Get the exported value of a module.
2000 * This static method is publicly exposed for debugging purposes
2001 * only and must not be used in production code. In production code,
2002 * please use the dynamically provided `require()` function instead.
2004 * In case of lazy-loaded modules via mw.loader#using(), the returned
2005 * Promise provides the function, see #using() for examples.
2009 * @param {string} moduleName Module name
2010 * @return {Mixed} Exported value
2012 require: function ( moduleName
) {
2013 var state
= mw
.loader
.getState( moduleName
);
2015 // Only ready modules can be required
2016 if ( state
!== 'ready' ) {
2017 // Module may've forgotten to declare a dependency
2018 throw new Error( 'Module "' + moduleName
+ '" is not loaded.' );
2021 return registry
[ moduleName
].module
.exports
;
2025 * On browsers that implement the localStorage API, the module store serves as a
2026 * smart complement to the browser cache. Unlike the browser cache, the module store
2027 * can slice a concatenated response from ResourceLoader into its constituent
2028 * modules and cache each of them separately, using each module's versioning scheme
2029 * to determine when the cache should be invalidated.
2033 * @class mw.loader.store
2036 // Whether the store is in use on this page.
2039 // Modules whose string representation exceeds 100 kB are
2040 // ineligible for storage. See bug T66721.
2041 MODULE_SIZE_MAX
: 100 * 1000,
2043 // The contents of the store, mapping '[name]@[version]' keys
2044 // to module implementations.
2047 // Names of modules to be stored during the next update.
2048 // See add() and update().
2052 stats
: { hits
: 0, misses
: 0, expired
: 0, failed
: 0 },
2055 * Construct a JSON-serializable object representing the content of the store.
2057 * @return {Object} Module store contents.
2059 toJSON: function () {
2060 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
2064 * Get the localStorage key for the entire module store. The key references
2065 * $wgDBname to prevent clashes between wikis which share a common host.
2067 * @return {string} localStorage item key
2069 getStoreKey: function () {
2070 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
2074 * Get a key on which to vary the module cache.
2076 * @return {string} String of concatenated vary conditions.
2078 getVary: function () {
2079 return mw
.config
.get( 'skin' ) + ':' +
2080 mw
.config
.get( 'wgResourceLoaderStorageVersion' ) + ':' +
2081 mw
.config
.get( 'wgUserLanguage' );
2085 * Initialize the store.
2087 * Retrieves store from localStorage and (if successfully retrieved) decoding
2088 * the stored JSON value to a plain object.
2090 * The try / catch block is used for JSON & localStorage feature detection.
2091 * See the in-line documentation for Modernizr's localStorage feature detection
2092 * code for a full account of why we need a try / catch:
2093 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2098 if ( this.enabled
!== null ) {
2104 // Disabled because localStorage quotas are tight and (in Firefox's case)
2105 // shared by multiple origins.
2106 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2107 /Firefox/.test( navigator
.userAgent
) ||
2109 // Disabled by configuration.
2110 !mw
.config
.get( 'wgResourceLoaderStorageEnabled' )
2112 // Clear any previous store to free up space. (T66721)
2114 this.enabled
= false;
2117 if ( mw
.config
.get( 'debug' ) ) {
2118 // Disable module store in debug mode
2119 this.enabled
= false;
2124 // This a string we stored, or `null` if the key does not (yet) exist.
2125 raw
= localStorage
.getItem( this.getStoreKey() );
2126 // If we get here, localStorage is available; mark enabled
2127 this.enabled
= true;
2128 // If null, JSON.parse() will cast to string and re-parse, still null.
2129 data
= JSON
.parse( raw
);
2130 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== this.getVary() ) {
2131 this.items
= data
.items
;
2135 mw
.trackError( 'resourceloader.exception', {
2137 source
: 'store-localstorage-init'
2141 // If we get here, one of four things happened:
2143 // 1. localStorage did not contain our store key.
2144 // This means `raw` is `null`, and we're on a fresh page view (cold cache).
2145 // The store was enabled, and `items` starts fresh.
2147 // 2. localStorage contained parseable data under our store key,
2148 // but it's not applicable to our current context (see getVary).
2149 // The store was enabled, and `items` starts fresh.
2151 // 3. JSON.parse threw (localStorage contained corrupt data).
2152 // This means `raw` contains a string.
2153 // The store was enabled, and `items` starts fresh.
2155 // 4. localStorage threw (disabled or otherwise unavailable).
2156 // This means `raw` was never assigned.
2157 // We will disable the store below.
2158 if ( raw
=== undefined ) {
2159 // localStorage failed; disable store
2160 this.enabled
= false;
2165 * Retrieve a module from the store and update cache hit stats.
2167 * @param {string} module Module name
2168 * @return {string|boolean} Module implementation or false if unavailable
2170 get: function ( module
) {
2173 if ( !this.enabled
) {
2177 key
= getModuleKey( module
);
2178 if ( key
in this.items
) {
2180 return this.items
[ key
];
2182 this.stats
.misses
++;
2187 * Queue the name of a module that the next update should consider storing.
2190 * @param {string} module Module name
2192 add: function ( module
) {
2193 if ( !this.enabled
) {
2196 this.queue
.push( module
);
2197 this.requestUpdate();
2201 * Add the contents of the named module to the in-memory store.
2203 * This method does not guarantee that the module will be stored.
2204 * Inspection of the module's meta data and size will ultimately decide that.
2206 * This method is considered internal to mw.loader.store and must only
2207 * be called if the store is enabled.
2210 * @param {string} module Module name
2212 set: function ( module
) {
2214 descriptor
= mw
.loader
.moduleRegistry
[ module
];
2216 key
= getModuleKey( module
);
2219 // Already stored a copy of this exact version
2220 key
in this.items
||
2221 // Module failed to load
2223 descriptor
.state
!== 'ready' ||
2224 // Unversioned, private, or site-/user-specific
2225 !descriptor
.version
||
2226 descriptor
.group
=== 'private' ||
2227 descriptor
.group
=== 'user' ||
2228 // Partial descriptor
2229 // (e.g. skipped module, or style module with state=ready)
2230 [ descriptor
.script
, descriptor
.style
, descriptor
.messages
,
2231 descriptor
.templates
].indexOf( undefined ) !== -1
2239 JSON
.stringify( key
),
2240 typeof descriptor
.script
=== 'function' ?
2241 String( descriptor
.script
) :
2242 JSON
.stringify( descriptor
.script
),
2243 JSON
.stringify( descriptor
.style
),
2244 JSON
.stringify( descriptor
.messages
),
2245 JSON
.stringify( descriptor
.templates
)
2248 mw
.trackError( 'resourceloader.exception', {
2250 source
: 'store-localstorage-json'
2255 src
= 'mw.loader.implement(' + args
.join( ',' ) + ');';
2256 if ( src
.length
> this.MODULE_SIZE_MAX
) {
2259 this.items
[ key
] = src
;
2263 * Iterate through the module store, removing any item that does not correspond
2264 * (in name and version) to an item in the module registry.
2266 prune: function () {
2269 for ( key
in this.items
) {
2270 module
= key
.slice( 0, key
.indexOf( '@' ) );
2271 if ( getModuleKey( module
) !== key
) {
2272 this.stats
.expired
++;
2273 delete this.items
[ key
];
2274 } else if ( this.items
[ key
].length
> this.MODULE_SIZE_MAX
) {
2275 // This value predates the enforcement of a size limit on cached modules.
2276 delete this.items
[ key
];
2282 * Clear the entire module store right now.
2284 clear: function () {
2287 localStorage
.removeItem( this.getStoreKey() );
2292 * Request a sync of the in-memory store back to persisted localStorage.
2294 * This function debounces updates. The debouncing logic should account
2295 * for the following factors:
2297 * - Writing to localStorage is an expensive operation that must not happen
2298 * during the critical path of initialising and executing module code.
2299 * Instead, it should happen at a later time after modules have been given
2300 * time and priority to do their thing first.
2302 * - This method is called from mw.loader.store.add(), which will be called
2303 * hundreds of times on a typical page, including within the same call-stack
2304 * and eventloop-tick. This is because responses from load.php happen in
2305 * batches. As such, we want to allow all modules from the same load.php
2306 * response to be written to disk with a single flush, not many.
2308 * - Repeatedly deleting and creating timers is non-trivial.
2310 * - localStorage is shared by all pages from the same origin, if multiple
2311 * pages are loaded with different module sets, the possibility exists that
2312 * modules saved by one page will be clobbered by another. The impact of
2313 * this is minor, it merely causes a less efficient cache use, and the
2314 * problem would be corrected by subsequent page views.
2316 * This method is considered internal to mw.loader.store and must only
2317 * be called if the store is enabled.
2322 requestUpdate
: ( function () {
2323 var hasPendingWrites
= false;
2325 function flushWrites() {
2328 // Remove anything from the in-memory store that came from previous page
2329 // loads that no longer corresponds with current module names and versions.
2330 mw
.loader
.store
.prune();
2331 // Process queued module names, serialise their contents to the in-memory store.
2332 while ( mw
.loader
.store
.queue
.length
) {
2333 mw
.loader
.store
.set( mw
.loader
.store
.queue
.shift() );
2336 key
= mw
.loader
.store
.getStoreKey();
2338 // Replacing the content of the module store might fail if the new
2339 // contents would exceed the browser's localStorage size limit. To
2340 // avoid clogging the browser with stale data, always remove the old
2341 // value before attempting to set the new one.
2342 localStorage
.removeItem( key
);
2343 data
= JSON
.stringify( mw
.loader
.store
);
2344 localStorage
.setItem( key
, data
);
2346 mw
.trackError( 'resourceloader.exception', {
2348 source
: 'store-localstorage-update'
2352 // Let the next call to requestUpdate() create a new timer.
2353 hasPendingWrites
= false;
2356 function onTimeout() {
2357 // Defer the actual write via requestIdleCallback
2358 mw
.requestIdleCallback( flushWrites
);
2361 return function () {
2362 // On the first call to requestUpdate(), create a timer that
2363 // waits at least two seconds, then calls onTimeout.
2364 // The main purpose is to allow the current batch of load.php
2365 // responses to complete before we do anything. This batch can
2366 // trigger many hundreds of calls to requestUpdate().
2367 if ( !hasPendingWrites
) {
2368 hasPendingWrites
= true;
2369 setTimeout( onTimeout
, 2000 );
2377 // Skeleton user object, extended by the 'mediawiki.user' module.
2384 * @property {mw.Map}
2388 * @property {mw.Map}
2393 // OOUI widgets specific to MediaWiki
2398 // Attach to window and globally alias
2399 window
.mw
= window
.mediaWiki
= mw
;