mediawiki.inspect: Use fixed numbers for sizes in bytes
[lhc/web/wiklou.git] / resources / src / mediawiki / mediawiki.inspect.js
1 /*!
2 * Tools for inspecting page composition and performance.
3 *
4 * @author Ori Livneh
5 * @since 1.22
6 */
7 /*jshint devel:true */
8 ( function ( mw, $ ) {
9
10 var inspect,
11 hasOwn = Object.prototype.hasOwnProperty;
12
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;
17 } );
18 }
19
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];
27 }
28
29 /**
30 * @class mw.inspect
31 * @singleton
32 */
33 inspect = {
34
35 /**
36 * Return a map of all dependency relationships between loaded modules.
37 *
38 * @return {Object} Maps module names to objects. Each sub-object has
39 * two properties, 'requires' and 'requiredBy'.
40 */
41 getDependencyGraph: function () {
42 var modules = inspect.getLoadedModules(), graph = {};
43
44 $.each( modules, function ( moduleIndex, moduleName ) {
45 var dependencies = mw.loader.moduleRegistry[moduleName].dependencies || [];
46
47 if ( !hasOwn.call( graph, moduleName ) ) {
48 graph[moduleName] = { requiredBy: [] };
49 }
50 graph[moduleName].requires = dependencies;
51
52 $.each( dependencies, function ( depIndex, depName ) {
53 if ( !hasOwn.call( graph, depName ) ) {
54 graph[depName] = { requiredBy: [] };
55 }
56 graph[depName].requiredBy.push( moduleName );
57 } );
58 } );
59 return graph;
60 },
61
62 /**
63 * Calculate the byte size of a ResourceLoader module.
64 *
65 * @param {string} moduleName The name of the module
66 * @return {number|null} Module size in bytes or null
67 */
68 getModuleSize: function ( moduleName ) {
69 var module = mw.loader.moduleRegistry[ moduleName ],
70 payload = 0;
71
72 if ( mw.loader.getState( moduleName ) !== 'ready' ) {
73 return null;
74 }
75
76 if ( !module.style && !module.script ) {
77 return null;
78 }
79
80 // Tally CSS
81 if ( module.style && $.isArray( module.style.css ) ) {
82 $.each( module.style.css, function ( i, stylesheet ) {
83 payload += $.byteLength( stylesheet );
84 } );
85 }
86
87 // Tally JavaScript
88 if ( $.isFunction( module.script ) ) {
89 payload += $.byteLength( module.script.toString() );
90 }
91
92 return payload;
93 },
94
95 /**
96 * Given CSS source, count both the total number of selectors it
97 * contains and the number which match some element in the current
98 * document.
99 *
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
104 */
105 auditSelectors: function ( css ) {
106 var selectors = { total: 0, matched: 0 },
107 style = document.createElement( 'style' ),
108 sheet, rules;
109
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 ) {
116 selectors.total++;
117 if ( document.querySelector( rule.selectorText ) !== null ) {
118 selectors.matched++;
119 }
120 } );
121 document.body.removeChild( style );
122 return selectors;
123 },
124
125 /**
126 * Get a list of all loaded ResourceLoader modules.
127 *
128 * @return {Array} List of module names
129 */
130 getLoadedModules: function () {
131 return $.grep( mw.loader.getModuleNames(), function ( module ) {
132 return mw.loader.getState( module ) === 'ready';
133 } );
134 },
135
136 /**
137 * Print tabular data to the console, using console.table, console.log,
138 * or mw.log (in declining order of preference).
139 *
140 * @param {Array} data Tabular data represented as an array of objects
141 * with common properties.
142 */
143 dumpTable: function ( data ) {
144 try {
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
149 // try to invoke it.
150 console.table.call( console, data );
151 return;
152 } catch ( e ) {}
153 try {
154 console.log( JSON.stringify( data, null, 2 ) );
155 return;
156 } catch ( e ) {}
157 mw.log( data );
158 },
159
160 /**
161 * Generate and print one more reports. When invoked with no arguments,
162 * print all reports.
163 *
164 * @param {string...} [reports] Report names to run, or unset to print
165 * all available reports.
166 */
167 runReports: function () {
168 var reports = arguments.length > 0 ?
169 Array.prototype.slice.call( arguments ) :
170 $.map( inspect.reports, function ( v, k ) { return k; } );
171
172 $.each( reports, function ( index, name ) {
173 inspect.dumpTable( inspect.reports[name]() );
174 } );
175 },
176
177 /**
178 * @class mw.inspect.reports
179 * @singleton
180 */
181 reports: {
182 /**
183 * Generate a breakdown of all loaded modules and their size in
184 * kilobytes. Modules are ordered from largest to smallest.
185 */
186 size: function () {
187 // Map each module to a descriptor object.
188 var modules = $.map( inspect.getLoadedModules(), function ( module ) {
189 return {
190 name: module,
191 size: inspect.getModuleSize( module )
192 };
193 } );
194
195 // Sort module descriptors by size, largest first.
196 sortByProperty( modules, 'size', true );
197
198 // Convert size to human-readable string.
199 $.each( modules, function ( i, module ) {
200 module.size = humanSize( module.size );
201 } );
202
203 return modules;
204 },
205
206 /**
207 * For each module with styles, count the number of selectors, and
208 * count how many match against some element currently in the DOM.
209 */
210 css: function () {
211 var modules = [];
212
213 $.each( inspect.getLoadedModules(), function ( index, name ) {
214 var css, stats, module = mw.loader.moduleRegistry[name];
215
216 try {
217 css = module.style.css.join();
218 } catch ( e ) { return; } // skip
219
220 stats = inspect.auditSelectors( css );
221 modules.push( {
222 module: name,
223 allSelectors: stats.total,
224 matchedSelectors: stats.matched,
225 percentMatched: stats.total !== 0 ?
226 ( stats.matched / stats.total * 100 ).toFixed( 2 ) + '%' : null
227 } );
228 } );
229 sortByProperty( modules, 'allSelectors', true );
230 return modules;
231 },
232
233 /**
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.
237 */
238 store: function () {
239 var raw, stats = { enabled: mw.loader.store.enabled };
240 if ( stats.enabled ) {
241 $.extend( stats, mw.loader.store.stats );
242 try {
243 raw = localStorage.getItem( mw.loader.store.getStoreKey() );
244 stats.totalSize = humanSize( $.byteLength( raw ) );
245 } catch ( e ) {}
246 }
247 return [stats];
248 }
249 },
250
251 /**
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.
255 *
256 * @param {string|RegExp} pattern String or regexp to match.
257 * @return {Array} Array of the names of modules that matched.
258 */
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' );
263 }
264
265 return $.grep( inspect.getLoadedModules(), function ( moduleName ) {
266 var module = mw.loader.moduleRegistry[moduleName];
267
268 // Grep module's JavaScript
269 if ( $.isFunction( module.script ) && pattern.test( module.script.toString() ) ) {
270 return true;
271 }
272
273 // Grep module's CSS
274 if (
275 $.isPlainObject( module.style ) && $.isArray( module.style.css )
276 && pattern.test( module.style.css.join( '' ) )
277 ) {
278 // Module's CSS source matches
279 return true;
280 }
281
282 return false;
283 } );
284 }
285 };
286
287 if ( mw.config.get( 'debug' ) ) {
288 mw.log( 'mw.inspect: reports are not available in debug mode.' );
289 }
290
291 mw.inspect = inspect;
292
293 }( mediaWiki, jQuery ) );