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