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