/** * SvelteKit bindings for Autumn billing integration * * @module */ import { createAutumnClientSvelteKit, setAutumnContext, getAutumnContext, hasAutumnContext, } from "./client.svelte.js"; import type { AutumnConvexApi, Customer } from "../svelte/types.js"; import type { AutumnServerState, InvalidateFunction } from "./client.svelte.js"; /** * Initialize Autumn for SvelteKit with SSR support. * * This function sets up Autumn billing integration for your SvelteKit application. * It should be called in your root layout component (+layout.svelte). * * @param convexApi - The Autumn API from your Convex backend (e.g., api.autumn) * @param getServerState - Optional function to get server-side customer data for SSR * @param invalidate - Optional SvelteKit invalidate function for automatic data refetching * @returns The Autumn client instance that can be used to access billing methods * * @example * ```svelte * * * * * ``` * * In your +layout.server.ts: * ```typescript * import type { LayoutServerLoad } from './$types'; * import { createAutumnHandlers } from '@stickerdaniel/convex-autumn-svelte/sveltekit/server'; * * export const load: LayoutServerLoad = async (event) => { * const { getCustomer } = createAutumnHandlers(); * const customer = await getCustomer(event); * * return { * autumnState: { * customer, * _timeFetched: Date.now() * } * }; * }; * ``` */ export function setupAutumn({ convexApi, getServerState, invalidate, }: { /** Autumn Convex API object (e.g., api.autumn from generated types) */ convexApi: AutumnConvexApi; /** Optional function to get server state for SSR hydration */ getServerState?: () => AutumnServerState; /** Optional SvelteKit invalidate function for automatic data refetching */ invalidate?: InvalidateFunction; }) { const autumn = createAutumnClientSvelteKit({ convexApi, getServerState, invalidate }); setAutumnContext(autumn); return autumn; } /** * Hook for accessing customer data and Autumn billing operations in SvelteKit. * * Must be called after `setupAutumn()` has been called in a parent component. * * Note: Customer data is pre-loaded server-side via SSR and automatically * refreshed after mutations using SvelteKit's `invalidateAll()`. No global * loading state is needed since data is always available on initial render. * * @returns Customer data and billing methods * @returns {Customer | null} customer - Customer data (pre-loaded via SSR, null if not found) * @returns {function(CheckParams): LocalCheckResult} allowed - Local check for feature access without consuming usage * @returns {function(CheckParams): Promise} check - Server-side check with usage tracking (auto-invalidates) * @returns {function(CheckoutParams): Promise} checkout - Initiate checkout; returns a hosted url or a preview to confirm with attach (auto-invalidates) * @returns {function(TrackParams): Promise} track - Track usage of a feature (auto-invalidates) * @returns {function(AttachParams): Promise} attach - Attach a product to the customer (auto-invalidates) * @returns {function(CancelParams): Promise} cancel - Cancel a product subscription (auto-invalidates) * @returns {function(BillingPortalParams): Promise} openBillingPortal - Open Stripe billing portal * @returns {function(CreateEntityParams): Promise} createEntity - Create a new entity (auto-invalidates) * @returns {function(GetEntityParams): Promise} getEntity - Get entity by ID * @returns {function(SetupPaymentParams): Promise} setupPayment - Setup payment method without charging (auto-invalidates) * @returns {function(CreateReferralCodeParams): Promise} createReferralCode - Create a referral code (auto-invalidates) * @returns {function(RedeemReferralCodeParams): Promise} redeemReferralCode - Redeem a referral code for rewards (auto-invalidates) * @returns {function(): Promise} listProducts - List all available products * @returns {function(SetUsageParams): Promise} usage - Set usage to an absolute value (not a query - use customer.features for reading) * @returns {function(QueryParams): Promise} query - Query customer data with custom parameters * @returns {function(EventListParams): Promise} listEvents - List raw Autumn usage events * @returns {function(EventAggregateParams): Promise} aggregateEvents - Aggregate Autumn usage events * @returns {function(): Promise} refetch - Manually trigger SvelteKit data refresh (invalidateAll) * * @example * ```svelte * * * * {#if customer} *

Welcome {customer.name}!

*

Messages: {customer.features?.messages?.balance}

* {#if !canUpload} * * {/if} * {/if} * ``` * * @example * ```svelte * * * * * * ``` * * @example * ```svelte * * * * * * * * * {#if customer?.features?.messages} *

Usage: {customer.features.messages.usage} / {customer.features.messages.included_usage}

* {/if} * ``` */ export function useCustomer() { const autumn = getAutumnContext(); if (!autumn) { throw new Error( "No Autumn client found in context. Did you forget to call setupAutumn()?", ); } return { get customer() { return autumn.customer; }, allowed: autumn.allowed, check: autumn.check, checkout: autumn.checkout, track: autumn.track, attach: autumn.attach, cancel: autumn.cancel, openBillingPortal: autumn.openBillingPortal, createEntity: autumn.createEntity, getEntity: autumn.getEntity, setupPayment: autumn.setupPayment, createReferralCode: autumn.createReferralCode, redeemReferralCode: autumn.redeemReferralCode, listProducts: autumn.listProducts, usage: autumn.usage, query: autumn.query, listEvents: autumn.listEvents, aggregateEvents: autumn.aggregateEvents, refetch: autumn.refetch, }; } /** * Check if Autumn has been set up in the current context */ export function isAutumnSetup(): boolean { return hasAutumnContext(); } /** * Helper for managing loading, error, and result state for Autumn operations. * * Reduces boilerplate when calling async billing operations like checkout, track, etc. * Returns reactive state ($state runes) that automatically updates during operation execution. * * @see {@link useAutumnOperation} for detailed documentation and examples */ export { useAutumnOperation } from "./client.svelte.js"; // Re-export types for convenience export type { Customer, Entity, Feature, Product, ProductItem, CheckParams, CheckResult, CheckoutParams, CheckoutResult, TrackParams, TrackResult, AttachParams, AttachResult, AttachFeatureOptions, CancelParams, BillingPortalParams, BillingPortalResult, CreateEntityParams, GetEntityParams, SetupPaymentParams, SetupPaymentResult, CreateReferralCodeParams, CreateReferralCodeResult, RedeemReferralCodeParams, RedeemReferralCodeResult, SetUsageParams, SetUsageResult, QueryParams, QueryResult, EventRecord, EventListParams, EventListResult, EventAggregateParams, LocalCheckResult, RefetchOptions, AutumnConvexApi, } from "../svelte/types.js"; export type { AutumnServerState, InvalidateFunction } from "./client.svelte.js";