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