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