"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// packages/api-fetch/src/index.ts
var index_exports = {};
__export(index_exports, {
  apiFetch: () => apiFetch,
  default: () => index_default
});
module.exports = __toCommonJS(index_exports);
var import_i18n = require("@wordpress/i18n");
var import_nonce = __toESM(require("./middlewares/nonce.cjs"));
var import_root_url = __toESM(require("./middlewares/root-url.cjs"));
var import_preloading = __toESM(require("./middlewares/preloading.cjs"));
var import_fetch_all_middleware = __toESM(require("./middlewares/fetch-all-middleware.cjs"));
var import_namespace_endpoint = __toESM(require("./middlewares/namespace-endpoint.cjs"));
var import_http_v1 = __toESM(require("./middlewares/http-v1.cjs"));
var import_user_locale = __toESM(require("./middlewares/user-locale.cjs"));
var import_media_upload = __toESM(require("./middlewares/media-upload.cjs"));
var import_theme_preview = __toESM(require("./middlewares/theme-preview.cjs"));
var import_response = require("./utils/response.cjs");
var DEFAULT_HEADERS = {
  // The backend uses the Accept header as a condition for considering an
  // incoming request as a REST request.
  //
  // See: https://core.trac.wordpress.org/ticket/44534
  Accept: "application/json, */*;q=0.1"
};
var DEFAULT_OPTIONS = {
  credentials: "include"
};
var middlewares = [
  import_user_locale.default,
  import_namespace_endpoint.default,
  import_http_v1.default,
  import_fetch_all_middleware.default
];
function registerMiddleware(middleware) {
  middlewares.unshift(middleware);
}
var defaultFetchHandler = (nextOptions) => {
  const { url, path, data, parse = true, ...remainingOptions } = nextOptions;
  let { body, headers } = nextOptions;
  headers = { ...DEFAULT_HEADERS, ...headers };
  if (data) {
    body = JSON.stringify(data);
    headers["Content-Type"] = "application/json";
  }
  const responsePromise = globalThis.fetch(
    // Fall back to explicitly passing `window.location` which is the behavior if `undefined` is passed.
    url || path || window.location.href,
    {
      ...DEFAULT_OPTIONS,
      ...remainingOptions,
      body,
      headers
    }
  );
  return responsePromise.then(
    (response) => {
      if (!response.ok) {
        return (0, import_response.parseAndThrowError)(response, parse);
      }
      return (0, import_response.parseResponseAndNormalizeError)(response, parse);
    },
    (err) => {
      if (err && err.name === "AbortError") {
        throw err;
      }
      if (!globalThis.navigator.onLine) {
        throw {
          code: "offline_error",
          message: (0, import_i18n.__)(
            "Unable to connect. Please check your Internet connection."
          )
        };
      }
      throw {
        code: "fetch_error",
        message: (0, import_i18n.__)(
          "Could not get a valid response from the server."
        )
      };
    }
  );
};
var fetchHandler = defaultFetchHandler;
function setFetchHandler(newFetchHandler) {
  fetchHandler = newFetchHandler;
}
var apiFetch = (options) => {
  const enhancedHandler = middlewares.reduceRight(
    (next, middleware) => {
      return (workingOptions) => middleware(workingOptions, next);
    },
    fetchHandler
  );
  return enhancedHandler(options).catch((error) => {
    if (error.code !== "rest_cookie_invalid_nonce") {
      return Promise.reject(error);
    }
    return globalThis.fetch(apiFetch.nonceEndpoint).then((response) => {
      if (!response.ok) {
        return Promise.reject(error);
      }
      return response.text();
    }).then((text) => {
      apiFetch.nonceMiddleware.nonce = text;
      return apiFetch(options);
    });
  });
};
apiFetch.use = registerMiddleware;
apiFetch.setFetchHandler = setFetchHandler;
apiFetch.createNonceMiddleware = import_nonce.default;
apiFetch.createPreloadingMiddleware = import_preloading.default;
apiFetch.createRootURLMiddleware = import_root_url.default;
apiFetch.fetchAllMiddleware = import_fetch_all_middleware.default;
apiFetch.mediaUploadMiddleware = import_media_upload.default;
apiFetch.createThemePreviewMiddleware = import_theme_preview.default;
var index_default = apiFetch;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  apiFetch
});
//# sourceMappingURL=index.cjs.map
