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