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