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