2 * The mediawiki.inspect module.
8 /* eslint-disable no-console */
12 // mw.inspect is a singleton class with static methods
13 // that itself can also be invoked as a function (mediawiki.base/mw#inspect).
14 // In JavaScript, that is implemented by starting with a function,
15 // and subsequently setting additional properties on the function object.
18 * Tools for inspecting page composition and performance.
24 var inspect
= mw
.inspect
,
25 byteLength
= require( 'mediawiki.String' ).byteLength
,
26 hasOwn
= Object
.prototype.hasOwnProperty
;
28 function sortByProperty( array
, prop
, descending
) {
29 var order
= descending
? -1 : 1;
30 return array
.sort( function ( a
, b
) {
31 if ( a
[ prop
] === undefined || b
[ prop
] === undefined ) {
32 // Sort undefined to the end, regardless of direction
33 return a
[ prop
] !== undefined ? -1 : b
[ prop
] !== undefined ? 1 : 0;
35 return a
[ prop
] > b
[ prop
] ? order
: a
[ prop
] < b
[ prop
] ? -order
: 0;
39 function humanSize( bytes
) {
41 units
= [ '', ' KiB', ' MiB', ' GiB', ' TiB', ' PiB' ];
43 if ( !$.isNumeric( bytes
) || bytes
=== 0 ) { return bytes
; }
45 for ( i
= 0; bytes
>= 1024; bytes
/= 1024 ) { i
++; }
46 // Maintain one decimal for kB and above, but don't
47 // add ".0" for bytes.
48 return bytes
.toFixed( i
> 0 ? 1 : 0 ) + units
[ i
];
52 * Return a map of all dependency relationships between loaded modules.
54 * @return {Object} Maps module names to objects. Each sub-object has
55 * two properties, 'requires' and 'requiredBy'.
57 inspect
.getDependencyGraph = function () {
58 var modules
= inspect
.getLoadedModules(),
61 modules
.forEach( function ( moduleName
) {
62 var dependencies
= mw
.loader
.moduleRegistry
[ moduleName
].dependencies
|| [];
64 if ( !hasOwn
.call( graph
, moduleName
) ) {
65 graph
[ moduleName
] = { requiredBy
: [] };
67 graph
[ moduleName
].requires
= dependencies
;
69 dependencies
.forEach( function ( depName
) {
70 if ( !hasOwn
.call( graph
, depName
) ) {
71 graph
[ depName
] = { requiredBy
: [] };
73 graph
[ depName
].requiredBy
.push( moduleName
);
80 * Calculate the byte size of a ResourceLoader module.
82 * @param {string} moduleName The name of the module
83 * @return {number|null} Module size in bytes or null
85 inspect
.getModuleSize = function ( moduleName
) {
86 var module
= mw
.loader
.moduleRegistry
[ moduleName
],
89 if ( module
.state
!== 'ready' ) {
93 if ( !module
.style
&& !module
.script
) {
97 function getFunctionBody( func
) {
99 // To ensure a deterministic result, replace the start of the function
100 // declaration with a fixed string. For example, in Chrome 55, it seems
101 // V8 seemingly-at-random decides to sometimes put a line break between
102 // the opening brace and first statement of the function body. T159751.
103 .replace( /^\s*function\s*\([^)]*\)\s*{\s*/, 'function(){' )
104 .replace( /\s*}\s*$/, '}' );
107 // Based on the load.php response for this module.
108 // For example: `mw.loader.implement("example", function(){}, {"css":[".x{color:red}"]});`
109 // @see mw.loader.store.set().
117 // Trim trailing null or empty object, as load.php would have done.
118 // @see ResourceLoader::makeLoaderImplementScript and ResourceLoader::trimArray.
121 if ( args
[ i
] === null || ( $.isPlainObject( args
[ i
] ) && $.isEmptyObject( args
[ i
] ) ) ) {
129 for ( i
= 0; i
< args
.length
; i
++ ) {
130 if ( typeof args
[ i
] === 'function' ) {
131 size
+= byteLength( getFunctionBody( args
[ i
] ) );
133 size
+= byteLength( JSON
.stringify( args
[ i
] ) );
141 * Given CSS source, count both the total number of selectors it
142 * contains and the number which match some element in the current
145 * @param {string} css CSS source
146 * @return {Object} Selector counts
147 * @return {number} return.selectors Total number of selectors
148 * @return {number} return.matched Number of matched selectors
150 inspect
.auditSelectors = function ( css
) {
151 var selectors
= { total
: 0, matched
: 0 },
152 style
= document
.createElement( 'style' );
154 style
.textContent
= css
;
155 document
.body
.appendChild( style
);
156 // eslint-disable-next-line no-restricted-properties
157 $.each( style
.sheet
.cssRules
, function ( index
, rule
) {
159 // document.querySelector() on prefixed pseudo-elements can throw exceptions
160 // in Firefox and Safari. Ignore these exceptions.
161 // https://bugs.webkit.org/show_bug.cgi?id=149160
162 // https://bugzilla.mozilla.org/show_bug.cgi?id=1204880
164 if ( document
.querySelector( rule
.selectorText
) !== null ) {
169 document
.body
.removeChild( style
);
174 * Get a list of all loaded ResourceLoader modules.
176 * @return {Array} List of module names
178 inspect
.getLoadedModules = function () {
179 return mw
.loader
.getModuleNames().filter( function ( module
) {
180 return mw
.loader
.getState( module
) === 'ready';
185 * Print tabular data to the console, using console.table, console.log,
186 * or mw.log (in declining order of preference).
188 * @param {Array} data Tabular data represented as an array of objects
189 * with common properties.
191 inspect
.dumpTable = function ( data
) {
193 // Use Function.prototype#call to force an exception on Firefox,
194 // which doesn't define console#table but doesn't complain if you
196 // eslint-disable-next-line no-useless-call
197 console
.table
.call( console
, data
);
201 console
.log( JSON
.stringify( data
, null, 2 ) );
206 * Generate and print reports.
208 * When invoked without arguments, prints all available reports.
210 * @param {...string} [reports] One or more of "size", "css", "store", or "time".
212 inspect
.runReports = function () {
213 var reports
= arguments
.length
> 0 ?
214 Array
.prototype.slice
.call( arguments
) :
215 Object
.keys( inspect
.reports
);
217 reports
.forEach( function ( name
) {
218 if ( console
.group
) {
219 console
.group( 'mw.inspect ' + name
+ ' report' );
221 console
.log( 'mw.inspect ' + name
+ ' report' );
223 inspect
.dumpTable( inspect
.reports
[ name
]() );
224 if ( console
.group
) {
225 console
.groupEnd( 'mw.inspect ' + name
+ ' report' );
231 * Perform a string search across the JavaScript and CSS source code
232 * of all loaded modules and return an array of the names of the
233 * modules that matched.
235 * @param {string|RegExp} pattern String or regexp to match.
236 * @return {Array} Array of the names of modules that matched.
238 inspect
.grep = function ( pattern
) {
239 if ( typeof pattern
.test
!== 'function' ) {
240 pattern
= new RegExp( mw
.RegExp
.escape( pattern
), 'g' );
243 return inspect
.getLoadedModules().filter( function ( moduleName
) {
244 var module
= mw
.loader
.moduleRegistry
[ moduleName
];
246 // Grep module's JavaScript
247 if ( typeof module
.script
=== 'function' && pattern
.test( module
.script
.toString() ) ) {
253 $.isPlainObject( module
.style
) && Array
.isArray( module
.style
.css
) &&
254 pattern
.test( module
.style
.css
.join( '' ) )
256 // Module's CSS source matches
266 * @class mw.inspect.reports
271 * Generate a breakdown of all loaded modules and their size in
272 * kilobytes. Modules are ordered from largest to smallest.
274 * @return {Object[]} Size reports
277 // Map each module to a descriptor object.
278 var modules
= inspect
.getLoadedModules().map( function ( module
) {
281 size
: inspect
.getModuleSize( module
)
285 // Sort module descriptors by size, largest first.
286 sortByProperty( modules
, 'size', true );
288 // Convert size to human-readable string.
289 modules
.forEach( function ( module
) {
290 module
.sizeInBytes
= module
.size
;
291 module
.size
= humanSize( module
.size
);
298 * For each module with styles, count the number of selectors, and
299 * count how many match against some element currently in the DOM.
301 * @return {Object[]} CSS reports
306 inspect
.getLoadedModules().forEach( function ( name
) {
307 var css
, stats
, module
= mw
.loader
.moduleRegistry
[ name
];
310 css
= module
.style
.css
.join();
311 } catch ( e
) { return; } // skip
313 stats
= inspect
.auditSelectors( css
);
316 allSelectors
: stats
.total
,
317 matchedSelectors
: stats
.matched
,
318 percentMatched
: stats
.total
!== 0 ?
319 ( stats
.matched
/ stats
.total
* 100 ).toFixed( 2 ) + '%' : null
322 sortByProperty( modules
, 'allSelectors', true );
327 * Report stats on mw.loader.store: the number of localStorage
328 * cache hits and misses, the number of items purged from the
329 * cache, and the total size of the module blob in localStorage.
331 * @return {Object[]} Store stats
334 var raw
, stats
= { enabled
: mw
.loader
.store
.enabled
};
335 if ( stats
.enabled
) {
336 $.extend( stats
, mw
.loader
.store
.stats
);
338 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
339 stats
.totalSizeInBytes
= byteLength( raw
);
340 stats
.totalSize
= humanSize( byteLength( raw
) );
347 * Generate a breakdown of all loaded modules and their time
348 * spent during initialisation (measured in milliseconds).
350 * This timing data is collected by mw.loader.profiler.
352 * @return {Object[]} Table rows
357 if ( !mw
.loader
.profiler
) {
358 mw
.log
.warn( 'mw.inspect: The time report requires $wgResourceLoaderEnableJSProfiler.' );
362 modules
= inspect
.getLoadedModules()
363 .map( function ( moduleName
) {
364 return mw
.loader
.profiler
.getProfile( moduleName
);
366 .filter( function ( perf
) {
367 // Exclude modules that reached "ready" state without involvement from mw.loader.
368 // This is primarily styles-only as loaded via <link rel="stylesheet">.
369 return perf
!== null;
372 // Sort by total time spent, highest first.
373 sortByProperty( modules
, 'total', true );
375 // Add human-readable strings
376 modules
.forEach( function ( module
) {
377 module
.totalInMs
= module
.total
;
378 module
.total
= module
.totalInMs
.toLocaleString() + ' ms';
385 if ( mw
.config
.get( 'debug' ) ) {
386 mw
.log( 'mw.inspect: reports are not available in debug mode.' );