Back

21.76% Statements 32/147
14.28% Branches 6/42
12.37% Functions 12/97
21.91% Lines 32/146

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668                                5x     1x 1x 1x 1x 1x                 1x 1x 1x     1x       1x             1x   1x   1x                                                           1x       1x     1x 1x         1x       1x 1x     1x                                           1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               1x                                                                                                                       1x                                                         2x                       2x                                                                     1x     1x                       3x 3x                                                           4x                                                
import { jetpackConfigGet, jetpackConfigHas } from '@automattic/jetpack-config';
import { addQueryArgs } from '@wordpress/url';
 
/**
 * Helps create new custom error classes to better notify upper layers.
 *
 * @param {string} name - the Error name that will be availble in Error.name
 * @return {Error}      a new custom error class.
 */
function createCustomError( name ) {
	class CustomError extends Error {
		constructor( ...args ) {
			super( ...args );
			this.name = name;
		}
	}
	return CustomError;
}
 
export const JsonParseError = createCustomError( 'JsonParseError' );
export const JsonParseAfterRedirectError = createCustomError( 'JsonParseAfterRedirectError' );
export const Api404Error = createCustomError( 'Api404Error' );
export const Api404AfterRedirectError = createCustomError( 'Api404AfterRedirectError' );
export const FetchNetworkError = createCustomError( 'FetchNetworkError' );
 
/**
 * Create a Jetpack Rest Api Client
 *
 * @param {string} root  - The API root
 * @param {string} nonce - The API Nonce
 */
function JetpackRestApiClient( root, nonce ) {
	let apiRoot = root,
		wpcomOriginApiUrl = root,
		headers = {
			'X-WP-Nonce': nonce,
		},
		getParams = {
			credentials: 'same-origin',
			headers,
		},
		postParams = {
			method: 'post',
			credentials: 'same-origin',
			headers: Object.assign( {}, headers, {
				'Content-type': 'application/json',
			} ),
		},
		cacheBusterCallback = addCacheBuster;
 
	const methods = {
		setApiRoot( newRoot ) {
			apiRoot = newRoot;
		},
		/**
		 * Sets API root for search endpoints.
		 * They are routed through wpcom API for wpcom simple sites,
		 * so we add `/wp-json/wpcom-origin/` to this path on wpcom.
		 * For non-wpcom sites, this is the same as apiRoot.
		 *
		 * @param {string} newRoot - API root for search endpoints.
		 */
		setWpcomOriginApiUrl( newRoot ) {
			wpcomOriginApiUrl = newRoot;
		},
		setApiNonce( newNonce ) {
			headers = {
				'X-WP-Nonce': newNonce,
			};
			getParams = {
				credentials: 'same-origin',
				headers: headers,
			};
			postParams = {
				method: 'post',
				credentials: 'same-origin',
				headers: Object.assign( {}, headers, {
					'Content-type': 'application/json',
				} ),
			};
		},
		setCacheBusterCallback: callback => {
			cacheBusterCallback = callback;
		},
 
		registerSite: ( deprecated, redirectUri, from, pluginSlug ) => {
			const params = {};
 
			// The caller's slug wins: a shared bundle's own jetpackConfig doesn't name the consuming plugin.
			if ( pluginSlug ) {
				params.plugin_slug = pluginSlug;
			} else Eif ( jetpackConfigHas( 'consumer_slug' ) ) {
				params.plugin_slug = jetpackConfigGet( 'consumer_slug' );
			}
 
			Iif ( null !== redirectUri ) {
				params.redirect_uri = redirectUri;
			}
 
			Eif ( from ) {
				params.from = from;
			}
 
			return postRequest( `${ apiRoot }jetpack/v4/connection/register`, postParams, {
				body: JSON.stringify( params ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse );
		},
 
		fetchAuthorizationUrl: redirectUri =>
			getRequest(
				addQueryArgs( `${ apiRoot }jetpack/v4/connection/authorize_url`, {
					no_iframe: '1',
					redirect_uri: redirectUri,
				} ),
				getParams
			)
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		fetchSiteConnectionData: () =>
			getRequest( `${ apiRoot }jetpack/v4/connection/data`, getParams ).then( parseJsonResponse ),
 
		fetchSiteConnectionStatus: () =>
			getRequest( `${ apiRoot }jetpack/v4/connection`, getParams ).then( parseJsonResponse ),
 
		fetchSiteConnectionTest: () =>
			getRequest( `${ apiRoot }jetpack/v4/connection/test`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		fetchUserConnectionData: () =>
			getRequest( `${ apiRoot }jetpack/v4/connection/data`, getParams ).then( parseJsonResponse ),
 
		fetchUserTrackingSettings: () =>
			getRequest( `${ apiRoot }jetpack/v4/tracking/settings`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		updateUserTrackingSettings: newSettings =>
			postRequest( `${ apiRoot }jetpack/v4/tracking/settings`, postParams, {
				body: JSON.stringify( newSettings ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		disconnectSite: () =>
			postRequest( `${ apiRoot }jetpack/v4/connection`, postParams, {
				body: JSON.stringify( { isActive: false } ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		fetchConnectUrl: () =>
			getRequest( `${ apiRoot }jetpack/v4/connection/url`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		unlinkUser: ( force = false, options = {} ) => {
			const params = {
				linked: false,
				force: !! force,
			};
 
			// Add any additional options to the params
			if ( options.disconnectAllUsers ) {
				params[ 'disconnect-all-users' ] = true;
			}
 
			return postRequest( `${ apiRoot }jetpack/v4/connection/user`, postParams, {
				body: JSON.stringify( params ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse );
		},
 
		fetchConnectionOwnerCandidates: () =>
			getRequest( `${ apiRoot }jetpack/v4/connection/owner/candidates`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		setConnectionOwner: ownerId =>
			postRequest( `${ apiRoot }jetpack/v4/connection/owner`, postParams, {
				body: JSON.stringify( { owner: ownerId } ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		reconnect: () =>
			postRequest( `${ apiRoot }jetpack/v4/connection/reconnect`, postParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		fetchConnectedPlugins: () =>
			getRequest( `${ apiRoot }jetpack/v4/connection/plugins`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		fetchModules: () =>
			getRequest( `${ apiRoot }jetpack/v4/module/all`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		fetchModule: slug =>
			getRequest( `${ apiRoot }jetpack/v4/module/${ slug }`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		activateModule: slug =>
			postRequest( `${ apiRoot }jetpack/v4/module/${ slug }/active`, postParams, {
				body: JSON.stringify( { active: true } ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		deactivateModule: slug =>
			postRequest( `${ apiRoot }jetpack/v4/module/${ slug }/active`, postParams, {
				body: JSON.stringify( { active: false } ),
			} ),
 
		updateModuleOptions: ( slug, newOptionValues ) =>
			postRequest( `${ apiRoot }jetpack/v4/module/${ slug }`, postParams, {
				body: JSON.stringify( newOptionValues ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		updateSettings: newOptionValues =>
			postRequest( `${ apiRoot }jetpack/v4/settings`, postParams, {
				body: JSON.stringify( newOptionValues ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		getProtectCount: () =>
			getRequest( `${ apiRoot }jetpack/v4/module/protect/data`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		resetOptions: options =>
			postRequest( `${ apiRoot }jetpack/v4/options/${ options }`, postParams, {
				body: JSON.stringify( { reset: true } ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		activateVaultPress: () =>
			postRequest( `${ apiRoot }jetpack/v4/plugins`, postParams, {
				body: JSON.stringify( { slug: 'vaultpress', status: 'active' } ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		getVaultPressData: () =>
			getRequest( `${ apiRoot }jetpack/v4/module/vaultpress/data`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		installPlugin: ( slug, source ) => {
			const props = { slug, status: 'active' };
 
			if ( source ) {
				props.source = source;
			}
 
			return postRequest( `${ apiRoot }jetpack/v4/plugins`, postParams, {
				body: JSON.stringify( props ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse );
		},
 
		activateAkismet: () =>
			postRequest( `${ apiRoot }jetpack/v4/plugins`, postParams, {
				body: JSON.stringify( { slug: 'akismet', status: 'active' } ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		getAkismetData: () =>
			getRequest( `${ apiRoot }jetpack/v4/module/akismet/data`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		checkAkismetKey: () =>
			getRequest( `${ apiRoot }jetpack/v4/module/akismet/key/check`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		checkAkismetKeyTyped: apiKey =>
			postRequest( `${ apiRoot }jetpack/v4/module/akismet/key/check`, postParams, {
				body: JSON.stringify( { api_key: apiKey } ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		getFeatureTypeStatus: customContentType =>
			getRequest( `${ apiRoot }jetpack/v4/feature/${ customContentType }`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		fetchStatsData: range =>
			getRequest( statsDataUrl( range ), getParams )
				.then( checkStatus )
				.then( parseJsonResponse )
				.then( handleStatsResponseError ),
 
		getPluginUpdates: () =>
			getRequest( `${ apiRoot }jetpack/v4/updates/plugins`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		getPlans: () =>
			getRequest( `${ apiRoot }jetpack/v4/plans`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		fetchSettings: () =>
			getRequest( `${ apiRoot }jetpack/v4/settings`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		updateSetting: updatedSetting =>
			postRequest( `${ apiRoot }jetpack/v4/settings`, postParams, {
				body: JSON.stringify( updatedSetting ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		fetchSiteData: () =>
			getRequest( `${ apiRoot }jetpack/v4/site`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse )
				.then( body => JSON.parse( body.data ) ),
 
		fetchSiteFeatures: () =>
			getRequest( `${ apiRoot }jetpack/v4/site/features`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse )
				.then( body => JSON.parse( body.data ) ),
 
		fetchSitePurchases: () =>
			getRequest( `${ apiRoot }jetpack/v4/site/purchases`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse )
				.then( body => JSON.parse( body.data ) ),
 
		fetchSiteBenefits: () =>
			getRequest( `${ apiRoot }jetpack/v4/site/benefits`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse )
				.then( body => JSON.parse( body.data ) ),
 
		fetchSetupQuestionnaire: () =>
			getRequest( `${ apiRoot }jetpack/v4/setup/questionnaire`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		fetchRewindStatus: () =>
			getRequest( `${ apiRoot }jetpack/v4/rewind`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse )
				.then( body => JSON.parse( body.data ) ),
 
		fetchScanStatus: () =>
			getRequest( `${ apiRoot }jetpack/v4/scan`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse )
				.then( body => JSON.parse( body.data ) ),
 
		dismissJetpackNotice: notice =>
			postRequest( `${ apiRoot }jetpack/v4/notice/${ notice }`, postParams, {
				body: JSON.stringify( { dismissed: true } ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		fetchPluginsData: () =>
			getRequest( `${ apiRoot }jetpack/v4/plugins`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		fetchVerifySiteGoogleStatus: keyringId => {
			const request =
				keyringId !== null
					? getRequest( `${ apiRoot }jetpack/v4/verify-site/google/${ keyringId }`, getParams )
					: getRequest( `${ apiRoot }jetpack/v4/verify-site/google`, getParams );
 
			return request.then( checkStatus ).then( parseJsonResponse );
		},
 
		verifySiteGoogle: keyringId =>
			postRequest( `${ apiRoot }jetpack/v4/verify-site/google`, postParams, {
				body: JSON.stringify( { keyring_id: keyringId } ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		submitSurvey: surveyResponse =>
			postRequest( `${ apiRoot }jetpack/v4/marketing/survey`, postParams, {
				body: JSON.stringify( surveyResponse ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		saveSetupQuestionnaire: props =>
			postRequest( `${ apiRoot }jetpack/v4/setup/questionnaire`, postParams, {
				body: JSON.stringify( props ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		updateLicensingError: props =>
			postRequest( `${ apiRoot }jetpack/v4/licensing/error`, postParams, {
				body: JSON.stringify( props ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		updateLicenseKey: license =>
			postRequest( `${ apiRoot }jetpack/v4/licensing/set-license`, postParams, {
				body: JSON.stringify( { license } ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		getUserLicensesCounts: () =>
			getRequest( `${ apiRoot }jetpack/v4/licensing/user/counts`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		getUserLicenses: () =>
			getRequest( `${ apiRoot }jetpack/v4/licensing/user/licenses`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		updateLicensingActivationNoticeDismiss: lastDetachedCount =>
			postRequest( `${ apiRoot }jetpack/v4/licensing/user/activation-notice-dismiss`, postParams, {
				body: JSON.stringify( { last_detached_count: lastDetachedCount } ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		confirmIDCSafeMode: () =>
			postRequest( `${ apiRoot }jetpack/v4/identity-crisis/confirm-safe-mode`, postParams ).then(
				checkStatus
			),
 
		startIDCFresh: redirectUri =>
			postRequest( `${ apiRoot }jetpack/v4/identity-crisis/start-fresh`, postParams, {
				body: JSON.stringify( { redirect_uri: redirectUri } ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse ),
 
		migrateIDC: () =>
			postRequest( `${ apiRoot }jetpack/v4/identity-crisis/migrate`, postParams ).then(
				checkStatus
			),
		attachLicenses: licenses =>
			postRequest( `${ apiRoot }jetpack/v4/licensing/attach-licenses`, postParams, {
				body: JSON.stringify( { licenses } ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse ),
		fetchSearchPlanInfo: () =>
			getRequest( `${ wpcomOriginApiUrl }jetpack/v4/search/plan`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
		activateSearchFreeProduct: source =>
			postRequest( `${ wpcomOriginApiUrl }jetpack/v4/search/plan/activate-free`, postParams, {
				body: JSON.stringify( source ? { source } : {} ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse ),
		fetchSearchSettings: () =>
			getRequest( `${ wpcomOriginApiUrl }jetpack/v4/search/settings`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
		updateSearchSettings: newSettings =>
			postRequest( `${ wpcomOriginApiUrl }jetpack/v4/search/settings`, postParams, {
				body: JSON.stringify( newSettings ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse ),
		fetchSearchStats: () =>
			getRequest( `${ wpcomOriginApiUrl }jetpack/v4/search/stats`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
		fetchWafSettings: () =>
			getRequest( `${ apiRoot }jetpack/v4/waf`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
		updateWafSettings: newSettings =>
			postRequest( `${ apiRoot }jetpack/v4/waf`, postParams, {
				body: JSON.stringify( newSettings ),
			} )
				.then( checkStatus )
				.then( parseJsonResponse ),
		fetchWordAdsSettings: () =>
			getRequest( `${ apiRoot }jetpack/v4/wordads/settings`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
		updateWordAdsSettings: newSettings =>
			postRequest( `${ apiRoot }jetpack/v4/wordads/settings`, postParams, {
				body: JSON.stringify( newSettings ),
			} ),
		fetchSearchPricing: () =>
			getRequest( `${ wpcomOriginApiUrl }jetpack/v4/search/pricing`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
		fetchMigrationStatus: () =>
			getRequest( `${ apiRoot }jetpack/v4/migration/status`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
		fetchBackupUndoEvent: () =>
			getRequest( `${ apiRoot }jetpack/v4/site/backup/undo-event`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
		fetchBackupPreflightStatus: () =>
			getRequest( `${ apiRoot }jetpack/v4/site/backup/preflight`, getParams )
				.then( checkStatus )
				.then( parseJsonResponse ),
	};
 
	/**
	 * The default callback to add a cachebuster parameter to route
	 *
	 * @param {string} route - the route
	 * @return {string} - the route with the cachebuster appended
	 */
	function addCacheBuster( route ) {
		const parts = route.split( '?' ),
			query = parts.length > 1 ? parts[ 1 ] : '',
			args = query.length ? query.split( '&' ) : [];
 
		args.push( '_cacheBuster=' + new Date().getTime() );
 
		return parts[ 0 ] + '?' + args.join( '&' );
	}
 
	/**
	 * Generate a request promise for the route and params. Automatically adds a cachebuster.
	 *
	 * @param {string} route  - the route
	 * @param {object} params - the params
	 * @return {Promise<Response>} - the http request promise
	 */
	function getRequest( route, params ) {
		return fetch( cacheBusterCallback( route ), params );
	}
 
	/**
	 * Generate a POST request promise for the route and params. Automatically adds a cachebuster.
	 *
	 * @param {string} route  - the route
	 * @param {object} params - the params
	 * @param {string} body   - the body
	 * @return {Promise<Response>} - the http response promise
	 */
	function postRequest( route, params, body ) {
		return fetch( route, Object.assign( {}, params, body ) ).catch( catchNetworkErrors );
	}
 
	/**
	 * Returns the stats data URL for the given date range
	 *
	 * @param {string} range - the range
	 * @return {string} - the stats URL
	 */
	function statsDataUrl( range ) {
		let url = `${ apiRoot }jetpack/v4/module/stats/data`;
		if ( url.indexOf( '?' ) !== -1 ) {
			url = url + `&range=${ encodeURIComponent( range ) }`;
		} else {
			url = url + `?range=${ encodeURIComponent( range ) }`;
		}
		return url;
	}
 
	/**
	 * Returns stats data if possible, otherwise an empty object
	 *
	 * @param {object} statsData - the stats data or error
	 * @return {object} - the handled stats data
	 */
	function handleStatsResponseError( statsData ) {
		// If we get a .response property, it means that .com's response is errory.
		// Probably because the site does not have stats yet.
		const responseOk =
			( statsData.general && statsData.general.response === undefined ) ||
			( statsData.week && statsData.week.response === undefined ) ||
			( statsData.month && statsData.month.response === undefined );
		return responseOk ? statsData : {};
	}
 
	Object.assign( this, methods );
}
 
const restApi = new JetpackRestApiClient();
 
export default restApi;
 
/**
 * Check the status of the response. Throw an error if it was not OK
 *
 * @param {Response} response - the API response
 * @return {Promise<object>} - a promise to return the parsed JSON body as an object
 */
function checkStatus( response ) {
	// Regular success responses
	Eif ( response.status >= 200 && response.status < 300 ) {
		return response;
	}
 
	if ( response.status === 404 ) {
		return new Promise( () => {
			const err = response.redirected
				? new Api404AfterRedirectError( response.redirected )
				: new Api404Error();
			throw err;
		} );
	}
 
	return response
		.json()
		.catch( e => catchJsonParseError( e ) )
		.then( json => {
			const error = new Error( `${ json.message } (Status ${ response.status })` );
			error.response = json;
			error.name = 'ApiError';
			throw error;
		} );
}
 
/**
 * Parse the JSON response
 *
 * @param {Response} response - the response object
 * @return {Promise<object>} - promise to return the parsed json object
 */
function parseJsonResponse( response ) {
	return response.json().catch( e => catchJsonParseError( e, response.redirected, response.url ) );
}
 
/**
 * Throw appropriate exception given an API error
 *
 * @param {Error}   e          - the error
 * @param {boolean} redirected - are we being redirected?
 * @param {string}  url        - the URL that returned the error
 */
function catchJsonParseError( e, redirected, url ) {
	const err = redirected ? new JsonParseAfterRedirectError( url ) : new JsonParseError();
	throw err;
}
 
/**
 * Catches TypeError coming from the Fetch API implementation
 */
function catchNetworkErrors() {
	//Either one of:
	// * A preflight error like a redirection to an external site (which results in a CORS)
	// * A preflight error like ERR_TOO_MANY_REDIRECTS
	throw new FetchNetworkError();
}