Let mw.Api recognize errorformat!=bc
[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 return payload;
99 },
100
101 /**
102 * Given CSS source, count both the total number of selectors it
103 * contains and the number which match some element in the current
104 * document.
105 *
106 * @param {string} css CSS source
107 * @return {Object} Selector counts
108 * @return {number} return.selectors Total number of selectors
109 * @return {number} return.matched Number of matched selectors
110 */
111 auditSelectors: function ( css ) {
112 var selectors = { total: 0, matched: 0 },
113 style = document.createElement( 'style' );
114
115 style.textContent = css;
116 document.body.appendChild( style );
117 $.each( style.sheet.cssRules, function ( index, rule ) {
118 selectors.total++;
119 // document.querySelector() on prefixed pseudo-elements can throw exceptions
120 // in Firefox and Safari. Ignore these exceptions.
121 // https://bugs.webkit.org/show_bug.cgi?id=149160
122 // https://bugzilla.mozilla.org/show_bug.cgi?id=1204880
123 try {
124 if ( document.querySelector( rule.selectorText ) !== null ) {
125 selectors.matched++;
126 }
127 } catch ( e ) {}
128 } );
129 document.body.removeChild( style );
130 return selectors;
131 },
132
133 /**
134 * Get a list of all loaded ResourceLoader modules.
135 *
136 * @return {Array} List of module names
137 */
138 getLoadedModules: function () {
139 return $.grep( mw.loader.getModuleNames(), function ( module ) {
140 return mw.loader.getState( module ) === 'ready';
141 } );
142 },
143
144 /**
145 * Print tabular data to the console, using console.table, console.log,
146 * or mw.log (in declining order of preference).
147 *
148 * @param {Array} data Tabular data represented as an array of objects
149 * with common properties.
150 */
151 dumpTable: function ( data ) {
152 try {
153 // Bartosz made me put this here.
154 if ( window.opera ) { throw window.opera; }
155 // Use Function.prototype#call to force an exception on Firefox,
156 // which doesn't define console#table but doesn't complain if you
157 // try to invoke it.
158 console.table.call( console, data );
159 return;
160 } catch ( e ) {}
161 try {
162 console.log( JSON.stringify( data, null, 2 ) );
163 return;
164 } catch ( e ) {}
165 mw.log( data );
166 },
167
168 /**
169 * Generate and print one more reports. When invoked with no arguments,
170 * print all reports.
171 *
172 * @param {...string} [reports] Report names to run, or unset to print
173 * all available reports.
174 */
175 runReports: function () {
176 var reports = arguments.length > 0 ?
177 Array.prototype.slice.call( arguments ) :
178 $.map( inspect.reports, function ( v, k ) { return k; } );
179
180 $.each( reports, function ( index, name ) {
181 inspect.dumpTable( inspect.reports[ name ]() );
182 } );
183 },
184
185 /**
186 * @class mw.inspect.reports
187 * @singleton
188 */
189 reports: {
190 /**
191 * Generate a breakdown of all loaded modules and their size in
192 * kilobytes. Modules are ordered from largest to smallest.
193 *
194 * @return {Object[]} Size reports
195 */
196 size: function () {
197 // Map each module to a descriptor object.
198 var modules = $.map( inspect.getLoadedModules(), function ( module ) {
199 return {
200 name: module,
201 size: inspect.getModuleSize( module )
202 };
203 } );
204
205 // Sort module descriptors by size, largest first.
206 sortByProperty( modules, 'size', true );
207
208 // Convert size to human-readable string.
209 $.each( modules, function ( i, module ) {
210 module.sizeInBytes = module.size;
211 module.size = humanSize( module.size );
212 } );
213
214 return modules;
215 },
216
217 /**
218 * For each module with styles, count the number of selectors, and
219 * count how many match against some element currently in the DOM.
220 *
221 * @return {Object[]} CSS reports
222 */
223 css: function () {
224 var modules = [];
225
226 $.each( inspect.getLoadedModules(), function ( index, name ) {
227 var css, stats, module = mw.loader.moduleRegistry[ name ];
228
229 try {
230 css = module.style.css.join();
231 } catch ( e ) { return; } // skip
232
233 stats = inspect.auditSelectors( css );
234 modules.push( {
235 module: name,
236 allSelectors: stats.total,
237 matchedSelectors: stats.matched,
238 percentMatched: stats.total !== 0 ?
239 ( stats.matched / stats.total * 100 ).toFixed( 2 ) + '%' : null
240 } );
241 } );
242 sortByProperty( modules, 'allSelectors', true );
243 return modules;
244 },
245
246 /**
247 * Report stats on mw.loader.store: the number of localStorage
248 * cache hits and misses, the number of items purged from the
249 * cache, and the total size of the module blob in localStorage.
250 *
251 * @return {Object[]} Store stats
252 */
253 store: function () {
254 var raw, stats = { enabled: mw.loader.store.enabled };
255 if ( stats.enabled ) {
256 $.extend( stats, mw.loader.store.stats );
257 try {
258 raw = localStorage.getItem( mw.loader.store.getStoreKey() );
259 stats.totalSizeInBytes = $.byteLength( raw );
260 stats.totalSize = humanSize( $.byteLength( raw ) );
261 } catch ( e ) {}
262 }
263 return [ stats ];
264 }
265 },
266
267 /**
268 * Perform a string search across the JavaScript and CSS source code
269 * of all loaded modules and return an array of the names of the
270 * modules that matched.
271 *
272 * @param {string|RegExp} pattern String or regexp to match.
273 * @return {Array} Array of the names of modules that matched.
274 */
275 grep: function ( pattern ) {
276 if ( typeof pattern.test !== 'function' ) {
277 pattern = new RegExp( mw.RegExp.escape( pattern ), 'g' );
278 }
279
280 return $.grep( inspect.getLoadedModules(), function ( moduleName ) {
281 var module = mw.loader.moduleRegistry[ moduleName ];
282
283 // Grep module's JavaScript
284 if ( $.isFunction( module.script ) && pattern.test( module.script.toString() ) ) {
285 return true;
286 }
287
288 // Grep module's CSS
289 if (
290 $.isPlainObject( module.style ) && $.isArray( module.style.css ) &&
291 pattern.test( module.style.css.join( '' ) )
292 ) {
293 // Module's CSS source matches
294 return true;
295 }
296
297 return false;
298 } );
299 }
300 };
301
302 if ( mw.config.get( 'debug' ) ) {
303 mw.log( 'mw.inspect: reports are not available in debug mode.' );
304 }
305
306 mw.inspect = inspect;
307
308 }( mediaWiki, jQuery ) );