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