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