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