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