UNPKG

autumn-js

Version:

Autumn JS Library

591 lines (572 loc) 15.1 kB
import { logger } from "./chunk-V7R5DCYR.mjs"; // src/utils/encryptUtils.tsx import crypto from "crypto"; // src/sdk/error.ts var AutumnError = class _AutumnError extends Error { message; code; constructor(response) { super(response.message); this.message = response.message; this.code = response.code; } static fromError(error) { return new _AutumnError({ message: error.message || "Unknown error", code: error.code || "unknown_error" }); } toString() { return `${this.message} (code: ${this.code})`; } toJSON() { return { message: this.message, code: this.code }; } }; // src/sdk/general/genMethods.ts var handleCheckout = async ({ instance, params }) => { return instance.post("/checkout", params); }; var handleAttach = async ({ instance, params }) => { return instance.post("/attach", params); }; var handleSetupPayment = async ({ instance, params }) => { return instance.post("/setup_payment", params); }; var handleCancel = async ({ instance, params }) => { return instance.post("/cancel", 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/libraries/backend/constants.ts var autumnApiUrl = "https://api.useautumn.com/v1"; // 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/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_beta"; 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, logger: logger2, logError = true }) => { if (response.status < 200 || response.status >= 300) { let error; try { error = await response.json(); if (logError) { logger2.error(`[Autumn] ${error.message}`); } } catch (error2) { throw 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) { throw 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 { secretKey; publishableKey; headers; url; logger = console; constructor(options) { 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 || autumnApiUrl; this.logger = logger; this.logger.level = options?.logLevel || "info"; } async get(path) { const response = await fetch(`${this.url}${path}`, { headers: this.headers }); return toContainerResult({ response, logger: this.logger }); } async post(path, body) { try { const response = await fetch(`${this.url}${path}`, { method: "POST", headers: this.headers, body: JSON.stringify(body) }); return toContainerResult({ response, logger: this.logger }); } 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, logger: this.logger }); } static customers = customerMethods(); static products = productMethods(); static entities = entityMethods(); static referrals = referralMethods(); customers = customerMethods(this); products = productMethods(this); entities = entityMethods(this); referrals = referralMethods(this); static checkout = (params) => staticWrapper(handleCheckout, void 0, { params }); async checkout(params) { return handleCheckout({ instance: this, params }); } static attach = (params) => staticWrapper(handleAttach, void 0, { params }); static usage = (params) => staticWrapper(handleUsage, void 0, { params }); async attach(params) { return handleAttach({ instance: this, params }); } static setupPayment = (params) => staticWrapper(handleSetupPayment, void 0, { params }); async setupPayment(params) { return handleSetupPayment({ instance: this, params }); } static cancel = (params) => staticWrapper(handleCancel, void 0, { params }); async cancel(params) { return handleCancel({ instance: this, params }); } static check = (params) => staticWrapper(handleCheck, void 0, { params }); async check(params) { return handleCheck({ instance: this, params }); } static track = (params) => staticWrapper(handleTrack, void 0, { params }); async track(params) { return handleTrack({ instance: this, params }); } async usage(params) { return handleUsage({ instance: this, params }); } }; // src/sdk/customers/entities/entTypes.ts import { z } from "zod"; var EntityDataSchema = z.object({ name: z.string().optional(), feature_id: z.string() }); // src/sdk/general/genTypes.ts import { z as z2 } from "zod"; var CancelParamsSchema = z2.object({ customer_id: z2.string(), product_id: z2.string(), entity_id: z2.string().optional(), cancel_immediately: z2.boolean().optional() }); var CancelResultSchema = z2.object({ success: z2.boolean(), customer_id: z2.string(), product_id: z2.string() }); var TrackParamsSchema = z2.object({ customer_id: z2.string(), value: z2.number().optional(), feature_id: z2.string().optional(), event_name: z2.string().optional(), entity_id: z2.string().optional(), customer_data: z2.any().optional(), idempotency_key: z2.string().optional(), entity_data: z2.any().optional() }); var TrackResultSchema = z2.object({ id: z2.string(), code: z2.string(), customer_id: z2.string(), feature_id: z2.string().optional(), event_name: z2.string().optional() }); var CheckParamsSchema = z2.object({ customer_id: z2.string(), feature_id: z2.string().optional(), product_id: z2.string().optional(), entity_id: z2.string().optional(), customer_data: z2.any().optional(), required_balance: z2.number().optional(), send_event: z2.boolean().optional(), with_preview: z2.boolean().optional(), entity_data: EntityDataSchema.optional() }); // src/sdk/customers/cusEnums.ts import { z as z3 } from "zod"; var CustomerExpandEnum = z3.enum([ "invoices", "rewards", "trials_used", "entities", "referrals", "payment_method" ]); // src/sdk/customers/cusTypes.ts import { z as z4 } from "zod"; var CustomerDataSchema = z4.object({ name: z4.string().nullish(), email: z4.string().nullish(), fingerprint: z4.string().nullish() }); var CreateCustomerParamsSchema = z4.object({ id: z4.string().nullish(), email: z4.string().nullish(), name: z4.string().nullish(), fingerprint: z4.string().nullish(), metadata: z4.record(z4.any()).optional(), expand: z4.array(CustomerExpandEnum).optional() }); var BillingPortalParamsSchema = z4.object({ return_url: z4.string().optional() }); // src/sdk/referrals/referralTypes.ts import { z as z5 } from "zod"; var CreateReferralCodeParamsSchema = z5.object({ customer_id: z5.string(), program_id: z5.string() }); var RedeemReferralCodeParamsSchema = z5.object({ code: z5.string(), customer_id: z5.string() }); // src/sdk/general/attachTypes.ts import { z as z6 } from "zod"; var AttachFeatureOptionsSchema = z6.object({ feature_id: z6.string(), quantity: z6.number() }); var AttachParamsSchema = z6.object({ customer_id: z6.string(), product_id: z6.string().optional(), entity_id: z6.string().optional(), options: z6.array(AttachFeatureOptionsSchema).optional(), product_ids: z6.array(z6.string()).optional(), free_trial: z6.boolean().optional(), success_url: z6.string().optional(), metadata: z6.record(z6.string()).optional(), force_checkout: z6.boolean().optional(), customer_data: CustomerDataSchema.optional(), entity_data: z6.any().optional(), checkout_session_params: z6.record(z6.any()).optional(), reward: z6.string().optional() }); var AttachResultSchema = z6.object({ checkout_url: z6.string().optional(), customer_id: z6.string(), product_ids: z6.array(z6.string()), code: z6.string(), message: z6.string(), customer_data: z6.any().optional() }); var CheckoutParamsSchema = z6.object({ customer_id: z6.string(), product_id: z6.string(), entity_id: z6.string().optional(), success_url: z6.string().optional(), customer_data: CustomerDataSchema.optional(), options: z6.array(AttachFeatureOptionsSchema).optional() }); // src/utils/encryptUtils.tsx var getKey = () => { if (!process.env.AUTUMN_SECRET_KEY) { throw new AutumnError({ message: "Autumn secret key not found in process.env.AUTUMN_SECRET_KEY. Please set it in your .env file.", code: "secret_key_not_found" }); } return crypto.createHash("sha512").update(process.env.AUTUMN_SECRET_KEY).digest("hex").substring(0, 32); }; function encryptData(data) { let key; try { key = getKey(); } catch (error) { throw new AutumnError({ message: `Failed to encrypt customer ID. ${error.message}`, code: "encrypt_customer_id_failed" }); } const iv = crypto.randomBytes(16); const cipher = crypto.createCipheriv("aes-256-cbc", key, iv); const encrypted = Buffer.concat([ cipher.update(data, "utf8"), cipher.final() ]); const result = Buffer.concat([iv, encrypted]); return result.toString("base64"); } function decryptData(encryptedData) { const buffer = Buffer.from(encryptedData, "base64"); const iv = buffer.slice(0, 16); const encrypted = buffer.slice(16); const key = getKey(); const decipher = crypto.createDecipheriv("aes-256-cbc", key, iv); const decrypted = Buffer.concat([ decipher.update(encrypted), decipher.final() ]); return decrypted.toString("utf8"); } export { decryptData, encryptData };