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 modules
.forEach( function ( 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 mw
.loader
.getModuleNames().filter( 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 // eslint-disable-next-line no-useless-call
187 console
.table
.call( console
, data
);
191 console
.log( JSON
.stringify( data
, null, 2 ) );
198 * Generate and print one more reports. When invoked with no arguments,
201 * @param {...string} [reports] Report names to run, or unset to print
202 * all available reports.
204 runReports: function () {
205 var reports
= arguments
.length
> 0 ?
206 Array
.prototype.slice
.call( arguments
) :
207 $.map( inspect
.reports
, function ( v
, k
) { return k
; } );
209 reports
.forEach( function ( name
) {
210 inspect
.dumpTable( inspect
.reports
[ name
]() );
215 * @class mw.inspect.reports
220 * Generate a breakdown of all loaded modules and their size in
221 * kilobytes. Modules are ordered from largest to smallest.
223 * @return {Object[]} Size reports
226 // Map each module to a descriptor object.
227 var modules
= inspect
.getLoadedModules().map( function ( module
) {
230 size
: inspect
.getModuleSize( module
)
234 // Sort module descriptors by size, largest first.
235 sortByProperty( modules
, 'size', true );
237 // Convert size to human-readable string.
238 modules
.forEach( function ( module
) {
239 module
.sizeInBytes
= module
.size
;
240 module
.size
= humanSize( module
.size
);
247 * For each module with styles, count the number of selectors, and
248 * count how many match against some element currently in the DOM.
250 * @return {Object[]} CSS reports
255 inspect
.getLoadedModules().forEach( function ( name
) {
256 var css
, stats
, module
= mw
.loader
.moduleRegistry
[ name
];
259 css
= module
.style
.css
.join();
260 } catch ( e
) { return; } // skip
262 stats
= inspect
.auditSelectors( css
);
265 allSelectors
: stats
.total
,
266 matchedSelectors
: stats
.matched
,
267 percentMatched
: stats
.total
!== 0 ?
268 ( stats
.matched
/ stats
.total
* 100 ).toFixed( 2 ) + '%' : null
271 sortByProperty( modules
, 'allSelectors', true );
276 * Report stats on mw.loader.store: the number of localStorage
277 * cache hits and misses, the number of items purged from the
278 * cache, and the total size of the module blob in localStorage.
280 * @return {Object[]} Store stats
283 var raw
, stats
= { enabled
: mw
.loader
.store
.enabled
};
284 if ( stats
.enabled
) {
285 $.extend( stats
, mw
.loader
.store
.stats
);
287 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
288 stats
.totalSizeInBytes
= $.byteLength( raw
);
289 stats
.totalSize
= humanSize( $.byteLength( raw
) );
297 * Perform a string search across the JavaScript and CSS source code
298 * of all loaded modules and return an array of the names of the
299 * modules that matched.
301 * @param {string|RegExp} pattern String or regexp to match.
302 * @return {Array} Array of the names of modules that matched.
304 grep: function ( pattern
) {
305 if ( typeof pattern
.test
!== 'function' ) {
306 pattern
= new RegExp( mw
.RegExp
.escape( pattern
), 'g' );
309 return inspect
.getLoadedModules().filter( function ( moduleName
) {
310 var module
= mw
.loader
.moduleRegistry
[ moduleName
];
312 // Grep module's JavaScript
313 if ( $.isFunction( module
.script
) && pattern
.test( module
.script
.toString() ) ) {
319 $.isPlainObject( module
.style
) && Array
.isArray( module
.style
.css
) &&
320 pattern
.test( module
.style
.css
.join( '' ) )
322 // Module's CSS source matches
331 if ( mw
.config
.get( 'debug' ) ) {
332 mw
.log( 'mw.inspect: reports are not available in debug mode.' );
335 mw
.inspect
= inspect
;
337 }( mediaWiki
, jQuery
) );