@usethrottle/subscriptions 1.5.1 → 2.0.1
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/{chunk-O7VSJ72M.js → chunk-C4MXEOJ3.js} +20 -2
- package/dist/chunk-C4MXEOJ3.js.map +1 -0
- package/dist/{errors-DPLUVIMf.d.cts → errors-1V2z7X4H.d.cts} +29 -6
- package/dist/{errors-DPLUVIMf.d.ts → errors-1V2z7X4H.d.ts} +29 -6
- package/dist/index.cjs +98 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +30 -3
- package/dist/index.d.ts +30 -3
- package/dist/index.js +77 -5
- package/dist/index.js.map +1 -1
- package/dist/server.cjs +19 -1
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +2 -2
- package/dist/server.d.ts +2 -2
- package/dist/server.js +1 -1
- package/package.json +4 -3
- package/dist/chunk-O7VSJ72M.js.map +0 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.tsx","../src/errors.ts","../src/normalize.ts","../src/client.ts","../src/provider.tsx","../src/hooks.ts","../src/helpers.ts","../src/components.tsx"],"sourcesContent":["export { SubscriptionsClient, createSubscriptionsClient } from './client';\nexport { ThrottleSubscriptionsError, ThrottleError, isThrottleError } from './errors';\nexport {\n SubscriptionProvider,\n SubscriptionProviderWithClient,\n createSubscriptionFetcher,\n useSubscriptionClient,\n useSubscriptionInvalidation,\n} from './provider';\nexport {\n useCancelSubscription,\n useChangePlan,\n useCreateCheckoutSession,\n useCreateSubscription,\n useCustomerByExternalId,\n useCustomerPaymentMethods,\n usePauseSubscription,\n useResumeSubscription,\n useSubscription,\n useSubscriptions,\n useTrialEligibility,\n useUpdateSubscription,\n} from './hooks';\nexport { DunningBanner, SubscriptionStatusBadge, TrialCountdown } from './components';\nexport {\n canCancelSubscription,\n canPauseSubscription,\n canResumeSubscription,\n daysUntil,\n isSubscriptionPastDue,\n isSubscriptionTrialing,\n isTerminalSubscription,\n} from './helpers';\nexport type * from './types';\n","import { ThrottleError } from '@usethrottle/errors';\n\n/**\n * Thrown on a non-2xx response from the Throttle Subscriptions API.\n *\n * Extends the shared {@link ThrottleError} so a single\n * `catch (e) { if (e instanceof ThrottleError) … }` covers errors from every\n * Throttle SDK. `instanceof ThrottleSubscriptionsError` keeps working.\n */\nexport class ThrottleSubscriptionsError extends ThrottleError {\n constructor(args: { code: string; message: string; statusCode: number; details?: unknown }) {\n super(args);\n this.name = 'ThrottleSubscriptionsError';\n }\n}\n\nexport { ThrottleError, isThrottleError } from '@usethrottle/errors';\n","import type {\n CheckoutSession,\n Customer,\n CustomerPaymentMethod,\n Pagination,\n Subscription,\n SubscriptionInterval,\n SubscriptionStatus,\n TrialEligibilityResult,\n} from './types';\n\nexport function normalizeSubscription(raw: any): Subscription {\n return {\n id: requiredString(raw?.id, 'subscription.id'),\n workspaceId: optionalString(raw?.workspaceId),\n applicationId: optionalString(raw?.applicationId),\n customerId: requiredString(raw?.customerId, 'subscription.customerId'),\n status: (raw?.status ?? 'active') as SubscriptionStatus,\n planReference: requiredString(raw?.planReference, 'subscription.planReference'),\n planName: optionalString(raw?.planName),\n interval: (raw?.interval ?? 'monthly') as SubscriptionInterval,\n amount: Number(raw?.amount ?? 0),\n currency: optionalString(raw?.currency) ?? 'USD',\n currentPeriodStart: requiredDateString(\n raw?.currentPeriodStart,\n 'subscription.currentPeriodStart',\n ),\n currentPeriodEnd: requiredDateString(\n raw?.currentPeriodEnd,\n 'subscription.currentPeriodEnd',\n ),\n trialEnd: optionalDateString(raw?.trialEnd),\n cancelAtPeriodEnd: Boolean(raw?.cancelAtPeriodEnd ?? false),\n failureCount: Number(raw?.failureCount ?? 0),\n lastPaymentAt: optionalDateString(raw?.lastPaymentAt),\n pausedAt: optionalDateString(raw?.pausedAt),\n cancelledAt: optionalDateString(raw?.cancelledAt),\n metadata: objectOrEmpty(raw?.metadata),\n createdAt: optionalDateString(raw?.createdAt) ?? undefined,\n updatedAt: optionalDateString(raw?.updatedAt) ?? undefined,\n };\n}\n\nexport function normalizeCustomer(raw: any): Customer | null {\n if (!raw) return null;\n return {\n id: requiredString(raw?.id, 'customer.id'),\n externalId: optionalString(raw?.externalId),\n email: optionalString(raw?.email),\n firstName: optionalString(raw?.firstName),\n lastName: optionalString(raw?.lastName),\n phone: optionalString(raw?.phone),\n company: optionalString(raw?.company),\n metadata: objectOrEmpty(raw?.metadata),\n createdAt: optionalDateString(raw?.createdAt) ?? undefined,\n updatedAt: optionalDateString(raw?.updatedAt) ?? undefined,\n };\n}\n\nexport function normalizeCustomerPaymentMethod(raw: any): CustomerPaymentMethod {\n return {\n id: requiredString(raw?.id, 'paymentMethod.id'),\n processor: optionalString(raw?.processor),\n methodType: optionalString(raw?.methodType),\n cardBrand: optionalString(raw?.cardBrand),\n cardLastFour: optionalString(raw?.cardLastFour),\n isDefault: Boolean(raw?.isDefault ?? false),\n isActive: Boolean(raw?.isActive ?? true),\n createdAt: optionalDateString(raw?.createdAt) ?? undefined,\n updatedAt: optionalDateString(raw?.updatedAt) ?? undefined,\n };\n}\n\nexport function normalizeCheckoutSession(raw: any): CheckoutSession {\n const sessionId = raw?.sessionId ?? raw?.id;\n return {\n ...withoutUnderscoreKeys(raw),\n id: optionalString(raw?.id) ?? undefined,\n sessionId: requiredString(sessionId, 'checkoutSession.sessionId'),\n checkoutUrl: optionalString(raw?.checkoutUrl) ?? undefined,\n embedToken: optionalString(raw?.embedToken) ?? undefined,\n expiresAt: optionalDateString(raw?.expiresAt) ?? undefined,\n };\n}\n\nexport function normalizeTrialEligibility(raw: any): TrialEligibilityResult {\n return {\n eligible: Boolean(raw?.eligible),\n reason: raw?.reason,\n };\n}\n\nexport function normalizePagination(raw: any): Pagination | undefined {\n if (!raw) return undefined;\n return {\n cursor: raw.cursor ?? null,\n hasMore: Boolean(raw.hasMore ?? false),\n };\n}\n\nexport function toIso(value: string | Date | undefined): string | undefined {\n if (value === undefined) return undefined;\n return value instanceof Date ? value.toISOString() : value;\n}\n\nfunction requiredString(value: unknown, label: string): string {\n if (typeof value === 'string' && value.length > 0) return value;\n throw new Error(`Invalid Throttle response: missing ${label}`);\n}\n\nfunction optionalString(value: unknown): string | null {\n return typeof value === 'string' ? value : null;\n}\n\nfunction requiredDateString(value: unknown, label: string): string {\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'string' && value.length > 0) return value;\n throw new Error(`Invalid Throttle response: missing ${label}`);\n}\n\nfunction optionalDateString(value: unknown): string | null {\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'string' && value.length > 0) return value;\n return null;\n}\n\nfunction objectOrEmpty(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n}\n\nfunction withoutUnderscoreKeys(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return {};\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).filter(([key]) => !key.includes('_')),\n );\n}\n","import { ThrottleSubscriptionsError } from './errors';\nimport {\n normalizeCheckoutSession,\n normalizeCustomer,\n normalizeCustomerPaymentMethod,\n normalizePagination,\n normalizeSubscription,\n normalizeTrialEligibility,\n toIso,\n} from './normalize';\nimport type {\n ChangePlanInput,\n CheckoutSession,\n CreateCheckoutSessionInput,\n CreateSubscriptionInput,\n Customer,\n CustomerPaymentMethod,\n ListSubscriptionsParams,\n PaginatedSubscriptions,\n Subscription,\n SubscriptionInvoiceRefund,\n SubscriptionsClientContract,\n SubscriptionsClientOptions,\n ThrottleEnvelope,\n TrialEligibilityInput,\n TrialEligibilityResult,\n UpdateSubscriptionInput,\n} from './types';\n\nexport class SubscriptionsClient implements SubscriptionsClientContract {\n private readonly apiKey?: string;\n private readonly baseUrl: string;\n private readonly fetchImpl: typeof globalThis.fetch;\n private readonly fetcher?: SubscriptionsClientOptions['fetcher'];\n private readonly timeoutMs: number;\n\n constructor(opts: SubscriptionsClientOptions = {}) {\n const fetchImpl = opts.fetch ?? globalThis.fetch;\n if (!fetchImpl) throw new Error('SubscriptionsClient: fetch is required');\n if (!opts.apiKey && !opts.fetcher) {\n throw new Error('SubscriptionsClient: apiKey or fetcher is required');\n }\n\n this.apiKey = opts.apiKey;\n this.baseUrl = (opts.baseUrl ?? 'https://api.usethrottle.dev').replace(/\\/+$/, '');\n this.fetchImpl = fetchImpl;\n this.fetcher = opts.fetcher;\n this.timeoutMs = opts.timeoutMs ?? 30_000;\n }\n\n async request<T = unknown>(method: string, path: string, body?: unknown): Promise<T> {\n const envelope = await this.requestEnvelope<T>(method, path, body);\n if (Object.prototype.hasOwnProperty.call(envelope, 'data')) {\n return envelope.data as T;\n }\n return envelope as T;\n }\n\n async requestEnvelope<T = unknown>(\n method: string,\n path: string,\n body?: unknown,\n ): Promise<ThrottleEnvelope<T>> {\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);\n\n try {\n const init: RequestInit = {\n method,\n headers: {\n 'content-type': 'application/json',\n ...(this.apiKey ? { 'x-api-key': this.apiKey } : {}),\n },\n body: body !== undefined ? JSON.stringify(body) : undefined,\n signal: ctrl.signal,\n };\n\n const res = this.fetcher\n ? await this.fetcher(path, init)\n : await this.fetchImpl(toAbsoluteUrl(this.baseUrl, path), init);\n\n if (res.status === 204) return { data: undefined as T };\n\n const json = (await res.json().catch(() => ({}))) as ThrottleEnvelope<T>;\n if (!res.ok) {\n throw new ThrottleSubscriptionsError({\n code: json.error?.code ?? 'unknown_error',\n message: json.error?.message ?? `HTTP ${res.status}`,\n statusCode: res.status,\n details: json.error?.details,\n });\n }\n return json;\n } finally {\n clearTimeout(timer);\n }\n }\n\n async create(input: CreateSubscriptionInput): Promise<Subscription> {\n const customerId = await this.resolveCustomerId(input.customerId, input.externalCustomerId);\n const data = await this.request<unknown>('POST', '/api/v1/subscriptions', {\n applicationId: input.applicationId,\n customerId,\n planReference: input.planReference,\n planName: input.planName,\n interval: input.interval,\n amount: input.amount,\n currency: input.currency,\n currentPeriodStart: toIso(input.currentPeriodStart),\n currentPeriodEnd: toIso(input.currentPeriodEnd),\n trialEnd: toIso(input.trialEnd),\n metadata: input.metadata ?? {},\n orderId: input.orderId,\n });\n return normalizeSubscription(data);\n }\n\n async list(params: ListSubscriptionsParams = {}): Promise<PaginatedSubscriptions> {\n const query = new URLSearchParams();\n setQuery(query, 'customerId', params.customerId);\n setQuery(query, 'externalCustomerId', params.externalCustomerId);\n setQuery(query, 'status', params.status);\n setQuery(query, 'interval', params.interval);\n setQuery(query, 'q', params.q);\n setQuery(query, 'cursor', params.cursor);\n setQuery(query, 'limit', params.limit);\n setQuery(query, 'sort', params.sort);\n setQuery(query, 'createdAfter', toIso(params.createdAfter));\n setQuery(query, 'createdBefore', toIso(params.createdBefore));\n\n const suffix = query.toString() ? `?${query}` : '';\n const envelope = await this.requestEnvelope<unknown[]>('GET', `/api/v1/subscriptions${suffix}`);\n return {\n data: (envelope.data ?? []).map(normalizeSubscription),\n pagination: normalizePagination(envelope.meta?.pagination),\n };\n }\n\n async get(id: string): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'GET',\n `/api/v1/subscriptions/${encodeURIComponent(id)}`,\n );\n return normalizeSubscription(data);\n }\n\n async update(id: string, input: UpdateSubscriptionInput): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'PATCH',\n `/api/v1/subscriptions/${encodeURIComponent(id)}`,\n input,\n );\n return normalizeSubscription(data);\n }\n\n changePlan(input: ChangePlanInput): Promise<Subscription> {\n const { id, ...body } = input;\n return this.update(id, body);\n }\n\n async pause(id: string): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/pause`,\n );\n return normalizeSubscription(data);\n }\n\n async resume(id: string): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/resume`,\n );\n return normalizeSubscription(data);\n }\n\n async cancel(\n id: string,\n input: { atPeriodEnd?: boolean; refund?: 'none' | 'prorated' | 'last_cycle' } = {},\n ): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/cancel`,\n { atPeriodEnd: input.atPeriodEnd ?? false, refund: input.refund ?? 'none' },\n );\n return normalizeSubscription(data);\n }\n\n /**\n * Refund one billing cycle.\n *\n * `intent` has no default: refunding money and ending the subscription are\n * separate decisions, and guessing either way is wrong often enough that the\n * API requires the caller to say which one they mean.\n */\n async refundInvoice(\n id: string,\n invoiceId: string,\n input: { intent: 'money_only' | 'refund_and_cancel'; amount?: number; reason?: string },\n ): Promise<SubscriptionInvoiceRefund> {\n return this.request<SubscriptionInvoiceRefund>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/invoices/${encodeURIComponent(invoiceId)}/refund`,\n input,\n );\n }\n\n async createCheckoutSession(input: CreateCheckoutSessionInput): Promise<CheckoutSession> {\n const data = await this.request<unknown>('POST', '/api/v1/checkout/sessions', input);\n return normalizeCheckoutSession(data);\n }\n\n async checkTrialEligibility(input: TrialEligibilityInput): Promise<TrialEligibilityResult> {\n const data = await this.request<unknown>('POST', '/api/v1/subscriptions/eligibility-check', {\n paymentMethodId: input.paymentMethodId,\n });\n return normalizeTrialEligibility(data);\n }\n\n async getCustomerByExternalId(externalId: string): Promise<Customer | null> {\n try {\n const data = await this.request<unknown>(\n 'GET',\n `/api/v1/customers/by-external/${encodeURIComponent(externalId)}`,\n );\n return normalizeCustomer(data);\n } catch (err) {\n if (err instanceof ThrottleSubscriptionsError && err.statusCode === 404) return null;\n throw err;\n }\n }\n\n async listCustomerPaymentMethods(customerId: string): Promise<CustomerPaymentMethod[]> {\n const data = await this.request<unknown[]>(\n 'GET',\n `/api/v1/customers/${encodeURIComponent(customerId)}/payment-methods`,\n );\n return (data ?? []).map(normalizeCustomerPaymentMethod);\n }\n\n private async resolveCustomerId(\n customerId?: string,\n externalCustomerId?: string,\n ): Promise<string> {\n if (customerId) return customerId;\n if (!externalCustomerId) {\n throw new ThrottleSubscriptionsError({\n code: 'invalid_request',\n message: 'customerId or externalCustomerId is required',\n statusCode: 400,\n });\n }\n\n const customer = await this.getCustomerByExternalId(externalCustomerId);\n if (!customer) {\n throw new ThrottleSubscriptionsError({\n code: 'customer_not_found',\n message: 'Customer not found',\n statusCode: 404,\n });\n }\n return customer.id;\n }\n}\n\nexport function createSubscriptionsClient(opts: SubscriptionsClientOptions): SubscriptionsClient {\n return new SubscriptionsClient(opts);\n}\n\nfunction toAbsoluteUrl(baseUrl: string, path: string): string {\n if (/^https?:\\/\\//i.test(path)) return path;\n return `${baseUrl}${path.startsWith('/') ? path : `/${path}`}`;\n}\n\nfunction setQuery(query: URLSearchParams, key: string, value: unknown): void {\n if (value === undefined || value === null || value === '') return;\n query.set(key, String(value));\n}\n","import { createContext, useCallback, useContext, useMemo, useReducer, type ReactNode } from 'react';\nimport { SubscriptionsClient } from './client';\nimport type {\n SubscriptionFetcher,\n SubscriptionProviderProps,\n SubscriptionsClientContract,\n} from './types';\n\ninterface SubscriptionContextValue {\n client: SubscriptionsClientContract;\n cacheVersion: number;\n invalidate: () => void;\n}\n\nconst SubscriptionContext = createContext<SubscriptionContextValue | null>(null);\n\nexport function SubscriptionProvider({\n children,\n client,\n fetcher,\n baseUrl,\n timeoutMs,\n}: SubscriptionProviderProps) {\n const [cacheVersion, invalidate] = useReducer((value: number) => value + 1, 0);\n const resolvedClient = useMemo(() => {\n if (client) return client;\n return new SubscriptionsClient({\n fetcher: fetcher ?? createSubscriptionFetcher('/api/throttle'),\n baseUrl,\n timeoutMs,\n });\n }, [baseUrl, client, fetcher, timeoutMs]);\n\n const value = useMemo(\n () => ({ client: resolvedClient, cacheVersion, invalidate }),\n [cacheVersion, resolvedClient],\n );\n\n return <SubscriptionContext.Provider value={value}>{children}</SubscriptionContext.Provider>;\n}\n\nexport function useSubscriptionClient(): SubscriptionsClientContract {\n return useSubscriptionContext().client;\n}\n\nexport function useSubscriptionInvalidation(): () => void {\n return useSubscriptionContext().invalidate;\n}\n\nexport function useSubscriptionCacheVersion(): number {\n return useSubscriptionContext().cacheVersion;\n}\n\nexport function createSubscriptionFetcher(basePath: string): SubscriptionFetcher {\n const cleanBase = basePath.replace(/\\/+$/, '');\n return (path, init) => {\n const cleanPath = path.startsWith('/') ? path : `/${path}`;\n return fetch(`${cleanBase}${cleanPath}`, init);\n };\n}\n\nexport function useSubscriptionContext(): SubscriptionContextValue {\n const ctx = useContext(SubscriptionContext);\n if (!ctx) {\n throw new Error(\n '@usethrottle/subscriptions hooks must be used inside <SubscriptionProvider />',\n );\n }\n return ctx;\n}\n\nexport function SubscriptionProviderWithClient({\n children,\n client,\n}: {\n children: ReactNode;\n client: SubscriptionsClientContract;\n}) {\n const [cacheVersion, invalidate] = useReducer((value: number) => value + 1, 0);\n const value = useMemo(() => ({ client, cacheVersion, invalidate }), [cacheVersion, client]);\n return <SubscriptionContext.Provider value={value}>{children}</SubscriptionContext.Provider>;\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport {\n useSubscriptionCacheVersion,\n useSubscriptionClient,\n useSubscriptionInvalidation,\n} from './provider';\nimport type {\n CancelSubscriptionInput,\n ChangePlanInput,\n CheckoutSession,\n CreateCheckoutSessionInput,\n CreateSubscriptionInput,\n Customer,\n CustomerPaymentMethod,\n ListSubscriptionsParams,\n MutationState,\n PaginatedSubscriptions,\n QueryOptions,\n QueryState,\n Subscription,\n TrialEligibilityInput,\n TrialEligibilityResult,\n UpdateSubscriptionInput,\n} from './types';\n\nexport function useSubscriptions(\n params: ListSubscriptionsParams = {},\n options: QueryOptions<PaginatedSubscriptions> = {},\n): QueryState<PaginatedSubscriptions> {\n const client = useSubscriptionClient();\n const cacheVersion = useSubscriptionCacheVersion();\n const stableParams = useStableValue(params);\n return useAsyncQuery(\n () => client.list(stableParams),\n [client, stableParams, cacheVersion],\n options,\n );\n}\n\nexport function useSubscription(\n id: string | null | undefined,\n options: QueryOptions<Subscription> = {},\n): QueryState<Subscription> {\n const client = useSubscriptionClient();\n const cacheVersion = useSubscriptionCacheVersion();\n return useAsyncQuery(\n () => (id ? client.get(id) : Promise.resolve(null)),\n [client, id, cacheVersion],\n { ...options, enabled: options.enabled ?? Boolean(id) },\n );\n}\n\nexport function useCustomerByExternalId(\n externalId: string | null | undefined,\n options: QueryOptions<Customer> = {},\n): QueryState<Customer> {\n const client = useSubscriptionClient();\n const cacheVersion = useSubscriptionCacheVersion();\n return useAsyncQuery(\n () => (externalId ? client.getCustomerByExternalId(externalId) : Promise.resolve(null)),\n [client, externalId, cacheVersion],\n { ...options, enabled: options.enabled ?? Boolean(externalId) },\n );\n}\n\nexport function useCustomerPaymentMethods(\n customerId: string | null | undefined,\n options: QueryOptions<CustomerPaymentMethod[]> = {},\n): QueryState<CustomerPaymentMethod[]> {\n const client = useSubscriptionClient();\n const cacheVersion = useSubscriptionCacheVersion();\n return useAsyncQuery(\n () => (customerId ? client.listCustomerPaymentMethods(customerId) : Promise.resolve(null)),\n [client, customerId, cacheVersion],\n { ...options, enabled: options.enabled ?? Boolean(customerId) },\n );\n}\n\nexport function useTrialEligibility(): MutationState<\n TrialEligibilityResult,\n TrialEligibilityInput\n> {\n const client = useSubscriptionClient();\n return useAsyncMutation((input) => client.checkTrialEligibility(input));\n}\n\nexport function useCreateSubscription(): MutationState<Subscription, CreateSubscriptionInput> {\n const client = useSubscriptionClient();\n const invalidate = useSubscriptionInvalidation();\n return useAsyncMutation((input) => client.create(input), invalidate);\n}\n\nexport function useUpdateSubscription(): MutationState<\n Subscription,\n { id: string; data: UpdateSubscriptionInput }\n> {\n const client = useSubscriptionClient();\n const invalidate = useSubscriptionInvalidation();\n return useAsyncMutation(({ id, data }) => client.update(id, data), invalidate);\n}\n\nexport function useChangePlan(): MutationState<Subscription, ChangePlanInput> {\n const client = useSubscriptionClient();\n const invalidate = useSubscriptionInvalidation();\n return useAsyncMutation((input) => client.changePlan(input), invalidate);\n}\n\nexport function useCancelSubscription(): MutationState<Subscription, CancelSubscriptionInput> {\n const client = useSubscriptionClient();\n const invalidate = useSubscriptionInvalidation();\n return useAsyncMutation(\n (input) => client.cancel(input.id, { atPeriodEnd: input.atPeriodEnd }),\n invalidate,\n );\n}\n\nexport function usePauseSubscription(): MutationState<Subscription, { id: string }> {\n const client = useSubscriptionClient();\n const invalidate = useSubscriptionInvalidation();\n return useAsyncMutation((input) => client.pause(input.id), invalidate);\n}\n\nexport function useResumeSubscription(): MutationState<Subscription, { id: string }> {\n const client = useSubscriptionClient();\n const invalidate = useSubscriptionInvalidation();\n return useAsyncMutation((input) => client.resume(input.id), invalidate);\n}\n\nexport function useCreateCheckoutSession(): MutationState<\n CheckoutSession,\n CreateCheckoutSessionInput\n> {\n const client = useSubscriptionClient();\n return useAsyncMutation((input) => client.createCheckoutSession(input));\n}\n\nfunction useAsyncQuery<T>(\n load: () => Promise<T | null>,\n deps: readonly unknown[],\n options: QueryOptions<T>,\n): QueryState<T> {\n const enabled = options.enabled ?? true;\n const [data, setData] = useState<T | null>(options.initialData ?? null);\n const [error, setError] = useState<unknown>(null);\n const [isLoading, setIsLoading] = useState(enabled && options.initialData === undefined);\n const [isFetching, setIsFetching] = useState(false);\n const loadRef = useRef(load);\n loadRef.current = load;\n\n const refetch = useCallback(async () => {\n if (!enabled) return data;\n setIsFetching(true);\n setError(null);\n try {\n const next = await loadRef.current();\n setData(next);\n return next;\n } catch (err) {\n setError(err);\n throw err;\n } finally {\n setIsFetching(false);\n setIsLoading(false);\n }\n }, [data, enabled]);\n\n useEffect(() => {\n if (!enabled) {\n setIsLoading(false);\n return;\n }\n let cancelled = false;\n setIsFetching(true);\n setError(null);\n load()\n .then((next) => {\n if (!cancelled) setData(next);\n })\n .catch((err) => {\n if (!cancelled) setError(err);\n })\n .finally(() => {\n if (!cancelled) {\n setIsLoading(false);\n setIsFetching(false);\n }\n });\n\n return () => {\n cancelled = true;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [enabled, ...deps]);\n\n return { data, error, isLoading, isFetching, refetch };\n}\n\nfunction useAsyncMutation<TData, TVariables>(\n action: (variables: TVariables) => Promise<TData>,\n onSuccess?: () => void,\n): MutationState<TData, TVariables> {\n const [data, setData] = useState<TData | null>(null);\n const [error, setError] = useState<unknown>(null);\n const [isPending, setIsPending] = useState(false);\n\n const mutateAsync = useCallback(\n async (variables: TVariables) => {\n setIsPending(true);\n setError(null);\n try {\n const next = await action(variables);\n setData(next);\n onSuccess?.();\n return next;\n } catch (err) {\n setError(err);\n throw err;\n } finally {\n setIsPending(false);\n }\n },\n [action, onSuccess],\n );\n\n const mutate = useCallback(\n (variables: TVariables) => {\n void mutateAsync(variables).catch(() => undefined);\n },\n [mutateAsync],\n );\n\n const reset = useCallback(() => {\n setData(null);\n setError(null);\n setIsPending(false);\n }, []);\n\n return { data, error, isPending, mutate, mutateAsync, reset };\n}\n\nfunction useStableValue<T>(value: T): T {\n const key = JSON.stringify(value);\n return useMemo(() => value, [key]);\n}\n","import type { Subscription, SubscriptionStatus } from './types';\n\nexport function isTerminalSubscription(status: SubscriptionStatus | Subscription): boolean {\n return getStatus(status) === 'cancelled';\n}\n\nexport function canPauseSubscription(status: SubscriptionStatus | Subscription): boolean {\n return getStatus(status) === 'active';\n}\n\nexport function canResumeSubscription(status: SubscriptionStatus | Subscription): boolean {\n return getStatus(status) === 'paused';\n}\n\nexport function canCancelSubscription(status: SubscriptionStatus | Subscription): boolean {\n return getStatus(status) !== 'cancelled';\n}\n\nexport function isSubscriptionPastDue(status: SubscriptionStatus | Subscription): boolean {\n return getStatus(status) === 'past_due';\n}\n\nexport function isSubscriptionTrialing(status: SubscriptionStatus | Subscription): boolean {\n return getStatus(status) === 'trialing';\n}\n\nexport function daysUntil(date: string | Date, now = new Date()): number {\n const end = date instanceof Date ? date : new Date(date);\n const ms = end.getTime() - now.getTime();\n if (!Number.isFinite(ms)) return 0;\n return Math.max(0, Math.ceil(ms / 86_400_000));\n}\n\nfunction getStatus(input: SubscriptionStatus | Subscription): SubscriptionStatus {\n return typeof input === 'string' ? input : input.status;\n}\n","import type { CSSProperties } from 'react';\nimport { daysUntil } from './helpers';\nimport type {\n DunningBannerProps,\n SubscriptionStatus,\n SubscriptionStatusBadgeProps,\n TrialCountdownProps,\n} from './types';\n\nconst STATUS_LABELS: Record<SubscriptionStatus, string> = {\n active: 'Active',\n paused: 'Paused',\n cancelled: 'Cancelled',\n past_due: 'Past due',\n trialing: 'Trialing',\n};\n\nconst STATUS_STYLES: Record<SubscriptionStatus, CSSProperties> = {\n active: { color: '#035c4f', background: '#dff8ef', borderColor: '#a8e8d2' },\n paused: { color: '#735c00', background: '#fff4ca', borderColor: '#f3d46b' },\n cancelled: { color: '#6c2632', background: '#ffe1e7', borderColor: '#f4a9b8' },\n past_due: { color: '#7a2d00', background: '#ffe8d6', borderColor: '#f5b47f' },\n trialing: { color: '#124c73', background: '#dff1ff', borderColor: '#9ed3fb' },\n};\n\nexport function SubscriptionStatusBadge({\n status,\n className,\n style,\n labels,\n}: SubscriptionStatusBadgeProps) {\n return (\n <span\n className={className}\n style={{\n display: 'inline-flex',\n alignItems: 'center',\n border: '1px solid',\n borderRadius: 999,\n padding: '2px 8px',\n fontSize: 12,\n fontWeight: 700,\n lineHeight: 1.6,\n whiteSpace: 'nowrap',\n ...STATUS_STYLES[status],\n ...style,\n }}\n >\n {labels?.[status] ?? STATUS_LABELS[status]}\n </span>\n );\n}\n\nexport function TrialCountdown({\n endDate,\n now,\n className,\n style,\n expiredLabel = 'Trial ended',\n prefix = 'Trial ends in',\n}: TrialCountdownProps) {\n const days = daysUntil(endDate, now);\n const label = days <= 0 ? expiredLabel : `${prefix} ${days} ${days === 1 ? 'day' : 'days'}`;\n\n return (\n <span className={className} style={style}>\n {label}\n </span>\n );\n}\n\nexport function DunningBanner({\n subscription,\n onUpdateCard,\n title = 'Payment needs attention',\n message,\n actionLabel = 'Update card',\n className,\n style,\n}: DunningBannerProps) {\n if (subscription.status !== 'past_due') return null;\n const fallbackMessage =\n subscription.failureCount > 0\n ? `We could not renew this subscription after ${subscription.failureCount} failed payment attempt${\n subscription.failureCount === 1 ? '' : 's'\n }.`\n : 'We could not renew this subscription with the saved payment method.';\n\n return (\n <div\n role=\"status\"\n className={className}\n style={{\n border: '1px solid #f5b47f',\n borderRadius: 8,\n background: '#fff7ed',\n color: '#7a2d00',\n padding: 16,\n display: 'grid',\n gap: 10,\n ...style,\n }}\n >\n <strong>{title}</strong>\n <span>{message ?? fallbackMessage}</span>\n {onUpdateCard ? (\n <button\n type=\"button\"\n onClick={onUpdateCard}\n style={{\n width: 'fit-content',\n border: '1px solid #7a2d00',\n borderRadius: 6,\n background: '#7a2d00',\n color: '#fff',\n padding: '8px 12px',\n fontWeight: 700,\n cursor: 'pointer',\n }}\n >\n {actionLabel}\n </button>\n ) : null}\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oBAA8B;AAgB9B,IAAAA,iBAA+C;AAPxC,IAAM,6BAAN,cAAyC,4BAAc;AAAA,EAC5D,YAAY,MAAgF;AAC1F,UAAM,IAAI;AACV,SAAK,OAAO;AAAA,EACd;AACF;;;ACHO,SAAS,sBAAsB,KAAwB;AAC5D,SAAO;AAAA,IACL,IAAI,eAAe,KAAK,IAAI,iBAAiB;AAAA,IAC7C,aAAa,eAAe,KAAK,WAAW;AAAA,IAC5C,eAAe,eAAe,KAAK,aAAa;AAAA,IAChD,YAAY,eAAe,KAAK,YAAY,yBAAyB;AAAA,IACrE,QAAS,KAAK,UAAU;AAAA,IACxB,eAAe,eAAe,KAAK,eAAe,4BAA4B;AAAA,IAC9E,UAAU,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AAAA,qDAAC,YAAQ,iBAAM;AAAA,QACf,6CAAC,UAAM,qBAAW,iBAAgB;AAAA,QACjC,eACC;AAAA,UAAC;AAAA;AAAA,YACC,MAAK;AAAA,YACL,SAAS;AAAA,YACT,OAAO;AAAA,cACL,OAAO;AAAA,cACP,QAAQ;AAAA,cACR,cAAc;AAAA,cACd,YAAY;AAAA,cACZ,OAAO;AAAA,cACP,SAAS;AAAA,cACT,YAAY;AAAA,cACZ,QAAQ;AAAA,YACV;AAAA,YAEC;AAAA;AAAA,QACH,IACE;AAAA;AAAA;AAAA,EACN;AAEJ;","names":["import_errors","value","import_react","import_jsx_runtime"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.tsx","../src/errors.ts","../src/normalize.ts","../src/client.ts","../src/provider.tsx","../src/hooks.ts","../../core-cadence/src/cadence.ts","../../core-cadence/src/installments.ts","../../core-cadence/src/labels.ts","../src/helpers.ts","../src/components.tsx"],"sourcesContent":["export { SubscriptionsClient, createSubscriptionsClient } from './client';\nexport { ThrottleSubscriptionsError, ThrottleError, isThrottleError } from './errors';\nexport {\n SubscriptionProvider,\n SubscriptionProviderWithClient,\n createSubscriptionFetcher,\n useSubscriptionClient,\n useSubscriptionInvalidation,\n} from './provider';\nexport {\n useCancelSubscription,\n useChangePlan,\n useCreateCheckoutSession,\n useCreateSubscription,\n useCustomerByExternalId,\n useCustomerPaymentMethods,\n usePauseSubscription,\n useResumeSubscription,\n useSubscription,\n useSubscriptions,\n useTrialEligibility,\n useUpdateSubscription,\n} from './hooks';\nexport { DunningBanner, SubscriptionStatusBadge, TrialCountdown } from './components';\nexport {\n cadenceLabel,\n cadenceNoun,\n canCancelSubscription,\n canPauseSubscription,\n canResumeSubscription,\n daysUntil,\n installmentProgress,\n isSubscriptionPastDue,\n isSubscriptionTrialing,\n isTerminalSubscription,\n type CadenceLike,\n type InstallmentProgress,\n} from './helpers';\nexport type * from './types';\n","import { ThrottleError, type ThrottleErrorArgs } from '@usethrottle/errors';\n\n/**\n * Thrown on a non-2xx response from the Throttle Subscriptions API.\n *\n * Extends the shared {@link ThrottleError} so a single\n * `catch (e) { if (e instanceof ThrottleError) … }` covers errors from every\n * Throttle SDK. `instanceof ThrottleSubscriptionsError` keeps working.\n */\nexport class ThrottleSubscriptionsError extends ThrottleError {\n constructor(args: {\n code: string;\n message: string;\n statusCode: number;\n details?: unknown;\n responseHeaders?: ThrottleErrorArgs['responseHeaders'];\n }) {\n super(args);\n this.name = 'ThrottleSubscriptionsError';\n }\n}\n\nexport { ThrottleError, isThrottleError } from '@usethrottle/errors';\n","import type {\n CheckoutSession,\n Customer,\n CustomerPaymentMethod,\n Pagination,\n Subscription,\n SubscriptionInterval,\n SubscriptionStatus,\n TrialEligibilityResult,\n} from './types';\n\nexport function normalizeSubscription(raw: any): Subscription {\n return {\n id: requiredString(raw?.id, 'subscription.id'),\n workspaceId: optionalString(raw?.workspaceId),\n applicationId: optionalString(raw?.applicationId),\n customerId: requiredString(raw?.customerId, 'subscription.customerId'),\n status: (raw?.status ?? 'active') as SubscriptionStatus,\n planReference: requiredString(raw?.planReference, 'subscription.planReference'),\n planName: optionalString(raw?.planName),\n interval: (raw?.interval ?? 'monthly') as SubscriptionInterval,\n intervalUnit: (optionalString(raw?.intervalUnit) as Subscription['intervalUnit']) ?? null,\n intervalCount: raw?.intervalCount == null ? null : Number(raw.intervalCount),\n totalPayments: raw?.totalPayments == null ? null : Number(raw.totalPayments),\n paymentsMade: Number(raw?.paymentsMade ?? 0),\n completedAt: optionalIsoDateString(raw?.completedAt),\n amount: Number(raw?.amount ?? 0),\n currency: optionalString(raw?.currency) ?? 'USD',\n currentPeriodStart: requiredDateString(\n raw?.currentPeriodStart,\n 'subscription.currentPeriodStart',\n ),\n currentPeriodEnd: requiredDateString(\n raw?.currentPeriodEnd,\n 'subscription.currentPeriodEnd',\n ),\n trialEnd: optionalDateString(raw?.trialEnd),\n cancelAtPeriodEnd: Boolean(raw?.cancelAtPeriodEnd ?? false),\n failureCount: Number(raw?.failureCount ?? 0),\n lastPaymentAt: optionalDateString(raw?.lastPaymentAt),\n pausedAt: optionalDateString(raw?.pausedAt),\n cancelledAt: optionalDateString(raw?.cancelledAt),\n metadata: objectOrEmpty(raw?.metadata),\n createdAt: optionalDateString(raw?.createdAt) ?? undefined,\n updatedAt: optionalDateString(raw?.updatedAt) ?? undefined,\n };\n}\n\nexport function normalizeCustomer(raw: any): Customer | null {\n if (!raw) return null;\n return {\n id: requiredString(raw?.id, 'customer.id'),\n externalId: optionalString(raw?.externalId),\n email: optionalString(raw?.email),\n firstName: optionalString(raw?.firstName),\n lastName: optionalString(raw?.lastName),\n phone: optionalString(raw?.phone),\n company: optionalString(raw?.company),\n metadata: objectOrEmpty(raw?.metadata),\n createdAt: optionalDateString(raw?.createdAt) ?? undefined,\n updatedAt: optionalDateString(raw?.updatedAt) ?? undefined,\n };\n}\n\nexport function normalizeCustomerPaymentMethod(raw: any): CustomerPaymentMethod {\n return {\n id: requiredString(raw?.id, 'paymentMethod.id'),\n processor: optionalString(raw?.processor),\n methodType: optionalString(raw?.methodType),\n cardBrand: optionalString(raw?.cardBrand),\n cardLastFour: optionalString(raw?.cardLastFour),\n isDefault: Boolean(raw?.isDefault ?? false),\n isActive: Boolean(raw?.isActive ?? true),\n createdAt: optionalDateString(raw?.createdAt) ?? undefined,\n updatedAt: optionalDateString(raw?.updatedAt) ?? undefined,\n };\n}\n\nexport function normalizeCheckoutSession(raw: any): CheckoutSession {\n const sessionId = raw?.sessionId ?? raw?.id;\n return {\n ...withoutUnderscoreKeys(raw),\n id: optionalString(raw?.id) ?? undefined,\n sessionId: requiredString(sessionId, 'checkoutSession.sessionId'),\n checkoutUrl: optionalString(raw?.checkoutUrl) ?? undefined,\n embedToken: optionalString(raw?.embedToken) ?? undefined,\n expiresAt: optionalDateString(raw?.expiresAt) ?? undefined,\n };\n}\n\nexport function normalizeTrialEligibility(raw: any): TrialEligibilityResult {\n return {\n eligible: Boolean(raw?.eligible),\n reason: raw?.reason,\n };\n}\n\nexport function normalizePagination(raw: any): Pagination | undefined {\n if (!raw) return undefined;\n return {\n cursor: raw.cursor ?? null,\n hasMore: Boolean(raw.hasMore ?? false),\n };\n}\n\nexport function toIso(value: string | Date | undefined): string | undefined {\n if (value === undefined) return undefined;\n return value instanceof Date ? value.toISOString() : value;\n}\n\nfunction requiredString(value: unknown, label: string): string {\n if (typeof value === 'string' && value.length > 0) return value;\n throw new Error(`Invalid Throttle response: missing ${label}`);\n}\n\nfunction optionalString(value: unknown): string | null {\n return typeof value === 'string' ? value : null;\n}\n\nfunction requiredDateString(value: unknown, label: string): string {\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'string' && value.length > 0) return value;\n throw new Error(`Invalid Throttle response: missing ${label}`);\n}\n\nfunction optionalDateString(value: unknown): string | null {\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'string' && value.length > 0) return value;\n return null;\n}\n\n/**\n * Like `optionalDateString`, but always reserializes to a full ISO string\n * (with milliseconds) rather than passing a raw string through unchanged.\n * `completedAt` is a fresh field with no legacy raw-string callers to stay\n * compatible with, so it normalizes cleanly instead of echoing whatever the\n * API sent.\n */\nfunction optionalIsoDateString(value: unknown): string | null {\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'string' && value.length > 0) {\n const d = new Date(value);\n return Number.isNaN(d.getTime()) ? value : d.toISOString();\n }\n return null;\n}\n\nfunction objectOrEmpty(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n}\n\nfunction withoutUnderscoreKeys(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return {};\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).filter(([key]) => !key.includes('_')),\n );\n}\n","import { ThrottleSubscriptionsError } from './errors';\nimport {\n normalizeCheckoutSession,\n normalizeCustomer,\n normalizeCustomerPaymentMethod,\n normalizePagination,\n normalizeSubscription,\n normalizeTrialEligibility,\n toIso,\n} from './normalize';\nimport type {\n ChangePlanInput,\n CheckoutSession,\n CreateCheckoutSessionInput,\n CreateSubscriptionInput,\n Customer,\n CustomerPaymentMethod,\n ListSubscriptionsParams,\n PaginatedSubscriptions,\n Subscription,\n SubscriptionInvoiceRefund,\n SubscriptionsClientContract,\n SubscriptionsClientOptions,\n ThrottleEnvelope,\n TrialEligibilityInput,\n TrialEligibilityResult,\n UpdateSubscriptionInput,\n} from './types';\n\nexport class SubscriptionsClient implements SubscriptionsClientContract {\n private readonly apiKey?: string;\n private readonly baseUrl: string;\n private readonly fetchImpl: typeof globalThis.fetch;\n private readonly fetcher?: SubscriptionsClientOptions['fetcher'];\n private readonly timeoutMs: number;\n\n constructor(opts: SubscriptionsClientOptions = {}) {\n const fetchImpl = opts.fetch ?? globalThis.fetch;\n if (!fetchImpl) throw new Error('SubscriptionsClient: fetch is required');\n if (!opts.apiKey && !opts.fetcher) {\n throw new Error('SubscriptionsClient: apiKey or fetcher is required');\n }\n\n this.apiKey = opts.apiKey;\n this.baseUrl = (opts.baseUrl ?? 'https://api.usethrottle.dev').replace(/\\/+$/, '');\n this.fetchImpl = fetchImpl;\n this.fetcher = opts.fetcher;\n this.timeoutMs = opts.timeoutMs ?? 30_000;\n }\n\n async request<T = unknown>(method: string, path: string, body?: unknown): Promise<T> {\n const envelope = await this.requestEnvelope<T>(method, path, body);\n if (Object.prototype.hasOwnProperty.call(envelope, 'data')) {\n return envelope.data as T;\n }\n return envelope as T;\n }\n\n async requestEnvelope<T = unknown>(\n method: string,\n path: string,\n body?: unknown,\n ): Promise<ThrottleEnvelope<T>> {\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);\n\n try {\n const init: RequestInit = {\n method,\n headers: {\n 'content-type': 'application/json',\n ...(this.apiKey ? { 'x-api-key': this.apiKey } : {}),\n },\n body: body !== undefined ? JSON.stringify(body) : undefined,\n signal: ctrl.signal,\n };\n\n const res = this.fetcher\n ? await this.fetcher(path, init)\n : await this.fetchImpl(toAbsoluteUrl(this.baseUrl, path), init);\n\n if (res.status === 204) return { data: undefined as T };\n\n const json = (await res.json().catch(() => ({}))) as ThrottleEnvelope<T>;\n if (!res.ok) {\n throw new ThrottleSubscriptionsError({\n code: json.error?.code ?? 'unknown_error',\n message: json.error?.message ?? `HTTP ${res.status}`,\n statusCode: res.status,\n details: json.error?.details,\n responseHeaders: res.headers,\n });\n }\n return json;\n } finally {\n clearTimeout(timer);\n }\n }\n\n async create(input: CreateSubscriptionInput): Promise<Subscription> {\n const customerId = await this.resolveCustomerId(input.customerId, input.externalCustomerId);\n const data = await this.request<unknown>('POST', '/api/v1/subscriptions', {\n applicationId: input.applicationId,\n customerId,\n planReference: input.planReference,\n planName: input.planName,\n interval: input.interval,\n intervalUnit: input.intervalUnit,\n intervalCount: input.intervalCount,\n totalPayments: input.totalPayments,\n amount: input.amount,\n currency: input.currency,\n currentPeriodStart: toIso(input.currentPeriodStart),\n currentPeriodEnd: toIso(input.currentPeriodEnd),\n trialEnd: toIso(input.trialEnd),\n metadata: input.metadata ?? {},\n orderId: input.orderId,\n });\n return normalizeSubscription(data);\n }\n\n async list(params: ListSubscriptionsParams = {}): Promise<PaginatedSubscriptions> {\n const query = new URLSearchParams();\n setQuery(query, 'customerId', params.customerId);\n setQuery(query, 'externalCustomerId', params.externalCustomerId);\n setQuery(query, 'status', params.status);\n setQuery(query, 'interval', params.interval);\n setQuery(query, 'installment', params.installment);\n setQuery(query, 'q', params.q);\n setQuery(query, 'cursor', params.cursor);\n setQuery(query, 'limit', params.limit);\n setQuery(query, 'sort', params.sort);\n setQuery(query, 'createdAfter', toIso(params.createdAfter));\n setQuery(query, 'createdBefore', toIso(params.createdBefore));\n\n const suffix = query.toString() ? `?${query}` : '';\n const envelope = await this.requestEnvelope<unknown[]>('GET', `/api/v1/subscriptions${suffix}`);\n return {\n data: (envelope.data ?? []).map(normalizeSubscription),\n pagination: normalizePagination(envelope.meta?.pagination),\n };\n }\n\n async get(id: string): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'GET',\n `/api/v1/subscriptions/${encodeURIComponent(id)}`,\n );\n return normalizeSubscription(data);\n }\n\n async update(id: string, input: UpdateSubscriptionInput): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'PATCH',\n `/api/v1/subscriptions/${encodeURIComponent(id)}`,\n input,\n );\n return normalizeSubscription(data);\n }\n\n changePlan(input: ChangePlanInput): Promise<Subscription> {\n const { id, ...body } = input;\n return this.update(id, body);\n }\n\n async pause(id: string): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/pause`,\n );\n return normalizeSubscription(data);\n }\n\n async resume(id: string): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/resume`,\n );\n return normalizeSubscription(data);\n }\n\n async cancel(\n id: string,\n input: { atPeriodEnd?: boolean; refund?: 'none' | 'prorated' | 'last_cycle' } = {},\n ): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/cancel`,\n { atPeriodEnd: input.atPeriodEnd ?? false, refund: input.refund ?? 'none' },\n );\n return normalizeSubscription(data);\n }\n\n /**\n * Refund one billing cycle.\n *\n * `intent` has no default: refunding money and ending the subscription are\n * separate decisions, and guessing either way is wrong often enough that the\n * API requires the caller to say which one they mean.\n */\n async refundInvoice(\n id: string,\n invoiceId: string,\n input: { intent: 'money_only' | 'refund_and_cancel'; amount?: number; reason?: string },\n ): Promise<SubscriptionInvoiceRefund> {\n return this.request<SubscriptionInvoiceRefund>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/invoices/${encodeURIComponent(invoiceId)}/refund`,\n input,\n );\n }\n\n async createCheckoutSession(input: CreateCheckoutSessionInput): Promise<CheckoutSession> {\n const data = await this.request<unknown>('POST', '/api/v1/checkout/sessions', input);\n return normalizeCheckoutSession(data);\n }\n\n async checkTrialEligibility(input: TrialEligibilityInput): Promise<TrialEligibilityResult> {\n const data = await this.request<unknown>('POST', '/api/v1/subscriptions/eligibility-check', {\n paymentMethodId: input.paymentMethodId,\n });\n return normalizeTrialEligibility(data);\n }\n\n async getCustomerByExternalId(externalId: string): Promise<Customer | null> {\n try {\n const data = await this.request<unknown>(\n 'GET',\n `/api/v1/customers/by-external/${encodeURIComponent(externalId)}`,\n );\n return normalizeCustomer(data);\n } catch (err) {\n if (err instanceof ThrottleSubscriptionsError && err.statusCode === 404) return null;\n throw err;\n }\n }\n\n async listCustomerPaymentMethods(customerId: string): Promise<CustomerPaymentMethod[]> {\n const data = await this.request<unknown[]>(\n 'GET',\n `/api/v1/customers/${encodeURIComponent(customerId)}/payment-methods`,\n );\n return (data ?? []).map(normalizeCustomerPaymentMethod);\n }\n\n private async resolveCustomerId(\n customerId?: string,\n externalCustomerId?: string,\n ): Promise<string> {\n if (customerId) return customerId;\n if (!externalCustomerId) {\n throw new ThrottleSubscriptionsError({\n code: 'invalid_request',\n message: 'customerId or externalCustomerId is required',\n statusCode: 400,\n });\n }\n\n const customer = await this.getCustomerByExternalId(externalCustomerId);\n if (!customer) {\n throw new ThrottleSubscriptionsError({\n code: 'customer_not_found',\n message: 'Customer not found',\n statusCode: 404,\n });\n }\n return customer.id;\n }\n}\n\nexport function createSubscriptionsClient(opts: SubscriptionsClientOptions): SubscriptionsClient {\n return new SubscriptionsClient(opts);\n}\n\nfunction toAbsoluteUrl(baseUrl: string, path: string): string {\n if (/^https?:\\/\\//i.test(path)) return path;\n return `${baseUrl}${path.startsWith('/') ? path : `/${path}`}`;\n}\n\nfunction setQuery(query: URLSearchParams, key: string, value: unknown): void {\n if (value === undefined || value === null || value === '') return;\n query.set(key, String(value));\n}\n","import { createContext, useCallback, useContext, useMemo, useReducer, type ReactNode } from 'react';\nimport { SubscriptionsClient } from './client';\nimport type {\n SubscriptionFetcher,\n SubscriptionProviderProps,\n SubscriptionsClientContract,\n} from './types';\n\ninterface SubscriptionContextValue {\n client: SubscriptionsClientContract;\n cacheVersion: number;\n invalidate: () => void;\n}\n\nconst SubscriptionContext = createContext<SubscriptionContextValue | null>(null);\n\nexport function SubscriptionProvider({\n children,\n client,\n fetcher,\n baseUrl,\n timeoutMs,\n}: SubscriptionProviderProps) {\n const [cacheVersion, invalidate] = useReducer((value: number) => value + 1, 0);\n const resolvedClient = useMemo(() => {\n if (client) return client;\n return new SubscriptionsClient({\n fetcher: fetcher ?? createSubscriptionFetcher('/api/throttle'),\n baseUrl,\n timeoutMs,\n });\n }, [baseUrl, client, fetcher, timeoutMs]);\n\n const value = useMemo(\n () => ({ client: resolvedClient, cacheVersion, invalidate }),\n [cacheVersion, resolvedClient],\n );\n\n return <SubscriptionContext.Provider value={value}>{children}</SubscriptionContext.Provider>;\n}\n\nexport function useSubscriptionClient(): SubscriptionsClientContract {\n return useSubscriptionContext().client;\n}\n\nexport function useSubscriptionInvalidation(): () => void {\n return useSubscriptionContext().invalidate;\n}\n\nexport function useSubscriptionCacheVersion(): number {\n return useSubscriptionContext().cacheVersion;\n}\n\nexport function createSubscriptionFetcher(basePath: string): SubscriptionFetcher {\n const cleanBase = basePath.replace(/\\/+$/, '');\n return (path, init) => {\n const cleanPath = path.startsWith('/') ? path : `/${path}`;\n return fetch(`${cleanBase}${cleanPath}`, init);\n };\n}\n\nexport function useSubscriptionContext(): SubscriptionContextValue {\n const ctx = useContext(SubscriptionContext);\n if (!ctx) {\n throw new Error(\n '@usethrottle/subscriptions hooks must be used inside <SubscriptionProvider />',\n );\n }\n return ctx;\n}\n\nexport function SubscriptionProviderWithClient({\n children,\n client,\n}: {\n children: ReactNode;\n client: SubscriptionsClientContract;\n}) {\n const [cacheVersion, invalidate] = useReducer((value: number) => value + 1, 0);\n const value = useMemo(() => ({ client, cacheVersion, invalidate }), [cacheVersion, client]);\n return <SubscriptionContext.Provider value={value}>{children}</SubscriptionContext.Provider>;\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport {\n useSubscriptionCacheVersion,\n useSubscriptionClient,\n useSubscriptionInvalidation,\n} from './provider';\nimport type {\n CancelSubscriptionInput,\n ChangePlanInput,\n CheckoutSession,\n CreateCheckoutSessionInput,\n CreateSubscriptionInput,\n Customer,\n CustomerPaymentMethod,\n ListSubscriptionsParams,\n MutationState,\n PaginatedSubscriptions,\n QueryOptions,\n QueryState,\n Subscription,\n TrialEligibilityInput,\n TrialEligibilityResult,\n UpdateSubscriptionInput,\n} from './types';\n\nexport function useSubscriptions(\n params: ListSubscriptionsParams = {},\n options: QueryOptions<PaginatedSubscriptions> = {},\n): QueryState<PaginatedSubscriptions> {\n const client = useSubscriptionClient();\n const cacheVersion = useSubscriptionCacheVersion();\n const stableParams = useStableValue(params);\n return useAsyncQuery(\n () => client.list(stableParams),\n [client, stableParams, cacheVersion],\n options,\n );\n}\n\nexport function useSubscription(\n id: string | null | undefined,\n options: QueryOptions<Subscription> = {},\n): QueryState<Subscription> {\n const client = useSubscriptionClient();\n const cacheVersion = useSubscriptionCacheVersion();\n return useAsyncQuery(\n () => (id ? client.get(id) : Promise.resolve(null)),\n [client, id, cacheVersion],\n { ...options, enabled: options.enabled ?? Boolean(id) },\n );\n}\n\nexport function useCustomerByExternalId(\n externalId: string | null | undefined,\n options: QueryOptions<Customer> = {},\n): QueryState<Customer> {\n const client = useSubscriptionClient();\n const cacheVersion = useSubscriptionCacheVersion();\n return useAsyncQuery(\n () => (externalId ? client.getCustomerByExternalId(externalId) : Promise.resolve(null)),\n [client, externalId, cacheVersion],\n { ...options, enabled: options.enabled ?? Boolean(externalId) },\n );\n}\n\nexport function useCustomerPaymentMethods(\n customerId: string | null | undefined,\n options: QueryOptions<CustomerPaymentMethod[]> = {},\n): QueryState<CustomerPaymentMethod[]> {\n const client = useSubscriptionClient();\n const cacheVersion = useSubscriptionCacheVersion();\n return useAsyncQuery(\n () => (customerId ? client.listCustomerPaymentMethods(customerId) : Promise.resolve(null)),\n [client, customerId, cacheVersion],\n { ...options, enabled: options.enabled ?? Boolean(customerId) },\n );\n}\n\nexport function useTrialEligibility(): MutationState<\n TrialEligibilityResult,\n TrialEligibilityInput\n> {\n const client = useSubscriptionClient();\n return useAsyncMutation((input) => client.checkTrialEligibility(input));\n}\n\nexport function useCreateSubscription(): MutationState<Subscription, CreateSubscriptionInput> {\n const client = useSubscriptionClient();\n const invalidate = useSubscriptionInvalidation();\n return useAsyncMutation((input) => client.create(input), invalidate);\n}\n\nexport function useUpdateSubscription(): MutationState<\n Subscription,\n { id: string; data: UpdateSubscriptionInput }\n> {\n const client = useSubscriptionClient();\n const invalidate = useSubscriptionInvalidation();\n return useAsyncMutation(({ id, data }) => client.update(id, data), invalidate);\n}\n\nexport function useChangePlan(): MutationState<Subscription, ChangePlanInput> {\n const client = useSubscriptionClient();\n const invalidate = useSubscriptionInvalidation();\n return useAsyncMutation((input) => client.changePlan(input), invalidate);\n}\n\nexport function useCancelSubscription(): MutationState<Subscription, CancelSubscriptionInput> {\n const client = useSubscriptionClient();\n const invalidate = useSubscriptionInvalidation();\n return useAsyncMutation(\n (input) => client.cancel(input.id, { atPeriodEnd: input.atPeriodEnd }),\n invalidate,\n );\n}\n\nexport function usePauseSubscription(): MutationState<Subscription, { id: string }> {\n const client = useSubscriptionClient();\n const invalidate = useSubscriptionInvalidation();\n return useAsyncMutation((input) => client.pause(input.id), invalidate);\n}\n\nexport function useResumeSubscription(): MutationState<Subscription, { id: string }> {\n const client = useSubscriptionClient();\n const invalidate = useSubscriptionInvalidation();\n return useAsyncMutation((input) => client.resume(input.id), invalidate);\n}\n\nexport function useCreateCheckoutSession(): MutationState<\n CheckoutSession,\n CreateCheckoutSessionInput\n> {\n const client = useSubscriptionClient();\n return useAsyncMutation((input) => client.createCheckoutSession(input));\n}\n\nfunction useAsyncQuery<T>(\n load: () => Promise<T | null>,\n deps: readonly unknown[],\n options: QueryOptions<T>,\n): QueryState<T> {\n const enabled = options.enabled ?? true;\n const [data, setData] = useState<T | null>(options.initialData ?? null);\n const [error, setError] = useState<unknown>(null);\n const [isLoading, setIsLoading] = useState(enabled && options.initialData === undefined);\n const [isFetching, setIsFetching] = useState(false);\n const loadRef = useRef(load);\n loadRef.current = load;\n\n const refetch = useCallback(async () => {\n if (!enabled) return data;\n setIsFetching(true);\n setError(null);\n try {\n const next = await loadRef.current();\n setData(next);\n return next;\n } catch (err) {\n setError(err);\n throw err;\n } finally {\n setIsFetching(false);\n setIsLoading(false);\n }\n }, [data, enabled]);\n\n useEffect(() => {\n if (!enabled) {\n setIsLoading(false);\n return;\n }\n let cancelled = false;\n setIsFetching(true);\n setError(null);\n load()\n .then((next) => {\n if (!cancelled) setData(next);\n })\n .catch((err) => {\n if (!cancelled) setError(err);\n })\n .finally(() => {\n if (!cancelled) {\n setIsLoading(false);\n setIsFetching(false);\n }\n });\n\n return () => {\n cancelled = true;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [enabled, ...deps]);\n\n return { data, error, isLoading, isFetching, refetch };\n}\n\nfunction useAsyncMutation<TData, TVariables>(\n action: (variables: TVariables) => Promise<TData>,\n onSuccess?: () => void,\n): MutationState<TData, TVariables> {\n const [data, setData] = useState<TData | null>(null);\n const [error, setError] = useState<unknown>(null);\n const [isPending, setIsPending] = useState(false);\n\n const mutateAsync = useCallback(\n async (variables: TVariables) => {\n setIsPending(true);\n setError(null);\n try {\n const next = await action(variables);\n setData(next);\n onSuccess?.();\n return next;\n } catch (err) {\n setError(err);\n throw err;\n } finally {\n setIsPending(false);\n }\n },\n [action, onSuccess],\n );\n\n const mutate = useCallback(\n (variables: TVariables) => {\n void mutateAsync(variables).catch(() => undefined);\n },\n [mutateAsync],\n );\n\n const reset = useCallback(() => {\n setData(null);\n setError(null);\n setIsPending(false);\n }, []);\n\n return { data, error, isPending, mutate, mutateAsync, reset };\n}\n\nfunction useStableValue<T>(value: T): T {\n const key = JSON.stringify(value);\n return useMemo(() => value, [key]);\n}\n","/**\n * A subscription's billing cadence: \"every N units\".\n *\n * Every subscription row stores a unit and a count; the five named intervals\n * are shorthand for particular combinations. This module is the only place\n * that knows the vocabulary, the bounds, and how a period boundary is\n * computed — the engine, the renewal cron, the API, the dashboard and the\n * buyer surfaces all import it. Before it existed there were three divergent\n * copies of the period math, and the renewal cron's advanced months with\n * `setMonth`, which overflows: a subscription started on Jan 31 renewed on\n * Mar 3 and never returned to the 31st.\n */\n\nexport const INTERVAL_UNITS = ['hour', 'day', 'week', 'month'] as const;\nexport type IntervalUnit = (typeof INTERVAL_UNITS)[number];\n\nexport const NAMED_INTERVALS = ['weekly', 'biweekly', 'monthly', 'quarterly', 'yearly'] as const;\nexport type NamedInterval = (typeof NAMED_INTERVALS)[number];\n\n/** What the `interval` field holds: a named interval, or `custom` for everything else. */\nexport const INTERVAL_VALUES = [...NAMED_INTERVALS, 'custom'] as const;\nexport type IntervalValue = (typeof INTERVAL_VALUES)[number];\n\nexport interface Cadence {\n interval: IntervalValue;\n unit: IntervalUnit;\n count: number;\n}\n\n/** Anything that describes a cadence the way the API and the database do. */\nexport interface CadenceLike {\n interval: string;\n intervalUnit?: string | null;\n intervalCount?: number | null;\n}\n\nexport interface CadenceInput {\n interval?: string | null;\n intervalUnit?: string | null;\n intervalCount?: number | null;\n}\n\nexport const NAMED_SHORTHAND: Readonly<Record<NamedInterval, { unit: IntervalUnit; count: number }>> = {\n weekly: { unit: 'week', count: 1 },\n biweekly: { unit: 'week', count: 2 },\n monthly: { unit: 'month', count: 1 },\n quarterly: { unit: 'month', count: 3 },\n // month × 12 rather than a year unit, so a Feb 29 anniversary clamps to Feb\n // 28 and comes back to Feb 29 in leap years like every other month cadence.\n yearly: { unit: 'month', count: 12 },\n};\n\n/** At most one year in every unit. The shortest cadence is 1 hour. */\nexport const MAX_INTERVAL_COUNT: Readonly<Record<IntervalUnit, number>> = {\n hour: 8760,\n day: 365,\n week: 52,\n month: 12,\n};\n\nexport const HOUR_MS = 3_600_000;\nexport const DAY_MS = 24 * HOUR_MS;\nexport const WEEK_MS = 7 * DAY_MS;\n\nconst FIXED_UNIT_MS = { hour: HOUR_MS, day: DAY_MS, week: WEEK_MS } as const;\n\nexport class CadenceError extends Error {\n readonly statusCode = 400;\n constructor(\n readonly code: 'invalid_interval' | 'interval_conflict',\n message: string,\n ) {\n super(message);\n this.name = 'CadenceError';\n }\n}\n\nexport function isNamedInterval(value: unknown): value is NamedInterval {\n return typeof value === 'string' && (NAMED_INTERVALS as readonly string[]).includes(value);\n}\n\nexport function isIntervalUnit(value: unknown): value is IntervalUnit {\n return typeof value === 'string' && (INTERVAL_UNITS as readonly string[]).includes(value);\n}\n\nfunction isIntervalValue(value: unknown): value is IntervalValue {\n return typeof value === 'string' && (INTERVAL_VALUES as readonly string[]).includes(value);\n}\n\nfunction reduceToLargestUnit(unit: IntervalUnit, count: number): { unit: IntervalUnit; count: number } {\n let u = unit;\n let c = count;\n if (u === 'hour' && c % 24 === 0) {\n u = 'day';\n c = c / 24;\n }\n if (u === 'day' && c % 7 === 0) {\n u = 'week';\n c = c / 7;\n }\n return { unit: u, count: c };\n}\n\nfunction namedFor(unit: IntervalUnit, count: number): NamedInterval | null {\n for (const name of NAMED_INTERVALS) {\n const s = NAMED_SHORTHAND[name];\n if (s.unit === unit && s.count === count) return name;\n }\n return null;\n}\n\n/**\n * Turn whatever a caller sent into the one stored form. Accepts a named\n * interval alone, a unit and count alone, or both — in which case they must\n * agree. The result is reduced to its largest exact unit and mapped to a named\n * interval whenever one matches, so there is exactly one representation per\n * cadence and \"every 2 weeks\" can never be filed apart from \"biweekly\".\n */\nexport function canonicalizeCadence(input: CadenceInput): Cadence {\n const interval = input.interval ?? undefined;\n if (interval !== undefined && !isIntervalValue(interval)) {\n throw new CadenceError('invalid_interval', `Unknown interval \"${interval}\"`);\n }\n const hasUnit = input.intervalUnit != null;\n const hasCount = input.intervalCount != null;\n if (hasUnit !== hasCount) {\n throw new CadenceError('invalid_interval', 'intervalUnit and intervalCount must be sent together');\n }\n if (!hasUnit) {\n if (isNamedInterval(interval)) return { interval, ...NAMED_SHORTHAND[interval] };\n throw new CadenceError(\n 'invalid_interval',\n interval === 'custom'\n ? 'A custom interval needs intervalUnit and intervalCount'\n : 'Send an interval, or intervalUnit and intervalCount',\n );\n }\n\n const unit = input.intervalUnit;\n const count = input.intervalCount as number;\n if (!isIntervalUnit(unit)) {\n throw new CadenceError('invalid_interval', 'intervalUnit must be one of hour, day, week, month');\n }\n if (!Number.isInteger(count) || count < 1) {\n throw new CadenceError('invalid_interval', 'intervalCount must be a whole number of at least 1');\n }\n if (count > MAX_INTERVAL_COUNT[unit]) {\n throw new CadenceError(\n 'invalid_interval',\n `A cadence can be at most one year: ${MAX_INTERVAL_COUNT[unit]} ${unit}s`,\n );\n }\n\n const reduced = reduceToLargestUnit(unit, count);\n const cadence: Cadence = { interval: namedFor(reduced.unit, reduced.count) ?? 'custom', ...reduced };\n if (interval !== undefined && interval !== 'custom' && interval !== cadence.interval) {\n throw new CadenceError(\n 'interval_conflict',\n `interval \"${interval}\" does not match every ${count} ${unit}${count === 1 ? '' : 's'}`,\n );\n }\n return cadence;\n}\n\n/**\n * Read the cadence off a stored subscription. A named interval always means\n * its shorthand, whatever the unit/count columns hold: a canonical row's\n * columns match the shorthand anyway, and code that predates the columns\n * (still serving between migration 0224 and the deploy) changes `interval`\n * without touching them, so for a named row they can be stale. Only a\n * `custom` row is read from its unit and count. The same rule applies to the\n * pending cadence — pass `{ interval: pendingInterval, intervalUnit:\n * pendingIntervalUnit, intervalCount: pendingIntervalCount }`.\n */\nexport function cadenceOf(row: CadenceLike): Cadence {\n if (isNamedInterval(row.interval)) return { interval: row.interval, ...NAMED_SHORTHAND[row.interval] };\n if (row.interval === 'custom' && row.intervalUnit != null && row.intervalCount != null && isIntervalUnit(row.intervalUnit)) {\n return { interval: 'custom', unit: row.intervalUnit, count: row.intervalCount };\n }\n throw new Error(`Unknown subscription interval: ${row.interval}`);\n}\n\n/** The exact period length for hour/day/week cadences; null for months, which vary. */\nexport function fixedPeriodMs(cadence: Cadence): number | null {\n return cadence.unit === 'month' ? null : cadence.count * FIXED_UNIT_MS[cadence.unit];\n}\n\n/** The shortest a period can be. A month counts as 28 days. */\nexport function minimumPeriodMs(cadence: Cadence): number {\n return fixedPeriodMs(cadence) ?? cadence.count * 28 * DAY_MS;\n}\n\n/** anchor + months, keeping the anchor's day-of-month (clamped to month end) and UTC time of day. */\nexport function addMonthsAnchored(anchor: Date, months: number): Date {\n const monthIndex = anchor.getUTCMonth() + months;\n const year = anchor.getUTCFullYear() + Math.floor(monthIndex / 12);\n const month = ((monthIndex % 12) + 12) % 12;\n const lastDay = new Date(Date.UTC(year, month + 1, 0)).getUTCDate();\n return new Date(\n Date.UTC(\n year,\n month,\n Math.min(anchor.getUTCDate(), lastDay),\n anchor.getUTCHours(),\n anchor.getUTCMinutes(),\n anchor.getUTCSeconds(),\n anchor.getUTCMilliseconds(),\n ),\n );\n}\n\n/**\n * The first period boundary strictly after `after`, on the grid measured from\n * `anchor`. Never chained from a previous boundary — that is what made the\n * month-end clamp stick on the 28th. An `after` that is off the grid (a late\n * tick, a recovery) resolves to the next grid date.\n */\nexport function nextPeriodEnd(args: { anchor: Date; cadence: Cadence; after: Date }): Date {\n const { anchor, cadence, after } = args;\n const step = fixedPeriodMs(cadence);\n if (step !== null) {\n const k = Math.max(1, Math.floor((after.getTime() - anchor.getTime()) / step) + 1);\n return new Date(anchor.getTime() + k * step);\n }\n const monthsElapsed =\n (after.getUTCFullYear() - anchor.getUTCFullYear()) * 12 + (after.getUTCMonth() - anchor.getUTCMonth());\n let k = Math.max(1, Math.floor(monthsElapsed / cadence.count));\n let boundary = addMonthsAnchored(anchor, k * cadence.count);\n while (boundary.getTime() <= after.getTime()) {\n k += 1;\n boundary = addMonthsAnchored(anchor, k * cadence.count);\n }\n return boundary;\n}\n\n/**\n * The grid period that contains `at`: the latest boundary at or before it (never\n * before the anchor) and the one after. A subscription that fell more than a\n * period behind is billed once, for this period, and the periods it missed are\n * skipped rather than charged back to back (D38).\n */\nexport function periodContaining(args: { anchor: Date; cadence: Cadence; at: Date }): { start: Date; end: Date } {\n const { anchor, cadence, at } = args;\n const step = fixedPeriodMs(cadence);\n if (step !== null) {\n const k = Math.max(0, Math.floor((at.getTime() - anchor.getTime()) / step));\n const start = new Date(anchor.getTime() + k * step);\n return { start, end: new Date(start.getTime() + step) };\n }\n const monthsElapsed =\n (at.getUTCFullYear() - anchor.getUTCFullYear()) * 12 + (at.getUTCMonth() - anchor.getUTCMonth());\n let k = Math.max(0, Math.floor(monthsElapsed / cadence.count));\n let start = addMonthsAnchored(anchor, k * cadence.count);\n while (k > 0 && start.getTime() > at.getTime()) {\n k -= 1;\n start = addMonthsAnchored(anchor, k * cadence.count);\n }\n return { start, end: addMonthsAnchored(anchor, (k + 1) * cadence.count) };\n}\n\nconst RETRY_CAP_DAYS = [1, 3, 7] as const;\n\n/**\n * How long to wait before retry number `failureNumber` (1..3). Short cadences\n * retry proportionally faster; anything of a week or longer lands on the\n * original 1 / 3 / 7 days exactly.\n */\nexport function dunningRetryDelayMs(cadence: Cadence, failureNumber: number): number {\n const n = Math.min(Math.max(Math.trunc(failureNumber), 1), RETRY_CAP_DAYS.length);\n return Math.min(n * minimumPeriodMs(cadence), RETRY_CAP_DAYS[n - 1] * DAY_MS);\n}\n\n/** The 3-days-ahead renewal reminder only makes sense for cadences of a week or longer. */\nexport function sendsRenewalReminder(cadence: Cadence): boolean {\n return minimumPeriodMs(cadence) >= WEEK_MS;\n}\n\n/**\n * Multiply a period's charge by this to get its monthly equivalent. Chosen so\n * `weekly` is exactly 52/12 and `biweekly` exactly 26/12, the factors\n * analytics already report — no existing MRR number moves.\n */\nexport function monthlyEquivalentFactor(cadence: Cadence): number {\n if (cadence.unit === 'month') return 1 / cadence.count;\n return (52 / 12) * (WEEK_MS / (fixedPeriodMs(cadence) as number));\n}\n","/**\n * Installment plans: a subscription with a fixed number of payments that ends\n * itself — status `completed` — the moment the last one succeeds.\n */\n\nexport const MIN_TOTAL_PAYMENTS = 2;\nexport const MAX_TOTAL_PAYMENTS = 60;\n\nexport type InstallmentErrorCode =\n | 'invalid_total_payments'\n | 'invalid_combination'\n | 'total_payments_immutable'\n | 'installment_plan_locked'\n | 'installment_plan_merchant_only';\n\nexport class InstallmentError extends Error {\n constructor(\n readonly code: InstallmentErrorCode,\n message: string,\n readonly statusCode: number,\n ) {\n super(message);\n this.name = 'InstallmentError';\n }\n}\n\nexport function validateTotalPayments(value: unknown): number | null {\n if (value === undefined || value === null) return null;\n if (\n typeof value !== 'number' ||\n !Number.isInteger(value) ||\n value < MIN_TOTAL_PAYMENTS ||\n value > MAX_TOTAL_PAYMENTS\n ) {\n throw new InstallmentError(\n 'invalid_total_payments',\n `totalPayments must be a whole number from ${MIN_TOTAL_PAYMENTS} to ${MAX_TOTAL_PAYMENTS}`,\n 400,\n );\n }\n return value;\n}\n\nexport function isInstallmentPlan(sub: { totalPayments?: number | null }): boolean {\n return sub.totalPayments != null;\n}\n\n/** After one counted payment — a charge or a waive — the new count and whether the plan is paid in full. */\nexport function countInstallmentPayment(sub: {\n totalPayments?: number | null;\n paymentsMade?: number | null;\n}): { paymentsMade: number; completes: boolean } | null {\n if (sub.totalPayments == null) return null;\n const paymentsMade = (sub.paymentsMade ?? 0) + 1;\n return { paymentsMade, completes: paymentsMade >= sub.totalPayments };\n}\n\nexport interface InstallmentProgress {\n paymentsMade: number;\n totalPayments: number;\n remainingPayments: number;\n remainingCents: number;\n}\n\nexport function installmentProgress(sub: {\n totalPayments?: number | null;\n paymentsMade?: number | null;\n amount: number;\n quantity?: number | null;\n}): InstallmentProgress | null {\n if (sub.totalPayments == null) return null;\n const paymentsMade = Math.min(sub.paymentsMade ?? 0, sub.totalPayments);\n const remainingPayments = sub.totalPayments - paymentsMade;\n return {\n paymentsMade,\n totalPayments: sub.totalPayments,\n remainingPayments,\n remainingCents: remainingPayments * sub.amount * (sub.quantity ?? 1),\n };\n}\n\nexport function installmentLocked(): InstallmentError {\n return new InstallmentError(\n 'installment_plan_locked',\n \"An installment plan's amount, cadence, quantity and plan are fixed when it is created. Cancel it and create a new one to change the terms.\",\n 409,\n );\n}\n\nexport function merchantOnly(): InstallmentError {\n return new InstallmentError(\n 'installment_plan_merchant_only',\n 'Installment plans can only be paused, resumed or cancelled by the merchant',\n 403,\n );\n}\n\nexport function totalPaymentsImmutable(): InstallmentError {\n return new InstallmentError(\n 'total_payments_immutable',\n 'totalPayments is set when a subscription is created and cannot be changed',\n 400,\n );\n}\n","import { isIntervalUnit, isNamedInterval, type CadenceLike, type NamedInterval } from './cadence';\n\nconst NAMED_NOUN: Record<NamedInterval, string> = {\n weekly: 'week',\n biweekly: '2 weeks',\n monthly: 'month',\n quarterly: 'quarter',\n yearly: 'year',\n};\n\nconst NAMED_LABEL: Record<NamedInterval, string> = {\n weekly: 'Weekly',\n biweekly: 'Biweekly',\n monthly: 'Monthly',\n quarterly: 'Quarterly',\n yearly: 'Yearly',\n};\n\n/**\n * The period as a noun — what reads correctly after a slash: \"$49.00 / 10\n * days\". This replaces the per-file `INTERVAL_WORD` maps whose drift shipped\n * \"$49.00 / biweekly\" once already. Unknown input falls through unchanged so a\n * value this build doesn't know still renders instead of vanishing.\n */\nexport function cadenceNoun(cadence: CadenceLike): string {\n if (isNamedInterval(cadence.interval)) return NAMED_NOUN[cadence.interval];\n if (isIntervalUnit(cadence.intervalUnit) && cadence.intervalCount != null) {\n return cadence.intervalCount === 1 ? cadence.intervalUnit : `${cadence.intervalCount} ${cadence.intervalUnit}s`;\n }\n return cadence.interval;\n}\n\n/** The cadence as a standalone label, e.g. an Interval column: \"Monthly\", \"Every 10 days\". */\nexport function cadenceLabel(cadence: CadenceLike): string {\n if (isNamedInterval(cadence.interval)) return NAMED_LABEL[cadence.interval];\n if (isIntervalUnit(cadence.intervalUnit) && cadence.intervalCount != null) return `Every ${cadenceNoun(cadence)}`;\n return cadence.interval;\n}\n\n/** Sub-daily cadences show the time of the next charge, not just its date. */\nexport function isSubDaily(cadence: CadenceLike): boolean {\n return cadence.intervalUnit === 'hour';\n}\n","import {\n cadenceNoun as coreCadenceNoun,\n cadenceLabel as coreCadenceLabel,\n installmentProgress as coreInstallmentProgress,\n} from '@core/cadence';\nimport type { Subscription, SubscriptionStatus } from './types';\n\n/** `cancelled` and `completed` (an installment plan paid in full) never bill again. */\nexport function isTerminalSubscription(status: SubscriptionStatus | Subscription): boolean {\n const s = getStatus(status);\n return s === 'cancelled' || s === 'completed';\n}\n\nexport function canPauseSubscription(status: SubscriptionStatus | Subscription): boolean {\n return getStatus(status) === 'active';\n}\n\nexport function canResumeSubscription(status: SubscriptionStatus | Subscription): boolean {\n return getStatus(status) === 'paused';\n}\n\nexport function canCancelSubscription(status: SubscriptionStatus | Subscription): boolean {\n return !isTerminalSubscription(status);\n}\n\nexport function isSubscriptionPastDue(status: SubscriptionStatus | Subscription): boolean {\n return getStatus(status) === 'past_due';\n}\n\nexport function isSubscriptionTrialing(status: SubscriptionStatus | Subscription): boolean {\n return getStatus(status) === 'trialing';\n}\n\nexport function daysUntil(date: string | Date, now = new Date()): number {\n const end = date instanceof Date ? date : new Date(date);\n const ms = end.getTime() - now.getTime();\n if (!Number.isFinite(ms)) return 0;\n return Math.max(0, Math.ceil(ms / 86_400_000));\n}\n\nfunction getStatus(input: SubscriptionStatus | Subscription): SubscriptionStatus {\n return typeof input === 'string' ? input : input.status;\n}\n\n/**\n * Anything that describes a cadence the way the API and the database do.\n * Structurally mirrors the private cadence engine's own shape — kept local\n * so the published `.d.ts` never names that unpublished package.\n */\nexport interface CadenceLike {\n interval: string;\n intervalUnit?: string | null;\n intervalCount?: number | null;\n}\n\nexport interface InstallmentProgress {\n paymentsMade: number;\n totalPayments: number;\n remainingPayments: number;\n remainingCents: number;\n}\n\n/** \"10 days\", \"2 weeks\", \"month\" — the period after a slash: `$49.00 / ${cadenceNoun(sub)}`. */\nexport function cadenceNoun(cadence: CadenceLike): string {\n return coreCadenceNoun(cadence);\n}\n\n/** The cadence as a standalone label, e.g. an Interval column: \"Monthly\", \"Every 10 days\". */\nexport function cadenceLabel(cadence: CadenceLike): string {\n return coreCadenceLabel(cadence);\n}\n\nexport function installmentProgress(sub: {\n totalPayments?: number | null;\n paymentsMade?: number | null;\n amount: number;\n quantity?: number | null;\n}): InstallmentProgress | null {\n return coreInstallmentProgress(sub);\n}\n","import type { CSSProperties } from 'react';\nimport { daysUntil } from './helpers';\nimport type {\n DunningBannerProps,\n SubscriptionStatus,\n SubscriptionStatusBadgeProps,\n TrialCountdownProps,\n} from './types';\n\nconst STATUS_LABELS: Record<SubscriptionStatus, string> = {\n active: 'Active',\n paused: 'Paused',\n cancelled: 'Cancelled',\n past_due: 'Past due',\n trialing: 'Trialing',\n unpaid: 'Unpaid',\n completed: 'Paid in full',\n};\n\nconst STATUS_STYLES: Record<SubscriptionStatus, CSSProperties> = {\n active: { color: '#035c4f', background: '#dff8ef', borderColor: '#a8e8d2' },\n paused: { color: '#735c00', background: '#fff4ca', borderColor: '#f3d46b' },\n cancelled: { color: '#6c2632', background: '#ffe1e7', borderColor: '#f4a9b8' },\n past_due: { color: '#7a2d00', background: '#ffe8d6', borderColor: '#f5b47f' },\n trialing: { color: '#124c73', background: '#dff1ff', borderColor: '#9ed3fb' },\n unpaid: { color: '#7a2d00', background: '#ffe8d6', borderColor: '#f5b47f' },\n completed: { color: '#035c4f', background: '#dff8ef', borderColor: '#a8e8d2' },\n};\n\nexport function SubscriptionStatusBadge({\n status,\n className,\n style,\n labels,\n}: SubscriptionStatusBadgeProps) {\n return (\n <span\n className={className}\n style={{\n display: 'inline-flex',\n alignItems: 'center',\n border: '1px solid',\n borderRadius: 999,\n padding: '2px 8px',\n fontSize: 12,\n fontWeight: 700,\n lineHeight: 1.6,\n whiteSpace: 'nowrap',\n ...STATUS_STYLES[status],\n ...style,\n }}\n >\n {labels?.[status] ?? STATUS_LABELS[status]}\n </span>\n );\n}\n\nexport function TrialCountdown({\n endDate,\n now,\n className,\n style,\n expiredLabel = 'Trial ended',\n prefix = 'Trial ends in',\n}: TrialCountdownProps) {\n const days = daysUntil(endDate, now);\n const label = days <= 0 ? expiredLabel : `${prefix} ${days} ${days === 1 ? 'day' : 'days'}`;\n\n return (\n <span className={className} style={style}>\n {label}\n </span>\n );\n}\n\nexport function DunningBanner({\n subscription,\n onUpdateCard,\n title = 'Payment needs attention',\n message,\n actionLabel = 'Update card',\n className,\n style,\n}: DunningBannerProps) {\n if (subscription.status !== 'past_due') return null;\n const fallbackMessage =\n subscription.failureCount > 0\n ? `We could not renew this subscription after ${subscription.failureCount} failed payment attempt${\n subscription.failureCount === 1 ? '' : 's'\n }.`\n : 'We could not renew this subscription with the saved payment method.';\n\n return (\n <div\n role=\"status\"\n className={className}\n style={{\n border: '1px solid #f5b47f',\n borderRadius: 8,\n background: '#fff7ed',\n color: '#7a2d00',\n padding: 16,\n display: 'grid',\n gap: 10,\n ...style,\n }}\n >\n <strong>{title}</strong>\n <span>{message ?? fallbackMessage}</span>\n {onUpdateCard ? (\n <button\n type=\"button\"\n onClick={onUpdateCard}\n style={{\n width: 'fit-content',\n border: '1px solid #7a2d00',\n borderRadius: 6,\n background: '#7a2d00',\n color: '#fff',\n padding: '8px 12px',\n fontWeight: 700,\n cursor: 'pointer',\n }}\n >\n {actionLabel}\n </button>\n ) : null}\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAAA;AAAA,EAAA,mBAAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,6BAAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oBAAsD;AAsBtD,IAAAC,iBAA+C;AAbxC,IAAM,6BAAN,cAAyC,4BAAc;AAAA,EAC5D,YAAY,MAMT;AACD,UAAM,IAAI;AACV,SAAK,OAAO;AAAA,EACd;AACF;;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AAK,GACzC,MACA;AAEN,SACE;AAAA,IAAC;AAAA;AAAA,MACC,MAAK;AAAA,MACL;AAAA,MACA,OAAO;AAAA,QACL,QAAQ;AAAA,QACR,cAAc;AAAA,QACd,YAAY;AAAA,QACZ,OAAO;AAAA,QACP,SAAS;AAAA,QACT,SAAS;AAAA,QACT,KAAK;AAAA,QACL,GAAG;AAAA,MACL;AAAA,MAEA;AAAA,qDAAC,YAAQ,iBAAM;AAAA,QACf,6CAAC,UAAM,qBAAW,iBAAgB;AAAA,QACjC,eACC;AAAA,UAAC;AAAA;AAAA,YACC,MAAK;AAAA,YACL,SAAS;AAAA,YACT,OAAO;AAAA,cACL,OAAO;AAAA,cACP,QAAQ;AAAA,cACR,cAAc;AAAA,cACd,YAAY;AAAA,cACZ,OAAO;AAAA,cACP,SAAS;AAAA,cACT,YAAY;AAAA,cACZ,QAAQ;AAAA,YACV;AAAA,YAEC;AAAA;AAAA,QACH,IACE;AAAA;AAAA;AAAA,EACN;AAEJ;","names":["cadenceLabel","cadenceNoun","installmentProgress","import_errors","value","import_react","cadenceNoun","cadenceLabel","installmentProgress","import_jsx_runtime"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { b as CheckoutCollectInput, c as CheckoutCustomerInput, i as Pagination, R as RecurringIntent, l as SubscriptionInterval, m as SubscriptionInvoiceRefund,
|
|
1
|
+
import { o as SubscriptionProviderProps, u as SubscriptionsClientContract, k as SubscriptionFetcher, M as MutationState, S as Subscription, C as CancelSubscriptionInput, a as ChangePlanInput, d as CheckoutSession, e as CreateCheckoutSessionInput, f as CreateSubscriptionInput, Q as QueryOptions, g as Customer, j as QueryState, h as CustomerPaymentMethod, L as ListSubscriptionsParams, P as PaginatedSubscriptions, A as TrialEligibilityResult, y as TrialEligibilityInput, U as UpdateSubscriptionInput, D as DunningBannerProps, r as SubscriptionStatusBadgeProps, x as TrialCountdownProps, q as SubscriptionStatus } from './errors-1V2z7X4H.cjs';
|
|
2
|
+
export { b as CheckoutCollectInput, c as CheckoutCustomerInput, i as Pagination, R as RecurringIntent, l as SubscriptionInterval, m as SubscriptionIntervalUnit, n as SubscriptionInvoiceRefund, p as SubscriptionSort, s as SubscriptionTaxAddress, t as SubscriptionsClient, v as SubscriptionsClientOptions, T as ThrottleEnvelope, w as ThrottleSubscriptionsError, z as TrialEligibilityReason, B as createSubscriptionsClient } from './errors-1V2z7X4H.cjs';
|
|
3
3
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
4
4
|
import { ReactNode } from 'react';
|
|
5
5
|
export { ThrottleError, isThrottleError } from '@usethrottle/errors';
|
|
@@ -37,6 +37,7 @@ declare function SubscriptionStatusBadge({ status, className, style, labels, }:
|
|
|
37
37
|
declare function TrialCountdown({ endDate, now, className, style, expiredLabel, prefix, }: TrialCountdownProps): react_jsx_runtime.JSX.Element;
|
|
38
38
|
declare function DunningBanner({ subscription, onUpdateCard, title, message, actionLabel, className, style, }: DunningBannerProps): react_jsx_runtime.JSX.Element | null;
|
|
39
39
|
|
|
40
|
+
/** `cancelled` and `completed` (an installment plan paid in full) never bill again. */
|
|
40
41
|
declare function isTerminalSubscription(status: SubscriptionStatus | Subscription): boolean;
|
|
41
42
|
declare function canPauseSubscription(status: SubscriptionStatus | Subscription): boolean;
|
|
42
43
|
declare function canResumeSubscription(status: SubscriptionStatus | Subscription): boolean;
|
|
@@ -44,5 +45,31 @@ declare function canCancelSubscription(status: SubscriptionStatus | Subscription
|
|
|
44
45
|
declare function isSubscriptionPastDue(status: SubscriptionStatus | Subscription): boolean;
|
|
45
46
|
declare function isSubscriptionTrialing(status: SubscriptionStatus | Subscription): boolean;
|
|
46
47
|
declare function daysUntil(date: string | Date, now?: Date): number;
|
|
48
|
+
/**
|
|
49
|
+
* Anything that describes a cadence the way the API and the database do.
|
|
50
|
+
* Structurally mirrors the private cadence engine's own shape — kept local
|
|
51
|
+
* so the published `.d.ts` never names that unpublished package.
|
|
52
|
+
*/
|
|
53
|
+
interface CadenceLike {
|
|
54
|
+
interval: string;
|
|
55
|
+
intervalUnit?: string | null;
|
|
56
|
+
intervalCount?: number | null;
|
|
57
|
+
}
|
|
58
|
+
interface InstallmentProgress {
|
|
59
|
+
paymentsMade: number;
|
|
60
|
+
totalPayments: number;
|
|
61
|
+
remainingPayments: number;
|
|
62
|
+
remainingCents: number;
|
|
63
|
+
}
|
|
64
|
+
/** "10 days", "2 weeks", "month" — the period after a slash: `$49.00 / ${cadenceNoun(sub)}`. */
|
|
65
|
+
declare function cadenceNoun(cadence: CadenceLike): string;
|
|
66
|
+
/** The cadence as a standalone label, e.g. an Interval column: "Monthly", "Every 10 days". */
|
|
67
|
+
declare function cadenceLabel(cadence: CadenceLike): string;
|
|
68
|
+
declare function installmentProgress(sub: {
|
|
69
|
+
totalPayments?: number | null;
|
|
70
|
+
paymentsMade?: number | null;
|
|
71
|
+
amount: number;
|
|
72
|
+
quantity?: number | null;
|
|
73
|
+
}): InstallmentProgress | null;
|
|
47
74
|
|
|
48
|
-
export { CancelSubscriptionInput, ChangePlanInput, CheckoutSession, CreateCheckoutSessionInput, CreateSubscriptionInput, Customer, CustomerPaymentMethod, DunningBanner, DunningBannerProps, ListSubscriptionsParams, MutationState, PaginatedSubscriptions, QueryOptions, QueryState, Subscription, SubscriptionFetcher, SubscriptionProvider, SubscriptionProviderProps, SubscriptionProviderWithClient, SubscriptionStatus, SubscriptionStatusBadge, SubscriptionStatusBadgeProps, SubscriptionsClientContract, TrialCountdown, TrialCountdownProps, TrialEligibilityInput, TrialEligibilityResult, UpdateSubscriptionInput, canCancelSubscription, canPauseSubscription, canResumeSubscription, createSubscriptionFetcher, daysUntil, isSubscriptionPastDue, isSubscriptionTrialing, isTerminalSubscription, useCancelSubscription, useChangePlan, useCreateCheckoutSession, useCreateSubscription, useCustomerByExternalId, useCustomerPaymentMethods, usePauseSubscription, useResumeSubscription, useSubscription, useSubscriptionClient, useSubscriptionInvalidation, useSubscriptions, useTrialEligibility, useUpdateSubscription };
|
|
75
|
+
export { type CadenceLike, CancelSubscriptionInput, ChangePlanInput, CheckoutSession, CreateCheckoutSessionInput, CreateSubscriptionInput, Customer, CustomerPaymentMethod, DunningBanner, DunningBannerProps, type InstallmentProgress, ListSubscriptionsParams, MutationState, PaginatedSubscriptions, QueryOptions, QueryState, Subscription, SubscriptionFetcher, SubscriptionProvider, SubscriptionProviderProps, SubscriptionProviderWithClient, SubscriptionStatus, SubscriptionStatusBadge, SubscriptionStatusBadgeProps, SubscriptionsClientContract, TrialCountdown, TrialCountdownProps, TrialEligibilityInput, TrialEligibilityResult, UpdateSubscriptionInput, cadenceLabel, cadenceNoun, canCancelSubscription, canPauseSubscription, canResumeSubscription, createSubscriptionFetcher, daysUntil, installmentProgress, isSubscriptionPastDue, isSubscriptionTrialing, isTerminalSubscription, useCancelSubscription, useChangePlan, useCreateCheckoutSession, useCreateSubscription, useCustomerByExternalId, useCustomerPaymentMethods, usePauseSubscription, useResumeSubscription, useSubscription, useSubscriptionClient, useSubscriptionInvalidation, useSubscriptions, useTrialEligibility, useUpdateSubscription };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { b as CheckoutCollectInput, c as CheckoutCustomerInput, i as Pagination, R as RecurringIntent, l as SubscriptionInterval, m as SubscriptionInvoiceRefund,
|
|
1
|
+
import { o as SubscriptionProviderProps, u as SubscriptionsClientContract, k as SubscriptionFetcher, M as MutationState, S as Subscription, C as CancelSubscriptionInput, a as ChangePlanInput, d as CheckoutSession, e as CreateCheckoutSessionInput, f as CreateSubscriptionInput, Q as QueryOptions, g as Customer, j as QueryState, h as CustomerPaymentMethod, L as ListSubscriptionsParams, P as PaginatedSubscriptions, A as TrialEligibilityResult, y as TrialEligibilityInput, U as UpdateSubscriptionInput, D as DunningBannerProps, r as SubscriptionStatusBadgeProps, x as TrialCountdownProps, q as SubscriptionStatus } from './errors-1V2z7X4H.js';
|
|
2
|
+
export { b as CheckoutCollectInput, c as CheckoutCustomerInput, i as Pagination, R as RecurringIntent, l as SubscriptionInterval, m as SubscriptionIntervalUnit, n as SubscriptionInvoiceRefund, p as SubscriptionSort, s as SubscriptionTaxAddress, t as SubscriptionsClient, v as SubscriptionsClientOptions, T as ThrottleEnvelope, w as ThrottleSubscriptionsError, z as TrialEligibilityReason, B as createSubscriptionsClient } from './errors-1V2z7X4H.js';
|
|
3
3
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
4
4
|
import { ReactNode } from 'react';
|
|
5
5
|
export { ThrottleError, isThrottleError } from '@usethrottle/errors';
|
|
@@ -37,6 +37,7 @@ declare function SubscriptionStatusBadge({ status, className, style, labels, }:
|
|
|
37
37
|
declare function TrialCountdown({ endDate, now, className, style, expiredLabel, prefix, }: TrialCountdownProps): react_jsx_runtime.JSX.Element;
|
|
38
38
|
declare function DunningBanner({ subscription, onUpdateCard, title, message, actionLabel, className, style, }: DunningBannerProps): react_jsx_runtime.JSX.Element | null;
|
|
39
39
|
|
|
40
|
+
/** `cancelled` and `completed` (an installment plan paid in full) never bill again. */
|
|
40
41
|
declare function isTerminalSubscription(status: SubscriptionStatus | Subscription): boolean;
|
|
41
42
|
declare function canPauseSubscription(status: SubscriptionStatus | Subscription): boolean;
|
|
42
43
|
declare function canResumeSubscription(status: SubscriptionStatus | Subscription): boolean;
|
|
@@ -44,5 +45,31 @@ declare function canCancelSubscription(status: SubscriptionStatus | Subscription
|
|
|
44
45
|
declare function isSubscriptionPastDue(status: SubscriptionStatus | Subscription): boolean;
|
|
45
46
|
declare function isSubscriptionTrialing(status: SubscriptionStatus | Subscription): boolean;
|
|
46
47
|
declare function daysUntil(date: string | Date, now?: Date): number;
|
|
48
|
+
/**
|
|
49
|
+
* Anything that describes a cadence the way the API and the database do.
|
|
50
|
+
* Structurally mirrors the private cadence engine's own shape — kept local
|
|
51
|
+
* so the published `.d.ts` never names that unpublished package.
|
|
52
|
+
*/
|
|
53
|
+
interface CadenceLike {
|
|
54
|
+
interval: string;
|
|
55
|
+
intervalUnit?: string | null;
|
|
56
|
+
intervalCount?: number | null;
|
|
57
|
+
}
|
|
58
|
+
interface InstallmentProgress {
|
|
59
|
+
paymentsMade: number;
|
|
60
|
+
totalPayments: number;
|
|
61
|
+
remainingPayments: number;
|
|
62
|
+
remainingCents: number;
|
|
63
|
+
}
|
|
64
|
+
/** "10 days", "2 weeks", "month" — the period after a slash: `$49.00 / ${cadenceNoun(sub)}`. */
|
|
65
|
+
declare function cadenceNoun(cadence: CadenceLike): string;
|
|
66
|
+
/** The cadence as a standalone label, e.g. an Interval column: "Monthly", "Every 10 days". */
|
|
67
|
+
declare function cadenceLabel(cadence: CadenceLike): string;
|
|
68
|
+
declare function installmentProgress(sub: {
|
|
69
|
+
totalPayments?: number | null;
|
|
70
|
+
paymentsMade?: number | null;
|
|
71
|
+
amount: number;
|
|
72
|
+
quantity?: number | null;
|
|
73
|
+
}): InstallmentProgress | null;
|
|
47
74
|
|
|
48
|
-
export { CancelSubscriptionInput, ChangePlanInput, CheckoutSession, CreateCheckoutSessionInput, CreateSubscriptionInput, Customer, CustomerPaymentMethod, DunningBanner, DunningBannerProps, ListSubscriptionsParams, MutationState, PaginatedSubscriptions, QueryOptions, QueryState, Subscription, SubscriptionFetcher, SubscriptionProvider, SubscriptionProviderProps, SubscriptionProviderWithClient, SubscriptionStatus, SubscriptionStatusBadge, SubscriptionStatusBadgeProps, SubscriptionsClientContract, TrialCountdown, TrialCountdownProps, TrialEligibilityInput, TrialEligibilityResult, UpdateSubscriptionInput, canCancelSubscription, canPauseSubscription, canResumeSubscription, createSubscriptionFetcher, daysUntil, isSubscriptionPastDue, isSubscriptionTrialing, isTerminalSubscription, useCancelSubscription, useChangePlan, useCreateCheckoutSession, useCreateSubscription, useCustomerByExternalId, useCustomerPaymentMethods, usePauseSubscription, useResumeSubscription, useSubscription, useSubscriptionClient, useSubscriptionInvalidation, useSubscriptions, useTrialEligibility, useUpdateSubscription };
|
|
75
|
+
export { type CadenceLike, CancelSubscriptionInput, ChangePlanInput, CheckoutSession, CreateCheckoutSessionInput, CreateSubscriptionInput, Customer, CustomerPaymentMethod, DunningBanner, DunningBannerProps, type InstallmentProgress, ListSubscriptionsParams, MutationState, PaginatedSubscriptions, QueryOptions, QueryState, Subscription, SubscriptionFetcher, SubscriptionProvider, SubscriptionProviderProps, SubscriptionProviderWithClient, SubscriptionStatus, SubscriptionStatusBadge, SubscriptionStatusBadgeProps, SubscriptionsClientContract, TrialCountdown, TrialCountdownProps, TrialEligibilityInput, TrialEligibilityResult, UpdateSubscriptionInput, cadenceLabel, cadenceNoun, canCancelSubscription, canPauseSubscription, canResumeSubscription, createSubscriptionFetcher, daysUntil, installmentProgress, isSubscriptionPastDue, isSubscriptionTrialing, isTerminalSubscription, useCancelSubscription, useChangePlan, useCreateCheckoutSession, useCreateSubscription, useCustomerByExternalId, useCustomerPaymentMethods, usePauseSubscription, useResumeSubscription, useSubscription, useSubscriptionClient, useSubscriptionInvalidation, useSubscriptions, useTrialEligibility, useUpdateSubscription };
|
package/dist/index.js
CHANGED
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
ThrottleSubscriptionsError,
|
|
5
5
|
createSubscriptionsClient,
|
|
6
6
|
isThrottleError
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-C4MXEOJ3.js";
|
|
8
8
|
|
|
9
9
|
// src/provider.tsx
|
|
10
10
|
import { createContext, useContext, useMemo, useReducer } from "react";
|
|
@@ -234,9 +234,65 @@ function useStableValue(value) {
|
|
|
234
234
|
return useMemo2(() => value, [key]);
|
|
235
235
|
}
|
|
236
236
|
|
|
237
|
+
// ../core-cadence/src/cadence.ts
|
|
238
|
+
var INTERVAL_UNITS = ["hour", "day", "week", "month"];
|
|
239
|
+
var NAMED_INTERVALS = ["weekly", "biweekly", "monthly", "quarterly", "yearly"];
|
|
240
|
+
var INTERVAL_VALUES = [...NAMED_INTERVALS, "custom"];
|
|
241
|
+
var HOUR_MS = 36e5;
|
|
242
|
+
var DAY_MS = 24 * HOUR_MS;
|
|
243
|
+
var WEEK_MS = 7 * DAY_MS;
|
|
244
|
+
function isNamedInterval(value) {
|
|
245
|
+
return typeof value === "string" && NAMED_INTERVALS.includes(value);
|
|
246
|
+
}
|
|
247
|
+
function isIntervalUnit(value) {
|
|
248
|
+
return typeof value === "string" && INTERVAL_UNITS.includes(value);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// ../core-cadence/src/installments.ts
|
|
252
|
+
function installmentProgress(sub) {
|
|
253
|
+
if (sub.totalPayments == null) return null;
|
|
254
|
+
const paymentsMade = Math.min(sub.paymentsMade ?? 0, sub.totalPayments);
|
|
255
|
+
const remainingPayments = sub.totalPayments - paymentsMade;
|
|
256
|
+
return {
|
|
257
|
+
paymentsMade,
|
|
258
|
+
totalPayments: sub.totalPayments,
|
|
259
|
+
remainingPayments,
|
|
260
|
+
remainingCents: remainingPayments * sub.amount * (sub.quantity ?? 1)
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// ../core-cadence/src/labels.ts
|
|
265
|
+
var NAMED_NOUN = {
|
|
266
|
+
weekly: "week",
|
|
267
|
+
biweekly: "2 weeks",
|
|
268
|
+
monthly: "month",
|
|
269
|
+
quarterly: "quarter",
|
|
270
|
+
yearly: "year"
|
|
271
|
+
};
|
|
272
|
+
var NAMED_LABEL = {
|
|
273
|
+
weekly: "Weekly",
|
|
274
|
+
biweekly: "Biweekly",
|
|
275
|
+
monthly: "Monthly",
|
|
276
|
+
quarterly: "Quarterly",
|
|
277
|
+
yearly: "Yearly"
|
|
278
|
+
};
|
|
279
|
+
function cadenceNoun(cadence) {
|
|
280
|
+
if (isNamedInterval(cadence.interval)) return NAMED_NOUN[cadence.interval];
|
|
281
|
+
if (isIntervalUnit(cadence.intervalUnit) && cadence.intervalCount != null) {
|
|
282
|
+
return cadence.intervalCount === 1 ? cadence.intervalUnit : `${cadence.intervalCount} ${cadence.intervalUnit}s`;
|
|
283
|
+
}
|
|
284
|
+
return cadence.interval;
|
|
285
|
+
}
|
|
286
|
+
function cadenceLabel(cadence) {
|
|
287
|
+
if (isNamedInterval(cadence.interval)) return NAMED_LABEL[cadence.interval];
|
|
288
|
+
if (isIntervalUnit(cadence.intervalUnit) && cadence.intervalCount != null) return `Every ${cadenceNoun(cadence)}`;
|
|
289
|
+
return cadence.interval;
|
|
290
|
+
}
|
|
291
|
+
|
|
237
292
|
// src/helpers.ts
|
|
238
293
|
function isTerminalSubscription(status) {
|
|
239
|
-
|
|
294
|
+
const s = getStatus(status);
|
|
295
|
+
return s === "cancelled" || s === "completed";
|
|
240
296
|
}
|
|
241
297
|
function canPauseSubscription(status) {
|
|
242
298
|
return getStatus(status) === "active";
|
|
@@ -245,7 +301,7 @@ function canResumeSubscription(status) {
|
|
|
245
301
|
return getStatus(status) === "paused";
|
|
246
302
|
}
|
|
247
303
|
function canCancelSubscription(status) {
|
|
248
|
-
return
|
|
304
|
+
return !isTerminalSubscription(status);
|
|
249
305
|
}
|
|
250
306
|
function isSubscriptionPastDue(status) {
|
|
251
307
|
return getStatus(status) === "past_due";
|
|
@@ -262,6 +318,15 @@ function daysUntil(date, now = /* @__PURE__ */ new Date()) {
|
|
|
262
318
|
function getStatus(input) {
|
|
263
319
|
return typeof input === "string" ? input : input.status;
|
|
264
320
|
}
|
|
321
|
+
function cadenceNoun2(cadence) {
|
|
322
|
+
return cadenceNoun(cadence);
|
|
323
|
+
}
|
|
324
|
+
function cadenceLabel2(cadence) {
|
|
325
|
+
return cadenceLabel(cadence);
|
|
326
|
+
}
|
|
327
|
+
function installmentProgress2(sub) {
|
|
328
|
+
return installmentProgress(sub);
|
|
329
|
+
}
|
|
265
330
|
|
|
266
331
|
// src/components.tsx
|
|
267
332
|
import { jsx as jsx2, jsxs } from "react/jsx-runtime";
|
|
@@ -270,14 +335,18 @@ var STATUS_LABELS = {
|
|
|
270
335
|
paused: "Paused",
|
|
271
336
|
cancelled: "Cancelled",
|
|
272
337
|
past_due: "Past due",
|
|
273
|
-
trialing: "Trialing"
|
|
338
|
+
trialing: "Trialing",
|
|
339
|
+
unpaid: "Unpaid",
|
|
340
|
+
completed: "Paid in full"
|
|
274
341
|
};
|
|
275
342
|
var STATUS_STYLES = {
|
|
276
343
|
active: { color: "#035c4f", background: "#dff8ef", borderColor: "#a8e8d2" },
|
|
277
344
|
paused: { color: "#735c00", background: "#fff4ca", borderColor: "#f3d46b" },
|
|
278
345
|
cancelled: { color: "#6c2632", background: "#ffe1e7", borderColor: "#f4a9b8" },
|
|
279
346
|
past_due: { color: "#7a2d00", background: "#ffe8d6", borderColor: "#f5b47f" },
|
|
280
|
-
trialing: { color: "#124c73", background: "#dff1ff", borderColor: "#9ed3fb" }
|
|
347
|
+
trialing: { color: "#124c73", background: "#dff1ff", borderColor: "#9ed3fb" },
|
|
348
|
+
unpaid: { color: "#7a2d00", background: "#ffe8d6", borderColor: "#f5b47f" },
|
|
349
|
+
completed: { color: "#035c4f", background: "#dff8ef", borderColor: "#a8e8d2" }
|
|
281
350
|
};
|
|
282
351
|
function SubscriptionStatusBadge({
|
|
283
352
|
status,
|
|
@@ -378,12 +447,15 @@ export {
|
|
|
378
447
|
ThrottleError,
|
|
379
448
|
ThrottleSubscriptionsError,
|
|
380
449
|
TrialCountdown,
|
|
450
|
+
cadenceLabel2 as cadenceLabel,
|
|
451
|
+
cadenceNoun2 as cadenceNoun,
|
|
381
452
|
canCancelSubscription,
|
|
382
453
|
canPauseSubscription,
|
|
383
454
|
canResumeSubscription,
|
|
384
455
|
createSubscriptionFetcher,
|
|
385
456
|
createSubscriptionsClient,
|
|
386
457
|
daysUntil,
|
|
458
|
+
installmentProgress2 as installmentProgress,
|
|
387
459
|
isSubscriptionPastDue,
|
|
388
460
|
isSubscriptionTrialing,
|
|
389
461
|
isTerminalSubscription,
|