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