@usebillow/sdk 0.7.0 → 0.8.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.
- package/CHANGELOG.md +7 -0
- package/dist/{chunk-JG2OOAMX.js → chunk-J6JIZGWB.js} +68 -2
- package/dist/chunk-J6JIZGWB.js.map +1 -0
- package/dist/config.d.cts +1 -1
- package/dist/config.d.ts +1 -1
- package/dist/{hosted-domains-z_I0edmM.d.ts → hosted-domains-BP91tg9P.d.ts} +53 -1
- package/dist/{hosted-domains-BYYl2DSa.d.cts → hosted-domains-BbuyxnuH.d.cts} +53 -1
- package/dist/index.cjs +66 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +65 -5
- package/dist/index.d.ts +65 -5
- package/dist/index.js +1 -1
- package/dist/ingestion.d.cts +1 -1
- package/dist/ingestion.d.ts +1 -1
- package/dist/react.js +1 -1
- package/dist/server.d.cts +1 -1
- package/dist/server.d.ts +1 -1
- package/dist/webhooks.d.cts +1 -1
- package/dist/webhooks.d.ts +1 -1
- package/package.json +1 -1
- package/dist/chunk-JG2OOAMX.js.map +0 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/billing-status.ts","../src/client.ts","../src/error-codes.ts","../src/money.ts","../src/subscription-status.ts","../src/types/admin-integrations.ts","../src/pagination.ts","../src/resources/charges.ts","../src/resources/credits.ts","../src/resources/customers.ts","../src/resources/deliverability.ts","../src/resources/hosted-domains.ts","../src/resources/invoices.ts","../src/resources/marketplace.ts","../src/resources/metrics.ts","../src/resources/portal-sessions.ts","../src/resources/products.ts","../src/resources/settings.ts","../src/resources/subscriptions.ts","../src/resources/webhook-endpoints.ts","../src/index.ts"],"names":["safeToRepeat","path"],"mappings":";;;AASO,IAAM,eAAA,GAAkB;AAAA,EAC7B,SAAA;AAAA,EACA,YAAA;AAAA,EACA,WAAA;AAAA,EACA,QAAA;AAAA,EACA,yBAAA;AA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AAE,CAAC,CAAA,QAAA;AAAA,KACnD;AAAA,IACF,MAAA,EAAQ,CAAC,EAAA,KACP,UAAA;AAAA,MACE,IAAA,CAAK,IAAA;AAAA,MACL,QAAA;AAAA,MACA,CAAA,wBAAA,EAA2B,kBAAA,CAAmB,EAAE,CAAC,CAAA;AAAA;AACnD,GACJ;AAAA;AAAA,EAGA,QAAA,GAAW;AAAA;AAAA,IAET,GAAA,EAAK,CAAC,OAAA,KACJ,UAAA,CAA2B,KAAK,IAAA,EAAM,KAAA,EAAO,kBAAA,EAAoB,MAAA,EAAW,OAAO,CAAA;AAAA;AAAA,IAErF,OAAO,MAAM,UAAA,CAA2C,IAAA,CAAK,IAAA,EAAM,QAAQ,kBAAkB;AAAA,GAC/F;AACF","file":"index.cjs","sourcesContent":["/**\n * Charge / invoice / refund / payment-method / webhook-delivery status vocabularies,\n * mirrored for the SDK (which cannot import the server-side `@billow/core`). The DB-enum\n * ones (charge, invoice, refund, payment method) mirror core enums and are parity-tested\n * against it (see billing-status.test.ts); webhook-delivery status is a free-text column\n * server-side with a fixed vocabulary, documented here.\n */\n\n/** A charge's lifecycle status — mirrors `@billow/core` `CHARGE_STATUSES`. */\nexport const CHARGE_STATUSES = [\n \"pending\",\n \"processing\",\n \"succeeded\",\n \"failed\",\n \"requires_reconciliation\",\n \"disputed\",\n] as const;\nexport type ChargeStatus = (typeof CHARGE_STATUSES)[number];\n\n/** An invoice's lifecycle status — mirrors `@billow/core` `INVOICE_STATUSES`. */\nexport const INVOICE_STATUSES = [\"draft\", \"open\", \"paid\", \"uncollectible\", \"void\"] as const;\nexport type InvoiceStatus = (typeof INVOICE_STATUSES)[number];\n\n/** A refund's lifecycle status — mirrors `@billow/core` `REFUND_STATUSES`. */\nexport const REFUND_STATUSES = [\"pending\", \"succeeded\", \"failed\"] as const;\nexport type RefundStatus = (typeof REFUND_STATUSES)[number];\n\n/** A saved payment method's status — mirrors `@billow/core` `PAYMENT_METHOD_STATUSES`. */\nexport const PAYMENT_METHOD_STATUSES = [\"active\", \"expired\", \"removed\"] as const;\nexport type PaymentMethodStatus = (typeof PAYMENT_METHOD_STATUSES)[number];\n\n/**\n * A webhook delivery attempt's status. Not a DB enum (a free-text column); the dispatcher\n * inserts one row per attempt with exactly `delivered` (a 2xx) or `failed` (anything else) —\n * see `packages/server/src/jobs/outbox.ts`. (Retry/backoff state lives on the outbox event,\n * a separate table, not on the delivery record.)\n */\nexport const WEBHOOK_DELIVERY_STATUSES = [\"delivered\", \"failed\"] as const;\nexport type WebhookDeliveryStatus = (typeof WEBHOOK_DELIVERY_STATUSES)[number];\n","import type { BillowErrorCode } from \"./error-codes\";\nimport type { BillowOptions, CallOptions, RequestOptions } from \"./types\";\n\n/** The response header carrying billow's per-request id (echoed on success and error alike). */\nconst REQUEST_ID_HEADER = \"x-request-id\";\n\n/** Build a `?a=b&c=d` string, skipping undefined/null/empty values. */\nexport function toQuery(params: object): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== null && v !== \"\") q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : \"\";\n}\n\nexport class BillowApiError extends Error {\n readonly status: number;\n /**\n * A known {@link BillowErrorCode} (widened to `string` so a newer server's code still type-checks),\n * or one the SDK raises itself: `invalid_response` for a success (2xx other than 204) whose body\n * was empty or could not be read or parsed. The request reached billow and was answered, but what\n * it answered is unknown - for a write, treat the outcome as UNKNOWN (retry it under the same\n * idempotency key), never as done or as refused.\n */\n readonly code: BillowErrorCode | (string & {});\n /** Structured error context from the server (e.g. per-field validation issues), when present. */\n readonly details?: unknown;\n /** billow's per-request id (`x-request-id`) — quote it in a bug report to trace the server log. */\n readonly requestId?: string | undefined;\n\n constructor(\n status: number,\n code: BillowErrorCode | (string & {}),\n message: string,\n details?: unknown,\n requestId?: string,\n ) {\n super(message);\n this.name = \"BillowApiError\";\n this.status = status;\n this.code = code;\n this.details = details;\n this.requestId = requestId;\n }\n}\n\n/** Hard per-request timeout when a caller doesn't set one. */\nconst DEFAULT_TIMEOUT_MS = 60_000;\n/** Base retry backoff when a caller doesn't set one. */\nconst DEFAULT_RETRY_BACKOFF_MS = 500;\n\n/** Everything a request needs: the transport, the base URL, the bearer, and resilience knobs. */\nexport interface RequestContext {\n fetch: typeof fetch;\n baseUrl: string;\n /** The bearer — a secret/publishable API key, or a portal-session token. */\n bearer: string;\n timeoutMs: number;\n maxRetries: number;\n retryBackoffMs: number;\n}\n\nexport function makeContext(bearer: string, opts: BillowOptions): RequestContext {\n return {\n fetch: opts.fetch ?? fetch,\n baseUrl: resolveBaseUrl(opts.baseUrl),\n bearer,\n timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n maxRetries: opts.maxRetries ?? 0,\n retryBackoffMs: opts.retryBackoffMs ?? DEFAULT_RETRY_BACKOFF_MS,\n };\n}\n\n/**\n * Whether a failed attempt is safe to retry. A `null` status is a network error or timeout\n * (no response). A `429` never executed (rate-limited), so it is safe to repeat regardless; a\n * network error / `5xx` might have applied a write, so those retry only when the request is\n * `safeToRepeat` — an idempotent method (`GET`/`HEAD`) or an idempotency-keyed write.\n */\nfunction isRetryable(status: number | null, safeToRepeat: boolean): boolean {\n if (status === 429) return true;\n if (status === null) return safeToRepeat;\n return safeToRepeat && status >= 500 && status <= 599;\n}\n\n/** Backoff before the next attempt: honor `Retry-After` (seconds) if given, else exponential. */\nfunction backoffMs(base: number, attempt: number, retryAfter: string | null): number {\n if (retryAfter) {\n const secs = Number(retryAfter);\n if (Number.isFinite(secs) && secs >= 0) return secs * 1000;\n }\n return base * 2 ** attempt;\n}\n\n/** The reason an aborted signal carries, or a plain `AbortError` when none was given. */\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException(\"The operation was aborted.\", \"AbortError\");\n}\n\n/** A backoff sleep that a caller's abort can cut short. */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(abortReason(signal));\n const timer = setTimeout(resolve, ms);\n signal?.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n reject(abortReason(signal));\n },\n { once: true },\n );\n });\n}\n\ninterface SendOptions {\n timeoutMs: number;\n /** Retry a network error / `5xx` (a `429` always retries) — set for GET/HEAD or keyed writes. */\n safeToRepeat: boolean;\n /** The caller's cancellation signal, if any. A caller abort is surfaced at once, never retried. */\n callerSignal: AbortSignal | undefined;\n}\n\n/**\n * Send one request with a per-attempt timeout and opt-in retries. Returns the final `Response`\n * (which may carry a non-retryable error status for the caller to parse); throws on a network\n * error / timeout that leaves no response, or immediately with the caller's reason if the\n * caller's `signal` aborts. Retryable responses are discarded and re-issued up to `maxRetries`\n * with {@link backoffMs} between attempts. The timeout is applied **per attempt**.\n */\nasync function sendWithResilience(\n ctx: RequestContext,\n url: string,\n init: RequestInit,\n opts: SendOptions,\n): Promise<Response> {\n const { timeoutMs, safeToRepeat, callerSignal } = opts;\n if (callerSignal?.aborted) throw abortReason(callerSignal);\n\n for (let attempt = 0; ; attempt++) {\n // A fresh controller per attempt, aborted by either the per-attempt timeout or the caller.\n const controller = new AbortController();\n let timedOut = false;\n const onCallerAbort = () => controller.abort(abortReason(callerSignal as AbortSignal));\n callerSignal?.addEventListener(\"abort\", onCallerAbort, { once: true });\n const timer =\n timeoutMs > 0\n ? setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeoutMs)\n : undefined;\n\n let res: Response | null = null;\n let err: unknown;\n try {\n res = await ctx.fetch(url, { ...init, signal: controller.signal });\n } catch (e) {\n err = e;\n } finally {\n if (timer) clearTimeout(timer);\n callerSignal?.removeEventListener(\"abort\", onCallerAbort);\n }\n\n // The caller cancelled — surface their reason immediately, never retry.\n if (callerSignal?.aborted) throw abortReason(callerSignal);\n\n if (res?.ok) return res;\n const status = res ? res.status : null;\n if (attempt < ctx.maxRetries && isRetryable(status, safeToRepeat)) {\n await sleep(\n backoffMs(ctx.retryBackoffMs, attempt, res?.headers.get(\"retry-after\") ?? null),\n callerSignal,\n );\n continue;\n }\n if (res) return res; // non-retryable (or retries exhausted) HTTP error — caller parses the body\n if (timedOut) throw new Error(`billow request timed out after ${timeoutMs}ms`);\n throw err instanceof Error ? err : new Error(\"billow request failed\");\n }\n}\n\n/** A method with no request body is inherently safe to repeat; a write needs an idempotency key. */\nfunction safeToRepeat(method: string, hasIdempotencyKey: boolean): boolean {\n return method === \"GET\" || method === \"HEAD\" || hasIdempotencyKey;\n}\n\n/** The hosted Billow API, which a client talks to unless told otherwise. */\nexport const DEFAULT_BASE_URL = \"https://api.usebillow.com\";\n\n/**\n * Resolve the API base URL: the explicit `baseUrl` option first, then the `BILLOW_URL`\n * environment variable (Node), then the hosted API. Local development and self-hosted\n * servers set one of the first two. Trailing slash stripped.\n */\nfunction resolveBaseUrl(explicit?: string): string {\n // biome-ignore lint/complexity/useLiteralKeys: the SDK cannot augment every consumer's ProcessEnv.\n const fromEnv = typeof process !== \"undefined\" ? process.env?.[\"BILLOW_URL\"] : undefined;\n return (explicit || fromEnv || DEFAULT_BASE_URL).replace(/\\/$/, \"\");\n}\n\nexport async function apiRequest<T>(\n ctx: RequestContext,\n method: string,\n path: string,\n body?: unknown,\n options?: RequestOptions,\n): Promise<T> {\n return (await apiRequestWithStatus<T>(ctx, method, path, body, options)).data;\n}\n\n/**\n * {@link apiRequest}, also answering the success status - for the writes whose status carries\n * meaning (an idempotent create answers `201` when it created, `200` when it replayed).\n */\nexport async function apiRequestWithStatus<T>(\n ctx: RequestContext,\n method: string,\n path: string,\n body?: unknown,\n options?: RequestOptions,\n): Promise<{ status: number; data: T }> {\n const init: RequestInit = {\n method,\n headers: {\n authorization: `Bearer ${ctx.bearer}`,\n ...(body ? { \"content-type\": \"application/json\" } : {}),\n ...(options?.idempotencyKey ? { \"idempotency-key\": options.idempotencyKey } : {}),\n },\n };\n if (body) init.body = JSON.stringify(body);\n const res = await sendWithResilience(ctx, `${ctx.baseUrl}${path}`, init, {\n timeoutMs: options?.timeoutMs ?? ctx.timeoutMs,\n safeToRepeat: safeToRepeat(method, !!options?.idempotencyKey),\n callerSignal: options?.signal,\n });\n // null: the body could not be read (the connection dropped mid-body, say).\n const text = await res.text().catch(() => null);\n if (!res.ok) throw errorFrom(res, safeParse(text ?? \"\"));\n return { status: res.status, data: parseSuccessBody<T>(res, text) };\n}\n\n/** billow's per-request id from a response, for {@link BillowApiError.requestId}. */\nfunction requestIdOf(res: Response): string | undefined {\n return res.headers.get(REQUEST_ID_HEADER) ?? undefined;\n}\n\n/** Parse leniently — a malformed *error* body still yields the HTTP-status error, not a parse error. */\nfunction safeParse(text: string): unknown {\n if (text.trim() === \"\") return {};\n try {\n return JSON.parse(text);\n } catch {\n return {};\n }\n}\n\n/**\n * A successful response must carry valid JSON; only a `204 No Content` (a delete) carries none. An\n * empty, unreadable or malformed 2xx body is an `invalid_response` error, never a silently-empty\n * `{}` - which a caller would take for an answer (a write it thinks done, with `undefined` fields).\n */\nfunction parseSuccessBody<T>(res: Response, text: string | null): T {\n if (res.status === 204) return {} as T;\n if (text !== null && text.trim() !== \"\") {\n try {\n return JSON.parse(text) as T;\n } catch {\n // Falls through to the error below.\n }\n }\n throw new BillowApiError(\n res.status,\n \"invalid_response\",\n `billow returned an empty or unreadable response body (HTTP ${res.status})`,\n undefined,\n requestIdOf(res),\n );\n}\n\n/** Build a {@link BillowApiError} from a failed response (surfacing `details` + the `requestId`). */\nfunction errorFrom(res: Response, data: unknown): BillowApiError {\n const err =\n (data as { error?: { code?: string; message?: string; details?: unknown } }).error ?? {};\n return new BillowApiError(\n res.status,\n err.code ?? \"error\",\n err.message ?? String(res.status),\n err.details,\n requestIdOf(res),\n );\n}\n\n/** Fetch a binary endpoint (e.g. a PDF) as raw bytes (a valid `BodyInit`). */\nexport async function apiRequestBinary(\n ctx: RequestContext,\n method: string,\n path: string,\n options?: CallOptions,\n): Promise<ArrayBuffer> {\n const res = await sendWithResilience(\n ctx,\n `${ctx.baseUrl}${path}`,\n { method, headers: { authorization: `Bearer ${ctx.bearer}` } },\n {\n timeoutMs: options?.timeoutMs ?? ctx.timeoutMs,\n safeToRepeat: safeToRepeat(method, false),\n callerSignal: options?.signal,\n },\n );\n if (!res.ok) throw errorFrom(res, safeParse(await res.text().catch(() => \"\")));\n return res.arrayBuffer();\n}\n","/**\n * The machine-readable error codes billow returns on `BillowApiError.code`. Mirrored from\n * `@billow/core`'s `BILLOW_ERROR_CODES` (the server's source of truth) — the SDK carries no\n * runtime dependency on core, so `error-codes.test.ts` asserts this list stays in lockstep.\n *\n * `switch` on these for programmatic handling (e.g. surface `rate_limited` vs `validation_error`\n * differently). The `code` field stays widened to `string` for forward-compatibility, so a code a\n * newer server adds never breaks type-checking against an older SDK.\n */\nexport const BILLOW_ERROR_CODES = [\n \"not_found\",\n \"validation_error\",\n \"authentication_error\",\n \"api_key_expired\",\n \"permission_denied\",\n \"conflict\",\n \"invalid_state_transition\",\n \"provider_error\",\n \"rate_limited\",\n \"quota_exceeded\",\n \"internal_error\",\n // Prepaid credits. 402 is shared with `quota_exceeded`: switch on the code, never the status.\n \"insufficient_credits\",\n \"account_frozen\",\n \"account_closed\",\n \"idempotency_conflict\",\n \"commit_exceeds_hold\",\n \"reversal_exceeds_consumption\",\n] as const;\n\nexport type BillowErrorCode = (typeof BILLOW_ERROR_CODES)[number];\n","/**\n * Money helpers, mirrored for the SDK (which cannot import the server-side `@billow/core`).\n * billow stores every amount as integer minor units (e.g. piasters) plus an ISO-4217 currency;\n * the number of minor units in one major unit depends on the currency's exponent, which is NOT\n * always 2 (KWD/BHD/OMR are 3, JPY/KRW are 0). Use these instead of a hardcoded `* 100` / `/ 100`,\n * which silently mis-handles those currencies 10-100x.\n *\n * The exponent table mirrors `@billow/core` and is parity-tested against it (see money.test.ts),\n * so a change in core fails CI until this mirror matches.\n */\n\n/**\n * ISO-4217 minor-unit exponents that are NOT the default of 2 (zero-decimal and three/four-decimal\n * currencies). Everything not listed — EGP, USD, EUR, SAR, AED, … — is 2.\n */\nconst CURRENCY_EXPONENTS: Readonly<Record<string, number>> = {\n // Zero-decimal\n BIF: 0,\n CLP: 0,\n DJF: 0,\n GNF: 0,\n ISK: 0,\n JPY: 0,\n KMF: 0,\n KRW: 0,\n PYG: 0,\n RWF: 0,\n UGX: 0,\n VND: 0,\n VUV: 0,\n XAF: 0,\n XOF: 0,\n XPF: 0,\n // Three-decimal\n BHD: 3,\n IQD: 3,\n JOD: 3,\n KWD: 3,\n LYD: 3,\n OMR: 3,\n TND: 3,\n // Four-decimal\n CLF: 4,\n UYW: 4,\n};\n\n/** The number of digits after the decimal point for `currency` (ISO-4217); defaults to 2. */\nexport function currencyExponent(currency: string): number {\n return CURRENCY_EXPONENTS[currency.toUpperCase()] ?? 2;\n}\n\n/**\n * Convert a major-unit amount (e.g. `5.00`) into integer minor units for `currency`, rounded to\n * the nearest minor unit. Use when building an amount to send to the API.\n */\nexport function toMinorUnits(major: number, currency: string): number {\n return Math.round(major * 10 ** currencyExponent(currency));\n}\n\n/** Convert integer minor units back to major units for `currency` (the inverse of toMinorUnits). */\nexport function toMajorUnits(minor: number, currency: string): number {\n return minor / 10 ** currencyExponent(currency);\n}\n\n/**\n * Format integer minor units with their currency for display (e.g. 10000, \"EGP\" → \"EGP 100.00\";\n * 5000, \"KWD\" → \"KWD 5.000\"). The currency's exponent drives both the divisor and the decimals.\n */\nexport function formatMoney(minor: number, currency: string): string {\n const exponent = currencyExponent(currency);\n const major = minor / 10 ** exponent;\n try {\n return new Intl.NumberFormat(\"en\", {\n style: \"currency\",\n currency,\n minimumFractionDigits: exponent,\n maximumFractionDigits: exponent,\n }).format(major);\n } catch {\n return `${major.toFixed(exponent)} ${currency}`;\n }\n}\n","/**\n * The subscription status vocabulary + access predicate, mirrored from @billow/core\n * (`enums.ts` + `billing/subscription-state.ts`) so SDK consumers can type and branch on\n * billow's own model instead of hand-maintaining a union that drifts (a real bug: an app\n * copy once carried a non-existent `ended` status - that string is a webhook event type,\n * not a subscription status).\n *\n * Mirrored, not imported: @billow/core is a server package the published SDK cannot depend\n * on (the same reason @billow/contracts mirrors core's pure logic). The parity test\n * `subscription-status.test.ts` imports @billow/core and fails CI on any drift.\n */\n\n/** The 8 canonical subscription statuses, in lifecycle order. */\nexport const SUBSCRIPTION_STATUSES = [\n \"incomplete\",\n \"incomplete_expired\",\n \"trialing\",\n \"active\",\n \"past_due\",\n \"paused\",\n \"canceled\",\n \"unpaid\",\n] as const;\n\nexport type SubscriptionStatus = (typeof SUBSCRIPTION_STATUSES)[number];\n\n/**\n * Statuses that currently grant access (a live commitment): `trialing`, `active`, and\n * `past_due` (access is retained through dunning). Note `paused` does NOT grant access.\n */\nexport const ACTIVE_SUBSCRIPTION_STATUSES: readonly SubscriptionStatus[] = [\n \"trialing\",\n \"active\",\n \"past_due\",\n];\n\n/** Statuses a subscription can never leave: `incomplete_expired` and `canceled`. */\nexport const TERMINAL_SUBSCRIPTION_STATUSES: readonly SubscriptionStatus[] = [\n \"incomplete_expired\",\n \"canceled\",\n];\n\n/** Statuses in which a subscription never activated (no access was ever granted). */\nexport const NEVER_ACTIVATED_SUBSCRIPTION_STATUSES: readonly SubscriptionStatus[] = [\n \"incomplete\",\n \"incomplete_expired\",\n];\n\n/** Whether access should currently be granted for a subscription in this state. */\nexport function grantsAccess(status: SubscriptionStatus): boolean {\n return ACTIVE_SUBSCRIPTION_STATUSES.includes(status);\n}\n\n/** Whether this is a terminal status the subscription can never leave. */\nexport function isTerminal(status: SubscriptionStatus): boolean {\n return TERMINAL_SUBSCRIPTION_STATUSES.includes(status);\n}\n","/** Public SDK types for this domain. Re-exported by ../types.ts. */\nimport type { TaxBehavior } from \"./common\";\n\n// ── Payment providers (ADR-0017) ────────────────────────────────────────────\n// Mirrors @billow/core's payment-provider manifest + verify types; the SDK is\n// standalone (no @billow/core dependency). Keep in sync with\n// packages/core/src/provider.ts. (`ConfigField` is the marketplace manifest field,\n// declared below and reused here.)\n\n/** A payment provider's declarative admin surface (rendered into the credentials form). */\nexport interface PaymentProviderDefinition {\n /** Registry key + `payment_credentials.provider` discriminator (e.g. \"paymob\"). */\n provider: string;\n label: string;\n /** Config-field manifest; secret fields are stored encrypted and never returned. */\n fields: ConfigField[];\n /** Customer-present checkout methods this provider can offer. */\n methods: (\"card\" | \"wallet\" | \"sympl\" | \"applepay\")[];\n /** Live verify targets the dashboard can \"Test\". */\n verifyTargets: ProviderVerifyTarget[];\n /**\n * When present, the dashboard surfaces a copy-able webhook URL to register in the\n * provider's own dashboard (e.g. Stripe). Omitted for providers that set their\n * callback per-charge (Paymob). `events` is an optional hint list; `url` is the\n * tenant's full endpoint, filled in by the API per (org, environment).\n */\n webhook?: { events?: string[]; url?: string };\n}\n\n/** One customer-present checkout method offered for a currency (for a method picker). */\nexport interface CheckoutMethodInfo {\n method: \"card\" | \"wallet\" | \"sympl\" | \"applepay\";\n label: string;\n /** Customer surcharge applied to this method's checkout total, in basis points. */\n feeBps?: number;\n}\n\n/** A verify target the dashboard can \"Test\" (key + label, optional integration field). */\nexport interface ProviderVerifyTarget {\n key: string;\n label: string;\n /**\n * The non-secret config field holding this target's integration id (the box's\n * primary field). Set ⇒ the dashboard renders the target as its own integration\n * box; absent ⇒ an account-level probe shown in the credentials card.\n */\n fieldKey?: string;\n /** Additional non-secret config fields rendered inside the same integration box. */\n extraFieldKeys?: string[];\n /** Short helper text shown under the integration box. */\n help?: string;\n}\n\n/** One verify target's live verdict. */\nexport interface ProviderVerifyTargetResult {\n /** The target key probed (matches a `PaymentProviderDefinition.verifyTargets` key). */\n target: string;\n configured: boolean;\n /** The provider validated this target's config against its live API. */\n valid: boolean;\n /** HTTP status of the probe (0 = not configured / transport error). */\n status: number;\n detail: string;\n /** Provider-specific extra detail (e.g. Paymob's gateway type). */\n meta?: Record<string, string>;\n /** Present only for a functional (money-moving) sub-test. */\n functional?: { ok: boolean; status: number; detail: string };\n}\n\nexport interface ProviderVerifyResult {\n provider: string;\n currency: string;\n targets: ProviderVerifyTargetResult[];\n}\n\n/** A credential set's non-secret surface (provider + currency + stored config). */\nexport interface ProviderCredentialSummary {\n provider: string;\n currency: string;\n config: Record<string, unknown>;\n}\n\n/** The editable view of one credential set — secret values are never returned. */\nexport interface CredentialSet {\n provider: string;\n currency: string;\n /** Stored non-secret field values, keyed by manifest field key (pre-fills the form). */\n config: Record<string, unknown>;\n /** Which secret fields currently have a value stored (the value is never returned). */\n secretsSet: Record<string, boolean>;\n updatedAt: string;\n}\n\n/**\n * Create or rotate a credential set. `values` carries each field keyed by the\n * provider definition's field key. On first create all required secrets are\n * required; on update omit a secret to keep the stored one, send \"\" to clear a\n * non-secret field, omit a field to leave it unchanged.\n */\nexport interface UpsertCredentialsInput {\n provider: string;\n currency: string;\n values: Record<string, unknown>;\n}\n\n/** The merchant's customer-facing business identity (seller block + email from-name). */\nexport interface BusinessProfile {\n displayName: string | null;\n legalName: string | null;\n address: string | null;\n /** Contact phone (PRD-02). */\n phone: string | null;\n /** ISO-3166-1 alpha-2 country code, e.g. \"EG\" (PRD-02). */\n country: string | null;\n taxId: string | null;\n supportEmail: string | null;\n /** Logo image URL rendered on documents + emails; null = name-only branding. */\n logoUrl: string | null;\n /** Brand/accent color as `#RRGGBB` (PRD-11); null = billow's default accent. */\n brandColor: string | null;\n /** Org-default tax treatment (Phase E) — every taxable price inherits this. */\n taxEnabled: boolean;\n /** Default rate in basis points (1% = 100 bps), e.g. 1400 for Egypt's 14% VAT. */\n taxRateBps: number;\n taxBehavior: TaxBehavior;\n /** What the tax is called on documents (e.g. \"VAT\"); null falls back to \"Tax\". */\n taxLabel: string | null;\n updatedAt: string;\n}\n\n/** Update a business profile; omit a field to leave it unchanged, send \"\" to clear it. */\nexport interface UpdateBusinessProfileInput {\n displayName?: string;\n legalName?: string;\n address?: string;\n phone?: string;\n country?: string;\n taxId?: string;\n supportEmail?: string;\n logoUrl?: string;\n /** `#RRGGBB` hex; empty string clears it (PRD-11). */\n brandColor?: string;\n taxEnabled?: boolean;\n taxRateBps?: number;\n taxBehavior?: TaxBehavior;\n taxLabel?: string;\n}\n\n// ── Marketplace Integrations (ADR-0008) ─────────────────────────────────────\n// Mirrors @billow/core's manifest types; the SDK is standalone (no @billow/core\n// dependency). Keep in sync with packages/core/src/integrations.ts.\n\nexport type IntegrationKind = \"email\" | \"accounting\";\nexport type IntegrationTier = \"official\" | \"community\";\nexport type ConfigFieldType =\n | \"text\"\n | \"password\"\n | \"email\"\n | \"url\"\n | \"number\"\n | \"percent\"\n | \"boolean\"\n | \"select\";\n\nexport interface ConfigFieldOption {\n value: string;\n label: string;\n}\n\n/** One field in an Integration's config manifest (the dashboard renders these). */\nexport interface ConfigField {\n key: string;\n label: string;\n type: ConfigFieldType;\n /** Secret values are stored encrypted and never returned by a read. */\n secret?: boolean;\n required?: boolean;\n placeholder?: string;\n help?: string;\n options?: ConfigFieldOption[];\n default?: string | number | boolean;\n}\n\n/** A catalog Integration's declarative definition. */\nexport interface IntegrationDefinition {\n slug: string;\n name: string;\n kind: IntegrationKind;\n tier: IntegrationTier;\n summary: string;\n description?: string;\n fields: ConfigField[];\n docsUrl?: string;\n}\n\n/** A catalog entry: the definition plus this tenant's install state. */\nexport interface CatalogItem {\n definition: IntegrationDefinition;\n installed: boolean;\n enabled: boolean;\n /** Stored non-secret config values, for pre-filling the form. */\n config: Record<string, unknown>;\n /** Which secret fields have a value stored (the value itself is never returned). */\n secretsSet: Record<string, boolean>;\n /** Result of the last test/verify probe; null until tested (reset on reconfigure). */\n lastTestStatus: \"ok\" | \"error\" | null;\n /** Failure message from the last test, when it errored. */\n lastTestError: string | null;\n /** When the last test/verify probe ran (ISO), or null if never tested. */\n lastTestedAt: string | null;\n updatedAt: string | null;\n}\n\n/** A config field carries a secret value when explicitly marked or password-typed. */\nexport function isSecretField(field: ConfigField): boolean {\n return field.secret === true || field.type === \"password\";\n}\n","import type { CursorListPromise, CursorPaginated, ListPromise, Paginated } from \"./types\";\n\n/**\n * The shared machinery behind every paginated `.list()`: a handle that is BOTH a Promise for the\n * first page AND an async iterable over every page, in one of two modes - offset\n * ({@link makeListPromise}) or cursor ({@link makeCursorListPromise}). The modes differ only in\n * how a walk steps from one page to the next.\n *\n * Page 1 is fetched ONCE per handle (single-flight): on a stored handle\n * (`const list = x.list(); await list; for await (const row of list) …`) the `await` and the\n * iteration reuse the same in-flight page-1 request.\n *\n * A handle is a SINGLE walk: page 1 stays cached on it, so iterating the SAME handle a second time\n * later reuses that (now-stale) page 1 while re-fetching pages 2+. For a fresh walk, call `.list()`\n * again. A rejected page 1 is NOT cached - it drops out so a later iteration re-attempts rather than\n * replaying the old failure forever.\n *\n * `fetchPage` closes over the caller's CallOptions, so `signal` / `timeoutMs` reach every page. An\n * abort mid-walk rejects the iteration BEFORE the next page's fetch (the current page's already-\n * fetched rows still drain first).\n */\nfunction makePagedList<T, Page extends { data: T[] }>(\n fetchFirst: () => Promise<Page>,\n /** Starts one walk: a step that fetches the page after `page`, or returns null after the last. */\n startWalk: () => (page: Page) => Promise<Page> | null,\n): Promise<Page> & AsyncIterable<T> & { listAll(): Promise<T[]> } {\n let firstPage: Promise<Page> | undefined;\n const first = (): Promise<Page> => {\n if (!firstPage) {\n const p = fetchFirst();\n firstPage = p;\n // Don't cache a rejected page 1 (a later walk re-attempts instead of replaying the failure),\n // and - since page 1 is fetched EAGERLY below - this attached handler also keeps a page-1\n // rejection on an un-awaited handle from surfacing as an unhandled rejection.\n p.catch(() => {\n if (firstPage === p) firstPage = undefined;\n });\n }\n return firstPage;\n };\n\n async function* iterate(): AsyncGenerator<T> {\n const next = startWalk();\n let page: Page | null = await first();\n while (page) {\n yield* page.data;\n const following = next(page);\n page = following ? await following : null;\n }\n }\n\n const listAll = async (): Promise<T[]> => {\n const out: T[] = [];\n for await (const item of iterate()) out.push(item);\n return out;\n };\n\n return Object.assign(first(), {\n [Symbol.asyncIterator]: iterate,\n listAll,\n });\n}\n\n/**\n * Offset mode: iteration walks forward by `offset`, requesting each next page at the server's\n * effective (clamped) page size, and stops as soon as a page comes back SHORTER than that size -\n * it never reads `total`, so a concurrent insert/delete can't make it skip or loop.\n */\nexport function makeListPromise<T, P extends { limit?: number; offset?: number }>(\n fetchPage: (params: P) => Promise<Paginated<T>>,\n params: P,\n): ListPromise<T> {\n return makePagedList(\n () => fetchPage(params),\n () => {\n let limit: number | undefined;\n let offset = params.offset ?? 0;\n return (page) => {\n // Page forward by the server's ECHOED (clamped) page size - never by params.limit, which\n // the server may have clamped down (e.g. 5000 -> 100). Fall back to the requested limit\n // only if a server fails to echo one, so a full page never silently truncates the walk.\n limit ??= page.limit > 0 ? page.limit : (params.limit ?? 0);\n offset += page.data.length;\n if (!(limit > 0 && page.data.length >= limit)) return null;\n return fetchPage({ ...params, limit, offset });\n };\n },\n ) as ListPromise<T>;\n}\n\n/**\n * Cursor mode, for a list whose rows keep arriving at the head (the credit ledger): iteration\n * passes each page's `nextCursor` back as `cursor` and stops on the page whose `nextCursor` is\n * null. The server walks by keyset, so rows arriving during the walk never shift an older row onto\n * another page: nothing is skipped or repeated.\n */\nexport function makeCursorListPromise<T, P extends { limit?: number; cursor?: string }>(\n fetchPage: (params: P) => Promise<CursorPaginated<T>>,\n params: P,\n): CursorListPromise<T> {\n return makePagedList(\n () => fetchPage(params),\n () => (page) =>\n page.nextCursor === null\n ? null\n : fetchPage({ ...params, limit: page.limit, cursor: page.nextCursor }),\n ) as CursorListPromise<T>;\n}\n","import {\n apiRequest,\n apiRequestBinary,\n apiRequestWithStatus,\n type RequestContext,\n toQuery,\n} from \"../client\";\nimport { makeListPromise } from \"../pagination\";\nimport type {\n CallOptions,\n Charge,\n ChargeListItem,\n ChargeListParams,\n CheckoutMethodInfo,\n CreateChargeInput,\n CreateMerchantInitiatedChargeInput,\n IdempotentRequestOptions,\n ListPromise,\n Paginated,\n Refund,\n RefundChargeInput,\n RefundRequestResult,\n RequestOptions,\n ResolveRefundInput,\n} from \"../types\";\n\nexport function createChargesResource(ctx: RequestContext) {\n return {\n /** Create a customer-present charge -> returns a hosted checkout URL. Pass an\n * `idempotencyKey` to make the create safe to retry (with `maxRetries`). */\n create: (input: CreateChargeInput, options?: RequestOptions) =>\n apiRequest<Charge>(ctx, \"POST\", \"/v1/charges\", input, options),\n /** Charge the customer's current saved card without customer presence. */\n createMerchantInitiated: (\n input: CreateMerchantInitiatedChargeInput,\n options: IdempotentRequestOptions,\n ) => apiRequest<Charge>(ctx, \"POST\", \"/v1/charges/mit\", input, options),\n /** Fetch a charge. Pass `{ sync: true }` to force an authoritative provider pull. */\n get: (id: string, opts?: { sync?: boolean } & CallOptions) =>\n apiRequest<Charge>(\n ctx,\n \"GET\",\n `/v1/charges/${encodeURIComponent(id)}${opts?.sync ? \"?sync=true\" : \"\"}`,\n undefined,\n opts,\n ),\n /** List charges (paginated). Filters: status, currency, customer (external id), from, to. */\n list: (params: ChargeListParams = {}, options?: CallOptions): ListPromise<ChargeListItem> =>\n makeListPromise(\n (p) =>\n apiRequest<Paginated<ChargeListItem>>(\n ctx,\n \"GET\",\n `/v1/charges${toQuery(p)}`,\n undefined,\n options,\n ),\n params,\n ),\n /** Download the one-off charge's receipt as a PDF (raw bytes). */\n receipt: (id: string, options?: CallOptions) =>\n apiRequestBinary(ctx, \"GET\", `/v1/charges/${encodeURIComponent(id)}/receipt.pdf`, options),\n /** Download the immutable credit note for a succeeded refund. */\n creditNote: (chargeId: string, refundId: string, options?: CallOptions) =>\n apiRequestBinary(\n ctx,\n \"GET\",\n `/v1/charges/${encodeURIComponent(chargeId)}/refunds/${encodeURIComponent(refundId)}/credit-note.pdf`,\n options,\n ),\n /**\n * Refund a succeeded charge: `{ amount }` (minor units) for a partial, `{}` for its whole\n * remaining balance. The `idempotencyKey` is required and must identify this one refund\n * (e.g. your own refund request's id): a retry under it - yours, or the SDK's own\n * `maxRetries` - answers the same refund, in whatever status, instead of refunding again.\n * Reuse the key whenever the outcome is unknown (a timeout or dropped connection); a new\n * key asks for a new refund, e.g. after this one `failed`. `replayed` tells the refund an\n * earlier request under the key made (`true`) from one this call made (`false`).\n *\n * Always check `status`: resolving does not mean refunded. A provider that declines the\n * refund answers `502 provider_error`, which throws with `maxRetries: 0` (the default); with\n * `maxRetries > 0` the SDK retries that 502 under the same key, so the call resolves instead\n * with the declined refund replayed: `status: \"failed\"`, `replayed: true`.\n */\n refund: async (\n chargeId: string,\n input: RefundChargeInput,\n options: IdempotentRequestOptions,\n ): Promise<RefundRequestResult> => {\n const { status, data } = await apiRequestWithStatus<Refund>(\n ctx,\n \"POST\",\n `/v1/charges/${encodeURIComponent(chargeId)}/refund`,\n input,\n options,\n );\n // The API answers 201 for a refund it made, 200 for the key's earlier refund.\n return { ...data, replayed: status === 200 };\n },\n /** A charge's refunds, newest first (`needsReview` flags one awaiting an Operator). */\n listRefunds: (chargeId: string, options?: CallOptions) =>\n apiRequest<{ data: Refund[] }>(\n ctx,\n \"GET\",\n `/v1/charges/${encodeURIComponent(chargeId)}/refunds`,\n undefined,\n options,\n ),\n /** Reconcile a pending refund with the provider now; resolves to the refund as it stands. */\n recheckRefund: (chargeId: string, refundId: string, options?: CallOptions) =>\n apiRequest<Refund>(\n ctx,\n \"POST\",\n `${refundPath(chargeId, refundId)}/recheck`,\n undefined,\n options,\n ),\n /**\n * Record the outcome you verified in the provider dashboard for a refund awaiting review\n * (`needsReview`): `succeeded` settles it with a credit note, `failed` releases its amount.\n * A refund with a provider conflict (`providerConflictStatus`) resolves only as `succeeded`.\n */\n resolveRefund: (\n chargeId: string,\n refundId: string,\n input: ResolveRefundInput,\n options?: CallOptions,\n ) =>\n apiRequest<Refund>(ctx, \"POST\", `${refundPath(chargeId, refundId)}/resolve`, input, options),\n };\n}\n\nfunction refundPath(chargeId: string, refundId: string): string {\n return `/v1/charges/${encodeURIComponent(chargeId)}/refunds/${encodeURIComponent(refundId)}`;\n}\n\nexport function createCheckoutMethodsResource(ctx: RequestContext) {\n return {\n /** The customer-present methods + fees offered for a currency (for a method picker). */\n list: (params: { currency: string }, options?: CallOptions) =>\n apiRequest<{ methods: CheckoutMethodInfo[] }>(\n ctx,\n \"GET\",\n `/v1/checkout-methods${toQuery(params)}`,\n undefined,\n options,\n ),\n };\n}\n","import { apiRequest, apiRequestWithStatus, type RequestContext, toQuery } from \"../client\";\nimport { makeCursorListPromise } from \"../pagination\";\nimport type {\n CallOptions,\n CreateCreditGrantInput,\n CreateCreditPackInput,\n CreateCreditQuoteInput,\n CreateCreditReservationInput,\n CreateCreditTopUpInput,\n CreditBalance,\n CreditGrant,\n CreditGrantRequestResult,\n CreditLedgerEntry,\n CreditLineItem,\n CreditPack,\n CreditPacks,\n CreditQuote,\n CreditRateCard,\n CreditReservation,\n CreditReservationRequestResult,\n CreditReversal,\n CreditReversalRequestResult,\n CreditTopUp,\n CreditTopUpListParams,\n CreditTopUpRequestResult,\n CreditUsage,\n CreditUsageParams,\n CursorListParams,\n CursorListPromise,\n CursorPaginated,\n IdempotentRequestOptions,\n PublishCreditRateCardInput,\n ReverseCreditConsumptionInput,\n UpdateCreditPackInput,\n} from \"../types\";\n\nexport function createCreditsResource(ctx: RequestContext) {\n return {\n grants: {\n /**\n * Grant prepaid credits to a Customer. The `idempotencyKey` is required and must identify\n * this one grant (e.g. your own promotion or support-ticket id): a retry under it - yours,\n * or the SDK's own `maxRetries` - answers the same grant instead of granting twice, with\n * `replayed: true`. Reusing the key for a different grant throws `idempotency_conflict`\n * (409). Credit quantities are decimal strings of microcredits in both directions.\n */\n create: async (\n input: CreateCreditGrantInput,\n options: IdempotentRequestOptions,\n ): Promise<CreditGrantRequestResult> => {\n const { status, data } = await apiRequestWithStatus<CreditGrant>(\n ctx,\n \"POST\",\n \"/v1/credits/grants\",\n input,\n options,\n );\n // The API answers 201 for a grant it made, 200 for the key's earlier grant.\n return { ...data, replayed: status === 200 };\n },\n },\n packs: {\n /**\n * The Credit Packs a customer can buy in `currency` (ISO 4217), cheapest first: credits and\n * bonus (decimal strings of microcredits), price (minor units), and the derived\n * `pricePerCredit` and `savingsBps` - so your pricing page never hardcodes a price.\n */\n list: (currency: string, options?: CallOptions) =>\n apiRequest<CreditPacks>(\n ctx,\n \"GET\",\n `/v1/credits/packs${toQuery({ currency })}`,\n undefined,\n options,\n ),\n /** Configure a Credit Pack on a one-time catalog Price. */\n create: (input: CreateCreditPackInput, options?: CallOptions) =>\n apiRequest<CreditPack>(ctx, \"POST\", \"/v1/credits/packs\", input, options),\n /** A Credit Pack's configuration, archived or not. */\n get: (packId: string, options?: CallOptions) =>\n apiRequest<CreditPack>(\n ctx,\n \"GET\",\n `/v1/credits/packs/${encodeURIComponent(packId)}`,\n undefined,\n options,\n ),\n /** Edit a pack's terms or Price, or archive it; top-ups already made keep their terms. */\n update: (packId: string, input: UpdateCreditPackInput, options?: CallOptions) =>\n apiRequest<CreditPack>(\n ctx,\n \"PATCH\",\n `/v1/credits/packs/${encodeURIComponent(packId)}`,\n input,\n options,\n ),\n },\n topUps: {\n /**\n * Buy a Credit Pack for a customer: answers the top-up with `checkoutUrl`, the hosted\n * checkout to send the buyer to. Credits are granted when the payment succeeds (listen for\n * `credit_top_up.succeeded`). The `idempotencyKey` is required and must identify this one\n * purchase: a retry under it answers the same top-up as it now stands (`replayed: true`) and\n * buys nothing again - asking the payment provider again for a checkout the first attempt\n * could not open, within its page's 40 minutes (Stripe only in the first 10, while 30\n * remain: it answers a timed-out first attempt with the checkout it made, or makes one never\n * made; Paymob only if the first attempt never made one); reusing it for another purchase\n * throws `idempotency_conflict` (409). A retry can also throw `conflict` (409), with\n * `details.reason`: `checkout_in_progress` - another request is still opening the\n * checkout, so retry the same key shortly - or `checkout_unavailable` - its checkout could\n * not be opened and never will be, so buy again under a new key.\n */\n create: async (\n input: CreateCreditTopUpInput,\n options: IdempotentRequestOptions,\n ): Promise<CreditTopUpRequestResult> => {\n const { status, data } = await apiRequestWithStatus<CreditTopUp>(\n ctx,\n \"POST\",\n \"/v1/credits/top-ups\",\n input,\n options,\n );\n return { ...data, replayed: status === 200 };\n },\n /** A top-up as it now stands: status, checkout, grants, and what refunds revoked. */\n get: (topUpId: string, options?: CallOptions) =>\n apiRequest<CreditTopUp>(\n ctx,\n \"GET\",\n `/v1/credits/top-ups/${encodeURIComponent(topUpId)}`,\n undefined,\n options,\n ),\n /**\n * A customer's top-ups (by external id), newest first, optionally of one status.\n * Auto-paginating by cursor: `await` the first page, `for await (…)` every top-up, or\n * `.listAll()` to collect them.\n */\n list: (\n customer: string,\n params: CreditTopUpListParams = {},\n options?: CallOptions,\n ): CursorListPromise<CreditTopUp> => {\n const { status, ...page } = params;\n return makeCursorListPromise(\n (p) =>\n apiRequest<CursorPaginated<CreditTopUp>>(\n ctx,\n \"GET\",\n `/v1/credits/top-ups${toQuery({ customer, status, ...p })}`,\n undefined,\n options,\n ),\n page,\n );\n },\n },\n balance: {\n /**\n * A Customer's credit balance (by external id): spendable, held, consumed this period,\n * expiring soon, by kind and category, the current period and the threshold level, true at\n * `asOf`. A Customer with no credit account yet reads as zeros.\n */\n get: (customer: string, options?: CallOptions) =>\n apiRequest<CreditBalance>(\n ctx,\n \"GET\",\n `/v1/credits/balance${toQuery({ customer })}`,\n undefined,\n options,\n ),\n },\n ledger: {\n /**\n * A Customer's credit ledger (by external id), newest first. Auto-paginating by cursor:\n * `await` the first page, `for await (…)` every entry, or `.listAll()` to collect them -\n * entries arriving meanwhile never make the walk skip or repeat one.\n */\n list: (\n customer: string,\n params: CursorListParams = {},\n options?: CallOptions,\n ): CursorListPromise<CreditLedgerEntry> =>\n makeCursorListPromise(\n (p) =>\n apiRequest<CursorPaginated<CreditLedgerEntry>>(\n ctx,\n \"GET\",\n `/v1/credits/ledger${toQuery({ customer, ...p })}`,\n undefined,\n options,\n ),\n params,\n ),\n },\n usage: {\n /**\n * A Customer's credit consumption (by external id) per UTC day, by Credit Action or\n * category, over at most 92 days (the 30 ending today by default).\n */\n get: (customer: string, params: CreditUsageParams = {}, options?: CallOptions) =>\n apiRequest<CreditUsage>(\n ctx,\n \"GET\",\n `/v1/credits/usage${toQuery({ customer, ...params })}`,\n undefined,\n options,\n ),\n },\n rateCards: {\n /**\n * Publish a new Rate Card version: what each Credit Action costs, as\n * `ceil(units * unitPrice / perUnits)` microcredits a line. Versions are immutable - a price\n * change is a new version - and take effect in order, at `effectiveAt` (now when omitted).\n */\n publish: (input: PublishCreditRateCardInput, options?: CallOptions) =>\n apiRequest<CreditRateCard>(ctx, \"POST\", \"/v1/credits/rate-cards\", input, options),\n /** The version in effect now (`not_found` before the first takes effect). */\n current: (options?: CallOptions) =>\n apiRequest<CreditRateCard>(\n ctx,\n \"GET\",\n \"/v1/credits/rate-cards/current\",\n undefined,\n options,\n ),\n /** One version, by its number. */\n get: (version: number, options?: CallOptions) =>\n apiRequest<CreditRateCard>(\n ctx,\n \"GET\",\n `/v1/credits/rate-cards/${encodeURIComponent(String(version))}`,\n undefined,\n options,\n ),\n /**\n * The published versions, newest first. Auto-paginating by cursor: `await` the first page,\n * `for await (…)` every version, or `.listAll()` to collect them.\n */\n list: (\n params: CursorListParams = {},\n options?: CallOptions,\n ): CursorListPromise<CreditRateCard> =>\n makeCursorListPromise(\n (p) =>\n apiRequest<CursorPaginated<CreditRateCard>>(\n ctx,\n \"GET\",\n `/v1/credits/rate-cards${toQuery(p)}`,\n undefined,\n options,\n ),\n params,\n ),\n },\n quotes: {\n /**\n * Price a customer's Credit Actions (all of one category) at the current Rate Card version\n * and keep the price for 15 minutes: a reservation over the quote holds exactly its\n * `amount`, and its commit prices at the version the quote pinned. A quote holds nothing.\n */\n create: (input: CreateCreditQuoteInput, options?: CallOptions) =>\n apiRequest<CreditQuote>(ctx, \"POST\", \"/v1/credits/quotes\", input, options),\n /** A quote as it was made. */\n get: (quoteId: string, options?: CallOptions) =>\n apiRequest<CreditQuote>(\n ctx,\n \"GET\",\n `/v1/credits/quotes/${encodeURIComponent(quoteId)}`,\n undefined,\n options,\n ),\n },\n reservations: {\n /**\n * Hold credits for one operation: over a `quoteId`, or over `items` priced at the current\n * Rate Card version. The `idempotencyKey` is required: a retry under it - after a lost\n * reply, even once the quote expired - answers the same reservation (`replayed: true`) and\n * holds nothing again. Reusing it for another request, or a new key with an `operationKey`\n * the customer already used (`details.reason: \"operation_key_used\"`), throws\n * `idempotency_conflict` (409). Throws `insufficient_credits` (402), `account_frozen`\n * (423), `account_closed` (409), `conflict` (409, `details.reason: \"quote_expired\"`), or\n * `validation_error` (422) - e.g. `details.reason: \"zero_amount\"` when the items cost nothing.\n * The `operationKey` is an operation id, never personal data: erasure replaces it.\n */\n create: async (\n input: CreateCreditReservationInput,\n options: IdempotentRequestOptions,\n ): Promise<CreditReservationRequestResult> => {\n const { status, data } = await apiRequestWithStatus<CreditReservation>(\n ctx,\n \"POST\",\n \"/v1/credits/reservations\",\n input,\n options,\n );\n return { ...data, replayed: status === 200 };\n },\n /** A reservation as it now stands. */\n get: (reservationId: string, options?: CallOptions) =>\n apiRequest<CreditReservation>(\n ctx,\n \"GET\",\n `/v1/credits/reservations/${encodeURIComponent(reservationId)}`,\n undefined,\n options,\n ),\n /**\n * A customer's reservation (by external id) made with `operationKey` - how to find one whose\n * reply was lost. Throws `not_found` (404) when there is none.\n */\n findByOperationKey: (customer: string, operationKey: string, options?: CallOptions) =>\n apiRequest<CreditReservation>(\n ctx,\n \"GET\",\n `/v1/credits/reservations${toQuery({ customer, operationKey })}`,\n undefined,\n options,\n ),\n /**\n * Commit what the operation used: lines priced at the reservation's Rate Card version,\n * consuming at most what it holds (`commit_exceeds_hold`, 409) and releasing the rest; lines\n * that cost nothing in all consume nothing (`consumed: \"0\"`, `consumptionId: null`). The\n * same commit again answers it again, so it is safe to retry; anything else after it throws\n * `invalid_state_transition` (409) with the reservation in `details` - with\n * `details.reason: \"reservation_expired\"` once the hold is past its `expiresAt`.\n */\n commit: (reservationId: string, items: CreditLineItem[], options?: CallOptions) =>\n apiRequest<CreditReservation>(\n ctx,\n \"POST\",\n `/v1/credits/reservations/${encodeURIComponent(reservationId)}/commit`,\n { items },\n options,\n ),\n /** Release the whole hold. Safe to retry; after a commit it throws (409). */\n release: (reservationId: string, options?: CallOptions) =>\n apiRequest<CreditReservation>(\n ctx,\n \"POST\",\n `/v1/credits/reservations/${encodeURIComponent(reservationId)}/release`,\n undefined,\n options,\n ),\n /**\n * Protect a held reservation whose operation was paid for and is still being fulfilled: it\n * never expires (commit or release it when done). Safe to retry. A hold already past its\n * `expiresAt` throws `invalid_state_transition` (409, `details.reason: \"reservation_expired\"`).\n */\n protect: (reservationId: string, options?: CallOptions) =>\n apiRequest<CreditReservation>(\n ctx,\n \"POST\",\n `/v1/credits/reservations/${encodeURIComponent(reservationId)}/protect`,\n undefined,\n options,\n ),\n },\n consumptions: {\n /**\n * Give back part or all of a commit's consumption (`consumptionId` on the committed\n * reservation), never more than is left (`reversal_exceeds_consumption`, 409). The\n * `idempotencyKey` is required: a retry under it answers the same reversal\n * (`replayed: true`) and gives nothing back again.\n */\n reverse: async (\n consumptionId: string,\n input: ReverseCreditConsumptionInput,\n options: IdempotentRequestOptions,\n ): Promise<CreditReversalRequestResult> => {\n const { status, data } = await apiRequestWithStatus<CreditReversal>(\n ctx,\n \"POST\",\n `/v1/credits/consumptions/${encodeURIComponent(consumptionId)}/reverse`,\n input,\n options,\n );\n return { ...data, replayed: status === 200 };\n },\n },\n };\n}\n","import { apiRequest, type RequestContext, toQuery } from \"../client\";\nimport { makeListPromise } from \"../pagination\";\nimport type {\n CallOptions,\n Customer,\n CustomerAnonymizationResult,\n CustomerDataExport,\n CustomerListItem,\n CustomerListParams,\n CustomerOverview,\n ListPromise,\n Paginated,\n SavedPaymentMethod,\n} from \"../types\";\n\nexport function createCustomersResource(ctx: RequestContext) {\n return {\n create: (input: {\n id: string;\n name?: string;\n email?: string;\n phone?: string;\n /** The customer's tax / VAT registration number, recorded on their invoices. */\n taxId?: string;\n }) => apiRequest<Customer>(ctx, \"POST\", \"/v1/customers\", input),\n get: (externalId: string, options?: CallOptions) =>\n apiRequest<Customer>(\n ctx,\n \"GET\",\n `/v1/customers/${encodeURIComponent(externalId)}`,\n undefined,\n options,\n ),\n /** List customers (`q` searches external id / email / name). Auto-paginating: `await` the\n * first page, `for await (…)` every page, or `.listAll()` to collect them. */\n list: (params: CustomerListParams = {}, options?: CallOptions): ListPromise<CustomerListItem> =>\n makeListPromise(\n (p) =>\n apiRequest<Paginated<CustomerListItem>>(\n ctx,\n \"GET\",\n `/v1/customers${toQuery(p)}`,\n undefined,\n options,\n ),\n params,\n ),\n /** Full per-customer view: profile + subscriptions + charges + cards + balances. */\n overview: (externalId: string, options?: CallOptions) =>\n apiRequest<CustomerOverview>(\n ctx,\n \"GET\",\n `/v1/customers/${encodeURIComponent(externalId)}/overview`,\n undefined,\n options,\n ),\n paymentMethods: {\n list: (customer: string, options?: CallOptions) =>\n apiRequest<{ paymentMethods: SavedPaymentMethod[] }>(\n ctx,\n \"GET\",\n `/v1/customers/${encodeURIComponent(customer)}/payment-methods`,\n undefined,\n options,\n ).then((r) => r.paymentMethods),\n setDefault: (customer: string, id: string) =>\n apiRequest<SavedPaymentMethod>(\n ctx,\n \"POST\",\n `/v1/customers/${encodeURIComponent(customer)}/payment-methods/${encodeURIComponent(id)}/default`,\n ),\n remove: (customer: string, id: string) =>\n apiRequest<{ removed: boolean }>(\n ctx,\n \"DELETE\",\n `/v1/customers/${encodeURIComponent(customer)}/payment-methods/${encodeURIComponent(id)}`,\n ),\n },\n /** Export all portable customer data held by Billow. Secret-key only. */\n exportData: (externalId: string, options?: CallOptions) =>\n apiRequest<CustomerDataExport>(\n ctx,\n \"GET\",\n `/v1/customers/${encodeURIComponent(externalId)}/export`,\n undefined,\n options,\n ),\n /** Anonymize PII after access-granting subscriptions have ended. Secret-key only. */\n anonymize: (externalId: string, options?: CallOptions) =>\n apiRequest<CustomerAnonymizationResult>(\n ctx,\n \"DELETE\",\n `/v1/customers/${encodeURIComponent(externalId)}`,\n undefined,\n options,\n ),\n };\n}\n","import { apiRequest, type RequestContext, toQuery } from \"../client\";\nimport { makeListPromise } from \"../pagination\";\nimport type {\n CallOptions,\n EmailDeliveryListItem,\n EmailDeliveryListParams,\n InboundWebhookListItem,\n InboundWebhookListParams,\n ListPromise,\n OutboxEventListItem,\n OutboxEventListParams,\n Paginated,\n} from \"../types\";\n\n/**\n * Delivery-failure visibility: the transactional emails and outbound events that\n * didn't get through. Read-only, tenant-scoped to the key's (project, environment).\n */\nexport function createDeliverabilityResource(ctx: RequestContext) {\n return {\n /** Email deliveries (newest first), optionally filtered by status. Auto-paginating. */\n emails: (\n params: EmailDeliveryListParams = {},\n options?: CallOptions,\n ): ListPromise<EmailDeliveryListItem> =>\n makeListPromise(\n (p) =>\n apiRequest<Paginated<EmailDeliveryListItem>>(\n ctx,\n \"GET\",\n `/v1/deliverability/emails${toQuery(p)}`,\n undefined,\n options,\n ),\n params,\n ),\n /** Outbound events (newest first), optionally filtered by status. Auto-paginating. */\n events: (\n params: OutboxEventListParams = {},\n options?: CallOptions,\n ): ListPromise<OutboxEventListItem> =>\n makeListPromise(\n (p) =>\n apiRequest<Paginated<OutboxEventListItem>>(\n ctx,\n \"GET\",\n `/v1/deliverability/events${toQuery(p)}`,\n undefined,\n options,\n ),\n params,\n ),\n /** Inbound provider webhooks (newest first), optionally filtered by outcome. Auto-paginating. */\n inbound: (\n params: InboundWebhookListParams = {},\n options?: CallOptions,\n ): ListPromise<InboundWebhookListItem> =>\n makeListPromise(\n (p) =>\n apiRequest<Paginated<InboundWebhookListItem>>(\n ctx,\n \"GET\",\n `/v1/deliverability/inbound${toQuery(p)}`,\n undefined,\n options,\n ),\n params,\n ),\n };\n}\n","import { apiRequest, type RequestContext } from \"../client\";\nimport type {\n CallOptions,\n CreateHostedDomainInput,\n HostedDomain,\n HostedDomainList,\n} from \"../types\";\n\nconst path = (id: string, action = \"\") => `/v1/hosted-domains/${encodeURIComponent(id)}${action}`;\n\n/**\n * Custom domains for the hosted customer portal (live keys only, behind a per-Project rollout\n * flag). Add a hostname, create the two DNS records it answers, and Billow verifies them.\n */\nexport function createHostedDomainsResource(ctx: RequestContext) {\n return {\n /** The Project's domains, and whether its plan allows adding more (`whiteLabel`). */\n list: (options?: CallOptions) =>\n apiRequest<HostedDomainList>(ctx, \"GET\", \"/v1/hosted-domains\", undefined, options),\n /**\n * Add a subdomain such as `billing.example.com`. Answers the domain with the TXT and CNAME\n * `records` to create. Needs a plan with white-label branding (`permission_denied` otherwise).\n */\n create: (input: CreateHostedDomainInput, options?: CallOptions) =>\n apiRequest<HostedDomain>(ctx, \"POST\", \"/v1/hosted-domains\", input, options),\n get: (id: string, options?: CallOptions) =>\n apiRequest<HostedDomain>(ctx, \"GET\", path(id), undefined, options),\n /** Check the DNS records now (2 per minute per domain); answers the refreshed domain. */\n verify: (id: string, options?: CallOptions) =>\n apiRequest<HostedDomain>(ctx, \"POST\", path(id, \"/verify\"), undefined, options),\n /** Make an active domain the default host for new portal sessions. */\n makePrimary: (id: string, options?: CallOptions) =>\n apiRequest<HostedDomain>(ctx, \"POST\", path(id, \"/primary\"), undefined, options),\n /** Remove a domain; the portal sessions on it end immediately. */\n remove: (id: string, options?: CallOptions) =>\n apiRequest<{ id: string; hostname: string; removed: true }>(\n ctx,\n \"DELETE\",\n path(id),\n undefined,\n options,\n ),\n };\n}\n","import { apiRequest, apiRequestBinary, type RequestContext, toQuery } from \"../client\";\nimport { makeListPromise } from \"../pagination\";\nimport type {\n CallOptions,\n ExternalPaymentResult,\n InvoiceDetail,\n InvoiceListItem,\n InvoiceListParams,\n InvoicePaymentResult,\n ListPromise,\n Paginated,\n PayInvoiceInput,\n RecordExternalPaymentInput,\n} from \"../types\";\n\nexport function createInvoicesResource(ctx: RequestContext) {\n return {\n /** List invoices. Filters: status, customer (external id), from, to. Auto-paginating. */\n list: (params: InvoiceListParams = {}, options?: CallOptions): ListPromise<InvoiceListItem> =>\n makeListPromise(\n (p) =>\n apiRequest<Paginated<InvoiceListItem>>(\n ctx,\n \"GET\",\n `/v1/invoices${toQuery(p)}`,\n undefined,\n options,\n ),\n params,\n ),\n /** Fetch an invoice with its line items. */\n get: (id: string, options?: CallOptions) =>\n apiRequest<InvoiceDetail>(\n ctx,\n \"GET\",\n `/v1/invoices/${encodeURIComponent(id)}`,\n undefined,\n options,\n ),\n /**\n * Record that an open invoice was paid outside the gateway (bank transfer, cash, cheque).\n * Settles the invoice and advances the subscription exactly like a gateway payment.\n * `amount` must equal the invoice total. Operator (secret key) only.\n */\n recordPayment: (id: string, input: RecordExternalPaymentInput) =>\n apiRequest<ExternalPaymentResult>(\n ctx,\n \"POST\",\n `/v1/invoices/${encodeURIComponent(id)}/record-payment`,\n input,\n ),\n /** Open or resume hosted checkout for an existing outstanding invoice. */\n pay: (id: string, input: PayInvoiceInput = {}, options?: CallOptions) =>\n apiRequest<InvoicePaymentResult>(\n ctx,\n \"POST\",\n `/v1/invoices/${encodeURIComponent(id)}/pay`,\n input,\n options,\n ),\n /** Download the invoice as a PDF (raw bytes). */\n pdf: (id: string, options?: CallOptions) =>\n apiRequestBinary(ctx, \"GET\", `/v1/invoices/${encodeURIComponent(id)}/pdf`, options),\n /** Download the invoice's payment receipt as a PDF (raw bytes; 404 if unpaid). */\n receipt: (id: string, options?: CallOptions) =>\n apiRequestBinary(ctx, \"GET\", `/v1/invoices/${encodeURIComponent(id)}/receipt.pdf`, options),\n };\n}\n","import { apiRequest, type RequestContext } from \"../client\";\nimport type { CallOptions, CatalogItem } from \"../types\";\n\n/** The marketplace Integration catalog — install / configure / toggle / uninstall (ADR-0008). */\nexport function createMarketplaceResource(ctx: RequestContext) {\n return {\n /** Every available Integration with this tenant's install state (no secret values). */\n catalog: (options?: CallOptions) =>\n apiRequest<{ catalog: CatalogItem[] }>(\n ctx,\n \"GET\",\n \"/v1/marketplace\",\n undefined,\n options,\n ).then((r) => r.catalog),\n /** One catalog entry by slug. */\n get: (slug: string, options?: CallOptions) =>\n apiRequest<{ item: CatalogItem }>(\n ctx,\n \"GET\",\n `/v1/marketplace/${encodeURIComponent(slug)}`,\n undefined,\n options,\n ).then((r) => r.item),\n /** Install or reconfigure an Integration; `values` are the manifest form's field values. */\n upsert: (slug: string, values: Record<string, unknown>) =>\n apiRequest<{ item: CatalogItem }>(ctx, \"PUT\", `/v1/marketplace/${encodeURIComponent(slug)}`, {\n values,\n }).then((r) => r.item),\n /** Enable or disable an installed Integration. */\n setEnabled: (slug: string, enabled: boolean) =>\n apiRequest<{ item: CatalogItem }>(\n ctx,\n \"POST\",\n `/v1/marketplace/${encodeURIComponent(slug)}/enabled`,\n { enabled },\n ).then((r) => r.item),\n /** Uninstall an Integration. */\n remove: (slug: string) =>\n apiRequest<{ removed: boolean }>(\n ctx,\n \"DELETE\",\n `/v1/marketplace/${encodeURIComponent(slug)}`,\n ),\n /**\n * Verify an installed Integration's config. An email Integration sends a test\n * message to `to` (returns `{ sent, to }`); an accounting Integration runs a\n * non-mutating connectivity check with no recipient (returns `{ ok: true }`).\n */\n test: (slug: string, to?: string) =>\n apiRequest<{ sent: boolean; to: string } | { ok: true }>(\n ctx,\n \"POST\",\n `/v1/marketplace/${encodeURIComponent(slug)}/test`,\n to ? { to } : {},\n ),\n };\n}\n","import { apiRequest, type RequestContext, toQuery } from \"../client\";\nimport type {\n CallOptions,\n MetricsOverview,\n MetricsParams,\n MetricsRollup,\n TimeseriesParams,\n TimeseriesResult,\n} from \"../types\";\n\nexport function createMetricsResource(ctx: RequestContext) {\n return {\n /** KPI cards for a currency over a window (`from`/`to` default to the last 30 days). */\n overview: (params: MetricsParams = {}, options?: CallOptions) =>\n apiRequest<MetricsOverview>(\n ctx,\n \"GET\",\n `/v1/metrics/overview${toQuery(params)}`,\n undefined,\n options,\n ),\n /** A single bucketed metric (revenue / mrr / subs / success rate) over a window. */\n timeseries: (params: TimeseriesParams = {}, options?: CallOptions) =>\n apiRequest<TimeseriesResult>(\n ctx,\n \"GET\",\n `/v1/metrics/timeseries${toQuery(params)}`,\n undefined,\n options,\n ),\n /**\n * KPIs rolled up into the org's reporting currency across all billing currencies\n * (Phase H). Resolves to `null` when no reporting currency is configured.\n */\n rollup: (params: { from?: string; to?: string } = {}, options?: CallOptions) =>\n apiRequest<{ rollup: MetricsRollup | null }>(\n ctx,\n \"GET\",\n `/v1/metrics/rollup${toQuery(params)}`,\n undefined,\n options,\n ).then((r) => r.rollup),\n };\n}\n","import { apiRequest, type RequestContext } from \"../client\";\nimport type { CreatePortalSessionInput, PortalSession } from \"../types\";\n\nexport function createPortalSessionsResource(ctx: RequestContext) {\n return {\n create: (input: CreatePortalSessionInput) =>\n apiRequest<PortalSession>(ctx, \"POST\", \"/v1/portal-sessions\", input),\n };\n}\n","import { apiRequest, type RequestContext } from \"../client\";\nimport type {\n CallOptions,\n CreateProductInput,\n MigrationResult,\n Product,\n UpdateProductInput,\n} from \"../types\";\n\nexport function createProductsResource(ctx: RequestContext) {\n return {\n /** Define a product (its first active version + prices + entitlements). */\n create: (input: CreateProductInput) => apiRequest<Product>(ctx, \"POST\", \"/v1/products\", input),\n /**\n * Update a product: rename, archive/unarchive, and/or edit its prices +\n * entitlements in place.\n */\n update: (slug: string, input: UpdateProductInput) =>\n apiRequest<Product>(ctx, \"PATCH\", `/v1/products/${encodeURIComponent(slug)}`, input),\n /** Fetch a product (active version + prices + entitlements) by slug. */\n get: (slug: string, options?: CallOptions) =>\n apiRequest<Product>(\n ctx,\n \"GET\",\n `/v1/products/${encodeURIComponent(slug)}`,\n undefined,\n options,\n ),\n /** List products. `includeArchived` also returns archived ones (for admin views). */\n list: (params: { includeArchived?: boolean } = {}, options?: CallOptions) =>\n apiRequest<{ products: Product[] }>(\n ctx,\n \"GET\",\n `/v1/products${params.includeArchived ? \"?includeArchived=true\" : \"\"}`,\n undefined,\n options,\n ).then((r) => r.products),\n /** Delete a plan (soft-delete, ADR-0015). */\n delete: (slug: string) =>\n apiRequest<void>(ctx, \"DELETE\", `/v1/products/${encodeURIComponent(slug)}`),\n /** Migrate every live subscriber of `fromSlug` onto `toSlug`. */\n migrateSubscribers: (fromSlug: string, toSlug: string) =>\n apiRequest<MigrationResult>(\n ctx,\n \"POST\",\n `/v1/products/${encodeURIComponent(fromSlug)}/migrate-subscribers`,\n { toSlug },\n ),\n /** Live-subscriber count per product, keyed by product id. */\n subscriberCounts: (options?: CallOptions) =>\n apiRequest<{ counts: Record<string, number> }>(\n ctx,\n \"GET\",\n \"/v1/products/subscriber-counts\",\n undefined,\n options,\n ).then((r) => r.counts),\n };\n}\n","import { apiRequest, type RequestContext } from \"../client\";\nimport type {\n CallOptions,\n EmailTemplateSetting,\n ExchangeRate,\n UpdateEmailTemplateInput,\n} from \"../types\";\n\n/**\n * Organization settings (Phase D3, F) — the configurable dunning schedule, usage settlement grace,\n * the cross-currency reporting currency + FX-rate registry (ADR-0013), and transactional email\n * template overrides (PRD-10). All secret-key/server-side surface.\n */\nexport function createSettingsResource(ctx: RequestContext) {\n return {\n /** The dunning retry schedule: configured gaps in days (null = default), + the default. */\n dunning: {\n get: (options?: CallOptions) =>\n apiRequest<{ retryDays: number[] | null; defaultRetryDays: number[] }>(\n ctx,\n \"GET\",\n \"/v1/settings/dunning\",\n undefined,\n options,\n ),\n /** Set the retry gaps (whole days); pass `null`/`[]` to reset to the default. */\n update: (retryDays: number[] | null) =>\n apiRequest<{ retryDays: number[] | null; defaultRetryDays: number[] }>(\n ctx,\n \"PUT\",\n \"/v1/settings/dunning\",\n { retryDays },\n ),\n },\n /**\n * Usage settlement grace (hours): defers *collection* of a boundary-adjacent priced\n * calendar-meter renewal past the tz month boundary until late usage settles — the billed\n * windows/amount are unchanged, only the invoice timing shifts. `0` disables it (the default);\n * a no-op for any subscription without a priced calendar meter. Cap 72h.\n */\n usageSettlementGrace: {\n get: (options?: CallOptions) =>\n apiRequest<{ graceHours: number }>(\n ctx,\n \"GET\",\n \"/v1/settings/usage-settlement-grace\",\n undefined,\n options,\n ),\n /** Set the grace window in whole hours (0–72); `0` disables. */\n update: (graceHours: number) =>\n apiRequest<{ graceHours: number }>(ctx, \"PUT\", \"/v1/settings/usage-settlement-grace\", {\n graceHours,\n }),\n },\n /** The currency cross-currency reporting rolls up into (null = none configured). */\n reporting: {\n get: (options?: CallOptions) =>\n apiRequest<{ reportingCurrency: string | null }>(\n ctx,\n \"GET\",\n \"/v1/settings/reporting\",\n undefined,\n options,\n ),\n /** Set the reporting currency (3-letter ISO), or `null` to clear it. */\n update: (currency: string | null) =>\n apiRequest<{ reportingCurrency: string | null }>(ctx, \"PUT\", \"/v1/settings/reporting\", {\n currency,\n }),\n },\n /** The manually-maintained FX rates the per-invoice reporting snapshot draws on. */\n fxRates: {\n list: (options?: CallOptions) =>\n apiRequest<{ rates: ExchangeRate[] }>(\n ctx,\n \"GET\",\n \"/v1/settings/fx-rates\",\n undefined,\n options,\n ).then((r) => r.rates),\n /** Upsert one `base → quote` rate (`rate` is the decimal quote-per-base, > 0). */\n set: (baseCurrency: string, quoteCurrency: string, rate: number) =>\n apiRequest<ExchangeRate>(ctx, \"PUT\", \"/v1/settings/fx-rates\", {\n baseCurrency,\n quoteCurrency,\n rate,\n }),\n /** Remove a `base → quote` rate. */\n remove: (baseCurrency: string, quoteCurrency: string) =>\n apiRequest<{ removed: boolean }>(\n ctx,\n \"DELETE\",\n `/v1/settings/fx-rates?base=${encodeURIComponent(baseCurrency)}"e=${encodeURIComponent(quoteCurrency)}`,\n ),\n },\n /** Transactional email templates (PRD-10): per-template subject/message overrides. */\n emailTemplates: {\n /** Every template, merged with this project's overrides, in display order. */\n list: (options?: CallOptions) =>\n apiRequest<{ templates: EmailTemplateSetting[] }>(\n ctx,\n \"GET\",\n \"/v1/settings/email-templates\",\n undefined,\n options,\n ).then((r) => r.templates),\n /** Update one template's override (validated against its variable allowlist). */\n update: (key: string, input: UpdateEmailTemplateInput) =>\n apiRequest<{ template: EmailTemplateSetting }>(\n ctx,\n \"PUT\",\n `/v1/settings/email-templates/${encodeURIComponent(key)}`,\n input,\n ).then((r) => r.template),\n /**\n * Send a `[Test]`-prefixed sample of one template to `to`. Dashboard-only:\n * the API rejects developer keys (the dashboard restricts the recipient to\n * the signed-in operator; a developer key has no such guarantee).\n */\n test: (key: string, to: string) =>\n apiRequest<{ sent: boolean; to: string }>(\n ctx,\n \"POST\",\n `/v1/settings/email-templates/${encodeURIComponent(key)}/test`,\n { to },\n ),\n },\n };\n}\n","import { apiRequest, type RequestContext, toQuery } from \"../client\";\nimport { makeListPromise } from \"../pagination\";\nimport type {\n ActivatedSubscriptionResult,\n CallOptions,\n CreateSubscriptionInput,\n CreateSubscriptionResult,\n ListPromise,\n Paginated,\n RequestOptions,\n Subscription,\n SubscriptionDetail,\n SubscriptionItem,\n SubscriptionListItem,\n SubscriptionListParams,\n} from \"../types\";\n\nexport function createSubscriptionsResource(ctx: RequestContext) {\n return {\n /** Start a subscription -> returns the subscription plus a hosted checkout URL. `productId`\n * accepts the product's id or slug. Pass an `idempotencyKey` to make it safe to retry. */\n create: (input: CreateSubscriptionInput, options?: RequestOptions) =>\n apiRequest<CreateSubscriptionResult>(ctx, \"POST\", \"/v1/subscriptions\", input, options),\n /** Grant a free comp subscription (operator action). `productId` accepts the product's id or slug. */\n comp: (input: { customerId: string; productId: string; currency?: string }) =>\n apiRequest<ActivatedSubscriptionResult>(ctx, \"POST\", \"/v1/subscriptions\", {\n ...input,\n comp: true,\n }),\n /** List subscriptions (paginated). Filters: status, customer (external id). */\n list: (\n params: SubscriptionListParams = {},\n options?: CallOptions,\n ): ListPromise<SubscriptionListItem> =>\n makeListPromise(\n (p) =>\n apiRequest<Paginated<SubscriptionListItem>>(\n ctx,\n \"GET\",\n `/v1/subscriptions${toQuery(p)}`,\n undefined,\n options,\n ),\n params,\n ),\n get: (id: string, options?: CallOptions) =>\n apiRequest<SubscriptionDetail>(\n ctx,\n \"GET\",\n `/v1/subscriptions/${encodeURIComponent(id)}`,\n undefined,\n options,\n ),\n /**\n * The single subscription that currently determines the customer's access, resolved by\n * billow's own rule (access-granting statuses first, then newest) - or `null` if the\n * customer has none. Prefer this over picking from `list()` yourself: it avoids the\n * \"newer failed-checkout subscription shadows an older active one\" selection bug.\n */\n current: (params: { customer: string }, options?: CallOptions) =>\n apiRequest<SubscriptionDetail | null>(\n ctx,\n \"GET\",\n `/v1/subscriptions/current${toQuery(params)}`,\n undefined,\n options,\n ),\n /** Cancel — immediately, or at period end with `{ atPeriodEnd: true }`. */\n cancel: (id: string, opts?: { atPeriodEnd?: boolean }) =>\n apiRequest<Subscription>(\n ctx,\n \"POST\",\n `/v1/subscriptions/${encodeURIComponent(id)}/cancel`,\n opts ?? {},\n ),\n /** Reverse a scheduled period-end cancellation. Duplicate calls are safe. */\n resumeCancellation: (id: string) =>\n apiRequest<Subscription>(\n ctx,\n \"POST\",\n `/v1/subscriptions/${encodeURIComponent(id)}/resume-cancellation`,\n ),\n pause: (id: string) =>\n apiRequest<Subscription>(ctx, \"POST\", `/v1/subscriptions/${encodeURIComponent(id)}/pause`),\n resume: (id: string) =>\n apiRequest<Subscription>(ctx, \"POST\", `/v1/subscriptions/${encodeURIComponent(id)}/resume`),\n /** Apply a coupon to an existing subscription. */\n applyCoupon: (id: string, code: string) =>\n apiRequest<{ id: string; couponId: string; cyclesRemaining: number | null }>(\n ctx,\n \"POST\",\n `/v1/subscriptions/${encodeURIComponent(id)}/coupon`,\n { code },\n ),\n /** Change plan — immediate prorated upgrade, or downgrade scheduled for period end. `productId` accepts the product's id or slug. */\n changePlan: (id: string, productId: string) =>\n apiRequest<\n Subscription & {\n change: \"upgrade\" | \"downgrade\" | \"noop\";\n prorationInvoiceId: string | null;\n chargeStatus: string | null;\n }\n >(ctx, \"POST\", `/v1/subscriptions/${encodeURIComponent(id)}/change-plan`, { productId }),\n /** Clear a pending downgrade. Duplicate calls are safe. */\n clearScheduledPlanChange: (id: string) =>\n apiRequest<Subscription>(\n ctx,\n \"DELETE\",\n `/v1/subscriptions/${encodeURIComponent(id)}/change-plan`,\n ),\n items: {\n /** List a subscription's items (base + add-ons). */\n list: (id: string, options?: CallOptions) =>\n apiRequest<{ items: SubscriptionItem[] }>(\n ctx,\n \"GET\",\n `/v1/subscriptions/${encodeURIComponent(id)}/items`,\n undefined,\n options,\n ).then((r) => r.items),\n /** Attach an add-on Product. `productId` accepts the product's id or slug. */\n add: (id: string, productId: string, quantity?: number) =>\n apiRequest<SubscriptionItem>(\n ctx,\n \"POST\",\n `/v1/subscriptions/${encodeURIComponent(id)}/items`,\n { productId, ...(quantity != null ? { quantity } : {}) },\n ),\n /** Change an item's quantity (seats). */\n updateQuantity: (id: string, itemId: string, quantity: number) =>\n apiRequest<SubscriptionItem>(\n ctx,\n \"PATCH\",\n `/v1/subscriptions/${encodeURIComponent(id)}/items/${encodeURIComponent(itemId)}`,\n { quantity },\n ),\n /** Detach an add-on item. */\n remove: (id: string, itemId: string) =>\n apiRequest<{ removed: boolean }>(\n ctx,\n \"DELETE\",\n `/v1/subscriptions/${encodeURIComponent(id)}/items/${encodeURIComponent(itemId)}`,\n ),\n },\n };\n}\n","import { apiRequest, type RequestContext, toQuery } from \"../client\";\nimport { makeListPromise } from \"../pagination\";\nimport type {\n CallOptions,\n CreateWebhookEndpointInput,\n ListParams,\n ListPromise,\n Paginated,\n UpdateWebhookEndpointInput,\n WebhookDelivery,\n WebhookEndpoint,\n WebhookEndpointWithSecret,\n} from \"../types\";\n\nexport function createWebhookEndpointsResource(ctx: RequestContext) {\n return {\n /** Register an endpoint. The signing secret is returned once. */\n create: (input: CreateWebhookEndpointInput) =>\n apiRequest<WebhookEndpointWithSecret>(ctx, \"POST\", \"/v1/webhook-endpoints\", input),\n /** List endpoints (newest first; secrets are never returned). Auto-paginating. */\n list: (params: ListParams = {}, options?: CallOptions): ListPromise<WebhookEndpoint> =>\n makeListPromise(\n (p) =>\n apiRequest<Paginated<WebhookEndpoint>>(\n ctx,\n \"GET\",\n `/v1/webhook-endpoints${toQuery(p)}`,\n undefined,\n options,\n ),\n params,\n ),\n /** Fetch one endpoint by id. */\n get: (id: string, options?: CallOptions) =>\n apiRequest<WebhookEndpoint>(\n ctx,\n \"GET\",\n `/v1/webhook-endpoints/${encodeURIComponent(id)}`,\n undefined,\n options,\n ),\n /** Update an endpoint's URL, enabled flag, or event filter. */\n update: (id: string, input: UpdateWebhookEndpointInput) =>\n apiRequest<WebhookEndpoint>(\n ctx,\n \"PATCH\",\n `/v1/webhook-endpoints/${encodeURIComponent(id)}`,\n input,\n ),\n /** Delete an endpoint and its delivery history. */\n delete: (id: string) =>\n apiRequest<void>(ctx, \"DELETE\", `/v1/webhook-endpoints/${encodeURIComponent(id)}`),\n /** Rotate the signing secret — the new plaintext is returned once. */\n rotateSecret: (id: string) =>\n apiRequest<WebhookEndpointWithSecret>(\n ctx,\n \"POST\",\n `/v1/webhook-endpoints/${encodeURIComponent(id)}/rotate-secret`,\n ),\n /** List delivery attempts for an endpoint (newest first). Auto-paginating. */\n deliveries: (\n id: string,\n params: ListParams = {},\n options?: CallOptions,\n ): ListPromise<WebhookDelivery> =>\n makeListPromise(\n (p) =>\n apiRequest<Paginated<WebhookDelivery>>(\n ctx,\n \"GET\",\n `/v1/webhook-endpoints/${encodeURIComponent(id)}/deliveries${toQuery(p)}`,\n undefined,\n options,\n ),\n params,\n ),\n };\n}\n","/**\n * billow client SDK — the \"two lines of code\" surface, mirroring Autumn's shape\n * (CONTEXT/ARCHITECTURE §10). A thin typed wrapper over the billow REST API.\n *\n * const billow = new Billow(process.env.BILLOW_SECRET_KEY!);\n * const { allowed } = await billow.check({ customerId, featureId: \"projects\" });\n *\n * Public request/response types live in ./types and are re-exported here, so the\n * package root stays the single import surface. They are contract-derived and inlined\n * into the shipped .d.ts at build time (tsup `dts.resolve` reads @billow/contracts'\n * bundled dist), so the declarations carry no bare `@billow/contracts` import a\n * consumer couldn't resolve.\n *\n * We deliberately do NOT re-export @billow/contracts' runtime zod schemas: a client\n * SDK shouldn't ship validation - the server is the schema authority - and\n * re-exporting them made @billow/contracts (a private, unpublished workspace package)\n * a runtime dependency that left the published SDK impossible to install. Contracts is\n * now a devDependency. The types are zod-inferred, so the declarations do reference\n * `zod` (a small, published package kept as a runtime dependency); the runtime bundle\n * itself imports neither zod nor @billow/contracts.\n */\n\nexport type {\n AddSubscriptionItemInput as ContractAddSubscriptionItemInput,\n ApplySubscriptionCouponInput as ContractApplySubscriptionCouponInput,\n CancelSubscriptionInput as ContractCancelSubscriptionInput,\n ChangeSubscriptionPlanInput as ContractChangeSubscriptionPlanInput,\n CreateChargeInput as ContractCreateChargeInput,\n CreateCustomerInput as ContractCreateCustomerInput,\n CreateMerchantInitiatedChargeInput as ContractCreateMerchantInitiatedChargeInput,\n CreatePortalSessionInput as ContractCreatePortalSessionInput,\n CreateProductInput as ContractCreateProductInput,\n CreateSubscriptionInput as ContractCreateSubscriptionInput,\n CreateWebhookEndpointInput as ContractCreateWebhookEndpointInput,\n MigrateSubscribersInput as ContractMigrateSubscribersInput,\n RefundChargeInput as ContractRefundChargeInput,\n ResolveRefundInput as ContractResolveRefundInput,\n UpdateProductInput as ContractUpdateProductInput,\n UpdateSubscriptionItemInput as ContractUpdateSubscriptionItemInput,\n UpdateWebhookEndpointInput as ContractUpdateWebhookEndpointInput,\n} from \"@billow/contracts\";\nexport * from \"./billing-status\";\nexport { BillowApiError } from \"./client\";\nexport * from \"./error-codes\";\nexport * from \"./money\";\nexport * from \"./subscription-status\";\nexport * from \"./types\";\n\nimport { apiRequest, apiRequestBinary, makeContext, type RequestContext, toQuery } from \"./client\";\nimport { makeListPromise } from \"./pagination\";\nimport { createChargesResource, createCheckoutMethodsResource } from \"./resources/charges\";\nimport { createCreditsResource } from \"./resources/credits\";\nimport { createCustomersResource } from \"./resources/customers\";\nimport { createDeliverabilityResource } from \"./resources/deliverability\";\nimport { createHostedDomainsResource } from \"./resources/hosted-domains\";\nimport { createInvoicesResource } from \"./resources/invoices\";\nimport { createMarketplaceResource } from \"./resources/marketplace\";\nimport { createMetricsResource } from \"./resources/metrics\";\nimport { createPortalSessionsResource } from \"./resources/portal-sessions\";\nimport { createProductsResource } from \"./resources/products\";\nimport { createSettingsResource } from \"./resources/settings\";\nimport { createSubscriptionsResource } from \"./resources/subscriptions\";\nimport { createWebhookEndpointsResource } from \"./resources/webhook-endpoints\";\nimport type {\n AttachResult,\n BillowOptions,\n BusinessProfile,\n CallOptions,\n CheckResult,\n Coupon,\n CreateCouponInput,\n CreateSubscriptionInput,\n CreateUsageAlertInput,\n CredentialSet,\n EntitlementView,\n Feature,\n FeatureKind,\n InvoiceListItem,\n InvoicePaymentResult,\n ListParams,\n ListPromise,\n MeterConfig,\n Paginated,\n PayInvoiceInput,\n PaymentProviderDefinition,\n PortalCardSetupResult,\n PortalCheckout,\n PortalPlanChange,\n PortalSessionExchange,\n PortalSessionExchangeInput,\n PortalSessionInfo,\n PortalSubscriptionStatus,\n PortalView,\n Product,\n ProviderCredentialSummary,\n ProviderVerifyResult,\n RequestOptions,\n SavedPaymentMethod,\n SearchResults,\n TrackResult,\n UpdateBusinessProfileInput,\n UpdateFeatureInput,\n UpsertCredentialsInput,\n UsageAlert,\n Whoami,\n} from \"./types\";\n\nexport class Billow {\n #ctx: RequestContext;\n\n customers!: ReturnType<typeof createCustomersResource>;\n charges!: ReturnType<typeof createChargesResource>;\n checkoutMethods!: ReturnType<typeof createCheckoutMethodsResource>;\n /** Prepaid credits: grant them to a Customer (quantities are decimal strings of microcredits). */\n credits!: ReturnType<typeof createCreditsResource>;\n invoices!: ReturnType<typeof createInvoicesResource>;\n metrics!: ReturnType<typeof createMetricsResource>;\n webhookEndpoints!: ReturnType<typeof createWebhookEndpointsResource>;\n products!: ReturnType<typeof createProductsResource>;\n subscriptions!: ReturnType<typeof createSubscriptionsResource>;\n portalSessions!: ReturnType<typeof createPortalSessionsResource>;\n deliverability!: ReturnType<typeof createDeliverabilityResource>;\n marketplace!: ReturnType<typeof createMarketplaceResource>;\n /** Custom domains for the hosted customer portal (live keys, behind a rollout flag). */\n hostedDomains!: ReturnType<typeof createHostedDomainsResource>;\n /**\n * Organization settings (Phase D3, F) — the configurable dunning schedule, usage settlement grace,\n * and the cross-currency reporting currency + FX-rate registry (ADR-0013).\n */\n settings!: ReturnType<typeof createSettingsResource>;\n\n constructor(apiKey: string, opts: BillowOptions = {}) {\n if (!apiKey) throw new Error(\"billow: an API key is required\");\n this.#ctx = makeContext(apiKey, opts);\n this.customers = createCustomersResource(this.#ctx);\n this.charges = createChargesResource(this.#ctx);\n this.checkoutMethods = createCheckoutMethodsResource(this.#ctx);\n this.credits = createCreditsResource(this.#ctx);\n this.invoices = createInvoicesResource(this.#ctx);\n this.metrics = createMetricsResource(this.#ctx);\n this.webhookEndpoints = createWebhookEndpointsResource(this.#ctx);\n this.products = createProductsResource(this.#ctx);\n this.subscriptions = createSubscriptionsResource(this.#ctx);\n this.portalSessions = createPortalSessionsResource(this.#ctx);\n this.deliverability = createDeliverabilityResource(this.#ctx);\n this.marketplace = createMarketplaceResource(this.#ctx);\n this.hostedDomains = createHostedDomainsResource(this.#ctx);\n this.settings = createSettingsResource(this.#ctx);\n }\n\n #request<T>(method: string, path: string, body?: unknown, options?: RequestOptions): Promise<T> {\n return apiRequest<T>(this.#ctx, method, path, body, options);\n }\n\n coupons = {\n /** Define a coupon (a reusable discount template). */\n create: (input: CreateCouponInput) => this.#request<Coupon>(\"POST\", \"/v1/coupons\", input),\n /** List coupons (secret key only — enumerates live promo codes). Auto-paginating. */\n list: (params: ListParams = {}, options?: CallOptions): ListPromise<Coupon> =>\n makeListPromise(\n (p) =>\n this.#request<Paginated<Coupon>>(\"GET\", `/v1/coupons${toQuery(p)}`, undefined, options),\n params,\n ),\n /** Deactivate a coupon (existing discounts keep running). */\n deactivate: (id: string) =>\n this.#request<Coupon>(\"POST\", `/v1/coupons/${encodeURIComponent(id)}/deactivate`),\n };\n\n /** Manage developer webhook endpoints — register, rotate secrets, inspect deliveries.\n * (To VERIFY incoming deliveries, import `constructEvent` from `@usebillow/sdk/webhooks`.) */\n features = {\n /** Define a feature (a boolean access gate, or a metered feature with a meter). */\n create: (input: { slug: string; name: string; kind: FeatureKind; meter?: MeterConfig }) =>\n this.#request<Feature>(\"POST\", \"/v1/features\", input),\n /**\n * Edit a feature in place: its `name`, and — for a metered feature — its `meter`\n * aggregation. The server refuses a meter change once usage has been recorded (it\n * would rewrite billed history), so set the meter right at create time or before you\n * start tracking. Returns the updated feature.\n */\n update: (slug: string, input: UpdateFeatureInput) =>\n this.#request<Feature>(\"PATCH\", `/v1/features/${encodeURIComponent(slug)}`, input),\n /** List features in the tenant. Auto-paginating. */\n list: (params: ListParams = {}, options?: CallOptions): ListPromise<Feature> =>\n makeListPromise(\n (p) =>\n this.#request<Paginated<Feature>>(\"GET\", `/v1/features${toQuery(p)}`, undefined, options),\n params,\n ),\n /**\n * Usage Alerts + Spend caps on a metered feature (Phase C). A `threshold`\n * Alert notifies (webhook + optional customer email) as usage crosses its\n * thresholds; a `cap` blocks `check` once reached.\n */\n alerts: {\n /** List the alerts + spend cap on a metered feature (by slug). */\n list: (feature: string, options?: CallOptions) =>\n this.#request<{ alerts: UsageAlert[] }>(\n \"GET\",\n `/v1/features/${encodeURIComponent(feature)}/alerts`,\n undefined,\n options,\n ).then((r) => r.alerts),\n /** Define an Alert or Spend cap on a metered feature. */\n create: (feature: string, input: CreateUsageAlertInput) =>\n this.#request<UsageAlert>(\n \"POST\",\n `/v1/features/${encodeURIComponent(feature)}/alerts`,\n input,\n ),\n /** Delete one alert/cap rule by id. */\n remove: (feature: string, id: string) =>\n this.#request<{ removed: boolean }>(\n \"DELETE\",\n `/v1/features/${encodeURIComponent(feature)}/alerts/${encodeURIComponent(id)}`,\n ),\n },\n };\n\n integrations = {\n /** The registered payment providers + their config manifests (drives the picker + form). */\n providers: (options?: CallOptions) =>\n this.#request<{ providers: PaymentProviderDefinition[] }>(\n \"GET\",\n \"/v1/integrations/providers\",\n undefined,\n options,\n ).then((r) => r.providers),\n /** List configured credential sets per currency (provider + non-secret config). Secret-only. */\n list: (options?: CallOptions) =>\n this.#request<{ integrations: ProviderCredentialSummary[] }>(\n \"GET\",\n \"/v1/integrations\",\n undefined,\n options,\n ).then((r) => r.integrations),\n /**\n * Verify a provider's configuration against its live API. Pass `currency` to\n * choose a credential set and `target` to probe one verify target (Paymob: a\n * method); pass `sampleToken` (SANDBOX ONLY) to run a functional sub-test.\n * This probe hits the provider's live API (mutates nothing here), so it takes a\n * per-call {@link CallOptions} for a timeout / cancellation — `opts` is spread into\n * the body, so `options` stays a separate trailing arg (never merged in).\n */\n verify: (\n provider: string,\n opts?: { currency?: string; target?: string; sampleToken?: string },\n options?: CallOptions,\n ) =>\n this.#request<ProviderVerifyResult>(\n \"POST\",\n \"/v1/integrations/verify\",\n { provider, ...opts },\n options,\n ),\n /** Manage stored payment-provider credentials (the dashboard's \"manage credentials\" forms). */\n credentials: {\n /** The editable view of stored credential sets (secrets are never returned). */\n list: (options?: CallOptions) =>\n this.#request<{ credentials: CredentialSet[] }>(\n \"GET\",\n \"/v1/integrations/credentials\",\n undefined,\n options,\n ).then((r) => r.credentials),\n /** Create or rotate a (provider, currency) credential set. */\n upsert: (input: UpsertCredentialsInput) =>\n this.#request<CredentialSet>(\"PUT\", \"/v1/integrations/credentials\", input),\n /** Delete a (provider, currency) credential set. */\n remove: (provider: string, currency: string) =>\n this.#request<{ removed: boolean }>(\n \"DELETE\",\n `/v1/integrations/credentials/${encodeURIComponent(provider)}/${encodeURIComponent(currency)}`,\n ),\n },\n };\n\n /** The merchant's business identity — the seller block on documents and email from-name. */\n businessProfile = {\n /** The stored profile, or null if one was never saved. */\n get: (options?: CallOptions) =>\n this.#request<{ profile: BusinessProfile | null }>(\n \"GET\",\n \"/v1/business-profile\",\n undefined,\n options,\n ).then((r) => r.profile),\n /** Create or update the profile; omit a field to keep it, send \"\" to clear it. */\n update: (input: UpdateBusinessProfileInput) =>\n this.#request<{ profile: BusinessProfile }>(\"PUT\", \"/v1/business-profile\", input).then(\n (r) => r.profile,\n ),\n };\n\n /**\n * Hosted customer surfaces (Phase G, ADR-0014). Mint a portal session for one of\n * your signed-in users and redirect them to the returned `url` — the self-serve\n * portal, or a `checkout` hand-off for `productId`. The Customer's own calls go\n * through {@link BillowPortal}, constructed with the session token.\n */\n /** Identity of this key's tenant — org, environment, configured currencies. */\n me(options?: CallOptions): Promise<Whoami> {\n return this.#request<Whoami>(\"GET\", \"/v1/me\", undefined, options);\n }\n\n /**\n * Global search (PRD-12) across customers, invoices, subscriptions, and charges\n * for the key's `(project, environment)`. Bounded per entity (default 5, max 10);\n * a blank query returns empty results. Backs the dashboard's ⌘K palette.\n */\n search(q: string, limit?: number, options?: CallOptions): Promise<SearchResults> {\n return this.#request<SearchResults>(\n \"GET\",\n `/v1/search${toQuery({ q, limit })}`,\n undefined,\n options,\n );\n }\n\n // ── The headline verbs ──────────────────────────────────────────────\n\n /**\n * Gate access to a feature. `featureId` is the feature slug. Returns\n * `{ allowed, balance }` — `balance` is `null` for unlimited/boolean features.\n */\n check(\n input: { customerId: string; featureId: string },\n options?: CallOptions,\n ): Promise<CheckResult> {\n return this.#request<CheckResult>(\"POST\", \"/v1/check\", input, options);\n }\n\n /**\n * Record usage of a metered feature (`value` defaults to 1; negative credits\n * back). Pass `idempotencyKey` to make a retried call a no-op — which also makes the call\n * safe to retry automatically when `maxRetries` is set.\n */\n track(\n input: {\n customerId: string;\n featureId: string;\n value?: number;\n /** Arbitrary event properties — used by meter filters and property-based aggregations. */\n properties?: Record<string, string | number>;\n idempotencyKey?: string;\n /**\n * When the usage occurred (ISO-8601). Defaults to now; backdate it to land a value in a\n * still-open reset window (e.g. a finalized month-end total). Rejected if more than 5 minutes\n * in the future or more than 7 days in the past.\n */\n occurredAt?: string;\n },\n options?: CallOptions,\n ): Promise<TrackResult> {\n return this.#request<TrackResult>(\n \"POST\",\n \"/v1/track\",\n input,\n input.idempotencyKey ? { ...options, idempotencyKey: input.idempotencyKey } : options,\n );\n }\n\n /** List a customer's live entitlements (one per feature). */\n entitlements(\n customerId: string,\n options?: CallOptions,\n ): Promise<{ entitlements: EntitlementView[] }> {\n return this.#request(\n \"GET\",\n `/v1/customers/${encodeURIComponent(customerId)}/entitlements`,\n undefined,\n options,\n );\n }\n\n /** Start a subscription → returns a hosted checkout URL to redirect the customer to. */\n attach(input: CreateSubscriptionInput, options?: RequestOptions): Promise<AttachResult> {\n return this.#request<AttachResult>(\"POST\", \"/v1/attach\", input, options);\n }\n}\n\n/**\n * The browser-safe client: construct it with a **publishable** key (`bl_<env>_pk_…`)\n * to read the public catalog from any origin (CORS-enabled). It exposes ONLY public,\n * project-scoped reads — products and their prices — so it is safe to ship in a\n * frontend bundle. Customer-scoped data (entitlements, checkout) is never reachable\n * with a publishable key; use the server handler or a portal session for that.\n */\nexport class BillowPublishable {\n #ctx: RequestContext;\n\n constructor(publishableKey: string, opts: BillowOptions = {}) {\n if (!publishableKey) throw new Error(\"billow: a publishable key is required\");\n // Guard against shipping a SECRET key in a browser bundle: publishable keys look\n // like `bl_<env>_pk_…`. The catalog accepts any key, so a misplaced secret would\n // appear to work while leaking full API access.\n if (!publishableKey.includes(\"_pk_\")) {\n throw new Error(\n \"billow: BillowPublishable needs a publishable key (bl_<env>_pk_…), not a secret key\",\n );\n }\n this.#ctx = makeContext(publishableKey, opts);\n }\n\n products = {\n /** The active catalog — products and their prices, for a pricing table. */\n list: (options?: CallOptions) =>\n apiRequest<{ products: Product[] }>(\n this.#ctx,\n \"GET\",\n \"/v1/products\",\n undefined,\n options,\n ).then((r) => r.products),\n /** Fetch one active product (with its prices) by slug. */\n get: (slug: string, options?: CallOptions) =>\n apiRequest<Product>(\n this.#ctx,\n \"GET\",\n `/v1/products/${encodeURIComponent(slug)}`,\n undefined,\n options,\n ),\n };\n}\n\n/**\n * The customer-surface client (Phase G, ADR-0014): construct it with a portal\n * session token (minted by your backend via `billow.portalSessions.create`) to act\n * as that one Customer. It exposes only their own data — no operator/secret-key\n * surface — so the token can be held by a hosted portal app safely.\n */\nexport class BillowPortal {\n #ctx: RequestContext;\n\n constructor(sessionToken: string, opts: BillowOptions = {}) {\n if (!sessionToken) throw new Error(\"billow: a portal session token is required\");\n this.#ctx = makeContext(sessionToken, opts);\n }\n\n /** The portal shell: flow, return URL, merchant brand, and customer identity —\n * the lightweight payload the hosting app frames every page with, and the\n * validate-and-route check at login. */\n session(options?: CallOptions): Promise<PortalSessionInfo> {\n return apiRequest<PortalSessionInfo>(this.#ctx, \"GET\", \"/portal/session\", undefined, options);\n }\n\n /**\n * The single-use entry exchange (ADR-0039): on a client built with a minted link's entry\n * token, trade it for the session token to use from now on. Succeeds once per link, and\n * afterwards only for the browser presenting that exchange's `sessionToken`; anything else is\n * a 401. For a hosted surface; an integrator's own surface may keep using the entry token.\n */\n exchange(\n input: PortalSessionExchangeInput,\n options?: CallOptions,\n ): Promise<PortalSessionExchange> {\n return apiRequest<PortalSessionExchange>(\n this.#ctx,\n \"POST\",\n \"/portal/session/exchange\",\n input,\n options,\n );\n }\n\n /** The self-serve home payload: identity + subscriptions + usage + saved cards. */\n me(options?: CallOptions): Promise<PortalView> {\n return apiRequest<PortalView>(this.#ctx, \"GET\", \"/portal/me\", undefined, options);\n }\n\n invoices = {\n /** The Customer's invoices (newest first). Auto-paginating. */\n list: (\n params: ListParams & { status?: InvoiceListItem[\"status\"] } = {},\n options?: CallOptions,\n ): ListPromise<InvoiceListItem> =>\n makeListPromise(\n (p) =>\n apiRequest<Paginated<InvoiceListItem>>(\n this.#ctx,\n \"GET\",\n `/portal/invoices${toQuery(p)}`,\n undefined,\n options,\n ),\n params,\n ),\n /** One of the Customer's invoices, in the list's shape. */\n get: (id: string, options?: CallOptions) =>\n apiRequest<InvoiceListItem>(\n this.#ctx,\n \"GET\",\n `/portal/invoices/${encodeURIComponent(id)}`,\n undefined,\n options,\n ),\n /** Open or resume checkout for this customer's outstanding invoice. */\n pay: (id: string, input: PayInvoiceInput = {}, options?: CallOptions) =>\n apiRequest<InvoicePaymentResult>(\n this.#ctx,\n \"POST\",\n `/portal/invoices/${encodeURIComponent(id)}/pay`,\n input,\n options,\n ),\n /** Download one of the Customer's invoices as a PDF (raw bytes). */\n pdf: (id: string, options?: CallOptions) =>\n apiRequestBinary(this.#ctx, \"GET\", `/portal/invoices/${encodeURIComponent(id)}/pdf`, options),\n /** Download the payment receipt for one of the Customer's invoices (raw bytes). */\n receiptPdf: (id: string, options?: CallOptions) =>\n apiRequestBinary(\n this.#ctx,\n \"GET\",\n `/portal/invoices/${encodeURIComponent(id)}/receipt.pdf`,\n options,\n ),\n };\n\n subscriptions = {\n /** Schedule one of the Customer's subscriptions to cancel at period end. */\n cancel: (id: string) =>\n apiRequest<PortalSubscriptionStatus>(\n this.#ctx,\n \"POST\",\n `/portal/subscriptions/${encodeURIComponent(id)}/cancel`,\n ),\n /** Reverse a scheduled period-end cancellation. */\n resumeCancellation: (id: string) =>\n apiRequest<PortalSubscriptionStatus>(\n this.#ctx,\n \"POST\",\n `/portal/subscriptions/${encodeURIComponent(id)}/resume-cancellation`,\n ),\n /** Move one of the Customer's subscriptions to another plan (upgrade now / downgrade scheduled). */\n changePlan: (id: string, productId: string) =>\n apiRequest<PortalPlanChange>(\n this.#ctx,\n \"POST\",\n `/portal/subscriptions/${encodeURIComponent(id)}/plan`,\n { productId },\n ),\n /** Clear a pending downgrade. */\n clearScheduledPlanChange: (id: string) =>\n apiRequest<PortalSubscriptionStatus>(\n this.#ctx,\n \"DELETE\",\n `/portal/subscriptions/${encodeURIComponent(id)}/plan`,\n ),\n };\n\n paymentMethod = {\n /** Open a checkout to save or replace the Customer's card (zero-amount tokenization). */\n update: (returnUrl?: string) =>\n apiRequest<PortalCardSetupResult>(\n this.#ctx,\n \"POST\",\n \"/portal/payment-method/update\",\n returnUrl ? { returnUrl } : {},\n ),\n };\n\n paymentMethods = {\n list: (options?: CallOptions) =>\n apiRequest<{ paymentMethods: SavedPaymentMethod[] }>(\n this.#ctx,\n \"GET\",\n \"/portal/payment-methods\",\n undefined,\n options,\n ).then((r) => r.paymentMethods),\n setDefault: (id: string) =>\n apiRequest<SavedPaymentMethod>(\n this.#ctx,\n \"POST\",\n `/portal/payment-methods/${encodeURIComponent(id)}/default`,\n ),\n remove: (id: string) =>\n apiRequest<{ removed: boolean }>(\n this.#ctx,\n \"DELETE\",\n `/portal/payment-methods/${encodeURIComponent(id)}`,\n ),\n };\n\n /** The checkout hand-off, for a session minted with `flow: \"checkout\"`. */\n checkout = {\n /** The plan being confirmed (product + base price). */\n get: (options?: CallOptions) =>\n apiRequest<PortalCheckout>(this.#ctx, \"GET\", \"/portal/checkout\", undefined, options),\n /** Subscribe to the plan → returns the hosted Paymob checkout URL to redirect to. */\n start: () => apiRequest<{ checkoutUrl: string | null }>(this.#ctx, \"POST\", \"/portal/checkout\"),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/billing-status.ts","../src/client.ts","../src/error-codes.ts","../src/money.ts","../src/subscription-status.ts","../src/types/admin-integrations.ts","../src/pagination.ts","../src/resources/charges.ts","../src/resources/credits.ts","../src/resources/customers.ts","../src/resources/deliverability.ts","../src/resources/hosted-domains.ts","../src/resources/invoices.ts","../src/resources/marketplace.ts","../src/resources/metrics.ts","../src/resources/portal-sessions.ts","../src/resources/products.ts","../src/resources/settings.ts","../src/resources/subscriptions.ts","../src/resources/webhook-endpoints.ts","../src/index.ts"],"names":["safeToRepeat","path"],"mappings":";;;AASO,IAAM,eAAA,GAAkB;AAAA,EAC7B,SAAA;AAAA,EACA,YAAA;AAAA,EACA,WAAA;AAAA,EACA,QAAA;AAAA,EACA,yBAAA;AAAA,EACA;AACF;AAIO,IAAM,mBAAmB,CAAC,OAAA,EAAS,MAAA,EAAQ,MAAA,EAAQ,iBAAiB,MAAM;AAI1E,IAAM,eAAA,GAAkB,CAAC,SAAA,EAAW,WAAA,EAAa,QAAQ;AAIzD,IAAM,uBAAA,GAA0B,CAAC,QAAA,EAAU,SAAA,EAAW,SAAS;AAS/D,IAAM,yBAAA,GAA4B,CAAC,WAAA,EAAa,QAAQ;;;ACjC/D,IAAM,iBAAA,GAAoB,cAAA;AAGnB,SAAS,QAAQ,MAAA,EAAwB;AAC9C,EAAA,MAAM,CAAA,GAAI,IAAI,eAAA,EAAgB;AAC9B,EAAA,KAAA,MAAW,CAAC,CAAA,EAAG,CAAC,KAAK,MAAA,CAAO,OAAA,CAAQ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AAA,CAAK,IAAA,EAAM,QAAQ,kBAAkB;AAAA,GAC/F;AACF","file":"index.cjs","sourcesContent":["/**\n * Charge / invoice / refund / payment-method / webhook-delivery status vocabularies,\n * mirrored for the SDK (which cannot import the server-side `@billow/core`). The DB-enum\n * ones (charge, invoice, refund, payment method) mirror core enums and are parity-tested\n * against it (see billing-status.test.ts); webhook-delivery status is a free-text column\n * server-side with a fixed vocabulary, documented here.\n */\n\n/** A charge's lifecycle status — mirrors `@billow/core` `CHARGE_STATUSES`. */\nexport const CHARGE_STATUSES = [\n \"pending\",\n \"processing\",\n \"succeeded\",\n \"failed\",\n \"requires_reconciliation\",\n \"disputed\",\n] as const;\nexport type ChargeStatus = (typeof CHARGE_STATUSES)[number];\n\n/** An invoice's lifecycle status — mirrors `@billow/core` `INVOICE_STATUSES`. */\nexport const INVOICE_STATUSES = [\"draft\", \"open\", \"paid\", \"uncollectible\", \"void\"] as const;\nexport type InvoiceStatus = (typeof INVOICE_STATUSES)[number];\n\n/** A refund's lifecycle status — mirrors `@billow/core` `REFUND_STATUSES`. */\nexport const REFUND_STATUSES = [\"pending\", \"succeeded\", \"failed\"] as const;\nexport type RefundStatus = (typeof REFUND_STATUSES)[number];\n\n/** A saved payment method's status — mirrors `@billow/core` `PAYMENT_METHOD_STATUSES`. */\nexport const PAYMENT_METHOD_STATUSES = [\"active\", \"expired\", \"removed\"] as const;\nexport type PaymentMethodStatus = (typeof PAYMENT_METHOD_STATUSES)[number];\n\n/**\n * A webhook delivery attempt's status. Not a DB enum (a free-text column); the dispatcher\n * inserts one row per attempt with exactly `delivered` (a 2xx) or `failed` (anything else) —\n * see `packages/server/src/jobs/outbox.ts`. (Retry/backoff state lives on the outbox event,\n * a separate table, not on the delivery record.)\n */\nexport const WEBHOOK_DELIVERY_STATUSES = [\"delivered\", \"failed\"] as const;\nexport type WebhookDeliveryStatus = (typeof WEBHOOK_DELIVERY_STATUSES)[number];\n","import type { BillowErrorCode } from \"./error-codes\";\nimport type { BillowOptions, CallOptions, RequestOptions } from \"./types\";\n\n/** The response header carrying billow's per-request id (echoed on success and error alike). */\nconst REQUEST_ID_HEADER = \"x-request-id\";\n\n/** Build a `?a=b&c=d` string, skipping undefined/null/empty values. */\nexport function toQuery(params: object): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== null && v !== \"\") q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : \"\";\n}\n\nexport class BillowApiError extends Error {\n readonly status: number;\n /**\n * A known {@link BillowErrorCode} (widened to `string` so a newer server's code still type-checks),\n * or one the SDK raises itself: `invalid_response` for a success (2xx other than 204) whose body\n * was empty or could not be read or parsed. The request reached billow and was answered, but what\n * it answered is unknown - for a write, treat the outcome as UNKNOWN (retry it under the same\n * idempotency key), never as done or as refused.\n */\n readonly code: BillowErrorCode | (string & {});\n /** Structured error context from the server (e.g. per-field validation issues), when present. */\n readonly details?: unknown;\n /** billow's per-request id (`x-request-id`) — quote it in a bug report to trace the server log. */\n readonly requestId?: string | undefined;\n\n constructor(\n status: number,\n code: BillowErrorCode | (string & {}),\n message: string,\n details?: unknown,\n requestId?: string,\n ) {\n super(message);\n this.name = \"BillowApiError\";\n this.status = status;\n this.code = code;\n this.details = details;\n this.requestId = requestId;\n }\n}\n\n/** Hard per-request timeout when a caller doesn't set one. */\nconst DEFAULT_TIMEOUT_MS = 60_000;\n/** Base retry backoff when a caller doesn't set one. */\nconst DEFAULT_RETRY_BACKOFF_MS = 500;\n\n/** Everything a request needs: the transport, the base URL, the bearer, and resilience knobs. */\nexport interface RequestContext {\n fetch: typeof fetch;\n baseUrl: string;\n /** The bearer — a secret/publishable API key, or a portal-session token. */\n bearer: string;\n timeoutMs: number;\n maxRetries: number;\n retryBackoffMs: number;\n}\n\nexport function makeContext(bearer: string, opts: BillowOptions): RequestContext {\n return {\n fetch: opts.fetch ?? fetch,\n baseUrl: resolveBaseUrl(opts.baseUrl),\n bearer,\n timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n maxRetries: opts.maxRetries ?? 0,\n retryBackoffMs: opts.retryBackoffMs ?? DEFAULT_RETRY_BACKOFF_MS,\n };\n}\n\n/**\n * Whether a failed attempt is safe to retry. A `null` status is a network error or timeout\n * (no response). A `429` never executed (rate-limited), so it is safe to repeat regardless; a\n * network error / `5xx` might have applied a write, so those retry only when the request is\n * `safeToRepeat` — an idempotent method (`GET`/`HEAD`) or an idempotency-keyed write.\n */\nfunction isRetryable(status: number | null, safeToRepeat: boolean): boolean {\n if (status === 429) return true;\n if (status === null) return safeToRepeat;\n return safeToRepeat && status >= 500 && status <= 599;\n}\n\n/** Backoff before the next attempt: honor `Retry-After` (seconds) if given, else exponential. */\nfunction backoffMs(base: number, attempt: number, retryAfter: string | null): number {\n if (retryAfter) {\n const secs = Number(retryAfter);\n if (Number.isFinite(secs) && secs >= 0) return secs * 1000;\n }\n return base * 2 ** attempt;\n}\n\n/** The reason an aborted signal carries, or a plain `AbortError` when none was given. */\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException(\"The operation was aborted.\", \"AbortError\");\n}\n\n/** A backoff sleep that a caller's abort can cut short. */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(abortReason(signal));\n const timer = setTimeout(resolve, ms);\n signal?.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n reject(abortReason(signal));\n },\n { once: true },\n );\n });\n}\n\ninterface SendOptions {\n timeoutMs: number;\n /** Retry a network error / `5xx` (a `429` always retries) — set for GET/HEAD or keyed writes. */\n safeToRepeat: boolean;\n /** The caller's cancellation signal, if any. A caller abort is surfaced at once, never retried. */\n callerSignal: AbortSignal | undefined;\n}\n\n/**\n * Send one request with a per-attempt timeout and opt-in retries. Returns the final `Response`\n * (which may carry a non-retryable error status for the caller to parse); throws on a network\n * error / timeout that leaves no response, or immediately with the caller's reason if the\n * caller's `signal` aborts. Retryable responses are discarded and re-issued up to `maxRetries`\n * with {@link backoffMs} between attempts. The timeout is applied **per attempt**.\n */\nasync function sendWithResilience(\n ctx: RequestContext,\n url: string,\n init: RequestInit,\n opts: SendOptions,\n): Promise<Response> {\n const { timeoutMs, safeToRepeat, callerSignal } = opts;\n if (callerSignal?.aborted) throw abortReason(callerSignal);\n\n for (let attempt = 0; ; attempt++) {\n // A fresh controller per attempt, aborted by either the per-attempt timeout or the caller.\n const controller = new AbortController();\n let timedOut = false;\n const onCallerAbort = () => controller.abort(abortReason(callerSignal as AbortSignal));\n callerSignal?.addEventListener(\"abort\", onCallerAbort, { once: true });\n const timer =\n timeoutMs > 0\n ? setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeoutMs)\n : undefined;\n\n let res: Response | null = null;\n let err: unknown;\n try {\n res = await ctx.fetch(url, { ...init, signal: controller.signal });\n } catch (e) {\n err = e;\n } finally {\n if (timer) clearTimeout(timer);\n callerSignal?.removeEventListener(\"abort\", onCallerAbort);\n }\n\n // The caller cancelled — surface their reason immediately, never retry.\n if (callerSignal?.aborted) throw abortReason(callerSignal);\n\n if (res?.ok) return res;\n const status = res ? res.status : null;\n if (attempt < ctx.maxRetries && isRetryable(status, safeToRepeat)) {\n await sleep(\n backoffMs(ctx.retryBackoffMs, attempt, res?.headers.get(\"retry-after\") ?? null),\n callerSignal,\n );\n continue;\n }\n if (res) return res; // non-retryable (or retries exhausted) HTTP error — caller parses the body\n if (timedOut) throw new Error(`billow request timed out after ${timeoutMs}ms`);\n throw err instanceof Error ? err : new Error(\"billow request failed\");\n }\n}\n\n/** A method with no request body is inherently safe to repeat; a write needs an idempotency key. */\nfunction safeToRepeat(method: string, hasIdempotencyKey: boolean): boolean {\n return method === \"GET\" || method === \"HEAD\" || hasIdempotencyKey;\n}\n\n/** The hosted Billow API, which a client talks to unless told otherwise. */\nexport const DEFAULT_BASE_URL = \"https://api.usebillow.com\";\n\n/**\n * Resolve the API base URL: the explicit `baseUrl` option first, then the `BILLOW_URL`\n * environment variable (Node), then the hosted API. Local development and self-hosted\n * servers set one of the first two. Trailing slash stripped.\n */\nfunction resolveBaseUrl(explicit?: string): string {\n // biome-ignore lint/complexity/useLiteralKeys: the SDK cannot augment every consumer's ProcessEnv.\n const fromEnv = typeof process !== \"undefined\" ? process.env?.[\"BILLOW_URL\"] : undefined;\n return (explicit || fromEnv || DEFAULT_BASE_URL).replace(/\\/$/, \"\");\n}\n\nexport async function apiRequest<T>(\n ctx: RequestContext,\n method: string,\n path: string,\n body?: unknown,\n options?: RequestOptions,\n): Promise<T> {\n return (await apiRequestWithStatus<T>(ctx, method, path, body, options)).data;\n}\n\n/**\n * {@link apiRequest}, also answering the success status - for the writes whose status carries\n * meaning (an idempotent create answers `201` when it created, `200` when it replayed).\n */\nexport async function apiRequestWithStatus<T>(\n ctx: RequestContext,\n method: string,\n path: string,\n body?: unknown,\n options?: RequestOptions,\n): Promise<{ status: number; data: T }> {\n const init: RequestInit = {\n method,\n headers: {\n authorization: `Bearer ${ctx.bearer}`,\n ...(body ? { \"content-type\": \"application/json\" } : {}),\n ...(options?.idempotencyKey ? { \"idempotency-key\": options.idempotencyKey } : {}),\n },\n };\n if (body) init.body = JSON.stringify(body);\n const res = await sendWithResilience(ctx, `${ctx.baseUrl}${path}`, init, {\n timeoutMs: options?.timeoutMs ?? ctx.timeoutMs,\n safeToRepeat: safeToRepeat(method, !!options?.idempotencyKey),\n callerSignal: options?.signal,\n });\n // null: the body could not be read (the connection dropped mid-body, say).\n const text = await res.text().catch(() => null);\n if (!res.ok) throw errorFrom(res, safeParse(text ?? \"\"));\n return { status: res.status, data: parseSuccessBody<T>(res, text) };\n}\n\n/** billow's per-request id from a response, for {@link BillowApiError.requestId}. */\nfunction requestIdOf(res: Response): string | undefined {\n return res.headers.get(REQUEST_ID_HEADER) ?? undefined;\n}\n\n/** Parse leniently — a malformed *error* body still yields the HTTP-status error, not a parse error. */\nfunction safeParse(text: string): unknown {\n if (text.trim() === \"\") return {};\n try {\n return JSON.parse(text);\n } catch {\n return {};\n }\n}\n\n/**\n * A successful response must carry valid JSON; only a `204 No Content` (a delete) carries none. An\n * empty, unreadable or malformed 2xx body is an `invalid_response` error, never a silently-empty\n * `{}` - which a caller would take for an answer (a write it thinks done, with `undefined` fields).\n */\nfunction parseSuccessBody<T>(res: Response, text: string | null): T {\n if (res.status === 204) return {} as T;\n if (text !== null && text.trim() !== \"\") {\n try {\n return JSON.parse(text) as T;\n } catch {\n // Falls through to the error below.\n }\n }\n throw new BillowApiError(\n res.status,\n \"invalid_response\",\n `billow returned an empty or unreadable response body (HTTP ${res.status})`,\n undefined,\n requestIdOf(res),\n );\n}\n\n/** Build a {@link BillowApiError} from a failed response (surfacing `details` + the `requestId`). */\nfunction errorFrom(res: Response, data: unknown): BillowApiError {\n const err =\n (data as { error?: { code?: string; message?: string; details?: unknown } }).error ?? {};\n return new BillowApiError(\n res.status,\n err.code ?? \"error\",\n err.message ?? String(res.status),\n err.details,\n requestIdOf(res),\n );\n}\n\n/** Fetch a binary endpoint (e.g. a PDF) as raw bytes (a valid `BodyInit`). */\nexport async function apiRequestBinary(\n ctx: RequestContext,\n method: string,\n path: string,\n options?: CallOptions,\n): Promise<ArrayBuffer> {\n const res = await sendWithResilience(\n ctx,\n `${ctx.baseUrl}${path}`,\n { method, headers: { authorization: `Bearer ${ctx.bearer}` } },\n {\n timeoutMs: options?.timeoutMs ?? ctx.timeoutMs,\n safeToRepeat: safeToRepeat(method, false),\n callerSignal: options?.signal,\n },\n );\n if (!res.ok) throw errorFrom(res, safeParse(await res.text().catch(() => \"\")));\n return res.arrayBuffer();\n}\n","/**\n * The machine-readable error codes billow returns on `BillowApiError.code`. Mirrored from\n * `@billow/core`'s `BILLOW_ERROR_CODES` (the server's source of truth) — the SDK carries no\n * runtime dependency on core, so `error-codes.test.ts` asserts this list stays in lockstep.\n *\n * `switch` on these for programmatic handling (e.g. surface `rate_limited` vs `validation_error`\n * differently). The `code` field stays widened to `string` for forward-compatibility, so a code a\n * newer server adds never breaks type-checking against an older SDK.\n */\nexport const BILLOW_ERROR_CODES = [\n \"not_found\",\n \"validation_error\",\n \"authentication_error\",\n \"api_key_expired\",\n \"permission_denied\",\n \"conflict\",\n \"invalid_state_transition\",\n \"provider_error\",\n \"rate_limited\",\n \"quota_exceeded\",\n \"internal_error\",\n // Prepaid credits. 402 is shared with `quota_exceeded`: switch on the code, never the status.\n \"insufficient_credits\",\n \"account_frozen\",\n \"account_closed\",\n \"idempotency_conflict\",\n \"commit_exceeds_hold\",\n \"reversal_exceeds_consumption\",\n] as const;\n\nexport type BillowErrorCode = (typeof BILLOW_ERROR_CODES)[number];\n","/**\n * Money helpers, mirrored for the SDK (which cannot import the server-side `@billow/core`).\n * billow stores every amount as integer minor units (e.g. piasters) plus an ISO-4217 currency;\n * the number of minor units in one major unit depends on the currency's exponent, which is NOT\n * always 2 (KWD/BHD/OMR are 3, JPY/KRW are 0). Use these instead of a hardcoded `* 100` / `/ 100`,\n * which silently mis-handles those currencies 10-100x.\n *\n * The exponent table mirrors `@billow/core` and is parity-tested against it (see money.test.ts),\n * so a change in core fails CI until this mirror matches.\n */\n\n/**\n * ISO-4217 minor-unit exponents that are NOT the default of 2 (zero-decimal and three/four-decimal\n * currencies). Everything not listed — EGP, USD, EUR, SAR, AED, … — is 2.\n */\nconst CURRENCY_EXPONENTS: Readonly<Record<string, number>> = {\n // Zero-decimal\n BIF: 0,\n CLP: 0,\n DJF: 0,\n GNF: 0,\n ISK: 0,\n JPY: 0,\n KMF: 0,\n KRW: 0,\n PYG: 0,\n RWF: 0,\n UGX: 0,\n VND: 0,\n VUV: 0,\n XAF: 0,\n XOF: 0,\n XPF: 0,\n // Three-decimal\n BHD: 3,\n IQD: 3,\n JOD: 3,\n KWD: 3,\n LYD: 3,\n OMR: 3,\n TND: 3,\n // Four-decimal\n CLF: 4,\n UYW: 4,\n};\n\n/** The number of digits after the decimal point for `currency` (ISO-4217); defaults to 2. */\nexport function currencyExponent(currency: string): number {\n return CURRENCY_EXPONENTS[currency.toUpperCase()] ?? 2;\n}\n\n/**\n * Convert a major-unit amount (e.g. `5.00`) into integer minor units for `currency`, rounded to\n * the nearest minor unit. Use when building an amount to send to the API.\n */\nexport function toMinorUnits(major: number, currency: string): number {\n return Math.round(major * 10 ** currencyExponent(currency));\n}\n\n/** Convert integer minor units back to major units for `currency` (the inverse of toMinorUnits). */\nexport function toMajorUnits(minor: number, currency: string): number {\n return minor / 10 ** currencyExponent(currency);\n}\n\n/**\n * Format integer minor units with their currency for display (e.g. 10000, \"EGP\" → \"EGP 100.00\";\n * 5000, \"KWD\" → \"KWD 5.000\"). The currency's exponent drives both the divisor and the decimals.\n */\nexport function formatMoney(minor: number, currency: string): string {\n const exponent = currencyExponent(currency);\n const major = minor / 10 ** exponent;\n try {\n return new Intl.NumberFormat(\"en\", {\n style: \"currency\",\n currency,\n minimumFractionDigits: exponent,\n maximumFractionDigits: exponent,\n }).format(major);\n } catch {\n return `${major.toFixed(exponent)} ${currency}`;\n }\n}\n","/**\n * The subscription status vocabulary + access predicate, mirrored from @billow/core\n * (`enums.ts` + `billing/subscription-state.ts`) so SDK consumers can type and branch on\n * billow's own model instead of hand-maintaining a union that drifts (a real bug: an app\n * copy once carried a non-existent `ended` status - that string is a webhook event type,\n * not a subscription status).\n *\n * Mirrored, not imported: @billow/core is a server package the published SDK cannot depend\n * on (the same reason @billow/contracts mirrors core's pure logic). The parity test\n * `subscription-status.test.ts` imports @billow/core and fails CI on any drift.\n */\n\n/** The 8 canonical subscription statuses, in lifecycle order. */\nexport const SUBSCRIPTION_STATUSES = [\n \"incomplete\",\n \"incomplete_expired\",\n \"trialing\",\n \"active\",\n \"past_due\",\n \"paused\",\n \"canceled\",\n \"unpaid\",\n] as const;\n\nexport type SubscriptionStatus = (typeof SUBSCRIPTION_STATUSES)[number];\n\n/**\n * Statuses that currently grant access (a live commitment): `trialing`, `active`, and\n * `past_due` (access is retained through dunning). Note `paused` does NOT grant access.\n */\nexport const ACTIVE_SUBSCRIPTION_STATUSES: readonly SubscriptionStatus[] = [\n \"trialing\",\n \"active\",\n \"past_due\",\n];\n\n/** Statuses a subscription can never leave: `incomplete_expired` and `canceled`. */\nexport const TERMINAL_SUBSCRIPTION_STATUSES: readonly SubscriptionStatus[] = [\n \"incomplete_expired\",\n \"canceled\",\n];\n\n/** Statuses in which a subscription never activated (no access was ever granted). */\nexport const NEVER_ACTIVATED_SUBSCRIPTION_STATUSES: readonly SubscriptionStatus[] = [\n \"incomplete\",\n \"incomplete_expired\",\n];\n\n/** Whether access should currently be granted for a subscription in this state. */\nexport function grantsAccess(status: SubscriptionStatus): boolean {\n return ACTIVE_SUBSCRIPTION_STATUSES.includes(status);\n}\n\n/** Whether this is a terminal status the subscription can never leave. */\nexport function isTerminal(status: SubscriptionStatus): boolean {\n return TERMINAL_SUBSCRIPTION_STATUSES.includes(status);\n}\n","/** Public SDK types for this domain. Re-exported by ../types.ts. */\nimport type { TaxBehavior } from \"./common\";\n\n// ── Payment providers (ADR-0017) ────────────────────────────────────────────\n// Mirrors @billow/core's payment-provider manifest + verify types; the SDK is\n// standalone (no @billow/core dependency). Keep in sync with\n// packages/core/src/provider.ts. (`ConfigField` is the marketplace manifest field,\n// declared below and reused here.)\n\n/** A payment provider's declarative admin surface (rendered into the credentials form). */\nexport interface PaymentProviderDefinition {\n /** Registry key + `payment_credentials.provider` discriminator (e.g. \"paymob\"). */\n provider: string;\n label: string;\n /** Config-field manifest; secret fields are stored encrypted and never returned. */\n fields: ConfigField[];\n /** Customer-present checkout methods this provider can offer. */\n methods: (\"card\" | \"wallet\" | \"sympl\" | \"applepay\")[];\n /** Live verify targets the dashboard can \"Test\". */\n verifyTargets: ProviderVerifyTarget[];\n /**\n * When present, the dashboard surfaces a copy-able webhook URL to register in the\n * provider's own dashboard (e.g. Stripe). Omitted for providers that set their\n * callback per-charge (Paymob). `events` is an optional hint list; `url` is the\n * tenant's full endpoint, filled in by the API per (org, environment).\n */\n webhook?: { events?: string[]; url?: string };\n}\n\n/** One customer-present checkout method offered for a currency (for a method picker). */\nexport interface CheckoutMethodInfo {\n method: \"card\" | \"wallet\" | \"sympl\" | \"applepay\";\n label: string;\n /** Customer surcharge applied to this method's checkout total, in basis points. */\n feeBps?: number;\n}\n\n/** A verify target the dashboard can \"Test\" (key + label, optional integration field). */\nexport interface ProviderVerifyTarget {\n key: string;\n label: string;\n /**\n * The non-secret config field holding this target's integration id (the box's\n * primary field). Set ⇒ the dashboard renders the target as its own integration\n * box; absent ⇒ an account-level probe shown in the credentials card.\n */\n fieldKey?: string;\n /** Additional non-secret config fields rendered inside the same integration box. */\n extraFieldKeys?: string[];\n /** Short helper text shown under the integration box. */\n help?: string;\n}\n\n/** One verify target's live verdict. */\nexport interface ProviderVerifyTargetResult {\n /** The target key probed (matches a `PaymentProviderDefinition.verifyTargets` key). */\n target: string;\n configured: boolean;\n /** The provider validated this target's config against its live API. */\n valid: boolean;\n /** HTTP status of the probe (0 = not configured / transport error). */\n status: number;\n detail: string;\n /** Provider-specific extra detail (e.g. Paymob's gateway type). */\n meta?: Record<string, string>;\n /** Present only for a functional (money-moving) sub-test. */\n functional?: { ok: boolean; status: number; detail: string };\n}\n\nexport interface ProviderVerifyResult {\n provider: string;\n currency: string;\n targets: ProviderVerifyTargetResult[];\n}\n\n/** A credential set's non-secret surface (provider + currency + stored config). */\nexport interface ProviderCredentialSummary {\n provider: string;\n currency: string;\n config: Record<string, unknown>;\n}\n\n/** The editable view of one credential set — secret values are never returned. */\nexport interface CredentialSet {\n provider: string;\n currency: string;\n /** Stored non-secret field values, keyed by manifest field key (pre-fills the form). */\n config: Record<string, unknown>;\n /** Which secret fields currently have a value stored (the value is never returned). */\n secretsSet: Record<string, boolean>;\n updatedAt: string;\n}\n\n/**\n * Create or rotate a credential set. `values` carries each field keyed by the\n * provider definition's field key. On first create all required secrets are\n * required; on update omit a secret to keep the stored one, send \"\" to clear a\n * non-secret field, omit a field to leave it unchanged.\n */\nexport interface UpsertCredentialsInput {\n provider: string;\n currency: string;\n values: Record<string, unknown>;\n}\n\n/** The merchant's customer-facing business identity (seller block + email from-name). */\nexport interface BusinessProfile {\n displayName: string | null;\n legalName: string | null;\n address: string | null;\n /** Contact phone (PRD-02). */\n phone: string | null;\n /** ISO-3166-1 alpha-2 country code, e.g. \"EG\" (PRD-02). */\n country: string | null;\n taxId: string | null;\n supportEmail: string | null;\n /** Logo image URL rendered on documents + emails; null = name-only branding. */\n logoUrl: string | null;\n /** Brand/accent color as `#RRGGBB` (PRD-11); null = billow's default accent. */\n brandColor: string | null;\n /** Org-default tax treatment (Phase E) — every taxable price inherits this. */\n taxEnabled: boolean;\n /** Default rate in basis points (1% = 100 bps), e.g. 1400 for Egypt's 14% VAT. */\n taxRateBps: number;\n taxBehavior: TaxBehavior;\n /** What the tax is called on documents (e.g. \"VAT\"); null falls back to \"Tax\". */\n taxLabel: string | null;\n updatedAt: string;\n}\n\n/** Update a business profile; omit a field to leave it unchanged, send \"\" to clear it. */\nexport interface UpdateBusinessProfileInput {\n displayName?: string;\n legalName?: string;\n address?: string;\n phone?: string;\n country?: string;\n taxId?: string;\n supportEmail?: string;\n logoUrl?: string;\n /** `#RRGGBB` hex; empty string clears it (PRD-11). */\n brandColor?: string;\n taxEnabled?: boolean;\n taxRateBps?: number;\n taxBehavior?: TaxBehavior;\n taxLabel?: string;\n}\n\n// ── Marketplace Integrations (ADR-0008) ─────────────────────────────────────\n// Mirrors @billow/core's manifest types; the SDK is standalone (no @billow/core\n// dependency). Keep in sync with packages/core/src/integrations.ts.\n\nexport type IntegrationKind = \"email\" | \"accounting\";\nexport type IntegrationTier = \"official\" | \"community\";\nexport type ConfigFieldType =\n | \"text\"\n | \"password\"\n | \"email\"\n | \"url\"\n | \"number\"\n | \"percent\"\n | \"boolean\"\n | \"select\";\n\nexport interface ConfigFieldOption {\n value: string;\n label: string;\n}\n\n/** One field in an Integration's config manifest (the dashboard renders these). */\nexport interface ConfigField {\n key: string;\n label: string;\n type: ConfigFieldType;\n /** Secret values are stored encrypted and never returned by a read. */\n secret?: boolean;\n required?: boolean;\n placeholder?: string;\n help?: string;\n options?: ConfigFieldOption[];\n default?: string | number | boolean;\n}\n\n/** A catalog Integration's declarative definition. */\nexport interface IntegrationDefinition {\n slug: string;\n name: string;\n kind: IntegrationKind;\n tier: IntegrationTier;\n summary: string;\n description?: string;\n fields: ConfigField[];\n docsUrl?: string;\n}\n\n/** A catalog entry: the definition plus this tenant's install state. */\nexport interface CatalogItem {\n definition: IntegrationDefinition;\n installed: boolean;\n enabled: boolean;\n /** Stored non-secret config values, for pre-filling the form. */\n config: Record<string, unknown>;\n /** Which secret fields have a value stored (the value itself is never returned). */\n secretsSet: Record<string, boolean>;\n /** Result of the last test/verify probe; null until tested (reset on reconfigure). */\n lastTestStatus: \"ok\" | \"error\" | null;\n /** Failure message from the last test, when it errored. */\n lastTestError: string | null;\n /** When the last test/verify probe ran (ISO), or null if never tested. */\n lastTestedAt: string | null;\n updatedAt: string | null;\n}\n\n/** A config field carries a secret value when explicitly marked or password-typed. */\nexport function isSecretField(field: ConfigField): boolean {\n return field.secret === true || field.type === \"password\";\n}\n","import type { CursorListPromise, CursorPaginated, ListPromise, Paginated } from \"./types\";\n\n/**\n * The shared machinery behind every paginated `.list()`: a handle that is BOTH a Promise for the\n * first page AND an async iterable over every page, in one of two modes - offset\n * ({@link makeListPromise}) or cursor ({@link makeCursorListPromise}). The modes differ only in\n * how a walk steps from one page to the next.\n *\n * Page 1 is fetched ONCE per handle (single-flight): on a stored handle\n * (`const list = x.list(); await list; for await (const row of list) …`) the `await` and the\n * iteration reuse the same in-flight page-1 request.\n *\n * A handle is a SINGLE walk: page 1 stays cached on it, so iterating the SAME handle a second time\n * later reuses that (now-stale) page 1 while re-fetching pages 2+. For a fresh walk, call `.list()`\n * again. A rejected page 1 is NOT cached - it drops out so a later iteration re-attempts rather than\n * replaying the old failure forever.\n *\n * `fetchPage` closes over the caller's CallOptions, so `signal` / `timeoutMs` reach every page. An\n * abort mid-walk rejects the iteration BEFORE the next page's fetch (the current page's already-\n * fetched rows still drain first).\n */\nfunction makePagedList<T, Page extends { data: T[] }>(\n fetchFirst: () => Promise<Page>,\n /** Starts one walk: a step that fetches the page after `page`, or returns null after the last. */\n startWalk: () => (page: Page) => Promise<Page> | null,\n): Promise<Page> & AsyncIterable<T> & { listAll(): Promise<T[]> } {\n let firstPage: Promise<Page> | undefined;\n const first = (): Promise<Page> => {\n if (!firstPage) {\n const p = fetchFirst();\n firstPage = p;\n // Don't cache a rejected page 1 (a later walk re-attempts instead of replaying the failure),\n // and - since page 1 is fetched EAGERLY below - this attached handler also keeps a page-1\n // rejection on an un-awaited handle from surfacing as an unhandled rejection.\n p.catch(() => {\n if (firstPage === p) firstPage = undefined;\n });\n }\n return firstPage;\n };\n\n async function* iterate(): AsyncGenerator<T> {\n const next = startWalk();\n let page: Page | null = await first();\n while (page) {\n yield* page.data;\n const following = next(page);\n page = following ? await following : null;\n }\n }\n\n const listAll = async (): Promise<T[]> => {\n const out: T[] = [];\n for await (const item of iterate()) out.push(item);\n return out;\n };\n\n return Object.assign(first(), {\n [Symbol.asyncIterator]: iterate,\n listAll,\n });\n}\n\n/**\n * Offset mode: iteration walks forward by `offset`, requesting each next page at the server's\n * effective (clamped) page size, and stops as soon as a page comes back SHORTER than that size -\n * it never reads `total`, so a concurrent insert/delete can't make it skip or loop.\n */\nexport function makeListPromise<T, P extends { limit?: number; offset?: number }>(\n fetchPage: (params: P) => Promise<Paginated<T>>,\n params: P,\n): ListPromise<T> {\n return makePagedList(\n () => fetchPage(params),\n () => {\n let limit: number | undefined;\n let offset = params.offset ?? 0;\n return (page) => {\n // Page forward by the server's ECHOED (clamped) page size - never by params.limit, which\n // the server may have clamped down (e.g. 5000 -> 100). Fall back to the requested limit\n // only if a server fails to echo one, so a full page never silently truncates the walk.\n limit ??= page.limit > 0 ? page.limit : (params.limit ?? 0);\n offset += page.data.length;\n if (!(limit > 0 && page.data.length >= limit)) return null;\n return fetchPage({ ...params, limit, offset });\n };\n },\n ) as ListPromise<T>;\n}\n\n/**\n * Cursor mode, for a list whose rows keep arriving at the head (the credit ledger): iteration\n * passes each page's `nextCursor` back as `cursor` and stops on the page whose `nextCursor` is\n * null. The server walks by keyset, so rows arriving during the walk never shift an older row onto\n * another page: nothing is skipped or repeated.\n */\nexport function makeCursorListPromise<\n T,\n P extends { limit?: number; cursor?: string },\n Page extends CursorPaginated<T> = CursorPaginated<T>,\n>(fetchPage: (params: P) => Promise<Page>, params: P): CursorListPromise<T, Page> {\n return makePagedList(\n () => fetchPage(params),\n () => (page) =>\n page.nextCursor === null\n ? null\n : fetchPage({ ...params, limit: page.limit, cursor: page.nextCursor }),\n ) as CursorListPromise<T, Page>;\n}\n","import {\n apiRequest,\n apiRequestBinary,\n apiRequestWithStatus,\n type RequestContext,\n toQuery,\n} from \"../client\";\nimport { makeListPromise } from \"../pagination\";\nimport type {\n CallOptions,\n Charge,\n ChargeListItem,\n ChargeListParams,\n CheckoutMethodInfo,\n CreateChargeInput,\n CreateMerchantInitiatedChargeInput,\n IdempotentRequestOptions,\n ListPromise,\n Paginated,\n Refund,\n RefundChargeInput,\n RefundRequestResult,\n RequestOptions,\n ResolveRefundInput,\n} from \"../types\";\n\nexport function createChargesResource(ctx: RequestContext) {\n return {\n /** Create a customer-present charge -> returns a hosted checkout URL. Pass an\n * `idempotencyKey` to make the create safe to retry (with `maxRetries`). */\n create: (input: CreateChargeInput, options?: RequestOptions) =>\n apiRequest<Charge>(ctx, \"POST\", \"/v1/charges\", input, options),\n /** Charge the customer's current saved card without customer presence. */\n createMerchantInitiated: (\n input: CreateMerchantInitiatedChargeInput,\n options: IdempotentRequestOptions,\n ) => apiRequest<Charge>(ctx, \"POST\", \"/v1/charges/mit\", input, options),\n /** Fetch a charge. Pass `{ sync: true }` to force an authoritative provider pull. */\n get: (id: string, opts?: { sync?: boolean } & CallOptions) =>\n apiRequest<Charge>(\n ctx,\n \"GET\",\n `/v1/charges/${encodeURIComponent(id)}${opts?.sync ? \"?sync=true\" : \"\"}`,\n undefined,\n opts,\n ),\n /** List charges (paginated). Filters: status, currency, customer (external id), from, to. */\n list: (params: ChargeListParams = {}, options?: CallOptions): ListPromise<ChargeListItem> =>\n makeListPromise(\n (p) =>\n apiRequest<Paginated<ChargeListItem>>(\n ctx,\n \"GET\",\n `/v1/charges${toQuery(p)}`,\n undefined,\n options,\n ),\n params,\n ),\n /** Download the one-off charge's receipt as a PDF (raw bytes). */\n receipt: (id: string, options?: CallOptions) =>\n apiRequestBinary(ctx, \"GET\", `/v1/charges/${encodeURIComponent(id)}/receipt.pdf`, options),\n /** Download the immutable credit note for a succeeded refund. */\n creditNote: (chargeId: string, refundId: string, options?: CallOptions) =>\n apiRequestBinary(\n ctx,\n \"GET\",\n `/v1/charges/${encodeURIComponent(chargeId)}/refunds/${encodeURIComponent(refundId)}/credit-note.pdf`,\n options,\n ),\n /**\n * Refund a succeeded charge: `{ amount }` (minor units) for a partial, `{}` for its whole\n * remaining balance. The `idempotencyKey` is required and must identify this one refund\n * (e.g. your own refund request's id): a retry under it - yours, or the SDK's own\n * `maxRetries` - answers the same refund, in whatever status, instead of refunding again.\n * Reuse the key whenever the outcome is unknown (a timeout or dropped connection); a new\n * key asks for a new refund, e.g. after this one `failed`. `replayed` tells the refund an\n * earlier request under the key made (`true`) from one this call made (`false`).\n *\n * Always check `status`: resolving does not mean refunded. A provider that declines the\n * refund answers `502 provider_error`, which throws with `maxRetries: 0` (the default); with\n * `maxRetries > 0` the SDK retries that 502 under the same key, so the call resolves instead\n * with the declined refund replayed: `status: \"failed\"`, `replayed: true`.\n */\n refund: async (\n chargeId: string,\n input: RefundChargeInput,\n options: IdempotentRequestOptions,\n ): Promise<RefundRequestResult> => {\n const { status, data } = await apiRequestWithStatus<Refund>(\n ctx,\n \"POST\",\n `/v1/charges/${encodeURIComponent(chargeId)}/refund`,\n input,\n options,\n );\n // The API answers 201 for a refund it made, 200 for the key's earlier refund.\n return { ...data, replayed: status === 200 };\n },\n /** A charge's refunds, newest first (`needsReview` flags one awaiting an Operator). */\n listRefunds: (chargeId: string, options?: CallOptions) =>\n apiRequest<{ data: Refund[] }>(\n ctx,\n \"GET\",\n `/v1/charges/${encodeURIComponent(chargeId)}/refunds`,\n undefined,\n options,\n ),\n /** Reconcile a pending refund with the provider now; resolves to the refund as it stands. */\n recheckRefund: (chargeId: string, refundId: string, options?: CallOptions) =>\n apiRequest<Refund>(\n ctx,\n \"POST\",\n `${refundPath(chargeId, refundId)}/recheck`,\n undefined,\n options,\n ),\n /**\n * Record the outcome you verified in the provider dashboard for a refund awaiting review\n * (`needsReview`): `succeeded` settles it with a credit note, `failed` releases its amount.\n * A refund with a provider conflict (`providerConflictStatus`) resolves only as `succeeded`.\n */\n resolveRefund: (\n chargeId: string,\n refundId: string,\n input: ResolveRefundInput,\n options?: CallOptions,\n ) =>\n apiRequest<Refund>(ctx, \"POST\", `${refundPath(chargeId, refundId)}/resolve`, input, options),\n };\n}\n\nfunction refundPath(chargeId: string, refundId: string): string {\n return `/v1/charges/${encodeURIComponent(chargeId)}/refunds/${encodeURIComponent(refundId)}`;\n}\n\nexport function createCheckoutMethodsResource(ctx: RequestContext) {\n return {\n /** The customer-present methods + fees offered for a currency (for a method picker). */\n list: (params: { currency: string }, options?: CallOptions) =>\n apiRequest<{ methods: CheckoutMethodInfo[] }>(\n ctx,\n \"GET\",\n `/v1/checkout-methods${toQuery(params)}`,\n undefined,\n options,\n ),\n };\n}\n","import { apiRequest, apiRequestWithStatus, type RequestContext, toQuery } from \"../client\";\nimport { makeCursorListPromise } from \"../pagination\";\nimport type {\n CallOptions,\n CreateCreditGrantInput,\n CreateCreditIncludedRuleInput,\n CreateCreditPackInput,\n CreateCreditQuoteInput,\n CreateCreditReservationInput,\n CreateCreditTopUpInput,\n CreditBalance,\n CreditGrant,\n CreditGrantRequestResult,\n CreditIncludedRule,\n CreditLedgerEntry,\n CreditLineItem,\n CreditPack,\n CreditPacks,\n CreditQuote,\n CreditRateCard,\n CreditReservation,\n CreditReservationListParams,\n CreditReservationPage,\n CreditReservationRequestResult,\n CreditReversal,\n CreditReversalRequestResult,\n CreditTopUp,\n CreditTopUpListParams,\n CreditTopUpRequestResult,\n CreditUsage,\n CreditUsageParams,\n CursorListParams,\n CursorListPromise,\n CursorPaginated,\n IdempotentRequestOptions,\n PublishCreditRateCardInput,\n ReverseCreditConsumptionInput,\n UpdateCreditIncludedRuleInput,\n UpdateCreditPackInput,\n} from \"../types\";\n\nexport function createCreditsResource(ctx: RequestContext) {\n return {\n grants: {\n /**\n * Grant prepaid credits to a Customer. The `idempotencyKey` is required and must identify\n * this one grant (e.g. your own promotion or support-ticket id): a retry under it - yours,\n * or the SDK's own `maxRetries` - answers the same grant instead of granting twice, with\n * `replayed: true`. Reusing the key for a different grant throws `idempotency_conflict`\n * (409). Credit quantities are decimal strings of microcredits in both directions.\n */\n create: async (\n input: CreateCreditGrantInput,\n options: IdempotentRequestOptions,\n ): Promise<CreditGrantRequestResult> => {\n const { status, data } = await apiRequestWithStatus<CreditGrant>(\n ctx,\n \"POST\",\n \"/v1/credits/grants\",\n input,\n options,\n );\n // The API answers 201 for a grant it made, 200 for the key's earlier grant.\n return { ...data, replayed: status === 200 };\n },\n },\n packs: {\n /**\n * The Credit Packs a customer can buy in `currency` (ISO 4217), cheapest first: credits and\n * bonus (decimal strings of microcredits), price (minor units), and the derived\n * `pricePerCredit` and `savingsBps` - so your pricing page never hardcodes a price.\n */\n list: (currency: string, options?: CallOptions) =>\n apiRequest<CreditPacks>(\n ctx,\n \"GET\",\n `/v1/credits/packs${toQuery({ currency })}`,\n undefined,\n options,\n ),\n /** Configure a Credit Pack on a one-time catalog Price. */\n create: (input: CreateCreditPackInput, options?: CallOptions) =>\n apiRequest<CreditPack>(ctx, \"POST\", \"/v1/credits/packs\", input, options),\n /** A Credit Pack's configuration, archived or not. */\n get: (packId: string, options?: CallOptions) =>\n apiRequest<CreditPack>(\n ctx,\n \"GET\",\n `/v1/credits/packs/${encodeURIComponent(packId)}`,\n undefined,\n options,\n ),\n /** Edit a pack's terms or Price, or archive it; top-ups already made keep their terms. */\n update: (packId: string, input: UpdateCreditPackInput, options?: CallOptions) =>\n apiRequest<CreditPack>(\n ctx,\n \"PATCH\",\n `/v1/credits/packs/${encodeURIComponent(packId)}`,\n input,\n options,\n ),\n },\n includedRules: {\n /**\n * Configure an Included Credit Rule on a recurring base Price: the credits a subscription on\n * it includes for each period Billow grants it - per billing period, or per month of a Price\n * billed for longer than a month - and for a trial. Configuration, so no idempotency key:\n * a second live rule for the same Price throws `conflict` (409,\n * `details.reason: \"included_rule_exists\"`, with the live rule's `ruleId`). Throws\n * `validation_error` (422) with `details.reason: \"not_a_base_price\"` for a Price that is not\n * a recurring base Price, or `\"allocation_not_shorter_than_billing\"` for a monthly\n * allocation on a Price not billed for longer than a month.\n */\n create: (input: CreateCreditIncludedRuleInput, options?: CallOptions) =>\n apiRequest<CreditIncludedRule>(ctx, \"POST\", \"/v1/credits/included-rules\", input, options),\n /** A rule, archived or not. */\n get: (ruleId: string, options?: CallOptions) =>\n apiRequest<CreditIncludedRule>(\n ctx,\n \"GET\",\n `/v1/credits/included-rules/${encodeURIComponent(ruleId)}`,\n undefined,\n options,\n ),\n /**\n * Every rule, archived ones included, newest first. Auto-paginating by cursor: `await` the\n * first page, `for await (…)` every rule, or `.listAll()` to collect them.\n */\n list: (\n params: CursorListParams = {},\n options?: CallOptions,\n ): CursorListPromise<CreditIncludedRule> =>\n makeCursorListPromise(\n (p) =>\n apiRequest<CursorPaginated<CreditIncludedRule>>(\n ctx,\n \"GET\",\n `/v1/credits/included-rules${toQuery(p)}`,\n undefined,\n options,\n ),\n params,\n ),\n /**\n * Edit a rule's credits, per-seat choice, trial credits or allocation interval, or archive\n * it (`archived: false` brings it back). It takes effect from the next period granted;\n * periods already granted keep what they were granted. A rule left live is judged against\n * its Price as it is now, with the same errors as `create`.\n */\n update: (ruleId: string, input: UpdateCreditIncludedRuleInput, options?: CallOptions) =>\n apiRequest<CreditIncludedRule>(\n ctx,\n \"PATCH\",\n `/v1/credits/included-rules/${encodeURIComponent(ruleId)}`,\n input,\n options,\n ),\n },\n topUps: {\n /**\n * Buy a Credit Pack for a customer: answers the top-up with `checkoutUrl`, the hosted\n * checkout to send the buyer to. Credits are granted when the payment succeeds (listen for\n * `credit_top_up.succeeded`). The `idempotencyKey` is required and must identify this one\n * purchase: a retry under it answers the same top-up as it now stands (`replayed: true`) and\n * buys nothing again - asking the payment provider again for a checkout the first attempt\n * could not open, within its page's 40 minutes (Stripe only in the first 10, while 30\n * remain: it answers a timed-out first attempt with the checkout it made, or makes one never\n * made; Paymob only if the first attempt never made one); reusing it for another purchase\n * throws `idempotency_conflict` (409). A retry can also throw `conflict` (409), with\n * `details.reason`: `checkout_in_progress` - another request is still opening the\n * checkout, so retry the same key shortly - or `checkout_unavailable` - its checkout could\n * not be opened and never will be, so buy again under a new key.\n */\n create: async (\n input: CreateCreditTopUpInput,\n options: IdempotentRequestOptions,\n ): Promise<CreditTopUpRequestResult> => {\n const { status, data } = await apiRequestWithStatus<CreditTopUp>(\n ctx,\n \"POST\",\n \"/v1/credits/top-ups\",\n input,\n options,\n );\n return { ...data, replayed: status === 200 };\n },\n /** A top-up as it now stands: status, checkout, grants, and what refunds revoked. */\n get: (topUpId: string, options?: CallOptions) =>\n apiRequest<CreditTopUp>(\n ctx,\n \"GET\",\n `/v1/credits/top-ups/${encodeURIComponent(topUpId)}`,\n undefined,\n options,\n ),\n /**\n * A customer's top-ups (by external id), newest first, optionally of one status.\n * Auto-paginating by cursor: `await` the first page, `for await (…)` every top-up, or\n * `.listAll()` to collect them.\n */\n list: (\n customer: string,\n params: CreditTopUpListParams = {},\n options?: CallOptions,\n ): CursorListPromise<CreditTopUp> => {\n const { status, ...page } = params;\n return makeCursorListPromise(\n (p) =>\n apiRequest<CursorPaginated<CreditTopUp>>(\n ctx,\n \"GET\",\n `/v1/credits/top-ups${toQuery({ customer, status, ...p })}`,\n undefined,\n options,\n ),\n page,\n );\n },\n },\n balance: {\n /**\n * A Customer's credit balance (by external id): spendable, held, consumed this period,\n * expiring soon, by kind and category, the current period and the threshold level, true at\n * `asOf`. A Customer with no credit account yet reads as zeros.\n */\n get: (customer: string, options?: CallOptions) =>\n apiRequest<CreditBalance>(\n ctx,\n \"GET\",\n `/v1/credits/balance${toQuery({ customer })}`,\n undefined,\n options,\n ),\n },\n ledger: {\n /**\n * A Customer's credit ledger (by external id), newest first. Auto-paginating by cursor:\n * `await` the first page, `for await (…)` every entry, or `.listAll()` to collect them -\n * entries arriving meanwhile never make the walk skip or repeat one.\n */\n list: (\n customer: string,\n params: CursorListParams = {},\n options?: CallOptions,\n ): CursorListPromise<CreditLedgerEntry> =>\n makeCursorListPromise(\n (p) =>\n apiRequest<CursorPaginated<CreditLedgerEntry>>(\n ctx,\n \"GET\",\n `/v1/credits/ledger${toQuery({ customer, ...p })}`,\n undefined,\n options,\n ),\n params,\n ),\n },\n usage: {\n /**\n * A Customer's credit consumption (by external id) per UTC day, by Credit Action or\n * category, over at most 92 days (the 30 ending today by default).\n */\n get: (customer: string, params: CreditUsageParams = {}, options?: CallOptions) =>\n apiRequest<CreditUsage>(\n ctx,\n \"GET\",\n `/v1/credits/usage${toQuery({ customer, ...params })}`,\n undefined,\n options,\n ),\n },\n rateCards: {\n /**\n * Publish a new Rate Card version: what each Credit Action costs, as\n * `ceil(units * unitPrice / perUnits)` microcredits a line. Versions are immutable - a price\n * change is a new version - and take effect in order, at `effectiveAt` (now when omitted).\n */\n publish: (input: PublishCreditRateCardInput, options?: CallOptions) =>\n apiRequest<CreditRateCard>(ctx, \"POST\", \"/v1/credits/rate-cards\", input, options),\n /** The version in effect now (`not_found` before the first takes effect). */\n current: (options?: CallOptions) =>\n apiRequest<CreditRateCard>(\n ctx,\n \"GET\",\n \"/v1/credits/rate-cards/current\",\n undefined,\n options,\n ),\n /** One version, by its number. */\n get: (version: number, options?: CallOptions) =>\n apiRequest<CreditRateCard>(\n ctx,\n \"GET\",\n `/v1/credits/rate-cards/${encodeURIComponent(String(version))}`,\n undefined,\n options,\n ),\n /**\n * The published versions, newest first. Auto-paginating by cursor: `await` the first page,\n * `for await (…)` every version, or `.listAll()` to collect them.\n */\n list: (\n params: CursorListParams = {},\n options?: CallOptions,\n ): CursorListPromise<CreditRateCard> =>\n makeCursorListPromise(\n (p) =>\n apiRequest<CursorPaginated<CreditRateCard>>(\n ctx,\n \"GET\",\n `/v1/credits/rate-cards${toQuery(p)}`,\n undefined,\n options,\n ),\n params,\n ),\n },\n quotes: {\n /**\n * Price a customer's Credit Actions (all of one category) at the current Rate Card version\n * and keep the price for 15 minutes: a reservation over the quote holds exactly its\n * `amount`, and its commit prices at the version the quote pinned. A quote holds nothing.\n */\n create: (input: CreateCreditQuoteInput, options?: CallOptions) =>\n apiRequest<CreditQuote>(ctx, \"POST\", \"/v1/credits/quotes\", input, options),\n /** A quote as it was made. */\n get: (quoteId: string, options?: CallOptions) =>\n apiRequest<CreditQuote>(\n ctx,\n \"GET\",\n `/v1/credits/quotes/${encodeURIComponent(quoteId)}`,\n undefined,\n options,\n ),\n },\n reservations: {\n /**\n * Hold credits for one operation: over a `quoteId`, or over `items` priced at the current\n * Rate Card version. The `idempotencyKey` is required: a retry under it - after a lost\n * reply, even once the quote expired - answers the same reservation (`replayed: true`) and\n * holds nothing again. Reusing it for another request, or a new key with an `operationKey`\n * the customer already used (`details.reason: \"operation_key_used\"`), throws\n * `idempotency_conflict` (409). Throws `insufficient_credits` (402), `account_frozen`\n * (423), `account_closed` (409), `conflict` (409, `details.reason: \"quote_expired\"`), or\n * `validation_error` (422) - e.g. `details.reason: \"zero_amount\"` when the items cost nothing.\n * The `operationKey` is an operation id, never personal data: erasure replaces it.\n */\n create: async (\n input: CreateCreditReservationInput,\n options: IdempotentRequestOptions,\n ): Promise<CreditReservationRequestResult> => {\n const { status, data } = await apiRequestWithStatus<CreditReservation>(\n ctx,\n \"POST\",\n \"/v1/credits/reservations\",\n input,\n options,\n );\n return { ...data, replayed: status === 200 };\n },\n /** A reservation as it now stands. */\n get: (reservationId: string, options?: CallOptions) =>\n apiRequest<CreditReservation>(\n ctx,\n \"GET\",\n `/v1/credits/reservations/${encodeURIComponent(reservationId)}`,\n undefined,\n options,\n ),\n /**\n * Your project's reservations, oldest first, optionally of one `status`, one `customer` (by\n * external id), or protected more than `protectedLongerThan` seconds ago - with\n * `{ status: \"protected\", protectedLongerThan: page.protectedHoldMaxSeconds }`, the paid\n * operations waiting past your maximum for a decision (commit or release each). Every page\n * carries `protectedHoldMaxSeconds`. Auto-paginating by cursor: `await` the first page,\n * `for await (…)` every reservation, or `.listAll()` to collect them.\n */\n list: (\n params: CreditReservationListParams = {},\n options?: CallOptions,\n ): CursorListPromise<CreditReservation, CreditReservationPage> =>\n makeCursorListPromise(\n (p: CreditReservationListParams) =>\n apiRequest<CreditReservationPage>(\n ctx,\n \"GET\",\n `/v1/credits/reservations${toQuery(p)}`,\n undefined,\n options,\n ),\n params,\n ),\n /**\n * A customer's reservation (by external id) made with `operationKey` - how to find one whose\n * reply was lost. Throws `not_found` (404) when there is none.\n */\n findByOperationKey: (customer: string, operationKey: string, options?: CallOptions) =>\n apiRequest<CreditReservation>(\n ctx,\n \"GET\",\n `/v1/credits/reservations${toQuery({ customer, operationKey })}`,\n undefined,\n options,\n ),\n /**\n * Commit what the operation used: lines priced at the reservation's Rate Card version,\n * consuming at most what it holds (`commit_exceeds_hold`, 409) and releasing the rest; lines\n * that cost nothing in all consume nothing (`consumed: \"0\"`, `consumptionId: null`). The\n * same commit again answers it again, so it is safe to retry; anything else after it throws\n * `invalid_state_transition` (409) with the reservation in `details` - with\n * `details.reason: \"reservation_expired\"` once the hold is past its `expiresAt`.\n */\n commit: (reservationId: string, items: CreditLineItem[], options?: CallOptions) =>\n apiRequest<CreditReservation>(\n ctx,\n \"POST\",\n `/v1/credits/reservations/${encodeURIComponent(reservationId)}/commit`,\n { items },\n options,\n ),\n /** Release the whole hold. Safe to retry; after a commit it throws (409). */\n release: (reservationId: string, options?: CallOptions) =>\n apiRequest<CreditReservation>(\n ctx,\n \"POST\",\n `/v1/credits/reservations/${encodeURIComponent(reservationId)}/release`,\n undefined,\n options,\n ),\n /**\n * Protect a held reservation whose operation was paid for and is still being fulfilled: it\n * never expires (commit or release it when done). Safe to retry. A hold already past its\n * `expiresAt` throws `invalid_state_transition` (409, `details.reason: \"reservation_expired\"`).\n */\n protect: (reservationId: string, options?: CallOptions) =>\n apiRequest<CreditReservation>(\n ctx,\n \"POST\",\n `/v1/credits/reservations/${encodeURIComponent(reservationId)}/protect`,\n undefined,\n options,\n ),\n },\n consumptions: {\n /**\n * Give back part or all of a commit's consumption (`consumptionId` on the committed\n * reservation), never more than is left (`reversal_exceeds_consumption`, 409). The\n * `idempotencyKey` is required: a retry under it answers the same reversal\n * (`replayed: true`) and gives nothing back again.\n */\n reverse: async (\n consumptionId: string,\n input: ReverseCreditConsumptionInput,\n options: IdempotentRequestOptions,\n ): Promise<CreditReversalRequestResult> => {\n const { status, data } = await apiRequestWithStatus<CreditReversal>(\n ctx,\n \"POST\",\n `/v1/credits/consumptions/${encodeURIComponent(consumptionId)}/reverse`,\n input,\n options,\n );\n return { ...data, replayed: status === 200 };\n },\n },\n };\n}\n","import { apiRequest, type RequestContext, toQuery } from \"../client\";\nimport { makeListPromise } from \"../pagination\";\nimport type {\n CallOptions,\n Customer,\n CustomerAnonymizationResult,\n CustomerDataExport,\n CustomerListItem,\n CustomerListParams,\n CustomerOverview,\n ListPromise,\n Paginated,\n SavedPaymentMethod,\n} from \"../types\";\n\nexport function createCustomersResource(ctx: RequestContext) {\n return {\n create: (input: {\n id: string;\n name?: string;\n email?: string;\n phone?: string;\n /** The customer's tax / VAT registration number, recorded on their invoices. */\n taxId?: string;\n }) => apiRequest<Customer>(ctx, \"POST\", \"/v1/customers\", input),\n get: (externalId: string, options?: CallOptions) =>\n apiRequest<Customer>(\n ctx,\n \"GET\",\n `/v1/customers/${encodeURIComponent(externalId)}`,\n undefined,\n options,\n ),\n /** List customers (`q` searches external id / email / name). Auto-paginating: `await` the\n * first page, `for await (…)` every page, or `.listAll()` to collect them. */\n list: (params: CustomerListParams = {}, options?: CallOptions): ListPromise<CustomerListItem> =>\n makeListPromise(\n (p) =>\n apiRequest<Paginated<CustomerListItem>>(\n ctx,\n \"GET\",\n `/v1/customers${toQuery(p)}`,\n undefined,\n options,\n ),\n params,\n ),\n /** Full per-customer view: profile + subscriptions + charges + cards + balances. */\n overview: (externalId: string, options?: CallOptions) =>\n apiRequest<CustomerOverview>(\n ctx,\n \"GET\",\n `/v1/customers/${encodeURIComponent(externalId)}/overview`,\n undefined,\n options,\n ),\n paymentMethods: {\n list: (customer: string, options?: CallOptions) =>\n apiRequest<{ paymentMethods: SavedPaymentMethod[] }>(\n ctx,\n \"GET\",\n `/v1/customers/${encodeURIComponent(customer)}/payment-methods`,\n undefined,\n options,\n ).then((r) => r.paymentMethods),\n setDefault: (customer: string, id: string) =>\n apiRequest<SavedPaymentMethod>(\n ctx,\n \"POST\",\n `/v1/customers/${encodeURIComponent(customer)}/payment-methods/${encodeURIComponent(id)}/default`,\n ),\n remove: (customer: string, id: string) =>\n apiRequest<{ removed: boolean }>(\n ctx,\n \"DELETE\",\n `/v1/customers/${encodeURIComponent(customer)}/payment-methods/${encodeURIComponent(id)}`,\n ),\n },\n /** Export all portable customer data held by Billow. Secret-key only. */\n exportData: (externalId: string, options?: CallOptions) =>\n apiRequest<CustomerDataExport>(\n ctx,\n \"GET\",\n `/v1/customers/${encodeURIComponent(externalId)}/export`,\n undefined,\n options,\n ),\n /** Anonymize PII after access-granting subscriptions have ended. Secret-key only. */\n anonymize: (externalId: string, options?: CallOptions) =>\n apiRequest<CustomerAnonymizationResult>(\n ctx,\n \"DELETE\",\n `/v1/customers/${encodeURIComponent(externalId)}`,\n undefined,\n options,\n ),\n };\n}\n","import { apiRequest, type RequestContext, toQuery } from \"../client\";\nimport { makeListPromise } from \"../pagination\";\nimport type {\n CallOptions,\n EmailDeliveryListItem,\n EmailDeliveryListParams,\n InboundWebhookListItem,\n InboundWebhookListParams,\n ListPromise,\n OutboxEventListItem,\n OutboxEventListParams,\n Paginated,\n} from \"../types\";\n\n/**\n * Delivery-failure visibility: the transactional emails and outbound events that\n * didn't get through. Read-only, tenant-scoped to the key's (project, environment).\n */\nexport function createDeliverabilityResource(ctx: RequestContext) {\n return {\n /** Email deliveries (newest first), optionally filtered by status. Auto-paginating. */\n emails: (\n params: EmailDeliveryListParams = {},\n options?: CallOptions,\n ): ListPromise<EmailDeliveryListItem> =>\n makeListPromise(\n (p) =>\n apiRequest<Paginated<EmailDeliveryListItem>>(\n ctx,\n \"GET\",\n `/v1/deliverability/emails${toQuery(p)}`,\n undefined,\n options,\n ),\n params,\n ),\n /** Outbound events (newest first), optionally filtered by status. Auto-paginating. */\n events: (\n params: OutboxEventListParams = {},\n options?: CallOptions,\n ): ListPromise<OutboxEventListItem> =>\n makeListPromise(\n (p) =>\n apiRequest<Paginated<OutboxEventListItem>>(\n ctx,\n \"GET\",\n `/v1/deliverability/events${toQuery(p)}`,\n undefined,\n options,\n ),\n params,\n ),\n /** Inbound provider webhooks (newest first), optionally filtered by outcome. Auto-paginating. */\n inbound: (\n params: InboundWebhookListParams = {},\n options?: CallOptions,\n ): ListPromise<InboundWebhookListItem> =>\n makeListPromise(\n (p) =>\n apiRequest<Paginated<InboundWebhookListItem>>(\n ctx,\n \"GET\",\n `/v1/deliverability/inbound${toQuery(p)}`,\n undefined,\n options,\n ),\n params,\n ),\n };\n}\n","import { apiRequest, type RequestContext } from \"../client\";\nimport type {\n CallOptions,\n CreateHostedDomainInput,\n HostedDomain,\n HostedDomainList,\n} from \"../types\";\n\nconst path = (id: string, action = \"\") => `/v1/hosted-domains/${encodeURIComponent(id)}${action}`;\n\n/**\n * Custom domains for the hosted customer portal (live keys only, behind a per-Project rollout\n * flag). Add a hostname, create the two DNS records it answers, and Billow verifies them.\n */\nexport function createHostedDomainsResource(ctx: RequestContext) {\n return {\n /** The Project's domains, and whether its plan allows adding more (`whiteLabel`). */\n list: (options?: CallOptions) =>\n apiRequest<HostedDomainList>(ctx, \"GET\", \"/v1/hosted-domains\", undefined, options),\n /**\n * Add a subdomain such as `billing.example.com`. Answers the domain with the TXT and CNAME\n * `records` to create. Needs a plan with white-label branding (`permission_denied` otherwise).\n */\n create: (input: CreateHostedDomainInput, options?: CallOptions) =>\n apiRequest<HostedDomain>(ctx, \"POST\", \"/v1/hosted-domains\", input, options),\n get: (id: string, options?: CallOptions) =>\n apiRequest<HostedDomain>(ctx, \"GET\", path(id), undefined, options),\n /** Check the DNS records now (2 per minute per domain); answers the refreshed domain. */\n verify: (id: string, options?: CallOptions) =>\n apiRequest<HostedDomain>(ctx, \"POST\", path(id, \"/verify\"), undefined, options),\n /** Make an active domain the default host for new portal sessions. */\n makePrimary: (id: string, options?: CallOptions) =>\n apiRequest<HostedDomain>(ctx, \"POST\", path(id, \"/primary\"), undefined, options),\n /** Remove a domain; the portal sessions on it end immediately. */\n remove: (id: string, options?: CallOptions) =>\n apiRequest<{ id: string; hostname: string; removed: true }>(\n ctx,\n \"DELETE\",\n path(id),\n undefined,\n options,\n ),\n };\n}\n","import { apiRequest, apiRequestBinary, type RequestContext, toQuery } from \"../client\";\nimport { makeListPromise } from \"../pagination\";\nimport type {\n CallOptions,\n ExternalPaymentResult,\n InvoiceDetail,\n InvoiceListItem,\n InvoiceListParams,\n InvoicePaymentResult,\n ListPromise,\n Paginated,\n PayInvoiceInput,\n RecordExternalPaymentInput,\n} from \"../types\";\n\nexport function createInvoicesResource(ctx: RequestContext) {\n return {\n /** List invoices. Filters: status, customer (external id), from, to. Auto-paginating. */\n list: (params: InvoiceListParams = {}, options?: CallOptions): ListPromise<InvoiceListItem> =>\n makeListPromise(\n (p) =>\n apiRequest<Paginated<InvoiceListItem>>(\n ctx,\n \"GET\",\n `/v1/invoices${toQuery(p)}`,\n undefined,\n options,\n ),\n params,\n ),\n /** Fetch an invoice with its line items. */\n get: (id: string, options?: CallOptions) =>\n apiRequest<InvoiceDetail>(\n ctx,\n \"GET\",\n `/v1/invoices/${encodeURIComponent(id)}`,\n undefined,\n options,\n ),\n /**\n * Record that an open invoice was paid outside the gateway (bank transfer, cash, cheque).\n * Settles the invoice and advances the subscription exactly like a gateway payment.\n * `amount` must equal the invoice total. Operator (secret key) only.\n */\n recordPayment: (id: string, input: RecordExternalPaymentInput) =>\n apiRequest<ExternalPaymentResult>(\n ctx,\n \"POST\",\n `/v1/invoices/${encodeURIComponent(id)}/record-payment`,\n input,\n ),\n /** Open or resume hosted checkout for an existing outstanding invoice. */\n pay: (id: string, input: PayInvoiceInput = {}, options?: CallOptions) =>\n apiRequest<InvoicePaymentResult>(\n ctx,\n \"POST\",\n `/v1/invoices/${encodeURIComponent(id)}/pay`,\n input,\n options,\n ),\n /** Download the invoice as a PDF (raw bytes). */\n pdf: (id: string, options?: CallOptions) =>\n apiRequestBinary(ctx, \"GET\", `/v1/invoices/${encodeURIComponent(id)}/pdf`, options),\n /** Download the invoice's payment receipt as a PDF (raw bytes; 404 if unpaid). */\n receipt: (id: string, options?: CallOptions) =>\n apiRequestBinary(ctx, \"GET\", `/v1/invoices/${encodeURIComponent(id)}/receipt.pdf`, options),\n };\n}\n","import { apiRequest, type RequestContext } from \"../client\";\nimport type { CallOptions, CatalogItem } from \"../types\";\n\n/** The marketplace Integration catalog — install / configure / toggle / uninstall (ADR-0008). */\nexport function createMarketplaceResource(ctx: RequestContext) {\n return {\n /** Every available Integration with this tenant's install state (no secret values). */\n catalog: (options?: CallOptions) =>\n apiRequest<{ catalog: CatalogItem[] }>(\n ctx,\n \"GET\",\n \"/v1/marketplace\",\n undefined,\n options,\n ).then((r) => r.catalog),\n /** One catalog entry by slug. */\n get: (slug: string, options?: CallOptions) =>\n apiRequest<{ item: CatalogItem }>(\n ctx,\n \"GET\",\n `/v1/marketplace/${encodeURIComponent(slug)}`,\n undefined,\n options,\n ).then((r) => r.item),\n /** Install or reconfigure an Integration; `values` are the manifest form's field values. */\n upsert: (slug: string, values: Record<string, unknown>) =>\n apiRequest<{ item: CatalogItem }>(ctx, \"PUT\", `/v1/marketplace/${encodeURIComponent(slug)}`, {\n values,\n }).then((r) => r.item),\n /** Enable or disable an installed Integration. */\n setEnabled: (slug: string, enabled: boolean) =>\n apiRequest<{ item: CatalogItem }>(\n ctx,\n \"POST\",\n `/v1/marketplace/${encodeURIComponent(slug)}/enabled`,\n { enabled },\n ).then((r) => r.item),\n /** Uninstall an Integration. */\n remove: (slug: string) =>\n apiRequest<{ removed: boolean }>(\n ctx,\n \"DELETE\",\n `/v1/marketplace/${encodeURIComponent(slug)}`,\n ),\n /**\n * Verify an installed Integration's config. An email Integration sends a test\n * message to `to` (returns `{ sent, to }`); an accounting Integration runs a\n * non-mutating connectivity check with no recipient (returns `{ ok: true }`).\n */\n test: (slug: string, to?: string) =>\n apiRequest<{ sent: boolean; to: string } | { ok: true }>(\n ctx,\n \"POST\",\n `/v1/marketplace/${encodeURIComponent(slug)}/test`,\n to ? { to } : {},\n ),\n };\n}\n","import { apiRequest, type RequestContext, toQuery } from \"../client\";\nimport type {\n CallOptions,\n MetricsOverview,\n MetricsParams,\n MetricsRollup,\n TimeseriesParams,\n TimeseriesResult,\n} from \"../types\";\n\nexport function createMetricsResource(ctx: RequestContext) {\n return {\n /** KPI cards for a currency over a window (`from`/`to` default to the last 30 days). */\n overview: (params: MetricsParams = {}, options?: CallOptions) =>\n apiRequest<MetricsOverview>(\n ctx,\n \"GET\",\n `/v1/metrics/overview${toQuery(params)}`,\n undefined,\n options,\n ),\n /** A single bucketed metric (revenue / mrr / subs / success rate) over a window. */\n timeseries: (params: TimeseriesParams = {}, options?: CallOptions) =>\n apiRequest<TimeseriesResult>(\n ctx,\n \"GET\",\n `/v1/metrics/timeseries${toQuery(params)}`,\n undefined,\n options,\n ),\n /**\n * KPIs rolled up into the org's reporting currency across all billing currencies\n * (Phase H). Resolves to `null` when no reporting currency is configured.\n */\n rollup: (params: { from?: string; to?: string } = {}, options?: CallOptions) =>\n apiRequest<{ rollup: MetricsRollup | null }>(\n ctx,\n \"GET\",\n `/v1/metrics/rollup${toQuery(params)}`,\n undefined,\n options,\n ).then((r) => r.rollup),\n };\n}\n","import { apiRequest, type RequestContext } from \"../client\";\nimport type { CreatePortalSessionInput, PortalSession } from \"../types\";\n\nexport function createPortalSessionsResource(ctx: RequestContext) {\n return {\n create: (input: CreatePortalSessionInput) =>\n apiRequest<PortalSession>(ctx, \"POST\", \"/v1/portal-sessions\", input),\n };\n}\n","import { apiRequest, type RequestContext } from \"../client\";\nimport type {\n CallOptions,\n CreateProductInput,\n MigrationResult,\n Product,\n UpdateProductInput,\n} from \"../types\";\n\nexport function createProductsResource(ctx: RequestContext) {\n return {\n /** Define a product (its first active version + prices + entitlements). */\n create: (input: CreateProductInput) => apiRequest<Product>(ctx, \"POST\", \"/v1/products\", input),\n /**\n * Update a product: rename, archive/unarchive, and/or edit its prices +\n * entitlements in place.\n */\n update: (slug: string, input: UpdateProductInput) =>\n apiRequest<Product>(ctx, \"PATCH\", `/v1/products/${encodeURIComponent(slug)}`, input),\n /** Fetch a product (active version + prices + entitlements) by slug. */\n get: (slug: string, options?: CallOptions) =>\n apiRequest<Product>(\n ctx,\n \"GET\",\n `/v1/products/${encodeURIComponent(slug)}`,\n undefined,\n options,\n ),\n /** List products. `includeArchived` also returns archived ones (for admin views). */\n list: (params: { includeArchived?: boolean } = {}, options?: CallOptions) =>\n apiRequest<{ products: Product[] }>(\n ctx,\n \"GET\",\n `/v1/products${params.includeArchived ? \"?includeArchived=true\" : \"\"}`,\n undefined,\n options,\n ).then((r) => r.products),\n /** Delete a plan (soft-delete, ADR-0015). */\n delete: (slug: string) =>\n apiRequest<void>(ctx, \"DELETE\", `/v1/products/${encodeURIComponent(slug)}`),\n /** Migrate every live subscriber of `fromSlug` onto `toSlug`. */\n migrateSubscribers: (fromSlug: string, toSlug: string) =>\n apiRequest<MigrationResult>(\n ctx,\n \"POST\",\n `/v1/products/${encodeURIComponent(fromSlug)}/migrate-subscribers`,\n { toSlug },\n ),\n /** Live-subscriber count per product, keyed by product id. */\n subscriberCounts: (options?: CallOptions) =>\n apiRequest<{ counts: Record<string, number> }>(\n ctx,\n \"GET\",\n \"/v1/products/subscriber-counts\",\n undefined,\n options,\n ).then((r) => r.counts),\n };\n}\n","import { apiRequest, type RequestContext } from \"../client\";\nimport type {\n CallOptions,\n EmailTemplateSetting,\n ExchangeRate,\n UpdateEmailTemplateInput,\n} from \"../types\";\n\n/**\n * Organization settings (Phase D3, F) — the configurable dunning schedule, usage settlement grace,\n * the cross-currency reporting currency + FX-rate registry (ADR-0013), and transactional email\n * template overrides (PRD-10). All secret-key/server-side surface.\n */\nexport function createSettingsResource(ctx: RequestContext) {\n return {\n /** The dunning retry schedule: configured gaps in days (null = default), + the default. */\n dunning: {\n get: (options?: CallOptions) =>\n apiRequest<{ retryDays: number[] | null; defaultRetryDays: number[] }>(\n ctx,\n \"GET\",\n \"/v1/settings/dunning\",\n undefined,\n options,\n ),\n /** Set the retry gaps (whole days); pass `null`/`[]` to reset to the default. */\n update: (retryDays: number[] | null) =>\n apiRequest<{ retryDays: number[] | null; defaultRetryDays: number[] }>(\n ctx,\n \"PUT\",\n \"/v1/settings/dunning\",\n { retryDays },\n ),\n },\n /**\n * Usage settlement grace (hours): defers *collection* of a boundary-adjacent priced\n * calendar-meter renewal past the tz month boundary until late usage settles — the billed\n * windows/amount are unchanged, only the invoice timing shifts. `0` disables it (the default);\n * a no-op for any subscription without a priced calendar meter. Cap 72h.\n */\n usageSettlementGrace: {\n get: (options?: CallOptions) =>\n apiRequest<{ graceHours: number }>(\n ctx,\n \"GET\",\n \"/v1/settings/usage-settlement-grace\",\n undefined,\n options,\n ),\n /** Set the grace window in whole hours (0–72); `0` disables. */\n update: (graceHours: number) =>\n apiRequest<{ graceHours: number }>(ctx, \"PUT\", \"/v1/settings/usage-settlement-grace\", {\n graceHours,\n }),\n },\n /** The currency cross-currency reporting rolls up into (null = none configured). */\n reporting: {\n get: (options?: CallOptions) =>\n apiRequest<{ reportingCurrency: string | null }>(\n ctx,\n \"GET\",\n \"/v1/settings/reporting\",\n undefined,\n options,\n ),\n /** Set the reporting currency (3-letter ISO), or `null` to clear it. */\n update: (currency: string | null) =>\n apiRequest<{ reportingCurrency: string | null }>(ctx, \"PUT\", \"/v1/settings/reporting\", {\n currency,\n }),\n },\n /** The manually-maintained FX rates the per-invoice reporting snapshot draws on. */\n fxRates: {\n list: (options?: CallOptions) =>\n apiRequest<{ rates: ExchangeRate[] }>(\n ctx,\n \"GET\",\n \"/v1/settings/fx-rates\",\n undefined,\n options,\n ).then((r) => r.rates),\n /** Upsert one `base → quote` rate (`rate` is the decimal quote-per-base, > 0). */\n set: (baseCurrency: string, quoteCurrency: string, rate: number) =>\n apiRequest<ExchangeRate>(ctx, \"PUT\", \"/v1/settings/fx-rates\", {\n baseCurrency,\n quoteCurrency,\n rate,\n }),\n /** Remove a `base → quote` rate. */\n remove: (baseCurrency: string, quoteCurrency: string) =>\n apiRequest<{ removed: boolean }>(\n ctx,\n \"DELETE\",\n `/v1/settings/fx-rates?base=${encodeURIComponent(baseCurrency)}"e=${encodeURIComponent(quoteCurrency)}`,\n ),\n },\n /** Transactional email templates (PRD-10): per-template subject/message overrides. */\n emailTemplates: {\n /** Every template, merged with this project's overrides, in display order. */\n list: (options?: CallOptions) =>\n apiRequest<{ templates: EmailTemplateSetting[] }>(\n ctx,\n \"GET\",\n \"/v1/settings/email-templates\",\n undefined,\n options,\n ).then((r) => r.templates),\n /** Update one template's override (validated against its variable allowlist). */\n update: (key: string, input: UpdateEmailTemplateInput) =>\n apiRequest<{ template: EmailTemplateSetting }>(\n ctx,\n \"PUT\",\n `/v1/settings/email-templates/${encodeURIComponent(key)}`,\n input,\n ).then((r) => r.template),\n /**\n * Send a `[Test]`-prefixed sample of one template to `to`. Dashboard-only:\n * the API rejects developer keys (the dashboard restricts the recipient to\n * the signed-in operator; a developer key has no such guarantee).\n */\n test: (key: string, to: string) =>\n apiRequest<{ sent: boolean; to: string }>(\n ctx,\n \"POST\",\n `/v1/settings/email-templates/${encodeURIComponent(key)}/test`,\n { to },\n ),\n },\n };\n}\n","import { apiRequest, type RequestContext, toQuery } from \"../client\";\nimport { makeListPromise } from \"../pagination\";\nimport type {\n ActivatedSubscriptionResult,\n CallOptions,\n CreateSubscriptionInput,\n CreateSubscriptionResult,\n ListPromise,\n Paginated,\n RequestOptions,\n Subscription,\n SubscriptionDetail,\n SubscriptionItem,\n SubscriptionListItem,\n SubscriptionListParams,\n} from \"../types\";\n\nexport function createSubscriptionsResource(ctx: RequestContext) {\n return {\n /** Start a subscription -> returns the subscription plus a hosted checkout URL. `productId`\n * accepts the product's id or slug. Pass an `idempotencyKey` to make it safe to retry. */\n create: (input: CreateSubscriptionInput, options?: RequestOptions) =>\n apiRequest<CreateSubscriptionResult>(ctx, \"POST\", \"/v1/subscriptions\", input, options),\n /** Grant a free comp subscription (operator action). `productId` accepts the product's id or slug. */\n comp: (input: { customerId: string; productId: string; currency?: string }) =>\n apiRequest<ActivatedSubscriptionResult>(ctx, \"POST\", \"/v1/subscriptions\", {\n ...input,\n comp: true,\n }),\n /** List subscriptions (paginated). Filters: status, customer (external id). */\n list: (\n params: SubscriptionListParams = {},\n options?: CallOptions,\n ): ListPromise<SubscriptionListItem> =>\n makeListPromise(\n (p) =>\n apiRequest<Paginated<SubscriptionListItem>>(\n ctx,\n \"GET\",\n `/v1/subscriptions${toQuery(p)}`,\n undefined,\n options,\n ),\n params,\n ),\n get: (id: string, options?: CallOptions) =>\n apiRequest<SubscriptionDetail>(\n ctx,\n \"GET\",\n `/v1/subscriptions/${encodeURIComponent(id)}`,\n undefined,\n options,\n ),\n /**\n * The single subscription that currently determines the customer's access, resolved by\n * billow's own rule (access-granting statuses first, then newest) - or `null` if the\n * customer has none. Prefer this over picking from `list()` yourself: it avoids the\n * \"newer failed-checkout subscription shadows an older active one\" selection bug.\n */\n current: (params: { customer: string }, options?: CallOptions) =>\n apiRequest<SubscriptionDetail | null>(\n ctx,\n \"GET\",\n `/v1/subscriptions/current${toQuery(params)}`,\n undefined,\n options,\n ),\n /** Cancel — immediately, or at period end with `{ atPeriodEnd: true }`. */\n cancel: (id: string, opts?: { atPeriodEnd?: boolean }) =>\n apiRequest<Subscription>(\n ctx,\n \"POST\",\n `/v1/subscriptions/${encodeURIComponent(id)}/cancel`,\n opts ?? {},\n ),\n /** Reverse a scheduled period-end cancellation. Duplicate calls are safe. */\n resumeCancellation: (id: string) =>\n apiRequest<Subscription>(\n ctx,\n \"POST\",\n `/v1/subscriptions/${encodeURIComponent(id)}/resume-cancellation`,\n ),\n pause: (id: string) =>\n apiRequest<Subscription>(ctx, \"POST\", `/v1/subscriptions/${encodeURIComponent(id)}/pause`),\n resume: (id: string) =>\n apiRequest<Subscription>(ctx, \"POST\", `/v1/subscriptions/${encodeURIComponent(id)}/resume`),\n /** Apply a coupon to an existing subscription. */\n applyCoupon: (id: string, code: string) =>\n apiRequest<{ id: string; couponId: string; cyclesRemaining: number | null }>(\n ctx,\n \"POST\",\n `/v1/subscriptions/${encodeURIComponent(id)}/coupon`,\n { code },\n ),\n /** Change plan — immediate prorated upgrade, or downgrade scheduled for period end. `productId` accepts the product's id or slug. */\n changePlan: (id: string, productId: string) =>\n apiRequest<\n Subscription & {\n change: \"upgrade\" | \"downgrade\" | \"noop\";\n prorationInvoiceId: string | null;\n chargeStatus: string | null;\n }\n >(ctx, \"POST\", `/v1/subscriptions/${encodeURIComponent(id)}/change-plan`, { productId }),\n /** Clear a pending downgrade. Duplicate calls are safe. */\n clearScheduledPlanChange: (id: string) =>\n apiRequest<Subscription>(\n ctx,\n \"DELETE\",\n `/v1/subscriptions/${encodeURIComponent(id)}/change-plan`,\n ),\n items: {\n /** List a subscription's items (base + add-ons). */\n list: (id: string, options?: CallOptions) =>\n apiRequest<{ items: SubscriptionItem[] }>(\n ctx,\n \"GET\",\n `/v1/subscriptions/${encodeURIComponent(id)}/items`,\n undefined,\n options,\n ).then((r) => r.items),\n /** Attach an add-on Product. `productId` accepts the product's id or slug. */\n add: (id: string, productId: string, quantity?: number) =>\n apiRequest<SubscriptionItem>(\n ctx,\n \"POST\",\n `/v1/subscriptions/${encodeURIComponent(id)}/items`,\n { productId, ...(quantity != null ? { quantity } : {}) },\n ),\n /** Change an item's quantity (seats). */\n updateQuantity: (id: string, itemId: string, quantity: number) =>\n apiRequest<SubscriptionItem>(\n ctx,\n \"PATCH\",\n `/v1/subscriptions/${encodeURIComponent(id)}/items/${encodeURIComponent(itemId)}`,\n { quantity },\n ),\n /** Detach an add-on item. */\n remove: (id: string, itemId: string) =>\n apiRequest<{ removed: boolean }>(\n ctx,\n \"DELETE\",\n `/v1/subscriptions/${encodeURIComponent(id)}/items/${encodeURIComponent(itemId)}`,\n ),\n },\n };\n}\n","import { apiRequest, type RequestContext, toQuery } from \"../client\";\nimport { makeListPromise } from \"../pagination\";\nimport type {\n CallOptions,\n CreateWebhookEndpointInput,\n ListParams,\n ListPromise,\n Paginated,\n UpdateWebhookEndpointInput,\n WebhookDelivery,\n WebhookEndpoint,\n WebhookEndpointWithSecret,\n} from \"../types\";\n\nexport function createWebhookEndpointsResource(ctx: RequestContext) {\n return {\n /** Register an endpoint. The signing secret is returned once. */\n create: (input: CreateWebhookEndpointInput) =>\n apiRequest<WebhookEndpointWithSecret>(ctx, \"POST\", \"/v1/webhook-endpoints\", input),\n /** List endpoints (newest first; secrets are never returned). Auto-paginating. */\n list: (params: ListParams = {}, options?: CallOptions): ListPromise<WebhookEndpoint> =>\n makeListPromise(\n (p) =>\n apiRequest<Paginated<WebhookEndpoint>>(\n ctx,\n \"GET\",\n `/v1/webhook-endpoints${toQuery(p)}`,\n undefined,\n options,\n ),\n params,\n ),\n /** Fetch one endpoint by id. */\n get: (id: string, options?: CallOptions) =>\n apiRequest<WebhookEndpoint>(\n ctx,\n \"GET\",\n `/v1/webhook-endpoints/${encodeURIComponent(id)}`,\n undefined,\n options,\n ),\n /** Update an endpoint's URL, enabled flag, or event filter. */\n update: (id: string, input: UpdateWebhookEndpointInput) =>\n apiRequest<WebhookEndpoint>(\n ctx,\n \"PATCH\",\n `/v1/webhook-endpoints/${encodeURIComponent(id)}`,\n input,\n ),\n /** Delete an endpoint and its delivery history. */\n delete: (id: string) =>\n apiRequest<void>(ctx, \"DELETE\", `/v1/webhook-endpoints/${encodeURIComponent(id)}`),\n /** Rotate the signing secret — the new plaintext is returned once. */\n rotateSecret: (id: string) =>\n apiRequest<WebhookEndpointWithSecret>(\n ctx,\n \"POST\",\n `/v1/webhook-endpoints/${encodeURIComponent(id)}/rotate-secret`,\n ),\n /** List delivery attempts for an endpoint (newest first). Auto-paginating. */\n deliveries: (\n id: string,\n params: ListParams = {},\n options?: CallOptions,\n ): ListPromise<WebhookDelivery> =>\n makeListPromise(\n (p) =>\n apiRequest<Paginated<WebhookDelivery>>(\n ctx,\n \"GET\",\n `/v1/webhook-endpoints/${encodeURIComponent(id)}/deliveries${toQuery(p)}`,\n undefined,\n options,\n ),\n params,\n ),\n };\n}\n","/**\n * billow client SDK — the \"two lines of code\" surface, mirroring Autumn's shape\n * (CONTEXT/ARCHITECTURE §10). A thin typed wrapper over the billow REST API.\n *\n * const billow = new Billow(process.env.BILLOW_SECRET_KEY!);\n * const { allowed } = await billow.check({ customerId, featureId: \"projects\" });\n *\n * Public request/response types live in ./types and are re-exported here, so the\n * package root stays the single import surface. They are contract-derived and inlined\n * into the shipped .d.ts at build time (tsup `dts.resolve` reads @billow/contracts'\n * bundled dist), so the declarations carry no bare `@billow/contracts` import a\n * consumer couldn't resolve.\n *\n * We deliberately do NOT re-export @billow/contracts' runtime zod schemas: a client\n * SDK shouldn't ship validation - the server is the schema authority - and\n * re-exporting them made @billow/contracts (a private, unpublished workspace package)\n * a runtime dependency that left the published SDK impossible to install. Contracts is\n * now a devDependency. The types are zod-inferred, so the declarations do reference\n * `zod` (a small, published package kept as a runtime dependency); the runtime bundle\n * itself imports neither zod nor @billow/contracts.\n */\n\nexport type {\n AddSubscriptionItemInput as ContractAddSubscriptionItemInput,\n ApplySubscriptionCouponInput as ContractApplySubscriptionCouponInput,\n CancelSubscriptionInput as ContractCancelSubscriptionInput,\n ChangeSubscriptionPlanInput as ContractChangeSubscriptionPlanInput,\n CreateChargeInput as ContractCreateChargeInput,\n CreateCustomerInput as ContractCreateCustomerInput,\n CreateMerchantInitiatedChargeInput as ContractCreateMerchantInitiatedChargeInput,\n CreatePortalSessionInput as ContractCreatePortalSessionInput,\n CreateProductInput as ContractCreateProductInput,\n CreateSubscriptionInput as ContractCreateSubscriptionInput,\n CreateWebhookEndpointInput as ContractCreateWebhookEndpointInput,\n MigrateSubscribersInput as ContractMigrateSubscribersInput,\n RefundChargeInput as ContractRefundChargeInput,\n ResolveRefundInput as ContractResolveRefundInput,\n UpdateProductInput as ContractUpdateProductInput,\n UpdateSubscriptionItemInput as ContractUpdateSubscriptionItemInput,\n UpdateWebhookEndpointInput as ContractUpdateWebhookEndpointInput,\n} from \"@billow/contracts\";\nexport * from \"./billing-status\";\nexport { BillowApiError } from \"./client\";\nexport * from \"./error-codes\";\nexport * from \"./money\";\nexport * from \"./subscription-status\";\nexport * from \"./types\";\n\nimport { apiRequest, apiRequestBinary, makeContext, type RequestContext, toQuery } from \"./client\";\nimport { makeListPromise } from \"./pagination\";\nimport { createChargesResource, createCheckoutMethodsResource } from \"./resources/charges\";\nimport { createCreditsResource } from \"./resources/credits\";\nimport { createCustomersResource } from \"./resources/customers\";\nimport { createDeliverabilityResource } from \"./resources/deliverability\";\nimport { createHostedDomainsResource } from \"./resources/hosted-domains\";\nimport { createInvoicesResource } from \"./resources/invoices\";\nimport { createMarketplaceResource } from \"./resources/marketplace\";\nimport { createMetricsResource } from \"./resources/metrics\";\nimport { createPortalSessionsResource } from \"./resources/portal-sessions\";\nimport { createProductsResource } from \"./resources/products\";\nimport { createSettingsResource } from \"./resources/settings\";\nimport { createSubscriptionsResource } from \"./resources/subscriptions\";\nimport { createWebhookEndpointsResource } from \"./resources/webhook-endpoints\";\nimport type {\n AttachResult,\n BillowOptions,\n BusinessProfile,\n CallOptions,\n CheckResult,\n Coupon,\n CreateCouponInput,\n CreateSubscriptionInput,\n CreateUsageAlertInput,\n CredentialSet,\n EntitlementView,\n Feature,\n FeatureKind,\n InvoiceListItem,\n InvoicePaymentResult,\n ListParams,\n ListPromise,\n MeterConfig,\n Paginated,\n PayInvoiceInput,\n PaymentProviderDefinition,\n PortalCardSetupResult,\n PortalCheckout,\n PortalPlanChange,\n PortalSessionExchange,\n PortalSessionExchangeInput,\n PortalSessionInfo,\n PortalSubscriptionStatus,\n PortalView,\n Product,\n ProviderCredentialSummary,\n ProviderVerifyResult,\n RequestOptions,\n SavedPaymentMethod,\n SearchResults,\n TrackResult,\n UpdateBusinessProfileInput,\n UpdateFeatureInput,\n UpsertCredentialsInput,\n UsageAlert,\n Whoami,\n} from \"./types\";\n\nexport class Billow {\n #ctx: RequestContext;\n\n customers!: ReturnType<typeof createCustomersResource>;\n charges!: ReturnType<typeof createChargesResource>;\n checkoutMethods!: ReturnType<typeof createCheckoutMethodsResource>;\n /** Prepaid credits: grant them to a Customer (quantities are decimal strings of microcredits). */\n credits!: ReturnType<typeof createCreditsResource>;\n invoices!: ReturnType<typeof createInvoicesResource>;\n metrics!: ReturnType<typeof createMetricsResource>;\n webhookEndpoints!: ReturnType<typeof createWebhookEndpointsResource>;\n products!: ReturnType<typeof createProductsResource>;\n subscriptions!: ReturnType<typeof createSubscriptionsResource>;\n portalSessions!: ReturnType<typeof createPortalSessionsResource>;\n deliverability!: ReturnType<typeof createDeliverabilityResource>;\n marketplace!: ReturnType<typeof createMarketplaceResource>;\n /** Custom domains for the hosted customer portal (live keys, behind a rollout flag). */\n hostedDomains!: ReturnType<typeof createHostedDomainsResource>;\n /**\n * Organization settings (Phase D3, F) — the configurable dunning schedule, usage settlement grace,\n * and the cross-currency reporting currency + FX-rate registry (ADR-0013).\n */\n settings!: ReturnType<typeof createSettingsResource>;\n\n constructor(apiKey: string, opts: BillowOptions = {}) {\n if (!apiKey) throw new Error(\"billow: an API key is required\");\n this.#ctx = makeContext(apiKey, opts);\n this.customers = createCustomersResource(this.#ctx);\n this.charges = createChargesResource(this.#ctx);\n this.checkoutMethods = createCheckoutMethodsResource(this.#ctx);\n this.credits = createCreditsResource(this.#ctx);\n this.invoices = createInvoicesResource(this.#ctx);\n this.metrics = createMetricsResource(this.#ctx);\n this.webhookEndpoints = createWebhookEndpointsResource(this.#ctx);\n this.products = createProductsResource(this.#ctx);\n this.subscriptions = createSubscriptionsResource(this.#ctx);\n this.portalSessions = createPortalSessionsResource(this.#ctx);\n this.deliverability = createDeliverabilityResource(this.#ctx);\n this.marketplace = createMarketplaceResource(this.#ctx);\n this.hostedDomains = createHostedDomainsResource(this.#ctx);\n this.settings = createSettingsResource(this.#ctx);\n }\n\n #request<T>(method: string, path: string, body?: unknown, options?: RequestOptions): Promise<T> {\n return apiRequest<T>(this.#ctx, method, path, body, options);\n }\n\n coupons = {\n /** Define a coupon (a reusable discount template). */\n create: (input: CreateCouponInput) => this.#request<Coupon>(\"POST\", \"/v1/coupons\", input),\n /** List coupons (secret key only — enumerates live promo codes). Auto-paginating. */\n list: (params: ListParams = {}, options?: CallOptions): ListPromise<Coupon> =>\n makeListPromise(\n (p) =>\n this.#request<Paginated<Coupon>>(\"GET\", `/v1/coupons${toQuery(p)}`, undefined, options),\n params,\n ),\n /** Deactivate a coupon (existing discounts keep running). */\n deactivate: (id: string) =>\n this.#request<Coupon>(\"POST\", `/v1/coupons/${encodeURIComponent(id)}/deactivate`),\n };\n\n /** Manage developer webhook endpoints — register, rotate secrets, inspect deliveries.\n * (To VERIFY incoming deliveries, import `constructEvent` from `@usebillow/sdk/webhooks`.) */\n features = {\n /** Define a feature (a boolean access gate, or a metered feature with a meter). */\n create: (input: { slug: string; name: string; kind: FeatureKind; meter?: MeterConfig }) =>\n this.#request<Feature>(\"POST\", \"/v1/features\", input),\n /**\n * Edit a feature in place: its `name`, and — for a metered feature — its `meter`\n * aggregation. The server refuses a meter change once usage has been recorded (it\n * would rewrite billed history), so set the meter right at create time or before you\n * start tracking. Returns the updated feature.\n */\n update: (slug: string, input: UpdateFeatureInput) =>\n this.#request<Feature>(\"PATCH\", `/v1/features/${encodeURIComponent(slug)}`, input),\n /** List features in the tenant. Auto-paginating. */\n list: (params: ListParams = {}, options?: CallOptions): ListPromise<Feature> =>\n makeListPromise(\n (p) =>\n this.#request<Paginated<Feature>>(\"GET\", `/v1/features${toQuery(p)}`, undefined, options),\n params,\n ),\n /**\n * Usage Alerts + Spend caps on a metered feature (Phase C). A `threshold`\n * Alert notifies (webhook + optional customer email) as usage crosses its\n * thresholds; a `cap` blocks `check` once reached.\n */\n alerts: {\n /** List the alerts + spend cap on a metered feature (by slug). */\n list: (feature: string, options?: CallOptions) =>\n this.#request<{ alerts: UsageAlert[] }>(\n \"GET\",\n `/v1/features/${encodeURIComponent(feature)}/alerts`,\n undefined,\n options,\n ).then((r) => r.alerts),\n /** Define an Alert or Spend cap on a metered feature. */\n create: (feature: string, input: CreateUsageAlertInput) =>\n this.#request<UsageAlert>(\n \"POST\",\n `/v1/features/${encodeURIComponent(feature)}/alerts`,\n input,\n ),\n /** Delete one alert/cap rule by id. */\n remove: (feature: string, id: string) =>\n this.#request<{ removed: boolean }>(\n \"DELETE\",\n `/v1/features/${encodeURIComponent(feature)}/alerts/${encodeURIComponent(id)}`,\n ),\n },\n };\n\n integrations = {\n /** The registered payment providers + their config manifests (drives the picker + form). */\n providers: (options?: CallOptions) =>\n this.#request<{ providers: PaymentProviderDefinition[] }>(\n \"GET\",\n \"/v1/integrations/providers\",\n undefined,\n options,\n ).then((r) => r.providers),\n /** List configured credential sets per currency (provider + non-secret config). Secret-only. */\n list: (options?: CallOptions) =>\n this.#request<{ integrations: ProviderCredentialSummary[] }>(\n \"GET\",\n \"/v1/integrations\",\n undefined,\n options,\n ).then((r) => r.integrations),\n /**\n * Verify a provider's configuration against its live API. Pass `currency` to\n * choose a credential set and `target` to probe one verify target (Paymob: a\n * method); pass `sampleToken` (SANDBOX ONLY) to run a functional sub-test.\n * This probe hits the provider's live API (mutates nothing here), so it takes a\n * per-call {@link CallOptions} for a timeout / cancellation — `opts` is spread into\n * the body, so `options` stays a separate trailing arg (never merged in).\n */\n verify: (\n provider: string,\n opts?: { currency?: string; target?: string; sampleToken?: string },\n options?: CallOptions,\n ) =>\n this.#request<ProviderVerifyResult>(\n \"POST\",\n \"/v1/integrations/verify\",\n { provider, ...opts },\n options,\n ),\n /** Manage stored payment-provider credentials (the dashboard's \"manage credentials\" forms). */\n credentials: {\n /** The editable view of stored credential sets (secrets are never returned). */\n list: (options?: CallOptions) =>\n this.#request<{ credentials: CredentialSet[] }>(\n \"GET\",\n \"/v1/integrations/credentials\",\n undefined,\n options,\n ).then((r) => r.credentials),\n /** Create or rotate a (provider, currency) credential set. */\n upsert: (input: UpsertCredentialsInput) =>\n this.#request<CredentialSet>(\"PUT\", \"/v1/integrations/credentials\", input),\n /** Delete a (provider, currency) credential set. */\n remove: (provider: string, currency: string) =>\n this.#request<{ removed: boolean }>(\n \"DELETE\",\n `/v1/integrations/credentials/${encodeURIComponent(provider)}/${encodeURIComponent(currency)}`,\n ),\n },\n };\n\n /** The merchant's business identity — the seller block on documents and email from-name. */\n businessProfile = {\n /** The stored profile, or null if one was never saved. */\n get: (options?: CallOptions) =>\n this.#request<{ profile: BusinessProfile | null }>(\n \"GET\",\n \"/v1/business-profile\",\n undefined,\n options,\n ).then((r) => r.profile),\n /** Create or update the profile; omit a field to keep it, send \"\" to clear it. */\n update: (input: UpdateBusinessProfileInput) =>\n this.#request<{ profile: BusinessProfile }>(\"PUT\", \"/v1/business-profile\", input).then(\n (r) => r.profile,\n ),\n };\n\n /**\n * Hosted customer surfaces (Phase G, ADR-0014). Mint a portal session for one of\n * your signed-in users and redirect them to the returned `url` — the self-serve\n * portal, or a `checkout` hand-off for `productId`. The Customer's own calls go\n * through {@link BillowPortal}, constructed with the session token.\n */\n /** Identity of this key's tenant — org, environment, configured currencies. */\n me(options?: CallOptions): Promise<Whoami> {\n return this.#request<Whoami>(\"GET\", \"/v1/me\", undefined, options);\n }\n\n /**\n * Global search (PRD-12) across customers, invoices, subscriptions, and charges\n * for the key's `(project, environment)`. Bounded per entity (default 5, max 10);\n * a blank query returns empty results. Backs the dashboard's ⌘K palette.\n */\n search(q: string, limit?: number, options?: CallOptions): Promise<SearchResults> {\n return this.#request<SearchResults>(\n \"GET\",\n `/v1/search${toQuery({ q, limit })}`,\n undefined,\n options,\n );\n }\n\n // ── The headline verbs ──────────────────────────────────────────────\n\n /**\n * Gate access to a feature. `featureId` is the feature slug. Returns\n * `{ allowed, balance }` — `balance` is `null` for unlimited/boolean features.\n */\n check(\n input: { customerId: string; featureId: string },\n options?: CallOptions,\n ): Promise<CheckResult> {\n return this.#request<CheckResult>(\"POST\", \"/v1/check\", input, options);\n }\n\n /**\n * Record usage of a metered feature (`value` defaults to 1; negative credits\n * back). Pass `idempotencyKey` to make a retried call a no-op — which also makes the call\n * safe to retry automatically when `maxRetries` is set.\n */\n track(\n input: {\n customerId: string;\n featureId: string;\n value?: number;\n /** Arbitrary event properties — used by meter filters and property-based aggregations. */\n properties?: Record<string, string | number>;\n idempotencyKey?: string;\n /**\n * When the usage occurred (ISO-8601). Defaults to now; backdate it to land a value in a\n * still-open reset window (e.g. a finalized month-end total). Rejected if more than 5 minutes\n * in the future or more than 7 days in the past.\n */\n occurredAt?: string;\n },\n options?: CallOptions,\n ): Promise<TrackResult> {\n return this.#request<TrackResult>(\n \"POST\",\n \"/v1/track\",\n input,\n input.idempotencyKey ? { ...options, idempotencyKey: input.idempotencyKey } : options,\n );\n }\n\n /** List a customer's live entitlements (one per feature). */\n entitlements(\n customerId: string,\n options?: CallOptions,\n ): Promise<{ entitlements: EntitlementView[] }> {\n return this.#request(\n \"GET\",\n `/v1/customers/${encodeURIComponent(customerId)}/entitlements`,\n undefined,\n options,\n );\n }\n\n /** Start a subscription → returns a hosted checkout URL to redirect the customer to. */\n attach(input: CreateSubscriptionInput, options?: RequestOptions): Promise<AttachResult> {\n return this.#request<AttachResult>(\"POST\", \"/v1/attach\", input, options);\n }\n}\n\n/**\n * The browser-safe client: construct it with a **publishable** key (`bl_<env>_pk_…`)\n * to read the public catalog from any origin (CORS-enabled). It exposes ONLY public,\n * project-scoped reads — products and their prices — so it is safe to ship in a\n * frontend bundle. Customer-scoped data (entitlements, checkout) is never reachable\n * with a publishable key; use the server handler or a portal session for that.\n */\nexport class BillowPublishable {\n #ctx: RequestContext;\n\n constructor(publishableKey: string, opts: BillowOptions = {}) {\n if (!publishableKey) throw new Error(\"billow: a publishable key is required\");\n // Guard against shipping a SECRET key in a browser bundle: publishable keys look\n // like `bl_<env>_pk_…`. The catalog accepts any key, so a misplaced secret would\n // appear to work while leaking full API access.\n if (!publishableKey.includes(\"_pk_\")) {\n throw new Error(\n \"billow: BillowPublishable needs a publishable key (bl_<env>_pk_…), not a secret key\",\n );\n }\n this.#ctx = makeContext(publishableKey, opts);\n }\n\n products = {\n /** The active catalog — products and their prices, for a pricing table. */\n list: (options?: CallOptions) =>\n apiRequest<{ products: Product[] }>(\n this.#ctx,\n \"GET\",\n \"/v1/products\",\n undefined,\n options,\n ).then((r) => r.products),\n /** Fetch one active product (with its prices) by slug. */\n get: (slug: string, options?: CallOptions) =>\n apiRequest<Product>(\n this.#ctx,\n \"GET\",\n `/v1/products/${encodeURIComponent(slug)}`,\n undefined,\n options,\n ),\n };\n}\n\n/**\n * The customer-surface client (Phase G, ADR-0014): construct it with a portal\n * session token (minted by your backend via `billow.portalSessions.create`) to act\n * as that one Customer. It exposes only their own data — no operator/secret-key\n * surface — so the token can be held by a hosted portal app safely.\n */\nexport class BillowPortal {\n #ctx: RequestContext;\n\n constructor(sessionToken: string, opts: BillowOptions = {}) {\n if (!sessionToken) throw new Error(\"billow: a portal session token is required\");\n this.#ctx = makeContext(sessionToken, opts);\n }\n\n /** The portal shell: flow, return URL, merchant brand, and customer identity —\n * the lightweight payload the hosting app frames every page with, and the\n * validate-and-route check at login. */\n session(options?: CallOptions): Promise<PortalSessionInfo> {\n return apiRequest<PortalSessionInfo>(this.#ctx, \"GET\", \"/portal/session\", undefined, options);\n }\n\n /**\n * The single-use entry exchange (ADR-0039): on a client built with a minted link's entry\n * token, trade it for the session token to use from now on. Succeeds once per link, and\n * afterwards only for the browser presenting that exchange's `sessionToken`; anything else is\n * a 401. For a hosted surface; an integrator's own surface may keep using the entry token.\n */\n exchange(\n input: PortalSessionExchangeInput,\n options?: CallOptions,\n ): Promise<PortalSessionExchange> {\n return apiRequest<PortalSessionExchange>(\n this.#ctx,\n \"POST\",\n \"/portal/session/exchange\",\n input,\n options,\n );\n }\n\n /** The self-serve home payload: identity + subscriptions + usage + saved cards. */\n me(options?: CallOptions): Promise<PortalView> {\n return apiRequest<PortalView>(this.#ctx, \"GET\", \"/portal/me\", undefined, options);\n }\n\n invoices = {\n /** The Customer's invoices (newest first). Auto-paginating. */\n list: (\n params: ListParams & { status?: InvoiceListItem[\"status\"] } = {},\n options?: CallOptions,\n ): ListPromise<InvoiceListItem> =>\n makeListPromise(\n (p) =>\n apiRequest<Paginated<InvoiceListItem>>(\n this.#ctx,\n \"GET\",\n `/portal/invoices${toQuery(p)}`,\n undefined,\n options,\n ),\n params,\n ),\n /** One of the Customer's invoices, in the list's shape. */\n get: (id: string, options?: CallOptions) =>\n apiRequest<InvoiceListItem>(\n this.#ctx,\n \"GET\",\n `/portal/invoices/${encodeURIComponent(id)}`,\n undefined,\n options,\n ),\n /** Open or resume checkout for this customer's outstanding invoice. */\n pay: (id: string, input: PayInvoiceInput = {}, options?: CallOptions) =>\n apiRequest<InvoicePaymentResult>(\n this.#ctx,\n \"POST\",\n `/portal/invoices/${encodeURIComponent(id)}/pay`,\n input,\n options,\n ),\n /** Download one of the Customer's invoices as a PDF (raw bytes). */\n pdf: (id: string, options?: CallOptions) =>\n apiRequestBinary(this.#ctx, \"GET\", `/portal/invoices/${encodeURIComponent(id)}/pdf`, options),\n /** Download the payment receipt for one of the Customer's invoices (raw bytes). */\n receiptPdf: (id: string, options?: CallOptions) =>\n apiRequestBinary(\n this.#ctx,\n \"GET\",\n `/portal/invoices/${encodeURIComponent(id)}/receipt.pdf`,\n options,\n ),\n };\n\n subscriptions = {\n /** Schedule one of the Customer's subscriptions to cancel at period end. */\n cancel: (id: string) =>\n apiRequest<PortalSubscriptionStatus>(\n this.#ctx,\n \"POST\",\n `/portal/subscriptions/${encodeURIComponent(id)}/cancel`,\n ),\n /** Reverse a scheduled period-end cancellation. */\n resumeCancellation: (id: string) =>\n apiRequest<PortalSubscriptionStatus>(\n this.#ctx,\n \"POST\",\n `/portal/subscriptions/${encodeURIComponent(id)}/resume-cancellation`,\n ),\n /** Move one of the Customer's subscriptions to another plan (upgrade now / downgrade scheduled). */\n changePlan: (id: string, productId: string) =>\n apiRequest<PortalPlanChange>(\n this.#ctx,\n \"POST\",\n `/portal/subscriptions/${encodeURIComponent(id)}/plan`,\n { productId },\n ),\n /** Clear a pending downgrade. */\n clearScheduledPlanChange: (id: string) =>\n apiRequest<PortalSubscriptionStatus>(\n this.#ctx,\n \"DELETE\",\n `/portal/subscriptions/${encodeURIComponent(id)}/plan`,\n ),\n };\n\n paymentMethod = {\n /** Open a checkout to save or replace the Customer's card (zero-amount tokenization). */\n update: (returnUrl?: string) =>\n apiRequest<PortalCardSetupResult>(\n this.#ctx,\n \"POST\",\n \"/portal/payment-method/update\",\n returnUrl ? { returnUrl } : {},\n ),\n };\n\n paymentMethods = {\n list: (options?: CallOptions) =>\n apiRequest<{ paymentMethods: SavedPaymentMethod[] }>(\n this.#ctx,\n \"GET\",\n \"/portal/payment-methods\",\n undefined,\n options,\n ).then((r) => r.paymentMethods),\n setDefault: (id: string) =>\n apiRequest<SavedPaymentMethod>(\n this.#ctx,\n \"POST\",\n `/portal/payment-methods/${encodeURIComponent(id)}/default`,\n ),\n remove: (id: string) =>\n apiRequest<{ removed: boolean }>(\n this.#ctx,\n \"DELETE\",\n `/portal/payment-methods/${encodeURIComponent(id)}`,\n ),\n };\n\n /** The checkout hand-off, for a session minted with `flow: \"checkout\"`. */\n checkout = {\n /** The plan being confirmed (product + base price). */\n get: (options?: CallOptions) =>\n apiRequest<PortalCheckout>(this.#ctx, \"GET\", \"/portal/checkout\", undefined, options),\n /** Subscribe to the plan → returns the hosted Paymob checkout URL to redirect to. */\n start: () => apiRequest<{ checkoutUrl: string | null }>(this.#ctx, \"POST\", \"/portal/checkout\"),\n };\n}\n"]}
|