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