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);

// src/index.ts
var src_exports = {};
__export(src_exports, {
  REST: () => REST,
  default: () => src_default
});
module.exports = __toCommonJS(src_exports);
var import_node_url = require("node:url");

// src/REST.ts
var import_fetch = __toESM(require("@genee/fetch"));
var fetchingRequests = {};
var AbstractREST = class {
  baseUrl;
  constructor(baseUrl) {
    this.baseUrl = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
  }
  init() {
    return Promise.resolve();
  }
  _initPromise;
  _initializing = false;
  initOnlyOnce() {
    if (!this._initPromise) {
      this._initPromise = this.init().then(() => {
        this._initializing = true;
      });
      this._initPromise.finally(() => {
        this._initializing = false;
      });
    }
    return this._initPromise;
  }
  timeout = 5e3;
  hashsum;
  _cookie;
  get cookie() {
    return this._cookie;
  }
  rawRequest(method, path, body, init_) {
    const url = this.url(path);
    const init = {
      ...init_,
      method,
      headers: {
        ...init_?.headers,
        ...this.additionalHeaders
      },
      body,
      timeout: this.timeout,
      beforeRequest: (url2, init2) => {
        init_?.beforeRequest?.(url2, init2);
        if (this._cookie) {
          init2.headers = { ...init2.headers, cookie: this._cookie };
          init2.credentials = "include";
        }
      },
      customParser: (r, defaultParser) => {
        const setCookie = r.headers.get("set-cookie");
        if (setCookie) {
          this._cookie = setCookie.replace(/expires=(.+?);\s/gi, "").replace(/path=\/(,?)(\s?)/gi, "").trim();
        }
        return defaultParser(r);
      }
    };
    if (this.hashsum === void 0) {
      return (0, import_fetch.default)(url, init);
    }
    const hash = this.hashsum(url, body);
    if (!(hash in fetchingRequests)) {
      fetchingRequests[hash] = (0, import_fetch.default)(url, init);
      fetchingRequests[hash].finally(() => {
        delete fetchingRequests[hash];
      });
    }
    return fetchingRequests[hash];
  }
  reset() {
    this._initPromise = null;
    this._initializing = false;
  }
  request(method, path, body, init) {
    if (this._initializing) {
      throw new Error("you cannot call request inside init function, use rawRequest instead!");
    }
    return this.initOnlyOnce().then(() => this.rawRequest(method, path, body, init));
  }
  get(path, init) {
    return this.request("GET", path, init);
  }
  post(path, body, init) {
    return this.request("POST", path, body, init);
  }
  put(path, body, init) {
    return this.request("PUT", path, body, init);
  }
  patch(path, body, init) {
    return this.request("PATCH", path, body, init);
  }
  delete(path, init) {
    return this.request("DELETE", path, init);
  }
};

// src/index.ts
var REST = class extends AbstractREST {
  url(path) {
    let u;
    if (typeof path !== "string") {
      u = new import_node_url.URL(path.path.replace(/^[\/.]+/, ""), this.baseUrl);
      if (typeof path.query == "string") {
        new import_node_url.URLSearchParams(path.query).forEach((v, k) => u.searchParams.append(k, v));
      } else {
        Object.keys(path.query).forEach((k) => {
          const v = path.query[k];
          Array.isArray(v) ? v.forEach((vv) => u.searchParams.append(k, vv)) : u.searchParams.append(k, v);
        });
      }
    } else {
      u = new import_node_url.URL(path.replace(/^[\/.]+/, ""), this.baseUrl);
    }
    if (this.additionalQueries) {
      Object.keys(this.additionalQueries).forEach((k) => {
        const v = this.additionalQueries[k];
        Array.isArray(v) ? v.forEach((vv) => u.searchParams.append(k, vv)) : u.searchParams.append(k, v);
      });
    }
    return u.toString();
  }
};
var src_default = REST;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  REST
});
