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