UNPKG

autumn-js

Version:

Autumn JS Library

492 lines (476 loc) 13.1 kB
'use strict'; var __defProp = Object.defineProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); // src/sdk/error.ts var AutumnError = class extends Error { constructor(response) { super(response.message); __publicField(this, "message"); __publicField(this, "code"); this.message = response.message; this.code = response.code; } toString() { return `${this.message} (code: ${this.code})`; } toJSON() { return { message: this.message, code: this.code }; } }; // src/sdk/utils.ts var staticWrapper = (callback, instance, args) => { if (!instance) { instance = new Autumn(); } return callback({ instance, ...args }); }; // src/sdk/customers/cusMethods.ts var customerMethods = (instance) => { return { get: (id, params) => staticWrapper(getCustomer, instance, { id, params }), create: (params) => staticWrapper(createCustomer, instance, { params }), update: (id, params) => staticWrapper(updateCustomer, instance, { id, params }), delete: (id) => staticWrapper(deleteCustomer, instance, { id }), billingPortal: (id, params) => staticWrapper(billingPortal, instance, { id, params }) }; }; var getExpandStr = (expand) => { if (!expand) { return ""; } return `expand=${expand.join(",")}`; }; var getCustomer = async ({ instance, id, params }) => { if (!id) { return { data: null, error: new AutumnError({ message: "Customer ID is required", code: "CUSTOMER_ID_REQUIRED" }) }; } return instance.get(`/customers/${id}?${getExpandStr(params?.expand)}`); }; var createCustomer = async ({ instance, params }) => { return instance.post(`/customers?${getExpandStr(params?.expand)}`, params); }; var updateCustomer = async ({ instance, id, params }) => { return instance.post(`/customers/${id}`, params); }; var deleteCustomer = async ({ instance, id }) => { return instance.delete(`/customers/${id}`); }; var billingPortal = async ({ instance, id, params }) => { return instance.post(`/customers/${id}/billing_portal`, params); }; // src/sdk/customers/entities/entMethods.ts var entityMethods = (instance) => { return { get: (customer_id, entity_id, params) => staticWrapper(getEntity, instance, { customer_id, entity_id, params }), create: (customer_id, params) => staticWrapper(createEntity, instance, { customer_id, params }), delete: (customer_id, entity_id) => staticWrapper(deleteEntity, instance, { customer_id, entity_id }) }; }; var getExpandStr2 = (expand) => { if (!expand) { return ""; } return `expand=${expand.join(",")}`; }; var getEntity = async ({ instance, customer_id, entity_id, params }) => { return instance.get( `/customers/${customer_id}/entities/${entity_id}?${getExpandStr2( params?.expand )}` ); }; var createEntity = async ({ instance, customer_id, params }) => { return instance.post(`/customers/${customer_id}/entities`, params); }; var deleteEntity = async ({ instance, customer_id, entity_id }) => { return instance.delete(`/customers/${customer_id}/entities/${entity_id}`); }; // src/sdk/general/genMethods.ts var handleAttach = async ({ instance, params }) => { return instance.post("/attach", params); }; var handleCancel = async ({ instance, params }) => { return instance.post("/cancel", params); }; var handleEntitled = async ({ instance, params }) => { return instance.post("/entitled", params); }; var handleEvent = async ({ instance, params }) => { return instance.post("/events", params); }; var handleTrack = async ({ instance, params }) => { return instance.post("/track", params); }; var handleUsage = async ({ instance, params }) => { return instance.post("/usage", params); }; var handleCheck = async ({ instance, params }) => { return instance.post("/check", params); }; // src/sdk/products/prodMethods.ts var productMethods = (instance) => { return { get: (id) => staticWrapper(getProduct, instance, { id }), create: (params) => staticWrapper(createProduct, instance, { params }), list: (params) => staticWrapper(listProducts, instance, { params }) }; }; var listProducts = async ({ instance, params }) => { let path = "/products"; if (params) { const queryParams = new URLSearchParams(); for (const [key, value] of Object.entries(params)) { if (value !== void 0) { queryParams.append(key, String(value)); } } const queryString = queryParams.toString(); if (queryString) { path += `?${queryString}`; } } return instance.get(path); }; var getProduct = async ({ instance, id }) => { return instance.get(`/products/${id}`); }; var createProduct = async ({ instance, params }) => { return instance.post("/products", params); }; // src/sdk/referrals/referralMethods.ts var referralMethods = (instance) => { return { createCode: (params) => staticWrapper(createReferralCode, instance, { params }), redeemCode: (params) => staticWrapper(redeemReferralCode, instance, { params }) }; }; var createReferralCode = async ({ instance, params }) => { return instance.post("/referrals/code", params); }; var redeemReferralCode = async ({ instance, params }) => { return instance.post("/referrals/redeem", params); }; // src/sdk/response.ts var toContainerResult = async (response) => { if (response.status < 200 || response.status >= 300) { let error; try { error = await response.json(); } catch (error2) { return { data: null, error: new AutumnError({ message: "Failed to parse JSON response from Autumn", code: "internal_error" }), statusCode: response.status }; } return { data: null, error: new AutumnError({ message: error.message, code: error.code }), statusCode: response.status }; } try { let data = await response.json(); return { data, error: null, statusCode: response?.status }; } catch (error) { return { data: null, error: new AutumnError({ message: "Failed to parse Autumn API response", code: "internal_error" }), statusCode: response?.status }; } }; // src/sdk/client.ts var LATEST_API_VERSION = "1.2"; var Autumn = class { constructor(options) { __publicField(this, "secretKey"); __publicField(this, "publishableKey"); __publicField(this, "level"); __publicField(this, "headers"); __publicField(this, "url"); __publicField(this, "customers", customerMethods(this)); __publicField(this, "products", productMethods(this)); __publicField(this, "entities", entityMethods(this)); __publicField(this, "referrals", referralMethods(this)); try { this.secretKey = options?.secretKey || process.env.AUTUMN_SECRET_KEY; this.publishableKey = options?.publishableKey || process.env.AUTUMN_PUBLISHABLE_KEY; } catch (error) { } if (!this.secretKey && !this.publishableKey && !options?.headers) { throw new Error("Autumn secret key or publishable key is required"); } this.headers = options?.headers || { Authorization: `Bearer ${this.secretKey || this.publishableKey}`, "Content-Type": "application/json" }; let version = options?.version || LATEST_API_VERSION; this.headers["x-api-version"] = version; this.url = options?.url || "https://api.useautumn.com/v1"; this.level = this.secretKey ? "secret" : "publishable"; } getLevel() { return this.level; } async get(path) { const response = await fetch(`${this.url}${path}`, { headers: this.headers }); return toContainerResult(response); } async post(path, body) { try { const response = await fetch(`${this.url}${path}`, { method: "POST", headers: this.headers, body: JSON.stringify(body) }); return toContainerResult(response); } catch (error) { console.error("Error sending request:", error); throw error; } } async delete(path) { const response = await fetch(`${this.url}${path}`, { method: "DELETE", headers: this.headers }); return toContainerResult(response); } async attach(params) { return handleAttach({ instance: this, params }); } async cancel(params) { return handleCancel({ instance: this, params }); } /** * @deprecated This method is deprecated and will be removed in a future version. * Please use the new check() method instead. */ async entitled(params) { return handleEntitled({ instance: this, params }); } async check(params) { return handleCheck({ instance: this, params }); } /** * @deprecated This method is deprecated and will be removed in a future version. * Please use the new track() method instead. */ async event(params) { return handleEvent({ instance: this, params }); } async track(params) { return handleTrack({ instance: this, params }); } async usage(params) { return handleUsage({ instance: this, params }); } }; __publicField(Autumn, "customers", customerMethods()); __publicField(Autumn, "products", productMethods()); __publicField(Autumn, "entities", entityMethods()); __publicField(Autumn, "referrals", referralMethods()); __publicField(Autumn, "attach", (params) => staticWrapper(handleAttach, void 0, { params })); __publicField(Autumn, "usage", (params) => staticWrapper(handleUsage, void 0, { params })); __publicField(Autumn, "cancel", (params) => staticWrapper(handleCancel, void 0, { params })); /** * @deprecated This method is deprecated and will be removed in a future version. * Please use the new check() method instead. */ __publicField(Autumn, "entitled", (params) => staticWrapper(handleEntitled, void 0, { params })); __publicField(Autumn, "check", (params) => staticWrapper(handleCheck, void 0, { params })); /** * @deprecated This method is deprecated and will be removed in a future version. * Please use the new track() method instead. */ __publicField(Autumn, "event", (params) => staticWrapper(handleEvent, void 0, { params })); __publicField(Autumn, "track", (params) => staticWrapper(handleTrack, void 0, { params })); // src/sdk/general/genEnums.ts var AppEnv = /* @__PURE__ */ ((AppEnv2) => { AppEnv2["Sandbox"] = "sandbox"; AppEnv2["Live"] = "live"; return AppEnv2; })(AppEnv || {}); // src/sdk/customers/cusEnums.ts var ProductStatus = /* @__PURE__ */ ((ProductStatus2) => { ProductStatus2["Active"] = "active"; ProductStatus2["Expired"] = "expired"; ProductStatus2["Trialing"] = "trialing"; ProductStatus2["Scheduled"] = "scheduled"; ProductStatus2["PastDue"] = "past_due"; return ProductStatus2; })(ProductStatus || {}); // src/sdk/products/prodEnums.ts var Infinite = "inf"; var FreeTrialDuration = /* @__PURE__ */ ((FreeTrialDuration2) => { FreeTrialDuration2["Day"] = "day"; return FreeTrialDuration2; })(FreeTrialDuration || {}); var UsageModel = /* @__PURE__ */ ((UsageModel2) => { UsageModel2["Prepaid"] = "prepaid"; UsageModel2["PayPerUse"] = "pay_per_use"; return UsageModel2; })(UsageModel || {}); var ProductItemInterval = /* @__PURE__ */ ((ProductItemInterval2) => { ProductItemInterval2["Minute"] = "minute"; ProductItemInterval2["Hour"] = "hour"; ProductItemInterval2["Day"] = "day"; ProductItemInterval2["Week"] = "week"; ProductItemInterval2["Month"] = "month"; ProductItemInterval2["Quarter"] = "quarter"; ProductItemInterval2["SemiAnnual"] = "semi_annual"; ProductItemInterval2["Year"] = "year"; ProductItemInterval2["Multiple"] = "multiple"; return ProductItemInterval2; })(ProductItemInterval || {}); // src/sdk/components/componentMethods.ts var fetchPricingTable = async ({ instance, params }) => { let path = "/components/pricing_table"; if (params) { const queryParams = new URLSearchParams(); for (const [key, value] of Object.entries(params)) { if (key === "products") { continue; } if (value !== void 0) { queryParams.append(key, String(value)); } } const queryString = queryParams.toString(); if (queryString) { path += `?${queryString}`; } } return await instance.get(path); }; exports.AppEnv = AppEnv; exports.Autumn = Autumn; exports.AutumnError = AutumnError; exports.FreeTrialDuration = FreeTrialDuration; exports.Infinite = Infinite; exports.ProductItemInterval = ProductItemInterval; exports.ProductStatus = ProductStatus; exports.UsageModel = UsageModel; exports.fetchPricingTable = fetchPricingTable; exports.toContainerResult = toContainerResult;