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