Files

119 lines
4.6 KiB
TypeScript

import { createHash } from "node:crypto";
import { z } from "zod";
import {
buildDesiredLagoCatalog,
lagoOrganizationResponseSchema,
lagoPlanResponseSchema,
lagoTaxResponseSchema,
toLagoPlanPayload,
toLagoTaxPayload,
type DesiredLagoCatalog,
type DesiredLagoPlan,
type LagoCatalogSnapshot,
} from "./catalog";
import { BillingCatalogOperatorError } from "./contracts";
const DEFAULT_TIMEOUT_MS = 10_000;
export class LagoCatalogClient {
private readonly apiUrl: string;
private readonly apiKey: string;
private readonly expectedOrganizationName: string;
private readonly expectedOrganizationIdSha256: string;
private readonly fetchImpl: typeof fetch;
private readonly timeoutMs: number;
constructor(input: {
apiUrl: string;
apiKey: string;
expectedOrganizationName: string;
expectedOrganizationIdSha256: string;
fetchImpl?: typeof fetch;
timeoutMs?: number;
}) {
this.apiUrl = input.apiUrl.replace(/\/+$/u, "");
this.apiKey = input.apiKey;
this.expectedOrganizationName = input.expectedOrganizationName;
this.expectedOrganizationIdSha256 = input.expectedOrganizationIdSha256;
this.fetchImpl = input.fetchImpl ?? fetch;
this.timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
}
async readCatalog(desired = buildDesiredLagoCatalog()): Promise<LagoCatalogSnapshot> {
const organization = await this.assertOrganization();
const [tax, ...plans] = await Promise.all([
this.request(`/taxes/${encodeURIComponent(desired.tax.code)}`, "GET", undefined, lagoTaxResponseSchema, true),
...desired.plans.map((plan) => this.request(`/plans/${encodeURIComponent(plan.code)}`, "GET", undefined, lagoPlanResponseSchema, true)),
]);
return {
organization,
tax: tax?.tax ?? null,
plans: plans.flatMap((response) => (response ? [{ ...response.plan, taxes: response.plan.taxes ?? [] }] : [])),
};
}
async applyTax(catalog: DesiredLagoCatalog, update: boolean): Promise<void> {
await this.assertOrganization();
await this.request(
update ? `/taxes/${encodeURIComponent(catalog.tax.code)}` : "/taxes",
update ? "PUT" : "POST",
toLagoTaxPayload(catalog.tax),
lagoTaxResponseSchema
);
}
async applyPlan(plan: DesiredLagoPlan, update: boolean): Promise<void> {
await this.assertOrganization();
await this.request(
update ? `/plans/${encodeURIComponent(plan.code)}` : "/plans",
update ? "PUT" : "POST",
toLagoPlanPayload(plan, update),
lagoPlanResponseSchema
);
}
private async assertOrganization(): Promise<LagoCatalogSnapshot["organization"]> {
const response = await this.request("/organizations", "GET", undefined, lagoOrganizationResponseSchema);
if (!response) throw new BillingCatalogOperatorError("billing catalog: Lago organization is unavailable");
const idSha256 = createHash("sha256").update(response.organization.lago_id).digest("hex");
if (response.organization.name !== this.expectedOrganizationName || idSha256 !== this.expectedOrganizationIdSha256) {
throw new BillingCatalogOperatorError("billing catalog: Lago organization does not match the pinned target identity");
}
return { name: response.organization.name, idSha256 };
}
private async request<T>(path: string, method: "GET" | "POST" | "PUT", body: unknown, schema: z.ZodType<T>, allowNotFound = false): Promise<T | null> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
try {
const response = await this.fetchImpl(`${this.apiUrl}/api/v1${path}`, {
method,
headers: {
authorization: `Bearer ${this.apiKey}`,
accept: "application/json",
...(body === undefined ? {} : { "content-type": "application/json" }),
},
body: body === undefined ? undefined : JSON.stringify(body),
redirect: "error",
signal: controller.signal,
});
if (allowNotFound && response.status === 404) return null;
if (!response.ok) {
throw new BillingCatalogOperatorError(`billing catalog: Lago request failed with status ${response.status}`);
}
const parsed = schema.safeParse(await response.json());
if (!parsed.success) {
throw new BillingCatalogOperatorError("billing catalog: Lago response shape is invalid");
}
return parsed.data;
} catch (error) {
if (error instanceof BillingCatalogOperatorError) throw error;
throw new BillingCatalogOperatorError("billing catalog: Lago request failed");
} finally {
clearTimeout(timeout);
}
}
}