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