mw.inspect: Include templates and messages in size
[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
8 /* eslint-disable no-console */
9
10 ( function ( mw, $ ) {
11
12 var inspect,
13 hasOwn = Object.prototype.hasOwnProperty;
14
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;
19 } );
20 }
21
22 function humanSize( bytes ) {
23 var i,
24 units = [ '', ' KiB', ' MiB', ' GiB', ' TiB', ' PiB' ];
25
26 if ( !$.isNumeric( bytes ) || bytes === 0 ) { return bytes; }
27
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 ];
32 }
33
34 /**
35 * @class mw.inspect
36 * @singleton
37 */
38 inspect = {
39
40 /**
41 * Return a map of all dependency relationships between loaded modules.
42 *
43 * @return {Object} Maps module names to objects. Each sub-object has
44 * two properties, 'requires' and 'requiredBy'.
45 */
46 getDependencyGraph: function () {
47 var modules = inspect.getLoadedModules(),
48 graph = {};
49
50 $.each( modules, function ( moduleIndex, moduleName ) {
51 var dependencies = mw.loader.moduleRegistry[ moduleName ].dependencies || [];
52
53 if ( !hasOwn.call( graph, moduleName ) ) {
54 graph[ moduleName ] = { requiredBy: [] };
55 }
56 graph[ moduleName ].requires = dependencies;
57
58 $.each( dependencies, function ( depIndex, depName ) {
59 if ( !hasOwn.call( graph, depName ) ) {
60 graph[ depName ] = { requiredBy: [] };
61 }
62 graph[ depName ].requiredBy.push( moduleName );
63 } );
64 } );
65 return graph;
66 },
67
68 /**
69 * Calculate the byte size of a ResourceLoader module.
70 *
71 * @param {string} moduleName The name of the module
72 * @return {number|null} Module size in bytes or null
73 */
74 getModuleSize: function ( moduleName ) {
75 var module = mw.loader.moduleRegistry[ moduleName ],
76 payload = 0;
77
78 if ( mw.loader.getState( moduleName ) !== 'ready' ) {
79 return null;
80 }
81
82 if ( !module.style && !module.script ) {
83 return null;
84 }
85
86 // Tally CSS
87 if ( module.style && $.isArray( module.style.css ) ) {
88 $.each( module.style.css, function ( i, stylesheet ) {
89 payload += $.byteLength( stylesheet );
90 } );
91 }
92
93 // Tally JavaScript
94 if ( $.isFunction( module.script ) ) {
95 payload += $.byteLength( module.script.toString() );
96 }
97
98 // Tally templates and messages. Calculate their JSON size so that keys
99 // are included in the module size - in the case of messages, keys can be
100 // longer than values - and so that empty objects are also included.
101 $.each( [ module.templates, module.messages ], function ( i, object ) {
102 if ( object ) {
103 payload += $.byteLength( JSON.stringify( object ) );
104 }
105 } );
106
107 return payload;
108 },
109
110 /**
111 * Given CSS source, count both the total number of selectors it
112 * contains and the number which match some element in the current
113 * document.
114 *
115 * @param {string} css CSS source
116 * @return {Object} Selector counts
117 * @return {number} return.selectors Total number of selectors
118 * @return {number} return.matched Number of matched selectors
119 */
120 auditSelectors: function ( css ) {
121 var selectors = { total: 0, matched: 0 },
122 style = document.createElement( 'style' );
123
124 style.textContent = css;
125 document.body.appendChild( style );
126 $.each( style.sheet.cssRules, function ( index, rule ) {
127 selectors.total++;
128 // document.querySelector() on prefixed pseudo-elements can throw exceptions
129 // in Firefox and Safari. Ignore these exceptions.
130 // https://bugs.webkit.org/show_bug.cgi?id=149160
131 // https://bugzilla.mozilla.org/show_bug.cgi?id=1204880
132 try {
133 if ( document.querySelector( rule.selectorText ) !== null ) {
134 selectors.matched++;
135 }
136 } catch ( e ) {}
137 } );
138 document.body.removeChild( style );
139 return selectors;
140 },
141
142 /**
143 * Get a list of all loaded ResourceLoader modules.
144 *
145 * @return {Array} List of module names
146 */
147 getLoadedModules: function () {
148 return $.grep( mw.loader.getModuleNames(), function ( module ) {
149 return mw.loader.getState( module ) === 'ready';
150 } );
151 },
152
153 /**
154 * Print tabular data to the console, using console.table, console.log,
155 * or mw.log (in declining order of preference).
156 *
157 * @param {Array} data Tabular data represented as an array of objects
158 * with common properties.
159 */
160 dumpTable: function ( data ) {
161 try {
162 // Bartosz made me put this here.
163 if ( window.opera ) { throw window.opera; }
164 // Use Function.prototype#call to force an exception on Firefox,
165 // which doesn't define console#table but doesn't complain if you
166 // try to invoke it.
167 console.table.call( console, data );
168 return;
169 } catch ( e ) {}
170 try {
171 console.log( JSON.stringify( data, null, 2 ) );
172 return;
173 } catch ( e ) {}
174 mw.log( data );
175 },
176
177 /**
178 * Generate and print one more reports. When invoked with no arguments,
179 * print all reports.
180 *
181 * @param {...string} [reports] Report names to run, or unset to print
182 * all available reports.
183 */
184 runReports: function () {
185 var reports = arguments.length > 0 ?
186 Array.prototype.slice.call( arguments ) :
187 $.map( inspect.reports, function ( v, k ) { return k; } );
188
189 $.each( reports, function ( index, name ) {
190 inspect.dumpTable( inspect.reports[ name ]() );
191 } );
192 },
193
194 /**
195 * @class mw.inspect.reports
196 * @singleton
197 */
198 reports: {
199 /**
200 * Generate a breakdown of all loaded modules and their size in
201 * kilobytes. Modules are ordered from largest to smallest.
202 *
203 * @return {Object[]} Size reports
204 */
205 size: function () {
206 // Map each module to a descriptor object.
207 var modules = $.map( inspect.getLoadedModules(), function ( module ) {
208 return {
209 name: module,
210 size: inspect.getModuleSize( module )
211 };
212 } );
213
214 // Sort module descriptors by size, largest first.
215 sortByProperty( modules, 'size', true );
216
217 // Convert size to human-readable string.
218 $.each( modules, function ( i, module ) {
219 module.sizeInBytes = module.size;
220 module.size = humanSize( module.size );
221 } );
222
223 return modules;
224 },
225
226 /**
227 * For each module with styles, count the number of selectors, and
228 * count how many match against some element currently in the DOM.
229 *
230 * @return {Object[]} CSS reports
231 */
232 css: function () {
233 var modules = [];
234
235 $.each( inspect.getLoadedModules(), function ( index, name ) {
236 var css, stats, module = mw.loader.moduleRegistry[ name ];
237
238 try {
239 css = module.style.css.join();
240 } catch ( e ) { return; } // skip
241
242 stats = inspect.auditSelectors( css );
243 modules.push( {
244 module: name,
245 allSelectors: stats.total,
246 matchedSelectors: stats.matched,
247 percentMatched: stats.total !== 0 ?
248 ( stats.matched / stats.total * 100 ).toFixed( 2 ) + '%' : null
249 } );
250 } );
251 sortByProperty( modules, 'allSelectors', true );
252 return modules;
253 },
254
255 /**
256 * Report stats on mw.loader.store: the number of localStorage
257 * cache hits and misses, the number of items purged from the
258 * cache, and the total size of the module blob in localStorage.
259 *
260 * @return {Object[]} Store stats
261 */
262 store: function () {
263 var raw, stats = { enabled: mw.loader.store.enabled };
264 if ( stats.enabled ) {
265 $.extend( stats, mw.loader.store.stats );
266 try {
267 raw = localStorage.getItem( mw.loader.store.getStoreKey() );
268 stats.totalSizeInBytes = $.byteLength( raw );
269 stats.totalSize = humanSize( $.byteLength( raw ) );
270 } catch ( e ) {}
271 }
272 return [ stats ];
273 }
274 },
275
276 /**
277 * Perform a string search across the JavaScript and CSS source code
278 * of all loaded modules and return an array of the names of the
279 * modules that matched.
280 *
281 * @param {string|RegExp} pattern String or regexp to match.
282 * @return {Array} Array of the names of modules that matched.
283 */
284 grep: function ( pattern ) {
285 if ( typeof pattern.test !== 'function' ) {
286 pattern = new RegExp( mw.RegExp.escape( pattern ), 'g' );
287 }
288
289 return $.grep( inspect.getLoadedModules(), function ( moduleName ) {
290 var module = mw.loader.moduleRegistry[ moduleName ];
291
292 // Grep module's JavaScript
293 if ( $.isFunction( module.script ) && pattern.test( module.script.toString() ) ) {
294 return true;
295 }
296
297 // Grep module's CSS
298 if (
299 $.isPlainObject( module.style ) && $.isArray( module.style.css ) &&
300 pattern.test( module.style.css.join( '' ) )
301 ) {
302 // Module's CSS source matches
303 return true;
304 }
305
306 return false;
307 } );
308 }
309 };
310
311 if ( mw.config.get( 'debug' ) ) {
312 mw.log( 'mw.inspect: reports are not available in debug mode.' );
313 }
314
315 mw.inspect = inspect;
316
317 }( mediaWiki, jQuery ) );