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