2 * Base library for MediaWiki.
4 * Exposed globally as `mediaWiki` with `mw` as shortcut.
7 * @alternateClassName mediaWiki
11 /* eslint-disable no-use-before-define */
16 var mw, StringSet, log,
17 hasOwn = Object.prototype.hasOwnProperty,
18 slice = Array.prototype.slice,
19 trackCallbacks = $.Callbacks( 'memory' ),
24 * FNV132 hash function
26 * This function implements the 32-bit version of FNV-1.
27 * It is equivalent to hash( 'fnv132', ... ) in PHP, except
28 * its output is base 36 rather than hex.
29 * See <https://en.wikipedia.org/wiki/FNV_hash_function>
32 * @param {string} str String to hash
33 * @return {string} hash as an seven-character base 36 string
35 function fnv132( str ) {
36 /* eslint-disable no-bitwise */
37 var hash = 0x811C9DC5,
40 for ( i = 0; i < str.length; i++ ) {
41 hash += ( hash << 1 ) + ( hash << 4 ) + ( hash << 7 ) + ( hash << 8 ) + ( hash << 24 );
42 hash ^= str.charCodeAt( i );
45 hash = ( hash >>> 0 ).toString( 36 );
46 while ( hash.length < 7 ) {
51 /* eslint-enable no-bitwise */
54 StringSet = window.Set || ( function () {
59 function StringSet() {
62 StringSet.prototype.add = function ( value ) {
63 this.set[ value ] = true;
65 StringSet.prototype.has = function ( value ) {
66 return this.set.hasOwnProperty( value );
72 * Create an object that can be read from or written to via methods that allow
73 * interaction both with single and multiple properties at once.
79 * @param {boolean} [global=false] Whether to synchronise =values to the global
80 * window object (for backwards-compatibility with mw.config; T72470). Values are
81 * copied in one direction only. Changes to globals do not reflect in the map.
83 function Map( global ) {
84 this.internalValues = {};
85 if ( global === true ) {
87 // Override #set to also set the global variable
88 this.set = function ( selection, value ) {
91 if ( $.isPlainObject( selection ) ) {
92 for ( s in selection ) {
93 setGlobalMapValue( this, s, selection[ s ] );
97 if ( typeof selection === 'string' && arguments.length ) {
98 setGlobalMapValue( this, selection, value );
105 // Deprecated since MediaWiki 1.28
110 'mw.Map#values is deprecated. Use mw.Map#get() instead.',
116 * Alias property to the global object.
120 * @param {mw.Map} map
121 * @param {string} key
122 * @param {Mixed} value
124 function setGlobalMapValue( map, key, value ) {
125 map.internalValues[ key ] = value;
130 // Deprecation notice for mw.config globals (T58550, T72470)
131 map === mw.config && 'Use mw.config instead.'
139 * Get the value of one or more keys.
141 * If called with no arguments, all values are returned.
143 * @param {string|Array} [selection] Key or array of keys to retrieve values for.
144 * @param {Mixed} [fallback=null] Value for keys that don't exist.
145 * @return {Mixed|Object| null} If selection was a string, returns the value,
146 * If selection was an array, returns an object of key/values.
147 * If no selection is passed, the internal container is returned. (Beware that,
148 * as is the default in JavaScript, the object is returned by reference.)
150 get: function ( selection, fallback ) {
152 // If we only do this in the `return` block, it'll fail for the
153 // call to get() from the mutli-selection block.
154 fallback = arguments.length > 1 ? fallback : null;
156 if ( $.isArray( selection ) ) {
157 selection = slice.call( selection );
159 for ( i = 0; i < selection.length; i++ ) {
160 results[ selection[ i ] ] = this.get( selection[ i ], fallback );
165 if ( typeof selection === 'string' ) {
166 if ( !hasOwn.call( this.internalValues, selection ) ) {
169 return this.internalValues[ selection ];
172 if ( selection === undefined ) {
173 return this.internalValues;
176 // Invalid selection key
181 * Set one or more key/value pairs.
183 * @param {string|Object} selection Key to set value for, or object mapping keys to values
184 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
185 * @return {boolean} True on success, false on failure
187 set: function ( selection, value ) {
190 if ( $.isPlainObject( selection ) ) {
191 for ( s in selection ) {
192 this.internalValues[ s ] = selection[ s ];
196 if ( typeof selection === 'string' && arguments.length > 1 ) {
197 this.internalValues[ selection ] = value;
204 * Check if one or more keys exist.
206 * @param {Mixed} selection Key or array of keys to check
207 * @return {boolean} True if the key(s) exist
209 exists: function ( selection ) {
212 if ( $.isArray( selection ) ) {
213 for ( s = 0; s < selection.length; s++ ) {
214 if ( typeof selection[ s ] !== 'string' || !hasOwn.call( this.internalValues, selection[ s ] ) ) {
220 return typeof selection === 'string' && hasOwn.call( this.internalValues, selection );
225 * Object constructor for messages.
227 * Similar to the Message class in MediaWiki PHP.
229 * Format defaults to 'text'.
235 * 'hello': 'Hello world',
236 * 'hello-user': 'Hello, $1!',
237 * 'welcome-user': 'Welcome back to $2, $1! Last visit by $1: $3'
240 * obj = new mw.Message( mw.messages, 'hello' );
241 * mw.log( obj.text() );
244 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John Doe' ] );
245 * mw.log( obj.text() );
246 * // Hello, John Doe!
248 * obj = new mw.Message( mw.messages, 'welcome-user', [ 'John Doe', 'Wikipedia', '2 hours ago' ] );
249 * mw.log( obj.text() );
250 * // Welcome back to Wikipedia, John Doe! Last visit by John Doe: 2 hours ago
252 * // Using mw.message shortcut
253 * obj = mw.message( 'hello-user', 'John Doe' );
254 * mw.log( obj.text() );
255 * // Hello, John Doe!
257 * // Using mw.msg shortcut
258 * str = mw.msg( 'hello-user', 'John Doe' );
260 * // Hello, John Doe!
262 * // Different formats
263 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John "Wiki" <3 Doe' ] );
265 * obj.format = 'text';
266 * str = obj.toString();
271 * // Hello, John "Wiki" <3 Doe!
273 * mw.log( obj.escaped() );
274 * // Hello, John "Wiki" <3 Doe!
279 * @param {mw.Map} map Message store
280 * @param {string} key
281 * @param {Array} [parameters]
283 function Message( map, key, parameters ) {
284 this.format = 'text';
287 this.parameters = parameters === undefined ? [] : slice.call( parameters );
291 Message.prototype = {
293 * Get parsed contents of the message.
295 * The default parser does simple $N replacements and nothing else.
296 * This may be overridden to provide a more complex message parser.
297 * The primary override is in the mediawiki.jqueryMsg module.
299 * This function will not be called for nonexistent messages.
301 * @return {string} Parsed message
303 parser: function () {
304 return mw.format.apply( null, [ this.map.get( this.key ) ].concat( this.parameters ) );
307 // eslint-disable-next-line valid-jsdoc
309 * Add (does not replace) parameters for `$N` placeholder values.
311 * @param {Array} parameters
314 params: function ( parameters ) {
316 for ( i = 0; i < parameters.length; i++ ) {
317 this.parameters.push( parameters[ i ] );
323 * Convert message object to its string form based on current format.
325 * @return {string} Message as a string in the current form, or `<key>` if key
328 toString: function () {
331 if ( !this.exists() ) {
332 // Use ⧼key⧽ as text if key does not exist
333 // Err on the side of safety, ensure that the output
334 // is always html safe in the event the message key is
335 // missing, since in that case its highly likely the
336 // message key is user-controlled.
337 // '⧼' is used instead of '<' to side-step any
338 // double-escaping issues.
339 // (Keep synchronised with Message::toString() in PHP.)
340 return '⧼' + mw.html.escape( this.key ) + '⧽';
343 if ( this.format === 'plain' || this.format === 'text' || this.format === 'parse' ) {
344 text = this.parser();
347 if ( this.format === 'escaped' ) {
348 text = this.parser();
349 text = mw.html.escape( text );
356 * Change format to 'parse' and convert message to string
358 * If jqueryMsg is loaded, this parses the message text from wikitext
359 * (where supported) to HTML
361 * Otherwise, it is equivalent to plain.
363 * @return {string} String form of parsed message
366 this.format = 'parse';
367 return this.toString();
371 * Change format to 'plain' and convert message to string
373 * This substitutes parameters, but otherwise does not change the
376 * @return {string} String form of plain message
379 this.format = 'plain';
380 return this.toString();
384 * Change format to 'text' and convert message to string
386 * If jqueryMsg is loaded, {{-transformation is done where supported
387 * (such as {{plural:}}, {{gender:}}, {{int:}}).
389 * Otherwise, it is equivalent to plain
391 * @return {string} String form of text message
394 this.format = 'text';
395 return this.toString();
399 * Change the format to 'escaped' and convert message to string
401 * This is equivalent to using the 'text' format (see #text), then
402 * HTML-escaping the output.
404 * @return {string} String form of html escaped message
406 escaped: function () {
407 this.format = 'escaped';
408 return this.toString();
412 * Check if a message exists
417 exists: function () {
418 return this.map.exists( this.key );
422 /* eslint-disable no-console */
423 log = ( function () {
424 // Also update the restoration of methods in mediawiki.log.js
425 // when adding or removing methods here.
426 var log = function () {},
427 console = window.console;
435 * Write a message to the console's warning channel.
436 * Actions not supported by the browser console are silently ignored.
438 * @param {...string} msg Messages to output to console
440 log.warn = console && console.warn && Function.prototype.bind ?
441 Function.prototype.bind.call( console.warn, console ) :
445 * Write a message to the console's error channel.
447 * Most browsers provide a stacktrace by default if the argument
448 * is a caught Error object.
451 * @param {Error|...string} msg Messages to output to console
453 log.error = console && console.error && Function.prototype.bind ?
454 Function.prototype.bind.call( console.error, console ) :
458 * Create a property in a host object that, when accessed, will produce
459 * a deprecation warning in the console.
461 * @param {Object} obj Host object of deprecated property
462 * @param {string} key Name of property to create in `obj`
463 * @param {Mixed} val The value this property should return when accessed
464 * @param {string} [msg] Optional text to include in the deprecation message
465 * @param {string} [logName=key] Optional custom name for the feature.
466 * This is used instead of `key` in the message and `mw.deprecate` tracking.
468 log.deprecate = !Object.defineProperty ? function ( obj, key, val ) {
470 } : function ( obj, key, val, msg, logName ) {
471 var logged = new StringSet();
472 logName = logName || key;
473 msg = 'Use of "' + logName + '" is deprecated.' + ( msg ? ( ' ' + msg ) : '' );
474 function uniqueTrace() {
475 var trace = new Error().stack;
476 if ( logged.has( trace ) ) {
482 // Support: Safari 5.0
483 // Throws "not supported on DOM Objects" for Node or Element objects (incl. document)
484 // Safari 4.0 doesn't have this method, and it was fixed in Safari 5.1.
486 Object.defineProperty( obj, key, {
490 if ( uniqueTrace() ) {
491 mw.track( 'mw.deprecate', logName );
496 set: function ( newVal ) {
497 if ( uniqueTrace() ) {
498 mw.track( 'mw.deprecate', logName );
511 /* eslint-enable no-console */
519 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
521 * On browsers that implement the Navigation Timing API, this function will produce floating-point
522 * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
523 * it will fall back to using `Date`.
525 * @return {number} Current time
528 var perf = window.performance,
529 navStart = perf && perf.timing && perf.timing.navigationStart;
530 return navStart && typeof perf.now === 'function' ?
531 function () { return navStart + perf.now(); } :
532 function () { return +new Date(); };
536 * Format a string. Replace $1, $2 ... $N with positional arguments.
538 * Used by Message#parser().
541 * @param {string} formatString Format string
542 * @param {...Mixed} parameters Values for $N replacements
543 * @return {string} Formatted string
545 format: function ( formatString ) {
546 var parameters = slice.call( arguments, 1 );
547 return formatString.replace( /\$(\d+)/g, function ( str, match ) {
548 var index = parseInt( match, 10 ) - 1;
549 return parameters[ index ] !== undefined ? parameters[ index ] : '$' + match;
554 * Track an analytic event.
556 * This method provides a generic means for MediaWiki JavaScript code to capture state
557 * information for analysis. Each logged event specifies a string topic name that describes
558 * the kind of event that it is. Topic names consist of dot-separated path components,
559 * arranged from most general to most specific. Each path component should have a clear and
560 * well-defined purpose.
562 * Data handlers are registered via `mw.trackSubscribe`, and receive the full set of
563 * events that match their subcription, including those that fired before the handler was
566 * @param {string} topic Topic name
567 * @param {Object} [data] Data describing the event, encoded as an object
569 track: function ( topic, data ) {
570 trackQueue.push( { topic: topic, timeStamp: mw.now(), data: data } );
571 trackCallbacks.fire( trackQueue );
575 * Register a handler for subset of analytic events, specified by topic.
577 * Handlers will be called once for each tracked event, including any events that fired before the
578 * handler was registered; 'this' is set to a plain object with a 'timeStamp' property indicating
579 * the exact time at which the event fired, a string 'topic' property naming the event, and a
580 * 'data' property which is an object of event-specific data. The event topic and event data are
581 * also passed to the callback as the first and second arguments, respectively.
583 * @param {string} topic Handle events whose name starts with this string prefix
584 * @param {Function} callback Handler to call for each matching tracked event
585 * @param {string} callback.topic
586 * @param {Object} [callback.data]
588 trackSubscribe: function ( topic, callback ) {
590 function handler( trackQueue ) {
592 for ( ; seen < trackQueue.length; seen++ ) {
593 event = trackQueue[ seen ];
594 if ( event.topic.indexOf( topic ) === 0 ) {
595 callback.call( event, event.topic, event.data );
600 trackHandlers.push( [ handler, callback ] );
602 trackCallbacks.add( handler );
606 * Stop handling events for a particular handler
608 * @param {Function} callback
610 trackUnsubscribe: function ( callback ) {
611 trackHandlers = $.grep( trackHandlers, function ( fns ) {
612 if ( fns[ 1 ] === callback ) {
613 trackCallbacks.remove( fns[ 0 ] );
614 // Ensure the tuple is removed to avoid holding on to closures
621 // Expose Map constructor
624 // Expose Message constructor
628 * Map of configuration values.
630 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
633 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
634 * global `window` object.
636 * @property {mw.Map} config
638 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
642 * Empty object for third-party libraries, for cases where you don't
643 * want to add a new global, or the global is bad and needs containment
651 * Access container for deprecated functionality that can be moved from
652 * from their legacy location and attached to this object (e.g. a global
653 * function that is deprecated and as stop-gap can be exposed through here).
655 * This was reserved for future use but never ended up being used.
657 * @deprecated since 1.22 Let deprecated identifiers keep their original name
658 * and use mw.log#deprecate to create an access container for tracking.
664 * Store for messages.
671 * Store for templates associated with a module.
675 templates: new Map(),
678 * Get a message object.
680 * Shortcut for `new mw.Message( mw.messages, key, parameters )`.
683 * @param {string} key Key of message to get
684 * @param {...Mixed} parameters Values for $N replacements
685 * @return {mw.Message}
687 message: function ( key ) {
688 var parameters = slice.call( arguments, 1 );
689 return new Message( mw.messages, key, parameters );
693 * Get a message string using the (default) 'text' format.
695 * Shortcut for `mw.message( key, parameters... ).text()`.
698 * @param {string} key Key of message to get
699 * @param {...Mixed} parameters Values for $N replacements
703 return mw.message.apply( mw.message, arguments ).toString();
707 * No-op dummy placeholder for {@link mw.log} in debug mode.
714 * Client for ResourceLoader server end point.
716 * This client is in charge of maintaining the module registry and state
717 * machine, initiating network (batch) requests for loading modules, as
718 * well as dependency resolution and execution of source code.
720 * For more information, refer to
721 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
726 loader: ( function () {
729 * Fired via mw.track on various resource loading errors.
731 * @event resourceloader_exception
732 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
733 * object, but in theory module code could manually throw something else, and that
734 * might also end up here.
735 * @param {string} [module] Name of the module which caused the error. Omitted if the
736 * error is not module-related or the module cannot be easily identified due to
738 * @param {string} source Source of the error. Possible values:
740 * - style: stylesheet error (only affects old IE where a special style loading method
742 * - load-callback: exception thrown by user callback
743 * - module-execute: exception thrown by module code
744 * - store-eval: could not evaluate module code cached in localStorage
745 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
746 * - store-localstorage-json: JSON conversion error in mw.loader.store.set
747 * - store-localstorage-update: localStorage or JSON conversion error in mw.loader.store.update
751 * Fired via mw.track on resource loading error conditions.
753 * @event resourceloader_assert
754 * @param {string} source Source of the error. Possible values:
756 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
757 * bug; see <https://phabricator.wikimedia.org/T59567> for details
761 * Mapping of registered modules.
763 * See #implement and #execute for exact details on support for script, style and messages.
769 * // From mw.loader.register()
770 * 'version': '########' (hash)
771 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function () {}
772 * 'group': 'somegroup', (or) null
773 * 'source': 'local', (or) 'anotherwiki'
774 * 'skip': 'return !!window.Example', (or) null
775 * 'module': export Object
777 * // Set from execute() or mw.loader.state()
778 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
780 * // Optionally added at run-time by mw.loader.implement()
782 * 'script': closure, array of urls, or string
783 * 'style': { ... } (see #execute)
784 * 'messages': { 'key': 'value', ... }
791 * The module is known to the system but not yet required.
792 * Meta data is registered via mw.loader#register. Calls to that method are
793 * generated server-side by the startup module.
795 * The module was required through mw.loader (either directly or as dependency of
796 * another module). The client will fetch module contents from the server.
797 * The contents are then stashed in the registry via mw.loader#implement.
799 * The module has been loaded from the server and stashed via mw.loader#implement.
800 * If the module has no more dependencies in-flight, the module will be executed
801 * immediately. Otherwise execution is deferred, controlled via #handlePending.
803 * The module is being executed.
805 * The module has been successfully executed.
807 * The module (or one of its dependencies) produced an error during execution.
809 * The module was registered client-side and requested, but the server denied knowledge
810 * of the module's existence.
816 // Mapping of sources, keyed by source-id, values are strings.
821 // 'sourceId': 'http://example.org/w/load.php'
826 // For queueModuleScript()
827 handlingPendingRequests = false,
828 pendingRequests = [],
830 // List of modules to be loaded
834 * List of callback jobs waiting for modules to be ready.
836 * Jobs are created by #enqueue() and run by #handlePending().
838 * Typically when a job is created for a module, the job's dependencies contain
839 * both the required module and all its recursive dependencies.
844 * 'dependencies': [ module names ],
845 * 'ready': Function callback
846 * 'error': Function callback
849 * @property {Object[]} jobs
857 // For addEmbeddedCSS()
859 cssBufferTimer = null,
860 cssCallbacks = $.Callbacks(),
861 isIE9 = document.documentMode === 9,
862 rAF = window.requestAnimationFrame || setTimeout;
864 function getMarker() {
867 marker = document.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' );
869 mw.log( 'Create <meta name="ResourceLoaderDynamicStyles"> dynamically' );
870 marker = $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' )[ 0 ];
877 * Create a new style element and add it to the DOM.
880 * @param {string} text CSS text
881 * @param {Node} [nextNode] The element where the style tag
882 * should be inserted before
883 * @return {HTMLElement} Reference to the created style element
885 function newStyleTag( text, nextNode ) {
886 var s = document.createElement( 'style' );
888 s.appendChild( document.createTextNode( text ) );
889 if ( nextNode && nextNode.parentNode ) {
890 nextNode.parentNode.insertBefore( s, nextNode );
892 document.getElementsByTagName( 'head' )[ 0 ].appendChild( s );
899 * Add a bit of CSS text to the current browser page.
901 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
902 * or create a new one based on whether the given `cssText` is safe for extension.
905 * @param {string} [cssText=cssBuffer] If called without cssText,
906 * the internal buffer will be inserted instead.
907 * @param {Function} [callback]
909 function addEmbeddedCSS( cssText, callback ) {
912 function fireCallbacks() {
913 var oldCallbacks = cssCallbacks;
914 // Reset cssCallbacks variable so it's not polluted by any calls to
915 // addEmbeddedCSS() from one of the callbacks (T105973)
916 cssCallbacks = $.Callbacks();
917 oldCallbacks.fire().empty();
921 cssCallbacks.add( callback );
924 // Yield once before creating the <style> tag. This lets multiple stylesheets
925 // accumulate into one buffer, allowing us to reduce how often new stylesheets
926 // are inserted in the browser. Appending a stylesheet and waiting for the
927 // browser to repaint is fairly expensive. (T47810)
929 // Don't extend the buffer if the item needs its own stylesheet.
930 // Keywords like `@import` are only valid at the start of a stylesheet (T37562).
931 if ( !cssBuffer || cssText.slice( 0, '@import'.length ) !== '@import' ) {
932 // Linebreak for somewhat distinguishable sections
933 cssBuffer += '\n' + cssText;
934 if ( !cssBufferTimer ) {
935 cssBufferTimer = rAF( function () {
936 // Wrap in anonymous function that takes no arguments
937 // Support: Firefox < 13
938 // Firefox 12 has non-standard behaviour of passing a number
939 // as first argument to a setTimeout callback.
940 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
947 // This is a scheduled flush for the buffer
949 cssBufferTimer = null;
954 // By default, always create a new <style>. Appending text to a <style> tag is
955 // is a performance anti-pattern as it requires CSS to be reparsed (T47810).
958 // Try to re-use existing <style> tags due to the IE stylesheet limit (T33676).
960 $style = $( getMarker() ).prev();
961 // Verify that the element before the marker actually is a <style> tag created
962 // by mw.loader (not some other style tag, or e.g. a <meta> tag).
963 if ( $style.data( 'ResourceLoaderDynamicStyleTag' ) ) {
964 styleEl = $style[ 0 ];
965 styleEl.appendChild( document.createTextNode( cssText ) );
969 // Else: No existing tag to reuse. Continue below and create the first one.
972 $style = $( newStyleTag( cssText, getMarker() ) );
975 $style.data( 'ResourceLoaderDynamicStyleTag', true );
983 * @param {Array} modules List of module names
984 * @return {string} Hash of concatenated version hashes.
986 function getCombinedVersion( modules ) {
987 var hashes = $.map( modules, function ( module ) {
988 return registry[ module ].version;
990 return fnv132( hashes.join( '' ) );
994 * Determine whether all dependencies are in state 'ready', which means we may
995 * execute the module or job now.
998 * @param {Array} modules Names of modules to be checked
999 * @return {boolean} True if all modules are in state 'ready', false otherwise
1001 function allReady( modules ) {
1003 for ( i = 0; i < modules.length; i++ ) {
1004 if ( mw.loader.getState( modules[ i ] ) !== 'ready' ) {
1012 * Determine whether all dependencies are in state 'ready', which means we may
1013 * execute the module or job now.
1016 * @param {Array} modules Names of modules to be checked
1017 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
1019 function anyFailed( modules ) {
1021 for ( i = 0; i < modules.length; i++ ) {
1022 state = mw.loader.getState( modules[ i ] );
1023 if ( state === 'error' || state === 'missing' ) {
1031 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
1032 * pending jobs and modules that depend upon this module. If the given module failed,
1033 * propagate the 'error' state up the dependency tree. Otherwise, go ahead and execute
1034 * all jobs/modules now having their dependencies satisfied.
1036 * Jobs that depend on a failed module, will have their error callback ran (if any).
1039 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
1041 function handlePending( module ) {
1042 var j, job, hasErrors, m, stateChange;
1044 if ( registry[ module ].state === 'error' || registry[ module ].state === 'missing' ) {
1045 // If the current module failed, mark all dependent modules also as failed.
1046 // Iterate until steady-state to propagate the error state upwards in the
1049 stateChange = false;
1050 for ( m in registry ) {
1051 if ( registry[ m ].state !== 'error' && registry[ m ].state !== 'missing' ) {
1052 if ( anyFailed( registry[ m ].dependencies ) ) {
1053 registry[ m ].state = 'error';
1058 } while ( stateChange );
1061 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
1062 for ( j = 0; j < jobs.length; j++ ) {
1063 hasErrors = anyFailed( jobs[ j ].dependencies );
1064 if ( hasErrors || allReady( jobs[ j ].dependencies ) ) {
1065 // All dependencies satisfied, or some have errors
1067 jobs.splice( j, 1 );
1071 if ( typeof job.error === 'function' ) {
1072 job.error( new Error( 'Module ' + module + ' has failed dependencies' ), [ module ] );
1075 if ( typeof job.ready === 'function' ) {
1080 // A user-defined callback raised an exception.
1081 // Swallow it to protect our state machine!
1082 mw.track( 'resourceloader.exception', { exception: e, module: module, source: 'load-callback' } );
1087 if ( registry[ module ].state === 'ready' ) {
1088 // The current module became 'ready'. Set it in the module store, and recursively execute all
1089 // dependent modules that are loaded and now have all dependencies satisfied.
1090 mw.loader.store.set( module, registry[ module ] );
1091 for ( m in registry ) {
1092 if ( registry[ m ].state === 'loaded' && allReady( registry[ m ].dependencies ) ) {
1100 * Resolve dependencies and detect circular references.
1103 * @param {string} module Name of the top-level module whose dependencies shall be
1104 * resolved and sorted.
1105 * @param {Array} resolved Returns a topological sort of the given module and its
1106 * dependencies, such that later modules depend on earlier modules. The array
1107 * contains the module names. If the array contains already some module names,
1108 * this function appends its result to the pre-existing array.
1109 * @param {StringSet} [unresolved] Used to track the current dependency
1110 * chain, and to report loops in the dependency graph.
1111 * @throws {Error} If any unregistered module or a dependency loop is encountered
1113 function sortDependencies( module, resolved, unresolved ) {
1116 if ( !hasOwn.call( registry, module ) ) {
1117 throw new Error( 'Unknown dependency: ' + module );
1120 if ( registry[ module ].skip !== null ) {
1121 // eslint-disable-next-line no-new-func
1122 skip = new Function( registry[ module ].skip );
1123 registry[ module ].skip = null;
1125 registry[ module ].skipped = true;
1126 registry[ module ].dependencies = [];
1127 registry[ module ].state = 'ready';
1128 handlePending( module );
1133 // Resolves dynamic loader function and replaces it with its own results
1134 if ( typeof registry[ module ].dependencies === 'function' ) {
1135 registry[ module ].dependencies = registry[ module ].dependencies();
1136 // Ensures the module's dependencies are always in an array
1137 if ( typeof registry[ module ].dependencies !== 'object' ) {
1138 registry[ module ].dependencies = [ registry[ module ].dependencies ];
1141 if ( $.inArray( module, resolved ) !== -1 ) {
1142 // Module already resolved; nothing to do
1145 // Create unresolved if not passed in
1146 if ( !unresolved ) {
1147 unresolved = new StringSet();
1149 // Tracks down dependencies
1150 deps = registry[ module ].dependencies;
1151 for ( i = 0; i < deps.length; i++ ) {
1152 if ( $.inArray( deps[ i ], resolved ) === -1 ) {
1153 if ( unresolved.has( deps[ i ] ) ) {
1154 throw new Error( mw.format(
1155 'Circular reference detected: $1 -> $2',
1161 unresolved.add( module );
1162 sortDependencies( deps[ i ], resolved, unresolved );
1165 resolved.push( module );
1169 * Get names of module that a module depends on, in their proper dependency order.
1172 * @param {string[]} modules Array of string module names
1173 * @return {Array} List of dependencies, including 'module'.
1174 * @throws {Error} If an unregistered module or a dependency loop is encountered
1176 function resolve( modules ) {
1177 var i, resolved = [];
1178 for ( i = 0; i < modules.length; i++ ) {
1179 sortDependencies( modules[ i ], resolved );
1185 * Load and execute a script.
1188 * @param {string} src URL to script, will be used as the src attribute in the script tag
1189 * @return {jQuery.Promise}
1191 function addScript( src ) {
1195 // Force jQuery behaviour to be for crossDomain. Otherwise jQuery would use
1196 // XHR for a same domain request instead of <script>, which changes the request
1197 // headers (potentially missing a cache hit), and reduces caching in general
1198 // since browsers cache XHR much less (if at all). And XHR means we retrieve
1199 // text, so we'd need to $.globalEval, which then messes up line numbers.
1206 * Queue the loading and execution of a script for a particular module.
1209 * @param {string} src URL of the script
1210 * @param {string} [moduleName] Name of currently executing module
1211 * @return {jQuery.Promise}
1213 function queueModuleScript( src, moduleName ) {
1214 var r = $.Deferred();
1216 pendingRequests.push( function () {
1217 if ( moduleName && hasOwn.call( registry, moduleName ) ) {
1218 // Emulate runScript() part of execute()
1219 window.require = mw.loader.require;
1220 window.module = registry[ moduleName ].module;
1222 addScript( src ).always( function () {
1223 // 'module.exports' should not persist after the file is executed to
1224 // avoid leakage to unrelated code. 'require' should be kept, however,
1225 // as asynchronous access to 'require' is allowed and expected. (T144879)
1226 delete window.module;
1229 // Start the next one (if any)
1230 if ( pendingRequests[ 0 ] ) {
1231 pendingRequests.shift()();
1233 handlingPendingRequests = false;
1237 if ( !handlingPendingRequests && pendingRequests[ 0 ] ) {
1238 handlingPendingRequests = true;
1239 pendingRequests.shift()();
1245 * Utility function for execute()
1248 * @param {string} [media] Media attribute
1249 * @param {string} url URL
1251 function addLink( media, url ) {
1252 var el = document.createElement( 'link' );
1254 el.rel = 'stylesheet';
1255 if ( media && media !== 'all' ) {
1258 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1259 // see #addEmbeddedCSS, bug 31676, and bug 47277 for details.
1262 $( getMarker() ).before( el );
1266 * Executes a loaded module, making it ready to use
1269 * @param {string} module Module name to execute
1271 function execute( module ) {
1272 var key, value, media, i, urls, cssHandle, checkCssHandles, runScript,
1273 cssHandlesRegistered = false;
1275 if ( !hasOwn.call( registry, module ) ) {
1276 throw new Error( 'Module has not been registered yet: ' + module );
1278 if ( registry[ module ].state !== 'loaded' ) {
1279 throw new Error( 'Module in state "' + registry[ module ].state + '" may not be executed: ' + module );
1282 registry[ module ].state = 'executing';
1284 runScript = function () {
1285 var script, markModuleReady, nestedAddScript, legacyWait, implicitDependencies,
1286 // Expand to include dependencies since we have to exclude both legacy modules
1287 // and their dependencies from the legacyWait (to prevent a circular dependency).
1288 legacyModules = resolve( mw.config.get( 'wgResourceLoaderLegacyModules', [] ) );
1290 script = registry[ module ].script;
1291 markModuleReady = function () {
1292 registry[ module ].state = 'ready';
1293 handlePending( module );
1295 nestedAddScript = function ( arr, callback, i ) {
1296 // Recursively call queueModuleScript() in its own callback
1297 // for each element of arr.
1298 if ( i >= arr.length ) {
1299 // We're at the end of the array
1304 queueModuleScript( arr[ i ], module ).always( function () {
1305 nestedAddScript( arr, callback, i + 1 );
1309 implicitDependencies = ( $.inArray( module, legacyModules ) !== -1 ) ?
1313 if ( module === 'user' ) {
1314 // Implicit dependency on the site module. Not real dependency because
1315 // it should run after 'site' regardless of whether it succeeds or fails.
1316 implicitDependencies.push( 'site' );
1319 legacyWait = implicitDependencies.length ?
1320 mw.loader.using( implicitDependencies ) :
1321 $.Deferred().resolve();
1323 legacyWait.always( function () {
1325 if ( $.isArray( script ) ) {
1326 nestedAddScript( script, markModuleReady, 0 );
1327 } else if ( typeof script === 'function' ) {
1328 // Pass jQuery twice so that the signature of the closure which wraps
1329 // the script can bind both '$' and 'jQuery'.
1330 script( $, $, mw.loader.require, registry[ module ].module );
1333 } else if ( typeof script === 'string' ) {
1334 // Site and user modules are legacy scripts that run in the global scope.
1335 // This is transported as a string instead of a function to avoid needing
1336 // to use string manipulation to undo the function wrapper.
1337 $.globalEval( script );
1341 // Module without script
1345 // Use mw.track instead of mw.log because these errors are common in production mode
1346 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1347 registry[ module ].state = 'error';
1348 mw.track( 'resourceloader.exception', { exception: e, module: module, source: 'module-execute' } );
1349 handlePending( module );
1354 // Add localizations to message system
1355 if ( registry[ module ].messages ) {
1356 mw.messages.set( registry[ module ].messages );
1359 // Initialise templates
1360 if ( registry[ module ].templates ) {
1361 mw.templates.set( module, registry[ module ].templates );
1364 // Make sure we don't run the scripts until all stylesheet insertions have completed.
1367 checkCssHandles = function () {
1368 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1369 // one of the cssHandles is fired while we're still creating more handles.
1370 if ( cssHandlesRegistered && pending === 0 && runScript ) {
1372 runScript = undefined; // Revoke
1375 cssHandle = function () {
1376 var check = checkCssHandles;
1378 return function () {
1382 check = undefined; // Revoke
1388 // Process styles (see also mw.loader.implement)
1389 // * back-compat: { <media>: css }
1390 // * back-compat: { <media>: [url, ..] }
1391 // * { "css": [css, ..] }
1392 // * { "url": { <media>: [url, ..] } }
1393 if ( registry[ module ].style ) {
1394 for ( key in registry[ module ].style ) {
1395 value = registry[ module ].style[ key ];
1398 if ( key !== 'url' && key !== 'css' ) {
1399 // Backwards compatibility, key is a media-type
1400 if ( typeof value === 'string' ) {
1401 // back-compat: { <media>: css }
1402 // Ignore 'media' because it isn't supported (nor was it used).
1403 // Strings are pre-wrapped in "@media". The media-type was just ""
1404 // (because it had to be set to something).
1405 // This is one of the reasons why this format is no longer used.
1406 addEmbeddedCSS( value, cssHandle() );
1408 // back-compat: { <media>: [url, ..] }
1414 // Array of css strings in key 'css',
1415 // or back-compat array of urls from media-type
1416 if ( $.isArray( value ) ) {
1417 for ( i = 0; i < value.length; i++ ) {
1418 if ( key === 'bc-url' ) {
1419 // back-compat: { <media>: [url, ..] }
1420 addLink( media, value[ i ] );
1421 } else if ( key === 'css' ) {
1422 // { "css": [css, ..] }
1423 addEmbeddedCSS( value[ i ], cssHandle() );
1426 // Not an array, but a regular object
1427 // Array of urls inside media-type key
1428 } else if ( typeof value === 'object' ) {
1429 // { "url": { <media>: [url, ..] } }
1430 for ( media in value ) {
1431 urls = value[ media ];
1432 for ( i = 0; i < urls.length; i++ ) {
1433 addLink( media, urls[ i ] );
1441 cssHandlesRegistered = true;
1446 * Add one or more modules to the module load queue.
1451 * @param {string|string[]} dependencies Module name or array of string module names
1452 * @param {Function} [ready] Callback to execute when all dependencies are ready
1453 * @param {Function} [error] Callback to execute when any dependency fails
1455 function enqueue( dependencies, ready, error ) {
1456 // Allow calling by single module name
1457 if ( typeof dependencies === 'string' ) {
1458 dependencies = [ dependencies ];
1461 // Add ready and error callbacks if they were given
1462 if ( ready !== undefined || error !== undefined ) {
1464 // Narrow down the list to modules that are worth waiting for
1465 dependencies: $.grep( dependencies, function ( module ) {
1466 var state = mw.loader.getState( module );
1467 return state === 'registered' || state === 'loaded' || state === 'loading' || state === 'executing';
1474 $.each( dependencies, function ( idx, module ) {
1475 var state = mw.loader.getState( module );
1476 // Only queue modules that are still in the initial 'registered' state
1477 // (not ones already loading, ready or error).
1478 if ( state === 'registered' && $.inArray( module, queue ) === -1 ) {
1479 // Private modules must be embedded in the page. Don't bother queuing
1480 // these as the server will deny them anyway (T101806).
1481 if ( registry[ module ].group === 'private' ) {
1482 registry[ module ].state = 'error';
1483 handlePending( module );
1486 queue.push( module );
1493 function sortQuery( o ) {
1499 if ( hasOwn.call( o, key ) ) {
1504 for ( key = 0; key < a.length; key++ ) {
1505 sorted[ a[ key ] ] = o[ a[ key ] ];
1511 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
1512 * to a query string of the form foo.bar,baz|bar.baz,quux
1515 * @param {Object} moduleMap Module map
1516 * @return {string} Module query string
1518 function buildModulesString( moduleMap ) {
1522 for ( prefix in moduleMap ) {
1523 p = prefix === '' ? '' : prefix + '.';
1524 arr.push( p + moduleMap[ prefix ].join( ',' ) );
1526 return arr.join( '|' );
1530 * Make a network request to load modules from the server.
1533 * @param {Object} moduleMap Module map, see #buildModulesString
1534 * @param {Object} currReqBase Object with other parameters (other than 'modules') to use in the request
1535 * @param {string} sourceLoadScript URL of load.php
1537 function doRequest( moduleMap, currReqBase, sourceLoadScript ) {
1538 var query = $.extend(
1539 { modules: buildModulesString( moduleMap ) },
1542 query = sortQuery( query );
1543 addScript( sourceLoadScript + '?' + $.param( query ) );
1547 * Resolve indexed dependencies.
1549 * ResourceLoader uses an optimization to save space which replaces module names in
1550 * dependency lists with the index of that module within the array of module
1551 * registration data if it exists. The benefit is a significant reduction in the data
1552 * size of the startup module. This function changes those dependency lists back to
1553 * arrays of strings.
1556 * @param {Array} modules Modules array
1558 function resolveIndexedDependencies( modules ) {
1560 function resolveIndex( dep ) {
1561 return typeof dep === 'number' ? modules[ dep ][ 0 ] : dep;
1563 for ( i = 0; i < modules.length; i++ ) {
1564 deps = modules[ i ][ 2 ];
1566 for ( j = 0; j < deps.length; j++ ) {
1567 deps[ j ] = resolveIndex( deps[ j ] );
1574 * Create network requests for a batch of modules.
1576 * This is an internal method for #work(). This must not be called directly
1577 * unless the modules are already registered, and no request is in progress,
1578 * and the module state has already been set to `loading`.
1581 * @param {string[]} batch
1583 function batchRequest( batch ) {
1584 var reqBase, splits, maxQueryLength, b, bSource, bGroup, bSourceGroup,
1585 source, group, i, modules, sourceLoadScript,
1586 currReqBase, currReqBaseLength, moduleMap, l,
1587 lastDotIndex, prefix, suffix, bytesAdded;
1589 if ( !batch.length ) {
1593 // Always order modules alphabetically to help reduce cache
1594 // misses for otherwise identical content.
1597 // Build a list of query parameters common to all requests
1599 skin: mw.config.get( 'skin' ),
1600 lang: mw.config.get( 'wgUserLanguage' ),
1601 debug: mw.config.get( 'debug' )
1603 maxQueryLength = mw.config.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1605 // Split module list by source and by group.
1607 for ( b = 0; b < batch.length; b++ ) {
1608 bSource = registry[ batch[ b ] ].source;
1609 bGroup = registry[ batch[ b ] ].group;
1610 if ( !hasOwn.call( splits, bSource ) ) {
1611 splits[ bSource ] = {};
1613 if ( !hasOwn.call( splits[ bSource ], bGroup ) ) {
1614 splits[ bSource ][ bGroup ] = [];
1616 bSourceGroup = splits[ bSource ][ bGroup ];
1617 bSourceGroup.push( batch[ b ] );
1620 for ( source in splits ) {
1622 sourceLoadScript = sources[ source ];
1624 for ( group in splits[ source ] ) {
1626 // Cache access to currently selected list of
1627 // modules for this group from this source.
1628 modules = splits[ source ][ group ];
1630 currReqBase = $.extend( {
1631 version: getCombinedVersion( modules )
1633 // For user modules append a user name to the query string.
1634 if ( group === 'user' && mw.config.get( 'wgUserName' ) !== null ) {
1635 currReqBase.user = mw.config.get( 'wgUserName' );
1637 currReqBaseLength = $.param( currReqBase ).length;
1638 // We may need to split up the request to honor the query string length limit,
1639 // so build it piece by piece.
1640 l = currReqBaseLength + 9; // '&modules='.length == 9
1642 moduleMap = {}; // { prefix: [ suffixes ] }
1644 for ( i = 0; i < modules.length; i++ ) {
1645 // Determine how many bytes this module would add to the query string
1646 lastDotIndex = modules[ i ].lastIndexOf( '.' );
1648 // If lastDotIndex is -1, substr() returns an empty string
1649 prefix = modules[ i ].substr( 0, lastDotIndex );
1650 suffix = modules[ i ].slice( lastDotIndex + 1 );
1652 bytesAdded = hasOwn.call( moduleMap, prefix ) ?
1653 suffix.length + 3 : // '%2C'.length == 3
1654 modules[ i ].length + 3; // '%7C'.length == 3
1656 // If the url would become too long, create a new one,
1657 // but don't create empty requests
1658 if ( maxQueryLength > 0 && !$.isEmptyObject( moduleMap ) && l + bytesAdded > maxQueryLength ) {
1659 // This url would become too long, create a new one, and start the old one
1660 doRequest( moduleMap, currReqBase, sourceLoadScript );
1662 l = currReqBaseLength + 9;
1663 mw.track( 'resourceloader.splitRequest', { maxQueryLength: maxQueryLength } );
1665 if ( !hasOwn.call( moduleMap, prefix ) ) {
1666 moduleMap[ prefix ] = [];
1668 moduleMap[ prefix ].push( suffix );
1671 // If there's anything left in moduleMap, request that too
1672 if ( !$.isEmptyObject( moduleMap ) ) {
1673 doRequest( moduleMap, currReqBase, sourceLoadScript );
1681 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1682 * form of calls to mw.loader#implement().
1683 * @param {Function} cb Callback in case of failure
1684 * @param {Error} cb.err
1686 function asyncEval( implementations, cb ) {
1687 if ( !implementations.length ) {
1690 mw.requestIdleCallback( function () {
1692 $.globalEval( implementations.join( ';' ) );
1700 * Make a versioned key for a specific module.
1703 * @param {string} module Module name
1704 * @return {string|null} Module key in format '`[name]@[version]`',
1705 * or null if the module does not exist
1707 function getModuleKey( module ) {
1708 return hasOwn.call( registry, module ) ?
1709 ( module + '@' + registry[ module ].version ) : null;
1714 * @param {string} key Module name or '`[name]@[version]`'
1717 function splitModuleKey( key ) {
1718 var index = key.indexOf( '@' );
1719 if ( index === -1 ) {
1720 return { name: key };
1723 name: key.slice( 0, index ),
1724 version: key.slice( index + 1 )
1728 /* Public Members */
1731 * The module registry is exposed as an aid for debugging and inspecting page
1732 * state; it is not a public interface for modifying the registry.
1738 moduleRegistry: registry,
1741 * @inheritdoc #newStyleTag
1744 addStyleTag: newStyleTag,
1747 * Start loading of all queued module dependencies.
1752 var q, batch, implementations, sourceModules;
1756 // Appends a list of modules from the queue to the batch
1757 for ( q = 0; q < queue.length; q++ ) {
1758 // Only load modules which are registered
1759 if ( hasOwn.call( registry, queue[ q ] ) && registry[ queue[ q ] ].state === 'registered' ) {
1760 // Prevent duplicate entries
1761 if ( $.inArray( queue[ q ], batch ) === -1 ) {
1762 batch.push( queue[ q ] );
1763 // Mark registered modules as loading
1764 registry[ queue[ q ] ].state = 'loading';
1769 // Now that the queue has been processed into a batch, clear the queue.
1770 // This MUST happen before we initiate any eval or network request. Otherwise,
1771 // it is possible for a cached script to instantly trigger the same work queue
1772 // again; all before we've cleared it causing each request to include modules
1773 // which are already loaded.
1776 if ( !batch.length ) {
1780 mw.loader.store.init();
1781 if ( mw.loader.store.enabled ) {
1782 implementations = [];
1784 batch = $.grep( batch, function ( module ) {
1785 var implementation = mw.loader.store.get( module );
1786 if ( implementation ) {
1787 implementations.push( implementation );
1788 sourceModules.push( module );
1793 asyncEval( implementations, function ( err ) {
1795 // Not good, the cached mw.loader.implement calls failed! This should
1796 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1797 // Depending on how corrupt the string is, it is likely that some
1798 // modules' implement() succeeded while the ones after the error will
1799 // never run and leave their modules in the 'loading' state forever.
1800 mw.loader.store.stats.failed++;
1802 // Since this is an error not caused by an individual module but by
1803 // something that infected the implement call itself, don't take any
1804 // risks and clear everything in this cache.
1805 mw.loader.store.clear();
1807 mw.track( 'resourceloader.exception', { exception: err, source: 'store-eval' } );
1808 // Re-add the failed ones that are still pending back to the batch
1809 failed = $.grep( sourceModules, function ( module ) {
1810 return registry[ module ].state === 'loading';
1812 batchRequest( failed );
1816 batchRequest( batch );
1820 * Register a source.
1822 * The #work() method will use this information to split up requests by source.
1824 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1826 * @param {string|Object} id Source ID, or object mapping ids to load urls
1827 * @param {string} loadUrl Url to a load.php end point
1828 * @throws {Error} If source id is already registered
1830 addSource: function ( id, loadUrl ) {
1832 // Allow multiple additions
1833 if ( typeof id === 'object' ) {
1834 for ( source in id ) {
1835 mw.loader.addSource( source, id[ source ] );
1840 if ( hasOwn.call( sources, id ) ) {
1841 throw new Error( 'source already registered: ' + id );
1844 sources[ id ] = loadUrl;
1848 * Register a module, letting the system know about it and its properties.
1850 * The startup modules contain calls to this method.
1852 * When using multiple module registration by passing an array, dependencies that
1853 * are specified as references to modules within the array will be resolved before
1854 * the modules are registered.
1856 * @param {string|Array} module Module name or array of arrays, each containing
1857 * a list of arguments compatible with this method
1858 * @param {string|number} version Module version hash (falls backs to empty string)
1859 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1860 * @param {string|Array|Function} dependencies One string or array of strings of module
1861 * names on which this module depends, or a function that returns that array.
1862 * @param {string} [group=null] Group which the module is in
1863 * @param {string} [source='local'] Name of the source
1864 * @param {string} [skip=null] Script body of the skip function
1866 register: function ( module, version, dependencies, group, source, skip ) {
1868 // Allow multiple registration
1869 if ( typeof module === 'object' ) {
1870 resolveIndexedDependencies( module );
1871 for ( i = 0; i < module.length; i++ ) {
1872 // module is an array of module names
1873 if ( typeof module[ i ] === 'string' ) {
1874 mw.loader.register( module[ i ] );
1875 // module is an array of arrays
1876 } else if ( typeof module[ i ] === 'object' ) {
1877 mw.loader.register.apply( mw.loader, module[ i ] );
1882 if ( hasOwn.call( registry, module ) ) {
1883 throw new Error( 'module already registered: ' + module );
1885 if ( typeof dependencies === 'string' ) {
1886 // A single module name
1887 deps = [ dependencies ];
1888 } else if ( typeof dependencies === 'object' || typeof dependencies === 'function' ) {
1889 // Array of module names or a function that returns an array
1890 deps = dependencies;
1892 // List the module as registered
1893 registry[ module ] = {
1894 // Exposed to execute() for mw.loader.implement() closures.
1895 // Import happens via require().
1899 version: version !== undefined ? String( version ) : '',
1900 dependencies: deps || [],
1901 group: typeof group === 'string' ? group : null,
1902 source: typeof source === 'string' ? source : 'local',
1903 state: 'registered',
1904 skip: typeof skip === 'string' ? skip : null
1909 * Implement a module given the components that make up the module.
1911 * When #load() or #using() requests one or more modules, the server
1912 * response contain calls to this function.
1914 * @param {string} module Name of module and current module version. Formatted
1915 * as '`[name]@[version]`". This version should match the requested version
1916 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1917 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1918 * @param {Function|Array|string} [script] Function with module code, list of URLs
1919 * to load via `<script src>`, or string of module code for `$.globalEval()`.
1920 * @param {Object} [style] Should follow one of the following patterns:
1922 * { "css": [css, ..] }
1923 * { "url": { <media>: [url, ..] } }
1925 * And for backwards compatibility (needs to be supported forever due to caching):
1928 * { <media>: [url, ..] }
1930 * The reason css strings are not concatenated anymore is bug 31676. We now check
1931 * whether it's safe to extend the stylesheet.
1934 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1935 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1937 implement: function ( module, script, style, messages, templates ) {
1938 var split = splitModuleKey( module ),
1940 version = split.version;
1941 // Automatically register module
1942 if ( !hasOwn.call( registry, name ) ) {
1943 mw.loader.register( name );
1945 // Check for duplicate implementation
1946 if ( hasOwn.call( registry, name ) && registry[ name ].script !== undefined ) {
1947 throw new Error( 'module already implemented: ' + name );
1950 // Without this reset, if there is a version mismatch between the
1951 // requested and received module version, then mw.loader.store would
1952 // cache the response under the requested key. Thus poisoning the cache
1953 // indefinitely with a stale value. (T117587)
1954 registry[ name ].version = version;
1956 // Attach components
1957 registry[ name ].script = script || null;
1958 registry[ name ].style = style || null;
1959 registry[ name ].messages = messages || null;
1960 registry[ name ].templates = templates || null;
1961 // The module may already have been marked as erroneous
1962 if ( $.inArray( registry[ name ].state, [ 'error', 'missing' ] ) === -1 ) {
1963 registry[ name ].state = 'loaded';
1964 if ( allReady( registry[ name ].dependencies ) ) {
1971 * Execute a function as soon as one or more required modules are ready.
1973 * Example of inline dependency on OOjs:
1975 * mw.loader.using( 'oojs', function () {
1976 * OO.compare( [ 1 ], [ 1 ] );
1979 * Since MediaWiki 1.23 this also returns a promise.
1981 * Since MediaWiki 1.28 the promise is resolved with a `require` function.
1983 * @param {string|Array} dependencies Module name or array of modules names the
1984 * callback depends on to be ready before executing
1985 * @param {Function} [ready] Callback to execute when all dependencies are ready
1986 * @param {Function} [error] Callback to execute if one or more dependencies failed
1987 * @return {jQuery.Promise} With a `require` function
1989 using: function ( dependencies, ready, error ) {
1990 var deferred = $.Deferred();
1992 // Allow calling with a single dependency as a string
1993 if ( typeof dependencies === 'string' ) {
1994 dependencies = [ dependencies ];
1998 deferred.done( ready );
2001 deferred.fail( error );
2005 // Resolve entire dependency map
2006 dependencies = resolve( dependencies );
2008 return deferred.reject( e ).promise();
2010 if ( allReady( dependencies ) ) {
2011 // Run ready immediately
2012 deferred.resolve( mw.loader.require );
2013 } else if ( anyFailed( dependencies ) ) {
2014 // Execute error immediately if any dependencies have errors
2016 new Error( 'One or more dependencies failed to load' ),
2020 // Not all dependencies are ready, add to the load queue
2021 enqueue( dependencies, function () {
2022 deferred.resolve( mw.loader.require );
2023 }, deferred.reject );
2026 return deferred.promise();
2030 * Load an external script or one or more modules.
2032 * @param {string|Array} modules Either the name of a module, array of modules,
2033 * or a URL of an external script or style
2034 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
2035 * external script or style; acceptable values are "text/css" and
2036 * "text/javascript"; if no type is provided, text/javascript is assumed.
2038 load: function ( modules, type ) {
2041 // Allow calling with a url or single dependency as a string
2042 if ( typeof modules === 'string' ) {
2043 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
2044 if ( /^(https?:)?\/?\//.test( modules ) ) {
2045 if ( type === 'text/css' ) {
2047 // Use properties instead of attributes as IE throws security
2048 // warnings when inserting a <link> tag with a protocol-relative
2049 // URL set though attributes - when on HTTPS. See bug 41331.
2050 l = document.createElement( 'link' );
2051 l.rel = 'stylesheet';
2053 $( 'head' ).append( l );
2056 if ( type === 'text/javascript' || type === undefined ) {
2057 addScript( modules );
2061 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type );
2063 // Called with single module
2064 modules = [ modules ];
2067 // Filter out undefined modules, otherwise resolve() will throw
2068 // an exception for trying to load an undefined module.
2069 // Undefined modules are acceptable here in load(), because load() takes
2070 // an array of unrelated modules, whereas the modules passed to
2071 // using() are related and must all be loaded.
2072 filtered = $.grep( modules, function ( module ) {
2073 var state = mw.loader.getState( module );
2074 return state !== null && state !== 'error' && state !== 'missing';
2077 if ( filtered.length === 0 ) {
2080 // Resolve entire dependency map
2081 filtered = resolve( filtered );
2082 // If all modules are ready, or if any modules have errors, nothing to be done.
2083 if ( allReady( filtered ) || anyFailed( filtered ) ) {
2086 // Some modules are not yet ready, add to module load queue.
2087 enqueue( filtered, undefined, undefined );
2091 * Change the state of one or more modules.
2093 * @param {string|Object} module Module name or object of module name/state pairs
2094 * @param {string} state State name
2096 state: function ( module, state ) {
2099 if ( typeof module === 'object' ) {
2100 for ( m in module ) {
2101 mw.loader.state( m, module[ m ] );
2105 if ( !hasOwn.call( registry, module ) ) {
2106 mw.loader.register( module );
2108 registry[ module ].state = state;
2109 if ( $.inArray( state, [ 'ready', 'error', 'missing' ] ) !== -1 ) {
2110 // Make sure pending modules depending on this one get executed if their
2111 // dependencies are now fulfilled!
2112 handlePending( module );
2117 * Get the version of a module.
2119 * @param {string} module Name of module
2120 * @return {string|null} The version, or null if the module (or its version) is not
2123 getVersion: function ( module ) {
2124 if ( !hasOwn.call( registry, module ) || registry[ module ].version === undefined ) {
2127 return registry[ module ].version;
2131 * Get the state of a module.
2133 * @param {string} module Name of module
2134 * @return {string|null} The state, or null if the module (or its state) is not
2137 getState: function ( module ) {
2138 if ( !hasOwn.call( registry, module ) || registry[ module ].state === undefined ) {
2141 return registry[ module ].state;
2145 * Get the names of all registered modules.
2149 getModuleNames: function () {
2150 return $.map( registry, function ( i, key ) {
2156 * Get the exported value of a module.
2158 * Modules may provide this via their local `module.exports`.
2162 * @param {string} moduleName Module name
2163 * @return {Mixed} Exported value
2165 require: function ( moduleName ) {
2166 var state = mw.loader.getState( moduleName );
2168 // Only ready modules can be required
2169 if ( state !== 'ready' ) {
2170 // Module may've forgotten to declare a dependency
2171 throw new Error( 'Module "' + moduleName + '" is not loaded.' );
2174 return registry[ moduleName ].module.exports;
2178 * @inheritdoc mw.inspect#runReports
2181 inspect: function () {
2182 var args = slice.call( arguments );
2183 mw.loader.using( 'mediawiki.inspect', function () {
2184 mw.inspect.runReports.apply( mw.inspect, args );
2189 * On browsers that implement the localStorage API, the module store serves as a
2190 * smart complement to the browser cache. Unlike the browser cache, the module store
2191 * can slice a concatenated response from ResourceLoader into its constituent
2192 * modules and cache each of them separately, using each module's versioning scheme
2193 * to determine when the cache should be invalidated.
2196 * @class mw.loader.store
2199 // Whether the store is in use on this page.
2202 MODULE_SIZE_MAX: 100 * 1000,
2204 // The contents of the store, mapping '[name]@[version]' keys
2205 // to module implementations.
2209 stats: { hits: 0, misses: 0, expired: 0, failed: 0 },
2212 * Construct a JSON-serializable object representing the content of the store.
2214 * @return {Object} Module store contents.
2216 toJSON: function () {
2217 return { items: mw.loader.store.items, vary: mw.loader.store.getVary() };
2221 * Get the localStorage key for the entire module store. The key references
2222 * $wgDBname to prevent clashes between wikis which share a common host.
2224 * @return {string} localStorage item key
2226 getStoreKey: function () {
2227 return 'MediaWikiModuleStore:' + mw.config.get( 'wgDBname' );
2231 * Get a key on which to vary the module cache.
2233 * @return {string} String of concatenated vary conditions.
2235 getVary: function () {
2237 mw.config.get( 'skin' ),
2238 mw.config.get( 'wgResourceLoaderStorageVersion' ),
2239 mw.config.get( 'wgUserLanguage' )
2244 * Initialize the store.
2246 * Retrieves store from localStorage and (if successfully retrieved) decoding
2247 * the stored JSON value to a plain object.
2249 * The try / catch block is used for JSON & localStorage feature detection.
2250 * See the in-line documentation for Modernizr's localStorage feature detection
2251 * code for a full account of why we need a try / catch:
2252 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2257 if ( mw.loader.store.enabled !== null ) {
2263 // Disabled because localStorage quotas are tight and (in Firefox's case)
2264 // shared by multiple origins.
2265 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2266 /Firefox|Opera/.test( navigator.userAgent ) ||
2268 // Disabled by configuration.
2269 !mw.config.get( 'wgResourceLoaderStorageEnabled' )
2271 // Clear any previous store to free up space. (T66721)
2272 mw.loader.store.clear();
2273 mw.loader.store.enabled = false;
2276 if ( mw.config.get( 'debug' ) ) {
2277 // Disable module store in debug mode
2278 mw.loader.store.enabled = false;
2283 raw = localStorage.getItem( mw.loader.store.getStoreKey() );
2284 // If we get here, localStorage is available; mark enabled
2285 mw.loader.store.enabled = true;
2286 data = JSON.parse( raw );
2287 if ( data && typeof data.items === 'object' && data.vary === mw.loader.store.getVary() ) {
2288 mw.loader.store.items = data.items;
2292 mw.track( 'resourceloader.exception', { exception: e, source: 'store-localstorage-init' } );
2295 if ( raw === undefined ) {
2296 // localStorage failed; disable store
2297 mw.loader.store.enabled = false;
2299 mw.loader.store.update();
2304 * Retrieve a module from the store and update cache hit stats.
2306 * @param {string} module Module name
2307 * @return {string|boolean} Module implementation or false if unavailable
2309 get: function ( module ) {
2312 if ( !mw.loader.store.enabled ) {
2316 key = getModuleKey( module );
2317 if ( key in mw.loader.store.items ) {
2318 mw.loader.store.stats.hits++;
2319 return mw.loader.store.items[ key ];
2321 mw.loader.store.stats.misses++;
2326 * Stringify a module and queue it for storage.
2328 * @param {string} module Module name
2329 * @param {Object} descriptor The module's descriptor as set in the registry
2330 * @return {boolean} Module was set
2332 set: function ( module, descriptor ) {
2335 if ( !mw.loader.store.enabled ) {
2339 key = getModuleKey( module );
2342 // Already stored a copy of this exact version
2343 key in mw.loader.store.items ||
2344 // Module failed to load
2345 descriptor.state !== 'ready' ||
2346 // Unversioned, private, or site-/user-specific
2347 ( !descriptor.version || $.inArray( descriptor.group, [ 'private', 'user' ] ) !== -1 ) ||
2348 // Partial descriptor
2349 // (e.g. skipped module, or style module with state=ready)
2350 $.inArray( undefined, [ descriptor.script, descriptor.style,
2351 descriptor.messages, descriptor.templates ] ) !== -1
2359 JSON.stringify( key ),
2360 typeof descriptor.script === 'function' ?
2361 String( descriptor.script ) :
2362 JSON.stringify( descriptor.script ),
2363 JSON.stringify( descriptor.style ),
2364 JSON.stringify( descriptor.messages ),
2365 JSON.stringify( descriptor.templates )
2367 // Attempted workaround for a possible Opera bug (bug T59567).
2368 // This regex should never match under sane conditions.
2369 if ( /^\s*\(/.test( args[ 1 ] ) ) {
2370 args[ 1 ] = 'function' + args[ 1 ];
2371 mw.track( 'resourceloader.assert', { source: 'bug-T59567' } );
2374 mw.track( 'resourceloader.exception', { exception: e, source: 'store-localstorage-json' } );
2378 src = 'mw.loader.implement(' + args.join( ',' ) + ');';
2379 if ( src.length > mw.loader.store.MODULE_SIZE_MAX ) {
2382 mw.loader.store.items[ key ] = src;
2383 mw.loader.store.update();
2388 * Iterate through the module store, removing any item that does not correspond
2389 * (in name and version) to an item in the module registry.
2391 * @return {boolean} Store was pruned
2393 prune: function () {
2396 if ( !mw.loader.store.enabled ) {
2400 for ( key in mw.loader.store.items ) {
2401 module = key.slice( 0, key.indexOf( '@' ) );
2402 if ( getModuleKey( module ) !== key ) {
2403 mw.loader.store.stats.expired++;
2404 delete mw.loader.store.items[ key ];
2405 } else if ( mw.loader.store.items[ key ].length > mw.loader.store.MODULE_SIZE_MAX ) {
2406 // This value predates the enforcement of a size limit on cached modules.
2407 delete mw.loader.store.items[ key ];
2414 * Clear the entire module store right now.
2416 clear: function () {
2417 mw.loader.store.items = {};
2419 localStorage.removeItem( mw.loader.store.getStoreKey() );
2420 } catch ( ignored ) {}
2424 * Sync in-memory store back to localStorage.
2426 * This function debounces updates. When called with a flush already pending,
2427 * the call is coalesced into the pending update. The call to
2428 * localStorage.setItem will be naturally deferred until the page is quiescent.
2430 * Because localStorage is shared by all pages from the same origin, if multiple
2431 * pages are loaded with different module sets, the possibility exists that
2432 * modules saved by one page will be clobbered by another. But the impact would
2433 * be minor and the problem would be corrected by subsequent page views.
2437 update: ( function () {
2438 var hasPendingWrite = false;
2440 function flushWrites() {
2442 if ( !hasPendingWrite || !mw.loader.store.enabled ) {
2446 mw.loader.store.prune();
2447 key = mw.loader.store.getStoreKey();
2449 // Replacing the content of the module store might fail if the new
2450 // contents would exceed the browser's localStorage size limit. To
2451 // avoid clogging the browser with stale data, always remove the old
2452 // value before attempting to set the new one.
2453 localStorage.removeItem( key );
2454 data = JSON.stringify( mw.loader.store );
2455 localStorage.setItem( key, data );
2457 mw.track( 'resourceloader.exception', { exception: e, source: 'store-localstorage-update' } );
2460 hasPendingWrite = false;
2463 return function () {
2464 if ( !hasPendingWrite ) {
2465 hasPendingWrite = true;
2466 mw.requestIdleCallback( flushWrites );
2475 * HTML construction helper functions
2482 * output = Html.element( 'div', {}, new Html.Raw(
2483 * Html.element( 'img', { src: '<' } )
2485 * mw.log( output ); // <div><img src="<"/></div>
2490 html: ( function () {
2491 function escapeCallback( s ) {
2508 * Escape a string for HTML.
2510 * Converts special characters to HTML entities.
2512 * mw.html.escape( '< > \' & "' );
2513 * // Returns < > ' & "
2515 * @param {string} s The string to escape
2516 * @return {string} HTML
2518 escape: function ( s ) {
2519 return s.replace( /['"<>&]/g, escapeCallback );
2523 * Create an HTML element string, with safe escaping.
2525 * @param {string} name The tag name.
2526 * @param {Object} [attrs] An object with members mapping element names to values
2527 * @param {string|mw.html.Raw|mw.html.Cdata|null} [contents=null] The contents of the element.
2529 * - string: Text to be escaped.
2530 * - null: The element is treated as void with short closing form, e.g. `<br/>`.
2531 * - this.Raw: The raw value is directly included.
2532 * - this.Cdata: The raw value is directly included. An exception is
2533 * thrown if it contains any illegal ETAGO delimiter.
2534 * See <https://www.w3.org/TR/html401/appendix/notes.html#h-B.3.2>.
2535 * @return {string} HTML
2537 element: function ( name, attrs, contents ) {
2538 var v, attrName, s = '<' + name;
2541 for ( attrName in attrs ) {
2542 v = attrs[ attrName ];
2543 // Convert name=true, to name=name
2547 } else if ( v === false ) {
2550 s += ' ' + attrName + '="' + this.escape( String( v ) ) + '"';
2553 if ( contents === undefined || contents === null ) {
2560 switch ( typeof contents ) {
2563 s += this.escape( contents );
2567 // Convert to string
2568 s += String( contents );
2571 if ( contents instanceof this.Raw ) {
2572 // Raw HTML inclusion
2573 s += contents.value;
2574 } else if ( contents instanceof this.Cdata ) {
2576 if ( /<\/[a-zA-z]/.test( contents.value ) ) {
2577 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
2579 s += contents.value;
2581 throw new Error( 'mw.html.element: Invalid type of contents' );
2584 s += '</' + name + '>';
2589 * Wrapper object for raw HTML passed to mw.html.element().
2591 * @class mw.html.Raw
2593 * @param {string} value
2595 Raw: function ( value ) {
2600 * Wrapper object for CDATA element contents passed to mw.html.element()
2602 * @class mw.html.Cdata
2604 * @param {string} value
2606 Cdata: function ( value ) {
2612 // Skeleton user object, extended by the 'mediawiki.user' module.
2619 * @property {mw.Map}
2623 * @property {mw.Map}
2628 // OOUI widgets specific to MediaWiki
2632 * Registry and firing of events.
2634 * MediaWiki has various interface components that are extended, enhanced
2635 * or manipulated in some other way by extensions, gadgets and even
2638 * This framework helps streamlining the timing of when these other
2639 * code paths fire their plugins (instead of using document-ready,
2640 * which can and should be limited to firing only once).
2642 * Features like navigating to other wiki pages, previewing an edit
2643 * and editing itself – without a refresh – can then retrigger these
2644 * hooks accordingly to ensure everything still works as expected.
2648 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
2649 * mw.hook( 'wikipage.content' ).fire( $content );
2651 * Handlers can be added and fired for arbitrary event names at any time. The same
2652 * event can be fired multiple times. The last run of an event is memorized
2653 * (similar to `$(document).ready` and `$.Deferred().done`).
2654 * This means if an event is fired, and a handler added afterwards, the added
2655 * function will be fired right away with the last given event data.
2657 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
2658 * Thus allowing flexible use and optimal maintainability and authority control.
2659 * You can pass around the `add` and/or `fire` method to another piece of code
2660 * without it having to know the event name (or `mw.hook` for that matter).
2662 * var h = mw.hook( 'bar.ready' );
2663 * new mw.Foo( .. ).fetch( { callback: h.fire } );
2665 * Note: Events are documented with an underscore instead of a dot in the event
2666 * name due to jsduck not supporting dots in that position.
2670 hook: ( function () {
2674 * Create an instance of mw.hook.
2678 * @param {string} name Name of hook.
2681 return function ( name ) {
2682 var list = hasOwn.call( lists, name ) ?
2684 lists[ name ] = $.Callbacks( 'memory' );
2688 * Register a hook handler
2690 * @param {...Function} handler Function to bind.
2696 * Unregister a hook handler
2698 * @param {...Function} handler Function to unbind.
2701 remove: list.remove,
2703 // eslint-disable-next-line valid-jsdoc
2707 * @param {...Mixed} data
2711 return list.fireWith.call( this, null, slice.call( arguments ) );
2718 // Alias $j to jQuery for backwards compatibility
2719 // @deprecated since 1.23 Use $ or jQuery instead
2720 mw.log.deprecate( window, '$j', $, 'Use $ or jQuery instead.' );
2723 * Log a message to window.console, if possible.
2725 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
2726 * also in production mode). Gets console references in each invocation instead of caching the
2727 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
2730 * @param {string} topic Stream name passed by mw.track
2731 * @param {Object} data Data passed by mw.track
2732 * @param {Error} [data.exception]
2733 * @param {string} data.source Error source
2734 * @param {string} [data.module] Name of module which caused the error
2736 function logError( topic, data ) {
2737 /* eslint-disable no-console */
2740 source = data.source,
2741 module = data.module,
2742 console = window.console;
2744 if ( console && console.log ) {
2745 msg = ( e ? 'Exception' : 'Error' ) + ' in ' + source;
2747 msg += ' in module ' + module;
2749 msg += ( e ? ':' : '.' );
2752 // If we have an exception object, log it to the error channel to trigger
2753 // proper stacktraces in browsers that support it. No fallback as we have
2754 // no browsers that don't support error(), but do support log().
2755 if ( e && console.error ) {
2756 console.error( String( e ), e );
2759 /* eslint-enable no-console */
2762 // Subscribe to error streams
2763 mw.trackSubscribe( 'resourceloader.exception', logError );
2764 mw.trackSubscribe( 'resourceloader.assert', logError );
2767 * Fired when all modules associated with the page have finished loading.
2769 * @event resourceloader_loadEnd
2773 var loading = $.grep( mw.loader.getModuleNames(), function ( module ) {
2774 return mw.loader.getState( module ) === 'loading';
2776 // We only need a callback, not any actual module. First try a single using()
2777 // for all loading modules. If one fails, fall back to tracking each module
2778 // separately via $.when(), this is expensive.
2779 loading = mw.loader.using( loading ).then( null, function () {
2780 var all = $.map( loading, function ( module ) {
2781 return mw.loader.using( module ).then( null, function () {
2782 return $.Deferred().resolve();
2785 return $.when.apply( $, all );
2787 loading.then( function () {
2788 mwPerformance.mark( 'mwLoadEnd' );
2789 mw.hook( 'resourceloader.loadEnd' ).fire();
2793 // Attach to window and globally alias
2794 window.mw = window.mediaWiki = mw;