2 * Tools for inspecting page composition and performance.
8 /* eslint-disable no-console */
10 ( function ( mw, $ ) {
13 hasOwn = Object.prototype.hasOwnProperty;
15 function sortByProperty( array, prop, descending ) {
16 var order = descending ? -1 : 1;
17 return array.sort( function ( a, b ) {
18 return a[ prop ] > b[ prop ] ? order : a[ prop ] < b[ prop ] ? -order : 0;
22 function humanSize( bytes ) {
24 units = [ '', ' KiB', ' MiB', ' GiB', ' TiB', ' PiB' ];
26 if ( !$.isNumeric( bytes ) || bytes === 0 ) { return bytes; }
28 for ( i = 0; bytes >= 1024; bytes /= 1024 ) { i++; }
29 // Maintain one decimal for kB and above, but don't
30 // add ".0" for bytes.
31 return bytes.toFixed( i > 0 ? 1 : 0 ) + units[ i ];
41 * Return a map of all dependency relationships between loaded modules.
43 * @return {Object} Maps module names to objects. Each sub-object has
44 * two properties, 'requires' and 'requiredBy'.
46 getDependencyGraph: function () {
47 var modules = inspect.getLoadedModules(),
50 $.each( modules, function ( moduleIndex, moduleName ) {
51 var dependencies = mw.loader.moduleRegistry[ moduleName ].dependencies || [];
53 if ( !hasOwn.call( graph, moduleName ) ) {
54 graph[ moduleName ] = { requiredBy: [] };
56 graph[ moduleName ].requires = dependencies;
58 $.each( dependencies, function ( depIndex, depName ) {
59 if ( !hasOwn.call( graph, depName ) ) {
60 graph[ depName ] = { requiredBy: [] };
62 graph[ depName ].requiredBy.push( moduleName );
69 * Calculate the byte size of a ResourceLoader module.
71 * @param {string} moduleName The name of the module
72 * @return {number|null} Module size in bytes or null
74 getModuleSize: function ( moduleName ) {
75 var module = mw.loader.moduleRegistry[ moduleName ],
78 if ( module.state !== 'ready' ) {
82 if ( !module.style && !module.script ) {
86 function getFunctionBody( func ) {
88 // To ensure a deterministic result, replace the start of the function
89 // declaration with a fixed string. For example, in Chrome 55, it seems
90 // V8 seemingly-at-random decides to sometimes put a line break between
91 // the opening brace and first statement of the function body. T159751.
92 .replace( /^\s*function\s*\([^)]*\)\s*{\s*/, 'function(){' )
93 .replace( /\s*}\s*$/, '}' );
96 // Based on the load.php response for this module.
97 // For example: `mw.loader.implement("example", function(){}, {"css":[".x{color:red}"]});`
98 // @see mw.loader.store.set().
106 // Trim trailing null or empty object, as load.php would have done.
107 // @see ResourceLoader::makeLoaderImplementScript and ResourceLoader::trimArray.
110 if ( args[ i ] === null || ( $.isPlainObject( args[ i ] ) && $.isEmptyObject( args[ i ] ) ) ) {
118 for ( i = 0; i < args.length; i++ ) {
119 if ( typeof args[ i ] === 'function' ) {
120 size += $.byteLength( getFunctionBody( args[ i ] ) );
122 size += $.byteLength( JSON.stringify( args[ i ] ) );
130 * Given CSS source, count both the total number of selectors it
131 * contains and the number which match some element in the current
134 * @param {string} css CSS source
135 * @return {Object} Selector counts
136 * @return {number} return.selectors Total number of selectors
137 * @return {number} return.matched Number of matched selectors
139 auditSelectors: function ( css ) {
140 var selectors = { total: 0, matched: 0 },
141 style = document.createElement( 'style' );
143 style.textContent = css;
144 document.body.appendChild( style );
145 $.each( style.sheet.cssRules, function ( index, rule ) {
147 // document.querySelector() on prefixed pseudo-elements can throw exceptions
148 // in Firefox and Safari. Ignore these exceptions.
149 // https://bugs.webkit.org/show_bug.cgi?id=149160
150 // https://bugzilla.mozilla.org/show_bug.cgi?id=1204880
152 if ( document.querySelector( rule.selectorText ) !== null ) {
157 document.body.removeChild( style );
162 * Get a list of all loaded ResourceLoader modules.
164 * @return {Array} List of module names
166 getLoadedModules: function () {
167 return $.grep( mw.loader.getModuleNames(), function ( module ) {
168 return mw.loader.getState( module ) === 'ready';
173 * Print tabular data to the console, using console.table, console.log,
174 * or mw.log (in declining order of preference).
176 * @param {Array} data Tabular data represented as an array of objects
177 * with common properties.
179 dumpTable: function ( data ) {
181 // Bartosz made me put this here.
182 if ( window.opera ) { throw window.opera; }
183 // Use Function.prototype#call to force an exception on Firefox,
184 // which doesn't define console#table but doesn't complain if you
186 console.table.call( console, data );
190 console.log( JSON.stringify( data, null, 2 ) );
197 * Generate and print one more reports. When invoked with no arguments,
200 * @param {...string} [reports] Report names to run, or unset to print
201 * all available reports.
203 runReports: function () {
204 var reports = arguments.length > 0 ?
205 Array.prototype.slice.call( arguments ) :
206 $.map( inspect.reports, function ( v, k ) { return k; } );
208 $.each( reports, function ( index, name ) {
209 inspect.dumpTable( inspect.reports[ name ]() );
214 * @class mw.inspect.reports
219 * Generate a breakdown of all loaded modules and their size in
220 * kilobytes. Modules are ordered from largest to smallest.
222 * @return {Object[]} Size reports
225 // Map each module to a descriptor object.
226 var modules = $.map( inspect.getLoadedModules(), function ( module ) {
229 size: inspect.getModuleSize( module )
233 // Sort module descriptors by size, largest first.
234 sortByProperty( modules, 'size', true );
236 // Convert size to human-readable string.
237 $.each( modules, function ( i, module ) {
238 module.sizeInBytes = module.size;
239 module.size = humanSize( module.size );
246 * For each module with styles, count the number of selectors, and
247 * count how many match against some element currently in the DOM.
249 * @return {Object[]} CSS reports
254 $.each( inspect.getLoadedModules(), function ( index, name ) {
255 var css, stats, module = mw.loader.moduleRegistry[ name ];
258 css = module.style.css.join();
259 } catch ( e ) { return; } // skip
261 stats = inspect.auditSelectors( css );
264 allSelectors: stats.total,
265 matchedSelectors: stats.matched,
266 percentMatched: stats.total !== 0 ?
267 ( stats.matched / stats.total * 100 ).toFixed( 2 ) + '%' : null
270 sortByProperty( modules, 'allSelectors', true );
275 * Report stats on mw.loader.store: the number of localStorage
276 * cache hits and misses, the number of items purged from the
277 * cache, and the total size of the module blob in localStorage.
279 * @return {Object[]} Store stats
282 var raw, stats = { enabled: mw.loader.store.enabled };
283 if ( stats.enabled ) {
284 $.extend( stats, mw.loader.store.stats );
286 raw = localStorage.getItem( mw.loader.store.getStoreKey() );
287 stats.totalSizeInBytes = $.byteLength( raw );
288 stats.totalSize = humanSize( $.byteLength( raw ) );
296 * Perform a string search across the JavaScript and CSS source code
297 * of all loaded modules and return an array of the names of the
298 * modules that matched.
300 * @param {string|RegExp} pattern String or regexp to match.
301 * @return {Array} Array of the names of modules that matched.
303 grep: function ( pattern ) {
304 if ( typeof pattern.test !== 'function' ) {
305 pattern = new RegExp( mw.RegExp.escape( pattern ), 'g' );
308 return $.grep( inspect.getLoadedModules(), function ( moduleName ) {
309 var module = mw.loader.moduleRegistry[ moduleName ];
311 // Grep module's JavaScript
312 if ( $.isFunction( module.script ) && pattern.test( module.script.toString() ) ) {
318 $.isPlainObject( module.style ) && $.isArray( module.style.css ) &&
319 pattern.test( module.style.css.join( '' ) )
321 // Module's CSS source matches
330 if ( mw.config.get( 'debug' ) ) {
331 mw.log( 'mw.inspect: reports are not available in debug mode.' );
334 mw.inspect = inspect;
336 }( mediaWiki, jQuery ) );