@billkit-eu/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/pagination.ts","../src/resources.ts","../src/errors.ts","../src/logging.ts","../src/retry.ts","../src/version.ts","../src/transport.ts","../src/client.ts","../src/webhooks.ts"],"names":["delayMs"],"mappings":";AAkDA,gBAAuB,QAAA,CACrB,MAAA,EACA,OAAA,GAA2B,EAAC,EACF;AAC1B,EAAA,MAAM,EAAE,QAAA,EAAU,OAAA,EAAQ,GAAI,OAAA;AAC9B,EAAA,MAAM,eAA2C,EAAC;AAClD,EAAA,IAAI,OAAA,EAAS;AACX,IAAA,KAAA,MAAW,CAAC,CAAA,EAAG,CAAC,KAAK,MAAA,CAAO,OAAA,CAAQ,OAAO,CAAA,EAAG;AAC5C,MAAA,IAAI,CAAA,KAAM,MAAA,EAAW,YAAA,CAAa,CAAC,CAAA,GAAI,CAAA;AAAA,IACzC;AAAA,EACF;AAEA,EAAA,IAAI,MAAA;AACJ,EAAA,WAAS;AACP,IAAA,MAAM,IAAA,GAAO,MAAM,MAAA,CAAO;AAAA,MACxB,GAAG,YAAA;AAAA,MACH,KAAA,EAAO,QAAA;AAAA,MACP,cAAA,EAAgB;AAAA,KACjB,CAAA;AACD,IAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,IAAA,IAAQ,EAAC;AAC5B,IAAA,KAAA,MAAW,IAAA,IAAQ,OAAO,MAAM,IAAA;AAChC,IAAA,IAAI,CAAC,IAAA,CAAK,QAAA,IAAY,KAAA,CAAM,WAAW,CAAA,EAAG;AAC1C,IAAA,MAAM,IAAA,GAAO,KAAA,CAAM,KAAA,CAAM,MAAA,GAAS,CAAC,CAAA;AACnC,IAAA,MAAA,GAAS,IAAA,EAAM,EAAA;AACf,IAAA,IAAI,WAAW,MAAA,EAAW;AAAA,EAC5B;AACF;;;ACiSA,SAAS,cAAiD,GAAA,EAA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;AACd,IAAA,IAAI,iBAAA,CAAkB,QAAA,EAAU,QAAQ,CAAA,EAAG,OAAA,GAAU,IAAA;AAAA,EACvD;AACA,EAAA,IAAI,CAAC,WAAA,EAAa;AAChB,IAAA,MAAM,IAAI,wBAAA;AAAA,MACR,CAAA,uCAAA,EAA0C,MAAA,CAAO,IAAA,CAAK,GAAG,CAAC,CAAA;AAAA,KAC5D;AAAA,EACF;AACA,EAAA,IAAI,CAAC,OAAA,EAAS;AACZ,IAAA,MAAM,IAAI,yBAAyB,qBAAqB,CAAA;AAAA,EAC1D;AAEA,EAAA,MAAM,UAAU,IAAI,WAAA,CAAY,SAAS,EAAE,KAAA,EAAO,OAAO,CAAA;AACzD,EAAA,MAAM,IAAA,GAAO,OAAA,CAAQ,MAAA,CAAO,YAAY,CAAA;AACxC,EAAA,IAAI;AACF,IAAA,OAAO,IAAA,CAAK,MAAM,IAAI,CAAA;AAAA,EACxB,SAAS,GAAA,EAAK;AACZ,IAAA,MAAM,IAAI,wBAAA;AAAA,MACR,CAAA,gCAAA,EAAoC,IAAc,OAAO,CAAA;AAAA,KAC3D;AAAA,EACF;AACF","file":"index.js","sourcesContent":["/**\n * Auto-pagination helper for list endpoints.\n *\n * The BillKit API returns Stripe-shape envelopes:\n *\n * { \"object\": \"list\", \"data\": [...], \"has_more\": bool }\n *\n * Cursor pagination is forward-only via the last item's `id` as\n * `starting_after`. `paginate` walks every page and yields each row.\n * Callers consume it via `for await`:\n *\n * for await (const customer of client.customers.iter()) {\n * ...\n * }\n */\n\nimport type { QueryValue } from \"./transport.js\";\n\nexport interface ListResponseEnvelope<T = unknown> {\n readonly data?: readonly T[];\n readonly has_more?: boolean;\n}\n\nexport interface PaginateOptions {\n /** Maps to the API's `limit` parameter. `undefined` lets the\n * server pick its default (10 today). */\n pageSize?: number | undefined;\n /** Extra filters forwarded on every page (e.g. `type` on events,\n * `action` on audit logs). Values are pruned of `undefined` so\n * callers can spread their full options object in. */\n filters?: Readonly<Record<string, QueryValue>>;\n}\n\ntype ListFn<T> = (params: {\n limit?: number | undefined;\n starting_after?: string | undefined;\n [key: string]: QueryValue;\n}) => Promise<ListResponseEnvelope<T>>;\n\n/**\n * Walk every page of `listFn` and yield each row.\n *\n * Three terminators, in priority order:\n * 1. `has_more=false`: the server's authoritative signal (common case).\n * 2. Empty `data` with `has_more=true`: shouldn't happen per the API\n * contract, but if a future server bug or proxy misbehaviour\n * produced it the iterator would loop forever. Belt-and-suspenders.\n * 3. The last row has no `id`, so there is no cursor to advance with. The schema\n * doesn't allow it today, but same defensive reasoning.\n */\nexport async function* paginate<T>(\n listFn: ListFn<T>,\n options: PaginateOptions = {},\n): AsyncIterableIterator<T> {\n const { pageSize, filters } = options;\n const cleanFilters: Record<string, QueryValue> = {};\n if (filters) {\n for (const [k, v] of Object.entries(filters)) {\n if (v !== undefined) cleanFilters[k] = v;\n }\n }\n\n let cursor: string | undefined;\n for (;;) {\n const page = await listFn({\n ...cleanFilters,\n limit: pageSize,\n starting_after: cursor,\n });\n const items = page.data ?? [];\n for (const item of items) yield item;\n if (!page.has_more || items.length === 0) return;\n const last = items[items.length - 1] as { id?: string } | undefined;\n cursor = last?.id;\n if (cursor === undefined) return;\n }\n}\n","/**\n * Resource accessors mirroring the BillKit API surface.\n *\n * Each resource exposes the public verbs from `/v1/<resource>`. The\n * return type defaults to `unknown`; the SDK doesn't ship runtime\n * schemas (zod / valibot) because the API is Stripe-shape and tenants\n * typically forward the JSON through their own data layer unchanged.\n * Callers who want strong types parameterise each call with their\n * own generic:\n *\n * interface Customer { id: string; email: string }\n * const c = await client.customers.create<Customer>({ email: \"...\" });\n *\n * Every list-returning resource also exposes an `iter()` method that\n * walks every page via the Stripe-shape `has_more` + `starting_after`\n * cursor protocol. Iterate with `for await`:\n *\n * for await (const customer of client.customers.iter()) { ... }\n */\n\nimport { paginate, type ListResponseEnvelope } from \"./pagination.js\";\nimport type { QueryValue, Transport } from \"./transport.js\";\n\n// ─── Shared parameter shapes ───────────────────────────────────────\n\n/**\n * Cursor-pagination knobs shared by every `list()` method.\n *\n * The index signature is what lets a resource-specific extension\n * (e.g. `EventsListParams` adds `type?: string`) flow through the\n * Transport's `query` shape without a cast. Excess fields are\n * tolerated; `undefined` values are pruned before serialisation.\n */\nexport interface BaseListParams {\n limit?: number;\n starting_after?: string;\n ending_before?: string;\n readonly [key: string]: QueryValue;\n}\n\n/**\n * `prices.list` params. Adds the server-side `product_id` filter on top of\n * the usual cursor knobs. `GET /v1/prices?product_id=...` narrows to one\n * product's prices, which beats listing everything and filtering client-side\n * once a tenant has more than a page of prices.\n */\nexport interface PricesListParams extends BaseListParams {\n product_id?: string;\n}\n\n/** Optional idempotency knob carried by every mutating call. */\nexport interface IdempotencyOptions {\n /** Coalesces retries across process restarts. The SDK generates\n * a random `sdk-<uuid>` key for every mutating call if you don't\n * supply one. Pass your own when you want retries from a different\n * process to converge on the same server-side result. */\n idempotencyKey?: string;\n}\n\n// Keep a type alias for backward compatibility with the previous\n// loosely-typed ListParams. New code should reach for the\n// resource-specific *ListParams (e.g. `EventsListParams`).\nexport type ListParams = BaseListParams & {\n readonly [key: string]: QueryValue;\n};\n\n// ─── Per-resource parameter shapes ─────────────────────────────────\n//\n// We keep one exported interface per public surface so callers can\n// import the shape, build it ahead of time, and pass it in. Inlined\n// shapes were inconsistent across resources; the named-interface\n// form is greppable and survives editor \"go to definition\".\n\nexport interface CreateCustomerParams extends IdempotencyOptions {\n email?: string;\n name?: string;\n country_code?: string;\n metadata?: Record<string, string>;\n}\n\nexport interface UpdateCustomerParams extends IdempotencyOptions {\n email?: string;\n name?: string;\n country_code?: string;\n metadata?: Record<string, string>;\n}\n\n/**\n * Body for `POST /v1/customers/{id}/vat_number`. The VAT number is\n * sent through VIES server-side; the response carries\n * `vat_number_validated` reflecting the outcome.\n */\nexport interface SetCustomerVatNumberParams extends IdempotencyOptions {\n vat_number: string;\n country_code?: string;\n}\n\n/**\n * Body for `POST /v1/customers/{id}/purge`. The server requires\n * `confirmed: true` as a fat-finger guard against accidental purges\n * fired from a DELETE that meant to soft-delete. The SDK defaults\n * `confirmed` to `true` so the caller doesn't have to opt in twice.\n */\nexport interface PurgeCustomerParams extends IdempotencyOptions {\n confirmed?: boolean;\n}\n\nexport interface CreateProductParams extends IdempotencyOptions {\n /** Customer-facing name, for example \"Pro\" or \"Enterprise\". */\n name: string;\n /** Optional long-form description shown in your own catalog UI. */\n description?: string;\n /** Ordered bullets suitable for pricing tables and checkout pages. */\n marketing_features?: string[];\n /** Small string metadata map echoed back on the Product object. */\n metadata?: Record<string, string>;\n}\n\nexport interface UpdateProductParams extends IdempotencyOptions {\n name?: string;\n description?: string;\n marketing_features?: string[];\n metadata?: Record<string, string>;\n /** Set false to stop selling a product without deleting history. */\n active?: boolean;\n}\n\nexport interface CreatePriceParams extends IdempotencyOptions {\n /** Existing Product id returned from `client.products.create`. */\n product_id: string;\n amount_cents: number;\n currency: string;\n interval: \"month\" | \"year\" | (string & {});\n metadata?: Record<string, string>;\n trial_days?: number;\n trial_verification_cents?: number;\n payment_methods?: Array<\"creditcard\" | \"directdebit\" | (string & {})>;\n /**\n * Per-Price refund-window override (`POST /v1/prices`). `undefined`\n * inherits the default policy table (7d / 30d initial, 3d renewal);\n * `0` disables refunds for that charge type; `N > 0` is an N-day\n * window (capped server-side at 365). Useful for \"Pro Bundle has a\n * 14-day money back\" or \"Lifetime: no refunds\" product decisions.\n */\n refund_window_initial_days?: number;\n refund_window_renewal_days?: number;\n /**\n * Whether `amount_cents` is quoted gross (`\"inclusive\"`, VAT is\n * backed out of it) or net (`\"exclusive\"`, VAT is added on top at\n * charge time). `undefined` inherits `\"unspecified\"`, which defers to\n * the tax rate configured for the buyer's country. Set it explicitly\n * when the amount you advertise has to be the amount charged,\n * regardless of what tax rates exist now or later.\n */\n tax_behavior?: \"inclusive\" | \"exclusive\" | \"unspecified\";\n}\n\nexport interface CreateCheckoutSessionParams extends IdempotencyOptions {\n /**\n * Existing Customer to attach the session to. Mutually exclusive\n * with `customer_email`; exactly one of the two must be set.\n */\n customer_id?: string;\n /**\n * Stripe-compatible shortcut: BillKit creates a fresh Customer row\n * in the same transaction as the checkout. Never dedupes by email\n * (emails are not unique identifiers in BillKit). Mutually exclusive\n * with `customer_id`.\n */\n customer_email?: string;\n /**\n * Optional friendly name carried onto the auto-created Customer when\n * using `customer_email`. Rejected with `422` if supplied alongside\n * `customer_id` (rename existing customers via `customers.update`).\n */\n customer_name?: string;\n price_id: string;\n success_url: string;\n cancel_url: string;\n /**\n * Pin the Mollie payment method. `undefined` lets Mollie pick from\n * the customer's available methods; when set, must be in the price's\n * `payment_methods` allowlist.\n */\n method?: \"creditcard\" | \"directdebit\" | (string & {});\n /** Optional coupon code applied at checkout; atomically claimed. */\n coupon_code?: string;\n /**\n * Per-session trial override. Replaces the price's `trial_days`\n * for this checkout. Capped server-side at `2 × max(price.trial_days, 14)`.\n * `0` disables a trial that the price would otherwise grant.\n */\n trial_days_override?: number;\n}\n\nexport interface CreateRefundParams extends IdempotencyOptions {\n payment_id?: string;\n subscription_id?: string;\n /**\n * Refund a mandate-less one-shot payment (`oneShotPayments.create`).\n * Mutually exclusive with `payment_id` / `subscription_id`; pass\n * exactly one target or the server rejects with `400`.\n */\n one_shot_payment_id?: string;\n /**\n * Partial-refund amount in minor units. Omit to refund the whole remaining\n * balance (the full charge when nothing has been refunded yet). A payment\n * may carry several partial refunds up to the charged amount; the one that\n * brings the cumulative total to the full charge cancels the bound\n * subscription (or flips a one-shot to `refunded`).\n */\n amount_cents?: number;\n reason?: string;\n}\n\n/**\n * Body for `POST /v1/checkout/one_shot`, a single mandate-less charge\n * (the Stripe PaymentIntent shape, mapped onto Mollie). No subscription,\n * no mandate, no renewals: it settles once against your `success_url`.\n */\nexport interface CreateOneShotPaymentParams extends IdempotencyOptions {\n /** Existing Customer to charge. */\n customer_id: string;\n amount_cents: number;\n /** ISO-4217, e.g. `\"EUR\"`. Validated against the tenant allowlist. */\n currency: string;\n /**\n * Concrete Mollie method to charge with. Required, because a one-shot commits\n * up front). Validated against the tenant's capability allowlist for\n * `currency`; one-off methods like `bancontact`/`eps` are allowed here\n * even though they can't back a subscription.\n *\n * `giropay` was removed: the scheme shut down at the end of 2024 and the\n * server now 422s it. The `(string & {})` tail keeps this open on\n * purpose: unlike the console's read-side `PaymentMethodKind`, this is a\n * *request* type the server validates, so an SDK that lags a newly-added\n * method should not be the thing that blocks the call.\n */\n method: \"creditcard\" | \"directdebit\" | \"ideal\" | \"bancontact\" | \"eps\" | (string & {});\n /** Where Mollie returns the payer after the hosted checkout. */\n success_url: string;\n /** Optional page for an abandoned/cancelled payment. */\n cancel_url?: string;\n /** Shown on the Mollie page + the payer's bank statement. */\n description?: string;\n /**\n * Per-payment refund-window override in days. `undefined` inherits the\n * one-shot default (30 days); `0` disables refunds for this payment;\n * `N > 0` is an N-day window (capped server-side at 365).\n */\n refund_window_days?: number;\n /**\n * Whether `amount_cents` is quoted gross or net.\n *\n * `\"inclusive\"` (the default when omitted) charges `amount_cents` and\n * backs the VAT out of it. `\"exclusive\"` reads it as a net figure and\n * charges the payer `amount_cents + tax`, so the response's\n * `amount_cents` comes back *larger* than the one you sent, because it\n * is always what was actually charged. Reconcile against `net_cents` /\n * `tax_cents` on the response.\n *\n * Omit to inherit the country default from your configured tax rate.\n */\n tax_behavior?: \"inclusive\" | \"exclusive\";\n metadata?: Record<string, string>;\n}\n\nexport interface CreateWebhookEndpointParams extends IdempotencyOptions {\n url: string;\n enabled_events?: string[];\n description?: string;\n}\n\nexport interface UpdateWebhookEndpointParams extends IdempotencyOptions {\n url?: string;\n enabled_events?: string[];\n description?: string;\n status?: string;\n}\n\nexport interface EventsListParams extends BaseListParams {\n /** Server-side filter, e.g. `customer.created`. */\n type?: string;\n}\n\nexport interface SetPortalBrandingParams extends IdempotencyOptions {\n business_name?: string;\n support_email?: string;\n logo_url?: string;\n theme?: Record<string, unknown>;\n capabilities?: Record<string, unknown>;\n}\n\nexport interface RotateProviderCredentialParams extends IdempotencyOptions {\n /** New raw provider API key. Encrypted server-side; never logged. */\n api_key: string;\n /** Defaults to the calling key's mode. */\n mode?: \"test\" | \"live\" | (string & {});\n /** Currently only `\"mollie\"`. */\n provider?: \"mollie\" | (string & {});\n}\n\nexport interface CreateCouponParams extends IdempotencyOptions {\n code: string;\n discount_type: \"percentage\" | \"amount\" | (string & {});\n discount_value: number;\n duration: \"once\" | \"repeating\" | \"forever\" | (string & {});\n duration_in_months?: number;\n max_redemptions?: number;\n redeem_by?: number;\n applies_to_price_ids?: string[];\n min_amount_cents?: number;\n}\n\nexport interface UpdateCouponParams extends IdempotencyOptions {\n active?: boolean;\n max_redemptions?: number;\n redeem_by?: number;\n applies_to_price_ids?: string[];\n min_amount_cents?: number;\n}\n\nexport interface ValidateCouponParams {\n code: string;\n /**\n * Scope the dry-run to one price. Optional: omit to validate the code\n * on its own (existence, active, not exhausted, not expired). Supply it\n * to also check the coupon's `applies_to_price_ids` restriction.\n */\n price_id?: string;\n /**\n * Base amount the discount is computed against, in minor units.\n * Optional: omit to skip the discount math and the `min_amount_cents`\n * check. `POST /v1/coupons/validate` treats both fields as nullable.\n */\n amount_cents?: number;\n}\n\nexport interface CreateTaxRateParams extends IdempotencyOptions {\n country_code: string;\n rate_basis_points: number;\n display_name?: string;\n inclusive?: boolean;\n}\n\nexport interface UpdateTaxRateParams extends IdempotencyOptions {\n rate_basis_points?: number;\n display_name?: string;\n inclusive?: boolean;\n active?: boolean;\n}\n\nexport interface AuditLogsListParams extends BaseListParams {\n action?: string;\n resource_type?: string;\n actor_id?: string;\n}\n\nexport interface CreateBillingPortalSessionParams extends IdempotencyOptions {\n subscription_id: string;\n return_url: string;\n}\n\n// ─── Internals ─────────────────────────────────────────────────────\n\nfunction dropUndefined<T extends Record<string, unknown>>(obj: T): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(obj)) {\n if (v !== undefined) out[k] = v;\n }\n return out;\n}\n\n/**\n * Strips the `idempotencyKey` carrier from a mutating-call body and\n * returns `{ body, idempotencyKey }`. Pulled out so the per-resource\n * methods read as \"describe the verb\" instead of \"shuffle keys\".\n */\nfunction splitIdempotency<P extends IdempotencyOptions>(\n params: P,\n): { body: Record<string, unknown>; idempotencyKey: string | undefined } {\n const { idempotencyKey, ...rest } = params;\n return { body: dropUndefined(rest as Record<string, unknown>), idempotencyKey };\n}\n\n/**\n * Shared transport wrapper. Resources subclass this so each method\n * reads as a single line, \"verb to path with params\", instead of\n * the four-line `this.t.request({ ... })` boilerplate the previous\n * draft repeated everywhere.\n */\nabstract class BaseResource {\n constructor(protected readonly t: Transport) {}\n\n protected get<T>(path: string, query?: BaseListParams & Record<string, QueryValue>): Promise<T> {\n return this.t.request<T>({ method: \"GET\", path, query });\n }\n\n protected post<T, P extends IdempotencyOptions>(path: string, params: P): Promise<T> {\n const { body, idempotencyKey } = splitIdempotency(params);\n return this.t.request<T>({ method: \"POST\", path, body, idempotencyKey });\n }\n\n /** POST with no body, used by lifecycle verbs (cancel, resume, revoke ...). */\n protected postEmpty<T>(path: string, params: IdempotencyOptions = {}): Promise<T> {\n return this.t.request<T>({\n method: \"POST\",\n path,\n idempotencyKey: params.idempotencyKey,\n });\n }\n\n /** POST with a fixed body and no idempotency stripping (used by\n * endpoints whose body is fully specified by the caller's args\n * and not optional, e.g. `preview_update`). */\n protected postFixed<T>(\n path: string,\n body: Record<string, unknown>,\n params: IdempotencyOptions = {},\n ): Promise<T> {\n return this.t.request<T>({\n method: \"POST\",\n path,\n body,\n idempotencyKey: params.idempotencyKey,\n });\n }\n\n protected del<T>(path: string, params: IdempotencyOptions = {}): Promise<T> {\n return this.t.request<T>({\n method: \"DELETE\",\n path,\n idempotencyKey: params.idempotencyKey,\n });\n }\n}\n\n// ─── Resources ─────────────────────────────────────────────────────\n\nexport class Customers extends BaseResource {\n /** Create a tenant-scoped buyer record. */\n create<T = unknown>(params: CreateCustomerParams = {}): Promise<T> {\n return this.post<T, CreateCustomerParams>(\"/v1/customers\", params);\n }\n\n retrieve<T = unknown>(id: string): Promise<T> {\n return this.get<T>(`/v1/customers/${id}`);\n }\n\n update<T = unknown>(id: string, params: UpdateCustomerParams = {}): Promise<T> {\n return this.post<T, UpdateCustomerParams>(`/v1/customers/${id}`, params);\n }\n\n delete<T = unknown>(id: string, params: IdempotencyOptions = {}): Promise<T> {\n return this.del<T>(`/v1/customers/${id}`, params);\n }\n\n list<T = unknown>(params: BaseListParams = {}): Promise<ListResponseEnvelope<T>> {\n return this.get<ListResponseEnvelope<T>>(\"/v1/customers\", params);\n }\n\n /** Walk every page of `list()` and yield each customer. */\n iter<T = unknown>(options: { pageSize?: number } = {}): AsyncIterableIterator<T> {\n return paginate<T>((p) => this.get(\"/v1/customers\", p), { pageSize: options.pageSize });\n }\n\n /**\n * Attach or replace the customer's VAT number; triggers server-side\n * VIES validation. The response carries `vat_number_validated`\n * reflecting whether VIES confirmed the number.\n */\n setVatNumber<T = unknown>(id: string, params: SetCustomerVatNumberParams): Promise<T> {\n return this.post<T, SetCustomerVatNumberParams>(`/v1/customers/${id}/vat_number`, params);\n }\n\n /**\n * Hard-purge a customer's PII for GDPR erasure. Distinct from\n * `delete()` (soft delete): purge nulls email/name/country/VAT/\n * metadata, sets `purged_at`, and is irreversible.\n *\n * The server requires `confirmed: true` as a fat-finger guard; the\n * SDK defaults it to `true` so callers don't have to opt in twice.\n */\n purge<T = unknown>(id: string, params: PurgeCustomerParams = {}): Promise<T> {\n const { confirmed = true, idempotencyKey } = params;\n return this.postFixed<T>(`/v1/customers/${id}/purge`, { confirmed }, { idempotencyKey });\n }\n}\n\nexport class Products extends BaseResource {\n /** Create a catalog Product, then attach one or more Prices to it. */\n create<T = unknown>(params: CreateProductParams): Promise<T> {\n return this.post<T, CreateProductParams>(\"/v1/products\", params);\n }\n\n retrieve<T = unknown>(id: string): Promise<T> {\n return this.get<T>(`/v1/products/${id}`);\n }\n\n /** Patch mutable Product fields. */\n update<T = unknown>(id: string, params: UpdateProductParams): Promise<T> {\n return this.post<T, UpdateProductParams>(`/v1/products/${id}`, params);\n }\n\n /** Archive a Product. */\n delete<T = unknown>(id: string, params: IdempotencyOptions = {}): Promise<T> {\n return this.del<T>(`/v1/products/${id}`, params);\n }\n\n list<T = unknown>(params: BaseListParams = {}): Promise<ListResponseEnvelope<T>> {\n return this.get<ListResponseEnvelope<T>>(\"/v1/products\", params);\n }\n\n iter<T = unknown>(options: { pageSize?: number } = {}): AsyncIterableIterator<T> {\n return paginate<T>((p) => this.get(\"/v1/products\", p), { pageSize: options.pageSize });\n }\n}\n\nexport class Prices extends BaseResource {\n /** Create immutable billing terms for an existing Product. */\n create<T = unknown>(params: CreatePriceParams): Promise<T> {\n return this.post<T, CreatePriceParams>(\"/v1/prices\", params);\n }\n\n retrieve<T = unknown>(id: string): Promise<T> {\n return this.get<T>(`/v1/prices/${id}`);\n }\n\n list<T = unknown>(params: PricesListParams = {}): Promise<ListResponseEnvelope<T>> {\n return this.get<ListResponseEnvelope<T>>(\"/v1/prices\", params);\n }\n\n iter<T = unknown>(\n options: { pageSize?: number; product_id?: string } = {},\n ): AsyncIterableIterator<T> {\n const filter = options.product_id === undefined ? {} : { product_id: options.product_id };\n return paginate<T>((p) => this.get(\"/v1/prices\", { ...filter, ...p }), {\n pageSize: options.pageSize,\n });\n }\n}\n\nexport class CheckoutSessions extends BaseResource {\n create<T = unknown>(params: CreateCheckoutSessionParams): Promise<T> {\n return this.post<T, CreateCheckoutSessionParams>(\"/v1/checkout/sessions\", params);\n }\n\n retrieve<T = unknown>(id: string): Promise<T> {\n return this.get<T>(`/v1/checkout/sessions/${id}`);\n }\n}\n\n/**\n * Mandate-less one-shot payments (`/v1/checkout/one_shot`).\n *\n * A one-shot is the Stripe PaymentIntent shape mapped onto Mollie: a\n * single `sequenceType=oneoff` charge that provisions nothing: no\n * subscription, no mandate, no renewals. Drive terminal state via the\n * `one_shot_payment.succeeded` / `.failed` webhook events; refund one\n * with `client.refunds.create({ one_shot_payment_id })`.\n */\nexport class OneShotPayments extends BaseResource {\n /** Create a one-off charge; returns the object with a `redirect_url`. */\n create<T = unknown>(params: CreateOneShotPaymentParams): Promise<T> {\n return this.post<T, CreateOneShotPaymentParams>(\"/v1/checkout/one_shot\", params);\n }\n\n retrieve<T = unknown>(id: string): Promise<T> {\n return this.get<T>(`/v1/checkout/one_shot/${id}`);\n }\n}\n\nexport class Subscriptions extends BaseResource {\n retrieve<T = unknown>(id: string): Promise<T> {\n return this.get<T>(`/v1/subscriptions/${id}`);\n }\n\n list<T = unknown>(params: BaseListParams = {}): Promise<ListResponseEnvelope<T>> {\n return this.get<ListResponseEnvelope<T>>(\"/v1/subscriptions\", params);\n }\n\n iter<T = unknown>(options: { pageSize?: number } = {}): AsyncIterableIterator<T> {\n return paginate<T>((p) => this.get(\"/v1/subscriptions\", p), { pageSize: options.pageSize });\n }\n\n cancel<T = unknown>(id: string, params: IdempotencyOptions = {}): Promise<T> {\n return this.postEmpty<T>(`/v1/subscriptions/${id}/cancel`, params);\n }\n\n pause<T = unknown>(id: string, params: IdempotencyOptions = {}): Promise<T> {\n return this.postEmpty<T>(`/v1/subscriptions/${id}/pause`, params);\n }\n\n resume<T = unknown>(id: string, params: IdempotencyOptions = {}): Promise<T> {\n return this.postEmpty<T>(`/v1/subscriptions/${id}/resume`, params);\n }\n\n /**\n * Reactivate a canceled-but-still-in-period subscription.\n *\n * Distinct from `resume()` (paused → active): `reactivate()` flips\n * `canceled` back to `active` for the remainder of the current\n * period, so the customer keeps service without a new checkout.\n * Returns `409` if the period has already elapsed.\n */\n reactivate<T = unknown>(id: string, params: IdempotencyOptions = {}): Promise<T> {\n return this.postEmpty<T>(`/v1/subscriptions/${id}/reactivate`, params);\n }\n\n previewUpdate<T = unknown>(id: string, params: { target_price_id: string }): Promise<T> {\n return this.postFixed<T>(`/v1/subscriptions/${id}/preview_update`, {\n target_price_id: params.target_price_id,\n });\n }\n\n update<T = unknown>(\n id: string,\n params: { target_price_id: string } & IdempotencyOptions,\n ): Promise<T> {\n return this.postFixed<T>(\n `/v1/subscriptions/${id}/update`,\n { target_price_id: params.target_price_id },\n { idempotencyKey: params.idempotencyKey },\n );\n }\n\n reauthorizePaymentMethod<T = unknown>(\n id: string,\n params: { return_url: string } & IdempotencyOptions,\n ): Promise<T> {\n return this.postFixed<T>(\n `/v1/subscriptions/${id}/reauthorize_payment_method`,\n { return_url: params.return_url },\n { idempotencyKey: params.idempotencyKey },\n );\n }\n}\n\nexport class Refunds extends BaseResource {\n create<T = unknown>(params: CreateRefundParams): Promise<T> {\n return this.post<T, CreateRefundParams>(\"/v1/refunds\", params);\n }\n\n retrieve<T = unknown>(id: string): Promise<T> {\n return this.get<T>(`/v1/refunds/${id}`);\n }\n\n list<T = unknown>(params: BaseListParams = {}): Promise<ListResponseEnvelope<T>> {\n return this.get<ListResponseEnvelope<T>>(\"/v1/refunds\", params);\n }\n\n iter<T = unknown>(options: { pageSize?: number } = {}): AsyncIterableIterator<T> {\n return paginate<T>((p) => this.get(\"/v1/refunds\", p), { pageSize: options.pageSize });\n }\n}\n\n/**\n * Chargebacks / disputes (`/v1/disputes`).\n *\n * Read-only. Disputes are provider-originated (opened by the cardholder's\n * bank) and surfaced via the `dispute.created` / `dispute.closed` webhook\n * events. There is no create/update. A dispute's `status` is `open` or `won`\n * (chargeback reversed); Mollie exposes no \"lost\" signal, so an upheld\n * chargeback stays `open` (treat any non-`won` dispute as unresolved).\n */\nexport class Disputes extends BaseResource {\n retrieve<T = unknown>(id: string): Promise<T> {\n return this.get<T>(`/v1/disputes/${id}`);\n }\n\n list<T = unknown>(params: BaseListParams = {}): Promise<ListResponseEnvelope<T>> {\n return this.get<ListResponseEnvelope<T>>(\"/v1/disputes\", params);\n }\n\n iter<T = unknown>(options: { pageSize?: number } = {}): AsyncIterableIterator<T> {\n return paginate<T>((p) => this.get(\"/v1/disputes\", p), { pageSize: options.pageSize });\n }\n}\n\nexport class WebhookEndpoints extends BaseResource {\n create<T = unknown>(params: CreateWebhookEndpointParams): Promise<T> {\n return this.post<T, CreateWebhookEndpointParams>(\"/v1/webhook_endpoints\", params);\n }\n\n retrieve<T = unknown>(id: string): Promise<T> {\n return this.get<T>(`/v1/webhook_endpoints/${id}`);\n }\n\n update<T = unknown>(id: string, params: UpdateWebhookEndpointParams): Promise<T> {\n return this.post<T, UpdateWebhookEndpointParams>(`/v1/webhook_endpoints/${id}`, params);\n }\n\n delete<T = unknown>(id: string, params: IdempotencyOptions = {}): Promise<T> {\n return this.del<T>(`/v1/webhook_endpoints/${id}`, params);\n }\n\n /** Rotate the signing secret. The new `whsec_...` is returned once. */\n rotateSecret<T = unknown>(id: string, params: IdempotencyOptions = {}): Promise<T> {\n return this.postEmpty<T>(`/v1/webhook_endpoints/${id}/rotate_secret`, params);\n }\n\n list<T = unknown>(params: BaseListParams = {}): Promise<ListResponseEnvelope<T>> {\n return this.get<ListResponseEnvelope<T>>(\"/v1/webhook_endpoints\", params);\n }\n\n iter<T = unknown>(options: { pageSize?: number } = {}): AsyncIterableIterator<T> {\n return paginate<T>((p) => this.get(\"/v1/webhook_endpoints\", p), {\n pageSize: options.pageSize,\n });\n }\n\n /**\n * List per-attempt delivery records for one endpoint.\n *\n * Useful when a tenant's receiver is failing. Surfaces the status\n * code, response body excerpt, error, and next-attempt timestamp\n * for each event × endpoint pair.\n */\n listDeliveries<T = unknown>(\n endpointId: string,\n params: BaseListParams = {},\n ): Promise<ListResponseEnvelope<T>> {\n return this.get<ListResponseEnvelope<T>>(\n `/v1/webhook_endpoints/${endpointId}/deliveries`,\n params,\n );\n }\n\n /** Walk every page of `listDeliveries()` for one endpoint. */\n iterDeliveries<T = unknown>(\n endpointId: string,\n options: { pageSize?: number } = {},\n ): AsyncIterableIterator<T> {\n return paginate<T>(\n (p) => this.get(`/v1/webhook_endpoints/${endpointId}/deliveries`, p),\n { pageSize: options.pageSize },\n );\n }\n\n /** Fetch one delivery row for inspection before deciding to redeliver. */\n getDelivery<T = unknown>(endpointId: string, deliveryId: string): Promise<T> {\n return this.get<T>(`/v1/webhook_endpoints/${endpointId}/deliveries/${deliveryId}`);\n }\n\n /**\n * Re-enqueue a delivery row for the dispatcher.\n *\n * Idempotent: a row already in `delivered` returns unchanged. A\n * `pending` / `failed` row flips to `pending` with\n * `next_attempt_at = now()`; `attempt_count` is preserved.\n */\n redeliver<T = unknown>(\n endpointId: string,\n deliveryId: string,\n params: IdempotencyOptions = {},\n ): Promise<T> {\n return this.postEmpty<T>(\n `/v1/webhook_endpoints/${endpointId}/deliveries/${deliveryId}/redeliver`,\n params,\n );\n }\n}\n\nexport class Events extends BaseResource {\n retrieve<T = unknown>(id: string): Promise<T> {\n return this.get<T>(`/v1/events/${id}`);\n }\n\n list<T = unknown>(params: EventsListParams = {}): Promise<ListResponseEnvelope<T>> {\n return this.get<ListResponseEnvelope<T>>(\"/v1/events\", params);\n }\n\n /** Walk every page of `list()`. Pass `type` to filter at the server. */\n iter<T = unknown>(\n options: { pageSize?: number; type?: string } = {},\n ): AsyncIterableIterator<T> {\n return paginate<T>((p) => this.get(\"/v1/events\", p), {\n pageSize: options.pageSize,\n filters: { type: options.type },\n });\n }\n}\n\n/**\n * Read + mutate tenant-level configuration.\n *\n * Exposes the Mollie capability cache, the portal-branding row, and\n * the encrypted Mollie API key. None of these are per-resource;\n * they're tenant-wide knobs.\n */\nexport class Tenant extends BaseResource {\n /** Cached Mollie profile shape (enabled methods, country, currency). */\n capabilities<T = unknown>(): Promise<T> {\n return this.get<T>(\"/v1/tenant/capabilities\");\n }\n\n /** Current portal branding row (business name, theme, capability flags). */\n portalBranding<T = unknown>(): Promise<T> {\n return this.get<T>(\"/v1/tenant/portal_branding\");\n }\n\n /**\n * Partial-update the portal branding row.\n *\n * Only fields you set are sent. Pass `undefined` to leave a field\n * untouched; sending an empty string explicitly clears it.\n */\n setPortalBranding<T = unknown>(params: SetPortalBrandingParams = {}): Promise<T> {\n return this.post<T, SetPortalBrandingParams>(\"/v1/tenant/portal_branding\", params);\n }\n\n /**\n * Rotate the encrypted provider credential for this tenant.\n *\n * The new `api_key` is encrypted server-side; nothing is logged.\n * `mode` defaults to the calling key's mode; prefix-mismatch\n * (`test_...` under live, `live_...` under test) is rejected at the\n * API boundary.\n */\n rotateProviderCredential<T = unknown>(params: RotateProviderCredentialParams): Promise<T> {\n return this.post<T, RotateProviderCredentialParams>(\n \"/v1/tenant/provider_credential\",\n params,\n );\n }\n}\n\nexport class Coupons extends BaseResource {\n create<T = unknown>(params: CreateCouponParams): Promise<T> {\n return this.post<T, CreateCouponParams>(\"/v1/coupons\", params);\n }\n\n retrieve<T = unknown>(id: string): Promise<T> {\n return this.get<T>(`/v1/coupons/${id}`);\n }\n\n update<T = unknown>(id: string, params: UpdateCouponParams): Promise<T> {\n return this.post<T, UpdateCouponParams>(`/v1/coupons/${id}`, params);\n }\n\n delete<T = unknown>(id: string, params: IdempotencyOptions = {}): Promise<T> {\n return this.del<T>(`/v1/coupons/${id}`, params);\n }\n\n /**\n * Server-side dry-run of a coupon redemption.\n *\n * Returns the discount math without atomically claiming the coupon,\n * which is useful for \"preview before checkout\" UX.\n */\n validate<T = unknown>(params: ValidateCouponParams): Promise<T> {\n // Omit the optional fields rather than sending explicit nulls, so the\n // request body matches what a caller who only has a code would hand\n // written by hand, and so `extra=\"forbid\"` schemas stay happy.\n const body: Record<string, unknown> = { code: params.code };\n if (params.price_id !== undefined) body[\"price_id\"] = params.price_id;\n if (params.amount_cents !== undefined) body[\"amount_cents\"] = params.amount_cents;\n return this.postFixed<T>(\"/v1/coupons/validate\", body);\n }\n\n list<T = unknown>(params: BaseListParams = {}): Promise<ListResponseEnvelope<T>> {\n return this.get<ListResponseEnvelope<T>>(\"/v1/coupons\", params);\n }\n\n iter<T = unknown>(options: { pageSize?: number } = {}): AsyncIterableIterator<T> {\n return paginate<T>((p) => this.get(\"/v1/coupons\", p), { pageSize: options.pageSize });\n }\n}\n\nexport class TaxRates extends BaseResource {\n create<T = unknown>(params: CreateTaxRateParams): Promise<T> {\n return this.post<T, CreateTaxRateParams>(\"/v1/tax_rates\", params);\n }\n\n retrieve<T = unknown>(id: string): Promise<T> {\n return this.get<T>(`/v1/tax_rates/${id}`);\n }\n\n update<T = unknown>(id: string, params: UpdateTaxRateParams): Promise<T> {\n return this.post<T, UpdateTaxRateParams>(`/v1/tax_rates/${id}`, params);\n }\n\n delete<T = unknown>(id: string, params: IdempotencyOptions = {}): Promise<T> {\n return this.del<T>(`/v1/tax_rates/${id}`, params);\n }\n\n list<T = unknown>(params: BaseListParams = {}): Promise<ListResponseEnvelope<T>> {\n return this.get<ListResponseEnvelope<T>>(\"/v1/tax_rates\", params);\n }\n\n iter<T = unknown>(options: { pageSize?: number } = {}): AsyncIterableIterator<T> {\n return paginate<T>((p) => this.get(\"/v1/tax_rates\", p), { pageSize: options.pageSize });\n }\n}\n\n/**\n * Read-only access to generated invoices.\n *\n * Invoices are produced by the billing pipeline; tenants don't create\n * them directly. PDF retrieval returns a 302 redirect to the storage\n * adapter's signed URL. Follow it transparently with the runtime's\n * fetch settings.\n */\nexport class Invoices extends BaseResource {\n retrieve<T = unknown>(id: string): Promise<T> {\n return this.get<T>(`/v1/invoices/${id}`);\n }\n\n list<T = unknown>(params: BaseListParams = {}): Promise<ListResponseEnvelope<T>> {\n return this.get<ListResponseEnvelope<T>>(\"/v1/invoices\", params);\n }\n\n iter<T = unknown>(options: { pageSize?: number } = {}): AsyncIterableIterator<T> {\n return paginate<T>((p) => this.get(\"/v1/invoices\", p), { pageSize: options.pageSize });\n }\n}\n\n/**\n * Read-only access to the per-tenant audit log.\n *\n * Supports server-side filters: `action`, `resource_type`, `actor_id`.\n * The filters are forwarded through to `iter()` so an audit walk can\n * scope to a single actor or action without client-side filtering.\n */\nexport class AuditLogs extends BaseResource {\n retrieve<T = unknown>(id: string): Promise<T> {\n return this.get<T>(`/v1/audit_logs/${id}`);\n }\n\n list<T = unknown>(params: AuditLogsListParams = {}): Promise<ListResponseEnvelope<T>> {\n return this.get<ListResponseEnvelope<T>>(\"/v1/audit_logs\", params);\n }\n\n iter<T = unknown>(\n options: { pageSize?: number; action?: string; resource_type?: string; actor_id?: string } = {},\n ): AsyncIterableIterator<T> {\n return paginate<T>((p) => this.get(\"/v1/audit_logs\", p), {\n pageSize: options.pageSize,\n filters: {\n action: options.action,\n resource_type: options.resource_type,\n actor_id: options.actor_id,\n },\n });\n }\n}\n\n/**\n * Read-only access to the payment ledger.\n *\n * Payments are written by the billing pipeline (checkout, renewal,\n * reauthorize). Inspect attempts and their Mollie-side metadata here;\n * refunds and disputes are separate flows.\n */\nexport class Payments extends BaseResource {\n retrieve<T = unknown>(id: string): Promise<T> {\n return this.get<T>(`/v1/payments/${id}`);\n }\n\n list<T = unknown>(params: BaseListParams = {}): Promise<ListResponseEnvelope<T>> {\n return this.get<ListResponseEnvelope<T>>(\"/v1/payments\", params);\n }\n\n iter<T = unknown>(options: { pageSize?: number } = {}): AsyncIterableIterator<T> {\n return paginate<T>((p) => this.get(\"/v1/payments\", p), { pageSize: options.pageSize });\n }\n}\n\n/**\n * Mint and revoke customer-facing billing-portal sessions.\n *\n * Each session token is scoped to a single subscription with a\n * sliding 30-minute idle window and a 2-hour hard cap. The raw token\n * is returned **once** on mint; the response also includes the URL\n * the tenant embeds in their app.\n */\nexport class BillingPortalSessions extends BaseResource {\n create<T = unknown>(params: CreateBillingPortalSessionParams): Promise<T> {\n return this.postFixed<T>(\n \"/v1/billing_portal/sessions\",\n {\n subscription_id: params.subscription_id,\n return_url: params.return_url,\n },\n { idempotencyKey: params.idempotencyKey },\n );\n }\n\n /** Kill an in-the-wild portal session. Idempotent. */\n revoke<T = unknown>(id: string, params: IdempotencyOptions = {}): Promise<T> {\n return this.postEmpty<T>(`/v1/billing_portal/sessions/${id}/revoke`, params);\n }\n}\n","/**\n * Typed exception hierarchy mirroring the BillKit API error envelope.\n *\n * The API returns errors in the Stripe-shape:\n *\n * { \"error\": { \"type\": \"...\", \"code\": \"...\", \"message\": \"...\", \"param\": \"...\" } }\n *\n * Each `type` maps to one error class so callers can `catch` on the\n * subclass they care about rather than branching on HTTP status codes.\n */\n\nexport interface ErrorEnvelope {\n type?: string;\n code?: string;\n message?: string;\n param?: string;\n}\n\nexport interface BillKitErrorOptions {\n type?: string | undefined;\n code?: string | undefined;\n param?: string | undefined;\n statusCode?: number | undefined;\n requestId?: string | undefined;\n rawBody?: unknown;\n}\n\n// TS treats `name = \"Foo\"` as a literal-type property, which then conflicts\n// when subclasses override it. We widen to `string` everywhere so the\n// hierarchy can re-set ``name`` cleanly.\nexport class BillKitError extends Error {\n override name: string = \"BillKitError\";\n readonly type: string | undefined;\n readonly code: string | undefined;\n readonly param: string | undefined;\n readonly statusCode: number | undefined;\n readonly requestId: string | undefined;\n readonly rawBody: unknown;\n\n constructor(message: string, options: BillKitErrorOptions = {}) {\n super(message);\n this.type = options.type;\n this.code = options.code;\n this.param = options.param;\n this.statusCode = options.statusCode;\n this.requestId = options.requestId;\n this.rawBody = options.rawBody;\n // Restore the prototype chain, required when targeting ES5 transpilers\n // (some bundlers still emit them) so `instanceof BillKitError` works.\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class APIConnectionError extends BillKitError {\n override name = \"APIConnectionError\";\n}\n\nexport class APIError extends BillKitError {\n override name = \"APIError\";\n}\n\nexport class ServerError extends APIError {\n override name = \"ServerError\";\n}\n\nexport class AuthenticationError extends BillKitError {\n override name = \"AuthenticationError\";\n}\n\nexport class PermissionError extends BillKitError {\n override name = \"PermissionError\";\n}\n\nexport class ResourceMissingError extends BillKitError {\n override name = \"ResourceMissingError\";\n}\n\nexport class InvalidRequestError extends BillKitError {\n override name = \"InvalidRequestError\";\n}\n\nexport class ConflictError extends BillKitError {\n override name = \"ConflictError\";\n}\n\nexport class RateLimitError extends BillKitError {\n override name = \"RateLimitError\";\n readonly retryAfter: number | undefined;\n\n constructor(\n message: string,\n options: BillKitErrorOptions & { retryAfter?: number | undefined } = {},\n ) {\n super(message, options);\n this.retryAfter = options.retryAfter;\n }\n}\n\nconst TYPE_TO_CLASS: Record<string, new (msg: string, opts: BillKitErrorOptions) => BillKitError> =\n {\n api_connection_error: APIConnectionError,\n // ``api_error`` is the Stripe-convention type for 5xx, so surface it as\n // ServerError (a subclass of APIError) so `catch (e instanceof\n // ServerError)` works without false negatives.\n api_error: ServerError,\n authentication_error: AuthenticationError,\n permission_error: PermissionError,\n invalid_request_error: InvalidRequestError,\n idempotency_error: ConflictError,\n conflict: ConflictError,\n rate_limit_error: RateLimitError,\n };\n\nfunction fallbackType(status: number): string {\n if (status === 401) return \"authentication_error\";\n if (status === 403) return \"permission_error\";\n if (status === 404) return \"invalid_request_error\";\n if (status === 409) return \"conflict\";\n if (status === 429) return \"rate_limit_error\";\n if (status >= 500) return \"api_error\";\n return \"invalid_request_error\";\n}\n\nfunction fallbackClass(\n status: number,\n): new (msg: string, opts: BillKitErrorOptions) => BillKitError {\n if (status === 401) return AuthenticationError;\n if (status === 403) return PermissionError;\n if (status === 404) return ResourceMissingError;\n if (status === 409) return ConflictError;\n if (status === 429) return RateLimitError;\n if (status >= 500) return ServerError;\n return InvalidRequestError;\n}\n\nexport function errorFromResponse(args: {\n status: number;\n body: unknown;\n requestId?: string | undefined;\n retryAfter?: number | undefined;\n}): BillKitError {\n const { status, body, requestId, retryAfter } = args;\n const envelope: ErrorEnvelope =\n typeof body === \"object\" && body !== null && \"error\" in body\n ? ((body as { error?: ErrorEnvelope }).error ?? {})\n : {};\n\n const type = envelope.type ?? fallbackType(status);\n const message =\n envelope.message ?? `BillKit API returned HTTP ${status} with no error body.`;\n\n let cls = TYPE_TO_CLASS[type] ?? fallbackClass(status);\n if (status === 404 && cls === InvalidRequestError) cls = ResourceMissingError;\n if (status === 409 && cls === InvalidRequestError) cls = ConflictError;\n\n const options: BillKitErrorOptions & { retryAfter?: number | undefined } = {\n type,\n code: envelope.code,\n param: envelope.param,\n statusCode: status,\n requestId,\n rawBody: typeof body === \"object\" && body !== null ? body : undefined,\n };\n if (cls === RateLimitError) {\n options.retryAfter = retryAfter;\n }\n return new cls(message, options);\n}\n","/**\n * Opt-in logging for the BillKit SDK.\n *\n * A library has no business deciding where its host application's logs\n * go, so this SDK ships no logger, no transport, and no destination. It\n * accepts one from you and writes to a no-op until you do:\n *\n * ```ts\n * const client = new BillKit({ logger: console });\n * ```\n *\n * `console` satisfies {@link BillKitLogger} structurally, so that line\n * works with no adapter. So does a pino/winston/bunyan child logger:\n * their `debug(msg, ctx)` / `warn(msg, ctx)` signatures line up. If yours\n * takes its arguments the other way round, wrap it:\n *\n * ```ts\n * const logger = {\n * debug: (m, c) => myLogger.debug(c, m),\n * warn: (m, c) => myLogger.warn(c, m),\n * };\n * ```\n *\n * ## What gets logged\n *\n * - **debug**: one call per HTTP attempt and one per response, with\n * `method`, `url`, `attempt`, `status`, `durationMs`, and `requestId`\n * (quote that id to BillKit support).\n * - **warn**: one call per retry, naming the reason and the delay before\n * the next attempt. A retry is a real anomaly worth surfacing without\n * being an error.\n *\n * ## What is deliberately never logged\n *\n * - The `Authorization` header or the API key, in any form.\n * - Request and response **bodies**. They carry customer PII (emails,\n * names, addresses) and billing detail; a payments SDK that quietly\n * copies those into its user's log sink has manufactured a compliance\n * problem on their behalf.\n * - The **query string**. List filters routinely carry values like\n * `email=ada@example.com`, so only the path is logged.\n * - The **final failure**. Every exhausted call throws a typed\n * `BillKitError` carrying the status, request id and retry-after;\n * logging it here as well would produce a duplicate the caller never\n * asked for and cannot suppress from their own sink.\n */\n\n/** Structured context attached to a log line. Never contains secrets. */\nexport type LogContext = Record<string, unknown>;\n\n/**\n * The minimum a logger must do for the SDK to use it. Deliberately two\n * methods: the SDK has exactly two things to say, and a narrow interface\n * is one almost every logger already satisfies without an adapter.\n */\nexport interface BillKitLogger {\n debug(message: string, context?: LogContext): void;\n warn(message: string, context?: LogContext): void;\n}\n\n/**\n * The default. Discards everything, so the SDK is silent until a logger\n * is supplied, and costs nothing when it isn't.\n */\nexport const NOOP_LOGGER: BillKitLogger = {\n debug(): void {\n /* intentionally empty */\n },\n warn(): void {\n /* intentionally empty */\n },\n};\n","/**\n * Retry policy for transient failures.\n *\n * Retries 5xx + network errors with jittered exponential backoff.\n * 4xx (including 409 Idempotency-Key conflicts) are caller-fault and\n * never retried. The SDK auto-generates an `Idempotency-Key` for every\n * mutating call so retrying a 5xx never double-charges.\n */\n\nexport interface RetryPolicy {\n readonly maxAttempts: number;\n readonly initialBackoffMs: number;\n readonly backoffMultiplier: number;\n readonly maxBackoffMs: number;\n readonly maxRetryAfterMs?: number;\n readonly jitter: number;\n}\n\nexport const DEFAULT_RETRY_POLICY: RetryPolicy = {\n maxAttempts: 4,\n initialBackoffMs: 500,\n backoffMultiplier: 2.0,\n maxBackoffMs: 8000,\n maxRetryAfterMs: 30_000,\n jitter: 0.25,\n};\n\n/**\n * Backoff before attempt `attempt` (1-indexed: attempt 2 is the first\n * retry). Caller never asks for attempt=1.\n */\nexport function backoffForMs(attempt: number, policy: RetryPolicy): number {\n const base = policy.initialBackoffMs * policy.backoffMultiplier ** (attempt - 2);\n const capped = Math.min(base, policy.maxBackoffMs);\n const jitterRange = capped * policy.jitter;\n const jittered = capped + (Math.random() * 2 - 1) * jitterRange;\n return Math.max(0, jittered);\n}\n\nexport function shouldRetry(\n status: number | null,\n attempt: number,\n policy: RetryPolicy,\n retryAfterMs?: number,\n): boolean {\n if (attempt >= policy.maxAttempts) return false;\n if (status === null) return true; // network error\n if (status === 429) {\n // 429 is retried only when the server supplies a short, parseable\n // Retry-After value; otherwise we surface the exception so the\n // caller can decide. ``maxRetryAfterMs`` may be left ``undefined``\n // to allow any Retry-After value within budget.\n if (retryAfterMs === undefined || retryAfterMs < 0) return false;\n return policy.maxRetryAfterMs === undefined || retryAfterMs <= policy.maxRetryAfterMs;\n }\n return status >= 500;\n}\n\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","export const VERSION = \"0.1.0\";\n","/**\n * Fetch-backed transport with retry + error mapping.\n *\n * Uses the runtime's native `fetch` (Node 20+, Bun, Deno, Cloudflare\n * Workers, browsers). The transport is the only place that touches HTTP;\n * everything else in the SDK speaks to a `Transport` interface so a\n * caller can inject a mock or replay layer for testing.\n */\n\nimport { APIConnectionError, errorFromResponse, type BillKitError } from \"./errors.js\";\nimport { NOOP_LOGGER, type BillKitLogger } from \"./logging.js\";\nimport {\n DEFAULT_RETRY_POLICY,\n type RetryPolicy,\n backoffForMs,\n shouldRetry,\n sleep,\n} from \"./retry.js\";\nimport { VERSION } from \"./version.js\";\n\nexport const DEFAULT_BASE_URL = \"https://api.billkit.eu\";\nexport const DEFAULT_TIMEOUT_MS = 30_000;\n\nexport type QueryValue = string | number | boolean | null | undefined;\n\nexport interface RequestOptions {\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path: string;\n // Loosened from ``Record<string, QueryValue>`` so resource methods\n // can pass a structurally-typed ``ListParams``-style object without\n // a cast, since TS demands an index signature otherwise.\n query?: { readonly [key: string]: QueryValue };\n body?: Record<string, unknown> | undefined;\n idempotencyKey?: string | undefined;\n extraHeaders?: Record<string, string>;\n}\n\nexport interface TransportConfig {\n apiKey: string;\n baseUrl?: string;\n timeoutMs?: number;\n retryPolicy?: RetryPolicy;\n fetch?: typeof fetch;\n /**\n * Where to send the SDK's request/retry lifecycle. Omitted (the\n * default) means a no-op: the SDK stays silent and never picks a\n * destination for you. `console` works as-is; see\n * {@link BillKitLogger}. Secrets, bodies and query strings are never\n * passed to it.\n */\n logger?: BillKitLogger;\n}\n\nfunction userAgent(): string {\n return `billkit-node/${VERSION}`;\n}\n\nfunction autoIdempotencyKey(method: string, supplied?: string): string | undefined {\n if (method === \"GET\") return undefined;\n if (supplied !== undefined) return supplied;\n const uuid = globalThis.crypto?.randomUUID?.();\n if (uuid === undefined) {\n // Deliberately fail loudly rather than fall back to\n // `Date.now()-Math.random()`. This key is what makes a retried\n // mutating call safe: two processes that generate the *same* key send\n // different requests the server treats as replays of each other, so it\n // returns the first call's response for the second, silently wrong on\n // a charge. `Math.random()` is not collision-resistant and is seeded\n // per-process, so a fleet starting together is exactly the case where\n // it collides. Every runtime this SDK supports (Node 20+, Bun, Deno,\n // Workers, modern browsers) has `crypto.randomUUID`.\n throw new Error(\n \"BillKit: crypto.randomUUID() is unavailable, so a safe Idempotency-Key \" +\n \"cannot be generated. Use Node 20+, Bun, Deno, or Cloudflare Workers, \" +\n \"or pass your own `idempotencyKey` on this call.\",\n );\n }\n return `sdk-${uuid}`;\n}\n\n/**\n * The URL with the **query string stripped**, for logging only.\n *\n * Never log the value {@link buildUrl} returns: list filters routinely\n * carry `?email=ada@example.com`, and copying customer PII into the\n * caller's log sink is exactly what this SDK must not do. Keeping the\n * two builders separate makes that a visible choice rather than an\n * accident waiting for someone to \"simplify\" it.\n */\nfunction logSafeUrl(baseUrl: string, path: string): string {\n const normalised = path.startsWith(\"/\") ? path : `/${path}`;\n return baseUrl.replace(/\\/$/, \"\") + normalised;\n}\n\nfunction buildUrl(baseUrl: string, path: string, query: RequestOptions[\"query\"]): string {\n const normalised = path.startsWith(\"/\") ? path : `/${path}`;\n const url = new URL(baseUrl.replace(/\\/$/, \"\") + normalised);\n if (query) {\n for (const [k, v] of Object.entries(query)) {\n if (v !== null && v !== undefined) {\n url.searchParams.set(k, String(v));\n }\n }\n }\n return url.toString();\n}\n\nfunction buildHeaders(\n apiKey: string,\n hasBody: boolean,\n idempotencyKey: string | undefined,\n extra: Record<string, string> | undefined,\n): Headers {\n const headers = new Headers({\n Authorization: `Bearer ${apiKey}`,\n \"User-Agent\": userAgent(),\n Accept: \"application/json\",\n });\n if (hasBody) headers.set(\"Content-Type\", \"application/json\");\n if (idempotencyKey) headers.set(\"Idempotency-Key\", idempotencyKey);\n if (extra) {\n for (const [k, v] of Object.entries(extra)) {\n headers.set(k, v);\n }\n }\n return headers;\n}\n\nasync function parseJson(response: Response): Promise<unknown> {\n const text = await response.text();\n if (!text) return null;\n try {\n return JSON.parse(text);\n } catch {\n return null;\n }\n}\n\nfunction parseRetryAfterMs(header: string | null): number | undefined {\n if (!header) return undefined;\n const n = Number.parseFloat(header);\n if (Number.isFinite(n) && n >= 0) return n * 1000;\n\n const retryAt = Date.parse(header);\n if (Number.isNaN(retryAt)) return undefined;\n return Math.max(0, retryAt - Date.now());\n}\n\nfunction retryDelayMs(\n status: number | null,\n attempt: number,\n policy: RetryPolicy,\n retryAfterMs?: number,\n): number {\n if (status === 429 && retryAfterMs !== undefined) return retryAfterMs;\n return backoffForMs(attempt + 1, policy);\n}\n\n/**\n * Map a thrown fetch/read error to an {@link APIConnectionError}.\n *\n * ``AbortSignal.timeout`` aborts with a ``TimeoutError`` (some runtimes\n * surface ``AbortError``); we translate that into an explicit, greppable\n * timeout message instead of the runtime's terse default.\n */\nfunction connectionError(err: unknown, timeoutMs: number): APIConnectionError {\n const e = err as { name?: string; message?: string } | undefined;\n if (e?.name === \"TimeoutError\" || e?.name === \"AbortError\") {\n return new APIConnectionError(`BillKit request timed out after ${timeoutMs}ms.`);\n }\n return new APIConnectionError(e?.message ?? \"Network request failed.\");\n}\n\nexport class Transport {\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly timeoutMs: number;\n private readonly retryPolicy: RetryPolicy;\n private readonly fetchFn: typeof fetch;\n private readonly logger: BillKitLogger;\n\n constructor(config: TransportConfig) {\n if (!config.apiKey) {\n throw new Error(\"BillKit: an API key is required (config.apiKey or BILLKIT_API_KEY env).\");\n }\n this.apiKey = config.apiKey;\n this.baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;\n this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n this.retryPolicy = config.retryPolicy ?? DEFAULT_RETRY_POLICY;\n this.logger = config.logger ?? NOOP_LOGGER;\n const fetchFn = config.fetch ?? globalThis.fetch;\n if (!fetchFn) {\n throw new Error(\n \"BillKit: no global fetch implementation found. Use Node 20+, Bun, Deno, \" +\n \"Cloudflare Workers, or pass { fetch } in the client options.\",\n );\n }\n this.fetchFn = fetchFn.bind(globalThis);\n }\n\n async request<T = unknown>(options: RequestOptions): Promise<T> {\n const idempotencyKey = autoIdempotencyKey(options.method, options.idempotencyKey);\n const url = buildUrl(this.baseUrl, options.path, options.query);\n const headers = buildHeaders(\n this.apiKey,\n options.body !== undefined,\n idempotencyKey,\n options.extraHeaders,\n );\n const body = options.body !== undefined ? JSON.stringify(options.body) : undefined;\n // Query-free; see `logSafeUrl`. Never swap this for `url`.\n const loggedUrl = logSafeUrl(this.baseUrl, options.path);\n\n let lastError: BillKitError | null = null;\n for (let attempt = 1; attempt <= this.retryPolicy.maxAttempts; attempt++) {\n this.logger.debug(\"BillKit request\", {\n method: options.method,\n url: loggedUrl,\n attempt,\n maxAttempts: this.retryPolicy.maxAttempts,\n });\n const startedAt = Date.now();\n let response: Response;\n let parsedBody: unknown;\n try {\n // ``body`` is only spread when present so a GET request goes\n // out without a body field. Some hosts (Cloudflare Workers'\n // outgoing fetch) refuse ``body: null`` on GET; omitting it\n // is the portable shape.\n //\n // ``AbortSignal.timeout`` stays armed through the *body read*\n // below, not just until the headers arrive, so a server that\n // streams headers and then stalls the body is still bounded by\n // ``timeoutMs`` instead of hanging forever. A fresh signal is\n // created per attempt because a timed-out signal can't be reused.\n const init: RequestInit = {\n method: options.method,\n headers,\n signal: AbortSignal.timeout(this.timeoutMs),\n };\n if (body !== undefined) init.body = body;\n response = await this.fetchFn(url, init);\n parsedBody = await parseJson(response);\n } catch (err) {\n lastError = connectionError(err, this.timeoutMs);\n if (!shouldRetry(null, attempt, this.retryPolicy)) throw lastError;\n const delayMs = retryDelayMs(null, attempt, this.retryPolicy);\n this.logger.warn(\"BillKit retrying\", {\n method: options.method,\n url: loggedUrl,\n reason: (err as { name?: string } | undefined)?.name ?? \"network error\",\n attempt,\n delayMs,\n });\n await sleep(delayMs);\n continue;\n }\n\n const requestId =\n response.headers.get(\"x-request-id\") ?? response.headers.get(\"request-id\") ?? undefined;\n this.logger.debug(\"BillKit response\", {\n method: options.method,\n url: loggedUrl,\n status: response.status,\n durationMs: Date.now() - startedAt,\n requestId: requestId ?? null,\n });\n\n if (response.ok) {\n return (parsedBody ?? undefined) as T;\n }\n\n const retryAfterMs = parseRetryAfterMs(response.headers.get(\"retry-after\"));\n const error = errorFromResponse({\n status: response.status,\n body: parsedBody,\n requestId,\n retryAfter: retryAfterMs === undefined ? undefined : retryAfterMs / 1000,\n });\n\n if (!shouldRetry(response.status, attempt, this.retryPolicy, retryAfterMs)) {\n throw error;\n }\n lastError = error;\n const delayMs = retryDelayMs(response.status, attempt, this.retryPolicy, retryAfterMs);\n this.logger.warn(\"BillKit retrying\", {\n method: options.method,\n url: loggedUrl,\n reason: `HTTP ${response.status}`,\n attempt,\n delayMs,\n });\n await sleep(delayMs);\n }\n\n // Loop exhausted; surface the last seen error.\n if (lastError) throw lastError;\n throw new APIConnectionError(\"Retry budget exhausted with no recorded error.\");\n }\n}\n","/**\n * Top-level BillKit client.\n *\n * Wraps a single Transport and exposes every resource family as a\n * field. The Transport is configured once at construction; every\n * resource reuses it, so a runtime-injected `fetch` impl (Cloudflare\n * Workers, MSW for tests, a debug proxy) flows through automatically.\n */\n\nimport {\n AuditLogs,\n BillingPortalSessions,\n CheckoutSessions,\n Coupons,\n Customers,\n Disputes,\n Events,\n Invoices,\n OneShotPayments,\n Payments,\n Prices,\n Products,\n Refunds,\n Subscriptions,\n TaxRates,\n Tenant,\n WebhookEndpoints,\n} from \"./resources.js\";\nimport { Transport, type TransportConfig } from \"./transport.js\";\n\nexport interface BillKitOptions extends Omit<TransportConfig, \"apiKey\"> {\n /** Falls back to `process.env.BILLKIT_API_KEY` when omitted. */\n apiKey?: string;\n}\n\nfunction resolveApiKey(supplied: string | undefined): string {\n if (supplied) return supplied;\n const env = (globalThis.process as { env?: Record<string, string> } | undefined)?.env\n ?.[\"BILLKIT_API_KEY\"];\n if (env) return env;\n throw new Error(\n \"BillKit: missing API key. Pass { apiKey } or set BILLKIT_API_KEY in the environment.\",\n );\n}\n\nexport class BillKit {\n readonly customers: Customers;\n readonly products: Products;\n readonly prices: Prices;\n readonly checkoutSessions: CheckoutSessions;\n readonly oneShotPayments: OneShotPayments;\n readonly subscriptions: Subscriptions;\n readonly refunds: Refunds;\n readonly disputes: Disputes;\n readonly webhookEndpoints: WebhookEndpoints;\n readonly events: Events;\n readonly tenant: Tenant;\n readonly coupons: Coupons;\n readonly taxRates: TaxRates;\n readonly invoices: Invoices;\n readonly auditLogs: AuditLogs;\n readonly payments: Payments;\n readonly billingPortalSessions: BillingPortalSessions;\n\n constructor(options: BillKitOptions = {}) {\n const transport = new Transport({\n ...options,\n apiKey: resolveApiKey(options.apiKey),\n });\n this.customers = new Customers(transport);\n this.products = new Products(transport);\n this.prices = new Prices(transport);\n this.checkoutSessions = new CheckoutSessions(transport);\n this.oneShotPayments = new OneShotPayments(transport);\n this.subscriptions = new Subscriptions(transport);\n this.refunds = new Refunds(transport);\n this.disputes = new Disputes(transport);\n this.webhookEndpoints = new WebhookEndpoints(transport);\n this.events = new Events(transport);\n this.tenant = new Tenant(transport);\n this.coupons = new Coupons(transport);\n this.taxRates = new TaxRates(transport);\n this.invoices = new Invoices(transport);\n this.auditLogs = new AuditLogs(transport);\n this.payments = new Payments(transport);\n this.billingPortalSessions = new BillingPortalSessions(transport);\n }\n}\n","/**\n * Verify `BillKit-Signature: t=<unix>,v1=<hex>` headers.\n *\n * Works in Node 20+, Bun, Deno, Cloudflare Workers and the browser:\n * we use the Web Crypto API (`globalThis.crypto.subtle`) which is\n * available in all modern runtimes. The verifier:\n *\n * 1. Parses the header (rejects malformed shapes). A header may carry\n * more than one `v1=` value, because the server emits both the old and new\n * signature during a signing-secret rotation, and verification passes\n * if any of them matches.\n * 2. Confirms the timestamp is within `toleranceSeconds` of now\n * (replay protection).\n * 3. Computes the expected HMAC and compares against each candidate in\n * constant time.\n */\n\nexport const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;\n\nexport class WebhookVerificationError extends Error {\n override name = \"WebhookVerificationError\";\n constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport interface VerifyWebhookOptions {\n payload: string | Uint8Array;\n signatureHeader: string | null | undefined;\n secret: string;\n toleranceSeconds?: number;\n nowMs?: number; // injectable for tests\n}\n\nconst textEncoder = new TextEncoder();\nconst V1_HEX_RE = /^[0-9a-fA-F]{64}$/;\n\nfunction toBytes(payload: string | Uint8Array): Uint8Array {\n return typeof payload === \"string\" ? textEncoder.encode(payload) : payload;\n}\n\nfunction constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) {\n diff |= (a[i] ?? 0) ^ (b[i] ?? 0);\n }\n return diff === 0;\n}\n\nfunction hexToBytes(hex: string): Uint8Array | null {\n if (!V1_HEX_RE.test(hex)) return null;\n const out = new Uint8Array(hex.length / 2);\n for (let i = 0; i < out.length; i++) {\n const byte = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n if (Number.isNaN(byte)) return null;\n out[i] = byte;\n }\n return out;\n}\n\nfunction parseSignatureHeader(header: string): { ts: number; v1List: string[] } {\n let tsRaw: string | undefined;\n const v1List: string[] = [];\n for (const chunk of header.split(\",\")) {\n const idx = chunk.indexOf(\"=\");\n if (idx < 0) continue;\n const key = chunk.slice(0, idx).trim();\n const value = chunk.slice(idx + 1).trim();\n // A rotation can carry more than one ``v1=`` (old + new secret);\n // collect them all and let the verifier accept any match.\n if (key === \"t\") tsRaw = value;\n else if (key === \"v1\") v1List.push(value);\n }\n if (!tsRaw || v1List.length === 0) {\n throw new WebhookVerificationError(`Malformed BillKit-Signature header: ${header}`);\n }\n const ts = Number.parseInt(tsRaw, 10);\n if (Number.isNaN(ts) || ts <= 0) {\n throw new WebhookVerificationError(`Malformed timestamp in BillKit-Signature: ${tsRaw}`);\n }\n return { ts, v1List };\n}\n\nfunction toArrayBuffer(view: Uint8Array): ArrayBuffer {\n // ``Uint8Array.buffer`` is ``ArrayBufferLike`` (could be\n // ``SharedArrayBuffer``); SubtleCrypto wants a concrete\n // ``ArrayBuffer``. We copy into a fresh ArrayBuffer to bridge.\n const out = new ArrayBuffer(view.byteLength);\n new Uint8Array(out).set(view);\n return out;\n}\n\nasync function computeHmac(secret: string, signed: Uint8Array): Promise<Uint8Array> {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) {\n throw new WebhookVerificationError(\n \"No SubtleCrypto available. The BillKit SDK requires Node 20+, Bun, Deno, \" +\n \"Cloudflare Workers, or any runtime that exposes globalThis.crypto.subtle.\",\n );\n }\n const key = await subtle.importKey(\n \"raw\",\n toArrayBuffer(textEncoder.encode(secret)),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n const signature = await subtle.sign(\"HMAC\", key, toArrayBuffer(signed));\n return new Uint8Array(signature);\n}\n\nexport async function verifyWebhookSignature<T = unknown>(\n options: VerifyWebhookOptions,\n): Promise<T> {\n const {\n payload,\n signatureHeader,\n secret,\n toleranceSeconds = DEFAULT_WEBHOOK_TOLERANCE_SECONDS,\n nowMs = Date.now(),\n } = options;\n\n if (signatureHeader === null || signatureHeader === undefined) {\n throw new WebhookVerificationError(\"Missing BillKit-Signature header.\");\n }\n\n const { ts, v1List } = parseSignatureHeader(signatureHeader);\n if (Math.abs(nowMs / 1000 - ts) > toleranceSeconds) {\n throw new WebhookVerificationError(\n `Signature timestamp outside ±${toleranceSeconds}s tolerance.`,\n );\n }\n\n const payloadBytes = toBytes(payload);\n const signed = new Uint8Array(payloadBytes.length + textEncoder.encode(`${ts}.`).length);\n const prefix = textEncoder.encode(`${ts}.`);\n signed.set(prefix, 0);\n signed.set(payloadBytes, prefix.length);\n\n const expected = await computeHmac(secret, signed);\n // Compare against every candidate; don't break on the first match so\n // the loop's timing doesn't reveal which signature matched.\n let sawValidHex = false;\n let matched = false;\n for (const v1 of v1List) {\n const received = hexToBytes(v1);\n if (!received) continue;\n sawValidHex = true;\n if (constantTimeEqual(expected, received)) matched = true;\n }\n if (!sawValidHex) {\n throw new WebhookVerificationError(\n `Malformed v1 hex in BillKit-Signature: ${v1List.join(\",\")}`,\n );\n }\n if (!matched) {\n throw new WebhookVerificationError(\"Signature mismatch.\");\n }\n\n const decoder = new TextDecoder(\"utf-8\", { fatal: false });\n const text = decoder.decode(payloadBytes);\n try {\n return JSON.parse(text) as T;\n } catch (err) {\n throw new WebhookVerificationError(\n `Webhook body is not valid JSON: ${(err as Error).message}`,\n );\n }\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,67 @@
1
+ {
2
+ "name": "@billkit-eu/sdk",
3
+ "version": "0.1.0",
4
+ "description": "Official Node.js SDK for BillKit: a Stripe-Billing-shape multi-tenant SaaS API on Mollie.",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "src",
19
+ "README.md",
20
+ "CHANGELOG.md",
21
+ "LICENSE"
22
+ ],
23
+ "scripts": {
24
+ "build": "tsup",
25
+ "test": "vitest run",
26
+ "test:watch": "vitest",
27
+ "typecheck": "tsc --noEmit",
28
+ "lint": "eslint src tests",
29
+ "prepublishOnly": "npm run build && npm run test && npm run typecheck"
30
+ },
31
+ "engines": {
32
+ "node": ">=20"
33
+ },
34
+ "keywords": [
35
+ "billkit",
36
+ "billing",
37
+ "subscriptions",
38
+ "mollie",
39
+ "stripe",
40
+ "saas"
41
+ ],
42
+ "author": "BillKit",
43
+ "license": "Apache-2.0",
44
+ "repository": {
45
+ "type": "git",
46
+ "url": "git+https://github.com/billkit-eu/billkit-node.git"
47
+ },
48
+ "homepage": "https://github.com/billkit-eu/billkit-node#readme",
49
+ "bugs": {
50
+ "url": "https://github.com/billkit-eu/billkit-node/issues"
51
+ },
52
+ "publishConfig": {
53
+ "access": "public",
54
+ "provenance": true
55
+ },
56
+ "devDependencies": {
57
+ "@types/node": "^26.2.0",
58
+ "@typescript-eslint/eslint-plugin": "^8.67.0",
59
+ "@typescript-eslint/parser": "^8.20.0",
60
+ "eslint": "^10.8.1",
61
+ "msw": "^2.15.0",
62
+ "tsup": "^8.3.5",
63
+ "typescript": "^6.0.3",
64
+ "vitest": "^4.1.10"
65
+ },
66
+ "sideEffects": false
67
+ }
package/src/client.ts ADDED
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Top-level BillKit client.
3
+ *
4
+ * Wraps a single Transport and exposes every resource family as a
5
+ * field. The Transport is configured once at construction; every
6
+ * resource reuses it, so a runtime-injected `fetch` impl (Cloudflare
7
+ * Workers, MSW for tests, a debug proxy) flows through automatically.
8
+ */
9
+
10
+ import {
11
+ AuditLogs,
12
+ BillingPortalSessions,
13
+ CheckoutSessions,
14
+ Coupons,
15
+ Customers,
16
+ Disputes,
17
+ Events,
18
+ Invoices,
19
+ OneShotPayments,
20
+ Payments,
21
+ Prices,
22
+ Products,
23
+ Refunds,
24
+ Subscriptions,
25
+ TaxRates,
26
+ Tenant,
27
+ WebhookEndpoints,
28
+ } from "./resources.js";
29
+ import { Transport, type TransportConfig } from "./transport.js";
30
+
31
+ export interface BillKitOptions extends Omit<TransportConfig, "apiKey"> {
32
+ /** Falls back to `process.env.BILLKIT_API_KEY` when omitted. */
33
+ apiKey?: string;
34
+ }
35
+
36
+ function resolveApiKey(supplied: string | undefined): string {
37
+ if (supplied) return supplied;
38
+ const env = (globalThis.process as { env?: Record<string, string> } | undefined)?.env
39
+ ?.["BILLKIT_API_KEY"];
40
+ if (env) return env;
41
+ throw new Error(
42
+ "BillKit: missing API key. Pass { apiKey } or set BILLKIT_API_KEY in the environment.",
43
+ );
44
+ }
45
+
46
+ export class BillKit {
47
+ readonly customers: Customers;
48
+ readonly products: Products;
49
+ readonly prices: Prices;
50
+ readonly checkoutSessions: CheckoutSessions;
51
+ readonly oneShotPayments: OneShotPayments;
52
+ readonly subscriptions: Subscriptions;
53
+ readonly refunds: Refunds;
54
+ readonly disputes: Disputes;
55
+ readonly webhookEndpoints: WebhookEndpoints;
56
+ readonly events: Events;
57
+ readonly tenant: Tenant;
58
+ readonly coupons: Coupons;
59
+ readonly taxRates: TaxRates;
60
+ readonly invoices: Invoices;
61
+ readonly auditLogs: AuditLogs;
62
+ readonly payments: Payments;
63
+ readonly billingPortalSessions: BillingPortalSessions;
64
+
65
+ constructor(options: BillKitOptions = {}) {
66
+ const transport = new Transport({
67
+ ...options,
68
+ apiKey: resolveApiKey(options.apiKey),
69
+ });
70
+ this.customers = new Customers(transport);
71
+ this.products = new Products(transport);
72
+ this.prices = new Prices(transport);
73
+ this.checkoutSessions = new CheckoutSessions(transport);
74
+ this.oneShotPayments = new OneShotPayments(transport);
75
+ this.subscriptions = new Subscriptions(transport);
76
+ this.refunds = new Refunds(transport);
77
+ this.disputes = new Disputes(transport);
78
+ this.webhookEndpoints = new WebhookEndpoints(transport);
79
+ this.events = new Events(transport);
80
+ this.tenant = new Tenant(transport);
81
+ this.coupons = new Coupons(transport);
82
+ this.taxRates = new TaxRates(transport);
83
+ this.invoices = new Invoices(transport);
84
+ this.auditLogs = new AuditLogs(transport);
85
+ this.payments = new Payments(transport);
86
+ this.billingPortalSessions = new BillingPortalSessions(transport);
87
+ }
88
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Typed exception hierarchy mirroring the BillKit API error envelope.
3
+ *
4
+ * The API returns errors in the Stripe-shape:
5
+ *
6
+ * { "error": { "type": "...", "code": "...", "message": "...", "param": "..." } }
7
+ *
8
+ * Each `type` maps to one error class so callers can `catch` on the
9
+ * subclass they care about rather than branching on HTTP status codes.
10
+ */
11
+
12
+ export interface ErrorEnvelope {
13
+ type?: string;
14
+ code?: string;
15
+ message?: string;
16
+ param?: string;
17
+ }
18
+
19
+ export interface BillKitErrorOptions {
20
+ type?: string | undefined;
21
+ code?: string | undefined;
22
+ param?: string | undefined;
23
+ statusCode?: number | undefined;
24
+ requestId?: string | undefined;
25
+ rawBody?: unknown;
26
+ }
27
+
28
+ // TS treats `name = "Foo"` as a literal-type property, which then conflicts
29
+ // when subclasses override it. We widen to `string` everywhere so the
30
+ // hierarchy can re-set ``name`` cleanly.
31
+ export class BillKitError extends Error {
32
+ override name: string = "BillKitError";
33
+ readonly type: string | undefined;
34
+ readonly code: string | undefined;
35
+ readonly param: string | undefined;
36
+ readonly statusCode: number | undefined;
37
+ readonly requestId: string | undefined;
38
+ readonly rawBody: unknown;
39
+
40
+ constructor(message: string, options: BillKitErrorOptions = {}) {
41
+ super(message);
42
+ this.type = options.type;
43
+ this.code = options.code;
44
+ this.param = options.param;
45
+ this.statusCode = options.statusCode;
46
+ this.requestId = options.requestId;
47
+ this.rawBody = options.rawBody;
48
+ // Restore the prototype chain, required when targeting ES5 transpilers
49
+ // (some bundlers still emit them) so `instanceof BillKitError` works.
50
+ Object.setPrototypeOf(this, new.target.prototype);
51
+ }
52
+ }
53
+
54
+ export class APIConnectionError extends BillKitError {
55
+ override name = "APIConnectionError";
56
+ }
57
+
58
+ export class APIError extends BillKitError {
59
+ override name = "APIError";
60
+ }
61
+
62
+ export class ServerError extends APIError {
63
+ override name = "ServerError";
64
+ }
65
+
66
+ export class AuthenticationError extends BillKitError {
67
+ override name = "AuthenticationError";
68
+ }
69
+
70
+ export class PermissionError extends BillKitError {
71
+ override name = "PermissionError";
72
+ }
73
+
74
+ export class ResourceMissingError extends BillKitError {
75
+ override name = "ResourceMissingError";
76
+ }
77
+
78
+ export class InvalidRequestError extends BillKitError {
79
+ override name = "InvalidRequestError";
80
+ }
81
+
82
+ export class ConflictError extends BillKitError {
83
+ override name = "ConflictError";
84
+ }
85
+
86
+ export class RateLimitError extends BillKitError {
87
+ override name = "RateLimitError";
88
+ readonly retryAfter: number | undefined;
89
+
90
+ constructor(
91
+ message: string,
92
+ options: BillKitErrorOptions & { retryAfter?: number | undefined } = {},
93
+ ) {
94
+ super(message, options);
95
+ this.retryAfter = options.retryAfter;
96
+ }
97
+ }
98
+
99
+ const TYPE_TO_CLASS: Record<string, new (msg: string, opts: BillKitErrorOptions) => BillKitError> =
100
+ {
101
+ api_connection_error: APIConnectionError,
102
+ // ``api_error`` is the Stripe-convention type for 5xx, so surface it as
103
+ // ServerError (a subclass of APIError) so `catch (e instanceof
104
+ // ServerError)` works without false negatives.
105
+ api_error: ServerError,
106
+ authentication_error: AuthenticationError,
107
+ permission_error: PermissionError,
108
+ invalid_request_error: InvalidRequestError,
109
+ idempotency_error: ConflictError,
110
+ conflict: ConflictError,
111
+ rate_limit_error: RateLimitError,
112
+ };
113
+
114
+ function fallbackType(status: number): string {
115
+ if (status === 401) return "authentication_error";
116
+ if (status === 403) return "permission_error";
117
+ if (status === 404) return "invalid_request_error";
118
+ if (status === 409) return "conflict";
119
+ if (status === 429) return "rate_limit_error";
120
+ if (status >= 500) return "api_error";
121
+ return "invalid_request_error";
122
+ }
123
+
124
+ function fallbackClass(
125
+ status: number,
126
+ ): new (msg: string, opts: BillKitErrorOptions) => BillKitError {
127
+ if (status === 401) return AuthenticationError;
128
+ if (status === 403) return PermissionError;
129
+ if (status === 404) return ResourceMissingError;
130
+ if (status === 409) return ConflictError;
131
+ if (status === 429) return RateLimitError;
132
+ if (status >= 500) return ServerError;
133
+ return InvalidRequestError;
134
+ }
135
+
136
+ export function errorFromResponse(args: {
137
+ status: number;
138
+ body: unknown;
139
+ requestId?: string | undefined;
140
+ retryAfter?: number | undefined;
141
+ }): BillKitError {
142
+ const { status, body, requestId, retryAfter } = args;
143
+ const envelope: ErrorEnvelope =
144
+ typeof body === "object" && body !== null && "error" in body
145
+ ? ((body as { error?: ErrorEnvelope }).error ?? {})
146
+ : {};
147
+
148
+ const type = envelope.type ?? fallbackType(status);
149
+ const message =
150
+ envelope.message ?? `BillKit API returned HTTP ${status} with no error body.`;
151
+
152
+ let cls = TYPE_TO_CLASS[type] ?? fallbackClass(status);
153
+ if (status === 404 && cls === InvalidRequestError) cls = ResourceMissingError;
154
+ if (status === 409 && cls === InvalidRequestError) cls = ConflictError;
155
+
156
+ const options: BillKitErrorOptions & { retryAfter?: number | undefined } = {
157
+ type,
158
+ code: envelope.code,
159
+ param: envelope.param,
160
+ statusCode: status,
161
+ requestId,
162
+ rawBody: typeof body === "object" && body !== null ? body : undefined,
163
+ };
164
+ if (cls === RateLimitError) {
165
+ options.retryAfter = retryAfter;
166
+ }
167
+ return new cls(message, options);
168
+ }