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