// src/index.ts
import { URL, URLSearchParams } from "node:url";

// src/REST.ts
import fetch from "@genee/fetch";
var fetchingRequests = {};
var AbstractREST = class {
  constructor(baseUrl) {
    this._initializing = false;
    this.baseUrl = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
  }
  init() {
    return Promise.resolve();
  }
  initOnlyOnce() {
    if (!this._initPromise) {
      this._initPromise = this.init().then(() => {
        this._initializing = true;
      });
      this._initPromise.finally(() => {
        this._initializing = false;
      });
    }
    return this._initPromise;
  }
  rawRequest(method, path, body) {
    const url = this.url(path);
    const init = {
      method,
      headers: {
        ...this.additionalHeaders
      },
      body
    };
    if (this.hashsum === void 0) {
      return fetch(url, init);
    }
    const hash = this.hashsum(url, body);
    if (!(hash in fetchingRequests)) {
      fetchingRequests[hash] = fetch(url, init);
      fetchingRequests[hash].finally(() => {
        delete fetchingRequests[hash];
      });
    }
    return fetchingRequests[hash];
  }
  reset() {
    this._initPromise = null;
    this._initializing = false;
  }
  request(method, path, body) {
    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));
  }
  get(path) {
    return this.request("GET", path);
  }
  post(path, body) {
    return this.request("POST", path, body);
  }
  put(path, body) {
    return this.request("PUT", path, body);
  }
  patch(path, body) {
    return this.request("PATCH", path, body);
  }
  delete(path) {
    return this.request("DELETE", path);
  }
};

// src/index.ts
var REST = class extends AbstractREST {
  url(path) {
    let u;
    if (typeof path !== "string") {
      u = new URL(path.path.replace(/^[\/.]+/, ""), this.baseUrl);
      if (typeof path.query == "string") {
        new 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 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;
export {
  REST,
  src_default as default
};
