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