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