"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 __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
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
));

// ../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js
var require_fast_deep_equal = __commonJS({
  "../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js"(exports2, module2) {
    "use strict";
    module2.exports = function equal(a, b) {
      if (a === b) return true;
      if (a && b && typeof a == "object" && typeof b == "object") {
        if (a.constructor !== b.constructor) return false;
        var length, i, keys;
        if (Array.isArray(a)) {
          length = a.length;
          if (length != b.length) return false;
          for (i = length; i-- !== 0; )
            if (!equal(a[i], b[i])) return false;
          return true;
        }
        if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
        if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
        if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
        keys = Object.keys(a);
        length = keys.length;
        if (length !== Object.keys(b).length) return false;
        for (i = length; i-- !== 0; )
          if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
        for (i = length; i-- !== 0; ) {
          var key = keys[i];
          if (!equal(a[key], b[key])) return false;
        }
        return true;
      }
      return a !== a && b !== b;
    };
  }
});

// ../../node_modules/.pnpm/is-buffer@2.0.5/node_modules/is-buffer/index.js
var require_is_buffer = __commonJS({
  "../../node_modules/.pnpm/is-buffer@2.0.5/node_modules/is-buffer/index.js"(exports2, module2) {
    "use strict";
    module2.exports = function isBuffer(obj) {
      return obj != null && obj.constructor != null && typeof obj.constructor.isBuffer === "function" && obj.constructor.isBuffer(obj);
    };
  }
});

// ../../node_modules/.pnpm/axios-mock-adapter@1.22.0_axios@1.7.2/node_modules/axios-mock-adapter/src/is_blob.js
var require_is_blob = __commonJS({
  "../../node_modules/.pnpm/axios-mock-adapter@1.22.0_axios@1.7.2/node_modules/axios-mock-adapter/src/is_blob.js"(exports2, module2) {
    "use strict";
    function isBlob(value) {
      if (typeof Blob === "undefined") {
        return false;
      }
      return value instanceof Blob || Object.prototype.toString.call(value) === "[object Blob]";
    }
    module2.exports = isBlob;
  }
});

// ../../node_modules/.pnpm/axios-mock-adapter@1.22.0_axios@1.7.2/node_modules/axios-mock-adapter/src/utils.js
var require_utils = __commonJS({
  "../../node_modules/.pnpm/axios-mock-adapter@1.22.0_axios@1.7.2/node_modules/axios-mock-adapter/src/utils.js"(exports2, module2) {
    "use strict";
    var axios3 = require("axios");
    var isEqual = require_fast_deep_equal();
    var isBuffer = require_is_buffer();
    var isBlob = require_is_blob();
    var toString = Object.prototype.toString;
    function find(array, predicate) {
      var length = array.length;
      for (var i = 0; i < length; i++) {
        var value = array[i];
        if (predicate(value)) return value;
      }
    }
    function isFunction(val) {
      return toString.call(val) === "[object Function]";
    }
    function isObjectOrArray(val) {
      return val !== null && typeof val === "object";
    }
    function isStream(val) {
      return isObjectOrArray(val) && isFunction(val.pipe);
    }
    function isArrayBuffer(val) {
      return toString.call(val) === "[object ArrayBuffer]";
    }
    function combineUrls(baseURL, url) {
      if (baseURL) {
        return baseURL.replace(/\/+$/, "") + "/" + url.replace(/^\/+/, "");
      }
      return url;
    }
    function findHandler(handlers, method, url, body, parameters, headers, baseURL) {
      return find(handlers[method.toLowerCase()], function(handler) {
        if (typeof handler[0] === "string") {
          return (isUrlMatching(url, handler[0]) || isUrlMatching(combineUrls(baseURL, url), handler[0])) && isBodyOrParametersMatching(method, body, parameters, handler[1]) && isObjectMatching(headers, handler[2]);
        } else if (handler[0] instanceof RegExp) {
          return (handler[0].test(url) || handler[0].test(combineUrls(baseURL, url))) && isBodyOrParametersMatching(method, body, parameters, handler[1]) && isObjectMatching(headers, handler[2]);
        }
      });
    }
    function isUrlMatching(url, required) {
      var noSlashUrl = url[0] === "/" ? url.substr(1) : url;
      var noSlashRequired = required[0] === "/" ? required.substr(1) : required;
      return noSlashUrl === noSlashRequired;
    }
    function isBodyOrParametersMatching(method, body, parameters, required) {
      var allowedParamsMethods = ["delete", "get", "head", "options"];
      if (allowedParamsMethods.indexOf(method.toLowerCase()) >= 0) {
        var data = required ? required.data : void 0;
        var params = required ? required.params : void 0;
        return isObjectMatching(parameters, params) && isBodyMatching(body, data);
      } else {
        return isBodyMatching(body, required);
      }
    }
    function isObjectMatching(actual, expected) {
      if (expected === void 0) return true;
      if (typeof expected.asymmetricMatch === "function") {
        return expected.asymmetricMatch(actual);
      }
      return isEqual(actual, expected);
    }
    function isBodyMatching(body, requiredBody) {
      if (requiredBody === void 0) {
        return true;
      }
      var parsedBody;
      try {
        parsedBody = JSON.parse(body);
      } catch (e) {
      }
      return isObjectMatching(parsedBody ? parsedBody : body, requiredBody);
    }
    function purgeIfReplyOnce(mock, handler) {
      Object.keys(mock.handlers).forEach(function(key) {
        var index = mock.handlers[key].indexOf(handler);
        if (index > -1) {
          mock.handlers[key].splice(index, 1);
        }
      });
    }
    function settle(resolve, reject, response, delay) {
      if (delay > 0) {
        setTimeout(settle, delay, resolve, reject, response);
        return;
      }
      if (!response.config.validateStatus || response.config.validateStatus(response.status)) {
        resolve(response);
      } else {
        reject(
          createAxiosError(
            "Request failed with status code " + response.status,
            response.config,
            response
          )
        );
      }
    }
    function createAxiosError(message, config, response, code) {
      if (typeof axios3.AxiosError === "function") {
        return axios3.AxiosError.from(new Error(message), code, config, null, response);
      }
      var error = new Error(message);
      error.isAxiosError = true;
      error.config = config;
      if (response !== void 0) {
        error.response = response;
      }
      if (code !== void 0) {
        error.code = code;
      }
      error.toJSON = function toJSON() {
        return {
          // Standard
          message: this.message,
          name: this.name,
          // Microsoft
          description: this.description,
          number: this.number,
          // Mozilla
          fileName: this.fileName,
          lineNumber: this.lineNumber,
          columnNumber: this.columnNumber,
          stack: this.stack,
          // Axios
          config: this.config,
          code: this.code
        };
      };
      return error;
    }
    function createCouldNotFindMockError(config) {
      var message = "Could not find mock for: \n" + JSON.stringify(config, ["method", "url"], 2);
      var error = new Error(message);
      error.isCouldNotFindMockError = true;
      error.url = config.url;
      error.method = config.method;
      return error;
    }
    module2.exports = {
      find,
      findHandler,
      purgeIfReplyOnce,
      settle,
      isStream,
      isArrayBuffer,
      isFunction,
      isObjectOrArray,
      isBuffer,
      isBlob,
      isBodyOrParametersMatching,
      isEqual,
      createAxiosError,
      createCouldNotFindMockError
    };
  }
});

// ../../node_modules/.pnpm/axios-mock-adapter@1.22.0_axios@1.7.2/node_modules/axios-mock-adapter/src/handle_request.js
var require_handle_request = __commonJS({
  "../../node_modules/.pnpm/axios-mock-adapter@1.22.0_axios@1.7.2/node_modules/axios-mock-adapter/src/handle_request.js"(exports2, module2) {
    "use strict";
    var utils = require_utils();
    function transformRequest(data) {
      if (utils.isArrayBuffer(data) || utils.isBuffer(data) || utils.isStream(data) || utils.isBlob(data)) {
        return data;
      }
      if (utils.isObjectOrArray(data)) {
        return JSON.parse(JSON.stringify(data));
      }
      return data;
    }
    function makeResponse(result, config) {
      return {
        status: result[0],
        data: transformRequest(result[1]),
        headers: result[2],
        config,
        request: {
          responseURL: config.url
        }
      };
    }
    function passThroughRequest(mockAdapter, resolve, reject, config) {
      var baseURL = config.baseURL;
      if (config.baseURL && !/^https?:/.test(config.baseURL)) {
        baseURL = void 0;
      }
      if (typeof mockAdapter.originalAdapter === "function") {
        return mockAdapter.originalAdapter(config).then(resolve, reject);
      }
      mockAdapter.axiosInstanceWithoutInterceptors(Object.assign({}, config, {
        baseURL,
        //  Use the original adapter, not the mock adapter
        adapter: mockAdapter.originalAdapter,
        // The request transformation runs on the original axios handler already
        transformRequest: [],
        transformResponse: []
      })).then(resolve, reject);
    }
    function handleRequest(mockAdapter, resolve, reject, config) {
      var url = config.url || "";
      if (config.baseURL && url.substr(0, config.baseURL.length) === config.baseURL) {
        url = url.slice(config.baseURL.length);
      }
      delete config.adapter;
      mockAdapter.history[config.method].push(config);
      var handler = utils.findHandler(
        mockAdapter.handlers,
        config.method,
        url,
        config.data,
        config.params,
        config.headers && config.headers.constructor.name === "AxiosHeaders" ? Object.assign({}, config.headers) : config.headers,
        config.baseURL
      );
      if (handler) {
        if (handler.length === 7) {
          utils.purgeIfReplyOnce(mockAdapter, handler);
        }
        if (handler.length === 2) {
          passThroughRequest(mockAdapter, resolve, reject, config);
        } else if (typeof handler[3] !== "function") {
          utils.settle(
            resolve,
            reject,
            makeResponse(handler.slice(3), config),
            getEffectiveDelay(mockAdapter, handler)
          );
        } else {
          var result = handler[3](config);
          if (typeof result.then !== "function") {
            utils.settle(
              resolve,
              reject,
              makeResponse(result, config),
              getEffectiveDelay(mockAdapter, handler)
            );
          } else {
            result.then(
              function(result2) {
                if (result2.config && result2.status) {
                  utils.settle(
                    resolve,
                    reject,
                    makeResponse(
                      [result2.status, result2.data, result2.headers],
                      result2.config
                    ),
                    0
                  );
                } else {
                  utils.settle(
                    resolve,
                    reject,
                    makeResponse(result2, config),
                    getEffectiveDelay(mockAdapter, handler)
                  );
                }
              },
              function(error) {
                if (mockAdapter.delayResponse > 0) {
                  setTimeout(function() {
                    reject(error);
                  }, getEffectiveDelay(mockAdapter, handler));
                } else {
                  reject(error);
                }
              }
            );
          }
        }
      } else {
        switch (mockAdapter.onNoMatch) {
          case "passthrough":
            passThroughRequest(mockAdapter, resolve, reject, config);
            break;
          case "throwException":
            throw utils.createCouldNotFindMockError(config);
          default:
            utils.settle(
              resolve,
              reject,
              {
                status: 404,
                config
              },
              mockAdapter.delayResponse
            );
        }
      }
    }
    function getEffectiveDelay(adapter, handler) {
      var delayPerRequest;
      if (handler.length === 8) {
        delayPerRequest = handler[7];
      }
      return delayPerRequest ? delayPerRequest : adapter.delayResponse;
    }
    module2.exports = handleRequest;
  }
});

// ../../node_modules/.pnpm/axios-mock-adapter@1.22.0_axios@1.7.2/node_modules/axios-mock-adapter/src/index.js
var require_src = __commonJS({
  "../../node_modules/.pnpm/axios-mock-adapter@1.22.0_axios@1.7.2/node_modules/axios-mock-adapter/src/index.js"(exports2, module2) {
    "use strict";
    var handleRequest = require_handle_request();
    var utils = require_utils();
    var VERBS = [
      "get",
      "post",
      "head",
      "delete",
      "patch",
      "put",
      "options",
      "list",
      "link",
      "unlink"
    ];
    function adapter() {
      return function(config) {
        var mockAdapter = this;
        return new Promise(function(resolve, reject) {
          handleRequest(mockAdapter, resolve, reject, config);
        });
      }.bind(this);
    }
    function getVerbObject() {
      return VERBS.reduce(function(accumulator, verb) {
        accumulator[verb] = [];
        return accumulator;
      }, {});
    }
    function reset() {
      resetHandlers.call(this);
      resetHistory.call(this);
    }
    function resetHandlers() {
      this.handlers = getVerbObject();
    }
    function resetHistory() {
      this.history = getVerbObject();
    }
    function MockAdapter2(axiosInstance, options) {
      reset.call(this);
      if (axiosInstance) {
        this.axiosInstance = axiosInstance;
        this.axiosInstanceWithoutInterceptors = axiosInstance.create ? axiosInstance.create() : void 0;
        this.originalAdapter = axiosInstance.defaults.adapter;
        this.delayResponse = options && options.delayResponse > 0 ? options.delayResponse : null;
        this.onNoMatch = options && options.onNoMatch || null;
        axiosInstance.defaults.adapter = this.adapter.call(this);
      } else {
        throw new Error("Please provide an instance of axios to mock");
      }
    }
    MockAdapter2.prototype.adapter = adapter;
    MockAdapter2.prototype.restore = function restore() {
      if (this.axiosInstance) {
        this.axiosInstance.defaults.adapter = this.originalAdapter;
        this.axiosInstance = void 0;
      }
    };
    MockAdapter2.prototype.reset = reset;
    MockAdapter2.prototype.resetHandlers = resetHandlers;
    MockAdapter2.prototype.resetHistory = resetHistory;
    VERBS.concat("any").forEach(function(method) {
      var methodName = "on" + method.charAt(0).toUpperCase() + method.slice(1);
      MockAdapter2.prototype[methodName] = function(matcher, body, requestHeaders) {
        var _this = this;
        var matcher = matcher === void 0 ? /.*/ : matcher;
        function reply(code, response, headers) {
          var handler = [matcher, body, requestHeaders, code, response, headers];
          addHandler(method, _this.handlers, handler);
          return _this;
        }
        function replyWithDelay(delay, code, response, headers) {
          var handler = [matcher, body, requestHeaders, code, response, headers, false, delay];
          addHandler(method, _this.handlers, handler);
          return _this;
        }
        function withDelayInMs(delay) {
          return function(code, response, headers) {
            replyWithDelay(delay, code, response, headers);
          };
        }
        function replyOnce(code, response, headers) {
          var handler = [
            matcher,
            body,
            requestHeaders,
            code,
            response,
            headers,
            true
          ];
          addHandler(method, _this.handlers, handler);
          return _this;
        }
        return {
          reply,
          replyOnce,
          withDelayInMs,
          passThrough: function passThrough() {
            var handler = [matcher, body];
            addHandler(method, _this.handlers, handler);
            return _this;
          },
          abortRequest: function() {
            return reply(function(config) {
              var error = utils.createAxiosError(
                "Request aborted",
                config,
                void 0,
                "ECONNABORTED"
              );
              return Promise.reject(error);
            });
          },
          abortRequestOnce: function() {
            return replyOnce(function(config) {
              var error = utils.createAxiosError(
                "Request aborted",
                config,
                void 0,
                "ECONNABORTED"
              );
              return Promise.reject(error);
            });
          },
          networkError: function() {
            return reply(function(config) {
              var error = utils.createAxiosError("Network Error", config);
              return Promise.reject(error);
            });
          },
          networkErrorOnce: function() {
            return replyOnce(function(config) {
              var error = utils.createAxiosError("Network Error", config);
              return Promise.reject(error);
            });
          },
          timeout: function() {
            return reply(function(config) {
              var error = utils.createAxiosError(
                config.timeoutErrorMessage || "timeout of " + config.timeout + "ms exceeded",
                config,
                void 0,
                config.transitional && config.transitional.clarifyTimeoutError ? "ETIMEDOUT" : "ECONNABORTED"
              );
              return Promise.reject(error);
            });
          },
          timeoutOnce: function() {
            return replyOnce(function(config) {
              var error = utils.createAxiosError(
                config.timeoutErrorMessage || "timeout of " + config.timeout + "ms exceeded",
                config,
                void 0,
                config.transitional && config.transitional.clarifyTimeoutError ? "ETIMEDOUT" : "ECONNABORTED"
              );
              return Promise.reject(error);
            });
          }
        };
      };
    });
    function findInHandlers(method, handlers, handler) {
      var index = -1;
      for (var i = 0; i < handlers[method].length; i += 1) {
        var item = handlers[method][i];
        var isReplyOnce = item.length === 7;
        var comparePaths = item[0] instanceof RegExp && handler[0] instanceof RegExp ? String(item[0]) === String(handler[0]) : item[0] === handler[0];
        var isSame = comparePaths && utils.isEqual(item[1], handler[1]) && utils.isEqual(item[2], handler[2]);
        if (isSame && !isReplyOnce) {
          index = i;
        }
      }
      return index;
    }
    function addHandler(method, handlers, handler) {
      if (method === "any") {
        VERBS.forEach(function(verb) {
          handlers[verb].push(handler);
        });
      } else {
        var indexOfExistingHandler = findInHandlers(method, handlers, handler);
        if (indexOfExistingHandler > -1 && handler.length < 7) {
          handlers[method].splice(indexOfExistingHandler, 1, handler);
        } else {
          handlers[method].push(handler);
        }
      }
    }
    module2.exports = MockAdapter2;
    module2.exports.default = MockAdapter2;
  }
});

// src/index.ts
var import_axios = __toESM(require("axios"));

// src/types/token.ts
var SupportedToken = /* @__PURE__ */ ((SupportedToken2) => {
  SupportedToken2["USDT"] = "USDT";
  return SupportedToken2;
})(SupportedToken || {});
var TOKEN_ADDRESSES = {
  // [SupportedToken.USDC]: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T',
  ["USDT" /* USDT */]: "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"
};
var TOKEN_DECIMALS = {
  // [SupportedToken.USDC]: 6, // USDC has 6 decimal places
  ["USDT" /* USDT */]: 6
  // USDT has 6 decimal places
};
var TokenUtils = class {
  /**
   * Get the SPL token address from a token enum
   */
  static getTokenAddress(token) {
    return TOKEN_ADDRESSES[token];
  }
  /**
   * Get token enum from SPL address
   */
  static getTokenFromAddress(address) {
    for (const [token, addr] of Object.entries(TOKEN_ADDRESSES)) {
      if (addr === address) {
        return token;
      }
    }
    return null;
  }
  /**
   * Get the number of decimal places for a given token
   */
  static getTokenDecimals(token) {
    return TOKEN_DECIMALS[token] || 6;
  }
  /**
   * Check if a token is supported
   */
  static isTokenSupported(token) {
    return Object.values(SupportedToken).includes(token);
  }
  /**
   * Get the default token (USDT)
   */
  static getDefaultToken() {
    return "USDT" /* USDT */;
  }
};

// src/modules/payments.ts
var PaymentsModule = class {
  constructor(client) {
    this.client = client;
  }
  // --- Product Methods ---
  async createProduct(payload) {
    const requestPayload = { ...payload };
    if (requestPayload.token && !requestPayload.splTokenAddress) {
      requestPayload.splTokenAddress = TokenUtils.getTokenAddress(requestPayload.token);
    }
    if (requestPayload.price) {
      const token = requestPayload.token || "USDT" /* USDT */;
      const decimals = TokenUtils.getTokenDecimals(token);
      const priceValue = typeof requestPayload.price === "string" ? parseFloat(requestPayload.price) : requestPayload.price;
      const priceInBaseUnits = Math.round(priceValue * 10 ** decimals);
      requestPayload.price = priceInBaseUnits.toString();
    }
    const response = await this.client.post("/v1/products", requestPayload);
    return response.data;
  }
  async getProduct(productId) {
    const response = await this.client.get(`/v1/products/${productId}`);
    return response.data;
  }
  async listProducts() {
    const response = await this.client.get("/v1/products");
    return response.data;
  }
  async updateProduct(productId, payload) {
    const requestPayload = { ...payload };
    if (requestPayload.token && !requestPayload.splTokenAddress) {
      requestPayload.splTokenAddress = TokenUtils.getTokenAddress(requestPayload.token);
    }
    const response = await this.client.put(
      `/v1/products/${productId}`,
      requestPayload
    );
    return response.data;
  }
  async deleteProduct(productId) {
    await this.client.delete(`/v1/products/${productId}`);
  }
  // --- Invoice Methods ---
  async createInvoice(payload) {
    const requestPayload = { ...payload };
    if ("token" in requestPayload && !("splTokenAddress" in requestPayload)) {
      requestPayload.splTokenAddress = TokenUtils.getTokenAddress(requestPayload.token);
    }
    const response = await this.client.post("/v1/invoices", requestPayload);
    return response.data;
  }
  async getInvoice(invoiceId) {
    const response = await this.client.get(`/v1/invoices/${invoiceId}`);
    return response.data;
  }
  async listInvoices() {
    const response = await this.client.get("/v1/invoices");
    return response.data;
  }
  async deleteInvoice(invoiceId) {
    await this.client.delete(`/v1/invoices/${invoiceId}`);
  }
};

// src/index.ts
var BeepClient = class {
  constructor(options) {
    this.client = import_axios.default.create({
      baseURL: options.serverUrl || "https://api.beep.com",
      // Default to production URL
      headers: {
        "Authorization": `Bearer ${options.apiKey}`,
        "Content-Type": "application/json"
      }
    });
    this.payments = new PaymentsModule(this.client);
  }
  /**
   * The simplest way to request a payment. 
   * This one-stop method creates an invoice and prepares it for payment.
   * @param payload The details of the charge.
   * @returns A promise that resolves to the created invoice.
   */
  /**
   * Converts a decimal amount to base units based on token decimals
   * @param amount The decimal amount (e.g., 0.01)
   * @param token The token type
   * @returns The amount in base units as an integer (e.g., 10000 for 0.01 USDT)
   */
  convertAmountToBaseUnits(amount, token) {
    const decimals = TOKEN_DECIMALS[token] || 6;
    return Math.round(amount * Math.pow(10, decimals));
  }
  async requestPayment(payload) {
    const requestBody = {
      description: payload.description || "Payment request"
      // Provide a default description
    };
    const token = payload.token || "USDT" /* USDT */;
    if (payload.splTokenAddress) {
      requestBody.splTokenAddress = payload.splTokenAddress;
    } else {
      requestBody.token = token;
    }
    requestBody.amount = this.convertAmountToBaseUnits(payload.amount, token);
    if (payload.payerType) {
      requestBody.payerType = payload.payerType;
    }
    try {
      const response = await this.client.post("/v1/payment/request-payment", requestBody);
      if (!response.data) {
        throw new Error("No data returned from payment request");
      }
      return response.data;
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      throw new Error(`Failed to request payment: ${errorMessage}`);
    }
  }
  // Example function
  async healthCheck() {
    try {
      const response = await this.client.get("/healthz");
      return response.data;
    } catch (error) {
      if (import_axios.default.isAxiosError(error)) {
        throw new Error(`API Error: ${error.response?.data?.message || error.message}`);
      } else {
        throw new Error("An unexpected error occurred.");
      }
    }
  }
};

// tests/beepClient.test.ts
var import_axios2 = __toESM(require("axios"));
var import_axios_mock_adapter = __toESM(require_src());
describe("BeepClient", () => {
  let client;
  let mockAxios;
  beforeEach(() => {
    mockAxios = new import_axios_mock_adapter.default(import_axios2.default);
    client = new BeepClient({
      apiKey: "test-api-key",
      serverUrl: "https://test-api.beep.com"
    });
  });
  afterEach(() => {
    mockAxios.restore();
  });
  it("healthCheck should check API health", async () => {
    mockAxios.onGet("/healthz").reply(200, "API is healthy");
    const result = await client.healthCheck();
    expect(result).toBeDefined();
    expect(result).toBe("API is healthy");
  });
  it("requestPayment creates an invoice with token", async () => {
    mockAxios.onPost("/v1/payment/request-payment").reply(200, {
      invoiceId: "inv_test123",
      referenceKey: "ref_abc123",
      paymentUrl: "https://pay.beep.com/abc123",
      qrCode: "data:image/png;base64,abc123==",
      amount: "10.99",
      token: "USDT" /* USDT */,
      splTokenAddress: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
      status: "pending",
      expiresAt: (/* @__PURE__ */ new Date()).toISOString(),
      receivingMerchantId: "merch_123",
      createdAt: (/* @__PURE__ */ new Date()).toISOString(),
      updatedAt: (/* @__PURE__ */ new Date()).toISOString()
    });
    const result = await client.requestPayment({
      amount: 10.99,
      token: "USDT" /* USDT */,
      description: "Test payment"
    });
    expect(result).toBeDefined();
    expect(result.invoiceId).toBe("inv_test123");
    expect(result.amount).toBe("10.99");
    expect(result.status).toBe("pending");
    expect(mockAxios.history.post.length).toBe(1);
    const requestData = JSON.parse(mockAxios.history.post[0].data);
    expect(requestData.token).toBe("USDT" /* USDT */);
    expect(requestData.amount).toBe(1099e4);
  });
  it("requestPayment falls back to splTokenAddress if token not provided", async () => {
    const splTokenAddress = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
    mockAxios.onPost("/v1/payment/request-payment").reply(200, {
      invoiceId: "inv_test123",
      merchantId: "merch_123",
      payerType: "customer_wallet",
      payerMerchantId: null,
      description: "Test payment",
      amount: "10.99",
      splTokenAddress,
      status: "pending",
      referenceKey: "ref_abc123",
      createdAt: (/* @__PURE__ */ new Date()).toISOString(),
      updatedAt: (/* @__PURE__ */ new Date()).toISOString()
    });
    const result = await client.requestPayment({
      amount: 10.99,
      splTokenAddress,
      description: "Test payment"
    });
    expect(result).toBeDefined();
    expect(result.splTokenAddress).toBe(splTokenAddress);
    expect(mockAxios.history.post.length).toBe(1);
    const requestData = JSON.parse(mockAxios.history.post[0].data);
    expect(requestData.splTokenAddress).toBe(splTokenAddress);
  });
  it("requestPayment defaults to USDT if no token or splTokenAddress provided", async () => {
    mockAxios.onPost("/v1/payment/request-payment").reply(200, {
      invoiceId: "inv_test123",
      merchantId: "merch_123",
      status: "pending"
    });
    await client.requestPayment({
      amount: 10.99,
      description: "Test payment"
    });
    expect(mockAxios.history.post.length).toBe(1);
    const requestData = JSON.parse(mockAxios.history.post[0].data);
    expect(requestData.token).toBe("USDT" /* USDT */);
  });
  it("requestPayment throws error when API request fails", async () => {
    mockAxios.onPost("/v1/payment/request-payment").reply(500);
    await expect(client.requestPayment({
      amount: 10.99,
      token: "USDT" /* USDT */,
      description: "Test payment"
    })).rejects.toThrow();
  });
  it("requestPayment throws error when response has no data", async () => {
    mockAxios.onPost("/v1/payment/request-payment").reply(200, null);
    await expect(client.requestPayment({
      amount: 10.99,
      token: "USDT" /* USDT */,
      description: "Test payment"
    })).rejects.toThrow("No data returned from payment request");
  });
  it("converts amount to base units correctly for different tokens", async () => {
    mockAxios.onPost("/v1/payment/request-payment").reply(200, {
      invoiceId: "inv_test123",
      referenceKey: "ref_abc123",
      status: "pending",
      expiresAt: (/* @__PURE__ */ new Date()).toISOString(),
      receivingMerchantId: "merch_123"
    });
    await client.requestPayment({
      amount: 0.01,
      token: "USDT" /* USDT */,
      description: "USDT payment"
    });
    const requestData = JSON.parse(mockAxios.history.post[0].data);
    expect(requestData.amount).toBe(1e4);
  });
  it("converts amount to base units correctly for USDT", async () => {
    mockAxios.onPost("/v1/payment/request-payment").reply(200, {
      invoiceId: "inv_test123",
      referenceKey: "ref_abc123",
      status: "pending",
      expiresAt: (/* @__PURE__ */ new Date()).toISOString(),
      receivingMerchantId: "merch_123"
    });
    await client.requestPayment({
      amount: 1e-6,
      token: "USDT" /* USDT */,
      description: "USDT minimum payment"
    });
    const requestData = JSON.parse(mockAxios.history.post[0].data);
    expect(requestData.amount).toBe(1);
  });
  it("handles payerType correctly when provided", async () => {
    mockAxios.onPost("/v1/payment/request-payment").reply(200, {
      invoiceId: "inv_test123",
      referenceKey: "ref_abc123",
      status: "pending"
    });
    await client.requestPayment({
      amount: 10.99,
      token: "USDT" /* USDT */,
      description: "Test payment",
      payerType: "merchant_wallet"
    });
    const requestData = JSON.parse(mockAxios.history.post[0].data);
    expect(requestData.payerType).toBe("merchant_wallet");
  });
  it("handles empty description by setting a default", async () => {
    mockAxios.onPost("/v1/payment/request-payment").reply(200, {
      invoiceId: "inv_test123",
      referenceKey: "ref_abc123",
      status: "pending"
    });
    await client.requestPayment({
      amount: 10.99,
      token: "USDT" /* USDT */,
      description: ""
    });
    const requestData = JSON.parse(mockAxios.history.post[0].data);
    expect(requestData.description).toBe("Payment request");
  });
  it("handles undefined description by setting a default", async () => {
    mockAxios.onPost("/v1/payment/request-payment").reply(200, {
      invoiceId: "inv_test123",
      referenceKey: "ref_abc123",
      status: "pending"
    });
    await client.requestPayment({
      amount: 10.99,
      token: "USDT" /* USDT */
      // description omitted
    });
    const requestData = JSON.parse(mockAxios.history.post[0].data);
    expect(requestData.description).toBe("Payment request");
  });
  it("handles large amounts correctly", async () => {
    mockAxios.onPost("/v1/payment/request-payment").reply(200, {
      invoiceId: "inv_test123",
      referenceKey: "ref_abc123",
      status: "pending"
    });
    await client.requestPayment({
      amount: 1e3,
      token: "USDT" /* USDT */,
      description: "Large payment"
    });
    const requestData = JSON.parse(mockAxios.history.post[0].data);
    expect(requestData.amount).toBe(1e9);
  });
});
/*! Bundled license information:

is-buffer/index.js:
  (*!
   * Determine if an object is a Buffer
   *
   * @author   Feross Aboukhadijeh <https://feross.org>
   * @license  MIT
   *)

axios-mock-adapter/src/is_blob.js:
  (*!
   * MIT License
   *
   * Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
   *
   * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
   * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
   * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
   * persons to whom the Software is furnished to do so, subject to the following conditions:
   *
   * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
   * Software.
   *
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
   * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
   * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
   * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
   *)
*/
