Debian Codegraph @

resources/src/mediawiki.api/index.js

raw symbols SCIP
1 ( function () {
2 /**
3 * @typedef {Object} mw.Api.Options
4 * @property {Object} [parameters = { action: 'query', format: 'json' }] Default query
5 * parameters for API requests
6 * @property {Object} [ajax = { url: mw.util.wikiScript( 'api' ), timeout: 30 * 1000, dataType: 'json' }]
7 * Default options for jQuery#ajax
8 * @property {boolean} [useUS] Whether to use U+001F when joining multi-valued
9 * parameters (since 1.28). Default is true if ajax.url is not set, false otherwise for
10 * compatibility.
11 */
12
13 /**
14 * @private
15 * @type {mw.Api.Options}
16 */
17 let defaultOptions = null;
18
19 /**
20 * @classdesc Interact with the MediaWiki API. `mw.Api` is a client library for
21 * the [action API](https://www.mediawiki.org/wiki/Special:MyLanguage/API:Main_page).
22 * An `mw.Api` object represents the API of a MediaWiki site. For the REST API,
23 * see {@link mw.Rest}.
24 *
25 * ```
26 * var api = new mw.Api();
27 * api.get( {
28 * action: 'query',
29 * meta: 'userinfo'
30 * } ).then( function ( data ) {
31 * console.log( data );
32 * } );
33 * ```
34 *
35 * Since MW 1.25, multiple values for a parameter can be specified using an array:
36 *
37 * ```
38 * var api = new mw.Api();
39 * api.get( {
40 * action: 'query',
41 * meta: [ 'userinfo', 'siteinfo' ] // same effect as 'userinfo|siteinfo'
42 * } ).then( function ( data ) {
43 * console.log( data );
44 * } );
45 * ```
46 *
47 * Since MW 1.26, boolean values for API parameters can be specified natively. Parameter
48 * values set to `false` or `undefined` will be omitted from the request, as required by
49 * the API.
50 *
51 * @class mw.Api
52 * @constructor
53 * @description Create an instance of `mw.Api`.
54 * @param {mw.Api.Options} [options] See {@link mw.Api.Options}. This can also be overridden for
55 * each request by passing them to [get()]{@link mw.Api#get} or [post()]{@link mw.Api#post} (or directly to
56 * [ajax()]{@link mw.Api#ajax}) later on.
57 */
58 mw.Api = function ( options ) {
59 const defaults = Object.assign( {}, options ),
60 setsUrl = options && options.ajax && options.ajax.url !== undefined;
61
62 defaults.parameters = Object.assign( {}, defaultOptions.parameters, defaults.parameters );
63 defaults.ajax = Object.assign( {}, defaultOptions.ajax, defaults.ajax );
64
65 // Force a string if we got a mw.Uri object
66 if ( setsUrl ) {
67 defaults.ajax.url = String( defaults.ajax.url );
68 }
69 if ( defaults.useUS === undefined ) {
70 defaults.useUS = !setsUrl;
71 }
72
73 this.defaults = defaults;
74 this.requests = [];
75 };
76
77 /**
78 * @private
79 * @type {mw.Api.Options}
80 */
81 defaultOptions = {
82 parameters: {
83 action: 'query',
84 format: 'json'
85 },
86 ajax: {
87 url: mw.util.wikiScript( 'api' ),
88 timeout: 30 * 1000, // 30 seconds
89 dataType: 'json'
90 }
91 };
92
93 function mapLegacyToken( action ) {
94 // Legacy types for backward-compatibility with API action=tokens.
95 const csrfActions = [
96 'edit',
97 'delete',
98 'protect',
99 'move',
100 'block',
101 'unblock',
102 'email',
103 'import',
104 'options'
105 ];
106 if ( csrfActions.indexOf( action ) !== -1 ) {
107 mw.track( 'mw.deprecate', 'apitoken_' + action );
108 mw.log.warn( 'Use of the "' + action + '" token is deprecated. Use "csrf" instead.' );
109 return 'csrf';
110 }
111 return action;
112 }
113
114 function createTokenCache() {
115 const tokenPromises = {};
116
117 // Pre-populate with fake ajax promises to avoid HTTP requests for tokens that
118 // we already have on the page from the embedded user.options module (T36733).
119 tokenPromises[ defaultOptions.ajax.url ] = {};
120 const tokens = mw.user.tokens.get();
121 for ( const tokenKey in tokens ) {
122 const value = tokens[ tokenKey ];
123 // This requires #getToken to use the same key as mw.user.tokens.
124 // Format: token-type + "Token" (eg. csrfToken, patrolToken, watchToken).
125 tokenPromises[ defaultOptions.ajax.url ][ tokenKey ] = $.Deferred()
126 .resolve( value )
127 .promise( { abort: function () {} } );
128 }
129
130 return tokenPromises;
131 }
132
133 // Keyed by ajax url and symbolic name for the individual request
134 let promises = createTokenCache();
135
136 mw.Api.prototype = {
137 /**
138 * Abort all unfinished requests issued by this Api object.
139 *
140 * @method
141 */
142 abort: function () {
143 this.requests.forEach( ( request ) => {
144 if ( request ) {
145 request.abort();
146 }
147 } );
148 },
149
150 /**
151 * Perform API get request. See [ajax()]{@link mw.Api#ajax} for details.
152 *
153 * @param {Object} parameters
154 * @param {Object} [ajaxOptions]
155 * @return {jQuery.Promise}
156 */
157 get: function ( parameters, ajaxOptions ) {
158 ajaxOptions = ajaxOptions || {};
159 ajaxOptions.type = 'GET';
160 return this.ajax( parameters, ajaxOptions );
161 },
162
163 /**
164 * Perform API post request. See [ajax()]{@link mw.Api#ajax} for details.
165 *
166 * @param {Object} parameters
167 * @param {Object} [ajaxOptions]
168 * @return {jQuery.Promise}
169 */
170 post: function ( parameters, ajaxOptions ) {
171 ajaxOptions = ajaxOptions || {};
172 ajaxOptions.type = 'POST';
173 return this.ajax( parameters, ajaxOptions );
174 },
175
176 /**
177 * Massage parameters from the nice format we accept into a format suitable for the API.
178 *
179 * NOTE: A value of undefined/null in an array will be represented by Array#join()
180 * as the empty string. Should we filter silently? Warn? Leave as-is?
181 *
182 * @private
183 * @param {Object} parameters (modified in-place)
184 * @param {boolean} useUS Whether to use U+001F when joining multivalued parameters.
185 */
186 preprocessParameters: function ( parameters, useUS ) {
187 let key;
188 // Handle common MediaWiki API idioms for passing parameters
189 for ( key in parameters ) {
190 // Multiple values are pipe-separated
191 if ( Array.isArray( parameters[ key ] ) ) {
192 if ( !useUS || parameters[ key ].join( '' ).indexOf( '|' ) === -1 ) {
193 parameters[ key ] = parameters[ key ].join( '|' );
194 } else {
195 parameters[ key ] = '\x1f' + parameters[ key ].join( '\x1f' );
196 }
197 } else if ( parameters[ key ] === false || parameters[ key ] === undefined ) {
198 // Boolean values are only false when not given at all
199 delete parameters[ key ];
200 }
201 }
202 },
203
204 /**
205 * Perform the API call.
206 *
207 * @param {Object} parameters Parameters to the API. See also {@link mw.Api.Options}
208 * @param {Object} [ajaxOptions] Parameters to pass to jQuery.ajax. See also
209 * {@link mw.Api.Options}
210 * @return {jQuery.Promise} A promise that settles when the API response is processed.
211 * Has an 'abort' method which can be used to abort the request.
212 *
213 * - On success, resolves to `( result, jqXHR )` where `result` is the parsed API response.
214 * - On an API error, rejects with `( code, result, result, jqXHR )` where `code` is the
215 * [API error code](https://www.mediawiki.org/wiki/API:Errors_and_warnings), and `result`
216 * is as above. When there are multiple errors, the code from the first one will be used.
217 * If there is no error code, "unknown" is used.
218 * - On other types of errors, rejects with `( 'http', details )` where `details` is an object
219 * with three fields: `xhr` (the jqXHR object), `textStatus`, and `exception`.
220 * The meaning of the last two fields is as follows:
221 * - When the request is aborted (the abort method of the promise is called), textStatus
222 * and exception are both set to "abort".
223 * - On a network timeout, textStatus and exception are both set to "timeout".
224 * - On a network error, textStatus is "error" and exception is the empty string.
225 * - When the HTTP response code is anything other than 2xx or 304 (the API does not
226 * use such response codes but some intermediate layer might), textStatus is "error"
227 * and exception is the HTTP status text (the text following the status code in the
228 * first line of the server response). For HTTP/2, `exception` is always an empty string.
229 * - When the response is not valid JSON but the previous error conditions aren't met,
230 * textStatus is "parsererror" and exception is the exception object thrown by
231 * {@link JSON.parse}.
232 */
233 ajax: function ( parameters, ajaxOptions ) {
234 const api = this,
235 apiDeferred = $.Deferred();
236
237 parameters = Object.assign( {}, this.defaults.parameters, parameters );
238 ajaxOptions = Object.assign( {}, this.defaults.ajax, ajaxOptions );
239
240 let token;
241 // Ensure that token parameter is last (per [[mw:API:Edit#Token]]).
242 if ( parameters.token ) {
243 token = parameters.token;
244 delete parameters.token;
245 }
246
247 this.preprocessParameters( parameters, this.defaults.useUS );
248
249 // If multipart/form-data has been requested and emulation is possible, emulate it
250 if (
251 ajaxOptions.type === 'POST' &&
252 window.FormData &&
253 ajaxOptions.contentType === 'multipart/form-data'
254 ) {
255
256 const formData = new FormData();
257
258 for ( const key in parameters ) {
259 formData.append( key, parameters[ key ] );
260 }
261 // If we extracted a token parameter, add it back in.
262 if ( token ) {
263 formData.append( 'token', token );
264 }
265
266 ajaxOptions.data = formData;
267
268 // Prevent jQuery from mangling our FormData object
269 ajaxOptions.processData = false;
270 // Prevent jQuery from overriding the Content-Type header
271 ajaxOptions.contentType = false;
272 } else {
273 // This works because jQuery accepts data as a query string or as an Object
274 ajaxOptions.data = $.param( parameters );
275 // If we extracted a token parameter, add it back in.
276 if ( token ) {
277 ajaxOptions.data += '&token=' + encodeURIComponent( token );
278 }
279
280 if ( ajaxOptions.contentType === 'multipart/form-data' ) {
281 // We were asked to emulate but can't, so drop the Content-Type header, otherwise
282 // it'll be wrong and the server will fail to decode the POST body
283 delete ajaxOptions.contentType;
284 }
285 }
286
287 // Make the AJAX request
288 const xhr = $.ajax( ajaxOptions )
289 // If AJAX fails, reject API call with error code 'http'
290 // and the details in the second argument.
291 .fail( ( jqXHR, textStatus, exception ) => {
292 apiDeferred.reject( 'http', {
293 xhr: jqXHR,
294 textStatus: textStatus,
295 exception: exception
296 } );
297 } )
298 // AJAX success just means "200 OK" response, also check API error codes
299 .done( ( result, textStatus, jqXHR ) => {
300 let code;
301 if ( result === undefined || result === null || result === '' ) {
302 apiDeferred.reject( 'ok-but-empty',
303 'OK response but empty result (check HTTP headers?)',
304 result,
305 jqXHR
306 );
307 } else if ( result.error ) {
308 // errorformat=bc
309 code = result.error.code === undefined ? 'unknown' : result.error.code;
310 apiDeferred.reject( code, result, result, jqXHR );
311 } else if ( result.errors ) {
312 // errorformat!=bc
313 code = result.errors[ 0 ].code === undefined ? 'unknown' : result.errors[ 0 ].code;
314 apiDeferred.reject( code, result, result, jqXHR );
315 } else {
316 apiDeferred.resolve( result, jqXHR );
317 }
318 } );
319
320 const requestIndex = this.requests.length;
321 this.requests.push( xhr );
322 xhr.always( () => {
323 api.requests[ requestIndex ] = null;
324 } );
325 // Return the Promise
326 return apiDeferred.promise( { abort: xhr.abort } ).fail( ( code, details ) => {
327 if ( !( code === 'http' && details && details.textStatus === 'abort' ) ) {
328 mw.log( 'mw.Api error: ', code, details );
329 }
330 } );
331 },
332
333 /**
334 * Post to API with the specified type of token. If we have no token, get one and try to post.
335 * If we already have a cached token, try using that, and if the request fails using the cached token,
336 * blank it out and start over.
337 *
338 * @example <caption>For example, to change a user option, you could do:</caption>
339 * new mw.Api().postWithToken( 'csrf', {
340 * action: 'options',
341 * optionname: 'gender',
342 * optionvalue: 'female'
343 * } );
344 *
345 * @param {string} tokenType The name of the token, like options or edit.
346 * @param {Object} params API parameters
347 * @param {Object} [ajaxOptions]
348 * @return {jQuery.Promise} See [post()]{@link mw.Api#post}
349 * @since 1.22
350 */
351 postWithToken: function ( tokenType, params, ajaxOptions ) {
352 const api = this,
353 assertParams = {
354 assert: params.assert,
355 assertuser: params.assertuser
356 },
357 abortedPromise = $.Deferred().reject( 'http',
358 { textStatus: 'abort', exception: 'abort' } ).promise();
359 let abortable,
360 aborted;
361
362 return api.getToken( tokenType, assertParams ).then( ( token ) => {
363 params.token = token;
364 // Request was aborted while token request was running, but we
365 // don't want to unnecessarily abort token requests, so abort
366 // a fake request instead
367 if ( aborted ) {
368 return abortedPromise;
369 }
370
371 return ( abortable = api.post( params, ajaxOptions ) ).catch(
372 // Error handler
373 function ( code ) {
374 if ( code === 'badtoken' ) {
375 api.badToken( tokenType );
376 // Try again, once
377 params.token = undefined;
378 abortable = null;
379 return api.getToken( tokenType, assertParams ).then( ( t ) => {
380 params.token = t;
381 if ( aborted ) {
382 return abortedPromise;
383 }
384
385 return ( abortable = api.post( params, ajaxOptions ) );
386 } );
387 }
388
389 // Let caller handle the error code
390 return $.Deferred().rejectWith( this, arguments );
391 }
392 );
393 } ).promise( { abort: function () {
394 if ( abortable ) {
395 abortable.abort();
396 } else {
397 aborted = true;
398 }
399 } } );
400 },
401
402 /**
403 * Get a token for a certain action from the API.
404 *
405 * @since 1.22
406 * @param {string} type Token type
407 * @param {Object|string} [additionalParams] Additional parameters for the API (since 1.35).
408 * When given a string, it's treated as the 'assert' parameter (since 1.25).
409 * @return {jQuery.Promise<string>} Received token.
410 */
411 getToken: function ( type, additionalParams ) {
412 type = mapLegacyToken( type );
413 if ( typeof additionalParams === 'string' ) {
414 additionalParams = { assert: additionalParams };
415 }
416
417 const cacheKey = type + 'Token';
418 let promiseGroup = promises[ this.defaults.ajax.url ];
419 if ( !promiseGroup ) {
420 promiseGroup = promises[ this.defaults.ajax.url ] = {};
421 }
422 let promise = promiseGroup && promiseGroup[ cacheKey ];
423
424 function reject() {
425 // Clear cache. Do not cache errors.
426 delete promiseGroup[ cacheKey ];
427
428 // Let caller handle the error code
429 return $.Deferred().rejectWith( this, arguments );
430 }
431
432 if ( !promise ) {
433 const apiPromise = this.get( Object.assign( {
434 action: 'query',
435 meta: 'tokens',
436 type: type
437 }, additionalParams ) );
438 promise = apiPromise
439 .then( ( res ) => {
440 if ( !res.query ) {
441 return reject( 'query-missing', res );
442 }
443 // If the token type is unknown, it is omitted from the response
444 if ( !res.query.tokens[ type + 'token' ] ) {
445 return $.Deferred().reject( 'token-missing', res );
446 }
447 return res.query.tokens[ type + 'token' ];
448 }, reject )
449 // Preserve abort handler
450 .promise( { abort: apiPromise.abort } );
451
452 // Optimization: Store the promise so we can reuse it immediately, even when
453 // other async code requests before this one finishes.
454 promiseGroup[ cacheKey ] = promise;
455 }
456
457 return promise;
458 },
459
460 /**
461 * Indicate that the cached token for a certain action of the API is bad.
462 *
463 * Call this if you get a 'badtoken' error when using the token returned by [getToken()]{@link mw.Api#getToken}.
464 * You may also want to use [postWithToken()]{@link mw.Api#postWithToken} instead, which invalidates bad cached tokens
465 * automatically.
466 *
467 * @param {string} type Token type
468 * @since 1.26
469 */
470 badToken: function ( type ) {
471 const promiseGroup = promises[ this.defaults.ajax.url ];
472
473 type = mapLegacyToken( type );
474 if ( promiseGroup ) {
475 delete promiseGroup[ type + 'Token' ];
476 }
477 },
478
479 /**
480 * Given an API response indicating an error, get a jQuery object containing a human-readable
481 * error message that you can display somewhere on the page.
482 *
483 * For better quality of error messages, it's recommended to use the following options in your
484 * API queries:
485 *
486 * ```
487 * errorformat: 'html',
488 * errorlang: mw.config.get( 'wgUserLanguage' ),
489 * errorsuselocal: true,
490 * ```
491 *
492 * Error messages, particularly for editing pages, may consist of multiple paragraphs of text.
493 * Your user interface should have enough space for that.
494 *
495 * @example
496 * var api = new mw.Api();
497 * // var title = 'Test valid title';
498 * var title = 'Test invalid title <>';
499 * api.postWithToken( 'watch', {
500 * action: 'watch',
501 * title: title
502 * } ).then( function ( data ) {
503 * mw.notify( 'Success!' );
504 * }, function ( code, data ) {
505 * mw.notify( api.getErrorMessage( data ), { type: 'error' } );
506 * } );
507 *
508 * @param {Object} data API response indicating an error
509 * @return {jQuery} Error messages, each wrapped in a `<div>`
510 */
511 getErrorMessage: function ( data ) {
512 if (
513 data === undefined || data === null || data === '' ||
514 // The #ajax method returns the data like this, it's not my fault...
515 data === 'OK response but empty result (check HTTP headers?)'
516 ) {
517 // The server failed so horribly that it did not set a HTTP error status
518 return $( '<div>' ).append( mw.message( 'api-clientside-error-invalidresponse' ).parseDom() );
519
520 } else if ( data.xhr ) {
521 if ( data.textStatus === 'timeout' ) {
522 // Hit the timeout (as defined above in defaultOptions)
523 return $( '<div>' ).append( mw.message( 'api-clientside-error-timeout' ).parseDom() );
524 } else if ( data.textStatus === 'abort' ) {
525 // The request was cancelled by calling the abort() method on the promise
526 return $( '<div>' ).append( mw.message( 'api-clientside-error-aborted' ).parseDom() );
527 } else if ( data.textStatus === 'parsererror' ) {
528 // Server returned invalid JSON
529 // data.exception is probably a SyntaxError exception
530 return $( '<div>' ).append( mw.message( 'api-clientside-error-invalidresponse' ).parseDom() );
531 } else if ( data.xhr.status ) {
532 // Server HTTP error
533 // data.exception is probably the HTTP "reason phrase", e.g. "Internal Server Error"
534 return $( '<div>' ).append( mw.message( 'api-clientside-error-http', data.xhr.status ).parseDom() );
535 } else {
536 // We don't know the status of the HTTP request. Common causes include (we have no way
537 // to distinguish these): user losing their network connection (request wasn't even sent),
538 // misconfigured CORS for cross-wiki queries.
539 return $( '<div>' ).append( mw.message( 'api-clientside-error-noconnect' ).parseDom() );
540 }
541
542 } else if ( data.error ) {
543 // errorformat: 'bc' (or not specified)
544 return $( '<div>' ).text( data.error.info );
545
546 } else if ( data.errors ) {
547 // errorformat: 'html' (hopefully) or another non-bc format
548 return $( data.errors.map( ( err ) => {
549 const $node = $( '<div>' );
550 if ( err.html ) {
551 $node.html( err.html );
552 } else if ( err.text ) {
553 $node.text( err.text );
554 } else {
555 // formatversion=1, we can’t tell if this was errorformat=html or errorformat=plaintext;
556 // err on the safe side and treat it as text
557 $node.text( err[ '*' ] );
558 }
559 return $node[ 0 ];
560 } ) );
561
562 } else {
563 // The server returned some valid but bogus JSON that probably doesn't even come from our API,
564 // or this method was called incorrectly (e.g. with a successful response)
565 mw.log.warn( 'mw.Api#getErrorMessage could not handle the response:', data );
566 return $( '<div>' ).append( mw.message( 'api-clientside-error-invalidresponse' ).parseDom() );
567 }
568 }
569 };
570
571 if ( window.QUnit ) {
572 mw.Api.resetTokenCacheForTest = function () {
573 promises = createTokenCache();
574 };
575 }
576 }() );