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