2 * Base library for MediaWiki.
4 * Exposed globally as `mediaWiki` with `mw` as shortcut.
7 * @alternateClassName mediaWiki
10 /* global $VARS, $CODE */
15 var mw
, StringSet
, log
,
16 hasOwn
= Object
.prototype.hasOwnProperty
,
20 * FNV132 hash function
22 * This function implements the 32-bit version of FNV-1.
23 * It is equivalent to hash( 'fnv132', ... ) in PHP, except
24 * its output is base 36 rather than hex.
25 * See <https://en.wikipedia.org/wiki/FNV_hash_function>
28 * @param {string} str String to hash
29 * @return {string} hash as an seven-character base 36 string
31 function fnv132( str
) {
32 /* eslint-disable no-bitwise */
33 var hash
= 0x811C9DC5,
36 for ( i
= 0; i
< str
.length
; i
++ ) {
37 hash
+= ( hash
<< 1 ) + ( hash
<< 4 ) + ( hash
<< 7 ) + ( hash
<< 8 ) + ( hash
<< 24 );
38 hash
^= str
.charCodeAt( i
);
41 hash
= ( hash
>>> 0 ).toString( 36 );
42 while ( hash
.length
< 7 ) {
47 /* eslint-enable no-bitwise */
50 function defineFallbacks() {
51 // <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set>
52 StringSet
= window
.Set
|| ( function () {
57 function StringSet() {
58 this.set = Object
.create( null );
60 StringSet
.prototype.add = function ( value
) {
61 this.set[ value
] = true;
63 StringSet
.prototype.has = function ( value
) {
64 return value
in this.set;
71 * Alias property to the global object.
78 * @param {Mixed} value
80 function setGlobalMapValue( map
, key
, value
) {
81 map
.values
[ key
] = value
;
86 // Deprecation notice for mw.config globals (T58550, T72470)
87 map
=== mw
.config
&& 'Use mw.config instead.'
92 * Log a message to window.console, if possible.
94 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
95 * also in production mode). Gets console references in each invocation instead of caching the
96 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
99 * @param {string} topic Stream name passed by mw.track
100 * @param {Object} data Data passed by mw.track
101 * @param {Error} [data.exception]
102 * @param {string} data.source Error source
103 * @param {string} [data.module] Name of module which caused the error
105 function logError( topic
, data
) {
106 /* eslint-disable no-console */
109 source
= data
.source
,
110 module
= data
.module
,
111 console
= window
.console
;
113 if ( console
&& console
.log
) {
114 msg
= ( e
? 'Exception' : 'Error' ) + ' in ' + source
;
116 msg
+= ' in module ' + module
;
118 msg
+= ( e
? ':' : '.' );
121 // If we have an exception object, log it to the warning channel to trigger
122 // proper stacktraces in browsers that support it.
123 if ( e
&& console
.warn
) {
127 /* eslint-enable no-console */
131 * Create an object that can be read from or written to via methods that allow
132 * interaction both with single and multiple properties at once.
138 * @param {boolean} [global=false] Whether to synchronise =values to the global
139 * window object (for backwards-compatibility with mw.config; T72470). Values are
140 * copied in one direction only. Changes to globals do not reflect in the map.
142 function Map( global
) {
143 this.values
= Object
.create( null );
144 if ( global
=== true ) {
145 // Override #set to also set the global variable
146 this.set = function ( selection
, value
) {
148 if ( arguments
.length
> 1 ) {
149 if ( typeof selection
!== 'string' ) {
152 setGlobalMapValue( this, selection
, value
);
155 if ( typeof selection
=== 'object' ) {
156 for ( s
in selection
) {
157 setGlobalMapValue( this, s
, selection
[ s
] );
170 * Get the value of one or more keys.
172 * If called with no arguments, all values are returned.
174 * @param {string|Array} [selection] Key or array of keys to retrieve values for.
175 * @param {Mixed} [fallback=null] Value for keys that don't exist.
176 * @return {Mixed|Object|null} If selection was a string, returns the value,
177 * If selection was an array, returns an object of key/values.
178 * If no selection is passed, a new object with all key/values is returned.
180 get: function ( selection
, fallback
) {
182 fallback
= arguments
.length
> 1 ? fallback
: null;
184 if ( Array
.isArray( selection
) ) {
186 for ( i
= 0; i
< selection
.length
; i
++ ) {
187 if ( typeof selection
[ i
] === 'string' ) {
188 results
[ selection
[ i
] ] = selection
[ i
] in this.values
?
189 this.values
[ selection
[ i
] ] :
196 if ( typeof selection
=== 'string' ) {
197 return selection
in this.values
?
198 this.values
[ selection
] :
202 if ( selection
=== undefined ) {
204 for ( i
in this.values
) {
205 results
[ i
] = this.values
[ i
];
210 // Invalid selection key
215 * Set one or more key/value pairs.
217 * @param {string|Object} selection Key to set value for, or object mapping keys to values
218 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
219 * @return {boolean} True on success, false on failure
221 set: function ( selection
, value
) {
223 // Use `arguments.length` because `undefined` is also a valid value.
224 if ( arguments
.length
> 1 ) {
225 if ( typeof selection
!== 'string' ) {
228 this.values
[ selection
] = value
;
231 if ( typeof selection
=== 'object' ) {
232 for ( s
in selection
) {
233 this.values
[ s
] = selection
[ s
];
241 * Check if one or more keys exist.
243 * @param {Mixed} selection Key or array of keys to check
244 * @return {boolean} True if the key(s) exist
246 exists: function ( selection
) {
248 if ( Array
.isArray( selection
) ) {
249 for ( i
= 0; i
< selection
.length
; i
++ ) {
250 if ( typeof selection
[ i
] !== 'string' || !( selection
[ i
] in this.values
) ) {
256 return typeof selection
=== 'string' && selection
in this.values
;
262 /* eslint-disable no-console */
263 log
= ( function () {
265 * Write a verbose message to the browser's console in debug mode.
267 * This method is mainly intended for verbose logging. It is a no-op in production mode.
268 * In ResourceLoader debug mode, it will use the browser's console if available, with
269 * fallback to creating a console interface in the DOM and logging messages there.
271 * See {@link mw.log} for other logging methods.
274 * @param {...string} msg Messages to output to console.
276 var log = function () {},
277 console
= window
.console
;
279 // Note: Keep list of methods in sync with restoration in mediawiki.log.js
280 // when adding or removing mw.log methods below!
283 * Collection of methods to help log messages to the console.
290 * Write a message to the browser console's warning channel.
292 * This method is a no-op in browsers that don't implement the Console API.
294 * @param {...string} msg Messages to output to console
296 log
.warn
= console
&& console
.warn
&& Function
.prototype.bind
?
297 Function
.prototype.bind
.call( console
.warn
, console
) :
301 * Write a message to the browser console's error channel.
303 * Most browsers also print a stacktrace when calling this method if the
304 * argument is an Error object.
306 * This method is a no-op in browsers that don't implement the Console API.
309 * @param {...Mixed} msg Messages to output to console
311 log
.error
= console
&& console
.error
&& Function
.prototype.bind
?
312 Function
.prototype.bind
.call( console
.error
, console
) :
316 * Create a property on a host object that, when accessed, will produce
317 * a deprecation warning in the console.
319 * @param {Object} obj Host object of deprecated property
320 * @param {string} key Name of property to create in `obj`
321 * @param {Mixed} val The value this property should return when accessed
322 * @param {string} [msg] Optional text to include in the deprecation message
323 * @param {string} [logName=key] Optional custom name for the feature.
324 * This is used instead of `key` in the message and `mw.deprecate` tracking.
326 log
.deprecate
= !Object
.defineProperty
? function ( obj
, key
, val
) {
328 } : function ( obj
, key
, val
, msg
, logName
) {
329 var logged
= new StringSet();
330 logName
= logName
|| key
;
331 msg
= 'Use of "' + logName
+ '" is deprecated.' + ( msg
? ( ' ' + msg
) : '' );
332 function uniqueTrace() {
333 var trace
= new Error().stack
;
334 if ( logged
.has( trace
) ) {
340 // Support: Safari 5.0
341 // Throws "not supported on DOM Objects" for Node or Element objects (incl. document)
342 // Safari 4.0 doesn't have this method, and it was fixed in Safari 5.1.
344 Object
.defineProperty( obj
, key
, {
348 if ( uniqueTrace() ) {
349 mw
.track( 'mw.deprecate', logName
);
354 set: function ( newVal
) {
355 if ( uniqueTrace() ) {
356 mw
.track( 'mw.deprecate', logName
);
369 /* eslint-enable no-console */
375 redefineFallbacksForTest: function () {
376 if ( !window
.QUnit
) {
377 throw new Error( 'Reset not allowed outside unit tests' );
383 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
385 * On browsers that implement the Navigation Timing API, this function will produce floating-point
386 * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
387 * it will fall back to using `Date`.
389 * @return {number} Current time
392 var perf
= window
.performance
,
393 navStart
= perf
&& perf
.timing
&& perf
.timing
.navigationStart
;
394 return navStart
&& typeof perf
.now
=== 'function' ?
395 function () { return navStart
+ perf
.now(); } :
396 function () { return Date
.now(); };
400 * List of all analytic events emitted so far.
405 trackQueue
: trackQueue
,
407 track: function ( topic
, data
) {
408 trackQueue
.push( { topic
: topic
, timeStamp
: mw
.now(), data
: data
} );
409 // The base module extends this method to fire events here
413 * Track an early error event via mw.track and send it to the window console.
416 * @param {string} topic Topic name
417 * @param {Object} data Data describing the event, encoded as an object; see mw#logError
419 trackError: function ( topic
, data
) {
420 mw
.track( topic
, data
);
421 logError( topic
, data
);
424 // Expose Map constructor
428 * Map of configuration values.
430 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
433 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
434 * global `window` object.
436 * @property {mw.Map} config
438 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
442 * Empty object for third-party libraries, for cases where you don't
443 * want to add a new global, or the global is bad and needs containment
451 * Access container for deprecated functionality that can be moved from
452 * from their legacy location and attached to this object (e.g. a global
453 * function that is deprecated and as stop-gap can be exposed through here).
455 * This was reserved for future use but never ended up being used.
457 * @deprecated since 1.22 Let deprecated identifiers keep their original name
458 * and use mw.log#deprecate to create an access container for tracking.
464 * Store for messages.
471 * Store for templates associated with a module.
475 templates
: new Map(),
481 * Client for ResourceLoader server end point.
483 * This client is in charge of maintaining the module registry and state
484 * machine, initiating network (batch) requests for loading modules, as
485 * well as dependency resolution and execution of source code.
487 * For more information, refer to
488 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
493 loader
: ( function () {
496 * Fired via mw.track on various resource loading errors.
498 * @event resourceloader_exception
499 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
500 * object, but in theory module code could manually throw something else, and that
501 * might also end up here.
502 * @param {string} [module] Name of the module which caused the error. Omitted if the
503 * error is not module-related or the module cannot be easily identified due to
505 * @param {string} source Source of the error. Possible values:
507 * - style: stylesheet error (only affects old IE where a special style loading method
509 * - load-callback: exception thrown by user callback
510 * - module-execute: exception thrown by module code
511 * - resolve: failed to sort dependencies for a module in mw.loader.load
512 * - store-eval: could not evaluate module code cached in localStorage
513 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
514 * - store-localstorage-json: JSON conversion error in mw.loader.store.set
515 * - store-localstorage-update: localStorage or JSON conversion error in mw.loader.store.update
519 * Fired via mw.track on resource loading error conditions.
521 * @event resourceloader_assert
522 * @param {string} source Source of the error. Possible values:
524 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
525 * bug; see <https://phabricator.wikimedia.org/T59567> for details
529 * Mapping of registered modules.
531 * See #implement and #execute for exact details on support for script, style and messages.
537 * // From mw.loader.register()
538 * 'version': '########' (hash)
539 * 'dependencies': ['required.foo', 'bar.also', ...]
540 * 'group': 'somegroup', (or) null
541 * 'source': 'local', (or) 'anotherwiki'
542 * 'skip': 'return !!window.Example', (or) null
543 * 'module': export Object
545 * // Set from execute() or mw.loader.state()
546 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
548 * // Optionally added at run-time by mw.loader.implement()
550 * 'script': closure, array of urls, or string
551 * 'style': { ... } (see #execute)
552 * 'messages': { 'key': 'value', ... }
559 * The module is known to the system but not yet required.
560 * Meta data is registered via mw.loader#register. Calls to that method are
561 * generated server-side by the startup module.
563 * The module was required through mw.loader (either directly or as dependency of
564 * another module). The client will fetch module contents from the server.
565 * The contents are then stashed in the registry via mw.loader#implement.
567 * The module has been loaded from the server and stashed via mw.loader#implement.
568 * If the module has no more dependencies in-flight, the module will be executed
569 * immediately. Otherwise execution is deferred, controlled via #handlePending.
571 * The module is being executed.
573 * The module has been successfully executed.
575 * The module (or one of its dependencies) produced an error during execution.
577 * The module was registered client-side and requested, but the server denied knowledge
578 * of the module's existence.
584 // Mapping of sources, keyed by source-id, values are strings.
589 // 'sourceId': 'http://example.org/w/load.php'
594 // For queueModuleScript()
595 handlingPendingRequests
= false,
596 pendingRequests
= [],
598 // List of modules to be loaded
602 * List of callback jobs waiting for modules to be ready.
604 * Jobs are created by #enqueue() and run by #handlePending().
606 * Typically when a job is created for a module, the job's dependencies contain
607 * both the required module and all its recursive dependencies.
612 * 'dependencies': [ module names ],
613 * 'ready': Function callback
614 * 'error': Function callback
617 * @property {Object[]} jobs
624 * @property {Array} baseModules
626 baseModules
= $VARS
.baseModules
,
629 * For #addEmbeddedCSS() and #addLink()
632 * @property {HTMLElement|null} marker
634 marker
= document
.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' ),
636 // For #addEmbeddedCSS()
638 rAF
= window
.requestAnimationFrame
|| setTimeout
;
641 * Create a new style element and add it to the DOM.
644 * @param {string} text CSS text
645 * @param {Node|null} [nextNode] The element where the style tag
646 * should be inserted before
647 * @return {HTMLElement} Reference to the created style element
649 function newStyleTag( text
, nextNode
) {
650 var el
= document
.createElement( 'style' );
651 el
.appendChild( document
.createTextNode( text
) );
652 if ( nextNode
&& nextNode
.parentNode
) {
653 nextNode
.parentNode
.insertBefore( el
, nextNode
);
655 document
.head
.appendChild( el
);
662 * @param {Object} cssBuffer
664 function flushCssBuffer( cssBuffer
) {
666 // Mark this object as inactive now so that further calls to addEmbeddedCSS() from
667 // the callbacks go to a new buffer instead of this one (T105973)
668 cssBuffer
.active
= false;
669 newStyleTag( cssBuffer
.cssText
, marker
);
670 for ( i
= 0; i
< cssBuffer
.callbacks
.length
; i
++ ) {
671 cssBuffer
.callbacks
[ i
]();
676 * Add a bit of CSS text to the current browser page.
678 * The creation and insertion of the `<style>` element is debounced for two reasons:
680 * - Performing the insertion before the next paint round via requestAnimationFrame
681 * avoids forced or wasted style recomputations, which are expensive in browsers.
682 * - Reduce how often new stylesheets are inserted by letting additional calls to this
683 * function accumulate into a buffer for at least one JavaScript tick. Modules are
684 * received from the server in batches, which means there is likely going to be many
685 * calls to this function in a row within the same tick / the same call stack.
689 * @param {string} cssText CSS text to be added in a `<style>` tag.
690 * @param {Function} callback Called after the insertion has occurred
692 function addEmbeddedCSS( cssText
, callback
) {
693 // Create a buffer if:
694 // - We don't have one yet.
695 // - The previous one is closed.
696 // - The next CSS chunk syntactically needs to be at the start of a stylesheet (T37562).
697 if ( !nextCssBuffer
|| nextCssBuffer
.active
=== false || cssText
.slice( 0, '@import'.length
) === '@import' ) {
705 // Linebreak for somewhat distinguishable sections
706 nextCssBuffer
.cssText
+= '\n' + cssText
;
707 nextCssBuffer
.callbacks
.push( callback
);
709 if ( nextCssBuffer
.active
=== null ) {
710 nextCssBuffer
.active
= true;
711 // The flushCssBuffer callback has its parameter bound by reference, which means
712 // 1) We can still extend the buffer from our object reference after this point.
713 // 2) We can safely re-assign the variable (not the object) to start a new buffer.
714 rAF( flushCssBuffer
.bind( null, nextCssBuffer
) );
720 * @param {Array} modules List of module names
721 * @return {string} Hash of concatenated version hashes.
723 function getCombinedVersion( modules
) {
724 var hashes
= modules
.reduce( function ( result
, module
) {
725 return result
+ registry
[ module
].version
;
727 return fnv132( hashes
);
731 * Determine whether all dependencies are in state 'ready', which means we may
732 * execute the module or job now.
735 * @param {Array} modules Names of modules to be checked
736 * @return {boolean} True if all modules are in state 'ready', false otherwise
738 function allReady( modules
) {
740 for ( i
= 0; i
< modules
.length
; i
++ ) {
741 if ( mw
.loader
.getState( modules
[ i
] ) !== 'ready' ) {
749 * Determine whether all direct and base dependencies are in state 'ready'
752 * @param {string} module Name of the module to be checked
753 * @return {boolean} True if all direct/base dependencies are in state 'ready'; false otherwise
755 function allWithImplicitReady( module
) {
756 return allReady( registry
[ module
].dependencies
) &&
757 ( baseModules
.indexOf( module
) !== -1 || allReady( baseModules
) );
761 * Determine whether all dependencies are in state 'ready', which means we may
762 * execute the module or job now.
765 * @param {Array} modules Names of modules to be checked
766 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
768 function anyFailed( modules
) {
770 for ( i
= 0; i
< modules
.length
; i
++ ) {
771 state
= mw
.loader
.getState( modules
[ i
] );
772 if ( state
=== 'error' || state
=== 'missing' ) {
780 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
781 * pending jobs and modules that depend upon this module. If the given module failed,
782 * propagate the 'error' state up the dependency tree. Otherwise, go ahead and execute
783 * all jobs/modules now having their dependencies satisfied.
785 * Jobs that depend on a failed module, will have their error callback ran (if any).
788 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
790 function handlePending( module
) {
791 var j
, job
, hasErrors
, m
, stateChange
, fromBaseModule
;
793 if ( registry
[ module
].state
=== 'error' || registry
[ module
].state
=== 'missing' ) {
794 fromBaseModule
= baseModules
.indexOf( module
) !== -1;
795 // If the current module failed, mark all dependent modules also as failed.
796 // Iterate until steady-state to propagate the error state upwards in the
800 for ( m
in registry
) {
801 if ( registry
[ m
].state
!== 'error' && registry
[ m
].state
!== 'missing' ) {
802 // Always propagate errors from base modules to regular modules (implicit dependency).
803 // Between base modules or regular modules, consider direct dependencies only.
805 ( fromBaseModule
&& baseModules
.indexOf( m
) === -1 ) ||
806 anyFailed( registry
[ m
].dependencies
)
808 registry
[ m
].state
= 'error';
813 } while ( stateChange
);
816 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
817 for ( j
= 0; j
< jobs
.length
; j
++ ) {
818 hasErrors
= anyFailed( jobs
[ j
].dependencies
);
819 if ( hasErrors
|| allReady( jobs
[ j
].dependencies
) ) {
820 // All dependencies satisfied, or some have errors
826 if ( typeof job
.error
=== 'function' ) {
827 job
.error( new Error( 'Module ' + module
+ ' has failed dependencies' ), [ module
] );
830 if ( typeof job
.ready
=== 'function' ) {
835 // A user-defined callback raised an exception.
836 // Swallow it to protect our state machine!
837 mw
.trackError( 'resourceloader.exception', {
840 source
: 'load-callback'
846 // The current module became 'ready'.
847 if ( registry
[ module
].state
=== 'ready' ) {
848 // Save it to the module store.
849 mw
.loader
.store
.set( module
, registry
[ module
] );
850 // Recursively execute all dependent modules that were already loaded
851 // (waiting for execution) and no longer have unsatisfied dependencies.
852 for ( m
in registry
) {
853 // Base modules may have dependencies amongst eachother to ensure correct
854 // execution order. Regular modules wait for all base modules.
855 if ( registry
[ m
].state
=== 'loaded' && allWithImplicitReady( m
) ) {
856 // eslint-disable-next-line no-use-before-define
864 * Resolve dependencies and detect circular references.
867 * @param {string} module Name of the top-level module whose dependencies shall be
868 * resolved and sorted.
869 * @param {Array} resolved Returns a topological sort of the given module and its
870 * dependencies, such that later modules depend on earlier modules. The array
871 * contains the module names. If the array contains already some module names,
872 * this function appends its result to the pre-existing array.
873 * @param {StringSet} [unresolved] Used to track the current dependency
874 * chain, and to report loops in the dependency graph.
875 * @throws {Error} If any unregistered module or a dependency loop is encountered
877 function sortDependencies( module
, resolved
, unresolved
) {
880 if ( !hasOwn
.call( registry
, module
) ) {
881 throw new Error( 'Unknown dependency: ' + module
);
884 if ( registry
[ module
].skip
!== null ) {
885 // eslint-disable-next-line no-new-func
886 skip
= new Function( registry
[ module
].skip
);
887 registry
[ module
].skip
= null;
889 registry
[ module
].skipped
= true;
890 registry
[ module
].dependencies
= [];
891 registry
[ module
].state
= 'ready';
892 handlePending( module
);
897 if ( resolved
.indexOf( module
) !== -1 ) {
898 // Module already resolved; nothing to do
901 // Create unresolved if not passed in
903 unresolved
= new StringSet();
907 if ( baseModules
.indexOf( module
) === -1 ) {
908 baseModules
.forEach( function ( baseModule
) {
909 if ( resolved
.indexOf( baseModule
) === -1 ) {
910 resolved
.push( baseModule
);
915 // Tracks down dependencies
916 deps
= registry
[ module
].dependencies
;
917 unresolved
.add( module
);
918 for ( i
= 0; i
< deps
.length
; i
++ ) {
919 if ( resolved
.indexOf( deps
[ i
] ) === -1 ) {
920 if ( unresolved
.has( deps
[ i
] ) ) {
922 'Circular reference detected: ' + module
+ ' -> ' + deps
[ i
]
926 sortDependencies( deps
[ i
], resolved
, unresolved
);
929 resolved
.push( module
);
933 * Get names of module that a module depends on, in their proper dependency order.
936 * @param {string[]} modules Array of string module names
937 * @return {Array} List of dependencies, including 'module'.
938 * @throws {Error} If an unregistered module or a dependency loop is encountered
940 function resolve( modules
) {
941 var i
, resolved
= [];
942 for ( i
= 0; i
< modules
.length
; i
++ ) {
943 sortDependencies( modules
[ i
], resolved
);
949 * Like #resolve(), except it will silently ignore modules that
950 * are missing or have missing dependencies.
953 * @param {string[]} modules Array of string module names
954 * @return {Array} List of dependencies.
956 function resolveStubbornly( modules
) {
957 var i
, saved
, resolved
= [];
958 for ( i
= 0; i
< modules
.length
; i
++ ) {
959 saved
= resolved
.slice();
961 sortDependencies( modules
[ i
], resolved
);
963 // This module is unknown or has unknown dependencies.
964 // Undo any incomplete resolutions made and keep going.
966 mw
.trackError( 'resourceloader.exception', {
976 * Load and execute a script.
979 * @param {string} src URL to script, will be used as the src attribute in the script tag
980 * @param {Function} [callback] Callback to run after request resolution
982 function addScript( src
, callback
) {
983 var script
= document
.createElement( 'script' );
985 script
.onload
= script
.onerror = function () {
986 if ( script
.parentNode
) {
987 script
.parentNode
.removeChild( script
);
995 document
.head
.appendChild( script
);
999 * Queue the loading and execution of a script for a particular module.
1001 * This does for debug mode what runScript() does for production.
1004 * @param {string} src URL of the script
1005 * @param {string} moduleName Name of currently executing module
1006 * @param {Function} callback Callback to run after addScript() resolution
1008 function queueModuleScript( src
, moduleName
, callback
) {
1009 pendingRequests
.push( function () {
1010 // Keep in sync with execute()/runScript().
1011 if ( moduleName
!== 'jquery' && hasOwn
.call( registry
, moduleName
) ) {
1012 window
.require
= mw
.loader
.require
;
1013 window
.module
= registry
[ moduleName
].module
;
1015 addScript( src
, function () {
1016 // 'module.exports' should not persist after the file is executed to
1017 // avoid leakage to unrelated code. 'require' should be kept, however,
1018 // as asynchronous access to 'require' is allowed and expected. (T144879)
1019 delete window
.module
;
1021 // Start the next one (if any)
1022 if ( pendingRequests
[ 0 ] ) {
1023 pendingRequests
.shift()();
1025 handlingPendingRequests
= false;
1029 if ( !handlingPendingRequests
&& pendingRequests
[ 0 ] ) {
1030 handlingPendingRequests
= true;
1031 pendingRequests
.shift()();
1036 * Utility function for execute()
1039 * @param {string} [media] Media attribute
1040 * @param {string} url URL
1042 function addLink( media
, url
) {
1043 var el
= document
.createElement( 'link' );
1045 el
.rel
= 'stylesheet';
1046 if ( media
&& media
!== 'all' ) {
1049 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1050 // see #addEmbeddedCSS, T33676, T43331, and T49277 for details.
1053 if ( marker
&& marker
.parentNode
) {
1054 marker
.parentNode
.insertBefore( el
, marker
);
1056 document
.head
.appendChild( el
);
1062 * @param {string} code JavaScript code
1064 function domEval( code
) {
1065 var script
= document
.createElement( 'script' );
1066 if ( mw
.config
.get( 'wgCSPNonce' ) !== false ) {
1067 script
.nonce
= mw
.config
.get( 'wgCSPNonce' );
1070 document
.head
.appendChild( script
);
1071 script
.parentNode
.removeChild( script
);
1075 * Add one or more modules to the module load queue.
1080 * @param {string[]} dependencies Array of module names in the registry
1081 * @param {Function} [ready] Callback to execute when all dependencies are ready
1082 * @param {Function} [error] Callback to execute when any dependency fails
1084 function enqueue( dependencies
, ready
, error
) {
1085 if ( allReady( dependencies
) ) {
1086 // Run ready immediately
1087 if ( ready
!== undefined ) {
1093 if ( anyFailed( dependencies
) ) {
1094 if ( error
!== undefined ) {
1095 // Execute error immediately if any dependencies have errors
1097 new Error( 'One or more dependencies failed to load' ),
1104 // Not all dependencies are ready, add to the load queue...
1106 // Add ready and error callbacks if they were given
1107 if ( ready
!== undefined || error
!== undefined ) {
1109 // Narrow down the list to modules that are worth waiting for
1110 dependencies
: dependencies
.filter( function ( module
) {
1111 var state
= registry
[ module
].state
;
1112 return state
=== 'registered' || state
=== 'loaded' || state
=== 'loading' || state
=== 'executing';
1119 dependencies
.forEach( function ( module
) {
1120 // Only queue modules that are still in the initial 'registered' state
1121 // (not ones already loading, ready or error).
1122 if ( registry
[ module
].state
=== 'registered' && queue
.indexOf( module
) === -1 ) {
1123 // Private modules must be embedded in the page. Don't bother queuing
1124 // these as the server will deny them anyway (T101806).
1125 if ( registry
[ module
].group
=== 'private' ) {
1126 registry
[ module
].state
= 'error';
1127 handlePending( module
);
1130 queue
.push( module
);
1138 * Executes a loaded module, making it ready to use
1141 * @param {string} module Module name to execute
1143 function execute( module
) {
1144 var key
, value
, media
, i
, urls
, cssHandle
, siteDeps
, siteDepErr
, runScript
,
1147 if ( !hasOwn
.call( registry
, module
) ) {
1148 throw new Error( 'Module has not been registered yet: ' + module
);
1150 if ( registry
[ module
].state
!== 'loaded' ) {
1151 throw new Error( 'Module in state "' + registry
[ module
].state
+ '" may not be executed: ' + module
);
1154 registry
[ module
].state
= 'executing';
1155 $CODE
.profileExecuteStart();
1157 runScript = function () {
1158 var script
, markModuleReady
, nestedAddScript
;
1160 $CODE
.profileScriptStart();
1161 script
= registry
[ module
].script
;
1162 markModuleReady = function () {
1163 $CODE
.profileScriptEnd();
1164 registry
[ module
].state
= 'ready';
1165 handlePending( module
);
1167 nestedAddScript = function ( arr
, callback
, i
) {
1168 // Recursively call queueModuleScript() in its own callback
1169 // for each element of arr.
1170 if ( i
>= arr
.length
) {
1171 // We're at the end of the array
1176 queueModuleScript( arr
[ i
], module
, function () {
1177 nestedAddScript( arr
, callback
, i
+ 1 );
1182 if ( Array
.isArray( script
) ) {
1183 nestedAddScript( script
, markModuleReady
, 0 );
1184 } else if ( typeof script
=== 'function' ) {
1185 // Keep in sync with queueModuleScript() for debug mode
1186 if ( module
=== 'jquery' ) {
1187 // This is a special case for when 'jquery' itself is being loaded.
1188 // - The standard jquery.js distribution does not set `window.jQuery`
1189 // in CommonJS-compatible environments (Node.js, AMD, RequireJS, etc.).
1190 // - MediaWiki's 'jquery' module also bundles jquery.migrate.js, which
1191 // in a CommonJS-compatible environment, will use require('jquery'),
1192 // but that can't work when we're still inside that module.
1195 // Pass jQuery twice so that the signature of the closure which wraps
1196 // the script can bind both '$' and 'jQuery'.
1197 script( window
.$, window
.$, mw
.loader
.require
, registry
[ module
].module
);
1201 } else if ( typeof script
=== 'string' ) {
1202 // Site and user modules are legacy scripts that run in the global scope.
1203 // This is transported as a string instead of a function to avoid needing
1204 // to use string manipulation to undo the function wrapper.
1209 // Module without script
1213 // Use mw.track instead of mw.log because these errors are common in production mode
1214 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1215 registry
[ module
].state
= 'error';
1216 $CODE
.profileScriptEnd();
1217 mw
.trackError( 'resourceloader.exception', {
1218 exception
: e
, module
:
1219 module
, source
: 'module-execute'
1221 handlePending( module
);
1225 // Add localizations to message system
1226 if ( registry
[ module
].messages
) {
1227 mw
.messages
.set( registry
[ module
].messages
);
1230 // Initialise templates
1231 if ( registry
[ module
].templates
) {
1232 mw
.templates
.set( module
, registry
[ module
].templates
);
1235 // Adding of stylesheets is asynchronous via addEmbeddedCSS().
1236 // The below function uses a counting semaphore to make sure we don't call
1237 // runScript() until after this module's stylesheets have been inserted
1239 cssHandle = function () {
1240 // Increase semaphore, when creating a callback for addEmbeddedCSS.
1242 return function () {
1244 // Decrease semaphore, when said callback is invoked.
1246 if ( cssPending
=== 0 ) {
1248 // This callback is exposed to addEmbeddedCSS, which is outside the execute()
1249 // function and is not concerned with state-machine integrity. In turn,
1250 // addEmbeddedCSS() actually exposes stuff further into the browser (rAF).
1251 // If increment and decrement callbacks happen in the wrong order, or start
1252 // again afterwards, then this branch could be reached multiple times.
1253 // To protect the integrity of the state-machine, prevent that from happening
1254 // by making runScript() cannot be called more than once. We store a private
1255 // reference when we first reach this branch, then deference the original, and
1256 // call our reference to it.
1257 runScriptCopy
= runScript
;
1258 runScript
= undefined;
1264 // Process styles (see also mw.loader.implement)
1265 // * back-compat: { <media>: css }
1266 // * back-compat: { <media>: [url, ..] }
1267 // * { "css": [css, ..] }
1268 // * { "url": { <media>: [url, ..] } }
1269 if ( registry
[ module
].style
) {
1270 for ( key
in registry
[ module
].style
) {
1271 value
= registry
[ module
].style
[ key
];
1274 if ( key
!== 'url' && key
!== 'css' ) {
1275 // Backwards compatibility, key is a media-type
1276 if ( typeof value
=== 'string' ) {
1277 // back-compat: { <media>: css }
1278 // Ignore 'media' because it isn't supported (nor was it used).
1279 // Strings are pre-wrapped in "@media". The media-type was just ""
1280 // (because it had to be set to something).
1281 // This is one of the reasons why this format is no longer used.
1282 addEmbeddedCSS( value
, cssHandle() );
1284 // back-compat: { <media>: [url, ..] }
1290 // Array of css strings in key 'css',
1291 // or back-compat array of urls from media-type
1292 if ( Array
.isArray( value
) ) {
1293 for ( i
= 0; i
< value
.length
; i
++ ) {
1294 if ( key
=== 'bc-url' ) {
1295 // back-compat: { <media>: [url, ..] }
1296 addLink( media
, value
[ i
] );
1297 } else if ( key
=== 'css' ) {
1298 // { "css": [css, ..] }
1299 addEmbeddedCSS( value
[ i
], cssHandle() );
1302 // Not an array, but a regular object
1303 // Array of urls inside media-type key
1304 } else if ( typeof value
=== 'object' ) {
1305 // { "url": { <media>: [url, ..] } }
1306 for ( media
in value
) {
1307 urls
= value
[ media
];
1308 for ( i
= 0; i
< urls
.length
; i
++ ) {
1309 addLink( media
, urls
[ i
] );
1316 // End profiling of execute()-self before we call runScript(),
1317 // which we want to measure separately without overlap.
1318 $CODE
.profileExecuteEnd();
1320 if ( module
=== 'user' ) {
1321 // Implicit dependency on the site module. Not a real dependency because it should
1322 // run after 'site' regardless of whether it succeeds or fails.
1323 // Note: This is a simplified version of mw.loader.using(), inlined here because
1324 // mw.loader.using() is part of mediawiki.base (depends on jQuery; T192623).
1326 siteDeps
= resolve( [ 'site' ] );
1331 if ( siteDepErr
=== undefined ) {
1332 enqueue( siteDeps
, runScript
, runScript
);
1334 } else if ( cssPending
=== 0 ) {
1335 // Regular module without styles
1338 // else: runScript will get called via cssHandle()
1341 function sortQuery( o
) {
1350 for ( key
= 0; key
< a
.length
; key
++ ) {
1351 sorted
[ a
[ key
] ] = o
[ a
[ key
] ];
1357 * Converts a module map of the form `{ foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }`
1358 * to a query string of the form `foo.bar,baz|bar.baz,quux`.
1360 * See `ResourceLoader::makePackedModulesString()` in PHP, of which this is a port.
1361 * On the server, unpacking is done by `ResourceLoaderContext::expandModuleNames()`.
1363 * Note: This is only half of the logic, the other half has to be in #batchRequest(),
1364 * because its implementation needs to keep track of potential string size in order
1365 * to decide when to split the requests due to url size.
1368 * @param {Object} moduleMap Module map
1370 * @return {string} return.str Module query string
1371 * @return {Array} return.list List of module names in matching order
1373 function buildModulesString( moduleMap
) {
1378 function restore( suffix
) {
1382 for ( prefix
in moduleMap
) {
1383 p
= prefix
=== '' ? '' : prefix
+ '.';
1384 str
.push( p
+ moduleMap
[ prefix
].join( ',' ) );
1385 list
.push
.apply( list
, moduleMap
[ prefix
].map( restore
) );
1388 str
: str
.join( '|' ),
1394 * Resolve indexed dependencies.
1396 * ResourceLoader uses an optimization to save space which replaces module names in
1397 * dependency lists with the index of that module within the array of module
1398 * registration data if it exists. The benefit is a significant reduction in the data
1399 * size of the startup module. This function changes those dependency lists back to
1400 * arrays of strings.
1403 * @param {Array} modules Modules array
1405 function resolveIndexedDependencies( modules
) {
1407 function resolveIndex( dep
) {
1408 return typeof dep
=== 'number' ? modules
[ dep
][ 0 ] : dep
;
1410 for ( i
= 0; i
< modules
.length
; i
++ ) {
1411 deps
= modules
[ i
][ 2 ];
1413 for ( j
= 0; j
< deps
.length
; j
++ ) {
1414 deps
[ j
] = resolveIndex( deps
[ j
] );
1422 * @param {Object} params Map of parameter names to values
1425 function makeQueryString( params
) {
1426 return Object
.keys( params
).map( function ( key
) {
1427 return encodeURIComponent( key
) + '=' + encodeURIComponent( params
[ key
] );
1432 * Create network requests for a batch of modules.
1434 * This is an internal method for #work(). This must not be called directly
1435 * unless the modules are already registered, and no request is in progress,
1436 * and the module state has already been set to `loading`.
1439 * @param {string[]} batch
1441 function batchRequest( batch
) {
1442 var reqBase
, splits
, maxQueryLength
, b
, bSource
, bGroup
,
1443 source
, group
, i
, modules
, sourceLoadScript
,
1444 currReqBase
, currReqBaseLength
, moduleMap
, currReqModules
, l
,
1445 lastDotIndex
, prefix
, suffix
, bytesAdded
;
1448 * Start the currently drafted request to the server.
1452 function doRequest() {
1453 // Optimisation: Inherit (Object.create), not copy ($.extend)
1454 var query
= Object
.create( currReqBase
),
1455 packed
= buildModulesString( moduleMap
);
1456 query
.modules
= packed
.str
;
1457 // The packing logic can change the effective order, even if the input was
1458 // sorted. As such, the call to getCombinedVersion() must use this
1459 // effective order, instead of currReqModules, as otherwise the combined
1460 // version will not match the hash expected by the server based on
1461 // combining versions from the module query string in-order. (T188076)
1462 query
.version
= getCombinedVersion( packed
.list
);
1463 query
= sortQuery( query
);
1464 addScript( sourceLoadScript
+ '?' + makeQueryString( query
) );
1467 if ( !batch
.length
) {
1471 // Always order modules alphabetically to help reduce cache
1472 // misses for otherwise identical content.
1475 // Query parameters common to all requests
1477 skin
: mw
.config
.get( 'skin' ),
1478 lang
: mw
.config
.get( 'wgUserLanguage' ),
1479 debug
: mw
.config
.get( 'debug' )
1481 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1483 // Split module list by source and by group.
1484 splits
= Object
.create( null );
1485 for ( b
= 0; b
< batch
.length
; b
++ ) {
1486 bSource
= registry
[ batch
[ b
] ].source
;
1487 bGroup
= registry
[ batch
[ b
] ].group
;
1488 if ( !splits
[ bSource
] ) {
1489 splits
[ bSource
] = Object
.create( null );
1491 if ( !splits
[ bSource
][ bGroup
] ) {
1492 splits
[ bSource
][ bGroup
] = [];
1494 splits
[ bSource
][ bGroup
].push( batch
[ b
] );
1497 for ( source
in splits
) {
1498 sourceLoadScript
= sources
[ source
];
1500 for ( group
in splits
[ source
] ) {
1502 // Cache access to currently selected list of
1503 // modules for this group from this source.
1504 modules
= splits
[ source
][ group
];
1506 // Query parameters common to requests for this module group
1507 // Optimisation: Inherit (Object.create), not copy ($.extend)
1508 currReqBase
= Object
.create( reqBase
);
1509 // User modules require a user name in the query string.
1510 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1511 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1514 // In addition to currReqBase, doRequest() will also add 'modules' and 'version'.
1515 // > '&modules='.length === 9
1516 // > '&version=1234567'.length === 16
1518 currReqBaseLength
= makeQueryString( currReqBase
).length
+ 25;
1520 // We may need to split up the request to honor the query string length limit,
1521 // so build it piece by piece.
1522 l
= currReqBaseLength
;
1523 moduleMap
= Object
.create( null ); // { prefix: [ suffixes ] }
1524 currReqModules
= [];
1526 for ( i
= 0; i
< modules
.length
; i
++ ) {
1527 // Determine how many bytes this module would add to the query string
1528 lastDotIndex
= modules
[ i
].lastIndexOf( '.' );
1529 // If lastDotIndex is -1, substr() returns an empty string
1530 prefix
= modules
[ i
].substr( 0, lastDotIndex
);
1531 suffix
= modules
[ i
].slice( lastDotIndex
+ 1 );
1532 bytesAdded
= moduleMap
[ prefix
] ?
1533 suffix
.length
+ 3 : // '%2C'.length == 3
1534 modules
[ i
].length
+ 3; // '%7C'.length == 3
1536 // If the url would become too long, create a new one, but don't create empty requests
1537 if ( maxQueryLength
> 0 && currReqModules
.length
&& l
+ bytesAdded
> maxQueryLength
) {
1538 // Dispatch what we've got...
1540 // .. and start again.
1541 l
= currReqBaseLength
;
1542 moduleMap
= Object
.create( null );
1543 currReqModules
= [];
1545 mw
.track( 'resourceloader.splitRequest', { maxQueryLength
: maxQueryLength
} );
1547 if ( !moduleMap
[ prefix
] ) {
1548 moduleMap
[ prefix
] = [];
1551 moduleMap
[ prefix
].push( suffix
);
1552 currReqModules
.push( modules
[ i
] );
1554 // If there's anything left in moduleMap, request that too
1555 if ( currReqModules
.length
) {
1564 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1565 * form of calls to mw.loader#implement().
1566 * @param {Function} cb Callback in case of failure
1567 * @param {Error} cb.err
1569 function asyncEval( implementations
, cb
) {
1570 if ( !implementations
.length
) {
1573 mw
.requestIdleCallback( function () {
1575 domEval( implementations
.join( ';' ) );
1583 * Make a versioned key for a specific module.
1586 * @param {string} module Module name
1587 * @return {string|null} Module key in format '`[name]@[version]`',
1588 * or null if the module does not exist
1590 function getModuleKey( module
) {
1591 return hasOwn
.call( registry
, module
) ?
1592 ( module
+ '@' + registry
[ module
].version
) : null;
1597 * @param {string} key Module name or '`[name]@[version]`'
1600 function splitModuleKey( key
) {
1601 var index
= key
.indexOf( '@' );
1602 if ( index
=== -1 ) {
1609 name
: key
.slice( 0, index
),
1610 version
: key
.slice( index
+ 1 )
1614 /* Public Members */
1617 * The module registry is exposed as an aid for debugging and inspecting page
1618 * state; it is not a public interface for modifying the registry.
1624 moduleRegistry
: registry
,
1627 * @inheritdoc #newStyleTag
1630 addStyleTag
: newStyleTag
,
1637 * Start loading of all queued module dependencies.
1642 var q
, batch
, implementations
, sourceModules
;
1646 // Appends a list of modules from the queue to the batch
1647 for ( q
= 0; q
< queue
.length
; q
++ ) {
1648 // Only load modules which are registered
1649 if ( hasOwn
.call( registry
, queue
[ q
] ) && registry
[ queue
[ q
] ].state
=== 'registered' ) {
1650 // Prevent duplicate entries
1651 if ( batch
.indexOf( queue
[ q
] ) === -1 ) {
1652 batch
.push( queue
[ q
] );
1653 // Mark registered modules as loading
1654 registry
[ queue
[ q
] ].state
= 'loading';
1659 // Now that the queue has been processed into a batch, clear the queue.
1660 // This MUST happen before we initiate any eval or network request. Otherwise,
1661 // it is possible for a cached script to instantly trigger the same work queue
1662 // again; all before we've cleared it causing each request to include modules
1663 // which are already loaded.
1666 if ( !batch
.length
) {
1670 mw
.loader
.store
.init();
1671 if ( mw
.loader
.store
.enabled
) {
1672 implementations
= [];
1674 batch
= batch
.filter( function ( module
) {
1675 var implementation
= mw
.loader
.store
.get( module
);
1676 if ( implementation
) {
1677 implementations
.push( implementation
);
1678 sourceModules
.push( module
);
1683 asyncEval( implementations
, function ( err
) {
1685 // Not good, the cached mw.loader.implement calls failed! This should
1686 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1687 // Depending on how corrupt the string is, it is likely that some
1688 // modules' implement() succeeded while the ones after the error will
1689 // never run and leave their modules in the 'loading' state forever.
1690 mw
.loader
.store
.stats
.failed
++;
1692 // Since this is an error not caused by an individual module but by
1693 // something that infected the implement call itself, don't take any
1694 // risks and clear everything in this cache.
1695 mw
.loader
.store
.clear();
1697 mw
.trackError( 'resourceloader.exception', {
1699 source
: 'store-eval'
1701 // Re-add the failed ones that are still pending back to the batch
1702 failed
= sourceModules
.filter( function ( module
) {
1703 return registry
[ module
].state
=== 'loading';
1705 batchRequest( failed
);
1709 batchRequest( batch
);
1713 * Register a source.
1715 * The #work() method will use this information to split up requests by source.
1717 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1719 * @param {string|Object} id Source ID, or object mapping ids to load urls
1720 * @param {string} loadUrl Url to a load.php end point
1721 * @throws {Error} If source id is already registered
1723 addSource: function ( id
, loadUrl
) {
1725 // Allow multiple additions
1726 if ( typeof id
=== 'object' ) {
1727 for ( source
in id
) {
1728 mw
.loader
.addSource( source
, id
[ source
] );
1733 if ( hasOwn
.call( sources
, id
) ) {
1734 throw new Error( 'source already registered: ' + id
);
1737 sources
[ id
] = loadUrl
;
1741 * Register a module, letting the system know about it and its properties.
1743 * The startup modules contain calls to this method.
1745 * When using multiple module registration by passing an array, dependencies that
1746 * are specified as references to modules within the array will be resolved before
1747 * the modules are registered.
1749 * @param {string|Array} module Module name or array of arrays, each containing
1750 * a list of arguments compatible with this method
1751 * @param {string|number} version Module version hash (falls backs to empty string)
1752 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1753 * @param {string[]} [dependencies] Array of module names on which this module depends.
1754 * @param {string} [group=null] Group which the module is in
1755 * @param {string} [source='local'] Name of the source
1756 * @param {string} [skip=null] Script body of the skip function
1758 register: function ( module
, version
, dependencies
, group
, source
, skip
) {
1760 // Allow multiple registration
1761 if ( typeof module
=== 'object' ) {
1762 resolveIndexedDependencies( module
);
1763 for ( i
= 0; i
< module
.length
; i
++ ) {
1764 // module is an array of module names
1765 if ( typeof module
[ i
] === 'string' ) {
1766 mw
.loader
.register( module
[ i
] );
1767 // module is an array of arrays
1768 } else if ( typeof module
[ i
] === 'object' ) {
1769 mw
.loader
.register
.apply( mw
.loader
, module
[ i
] );
1774 if ( hasOwn
.call( registry
, module
) ) {
1775 throw new Error( 'module already registered: ' + module
);
1777 // List the module as registered
1778 registry
[ module
] = {
1779 // Exposed to execute() for mw.loader.implement() closures.
1780 // Import happens via require().
1784 version
: String( version
|| '' ),
1785 dependencies
: dependencies
|| [],
1786 group
: typeof group
=== 'string' ? group
: null,
1787 source
: typeof source
=== 'string' ? source
: 'local',
1788 state
: 'registered',
1789 skip
: typeof skip
=== 'string' ? skip
: null
1794 * Implement a module given the components that make up the module.
1796 * When #load() or #using() requests one or more modules, the server
1797 * response contain calls to this function.
1799 * @param {string} module Name of module and current module version. Formatted
1800 * as '`[name]@[version]`". This version should match the requested version
1801 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1802 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1803 * @param {Function|Array|string} [script] Function with module code, list of URLs
1804 * to load via `<script src>`, or string of module code for `$.globalEval()`.
1805 * @param {Object} [style] Should follow one of the following patterns:
1807 * { "css": [css, ..] }
1808 * { "url": { <media>: [url, ..] } }
1810 * And for backwards compatibility (needs to be supported forever due to caching):
1813 * { <media>: [url, ..] }
1815 * The reason css strings are not concatenated anymore is T33676. We now check
1816 * whether it's safe to extend the stylesheet.
1819 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1820 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1822 implement: function ( module
, script
, style
, messages
, templates
) {
1823 var split
= splitModuleKey( module
),
1825 version
= split
.version
;
1826 // Automatically register module
1827 if ( !hasOwn
.call( registry
, name
) ) {
1828 mw
.loader
.register( name
);
1830 // Check for duplicate implementation
1831 if ( hasOwn
.call( registry
, name
) && registry
[ name
].script
!== undefined ) {
1832 throw new Error( 'module already implemented: ' + name
);
1835 // Without this reset, if there is a version mismatch between the
1836 // requested and received module version, then mw.loader.store would
1837 // cache the response under the requested key. Thus poisoning the cache
1838 // indefinitely with a stale value. (T117587)
1839 registry
[ name
].version
= version
;
1841 // Attach components
1842 registry
[ name
].script
= script
|| null;
1843 registry
[ name
].style
= style
|| null;
1844 registry
[ name
].messages
= messages
|| null;
1845 registry
[ name
].templates
= templates
|| null;
1846 // The module may already have been marked as erroneous
1847 if ( registry
[ name
].state
!== 'error' && registry
[ name
].state
!== 'missing' ) {
1848 registry
[ name
].state
= 'loaded';
1849 if ( allWithImplicitReady( name
) ) {
1856 * Load an external script or one or more modules.
1858 * This method takes a list of unrelated modules. Use cases:
1860 * - A web page will be composed of many different widgets. These widgets independently
1861 * queue their ResourceLoader modules (`OutputPage::addModules()`). If any of them
1862 * have problems, or are no longer known (e.g. cached HTML), the other modules
1863 * should still be loaded.
1864 * - This method is used for preloading, which must not throw. Later code that
1865 * calls #using() will handle the error.
1867 * @param {string|Array} modules Either the name of a module, array of modules,
1868 * or a URL of an external script or style
1869 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
1870 * external script or style; acceptable values are "text/css" and
1871 * "text/javascript"; if no type is provided, text/javascript is assumed.
1873 load: function ( modules
, type
) {
1876 // Allow calling with a url or single dependency as a string
1877 if ( typeof modules
=== 'string' ) {
1878 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
1879 if ( /^(https?:)?\/?\//.test( modules
) ) {
1880 if ( type
=== 'text/css' ) {
1881 l
= document
.createElement( 'link' );
1882 l
.rel
= 'stylesheet';
1884 document
.head
.appendChild( l
);
1887 if ( type
=== 'text/javascript' || type
=== undefined ) {
1888 addScript( modules
);
1892 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
1894 // Called with single module
1895 modules
= [ modules
];
1898 // Filter out top-level modules that are unknown or failed to load before.
1899 filtered
= modules
.filter( function ( module
) {
1900 var state
= mw
.loader
.getState( module
);
1901 return state
!== 'error' && state
!== 'missing';
1903 // Resolve remaining list using the known dependency tree.
1904 // This also filters out modules with unknown dependencies. (T36853)
1905 filtered
= resolveStubbornly( filtered
);
1906 // Some modules are not yet ready, add to module load queue.
1907 enqueue( filtered
, undefined, undefined );
1911 * Change the state of one or more modules.
1913 * @param {Object} modules Object of module name/state pairs
1915 state: function ( modules
) {
1917 for ( module
in modules
) {
1918 state
= modules
[ module
];
1919 if ( !hasOwn
.call( registry
, module
) ) {
1920 mw
.loader
.register( module
);
1922 registry
[ module
].state
= state
;
1923 if ( state
=== 'ready' || state
=== 'error' || state
=== 'missing' ) {
1924 // Make sure pending modules depending on this one get executed if their
1925 // dependencies are now fulfilled!
1926 handlePending( module
);
1932 * Get the version of a module.
1934 * @param {string} module Name of module
1935 * @return {string|null} The version, or null if the module (or its version) is not
1938 getVersion: function ( module
) {
1939 return hasOwn
.call( registry
, module
) ? registry
[ module
].version
: null;
1943 * Get the state of a module.
1945 * @param {string} module Name of module
1946 * @return {string|null} The state, or null if the module (or its state) is not
1949 getState: function ( module
) {
1950 return hasOwn
.call( registry
, module
) ? registry
[ module
].state
: null;
1954 * Get the names of all registered modules.
1958 getModuleNames: function () {
1959 return Object
.keys( registry
);
1963 * Get the exported value of a module.
1965 * This static method is publicly exposed for debugging purposes
1966 * only and must not be used in production code. In production code,
1967 * please use the dynamically provided `require()` function instead.
1969 * In case of lazy-loaded modules via mw.loader#using(), the returned
1970 * Promise provides the function, see #using() for examples.
1974 * @param {string} moduleName Module name
1975 * @return {Mixed} Exported value
1977 require: function ( moduleName
) {
1978 var state
= mw
.loader
.getState( moduleName
);
1980 // Only ready modules can be required
1981 if ( state
!== 'ready' ) {
1982 // Module may've forgotten to declare a dependency
1983 throw new Error( 'Module "' + moduleName
+ '" is not loaded.' );
1986 return registry
[ moduleName
].module
.exports
;
1990 * On browsers that implement the localStorage API, the module store serves as a
1991 * smart complement to the browser cache. Unlike the browser cache, the module store
1992 * can slice a concatenated response from ResourceLoader into its constituent
1993 * modules and cache each of them separately, using each module's versioning scheme
1994 * to determine when the cache should be invalidated.
1998 * @class mw.loader.store
2001 // Whether the store is in use on this page.
2004 // Modules whose string representation exceeds 100 kB are
2005 // ineligible for storage. See bug T66721.
2006 MODULE_SIZE_MAX
: 100 * 1000,
2008 // The contents of the store, mapping '[name]@[version]' keys
2009 // to module implementations.
2013 stats
: { hits
: 0, misses
: 0, expired
: 0, failed
: 0 },
2016 * Construct a JSON-serializable object representing the content of the store.
2018 * @return {Object} Module store contents.
2020 toJSON: function () {
2021 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
2025 * Get the localStorage key for the entire module store. The key references
2026 * $wgDBname to prevent clashes between wikis which share a common host.
2028 * @return {string} localStorage item key
2030 getStoreKey: function () {
2031 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
2035 * Get a key on which to vary the module cache.
2037 * @return {string} String of concatenated vary conditions.
2039 getVary: function () {
2040 return mw
.config
.get( 'skin' ) + ':' +
2041 mw
.config
.get( 'wgResourceLoaderStorageVersion' ) + ':' +
2042 mw
.config
.get( 'wgUserLanguage' );
2046 * Initialize the store.
2048 * Retrieves store from localStorage and (if successfully retrieved) decoding
2049 * the stored JSON value to a plain object.
2051 * The try / catch block is used for JSON & localStorage feature detection.
2052 * See the in-line documentation for Modernizr's localStorage feature detection
2053 * code for a full account of why we need a try / catch:
2054 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2059 if ( mw
.loader
.store
.enabled
!== null ) {
2065 // Disabled because localStorage quotas are tight and (in Firefox's case)
2066 // shared by multiple origins.
2067 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2068 /Firefox|Opera/.test( navigator
.userAgent
) ||
2070 // Disabled by configuration.
2071 !mw
.config
.get( 'wgResourceLoaderStorageEnabled' )
2073 // Clear any previous store to free up space. (T66721)
2074 mw
.loader
.store
.clear();
2075 mw
.loader
.store
.enabled
= false;
2078 if ( mw
.config
.get( 'debug' ) ) {
2079 // Disable module store in debug mode
2080 mw
.loader
.store
.enabled
= false;
2085 // This a string we stored, or `null` if the key does not (yet) exist.
2086 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
2087 // If we get here, localStorage is available; mark enabled
2088 mw
.loader
.store
.enabled
= true;
2089 // If null, JSON.parse() will cast to string and re-parse, still null.
2090 data
= JSON
.parse( raw
);
2091 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== mw
.loader
.store
.getVary() ) {
2092 mw
.loader
.store
.items
= data
.items
;
2096 mw
.trackError( 'resourceloader.exception', {
2098 source
: 'store-localstorage-init'
2102 // If we get here, one of four things happened:
2104 // 1. localStorage did not contain our store key.
2105 // This means `raw` is `null`, and we're on a fresh page view (cold cache).
2106 // The store was enabled, and `items` starts fresh.
2108 // 2. localStorage contained parseable data under our store key,
2109 // but it's not applicable to our current context (see getVary).
2110 // The store was enabled, and `items` starts fresh.
2112 // 3. JSON.parse threw (localStorage contained corrupt data).
2113 // This means `raw` contains a string.
2114 // The store was enabled, and `items` starts fresh.
2116 // 4. localStorage threw (disabled or otherwise unavailable).
2117 // This means `raw` was never assigned.
2118 // We will disable the store below.
2119 if ( raw
=== undefined ) {
2120 // localStorage failed; disable store
2121 mw
.loader
.store
.enabled
= false;
2126 * Retrieve a module from the store and update cache hit stats.
2128 * @param {string} module Module name
2129 * @return {string|boolean} Module implementation or false if unavailable
2131 get: function ( module
) {
2134 if ( !mw
.loader
.store
.enabled
) {
2138 key
= getModuleKey( module
);
2139 if ( key
in mw
.loader
.store
.items
) {
2140 mw
.loader
.store
.stats
.hits
++;
2141 return mw
.loader
.store
.items
[ key
];
2143 mw
.loader
.store
.stats
.misses
++;
2148 * Stringify a module and queue it for storage.
2150 * @param {string} module Module name
2151 * @param {Object} descriptor The module's descriptor as set in the registry
2153 set: function ( module
, descriptor
) {
2156 if ( !mw
.loader
.store
.enabled
) {
2160 key
= getModuleKey( module
);
2163 // Already stored a copy of this exact version
2164 key
in mw
.loader
.store
.items
||
2165 // Module failed to load
2166 descriptor
.state
!== 'ready' ||
2167 // Unversioned, private, or site-/user-specific
2168 !descriptor
.version
||
2169 descriptor
.group
=== 'private' ||
2170 descriptor
.group
=== 'user' ||
2171 // Partial descriptor
2172 // (e.g. skipped module, or style module with state=ready)
2173 [ descriptor
.script
, descriptor
.style
, descriptor
.messages
,
2174 descriptor
.templates
].indexOf( undefined ) !== -1
2182 JSON
.stringify( key
),
2183 typeof descriptor
.script
=== 'function' ?
2184 String( descriptor
.script
) :
2185 JSON
.stringify( descriptor
.script
),
2186 JSON
.stringify( descriptor
.style
),
2187 JSON
.stringify( descriptor
.messages
),
2188 JSON
.stringify( descriptor
.templates
)
2191 mw
.trackError( 'resourceloader.exception', {
2193 source
: 'store-localstorage-json'
2198 src
= 'mw.loader.implement(' + args
.join( ',' ) + ');';
2199 if ( src
.length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2202 mw
.loader
.store
.items
[ key
] = src
;
2203 mw
.loader
.store
.update();
2207 * Iterate through the module store, removing any item that does not correspond
2208 * (in name and version) to an item in the module registry.
2210 prune: function () {
2213 for ( key
in mw
.loader
.store
.items
) {
2214 module
= key
.slice( 0, key
.indexOf( '@' ) );
2215 if ( getModuleKey( module
) !== key
) {
2216 mw
.loader
.store
.stats
.expired
++;
2217 delete mw
.loader
.store
.items
[ key
];
2218 } else if ( mw
.loader
.store
.items
[ key
].length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2219 // This value predates the enforcement of a size limit on cached modules.
2220 delete mw
.loader
.store
.items
[ key
];
2226 * Clear the entire module store right now.
2228 clear: function () {
2229 mw
.loader
.store
.items
= {};
2231 localStorage
.removeItem( mw
.loader
.store
.getStoreKey() );
2236 * Sync in-memory store back to localStorage.
2238 * This function debounces updates. When called with a flush already pending, the
2239 * scheduled flush is postponed. The call to localStorage.setItem will be keep
2240 * being deferred until the page is quiescent for 2 seconds.
2242 * Because localStorage is shared by all pages from the same origin, if multiple
2243 * pages are loaded with different module sets, the possibility exists that
2244 * modules saved by one page will be clobbered by another. The only impact of this
2245 * is minor (merely a less efficient cache use) and the problem would be corrected
2246 * by subsequent page views.
2250 update
: ( function () {
2251 var timer
, hasPendingWrites
= false;
2253 function flushWrites() {
2255 if ( !mw
.loader
.store
.enabled
) {
2259 mw
.loader
.store
.prune();
2260 key
= mw
.loader
.store
.getStoreKey();
2262 // Replacing the content of the module store might fail if the new
2263 // contents would exceed the browser's localStorage size limit. To
2264 // avoid clogging the browser with stale data, always remove the old
2265 // value before attempting to set the new one.
2266 localStorage
.removeItem( key
);
2267 data
= JSON
.stringify( mw
.loader
.store
);
2268 localStorage
.setItem( key
, data
);
2270 mw
.trackError( 'resourceloader.exception', {
2272 source
: 'store-localstorage-update'
2276 hasPendingWrites
= false;
2279 function request() {
2280 // If another mw.loader.store.set()/update() call happens in the narrow
2281 // time window between requestIdleCallback() and flushWrites firing, ignore it.
2282 // It'll be saved by the already-scheduled flush.
2283 if ( !hasPendingWrites
) {
2284 hasPendingWrites
= true;
2285 mw
.requestIdleCallback( flushWrites
);
2289 return function () {
2290 // Cancel the previous timer (if it hasn't fired yet)
2291 clearTimeout( timer
);
2292 timer
= setTimeout( request
, 2000 );
2299 // Skeleton user object, extended by the 'mediawiki.user' module.
2306 * @property {mw.Map}
2310 * @property {mw.Map}
2315 // OOUI widgets specific to MediaWiki
2320 // Attach to window and globally alias
2321 window
.mw
= window
.mediaWiki
= mw
;