Merge "Improve sorting on SpecialWanted*-Pages"
[mediawiki.git] / resources / src / mediawiki / mediawiki.js
blob33f146b9d46e7fe2426767244542fdecf51edcdc
1 /**
2  * Base library for MediaWiki.
3  *
4  * Exposed globally as `mediaWiki` with `mw` as shortcut.
5  *
6  * @class mw
7  * @alternateClassName mediaWiki
8  * @singleton
9  */
11 /* global mwNow */
12 /* eslint-disable no-use-before-define */
14 ( function ( $ ) {
15         'use strict';
17         var mw, StringSet, log,
18                 hasOwn = Object.prototype.hasOwnProperty,
19                 slice = Array.prototype.slice,
20                 trackCallbacks = $.Callbacks( 'memory' ),
21                 trackHandlers = [],
22                 trackQueue = [];
24         /**
25          * FNV132 hash function
26          *
27          * This function implements the 32-bit version of FNV-1.
28          * It is equivalent to hash( 'fnv132', ... ) in PHP, except
29          * its output is base 36 rather than hex.
30          * See <https://en.wikipedia.org/wiki/FNV_hash_function>
31          *
32          * @private
33          * @param {string} str String to hash
34          * @return {string} hash as an seven-character base 36 string
35          */
36         function fnv132( str ) {
37                 /* eslint-disable no-bitwise */
38                 var hash = 0x811C9DC5,
39                         i;
41                 for ( i = 0; i < str.length; i++ ) {
42                         hash += ( hash << 1 ) + ( hash << 4 ) + ( hash << 7 ) + ( hash << 8 ) + ( hash << 24 );
43                         hash ^= str.charCodeAt( i );
44                 }
46                 hash = ( hash >>> 0 ).toString( 36 );
47                 while ( hash.length < 7 ) {
48                         hash = '0' + hash;
49                 }
51                 return hash;
52                 /* eslint-enable no-bitwise */
53         }
55         // <https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Set>
56         StringSet = window.Set || ( function () {
57                 /**
58                  * @private
59                  * @class
60                  */
61                 function StringSet() {
62                         this.set = {};
63                 }
64                 StringSet.prototype.add = function ( value ) {
65                         this.set[ value ] = true;
66                 };
67                 StringSet.prototype.has = function ( value ) {
68                         return hasOwn.call( this.set, value );
69                 };
70                 return StringSet;
71         }() );
73         /**
74          * Create an object that can be read from or written to via methods that allow
75          * interaction both with single and multiple properties at once.
76          *
77          * @private
78          * @class mw.Map
79          *
80          * @constructor
81          * @param {boolean} [global=false] Whether to synchronise =values to the global
82          *  window object (for backwards-compatibility with mw.config; T72470). Values are
83          *  copied in one direction only. Changes to globals do not reflect in the map.
84          */
85         function Map( global ) {
86                 this.values = {};
87                 if ( global === true ) {
88                         // Override #set to also set the global variable
89                         this.set = function ( selection, value ) {
90                                 var s;
92                                 if ( $.isPlainObject( selection ) ) {
93                                         for ( s in selection ) {
94                                                 setGlobalMapValue( this, s, selection[ s ] );
95                                         }
96                                         return true;
97                                 }
98                                 if ( typeof selection === 'string' && arguments.length ) {
99                                         setGlobalMapValue( this, selection, value );
100                                         return true;
101                                 }
102                                 return false;
103                         };
104                 }
105         }
107         /**
108          * Alias property to the global object.
109          *
110          * @private
111          * @static
112          * @param {mw.Map} map
113          * @param {string} key
114          * @param {Mixed} value
115          */
116         function setGlobalMapValue( map, key, value ) {
117                 map.values[ key ] = value;
118                 log.deprecate(
119                                 window,
120                                 key,
121                                 value,
122                                 // Deprecation notice for mw.config globals (T58550, T72470)
123                                 map === mw.config && 'Use mw.config instead.'
124                 );
125         }
127         Map.prototype = {
128                 constructor: Map,
130                 /**
131                  * Get the value of one or more keys.
132                  *
133                  * If called with no arguments, all values are returned.
134                  *
135                  * @param {string|Array} [selection] Key or array of keys to retrieve values for.
136                  * @param {Mixed} [fallback=null] Value for keys that don't exist.
137                  * @return {Mixed|Object|null} If selection was a string, returns the value,
138                  *  If selection was an array, returns an object of key/values.
139                  *  If no selection is passed, a new object with all key/values is returned.
140                  */
141                 get: function ( selection, fallback ) {
142                         var results, i;
143                         fallback = arguments.length > 1 ? fallback : null;
145                         if ( $.isArray( selection ) ) {
146                                 results = {};
147                                 for ( i = 0; i < selection.length; i++ ) {
148                                         if ( typeof selection[ i ] === 'string' ) {
149                                                 results[ selection[ i ] ] = hasOwn.call( this.values, selection[ i ] ) ?
150                                                         this.values[ selection[ i ] ] :
151                                                         fallback;
152                                         }
153                                 }
154                                 return results;
155                         }
157                         if ( typeof selection === 'string' ) {
158                                 return hasOwn.call( this.values, selection ) ?
159                                         this.values[ selection ] :
160                                         fallback;
161                         }
163                         if ( selection === undefined ) {
164                                 results = {};
165                                 for ( i in this.values ) {
166                                         results[ i ] = this.values[ i ];
167                                 }
168                                 return results;
169                         }
171                         // Invalid selection key
172                         return fallback;
173                 },
175                 /**
176                  * Set one or more key/value pairs.
177                  *
178                  * @param {string|Object} selection Key to set value for, or object mapping keys to values
179                  * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
180                  * @return {boolean} True on success, false on failure
181                  */
182                 set: function ( selection, value ) {
183                         var s;
185                         if ( $.isPlainObject( selection ) ) {
186                                 for ( s in selection ) {
187                                         this.values[ s ] = selection[ s ];
188                                 }
189                                 return true;
190                         }
191                         if ( typeof selection === 'string' && arguments.length > 1 ) {
192                                 this.values[ selection ] = value;
193                                 return true;
194                         }
195                         return false;
196                 },
198                 /**
199                  * Check if one or more keys exist.
200                  *
201                  * @param {Mixed} selection Key or array of keys to check
202                  * @return {boolean} True if the key(s) exist
203                  */
204                 exists: function ( selection ) {
205                         var i;
206                         if ( $.isArray( selection ) ) {
207                                 for ( i = 0; i < selection.length; i++ ) {
208                                         if ( typeof selection[ i ] !== 'string' || !hasOwn.call( this.values, selection[ i ] ) ) {
209                                                 return false;
210                                         }
211                                 }
212                                 return true;
213                         }
214                         return typeof selection === 'string' && hasOwn.call( this.values, selection );
215                 }
216         };
218         /**
219          * Object constructor for messages.
220          *
221          * Similar to the Message class in MediaWiki PHP.
222          *
223          * Format defaults to 'text'.
224          *
225          *     @example
226          *
227          *     var obj, str;
228          *     mw.messages.set( {
229          *         'hello': 'Hello world',
230          *         'hello-user': 'Hello, $1!',
231          *         'welcome-user': 'Welcome back to $2, $1! Last visit by $1: $3'
232          *     } );
233          *
234          *     obj = new mw.Message( mw.messages, 'hello' );
235          *     mw.log( obj.text() );
236          *     // Hello world
237          *
238          *     obj = new mw.Message( mw.messages, 'hello-user', [ 'John Doe' ] );
239          *     mw.log( obj.text() );
240          *     // Hello, John Doe!
241          *
242          *     obj = new mw.Message( mw.messages, 'welcome-user', [ 'John Doe', 'Wikipedia', '2 hours ago' ] );
243          *     mw.log( obj.text() );
244          *     // Welcome back to Wikipedia, John Doe! Last visit by John Doe: 2 hours ago
245          *
246          *     // Using mw.message shortcut
247          *     obj = mw.message( 'hello-user', 'John Doe' );
248          *     mw.log( obj.text() );
249          *     // Hello, John Doe!
250          *
251          *     // Using mw.msg shortcut
252          *     str = mw.msg( 'hello-user', 'John Doe' );
253          *     mw.log( str );
254          *     // Hello, John Doe!
255          *
256          *     // Different formats
257          *     obj = new mw.Message( mw.messages, 'hello-user', [ 'John "Wiki" <3 Doe' ] );
258          *
259          *     obj.format = 'text';
260          *     str = obj.toString();
261          *     // Same as:
262          *     str = obj.text();
263          *
264          *     mw.log( str );
265          *     // Hello, John "Wiki" <3 Doe!
266          *
267          *     mw.log( obj.escaped() );
268          *     // Hello, John &quot;Wiki&quot; &lt;3 Doe!
269          *
270          * @class mw.Message
271          *
272          * @constructor
273          * @param {mw.Map} map Message store
274          * @param {string} key
275          * @param {Array} [parameters]
276          */
277         function Message( map, key, parameters ) {
278                 this.format = 'text';
279                 this.map = map;
280                 this.key = key;
281                 this.parameters = parameters === undefined ? [] : slice.call( parameters );
282                 return this;
283         }
285         Message.prototype = {
286                 /**
287                  * Get parsed contents of the message.
288                  *
289                  * The default parser does simple $N replacements and nothing else.
290                  * This may be overridden to provide a more complex message parser.
291                  * The primary override is in the mediawiki.jqueryMsg module.
292                  *
293                  * This function will not be called for nonexistent messages.
294                  *
295                  * @return {string} Parsed message
296                  */
297                 parser: function () {
298                         return mw.format.apply( null, [ this.map.get( this.key ) ].concat( this.parameters ) );
299                 },
301                 // eslint-disable-next-line valid-jsdoc
302                 /**
303                  * Add (does not replace) parameters for `$N` placeholder values.
304                  *
305                  * @param {Array} parameters
306                  * @chainable
307                  */
308                 params: function ( parameters ) {
309                         var i;
310                         for ( i = 0; i < parameters.length; i++ ) {
311                                 this.parameters.push( parameters[ i ] );
312                         }
313                         return this;
314                 },
316                 /**
317                  * Convert message object to its string form based on current format.
318                  *
319                  * @return {string} Message as a string in the current form, or `<key>` if key
320                  *  does not exist.
321                  */
322                 toString: function () {
323                         var text;
325                         if ( !this.exists() ) {
326                                 // Use ⧼key⧽ as text if key does not exist
327                                 // Err on the side of safety, ensure that the output
328                                 // is always html safe in the event the message key is
329                                 // missing, since in that case its highly likely the
330                                 // message key is user-controlled.
331                                 // '⧼' is used instead of '<' to side-step any
332                                 // double-escaping issues.
333                                 // (Keep synchronised with Message::toString() in PHP.)
334                                 return '⧼' + mw.html.escape( this.key ) + '⧽';
335                         }
337                         if ( this.format === 'plain' || this.format === 'text' || this.format === 'parse' ) {
338                                 text = this.parser();
339                         }
341                         if ( this.format === 'escaped' ) {
342                                 text = this.parser();
343                                 text = mw.html.escape( text );
344                         }
346                         return text;
347                 },
349                 /**
350                  * Change format to 'parse' and convert message to string
351                  *
352                  * If jqueryMsg is loaded, this parses the message text from wikitext
353                  * (where supported) to HTML
354                  *
355                  * Otherwise, it is equivalent to plain.
356                  *
357                  * @return {string} String form of parsed message
358                  */
359                 parse: function () {
360                         this.format = 'parse';
361                         return this.toString();
362                 },
364                 /**
365                  * Change format to 'plain' and convert message to string
366                  *
367                  * This substitutes parameters, but otherwise does not change the
368                  * message text.
369                  *
370                  * @return {string} String form of plain message
371                  */
372                 plain: function () {
373                         this.format = 'plain';
374                         return this.toString();
375                 },
377                 /**
378                  * Change format to 'text' and convert message to string
379                  *
380                  * If jqueryMsg is loaded, {{-transformation is done where supported
381                  * (such as {{plural:}}, {{gender:}}, {{int:}}).
382                  *
383                  * Otherwise, it is equivalent to plain
384                  *
385                  * @return {string} String form of text message
386                  */
387                 text: function () {
388                         this.format = 'text';
389                         return this.toString();
390                 },
392                 /**
393                  * Change the format to 'escaped' and convert message to string
394                  *
395                  * This is equivalent to using the 'text' format (see #text), then
396                  * HTML-escaping the output.
397                  *
398                  * @return {string} String form of html escaped message
399                  */
400                 escaped: function () {
401                         this.format = 'escaped';
402                         return this.toString();
403                 },
405                 /**
406                  * Check if a message exists
407                  *
408                  * @see mw.Map#exists
409                  * @return {boolean}
410                  */
411                 exists: function () {
412                         return this.map.exists( this.key );
413                 }
414         };
416         /* eslint-disable no-console */
417         log = ( function () {
418                 // Also update the restoration of methods in mediawiki.log.js
419                 // when adding or removing methods here.
420                 var log = function () {},
421                         console = window.console;
423                 /**
424                  * @class mw.log
425                  * @singleton
426                  */
428                 /**
429                  * Write a message to the console's warning channel.
430                  * Actions not supported by the browser console are silently ignored.
431                  *
432                  * @param {...string} msg Messages to output to console
433                  */
434                 log.warn = console && console.warn && Function.prototype.bind ?
435                         Function.prototype.bind.call( console.warn, console ) :
436                         $.noop;
438                 /**
439                  * Write a message to the console's error channel.
440                  *
441                  * Most browsers provide a stacktrace by default if the argument
442                  * is a caught Error object.
443                  *
444                  * @since 1.26
445                  * @param {Error|...string} msg Messages to output to console
446                  */
447                 log.error = console && console.error && Function.prototype.bind ?
448                         Function.prototype.bind.call( console.error, console ) :
449                         $.noop;
451                 /**
452                  * Create a property in a host object that, when accessed, will produce
453                  * a deprecation warning in the console.
454                  *
455                  * @param {Object} obj Host object of deprecated property
456                  * @param {string} key Name of property to create in `obj`
457                  * @param {Mixed} val The value this property should return when accessed
458                  * @param {string} [msg] Optional text to include in the deprecation message
459                  * @param {string} [logName=key] Optional custom name for the feature.
460                  *  This is used instead of `key` in the message and `mw.deprecate` tracking.
461                  */
462                 log.deprecate = !Object.defineProperty ? function ( obj, key, val ) {
463                         obj[ key ] = val;
464                 } : function ( obj, key, val, msg, logName ) {
465                         var logged = new StringSet();
466                         logName = logName || key;
467                         msg = 'Use of "' + logName + '" is deprecated.' + ( msg ? ( ' ' + msg ) : '' );
468                         function uniqueTrace() {
469                                 var trace = new Error().stack;
470                                 if ( logged.has( trace ) ) {
471                                         return false;
472                                 }
473                                 logged.add( trace );
474                                 return true;
475                         }
476                         // Support: Safari 5.0
477                         // Throws "not supported on DOM Objects" for Node or Element objects (incl. document)
478                         // Safari 4.0 doesn't have this method, and it was fixed in Safari 5.1.
479                         try {
480                                 Object.defineProperty( obj, key, {
481                                         configurable: true,
482                                         enumerable: true,
483                                         get: function () {
484                                                 if ( uniqueTrace() ) {
485                                                         mw.track( 'mw.deprecate', logName );
486                                                         mw.log.warn( msg );
487                                                 }
488                                                 return val;
489                                         },
490                                         set: function ( newVal ) {
491                                                 if ( uniqueTrace() ) {
492                                                         mw.track( 'mw.deprecate', logName );
493                                                         mw.log.warn( msg );
494                                                 }
495                                                 val = newVal;
496                                         }
497                                 } );
498                         } catch ( err ) {
499                                 obj[ key ] = val;
500                         }
501                 };
503                 return log;
504         }() );
505         /* eslint-enable no-console */
507         /**
508          * @class mw
509          */
510         mw = {
512                 /**
513                  * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
514                  *
515                  * On browsers that implement the Navigation Timing API, this function will produce floating-point
516                  * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
517                  * it will fall back to using `Date`.
518                  *
519                  * @return {number} Current time
520                  */
521                 now: mwNow,
522                 // mwNow is defined in startup.js
524                 /**
525                  * Format a string. Replace $1, $2 ... $N with positional arguments.
526                  *
527                  * Used by Message#parser().
528                  *
529                  * @since 1.25
530                  * @param {string} formatString Format string
531                  * @param {...Mixed} parameters Values for $N replacements
532                  * @return {string} Formatted string
533                  */
534                 format: function ( formatString ) {
535                         var parameters = slice.call( arguments, 1 );
536                         return formatString.replace( /\$(\d+)/g, function ( str, match ) {
537                                 var index = parseInt( match, 10 ) - 1;
538                                 return parameters[ index ] !== undefined ? parameters[ index ] : '$' + match;
539                         } );
540                 },
542                 /**
543                  * Track an analytic event.
544                  *
545                  * This method provides a generic means for MediaWiki JavaScript code to capture state
546                  * information for analysis. Each logged event specifies a string topic name that describes
547                  * the kind of event that it is. Topic names consist of dot-separated path components,
548                  * arranged from most general to most specific. Each path component should have a clear and
549                  * well-defined purpose.
550                  *
551                  * Data handlers are registered via `mw.trackSubscribe`, and receive the full set of
552                  * events that match their subcription, including those that fired before the handler was
553                  * bound.
554                  *
555                  * @param {string} topic Topic name
556                  * @param {Object} [data] Data describing the event, encoded as an object
557                  */
558                 track: function ( topic, data ) {
559                         trackQueue.push( { topic: topic, timeStamp: mw.now(), data: data } );
560                         trackCallbacks.fire( trackQueue );
561                 },
563                 /**
564                  * Register a handler for subset of analytic events, specified by topic.
565                  *
566                  * Handlers will be called once for each tracked event, including any events that fired before the
567                  * handler was registered; 'this' is set to a plain object with a 'timeStamp' property indicating
568                  * the exact time at which the event fired, a string 'topic' property naming the event, and a
569                  * 'data' property which is an object of event-specific data. The event topic and event data are
570                  * also passed to the callback as the first and second arguments, respectively.
571                  *
572                  * @param {string} topic Handle events whose name starts with this string prefix
573                  * @param {Function} callback Handler to call for each matching tracked event
574                  * @param {string} callback.topic
575                  * @param {Object} [callback.data]
576                  */
577                 trackSubscribe: function ( topic, callback ) {
578                         var seen = 0;
579                         function handler( trackQueue ) {
580                                 var event;
581                                 for ( ; seen < trackQueue.length; seen++ ) {
582                                         event = trackQueue[ seen ];
583                                         if ( event.topic.indexOf( topic ) === 0 ) {
584                                                 callback.call( event, event.topic, event.data );
585                                         }
586                                 }
587                         }
589                         trackHandlers.push( [ handler, callback ] );
591                         trackCallbacks.add( handler );
592                 },
594                 /**
595                  * Stop handling events for a particular handler
596                  *
597                  * @param {Function} callback
598                  */
599                 trackUnsubscribe: function ( callback ) {
600                         trackHandlers = $.grep( trackHandlers, function ( fns ) {
601                                 if ( fns[ 1 ] === callback ) {
602                                         trackCallbacks.remove( fns[ 0 ] );
603                                         // Ensure the tuple is removed to avoid holding on to closures
604                                         return false;
605                                 }
606                                 return true;
607                         } );
608                 },
610                 // Expose Map constructor
611                 Map: Map,
613                 // Expose Message constructor
614                 Message: Message,
616                 /**
617                  * Map of configuration values.
618                  *
619                  * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
620                  * on mediawiki.org.
621                  *
622                  * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
623                  * global `window` object.
624                  *
625                  * @property {mw.Map} config
626                  */
627                 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
628                 config: null,
630                 /**
631                  * Empty object for third-party libraries, for cases where you don't
632                  * want to add a new global, or the global is bad and needs containment
633                  * or wrapping.
634                  *
635                  * @property
636                  */
637                 libs: {},
639                 /**
640                  * Access container for deprecated functionality that can be moved from
641                  * from their legacy location and attached to this object (e.g. a global
642                  * function that is deprecated and as stop-gap can be exposed through here).
643                  *
644                  * This was reserved for future use but never ended up being used.
645                  *
646                  * @deprecated since 1.22 Let deprecated identifiers keep their original name
647                  *  and use mw.log#deprecate to create an access container for tracking.
648                  * @property
649                  */
650                 legacy: {},
652                 /**
653                  * Store for messages.
654                  *
655                  * @property {mw.Map}
656                  */
657                 messages: new Map(),
659                 /**
660                  * Store for templates associated with a module.
661                  *
662                  * @property {mw.Map}
663                  */
664                 templates: new Map(),
666                 /**
667                  * Get a message object.
668                  *
669                  * Shortcut for `new mw.Message( mw.messages, key, parameters )`.
670                  *
671                  * @see mw.Message
672                  * @param {string} key Key of message to get
673                  * @param {...Mixed} parameters Values for $N replacements
674                  * @return {mw.Message}
675                  */
676                 message: function ( key ) {
677                         var parameters = slice.call( arguments, 1 );
678                         return new Message( mw.messages, key, parameters );
679                 },
681                 /**
682                  * Get a message string using the (default) 'text' format.
683                  *
684                  * Shortcut for `mw.message( key, parameters... ).text()`.
685                  *
686                  * @see mw.Message
687                  * @param {string} key Key of message to get
688                  * @param {...Mixed} parameters Values for $N replacements
689                  * @return {string}
690                  */
691                 msg: function () {
692                         return mw.message.apply( mw.message, arguments ).toString();
693                 },
695                 /**
696                  * No-op dummy placeholder for {@link mw.log} in debug mode.
697                  *
698                  * @method
699                  */
700                 log: log,
702                 /**
703                  * Client for ResourceLoader server end point.
704                  *
705                  * This client is in charge of maintaining the module registry and state
706                  * machine, initiating network (batch) requests for loading modules, as
707                  * well as dependency resolution and execution of source code.
708                  *
709                  * For more information, refer to
710                  * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
711                  *
712                  * @class mw.loader
713                  * @singleton
714                  */
715                 loader: ( function () {
717                         /**
718                          * Fired via mw.track on various resource loading errors.
719                          *
720                          * @event resourceloader_exception
721                          * @param {Error|Mixed} e The error that was thrown. Almost always an Error
722                          *   object, but in theory module code could manually throw something else, and that
723                          *   might also end up here.
724                          * @param {string} [module] Name of the module which caused the error. Omitted if the
725                          *   error is not module-related or the module cannot be easily identified due to
726                          *   batched handling.
727                          * @param {string} source Source of the error. Possible values:
728                          *
729                          *   - style: stylesheet error (only affects old IE where a special style loading method
730                          *     is used)
731                          *   - load-callback: exception thrown by user callback
732                          *   - module-execute: exception thrown by module code
733                          *   - store-eval: could not evaluate module code cached in localStorage
734                          *   - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
735                          *   - store-localstorage-json: JSON conversion error in mw.loader.store.set
736                          *   - store-localstorage-update: localStorage or JSON conversion error in mw.loader.store.update
737                          */
739                         /**
740                          * Fired via mw.track on resource loading error conditions.
741                          *
742                          * @event resourceloader_assert
743                          * @param {string} source Source of the error. Possible values:
744                          *
745                          *   - bug-T59567: failed to cache script due to an Opera function -> string conversion
746                          *     bug; see <https://phabricator.wikimedia.org/T59567> for details
747                          */
749                         /**
750                          * Mapping of registered modules.
751                          *
752                          * See #implement and #execute for exact details on support for script, style and messages.
753                          *
754                          * Format:
755                          *
756                          *     {
757                          *         'moduleName': {
758                          *             // From mw.loader.register()
759                          *             'version': '########' (hash)
760                          *             'dependencies': ['required.foo', 'bar.also', ...], (or) function () {}
761                          *             'group': 'somegroup', (or) null
762                          *             'source': 'local', (or) 'anotherwiki'
763                          *             'skip': 'return !!window.Example', (or) null
764                          *             'module': export Object
765                          *
766                          *             // Set from execute() or mw.loader.state()
767                          *             'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
768                          *
769                          *             // Optionally added at run-time by mw.loader.implement()
770                          *             'skipped': true
771                          *             'script': closure, array of urls, or string
772                          *             'style': { ... } (see #execute)
773                          *             'messages': { 'key': 'value', ... }
774                          *         }
775                          *     }
776                          *
777                          * State machine:
778                          *
779                          * - `registered`:
780                          *    The module is known to the system but not yet required.
781                          *    Meta data is registered via mw.loader#register. Calls to that method are
782                          *    generated server-side by the startup module.
783                          * - `loading`:
784                          *    The module was required through mw.loader (either directly or as dependency of
785                          *    another module). The client will fetch module contents from the server.
786                          *    The contents are then stashed in the registry via mw.loader#implement.
787                          * - `loaded`:
788                          *    The module has been loaded from the server and stashed via mw.loader#implement.
789                          *    If the module has no more dependencies in-flight, the module will be executed
790                          *    immediately. Otherwise execution is deferred, controlled via #handlePending.
791                          * - `executing`:
792                          *    The module is being executed.
793                          * - `ready`:
794                          *    The module has been successfully executed.
795                          * - `error`:
796                          *    The module (or one of its dependencies) produced an error during execution.
797                          * - `missing`:
798                          *    The module was registered client-side and requested, but the server denied knowledge
799                          *    of the module's existence.
800                          *
801                          * @property
802                          * @private
803                          */
804                         var registry = {},
805                                 // Mapping of sources, keyed by source-id, values are strings.
806                                 //
807                                 // Format:
808                                 //
809                                 //     {
810                                 //         'sourceId': 'http://example.org/w/load.php'
811                                 //     }
812                                 //
813                                 sources = {},
815                                 // For queueModuleScript()
816                                 handlingPendingRequests = false,
817                                 pendingRequests = [],
819                                 // List of modules to be loaded
820                                 queue = [],
822                                 /**
823                                  * List of callback jobs waiting for modules to be ready.
824                                  *
825                                  * Jobs are created by #enqueue() and run by #handlePending().
826                                  *
827                                  * Typically when a job is created for a module, the job's dependencies contain
828                                  * both the required module and all its recursive dependencies.
829                                  *
830                                  * Format:
831                                  *
832                                  *     {
833                                  *         'dependencies': [ module names ],
834                                  *         'ready': Function callback
835                                  *         'error': Function callback
836                                  *     }
837                                  *
838                                  * @property {Object[]} jobs
839                                  * @private
840                                  */
841                                 jobs = [],
843                                 // For getMarker()
844                                 marker = null,
846                                 // For addEmbeddedCSS()
847                                 cssBuffer = '',
848                                 cssBufferTimer = null,
849                                 cssCallbacks = $.Callbacks(),
850                                 isIE9 = document.documentMode === 9,
851                                 rAF = window.requestAnimationFrame || setTimeout;
853                         function getMarker() {
854                                 if ( !marker ) {
855                                         // Cache
856                                         marker = document.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' );
857                                         if ( !marker ) {
858                                                 mw.log( 'Create <meta name="ResourceLoaderDynamicStyles"> dynamically' );
859                                                 marker = $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' )[ 0 ];
860                                         }
861                                 }
862                                 return marker;
863                         }
865                         /**
866                          * Create a new style element and add it to the DOM.
867                          *
868                          * @private
869                          * @param {string} text CSS text
870                          * @param {Node} [nextNode] The element where the style tag
871                          *  should be inserted before
872                          * @return {HTMLElement} Reference to the created style element
873                          */
874                         function newStyleTag( text, nextNode ) {
875                                 var s = document.createElement( 'style' );
877                                 s.appendChild( document.createTextNode( text ) );
878                                 if ( nextNode && nextNode.parentNode ) {
879                                         nextNode.parentNode.insertBefore( s, nextNode );
880                                 } else {
881                                         document.getElementsByTagName( 'head' )[ 0 ].appendChild( s );
882                                 }
884                                 return s;
885                         }
887                         /**
888                          * Add a bit of CSS text to the current browser page.
889                          *
890                          * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
891                          * or create a new one based on whether the given `cssText` is safe for extension.
892                          *
893                          * @private
894                          * @param {string} [cssText=cssBuffer] If called without cssText,
895                          *  the internal buffer will be inserted instead.
896                          * @param {Function} [callback]
897                          */
898                         function addEmbeddedCSS( cssText, callback ) {
899                                 var $style, styleEl;
901                                 function fireCallbacks() {
902                                         var oldCallbacks = cssCallbacks;
903                                         // Reset cssCallbacks variable so it's not polluted by any calls to
904                                         // addEmbeddedCSS() from one of the callbacks (T105973)
905                                         cssCallbacks = $.Callbacks();
906                                         oldCallbacks.fire().empty();
907                                 }
909                                 if ( callback ) {
910                                         cssCallbacks.add( callback );
911                                 }
913                                 // Yield once before creating the <style> tag. This lets multiple stylesheets
914                                 // accumulate into one buffer, allowing us to reduce how often new stylesheets
915                                 // are inserted in the browser. Appending a stylesheet and waiting for the
916                                 // browser to repaint is fairly expensive. (T47810)
917                                 if ( cssText ) {
918                                         // Don't extend the buffer if the item needs its own stylesheet.
919                                         // Keywords like `@import` are only valid at the start of a stylesheet (T37562).
920                                         if ( !cssBuffer || cssText.slice( 0, '@import'.length ) !== '@import' ) {
921                                                 // Linebreak for somewhat distinguishable sections
922                                                 cssBuffer += '\n' + cssText;
923                                                 if ( !cssBufferTimer ) {
924                                                         cssBufferTimer = rAF( function () {
925                                                                 // Wrap in anonymous function that takes no arguments
926                                                                 // Support: Firefox < 13
927                                                                 // Firefox 12 has non-standard behaviour of passing a number
928                                                                 // as first argument to a setTimeout callback.
929                                                                 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
930                                                                 addEmbeddedCSS();
931                                                         } );
932                                                 }
933                                                 return;
934                                         }
936                                 // This is a scheduled flush for the buffer
937                                 } else {
938                                         cssBufferTimer = null;
939                                         cssText = cssBuffer;
940                                         cssBuffer = '';
941                                 }
943                                 // By default, always create a new <style>. Appending text to a <style> tag is
944                                 // is a performance anti-pattern as it requires CSS to be reparsed (T47810).
945                                 //
946                                 // Support: IE 6-9
947                                 // Try to re-use existing <style> tags due to the IE stylesheet limit (T33676).
948                                 if ( isIE9 ) {
949                                         $style = $( getMarker() ).prev();
950                                         // Verify that the element before the marker actually is a <style> tag created
951                                         // by mw.loader (not some other style tag, or e.g. a <meta> tag).
952                                         if ( $style.data( 'ResourceLoaderDynamicStyleTag' ) ) {
953                                                 styleEl = $style[ 0 ];
954                                                 styleEl.appendChild( document.createTextNode( cssText ) );
955                                                 fireCallbacks();
956                                                 return;
957                                         }
958                                         // Else: No existing tag to reuse. Continue below and create the first one.
959                                 }
961                                 $style = $( newStyleTag( cssText, getMarker() ) );
963                                 if ( isIE9 ) {
964                                         $style.data( 'ResourceLoaderDynamicStyleTag', true );
965                                 }
967                                 fireCallbacks();
968                         }
970                         /**
971                          * @private
972                          * @param {Array} modules List of module names
973                          * @return {string} Hash of concatenated version hashes.
974                          */
975                         function getCombinedVersion( modules ) {
976                                 var hashes = $.map( modules, function ( module ) {
977                                         return registry[ module ].version;
978                                 } );
979                                 return fnv132( hashes.join( '' ) );
980                         }
982                         /**
983                          * Determine whether all dependencies are in state 'ready', which means we may
984                          * execute the module or job now.
985                          *
986                          * @private
987                          * @param {Array} modules Names of modules to be checked
988                          * @return {boolean} True if all modules are in state 'ready', false otherwise
989                          */
990                         function allReady( modules ) {
991                                 var i;
992                                 for ( i = 0; i < modules.length; i++ ) {
993                                         if ( mw.loader.getState( modules[ i ] ) !== 'ready' ) {
994                                                 return false;
995                                         }
996                                 }
997                                 return true;
998                         }
1000                         /**
1001                          * Determine whether all dependencies are in state 'ready', which means we may
1002                          * execute the module or job now.
1003                          *
1004                          * @private
1005                          * @param {Array} modules Names of modules to be checked
1006                          * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
1007                          */
1008                         function anyFailed( modules ) {
1009                                 var i, state;
1010                                 for ( i = 0; i < modules.length; i++ ) {
1011                                         state = mw.loader.getState( modules[ i ] );
1012                                         if ( state === 'error' || state === 'missing' ) {
1013                                                 return true;
1014                                         }
1015                                 }
1016                                 return false;
1017                         }
1019                         /**
1020                          * A module has entered state 'ready', 'error', or 'missing'. Automatically update
1021                          * pending jobs and modules that depend upon this module. If the given module failed,
1022                          * propagate the 'error' state up the dependency tree. Otherwise, go ahead and execute
1023                          * all jobs/modules now having their dependencies satisfied.
1024                          *
1025                          * Jobs that depend on a failed module, will have their error callback ran (if any).
1026                          *
1027                          * @private
1028                          * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
1029                          */
1030                         function handlePending( module ) {
1031                                 var j, job, hasErrors, m, stateChange;
1033                                 if ( registry[ module ].state === 'error' || registry[ module ].state === 'missing' ) {
1034                                         // If the current module failed, mark all dependent modules also as failed.
1035                                         // Iterate until steady-state to propagate the error state upwards in the
1036                                         // dependency tree.
1037                                         do {
1038                                                 stateChange = false;
1039                                                 for ( m in registry ) {
1040                                                         if ( registry[ m ].state !== 'error' && registry[ m ].state !== 'missing' ) {
1041                                                                 if ( anyFailed( registry[ m ].dependencies ) ) {
1042                                                                         registry[ m ].state = 'error';
1043                                                                         stateChange = true;
1044                                                                 }
1045                                                         }
1046                                                 }
1047                                         } while ( stateChange );
1048                                 }
1050                                 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
1051                                 for ( j = 0; j < jobs.length; j++ ) {
1052                                         hasErrors = anyFailed( jobs[ j ].dependencies );
1053                                         if ( hasErrors || allReady( jobs[ j ].dependencies ) ) {
1054                                                 // All dependencies satisfied, or some have errors
1055                                                 job = jobs[ j ];
1056                                                 jobs.splice( j, 1 );
1057                                                 j -= 1;
1058                                                 try {
1059                                                         if ( hasErrors ) {
1060                                                                 if ( typeof job.error === 'function' ) {
1061                                                                         job.error( new Error( 'Module ' + module + ' has failed dependencies' ), [ module ] );
1062                                                                 }
1063                                                         } else {
1064                                                                 if ( typeof job.ready === 'function' ) {
1065                                                                         job.ready();
1066                                                                 }
1067                                                         }
1068                                                 } catch ( e ) {
1069                                                         // A user-defined callback raised an exception.
1070                                                         // Swallow it to protect our state machine!
1071                                                         mw.track( 'resourceloader.exception', { exception: e, module: module, source: 'load-callback' } );
1072                                                 }
1073                                         }
1074                                 }
1076                                 if ( registry[ module ].state === 'ready' ) {
1077                                         // The current module became 'ready'. Set it in the module store, and recursively execute all
1078                                         // dependent modules that are loaded and now have all dependencies satisfied.
1079                                         mw.loader.store.set( module, registry[ module ] );
1080                                         for ( m in registry ) {
1081                                                 if ( registry[ m ].state === 'loaded' && allReady( registry[ m ].dependencies ) ) {
1082                                                         execute( m );
1083                                                 }
1084                                         }
1085                                 }
1086                         }
1088                         /**
1089                          * Resolve dependencies and detect circular references.
1090                          *
1091                          * @private
1092                          * @param {string} module Name of the top-level module whose dependencies shall be
1093                          *  resolved and sorted.
1094                          * @param {Array} resolved Returns a topological sort of the given module and its
1095                          *  dependencies, such that later modules depend on earlier modules. The array
1096                          *  contains the module names. If the array contains already some module names,
1097                          *  this function appends its result to the pre-existing array.
1098                          * @param {StringSet} [unresolved] Used to track the current dependency
1099                          *  chain, and to report loops in the dependency graph.
1100                          * @throws {Error} If any unregistered module or a dependency loop is encountered
1101                          */
1102                         function sortDependencies( module, resolved, unresolved ) {
1103                                 var i, deps, skip;
1105                                 if ( !hasOwn.call( registry, module ) ) {
1106                                         throw new Error( 'Unknown dependency: ' + module );
1107                                 }
1109                                 if ( registry[ module ].skip !== null ) {
1110                                         // eslint-disable-next-line no-new-func
1111                                         skip = new Function( registry[ module ].skip );
1112                                         registry[ module ].skip = null;
1113                                         if ( skip() ) {
1114                                                 registry[ module ].skipped = true;
1115                                                 registry[ module ].dependencies = [];
1116                                                 registry[ module ].state = 'ready';
1117                                                 handlePending( module );
1118                                                 return;
1119                                         }
1120                                 }
1122                                 // Resolves dynamic loader function and replaces it with its own results
1123                                 if ( typeof registry[ module ].dependencies === 'function' ) {
1124                                         registry[ module ].dependencies = registry[ module ].dependencies();
1125                                         // Ensures the module's dependencies are always in an array
1126                                         if ( typeof registry[ module ].dependencies !== 'object' ) {
1127                                                 registry[ module ].dependencies = [ registry[ module ].dependencies ];
1128                                         }
1129                                 }
1130                                 if ( $.inArray( module, resolved ) !== -1 ) {
1131                                         // Module already resolved; nothing to do
1132                                         return;
1133                                 }
1134                                 // Create unresolved if not passed in
1135                                 if ( !unresolved ) {
1136                                         unresolved = new StringSet();
1137                                 }
1138                                 // Tracks down dependencies
1139                                 deps = registry[ module ].dependencies;
1140                                 for ( i = 0; i < deps.length; i++ ) {
1141                                         if ( $.inArray( deps[ i ], resolved ) === -1 ) {
1142                                                 if ( unresolved.has( deps[ i ] ) ) {
1143                                                         throw new Error( mw.format(
1144                                                                 'Circular reference detected: $1 -> $2',
1145                                                                 module,
1146                                                                 deps[ i ]
1147                                                         ) );
1148                                                 }
1150                                                 unresolved.add( module );
1151                                                 sortDependencies( deps[ i ], resolved, unresolved );
1152                                         }
1153                                 }
1154                                 resolved.push( module );
1155                         }
1157                         /**
1158                          * Get names of module that a module depends on, in their proper dependency order.
1159                          *
1160                          * @private
1161                          * @param {string[]} modules Array of string module names
1162                          * @return {Array} List of dependencies, including 'module'.
1163                          * @throws {Error} If an unregistered module or a dependency loop is encountered
1164                          */
1165                         function resolve( modules ) {
1166                                 var i, resolved = [];
1167                                 for ( i = 0; i < modules.length; i++ ) {
1168                                         sortDependencies( modules[ i ], resolved );
1169                                 }
1170                                 return resolved;
1171                         }
1173                         /**
1174                          * Load and execute a script.
1175                          *
1176                          * @private
1177                          * @param {string} src URL to script, will be used as the src attribute in the script tag
1178                          * @return {jQuery.Promise}
1179                          */
1180                         function addScript( src ) {
1181                                 return $.ajax( {
1182                                         url: src,
1183                                         dataType: 'script',
1184                                         // Force jQuery behaviour to be for crossDomain. Otherwise jQuery would use
1185                                         // XHR for a same domain request instead of <script>, which changes the request
1186                                         // headers (potentially missing a cache hit), and reduces caching in general
1187                                         // since browsers cache XHR much less (if at all). And XHR means we retrieve
1188                                         // text, so we'd need to $.globalEval, which then messes up line numbers.
1189                                         crossDomain: true,
1190                                         cache: true
1191                                 } );
1192                         }
1194                         /**
1195                          * Queue the loading and execution of a script for a particular module.
1196                          *
1197                          * @private
1198                          * @param {string} src URL of the script
1199                          * @param {string} [moduleName] Name of currently executing module
1200                          * @return {jQuery.Promise}
1201                          */
1202                         function queueModuleScript( src, moduleName ) {
1203                                 var r = $.Deferred();
1205                                 pendingRequests.push( function () {
1206                                         if ( moduleName && hasOwn.call( registry, moduleName ) ) {
1207                                                 // Emulate runScript() part of execute()
1208                                                 window.require = mw.loader.require;
1209                                                 window.module = registry[ moduleName ].module;
1210                                         }
1211                                         addScript( src ).always( function () {
1212                                                 // 'module.exports' should not persist after the file is executed to
1213                                                 // avoid leakage to unrelated code. 'require' should be kept, however,
1214                                                 // as asynchronous access to 'require' is allowed and expected. (T144879)
1215                                                 delete window.module;
1216                                                 r.resolve();
1218                                                 // Start the next one (if any)
1219                                                 if ( pendingRequests[ 0 ] ) {
1220                                                         pendingRequests.shift()();
1221                                                 } else {
1222                                                         handlingPendingRequests = false;
1223                                                 }
1224                                         } );
1225                                 } );
1226                                 if ( !handlingPendingRequests && pendingRequests[ 0 ] ) {
1227                                         handlingPendingRequests = true;
1228                                         pendingRequests.shift()();
1229                                 }
1230                                 return r.promise();
1231                         }
1233                         /**
1234                          * Utility function for execute()
1235                          *
1236                          * @ignore
1237                          * @param {string} [media] Media attribute
1238                          * @param {string} url URL
1239                          */
1240                         function addLink( media, url ) {
1241                                 var el = document.createElement( 'link' );
1243                                 el.rel = 'stylesheet';
1244                                 if ( media && media !== 'all' ) {
1245                                         el.media = media;
1246                                 }
1247                                 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1248                                 // see #addEmbeddedCSS, T33676, and T49277 for details.
1249                                 el.href = url;
1251                                 $( getMarker() ).before( el );
1252                         }
1254                         /**
1255                          * Executes a loaded module, making it ready to use
1256                          *
1257                          * @private
1258                          * @param {string} module Module name to execute
1259                          */
1260                         function execute( module ) {
1261                                 var key, value, media, i, urls, cssHandle, checkCssHandles, runScript,
1262                                         cssHandlesRegistered = false;
1264                                 if ( !hasOwn.call( registry, module ) ) {
1265                                         throw new Error( 'Module has not been registered yet: ' + module );
1266                                 }
1267                                 if ( registry[ module ].state !== 'loaded' ) {
1268                                         throw new Error( 'Module in state "' + registry[ module ].state + '" may not be executed: ' + module );
1269                                 }
1271                                 registry[ module ].state = 'executing';
1273                                 runScript = function () {
1274                                         var script, markModuleReady, nestedAddScript, legacyWait, implicitDependencies,
1275                                                 // Expand to include dependencies since we have to exclude both legacy modules
1276                                                 // and their dependencies from the legacyWait (to prevent a circular dependency).
1277                                                 legacyModules = resolve( mw.config.get( 'wgResourceLoaderLegacyModules', [] ) );
1279                                         script = registry[ module ].script;
1280                                         markModuleReady = function () {
1281                                                 registry[ module ].state = 'ready';
1282                                                 handlePending( module );
1283                                         };
1284                                         nestedAddScript = function ( arr, callback, i ) {
1285                                                 // Recursively call queueModuleScript() in its own callback
1286                                                 // for each element of arr.
1287                                                 if ( i >= arr.length ) {
1288                                                         // We're at the end of the array
1289                                                         callback();
1290                                                         return;
1291                                                 }
1293                                                 queueModuleScript( arr[ i ], module ).always( function () {
1294                                                         nestedAddScript( arr, callback, i + 1 );
1295                                                 } );
1296                                         };
1298                                         implicitDependencies = ( $.inArray( module, legacyModules ) !== -1 ) ?
1299                                                 [] :
1300                                                 legacyModules;
1302                                         if ( module === 'user' ) {
1303                                                 // Implicit dependency on the site module. Not real dependency because
1304                                                 // it should run after 'site' regardless of whether it succeeds or fails.
1305                                                 implicitDependencies.push( 'site' );
1306                                         }
1308                                         legacyWait = implicitDependencies.length ?
1309                                                 mw.loader.using( implicitDependencies ) :
1310                                                 $.Deferred().resolve();
1312                                         legacyWait.always( function () {
1313                                                 try {
1314                                                         if ( $.isArray( script ) ) {
1315                                                                 nestedAddScript( script, markModuleReady, 0 );
1316                                                         } else if ( typeof script === 'function' ) {
1317                                                                 // Pass jQuery twice so that the signature of the closure which wraps
1318                                                                 // the script can bind both '$' and 'jQuery'.
1319                                                                 script( $, $, mw.loader.require, registry[ module ].module );
1320                                                                 markModuleReady();
1322                                                         } else if ( typeof script === 'string' ) {
1323                                                                 // Site and user modules are legacy scripts that run in the global scope.
1324                                                                 // This is transported as a string instead of a function to avoid needing
1325                                                                 // to use string manipulation to undo the function wrapper.
1326                                                                 $.globalEval( script );
1327                                                                 markModuleReady();
1329                                                         } else {
1330                                                                 // Module without script
1331                                                                 markModuleReady();
1332                                                         }
1333                                                 } catch ( e ) {
1334                                                         // Use mw.track instead of mw.log because these errors are common in production mode
1335                                                         // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1336                                                         registry[ module ].state = 'error';
1337                                                         mw.track( 'resourceloader.exception', { exception: e, module: module, source: 'module-execute' } );
1338                                                         handlePending( module );
1339                                                 }
1340                                         } );
1341                                 };
1343                                 // Add localizations to message system
1344                                 if ( registry[ module ].messages ) {
1345                                         mw.messages.set( registry[ module ].messages );
1346                                 }
1348                                 // Initialise templates
1349                                 if ( registry[ module ].templates ) {
1350                                         mw.templates.set( module, registry[ module ].templates );
1351                                 }
1353                                 // Make sure we don't run the scripts until all stylesheet insertions have completed.
1354                                 ( function () {
1355                                         var pending = 0;
1356                                         checkCssHandles = function () {
1357                                                 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1358                                                 // one of the cssHandles is fired while we're still creating more handles.
1359                                                 if ( cssHandlesRegistered && pending === 0 && runScript ) {
1360                                                         runScript();
1361                                                         runScript = undefined; // Revoke
1362                                                 }
1363                                         };
1364                                         cssHandle = function () {
1365                                                 var check = checkCssHandles;
1366                                                 pending++;
1367                                                 return function () {
1368                                                         if ( check ) {
1369                                                                 pending--;
1370                                                                 check();
1371                                                                 check = undefined; // Revoke
1372                                                         }
1373                                                 };
1374                                         };
1375                                 }() );
1377                                 // Process styles (see also mw.loader.implement)
1378                                 // * back-compat: { <media>: css }
1379                                 // * back-compat: { <media>: [url, ..] }
1380                                 // * { "css": [css, ..] }
1381                                 // * { "url": { <media>: [url, ..] } }
1382                                 if ( registry[ module ].style ) {
1383                                         for ( key in registry[ module ].style ) {
1384                                                 value = registry[ module ].style[ key ];
1385                                                 media = undefined;
1387                                                 if ( key !== 'url' && key !== 'css' ) {
1388                                                         // Backwards compatibility, key is a media-type
1389                                                         if ( typeof value === 'string' ) {
1390                                                                 // back-compat: { <media>: css }
1391                                                                 // Ignore 'media' because it isn't supported (nor was it used).
1392                                                                 // Strings are pre-wrapped in "@media". The media-type was just ""
1393                                                                 // (because it had to be set to something).
1394                                                                 // This is one of the reasons why this format is no longer used.
1395                                                                 addEmbeddedCSS( value, cssHandle() );
1396                                                         } else {
1397                                                                 // back-compat: { <media>: [url, ..] }
1398                                                                 media = key;
1399                                                                 key = 'bc-url';
1400                                                         }
1401                                                 }
1403                                                 // Array of css strings in key 'css',
1404                                                 // or back-compat array of urls from media-type
1405                                                 if ( $.isArray( value ) ) {
1406                                                         for ( i = 0; i < value.length; i++ ) {
1407                                                                 if ( key === 'bc-url' ) {
1408                                                                         // back-compat: { <media>: [url, ..] }
1409                                                                         addLink( media, value[ i ] );
1410                                                                 } else if ( key === 'css' ) {
1411                                                                         // { "css": [css, ..] }
1412                                                                         addEmbeddedCSS( value[ i ], cssHandle() );
1413                                                                 }
1414                                                         }
1415                                                 // Not an array, but a regular object
1416                                                 // Array of urls inside media-type key
1417                                                 } else if ( typeof value === 'object' ) {
1418                                                         // { "url": { <media>: [url, ..] } }
1419                                                         for ( media in value ) {
1420                                                                 urls = value[ media ];
1421                                                                 for ( i = 0; i < urls.length; i++ ) {
1422                                                                         addLink( media, urls[ i ] );
1423                                                                 }
1424                                                         }
1425                                                 }
1426                                         }
1427                                 }
1429                                 // Kick off.
1430                                 cssHandlesRegistered = true;
1431                                 checkCssHandles();
1432                         }
1434                         /**
1435                          * Add one or more modules to the module load queue.
1436                          *
1437                          * See also #work().
1438                          *
1439                          * @private
1440                          * @param {string|string[]} dependencies Module name or array of string module names
1441                          * @param {Function} [ready] Callback to execute when all dependencies are ready
1442                          * @param {Function} [error] Callback to execute when any dependency fails
1443                          */
1444                         function enqueue( dependencies, ready, error ) {
1445                                 // Allow calling by single module name
1446                                 if ( typeof dependencies === 'string' ) {
1447                                         dependencies = [ dependencies ];
1448                                 }
1450                                 // Add ready and error callbacks if they were given
1451                                 if ( ready !== undefined || error !== undefined ) {
1452                                         jobs.push( {
1453                                                 // Narrow down the list to modules that are worth waiting for
1454                                                 dependencies: $.grep( dependencies, function ( module ) {
1455                                                         var state = mw.loader.getState( module );
1456                                                         return state === 'registered' || state === 'loaded' || state === 'loading' || state === 'executing';
1457                                                 } ),
1458                                                 ready: ready,
1459                                                 error: error
1460                                         } );
1461                                 }
1463                                 $.each( dependencies, function ( idx, module ) {
1464                                         var state = mw.loader.getState( module );
1465                                         // Only queue modules that are still in the initial 'registered' state
1466                                         // (not ones already loading, ready or error).
1467                                         if ( state === 'registered' && $.inArray( module, queue ) === -1 ) {
1468                                                 // Private modules must be embedded in the page. Don't bother queuing
1469                                                 // these as the server will deny them anyway (T101806).
1470                                                 if ( registry[ module ].group === 'private' ) {
1471                                                         registry[ module ].state = 'error';
1472                                                         handlePending( module );
1473                                                         return;
1474                                                 }
1475                                                 queue.push( module );
1476                                         }
1477                                 } );
1479                                 mw.loader.work();
1480                         }
1482                         function sortQuery( o ) {
1483                                 var key,
1484                                         sorted = {},
1485                                         a = [];
1487                                 for ( key in o ) {
1488                                         if ( hasOwn.call( o, key ) ) {
1489                                                 a.push( key );
1490                                         }
1491                                 }
1492                                 a.sort();
1493                                 for ( key = 0; key < a.length; key++ ) {
1494                                         sorted[ a[ key ] ] = o[ a[ key ] ];
1495                                 }
1496                                 return sorted;
1497                         }
1499                         /**
1500                          * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
1501                          * to a query string of the form foo.bar,baz|bar.baz,quux
1502                          *
1503                          * @private
1504                          * @param {Object} moduleMap Module map
1505                          * @return {string} Module query string
1506                          */
1507                         function buildModulesString( moduleMap ) {
1508                                 var p, prefix,
1509                                         arr = [];
1511                                 for ( prefix in moduleMap ) {
1512                                         p = prefix === '' ? '' : prefix + '.';
1513                                         arr.push( p + moduleMap[ prefix ].join( ',' ) );
1514                                 }
1515                                 return arr.join( '|' );
1516                         }
1518                         /**
1519                          * Make a network request to load modules from the server.
1520                          *
1521                          * @private
1522                          * @param {Object} moduleMap Module map, see #buildModulesString
1523                          * @param {Object} currReqBase Object with other parameters (other than 'modules') to use in the request
1524                          * @param {string} sourceLoadScript URL of load.php
1525                          */
1526                         function doRequest( moduleMap, currReqBase, sourceLoadScript ) {
1527                                 var query = $.extend(
1528                                         { modules: buildModulesString( moduleMap ) },
1529                                         currReqBase
1530                                 );
1531                                 query = sortQuery( query );
1532                                 addScript( sourceLoadScript + '?' + $.param( query ) );
1533                         }
1535                         /**
1536                          * Resolve indexed dependencies.
1537                          *
1538                          * ResourceLoader uses an optimization to save space which replaces module names in
1539                          * dependency lists with the index of that module within the array of module
1540                          * registration data if it exists. The benefit is a significant reduction in the data
1541                          * size of the startup module. This function changes those dependency lists back to
1542                          * arrays of strings.
1543                          *
1544                          * @private
1545                          * @param {Array} modules Modules array
1546                          */
1547                         function resolveIndexedDependencies( modules ) {
1548                                 var i, j, deps;
1549                                 function resolveIndex( dep ) {
1550                                         return typeof dep === 'number' ? modules[ dep ][ 0 ] : dep;
1551                                 }
1552                                 for ( i = 0; i < modules.length; i++ ) {
1553                                         deps = modules[ i ][ 2 ];
1554                                         if ( deps ) {
1555                                                 for ( j = 0; j < deps.length; j++ ) {
1556                                                         deps[ j ] = resolveIndex( deps[ j ] );
1557                                                 }
1558                                         }
1559                                 }
1560                         }
1562                         /**
1563                          * Create network requests for a batch of modules.
1564                          *
1565                          * This is an internal method for #work(). This must not be called directly
1566                          * unless the modules are already registered, and no request is in progress,
1567                          * and the module state has already been set to `loading`.
1568                          *
1569                          * @private
1570                          * @param {string[]} batch
1571                          */
1572                         function batchRequest( batch ) {
1573                                 var reqBase, splits, maxQueryLength, b, bSource, bGroup, bSourceGroup,
1574                                         source, group, i, modules, sourceLoadScript,
1575                                         currReqBase, currReqBaseLength, moduleMap, l,
1576                                         lastDotIndex, prefix, suffix, bytesAdded;
1578                                 if ( !batch.length ) {
1579                                         return;
1580                                 }
1582                                 // Always order modules alphabetically to help reduce cache
1583                                 // misses for otherwise identical content.
1584                                 batch.sort();
1586                                 // Build a list of query parameters common to all requests
1587                                 reqBase = {
1588                                         skin: mw.config.get( 'skin' ),
1589                                         lang: mw.config.get( 'wgUserLanguage' ),
1590                                         debug: mw.config.get( 'debug' )
1591                                 };
1592                                 maxQueryLength = mw.config.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1594                                 // Split module list by source and by group.
1595                                 splits = {};
1596                                 for ( b = 0; b < batch.length; b++ ) {
1597                                         bSource = registry[ batch[ b ] ].source;
1598                                         bGroup = registry[ batch[ b ] ].group;
1599                                         if ( !hasOwn.call( splits, bSource ) ) {
1600                                                 splits[ bSource ] = {};
1601                                         }
1602                                         if ( !hasOwn.call( splits[ bSource ], bGroup ) ) {
1603                                                 splits[ bSource ][ bGroup ] = [];
1604                                         }
1605                                         bSourceGroup = splits[ bSource ][ bGroup ];
1606                                         bSourceGroup.push( batch[ b ] );
1607                                 }
1609                                 for ( source in splits ) {
1611                                         sourceLoadScript = sources[ source ];
1613                                         for ( group in splits[ source ] ) {
1615                                                 // Cache access to currently selected list of
1616                                                 // modules for this group from this source.
1617                                                 modules = splits[ source ][ group ];
1619                                                 currReqBase = $.extend( {
1620                                                         version: getCombinedVersion( modules )
1621                                                 }, reqBase );
1622                                                 // For user modules append a user name to the query string.
1623                                                 if ( group === 'user' && mw.config.get( 'wgUserName' ) !== null ) {
1624                                                         currReqBase.user = mw.config.get( 'wgUserName' );
1625                                                 }
1626                                                 currReqBaseLength = $.param( currReqBase ).length;
1627                                                 // We may need to split up the request to honor the query string length limit,
1628                                                 // so build it piece by piece.
1629                                                 l = currReqBaseLength + 9; // '&modules='.length == 9
1631                                                 moduleMap = {}; // { prefix: [ suffixes ] }
1633                                                 for ( i = 0; i < modules.length; i++ ) {
1634                                                         // Determine how many bytes this module would add to the query string
1635                                                         lastDotIndex = modules[ i ].lastIndexOf( '.' );
1637                                                         // If lastDotIndex is -1, substr() returns an empty string
1638                                                         prefix = modules[ i ].substr( 0, lastDotIndex );
1639                                                         suffix = modules[ i ].slice( lastDotIndex + 1 );
1641                                                         bytesAdded = hasOwn.call( moduleMap, prefix ) ?
1642                                                                 suffix.length + 3 : // '%2C'.length == 3
1643                                                                 modules[ i ].length + 3; // '%7C'.length == 3
1645                                                         // If the url would become too long, create a new one,
1646                                                         // but don't create empty requests
1647                                                         if ( maxQueryLength > 0 && !$.isEmptyObject( moduleMap ) && l + bytesAdded > maxQueryLength ) {
1648                                                                 // This url would become too long, create a new one, and start the old one
1649                                                                 doRequest( moduleMap, currReqBase, sourceLoadScript );
1650                                                                 moduleMap = {};
1651                                                                 l = currReqBaseLength + 9;
1652                                                                 mw.track( 'resourceloader.splitRequest', { maxQueryLength: maxQueryLength } );
1653                                                         }
1654                                                         if ( !hasOwn.call( moduleMap, prefix ) ) {
1655                                                                 moduleMap[ prefix ] = [];
1656                                                         }
1657                                                         moduleMap[ prefix ].push( suffix );
1658                                                         l += bytesAdded;
1659                                                 }
1660                                                 // If there's anything left in moduleMap, request that too
1661                                                 if ( !$.isEmptyObject( moduleMap ) ) {
1662                                                         doRequest( moduleMap, currReqBase, sourceLoadScript );
1663                                                 }
1664                                         }
1665                                 }
1666                         }
1668                         /**
1669                          * @private
1670                          * @param {string[]} implementations Array containing pieces of JavaScript code in the
1671                          *  form of calls to mw.loader#implement().
1672                          * @param {Function} cb Callback in case of failure
1673                          * @param {Error} cb.err
1674                          */
1675                         function asyncEval( implementations, cb ) {
1676                                 if ( !implementations.length ) {
1677                                         return;
1678                                 }
1679                                 mw.requestIdleCallback( function () {
1680                                         try {
1681                                                 $.globalEval( implementations.join( ';' ) );
1682                                         } catch ( err ) {
1683                                                 cb( err );
1684                                         }
1685                                 } );
1686                         }
1688                         /**
1689                          * Make a versioned key for a specific module.
1690                          *
1691                          * @private
1692                          * @param {string} module Module name
1693                          * @return {string|null} Module key in format '`[name]@[version]`',
1694                          *  or null if the module does not exist
1695                          */
1696                         function getModuleKey( module ) {
1697                                 return hasOwn.call( registry, module ) ?
1698                                         ( module + '@' + registry[ module ].version ) : null;
1699                         }
1701                         /**
1702                          * @private
1703                          * @param {string} key Module name or '`[name]@[version]`'
1704                          * @return {Object}
1705                          */
1706                         function splitModuleKey( key ) {
1707                                 var index = key.indexOf( '@' );
1708                                 if ( index === -1 ) {
1709                                         return { name: key };
1710                                 }
1711                                 return {
1712                                         name: key.slice( 0, index ),
1713                                         version: key.slice( index + 1 )
1714                                 };
1715                         }
1717                         /* Public Members */
1718                         return {
1719                                 /**
1720                                  * The module registry is exposed as an aid for debugging and inspecting page
1721                                  * state; it is not a public interface for modifying the registry.
1722                                  *
1723                                  * @see #registry
1724                                  * @property
1725                                  * @private
1726                                  */
1727                                 moduleRegistry: registry,
1729                                 /**
1730                                  * @inheritdoc #newStyleTag
1731                                  * @method
1732                                  */
1733                                 addStyleTag: newStyleTag,
1735                                 /**
1736                                  * Start loading of all queued module dependencies.
1737                                  *
1738                                  * @protected
1739                                  */
1740                                 work: function () {
1741                                         var q, batch, implementations, sourceModules;
1743                                         batch = [];
1745                                         // Appends a list of modules from the queue to the batch
1746                                         for ( q = 0; q < queue.length; q++ ) {
1747                                                 // Only load modules which are registered
1748                                                 if ( hasOwn.call( registry, queue[ q ] ) && registry[ queue[ q ] ].state === 'registered' ) {
1749                                                         // Prevent duplicate entries
1750                                                         if ( $.inArray( queue[ q ], batch ) === -1 ) {
1751                                                                 batch.push( queue[ q ] );
1752                                                                 // Mark registered modules as loading
1753                                                                 registry[ queue[ q ] ].state = 'loading';
1754                                                         }
1755                                                 }
1756                                         }
1758                                         // Now that the queue has been processed into a batch, clear the queue.
1759                                         // This MUST happen before we initiate any eval or network request. Otherwise,
1760                                         // it is possible for a cached script to instantly trigger the same work queue
1761                                         // again; all before we've cleared it causing each request to include modules
1762                                         // which are already loaded.
1763                                         queue = [];
1765                                         if ( !batch.length ) {
1766                                                 return;
1767                                         }
1769                                         mw.loader.store.init();
1770                                         if ( mw.loader.store.enabled ) {
1771                                                 implementations = [];
1772                                                 sourceModules = [];
1773                                                 batch = $.grep( batch, function ( module ) {
1774                                                         var implementation = mw.loader.store.get( module );
1775                                                         if ( implementation ) {
1776                                                                 implementations.push( implementation );
1777                                                                 sourceModules.push( module );
1778                                                                 return false;
1779                                                         }
1780                                                         return true;
1781                                                 } );
1782                                                 asyncEval( implementations, function ( err ) {
1783                                                         var failed;
1784                                                         // Not good, the cached mw.loader.implement calls failed! This should
1785                                                         // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1786                                                         // Depending on how corrupt the string is, it is likely that some
1787                                                         // modules' implement() succeeded while the ones after the error will
1788                                                         // never run and leave their modules in the 'loading' state forever.
1789                                                         mw.loader.store.stats.failed++;
1791                                                         // Since this is an error not caused by an individual module but by
1792                                                         // something that infected the implement call itself, don't take any
1793                                                         // risks and clear everything in this cache.
1794                                                         mw.loader.store.clear();
1796                                                         mw.track( 'resourceloader.exception', { exception: err, source: 'store-eval' } );
1797                                                         // Re-add the failed ones that are still pending back to the batch
1798                                                         failed = $.grep( sourceModules, function ( module ) {
1799                                                                 return registry[ module ].state === 'loading';
1800                                                         } );
1801                                                         batchRequest( failed );
1802                                                 } );
1803                                         }
1805                                         batchRequest( batch );
1806                                 },
1808                                 /**
1809                                  * Register a source.
1810                                  *
1811                                  * The #work() method will use this information to split up requests by source.
1812                                  *
1813                                  *     mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1814                                  *
1815                                  * @param {string|Object} id Source ID, or object mapping ids to load urls
1816                                  * @param {string} loadUrl Url to a load.php end point
1817                                  * @throws {Error} If source id is already registered
1818                                  */
1819                                 addSource: function ( id, loadUrl ) {
1820                                         var source;
1821                                         // Allow multiple additions
1822                                         if ( typeof id === 'object' ) {
1823                                                 for ( source in id ) {
1824                                                         mw.loader.addSource( source, id[ source ] );
1825                                                 }
1826                                                 return;
1827                                         }
1829                                         if ( hasOwn.call( sources, id ) ) {
1830                                                 throw new Error( 'source already registered: ' + id );
1831                                         }
1833                                         sources[ id ] = loadUrl;
1834                                 },
1836                                 /**
1837                                  * Register a module, letting the system know about it and its properties.
1838                                  *
1839                                  * The startup modules contain calls to this method.
1840                                  *
1841                                  * When using multiple module registration by passing an array, dependencies that
1842                                  * are specified as references to modules within the array will be resolved before
1843                                  * the modules are registered.
1844                                  *
1845                                  * @param {string|Array} module Module name or array of arrays, each containing
1846                                  *  a list of arguments compatible with this method
1847                                  * @param {string|number} version Module version hash (falls backs to empty string)
1848                                  *  Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1849                                  * @param {string|Array|Function} dependencies One string or array of strings of module
1850                                  *  names on which this module depends, or a function that returns that array.
1851                                  * @param {string} [group=null] Group which the module is in
1852                                  * @param {string} [source='local'] Name of the source
1853                                  * @param {string} [skip=null] Script body of the skip function
1854                                  */
1855                                 register: function ( module, version, dependencies, group, source, skip ) {
1856                                         var i, deps;
1857                                         // Allow multiple registration
1858                                         if ( typeof module === 'object' ) {
1859                                                 resolveIndexedDependencies( module );
1860                                                 for ( i = 0; i < module.length; i++ ) {
1861                                                         // module is an array of module names
1862                                                         if ( typeof module[ i ] === 'string' ) {
1863                                                                 mw.loader.register( module[ i ] );
1864                                                         // module is an array of arrays
1865                                                         } else if ( typeof module[ i ] === 'object' ) {
1866                                                                 mw.loader.register.apply( mw.loader, module[ i ] );
1867                                                         }
1868                                                 }
1869                                                 return;
1870                                         }
1871                                         if ( hasOwn.call( registry, module ) ) {
1872                                                 throw new Error( 'module already registered: ' + module );
1873                                         }
1874                                         if ( typeof dependencies === 'string' ) {
1875                                                 // A single module name
1876                                                 deps = [ dependencies ];
1877                                         } else if ( typeof dependencies === 'object' || typeof dependencies === 'function' ) {
1878                                                 // Array of module names or a function that returns an array
1879                                                 deps = dependencies;
1880                                         }
1881                                         // List the module as registered
1882                                         registry[ module ] = {
1883                                                 // Exposed to execute() for mw.loader.implement() closures.
1884                                                 // Import happens via require().
1885                                                 module: {
1886                                                         exports: {}
1887                                                 },
1888                                                 version: version !== undefined ? String( version ) : '',
1889                                                 dependencies: deps || [],
1890                                                 group: typeof group === 'string' ? group : null,
1891                                                 source: typeof source === 'string' ? source : 'local',
1892                                                 state: 'registered',
1893                                                 skip: typeof skip === 'string' ? skip : null
1894                                         };
1895                                 },
1897                                 /**
1898                                  * Implement a module given the components that make up the module.
1899                                  *
1900                                  * When #load() or #using() requests one or more modules, the server
1901                                  * response contain calls to this function.
1902                                  *
1903                                  * @param {string} module Name of module and current module version. Formatted
1904                                  *  as '`[name]@[version]`". This version should match the requested version
1905                                  *  (from #batchRequest and #registry). This avoids race conditions (T117587).
1906                                  *  For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1907                                  * @param {Function|Array|string} [script] Function with module code, list of URLs
1908                                  *  to load via `<script src>`, or string of module code for `$.globalEval()`.
1909                                  * @param {Object} [style] Should follow one of the following patterns:
1910                                  *
1911                                  *     { "css": [css, ..] }
1912                                  *     { "url": { <media>: [url, ..] } }
1913                                  *
1914                                  * And for backwards compatibility (needs to be supported forever due to caching):
1915                                  *
1916                                  *     { <media>: css }
1917                                  *     { <media>: [url, ..] }
1918                                  *
1919                                  * The reason css strings are not concatenated anymore is T33676. We now check
1920                                  * whether it's safe to extend the stylesheet.
1921                                  *
1922                                  * @protected
1923                                  * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1924                                  * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1925                                  */
1926                                 implement: function ( module, script, style, messages, templates ) {
1927                                         var split = splitModuleKey( module ),
1928                                                 name = split.name,
1929                                                 version = split.version;
1930                                         // Automatically register module
1931                                         if ( !hasOwn.call( registry, name ) ) {
1932                                                 mw.loader.register( name );
1933                                         }
1934                                         // Check for duplicate implementation
1935                                         if ( hasOwn.call( registry, name ) && registry[ name ].script !== undefined ) {
1936                                                 throw new Error( 'module already implemented: ' + name );
1937                                         }
1938                                         if ( version ) {
1939                                                 // Without this reset, if there is a version mismatch between the
1940                                                 // requested and received module version, then mw.loader.store would
1941                                                 // cache the response under the requested key. Thus poisoning the cache
1942                                                 // indefinitely with a stale value. (T117587)
1943                                                 registry[ name ].version = version;
1944                                         }
1945                                         // Attach components
1946                                         registry[ name ].script = script || null;
1947                                         registry[ name ].style = style || null;
1948                                         registry[ name ].messages = messages || null;
1949                                         registry[ name ].templates = templates || null;
1950                                         // The module may already have been marked as erroneous
1951                                         if ( $.inArray( registry[ name ].state, [ 'error', 'missing' ] ) === -1 ) {
1952                                                 registry[ name ].state = 'loaded';
1953                                                 if ( allReady( registry[ name ].dependencies ) ) {
1954                                                         execute( name );
1955                                                 }
1956                                         }
1957                                 },
1959                                 /**
1960                                  * Execute a function as soon as one or more required modules are ready.
1961                                  *
1962                                  * Example of inline dependency on OOjs:
1963                                  *
1964                                  *     mw.loader.using( 'oojs', function () {
1965                                  *         OO.compare( [ 1 ], [ 1 ] );
1966                                  *     } );
1967                                  *
1968                                  * Since MediaWiki 1.23 this also returns a promise.
1969                                  *
1970                                  * Since MediaWiki 1.28 the promise is resolved with a `require` function.
1971                                  *
1972                                  * @param {string|Array} dependencies Module name or array of modules names the
1973                                  *  callback depends on to be ready before executing
1974                                  * @param {Function} [ready] Callback to execute when all dependencies are ready
1975                                  * @param {Function} [error] Callback to execute if one or more dependencies failed
1976                                  * @return {jQuery.Promise} With a `require` function
1977                                  */
1978                                 using: function ( dependencies, ready, error ) {
1979                                         var deferred = $.Deferred();
1981                                         // Allow calling with a single dependency as a string
1982                                         if ( typeof dependencies === 'string' ) {
1983                                                 dependencies = [ dependencies ];
1984                                         }
1986                                         if ( ready ) {
1987                                                 deferred.done( ready );
1988                                         }
1989                                         if ( error ) {
1990                                                 deferred.fail( error );
1991                                         }
1993                                         try {
1994                                                 // Resolve entire dependency map
1995                                                 dependencies = resolve( dependencies );
1996                                         } catch ( e ) {
1997                                                 return deferred.reject( e ).promise();
1998                                         }
1999                                         if ( allReady( dependencies ) ) {
2000                                                 // Run ready immediately
2001                                                 deferred.resolve( mw.loader.require );
2002                                         } else if ( anyFailed( dependencies ) ) {
2003                                                 // Execute error immediately if any dependencies have errors
2004                                                 deferred.reject(
2005                                                         new Error( 'One or more dependencies failed to load' ),
2006                                                         dependencies
2007                                                 );
2008                                         } else {
2009                                                 // Not all dependencies are ready, add to the load queue
2010                                                 enqueue( dependencies, function () {
2011                                                         deferred.resolve( mw.loader.require );
2012                                                 }, deferred.reject );
2013                                         }
2015                                         return deferred.promise();
2016                                 },
2018                                 /**
2019                                  * Load an external script or one or more modules.
2020                                  *
2021                                  * @param {string|Array} modules Either the name of a module, array of modules,
2022                                  *  or a URL of an external script or style
2023                                  * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
2024                                  *  external script or style; acceptable values are "text/css" and
2025                                  *  "text/javascript"; if no type is provided, text/javascript is assumed.
2026                                  */
2027                                 load: function ( modules, type ) {
2028                                         var filtered, l;
2030                                         // Allow calling with a url or single dependency as a string
2031                                         if ( typeof modules === 'string' ) {
2032                                                 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
2033                                                 if ( /^(https?:)?\/?\//.test( modules ) ) {
2034                                                         if ( type === 'text/css' ) {
2035                                                                 // Support: IE 7-8
2036                                                                 // Use properties instead of attributes as IE throws security
2037                                                                 // warnings when inserting a <link> tag with a protocol-relative
2038                                                                 // URL set though attributes - when on HTTPS. See T43331.
2039                                                                 l = document.createElement( 'link' );
2040                                                                 l.rel = 'stylesheet';
2041                                                                 l.href = modules;
2042                                                                 $( 'head' ).append( l );
2043                                                                 return;
2044                                                         }
2045                                                         if ( type === 'text/javascript' || type === undefined ) {
2046                                                                 addScript( modules );
2047                                                                 return;
2048                                                         }
2049                                                         // Unknown type
2050                                                         throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type );
2051                                                 }
2052                                                 // Called with single module
2053                                                 modules = [ modules ];
2054                                         }
2056                                         // Filter out undefined modules, otherwise resolve() will throw
2057                                         // an exception for trying to load an undefined module.
2058                                         // Undefined modules are acceptable here in load(), because load() takes
2059                                         // an array of unrelated modules, whereas the modules passed to
2060                                         // using() are related and must all be loaded.
2061                                         filtered = $.grep( modules, function ( module ) {
2062                                                 var state = mw.loader.getState( module );
2063                                                 return state !== null && state !== 'error' && state !== 'missing';
2064                                         } );
2066                                         if ( filtered.length === 0 ) {
2067                                                 return;
2068                                         }
2069                                         // Resolve entire dependency map
2070                                         filtered = resolve( filtered );
2071                                         // If all modules are ready, or if any modules have errors, nothing to be done.
2072                                         if ( allReady( filtered ) || anyFailed( filtered ) ) {
2073                                                 return;
2074                                         }
2075                                         // Some modules are not yet ready, add to module load queue.
2076                                         enqueue( filtered, undefined, undefined );
2077                                 },
2079                                 /**
2080                                  * Change the state of one or more modules.
2081                                  *
2082                                  * @param {string|Object} module Module name or object of module name/state pairs
2083                                  * @param {string} state State name
2084                                  */
2085                                 state: function ( module, state ) {
2086                                         var m;
2088                                         if ( typeof module === 'object' ) {
2089                                                 for ( m in module ) {
2090                                                         mw.loader.state( m, module[ m ] );
2091                                                 }
2092                                                 return;
2093                                         }
2094                                         if ( !hasOwn.call( registry, module ) ) {
2095                                                 mw.loader.register( module );
2096                                         }
2097                                         registry[ module ].state = state;
2098                                         if ( $.inArray( state, [ 'ready', 'error', 'missing' ] ) !== -1 ) {
2099                                                 // Make sure pending modules depending on this one get executed if their
2100                                                 // dependencies are now fulfilled!
2101                                                 handlePending( module );
2102                                         }
2103                                 },
2105                                 /**
2106                                  * Get the version of a module.
2107                                  *
2108                                  * @param {string} module Name of module
2109                                  * @return {string|null} The version, or null if the module (or its version) is not
2110                                  *  in the registry.
2111                                  */
2112                                 getVersion: function ( module ) {
2113                                         if ( !hasOwn.call( registry, module ) || registry[ module ].version === undefined ) {
2114                                                 return null;
2115                                         }
2116                                         return registry[ module ].version;
2117                                 },
2119                                 /**
2120                                  * Get the state of a module.
2121                                  *
2122                                  * @param {string} module Name of module
2123                                  * @return {string|null} The state, or null if the module (or its state) is not
2124                                  *  in the registry.
2125                                  */
2126                                 getState: function ( module ) {
2127                                         if ( !hasOwn.call( registry, module ) || registry[ module ].state === undefined ) {
2128                                                 return null;
2129                                         }
2130                                         return registry[ module ].state;
2131                                 },
2133                                 /**
2134                                  * Get the names of all registered modules.
2135                                  *
2136                                  * @return {Array}
2137                                  */
2138                                 getModuleNames: function () {
2139                                         return $.map( registry, function ( i, key ) {
2140                                                 return key;
2141                                         } );
2142                                 },
2144                                 /**
2145                                  * Get the exported value of a module.
2146                                  *
2147                                  * Modules may provide this via their local `module.exports`.
2148                                  *
2149                                  * @protected
2150                                  * @since 1.27
2151                                  * @param {string} moduleName Module name
2152                                  * @return {Mixed} Exported value
2153                                  */
2154                                 require: function ( moduleName ) {
2155                                         var state = mw.loader.getState( moduleName );
2157                                         // Only ready modules can be required
2158                                         if ( state !== 'ready' ) {
2159                                                 // Module may've forgotten to declare a dependency
2160                                                 throw new Error( 'Module "' + moduleName + '" is not loaded.' );
2161                                         }
2163                                         return registry[ moduleName ].module.exports;
2164                                 },
2166                                 /**
2167                                  * @inheritdoc mw.inspect#runReports
2168                                  * @method
2169                                  */
2170                                 inspect: function () {
2171                                         var args = slice.call( arguments );
2172                                         mw.loader.using( 'mediawiki.inspect', function () {
2173                                                 mw.inspect.runReports.apply( mw.inspect, args );
2174                                         } );
2175                                 },
2177                                 /**
2178                                  * On browsers that implement the localStorage API, the module store serves as a
2179                                  * smart complement to the browser cache. Unlike the browser cache, the module store
2180                                  * can slice a concatenated response from ResourceLoader into its constituent
2181                                  * modules and cache each of them separately, using each module's versioning scheme
2182                                  * to determine when the cache should be invalidated.
2183                                  *
2184                                  * @singleton
2185                                  * @class mw.loader.store
2186                                  */
2187                                 store: {
2188                                         // Whether the store is in use on this page.
2189                                         enabled: null,
2191                                         // Modules whose string representation exceeds 100 kB are
2192                                         // ineligible for storage. See bug T66721.
2193                                         MODULE_SIZE_MAX: 100 * 1000,
2195                                         // The contents of the store, mapping '[name]@[version]' keys
2196                                         // to module implementations.
2197                                         items: {},
2199                                         // Cache hit stats
2200                                         stats: { hits: 0, misses: 0, expired: 0, failed: 0 },
2202                                         /**
2203                                          * Construct a JSON-serializable object representing the content of the store.
2204                                          *
2205                                          * @return {Object} Module store contents.
2206                                          */
2207                                         toJSON: function () {
2208                                                 return { items: mw.loader.store.items, vary: mw.loader.store.getVary() };
2209                                         },
2211                                         /**
2212                                          * Get the localStorage key for the entire module store. The key references
2213                                          * $wgDBname to prevent clashes between wikis which share a common host.
2214                                          *
2215                                          * @return {string} localStorage item key
2216                                          */
2217                                         getStoreKey: function () {
2218                                                 return 'MediaWikiModuleStore:' + mw.config.get( 'wgDBname' );
2219                                         },
2221                                         /**
2222                                          * Get a key on which to vary the module cache.
2223                                          *
2224                                          * @return {string} String of concatenated vary conditions.
2225                                          */
2226                                         getVary: function () {
2227                                                 return [
2228                                                         mw.config.get( 'skin' ),
2229                                                         mw.config.get( 'wgResourceLoaderStorageVersion' ),
2230                                                         mw.config.get( 'wgUserLanguage' )
2231                                                 ].join( ':' );
2232                                         },
2234                                         /**
2235                                          * Initialize the store.
2236                                          *
2237                                          * Retrieves store from localStorage and (if successfully retrieved) decoding
2238                                          * the stored JSON value to a plain object.
2239                                          *
2240                                          * The try / catch block is used for JSON & localStorage feature detection.
2241                                          * See the in-line documentation for Modernizr's localStorage feature detection
2242                                          * code for a full account of why we need a try / catch:
2243                                          * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2244                                          */
2245                                         init: function () {
2246                                                 var raw, data;
2248                                                 if ( mw.loader.store.enabled !== null ) {
2249                                                         // Init already ran
2250                                                         return;
2251                                                 }
2253                                                 if (
2254                                                         // Disabled because localStorage quotas are tight and (in Firefox's case)
2255                                                         // shared by multiple origins.
2256                                                         // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2257                                                         /Firefox|Opera/.test( navigator.userAgent ) ||
2259                                                         // Disabled by configuration.
2260                                                         !mw.config.get( 'wgResourceLoaderStorageEnabled' )
2261                                                 ) {
2262                                                         // Clear any previous store to free up space. (T66721)
2263                                                         mw.loader.store.clear();
2264                                                         mw.loader.store.enabled = false;
2265                                                         return;
2266                                                 }
2267                                                 if ( mw.config.get( 'debug' ) ) {
2268                                                         // Disable module store in debug mode
2269                                                         mw.loader.store.enabled = false;
2270                                                         return;
2271                                                 }
2273                                                 try {
2274                                                         raw = localStorage.getItem( mw.loader.store.getStoreKey() );
2275                                                         // If we get here, localStorage is available; mark enabled
2276                                                         mw.loader.store.enabled = true;
2277                                                         data = JSON.parse( raw );
2278                                                         if ( data && typeof data.items === 'object' && data.vary === mw.loader.store.getVary() ) {
2279                                                                 mw.loader.store.items = data.items;
2280                                                                 return;
2281                                                         }
2282                                                 } catch ( e ) {
2283                                                         mw.track( 'resourceloader.exception', { exception: e, source: 'store-localstorage-init' } );
2284                                                 }
2286                                                 if ( raw === undefined ) {
2287                                                         // localStorage failed; disable store
2288                                                         mw.loader.store.enabled = false;
2289                                                 } else {
2290                                                         mw.loader.store.update();
2291                                                 }
2292                                         },
2294                                         /**
2295                                          * Retrieve a module from the store and update cache hit stats.
2296                                          *
2297                                          * @param {string} module Module name
2298                                          * @return {string|boolean} Module implementation or false if unavailable
2299                                          */
2300                                         get: function ( module ) {
2301                                                 var key;
2303                                                 if ( !mw.loader.store.enabled ) {
2304                                                         return false;
2305                                                 }
2307                                                 key = getModuleKey( module );
2308                                                 if ( key in mw.loader.store.items ) {
2309                                                         mw.loader.store.stats.hits++;
2310                                                         return mw.loader.store.items[ key ];
2311                                                 }
2312                                                 mw.loader.store.stats.misses++;
2313                                                 return false;
2314                                         },
2316                                         /**
2317                                          * Stringify a module and queue it for storage.
2318                                          *
2319                                          * @param {string} module Module name
2320                                          * @param {Object} descriptor The module's descriptor as set in the registry
2321                                          * @return {boolean} Module was set
2322                                          */
2323                                         set: function ( module, descriptor ) {
2324                                                 var args, key, src;
2326                                                 if ( !mw.loader.store.enabled ) {
2327                                                         return false;
2328                                                 }
2330                                                 key = getModuleKey( module );
2332                                                 if (
2333                                                         // Already stored a copy of this exact version
2334                                                         key in mw.loader.store.items ||
2335                                                         // Module failed to load
2336                                                         descriptor.state !== 'ready' ||
2337                                                         // Unversioned, private, or site-/user-specific
2338                                                         ( !descriptor.version || $.inArray( descriptor.group, [ 'private', 'user' ] ) !== -1 ) ||
2339                                                         // Partial descriptor
2340                                                         // (e.g. skipped module, or style module with state=ready)
2341                                                         $.inArray( undefined, [ descriptor.script, descriptor.style,
2342                                                                 descriptor.messages, descriptor.templates ] ) !== -1
2343                                                 ) {
2344                                                         // Decline to store
2345                                                         return false;
2346                                                 }
2348                                                 try {
2349                                                         args = [
2350                                                                 JSON.stringify( key ),
2351                                                                 typeof descriptor.script === 'function' ?
2352                                                                         String( descriptor.script ) :
2353                                                                         JSON.stringify( descriptor.script ),
2354                                                                 JSON.stringify( descriptor.style ),
2355                                                                 JSON.stringify( descriptor.messages ),
2356                                                                 JSON.stringify( descriptor.templates )
2357                                                         ];
2358                                                         // Attempted workaround for a possible Opera bug (bug T59567).
2359                                                         // This regex should never match under sane conditions.
2360                                                         if ( /^\s*\(/.test( args[ 1 ] ) ) {
2361                                                                 args[ 1 ] = 'function' + args[ 1 ];
2362                                                                 mw.track( 'resourceloader.assert', { source: 'bug-T59567' } );
2363                                                         }
2364                                                 } catch ( e ) {
2365                                                         mw.track( 'resourceloader.exception', { exception: e, source: 'store-localstorage-json' } );
2366                                                         return false;
2367                                                 }
2369                                                 src = 'mw.loader.implement(' + args.join( ',' ) + ');';
2370                                                 if ( src.length > mw.loader.store.MODULE_SIZE_MAX ) {
2371                                                         return false;
2372                                                 }
2373                                                 mw.loader.store.items[ key ] = src;
2374                                                 mw.loader.store.update();
2375                                                 return true;
2376                                         },
2378                                         /**
2379                                          * Iterate through the module store, removing any item that does not correspond
2380                                          * (in name and version) to an item in the module registry.
2381                                          *
2382                                          * @return {boolean} Store was pruned
2383                                          */
2384                                         prune: function () {
2385                                                 var key, module;
2387                                                 if ( !mw.loader.store.enabled ) {
2388                                                         return false;
2389                                                 }
2391                                                 for ( key in mw.loader.store.items ) {
2392                                                         module = key.slice( 0, key.indexOf( '@' ) );
2393                                                         if ( getModuleKey( module ) !== key ) {
2394                                                                 mw.loader.store.stats.expired++;
2395                                                                 delete mw.loader.store.items[ key ];
2396                                                         } else if ( mw.loader.store.items[ key ].length > mw.loader.store.MODULE_SIZE_MAX ) {
2397                                                                 // This value predates the enforcement of a size limit on cached modules.
2398                                                                 delete mw.loader.store.items[ key ];
2399                                                         }
2400                                                 }
2401                                                 return true;
2402                                         },
2404                                         /**
2405                                          * Clear the entire module store right now.
2406                                          */
2407                                         clear: function () {
2408                                                 mw.loader.store.items = {};
2409                                                 try {
2410                                                         localStorage.removeItem( mw.loader.store.getStoreKey() );
2411                                                 } catch ( ignored ) {}
2412                                         },
2414                                         /**
2415                                          * Sync in-memory store back to localStorage.
2416                                          *
2417                                          * This function debounces updates. When called with a flush already pending,
2418                                          * the call is coalesced into the pending update. The call to
2419                                          * localStorage.setItem will be naturally deferred until the page is quiescent.
2420                                          *
2421                                          * Because localStorage is shared by all pages from the same origin, if multiple
2422                                          * pages are loaded with different module sets, the possibility exists that
2423                                          * modules saved by one page will be clobbered by another. But the impact would
2424                                          * be minor and the problem would be corrected by subsequent page views.
2425                                          *
2426                                          * @method
2427                                          */
2428                                         update: ( function () {
2429                                                 var hasPendingWrite = false;
2431                                                 function flushWrites() {
2432                                                         var data, key;
2433                                                         if ( !hasPendingWrite || !mw.loader.store.enabled ) {
2434                                                                 return;
2435                                                         }
2437                                                         mw.loader.store.prune();
2438                                                         key = mw.loader.store.getStoreKey();
2439                                                         try {
2440                                                                 // Replacing the content of the module store might fail if the new
2441                                                                 // contents would exceed the browser's localStorage size limit. To
2442                                                                 // avoid clogging the browser with stale data, always remove the old
2443                                                                 // value before attempting to set the new one.
2444                                                                 localStorage.removeItem( key );
2445                                                                 data = JSON.stringify( mw.loader.store );
2446                                                                 localStorage.setItem( key, data );
2447                                                         } catch ( e ) {
2448                                                                 mw.track( 'resourceloader.exception', { exception: e, source: 'store-localstorage-update' } );
2449                                                         }
2451                                                         hasPendingWrite = false;
2452                                                 }
2454                                                 return function () {
2455                                                         if ( !hasPendingWrite ) {
2456                                                                 hasPendingWrite = true;
2457                                                                 mw.requestIdleCallback( flushWrites );
2458                                                         }
2459                                                 };
2460                                         }() )
2461                                 }
2462                         };
2463                 }() ),
2465                 /**
2466                  * HTML construction helper functions
2467                  *
2468                  *     @example
2469                  *
2470                  *     var Html, output;
2471                  *
2472                  *     Html = mw.html;
2473                  *     output = Html.element( 'div', {}, new Html.Raw(
2474                  *         Html.element( 'img', { src: '<' } )
2475                  *     ) );
2476                  *     mw.log( output ); // <div><img src="&lt;"/></div>
2477                  *
2478                  * @class mw.html
2479                  * @singleton
2480                  */
2481                 html: ( function () {
2482                         function escapeCallback( s ) {
2483                                 switch ( s ) {
2484                                         case '\'':
2485                                                 return '&#039;';
2486                                         case '"':
2487                                                 return '&quot;';
2488                                         case '<':
2489                                                 return '&lt;';
2490                                         case '>':
2491                                                 return '&gt;';
2492                                         case '&':
2493                                                 return '&amp;';
2494                                 }
2495                         }
2497                         return {
2498                                 /**
2499                                  * Escape a string for HTML.
2500                                  *
2501                                  * Converts special characters to HTML entities.
2502                                  *
2503                                  *     mw.html.escape( '< > \' & "' );
2504                                  *     // Returns &lt; &gt; &#039; &amp; &quot;
2505                                  *
2506                                  * @param {string} s The string to escape
2507                                  * @return {string} HTML
2508                                  */
2509                                 escape: function ( s ) {
2510                                         return s.replace( /['"<>&]/g, escapeCallback );
2511                                 },
2513                                 /**
2514                                  * Create an HTML element string, with safe escaping.
2515                                  *
2516                                  * @param {string} name The tag name.
2517                                  * @param {Object} [attrs] An object with members mapping element names to values
2518                                  * @param {string|mw.html.Raw|mw.html.Cdata|null} [contents=null] The contents of the element.
2519                                  *
2520                                  *  - string: Text to be escaped.
2521                                  *  - null: The element is treated as void with short closing form, e.g. `<br/>`.
2522                                  *  - this.Raw: The raw value is directly included.
2523                                  *  - this.Cdata: The raw value is directly included. An exception is
2524                                  *    thrown if it contains any illegal ETAGO delimiter.
2525                                  *    See <https://www.w3.org/TR/html401/appendix/notes.html#h-B.3.2>.
2526                                  * @return {string} HTML
2527                                  */
2528                                 element: function ( name, attrs, contents ) {
2529                                         var v, attrName, s = '<' + name;
2531                                         if ( attrs ) {
2532                                                 for ( attrName in attrs ) {
2533                                                         v = attrs[ attrName ];
2534                                                         // Convert name=true, to name=name
2535                                                         if ( v === true ) {
2536                                                                 v = attrName;
2537                                                         // Skip name=false
2538                                                         } else if ( v === false ) {
2539                                                                 continue;
2540                                                         }
2541                                                         s += ' ' + attrName + '="' + this.escape( String( v ) ) + '"';
2542                                                 }
2543                                         }
2544                                         if ( contents === undefined || contents === null ) {
2545                                                 // Self close tag
2546                                                 s += '/>';
2547                                                 return s;
2548                                         }
2549                                         // Regular open tag
2550                                         s += '>';
2551                                         switch ( typeof contents ) {
2552                                                 case 'string':
2553                                                         // Escaped
2554                                                         s += this.escape( contents );
2555                                                         break;
2556                                                 case 'number':
2557                                                 case 'boolean':
2558                                                         // Convert to string
2559                                                         s += String( contents );
2560                                                         break;
2561                                                 default:
2562                                                         if ( contents instanceof this.Raw ) {
2563                                                                 // Raw HTML inclusion
2564                                                                 s += contents.value;
2565                                                         } else if ( contents instanceof this.Cdata ) {
2566                                                                 // CDATA
2567                                                                 if ( /<\/[a-zA-z]/.test( contents.value ) ) {
2568                                                                         throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
2569                                                                 }
2570                                                                 s += contents.value;
2571                                                         } else {
2572                                                                 throw new Error( 'mw.html.element: Invalid type of contents' );
2573                                                         }
2574                                         }
2575                                         s += '</' + name + '>';
2576                                         return s;
2577                                 },
2579                                 /**
2580                                  * Wrapper object for raw HTML passed to mw.html.element().
2581                                  *
2582                                  * @class mw.html.Raw
2583                                  * @constructor
2584                                  * @param {string} value
2585                                  */
2586                                 Raw: function ( value ) {
2587                                         this.value = value;
2588                                 },
2590                                 /**
2591                                  * Wrapper object for CDATA element contents passed to mw.html.element()
2592                                  *
2593                                  * @class mw.html.Cdata
2594                                  * @constructor
2595                                  * @param {string} value
2596                                  */
2597                                 Cdata: function ( value ) {
2598                                         this.value = value;
2599                                 }
2600                         };
2601                 }() ),
2603                 // Skeleton user object, extended by the 'mediawiki.user' module.
2604                 /**
2605                  * @class mw.user
2606                  * @singleton
2607                  */
2608                 user: {
2609                         /**
2610                          * @property {mw.Map}
2611                          */
2612                         options: new Map(),
2613                         /**
2614                          * @property {mw.Map}
2615                          */
2616                         tokens: new Map()
2617                 },
2619                 // OOUI widgets specific to MediaWiki
2620                 widgets: {},
2622                 /**
2623                  * Registry and firing of events.
2624                  *
2625                  * MediaWiki has various interface components that are extended, enhanced
2626                  * or manipulated in some other way by extensions, gadgets and even
2627                  * in core itself.
2628                  *
2629                  * This framework helps streamlining the timing of when these other
2630                  * code paths fire their plugins (instead of using document-ready,
2631                  * which can and should be limited to firing only once).
2632                  *
2633                  * Features like navigating to other wiki pages, previewing an edit
2634                  * and editing itself – without a refresh – can then retrigger these
2635                  * hooks accordingly to ensure everything still works as expected.
2636                  *
2637                  * Example usage:
2638                  *
2639                  *     mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
2640                  *     mw.hook( 'wikipage.content' ).fire( $content );
2641                  *
2642                  * Handlers can be added and fired for arbitrary event names at any time. The same
2643                  * event can be fired multiple times. The last run of an event is memorized
2644                  * (similar to `$(document).ready` and `$.Deferred().done`).
2645                  * This means if an event is fired, and a handler added afterwards, the added
2646                  * function will be fired right away with the last given event data.
2647                  *
2648                  * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
2649                  * Thus allowing flexible use and optimal maintainability and authority control.
2650                  * You can pass around the `add` and/or `fire` method to another piece of code
2651                  * without it having to know the event name (or `mw.hook` for that matter).
2652                  *
2653                  *     var h = mw.hook( 'bar.ready' );
2654                  *     new mw.Foo( .. ).fetch( { callback: h.fire } );
2655                  *
2656                  * Note: Events are documented with an underscore instead of a dot in the event
2657                  * name due to jsduck not supporting dots in that position.
2658                  *
2659                  * @class mw.hook
2660                  */
2661                 hook: ( function () {
2662                         var lists = {};
2664                         /**
2665                          * Create an instance of mw.hook.
2666                          *
2667                          * @method hook
2668                          * @member mw
2669                          * @param {string} name Name of hook.
2670                          * @return {mw.hook}
2671                          */
2672                         return function ( name ) {
2673                                 var list = hasOwn.call( lists, name ) ?
2674                                         lists[ name ] :
2675                                         lists[ name ] = $.Callbacks( 'memory' );
2677                                 return {
2678                                         /**
2679                                          * Register a hook handler
2680                                          *
2681                                          * @param {...Function} handler Function to bind.
2682                                          * @chainable
2683                                          */
2684                                         add: list.add,
2686                                         /**
2687                                          * Unregister a hook handler
2688                                          *
2689                                          * @param {...Function} handler Function to unbind.
2690                                          * @chainable
2691                                          */
2692                                         remove: list.remove,
2694                                         // eslint-disable-next-line valid-jsdoc
2695                                         /**
2696                                          * Run a hook.
2697                                          *
2698                                          * @param {...Mixed} data
2699                                          * @chainable
2700                                          */
2701                                         fire: function () {
2702                                                 return list.fireWith.call( this, null, slice.call( arguments ) );
2703                                         }
2704                                 };
2705                         };
2706                 }() )
2707         };
2709         // Alias $j to jQuery for backwards compatibility
2710         // @deprecated since 1.23 Use $ or jQuery instead
2711         mw.log.deprecate( window, '$j', $, 'Use $ or jQuery instead.' );
2713         /**
2714          * Log a message to window.console, if possible.
2715          *
2716          * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
2717          * also in production mode). Gets console references in each invocation instead of caching the
2718          * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
2719          *
2720          * @private
2721          * @param {string} topic Stream name passed by mw.track
2722          * @param {Object} data Data passed by mw.track
2723          * @param {Error} [data.exception]
2724          * @param {string} data.source Error source
2725          * @param {string} [data.module] Name of module which caused the error
2726          */
2727         function logError( topic, data ) {
2728                 /* eslint-disable no-console */
2729                 var msg,
2730                         e = data.exception,
2731                         source = data.source,
2732                         module = data.module,
2733                         console = window.console;
2735                 if ( console && console.log ) {
2736                         msg = ( e ? 'Exception' : 'Error' ) + ' in ' + source;
2737                         if ( module ) {
2738                                 msg += ' in module ' + module;
2739                         }
2740                         msg += ( e ? ':' : '.' );
2741                         console.log( msg );
2743                         // If we have an exception object, log it to the error channel to trigger
2744                         // proper stacktraces in browsers that support it. No fallback as we have
2745                         // no browsers that don't support error(), but do support log().
2746                         if ( e && console.error ) {
2747                                 console.error( String( e ), e );
2748                         }
2749                 }
2750                 /* eslint-enable no-console */
2751         }
2753         // Subscribe to error streams
2754         mw.trackSubscribe( 'resourceloader.exception', logError );
2755         mw.trackSubscribe( 'resourceloader.assert', logError );
2757         /**
2758          * Fired when all modules associated with the page have finished loading.
2759          *
2760          * @event resourceloader_loadEnd
2761          * @member mw.hook
2762          */
2763         $( function () {
2764                 var loading = $.grep( mw.loader.getModuleNames(), function ( module ) {
2765                         return mw.loader.getState( module ) === 'loading';
2766                 } );
2767                 // We only need a callback, not any actual module. First try a single using()
2768                 // for all loading modules. If one fails, fall back to tracking each module
2769                 // separately via $.when(), this is expensive.
2770                 loading = mw.loader.using( loading ).then( null, function () {
2771                         var all = $.map( loading, function ( module ) {
2772                                 return mw.loader.using( module ).then( null, function () {
2773                                         return $.Deferred().resolve();
2774                                 } );
2775                         } );
2776                         return $.when.apply( $, all );
2777                 } );
2778                 loading.then( function () {
2779                         /* global mwPerformance */
2780                         mwPerformance.mark( 'mwLoadEnd' );
2781                         mw.hook( 'resourceloader.loadEnd' ).fire();
2782                 } );
2783         } );
2785         // Attach to window and globally alias
2786         window.mw = window.mediaWiki = mw;
2787 }( jQuery ) );