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