f4545dee0f626ff1fba6ff9cae91e890dcfdf9b7
[lhc/web/wiklou.git] / resources / src / mediawiki.inspect.js
1 /*!
2 * The mediawiki.inspect module.
3 *
4 * @author Ori Livneh
5 * @since 1.22
6 */
7
8 /* eslint-disable no-console */
9
10 ( function ( mw, $ ) {
11
12 // mw.inspect is a singleton class with static methods
13 // that itself can also be invoked as a function (mediawiki.base/mw#inspect).
14 // In JavaScript, that is implemented by starting with a function,
15 // and subsequently setting additional properties on the function object.
16
17 /**
18 * Tools for inspecting page composition and performance.
19 *
20 * @class mw.inspect
21 * @singleton
22 */
23
24 var inspect = mw.inspect,
25 byteLength = require( 'mediawiki.String' ).byteLength,
26 hasOwn = Object.prototype.hasOwnProperty;
27
28 function sortByProperty( array, prop, descending ) {
29 var order = descending ? -1 : 1;
30 return array.sort( function ( a, b ) {
31 if ( a[ prop ] === undefined || b[ prop ] === undefined ) {
32 // Sort undefined to the end, regardless of direction
33 return a[ prop ] !== undefined ? -1 : b[ prop ] !== undefined ? 1 : 0;
34 }
35 return a[ prop ] > b[ prop ] ? order : a[ prop ] < b[ prop ] ? -order : 0;
36 } );
37 }
38
39 function humanSize( bytes ) {
40 var i,
41 units = [ '', ' KiB', ' MiB', ' GiB', ' TiB', ' PiB' ];
42
43 if ( !$.isNumeric( bytes ) || bytes === 0 ) { return bytes; }
44
45 for ( i = 0; bytes >= 1024; bytes /= 1024 ) { i++; }
46 // Maintain one decimal for kB and above, but don't
47 // add ".0" for bytes.
48 return bytes.toFixed( i > 0 ? 1 : 0 ) + units[ i ];
49 }
50
51 /**
52 * Return a map of all dependency relationships between loaded modules.
53 *
54 * @return {Object} Maps module names to objects. Each sub-object has
55 * two properties, 'requires' and 'requiredBy'.
56 */
57 inspect.getDependencyGraph = function () {
58 var modules = inspect.getLoadedModules(),
59 graph = {};
60
61 modules.forEach( function ( moduleName ) {
62 var dependencies = mw.loader.moduleRegistry[ moduleName ].dependencies || [];
63
64 if ( !hasOwn.call( graph, moduleName ) ) {
65 graph[ moduleName ] = { requiredBy: [] };
66 }
67 graph[ moduleName ].requires = dependencies;
68
69 dependencies.forEach( function ( depName ) {
70 if ( !hasOwn.call( graph, depName ) ) {
71 graph[ depName ] = { requiredBy: [] };
72 }
73 graph[ depName ].requiredBy.push( moduleName );
74 } );
75 } );
76 return graph;
77 };
78
79 /**
80 * Calculate the byte size of a ResourceLoader module.
81 *
82 * @param {string} moduleName The name of the module
83 * @return {number|null} Module size in bytes or null
84 */
85 inspect.getModuleSize = function ( moduleName ) {
86 var module = mw.loader.moduleRegistry[ moduleName ],
87 args, i, size;
88
89 if ( module.state !== 'ready' ) {
90 return null;
91 }
92
93 if ( !module.style && !module.script ) {
94 return 0;
95 }
96
97 function getFunctionBody( func ) {
98 return String( func )
99 // To ensure a deterministic result, replace the start of the function
100 // declaration with a fixed string. For example, in Chrome 55, it seems
101 // V8 seemingly-at-random decides to sometimes put a line break between
102 // the opening brace and first statement of the function body. T159751.
103 .replace( /^\s*function\s*\([^)]*\)\s*{\s*/, 'function(){' )
104 .replace( /\s*}\s*$/, '}' );
105 }
106
107 // Based on the load.php response for this module.
108 // For example: `mw.loader.implement("example", function(){}, {"css":[".x{color:red}"]});`
109 // @see mw.loader.store.set().
110 args = [
111 moduleName,
112 module.script,
113 module.style,
114 module.messages,
115 module.templates
116 ];
117 // Trim trailing null or empty object, as load.php would have done.
118 // @see ResourceLoader::makeLoaderImplementScript and ResourceLoader::trimArray.
119 i = args.length;
120 while ( i-- ) {
121 if ( args[ i ] === null || ( $.isPlainObject( args[ i ] ) && $.isEmptyObject( args[ i ] ) ) ) {
122 args.splice( i, 1 );
123 } else {
124 break;
125 }
126 }
127
128 size = 0;
129 for ( i = 0; i < args.length; i++ ) {
130 if ( typeof args[ i ] === 'function' ) {
131 size += byteLength( getFunctionBody( args[ i ] ) );
132 } else {
133 size += byteLength( JSON.stringify( args[ i ] ) );
134 }
135 }
136
137 return size;
138 };
139
140 /**
141 * Given CSS source, count both the total number of selectors it
142 * contains and the number which match some element in the current
143 * document.
144 *
145 * @param {string} css CSS source
146 * @return {Object} Selector counts
147 * @return {number} return.selectors Total number of selectors
148 * @return {number} return.matched Number of matched selectors
149 */
150 inspect.auditSelectors = function ( css ) {
151 var selectors = { total: 0, matched: 0 },
152 style = document.createElement( 'style' );
153
154 style.textContent = css;
155 document.body.appendChild( style );
156 $.each( style.sheet.cssRules, function ( index, rule ) {
157 selectors.total++;
158 // document.querySelector() on prefixed pseudo-elements can throw exceptions
159 // in Firefox and Safari. Ignore these exceptions.
160 // https://bugs.webkit.org/show_bug.cgi?id=149160
161 // https://bugzilla.mozilla.org/show_bug.cgi?id=1204880
162 try {
163 if ( document.querySelector( rule.selectorText ) !== null ) {
164 selectors.matched++;
165 }
166 } catch ( e ) {}
167 } );
168 document.body.removeChild( style );
169 return selectors;
170 };
171
172 /**
173 * Get a list of all loaded ResourceLoader modules.
174 *
175 * @return {Array} List of module names
176 */
177 inspect.getLoadedModules = function () {
178 return mw.loader.getModuleNames().filter( function ( module ) {
179 return mw.loader.getState( module ) === 'ready';
180 } );
181 };
182
183 /**
184 * Print tabular data to the console, using console.table, console.log,
185 * or mw.log (in declining order of preference).
186 *
187 * @param {Array} data Tabular data represented as an array of objects
188 * with common properties.
189 */
190 inspect.dumpTable = function ( data ) {
191 try {
192 // Use Function.prototype#call to force an exception on Firefox,
193 // which doesn't define console#table but doesn't complain if you
194 // try to invoke it.
195 // eslint-disable-next-line no-useless-call
196 console.table.call( console, data );
197 return;
198 } catch ( e ) {}
199 try {
200 console.log( JSON.stringify( data, null, 2 ) );
201 } catch ( e ) {}
202 };
203
204 /**
205 * Generate and print reports.
206 *
207 * When invoked without arguments, prints all available reports.
208 *
209 * @param {...string} [reports] One or more of "size", "css", "store", or "time".
210 */
211 inspect.runReports = function () {
212 var reports = arguments.length > 0 ?
213 Array.prototype.slice.call( arguments ) :
214 Object.keys( inspect.reports );
215
216 reports.forEach( function ( name ) {
217 if ( console.group ) {
218 console.group( 'mw.inspect ' + name + ' report' );
219 } else {
220 console.log( 'mw.inspect ' + name + ' report' );
221 }
222 inspect.dumpTable( inspect.reports[ name ]() );
223 if ( console.group ) {
224 console.groupEnd( 'mw.inspect ' + name + ' report' );
225 }
226 } );
227 };
228
229 /**
230 * Perform a string search across the JavaScript and CSS source code
231 * of all loaded modules and return an array of the names of the
232 * modules that matched.
233 *
234 * @param {string|RegExp} pattern String or regexp to match.
235 * @return {Array} Array of the names of modules that matched.
236 */
237 inspect.grep = function ( pattern ) {
238 if ( typeof pattern.test !== 'function' ) {
239 pattern = new RegExp( mw.RegExp.escape( pattern ), 'g' );
240 }
241
242 return inspect.getLoadedModules().filter( function ( moduleName ) {
243 var module = mw.loader.moduleRegistry[ moduleName ];
244
245 // Grep module's JavaScript
246 if ( typeof module.script === 'function' && pattern.test( module.script.toString() ) ) {
247 return true;
248 }
249
250 // Grep module's CSS
251 if (
252 $.isPlainObject( module.style ) && Array.isArray( module.style.css ) &&
253 pattern.test( module.style.css.join( '' ) )
254 ) {
255 // Module's CSS source matches
256 return true;
257 }
258
259 return false;
260 } );
261 };
262
263 /**
264 * @private
265 * @class mw.inspect.reports
266 * @singleton
267 */
268 inspect.reports = {
269 /**
270 * Generate a breakdown of all loaded modules and their size in
271 * kilobytes. Modules are ordered from largest to smallest.
272 *
273 * @return {Object[]} Size reports
274 */
275 size: function () {
276 // Map each module to a descriptor object.
277 var modules = inspect.getLoadedModules().map( function ( module ) {
278 return {
279 name: module,
280 size: inspect.getModuleSize( module )
281 };
282 } );
283
284 // Sort module descriptors by size, largest first.
285 sortByProperty( modules, 'size', true );
286
287 // Convert size to human-readable string.
288 modules.forEach( function ( module ) {
289 module.sizeInBytes = module.size;
290 module.size = humanSize( module.size );
291 } );
292
293 return modules;
294 },
295
296 /**
297 * For each module with styles, count the number of selectors, and
298 * count how many match against some element currently in the DOM.
299 *
300 * @return {Object[]} CSS reports
301 */
302 css: function () {
303 var modules = [];
304
305 inspect.getLoadedModules().forEach( function ( name ) {
306 var css, stats, module = mw.loader.moduleRegistry[ name ];
307
308 try {
309 css = module.style.css.join();
310 } catch ( e ) { return; } // skip
311
312 stats = inspect.auditSelectors( css );
313 modules.push( {
314 module: name,
315 allSelectors: stats.total,
316 matchedSelectors: stats.matched,
317 percentMatched: stats.total !== 0 ?
318 ( stats.matched / stats.total * 100 ).toFixed( 2 ) + '%' : null
319 } );
320 } );
321 sortByProperty( modules, 'allSelectors', true );
322 return modules;
323 },
324
325 /**
326 * Report stats on mw.loader.store: the number of localStorage
327 * cache hits and misses, the number of items purged from the
328 * cache, and the total size of the module blob in localStorage.
329 *
330 * @return {Object[]} Store stats
331 */
332 store: function () {
333 var raw, stats = { enabled: mw.loader.store.enabled };
334 if ( stats.enabled ) {
335 $.extend( stats, mw.loader.store.stats );
336 try {
337 raw = localStorage.getItem( mw.loader.store.getStoreKey() );
338 stats.totalSizeInBytes = byteLength( raw );
339 stats.totalSize = humanSize( byteLength( raw ) );
340 } catch ( e ) {}
341 }
342 return [ stats ];
343 },
344
345 /**
346 * Generate a breakdown of all loaded modules and their time
347 * spent during initialisation (measured in milliseconds).
348 *
349 * This timing data is collected by mw.loader.profiler.
350 *
351 * @return {Object[]} Table rows
352 */
353 time: function () {
354 var modules;
355
356 if ( !mw.loader.profiler ) {
357 mw.log.warn( 'mw.inspect: The time report requires $wgResourceLoaderEnableJSProfiler.' );
358 return [];
359 }
360
361 modules = inspect.getLoadedModules()
362 .map( function ( moduleName ) {
363 return mw.loader.profiler.getProfile( moduleName );
364 } )
365 .filter( function ( perf ) {
366 // Exclude modules that reached "ready" state without involvement from mw.loader.
367 // This is primarily styles-only as loaded via <link rel="stylesheet">.
368 return perf !== null;
369 } );
370
371 // Sort by total time spent, highest first.
372 sortByProperty( modules, 'total', true );
373
374 // Add human-readable strings
375 modules.forEach( function ( module ) {
376 module.totalInMs = module.total;
377 module.total = module.totalInMs.toLocaleString() + ' ms';
378 } );
379
380 return modules;
381 }
382 };
383
384 if ( mw.config.get( 'debug' ) ) {
385 mw.log( 'mw.inspect: reports are not available in debug mode.' );
386 }
387
388 }( mediaWiki, jQuery ) );