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