2 * Tools for inspecting page composition and performance.
8 /* eslint-disable no-console */
10 ( function ( mw
, $ ) {
13 byteLength
= require( 'mediawiki.String' ).byteLength
,
14 hasOwn
= Object
.prototype.hasOwnProperty
;
16 function sortByProperty( array
, prop
, descending
) {
17 var order
= descending
? -1 : 1;
18 return array
.sort( function ( a
, b
) {
19 return a
[ prop
] > b
[ prop
] ? order
: a
[ prop
] < b
[ prop
] ? -order
: 0;
23 function humanSize( bytes
) {
25 units
= [ '', ' KiB', ' MiB', ' GiB', ' TiB', ' PiB' ];
27 if ( !$.isNumeric( bytes
) || bytes
=== 0 ) { return bytes
; }
29 for ( i
= 0; bytes
>= 1024; bytes
/= 1024 ) { i
++; }
30 // Maintain one decimal for kB and above, but don't
31 // add ".0" for bytes.
32 return bytes
.toFixed( i
> 0 ? 1 : 0 ) + units
[ i
];
42 * Return a map of all dependency relationships between loaded modules.
44 * @return {Object} Maps module names to objects. Each sub-object has
45 * two properties, 'requires' and 'requiredBy'.
47 getDependencyGraph: function () {
48 var modules
= inspect
.getLoadedModules(),
51 modules
.forEach( function ( moduleName
) {
52 var dependencies
= mw
.loader
.moduleRegistry
[ moduleName
].dependencies
|| [];
54 if ( !hasOwn
.call( graph
, moduleName
) ) {
55 graph
[ moduleName
] = { requiredBy
: [] };
57 graph
[ moduleName
].requires
= dependencies
;
59 dependencies
.forEach( function ( depName
) {
60 if ( !hasOwn
.call( graph
, depName
) ) {
61 graph
[ depName
] = { requiredBy
: [] };
63 graph
[ depName
].requiredBy
.push( moduleName
);
70 * Calculate the byte size of a ResourceLoader module.
72 * @param {string} moduleName The name of the module
73 * @return {number|null} Module size in bytes or null
75 getModuleSize: function ( moduleName
) {
76 var module
= mw
.loader
.moduleRegistry
[ moduleName
],
79 if ( module
.state
!== 'ready' ) {
83 if ( !module
.style
&& !module
.script
) {
87 function getFunctionBody( func
) {
89 // To ensure a deterministic result, replace the start of the function
90 // declaration with a fixed string. For example, in Chrome 55, it seems
91 // V8 seemingly-at-random decides to sometimes put a line break between
92 // the opening brace and first statement of the function body. T159751.
93 .replace( /^\s*function\s*\([^)]*\)\s*{\s*/, 'function(){' )
94 .replace( /\s*}\s*$/, '}' );
97 // Based on the load.php response for this module.
98 // For example: `mw.loader.implement("example", function(){}, {"css":[".x{color:red}"]});`
99 // @see mw.loader.store.set().
107 // Trim trailing null or empty object, as load.php would have done.
108 // @see ResourceLoader::makeLoaderImplementScript and ResourceLoader::trimArray.
111 if ( args
[ i
] === null || ( $.isPlainObject( args
[ i
] ) && $.isEmptyObject( args
[ i
] ) ) ) {
119 for ( i
= 0; i
< args
.length
; i
++ ) {
120 if ( typeof args
[ i
] === 'function' ) {
121 size
+= byteLength( getFunctionBody( args
[ i
] ) );
123 size
+= byteLength( JSON
.stringify( args
[ i
] ) );
131 * Given CSS source, count both the total number of selectors it
132 * contains and the number which match some element in the current
135 * @param {string} css CSS source
136 * @return {Object} Selector counts
137 * @return {number} return.selectors Total number of selectors
138 * @return {number} return.matched Number of matched selectors
140 auditSelectors: function ( css
) {
141 var selectors
= { total
: 0, matched
: 0 },
142 style
= document
.createElement( 'style' );
144 style
.textContent
= css
;
145 document
.body
.appendChild( style
);
146 $.each( style
.sheet
.cssRules
, function ( index
, rule
) {
148 // document.querySelector() on prefixed pseudo-elements can throw exceptions
149 // in Firefox and Safari. Ignore these exceptions.
150 // https://bugs.webkit.org/show_bug.cgi?id=149160
151 // https://bugzilla.mozilla.org/show_bug.cgi?id=1204880
153 if ( document
.querySelector( rule
.selectorText
) !== null ) {
158 document
.body
.removeChild( style
);
163 * Get a list of all loaded ResourceLoader modules.
165 * @return {Array} List of module names
167 getLoadedModules: function () {
168 return mw
.loader
.getModuleNames().filter( function ( module
) {
169 return mw
.loader
.getState( module
) === 'ready';
174 * Print tabular data to the console, using console.table, console.log,
175 * or mw.log (in declining order of preference).
177 * @param {Array} data Tabular data represented as an array of objects
178 * with common properties.
180 dumpTable: function ( data
) {
182 // Bartosz made me put this here.
183 if ( window
.opera
) { throw window
.opera
; }
184 // Use Function.prototype#call to force an exception on Firefox,
185 // which doesn't define console#table but doesn't complain if you
187 // eslint-disable-next-line no-useless-call
188 console
.table
.call( console
, data
);
192 console
.log( JSON
.stringify( data
, null, 2 ) );
199 * Generate and print one more reports. When invoked with no arguments,
202 * @param {...string} [reports] Report names to run, or unset to print
203 * all available reports.
205 runReports: function () {
206 var reports
= arguments
.length
> 0 ?
207 Array
.prototype.slice
.call( arguments
) :
208 $.map( inspect
.reports
, function ( v
, k
) { return k
; } );
210 reports
.forEach( function ( name
) {
211 inspect
.dumpTable( inspect
.reports
[ name
]() );
216 * @class mw.inspect.reports
221 * Generate a breakdown of all loaded modules and their size in
222 * kilobytes. Modules are ordered from largest to smallest.
224 * @return {Object[]} Size reports
227 // Map each module to a descriptor object.
228 var modules
= inspect
.getLoadedModules().map( function ( module
) {
231 size
: inspect
.getModuleSize( module
)
235 // Sort module descriptors by size, largest first.
236 sortByProperty( modules
, 'size', true );
238 // Convert size to human-readable string.
239 modules
.forEach( function ( module
) {
240 module
.sizeInBytes
= module
.size
;
241 module
.size
= humanSize( module
.size
);
248 * For each module with styles, count the number of selectors, and
249 * count how many match against some element currently in the DOM.
251 * @return {Object[]} CSS reports
256 inspect
.getLoadedModules().forEach( function ( name
) {
257 var css
, stats
, module
= mw
.loader
.moduleRegistry
[ name
];
260 css
= module
.style
.css
.join();
261 } catch ( e
) { return; } // skip
263 stats
= inspect
.auditSelectors( css
);
266 allSelectors
: stats
.total
,
267 matchedSelectors
: stats
.matched
,
268 percentMatched
: stats
.total
!== 0 ?
269 ( stats
.matched
/ stats
.total
* 100 ).toFixed( 2 ) + '%' : null
272 sortByProperty( modules
, 'allSelectors', true );
277 * Report stats on mw.loader.store: the number of localStorage
278 * cache hits and misses, the number of items purged from the
279 * cache, and the total size of the module blob in localStorage.
281 * @return {Object[]} Store stats
284 var raw
, stats
= { enabled
: mw
.loader
.store
.enabled
};
285 if ( stats
.enabled
) {
286 $.extend( stats
, mw
.loader
.store
.stats
);
288 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
289 stats
.totalSizeInBytes
= byteLength( raw
);
290 stats
.totalSize
= humanSize( byteLength( raw
) );
298 * Perform a string search across the JavaScript and CSS source code
299 * of all loaded modules and return an array of the names of the
300 * modules that matched.
302 * @param {string|RegExp} pattern String or regexp to match.
303 * @return {Array} Array of the names of modules that matched.
305 grep: function ( pattern
) {
306 if ( typeof pattern
.test
!== 'function' ) {
307 pattern
= new RegExp( mw
.RegExp
.escape( pattern
), 'g' );
310 return inspect
.getLoadedModules().filter( function ( moduleName
) {
311 var module
= mw
.loader
.moduleRegistry
[ moduleName
];
313 // Grep module's JavaScript
314 if ( $.isFunction( module
.script
) && pattern
.test( module
.script
.toString() ) ) {
320 $.isPlainObject( module
.style
) && Array
.isArray( module
.style
.css
) &&
321 pattern
.test( module
.style
.css
.join( '' ) )
323 // Module's CSS source matches
332 if ( mw
.config
.get( 'debug' ) ) {
333 mw
.log( 'mw.inspect: reports are not available in debug mode.' );
336 mw
.inspect
= inspect
;
338 }( mediaWiki
, jQuery
) );