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