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