diff --git a/.changeset/billing-provider-from-env.md b/.changeset/billing-provider-from-env.md new file mode 100644 index 0000000..2422570 --- /dev/null +++ b/.changeset/billing-provider-from-env.md @@ -0,0 +1,9 @@ +--- +"@codelitdev/billing": minor +--- + +Choose the payment provider and catalog from env settings, so a product switches between Dodo and Lemon Squeezy without code changes. + +- `@codelitdev/billing/providers/env`: `readBillingProviderEnv(env, { offers })` reads `BILLING_PROVIDER`, the catalog revision, currency and each offer's amount and product ID, and checks each provider's credentials. It returns null when `BILLING_PROVIDER` is unset, and names the setting when one is missing or invalid. +- A provider other than the checkout one stays connected while its credentials are set, so its subscribers keep working after a switch. +- `createBillingProvidersFromEnv(providers, env, clock)` loads each adapter only when used. `dodoOptionsFromEnv` and `lemonSqueezyOptionsFromEnv` build the options alone. diff --git a/docs/decisions/0019-choose-billing-provider-by-settings.md b/docs/decisions/0019-choose-billing-provider-by-settings.md new file mode 100644 index 0000000..3d45b2d --- /dev/null +++ b/docs/decisions/0019-choose-billing-provider-by-settings.md @@ -0,0 +1,39 @@ +# ADR 0019: Choose the billing provider by settings + +Status: accepted +Date: 2026-11-17 + +## Context + +The provider contract lets a product swap adapters, but each product parsed its +own env and called one adapter's constructor. Moving CourseLit from Dodo to +Lemon Squeezy, and back when Lemon Squeezy announced it is winding down, needed +code changes each time. MediaLit had already written env parsing that picks the +provider and keeps the old one connected for its subscribers. + +## Decision + +- Add `@codelitdev/billing/providers/env`, based on MediaLit's parsing: + `readBillingProviderEnv`, `createBillingProvidersFromEnv`, + `dodoOptionsFromEnv` and `lemonSqueezyOptionsFromEnv`. +- The functions take the env record as an argument. Core and adapters still + never read the process environment (invariant 2). +- Settings names are shared by every product: `BILLING_PROVIDER`, + `BILLING_CATALOG_REVISION`, `BILLING_CURRENCY`, + `BILLING_DATA_ENCRYPTION_KEY`, `BILLING__AMOUNT_MINOR` and + `BILLING__PRODUCT_ID`, plus each provider's credentials. +- New checkout goes to `BILLING_PROVIDER`. Any other provider whose + credentials are set stays connected, so its subscriptions keep receiving + webhooks and reconciliation. +- Offers always have `providerTrialDays: 0`. Trials are the product's own. +- Adapters are loaded with dynamic imports, so the optional `dodopayments` peer + is needed only by products that use Dodo. + +## Consequences + +- A product switches provider by changing settings and raising + `BILLING_CATALOG_REVISION`. +- Products should accept every connected provider on + `POST /webhooks/billing/:provider`. +- `createBillingProvidersFromEnv` is async, so engine composition that uses it + must be too. diff --git a/packages/billing/AGENTS.md b/packages/billing/AGENTS.md index 65b1ed5..494f061 100644 --- a/packages/billing/AGENTS.md +++ b/packages/billing/AGENTS.md @@ -33,7 +33,7 @@ Do not add `console.log` (Biome's console rule, `warn`/`error` allowed). Do not | `src/schema/` | Canonical model + TS generator. | | `src/cli/` | `generate` / `--check` only. No migrate command. | | `src/adapters/drizzle/` | Store, `withTransaction`, `getTransaction()`, `noteProviderCall`. Only place that imports drizzle-orm. | -| `src/providers/` | Contract, registry, fake, Dodo. Dodo must not read `process.env` or emit `sendlit*` metadata. | +| `src/providers/` | Contract, registry, fake, Dodo, Lemon Squeezy, and `env/` (choose the provider from an env record passed in). None of them read `process.env`; Dodo must not emit `sendlit*` metadata. | | `src/workflows/engine.ts` | All cross-boundary workflows in one module (`createBilling`). Experimental. | | `src/operations/` | Operator inspect/retry/reconcile/cancel/decrypt. Requires `OperatorContext`. | | `src/ports/` | Audit, authorization grant, lifecycle hooks, sensitive values, telemetry. | diff --git a/packages/billing/README.md b/packages/billing/README.md index 74b2724..4ffd98e 100644 --- a/packages/billing/README.md +++ b/packages/billing/README.md @@ -80,6 +80,7 @@ Public imports (do not import `src/`): | `@codelitdev/billing/providers` | Registry, fake, contract types | | `@codelitdev/billing/providers/dodo` | `createDodoBillingProvider` | | `@codelitdev/billing/providers/lemonsqueezy` | `createLemonSqueezyBillingProvider` | +| `@codelitdev/billing/providers/env` | Choose the provider and catalog from env settings | | `@codelitdev/billing/core` | Statuses, money, errors, clock | | `@codelitdev/billing/catalog` | Offer validation / public catalog | | `@codelitdev/billing/testing` | Provider contract + workflow harness | @@ -175,6 +176,42 @@ When several products share one Dodo business, Dodo sends every event to every w To sell through Lemon Squeezy instead, compose `createLemonSqueezyBillingProvider` from `@codelitdev/billing/providers/lemonsqueezy` with `apiKey`, the product's `storeId`, and the store webhook's `webhookSecrets`, and set `checkoutProvider: "lemonsqueezy"`. Catalog offers name Lemon Squeezy variant IDs as `providerProductId`. Webhooks from other stores are stored as `ignored`. Trials come from the variant, so checkout rejects `trialDays`; plan changes apply immediately, and `do_not_bill` is refused for a change to another interval because Lemon Squeezy bills that at once. Turn off plan changes in the store's customer portal settings: the engine quarantines a plan change it did not start, along with that subscription's later webhooks. +### Choosing the provider by settings + +`@codelitdev/billing/providers/env` lets a product change provider by changing settings, without code changes. The app passes its env record; the package does not read the process environment. + +```ts +import { + createBillingProvidersFromEnv, + readBillingProviderEnv, +} from "@codelitdev/billing/providers/env"; + +const config = readBillingProviderEnv(process.env, { + offers: [ + { key: "pro_month", plan: "pro", interval: "month" }, + { key: "pro_year", plan: "pro", interval: "year" }, + ], +}); +// null when BILLING_PROVIDER is unset, e.g. a fake provider in development. +const providers = config + ? await createBillingProvidersFromEnv(config.providers, process.env, clock) + : []; +// createBilling({ providers, checkoutProvider: config.checkoutProvider, +// requestedRevision: config.revision, offers: config.offers, ... }) +``` + +| Setting | Meaning | +| --- | --- | +| `BILLING_PROVIDER` | `dodo` or `lemonsqueezy`: where new checkout goes | +| `BILLING_CATALOG_REVISION` | Raise it whenever prices, product IDs or the provider change | +| `BILLING_CURRENCY` | Three-letter code | +| `BILLING_DATA_ENCRYPTION_KEY` | Required here so a missing key fails at startup | +| `BILLING__AMOUNT_MINOR`, `BILLING__PRODUCT_ID` | Per offer; `pro_month` reads `BILLING_PRO_MONTH_*`. A Dodo product ID or a Lemon Squeezy variant ID | +| `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY_CURRENT` | Dodo credentials. Optional: `DODO_PAYMENTS_ENVIRONMENT` (`test_mode` by default), `DODO_PAYMENTS_WEBHOOK_KEY_PREVIOUS`, `DODO_BRAND_ID` | +| `LEMONSQUEEZY_API_KEY`, `LEMONSQUEEZY_STORE_ID`, `LEMONSQUEEZY_WEBHOOK_SECRET` | Lemon Squeezy credentials. Optional: `LEMONSQUEEZY_WEBHOOK_SECRET_PREVIOUS` | + +A provider other than `BILLING_PROVIDER` stays connected while its credentials are set, so its existing subscribers keep receiving webhooks after a switch; set all of its credentials or none. Accept every name in `config.providers` on `POST /webhooks/billing/:provider`. Provider products must have no trial: offers always carry `providerTrialDays: 0`. Each adapter loads only when used, so `dodopayments` is needed only with Dodo. + ```ts import { systemClock } from "@codelitdev/billing/core"; import { createDrizzleBillingStore } from "@codelitdev/billing/drizzle"; diff --git a/packages/billing/package.json b/packages/billing/package.json index 1cd1ad1..cfca5cd 100644 --- a/packages/billing/package.json +++ b/packages/billing/package.json @@ -58,6 +58,11 @@ "import": "./dist/providers/dodo/index.js", "default": "./dist/providers/dodo/index.js" }, + "./providers/env": { + "types": "./dist/providers/env/index.d.ts", + "import": "./dist/providers/env/index.js", + "default": "./dist/providers/env/index.js" + }, "./providers/lemonsqueezy": { "types": "./dist/providers/lemonsqueezy/index.d.ts", "import": "./dist/providers/lemonsqueezy/index.js", diff --git a/packages/billing/src/exports.test.ts b/packages/billing/src/exports.test.ts index 01d8366..916d10f 100644 --- a/packages/billing/src/exports.test.ts +++ b/packages/billing/src/exports.test.ts @@ -19,6 +19,7 @@ describe("public exports", () => { "./operations", "./providers", "./providers/dodo", + "./providers/env", "./providers/lemonsqueezy", "./testing", ]; diff --git a/packages/billing/src/providers/env/index.test.ts b/packages/billing/src/providers/env/index.test.ts new file mode 100644 index 0000000..c1892af --- /dev/null +++ b/packages/billing/src/providers/env/index.test.ts @@ -0,0 +1,174 @@ +import { describe, expect, it } from "bun:test"; +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { systemClock } from "../../core/clock.js"; +import { + type BillingEnv, + createBillingProvidersFromEnv, + dodoOptionsFromEnv, + lemonSqueezyOptionsFromEnv, + readBillingProviderEnv, +} from "./index.js"; + +const OFFERS = [ + { key: "pro_month", plan: "pro", interval: "month" }, + { key: "pro_year", plan: "pro", interval: "year" }, +] as const; + +const LEMONSQUEEZY: BillingEnv = { + LEMONSQUEEZY_API_KEY: "ls-key", + LEMONSQUEEZY_STORE_ID: "4242", + LEMONSQUEEZY_WEBHOOK_SECRET: "ls-secret", +}; +const DODO: BillingEnv = { + DODO_PAYMENTS_API_KEY: "dodo-key", + DODO_PAYMENTS_WEBHOOK_KEY_CURRENT: "whsec_current", +}; + +function env(provider: string, overrides: BillingEnv = {}): BillingEnv { + const dodo = provider === "dodo"; + return { + BILLING_PROVIDER: provider, + BILLING_CATALOG_REVISION: "3", + BILLING_CURRENCY: "usd", + BILLING_DATA_ENCRYPTION_KEY: "test-encryption-key", + BILLING_PRO_MONTH_AMOUNT_MINOR: "1900", + BILLING_PRO_YEAR_AMOUNT_MINOR: "19000", + BILLING_PRO_MONTH_PRODUCT_ID: dodo ? "pdt_month" : "1001", + BILLING_PRO_YEAR_PRODUCT_ID: dodo ? "pdt_year" : "1002", + ...(dodo ? DODO : LEMONSQUEEZY), + ...overrides, + }; +} + +const read = (values: BillingEnv) => readBillingProviderEnv(values, { offers: OFFERS }); + +describe("readBillingProviderEnv", () => { + it("returns null without BILLING_PROVIDER", () => { + expect(read({})).toBeNull(); + expect(read({ BILLING_PROVIDER: " " })).toBeNull(); + }); + + it("builds the catalog for the checkout provider", () => { + for (const provider of ["dodo", "lemonsqueezy"] as const) { + const config = read(env(provider)); + expect(config?.checkoutProvider).toBe(provider); + expect(config?.providers).toEqual([provider]); + expect(config?.revision).toBe(3); + expect(config?.currency).toBe("USD"); + expect(config?.offers[0]).toEqual({ + key: "pro_month", + revision: 3, + plan: "pro", + interval: "month", + currency: "USD", + amountMinor: 1900, + provider, + providerProductId: provider === "dodo" ? "pdt_month" : "1001", + providerTrialDays: 0, + }); + } + }); + + it("switches provider by settings alone and keeps the old one connected", () => { + const config = read(env("dodo", LEMONSQUEEZY)); + expect(config?.checkoutProvider).toBe("dodo"); + expect(config?.providers).toEqual(["dodo", "lemonsqueezy"]); + expect(config?.offers.every((offer) => offer.provider === "dodo")).toBe(true); + }); + + it("rejects an unknown provider", () => { + expect(() => read(env("stripe"))).toThrow("BILLING_PROVIDER_invalid"); + }); + + it("names a missing setting", () => { + expect(() => read(env("dodo", { DODO_PAYMENTS_API_KEY: "" }))).toThrow( + "DODO_PAYMENTS_API_KEY_required", + ); + expect(() => + read(env("lemonsqueezy", { BILLING_PRO_YEAR_AMOUNT_MINOR: undefined })), + ).toThrow("BILLING_PRO_YEAR_AMOUNT_MINOR_required"); + expect(() => read(env("dodo", { BILLING_DATA_ENCRYPTION_KEY: "" }))).toThrow( + "BILLING_DATA_ENCRYPTION_KEY_required", + ); + }); + + it("refuses a partly configured second provider", () => { + expect(() => read(env("dodo", { LEMONSQUEEZY_API_KEY: "ls-key" }))).toThrow( + "LEMONSQUEEZY_STORE_ID_required", + ); + }); + + it("validates amounts, revision, currency and product ids", () => { + expect(() => + read(env("dodo", { BILLING_PRO_MONTH_AMOUNT_MINOR: "19.00" })), + ).toThrow("BILLING_PRO_MONTH_AMOUNT_MINOR_invalid"); + expect(() => read(env("dodo", { BILLING_CATALOG_REVISION: "0" }))).toThrow( + "BILLING_CATALOG_REVISION_invalid", + ); + expect(() => read(env("dodo", { BILLING_CURRENCY: "dollars" }))).toThrow( + "BILLING_CURRENCY_invalid", + ); + expect(() => + read(env("lemonsqueezy", { BILLING_PRO_MONTH_PRODUCT_ID: "pdt_month" })), + ).toThrow("BILLING_PRO_MONTH_PRODUCT_ID_invalid"); + expect(() => + read(env("dodo", { BILLING_PRO_YEAR_PRODUCT_ID: "pdt_month" })), + ).toThrow("BILLING_PRODUCT_IDS_must_be_unique"); + }); +}); + +describe("provider options", () => { + it("reads Dodo options with rotation and brand", () => { + const options = dodoOptionsFromEnv( + { + ...DODO, + DODO_PAYMENTS_ENVIRONMENT: "live_mode", + DODO_PAYMENTS_WEBHOOK_KEY_PREVIOUS: "whsec_old", + DODO_BRAND_ID: "brnd_1", + }, + systemClock, + ); + expect(options.environment).toBe("live_mode"); + expect(options.brandId).toBe("brnd_1"); + expect(options.webhookSecrets.map((entry) => entry.version)).toEqual([ + "current", + "previous", + ]); + expect(dodoOptionsFromEnv(DODO, systemClock).environment).toBe("test_mode"); + expect(() => + dodoOptionsFromEnv({ ...DODO, DODO_PAYMENTS_ENVIRONMENT: "prod" }, systemClock), + ).toThrow("DODO_PAYMENTS_ENVIRONMENT_invalid"); + }); + + it("reads Lemon Squeezy options", () => { + const options = lemonSqueezyOptionsFromEnv(LEMONSQUEEZY, systemClock); + expect(options.storeId).toBe("4242"); + expect(options.webhookSecrets).toEqual([ + { version: "current", secret: "ls-secret" }, + ]); + }); +}); + +describe("createBillingProvidersFromEnv", () => { + it("creates each connected adapter, checkout provider first", async () => { + const adapters = await createBillingProvidersFromEnv( + ["dodo", "lemonsqueezy"], + { ...DODO, ...LEMONSQUEEZY }, + systemClock, + ); + expect(adapters.map((adapter) => adapter.provider)).toEqual([ + "dodo", + "lemonsqueezy", + ]); + }); + + it("does not read process.env or import the Dodo SDK statically", async () => { + const dir = path.dirname(fileURLToPath(import.meta.url)); + const source = await readFile(path.join(dir, "index.ts"), "utf8"); + expect(source).not.toMatch(/process\.env/); + expect(source).not.toMatch(/from "dodopayments"/); + expect(source).not.toMatch(/^import .*\/dodo\/index\.js/m); + }); +}); diff --git a/packages/billing/src/providers/env/index.ts b/packages/billing/src/providers/env/index.ts new file mode 100644 index 0000000..f548add --- /dev/null +++ b/packages/billing/src/providers/env/index.ts @@ -0,0 +1,227 @@ +import { type BillingOffer, validateCatalog } from "../../catalog/index.js"; +import type { Clock } from "../../core/clock.js"; +import { BillingConfigurationError } from "../../core/errors.js"; +import type { BillingInterval } from "../../core/ids.js"; +import type { + BillingProviderAdapter, + DodoBillingProviderOptions, + LemonSqueezyBillingProviderOptions, +} from "../contract.js"; + +/** + * Picks the payment provider and the paid catalog from environment variables, so + * a product changes provider by changing settings, not code (ADR 0019). + * + * The env record is passed in; nothing here reads the process environment. Settings: + * + * BILLING_PROVIDER=dodo | lemonsqueezy where new checkout goes + * BILLING_CATALOG_REVISION= raise it whenever prices, product ids or the provider change + * BILLING_CURRENCY=USD + * BILLING_DATA_ENCRYPTION_KEY= encrypts stored checkout URLs and webhook payloads + * BILLING__AMOUNT_MINOR= per offer, e.g. BILLING_PRO_MONTH_AMOUNT_MINOR + * BILLING__PRODUCT_ID= Dodo product id or Lemon Squeezy variant id + * + * plus the credentials of each provider in use (`BILLING_PROVIDER_ENV`). A provider + * other than the checkout one stays connected while any of its credentials is set, + * so its existing subscriptions keep receiving webhooks after a switch. + */ +export const BILLING_PROVIDER_NAMES = ["dodo", "lemonsqueezy"] as const; +export type BillingProviderName = (typeof BILLING_PROVIDER_NAMES)[number]; + +/** Credentials each provider needs. All of them must be set once any one is. */ +export const BILLING_PROVIDER_ENV: Record = { + dodo: ["DODO_PAYMENTS_API_KEY", "DODO_PAYMENTS_WEBHOOK_KEY_CURRENT"], + lemonsqueezy: [ + "LEMONSQUEEZY_API_KEY", + "LEMONSQUEEZY_STORE_ID", + "LEMONSQUEEZY_WEBHOOK_SECRET", + ], +}; + +export type BillingEnv = Record; + +/** One paid offer of the product. Its env names come from the key: `pro_month` reads `BILLING_PRO_MONTH_*`. */ +export type BillingEnvOffer< + PlanId extends string = string, + OfferKey extends string = string, +> = { + key: OfferKey; + plan: PlanId; + interval: BillingInterval; +}; + +export type BillingProviderEnvConfig< + PlanId extends string = string, + OfferKey extends string = string, +> = { + /** Where new checkout goes. */ + checkoutProvider: BillingProviderName; + /** The checkout provider first, then every other provider with credentials set. */ + providers: BillingProviderName[]; + revision: number; + currency: string; + offers: BillingOffer[]; +}; + +function value(env: BillingEnv, name: string): string | undefined { + const raw = env[name]?.trim(); + return raw ? raw : undefined; +} + +function required(env: BillingEnv, name: string): string { + const raw = value(env, name); + if (!raw) throw new BillingConfigurationError(`${name}_required`); + return raw; +} + +function positiveInt(env: BillingEnv, name: string): number { + const raw = required(env, name); + const parsed = Number(raw); + if (!/^[1-9][0-9]*$/.test(raw) || !Number.isSafeInteger(parsed)) { + throw new BillingConfigurationError(`${name}_invalid`); + } + return parsed; +} + +function isProviderName(name: string): name is BillingProviderName { + return (BILLING_PROVIDER_NAMES as readonly string[]).includes(name); +} + +function connected(env: BillingEnv, name: BillingProviderName): boolean { + const set = BILLING_PROVIDER_ENV[name].filter((key) => value(env, key)); + if (set.length === 0) return false; + if (set.length !== BILLING_PROVIDER_ENV[name].length) { + const missing = BILLING_PROVIDER_ENV[name].find((key) => !value(env, key)); + throw new BillingConfigurationError(`${missing}_required`); + } + return true; +} + +/** + * Reads the checkout provider, connected providers and paid catalog. Returns null + * when `BILLING_PROVIDER` is unset, so a product can fall back to a fake provider in + * development. Anything set but incomplete or invalid throws, naming the setting. + */ +export function readBillingProviderEnv( + env: BillingEnv, + options: { offers: readonly BillingEnvOffer[] }, +): BillingProviderEnvConfig | null { + const checkoutProvider = value(env, "BILLING_PROVIDER"); + if (!checkoutProvider) return null; + if (!isProviderName(checkoutProvider)) { + throw new BillingConfigurationError("BILLING_PROVIDER_invalid"); + } + for (const name of BILLING_PROVIDER_ENV[checkoutProvider]) required(env, name); + const providers: BillingProviderName[] = [ + checkoutProvider, + ...BILLING_PROVIDER_NAMES.filter( + (name) => name !== checkoutProvider && connected(env, name), + ), + ]; + // Only read by the app's sensitive-values store, but checked here so a missing key + // fails at startup rather than at the first checkout. + required(env, "BILLING_DATA_ENCRYPTION_KEY"); + const revision = positiveInt(env, "BILLING_CATALOG_REVISION"); + const currency = required(env, "BILLING_CURRENCY").toUpperCase(); + if (!/^[A-Z]{3}$/.test(currency)) { + throw new BillingConfigurationError("BILLING_CURRENCY_invalid"); + } + const productPattern = + checkoutProvider === "lemonsqueezy" ? /^[0-9]+$/ : /^\S{2,256}$/; + const offers = options.offers.map((offer): BillingOffer => { + const name = `BILLING_${offer.key.toUpperCase()}`; + const providerProductId = required(env, `${name}_PRODUCT_ID`); + if (!productPattern.test(providerProductId)) { + throw new BillingConfigurationError(`${name}_PRODUCT_ID_invalid`); + } + return { + key: offer.key, + revision, + plan: offer.plan, + interval: offer.interval, + currency, + amountMinor: positiveInt(env, `${name}_AMOUNT_MINOR`), + provider: checkoutProvider, + providerProductId, + // Trials are the product's own; provider products must have none. + providerTrialDays: 0, + }; + }); + if (new Set(offers.map((offer) => offer.providerProductId)).size !== offers.length) { + throw new BillingConfigurationError("BILLING_PRODUCT_IDS_must_be_unique"); + } + validateCatalog({ + offers, + requiredOfferKeys: offers.map((offer) => offer.key), + revision, + checkoutProvider, + }); + return { checkoutProvider, providers, revision, currency, offers }; +} + +function secrets(current: string, previous: string | undefined) { + return [ + { version: "current", secret: current }, + ...(previous ? [{ version: "previous", secret: previous }] : []), + ]; +} + +export function dodoOptionsFromEnv( + env: BillingEnv, + clock: Clock, +): DodoBillingProviderOptions { + const environment = value(env, "DODO_PAYMENTS_ENVIRONMENT") ?? "test_mode"; + if (environment !== "test_mode" && environment !== "live_mode") { + throw new BillingConfigurationError("DODO_PAYMENTS_ENVIRONMENT_invalid"); + } + const brandId = value(env, "DODO_BRAND_ID"); + return { + apiKey: required(env, "DODO_PAYMENTS_API_KEY"), + environment, + webhookSecrets: secrets( + required(env, "DODO_PAYMENTS_WEBHOOK_KEY_CURRENT"), + value(env, "DODO_PAYMENTS_WEBHOOK_KEY_PREVIOUS"), + ), + // Dodo sends every brand's events to every endpoint; others are ignored. + ...(brandId ? { brandId } : {}), + clock, + }; +} + +export function lemonSqueezyOptionsFromEnv( + env: BillingEnv, + clock: Clock, +): LemonSqueezyBillingProviderOptions { + return { + apiKey: required(env, "LEMONSQUEEZY_API_KEY"), + storeId: required(env, "LEMONSQUEEZY_STORE_ID"), + webhookSecrets: secrets( + required(env, "LEMONSQUEEZY_WEBHOOK_SECRET"), + value(env, "LEMONSQUEEZY_WEBHOOK_SECRET_PREVIOUS"), + ), + clock, + }; +} + +/** + * Adapters for the given providers, checkout provider first. Each adapter is loaded + * only when used, so the optional `dodopayments` SDK is needed only with Dodo. + */ +export async function createBillingProvidersFromEnv( + providers: readonly BillingProviderName[], + env: BillingEnv, + clock: Clock, +): Promise { + return Promise.all( + providers.map(async (name): Promise => { + if (name === "dodo") { + const { createDodoBillingProvider } = await import("../dodo/index.js"); + return createDodoBillingProvider(dodoOptionsFromEnv(env, clock)); + } + const { createLemonSqueezyBillingProvider } = await import( + "../lemonsqueezy/index.js" + ); + return createLemonSqueezyBillingProvider(lemonSqueezyOptionsFromEnv(env, clock)); + }), + ); +}