autumn-js
Version:
Autumn JS Library
925 lines (890 loc) • 30 kB
TypeScript
import { z } from 'zod/v4';
import * as swr from 'swr';
import { SWRConfiguration } from 'swr';
import React, { JSX } from 'react';
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";
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;
};
}
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;
};
}
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 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 EventsListParamsSchema: z.ZodObject<{
offset: z.ZodOptional<z.ZodDefault<z.ZodCoercedNumber<unknown>>>;
limit: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
featureId: z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodString>]>;
customRange: z.ZodOptional<z.ZodObject<{
start: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
end: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
}, z.core.$strip>>;
}, z.core.$strip>;
type EventsListParams = z.infer<typeof EventsListParamsSchema>;
declare const EventAggregationParamsSchema: z.ZodObject<{
featureId: z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodString>]>;
groupBy: z.ZodOptional<z.ZodString>;
range: z.ZodOptional<z.ZodEnum<{
"24h": "24h";
"7d": "7d";
"30d": "30d";
"90d": "90d";
last_cycle: "last_cycle";
"1bc": "1bc";
"3bc": "3bc";
}>>;
binSize: z.ZodOptional<z.ZodDefault<z.ZodEnum<{
day: "day";
hour: "hour";
}>>>;
customRange: z.ZodOptional<z.ZodObject<{
start: z.ZodNumber;
end: z.ZodNumber;
}, z.core.$strip>>;
}, z.core.$strip>;
type EventAggregationParams = z.infer<typeof EventAggregationParamsSchema>;
type FlatAggregatedRow = {
period: number;
[featureName: string]: number;
};
type GroupedAggregatedRow = {
period: number;
} & {
[featureName: string]: Record<string, number>;
};
type AggregatedEventRow = FlatAggregatedRow | GroupedAggregatedRow;
declare const EventAggregationTotalSchema: z.ZodRecord<z.ZodString, z.ZodObject<{
count: z.ZodNumber;
sum: z.ZodNumber;
}, z.core.$strip>>;
type EventAggregationTotal = z.infer<typeof EventAggregationTotalSchema>;
type EventAggregationResponse = {
list: AggregatedEventRow[];
total: EventAggregationTotal;
};
declare enum ProductStatus {
Active = "active",
Expired = "expired",
Trialing = "trialing",
Scheduled = "scheduled",
PastDue = "past_due"
}
type CustomerExpandOption = "invoices" | "rewards" | "trials_used" | "entities" | "referrals" | "payment_method";
interface Entity {
id: string;
name: string;
customer_id: string;
created_at: number;
env: string;
products: CustomerProduct[];
features: Record<string, CustomerFeature>;
invoices?: CustomerInvoice[];
}
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>;
payment_method?: any;
referrals?: CustomerReferral[];
}
/**
* Maps expand option strings to their corresponding types.
* Used for conditional type expansion based on the expand parameter.
*/
interface CustomerExpandedFields {
invoices: CustomerInvoice[];
entities: Entity[];
referrals: CustomerReferral[];
rewards: unknown;
trials_used: unknown;
payment_method: unknown;
}
/**
* Utility type that creates a Customer with additional expanded fields
* based on the expand array passed to the API.
*
* @example
* // Base customer without expanded fields
* type Base = ExpandedCustomer<[]>;
*
* // Customer with invoices and entities expanded
* type WithExpansion = ExpandedCustomer<['invoices', 'entities']>;
* // Result: Customer & { invoices: CustomerInvoice[]; entities: Entity[] }
*/
type ExpandedCustomer<T extends readonly CustomerExpandOption[] = readonly []> = Customer & {
[K in T[number]]: CustomerExpandedFields[K];
};
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;
}
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>;
new_billing_subscription: z.ZodOptional<z.ZodBoolean>;
}, 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 QueryResult = {
list: Array<{
period: number;
} & {
[key: string]: number | Record<string, number>;
}>;
};
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;
};
}
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 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 useAggregateEvents: (params: EventAggregationParams & {
swrConfig?: SWRConfiguration;
}) => {
list: AggregatedEventRow[] | undefined;
total: Record<string, {
count: number;
sum: number;
}> | undefined;
isLoading: boolean;
error: AutumnError | undefined;
refetch: swr.KeyedMutator<EventAggregationResponse>;
};
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.ZodOptional<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";
"1bc": "1bc";
"3bc": "3bc";
}>>;
}, z.core.$strip>;
type QueryParams = z.infer<typeof QueryParamsSchema>;
/**
* @deprecated Use useAggregateEvents or useListEvents instead
*/
declare const useAnalytics: (params: QueryParams) => {
data: ({
period: number;
} & {
[key: string]: number | Record<string, number>;
})[] | undefined;
isLoading: boolean;
error: AutumnError | undefined;
refetch: swr.KeyedMutator<QueryResult>;
};
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>>;
newBillingSubscription: z.ZodOptional<z.ZodBoolean>;
}, 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>;
freeTrial: z.ZodOptional<z.ZodBoolean>;
checkoutSessionParams: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
reward: z.ZodOptional<z.ZodString>;
newBillingSubscription: z.ZodOptional<z.ZodBoolean>;
}, z.core.$strip>;
type CheckoutParams = z.infer<typeof CheckoutParamsSchema>;
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<T extends readonly CustomerExpandOption[] = readonly []> {
/** The current customer data including subscription and feature information */
customer: ExpandedCustomer<T> | 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<ExpandedCustomer<T> | 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<T extends readonly CustomerExpandOption[] = readonly []> {
errorOnNotFound?: boolean;
expand?: T;
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>
* );
* }
* ```
*
* @example
* ```tsx
* // With expanded fields - customer.entities will be typed
* const { customer } = useCustomer({ expand: ['entities', 'invoices'] });
* customer?.entities; // Entity[] - fully typed!
* customer?.invoices; // CustomerInvoice[] - fully typed!
* ```
*
* @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: <const T extends readonly CustomerExpandOption[] = readonly []>(params?: UseCustomerParams<T>) => UseCustomerResult<T>;
declare const useEntity: (entityId: string | null, params?: GetEntityParams) => {
entity: Entity | null;
isLoading: boolean;
error: AutumnError | undefined | null;
refetch: () => void;
check: (params: CheckParams) => {
data: CheckResult;
error: null;
} | {
data: null;
error: AutumnError;
};
attach: (params: AttachParams) => void;
cancel: (params: CancelParams) => void;
track: (params: TrackParams) => void;
};
declare const useListEvents: (params: EventsListParams & {
swrConfig?: SWRConfiguration;
}) => {
list: {
id: string;
timestamp: number;
feature_id: string;
customer_id: string;
value: number;
properties: Record<string, never>;
}[] | undefined;
hasMore: boolean;
hasPrevious: boolean;
page: number;
isLoading: boolean;
error: AutumnError | undefined;
refetch: swr.KeyedMutator<{
list: {
id: string;
timestamp: number;
feature_id: string;
customer_id: string;
value: number;
properties: Record<string, never>;
}[];
has_more: boolean;
offset: number;
limit: number;
total: number;
}>;
nextPage: () => void;
prevPage: () => void;
goToPage: (pageNum: number) => void;
resetPagination: () => void;
};
declare const usePaywall: ({ featureId, entityId, }: {
featureId?: string;
entityId?: string;
}) => {
data: CheckFeaturePreview | undefined;
error: any;
isLoading: boolean;
};
declare const usePricingTable: (params?: {
productDetails?: ProductDetails[];
}) => {
products: Product[] | null;
isLoading: boolean;
error: AutumnError | undefined;
refetch: () => void;
};
declare const ReactAutumnProvider: ({ children, getBearerToken, convex, backendUrl, customerData, includeCredentials, betterAuthUrl, headers, convexApi, pathPrefix, suppressLogs, }: {
children: React.ReactNode;
getBearerToken?: () => Promise<string | null>;
convex?: any;
backendUrl?: string;
customerData?: CustomerData;
includeCredentials?: boolean;
betterAuthUrl?: string;
headers?: Record<string, string>;
convexApi?: any;
pathPrefix?: string;
suppressLogs?: boolean;
}) => React.JSX.Element;
interface CheckoutDialogProps {
open: boolean;
setOpen: (open: boolean) => void;
checkoutResult: CheckoutResult;
checkoutParams?: CheckoutParams$1;
}
declare function CheckoutDialog(params: CheckoutDialogProps): React.JSX.Element;
interface PaywallDialogProps {
open: boolean;
setOpen: (open: boolean) => void;
featureId: string;
entityId?: string;
}
declare function PaywallDialog(params?: PaywallDialogProps): JSX.Element;
declare function PricingTable({ productDetails, checkoutParams, }: {
productDetails?: ProductDetails[];
checkoutParams?: CheckoutParams;
}): React.JSX.Element;
/** @deprecated */
declare const useAutumn: () => void;
export { ReactAutumnProvider as AutumnProvider, CheckoutDialog, PaywallDialog, PricingTable, type PricingTableProduct, type ProductDetails, useAggregateEvents, useAnalytics, useAutumn, useCustomer, useEntity, useListEvents, usePaywall, usePricingTable };