@usebillow/sdk 0.9.0 → 0.11.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/{billing-B16zL5xU.d.cts → billing-8ug1Gw05.d.cts} +9 -9
  3. package/dist/{billing-BF4OGaLI.d.ts → billing-Bs10EcjR.d.ts} +9 -9
  4. package/dist/{billing-status-BZQN_gm7.d.cts → billing-status-DZkB0VPK.d.cts} +5 -5
  5. package/dist/{billing-status-BZQN_gm7.d.ts → billing-status-DZkB0VPK.d.ts} +5 -5
  6. package/dist/{chunk-CCG4F5FK.js → chunk-47J7FYM5.js} +2 -2
  7. package/dist/chunk-47J7FYM5.js.map +1 -0
  8. package/dist/{chunk-GT5VBLN5.js → chunk-XUFQG6EA.js} +74 -22
  9. package/dist/chunk-XUFQG6EA.js.map +1 -0
  10. package/dist/config.cjs +3 -3
  11. package/dist/config.cjs.map +1 -1
  12. package/dist/config.d.cts +9 -9
  13. package/dist/config.d.ts +9 -9
  14. package/dist/config.js +3 -3
  15. package/dist/config.js.map +1 -1
  16. package/dist/{hosted-domains-DSTQ1GZz.d.ts → hosted-domains-BrnwkHqq.d.ts} +40 -2
  17. package/dist/{hosted-domains-DwakPG4J.d.cts → hosted-domains-zWm2srOk.d.cts} +40 -2
  18. package/dist/index.cjs +72 -20
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +70 -48
  21. package/dist/index.d.ts +70 -48
  22. package/dist/index.js +2 -2
  23. package/dist/ingestion.cjs.map +1 -1
  24. package/dist/ingestion.d.cts +18 -18
  25. package/dist/ingestion.d.ts +18 -18
  26. package/dist/ingestion.js.map +1 -1
  27. package/dist/react.cjs +28 -5
  28. package/dist/react.cjs.map +1 -1
  29. package/dist/react.d.cts +6 -6
  30. package/dist/react.d.ts +6 -6
  31. package/dist/react.js +2 -2
  32. package/dist/react.js.map +1 -1
  33. package/dist/server.cjs.map +1 -1
  34. package/dist/server.d.cts +11 -11
  35. package/dist/server.d.ts +11 -11
  36. package/dist/server.js.map +1 -1
  37. package/dist/status.cjs.map +1 -1
  38. package/dist/status.d.cts +1 -1
  39. package/dist/status.d.ts +1 -1
  40. package/dist/status.js +1 -1
  41. package/dist/webhooks.cjs.map +1 -1
  42. package/dist/webhooks.d.cts +20 -15
  43. package/dist/webhooks.d.ts +20 -15
  44. package/dist/webhooks.js.map +1 -1
  45. package/package.json +1 -1
  46. package/dist/chunk-CCG4F5FK.js.map +0 -1
  47. package/dist/chunk-GT5VBLN5.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.ts","../src/index.ts","../src/react.tsx"],"names":["safeToRepeat","createContext","useCallback","useState","useEffect","useMemo","jsx","useContext"],"mappings":";;;;;;AAIA,IAAM,iBAAA,GAAoB,cAAA;AAYnB,IAAM,cAAA,GAAN,cAA6B,KAAA,CAAM;AAAA,EAC/B,MAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,IAAA;AAAA;AAAA,EAEA,OAAA;AAAA;AAAA,EAEA,SAAA;AAAA,EAET,WAAA,CACE,MAAA,EACA,IAAA,EACA,OAAA,EACA,SACA,SAAA,EACA;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,gBAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AACf,IAAA,IAAA,CAAK,SAAA,GAAY,SAAA;AAAA,EACnB;AACF,CAAA;AAGA,IAAM,kBAAA,GAAqB,GAAA;AAE3B,IAAM,wBAAA,GAA2B,GAAA;AAa1B,SAAS,WAAA,CAAY,QAAgB,IAAA,EAAqC;AAC/E,EAAA,OAAO;AAAA,IACL,KAAA,EAAO,KAAK,KAAA,IAAS,KAAA;AAAA,IACrB,OA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AAI,EAAE,CAAA;AAC/E,IAAA,MAAA,CAAO,QAAA,CAAS,MAAK,CAAE,IAAA;AAAA,MACrB,CAAC,IAAA,KAAS;AACR,QAAA,IAAI,CAAC,MAAA,EAAQ;AACb,QAAA,WAAA,CAAY,IAAI,CAAA;AAChB,QAAA,QAAA,CAAS,IAAI,CAAA;AACb,QAAA,YAAA,CAAa,KAAK,CAAA;AAAA,MACpB,CAAA;AAAA,MACA,CAAC,CAAA,KAAe;AACd,QAAA,IAAI,CAAC,MAAA,EAAQ;AACb,QAAA,QAAA,CAAS,aAAa,KAAA,GAAQ,CAAA,CAAE,OAAA,GAAU,MAAA,CAAO,CAAC,CAAC,CAAA;AACnD,QAAA,YAAA,CAAa,KAAK,CAAA;AAAA,MACpB;AAAA,KACF;AACA,IAAA,OAAO,MAAM;AACX,MAAA,MAAA,GAAS,KAAA;AAAA,IACX,CAAA;AAAA,EACF,CAAA,EAAG,CAAC,cAAA,EAAgB,OAAO,CAAC,CAAA;AAE5B,EAAA,OAAO,EAAE,QAAA,EAAU,SAAA,EAAW,KAAA,EAAM;AACtC","file":"react.cjs","sourcesContent":["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 * 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","\"use client\";\n\n/**\n * React adapter (ARCHITECTURE §6: \"framework adapters — React hooks first\"). These\n * hooks talk to the same-origin billow handler (`@usebillow/sdk/server`), never to billow\n * directly — the secret key stays on your server and the customer is resolved from\n * your session. Wrap your app in `<BillowProvider>` and use the hooks below.\n *\n * <BillowProvider>\n * <App />\n * </BillowProvider>\n *\n * const { allowed } = useCheck(\"projects\");\n * const attach = useAttach();\n * <button onClick={() => attach({ productId: \"pro\" }, { redirect: true })}>Upgrade</button>\n */\nimport {\n createContext,\n type ReactNode,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n} from \"react\";\nimport type { AttachResult, CheckResult, EntitlementView, Product, TrackResult } from \"./index\";\nimport { BillowPublishable } from \"./index\";\n\ninterface BillowContextValue {\n request: <T>(method: string, path: string, body?: unknown) => Promise<T>;\n entitlements: EntitlementView[];\n isLoading: boolean;\n error: Error | null;\n refresh: () => Promise<void>;\n}\n\nconst BillowContext = createContext<BillowContextValue | null>(null);\n\nexport interface BillowProviderProps {\n children: ReactNode;\n /** Where the billow handler is mounted. Default `/api/billow`. */\n basePath?: string;\n /** Custom fetch (SSR/testing). Defaults to the global `fetch`. */\n fetcher?: typeof fetch;\n}\n\nexport function BillowProvider({\n children,\n basePath = \"/api/billow\",\n fetcher,\n}: BillowProviderProps) {\n const base = basePath.replace(/\\/$/, \"\");\n const doFetch = fetcher ?? (globalThis.fetch as typeof fetch);\n\n const request = useCallback(\n async <T,>(method: string, path: string, body?: unknown): Promise<T> => {\n const init: RequestInit = { method };\n if (body) {\n init.headers = { \"content-type\": \"application/json\" };\n init.body = JSON.stringify(body);\n }\n const res = await doFetch(`${base}${path}`, init);\n const data = (await res.json().catch(() => ({}))) as { error?: { message?: string } };\n if (!res.ok) {\n throw new Error(data.error?.message ?? `billow ${method} ${path} failed (${res.status})`);\n }\n return data as T;\n },\n [base, doFetch],\n );\n\n const [entitlements, setEntitlements] = useState<EntitlementView[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n const refresh = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n try {\n const data = await request<{ entitlements: EntitlementView[] }>(\"GET\", \"/entitlements\");\n setEntitlements(data.entitlements);\n } catch (err) {\n setError(err instanceof Error ? err : new Error(String(err)));\n } finally {\n setIsLoading(false);\n }\n }, [request]);\n\n useEffect(() => {\n void refresh();\n }, [refresh]);\n\n const value = useMemo<BillowContextValue>(\n () => ({ request, entitlements, isLoading, error, refresh }),\n [request, entitlements, isLoading, error, refresh],\n );\n\n return <BillowContext.Provider value={value}>{children}</BillowContext.Provider>;\n}\n\nfunction useBillowContext(): BillowContextValue {\n const ctx = useContext(BillowContext);\n if (!ctx) throw new Error(\"billow: wrap your app in <BillowProvider>\");\n return ctx;\n}\n\n/** The identified customer's live entitlements (one per granted feature), with a `refresh`. */\nexport function useEntitlements(): {\n entitlements: EntitlementView[];\n isLoading: boolean;\n error: Error | null;\n refresh: () => Promise<void>;\n} {\n const { entitlements, isLoading, error, refresh } = useBillowContext();\n return { entitlements, isLoading, error, refresh };\n}\n\n/**\n * Gate a feature, derived client-side from the cached entitlements (no round-trip).\n * `error` is set when the entitlements fetch failed — distinguish that from a real\n * `allowed: false` (otherwise an auth/network failure looks like a denied feature).\n */\nexport function useCheck(\n featureId: string,\n): CheckResult & { isLoading: boolean; error: Error | null } {\n const { entitlements, isLoading, error } = useBillowContext();\n const match = entitlements.find((e) => e.feature === featureId);\n return {\n feature: featureId,\n allowed: match?.allowed ?? false,\n balance: match?.balance ?? null,\n isLoading,\n error,\n };\n}\n\n/** Start a subscription → checkout URL. Pass `{ redirect: true }` to navigate to it. */\nexport function useAttach(): (\n input: { productId: string; couponCode?: string },\n opts?: { redirect?: boolean },\n) => Promise<AttachResult> {\n const { request, refresh } = useBillowContext();\n return useCallback(\n async (input, opts = {}) => {\n const result = await request<AttachResult>(\"POST\", \"/attach\", input);\n await refresh();\n const loc = (globalThis as { location?: { href: string } }).location;\n if (opts.redirect && result.url && loc) loc.href = result.url;\n return result;\n },\n [request, refresh],\n );\n}\n\n/**\n * Record usage from the browser. Requires the handler's `allowClientTrack` — most\n * apps should `track` server-side instead (a browser caller can forge usage).\n */\nexport function useTrack(): (input: {\n featureId: string;\n value?: number;\n idempotencyKey?: string;\n}) => Promise<TrackResult> {\n const { request, refresh } = useBillowContext();\n return useCallback(\n async (input) => {\n const result = await request<TrackResult>(\"POST\", \"/track\", input);\n await refresh();\n return result;\n },\n [request, refresh],\n );\n}\n\n/** Fetch the public product catalog (for a pricing table). */\nexport function useProducts(): { products: Product[]; isLoading: boolean; error: Error | null } {\n const { request } = useBillowContext();\n const [products, setProducts] = useState<Product[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n useEffect(() => {\n let active = true;\n setIsLoading(true);\n request<{ products: Product[] }>(\"GET\", \"/products\")\n .then((r) => {\n if (!active) return;\n setProducts(r.products);\n setError(null);\n })\n .catch((err) => {\n if (active) setError(err instanceof Error ? err : new Error(String(err)));\n })\n .finally(() => {\n if (active) setIsLoading(false);\n });\n return () => {\n active = false;\n };\n }, [request]);\n\n return { products, isLoading, error };\n}\n\nexport interface PublishableConfig {\n /** A publishable key (`bl_<env>_pk_…`) — safe to ship in a frontend bundle. */\n publishableKey: string;\n /** The Billow API base URL. Defaults to the hosted API, `https://api.usebillow.com`. */\n baseUrl?: string;\n}\n\n/**\n * Drop-in catalog reader for a pure-SPA pricing table: fetches the public products +\n * prices directly from the browser with a publishable key (CORS-enabled), no backend\n * handler required. Reads only public data — customer entitlements/checkout still need\n * the server handler or a portal session.\n */\nexport function usePublishableProducts(config: PublishableConfig): {\n products: Product[];\n isLoading: boolean;\n error: string | null;\n} {\n const { publishableKey, baseUrl } = config;\n const [products, setProducts] = useState<Product[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n useEffect(() => {\n let active = true;\n setIsLoading(true);\n const client = new BillowPublishable(publishableKey, baseUrl ? { baseUrl } : {});\n client.products.list().then(\n (list) => {\n if (!active) return;\n setProducts(list);\n setError(null);\n setIsLoading(false);\n },\n (e: unknown) => {\n if (!active) return;\n setError(e instanceof Error ? e.message : String(e));\n setIsLoading(false);\n },\n );\n return () => {\n active = false;\n };\n }, [publishableKey, baseUrl]);\n\n return { products, isLoading, error };\n}\n"]}
1
+ {"version":3,"sources":["../src/client.ts","../src/index.ts","../src/react.tsx"],"names":["safeToRepeat","createContext","useCallback","useState","useEffect","useMemo","jsx","useContext"],"mappings":";;;;;;AAIA,IAAM,iBAAA,GAAoB,cAAA;AAYnB,IAAM,cAAA,GAAN,cAA6B,KAAA,CAAM;AAAA,EAC/B,MAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,IAAA;AAAA;AAAA,EAEA,OAAA;AAAA;AAAA,EAEA,SAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA,iBAAA;AAAA,EAET,YACE,MAAA,EACA,IAAA,EACA,OAAA,EACA,OAAA,EACA,WACA,iBAAA,EACA;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,gBAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AACf,IAAA,IAAA,CAAK,SAAA,GAAY,SAAA;AACjB,IAAA,IAAA,CAAK,iBAAA,GAAoB,iBAAA;AAAA,EAC3B;AACF,CAAA;AAGA,IAAM,kBAAA,GAAqB,GAAA;AAE3B,IAAM,wBAAA,GAA2B,GAAA;AAEjC,IAAM,uBAAA,GAA0B,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A;AAAA,MACA,CAAC,CAAA,KAAe;AACd,QAAA,IAAI,CAAC,MAAA,EAAQ;AACb,QAAA,QAAA,CAAS,aAAa,KAAA,GAAQ,CAAA,CAAE,OAAA,GAAU,MAAA,CAAO,CAAC,CAAC,CAAA;AACnD,QAAA,YAAA,CAAa,KAAK,CAAA;AAAA,MACpB;AAAA,KACF;AACA,IAAA,OAAO,MAAM;AACX,MAAA,MAAA,GAAS,KAAA;AAAA,IACX,CAAA;AAAA,EACF,CAAA,EAAG,CAAC,cAAA,EAAgB,OAAO,CAAC,CAAA;AAE5B,EAAA,OAAO,EAAE,QAAA,EAAU,SAAA,EAAW,KAAA,EAAM;AACtC","file":"react.cjs","sourcesContent":["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 * How many seconds to wait before trying again, from the response's `Retry-After` header (sent\n * with a `429 rate_limited`); undefined when the response did not say.\n */\n readonly retryAfterSeconds?: number | undefined;\n\n constructor(\n status: number,\n code: BillowErrorCode | (string & {}),\n message: string,\n details?: unknown,\n requestId?: string,\n retryAfterSeconds?: number,\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 this.retryAfterSeconds = retryAfterSeconds;\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/** The longest wait a `Retry-After` is taken at: anything longer reads as an hour. */\nconst MAX_RETRY_AFTER_SECONDS = 3600;\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/**\n * Backoff before the next attempt: honor `Retry-After` (seconds, at most an hour) if given, else\n * exponential.\n */\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 Math.min(secs, MAX_RETRY_AFTER_SECONDS) * 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 retryAfterOf(res),\n );\n}\n\n/** An HTTP date in its preferred form (IMF-fixdate, RFC 9110): `Sun, 06 Nov 1994 08:49:37 GMT`. */\nconst IMF_FIXDATE = /^[A-Z][a-z]{2}, \\d{2} [A-Z][a-z]{2} \\d{4} \\d{2}:\\d{2}:\\d{2} GMT$/;\n\n/**\n * The seconds a response's `Retry-After` asks a client to wait: whole seconds, or an HTTP date\n * counted from now (never below 0), at most an hour. Undefined when absent or unreadable: a value\n * that is neither (a fraction, a sign, a date in another form) is not guessed at.\n */\nfunction retryAfterOf(res: Response): number | undefined {\n const value = res.headers.get(\"retry-after\")?.trim();\n if (!value) return undefined;\n let seconds: number;\n if (/^\\d+$/.test(value)) {\n seconds = Number(value);\n } else if (IMF_FIXDATE.test(value)) {\n seconds = Math.ceil((Date.parse(value) - Date.now()) / 1000);\n } else {\n return undefined;\n }\n if (!Number.isFinite(seconds)) return undefined;\n return Math.min(Math.max(0, seconds), MAX_RETRY_AFTER_SECONDS);\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 * 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","\"use client\";\n\n/**\n * React adapter (ARCHITECTURE §6: \"framework adapters - React hooks first\"). These\n * hooks talk to the same-origin billow handler (`@usebillow/sdk/server`), never to billow\n * directly - the secret key stays on your server and the customer is resolved from\n * your session. Wrap your app in `<BillowProvider>` and use the hooks below.\n *\n * <BillowProvider>\n * <App />\n * </BillowProvider>\n *\n * const { allowed } = useCheck(\"projects\");\n * const attach = useAttach();\n * <button onClick={() => attach({ productId: \"pro\" }, { redirect: true })}>Upgrade</button>\n */\nimport {\n createContext,\n type ReactNode,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n} from \"react\";\nimport type { AttachResult, CheckResult, EntitlementView, Product, TrackResult } from \"./index\";\nimport { BillowPublishable } from \"./index\";\n\ninterface BillowContextValue {\n request: <T>(method: string, path: string, body?: unknown) => Promise<T>;\n entitlements: EntitlementView[];\n isLoading: boolean;\n error: Error | null;\n refresh: () => Promise<void>;\n}\n\nconst BillowContext = createContext<BillowContextValue | null>(null);\n\nexport interface BillowProviderProps {\n children: ReactNode;\n /** Where the billow handler is mounted. Default `/api/billow`. */\n basePath?: string;\n /** Custom fetch (SSR/testing). Defaults to the global `fetch`. */\n fetcher?: typeof fetch;\n}\n\nexport function BillowProvider({\n children,\n basePath = \"/api/billow\",\n fetcher,\n}: BillowProviderProps) {\n const base = basePath.replace(/\\/$/, \"\");\n const doFetch = fetcher ?? (globalThis.fetch as typeof fetch);\n\n const request = useCallback(\n async <T,>(method: string, path: string, body?: unknown): Promise<T> => {\n const init: RequestInit = { method };\n if (body) {\n init.headers = { \"content-type\": \"application/json\" };\n init.body = JSON.stringify(body);\n }\n const res = await doFetch(`${base}${path}`, init);\n const data = (await res.json().catch(() => ({}))) as { error?: { message?: string } };\n if (!res.ok) {\n throw new Error(data.error?.message ?? `billow ${method} ${path} failed (${res.status})`);\n }\n return data as T;\n },\n [base, doFetch],\n );\n\n const [entitlements, setEntitlements] = useState<EntitlementView[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n const refresh = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n try {\n const data = await request<{ entitlements: EntitlementView[] }>(\"GET\", \"/entitlements\");\n setEntitlements(data.entitlements);\n } catch (err) {\n setError(err instanceof Error ? err : new Error(String(err)));\n } finally {\n setIsLoading(false);\n }\n }, [request]);\n\n useEffect(() => {\n void refresh();\n }, [refresh]);\n\n const value = useMemo<BillowContextValue>(\n () => ({ request, entitlements, isLoading, error, refresh }),\n [request, entitlements, isLoading, error, refresh],\n );\n\n return <BillowContext.Provider value={value}>{children}</BillowContext.Provider>;\n}\n\nfunction useBillowContext(): BillowContextValue {\n const ctx = useContext(BillowContext);\n if (!ctx) throw new Error(\"billow: wrap your app in <BillowProvider>\");\n return ctx;\n}\n\n/** The identified customer's live entitlements (one per granted feature), with a `refresh`. */\nexport function useEntitlements(): {\n entitlements: EntitlementView[];\n isLoading: boolean;\n error: Error | null;\n refresh: () => Promise<void>;\n} {\n const { entitlements, isLoading, error, refresh } = useBillowContext();\n return { entitlements, isLoading, error, refresh };\n}\n\n/**\n * Gate a feature, derived client-side from the cached entitlements (no round-trip).\n * `error` is set when the entitlements fetch failed - distinguish that from a real\n * `allowed: false` (otherwise an auth/network failure looks like a denied feature).\n */\nexport function useCheck(\n featureId: string,\n): CheckResult & { isLoading: boolean; error: Error | null } {\n const { entitlements, isLoading, error } = useBillowContext();\n const match = entitlements.find((e) => e.feature === featureId);\n return {\n feature: featureId,\n allowed: match?.allowed ?? false,\n balance: match?.balance ?? null,\n isLoading,\n error,\n };\n}\n\n/** Start a subscription → checkout URL. Pass `{ redirect: true }` to navigate to it. */\nexport function useAttach(): (\n input: { productId: string; couponCode?: string },\n opts?: { redirect?: boolean },\n) => Promise<AttachResult> {\n const { request, refresh } = useBillowContext();\n return useCallback(\n async (input, opts = {}) => {\n const result = await request<AttachResult>(\"POST\", \"/attach\", input);\n await refresh();\n const loc = (globalThis as { location?: { href: string } }).location;\n if (opts.redirect && result.url && loc) loc.href = result.url;\n return result;\n },\n [request, refresh],\n );\n}\n\n/**\n * Record usage from the browser. Requires the handler's `allowClientTrack` - most\n * apps should `track` server-side instead (a browser caller can forge usage).\n */\nexport function useTrack(): (input: {\n featureId: string;\n value?: number;\n idempotencyKey?: string;\n}) => Promise<TrackResult> {\n const { request, refresh } = useBillowContext();\n return useCallback(\n async (input) => {\n const result = await request<TrackResult>(\"POST\", \"/track\", input);\n await refresh();\n return result;\n },\n [request, refresh],\n );\n}\n\n/** Fetch the public product catalog (for a pricing table). */\nexport function useProducts(): { products: Product[]; isLoading: boolean; error: Error | null } {\n const { request } = useBillowContext();\n const [products, setProducts] = useState<Product[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n useEffect(() => {\n let active = true;\n setIsLoading(true);\n request<{ products: Product[] }>(\"GET\", \"/products\")\n .then((r) => {\n if (!active) return;\n setProducts(r.products);\n setError(null);\n })\n .catch((err) => {\n if (active) setError(err instanceof Error ? err : new Error(String(err)));\n })\n .finally(() => {\n if (active) setIsLoading(false);\n });\n return () => {\n active = false;\n };\n }, [request]);\n\n return { products, isLoading, error };\n}\n\nexport interface PublishableConfig {\n /** A publishable key (`bl_<env>_pk_…`) - safe to ship in a frontend bundle. */\n publishableKey: string;\n /** The Billow API base URL. Defaults to the hosted API, `https://api.usebillow.com`. */\n baseUrl?: string;\n}\n\n/**\n * Drop-in catalog reader for a pure-SPA pricing table: fetches the public products +\n * prices directly from the browser with a publishable key (CORS-enabled), no backend\n * handler required. Reads only public data - customer entitlements/checkout still need\n * the server handler or a portal session.\n */\nexport function usePublishableProducts(config: PublishableConfig): {\n products: Product[];\n isLoading: boolean;\n error: string | null;\n} {\n const { publishableKey, baseUrl } = config;\n const [products, setProducts] = useState<Product[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n useEffect(() => {\n let active = true;\n setIsLoading(true);\n const client = new BillowPublishable(publishableKey, baseUrl ? { baseUrl } : {});\n client.products.list().then(\n (list) => {\n if (!active) return;\n setProducts(list);\n setError(null);\n setIsLoading(false);\n },\n (e: unknown) => {\n if (!active) return;\n setError(e instanceof Error ? e.message : String(e));\n setIsLoading(false);\n },\n );\n return () => {\n active = false;\n };\n }, [publishableKey, baseUrl]);\n\n return { products, isLoading, error };\n}\n"]}
package/dist/react.d.cts CHANGED
@@ -1,9 +1,9 @@
1
1
  import * as react from 'react';
2
2
  import { ReactNode } from 'react';
3
- import { A as AttachResult, b as CheckResult, E as EntitlementView, P as Product, T as TrackResult } from './billing-B16zL5xU.cjs';
3
+ import { A as AttachResult, b as CheckResult, E as EntitlementView, P as Product, T as TrackResult } from './billing-8ug1Gw05.cjs';
4
4
  import './index.d-DSEYhV2c.cjs';
5
5
  import 'zod';
6
- import './billing-status-BZQN_gm7.cjs';
6
+ import './billing-status-DZkB0VPK.cjs';
7
7
 
8
8
  interface BillowProviderProps {
9
9
  children: ReactNode;
@@ -22,7 +22,7 @@ declare function useEntitlements(): {
22
22
  };
23
23
  /**
24
24
  * Gate a feature, derived client-side from the cached entitlements (no round-trip).
25
- * `error` is set when the entitlements fetch failed — distinguish that from a real
25
+ * `error` is set when the entitlements fetch failed - distinguish that from a real
26
26
  * `allowed: false` (otherwise an auth/network failure looks like a denied feature).
27
27
  */
28
28
  declare function useCheck(featureId: string): CheckResult & {
@@ -37,7 +37,7 @@ declare function useAttach(): (input: {
37
37
  redirect?: boolean;
38
38
  }) => Promise<AttachResult>;
39
39
  /**
40
- * Record usage from the browser. Requires the handler's `allowClientTrack` — most
40
+ * Record usage from the browser. Requires the handler's `allowClientTrack` - most
41
41
  * apps should `track` server-side instead (a browser caller can forge usage).
42
42
  */
43
43
  declare function useTrack(): (input: {
@@ -52,7 +52,7 @@ declare function useProducts(): {
52
52
  error: Error | null;
53
53
  };
54
54
  interface PublishableConfig {
55
- /** A publishable key (`bl_<env>_pk_…`) — safe to ship in a frontend bundle. */
55
+ /** A publishable key (`bl_<env>_pk_…`) - safe to ship in a frontend bundle. */
56
56
  publishableKey: string;
57
57
  /** The Billow API base URL. Defaults to the hosted API, `https://api.usebillow.com`. */
58
58
  baseUrl?: string;
@@ -60,7 +60,7 @@ interface PublishableConfig {
60
60
  /**
61
61
  * Drop-in catalog reader for a pure-SPA pricing table: fetches the public products +
62
62
  * prices directly from the browser with a publishable key (CORS-enabled), no backend
63
- * handler required. Reads only public data — customer entitlements/checkout still need
63
+ * handler required. Reads only public data - customer entitlements/checkout still need
64
64
  * the server handler or a portal session.
65
65
  */
66
66
  declare function usePublishableProducts(config: PublishableConfig): {
package/dist/react.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import * as react from 'react';
2
2
  import { ReactNode } from 'react';
3
- import { A as AttachResult, b as CheckResult, E as EntitlementView, P as Product, T as TrackResult } from './billing-BF4OGaLI.js';
3
+ import { A as AttachResult, b as CheckResult, E as EntitlementView, P as Product, T as TrackResult } from './billing-Bs10EcjR.js';
4
4
  import './index.d-DSEYhV2c.js';
5
5
  import 'zod';
6
- import './billing-status-BZQN_gm7.js';
6
+ import './billing-status-DZkB0VPK.js';
7
7
 
8
8
  interface BillowProviderProps {
9
9
  children: ReactNode;
@@ -22,7 +22,7 @@ declare function useEntitlements(): {
22
22
  };
23
23
  /**
24
24
  * Gate a feature, derived client-side from the cached entitlements (no round-trip).
25
- * `error` is set when the entitlements fetch failed — distinguish that from a real
25
+ * `error` is set when the entitlements fetch failed - distinguish that from a real
26
26
  * `allowed: false` (otherwise an auth/network failure looks like a denied feature).
27
27
  */
28
28
  declare function useCheck(featureId: string): CheckResult & {
@@ -37,7 +37,7 @@ declare function useAttach(): (input: {
37
37
  redirect?: boolean;
38
38
  }) => Promise<AttachResult>;
39
39
  /**
40
- * Record usage from the browser. Requires the handler's `allowClientTrack` — most
40
+ * Record usage from the browser. Requires the handler's `allowClientTrack` - most
41
41
  * apps should `track` server-side instead (a browser caller can forge usage).
42
42
  */
43
43
  declare function useTrack(): (input: {
@@ -52,7 +52,7 @@ declare function useProducts(): {
52
52
  error: Error | null;
53
53
  };
54
54
  interface PublishableConfig {
55
- /** A publishable key (`bl_<env>_pk_…`) — safe to ship in a frontend bundle. */
55
+ /** A publishable key (`bl_<env>_pk_…`) - safe to ship in a frontend bundle. */
56
56
  publishableKey: string;
57
57
  /** The Billow API base URL. Defaults to the hosted API, `https://api.usebillow.com`. */
58
58
  baseUrl?: string;
@@ -60,7 +60,7 @@ interface PublishableConfig {
60
60
  /**
61
61
  * Drop-in catalog reader for a pure-SPA pricing table: fetches the public products +
62
62
  * prices directly from the browser with a publishable key (CORS-enabled), no backend
63
- * handler required. Reads only public data — customer entitlements/checkout still need
63
+ * handler required. Reads only public data - customer entitlements/checkout still need
64
64
  * the server handler or a portal session.
65
65
  */
66
66
  declare function usePublishableProducts(config: PublishableConfig): {
package/dist/react.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use client";
2
- import { BillowPublishable } from './chunk-GT5VBLN5.js';
3
- import './chunk-CCG4F5FK.js';
2
+ import { BillowPublishable } from './chunk-XUFQG6EA.js';
3
+ import './chunk-47J7FYM5.js';
4
4
  import { createContext, useCallback, useState, useEffect, useMemo, useContext } from 'react';
5
5
  import { jsx } from 'react/jsx-runtime';
6
6
 
package/dist/react.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/react.tsx"],"names":[],"mappings":";;;;;AAoCA,IAAM,aAAA,GAAgB,cAAyC,IAAI,CAAA;AAU5D,SAAS,cAAA,CAAe;AAAA,EAC7B,QAAA;AAAA,EACA,QAAA,GAAW,aAAA;AAAA,EACX;AACF,CAAA,EAAwB;AACtB,EAAA,MAAM,IAAA,GAAO,QAAA,CAAS,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AACvC,EAAA,MAAM,OAAA,GAAU,WAAY,UAAA,CAAW,KAAA;AAEvC,EAAA,MAAM,OAAA,GAAU,WAAA;AAAA,IACd,OAAW,MAAA,EAAgB,IAAA,EAAc,IAAA,KAA+B;AACtE,MAAA,MAAM,IAAA,GAAoB,EAAE,MAAA,EAAO;AACnC,MAAA,IAAI,IAAA,EAAM;AACR,QAAA,IAAA,CAAK,OAAA,GAAU,EAAE,cAAA,EAAgB,kBAAA,EAAmB;AACpD,QAAA,IAAA,CAAK,IAAA,GAAO,IAAA,CAAK,SAAA,CAAU,IAAI,CAAA;AAAA,MACjC;AACA,MAAA,MAAM,GAAA,GAAM,MAAM,OAAA,CAAQ,CAAA,EAAG,IAAI,CAAA,EAAG,IAAI,IAAI,IAAI,CAAA;AAChD,MAAA,MAAM,IAAA,GAAQ,MAAM,GAAA,CAAI,IAAA,GAAO,KAAA,CAAM,OAAO,EAAC,CAAE,CAAA;AAC/C,MAAA,IAAI,CA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,MACA,CAAC,CAAA,KAAe;AACd,QAAA,IAAI,CAAC,MAAA,EAAQ;AACb,QAAA,QAAA,CAAS,aAAa,KAAA,GAAQ,CAAA,CAAE,OAAA,GAAU,MAAA,CAAO,CAAC,CAAC,CAAA;AACnD,QAAA,YAAA,CAAa,KAAK,CAAA;AAAA,MACpB;AAAA,KACF;AACA,IAAA,OAAO,MAAM;AACX,MAAA,MAAA,GAAS,KAAA;AAAA,IACX,CAAA;AAAA,EACF,CAAA,EAAG,CAAC,cAAA,EAAgB,OAAO,CAAC,CAAA;AAE5B,EAAA,OAAO,EAAE,QAAA,EAAU,SAAA,EAAW,KAAA,EAAM;AACtC","file":"react.js","sourcesContent":["\"use client\";\n\n/**\n * React adapter (ARCHITECTURE §6: \"framework adapters — React hooks first\"). These\n * hooks talk to the same-origin billow handler (`@usebillow/sdk/server`), never to billow\n * directly — the secret key stays on your server and the customer is resolved from\n * your session. Wrap your app in `<BillowProvider>` and use the hooks below.\n *\n * <BillowProvider>\n * <App />\n * </BillowProvider>\n *\n * const { allowed } = useCheck(\"projects\");\n * const attach = useAttach();\n * <button onClick={() => attach({ productId: \"pro\" }, { redirect: true })}>Upgrade</button>\n */\nimport {\n createContext,\n type ReactNode,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n} from \"react\";\nimport type { AttachResult, CheckResult, EntitlementView, Product, TrackResult } from \"./index\";\nimport { BillowPublishable } from \"./index\";\n\ninterface BillowContextValue {\n request: <T>(method: string, path: string, body?: unknown) => Promise<T>;\n entitlements: EntitlementView[];\n isLoading: boolean;\n error: Error | null;\n refresh: () => Promise<void>;\n}\n\nconst BillowContext = createContext<BillowContextValue | null>(null);\n\nexport interface BillowProviderProps {\n children: ReactNode;\n /** Where the billow handler is mounted. Default `/api/billow`. */\n basePath?: string;\n /** Custom fetch (SSR/testing). Defaults to the global `fetch`. */\n fetcher?: typeof fetch;\n}\n\nexport function BillowProvider({\n children,\n basePath = \"/api/billow\",\n fetcher,\n}: BillowProviderProps) {\n const base = basePath.replace(/\\/$/, \"\");\n const doFetch = fetcher ?? (globalThis.fetch as typeof fetch);\n\n const request = useCallback(\n async <T,>(method: string, path: string, body?: unknown): Promise<T> => {\n const init: RequestInit = { method };\n if (body) {\n init.headers = { \"content-type\": \"application/json\" };\n init.body = JSON.stringify(body);\n }\n const res = await doFetch(`${base}${path}`, init);\n const data = (await res.json().catch(() => ({}))) as { error?: { message?: string } };\n if (!res.ok) {\n throw new Error(data.error?.message ?? `billow ${method} ${path} failed (${res.status})`);\n }\n return data as T;\n },\n [base, doFetch],\n );\n\n const [entitlements, setEntitlements] = useState<EntitlementView[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n const refresh = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n try {\n const data = await request<{ entitlements: EntitlementView[] }>(\"GET\", \"/entitlements\");\n setEntitlements(data.entitlements);\n } catch (err) {\n setError(err instanceof Error ? err : new Error(String(err)));\n } finally {\n setIsLoading(false);\n }\n }, [request]);\n\n useEffect(() => {\n void refresh();\n }, [refresh]);\n\n const value = useMemo<BillowContextValue>(\n () => ({ request, entitlements, isLoading, error, refresh }),\n [request, entitlements, isLoading, error, refresh],\n );\n\n return <BillowContext.Provider value={value}>{children}</BillowContext.Provider>;\n}\n\nfunction useBillowContext(): BillowContextValue {\n const ctx = useContext(BillowContext);\n if (!ctx) throw new Error(\"billow: wrap your app in <BillowProvider>\");\n return ctx;\n}\n\n/** The identified customer's live entitlements (one per granted feature), with a `refresh`. */\nexport function useEntitlements(): {\n entitlements: EntitlementView[];\n isLoading: boolean;\n error: Error | null;\n refresh: () => Promise<void>;\n} {\n const { entitlements, isLoading, error, refresh } = useBillowContext();\n return { entitlements, isLoading, error, refresh };\n}\n\n/**\n * Gate a feature, derived client-side from the cached entitlements (no round-trip).\n * `error` is set when the entitlements fetch failed — distinguish that from a real\n * `allowed: false` (otherwise an auth/network failure looks like a denied feature).\n */\nexport function useCheck(\n featureId: string,\n): CheckResult & { isLoading: boolean; error: Error | null } {\n const { entitlements, isLoading, error } = useBillowContext();\n const match = entitlements.find((e) => e.feature === featureId);\n return {\n feature: featureId,\n allowed: match?.allowed ?? false,\n balance: match?.balance ?? null,\n isLoading,\n error,\n };\n}\n\n/** Start a subscription → checkout URL. Pass `{ redirect: true }` to navigate to it. */\nexport function useAttach(): (\n input: { productId: string; couponCode?: string },\n opts?: { redirect?: boolean },\n) => Promise<AttachResult> {\n const { request, refresh } = useBillowContext();\n return useCallback(\n async (input, opts = {}) => {\n const result = await request<AttachResult>(\"POST\", \"/attach\", input);\n await refresh();\n const loc = (globalThis as { location?: { href: string } }).location;\n if (opts.redirect && result.url && loc) loc.href = result.url;\n return result;\n },\n [request, refresh],\n );\n}\n\n/**\n * Record usage from the browser. Requires the handler's `allowClientTrack` — most\n * apps should `track` server-side instead (a browser caller can forge usage).\n */\nexport function useTrack(): (input: {\n featureId: string;\n value?: number;\n idempotencyKey?: string;\n}) => Promise<TrackResult> {\n const { request, refresh } = useBillowContext();\n return useCallback(\n async (input) => {\n const result = await request<TrackResult>(\"POST\", \"/track\", input);\n await refresh();\n return result;\n },\n [request, refresh],\n );\n}\n\n/** Fetch the public product catalog (for a pricing table). */\nexport function useProducts(): { products: Product[]; isLoading: boolean; error: Error | null } {\n const { request } = useBillowContext();\n const [products, setProducts] = useState<Product[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n useEffect(() => {\n let active = true;\n setIsLoading(true);\n request<{ products: Product[] }>(\"GET\", \"/products\")\n .then((r) => {\n if (!active) return;\n setProducts(r.products);\n setError(null);\n })\n .catch((err) => {\n if (active) setError(err instanceof Error ? err : new Error(String(err)));\n })\n .finally(() => {\n if (active) setIsLoading(false);\n });\n return () => {\n active = false;\n };\n }, [request]);\n\n return { products, isLoading, error };\n}\n\nexport interface PublishableConfig {\n /** A publishable key (`bl_<env>_pk_…`) — safe to ship in a frontend bundle. */\n publishableKey: string;\n /** The Billow API base URL. Defaults to the hosted API, `https://api.usebillow.com`. */\n baseUrl?: string;\n}\n\n/**\n * Drop-in catalog reader for a pure-SPA pricing table: fetches the public products +\n * prices directly from the browser with a publishable key (CORS-enabled), no backend\n * handler required. Reads only public data — customer entitlements/checkout still need\n * the server handler or a portal session.\n */\nexport function usePublishableProducts(config: PublishableConfig): {\n products: Product[];\n isLoading: boolean;\n error: string | null;\n} {\n const { publishableKey, baseUrl } = config;\n const [products, setProducts] = useState<Product[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n useEffect(() => {\n let active = true;\n setIsLoading(true);\n const client = new BillowPublishable(publishableKey, baseUrl ? { baseUrl } : {});\n client.products.list().then(\n (list) => {\n if (!active) return;\n setProducts(list);\n setError(null);\n setIsLoading(false);\n },\n (e: unknown) => {\n if (!active) return;\n setError(e instanceof Error ? e.message : String(e));\n setIsLoading(false);\n },\n );\n return () => {\n active = false;\n };\n }, [publishableKey, baseUrl]);\n\n return { products, isLoading, error };\n}\n"]}
1
+ {"version":3,"sources":["../src/react.tsx"],"names":[],"mappings":";;;;;AAoCA,IAAM,aAAA,GAAgB,cAAyC,IAAI,CAAA;AAU5D,SAAS,cAAA,CAAe;AAAA,EAC7B,QAAA;AAAA,EACA,QAAA,GAAW,aAAA;AAAA,EACX;AACF,CAAA,EAAwB;AACtB,EAAA,MAAM,IAAA,GAAO,QAAA,CAAS,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AACvC,EAAA,MAAM,OAAA,GAAU,WAAY,UAAA,CAAW,KAAA;AAEvC,EAAA,MAAM,OAAA,GAAU,WAAA;AAAA,IACd,OAAW,MAAA,EAAgB,IAAA,EAAc,IAAA,KAA+B;AACtE,MAAA,MAAM,IAAA,GAAoB,EAAE,MAAA,EAAO;AACnC,MAAA,IAAI,IAAA,EAAM;AACR,QAAA,IAAA,CAAK,OAAA,GAAU,EAAE,cAAA,EAAgB,kBAAA,EAAmB;AACpD,QAAA,IAA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U,EAAE,OAAA,EAAQ,GAAI,EAAE,CAAA;AAC/E,IAAA,MAAA,CAAO,QAAA,CAAS,MAAK,CAAE,IAAA;AAAA,MACrB,CAAC,IAAA,KAAS;AACR,QAAA,IAAI,CAAC,MAAA,EAAQ;AACb,QAAA,WAAA,CAAY,IAAI,CAAA;AAChB,QAAA,QAAA,CAAS,IAAI,CAAA;AACb,QAAA,YAAA,CAAa,KAAK,CAAA;AAAA,MACpB,CAAA;AAAA,MACA,CAAC,CAAA,KAAe;AACd,QAAA,IAAI,CAAC,MAAA,EAAQ;AACb,QAAA,QAAA,CAAS,aAAa,KAAA,GAAQ,CAAA,CAAE,OAAA,GAAU,MAAA,CAAO,CAAC,CAAC,CAAA;AACnD,QAAA,YAAA,CAAa,KAAK,CAAA;AAAA,MACpB;AAAA,KACF;AACA,IAAA,OAAO,MAAM;AACX,MAAA,MAAA,GAAS,KAAA;AAAA,IACX,CAAA;AAAA,EACF,CAAA,EAAG,CAAC,cAAA,EAAgB,OAAO,CAAC,CAAA;AAE5B,EAAA,OAAO,EAAE,QAAA,EAAU,SAAA,EAAW,KAAA,EAAM;AACtC","file":"react.js","sourcesContent":["\"use client\";\n\n/**\n * React adapter (ARCHITECTURE §6: \"framework adapters - React hooks first\"). These\n * hooks talk to the same-origin billow handler (`@usebillow/sdk/server`), never to billow\n * directly - the secret key stays on your server and the customer is resolved from\n * your session. Wrap your app in `<BillowProvider>` and use the hooks below.\n *\n * <BillowProvider>\n * <App />\n * </BillowProvider>\n *\n * const { allowed } = useCheck(\"projects\");\n * const attach = useAttach();\n * <button onClick={() => attach({ productId: \"pro\" }, { redirect: true })}>Upgrade</button>\n */\nimport {\n createContext,\n type ReactNode,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n} from \"react\";\nimport type { AttachResult, CheckResult, EntitlementView, Product, TrackResult } from \"./index\";\nimport { BillowPublishable } from \"./index\";\n\ninterface BillowContextValue {\n request: <T>(method: string, path: string, body?: unknown) => Promise<T>;\n entitlements: EntitlementView[];\n isLoading: boolean;\n error: Error | null;\n refresh: () => Promise<void>;\n}\n\nconst BillowContext = createContext<BillowContextValue | null>(null);\n\nexport interface BillowProviderProps {\n children: ReactNode;\n /** Where the billow handler is mounted. Default `/api/billow`. */\n basePath?: string;\n /** Custom fetch (SSR/testing). Defaults to the global `fetch`. */\n fetcher?: typeof fetch;\n}\n\nexport function BillowProvider({\n children,\n basePath = \"/api/billow\",\n fetcher,\n}: BillowProviderProps) {\n const base = basePath.replace(/\\/$/, \"\");\n const doFetch = fetcher ?? (globalThis.fetch as typeof fetch);\n\n const request = useCallback(\n async <T,>(method: string, path: string, body?: unknown): Promise<T> => {\n const init: RequestInit = { method };\n if (body) {\n init.headers = { \"content-type\": \"application/json\" };\n init.body = JSON.stringify(body);\n }\n const res = await doFetch(`${base}${path}`, init);\n const data = (await res.json().catch(() => ({}))) as { error?: { message?: string } };\n if (!res.ok) {\n throw new Error(data.error?.message ?? `billow ${method} ${path} failed (${res.status})`);\n }\n return data as T;\n },\n [base, doFetch],\n );\n\n const [entitlements, setEntitlements] = useState<EntitlementView[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n const refresh = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n try {\n const data = await request<{ entitlements: EntitlementView[] }>(\"GET\", \"/entitlements\");\n setEntitlements(data.entitlements);\n } catch (err) {\n setError(err instanceof Error ? err : new Error(String(err)));\n } finally {\n setIsLoading(false);\n }\n }, [request]);\n\n useEffect(() => {\n void refresh();\n }, [refresh]);\n\n const value = useMemo<BillowContextValue>(\n () => ({ request, entitlements, isLoading, error, refresh }),\n [request, entitlements, isLoading, error, refresh],\n );\n\n return <BillowContext.Provider value={value}>{children}</BillowContext.Provider>;\n}\n\nfunction useBillowContext(): BillowContextValue {\n const ctx = useContext(BillowContext);\n if (!ctx) throw new Error(\"billow: wrap your app in <BillowProvider>\");\n return ctx;\n}\n\n/** The identified customer's live entitlements (one per granted feature), with a `refresh`. */\nexport function useEntitlements(): {\n entitlements: EntitlementView[];\n isLoading: boolean;\n error: Error | null;\n refresh: () => Promise<void>;\n} {\n const { entitlements, isLoading, error, refresh } = useBillowContext();\n return { entitlements, isLoading, error, refresh };\n}\n\n/**\n * Gate a feature, derived client-side from the cached entitlements (no round-trip).\n * `error` is set when the entitlements fetch failed - distinguish that from a real\n * `allowed: false` (otherwise an auth/network failure looks like a denied feature).\n */\nexport function useCheck(\n featureId: string,\n): CheckResult & { isLoading: boolean; error: Error | null } {\n const { entitlements, isLoading, error } = useBillowContext();\n const match = entitlements.find((e) => e.feature === featureId);\n return {\n feature: featureId,\n allowed: match?.allowed ?? false,\n balance: match?.balance ?? null,\n isLoading,\n error,\n };\n}\n\n/** Start a subscription → checkout URL. Pass `{ redirect: true }` to navigate to it. */\nexport function useAttach(): (\n input: { productId: string; couponCode?: string },\n opts?: { redirect?: boolean },\n) => Promise<AttachResult> {\n const { request, refresh } = useBillowContext();\n return useCallback(\n async (input, opts = {}) => {\n const result = await request<AttachResult>(\"POST\", \"/attach\", input);\n await refresh();\n const loc = (globalThis as { location?: { href: string } }).location;\n if (opts.redirect && result.url && loc) loc.href = result.url;\n return result;\n },\n [request, refresh],\n );\n}\n\n/**\n * Record usage from the browser. Requires the handler's `allowClientTrack` - most\n * apps should `track` server-side instead (a browser caller can forge usage).\n */\nexport function useTrack(): (input: {\n featureId: string;\n value?: number;\n idempotencyKey?: string;\n}) => Promise<TrackResult> {\n const { request, refresh } = useBillowContext();\n return useCallback(\n async (input) => {\n const result = await request<TrackResult>(\"POST\", \"/track\", input);\n await refresh();\n return result;\n },\n [request, refresh],\n );\n}\n\n/** Fetch the public product catalog (for a pricing table). */\nexport function useProducts(): { products: Product[]; isLoading: boolean; error: Error | null } {\n const { request } = useBillowContext();\n const [products, setProducts] = useState<Product[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n useEffect(() => {\n let active = true;\n setIsLoading(true);\n request<{ products: Product[] }>(\"GET\", \"/products\")\n .then((r) => {\n if (!active) return;\n setProducts(r.products);\n setError(null);\n })\n .catch((err) => {\n if (active) setError(err instanceof Error ? err : new Error(String(err)));\n })\n .finally(() => {\n if (active) setIsLoading(false);\n });\n return () => {\n active = false;\n };\n }, [request]);\n\n return { products, isLoading, error };\n}\n\nexport interface PublishableConfig {\n /** A publishable key (`bl_<env>_pk_…`) - safe to ship in a frontend bundle. */\n publishableKey: string;\n /** The Billow API base URL. Defaults to the hosted API, `https://api.usebillow.com`. */\n baseUrl?: string;\n}\n\n/**\n * Drop-in catalog reader for a pure-SPA pricing table: fetches the public products +\n * prices directly from the browser with a publishable key (CORS-enabled), no backend\n * handler required. Reads only public data - customer entitlements/checkout still need\n * the server handler or a portal session.\n */\nexport function usePublishableProducts(config: PublishableConfig): {\n products: Product[];\n isLoading: boolean;\n error: string | null;\n} {\n const { publishableKey, baseUrl } = config;\n const [products, setProducts] = useState<Product[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n useEffect(() => {\n let active = true;\n setIsLoading(true);\n const client = new BillowPublishable(publishableKey, baseUrl ? { baseUrl } : {});\n client.products.list().then(\n (list) => {\n if (!active) return;\n setProducts(list);\n setError(null);\n setIsLoading(false);\n },\n (e: unknown) => {\n if (!active) return;\n setError(e instanceof Error ? e.message : String(e));\n setIsLoading(false);\n },\n );\n return () => {\n active = false;\n };\n }, [publishableKey, baseUrl]);\n\n return { products, isLoading, error };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/server.ts"],"names":[],"mappings":";;;AA+CO,SAAS,mBAAA,CAAoB,QAAgB,IAAA,EAAqC;AACvF,EAAA,MAAM,YAAY,IAAA,CAAK,QAAA,IAAY,aAAA,EAAe,OAAA,CAAQ,OAAO,EAAE,CAAA;AAEnE,EAAA,OAAO,eAAe,QAAQ,GAAA,EAAiC;AAC7D,IAAA,MAAM,KAAA,GAAQ,SAAS,IAAI,GAAA,CA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ACzD,IAAA,IAAI,MAAA,CAAO,UAAU,MAAM,CAAA,IAAK,UAAU,GAAA,IAAO,MAAA,IAAU,KAAK,OAAO,MAAA;AAAA,EACzE;AACA,EAAA,OAAO,GAAA;AACT;AAEA,SAAS,UAAU,GAAA,EAAsB;AACvC,EAAA,IAAI,GAAA,IAAO,OAAO,GAAA,KAAQ,QAAA,IAAY,MAAA,IAAU,GAAA;AAC9C,IAAA,OAAO,MAAA,CAAQ,IAA0B,IAAI,CAAA;AAC/C,EAAA,OAAO,OAAA;AACT;AAEA,SAAS,aAAa,GAAA,EAAsB;AAC1C,EAAA,OAAO,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,sBAAA;AAC9C","file":"server.cjs","sourcesContent":["/**\n * Backend handler for the browser-facing surface (the React hooks talk to this,\n * never to billow directly). Mount it at `/api/billow/*` in your app; it holds the\n * secret key server-side and resolves the customer from *your* session via\n * `identify` — so the browser can never choose which customer it is.\n *\n * // Next.js app/api/billow/[...billow]/route.ts\n * import { Billow } from \"@usebillow/sdk\";\n * import { createBillowHandler } from \"@usebillow/sdk/server\";\n * const billow = new Billow(process.env.BILLOW_SECRET_KEY!);\n * const handler = createBillowHandler(billow, {\n * identify: async (req) => (await getSession(req))?.customerId ?? null,\n * });\n * export { handler as GET, handler as POST };\n *\n * Exposed (all customer-scoped except the public catalog):\n * GET /products — catalog for pricing tables (no customer needed)\n * GET /entitlements — the identified customer's live entitlements\n * POST /check — gate one feature for the identified customer\n * POST /attach — start a subscription the customer pays for\n *\n * **Not** exposed by default: `track`. Recording usage from the browser would let\n * a user forge their own balance (`value: -999999`) — it is a server-trust verb.\n * Call `billow.track(...)` from your backend when the metered event happens. If you\n * accept the risk for a low-stakes counter, opt in with `allowClientTrack: true`.\n */\nimport type { Billow } from \"./index\";\n\nexport interface BillowHandlerOptions {\n /**\n * Resolve the **trusted** customer id from the request (your own session/auth).\n * Return `null` when unauthenticated — customer-scoped routes then 401.\n */\n identify: (req: Request) => Promise<string | null> | string | null;\n /** Path the handler is mounted under. Default `/api/billow`. */\n basePath?: string;\n /** Fixed post-checkout return URL (the client cannot override it). */\n checkoutReturnUrl?: string;\n /**\n * Allow the browser to POST `/track`. Off by default — see the file header.\n * Only enable for usage a malicious client forging is acceptable for.\n */\n allowClientTrack?: boolean;\n}\n\ntype Handler = (req: Request) => Promise<Response>;\n\nexport function createBillowHandler(billow: Billow, opts: BillowHandlerOptions): Handler {\n const basePath = (opts.basePath ?? \"/api/billow\").replace(/\\/$/, \"\");\n\n return async function handler(req: Request): Promise<Response> {\n const route = subRoute(new URL(req.url).pathname, basePath);\n const method = req.method.toUpperCase();\n if (route === null) {\n return json({ error: { code: \"not_found\", message: \"Not a billow route\" } }, 404);\n }\n\n try {\n // Public catalog — no customer needed (pricing tables).\n if (method === \"GET\" && route === \"/products\") {\n return json({ products: await billow.products.list() });\n }\n\n // Everything else is scoped to the server-identified customer.\n const customerId = await opts.identify(req);\n if (!customerId) {\n return json({ error: { code: \"unauthenticated\", message: \"No customer\" } }, 401);\n }\n\n if (method === \"GET\" && route === \"/entitlements\") {\n return json(await billow.entitlements(customerId));\n }\n if (method === \"POST\" && route === \"/check\") {\n const body = await readJson<{ featureId?: unknown }>(req);\n return json(await billow.check({ customerId, featureId: String(body.featureId) }));\n }\n if (method === \"POST\" && route === \"/attach\") {\n const body = await readJson<{ productId?: unknown; couponCode?: unknown }>(req);\n const input: Parameters<typeof billow.attach>[0] = {\n customerId,\n productId: String(body.productId),\n };\n // Only a user-entered promo is forwarded; trial/card policy is the\n // merchant's, not the client's — set those in a server-side route.\n if (body.couponCode) input.couponCode = String(body.couponCode);\n if (opts.checkoutReturnUrl) input.redirectionUrl = opts.checkoutReturnUrl;\n return json(await billow.attach(input));\n }\n if (method === \"POST\" && route === \"/track\") {\n if (!opts.allowClientTrack) {\n return json({ error: { code: \"not_found\", message: \"track is server-only\" } }, 404);\n }\n const body = await readJson<{\n featureId?: unknown;\n value?: unknown;\n idempotencyKey?: unknown;\n }>(req);\n const input: Parameters<typeof billow.track>[0] = {\n customerId,\n featureId: String(body.featureId),\n };\n if (typeof body.value === \"number\") input.value = body.value;\n if (body.idempotencyKey) input.idempotencyKey = String(body.idempotencyKey);\n return json(await billow.track(input));\n }\n\n return json(\n { error: { code: \"not_found\", message: `No billow route ${method} ${route}` } },\n 404,\n );\n } catch (err) {\n return json(\n { error: { code: errorCode(err), message: errorMessage(err) } },\n errorStatus(err),\n );\n }\n };\n}\n\n/** The path under `basePath`, or `null` when the request isn't under it at all. */\nfunction subRoute(pathname: string, basePath: string): string | null {\n if (pathname === basePath) return \"/\";\n if (!pathname.startsWith(`${basePath}/`)) return null;\n return pathname.slice(basePath.length).replace(/\\/+$/, \"\") || \"/\";\n}\n\nfunction json(data: unknown, status = 200): Response {\n return new Response(JSON.stringify(data), {\n status,\n headers: { \"content-type\": \"application/json\" },\n });\n}\n\nasync function readJson<T = Record<string, unknown>>(req: Request): Promise<T> {\n try {\n return (await req.json()) as T;\n } catch {\n return {} as T;\n }\n}\n\nfunction errorStatus(err: unknown): number {\n if (err && typeof err === \"object\" && \"status\" in err) {\n const status = Number((err as { status: unknown }).status);\n if (Number.isInteger(status) && status >= 400 && status <= 599) return status;\n }\n return 500;\n}\n\nfunction errorCode(err: unknown): string {\n if (err && typeof err === \"object\" && \"code\" in err)\n return String((err as { code: unknown }).code);\n return \"error\";\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : \"billow handler error\";\n}\n"]}
1
+ {"version":3,"sources":["../src/server.ts"],"names":[],"mappings":";;;AA+CO,SAAS,mBAAA,CAAoB,QAAgB,IAAA,EAAqC;AACvF,EAAA,MAAM,YAAY,IAAA,CAAK,QAAA,IAAY,aAAA,EAAe,OAAA,CAAQ,OAAO,EAAE,CAAA;AAEnE,EAAA,OAAO,eAAe,QAAQ,GAAA,EAAiC;AAC7D,IAAA,MAAM,KAAA,GAAQ,SAAS,IAAI,GAAA,CAAI,IAAI,GAAG,CAAA,CAAE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O,UAAU,MAAM,CAAA,IAAK,UAAU,GAAA,IAAO,MAAA,IAAU,KAAK,OAAO,MAAA;AAAA,EACzE;AACA,EAAA,OAAO,GAAA;AACT;AAEA,SAAS,UAAU,GAAA,EAAsB;AACvC,EAAA,IAAI,GAAA,IAAO,OAAO,GAAA,KAAQ,QAAA,IAAY,MAAA,IAAU,GAAA;AAC9C,IAAA,OAAO,MAAA,CAAQ,IAA0B,IAAI,CAAA;AAC/C,EAAA,OAAO,OAAA;AACT;AAEA,SAAS,aAAa,GAAA,EAAsB;AAC1C,EAAA,OAAO,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,sBAAA;AAC9C","file":"server.cjs","sourcesContent":["/**\n * Backend handler for the browser-facing surface (the React hooks talk to this,\n * never to billow directly). Mount it at `/api/billow/*` in your app; it holds the\n * secret key server-side and resolves the customer from *your* session via\n * `identify` - so the browser can never choose which customer it is.\n *\n * // Next.js app/api/billow/[...billow]/route.ts\n * import { Billow } from \"@usebillow/sdk\";\n * import { createBillowHandler } from \"@usebillow/sdk/server\";\n * const billow = new Billow(process.env.BILLOW_SECRET_KEY!);\n * const handler = createBillowHandler(billow, {\n * identify: async (req) => (await getSession(req))?.customerId ?? null,\n * });\n * export { handler as GET, handler as POST };\n *\n * Exposed (all customer-scoped except the public catalog):\n * GET /products - catalog for pricing tables (no customer needed)\n * GET /entitlements - the identified customer's live entitlements\n * POST /check - gate one feature for the identified customer\n * POST /attach - start a subscription the customer pays for\n *\n * **Not** exposed by default: `track`. Recording usage from the browser would let\n * a user forge their own balance (`value: -999999`) - it is a server-trust verb.\n * Call `billow.track(...)` from your backend when the metered event happens. If you\n * accept the risk for a low-stakes counter, opt in with `allowClientTrack: true`.\n */\nimport type { Billow } from \"./index\";\n\nexport interface BillowHandlerOptions {\n /**\n * Resolve the **trusted** customer id from the request (your own session/auth).\n * Return `null` when unauthenticated - customer-scoped routes then 401.\n */\n identify: (req: Request) => Promise<string | null> | string | null;\n /** Path the handler is mounted under. Default `/api/billow`. */\n basePath?: string;\n /** Fixed post-checkout return URL (the client cannot override it). */\n checkoutReturnUrl?: string;\n /**\n * Allow the browser to POST `/track`. Off by default - see the file header.\n * Only enable for usage a malicious client forging is acceptable for.\n */\n allowClientTrack?: boolean;\n}\n\ntype Handler = (req: Request) => Promise<Response>;\n\nexport function createBillowHandler(billow: Billow, opts: BillowHandlerOptions): Handler {\n const basePath = (opts.basePath ?? \"/api/billow\").replace(/\\/$/, \"\");\n\n return async function handler(req: Request): Promise<Response> {\n const route = subRoute(new URL(req.url).pathname, basePath);\n const method = req.method.toUpperCase();\n if (route === null) {\n return json({ error: { code: \"not_found\", message: \"Not a billow route\" } }, 404);\n }\n\n try {\n // Public catalog - no customer needed (pricing tables).\n if (method === \"GET\" && route === \"/products\") {\n return json({ products: await billow.products.list() });\n }\n\n // Everything else is scoped to the server-identified customer.\n const customerId = await opts.identify(req);\n if (!customerId) {\n return json({ error: { code: \"unauthenticated\", message: \"No customer\" } }, 401);\n }\n\n if (method === \"GET\" && route === \"/entitlements\") {\n return json(await billow.entitlements(customerId));\n }\n if (method === \"POST\" && route === \"/check\") {\n const body = await readJson<{ featureId?: unknown }>(req);\n return json(await billow.check({ customerId, featureId: String(body.featureId) }));\n }\n if (method === \"POST\" && route === \"/attach\") {\n const body = await readJson<{ productId?: unknown; couponCode?: unknown }>(req);\n const input: Parameters<typeof billow.attach>[0] = {\n customerId,\n productId: String(body.productId),\n };\n // Only a user-entered promo is forwarded; trial/card policy is the\n // merchant's, not the client's - set those in a server-side route.\n if (body.couponCode) input.couponCode = String(body.couponCode);\n if (opts.checkoutReturnUrl) input.redirectionUrl = opts.checkoutReturnUrl;\n return json(await billow.attach(input));\n }\n if (method === \"POST\" && route === \"/track\") {\n if (!opts.allowClientTrack) {\n return json({ error: { code: \"not_found\", message: \"track is server-only\" } }, 404);\n }\n const body = await readJson<{\n featureId?: unknown;\n value?: unknown;\n idempotencyKey?: unknown;\n }>(req);\n const input: Parameters<typeof billow.track>[0] = {\n customerId,\n featureId: String(body.featureId),\n };\n if (typeof body.value === \"number\") input.value = body.value;\n if (body.idempotencyKey) input.idempotencyKey = String(body.idempotencyKey);\n return json(await billow.track(input));\n }\n\n return json(\n { error: { code: \"not_found\", message: `No billow route ${method} ${route}` } },\n 404,\n );\n } catch (err) {\n return json(\n { error: { code: errorCode(err), message: errorMessage(err) } },\n errorStatus(err),\n );\n }\n };\n}\n\n/** The path under `basePath`, or `null` when the request isn't under it at all. */\nfunction subRoute(pathname: string, basePath: string): string | null {\n if (pathname === basePath) return \"/\";\n if (!pathname.startsWith(`${basePath}/`)) return null;\n return pathname.slice(basePath.length).replace(/\\/+$/, \"\") || \"/\";\n}\n\nfunction json(data: unknown, status = 200): Response {\n return new Response(JSON.stringify(data), {\n status,\n headers: { \"content-type\": \"application/json\" },\n });\n}\n\nasync function readJson<T = Record<string, unknown>>(req: Request): Promise<T> {\n try {\n return (await req.json()) as T;\n } catch {\n return {} as T;\n }\n}\n\nfunction errorStatus(err: unknown): number {\n if (err && typeof err === \"object\" && \"status\" in err) {\n const status = Number((err as { status: unknown }).status);\n if (Number.isInteger(status) && status >= 400 && status <= 599) return status;\n }\n return 500;\n}\n\nfunction errorCode(err: unknown): string {\n if (err && typeof err === \"object\" && \"code\" in err)\n return String((err as { code: unknown }).code);\n return \"error\";\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : \"billow handler error\";\n}\n"]}
package/dist/server.d.cts CHANGED
@@ -1,16 +1,16 @@
1
1
  import { Billow } from './index.cjs';
2
2
  import './index.d-DSEYhV2c.cjs';
3
3
  import 'zod';
4
- import './billing-status-BZQN_gm7.cjs';
4
+ import './billing-status-DZkB0VPK.cjs';
5
5
  import './status.cjs';
6
- import './billing-B16zL5xU.cjs';
7
- import './hosted-domains-DwakPG4J.cjs';
6
+ import './billing-8ug1Gw05.cjs';
7
+ import './hosted-domains-zWm2srOk.cjs';
8
8
 
9
9
  /**
10
10
  * Backend handler for the browser-facing surface (the React hooks talk to this,
11
11
  * never to billow directly). Mount it at `/api/billow/*` in your app; it holds the
12
12
  * secret key server-side and resolves the customer from *your* session via
13
- * `identify` — so the browser can never choose which customer it is.
13
+ * `identify` - so the browser can never choose which customer it is.
14
14
  *
15
15
  * // Next.js app/api/billow/[...billow]/route.ts
16
16
  * import { Billow } from "@usebillow/sdk";
@@ -22,13 +22,13 @@ import './hosted-domains-DwakPG4J.cjs';
22
22
  * export { handler as GET, handler as POST };
23
23
  *
24
24
  * Exposed (all customer-scoped except the public catalog):
25
- * GET /products — catalog for pricing tables (no customer needed)
26
- * GET /entitlements — the identified customer's live entitlements
27
- * POST /check — gate one feature for the identified customer
28
- * POST /attach — start a subscription the customer pays for
25
+ * GET /products - catalog for pricing tables (no customer needed)
26
+ * GET /entitlements - the identified customer's live entitlements
27
+ * POST /check - gate one feature for the identified customer
28
+ * POST /attach - start a subscription the customer pays for
29
29
  *
30
30
  * **Not** exposed by default: `track`. Recording usage from the browser would let
31
- * a user forge their own balance (`value: -999999`) — it is a server-trust verb.
31
+ * a user forge their own balance (`value: -999999`) - it is a server-trust verb.
32
32
  * Call `billow.track(...)` from your backend when the metered event happens. If you
33
33
  * accept the risk for a low-stakes counter, opt in with `allowClientTrack: true`.
34
34
  */
@@ -36,7 +36,7 @@ import './hosted-domains-DwakPG4J.cjs';
36
36
  interface BillowHandlerOptions {
37
37
  /**
38
38
  * Resolve the **trusted** customer id from the request (your own session/auth).
39
- * Return `null` when unauthenticated — customer-scoped routes then 401.
39
+ * Return `null` when unauthenticated - customer-scoped routes then 401.
40
40
  */
41
41
  identify: (req: Request) => Promise<string | null> | string | null;
42
42
  /** Path the handler is mounted under. Default `/api/billow`. */
@@ -44,7 +44,7 @@ interface BillowHandlerOptions {
44
44
  /** Fixed post-checkout return URL (the client cannot override it). */
45
45
  checkoutReturnUrl?: string;
46
46
  /**
47
- * Allow the browser to POST `/track`. Off by default — see the file header.
47
+ * Allow the browser to POST `/track`. Off by default - see the file header.
48
48
  * Only enable for usage a malicious client forging is acceptable for.
49
49
  */
50
50
  allowClientTrack?: boolean;