2 * Tools for inspecting page composition and performance.
11 hasOwn
= Object
.prototype.hasOwnProperty
;
13 function sortByProperty( array
, prop
, descending
) {
14 var order
= descending
? -1 : 1;
15 return array
.sort( function ( a
, b
) {
16 return a
[prop
] > b
[prop
] ? order
: a
[prop
] < b
[prop
] ? -order
: 0;
20 function humanSize( bytes
) {
21 if ( !$.isNumeric( bytes
) || bytes
=== 0 ) { return bytes
; }
22 var i
= 0, units
= [ '', ' kB', ' MB', ' GB', ' TB', ' PB' ];
23 for ( ; bytes
>= 1024; bytes
/= 1024 ) { i
++; }
24 // Maintain one decimal for kB and above, but don't
25 // add ".0" for bytes.
26 return bytes
.toFixed( i
> 0 ? 1 : 0 ) + units
[i
];
36 * Return a map of all dependency relationships between loaded modules.
38 * @return {Object} Maps module names to objects. Each sub-object has
39 * two properties, 'requires' and 'requiredBy'.
41 getDependencyGraph: function () {
42 var modules
= inspect
.getLoadedModules(), graph
= {};
44 $.each( modules
, function ( moduleIndex
, moduleName
) {
45 var dependencies
= mw
.loader
.moduleRegistry
[moduleName
].dependencies
|| [];
47 if ( !hasOwn
.call( graph
, moduleName
) ) {
48 graph
[moduleName
] = { requiredBy
: [] };
50 graph
[moduleName
].requires
= dependencies
;
52 $.each( dependencies
, function ( depIndex
, depName
) {
53 if ( !hasOwn
.call( graph
, depName
) ) {
54 graph
[depName
] = { requiredBy
: [] };
56 graph
[depName
].requiredBy
.push( moduleName
);
63 * Calculate the byte size of a ResourceLoader module.
65 * @param {string} moduleName The name of the module
66 * @return {number|null} Module size in bytes or null
68 getModuleSize: function ( moduleName
) {
69 var module
= mw
.loader
.moduleRegistry
[ moduleName
],
72 if ( mw
.loader
.getState( moduleName
) !== 'ready' ) {
76 if ( !module
.style
&& !module
.script
) {
81 if ( module
.style
&& $.isArray( module
.style
.css
) ) {
82 $.each( module
.style
.css
, function ( i
, stylesheet
) {
83 payload
+= $.byteLength( stylesheet
);
88 if ( $.isFunction( module
.script
) ) {
89 payload
+= $.byteLength( module
.script
.toString() );
96 * Given CSS source, count both the total number of selectors it
97 * contains and the number which match some element in the current
100 * @param {string} css CSS source
101 * @return Selector counts
102 * @return {number} return.selectors Total number of selectors
103 * @return {number} return.matched Number of matched selectors
105 auditSelectors: function ( css
) {
106 var selectors
= { total
: 0, matched
: 0 },
107 style
= document
.createElement( 'style' ),
110 style
.textContent
= css
;
111 document
.body
.appendChild( style
);
112 // Standards-compliant browsers use .sheet.cssRules, IE8 uses .styleSheet.rules…
113 sheet
= style
.sheet
|| style
.styleSheet
;
114 rules
= sheet
.cssRules
|| sheet
.rules
;
115 $.each( rules
, function ( index
, rule
) {
117 if ( document
.querySelector( rule
.selectorText
) !== null ) {
121 document
.body
.removeChild( style
);
126 * Get a list of all loaded ResourceLoader modules.
128 * @return {Array} List of module names
130 getLoadedModules: function () {
131 return $.grep( mw
.loader
.getModuleNames(), function ( module
) {
132 return mw
.loader
.getState( module
) === 'ready';
137 * Print tabular data to the console, using console.table, console.log,
138 * or mw.log (in declining order of preference).
140 * @param {Array} data Tabular data represented as an array of objects
141 * with common properties.
143 dumpTable: function ( data
) {
145 // Bartosz made me put this here.
146 if ( window
.opera
) { throw window
.opera
; }
147 // Use Function.prototype#call to force an exception on Firefox,
148 // which doesn't define console#table but doesn't complain if you
150 console
.table
.call( console
, data
);
154 console
.log( JSON
.stringify( data
, null, 2 ) );
161 * Generate and print one more reports. When invoked with no arguments,
164 * @param {string...} [reports] Report names to run, or unset to print
165 * all available reports.
167 runReports: function () {
168 var reports
= arguments
.length
> 0 ?
169 Array
.prototype.slice
.call( arguments
) :
170 $.map( inspect
.reports
, function ( v
, k
) { return k
; } );
172 $.each( reports
, function ( index
, name
) {
173 inspect
.dumpTable( inspect
.reports
[name
]() );
178 * @class mw.inspect.reports
183 * Generate a breakdown of all loaded modules and their size in
184 * kilobytes. Modules are ordered from largest to smallest.
187 // Map each module to a descriptor object.
188 var modules
= $.map( inspect
.getLoadedModules(), function ( module
) {
191 size
: inspect
.getModuleSize( module
)
195 // Sort module descriptors by size, largest first.
196 sortByProperty( modules
, 'size', true );
198 // Convert size to human-readable string.
199 $.each( modules
, function ( i
, module
) {
200 module
.size
= humanSize( module
.size
);
207 * For each module with styles, count the number of selectors, and
208 * count how many match against some element currently in the DOM.
213 $.each( inspect
.getLoadedModules(), function ( index
, name
) {
214 var css
, stats
, module
= mw
.loader
.moduleRegistry
[name
];
217 css
= module
.style
.css
.join();
218 } catch ( e
) { return; } // skip
220 stats
= inspect
.auditSelectors( css
);
223 allSelectors
: stats
.total
,
224 matchedSelectors
: stats
.matched
,
225 percentMatched
: stats
.total
!== 0 ?
226 ( stats
.matched
/ stats
.total
* 100 ).toFixed( 2 ) + '%' : null
229 sortByProperty( modules
, 'allSelectors', true );
234 * Report stats on mw.loader.store: the number of localStorage
235 * cache hits and misses, the number of items purged from the
236 * cache, and the total size of the module blob in localStorage.
239 var raw
, stats
= { enabled
: mw
.loader
.store
.enabled
};
240 if ( stats
.enabled
) {
241 $.extend( stats
, mw
.loader
.store
.stats
);
243 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
244 stats
.totalSize
= humanSize( $.byteLength( raw
) );
252 * Perform a string search across the JavaScript and CSS source code
253 * of all loaded modules and return an array of the names of the
254 * modules that matched.
256 * @param {string|RegExp} pattern String or regexp to match.
257 * @return {Array} Array of the names of modules that matched.
259 grep: function ( pattern
) {
260 if ( typeof pattern
.test
!== 'function' ) {
261 // Based on Y.Escape.regex from YUI v3.15.0
262 pattern
= new RegExp( pattern
.replace( /[\-$\^*()+\[\]{}|\\,.?\s]/g, '\\$&' ), 'g' );
265 return $.grep( inspect
.getLoadedModules(), function ( moduleName
) {
266 var module
= mw
.loader
.moduleRegistry
[moduleName
];
268 // Grep module's JavaScript
269 if ( $.isFunction( module
.script
) && pattern
.test( module
.script
.toString() ) ) {
275 $.isPlainObject( module
.style
) && $.isArray( module
.style
.css
)
276 && pattern
.test( module
.style
.css
.join( '' ) )
278 // Module's CSS source matches
287 if ( mw
.config
.get( 'debug' ) ) {
288 mw
.log( 'mw.inspect: reports are not available in debug mode.' );
291 mw
.inspect
= inspect
;
293 }( mediaWiki
, jQuery
) );