[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

   1  /******/ (() => { // webpackBootstrap
   2  /******/     "use strict";
   3  /******/     // The require scope
   4  /******/     var __webpack_require__ = {};
   5  /******/     
   6  /************************************************************************/
   7  /******/     /* webpack/runtime/define property getters */
   8  /******/     (() => {
   9  /******/         // define getter functions for harmony exports
  10  /******/         __webpack_require__.d = (exports, definition) => {
  11  /******/             for(var key in definition) {
  12  /******/                 if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  13  /******/                     Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
  14  /******/                 }
  15  /******/             }
  16  /******/         };
  17  /******/     })();
  18  /******/     
  19  /******/     /* webpack/runtime/hasOwnProperty shorthand */
  20  /******/     (() => {
  21  /******/         __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
  22  /******/     })();
  23  /******/     
  24  /************************************************************************/
  25  var __webpack_exports__ = {};
  26  
  27  // EXPORTS
  28  __webpack_require__.d(__webpack_exports__, {
  29    "default": () => (/* binding */ index_default)
  30  });
  31  
  32  ;// external ["wp","i18n"]
  33  const external_wp_i18n_namespaceObject = window["wp"]["i18n"];
  34  ;// ./node_modules/@wordpress/api-fetch/build-module/middlewares/nonce.js
  35  function createNonceMiddleware(nonce) {
  36    const middleware = (options, next) => {
  37      const { headers = {} } = options;
  38      for (const headerName in headers) {
  39        if (headerName.toLowerCase() === "x-wp-nonce" && headers[headerName] === middleware.nonce) {
  40          return next(options);
  41        }
  42      }
  43      return next({
  44        ...options,
  45        headers: {
  46          ...headers,
  47          "X-WP-Nonce": middleware.nonce
  48        }
  49      });
  50    };
  51    middleware.nonce = nonce;
  52    return middleware;
  53  }
  54  var nonce_default = createNonceMiddleware;
  55  
  56  
  57  ;// ./node_modules/@wordpress/api-fetch/build-module/middlewares/namespace-endpoint.js
  58  const namespaceAndEndpointMiddleware = (options, next) => {
  59    let path = options.path;
  60    let namespaceTrimmed, endpointTrimmed;
  61    if (typeof options.namespace === "string" && typeof options.endpoint === "string") {
  62      namespaceTrimmed = options.namespace.replace(/^\/|\/$/g, "");
  63      endpointTrimmed = options.endpoint.replace(/^\//, "");
  64      if (endpointTrimmed) {
  65        path = namespaceTrimmed + "/" + endpointTrimmed;
  66      } else {
  67        path = namespaceTrimmed;
  68      }
  69    }
  70    delete options.namespace;
  71    delete options.endpoint;
  72    return next({
  73      ...options,
  74      path
  75    });
  76  };
  77  var namespace_endpoint_default = namespaceAndEndpointMiddleware;
  78  
  79  
  80  ;// ./node_modules/@wordpress/api-fetch/build-module/middlewares/root-url.js
  81  
  82  const createRootURLMiddleware = (rootURL) => (options, next) => {
  83    return namespace_endpoint_default(options, (optionsWithPath) => {
  84      let url = optionsWithPath.url;
  85      let path = optionsWithPath.path;
  86      let apiRoot;
  87      if (typeof path === "string") {
  88        apiRoot = rootURL;
  89        if (-1 !== rootURL.indexOf("?")) {
  90          path = path.replace("?", "&");
  91        }
  92        path = path.replace(/^\//, "");
  93        if ("string" === typeof apiRoot && -1 !== apiRoot.indexOf("?")) {
  94          path = path.replace("?", "&");
  95        }
  96        url = apiRoot + path;
  97      }
  98      return next({
  99        ...optionsWithPath,
 100        url
 101      });
 102    });
 103  };
 104  var root_url_default = createRootURLMiddleware;
 105  
 106  
 107  ;// external ["wp","url"]
 108  const external_wp_url_namespaceObject = window["wp"]["url"];
 109  ;// ./node_modules/@wordpress/api-fetch/build-module/middlewares/preloading.js
 110  
 111  function createPreloadingMiddleware(preloadedData) {
 112    const cache = Object.fromEntries(
 113      Object.entries(preloadedData).map(([path, data]) => [
 114        (0,external_wp_url_namespaceObject.normalizePath)(path),
 115        data
 116      ])
 117    );
 118    return (options, next) => {
 119      const { parse = true } = options;
 120      let rawPath = options.path;
 121      if (!rawPath && options.url) {
 122        const { rest_route: pathFromQuery, ...queryArgs } = (0,external_wp_url_namespaceObject.getQueryArgs)(
 123          options.url
 124        );
 125        if (typeof pathFromQuery === "string") {
 126          rawPath = (0,external_wp_url_namespaceObject.addQueryArgs)(pathFromQuery, queryArgs);
 127        }
 128      }
 129      if (typeof rawPath !== "string") {
 130        return next(options);
 131      }
 132      const method = options.method || "GET";
 133      const path = (0,external_wp_url_namespaceObject.normalizePath)(rawPath);
 134      if ("GET" === method && cache[path]) {
 135        const cacheData = cache[path];
 136        delete cache[path];
 137        return prepareResponse(cacheData, !!parse);
 138      } else if ("OPTIONS" === method && cache[method] && cache[method][path]) {
 139        const cacheData = cache[method][path];
 140        delete cache[method][path];
 141        return prepareResponse(cacheData, !!parse);
 142      }
 143      return next(options);
 144    };
 145  }
 146  function prepareResponse(responseData, parse) {
 147    if (parse) {
 148      return Promise.resolve(responseData.body);
 149    }
 150    try {
 151      return Promise.resolve(
 152        new window.Response(JSON.stringify(responseData.body), {
 153          status: 200,
 154          statusText: "OK",
 155          headers: responseData.headers
 156        })
 157      );
 158    } catch {
 159      Object.entries(
 160        responseData.headers
 161      ).forEach(([key, value]) => {
 162        if (key.toLowerCase() === "link") {
 163          responseData.headers[key] = value.replace(
 164            /<([^>]+)>/,
 165            (_, url) => `<$encodeURI(url)}>`
 166          );
 167        }
 168      });
 169      return Promise.resolve(
 170        parse ? responseData.body : new window.Response(JSON.stringify(responseData.body), {
 171          status: 200,
 172          statusText: "OK",
 173          headers: responseData.headers
 174        })
 175      );
 176    }
 177  }
 178  var preloading_default = createPreloadingMiddleware;
 179  
 180  
 181  ;// ./node_modules/@wordpress/api-fetch/build-module/middlewares/fetch-all-middleware.js
 182  
 183  
 184  const modifyQuery = ({ path, url, ...options }, queryArgs) => ({
 185    ...options,
 186    url: url && (0,external_wp_url_namespaceObject.addQueryArgs)(url, queryArgs),
 187    path: path && (0,external_wp_url_namespaceObject.addQueryArgs)(path, queryArgs)
 188  });
 189  const parseResponse = (response) => response.json ? response.json() : Promise.reject(response);
 190  const parseLinkHeader = (linkHeader) => {
 191    if (!linkHeader) {
 192      return {};
 193    }
 194    const match = linkHeader.match(/<([^>]+)>; rel="next"/);
 195    return match ? {
 196      next: match[1]
 197    } : {};
 198  };
 199  const getNextPageUrl = (response) => {
 200    const { next } = parseLinkHeader(response.headers.get("link"));
 201    return next;
 202  };
 203  const requestContainsUnboundedQuery = (options) => {
 204    const pathIsUnbounded = !!options.path && options.path.indexOf("per_page=-1") !== -1;
 205    const urlIsUnbounded = !!options.url && options.url.indexOf("per_page=-1") !== -1;
 206    return pathIsUnbounded || urlIsUnbounded;
 207  };
 208  const fetchAllMiddleware = async (options, next) => {
 209    if (options.parse === false) {
 210      return next(options);
 211    }
 212    if (!requestContainsUnboundedQuery(options)) {
 213      return next(options);
 214    }
 215    const response = await index_default({
 216      ...modifyQuery(options, {
 217        per_page: 100
 218      }),
 219      // Ensure headers are returned for page 1.
 220      parse: false
 221    });
 222    const results = await parseResponse(response);
 223    if (!Array.isArray(results)) {
 224      return results;
 225    }
 226    let nextPage = getNextPageUrl(response);
 227    if (!nextPage) {
 228      return results;
 229    }
 230    let mergedResults = [].concat(results);
 231    while (nextPage) {
 232      const nextResponse = await index_default({
 233        ...options,
 234        // Ensure the URL for the next page is used instead of any provided path.
 235        path: void 0,
 236        url: nextPage,
 237        // Ensure we still get headers so we can identify the next page.
 238        parse: false
 239      });
 240      const nextResults = await parseResponse(nextResponse);
 241      mergedResults = mergedResults.concat(nextResults);
 242      nextPage = getNextPageUrl(nextResponse);
 243    }
 244    return mergedResults;
 245  };
 246  var fetch_all_middleware_default = fetchAllMiddleware;
 247  
 248  
 249  ;// ./node_modules/@wordpress/api-fetch/build-module/middlewares/http-v1.js
 250  const OVERRIDE_METHODS = /* @__PURE__ */ new Set(["PATCH", "PUT", "DELETE"]);
 251  const DEFAULT_METHOD = "GET";
 252  const httpV1Middleware = (options, next) => {
 253    const { method = DEFAULT_METHOD } = options;
 254    if (OVERRIDE_METHODS.has(method.toUpperCase())) {
 255      options = {
 256        ...options,
 257        headers: {
 258          ...options.headers,
 259          "X-HTTP-Method-Override": method,
 260          "Content-Type": "application/json"
 261        },
 262        method: "POST"
 263      };
 264    }
 265    return next(options);
 266  };
 267  var http_v1_default = httpV1Middleware;
 268  
 269  
 270  ;// ./node_modules/@wordpress/api-fetch/build-module/middlewares/user-locale.js
 271  
 272  const userLocaleMiddleware = (options, next) => {
 273    if (typeof options.url === "string" && !(0,external_wp_url_namespaceObject.hasQueryArg)(options.url, "_locale")) {
 274      options.url = (0,external_wp_url_namespaceObject.addQueryArgs)(options.url, { _locale: "user" });
 275    }
 276    if (typeof options.path === "string" && !(0,external_wp_url_namespaceObject.hasQueryArg)(options.path, "_locale")) {
 277      options.path = (0,external_wp_url_namespaceObject.addQueryArgs)(options.path, { _locale: "user" });
 278    }
 279    return next(options);
 280  };
 281  var user_locale_default = userLocaleMiddleware;
 282  
 283  
 284  ;// ./node_modules/@wordpress/api-fetch/build-module/utils/response.js
 285  
 286  async function parseJsonAndNormalizeError(response) {
 287    try {
 288      return await response.json();
 289    } catch {
 290      throw {
 291        code: "invalid_json",
 292        message: (0,external_wp_i18n_namespaceObject.__)("The response is not a valid JSON response.")
 293      };
 294    }
 295  }
 296  async function parseResponseAndNormalizeError(response, shouldParseResponse = true) {
 297    if (!shouldParseResponse) {
 298      return response;
 299    }
 300    if (response.status === 204) {
 301      return null;
 302    }
 303    return await parseJsonAndNormalizeError(response);
 304  }
 305  async function parseAndThrowError(response, shouldParseResponse = true) {
 306    if (!shouldParseResponse) {
 307      throw response;
 308    }
 309    throw await parseJsonAndNormalizeError(response);
 310  }
 311  
 312  
 313  ;// ./node_modules/@wordpress/api-fetch/build-module/middlewares/media-upload.js
 314  
 315  
 316  function isMediaUploadRequest(options) {
 317    const isCreateMethod = !!options.method && options.method === "POST";
 318    const isMediaEndpoint = !!options.path && options.path.indexOf("/wp/v2/media") !== -1 || !!options.url && options.url.indexOf("/wp/v2/media") !== -1;
 319    return isMediaEndpoint && isCreateMethod;
 320  }
 321  const mediaUploadMiddleware = (options, next) => {
 322    if (!isMediaUploadRequest(options)) {
 323      return next(options);
 324    }
 325    let retries = 0;
 326    const maxRetries = 5;
 327    const postProcess = (attachmentId) => {
 328      retries++;
 329      return next({
 330        path: `/wp/v2/media/$attachmentId}/post-process`,
 331        method: "POST",
 332        data: { action: "create-image-subsizes" },
 333        parse: false
 334      }).catch(() => {
 335        if (retries < maxRetries) {
 336          return postProcess(attachmentId);
 337        }
 338        next({
 339          path: `/wp/v2/media/$attachmentId}?force=true`,
 340          method: "DELETE"
 341        });
 342        return Promise.reject();
 343      });
 344    };
 345    return next({ ...options, parse: false }).catch((response) => {
 346      if (!(response instanceof globalThis.Response)) {
 347        return Promise.reject(response);
 348      }
 349      const attachmentId = response.headers.get(
 350        "x-wp-upload-attachment-id"
 351      );
 352      if (response.status >= 500 && response.status < 600 && attachmentId) {
 353        return postProcess(attachmentId).catch(() => {
 354          if (options.parse !== false) {
 355            return Promise.reject({
 356              code: "post_process",
 357              message: (0,external_wp_i18n_namespaceObject.__)(
 358                "Media upload failed. If this is a photo or a large image, please scale it down and try again."
 359              )
 360            });
 361          }
 362          return Promise.reject(response);
 363        });
 364      }
 365      return parseAndThrowError(response, options.parse);
 366    }).then(
 367      (response) => parseResponseAndNormalizeError(response, options.parse)
 368    );
 369  };
 370  var media_upload_default = mediaUploadMiddleware;
 371  
 372  
 373  ;// ./node_modules/@wordpress/api-fetch/build-module/middlewares/theme-preview.js
 374  
 375  const createThemePreviewMiddleware = (themePath) => (options, next) => {
 376    if (typeof options.url === "string") {
 377      const wpThemePreview = (0,external_wp_url_namespaceObject.getQueryArg)(
 378        options.url,
 379        "wp_theme_preview"
 380      );
 381      if (wpThemePreview === void 0) {
 382        options.url = (0,external_wp_url_namespaceObject.addQueryArgs)(options.url, {
 383          wp_theme_preview: themePath
 384        });
 385      } else if (wpThemePreview === "") {
 386        options.url = (0,external_wp_url_namespaceObject.removeQueryArgs)(
 387          options.url,
 388          "wp_theme_preview"
 389        );
 390      }
 391    }
 392    if (typeof options.path === "string") {
 393      const wpThemePreview = (0,external_wp_url_namespaceObject.getQueryArg)(
 394        options.path,
 395        "wp_theme_preview"
 396      );
 397      if (wpThemePreview === void 0) {
 398        options.path = (0,external_wp_url_namespaceObject.addQueryArgs)(options.path, {
 399          wp_theme_preview: themePath
 400        });
 401      } else if (wpThemePreview === "") {
 402        options.path = (0,external_wp_url_namespaceObject.removeQueryArgs)(
 403          options.path,
 404          "wp_theme_preview"
 405        );
 406      }
 407    }
 408    return next(options);
 409  };
 410  var theme_preview_default = createThemePreviewMiddleware;
 411  
 412  
 413  ;// ./node_modules/@wordpress/api-fetch/build-module/index.js
 414  
 415  
 416  
 417  
 418  
 419  
 420  
 421  
 422  
 423  
 424  
 425  const DEFAULT_HEADERS = {
 426    // The backend uses the Accept header as a condition for considering an
 427    // incoming request as a REST request.
 428    //
 429    // See: https://core.trac.wordpress.org/ticket/44534
 430    Accept: "application/json, */*;q=0.1"
 431  };
 432  const DEFAULT_OPTIONS = {
 433    credentials: "include"
 434  };
 435  const middlewares = [
 436    user_locale_default,
 437    namespace_endpoint_default,
 438    http_v1_default,
 439    fetch_all_middleware_default
 440  ];
 441  function registerMiddleware(middleware) {
 442    middlewares.unshift(middleware);
 443  }
 444  const defaultFetchHandler = (nextOptions) => {
 445    const { url, path, data, parse = true, ...remainingOptions } = nextOptions;
 446    let { body, headers } = nextOptions;
 447    headers = { ...DEFAULT_HEADERS, ...headers };
 448    if (data) {
 449      body = JSON.stringify(data);
 450      headers["Content-Type"] = "application/json";
 451    }
 452    const responsePromise = globalThis.fetch(
 453      // Fall back to explicitly passing `window.location` which is the behavior if `undefined` is passed.
 454      url || path || window.location.href,
 455      {
 456        ...DEFAULT_OPTIONS,
 457        ...remainingOptions,
 458        body,
 459        headers
 460      }
 461    );
 462    return responsePromise.then(
 463      (response) => {
 464        if (!response.ok) {
 465          return parseAndThrowError(response, parse);
 466        }
 467        return parseResponseAndNormalizeError(response, parse);
 468      },
 469      (err) => {
 470        if (err && err.name === "AbortError") {
 471          throw err;
 472        }
 473        if (!globalThis.navigator.onLine) {
 474          throw {
 475            code: "offline_error",
 476            message: (0,external_wp_i18n_namespaceObject.__)(
 477              "Unable to connect. Please check your Internet connection."
 478            )
 479          };
 480        }
 481        throw {
 482          code: "fetch_error",
 483          message: (0,external_wp_i18n_namespaceObject.__)(
 484            "Could not get a valid response from the server."
 485          )
 486        };
 487      }
 488    );
 489  };
 490  let fetchHandler = defaultFetchHandler;
 491  function setFetchHandler(newFetchHandler) {
 492    fetchHandler = newFetchHandler;
 493  }
 494  const apiFetch = (options) => {
 495    const enhancedHandler = middlewares.reduceRight(
 496      (next, middleware) => {
 497        return (workingOptions) => middleware(workingOptions, next);
 498      },
 499      fetchHandler
 500    );
 501    return enhancedHandler(options).catch((error) => {
 502      if (error.code !== "rest_cookie_invalid_nonce") {
 503        return Promise.reject(error);
 504      }
 505      return globalThis.fetch(apiFetch.nonceEndpoint).then((response) => {
 506        if (!response.ok) {
 507          return Promise.reject(error);
 508        }
 509        return response.text();
 510      }).then((text) => {
 511        apiFetch.nonceMiddleware.nonce = text;
 512        return apiFetch(options);
 513      });
 514    });
 515  };
 516  apiFetch.use = registerMiddleware;
 517  apiFetch.setFetchHandler = setFetchHandler;
 518  apiFetch.createNonceMiddleware = nonce_default;
 519  apiFetch.createPreloadingMiddleware = preloading_default;
 520  apiFetch.createRootURLMiddleware = root_url_default;
 521  apiFetch.fetchAllMiddleware = fetch_all_middleware_default;
 522  apiFetch.mediaUploadMiddleware = media_upload_default;
 523  apiFetch.createThemePreviewMiddleware = theme_preview_default;
 524  var index_default = apiFetch;
 525  
 526  
 527  
 528  (window.wp = window.wp || {}).apiFetch = __webpack_exports__["default"];
 529  /******/ })()
 530  ;


Generated : Wed Oct 29 08:20:06 2025 Cross-referenced by PHPXref