Merge "resourceloader: Remove unused code in private mw.loader#enqueue()"
[lhc/web/wiklou.git] / resources / src / startup / 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 /* global $VARS, $CODE */
11
12 ( function () {
13 'use strict';
14
15 var mw, StringSet, log,
16 hasOwn = Object.prototype.hasOwnProperty,
17 trackQueue = [];
18
19 /**
20 * FNV132 hash function
21 *
22 * This function implements the 32-bit version of FNV-1.
23 * It is equivalent to hash( 'fnv132', ... ) in PHP, except
24 * its output is base 36 rather than hex.
25 * See <https://en.wikipedia.org/wiki/FNV_hash_function>
26 *
27 * @private
28 * @param {string} str String to hash
29 * @return {string} hash as an seven-character base 36 string
30 */
31 function fnv132( str ) {
32 /* eslint-disable no-bitwise */
33 var hash = 0x811C9DC5,
34 i;
35
36 for ( i = 0; i < str.length; i++ ) {
37 hash += ( hash << 1 ) + ( hash << 4 ) + ( hash << 7 ) + ( hash << 8 ) + ( hash << 24 );
38 hash ^= str.charCodeAt( i );
39 }
40
41 hash = ( hash >>> 0 ).toString( 36 );
42 while ( hash.length < 7 ) {
43 hash = '0' + hash;
44 }
45
46 return hash;
47 /* eslint-enable no-bitwise */
48 }
49
50 function defineFallbacks() {
51 // <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set>
52 StringSet = window.Set || ( function () {
53 /**
54 * @private
55 * @class
56 */
57 function StringSet() {
58 this.set = {};
59 }
60 StringSet.prototype.add = function ( value ) {
61 this.set[ value ] = true;
62 };
63 StringSet.prototype.has = function ( value ) {
64 return hasOwn.call( this.set, value );
65 };
66 return StringSet;
67 }() );
68 }
69
70 /**
71 * Alias property to the global object.
72 *
73 * @private
74 * @static
75 * @member mw.Map
76 * @param {mw.Map} map
77 * @param {string} key
78 * @param {Mixed} value
79 */
80 function setGlobalMapValue( map, key, value ) {
81 map.values[ key ] = value;
82 log.deprecate(
83 window,
84 key,
85 value,
86 // Deprecation notice for mw.config globals (T58550, T72470)
87 map === mw.config && 'Use mw.config instead.'
88 );
89 }
90
91 /**
92 * Log a message to window.console, if possible.
93 *
94 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
95 * also in production mode). Gets console references in each invocation instead of caching the
96 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
97 *
98 * @private
99 * @param {string} topic Stream name passed by mw.track
100 * @param {Object} data Data passed by mw.track
101 * @param {Error} [data.exception]
102 * @param {string} data.source Error source
103 * @param {string} [data.module] Name of module which caused the error
104 */
105 function logError( topic, data ) {
106 /* eslint-disable no-console */
107 var msg,
108 e = data.exception,
109 source = data.source,
110 module = data.module,
111 console = window.console;
112
113 if ( console && console.log ) {
114 msg = ( e ? 'Exception' : 'Error' ) + ' in ' + source;
115 if ( module ) {
116 msg += ' in module ' + module;
117 }
118 msg += ( e ? ':' : '.' );
119 console.log( msg );
120
121 // If we have an exception object, log it to the warning channel to trigger
122 // proper stacktraces in browsers that support it.
123 if ( e && console.warn ) {
124 console.warn( e );
125 }
126 }
127 /* eslint-enable no-console */
128 }
129
130 /**
131 * Create an object that can be read from or written to via methods that allow
132 * interaction both with single and multiple properties at once.
133 *
134 * @private
135 * @class mw.Map
136 *
137 * @constructor
138 * @param {boolean} [global=false] Whether to synchronise =values to the global
139 * window object (for backwards-compatibility with mw.config; T72470). Values are
140 * copied in one direction only. Changes to globals do not reflect in the map.
141 */
142 function Map( global ) {
143 this.values = {};
144 if ( global === true ) {
145 // Override #set to also set the global variable
146 this.set = function ( selection, value ) {
147 var s;
148 if ( arguments.length > 1 ) {
149 if ( typeof selection !== 'string' ) {
150 return false;
151 }
152 setGlobalMapValue( this, selection, value );
153 return true;
154 }
155 if ( typeof selection === 'object' ) {
156 for ( s in selection ) {
157 setGlobalMapValue( this, s, selection[ s ] );
158 }
159 return true;
160 }
161 return false;
162 };
163 }
164 }
165
166 Map.prototype = {
167 constructor: Map,
168
169 /**
170 * Get the value of one or more keys.
171 *
172 * If called with no arguments, all values are returned.
173 *
174 * @param {string|Array} [selection] Key or array of keys to retrieve values for.
175 * @param {Mixed} [fallback=null] Value for keys that don't exist.
176 * @return {Mixed|Object|null} If selection was a string, returns the value,
177 * If selection was an array, returns an object of key/values.
178 * If no selection is passed, a new object with all key/values is returned.
179 */
180 get: function ( selection, fallback ) {
181 var results, i;
182 fallback = arguments.length > 1 ? fallback : null;
183
184 if ( Array.isArray( selection ) ) {
185 results = {};
186 for ( i = 0; i < selection.length; i++ ) {
187 if ( typeof selection[ i ] === 'string' ) {
188 results[ selection[ i ] ] = hasOwn.call( this.values, selection[ i ] ) ?
189 this.values[ selection[ i ] ] :
190 fallback;
191 }
192 }
193 return results;
194 }
195
196 if ( typeof selection === 'string' ) {
197 return hasOwn.call( this.values, selection ) ?
198 this.values[ selection ] :
199 fallback;
200 }
201
202 if ( selection === undefined ) {
203 results = {};
204 for ( i in this.values ) {
205 results[ i ] = this.values[ i ];
206 }
207 return results;
208 }
209
210 // Invalid selection key
211 return fallback;
212 },
213
214 /**
215 * Set one or more key/value pairs.
216 *
217 * @param {string|Object} selection Key to set value for, or object mapping keys to values
218 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
219 * @return {boolean} True on success, false on failure
220 */
221 set: function ( selection, value ) {
222 var s;
223 // Use `arguments.length` because `undefined` is also a valid value.
224 if ( arguments.length > 1 ) {
225 if ( typeof selection !== 'string' ) {
226 return false;
227 }
228 this.values[ selection ] = value;
229 return true;
230 }
231 if ( typeof selection === 'object' ) {
232 for ( s in selection ) {
233 this.values[ s ] = selection[ s ];
234 }
235 return true;
236 }
237 return false;
238 },
239
240 /**
241 * Check if one or more keys exist.
242 *
243 * @param {Mixed} selection Key or array of keys to check
244 * @return {boolean} True if the key(s) exist
245 */
246 exists: function ( selection ) {
247 var i;
248 if ( Array.isArray( selection ) ) {
249 for ( i = 0; i < selection.length; i++ ) {
250 if ( typeof selection[ i ] !== 'string' || !hasOwn.call( this.values, selection[ i ] ) ) {
251 return false;
252 }
253 }
254 return true;
255 }
256 return typeof selection === 'string' && hasOwn.call( this.values, selection );
257 }
258 };
259
260 defineFallbacks();
261
262 /* eslint-disable no-console */
263 log = ( function () {
264 /**
265 * Write a verbose message to the browser's console in debug mode.
266 *
267 * This method is mainly intended for verbose logging. It is a no-op in production mode.
268 * In ResourceLoader debug mode, it will use the browser's console if available, with
269 * fallback to creating a console interface in the DOM and logging messages there.
270 *
271 * See {@link mw.log} for other logging methods.
272 *
273 * @member mw
274 * @param {...string} msg Messages to output to console.
275 */
276 var log = function () {},
277 console = window.console;
278
279 // Note: Keep list of methods in sync with restoration in mediawiki.log.js
280 // when adding or removing mw.log methods below!
281
282 /**
283 * Collection of methods to help log messages to the console.
284 *
285 * @class mw.log
286 * @singleton
287 */
288
289 /**
290 * Write a message to the browser console's warning channel.
291 *
292 * This method is a no-op in browsers that don't implement the Console API.
293 *
294 * @param {...string} msg Messages to output to console
295 */
296 log.warn = console && console.warn && Function.prototype.bind ?
297 Function.prototype.bind.call( console.warn, console ) :
298 function () {};
299
300 /**
301 * Write a message to the browser console's error channel.
302 *
303 * Most browsers also print a stacktrace when calling this method if the
304 * argument is an Error object.
305 *
306 * This method is a no-op in browsers that don't implement the Console API.
307 *
308 * @since 1.26
309 * @param {...Mixed} msg Messages to output to console
310 */
311 log.error = console && console.error && Function.prototype.bind ?
312 Function.prototype.bind.call( console.error, console ) :
313 function () {};
314
315 /**
316 * Create a property on a host object that, when accessed, will produce
317 * a deprecation warning in the console.
318 *
319 * @param {Object} obj Host object of deprecated property
320 * @param {string} key Name of property to create in `obj`
321 * @param {Mixed} val The value this property should return when accessed
322 * @param {string} [msg] Optional text to include in the deprecation message
323 * @param {string} [logName=key] Optional custom name for the feature.
324 * This is used instead of `key` in the message and `mw.deprecate` tracking.
325 */
326 log.deprecate = !Object.defineProperty ? function ( obj, key, val ) {
327 obj[ key ] = val;
328 } : function ( obj, key, val, msg, logName ) {
329 var logged = new StringSet();
330 logName = logName || key;
331 msg = 'Use of "' + logName + '" is deprecated.' + ( msg ? ( ' ' + msg ) : '' );
332 function uniqueTrace() {
333 var trace = new Error().stack;
334 if ( logged.has( trace ) ) {
335 return false;
336 }
337 logged.add( trace );
338 return true;
339 }
340 // Support: Safari 5.0
341 // Throws "not supported on DOM Objects" for Node or Element objects (incl. document)
342 // Safari 4.0 doesn't have this method, and it was fixed in Safari 5.1.
343 try {
344 Object.defineProperty( obj, key, {
345 configurable: true,
346 enumerable: true,
347 get: function () {
348 if ( uniqueTrace() ) {
349 mw.track( 'mw.deprecate', logName );
350 mw.log.warn( msg );
351 }
352 return val;
353 },
354 set: function ( newVal ) {
355 if ( uniqueTrace() ) {
356 mw.track( 'mw.deprecate', logName );
357 mw.log.warn( msg );
358 }
359 val = newVal;
360 }
361 } );
362 } catch ( err ) {
363 obj[ key ] = val;
364 }
365 };
366
367 return log;
368 }() );
369 /* eslint-enable no-console */
370
371 /**
372 * @class mw
373 */
374 mw = {
375 redefineFallbacksForTest: function () {
376 if ( !window.QUnit ) {
377 throw new Error( 'Reset not allowed outside unit tests' );
378 }
379 defineFallbacks();
380 },
381
382 /**
383 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
384 *
385 * On browsers that implement the Navigation Timing API, this function will produce floating-point
386 * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
387 * it will fall back to using `Date`.
388 *
389 * @return {number} Current time
390 */
391 now: ( function () {
392 var perf = window.performance,
393 navStart = perf && perf.timing && perf.timing.navigationStart;
394 return navStart && typeof perf.now === 'function' ?
395 function () { return navStart + perf.now(); } :
396 function () { return Date.now(); };
397 }() ),
398
399 /**
400 * List of all analytic events emitted so far.
401 *
402 * @private
403 * @property {Array}
404 */
405 trackQueue: trackQueue,
406
407 track: function ( topic, data ) {
408 trackQueue.push( { topic: topic, timeStamp: mw.now(), data: data } );
409 // The base module extends this method to fire events here
410 },
411
412 /**
413 * Track an early error event via mw.track and send it to the window console.
414 *
415 * @private
416 * @param {string} topic Topic name
417 * @param {Object} data Data describing the event, encoded as an object; see mw#logError
418 */
419 trackError: function ( topic, data ) {
420 mw.track( topic, data );
421 logError( topic, data );
422 },
423
424 // Expose Map constructor
425 Map: Map,
426
427 /**
428 * Map of configuration values.
429 *
430 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
431 * on mediawiki.org.
432 *
433 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
434 * global `window` object.
435 *
436 * @property {mw.Map} config
437 */
438 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
439 config: null,
440
441 /**
442 * Empty object for third-party libraries, for cases where you don't
443 * want to add a new global, or the global is bad and needs containment
444 * or wrapping.
445 *
446 * @property
447 */
448 libs: {},
449
450 /**
451 * Access container for deprecated functionality that can be moved from
452 * from their legacy location and attached to this object (e.g. a global
453 * function that is deprecated and as stop-gap can be exposed through here).
454 *
455 * This was reserved for future use but never ended up being used.
456 *
457 * @deprecated since 1.22 Let deprecated identifiers keep their original name
458 * and use mw.log#deprecate to create an access container for tracking.
459 * @property
460 */
461 legacy: {},
462
463 /**
464 * Store for messages.
465 *
466 * @property {mw.Map}
467 */
468 messages: new Map(),
469
470 /**
471 * Store for templates associated with a module.
472 *
473 * @property {mw.Map}
474 */
475 templates: new Map(),
476
477 // Expose mw.log
478 log: log,
479
480 /**
481 * Client for ResourceLoader server end point.
482 *
483 * This client is in charge of maintaining the module registry and state
484 * machine, initiating network (batch) requests for loading modules, as
485 * well as dependency resolution and execution of source code.
486 *
487 * For more information, refer to
488 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
489 *
490 * @class mw.loader
491 * @singleton
492 */
493 loader: ( function () {
494
495 /**
496 * Fired via mw.track on various resource loading errors.
497 *
498 * @event resourceloader_exception
499 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
500 * object, but in theory module code could manually throw something else, and that
501 * might also end up here.
502 * @param {string} [module] Name of the module which caused the error. Omitted if the
503 * error is not module-related or the module cannot be easily identified due to
504 * batched handling.
505 * @param {string} source Source of the error. Possible values:
506 *
507 * - style: stylesheet error (only affects old IE where a special style loading method
508 * is used)
509 * - load-callback: exception thrown by user callback
510 * - module-execute: exception thrown by module code
511 * - resolve: failed to sort dependencies for a module in mw.loader.load
512 * - store-eval: could not evaluate module code cached in localStorage
513 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
514 * - store-localstorage-json: JSON conversion error in mw.loader.store.set
515 * - store-localstorage-update: localStorage or JSON conversion error in mw.loader.store.update
516 */
517
518 /**
519 * Fired via mw.track on resource loading error conditions.
520 *
521 * @event resourceloader_assert
522 * @param {string} source Source of the error. Possible values:
523 *
524 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
525 * bug; see <https://phabricator.wikimedia.org/T59567> for details
526 */
527
528 /**
529 * Mapping of registered modules.
530 *
531 * See #implement and #execute for exact details on support for script, style and messages.
532 *
533 * Format:
534 *
535 * {
536 * 'moduleName': {
537 * // From mw.loader.register()
538 * 'version': '########' (hash)
539 * 'dependencies': ['required.foo', 'bar.also', ...]
540 * 'group': 'somegroup', (or) null
541 * 'source': 'local', (or) 'anotherwiki'
542 * 'skip': 'return !!window.Example', (or) null
543 * 'module': export Object
544 *
545 * // Set from execute() or mw.loader.state()
546 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
547 *
548 * // Optionally added at run-time by mw.loader.implement()
549 * 'skipped': true
550 * 'script': closure, array of urls, or string
551 * 'style': { ... } (see #execute)
552 * 'messages': { 'key': 'value', ... }
553 * }
554 * }
555 *
556 * State machine:
557 *
558 * - `registered`:
559 * The module is known to the system but not yet required.
560 * Meta data is registered via mw.loader#register. Calls to that method are
561 * generated server-side by the startup module.
562 * - `loading`:
563 * The module was required through mw.loader (either directly or as dependency of
564 * another module). The client will fetch module contents from the server.
565 * The contents are then stashed in the registry via mw.loader#implement.
566 * - `loaded`:
567 * The module has been loaded from the server and stashed via mw.loader#implement.
568 * If the module has no more dependencies in-flight, the module will be executed
569 * immediately. Otherwise execution is deferred, controlled via #handlePending.
570 * - `executing`:
571 * The module is being executed.
572 * - `ready`:
573 * The module has been successfully executed.
574 * - `error`:
575 * The module (or one of its dependencies) produced an error during execution.
576 * - `missing`:
577 * The module was registered client-side and requested, but the server denied knowledge
578 * of the module's existence.
579 *
580 * @property
581 * @private
582 */
583 var registry = {},
584 // Mapping of sources, keyed by source-id, values are strings.
585 //
586 // Format:
587 //
588 // {
589 // 'sourceId': 'http://example.org/w/load.php'
590 // }
591 //
592 sources = {},
593
594 // For queueModuleScript()
595 handlingPendingRequests = false,
596 pendingRequests = [],
597
598 // List of modules to be loaded
599 queue = [],
600
601 /**
602 * List of callback jobs waiting for modules to be ready.
603 *
604 * Jobs are created by #enqueue() and run by #handlePending().
605 *
606 * Typically when a job is created for a module, the job's dependencies contain
607 * both the required module and all its recursive dependencies.
608 *
609 * Format:
610 *
611 * {
612 * 'dependencies': [ module names ],
613 * 'ready': Function callback
614 * 'error': Function callback
615 * }
616 *
617 * @property {Object[]} jobs
618 * @private
619 */
620 jobs = [],
621
622 /**
623 * @private
624 * @property {Array} baseModules
625 */
626 baseModules = $VARS.baseModules,
627
628 /**
629 * For #addEmbeddedCSS() and #addLink()
630 *
631 * @private
632 * @property {HTMLElement|null} marker
633 */
634 marker = document.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' ),
635
636 // For addEmbeddedCSS()
637 cssBuffer = '',
638 cssBufferTimer = null,
639 cssCallbacks = [],
640 rAF = window.requestAnimationFrame || setTimeout;
641
642 /**
643 * Create a new style element and add it to the DOM.
644 *
645 * @private
646 * @param {string} text CSS text
647 * @param {Node|null} [nextNode] The element where the style tag
648 * should be inserted before
649 * @return {HTMLElement} Reference to the created style element
650 */
651 function newStyleTag( text, nextNode ) {
652 var el = document.createElement( 'style' );
653 el.appendChild( document.createTextNode( text ) );
654 if ( nextNode && nextNode.parentNode ) {
655 nextNode.parentNode.insertBefore( el, nextNode );
656 } else {
657 document.head.appendChild( el );
658 }
659 return el;
660 }
661
662 /**
663 * Add a bit of CSS text to the current browser page.
664 *
665 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
666 * or create a new one based on whether the given `cssText` is safe for extension.
667 *
668 * @private
669 * @param {string} [cssText=cssBuffer] If called without cssText,
670 * the internal buffer will be inserted instead.
671 * @param {Function} [callback]
672 */
673 function addEmbeddedCSS( cssText, callback ) {
674 function fireCallbacks() {
675 var i,
676 oldCallbacks = cssCallbacks;
677 // Reset cssCallbacks variable so it's not polluted by any calls to
678 // addEmbeddedCSS() from one of the callbacks (T105973)
679 cssCallbacks = [];
680 for ( i = 0; i < oldCallbacks.length; i++ ) {
681 oldCallbacks[ i ]();
682 }
683 }
684
685 if ( callback ) {
686 cssCallbacks.push( callback );
687 }
688
689 // Yield once before creating the <style> tag. This lets multiple stylesheets
690 // accumulate into one buffer, allowing us to reduce how often new stylesheets
691 // are inserted in the browser. Appending a stylesheet and waiting for the
692 // browser to repaint is fairly expensive. (T47810)
693 if ( cssText ) {
694 // Don't extend the buffer if the item needs its own stylesheet.
695 // Keywords like `@import` are only valid at the start of a stylesheet (T37562).
696 if ( !cssBuffer || cssText.slice( 0, '@import'.length ) !== '@import' ) {
697 // Linebreak for somewhat distinguishable sections
698 cssBuffer += '\n' + cssText;
699 if ( !cssBufferTimer ) {
700 cssBufferTimer = rAF( function () {
701 // Wrap in anonymous function that takes no arguments
702 // Support: Firefox < 13
703 // Firefox 12 has non-standard behaviour of passing a number
704 // as first argument to a setTimeout callback.
705 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
706 addEmbeddedCSS();
707 } );
708 }
709 return;
710 }
711
712 // This is a scheduled flush for the buffer
713 } else {
714 cssBufferTimer = null;
715 cssText = cssBuffer;
716 cssBuffer = '';
717 }
718
719 newStyleTag( cssText, marker );
720
721 fireCallbacks();
722 }
723
724 /**
725 * @private
726 * @param {Array} modules List of module names
727 * @return {string} Hash of concatenated version hashes.
728 */
729 function getCombinedVersion( modules ) {
730 var hashes = modules.reduce( function ( result, module ) {
731 return result + registry[ module ].version;
732 }, '' );
733 return fnv132( hashes );
734 }
735
736 /**
737 * Determine whether all dependencies are in state 'ready', which means we may
738 * execute the module or job now.
739 *
740 * @private
741 * @param {Array} modules Names of modules to be checked
742 * @return {boolean} True if all modules are in state 'ready', false otherwise
743 */
744 function allReady( modules ) {
745 var i;
746 for ( i = 0; i < modules.length; i++ ) {
747 if ( mw.loader.getState( modules[ i ] ) !== 'ready' ) {
748 return false;
749 }
750 }
751 return true;
752 }
753
754 /**
755 * Determine whether all direct and base dependencies are in state 'ready'
756 *
757 * @private
758 * @param {string} module Name of the module to be checked
759 * @return {boolean} True if all direct/base dependencies are in state 'ready'; false otherwise
760 */
761 function allWithImplicitReady( module ) {
762 return allReady( registry[ module ].dependencies ) &&
763 ( baseModules.indexOf( module ) !== -1 || allReady( baseModules ) );
764 }
765
766 /**
767 * Determine whether all dependencies are in state 'ready', which means we may
768 * execute the module or job now.
769 *
770 * @private
771 * @param {Array} modules Names of modules to be checked
772 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
773 */
774 function anyFailed( modules ) {
775 var i, state;
776 for ( i = 0; i < modules.length; i++ ) {
777 state = mw.loader.getState( modules[ i ] );
778 if ( state === 'error' || state === 'missing' ) {
779 return true;
780 }
781 }
782 return false;
783 }
784
785 /**
786 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
787 * pending jobs and modules that depend upon this module. If the given module failed,
788 * propagate the 'error' state up the dependency tree. Otherwise, go ahead and execute
789 * all jobs/modules now having their dependencies satisfied.
790 *
791 * Jobs that depend on a failed module, will have their error callback ran (if any).
792 *
793 * @private
794 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
795 */
796 function handlePending( module ) {
797 var j, job, hasErrors, m, stateChange, fromBaseModule;
798
799 if ( registry[ module ].state === 'error' || registry[ module ].state === 'missing' ) {
800 fromBaseModule = baseModules.indexOf( module ) !== -1;
801 // If the current module failed, mark all dependent modules also as failed.
802 // Iterate until steady-state to propagate the error state upwards in the
803 // dependency tree.
804 do {
805 stateChange = false;
806 for ( m in registry ) {
807 if ( registry[ m ].state !== 'error' && registry[ m ].state !== 'missing' ) {
808 // Always propagate errors from base modules to regular modules (implicit dependency).
809 // Between base modules or regular modules, consider direct dependencies only.
810 if (
811 ( fromBaseModule && baseModules.indexOf( m ) === -1 ) ||
812 anyFailed( registry[ m ].dependencies )
813 ) {
814 registry[ m ].state = 'error';
815 stateChange = true;
816 }
817 }
818 }
819 } while ( stateChange );
820 }
821
822 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
823 for ( j = 0; j < jobs.length; j++ ) {
824 hasErrors = anyFailed( jobs[ j ].dependencies );
825 if ( hasErrors || allReady( jobs[ j ].dependencies ) ) {
826 // All dependencies satisfied, or some have errors
827 job = jobs[ j ];
828 jobs.splice( j, 1 );
829 j -= 1;
830 try {
831 if ( hasErrors ) {
832 if ( typeof job.error === 'function' ) {
833 job.error( new Error( 'Module ' + module + ' has failed dependencies' ), [ module ] );
834 }
835 } else {
836 if ( typeof job.ready === 'function' ) {
837 job.ready();
838 }
839 }
840 } catch ( e ) {
841 // A user-defined callback raised an exception.
842 // Swallow it to protect our state machine!
843 mw.trackError( 'resourceloader.exception', {
844 exception: e,
845 module: module,
846 source: 'load-callback'
847 } );
848 }
849 }
850 }
851
852 // The current module became 'ready'.
853 if ( registry[ module ].state === 'ready' ) {
854 // Save it to the module store.
855 mw.loader.store.set( module, registry[ module ] );
856 // Recursively execute all dependent modules that were already loaded
857 // (waiting for execution) and no longer have unsatisfied dependencies.
858 for ( m in registry ) {
859 // Base modules may have dependencies amongst eachother to ensure correct
860 // execution order. Regular modules wait for all base modules.
861 if ( registry[ m ].state === 'loaded' && allWithImplicitReady( m ) ) {
862 // eslint-disable-next-line no-use-before-define
863 execute( m );
864 }
865 }
866 }
867 }
868
869 /**
870 * Resolve dependencies and detect circular references.
871 *
872 * @private
873 * @param {string} module Name of the top-level module whose dependencies shall be
874 * resolved and sorted.
875 * @param {Array} resolved Returns a topological sort of the given module and its
876 * dependencies, such that later modules depend on earlier modules. The array
877 * contains the module names. If the array contains already some module names,
878 * this function appends its result to the pre-existing array.
879 * @param {StringSet} [unresolved] Used to track the current dependency
880 * chain, and to report loops in the dependency graph.
881 * @throws {Error} If any unregistered module or a dependency loop is encountered
882 */
883 function sortDependencies( module, resolved, unresolved ) {
884 var i, deps, skip;
885
886 if ( !hasOwn.call( registry, module ) ) {
887 throw new Error( 'Unknown dependency: ' + module );
888 }
889
890 if ( registry[ module ].skip !== null ) {
891 // eslint-disable-next-line no-new-func
892 skip = new Function( registry[ module ].skip );
893 registry[ module ].skip = null;
894 if ( skip() ) {
895 registry[ module ].skipped = true;
896 registry[ module ].dependencies = [];
897 registry[ module ].state = 'ready';
898 handlePending( module );
899 return;
900 }
901 }
902
903 if ( resolved.indexOf( module ) !== -1 ) {
904 // Module already resolved; nothing to do
905 return;
906 }
907 // Create unresolved if not passed in
908 if ( !unresolved ) {
909 unresolved = new StringSet();
910 }
911
912 // Add base modules
913 if ( baseModules.indexOf( module ) === -1 ) {
914 baseModules.forEach( function ( baseModule ) {
915 if ( resolved.indexOf( baseModule ) === -1 ) {
916 resolved.push( baseModule );
917 }
918 } );
919 }
920
921 // Tracks down dependencies
922 deps = registry[ module ].dependencies;
923 unresolved.add( module );
924 for ( i = 0; i < deps.length; i++ ) {
925 if ( resolved.indexOf( deps[ i ] ) === -1 ) {
926 if ( unresolved.has( deps[ i ] ) ) {
927 throw new Error(
928 'Circular reference detected: ' + module + ' -> ' + deps[ i ]
929 );
930 }
931
932 sortDependencies( deps[ i ], resolved, unresolved );
933 }
934 }
935 resolved.push( module );
936 }
937
938 /**
939 * Get names of module that a module depends on, in their proper dependency order.
940 *
941 * @private
942 * @param {string[]} modules Array of string module names
943 * @return {Array} List of dependencies, including 'module'.
944 * @throws {Error} If an unregistered module or a dependency loop is encountered
945 */
946 function resolve( modules ) {
947 var i, resolved = [];
948 for ( i = 0; i < modules.length; i++ ) {
949 sortDependencies( modules[ i ], resolved );
950 }
951 return resolved;
952 }
953
954 /**
955 * Like #resolve(), except it will silently ignore modules that
956 * are missing or have missing dependencies.
957 *
958 * @private
959 * @param {string[]} modules Array of string module names
960 * @return {Array} List of dependencies.
961 */
962 function resolveStubbornly( modules ) {
963 var i, saved, resolved = [];
964 for ( i = 0; i < modules.length; i++ ) {
965 saved = resolved.slice();
966 try {
967 sortDependencies( modules[ i ], resolved );
968 } catch ( err ) {
969 // This module is unknown or has unknown dependencies.
970 // Undo any incomplete resolutions made and keep going.
971 resolved = saved;
972 mw.trackError( 'resourceloader.exception', {
973 exception: err,
974 source: 'resolve'
975 } );
976 }
977 }
978 return resolved;
979 }
980
981 /**
982 * Load and execute a script.
983 *
984 * @private
985 * @param {string} src URL to script, will be used as the src attribute in the script tag
986 * @param {Function} [callback] Callback to run after request resolution
987 */
988 function addScript( src, callback ) {
989 var script = document.createElement( 'script' );
990 script.src = src;
991 script.onload = script.onerror = function () {
992 if ( script.parentNode ) {
993 script.parentNode.removeChild( script );
994 }
995 script = null;
996 if ( callback ) {
997 callback();
998 callback = null;
999 }
1000 };
1001 document.head.appendChild( script );
1002 }
1003
1004 /**
1005 * Queue the loading and execution of a script for a particular module.
1006 *
1007 * This does for debug mode what runScript() does for production.
1008 *
1009 * @private
1010 * @param {string} src URL of the script
1011 * @param {string} moduleName Name of currently executing module
1012 * @param {Function} callback Callback to run after addScript() resolution
1013 */
1014 function queueModuleScript( src, moduleName, callback ) {
1015 pendingRequests.push( function () {
1016 // Keep in sync with execute()/runScript().
1017 if ( moduleName !== 'jquery' && hasOwn.call( registry, moduleName ) ) {
1018 window.require = mw.loader.require;
1019 window.module = registry[ moduleName ].module;
1020 }
1021 addScript( src, function () {
1022 // 'module.exports' should not persist after the file is executed to
1023 // avoid leakage to unrelated code. 'require' should be kept, however,
1024 // as asynchronous access to 'require' is allowed and expected. (T144879)
1025 delete window.module;
1026 callback();
1027 // Start the next one (if any)
1028 if ( pendingRequests[ 0 ] ) {
1029 pendingRequests.shift()();
1030 } else {
1031 handlingPendingRequests = false;
1032 }
1033 } );
1034 } );
1035 if ( !handlingPendingRequests && pendingRequests[ 0 ] ) {
1036 handlingPendingRequests = true;
1037 pendingRequests.shift()();
1038 }
1039 }
1040
1041 /**
1042 * Utility function for execute()
1043 *
1044 * @ignore
1045 * @param {string} [media] Media attribute
1046 * @param {string} url URL
1047 */
1048 function addLink( media, url ) {
1049 var el = document.createElement( 'link' );
1050
1051 el.rel = 'stylesheet';
1052 if ( media && media !== 'all' ) {
1053 el.media = media;
1054 }
1055 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1056 // see #addEmbeddedCSS, T33676, T43331, and T49277 for details.
1057 el.href = url;
1058
1059 if ( marker && marker.parentNode ) {
1060 marker.parentNode.insertBefore( el, marker );
1061 } else {
1062 document.head.appendChild( el );
1063 }
1064 }
1065
1066 /**
1067 * @private
1068 * @param {string} code JavaScript code
1069 */
1070 function domEval( code ) {
1071 var script = document.createElement( 'script' );
1072 if ( mw.config.get( 'wgCSPNonce' ) !== false ) {
1073 script.nonce = mw.config.get( 'wgCSPNonce' );
1074 }
1075 script.text = code;
1076 document.head.appendChild( script );
1077 script.parentNode.removeChild( script );
1078 }
1079
1080 /**
1081 * Add one or more modules to the module load queue.
1082 *
1083 * See also #work().
1084 *
1085 * @private
1086 * @param {string[]} dependencies Array of module names in the registry
1087 * @param {Function} [ready] Callback to execute when all dependencies are ready
1088 * @param {Function} [error] Callback to execute when any dependency fails
1089 */
1090 function enqueue( dependencies, ready, error ) {
1091 if ( allReady( dependencies ) ) {
1092 // Run ready immediately
1093 if ( ready !== undefined ) {
1094 ready();
1095 }
1096
1097 return;
1098 }
1099
1100 if ( anyFailed( dependencies ) ) {
1101 if ( error !== undefined ) {
1102 // Execute error immediately if any dependencies have errors
1103 error(
1104 new Error( 'One or more dependencies failed to load' ),
1105 dependencies
1106 );
1107 }
1108
1109 return;
1110 }
1111
1112 // Not all dependencies are ready, add to the load queue...
1113
1114 // Add ready and error callbacks if they were given
1115 if ( ready !== undefined || error !== undefined ) {
1116 jobs.push( {
1117 // Narrow down the list to modules that are worth waiting for
1118 dependencies: dependencies.filter( function ( module ) {
1119 var state = mw.loader.getState( module );
1120 return state === 'registered' || state === 'loaded' || state === 'loading' || state === 'executing';
1121 } ),
1122 ready: ready,
1123 error: error
1124 } );
1125 }
1126
1127 dependencies.forEach( function ( module ) {
1128 var state = mw.loader.getState( module );
1129 // Only queue modules that are still in the initial 'registered' state
1130 // (not ones already loading, ready or error).
1131 if ( state === 'registered' && queue.indexOf( module ) === -1 ) {
1132 // Private modules must be embedded in the page. Don't bother queuing
1133 // these as the server will deny them anyway (T101806).
1134 if ( registry[ module ].group === 'private' ) {
1135 registry[ module ].state = 'error';
1136 handlePending( module );
1137 return;
1138 }
1139 queue.push( module );
1140 }
1141 } );
1142
1143 mw.loader.work();
1144 }
1145
1146 /**
1147 * Executes a loaded module, making it ready to use
1148 *
1149 * @private
1150 * @param {string} module Module name to execute
1151 */
1152 function execute( module ) {
1153 var key, value, media, i, urls, cssHandle, checkCssHandles, runScript,
1154 cssHandlesRegistered = false;
1155
1156 if ( !hasOwn.call( registry, module ) ) {
1157 throw new Error( 'Module has not been registered yet: ' + module );
1158 }
1159 if ( registry[ module ].state !== 'loaded' ) {
1160 throw new Error( 'Module in state "' + registry[ module ].state + '" may not be executed: ' + module );
1161 }
1162
1163 registry[ module ].state = 'executing';
1164 $CODE.profileExecuteStart();
1165
1166 runScript = function () {
1167 var script, markModuleReady, nestedAddScript;
1168
1169 $CODE.profileScriptStart();
1170 script = registry[ module ].script;
1171 markModuleReady = function () {
1172 $CODE.profileScriptEnd();
1173 registry[ module ].state = 'ready';
1174 handlePending( module );
1175 };
1176 nestedAddScript = function ( arr, callback, i ) {
1177 // Recursively call queueModuleScript() in its own callback
1178 // for each element of arr.
1179 if ( i >= arr.length ) {
1180 // We're at the end of the array
1181 callback();
1182 return;
1183 }
1184
1185 queueModuleScript( arr[ i ], module, function () {
1186 nestedAddScript( arr, callback, i + 1 );
1187 } );
1188 };
1189
1190 try {
1191 if ( Array.isArray( script ) ) {
1192 nestedAddScript( script, markModuleReady, 0 );
1193 } else if ( typeof script === 'function' ) {
1194 // Keep in sync with queueModuleScript() for debug mode
1195 if ( module === 'jquery' ) {
1196 // This is a special case for when 'jquery' itself is being loaded.
1197 // - The standard jquery.js distribution does not set `window.jQuery`
1198 // in CommonJS-compatible environments (Node.js, AMD, RequireJS, etc.).
1199 // - MediaWiki's 'jquery' module also bundles jquery.migrate.js, which
1200 // in a CommonJS-compatible environment, will use require('jquery'),
1201 // but that can't work when we're still inside that module.
1202 script();
1203 } else {
1204 // Pass jQuery twice so that the signature of the closure which wraps
1205 // the script can bind both '$' and 'jQuery'.
1206 script( window.$, window.$, mw.loader.require, registry[ module ].module );
1207 }
1208 markModuleReady();
1209
1210 } else if ( typeof script === 'string' ) {
1211 // Site and user modules are legacy scripts that run in the global scope.
1212 // This is transported as a string instead of a function to avoid needing
1213 // to use string manipulation to undo the function wrapper.
1214 domEval( script );
1215 markModuleReady();
1216
1217 } else {
1218 // Module without script
1219 markModuleReady();
1220 }
1221 } catch ( e ) {
1222 // Use mw.track instead of mw.log because these errors are common in production mode
1223 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1224 registry[ module ].state = 'error';
1225 $CODE.profileScriptEnd();
1226 mw.trackError( 'resourceloader.exception', {
1227 exception: e, module:
1228 module, source: 'module-execute'
1229 } );
1230 handlePending( module );
1231 }
1232 };
1233
1234 // Add localizations to message system
1235 if ( registry[ module ].messages ) {
1236 mw.messages.set( registry[ module ].messages );
1237 }
1238
1239 // Initialise templates
1240 if ( registry[ module ].templates ) {
1241 mw.templates.set( module, registry[ module ].templates );
1242 }
1243
1244 // Make sure we don't run the scripts until all stylesheet insertions have completed.
1245 ( function () {
1246 var pending = 0;
1247 checkCssHandles = function () {
1248 var ex, dependencies;
1249 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1250 // one of the cssHandles is fired while we're still creating more handles.
1251 if ( cssHandlesRegistered && pending === 0 && runScript ) {
1252 if ( module === 'user' ) {
1253 // Implicit dependency on the site module. Not real dependency because
1254 // it should run after 'site' regardless of whether it succeeds or fails.
1255 // Note: This is a simplified version of mw.loader.using(), inlined here
1256 // as using() depends on jQuery (T192623).
1257 try {
1258 dependencies = resolve( [ 'site' ] );
1259 } catch ( e ) {
1260 ex = e;
1261 runScript();
1262 }
1263 if ( ex === undefined ) {
1264 enqueue( dependencies, runScript, runScript );
1265 }
1266 } else {
1267 runScript();
1268 }
1269 runScript = undefined; // Revoke
1270 }
1271 };
1272 cssHandle = function () {
1273 var check = checkCssHandles;
1274 pending++;
1275 return function () {
1276 if ( check ) {
1277 pending--;
1278 check();
1279 check = undefined; // Revoke
1280 }
1281 };
1282 };
1283 }() );
1284
1285 // Process styles (see also mw.loader.implement)
1286 // * back-compat: { <media>: css }
1287 // * back-compat: { <media>: [url, ..] }
1288 // * { "css": [css, ..] }
1289 // * { "url": { <media>: [url, ..] } }
1290 if ( registry[ module ].style ) {
1291 for ( key in registry[ module ].style ) {
1292 value = registry[ module ].style[ key ];
1293 media = undefined;
1294
1295 if ( key !== 'url' && key !== 'css' ) {
1296 // Backwards compatibility, key is a media-type
1297 if ( typeof value === 'string' ) {
1298 // back-compat: { <media>: css }
1299 // Ignore 'media' because it isn't supported (nor was it used).
1300 // Strings are pre-wrapped in "@media". The media-type was just ""
1301 // (because it had to be set to something).
1302 // This is one of the reasons why this format is no longer used.
1303 addEmbeddedCSS( value, cssHandle() );
1304 } else {
1305 // back-compat: { <media>: [url, ..] }
1306 media = key;
1307 key = 'bc-url';
1308 }
1309 }
1310
1311 // Array of css strings in key 'css',
1312 // or back-compat array of urls from media-type
1313 if ( Array.isArray( value ) ) {
1314 for ( i = 0; i < value.length; i++ ) {
1315 if ( key === 'bc-url' ) {
1316 // back-compat: { <media>: [url, ..] }
1317 addLink( media, value[ i ] );
1318 } else if ( key === 'css' ) {
1319 // { "css": [css, ..] }
1320 addEmbeddedCSS( value[ i ], cssHandle() );
1321 }
1322 }
1323 // Not an array, but a regular object
1324 // Array of urls inside media-type key
1325 } else if ( typeof value === 'object' ) {
1326 // { "url": { <media>: [url, ..] } }
1327 for ( media in value ) {
1328 urls = value[ media ];
1329 for ( i = 0; i < urls.length; i++ ) {
1330 addLink( media, urls[ i ] );
1331 }
1332 }
1333 }
1334 }
1335 }
1336
1337 // End profiling of execute()-self before we call checkCssHandles(),
1338 // which (sometimes asynchronously) calls runScript(), which we want
1339 // to measure separately without overlap.
1340 $CODE.profileExecuteEnd();
1341
1342 // Kick off.
1343 cssHandlesRegistered = true;
1344 checkCssHandles();
1345 }
1346
1347 function sortQuery( o ) {
1348 var key,
1349 sorted = {},
1350 a = [];
1351
1352 for ( key in o ) {
1353 a.push( key );
1354 }
1355 a.sort();
1356 for ( key = 0; key < a.length; key++ ) {
1357 sorted[ a[ key ] ] = o[ a[ key ] ];
1358 }
1359 return sorted;
1360 }
1361
1362 /**
1363 * Converts a module map of the form `{ foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }`
1364 * to a query string of the form `foo.bar,baz|bar.baz,quux`.
1365 *
1366 * See `ResourceLoader::makePackedModulesString()` in PHP, of which this is a port.
1367 * On the server, unpacking is done by `ResourceLoaderContext::expandModuleNames()`.
1368 *
1369 * Note: This is only half of the logic, the other half has to be in #batchRequest(),
1370 * because its implementation needs to keep track of potential string size in order
1371 * to decide when to split the requests due to url size.
1372 *
1373 * @private
1374 * @param {Object} moduleMap Module map
1375 * @return {Object}
1376 * @return {string} return.str Module query string
1377 * @return {Array} return.list List of module names in matching order
1378 */
1379 function buildModulesString( moduleMap ) {
1380 var p, prefix,
1381 str = [],
1382 list = [];
1383
1384 function restore( suffix ) {
1385 return p + suffix;
1386 }
1387
1388 for ( prefix in moduleMap ) {
1389 p = prefix === '' ? '' : prefix + '.';
1390 str.push( p + moduleMap[ prefix ].join( ',' ) );
1391 list.push.apply( list, moduleMap[ prefix ].map( restore ) );
1392 }
1393 return {
1394 str: str.join( '|' ),
1395 list: list
1396 };
1397 }
1398
1399 /**
1400 * Resolve indexed dependencies.
1401 *
1402 * ResourceLoader uses an optimization to save space which replaces module names in
1403 * dependency lists with the index of that module within the array of module
1404 * registration data if it exists. The benefit is a significant reduction in the data
1405 * size of the startup module. This function changes those dependency lists back to
1406 * arrays of strings.
1407 *
1408 * @private
1409 * @param {Array} modules Modules array
1410 */
1411 function resolveIndexedDependencies( modules ) {
1412 var i, j, deps;
1413 function resolveIndex( dep ) {
1414 return typeof dep === 'number' ? modules[ dep ][ 0 ] : dep;
1415 }
1416 for ( i = 0; i < modules.length; i++ ) {
1417 deps = modules[ i ][ 2 ];
1418 if ( deps ) {
1419 for ( j = 0; j < deps.length; j++ ) {
1420 deps[ j ] = resolveIndex( deps[ j ] );
1421 }
1422 }
1423 }
1424 }
1425
1426 /**
1427 * @private
1428 * @param {Object} params Map of parameter names to values
1429 * @return {string}
1430 */
1431 function makeQueryString( params ) {
1432 return Object.keys( params ).map( function ( key ) {
1433 return encodeURIComponent( key ) + '=' + encodeURIComponent( params[ key ] );
1434 } ).join( '&' );
1435 }
1436
1437 /**
1438 * Create network requests for a batch of modules.
1439 *
1440 * This is an internal method for #work(). This must not be called directly
1441 * unless the modules are already registered, and no request is in progress,
1442 * and the module state has already been set to `loading`.
1443 *
1444 * @private
1445 * @param {string[]} batch
1446 */
1447 function batchRequest( batch ) {
1448 var reqBase, splits, maxQueryLength, b, bSource, bGroup,
1449 source, group, i, modules, sourceLoadScript,
1450 currReqBase, currReqBaseLength, moduleMap, currReqModules, l,
1451 lastDotIndex, prefix, suffix, bytesAdded;
1452
1453 /**
1454 * Start the currently drafted request to the server.
1455 *
1456 * @ignore
1457 */
1458 function doRequest() {
1459 // Optimisation: Inherit (Object.create), not copy ($.extend)
1460 var query = Object.create( currReqBase ),
1461 packed = buildModulesString( moduleMap );
1462 query.modules = packed.str;
1463 // The packing logic can change the effective order, even if the input was
1464 // sorted. As such, the call to getCombinedVersion() must use this
1465 // effective order, instead of currReqModules, as otherwise the combined
1466 // version will not match the hash expected by the server based on
1467 // combining versions from the module query string in-order. (T188076)
1468 query.version = getCombinedVersion( packed.list );
1469 query = sortQuery( query );
1470 addScript( sourceLoadScript + '?' + makeQueryString( query ) );
1471 }
1472
1473 if ( !batch.length ) {
1474 return;
1475 }
1476
1477 // Always order modules alphabetically to help reduce cache
1478 // misses for otherwise identical content.
1479 batch.sort();
1480
1481 // Query parameters common to all requests
1482 reqBase = {
1483 skin: mw.config.get( 'skin' ),
1484 lang: mw.config.get( 'wgUserLanguage' ),
1485 debug: mw.config.get( 'debug' )
1486 };
1487 maxQueryLength = mw.config.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1488
1489 // Split module list by source and by group.
1490 splits = Object.create( null );
1491 for ( b = 0; b < batch.length; b++ ) {
1492 bSource = registry[ batch[ b ] ].source;
1493 bGroup = registry[ batch[ b ] ].group;
1494 if ( !splits[ bSource ] ) {
1495 splits[ bSource ] = Object.create( null );
1496 }
1497 if ( !splits[ bSource ][ bGroup ] ) {
1498 splits[ bSource ][ bGroup ] = [];
1499 }
1500 splits[ bSource ][ bGroup ].push( batch[ b ] );
1501 }
1502
1503 for ( source in splits ) {
1504 sourceLoadScript = sources[ source ];
1505
1506 for ( group in splits[ source ] ) {
1507
1508 // Cache access to currently selected list of
1509 // modules for this group from this source.
1510 modules = splits[ source ][ group ];
1511
1512 // Query parameters common to requests for this module group
1513 // Optimisation: Inherit (Object.create), not copy ($.extend)
1514 currReqBase = Object.create( reqBase );
1515 // User modules require a user name in the query string.
1516 if ( group === 'user' && mw.config.get( 'wgUserName' ) !== null ) {
1517 currReqBase.user = mw.config.get( 'wgUserName' );
1518 }
1519
1520 // In addition to currReqBase, doRequest() will also add 'modules' and 'version'.
1521 // > '&modules='.length === 9
1522 // > '&version=1234567'.length === 16
1523 // > 9 + 16 = 25
1524 currReqBaseLength = makeQueryString( currReqBase ).length + 25;
1525
1526 // We may need to split up the request to honor the query string length limit,
1527 // so build it piece by piece.
1528 l = currReqBaseLength;
1529 moduleMap = Object.create( null ); // { prefix: [ suffixes ] }
1530 currReqModules = [];
1531
1532 for ( i = 0; i < modules.length; i++ ) {
1533 // Determine how many bytes this module would add to the query string
1534 lastDotIndex = modules[ i ].lastIndexOf( '.' );
1535 // If lastDotIndex is -1, substr() returns an empty string
1536 prefix = modules[ i ].substr( 0, lastDotIndex );
1537 suffix = modules[ i ].slice( lastDotIndex + 1 );
1538 bytesAdded = moduleMap[ prefix ] ?
1539 suffix.length + 3 : // '%2C'.length == 3
1540 modules[ i ].length + 3; // '%7C'.length == 3
1541
1542 // If the url would become too long, create a new one, but don't create empty requests
1543 if ( maxQueryLength > 0 && currReqModules.length && l + bytesAdded > maxQueryLength ) {
1544 // Dispatch what we've got...
1545 doRequest();
1546 // .. and start again.
1547 l = currReqBaseLength;
1548 moduleMap = Object.create( null );
1549 currReqModules = [];
1550
1551 mw.track( 'resourceloader.splitRequest', { maxQueryLength: maxQueryLength } );
1552 }
1553 if ( !moduleMap[ prefix ] ) {
1554 moduleMap[ prefix ] = [];
1555 }
1556 l += bytesAdded;
1557 moduleMap[ prefix ].push( suffix );
1558 currReqModules.push( modules[ i ] );
1559 }
1560 // If there's anything left in moduleMap, request that too
1561 if ( currReqModules.length ) {
1562 doRequest();
1563 }
1564 }
1565 }
1566 }
1567
1568 /**
1569 * @private
1570 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1571 * form of calls to mw.loader#implement().
1572 * @param {Function} cb Callback in case of failure
1573 * @param {Error} cb.err
1574 */
1575 function asyncEval( implementations, cb ) {
1576 if ( !implementations.length ) {
1577 return;
1578 }
1579 mw.requestIdleCallback( function () {
1580 try {
1581 domEval( implementations.join( ';' ) );
1582 } catch ( err ) {
1583 cb( err );
1584 }
1585 } );
1586 }
1587
1588 /**
1589 * Make a versioned key for a specific module.
1590 *
1591 * @private
1592 * @param {string} module Module name
1593 * @return {string|null} Module key in format '`[name]@[version]`',
1594 * or null if the module does not exist
1595 */
1596 function getModuleKey( module ) {
1597 return hasOwn.call( registry, module ) ?
1598 ( module + '@' + registry[ module ].version ) : null;
1599 }
1600
1601 /**
1602 * @private
1603 * @param {string} key Module name or '`[name]@[version]`'
1604 * @return {Object}
1605 */
1606 function splitModuleKey( key ) {
1607 var index = key.indexOf( '@' );
1608 if ( index === -1 ) {
1609 return {
1610 name: key,
1611 version: ''
1612 };
1613 }
1614 return {
1615 name: key.slice( 0, index ),
1616 version: key.slice( index + 1 )
1617 };
1618 }
1619
1620 /* Public Members */
1621 return {
1622 /**
1623 * The module registry is exposed as an aid for debugging and inspecting page
1624 * state; it is not a public interface for modifying the registry.
1625 *
1626 * @see #registry
1627 * @property
1628 * @private
1629 */
1630 moduleRegistry: registry,
1631
1632 /**
1633 * @inheritdoc #newStyleTag
1634 * @method
1635 */
1636 addStyleTag: newStyleTag,
1637
1638 enqueue: enqueue,
1639
1640 resolve: resolve,
1641
1642 /**
1643 * Start loading of all queued module dependencies.
1644 *
1645 * @protected
1646 */
1647 work: function () {
1648 var q, batch, implementations, sourceModules;
1649
1650 batch = [];
1651
1652 // Appends a list of modules from the queue to the batch
1653 for ( q = 0; q < queue.length; q++ ) {
1654 // Only load modules which are registered
1655 if ( hasOwn.call( registry, queue[ q ] ) && registry[ queue[ q ] ].state === 'registered' ) {
1656 // Prevent duplicate entries
1657 if ( batch.indexOf( queue[ q ] ) === -1 ) {
1658 batch.push( queue[ q ] );
1659 // Mark registered modules as loading
1660 registry[ queue[ q ] ].state = 'loading';
1661 }
1662 }
1663 }
1664
1665 // Now that the queue has been processed into a batch, clear the queue.
1666 // This MUST happen before we initiate any eval or network request. Otherwise,
1667 // it is possible for a cached script to instantly trigger the same work queue
1668 // again; all before we've cleared it causing each request to include modules
1669 // which are already loaded.
1670 queue = [];
1671
1672 if ( !batch.length ) {
1673 return;
1674 }
1675
1676 mw.loader.store.init();
1677 if ( mw.loader.store.enabled ) {
1678 implementations = [];
1679 sourceModules = [];
1680 batch = batch.filter( function ( module ) {
1681 var implementation = mw.loader.store.get( module );
1682 if ( implementation ) {
1683 implementations.push( implementation );
1684 sourceModules.push( module );
1685 return false;
1686 }
1687 return true;
1688 } );
1689 asyncEval( implementations, function ( err ) {
1690 var failed;
1691 // Not good, the cached mw.loader.implement calls failed! This should
1692 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1693 // Depending on how corrupt the string is, it is likely that some
1694 // modules' implement() succeeded while the ones after the error will
1695 // never run and leave their modules in the 'loading' state forever.
1696 mw.loader.store.stats.failed++;
1697
1698 // Since this is an error not caused by an individual module but by
1699 // something that infected the implement call itself, don't take any
1700 // risks and clear everything in this cache.
1701 mw.loader.store.clear();
1702
1703 mw.trackError( 'resourceloader.exception', {
1704 exception: err,
1705 source: 'store-eval'
1706 } );
1707 // Re-add the failed ones that are still pending back to the batch
1708 failed = sourceModules.filter( function ( module ) {
1709 return registry[ module ].state === 'loading';
1710 } );
1711 batchRequest( failed );
1712 } );
1713 }
1714
1715 batchRequest( batch );
1716 },
1717
1718 /**
1719 * Register a source.
1720 *
1721 * The #work() method will use this information to split up requests by source.
1722 *
1723 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1724 *
1725 * @param {string|Object} id Source ID, or object mapping ids to load urls
1726 * @param {string} loadUrl Url to a load.php end point
1727 * @throws {Error} If source id is already registered
1728 */
1729 addSource: function ( id, loadUrl ) {
1730 var source;
1731 // Allow multiple additions
1732 if ( typeof id === 'object' ) {
1733 for ( source in id ) {
1734 mw.loader.addSource( source, id[ source ] );
1735 }
1736 return;
1737 }
1738
1739 if ( hasOwn.call( sources, id ) ) {
1740 throw new Error( 'source already registered: ' + id );
1741 }
1742
1743 sources[ id ] = loadUrl;
1744 },
1745
1746 /**
1747 * Register a module, letting the system know about it and its properties.
1748 *
1749 * The startup modules contain calls to this method.
1750 *
1751 * When using multiple module registration by passing an array, dependencies that
1752 * are specified as references to modules within the array will be resolved before
1753 * the modules are registered.
1754 *
1755 * @param {string|Array} module Module name or array of arrays, each containing
1756 * a list of arguments compatible with this method
1757 * @param {string|number} version Module version hash (falls backs to empty string)
1758 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1759 * @param {string|Array} dependencies One string or array of strings of module
1760 * names on which this module depends.
1761 * @param {string} [group=null] Group which the module is in
1762 * @param {string} [source='local'] Name of the source
1763 * @param {string} [skip=null] Script body of the skip function
1764 */
1765 register: function ( module, version, dependencies, group, source, skip ) {
1766 var i, deps;
1767 // Allow multiple registration
1768 if ( typeof module === 'object' ) {
1769 resolveIndexedDependencies( module );
1770 for ( i = 0; i < module.length; i++ ) {
1771 // module is an array of module names
1772 if ( typeof module[ i ] === 'string' ) {
1773 mw.loader.register( module[ i ] );
1774 // module is an array of arrays
1775 } else if ( typeof module[ i ] === 'object' ) {
1776 mw.loader.register.apply( mw.loader, module[ i ] );
1777 }
1778 }
1779 return;
1780 }
1781 if ( hasOwn.call( registry, module ) ) {
1782 throw new Error( 'module already registered: ' + module );
1783 }
1784 if ( typeof dependencies === 'string' ) {
1785 // A single module name
1786 deps = [ dependencies ];
1787 } else if ( typeof dependencies === 'object' ) {
1788 // Array of module names
1789 deps = dependencies;
1790 }
1791 // List the module as registered
1792 registry[ module ] = {
1793 // Exposed to execute() for mw.loader.implement() closures.
1794 // Import happens via require().
1795 module: {
1796 exports: {}
1797 },
1798 version: String( version || '' ),
1799 dependencies: deps || [],
1800 group: typeof group === 'string' ? group : null,
1801 source: typeof source === 'string' ? source : 'local',
1802 state: 'registered',
1803 skip: typeof skip === 'string' ? skip : null
1804 };
1805 },
1806
1807 /**
1808 * Implement a module given the components that make up the module.
1809 *
1810 * When #load() or #using() requests one or more modules, the server
1811 * response contain calls to this function.
1812 *
1813 * @param {string} module Name of module and current module version. Formatted
1814 * as '`[name]@[version]`". This version should match the requested version
1815 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1816 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1817 * @param {Function|Array|string} [script] Function with module code, list of URLs
1818 * to load via `<script src>`, or string of module code for `$.globalEval()`.
1819 * @param {Object} [style] Should follow one of the following patterns:
1820 *
1821 * { "css": [css, ..] }
1822 * { "url": { <media>: [url, ..] } }
1823 *
1824 * And for backwards compatibility (needs to be supported forever due to caching):
1825 *
1826 * { <media>: css }
1827 * { <media>: [url, ..] }
1828 *
1829 * The reason css strings are not concatenated anymore is T33676. We now check
1830 * whether it's safe to extend the stylesheet.
1831 *
1832 * @protected
1833 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1834 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1835 */
1836 implement: function ( module, script, style, messages, templates ) {
1837 var split = splitModuleKey( module ),
1838 name = split.name,
1839 version = split.version;
1840 // Automatically register module
1841 if ( !hasOwn.call( registry, name ) ) {
1842 mw.loader.register( name );
1843 }
1844 // Check for duplicate implementation
1845 if ( hasOwn.call( registry, name ) && registry[ name ].script !== undefined ) {
1846 throw new Error( 'module already implemented: ' + name );
1847 }
1848 if ( version ) {
1849 // Without this reset, if there is a version mismatch between the
1850 // requested and received module version, then mw.loader.store would
1851 // cache the response under the requested key. Thus poisoning the cache
1852 // indefinitely with a stale value. (T117587)
1853 registry[ name ].version = version;
1854 }
1855 // Attach components
1856 registry[ name ].script = script || null;
1857 registry[ name ].style = style || null;
1858 registry[ name ].messages = messages || null;
1859 registry[ name ].templates = templates || null;
1860 // The module may already have been marked as erroneous
1861 if ( registry[ name ].state !== 'error' && registry[ name ].state !== 'missing' ) {
1862 registry[ name ].state = 'loaded';
1863 if ( allWithImplicitReady( name ) ) {
1864 execute( name );
1865 }
1866 }
1867 },
1868
1869 /**
1870 * Load an external script or one or more modules.
1871 *
1872 * This method takes a list of unrelated modules. Use cases:
1873 *
1874 * - A web page will be composed of many different widgets. These widgets independently
1875 * queue their ResourceLoader modules (`OutputPage::addModules()`). If any of them
1876 * have problems, or are no longer known (e.g. cached HTML), the other modules
1877 * should still be loaded.
1878 * - This method is used for preloading, which must not throw. Later code that
1879 * calls #using() will handle the error.
1880 *
1881 * @param {string|Array} modules Either the name of a module, array of modules,
1882 * or a URL of an external script or style
1883 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
1884 * external script or style; acceptable values are "text/css" and
1885 * "text/javascript"; if no type is provided, text/javascript is assumed.
1886 */
1887 load: function ( modules, type ) {
1888 var filtered, l;
1889
1890 // Allow calling with a url or single dependency as a string
1891 if ( typeof modules === 'string' ) {
1892 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
1893 if ( /^(https?:)?\/?\//.test( modules ) ) {
1894 if ( type === 'text/css' ) {
1895 l = document.createElement( 'link' );
1896 l.rel = 'stylesheet';
1897 l.href = modules;
1898 document.head.appendChild( l );
1899 return;
1900 }
1901 if ( type === 'text/javascript' || type === undefined ) {
1902 addScript( modules );
1903 return;
1904 }
1905 // Unknown type
1906 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type );
1907 }
1908 // Called with single module
1909 modules = [ modules ];
1910 }
1911
1912 // Filter out top-level modules that are unknown or failed to load before.
1913 filtered = modules.filter( function ( module ) {
1914 var state = mw.loader.getState( module );
1915 return state !== 'error' && state !== 'missing';
1916 } );
1917 // Resolve remaining list using the known dependency tree.
1918 // This also filters out modules with unknown dependencies. (T36853)
1919 filtered = resolveStubbornly( filtered );
1920 // Some modules are not yet ready, add to module load queue.
1921 enqueue( filtered, undefined, undefined );
1922 },
1923
1924 /**
1925 * Change the state of one or more modules.
1926 *
1927 * @param {Object} modules Object of module name/state pairs
1928 */
1929 state: function ( modules ) {
1930 var module, state;
1931 for ( module in modules ) {
1932 state = modules[ module ];
1933 if ( !hasOwn.call( registry, module ) ) {
1934 mw.loader.register( module );
1935 }
1936 registry[ module ].state = state;
1937 if ( state === 'ready' || state === 'error' || state === 'missing' ) {
1938 // Make sure pending modules depending on this one get executed if their
1939 // dependencies are now fulfilled!
1940 handlePending( module );
1941 }
1942 }
1943 },
1944
1945 /**
1946 * Get the version of a module.
1947 *
1948 * @param {string} module Name of module
1949 * @return {string|null} The version, or null if the module (or its version) is not
1950 * in the registry.
1951 */
1952 getVersion: function ( module ) {
1953 return hasOwn.call( registry, module ) ? registry[ module ].version : null;
1954 },
1955
1956 /**
1957 * Get the state of a module.
1958 *
1959 * @param {string} module Name of module
1960 * @return {string|null} The state, or null if the module (or its state) is not
1961 * in the registry.
1962 */
1963 getState: function ( module ) {
1964 return hasOwn.call( registry, module ) ? registry[ module ].state : null;
1965 },
1966
1967 /**
1968 * Get the names of all registered modules.
1969 *
1970 * @return {Array}
1971 */
1972 getModuleNames: function () {
1973 return Object.keys( registry );
1974 },
1975
1976 /**
1977 * Get the exported value of a module.
1978 *
1979 * This static method is publicly exposed for debugging purposes
1980 * only and must not be used in production code. In production code,
1981 * please use the dynamically provided `require()` function instead.
1982 *
1983 * In case of lazy-loaded modules via mw.loader#using(), the returned
1984 * Promise provides the function, see #using() for examples.
1985 *
1986 * @private
1987 * @since 1.27
1988 * @param {string} moduleName Module name
1989 * @return {Mixed} Exported value
1990 */
1991 require: function ( moduleName ) {
1992 var state = mw.loader.getState( moduleName );
1993
1994 // Only ready modules can be required
1995 if ( state !== 'ready' ) {
1996 // Module may've forgotten to declare a dependency
1997 throw new Error( 'Module "' + moduleName + '" is not loaded.' );
1998 }
1999
2000 return registry[ moduleName ].module.exports;
2001 },
2002
2003 /**
2004 * On browsers that implement the localStorage API, the module store serves as a
2005 * smart complement to the browser cache. Unlike the browser cache, the module store
2006 * can slice a concatenated response from ResourceLoader into its constituent
2007 * modules and cache each of them separately, using each module's versioning scheme
2008 * to determine when the cache should be invalidated.
2009 *
2010 * @singleton
2011 * @class mw.loader.store
2012 */
2013 store: {
2014 // Whether the store is in use on this page.
2015 enabled: null,
2016
2017 // Modules whose string representation exceeds 100 kB are
2018 // ineligible for storage. See bug T66721.
2019 MODULE_SIZE_MAX: 100 * 1000,
2020
2021 // The contents of the store, mapping '[name]@[version]' keys
2022 // to module implementations.
2023 items: {},
2024
2025 // Cache hit stats
2026 stats: { hits: 0, misses: 0, expired: 0, failed: 0 },
2027
2028 /**
2029 * Construct a JSON-serializable object representing the content of the store.
2030 *
2031 * @return {Object} Module store contents.
2032 */
2033 toJSON: function () {
2034 return { items: mw.loader.store.items, vary: mw.loader.store.getVary() };
2035 },
2036
2037 /**
2038 * Get the localStorage key for the entire module store. The key references
2039 * $wgDBname to prevent clashes between wikis which share a common host.
2040 *
2041 * @return {string} localStorage item key
2042 */
2043 getStoreKey: function () {
2044 return 'MediaWikiModuleStore:' + mw.config.get( 'wgDBname' );
2045 },
2046
2047 /**
2048 * Get a key on which to vary the module cache.
2049 *
2050 * @return {string} String of concatenated vary conditions.
2051 */
2052 getVary: function () {
2053 return [
2054 mw.config.get( 'skin' ),
2055 mw.config.get( 'wgResourceLoaderStorageVersion' ),
2056 mw.config.get( 'wgUserLanguage' )
2057 ].join( ':' );
2058 },
2059
2060 /**
2061 * Initialize the store.
2062 *
2063 * Retrieves store from localStorage and (if successfully retrieved) decoding
2064 * the stored JSON value to a plain object.
2065 *
2066 * The try / catch block is used for JSON & localStorage feature detection.
2067 * See the in-line documentation for Modernizr's localStorage feature detection
2068 * code for a full account of why we need a try / catch:
2069 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2070 */
2071 init: function () {
2072 var raw, data;
2073
2074 if ( mw.loader.store.enabled !== null ) {
2075 // Init already ran
2076 return;
2077 }
2078
2079 if (
2080 // Disabled because localStorage quotas are tight and (in Firefox's case)
2081 // shared by multiple origins.
2082 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2083 /Firefox|Opera/.test( navigator.userAgent ) ||
2084
2085 // Disabled by configuration.
2086 !mw.config.get( 'wgResourceLoaderStorageEnabled' )
2087 ) {
2088 // Clear any previous store to free up space. (T66721)
2089 mw.loader.store.clear();
2090 mw.loader.store.enabled = false;
2091 return;
2092 }
2093 if ( mw.config.get( 'debug' ) ) {
2094 // Disable module store in debug mode
2095 mw.loader.store.enabled = false;
2096 return;
2097 }
2098
2099 try {
2100 raw = localStorage.getItem( mw.loader.store.getStoreKey() );
2101 // If we get here, localStorage is available; mark enabled
2102 mw.loader.store.enabled = true;
2103 data = JSON.parse( raw );
2104 if ( data && typeof data.items === 'object' && data.vary === mw.loader.store.getVary() ) {
2105 mw.loader.store.items = data.items;
2106 return;
2107 }
2108 } catch ( e ) {
2109 mw.trackError( 'resourceloader.exception', {
2110 exception: e,
2111 source: 'store-localstorage-init'
2112 } );
2113 }
2114
2115 if ( raw === undefined ) {
2116 // localStorage failed; disable store
2117 mw.loader.store.enabled = false;
2118 } else {
2119 mw.loader.store.update();
2120 }
2121 },
2122
2123 /**
2124 * Retrieve a module from the store and update cache hit stats.
2125 *
2126 * @param {string} module Module name
2127 * @return {string|boolean} Module implementation or false if unavailable
2128 */
2129 get: function ( module ) {
2130 var key;
2131
2132 if ( !mw.loader.store.enabled ) {
2133 return false;
2134 }
2135
2136 key = getModuleKey( module );
2137 if ( key in mw.loader.store.items ) {
2138 mw.loader.store.stats.hits++;
2139 return mw.loader.store.items[ key ];
2140 }
2141 mw.loader.store.stats.misses++;
2142 return false;
2143 },
2144
2145 /**
2146 * Stringify a module and queue it for storage.
2147 *
2148 * @param {string} module Module name
2149 * @param {Object} descriptor The module's descriptor as set in the registry
2150 * @return {boolean} Module was set
2151 */
2152 set: function ( module, descriptor ) {
2153 var args, key, src;
2154
2155 if ( !mw.loader.store.enabled ) {
2156 return false;
2157 }
2158
2159 key = getModuleKey( module );
2160
2161 if (
2162 // Already stored a copy of this exact version
2163 key in mw.loader.store.items ||
2164 // Module failed to load
2165 descriptor.state !== 'ready' ||
2166 // Unversioned, private, or site-/user-specific
2167 !descriptor.version ||
2168 descriptor.group === 'private' ||
2169 descriptor.group === 'user' ||
2170 // Partial descriptor
2171 // (e.g. skipped module, or style module with state=ready)
2172 [ descriptor.script, descriptor.style, descriptor.messages,
2173 descriptor.templates ].indexOf( undefined ) !== -1
2174 ) {
2175 // Decline to store
2176 return false;
2177 }
2178
2179 try {
2180 args = [
2181 JSON.stringify( key ),
2182 typeof descriptor.script === 'function' ?
2183 String( descriptor.script ) :
2184 JSON.stringify( descriptor.script ),
2185 JSON.stringify( descriptor.style ),
2186 JSON.stringify( descriptor.messages ),
2187 JSON.stringify( descriptor.templates )
2188 ];
2189 // Attempted workaround for a possible Opera bug (bug T59567).
2190 // This regex should never match under sane conditions.
2191 if ( /^\s*\(/.test( args[ 1 ] ) ) {
2192 args[ 1 ] = 'function' + args[ 1 ];
2193 mw.trackError( 'resourceloader.assert', { source: 'bug-T59567' } );
2194 }
2195 } catch ( e ) {
2196 mw.trackError( 'resourceloader.exception', {
2197 exception: e,
2198 source: 'store-localstorage-json'
2199 } );
2200 return false;
2201 }
2202
2203 src = 'mw.loader.implement(' + args.join( ',' ) + ');';
2204 if ( src.length > mw.loader.store.MODULE_SIZE_MAX ) {
2205 return false;
2206 }
2207 mw.loader.store.items[ key ] = src;
2208 mw.loader.store.update();
2209 return true;
2210 },
2211
2212 /**
2213 * Iterate through the module store, removing any item that does not correspond
2214 * (in name and version) to an item in the module registry.
2215 *
2216 * @return {boolean} Store was pruned
2217 */
2218 prune: function () {
2219 var key, module;
2220
2221 if ( !mw.loader.store.enabled ) {
2222 return false;
2223 }
2224
2225 for ( key in mw.loader.store.items ) {
2226 module = key.slice( 0, key.indexOf( '@' ) );
2227 if ( getModuleKey( module ) !== key ) {
2228 mw.loader.store.stats.expired++;
2229 delete mw.loader.store.items[ key ];
2230 } else if ( mw.loader.store.items[ key ].length > mw.loader.store.MODULE_SIZE_MAX ) {
2231 // This value predates the enforcement of a size limit on cached modules.
2232 delete mw.loader.store.items[ key ];
2233 }
2234 }
2235 return true;
2236 },
2237
2238 /**
2239 * Clear the entire module store right now.
2240 */
2241 clear: function () {
2242 mw.loader.store.items = {};
2243 try {
2244 localStorage.removeItem( mw.loader.store.getStoreKey() );
2245 } catch ( ignored ) {}
2246 },
2247
2248 /**
2249 * Sync in-memory store back to localStorage.
2250 *
2251 * This function debounces updates. When called with a flush already pending,
2252 * the call is coalesced into the pending update. The call to
2253 * localStorage.setItem will be naturally deferred until the page is quiescent.
2254 *
2255 * Because localStorage is shared by all pages from the same origin, if multiple
2256 * pages are loaded with different module sets, the possibility exists that
2257 * modules saved by one page will be clobbered by another. But the impact would
2258 * be minor and the problem would be corrected by subsequent page views.
2259 *
2260 * @method
2261 */
2262 update: ( function () {
2263 var hasPendingWrite = false;
2264
2265 function flushWrites() {
2266 var data, key;
2267 if ( !hasPendingWrite || !mw.loader.store.enabled ) {
2268 return;
2269 }
2270
2271 mw.loader.store.prune();
2272 key = mw.loader.store.getStoreKey();
2273 try {
2274 // Replacing the content of the module store might fail if the new
2275 // contents would exceed the browser's localStorage size limit. To
2276 // avoid clogging the browser with stale data, always remove the old
2277 // value before attempting to set the new one.
2278 localStorage.removeItem( key );
2279 data = JSON.stringify( mw.loader.store );
2280 localStorage.setItem( key, data );
2281 } catch ( e ) {
2282 mw.trackError( 'resourceloader.exception', {
2283 exception: e,
2284 source: 'store-localstorage-update'
2285 } );
2286 }
2287
2288 hasPendingWrite = false;
2289 }
2290
2291 return function () {
2292 if ( !hasPendingWrite ) {
2293 hasPendingWrite = true;
2294 mw.requestIdleCallback( flushWrites );
2295 }
2296 };
2297 }() )
2298 }
2299 };
2300 }() ),
2301
2302 // Skeleton user object, extended by the 'mediawiki.user' module.
2303 /**
2304 * @class mw.user
2305 * @singleton
2306 */
2307 user: {
2308 /**
2309 * @property {mw.Map}
2310 */
2311 options: new Map(),
2312 /**
2313 * @property {mw.Map}
2314 */
2315 tokens: new Map()
2316 },
2317
2318 // OOUI widgets specific to MediaWiki
2319 widgets: {}
2320
2321 };
2322
2323 // Attach to window and globally alias
2324 window.mw = window.mediaWiki = mw;
2325 }() );