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