@usebillow/sdk 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -6,8 +6,8 @@ import { SubscriptionStatus } from './status.cjs';
6
6
  export { ACTIVE_SUBSCRIPTION_STATUSES, NEVER_ACTIVATED_SUBSCRIPTION_STATUSES, SUBSCRIPTION_STATUSES, TERMINAL_SUBSCRIPTION_STATUSES, grantsAccess, isTerminal } from './status.cjs';
7
7
  import { c as TaxBehavior, d as Customer, U as UnappliedPaymentReason, e as CreateChargeInput, R as RequestOptions, f as Charge, g as CreateMerchantInitiatedChargeInput, I as IdempotentRequestOptions, h as CallOptions, C as CreateProductInput, i as UpdateProductInput, j as MigrationResult, k as CreateSubscriptionInput, B as BillowOptions, a as CreateCouponInput, l as Coupon, F as FeatureKind, M as MeterConfig, m as Feature, n as UpdateFeatureInput, o as UsageAlert, p as CreateUsageAlertInput, b as CheckResult, T as TrackResult, E as EntitlementView, A as AttachResult } from './billing-B-VyZCXV.cjs';
8
8
  export { q as ActivatedSubscriptionResult, r as BillingInterval, s as CouponDuration, t as CouponKind, u as CreateSubscriptionResult, v as EntitlementInput, w as MeterAggregation, x as MeterFilter, y as MeterRoundingMode, z as PendingSubscriptionCheckoutResult, D as PriceInput, P as Product, G as ProductEntitlement, H as ProductPrice, S as Subscription, J as SubscriptionDetail, K as SubscriptionItem, L as UpdatePriceInput, N as UsageAlertKind, O as UsageAlertMetric, Q as UsageModel, V as UsageTier } from './billing-B-VyZCXV.cjs';
9
- import { a as CreditThresholdLevel, e as CreditGrant, f as CreditTopUp, g as CreateCreditGrantInput, h as CreditGrantRequestResult, i as CreditPacks, j as CreateCreditPackInput, k as CreditPack, U as UpdateCreditPackInput, l as CreateCreditTopUpInput, m as CreditTopUpRequestResult, n as CreditTopUpListParams, o as CreditBalance, p as CreditLedgerEntry, q as CreditUsageParams, r as CreditUsage } from './hosted-domains-BtCd-Rur.cjs';
10
- export { s as CreditAccountStatus, C as CreditGrantKind, t as CreditMoney, u as CreditPackListItem, v as CreditTopUpStatus, w as CreditTransactionType, x as CreditUsageGroupBy, H as HostedDomainActivatedData, d as HostedDomainDisabledData, b as HostedDomainDnsFailingData, y as HostedDomainEventBase, c as HostedDomainReassignmentPendingData, z as HostedDomainStatus, A as HostedDomainStatusReason } from './hosted-domains-BtCd-Rur.cjs';
9
+ import { a as CreditThresholdLevel, e as CreditGrant, f as CreditTopUp, g as CreateCreditGrantInput, h as CreditGrantRequestResult, i as CreditPacks, j as CreateCreditPackInput, k as CreditPack, U as UpdateCreditPackInput, l as CreateCreditTopUpInput, m as CreditTopUpRequestResult, n as CreditTopUpListParams, o as CreditBalance, p as CreditLedgerEntry, q as CreditUsageParams, r as CreditUsage } from './hosted-domains-BYYl2DSa.cjs';
10
+ export { s as CreditAccountStatus, C as CreditGrantKind, t as CreditMoney, u as CreditPackBreakdown, v as CreditPackListItem, w as CreditTopUpStatus, x as CreditTransactionType, y as CreditUsageGroupBy, H as HostedDomainActivatedData, d as HostedDomainDisabledData, b as HostedDomainDnsFailingData, z as HostedDomainEventBase, c as HostedDomainReassignmentPendingData, A as HostedDomainStatus, B as HostedDomainStatusReason } from './hosted-domains-BYYl2DSa.cjs';
11
11
  import 'zod';
12
12
 
13
13
  /**
@@ -902,10 +902,18 @@ interface CreatePortalSessionInput {
902
902
  flow?: PortalSessionFlow;
903
903
  /** Product slug to subscribe to — required when `flow` is `checkout`. */
904
904
  productId?: string;
905
- /** Where the surface returns the Customer when they finish or exit. */
905
+ /**
906
+ * Where the surface returns the Customer when they finish or exit: an absolute `https` URL
907
+ * without credentials (and, in live, without a port other than 443). A loopback host such as
908
+ * `localhost` is also accepted over `http`, on any port, in either environment.
909
+ */
906
910
  returnUrl?: string;
907
911
  }
908
- /** The minted portal session: redirect the Customer to `url` (it carries the bearer). */
912
+ /**
913
+ * The minted portal session: redirect the Customer to `url` at once. Its token is a single-use
914
+ * entry token - Billow's hosted portal exchanges it on first open, after which the link works
915
+ * only for the browser that opened it.
916
+ */
909
917
  interface PortalSession {
910
918
  id: string;
911
919
  url: string;
@@ -913,6 +921,21 @@ interface PortalSession {
913
921
  /** ISO-8601 expiry — the session (and its URL) stop working after this. */
914
922
  expiresAt: string;
915
923
  }
924
+ /** The single-use entry exchange's input (`BillowPortal.exchange`). */
925
+ interface PortalSessionExchangeInput {
926
+ /** The `Host` the link was opened on: it must be the host the session is bound to. */
927
+ host: string;
928
+ /** The session token the browser already holds, if any: a revisit by the browser that
929
+ * exchanged the link lands on its own session, and only that browser's. */
930
+ sessionToken?: string;
931
+ }
932
+ /** What the exchange returns: the session's bearer from now on, and its unchanged expiry. */
933
+ interface PortalSessionExchange {
934
+ sessionToken: string;
935
+ flow: PortalSessionFlow;
936
+ /** ISO-8601 expiry of the session, set when it was minted. */
937
+ expiresAt: string;
938
+ }
916
939
  /**
917
940
  * The portal shell: the session's flow + return URL, the merchant's
918
941
  * customer-facing brand, and the Customer's identity. The lightweight payload a
@@ -2803,6 +2826,13 @@ declare class BillowPortal {
2803
2826
  * the lightweight payload the hosting app frames every page with, and the
2804
2827
  * validate-and-route check at login. */
2805
2828
  session(options?: CallOptions): Promise<PortalSessionInfo>;
2829
+ /**
2830
+ * The single-use entry exchange (ADR-0039): on a client built with a minted link's entry
2831
+ * token, trade it for the session token to use from now on. Succeeds once per link, and
2832
+ * afterwards only for the browser presenting that exchange's `sessionToken`; anything else is
2833
+ * a 401. For a hosted surface; an integrator's own surface may keep using the entry token.
2834
+ */
2835
+ exchange(input: PortalSessionExchangeInput, options?: CallOptions): Promise<PortalSessionExchange>;
2806
2836
  /** The self-serve home payload: identity + subscriptions + usage + saved cards. */
2807
2837
  me(options?: CallOptions): Promise<PortalView>;
2808
2838
  invoices: {
@@ -2810,6 +2840,8 @@ declare class BillowPortal {
2810
2840
  list: (params?: ListParams & {
2811
2841
  status?: InvoiceListItem["status"];
2812
2842
  }, options?: CallOptions) => ListPromise<InvoiceListItem>;
2843
+ /** One of the Customer's invoices, in the list's shape. */
2844
+ get: (id: string, options?: CallOptions) => Promise<InvoiceListItem>;
2813
2845
  /** Open or resume checkout for this customer's outstanding invoice. */
2814
2846
  pay: (id: string, input?: PayInvoiceInput, options?: CallOptions) => Promise<{
2815
2847
  invoiceId: string;
@@ -2881,4 +2913,4 @@ declare class BillowPortal {
2881
2913
  };
2882
2914
  }
2883
2915
 
2884
- export { AttachResult, BILLOW_ERROR_CODES, Billow, BillowApiError, type BillowErrorCode, BillowOptions, BillowPortal, BillowPublishable, type BusinessProfile, CallOptions, type CatalogItem, Charge, type ChargeListItem, type ChargeListParams, type ChargeSearchHit, ChargeStatus, CheckResult, type CheckoutMethodInfo, type ConfigField, type ConfigFieldOption, type ConfigFieldType, Coupon, CreateChargeInput, CreateCouponInput, CreateCreditGrantInput, CreateCreditPackInput, type CreateCreditQuoteInput, type CreateCreditReservationInput, CreateCreditTopUpInput, CreateHostedDomainInput, CreateMerchantInitiatedChargeInput, type CreatePortalSessionInput, CreateProductInput, CreateSubscriptionInput, CreateUsageAlertInput, type CreateWebhookEndpointInput, type CredentialSet, CreditBalance, type CreditDimensions, CreditGrant, CreditGrantRequestResult, CreditLedgerEntry, type CreditLineItem, CreditPack, CreditPacks, type CreditPricedLine, type CreditQuote, type CreditRateCard, type CreditRateCardItem, type CreditReservation, type CreditReservationRequestResult, type CreditReservationStatus, type CreditReversal, type CreditReversalRequestResult, CreditThresholdLevel, CreditTopUp, CreditTopUpListParams, CreditTopUpRequestResult, CreditUsage, CreditUsageParams, type CursorListParams, type CursorListPromise, type CursorPaginated, Customer, type CustomerAnonymizationResult, type CustomerCreditsExport, type CustomerDataExport, type CustomerListItem, type CustomerListParams, type CustomerOverview, type CustomerSearchHit, type CustomerUsage, type CustomerUsageDetail, type EmailDeliveryListItem, type EmailDeliveryListParams, type EmailDeliveryStatus, type EmailTemplateSetting, EntitlementView, type ExchangeRate, type ExportJsonValue, type ExternalPaymentMethod, type ExternalPaymentResult, Feature, FeatureKind, IdempotentRequestOptions, type InboundWebhookListItem, type InboundWebhookListParams, type InboundWebhookOutcome, type IntegrationDefinition, type IntegrationKind, type IntegrationTier, type Invoice, type InvoiceDetail, type InvoiceLineItem, type InvoiceListItem, type InvoiceListParams, type InvoiceSearchHit, InvoiceStatus, type ListParams, type ListPromise, MeterConfig, type MetricsOverview, type MetricsParams, type MetricsRollup, MigrationResult, type OutboxEventListItem, type OutboxEventListParams, type OutboxEventStatus, type Paginated, PayInvoiceInput, type PaymentMethod, PaymentMethodStatus, type PaymentProviderDefinition, type PortalCardSetupResult, type PortalCheckout, type PortalPlanChange, type PortalSession, type PortalSessionFlow, type PortalSessionInfo, type PortalSubscriptionStatus, type PortalView, type ProviderCredentialSummary, type ProviderVerifyResult, type ProviderVerifyTarget, type ProviderVerifyTargetResult, type PublishCreditRateCardInput, type RecordExternalPaymentInput, type Refund, type RefundChargeInput, type RefundRequestResult, type RefundReviewReason, RefundStatus, RequestOptions, type ResolveRefundInput, type ReverseCreditConsumptionInput, SavedPaymentMethod, type ScheduledSubscriptionChange, type SearchResults, type SubscriptionListItem, type SubscriptionListParams, type SubscriptionSearchHit, SubscriptionStatus, TaxBehavior, type TimeseriesInterval, type TimeseriesMetric, type TimeseriesParams, type TimeseriesPoint, type TimeseriesResult, TrackResult, UnappliedPaymentReason, type UpdateBusinessProfileInput, UpdateCreditPackInput, type UpdateEmailTemplateInput, UpdateFeatureInput, UpdateProductInput, type UpdateWebhookEndpointInput, type UpsertCredentialsInput, UsageAlert, type WebhookDelivery, WebhookDeliveryStatus, type WebhookEndpoint, type WebhookEndpointWithSecret, type Whoami, currencyExponent, formatMoney, isSecretField, toMajorUnits, toMinorUnits };
2916
+ export { AttachResult, BILLOW_ERROR_CODES, Billow, BillowApiError, type BillowErrorCode, BillowOptions, BillowPortal, BillowPublishable, type BusinessProfile, CallOptions, type CatalogItem, Charge, type ChargeListItem, type ChargeListParams, type ChargeSearchHit, ChargeStatus, CheckResult, type CheckoutMethodInfo, type ConfigField, type ConfigFieldOption, type ConfigFieldType, Coupon, CreateChargeInput, CreateCouponInput, CreateCreditGrantInput, CreateCreditPackInput, type CreateCreditQuoteInput, type CreateCreditReservationInput, CreateCreditTopUpInput, CreateHostedDomainInput, CreateMerchantInitiatedChargeInput, type CreatePortalSessionInput, CreateProductInput, CreateSubscriptionInput, CreateUsageAlertInput, type CreateWebhookEndpointInput, type CredentialSet, CreditBalance, type CreditDimensions, CreditGrant, CreditGrantRequestResult, CreditLedgerEntry, type CreditLineItem, CreditPack, CreditPacks, type CreditPricedLine, type CreditQuote, type CreditRateCard, type CreditRateCardItem, type CreditReservation, type CreditReservationRequestResult, type CreditReservationStatus, type CreditReversal, type CreditReversalRequestResult, CreditThresholdLevel, CreditTopUp, CreditTopUpListParams, CreditTopUpRequestResult, CreditUsage, CreditUsageParams, type CursorListParams, type CursorListPromise, type CursorPaginated, Customer, type CustomerAnonymizationResult, type CustomerCreditsExport, type CustomerDataExport, type CustomerListItem, type CustomerListParams, type CustomerOverview, type CustomerSearchHit, type CustomerUsage, type CustomerUsageDetail, type EmailDeliveryListItem, type EmailDeliveryListParams, type EmailDeliveryStatus, type EmailTemplateSetting, EntitlementView, type ExchangeRate, type ExportJsonValue, type ExternalPaymentMethod, type ExternalPaymentResult, Feature, FeatureKind, IdempotentRequestOptions, type InboundWebhookListItem, type InboundWebhookListParams, type InboundWebhookOutcome, type IntegrationDefinition, type IntegrationKind, type IntegrationTier, type Invoice, type InvoiceDetail, type InvoiceLineItem, type InvoiceListItem, type InvoiceListParams, type InvoiceSearchHit, InvoiceStatus, type ListParams, type ListPromise, MeterConfig, type MetricsOverview, type MetricsParams, type MetricsRollup, MigrationResult, type OutboxEventListItem, type OutboxEventListParams, type OutboxEventStatus, type Paginated, PayInvoiceInput, type PaymentMethod, PaymentMethodStatus, type PaymentProviderDefinition, type PortalCardSetupResult, type PortalCheckout, type PortalPlanChange, type PortalSession, type PortalSessionExchange, type PortalSessionExchangeInput, type PortalSessionFlow, type PortalSessionInfo, type PortalSubscriptionStatus, type PortalView, type ProviderCredentialSummary, type ProviderVerifyResult, type ProviderVerifyTarget, type ProviderVerifyTargetResult, type PublishCreditRateCardInput, type RecordExternalPaymentInput, type Refund, type RefundChargeInput, type RefundRequestResult, type RefundReviewReason, RefundStatus, RequestOptions, type ResolveRefundInput, type ReverseCreditConsumptionInput, SavedPaymentMethod, type ScheduledSubscriptionChange, type SearchResults, type SubscriptionListItem, type SubscriptionListParams, type SubscriptionSearchHit, SubscriptionStatus, TaxBehavior, type TimeseriesInterval, type TimeseriesMetric, type TimeseriesParams, type TimeseriesPoint, type TimeseriesResult, TrackResult, UnappliedPaymentReason, type UpdateBusinessProfileInput, UpdateCreditPackInput, type UpdateEmailTemplateInput, UpdateFeatureInput, UpdateProductInput, type UpdateWebhookEndpointInput, type UpsertCredentialsInput, UsageAlert, type WebhookDelivery, WebhookDeliveryStatus, type WebhookEndpoint, type WebhookEndpointWithSecret, type Whoami, currencyExponent, formatMoney, isSecretField, toMajorUnits, toMinorUnits };
package/dist/index.d.ts CHANGED
@@ -6,8 +6,8 @@ import { SubscriptionStatus } from './status.js';
6
6
  export { ACTIVE_SUBSCRIPTION_STATUSES, NEVER_ACTIVATED_SUBSCRIPTION_STATUSES, SUBSCRIPTION_STATUSES, TERMINAL_SUBSCRIPTION_STATUSES, grantsAccess, isTerminal } from './status.js';
7
7
  import { c as TaxBehavior, d as Customer, U as UnappliedPaymentReason, e as CreateChargeInput, R as RequestOptions, f as Charge, g as CreateMerchantInitiatedChargeInput, I as IdempotentRequestOptions, h as CallOptions, C as CreateProductInput, i as UpdateProductInput, j as MigrationResult, k as CreateSubscriptionInput, B as BillowOptions, a as CreateCouponInput, l as Coupon, F as FeatureKind, M as MeterConfig, m as Feature, n as UpdateFeatureInput, o as UsageAlert, p as CreateUsageAlertInput, b as CheckResult, T as TrackResult, E as EntitlementView, A as AttachResult } from './billing-CgjcWmvb.js';
8
8
  export { q as ActivatedSubscriptionResult, r as BillingInterval, s as CouponDuration, t as CouponKind, u as CreateSubscriptionResult, v as EntitlementInput, w as MeterAggregation, x as MeterFilter, y as MeterRoundingMode, z as PendingSubscriptionCheckoutResult, D as PriceInput, P as Product, G as ProductEntitlement, H as ProductPrice, S as Subscription, J as SubscriptionDetail, K as SubscriptionItem, L as UpdatePriceInput, N as UsageAlertKind, O as UsageAlertMetric, Q as UsageModel, V as UsageTier } from './billing-CgjcWmvb.js';
9
- import { a as CreditThresholdLevel, e as CreditGrant, f as CreditTopUp, g as CreateCreditGrantInput, h as CreditGrantRequestResult, i as CreditPacks, j as CreateCreditPackInput, k as CreditPack, U as UpdateCreditPackInput, l as CreateCreditTopUpInput, m as CreditTopUpRequestResult, n as CreditTopUpListParams, o as CreditBalance, p as CreditLedgerEntry, q as CreditUsageParams, r as CreditUsage } from './hosted-domains-CrVDsk2i.js';
10
- export { s as CreditAccountStatus, C as CreditGrantKind, t as CreditMoney, u as CreditPackListItem, v as CreditTopUpStatus, w as CreditTransactionType, x as CreditUsageGroupBy, H as HostedDomainActivatedData, d as HostedDomainDisabledData, b as HostedDomainDnsFailingData, y as HostedDomainEventBase, c as HostedDomainReassignmentPendingData, z as HostedDomainStatus, A as HostedDomainStatusReason } from './hosted-domains-CrVDsk2i.js';
9
+ import { a as CreditThresholdLevel, e as CreditGrant, f as CreditTopUp, g as CreateCreditGrantInput, h as CreditGrantRequestResult, i as CreditPacks, j as CreateCreditPackInput, k as CreditPack, U as UpdateCreditPackInput, l as CreateCreditTopUpInput, m as CreditTopUpRequestResult, n as CreditTopUpListParams, o as CreditBalance, p as CreditLedgerEntry, q as CreditUsageParams, r as CreditUsage } from './hosted-domains-z_I0edmM.js';
10
+ export { s as CreditAccountStatus, C as CreditGrantKind, t as CreditMoney, u as CreditPackBreakdown, v as CreditPackListItem, w as CreditTopUpStatus, x as CreditTransactionType, y as CreditUsageGroupBy, H as HostedDomainActivatedData, d as HostedDomainDisabledData, b as HostedDomainDnsFailingData, z as HostedDomainEventBase, c as HostedDomainReassignmentPendingData, A as HostedDomainStatus, B as HostedDomainStatusReason } from './hosted-domains-z_I0edmM.js';
11
11
  import 'zod';
12
12
 
13
13
  /**
@@ -902,10 +902,18 @@ interface CreatePortalSessionInput {
902
902
  flow?: PortalSessionFlow;
903
903
  /** Product slug to subscribe to — required when `flow` is `checkout`. */
904
904
  productId?: string;
905
- /** Where the surface returns the Customer when they finish or exit. */
905
+ /**
906
+ * Where the surface returns the Customer when they finish or exit: an absolute `https` URL
907
+ * without credentials (and, in live, without a port other than 443). A loopback host such as
908
+ * `localhost` is also accepted over `http`, on any port, in either environment.
909
+ */
906
910
  returnUrl?: string;
907
911
  }
908
- /** The minted portal session: redirect the Customer to `url` (it carries the bearer). */
912
+ /**
913
+ * The minted portal session: redirect the Customer to `url` at once. Its token is a single-use
914
+ * entry token - Billow's hosted portal exchanges it on first open, after which the link works
915
+ * only for the browser that opened it.
916
+ */
909
917
  interface PortalSession {
910
918
  id: string;
911
919
  url: string;
@@ -913,6 +921,21 @@ interface PortalSession {
913
921
  /** ISO-8601 expiry — the session (and its URL) stop working after this. */
914
922
  expiresAt: string;
915
923
  }
924
+ /** The single-use entry exchange's input (`BillowPortal.exchange`). */
925
+ interface PortalSessionExchangeInput {
926
+ /** The `Host` the link was opened on: it must be the host the session is bound to. */
927
+ host: string;
928
+ /** The session token the browser already holds, if any: a revisit by the browser that
929
+ * exchanged the link lands on its own session, and only that browser's. */
930
+ sessionToken?: string;
931
+ }
932
+ /** What the exchange returns: the session's bearer from now on, and its unchanged expiry. */
933
+ interface PortalSessionExchange {
934
+ sessionToken: string;
935
+ flow: PortalSessionFlow;
936
+ /** ISO-8601 expiry of the session, set when it was minted. */
937
+ expiresAt: string;
938
+ }
916
939
  /**
917
940
  * The portal shell: the session's flow + return URL, the merchant's
918
941
  * customer-facing brand, and the Customer's identity. The lightweight payload a
@@ -2803,6 +2826,13 @@ declare class BillowPortal {
2803
2826
  * the lightweight payload the hosting app frames every page with, and the
2804
2827
  * validate-and-route check at login. */
2805
2828
  session(options?: CallOptions): Promise<PortalSessionInfo>;
2829
+ /**
2830
+ * The single-use entry exchange (ADR-0039): on a client built with a minted link's entry
2831
+ * token, trade it for the session token to use from now on. Succeeds once per link, and
2832
+ * afterwards only for the browser presenting that exchange's `sessionToken`; anything else is
2833
+ * a 401. For a hosted surface; an integrator's own surface may keep using the entry token.
2834
+ */
2835
+ exchange(input: PortalSessionExchangeInput, options?: CallOptions): Promise<PortalSessionExchange>;
2806
2836
  /** The self-serve home payload: identity + subscriptions + usage + saved cards. */
2807
2837
  me(options?: CallOptions): Promise<PortalView>;
2808
2838
  invoices: {
@@ -2810,6 +2840,8 @@ declare class BillowPortal {
2810
2840
  list: (params?: ListParams & {
2811
2841
  status?: InvoiceListItem["status"];
2812
2842
  }, options?: CallOptions) => ListPromise<InvoiceListItem>;
2843
+ /** One of the Customer's invoices, in the list's shape. */
2844
+ get: (id: string, options?: CallOptions) => Promise<InvoiceListItem>;
2813
2845
  /** Open or resume checkout for this customer's outstanding invoice. */
2814
2846
  pay: (id: string, input?: PayInvoiceInput, options?: CallOptions) => Promise<{
2815
2847
  invoiceId: string;
@@ -2881,4 +2913,4 @@ declare class BillowPortal {
2881
2913
  };
2882
2914
  }
2883
2915
 
2884
- export { AttachResult, BILLOW_ERROR_CODES, Billow, BillowApiError, type BillowErrorCode, BillowOptions, BillowPortal, BillowPublishable, type BusinessProfile, CallOptions, type CatalogItem, Charge, type ChargeListItem, type ChargeListParams, type ChargeSearchHit, ChargeStatus, CheckResult, type CheckoutMethodInfo, type ConfigField, type ConfigFieldOption, type ConfigFieldType, Coupon, CreateChargeInput, CreateCouponInput, CreateCreditGrantInput, CreateCreditPackInput, type CreateCreditQuoteInput, type CreateCreditReservationInput, CreateCreditTopUpInput, CreateHostedDomainInput, CreateMerchantInitiatedChargeInput, type CreatePortalSessionInput, CreateProductInput, CreateSubscriptionInput, CreateUsageAlertInput, type CreateWebhookEndpointInput, type CredentialSet, CreditBalance, type CreditDimensions, CreditGrant, CreditGrantRequestResult, CreditLedgerEntry, type CreditLineItem, CreditPack, CreditPacks, type CreditPricedLine, type CreditQuote, type CreditRateCard, type CreditRateCardItem, type CreditReservation, type CreditReservationRequestResult, type CreditReservationStatus, type CreditReversal, type CreditReversalRequestResult, CreditThresholdLevel, CreditTopUp, CreditTopUpListParams, CreditTopUpRequestResult, CreditUsage, CreditUsageParams, type CursorListParams, type CursorListPromise, type CursorPaginated, Customer, type CustomerAnonymizationResult, type CustomerCreditsExport, type CustomerDataExport, type CustomerListItem, type CustomerListParams, type CustomerOverview, type CustomerSearchHit, type CustomerUsage, type CustomerUsageDetail, type EmailDeliveryListItem, type EmailDeliveryListParams, type EmailDeliveryStatus, type EmailTemplateSetting, EntitlementView, type ExchangeRate, type ExportJsonValue, type ExternalPaymentMethod, type ExternalPaymentResult, Feature, FeatureKind, IdempotentRequestOptions, type InboundWebhookListItem, type InboundWebhookListParams, type InboundWebhookOutcome, type IntegrationDefinition, type IntegrationKind, type IntegrationTier, type Invoice, type InvoiceDetail, type InvoiceLineItem, type InvoiceListItem, type InvoiceListParams, type InvoiceSearchHit, InvoiceStatus, type ListParams, type ListPromise, MeterConfig, type MetricsOverview, type MetricsParams, type MetricsRollup, MigrationResult, type OutboxEventListItem, type OutboxEventListParams, type OutboxEventStatus, type Paginated, PayInvoiceInput, type PaymentMethod, PaymentMethodStatus, type PaymentProviderDefinition, type PortalCardSetupResult, type PortalCheckout, type PortalPlanChange, type PortalSession, type PortalSessionFlow, type PortalSessionInfo, type PortalSubscriptionStatus, type PortalView, type ProviderCredentialSummary, type ProviderVerifyResult, type ProviderVerifyTarget, type ProviderVerifyTargetResult, type PublishCreditRateCardInput, type RecordExternalPaymentInput, type Refund, type RefundChargeInput, type RefundRequestResult, type RefundReviewReason, RefundStatus, RequestOptions, type ResolveRefundInput, type ReverseCreditConsumptionInput, SavedPaymentMethod, type ScheduledSubscriptionChange, type SearchResults, type SubscriptionListItem, type SubscriptionListParams, type SubscriptionSearchHit, SubscriptionStatus, TaxBehavior, type TimeseriesInterval, type TimeseriesMetric, type TimeseriesParams, type TimeseriesPoint, type TimeseriesResult, TrackResult, UnappliedPaymentReason, type UpdateBusinessProfileInput, UpdateCreditPackInput, type UpdateEmailTemplateInput, UpdateFeatureInput, UpdateProductInput, type UpdateWebhookEndpointInput, type UpsertCredentialsInput, UsageAlert, type WebhookDelivery, WebhookDeliveryStatus, type WebhookEndpoint, type WebhookEndpointWithSecret, type Whoami, currencyExponent, formatMoney, isSecretField, toMajorUnits, toMinorUnits };
2916
+ export { AttachResult, BILLOW_ERROR_CODES, Billow, BillowApiError, type BillowErrorCode, BillowOptions, BillowPortal, BillowPublishable, type BusinessProfile, CallOptions, type CatalogItem, Charge, type ChargeListItem, type ChargeListParams, type ChargeSearchHit, ChargeStatus, CheckResult, type CheckoutMethodInfo, type ConfigField, type ConfigFieldOption, type ConfigFieldType, Coupon, CreateChargeInput, CreateCouponInput, CreateCreditGrantInput, CreateCreditPackInput, type CreateCreditQuoteInput, type CreateCreditReservationInput, CreateCreditTopUpInput, CreateHostedDomainInput, CreateMerchantInitiatedChargeInput, type CreatePortalSessionInput, CreateProductInput, CreateSubscriptionInput, CreateUsageAlertInput, type CreateWebhookEndpointInput, type CredentialSet, CreditBalance, type CreditDimensions, CreditGrant, CreditGrantRequestResult, CreditLedgerEntry, type CreditLineItem, CreditPack, CreditPacks, type CreditPricedLine, type CreditQuote, type CreditRateCard, type CreditRateCardItem, type CreditReservation, type CreditReservationRequestResult, type CreditReservationStatus, type CreditReversal, type CreditReversalRequestResult, CreditThresholdLevel, CreditTopUp, CreditTopUpListParams, CreditTopUpRequestResult, CreditUsage, CreditUsageParams, type CursorListParams, type CursorListPromise, type CursorPaginated, Customer, type CustomerAnonymizationResult, type CustomerCreditsExport, type CustomerDataExport, type CustomerListItem, type CustomerListParams, type CustomerOverview, type CustomerSearchHit, type CustomerUsage, type CustomerUsageDetail, type EmailDeliveryListItem, type EmailDeliveryListParams, type EmailDeliveryStatus, type EmailTemplateSetting, EntitlementView, type ExchangeRate, type ExportJsonValue, type ExternalPaymentMethod, type ExternalPaymentResult, Feature, FeatureKind, IdempotentRequestOptions, type InboundWebhookListItem, type InboundWebhookListParams, type InboundWebhookOutcome, type IntegrationDefinition, type IntegrationKind, type IntegrationTier, type Invoice, type InvoiceDetail, type InvoiceLineItem, type InvoiceListItem, type InvoiceListParams, type InvoiceSearchHit, InvoiceStatus, type ListParams, type ListPromise, MeterConfig, type MetricsOverview, type MetricsParams, type MetricsRollup, MigrationResult, type OutboxEventListItem, type OutboxEventListParams, type OutboxEventStatus, type Paginated, PayInvoiceInput, type PaymentMethod, PaymentMethodStatus, type PaymentProviderDefinition, type PortalCardSetupResult, type PortalCheckout, type PortalPlanChange, type PortalSession, type PortalSessionExchange, type PortalSessionExchangeInput, type PortalSessionFlow, type PortalSessionInfo, type PortalSubscriptionStatus, type PortalView, type ProviderCredentialSummary, type ProviderVerifyResult, type ProviderVerifyTarget, type ProviderVerifyTargetResult, type PublishCreditRateCardInput, type RecordExternalPaymentInput, type Refund, type RefundChargeInput, type RefundRequestResult, type RefundReviewReason, RefundStatus, RequestOptions, type ResolveRefundInput, type ReverseCreditConsumptionInput, SavedPaymentMethod, type ScheduledSubscriptionChange, type SearchResults, type SubscriptionListItem, type SubscriptionListParams, type SubscriptionSearchHit, SubscriptionStatus, TaxBehavior, type TimeseriesInterval, type TimeseriesMetric, type TimeseriesParams, type TimeseriesPoint, type TimeseriesResult, TrackResult, UnappliedPaymentReason, type UpdateBusinessProfileInput, UpdateCreditPackInput, type UpdateEmailTemplateInput, UpdateFeatureInput, UpdateProductInput, type UpdateWebhookEndpointInput, type UpsertCredentialsInput, UsageAlert, type WebhookDelivery, WebhookDeliveryStatus, type WebhookEndpoint, type WebhookEndpointWithSecret, type Whoami, currencyExponent, formatMoney, isSecretField, toMajorUnits, toMinorUnits };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { BILLOW_ERROR_CODES, Billow, BillowApiError, BillowPortal, BillowPublishable, currencyExponent, formatMoney, isSecretField, toMajorUnits, toMinorUnits } from './chunk-DYWGZRE2.js';
1
+ export { BILLOW_ERROR_CODES, Billow, BillowApiError, BillowPortal, BillowPublishable, currencyExponent, formatMoney, isSecretField, toMajorUnits, toMinorUnits } from './chunk-JG2OOAMX.js';
2
2
  export { ACTIVE_SUBSCRIPTION_STATUSES, CHARGE_STATUSES, INVOICE_STATUSES, NEVER_ACTIVATED_SUBSCRIPTION_STATUSES, PAYMENT_METHOD_STATUSES, REFUND_STATUSES, SUBSCRIPTION_STATUSES, TERMINAL_SUBSCRIPTION_STATUSES, WEBHOOK_DELIVERY_STATUSES, grantsAccess, isTerminal } from './chunk-CCG4F5FK.js';
3
3
  //# sourceMappingURL=index.js.map
4
4
  //# sourceMappingURL=index.js.map
@@ -4,7 +4,7 @@ import 'zod';
4
4
  import './billing-status-BZQN_gm7.cjs';
5
5
  import './status.cjs';
6
6
  import './billing-B-VyZCXV.cjs';
7
- import './hosted-domains-BtCd-Rur.cjs';
7
+ import './hosted-domains-BYYl2DSa.cjs';
8
8
 
9
9
  /**
10
10
  * Auto-metering (PRD-16): ingestion strategies that call billow's `track()` for you,
@@ -4,7 +4,7 @@ import 'zod';
4
4
  import './billing-status-BZQN_gm7.js';
5
5
  import './status.js';
6
6
  import './billing-CgjcWmvb.js';
7
- import './hosted-domains-CrVDsk2i.js';
7
+ import './hosted-domains-z_I0edmM.js';
8
8
 
9
9
  /**
10
10
  * Auto-metering (PRD-16): ingestion strategies that call billow's `track()` for you,
@@ -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;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AAE,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 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 /** 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 /** 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,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;A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AACb,IAAA,YAAA,CAAa,IAAI,CAAA;AACjB,IAAA,MAAM,MAAA,GAAS,IAAI,iBAAA,CAAkB,cAAA,EAAgB,UAAU,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.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"]}
package/dist/react.js CHANGED
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import { BillowPublishable } from './chunk-DYWGZRE2.js';
2
+ import { BillowPublishable } from './chunk-JG2OOAMX.js';
3
3
  import './chunk-CCG4F5FK.js';
4
4
  import { createContext, useCallback, useState, useEffect, useMemo, useContext } from 'react';
5
5
  import { jsx } from 'react/jsx-runtime';
package/dist/server.d.cts CHANGED
@@ -4,7 +4,7 @@ import 'zod';
4
4
  import './billing-status-BZQN_gm7.cjs';
5
5
  import './status.cjs';
6
6
  import './billing-B-VyZCXV.cjs';
7
- import './hosted-domains-BtCd-Rur.cjs';
7
+ import './hosted-domains-BYYl2DSa.cjs';
8
8
 
9
9
  /**
10
10
  * Backend handler for the browser-facing surface (the React hooks talk to this,
package/dist/server.d.ts CHANGED
@@ -4,7 +4,7 @@ import 'zod';
4
4
  import './billing-status-BZQN_gm7.js';
5
5
  import './status.js';
6
6
  import './billing-CgjcWmvb.js';
7
- import './hosted-domains-CrVDsk2i.js';
7
+ import './hosted-domains-z_I0edmM.js';
8
8
 
9
9
  /**
10
10
  * Backend handler for the browser-facing surface (the React hooks talk to this,
@@ -1,4 +1,4 @@
1
- import { C as CreditGrantKind, a as CreditThresholdLevel, H as HostedDomainActivatedData, b as HostedDomainDnsFailingData, c as HostedDomainReassignmentPendingData, d as HostedDomainDisabledData } from './hosted-domains-BtCd-Rur.cjs';
1
+ import { C as CreditGrantKind, a as CreditThresholdLevel, H as HostedDomainActivatedData, b as HostedDomainDnsFailingData, c as HostedDomainReassignmentPendingData, d as HostedDomainDisabledData } from './hosted-domains-BYYl2DSa.cjs';
2
2
  import './index.d-CKQAhQfJ.cjs';
3
3
  import 'zod';
4
4
 
@@ -1,4 +1,4 @@
1
- import { C as CreditGrantKind, a as CreditThresholdLevel, H as HostedDomainActivatedData, b as HostedDomainDnsFailingData, c as HostedDomainReassignmentPendingData, d as HostedDomainDisabledData } from './hosted-domains-CrVDsk2i.js';
1
+ import { C as CreditGrantKind, a as CreditThresholdLevel, H as HostedDomainActivatedData, b as HostedDomainDnsFailingData, c as HostedDomainReassignmentPendingData, d as HostedDomainDisabledData } from './hosted-domains-z_I0edmM.js';
2
2
  import './index.d-CKQAhQfJ.js';
3
3
  import 'zod';
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usebillow/sdk",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Billow client SDK - attach / check / track, auto-metering, config sync, React hooks, and webhook verification",
5
5
  "license": "MIT",
6
6
  "author": "DevCoat",