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 ( mw
.loader
.getState( moduleName
) !== 'ready' ) {
82 if ( !module
.style
&& !module
.script
) {
86 // Reverse-engineer the load.php response for this module.
87 // For example: `mw.loader.implement("example", function(){}, );`
88 // @see mw.loader.store.set().
90 JSON
.stringify( moduleName
),
91 // function, array of urls, or eval string
92 typeof module
.script
=== 'function' ?
93 String( module
.script
) :
94 JSON
.stringify( module
.script
),
95 JSON
.stringify( module
.style
),
96 JSON
.stringify( module
.messages
),
97 JSON
.stringify( module
.templates
)
99 // Trim trailing null or empty object, as load.php would have done.
100 // @see ResourceLoader::makeLoaderImplementScript and ResourceLoader::trimArray.
103 if ( args
[ i
] === '{}' || args
[ i
] === 'null' ) {
110 return $.byteLength( args
.join( ',' ) );
114 * Given CSS source, count both the total number of selectors it
115 * contains and the number which match some element in the current
118 * @param {string} css CSS source
119 * @return {Object} Selector counts
120 * @return {number} return.selectors Total number of selectors
121 * @return {number} return.matched Number of matched selectors
123 auditSelectors: function ( css
) {
124 var selectors
= { total
: 0, matched
: 0 },
125 style
= document
.createElement( 'style' );
127 style
.textContent
= css
;
128 document
.body
.appendChild( style
);
129 $.each( style
.sheet
.cssRules
, function ( index
, rule
) {
131 // document.querySelector() on prefixed pseudo-elements can throw exceptions
132 // in Firefox and Safari. Ignore these exceptions.
133 // https://bugs.webkit.org/show_bug.cgi?id=149160
134 // https://bugzilla.mozilla.org/show_bug.cgi?id=1204880
136 if ( document
.querySelector( rule
.selectorText
) !== null ) {
141 document
.body
.removeChild( style
);
146 * Get a list of all loaded ResourceLoader modules.
148 * @return {Array} List of module names
150 getLoadedModules: function () {
151 return $.grep( mw
.loader
.getModuleNames(), function ( module
) {
152 return mw
.loader
.getState( module
) === 'ready';
157 * Print tabular data to the console, using console.table, console.log,
158 * or mw.log (in declining order of preference).
160 * @param {Array} data Tabular data represented as an array of objects
161 * with common properties.
163 dumpTable: function ( data
) {
165 // Bartosz made me put this here.
166 if ( window
.opera
) { throw window
.opera
; }
167 // Use Function.prototype#call to force an exception on Firefox,
168 // which doesn't define console#table but doesn't complain if you
170 console
.table
.call( console
, data
);
174 console
.log( JSON
.stringify( data
, null, 2 ) );
181 * Generate and print one more reports. When invoked with no arguments,
184 * @param {...string} [reports] Report names to run, or unset to print
185 * all available reports.
187 runReports: function () {
188 var reports
= arguments
.length
> 0 ?
189 Array
.prototype.slice
.call( arguments
) :
190 $.map( inspect
.reports
, function ( v
, k
) { return k
; } );
192 $.each( reports
, function ( index
, name
) {
193 inspect
.dumpTable( inspect
.reports
[ name
]() );
198 * @class mw.inspect.reports
203 * Generate a breakdown of all loaded modules and their size in
204 * kilobytes. Modules are ordered from largest to smallest.
206 * @return {Object[]} Size reports
209 // Map each module to a descriptor object.
210 var modules
= $.map( inspect
.getLoadedModules(), function ( module
) {
213 size
: inspect
.getModuleSize( module
)
217 // Sort module descriptors by size, largest first.
218 sortByProperty( modules
, 'size', true );
220 // Convert size to human-readable string.
221 $.each( modules
, function ( i
, module
) {
222 module
.sizeInBytes
= module
.size
;
223 module
.size
= humanSize( module
.size
);
230 * For each module with styles, count the number of selectors, and
231 * count how many match against some element currently in the DOM.
233 * @return {Object[]} CSS reports
238 $.each( inspect
.getLoadedModules(), function ( index
, name
) {
239 var css
, stats
, module
= mw
.loader
.moduleRegistry
[ name
];
242 css
= module
.style
.css
.join();
243 } catch ( e
) { return; } // skip
245 stats
= inspect
.auditSelectors( css
);
248 allSelectors
: stats
.total
,
249 matchedSelectors
: stats
.matched
,
250 percentMatched
: stats
.total
!== 0 ?
251 ( stats
.matched
/ stats
.total
* 100 ).toFixed( 2 ) + '%' : null
254 sortByProperty( modules
, 'allSelectors', true );
259 * Report stats on mw.loader.store: the number of localStorage
260 * cache hits and misses, the number of items purged from the
261 * cache, and the total size of the module blob in localStorage.
263 * @return {Object[]} Store stats
266 var raw
, stats
= { enabled
: mw
.loader
.store
.enabled
};
267 if ( stats
.enabled
) {
268 $.extend( stats
, mw
.loader
.store
.stats
);
270 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
271 stats
.totalSizeInBytes
= $.byteLength( raw
);
272 stats
.totalSize
= humanSize( $.byteLength( raw
) );
280 * Perform a string search across the JavaScript and CSS source code
281 * of all loaded modules and return an array of the names of the
282 * modules that matched.
284 * @param {string|RegExp} pattern String or regexp to match.
285 * @return {Array} Array of the names of modules that matched.
287 grep: function ( pattern
) {
288 if ( typeof pattern
.test
!== 'function' ) {
289 pattern
= new RegExp( mw
.RegExp
.escape( pattern
), 'g' );
292 return $.grep( inspect
.getLoadedModules(), function ( moduleName
) {
293 var module
= mw
.loader
.moduleRegistry
[ moduleName
];
295 // Grep module's JavaScript
296 if ( $.isFunction( module
.script
) && pattern
.test( module
.script
.toString() ) ) {
302 $.isPlainObject( module
.style
) && $.isArray( module
.style
.css
) &&
303 pattern
.test( module
.style
.css
.join( '' ) )
305 // Module's CSS source matches
314 if ( mw
.config
.get( 'debug' ) ) {
315 mw
.log( 'mw.inspect: reports are not available in debug mode.' );
318 mw
.inspect
= inspect
;
320 }( mediaWiki
, jQuery
) );