UNPKG

autumn-js

Version:
784 lines (753 loc) 25.3 kB
import * as react_jsx_runtime from 'react/jsx-runtime'; import { z } from 'zod/v4'; import * as swr from 'swr'; import { SWRConfiguration } from 'swr'; interface ErrorResponse { message: string; code: string; } declare class AutumnError extends Error { readonly message: string; readonly code: string; constructor(response: ErrorResponse); static fromError(error: any): AutumnError; toString(): string; toJSON(): { message: string; code: string; }; } declare const Infinite = "inf"; declare enum FreeTrialDuration { Day = "day" } declare enum UsageModel { Prepaid = "prepaid", PayPerUse = "pay_per_use" } type UsageModelType = "prepaid" | "pay_per_use"; declare enum ProductItemInterval { Minute = "minute", Hour = "hour", Day = "day", Week = "week", Month = "month", Quarter = "quarter", SemiAnnual = "semi_annual", Year = "year", Multiple = "multiple" } type ProductItemIntervalType = "minute" | "hour" | "day" | "week" | "month" | "quarter" | "semi_annual" | "year" | "multiple"; type CheckFeatureScenario = "usage_limit" | "feature_flag"; declare const CheckFeatureResultSchema: z.ZodObject<{ allowed: z.ZodBoolean; feature_id: z.ZodString; customer_id: z.ZodString; entity_id: z.ZodOptional<z.ZodString>; required_balance: z.ZodNumber; unlimited: z.ZodOptional<z.ZodBoolean>; interval: z.ZodOptional<z.ZodEnum<typeof ProductItemInterval>>; balance: z.ZodOptional<z.ZodNullable<z.ZodNumber>>; usage: z.ZodOptional<z.ZodNumber>; included_usage: z.ZodOptional<z.ZodNumber>; next_reset_at: z.ZodOptional<z.ZodNullable<z.ZodNumber>>; overage_allowed: z.ZodOptional<z.ZodBoolean>; usage_limit: z.ZodOptional<z.ZodNumber>; rollovers: z.ZodOptional<z.ZodObject<{ balance: z.ZodNumber; expires_at: z.ZodNumber; }, z.core.$strip>>; breakdown: z.ZodOptional<z.ZodArray<z.ZodObject<{ interval: z.ZodEnum<typeof ProductItemInterval>; balance: z.ZodOptional<z.ZodNumber>; usage: z.ZodOptional<z.ZodNumber>; included_usage: z.ZodOptional<z.ZodNumber>; next_reset_at: z.ZodOptional<z.ZodNumber>; }, z.core.$strip>>>; credit_schema: z.ZodOptional<z.ZodArray<z.ZodObject<{ feature_id: z.ZodString; credit_amount: z.ZodNumber; }, z.core.$strip>>>; }, z.core.$strip>; type CheckFeatureResult = z.infer<typeof CheckFeatureResultSchema>; interface CheckFeaturePreview { scenario: CheckFeatureScenario; title: string; message: string; feature_id: string; feature_name: string; products: Product[]; } type ProductScenario = "scheduled" | "active" | "new" | "renew" | "upgrade" | "downgrade" | "cancel"; interface CheckProductResult { allowed: boolean; customer_id: string; product_id: string; entity_id?: string; status?: string; preview?: CheckProductPreview; } interface CheckProductPreview { scenario: ProductScenario; product_id: string; product_name: string; recurring: boolean; error_on_attach?: boolean; next_cycle_at?: number; current_product_name?: string; items?: { price: string; description: string; usage_model?: UsageModelType; }[]; options?: { feature_id: string; feature_name: string; billing_units: number; price?: number; tiers?: { to: number | string; amount: number; }[]; }[]; due_today?: { price: number; currency: string; }; due_next_cycle?: { price: number; currency: string; }; } declare enum AppEnv { Sandbox = "sandbox", Live = "live" } interface Feature { id: string; name: string; type: "boolean" | "continuous_use" | "single_use" | "credit_system"; } interface ProductItem { type?: "feature" | "priced_feature" | "price"; feature_id?: string; included_usage?: number | typeof Infinite; interval?: ProductItemIntervalType; feature?: Feature; usage_model?: UsageModel; price?: number; billing_units?: number; entity_feature_id?: string; reset_usage_when_enabled?: boolean; quantity?: number; next_cycle_quantity?: number; display?: { primary_text?: string; secondary_text?: string; }; } interface FreeTrial { duration: FreeTrialDuration; length: number; unique_fingerprint: boolean; trial_available?: boolean; } interface Product { id: string; created_at: number; name: string; env: AppEnv; is_add_on: boolean; is_default: boolean; group: string; version: number; items: ProductItem[]; free_trial: FreeTrial | null; scenario?: ProductScenario; base_variant_id: string | null; properties: { is_free: boolean; is_one_off: boolean; interval_group: string; has_trial: boolean; updateable: boolean; }; display?: { name?: string; description?: string; button_text?: string; recommend_text?: string; everything_from?: string; button_url?: string; }; } declare enum ProductStatus { Active = "active", Expired = "expired", Trialing = "trialing", Scheduled = "scheduled", PastDue = "past_due" } type CustomerExpandOption = "invoices" | "rewards" | "trials_used" | "entities" | "referrals" | "payment_method"; declare const CoreCusFeatureSchema: z.ZodObject<{ unlimited: z.ZodOptional<z.ZodBoolean>; interval: z.ZodOptional<z.ZodEnum<typeof ProductItemInterval>>; balance: z.ZodOptional<z.ZodNullable<z.ZodNumber>>; usage: z.ZodOptional<z.ZodNumber>; included_usage: z.ZodOptional<z.ZodNumber>; next_reset_at: z.ZodOptional<z.ZodNullable<z.ZodNumber>>; overage_allowed: z.ZodOptional<z.ZodBoolean>; usage_limit: z.ZodOptional<z.ZodNumber>; rollovers: z.ZodOptional<z.ZodObject<{ balance: z.ZodNumber; expires_at: z.ZodNumber; }, z.core.$strip>>; breakdown: z.ZodOptional<z.ZodArray<z.ZodObject<{ interval: z.ZodEnum<typeof ProductItemInterval>; balance: z.ZodOptional<z.ZodNumber>; usage: z.ZodOptional<z.ZodNumber>; included_usage: z.ZodOptional<z.ZodNumber>; next_reset_at: z.ZodOptional<z.ZodNumber>; }, z.core.$strip>>>; credit_schema: z.ZodOptional<z.ZodArray<z.ZodObject<{ feature_id: z.ZodString; credit_amount: z.ZodNumber; }, z.core.$strip>>>; }, z.core.$strip>; type CoreCustomerFeature = z.infer<typeof CoreCusFeatureSchema>; interface CustomerFeature extends CoreCustomerFeature { id: string; name: string; type: "static" | "single_use" | "continuous_use"; } interface CustomerReferral { program_id: string; customer: { id: string; name: string | null; email: string | null; }; reward_applied: boolean; created_at: number; } interface CustomerProduct { id: string; name: string | null; group: string | null; status: ProductStatus; started_at: number; canceled_at: number | null; version: number; subscription_ids?: string[] | null; current_period_start?: number | null; current_period_end?: number | null; trial_ends_at?: number; entity_id?: string; is_add_on: boolean; is_default: boolean; items: ProductItem[]; } interface Customer { id: string | null; created_at: number; name: string | null; email: string | null; fingerprint: string | null; stripe_id: string | null; env: AppEnv; metadata: Record<string, any>; products: CustomerProduct[]; features: Record<string, CustomerFeature>; invoices?: CustomerInvoice[]; payment_method?: any; referrals?: CustomerReferral[]; } declare const CustomerDataSchema: z.ZodObject<{ name: z.ZodOptional<z.ZodNullable<z.ZodString>>; email: z.ZodOptional<z.ZodNullable<z.ZodString>>; fingerprint: z.ZodOptional<z.ZodNullable<z.ZodString>>; }, z.core.$strip>; type CustomerData = z.infer<typeof CustomerDataSchema>; interface BillingPortalResult { customer_id: string; url: string; } interface CustomerInvoice { product_ids: string[]; stripe_id: string; status: string; total: number; currency: string; created_at: number; hosted_invoice_url: string; } declare const CancelResultSchema: z.ZodObject<{ success: z.ZodBoolean; customer_id: z.ZodString; product_id: z.ZodString; }, z.core.$strip>; type CancelResult = z.infer<typeof CancelResultSchema>; declare const TrackResultSchema: z.ZodObject<{ id: z.ZodString; code: z.ZodString; customer_id: z.ZodString; feature_id: z.ZodOptional<z.ZodString>; event_name: z.ZodOptional<z.ZodString>; }, z.core.$strip>; type TrackResult = z.infer<typeof TrackResultSchema>; type CheckResult = CheckFeatureResult & CheckProductResult; interface SetupPaymentResult { customer_id: string; url: string; } type QueryResult = { list: Array<{ period: number; } & { [key: string]: number; }>; }; declare const AttachFeatureOptionsSchema: z.ZodObject<{ feature_id: z.ZodString; quantity: z.ZodNumber; }, z.core.$strip>; type AttachFeatureOptions = z.infer<typeof AttachFeatureOptionsSchema>; declare const AttachResultSchema: z.ZodObject<{ checkout_url: z.ZodOptional<z.ZodString>; customer_id: z.ZodString; product_ids: z.ZodArray<z.ZodString>; code: z.ZodString; message: z.ZodString; customer_data: z.ZodOptional<z.ZodAny>; invoice: z.ZodOptional<z.ZodObject<{ status: z.ZodString; stripe_id: z.ZodString; hosted_invoice_url: z.ZodNullable<z.ZodString>; total: z.ZodNumber; currency: z.ZodString; }, z.core.$strip>>; }, z.core.$strip>; type AttachResult = z.infer<typeof AttachResultSchema>; declare const CheckoutParamsSchema$1: z.ZodObject<{ customer_id: z.ZodString; product_id: z.ZodString; product_ids: z.ZodOptional<z.ZodArray<z.ZodString>>; entity_id: z.ZodOptional<z.ZodString>; options: z.ZodOptional<z.ZodArray<z.ZodObject<{ feature_id: z.ZodString; quantity: z.ZodNumber; }, z.core.$strip>>>; force_checkout: z.ZodOptional<z.ZodBoolean>; invoice: z.ZodOptional<z.ZodBoolean>; success_url: z.ZodOptional<z.ZodString>; customer_data: z.ZodOptional<z.ZodObject<{ name: z.ZodOptional<z.ZodNullable<z.ZodString>>; email: z.ZodOptional<z.ZodNullable<z.ZodString>>; fingerprint: z.ZodOptional<z.ZodNullable<z.ZodString>>; }, z.core.$strip>>; entity_data: z.ZodOptional<z.ZodAny>; checkout_session_params: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>; reward: z.ZodOptional<z.ZodString>; }, z.core.$strip>; type CheckoutParams$1 = z.infer<typeof CheckoutParamsSchema$1>; type CheckoutResult = { url?: string; customer_id: string; has_prorations: boolean; lines: { description: string; amount: number; item: ProductItem; }[]; total: number; currency: string; options: AttachFeatureOptions[]; product: Product; current_product: Product; free_trial?: boolean; next_cycle?: { starts_at: number; total: number; }; }; type Success<T> = { data: T; error: null; statusCode?: number; }; type Failure<E> = { data: null; error: E; statusCode?: number; }; type Result<T, E> = Success<T> | Failure<E>; type AutumnPromise<T> = Promise<Result<T, AutumnError>>; interface PricingTableProduct { id: string; name: string; description?: string; button_text?: string; recommend_text?: string; everything_from?: string; price: { primary_text: string; secondary_text?: string; } & ProductItem; items: ({ primary_text: string; secondary_text?: string; } & ProductItem)[]; scenario: ProductScenario; } interface Entity { id: string; name: string; customer_id: string; created_at: number; env: string; products: CustomerProduct[]; features: Record<string, CustomerFeature>; invoices?: CustomerInvoice[]; } interface CreateReferralCodeResult { code: string; customer_id: string; created_at: number; } interface RedeemReferralCodeResult { id: string; customer_id: string; reward_id: string; referrer: { id: string; name: string | null; email: string | null; }; } declare const ReactAutumnProvider: ({ children, getBearerToken, convex, backendUrl, customerData, includeCredentials, betterAuthUrl, headers, convexApi, }: { children: React.ReactNode; getBearerToken?: () => Promise<string | null>; convex?: any; backendUrl?: string; customerData?: CustomerData; includeCredentials?: boolean; betterAuthUrl?: string; headers?: Record<string, string>; convexApi?: any; }) => react_jsx_runtime.JSX.Element; interface ProductDetails { id?: string; name?: string; description?: string; buttonText?: string; buttonUrl?: string; recommendText?: string; everythingFrom?: string; price?: { primaryText: string; secondaryText?: string; }; items?: { featureId?: string; primaryText?: string; secondaryText?: string; }[]; } declare const AttachParamsSchema: z.ZodObject<{ productId: z.ZodOptional<z.ZodString>; entityId: z.ZodOptional<z.ZodString>; options: z.ZodOptional<z.ZodArray<z.ZodObject<{ featureId: z.ZodString; quantity: z.ZodNumber; }, z.core.$strip>>>; productIds: z.ZodOptional<z.ZodArray<z.ZodString>>; freeTrial: z.ZodOptional<z.ZodBoolean>; successUrl: z.ZodOptional<z.ZodString>; metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>; forceCheckout: z.ZodOptional<z.ZodBoolean>; dialog: z.ZodOptional<z.ZodAny>; entityData: z.ZodOptional<z.ZodAny>; openInNewTab: z.ZodOptional<z.ZodBoolean>; reward: z.ZodOptional<z.ZodString>; checkoutSessionParams: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>; }, z.core.$strip>; type AttachParams = z.infer<typeof AttachParamsSchema>; declare const CheckoutParamsSchema: z.ZodObject<{ productId: z.ZodOptional<z.ZodString>; productIds: z.ZodOptional<z.ZodArray<z.ZodString>>; entityId: z.ZodOptional<z.ZodString>; entityData: z.ZodOptional<z.ZodAny>; options: z.ZodOptional<z.ZodArray<z.ZodObject<{ featureId: z.ZodString; quantity: z.ZodNumber; }, z.core.$strip>>>; successUrl: z.ZodOptional<z.ZodString>; openInNewTab: z.ZodOptional<z.ZodBoolean>; dialog: z.ZodOptional<z.ZodAny>; forceCheckout: z.ZodOptional<z.ZodBoolean>; checkoutSessionParams: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>; reward: z.ZodOptional<z.ZodString>; }, z.core.$strip>; type CheckoutParams = z.infer<typeof CheckoutParamsSchema>; declare const CancelParamsSchema: z.ZodObject<{ productId: z.ZodString; entityId: z.ZodOptional<z.ZodString>; cancelImmediately: z.ZodOptional<z.ZodBoolean>; }, z.core.$strip>; type CancelParams = z.infer<typeof CancelParamsSchema>; declare const CheckParamsSchema: z.ZodObject<{ featureId: z.ZodOptional<z.ZodString>; productId: z.ZodOptional<z.ZodString>; entityId: z.ZodOptional<z.ZodString>; requiredBalance: z.ZodOptional<z.ZodNumber>; sendEvent: z.ZodOptional<z.ZodBoolean>; withPreview: z.ZodOptional<z.ZodBoolean>; dialog: z.ZodOptional<z.ZodAny>; entityData: z.ZodOptional<z.ZodAny>; properties: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>; }, z.core.$strip>; type CheckParams = z.infer<typeof CheckParamsSchema>; declare const TrackParamsSchema: z.ZodObject<{ featureId: z.ZodOptional<z.ZodString>; eventName: z.ZodOptional<z.ZodString>; entityId: z.ZodOptional<z.ZodString>; value: z.ZodOptional<z.ZodNumber>; idempotencyKey: z.ZodOptional<z.ZodString>; entityData: z.ZodOptional<z.ZodAny>; }, z.core.$strip>; type TrackParams = z.infer<typeof TrackParamsSchema>; declare const OpenBillingPortalParamsSchema: z.ZodObject<{ returnUrl: z.ZodOptional<z.ZodString>; openInNewTab: z.ZodOptional<z.ZodBoolean>; }, z.core.$strip>; type OpenBillingPortalParams = z.infer<typeof OpenBillingPortalParamsSchema>; declare const SetupPaymentParamsSchema: z.ZodObject<{ successUrl: z.ZodOptional<z.ZodString>; checkoutSessionParams: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>; openInNewTab: z.ZodOptional<z.ZodBoolean>; }, z.core.$strip>; type SetupPaymentParams = z.infer<typeof SetupPaymentParamsSchema>; declare const QueryParamsSchema: z.ZodObject<{ featureId: z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodString>]>; range: z.ZodOptional<z.ZodEnum<{ "24h": "24h"; "7d": "7d"; "30d": "30d"; "90d": "90d"; last_cycle: "last_cycle"; }>>; }, z.core.$strip>; type QueryParams = z.infer<typeof QueryParamsSchema>; declare const CreateEntityParamsSchema: z.ZodObject<{ id: z.ZodString; name: z.ZodOptional<z.ZodString>; featureId: z.ZodString; }, z.core.$strip>; type CreateEntityParams = z.infer<typeof CreateEntityParamsSchema>; declare const GetEntityParamsSchema: z.ZodObject<{ expand: z.ZodOptional<z.ZodArray<z.ZodString>>; }, z.core.$strip>; type GetEntityParams = z.infer<typeof GetEntityParamsSchema>; declare const CreateReferralCodeParamsSchema: z.ZodObject<{ programId: z.ZodString; }, z.core.$strip>; type CreateReferralCodeParams = z.infer<typeof CreateReferralCodeParamsSchema>; declare const RedeemReferralCodeParamsSchema: z.ZodObject<{ code: z.ZodString; }, z.core.$strip>; type RedeemReferralCodeParams = z.infer<typeof RedeemReferralCodeParamsSchema>; interface UseCustomerResult { /** The current customer data including subscription and feature information */ customer: Customer | null; /** Whether customer data is currently being loaded */ isLoading: boolean; /** Any error that occurred while fetching customer data */ error: AutumnError | null; /** * Attaches a product to the current customer, enabling access and handling billing. * Activates a product and applies all product items with automatic payment handling. */ attach: (params: AttachParams) => AutumnPromise<AttachResult | CheckResult>; /** * Tracks usage events for metered features. * Records feature usage and updates customer balances server-side. */ track: (params: TrackParams) => AutumnPromise<TrackResult>; /** * Cancels a customer's subscription or product attachment. * Can cancel immediately or at the end of the billing cycle. */ cancel: (params: CancelParams) => AutumnPromise<CancelResult>; /** * Sets up a payment method for the customer. * Collects payment information without immediately charging. */ setupPayment: (params: SetupPaymentParams) => AutumnPromise<SetupPaymentResult>; /** * Opens the Stripe billing portal for the customer. * Allows customers to manage their subscription and payment methods. */ openBillingPortal: (params?: OpenBillingPortalParams) => AutumnPromise<BillingPortalResult>; /** * Initiates a checkout flow for product purchase. * Handles payment collection and redirects to Stripe checkout when needed. */ checkout: (params: CheckoutParams) => AutumnPromise<CheckoutResult>; /** Refetches the customer data from the server */ refetch: () => Promise<Customer | null>; /** * Creates new entities for granular feature tracking. * Entities allow per-user or per-workspace feature limits. */ createEntity: (params: CreateEntityParams | CreateEntityParams[]) => AutumnPromise<Entity | Entity[]>; /** * Creates a referral code for the customer. * Generates codes that can be shared for referral programs. */ createReferralCode: (params: CreateReferralCodeParams) => AutumnPromise<CreateReferralCodeResult>; /** * Redeems a referral code for the customer. * Applies referral benefits when a valid code is provided. */ redeemReferralCode: (params: RedeemReferralCodeParams) => AutumnPromise<RedeemReferralCodeResult>; /** * Checks if a customer has access to a feature and shows paywalls if needed. * Client-side feature gating with optional dialog display for upgrades. */ check: (params: CheckParams) => Success<CheckResult>; } interface UseCustomerParams { errorOnNotFound?: boolean; expand?: CustomerExpandOption[]; swrConfig?: SWRConfiguration; } /** * React hook for managing customer billing, subscriptions, and feature access. * * Provides access to all Autumn billing functions including product attachment, * subscription management, usage tracking, and feature gating. Automatically * handles customer data fetching and caching. * * @param params - Optional configuration for the hook * @returns Object containing customer data and billing functions * * @example * ```tsx * import { useCustomer } from "autumn-js/react"; * * function MyComponent() { * const { * customer, * isLoading, * attach, * cancel, * check, * track, * checkout, * openBillingPortal, * setupPayment, * createReferralCode, * redeemReferralCode, * createEntity, * refetch * } = useCustomer(); * * return ( * <div> * <button onClick={() => attach({ productId: "pro" })}> * Upgrade to Pro * </button> * <button onClick={() => cancel({ productId: "pro" })}> * Cancel Subscription * </button> * </div> * ); * } * ``` * * @returns {Object} Hook result object * @returns {Customer | null} returns.customer - Current customer data with subscription info * @returns {boolean} returns.isLoading - Whether customer data is loading * @returns {AutumnError | null} returns.error - Any error from customer data fetching * @returns {Function} returns.attach - Attach product to customer with billing * @returns {Function} returns.cancel - Cancel customer subscription/product * @returns {Function} returns.check - Check feature access and show paywalls * @returns {Function} returns.track - Track feature usage events * @returns {Function} returns.checkout - Initiate product checkout flow * @returns {Function} returns.openBillingPortal - Open Stripe billing portal * @returns {Function} returns.setupPayment - Setup payment method * @returns {Function} returns.createReferralCode - Create referral codes * @returns {Function} returns.redeemReferralCode - Redeem referral codes * @returns {Function} returns.createEntity - Create entities for granular tracking * @returns {Function} returns.refetch - Manually refetch customer data */ declare const useCustomer: (params?: UseCustomerParams) => UseCustomerResult; declare const usePricingTable: (params?: { productDetails?: ProductDetails[]; }) => { products: Product[] | null; isLoading: boolean; error: AutumnError | undefined; refetch: swr.KeyedMutator<Product[]>; }; declare const useEntity: (entityId: string | null, params?: GetEntityParams) => { entity: Entity | null; isLoading: boolean; error: any; refetch: swr.KeyedMutator<Entity | null>; check: (params: CheckParams) => { data: CheckResult; error: null; }; attach: (params: AttachParams) => Promise<any>; cancel: (params: CancelParams) => AutumnPromise<{ success: boolean; customer_id: string; product_id: string; }>; track: (params: TrackParams) => AutumnPromise<{ id: string; code: string; customer_id: string; feature_id?: string | undefined; event_name?: string | undefined; }>; }; declare const useAnalytics: (params: QueryParams) => { data: ({ period: number; } & { [key: string]: number; })[] | undefined; isLoading: boolean; error: AutumnError | undefined; refetch: swr.KeyedMutator<QueryResult>; }; declare const usePaywall: ({ featureId, entityId, }: { featureId?: string; entityId?: string; }) => { data: CheckFeaturePreview | undefined; error: any; isLoading: boolean; }; interface CheckoutDialogProps { open: boolean; setOpen: (open: boolean) => void; checkoutResult: CheckoutResult; checkoutParams?: CheckoutParams$1; } declare function CheckoutDialog(params: CheckoutDialogProps): react_jsx_runtime.JSX.Element; interface PaywallDialogProps { open: boolean; setOpen: (open: boolean) => void; featureId: string; entityId?: string; } declare function PaywallDialog(params?: PaywallDialogProps): react_jsx_runtime.JSX.Element; declare function PricingTable({ productDetails, }: { productDetails?: ProductDetails[]; }): react_jsx_runtime.JSX.Element; /** @deprecated */ declare const useAutumn: () => void; export { ReactAutumnProvider as AutumnProvider, CheckoutDialog, PaywallDialog, PricingTable, type PricingTableProduct, type ProductDetails, useAnalytics, useAutumn, useCustomer, useEntity, usePaywall, usePricingTable };