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