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