[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

/wp-includes/js/dist/ -> api-fetch.js (source)

   1  this["wp"] = this["wp"] || {}; this["wp"]["apiFetch"] =
   2  /******/ (function(modules) { // webpackBootstrap
   3  /******/     // The module cache
   4  /******/     var installedModules = {};
   5  /******/
   6  /******/     // The require function
   7  /******/ 	function __webpack_require__(moduleId) {
   8  /******/
   9  /******/         // Check if module is in cache
  10  /******/         if(installedModules[moduleId]) {
  11  /******/             return installedModules[moduleId].exports;
  12  /******/         }
  13  /******/         // Create a new module (and put it into the cache)
  14  /******/         var module = installedModules[moduleId] = {
  15  /******/             i: moduleId,
  16  /******/             l: false,
  17  /******/             exports: {}
  18  /******/         };
  19  /******/
  20  /******/         // Execute the module function
  21  /******/         modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  22  /******/
  23  /******/         // Flag the module as loaded
  24  /******/         module.l = true;
  25  /******/
  26  /******/         // Return the exports of the module
  27  /******/         return module.exports;
  28  /******/     }
  29  /******/
  30  /******/
  31  /******/     // expose the modules object (__webpack_modules__)
  32  /******/     __webpack_require__.m = modules;
  33  /******/
  34  /******/     // expose the module cache
  35  /******/     __webpack_require__.c = installedModules;
  36  /******/
  37  /******/     // define getter function for harmony exports
  38  /******/     __webpack_require__.d = function(exports, name, getter) {
  39  /******/         if(!__webpack_require__.o(exports, name)) {
  40  /******/             Object.defineProperty(exports, name, { enumerable: true, get: getter });
  41  /******/         }
  42  /******/     };
  43  /******/
  44  /******/     // define __esModule on exports
  45  /******/     __webpack_require__.r = function(exports) {
  46  /******/         if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  47  /******/             Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  48  /******/         }
  49  /******/         Object.defineProperty(exports, '__esModule', { value: true });
  50  /******/     };
  51  /******/
  52  /******/     // create a fake namespace object
  53  /******/     // mode & 1: value is a module id, require it
  54  /******/     // mode & 2: merge all properties of value into the ns
  55  /******/     // mode & 4: return value when already ns object
  56  /******/     // mode & 8|1: behave like require
  57  /******/     __webpack_require__.t = function(value, mode) {
  58  /******/         if(mode & 1) value = __webpack_require__(value);
  59  /******/         if(mode & 8) return value;
  60  /******/         if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  61  /******/         var ns = Object.create(null);
  62  /******/         __webpack_require__.r(ns);
  63  /******/         Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  64  /******/         if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  65  /******/         return ns;
  66  /******/     };
  67  /******/
  68  /******/     // getDefaultExport function for compatibility with non-harmony modules
  69  /******/     __webpack_require__.n = function(module) {
  70  /******/         var getter = module && module.__esModule ?
  71  /******/ 			function getDefault() { return module['default']; } :
  72  /******/ 			function getModuleExports() { return module; };
  73  /******/         __webpack_require__.d(getter, 'a', getter);
  74  /******/         return getter;
  75  /******/     };
  76  /******/
  77  /******/     // Object.prototype.hasOwnProperty.call
  78  /******/     __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  79  /******/
  80  /******/     // __webpack_public_path__
  81  /******/     __webpack_require__.p = "";
  82  /******/
  83  /******/
  84  /******/     // Load entry module and return exports
  85  /******/     return __webpack_require__(__webpack_require__.s = "jqrR");
  86  /******/ })
  87  /************************************************************************/
  88  /******/ ({
  89  
  90  /***/ "Mmq9":
  91  /***/ (function(module, exports) {
  92  
  93  (function() { module.exports = window["wp"]["url"]; }());
  94  
  95  /***/ }),
  96  
  97  /***/ "jqrR":
  98  /***/ (function(module, __webpack_exports__, __webpack_require__) {
  99  
 100  "use strict";
 101  // ESM COMPAT FLAG
 102  __webpack_require__.r(__webpack_exports__);
 103  
 104  // EXTERNAL MODULE: external ["wp","i18n"]
 105  var external_wp_i18n_ = __webpack_require__("l3Sj");
 106  
 107  // CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/nonce.js
 108  /**
 109   * @param {string} nonce
 110   * @return {import('../types').APIFetchMiddleware & { nonce: string }} A middleware to enhance a request with a nonce.
 111   */
 112  function createNonceMiddleware(nonce) {
 113    /**
 114     * @type {import('../types').APIFetchMiddleware & { nonce: string }}
 115     */
 116    const middleware = (options, next) => {
 117      const {
 118        headers = {}
 119      } = options; // If an 'X-WP-Nonce' header (or any case-insensitive variation
 120      // thereof) was specified, no need to add a nonce header.
 121  
 122      for (const headerName in headers) {
 123        if (headerName.toLowerCase() === 'x-wp-nonce' && headers[headerName] === middleware.nonce) {
 124          return next(options);
 125        }
 126      }
 127  
 128      return next({ ...options,
 129        headers: { ...headers,
 130          'X-WP-Nonce': middleware.nonce
 131        }
 132      });
 133    };
 134  
 135    middleware.nonce = nonce;
 136    return middleware;
 137  }
 138  
 139  /* harmony default export */ var nonce = (createNonceMiddleware);
 140  
 141  // CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/namespace-endpoint.js
 142  /**
 143   * @type {import('../types').APIFetchMiddleware}
 144   */
 145  const namespaceAndEndpointMiddleware = (options, next) => {
 146    let path = options.path;
 147    let namespaceTrimmed, endpointTrimmed;
 148  
 149    if (typeof options.namespace === 'string' && typeof options.endpoint === 'string') {
 150      namespaceTrimmed = options.namespace.replace(/^\/|\/$/g, '');
 151      endpointTrimmed = options.endpoint.replace(/^\//, '');
 152  
 153      if (endpointTrimmed) {
 154        path = namespaceTrimmed + '/' + endpointTrimmed;
 155      } else {
 156        path = namespaceTrimmed;
 157      }
 158    }
 159  
 160    delete options.namespace;
 161    delete options.endpoint;
 162    return next({ ...options,
 163      path
 164    });
 165  };
 166  
 167  /* harmony default export */ var namespace_endpoint = (namespaceAndEndpointMiddleware);
 168  
 169  // CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/root-url.js
 170  /**
 171   * Internal dependencies
 172   */
 173  
 174  /**
 175   * @param {string} rootURL
 176   * @return {import('../types').APIFetchMiddleware} Root URL middleware.
 177   */
 178  
 179  const createRootURLMiddleware = rootURL => (options, next) => {
 180    return namespace_endpoint(options, optionsWithPath => {
 181      let url = optionsWithPath.url;
 182      let path = optionsWithPath.path;
 183      let apiRoot;
 184  
 185      if (typeof path === 'string') {
 186        apiRoot = rootURL;
 187  
 188        if (-1 !== rootURL.indexOf('?')) {
 189          path = path.replace('?', '&');
 190        }
 191  
 192        path = path.replace(/^\//, ''); // API root may already include query parameter prefix if site is
 193        // configured to use plain permalinks.
 194  
 195        if ('string' === typeof apiRoot && -1 !== apiRoot.indexOf('?')) {
 196          path = path.replace('?', '&');
 197        }
 198  
 199        url = apiRoot + path;
 200      }
 201  
 202      return next({ ...optionsWithPath,
 203        url
 204      });
 205    });
 206  };
 207  
 208  /* harmony default export */ var root_url = (createRootURLMiddleware);
 209  
 210  // CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/preloading.js
 211  /**
 212   * Given a path, returns a normalized path where equal query parameter values
 213   * will be treated as identical, regardless of order they appear in the original
 214   * text.
 215   *
 216   * @param {string} path Original path.
 217   *
 218   * @return {string} Normalized path.
 219   */
 220  function getStablePath(path) {
 221    const splitted = path.split('?');
 222    const query = splitted[1];
 223    const base = splitted[0];
 224  
 225    if (!query) {
 226      return base;
 227    } // 'b=1&c=2&a=5'
 228  
 229  
 230    return base + '?' + query // [ 'b=1', 'c=2', 'a=5' ]
 231    .split('&') // [ [ 'b, '1' ], [ 'c', '2' ], [ 'a', '5' ] ]
 232    .map(entry => entry.split('=')) // [ [ 'a', '5' ], [ 'b, '1' ], [ 'c', '2' ] ]
 233    .sort((a, b) => a[0].localeCompare(b[0])) // [ 'a=5', 'b=1', 'c=2' ]
 234    .map(pair => pair.join('=')) // 'a=5&b=1&c=2'
 235    .join('&');
 236  }
 237  /**
 238   * @param {Record<string, any>} preloadedData
 239   * @return {import('../types').APIFetchMiddleware} Preloading middleware.
 240   */
 241  
 242  function createPreloadingMiddleware(preloadedData) {
 243    const cache = Object.keys(preloadedData).reduce((result, path) => {
 244      result[getStablePath(path)] = preloadedData[path];
 245      return result;
 246    },
 247    /** @type {Record<string, any>} */
 248    {});
 249    return (options, next) => {
 250      const {
 251        parse = true
 252      } = options;
 253  
 254      if (typeof options.path === 'string') {
 255        const method = options.method || 'GET';
 256        const path = getStablePath(options.path);
 257  
 258        if ('GET' === method && cache[path]) {
 259          const cacheData = cache[path]; // Unsetting the cache key ensures that the data is only preloaded a single time
 260  
 261          delete cache[path];
 262          return Promise.resolve(parse ? cacheData.body : new window.Response(JSON.stringify(cacheData.body), {
 263            status: 200,
 264            statusText: 'OK',
 265            headers: cacheData.headers
 266          }));
 267        } else if ('OPTIONS' === method && cache[method] && cache[method][path]) {
 268          return Promise.resolve(parse ? cache[method][path].body : cache[method][path]);
 269        }
 270      }
 271  
 272      return next(options);
 273    };
 274  }
 275  
 276  /* harmony default export */ var preloading = (createPreloadingMiddleware);
 277  
 278  // EXTERNAL MODULE: external ["wp","url"]
 279  var external_wp_url_ = __webpack_require__("Mmq9");
 280  
 281  // CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/fetch-all-middleware.js
 282  /**
 283   * WordPress dependencies
 284   */
 285  
 286  /**
 287   * Internal dependencies
 288   */
 289  
 290  
 291  /**
 292   * Apply query arguments to both URL and Path, whichever is present.
 293   *
 294   * @param {import('../types').APIFetchOptions} props
 295   * @param {Record<string, string | number>} queryArgs
 296   * @return {import('../types').APIFetchOptions} The request with the modified query args
 297   */
 298  
 299  const modifyQuery = ({
 300    path,
 301    url,
 302    ...options
 303  }, queryArgs) => ({ ...options,
 304    url: url && Object(external_wp_url_["addQueryArgs"])(url, queryArgs),
 305    path: path && Object(external_wp_url_["addQueryArgs"])(path, queryArgs)
 306  });
 307  /**
 308   * Duplicates parsing functionality from apiFetch.
 309   *
 310   * @param {Response} response
 311   * @return {Promise<any>} Parsed response json.
 312   */
 313  
 314  
 315  const parseResponse = response => response.json ? response.json() : Promise.reject(response);
 316  /**
 317   * @param {string | null} linkHeader
 318   * @return {{ next?: string }} The parsed link header.
 319   */
 320  
 321  
 322  const parseLinkHeader = linkHeader => {
 323    if (!linkHeader) {
 324      return {};
 325    }
 326  
 327    const match = linkHeader.match(/<([^>]+)>; rel="next"/);
 328    return match ? {
 329      next: match[1]
 330    } : {};
 331  };
 332  /**
 333   * @param {Response} response
 334   * @return {string | undefined} The next page URL.
 335   */
 336  
 337  
 338  const getNextPageUrl = response => {
 339    const {
 340      next
 341    } = parseLinkHeader(response.headers.get('link'));
 342    return next;
 343  };
 344  /**
 345   * @param {import('../types').APIFetchOptions} options
 346   * @return {boolean} True if the request contains an unbounded query.
 347   */
 348  
 349  
 350  const requestContainsUnboundedQuery = options => {
 351    const pathIsUnbounded = !!options.path && options.path.indexOf('per_page=-1') !== -1;
 352    const urlIsUnbounded = !!options.url && options.url.indexOf('per_page=-1') !== -1;
 353    return pathIsUnbounded || urlIsUnbounded;
 354  };
 355  /**
 356   * The REST API enforces an upper limit on the per_page option. To handle large
 357   * collections, apiFetch consumers can pass `per_page=-1`; this middleware will
 358   * then recursively assemble a full response array from all available pages.
 359   *
 360   * @type {import('../types').APIFetchMiddleware}
 361   */
 362  
 363  
 364  const fetchAllMiddleware = async (options, next) => {
 365    if (options.parse === false) {
 366      // If a consumer has opted out of parsing, do not apply middleware.
 367      return next(options);
 368    }
 369  
 370    if (!requestContainsUnboundedQuery(options)) {
 371      // If neither url nor path is requesting all items, do not apply middleware.
 372      return next(options);
 373    } // Retrieve requested page of results.
 374  
 375  
 376    const response = await build_module({ ...modifyQuery(options, {
 377        per_page: 100
 378      }),
 379      // Ensure headers are returned for page 1.
 380      parse: false
 381    });
 382    const results = await parseResponse(response);
 383  
 384    if (!Array.isArray(results)) {
 385      // We have no reliable way of merging non-array results.
 386      return results;
 387    }
 388  
 389    let nextPage = getNextPageUrl(response);
 390  
 391    if (!nextPage) {
 392      // There are no further pages to request.
 393      return results;
 394    } // Iteratively fetch all remaining pages until no "next" header is found.
 395  
 396  
 397    let mergedResults =
 398    /** @type {any[]} */
 399    [].concat(results);
 400  
 401    while (nextPage) {
 402      const nextResponse = await build_module({ ...options,
 403        // Ensure the URL for the next page is used instead of any provided path.
 404        path: undefined,
 405        url: nextPage,
 406        // Ensure we still get headers so we can identify the next page.
 407        parse: false
 408      });
 409      const nextResults = await parseResponse(nextResponse);
 410      mergedResults = mergedResults.concat(nextResults);
 411      nextPage = getNextPageUrl(nextResponse);
 412    }
 413  
 414    return mergedResults;
 415  };
 416  
 417  /* harmony default export */ var fetch_all_middleware = (fetchAllMiddleware);
 418  
 419  // CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/http-v1.js
 420  /**
 421   * Set of HTTP methods which are eligible to be overridden.
 422   *
 423   * @type {Set<string>}
 424   */
 425  const OVERRIDE_METHODS = new Set(['PATCH', 'PUT', 'DELETE']);
 426  /**
 427   * Default request method.
 428   *
 429   * "A request has an associated method (a method). Unless stated otherwise it
 430   * is `GET`."
 431   *
 432   * @see  https://fetch.spec.whatwg.org/#requests
 433   *
 434   * @type {string}
 435   */
 436  
 437  const DEFAULT_METHOD = 'GET';
 438  /**
 439   * API Fetch middleware which overrides the request method for HTTP v1
 440   * compatibility leveraging the REST API X-HTTP-Method-Override header.
 441   *
 442   * @type {import('../types').APIFetchMiddleware}
 443   */
 444  
 445  const httpV1Middleware = (options, next) => {
 446    const {
 447      method = DEFAULT_METHOD
 448    } = options;
 449  
 450    if (OVERRIDE_METHODS.has(method.toUpperCase())) {
 451      options = { ...options,
 452        headers: { ...options.headers,
 453          'X-HTTP-Method-Override': method,
 454          'Content-Type': 'application/json'
 455        },
 456        method: 'POST'
 457      };
 458    }
 459  
 460    return next(options);
 461  };
 462  
 463  /* harmony default export */ var http_v1 = (httpV1Middleware);
 464  
 465  // CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/user-locale.js
 466  /**
 467   * WordPress dependencies
 468   */
 469  
 470  /**
 471   * @type {import('../types').APIFetchMiddleware}
 472   */
 473  
 474  const userLocaleMiddleware = (options, next) => {
 475    if (typeof options.url === 'string' && !Object(external_wp_url_["hasQueryArg"])(options.url, '_locale')) {
 476      options.url = Object(external_wp_url_["addQueryArgs"])(options.url, {
 477        _locale: 'user'
 478      });
 479    }
 480  
 481    if (typeof options.path === 'string' && !Object(external_wp_url_["hasQueryArg"])(options.path, '_locale')) {
 482      options.path = Object(external_wp_url_["addQueryArgs"])(options.path, {
 483        _locale: 'user'
 484      });
 485    }
 486  
 487    return next(options);
 488  };
 489  
 490  /* harmony default export */ var user_locale = (userLocaleMiddleware);
 491  
 492  // CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/utils/response.js
 493  /**
 494   * WordPress dependencies
 495   */
 496  
 497  /**
 498   * Parses the apiFetch response.
 499   *
 500   * @param {Response} response
 501   * @param {boolean}  shouldParseResponse
 502   *
 503   * @return {Promise<any> | null | Response} Parsed response.
 504   */
 505  
 506  const response_parseResponse = (response, shouldParseResponse = true) => {
 507    if (shouldParseResponse) {
 508      if (response.status === 204) {
 509        return null;
 510      }
 511  
 512      return response.json ? response.json() : Promise.reject(response);
 513    }
 514  
 515    return response;
 516  };
 517  /**
 518   * Calls the `json` function on the Response, throwing an error if the response
 519   * doesn't have a json function or if parsing the json itself fails.
 520   *
 521   * @param {Response} response
 522   * @return {Promise<any>} Parsed response.
 523   */
 524  
 525  
 526  const parseJsonAndNormalizeError = response => {
 527    const invalidJsonError = {
 528      code: 'invalid_json',
 529      message: Object(external_wp_i18n_["__"])('The response is not a valid JSON response.')
 530    };
 531  
 532    if (!response || !response.json) {
 533      throw invalidJsonError;
 534    }
 535  
 536    return response.json().catch(() => {
 537      throw invalidJsonError;
 538    });
 539  };
 540  /**
 541   * Parses the apiFetch response properly and normalize response errors.
 542   *
 543   * @param {Response} response
 544   * @param {boolean}  shouldParseResponse
 545   *
 546   * @return {Promise<any>} Parsed response.
 547   */
 548  
 549  
 550  const parseResponseAndNormalizeError = (response, shouldParseResponse = true) => {
 551    return Promise.resolve(response_parseResponse(response, shouldParseResponse)).catch(res => parseAndThrowError(res, shouldParseResponse));
 552  };
 553  /**
 554   * Parses a response, throwing an error if parsing the response fails.
 555   *
 556   * @param {Response} response
 557   * @param {boolean} shouldParseResponse
 558   * @return {Promise<any>} Parsed response.
 559   */
 560  
 561  function parseAndThrowError(response, shouldParseResponse = true) {
 562    if (!shouldParseResponse) {
 563      throw response;
 564    }
 565  
 566    return parseJsonAndNormalizeError(response).then(error => {
 567      const unknownError = {
 568        code: 'unknown_error',
 569        message: Object(external_wp_i18n_["__"])('An unknown error occurred.')
 570      };
 571      throw error || unknownError;
 572    });
 573  }
 574  
 575  // CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/middlewares/media-upload.js
 576  /**
 577   * WordPress dependencies
 578   */
 579  
 580  /**
 581   * Internal dependencies
 582   */
 583  
 584  
 585  /**
 586   * Middleware handling media upload failures and retries.
 587   *
 588   * @type {import('../types').APIFetchMiddleware}
 589   */
 590  
 591  const mediaUploadMiddleware = (options, next) => {
 592    const isMediaUploadRequest = options.path && options.path.indexOf('/wp/v2/media') !== -1 || options.url && options.url.indexOf('/wp/v2/media') !== -1;
 593  
 594    if (!isMediaUploadRequest) {
 595      return next(options);
 596    }
 597  
 598    let retries = 0;
 599    const maxRetries = 5;
 600    /**
 601     * @param {string} attachmentId
 602     * @return {Promise<any>} Processed post response.
 603     */
 604  
 605    const postProcess = attachmentId => {
 606      retries++;
 607      return next({
 608        path: `/wp/v2/media/$attachmentId}/post-process`,
 609        method: 'POST',
 610        data: {
 611          action: 'create-image-subsizes'
 612        },
 613        parse: false
 614      }).catch(() => {
 615        if (retries < maxRetries) {
 616          return postProcess(attachmentId);
 617        }
 618  
 619        next({
 620          path: `/wp/v2/media/$attachmentId}?force=true`,
 621          method: 'DELETE'
 622        });
 623        return Promise.reject();
 624      });
 625    };
 626  
 627    return next({ ...options,
 628      parse: false
 629    }).catch(response => {
 630      const attachmentId = response.headers.get('x-wp-upload-attachment-id');
 631  
 632      if (response.status >= 500 && response.status < 600 && attachmentId) {
 633        return postProcess(attachmentId).catch(() => {
 634          if (options.parse !== false) {
 635            return Promise.reject({
 636              code: 'post_process',
 637              message: Object(external_wp_i18n_["__"])('Media upload failed. If this is a photo or a large image, please scale it down and try again.')
 638            });
 639          }
 640  
 641          return Promise.reject(response);
 642        });
 643      }
 644  
 645      return parseAndThrowError(response, options.parse);
 646    }).then(response => parseResponseAndNormalizeError(response, options.parse));
 647  };
 648  
 649  /* harmony default export */ var media_upload = (mediaUploadMiddleware);
 650  
 651  // CONCATENATED MODULE: ./node_modules/@wordpress/api-fetch/build-module/index.js
 652  /**
 653   * WordPress dependencies
 654   */
 655  
 656  /**
 657   * Internal dependencies
 658   */
 659  
 660  
 661  
 662  
 663  
 664  
 665  
 666  
 667  
 668  
 669  /**
 670   * Default set of header values which should be sent with every request unless
 671   * explicitly provided through apiFetch options.
 672   *
 673   * @type {Record<string, string>}
 674   */
 675  
 676  const DEFAULT_HEADERS = {
 677    // The backend uses the Accept header as a condition for considering an
 678    // incoming request as a REST request.
 679    //
 680    // See: https://core.trac.wordpress.org/ticket/44534
 681    Accept: 'application/json, */*;q=0.1'
 682  };
 683  /**
 684   * Default set of fetch option values which should be sent with every request
 685   * unless explicitly provided through apiFetch options.
 686   *
 687   * @type {Object}
 688   */
 689  
 690  const DEFAULT_OPTIONS = {
 691    credentials: 'include'
 692  };
 693  /** @typedef {import('./types').APIFetchMiddleware} APIFetchMiddleware */
 694  
 695  /** @typedef {import('./types').APIFetchOptions} APIFetchOptions */
 696  
 697  /**
 698   * @type {import('./types').APIFetchMiddleware[]}
 699   */
 700  
 701  const middlewares = [user_locale, namespace_endpoint, http_v1, fetch_all_middleware];
 702  /**
 703   * Register a middleware
 704   *
 705   * @param {import('./types').APIFetchMiddleware} middleware
 706   */
 707  
 708  function registerMiddleware(middleware) {
 709    middlewares.unshift(middleware);
 710  }
 711  /**
 712   * Checks the status of a response, throwing the Response as an error if
 713   * it is outside the 200 range.
 714   *
 715   * @param {Response} response
 716   * @return {Response} The response if the status is in the 200 range.
 717   */
 718  
 719  
 720  const checkStatus = response => {
 721    if (response.status >= 200 && response.status < 300) {
 722      return response;
 723    }
 724  
 725    throw response;
 726  };
 727  /** @typedef {(options: import('./types').APIFetchOptions) => Promise<any>} FetchHandler*/
 728  
 729  /**
 730   * @type {FetchHandler}
 731   */
 732  
 733  
 734  const defaultFetchHandler = nextOptions => {
 735    const {
 736      url,
 737      path,
 738      data,
 739      parse = true,
 740      ...remainingOptions
 741    } = nextOptions;
 742    let {
 743      body,
 744      headers
 745    } = nextOptions; // Merge explicitly-provided headers with default values.
 746  
 747    headers = { ...DEFAULT_HEADERS,
 748      ...headers
 749    }; // The `data` property is a shorthand for sending a JSON body.
 750  
 751    if (data) {
 752      body = JSON.stringify(data);
 753      headers['Content-Type'] = 'application/json';
 754    }
 755  
 756    const responsePromise = window.fetch( // fall back to explicitly passing `window.location` which is the behavior if `undefined` is passed
 757    url || path || window.location.href, { ...DEFAULT_OPTIONS,
 758      ...remainingOptions,
 759      body,
 760      headers
 761    });
 762    return responsePromise // Return early if fetch errors. If fetch error, there is most likely no
 763    // network connection. Unfortunately fetch just throws a TypeError and
 764    // the message might depend on the browser.
 765    .then(value => Promise.resolve(value).then(checkStatus).catch(response => parseAndThrowError(response, parse)).then(response => parseResponseAndNormalizeError(response, parse)), () => {
 766      throw {
 767        code: 'fetch_error',
 768        message: Object(external_wp_i18n_["__"])('You are probably offline.')
 769      };
 770    });
 771  };
 772  /** @type {FetchHandler} */
 773  
 774  
 775  let fetchHandler = defaultFetchHandler;
 776  /**
 777   * Defines a custom fetch handler for making the requests that will override
 778   * the default one using window.fetch
 779   *
 780   * @param {FetchHandler} newFetchHandler The new fetch handler
 781   */
 782  
 783  function setFetchHandler(newFetchHandler) {
 784    fetchHandler = newFetchHandler;
 785  }
 786  /**
 787   * @template T
 788   * @param {import('./types').APIFetchOptions} options
 789   * @return {Promise<T>} A promise representing the request processed via the registered middlewares.
 790   */
 791  
 792  
 793  function apiFetch(options) {
 794    // creates a nested function chain that calls all middlewares and finally the `fetchHandler`,
 795    // converting `middlewares = [ m1, m2, m3 ]` into:
 796    // ```
 797    // opts1 => m1( opts1, opts2 => m2( opts2, opts3 => m3( opts3, fetchHandler ) ) );
 798    // ```
 799    const enhancedHandler = middlewares.reduceRight((
 800    /** @type {FetchHandler} */
 801    next, middleware) => {
 802      return workingOptions => middleware(workingOptions, next);
 803    }, fetchHandler);
 804    return enhancedHandler(options).catch(error => {
 805      if (error.code !== 'rest_cookie_invalid_nonce') {
 806        return Promise.reject(error);
 807      } // If the nonce is invalid, refresh it and try again.
 808  
 809  
 810      return window // @ts-ignore
 811      .fetch(apiFetch.nonceEndpoint).then(checkStatus).then(data => data.text()).then(text => {
 812        // @ts-ignore
 813        apiFetch.nonceMiddleware.nonce = text;
 814        return apiFetch(options);
 815      });
 816    });
 817  }
 818  
 819  apiFetch.use = registerMiddleware;
 820  apiFetch.setFetchHandler = setFetchHandler;
 821  apiFetch.createNonceMiddleware = nonce;
 822  apiFetch.createPreloadingMiddleware = preloading;
 823  apiFetch.createRootURLMiddleware = root_url;
 824  apiFetch.fetchAllMiddleware = fetch_all_middleware;
 825  apiFetch.mediaUploadMiddleware = media_upload;
 826  /* harmony default export */ var build_module = __webpack_exports__["default"] = (apiFetch);
 827  
 828  
 829  /***/ }),
 830  
 831  /***/ "l3Sj":
 832  /***/ (function(module, exports) {
 833  
 834  (function() { module.exports = window["wp"]["i18n"]; }());
 835  
 836  /***/ })
 837  
 838  /******/ })["default"];


Generated: Sun Aug 1 01:00:05 2021 Cross-referenced by PHPXref 0.7.1