import { z } from "zod"; import type { BillingGateway, BillingGatewayCustomer, BillingGatewayCustomerInput, BillingGatewayInvoice, BillingGatewayInvoiceListInput, BillingGatewaySubscription, BillingGatewaySubscriptionInput, } from "./types.js"; const DEFAULT_LAGO_TIMEOUT_MS = 10_000; const DEFAULT_LAGO_PER_PAGE = 20; export type LagoBillingGatewayConfig = { apiUrl: string; apiKey: string; timeoutMs?: number; fetchImpl?: typeof fetch; }; export class LagoBillingGatewayError extends Error { readonly code: "CONFIG_INVALID" | "REQUEST_FAILED" | "RESPONSE_INVALID"; readonly status?: number; constructor(message: string, code: LagoBillingGatewayError["code"], status?: number) { super(message); this.name = "LagoBillingGatewayError"; this.code = code; this.status = status; } } const nullableString = z.string().nullable().optional(); const lagoCustomerSchema = z.object({ lago_id: z.string(), external_id: z.string(), name: nullableString, email: nullableString, currency: nullableString, created_at: nullableString, }); const lagoSubscriptionSchema = z.object({ lago_id: z.string(), external_id: z.string(), external_customer_id: z.string(), plan_code: z.string(), status: z.string().nullable().optional(), name: nullableString, current_billing_period_started_at: nullableString, current_billing_period_ending_at: nullableString, created_at: nullableString, }); const lagoInvoiceSchema = z.object({ lago_id: z.string(), number: nullableString, external_customer_id: nullableString, customer: z .object({ external_id: nullableString, }) .nullable() .optional(), status: z.string().nullable().optional(), payment_status: z.string().nullable().optional(), invoice_type: nullableString, currency: nullableString, total_amount_cents: z.number().nullable().optional(), issuing_date: nullableString, file_url: nullableString, }); const customerResponseSchema = z.object({ customer: lagoCustomerSchema }); const subscriptionResponseSchema = z.object({ subscription: lagoSubscriptionSchema }); const invoiceResponseSchema = z.object({ invoice: lagoInvoiceSchema }); const invoicesResponseSchema = z.object({ invoices: z.array(lagoInvoiceSchema) }); type LagoCustomer = z.infer; type LagoSubscription = z.infer; type LagoInvoice = z.infer; export function createLagoBillingGateway(config: LagoBillingGatewayConfig): BillingGateway { return new LagoBillingGateway(config); } export function normalizeLagoApiUrl(apiUrl: string): string { let url: URL; try { url = new URL(apiUrl); } catch { throw new LagoBillingGatewayError("Lago API URL must be an absolute URL.", "CONFIG_INVALID"); } if (url.protocol !== "http:" && url.protocol !== "https:") { throw new LagoBillingGatewayError("Lago API URL must use http or https.", "CONFIG_INVALID"); } url.pathname = url.pathname.replace(/\/+$/u, ""); return url.toString().replace(/\/$/u, ""); } export function redactLagoValue(value: string | null | undefined): string | null { if (!value) return null; if (value.length <= 8) return "[redacted]"; return `${value.slice(0, 4)}…${value.slice(-4)}`; } class LagoBillingGateway implements BillingGateway { private readonly apiUrl: string; private readonly apiKey: string; private readonly timeoutMs: number; private readonly fetchImpl: typeof fetch; constructor(config: LagoBillingGatewayConfig) { this.apiUrl = normalizeLagoApiUrl(config.apiUrl); this.apiKey = config.apiKey.trim(); if (!this.apiKey) { throw new LagoBillingGatewayError("Lago API key is required.", "CONFIG_INVALID"); } this.timeoutMs = normalizeTimeout(config.timeoutMs); this.fetchImpl = config.fetchImpl ?? fetch; } async createCustomer(input: BillingGatewayCustomerInput): Promise { const response = await this.request("/customers", { method: "POST", body: { customer: { external_id: input.tenantId, name: input.name, ...(input.email ? { email: input.email } : {}), ...(input.currency ? { currency: input.currency } : {}), ...(input.country ? { country: input.country } : {}), ...(input.timezone ? { timezone: input.timezone } : {}), }, }, }); return toCustomer(parseLagoResponse(customerResponseSchema, response)); } async getCustomer(tenantId: string): Promise { const response = await this.request(`/customers/${encodeURIComponent(tenantId)}`, { method: "GET", allowNotFound: true }); return response === null ? null : toCustomer(parseLagoResponse(customerResponseSchema, response)); } async createSubscription(input: BillingGatewaySubscriptionInput): Promise { assertPositiveSeatQuantity(input.seatQuantity); const response = await this.request("/subscriptions", { method: "POST", body: { subscription: { external_customer_id: input.tenantId, external_id: input.subscriptionExternalId, plan_code: input.planCode, name: input.name ?? `${input.planCode} (${input.seatQuantity} seats)`, billing_time: "anniversary", ...(input.subscriptionAt ? { subscription_at: toIsoString(input.subscriptionAt) } : {}), ...(input.endingAt ? { ending_at: toIsoString(input.endingAt) } : {}), }, }, }); return toSubscription(parseLagoResponse(subscriptionResponseSchema, response)); } async getSubscription(subscriptionExternalId: string): Promise { const response = await this.request(`/subscriptions/${encodeURIComponent(subscriptionExternalId)}`, { method: "GET", allowNotFound: true }); return response === null ? null : toSubscription(parseLagoResponse(subscriptionResponseSchema, response)); } async listInvoices(input: BillingGatewayInvoiceListInput = {}): Promise { const query = new URLSearchParams(); if (input.tenantId) query.set("external_customer_id", input.tenantId); query.set("page", String(input.page ?? 1)); query.set("per_page", String(input.perPage ?? DEFAULT_LAGO_PER_PAGE)); const response = await this.request(`/invoices?${query.toString()}`, { method: "GET" }); return parseLagoResponse(invoicesResponseSchema, response).invoices.map(toInvoice); } async downloadInvoice(providerInvoiceId: string): Promise { const id = providerInvoiceId.trim(); if (!id) { throw new LagoBillingGatewayError("Invoice id is required.", "CONFIG_INVALID"); } const response = await this.request(`/invoices/${encodeURIComponent(id)}/download`, { method: "POST", allowNotFound: true }); return response === null ? null : toInvoice(parseLagoResponse(invoiceResponseSchema, response).invoice); } async updateInvoicePaymentStatus(providerInvoiceId: string, paymentStatus: BillingGatewayInvoice["paymentStatus"]): Promise { const id = providerInvoiceId.trim(); if (!id) { throw new LagoBillingGatewayError("Invoice id is required.", "CONFIG_INVALID"); } if (paymentStatus !== "pending" && paymentStatus !== "succeeded" && paymentStatus !== "failed") { throw new LagoBillingGatewayError("Invoice payment status is invalid.", "CONFIG_INVALID"); } const response = await this.request(`/invoices/${encodeURIComponent(id)}`, { method: "PUT", body: { invoice: { payment_status: paymentStatus, }, }, }); return toInvoice(parseLagoResponse(invoiceResponseSchema, response).invoice); } private async request(path: string, options: { method: "GET" | "POST" | "PUT"; body?: unknown; allowNotFound?: boolean }): Promise { const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), this.timeoutMs); try { const response = await this.fetchImpl(`${this.apiUrl}/api/v1${path}`, { method: options.method, headers: { authorization: `Bearer ${this.apiKey}`, accept: "application/json", ...(options.body ? { "content-type": "application/json" } : {}), }, body: options.body ? JSON.stringify(options.body) : undefined, signal: controller.signal, }); if (response.status === 404 && options.allowNotFound) { return null; } if (!response.ok) { throw new LagoBillingGatewayError(`Lago request failed with status ${response.status}.`, "REQUEST_FAILED", response.status); } return await response.json(); } catch (error) { if (error instanceof LagoBillingGatewayError) throw error; throw new LagoBillingGatewayError("Lago request failed.", "REQUEST_FAILED"); } finally { clearTimeout(timeout); } } } function parseLagoResponse(schema: z.ZodType, response: unknown): T { const result = schema.safeParse(response); if (!result.success) { throw new LagoBillingGatewayError("Lago response shape is invalid.", "RESPONSE_INVALID"); } return result.data; } function toCustomer(response: { customer: LagoCustomer }): BillingGatewayCustomer { const customer = response.customer; return { provider: "lago", externalId: customer.external_id, providerCustomerId: customer.lago_id, name: customer.name ?? null, email: customer.email ?? null, currency: customer.currency ?? null, createdAt: customer.created_at ?? null, }; } function toSubscription(response: { subscription: LagoSubscription }): BillingGatewaySubscription { const subscription = response.subscription; return { provider: "lago", externalId: subscription.external_id, providerSubscriptionId: subscription.lago_id, externalCustomerId: subscription.external_customer_id, planCode: subscription.plan_code, status: normalizeSubscriptionStatus(subscription.status), name: subscription.name ?? null, currentBillingPeriodStartedAt: subscription.current_billing_period_started_at ?? null, currentBillingPeriodEndingAt: subscription.current_billing_period_ending_at ?? null, createdAt: subscription.created_at ?? null, }; } function toInvoice(invoice: LagoInvoice): BillingGatewayInvoice { return { provider: "lago", providerInvoiceId: invoice.lago_id, number: invoice.number ?? null, externalCustomerId: invoice.external_customer_id ?? invoice.customer?.external_id ?? null, status: normalizeInvoiceStatus(invoice.status), paymentStatus: normalizePaymentStatus(invoice.payment_status), invoiceType: invoice.invoice_type ?? null, currency: invoice.currency ?? null, totalAmountCents: invoice.total_amount_cents ?? null, issuingDate: invoice.issuing_date ?? null, fileUrl: invoice.file_url ?? null, }; } function normalizeTimeout(timeoutMs: number | undefined): number { return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.trunc(timeoutMs) : DEFAULT_LAGO_TIMEOUT_MS; } function assertPositiveSeatQuantity(seatQuantity: number): void { if (!Number.isInteger(seatQuantity) || seatQuantity < 1) { throw new LagoBillingGatewayError("Seat quantity must be a positive integer.", "CONFIG_INVALID"); } } function toIsoString(value: Date | string): string { return value instanceof Date ? value.toISOString() : value; } function normalizeSubscriptionStatus(value: string | null | undefined): BillingGatewaySubscription["status"] { if (value === "pending" || value === "active" || value === "terminated" || value === "canceled" || value === "cancelled") return value; return "unknown"; } function normalizeInvoiceStatus(value: string | null | undefined): BillingGatewayInvoice["status"] { if (value === "draft" || value === "finalized" || value === "voided" || value === "failed" || value === "pending") return value; return "unknown"; } function normalizePaymentStatus(value: string | null | undefined): BillingGatewayInvoice["paymentStatus"] { if (value === "pending" || value === "succeeded" || value === "failed") return value; return "unknown"; }