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