@foldspace-fe/casdoor-next-auth-kit 0.1.7 → 0.1.8

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/react/provider.tsx","../../src/react/hooks.ts","../../src/billing/react.tsx"],"sourcesContent":["'use client';\n\nimport type { ReactNode } from 'react';\nimport type { Session } from 'next-auth';\nimport { SessionProvider } from 'next-auth/react';\n\nexport function AuthProvider({\n children,\n session,\n}: {\n children: ReactNode;\n session?: Session | null;\n}) {\n return <SessionProvider session={session}>{children}</SessionProvider>;\n}\n","'use client';\n\nimport { useSession } from 'next-auth/react';\nimport { buildAuthJumpHref } from '../core/redirect';\nimport type { AuthSession } from '../next/options';\n\nexport type AuthRole = 'guest' | 'user' | 'admin';\n\nexport interface AuthUserSummary {\n id: string | null;\n name: string;\n email: string | null;\n image: string | null;\n isAuthenticated: boolean;\n isAdmin: boolean;\n tokenBalance: number;\n isVip: boolean;\n role: AuthRole;\n}\n\nexport interface AuthActions {\n loginHref: string;\n signupHref: string;\n logoutHref: string;\n accountHref: string;\n adminHref: string;\n}\n\nexport interface AuthActionsOptions {\n redirect?: string | null;\n}\n\nfunction getUserSummary(session: AuthSession | null | undefined): AuthUserSummary {\n const user = session?.user;\n const name = user?.name || '登录';\n const isAuthenticated = Boolean(user);\n const isAdmin = Boolean(user?.isAdmin);\n const role: AuthRole = !isAuthenticated ? 'guest' : isAdmin ? 'admin' : 'user';\n\n return {\n id: user?.id ?? null,\n name,\n email: user?.email ?? null,\n image: user?.image ?? null,\n isAuthenticated,\n isAdmin,\n tokenBalance: Number(user?.tokenBalance ?? 2580),\n isVip: Boolean(user?.isVip ?? true),\n role,\n };\n}\n\nexport function useAuthSession() {\n return useSession() as ReturnType<typeof useSession> & {\n data: AuthSession | null | undefined;\n };\n}\n\nexport function useAuthUser(): AuthUserSummary {\n const { data: session } = useAuthSession();\n return getUserSummary(session ?? null);\n}\n\nexport function useAuthRole(): AuthRole {\n return useAuthUser().role;\n}\n\nexport function useAuthActions(options: AuthActionsOptions = {}): AuthActions {\n const user = useAuthUser();\n const redirect = options.redirect ?? null;\n\n return {\n loginHref: buildAuthJumpHref('login', redirect ?? undefined),\n signupHref: buildAuthJumpHref('signup', redirect ?? undefined),\n logoutHref: '/logout',\n accountHref: '/user/account',\n adminHref: '/admin',\n };\n}\n","'use client';\n\nimport {\n type Context,\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n type ReactNode,\n} from 'react';\n\nimport {\n buildBillingActionPayload,\n deriveBillingCreditsState,\n deriveBillingEntitlements,\n filterProductsByKind,\n normalizeBillingPurchaseStatus,\n normalizeBillingCatalogConfig,\n normalizeBillingRuntimeConfig,\n resolveBillingItem,\n resolveBillingProductSnapshot,\n resolveBillingSubscriptionProduct,\n} from './runtime';\nimport type {\n BillingActionExecutor,\n BillingActionKind,\n BillingActionPayload,\n BillingApiClient,\n BillingCatalogConfig,\n BillingCoreContextValue,\n BillingCreditsContextValue,\n BillingCreditsState,\n BillingDefaults,\n BillingEntitlementState,\n BillingLoaders,\n BillingOrderHistoryItem,\n BillingPaymentHistoryItem,\n BillingItem,\n BillingProductState,\n BillingProductContextValue,\n BillingProductSnapshot,\n BillingPurchaseStatus,\n BillingRuntimeConfig,\n BillingStatusState,\n BillingSubscriptionContextValue,\n BillingSubscriptionHistoryItem,\n BillingSubscriptionPurchaseConfig,\n BillingSubscriptionState,\n BillingProductPurchaseConfig,\n} from './types';\n\nexport interface BillingProviderProps {\n children: ReactNode;\n apiClient: BillingApiClient;\n loaders?: BillingLoaders;\n runtimeConfigLoader?: BillingLoaders['runtimeConfigLoader'];\n actionExecutor?: BillingActionExecutor;\n defaults?: BillingDefaults;\n runtimeConfig?: BillingRuntimeConfig | BillingCatalogConfig;\n subscription?: BillingSubscriptionState;\n subscriptionHistory?: BillingSubscriptionHistoryItem[];\n products?: BillingProductState[];\n orderHistory?: BillingOrderHistoryItem[];\n paymentHistory?: BillingPaymentHistoryItem[];\n credits?: BillingCreditsState;\n entitlements?: BillingEntitlementState;\n status?: BillingStatusState;\n purchaseStatus?: BillingPurchaseStatus;\n autoRefresh?: boolean;\n}\n\nexport type BillingCoreProviderProps = BillingProviderProps;\nexport interface BillingSubscriptionProviderProps {\n children: ReactNode;\n availablePlans?: BillingItem[];\n subscription?: BillingSubscriptionState;\n subscriptionHistory?: BillingSubscriptionHistoryItem[];\n entitlements?: BillingEntitlementState;\n status?: BillingStatusState;\n}\n\nexport interface BillingProductProviderProps {\n children: ReactNode;\n availableProducts?: BillingItem[];\n products?: BillingProductState[];\n orderHistory?: BillingOrderHistoryItem[];\n paymentHistory?: BillingPaymentHistoryItem[];\n status?: BillingStatusState;\n}\n\nexport interface BillingCreditsProviderProps {\n children: ReactNode;\n credits?: BillingCreditsState;\n status?: BillingStatusState;\n}\n\nexport interface BillingPipelineOptions {\n onBeforeAction?: (payload: BillingActionPayload) => Promise<BillingActionPayload>;\n onAfterAction?: (result: { redirectTo?: string; nextAction?: string }) => Promise<void>;\n onError?: (error: unknown) => Promise<void>;\n}\n\nconst BillingCoreContext = createContext<BillingCoreContextValue | null>(null);\nconst BillingSubscriptionContext = createContext<BillingSubscriptionContextValue | null>(null);\nconst BillingProductContext = createContext<BillingProductContextValue | null>(null);\nconst BillingCreditsContext = createContext<BillingCreditsContextValue | null>(null);\n\nfunction useOptionalContext<T>(context: Context<T | null>): T | null {\n return useContext(context);\n}\n\nfunction useRequiredCoreContext(): BillingCoreContextValue {\n const context = useContext(BillingCoreContext);\n if (!context) {\n throw new Error('Billing hooks must be used inside BillingProvider or BillingCoreProvider.');\n }\n return context;\n}\n\nfunction choose<T>(primary: T | undefined, fallback: T | undefined): T | undefined {\n return primary ?? fallback;\n}\n\nfunction getLatestOrder(orders: BillingOrderHistoryItem[] | undefined): BillingOrderHistoryItem | undefined {\n return [...(orders ?? [])].sort((a, b) => {\n const left = Date.parse(b.updatedAt ?? b.createdAt ?? '') || 0;\n const right = Date.parse(a.updatedAt ?? a.createdAt ?? '') || 0;\n return left - right;\n })[0];\n}\n\nfunction getLatestPayment(payments: BillingPaymentHistoryItem[] | undefined): BillingPaymentHistoryItem | undefined {\n return [...(payments ?? [])].sort((a, b) => {\n const left = Date.parse(b.updatedAt ?? b.createdAt ?? '') || 0;\n const right = Date.parse(a.updatedAt ?? a.createdAt ?? '') || 0;\n return left - right;\n })[0];\n}\n\nfunction normalizeRuntimeConfigInput(config?: BillingRuntimeConfig | BillingCatalogConfig | null): BillingRuntimeConfig | undefined {\n if (!config) return undefined;\n return normalizeBillingRuntimeConfig(config);\n}\n\nfunction normalizeCatalogConfigInput(config?: BillingRuntimeConfig | BillingCatalogConfig | null): BillingCatalogConfig | undefined {\n if (!config) return undefined;\n return normalizeBillingCatalogConfig(config);\n}\n\nfunction buildCoreValue(input: {\n apiClient: BillingApiClient;\n loaders?: BillingLoaders;\n runtimeConfigLoader?: BillingLoaders['runtimeConfigLoader'];\n actionExecutor?: BillingActionExecutor;\n defaults?: BillingDefaults;\n runtimeConfig?: BillingRuntimeConfig | BillingCatalogConfig;\n runtimeCatalog?: BillingCatalogConfig;\n runtimeConfigLoading: boolean;\n runtimeConfigError: string | null;\n subscription?: BillingSubscriptionState;\n subscriptionHistory?: BillingSubscriptionHistoryItem[];\n products?: BillingProductState[];\n orderHistory?: BillingOrderHistoryItem[];\n paymentHistory?: BillingPaymentHistoryItem[];\n credits?: BillingCreditsState;\n entitlements?: BillingEntitlementState;\n purchaseStatus?: BillingPurchaseStatus;\n status: BillingStatusState;\n refresh: () => Promise<void>;\n runAction: (payload: BillingActionPayload) => Promise<{\n redirectTo?: string;\n nextAction?: string;\n status?: 'pending' | 'succeeded' | 'failed';\n }>;\n setRuntimeConfig: (config?: BillingRuntimeConfig) => void;\n setSubscription: (value?: BillingSubscriptionState) => void;\n setSubscriptionHistory: (value?: BillingSubscriptionHistoryItem[]) => void;\n setProducts: (value?: BillingProductState[]) => void;\n setOrderHistory: (value?: BillingOrderHistoryItem[]) => void;\n setPaymentHistory: (value?: BillingPaymentHistoryItem[]) => void;\n setCredits: (value?: BillingCreditsState) => void;\n setEntitlements: (value?: BillingEntitlementState) => void;\n setPurchaseStatus: (status?: BillingPurchaseStatus) => void;\n setStatus: (status: BillingStatusState | ((current: BillingStatusState) => BillingStatusState)) => void;\n}): BillingCoreContextValue {\n return {\n apiClient: input.apiClient,\n loaders: input.loaders,\n runtimeConfigLoader: input.runtimeConfigLoader,\n actionExecutor: input.actionExecutor,\n defaults: input.defaults,\n runtimeConfig: input.runtimeConfig,\n runtimeCatalog: input.runtimeCatalog,\n runtimeConfigLoading: input.runtimeConfigLoading,\n runtimeConfigError: input.runtimeConfigError,\n subscription: input.subscription,\n subscriptionHistory: input.subscriptionHistory,\n products: input.products,\n orderHistory: input.orderHistory,\n paymentHistory: input.paymentHistory,\n credits: input.credits,\n entitlements: input.entitlements,\n purchaseStatus: input.purchaseStatus,\n status: input.status,\n refresh: input.refresh,\n runAction: input.runAction,\n setRuntimeConfig: input.setRuntimeConfig,\n setSubscription: input.setSubscription,\n setSubscriptionHistory: input.setSubscriptionHistory,\n setProducts: input.setProducts,\n setOrderHistory: input.setOrderHistory,\n setPaymentHistory: input.setPaymentHistory,\n setCredits: input.setCredits,\n setEntitlements: input.setEntitlements,\n setPurchaseStatus: input.setPurchaseStatus,\n setStatus: input.setStatus,\n };\n}\n\nexport function BillingProvider({\n children,\n apiClient,\n loaders,\n runtimeConfigLoader,\n actionExecutor,\n defaults,\n runtimeConfig: runtimeConfigProp,\n subscription: subscriptionProp,\n subscriptionHistory: subscriptionHistoryProp,\n products: productsProp,\n orderHistory: orderHistoryProp,\n paymentHistory: paymentHistoryProp,\n credits: creditsProp,\n entitlements: entitlementsProp,\n status: statusProp,\n purchaseStatus: purchaseStatusProp,\n autoRefresh = true,\n}: BillingProviderProps) {\n const [runtimeConfig, setRuntimeConfig] = useState<BillingRuntimeConfig | undefined>(normalizeRuntimeConfigInput(runtimeConfigProp));\n const [runtimeCatalog, setRuntimeCatalog] = useState<BillingCatalogConfig | undefined>(normalizeCatalogConfigInput(runtimeConfigProp));\n const [runtimeConfigLoading, setRuntimeConfigLoading] = useState(false);\n const [runtimeConfigError, setRuntimeConfigError] = useState<string | null>(null);\n const [subscription, setSubscription] = useState<BillingSubscriptionState | undefined>(subscriptionProp);\n const [subscriptionHistory, setSubscriptionHistory] = useState<BillingSubscriptionHistoryItem[] | undefined>(subscriptionHistoryProp);\n const [products, setProducts] = useState<BillingProductState[] | undefined>(productsProp);\n const [orderHistory, setOrderHistory] = useState<BillingOrderHistoryItem[] | undefined>(orderHistoryProp);\n const [paymentHistory, setPaymentHistory] = useState<BillingPaymentHistoryItem[] | undefined>(paymentHistoryProp);\n const [credits, setCredits] = useState<BillingCreditsState | undefined>(creditsProp);\n const [entitlements, setEntitlements] = useState<BillingEntitlementState | undefined>(entitlementsProp);\n const [purchaseStatus, setPurchaseStatus] = useState<BillingPurchaseStatus | undefined>(purchaseStatusProp);\n const [status, setStatus] = useState<BillingStatusState>(\n statusProp ?? { loading: false, refreshing: false, error: null },\n );\n\n useEffect(() => {\n if (runtimeConfigProp) {\n setRuntimeConfig(normalizeRuntimeConfigInput(runtimeConfigProp));\n setRuntimeCatalog(normalizeCatalogConfigInput(runtimeConfigProp));\n }\n }, [runtimeConfigProp]);\n\n useEffect(() => {\n if (subscriptionProp) setSubscription(subscriptionProp);\n }, [subscriptionProp]);\n\n useEffect(() => {\n if (subscriptionHistoryProp) setSubscriptionHistory(subscriptionHistoryProp);\n }, [subscriptionHistoryProp]);\n\n useEffect(() => {\n if (productsProp) setProducts(productsProp);\n }, [productsProp]);\n\n useEffect(() => {\n if (orderHistoryProp) setOrderHistory(orderHistoryProp);\n }, [orderHistoryProp]);\n\n useEffect(() => {\n if (paymentHistoryProp) setPaymentHistory(paymentHistoryProp);\n }, [paymentHistoryProp]);\n\n useEffect(() => {\n if (creditsProp) setCredits(creditsProp);\n }, [creditsProp]);\n\n useEffect(() => {\n if (entitlementsProp) setEntitlements(entitlementsProp);\n }, [entitlementsProp]);\n\n useEffect(() => {\n if (purchaseStatusProp) setPurchaseStatus(purchaseStatusProp);\n }, [purchaseStatusProp]);\n\n useEffect(() => {\n if (statusProp) setStatus(statusProp);\n }, [statusProp]);\n\n const refresh = useCallback(async () => {\n const catalogKey = runtimeCatalog?.catalogKey ?? runtimeConfig?.catalogKey ?? 'default';\n const runtimeLoader = runtimeConfigLoader ?? apiClient.fetchRuntimeConfig;\n const resolvedLoaders = loaders ?? {};\n const subscriptionLoader = resolvedLoaders.subscriptionLoader ?? apiClient.fetchSubscription;\n const subscriptionHistoryLoader = resolvedLoaders.subscriptionHistoryLoader ?? apiClient.fetchSubscriptionHistory;\n const productsLoader = resolvedLoaders.productsLoader ?? apiClient.fetchProducts;\n const orderHistoryLoader = resolvedLoaders.orderHistoryLoader ?? apiClient.fetchOrderHistory;\n const paymentHistoryLoader = resolvedLoaders.paymentHistoryLoader ?? apiClient.fetchPaymentHistory;\n const purchaseStatusLoader = resolvedLoaders.purchaseStatusLoader ?? apiClient.fetchPurchaseStatus;\n const creditsLoader = resolvedLoaders.creditsLoader ?? apiClient.fetchCredits;\n const entitlementsLoader = resolvedLoaders.entitlementsLoader ?? apiClient.fetchEntitlements;\n\n setRuntimeConfigLoading(true);\n setRuntimeConfigError(null);\n setStatus((current) => ({ ...current, loading: true, refreshing: true, error: null }));\n\n try {\n const nextRuntimeCatalog = normalizeCatalogConfigInput(await runtimeLoader(catalogKey));\n const nextRuntimeConfig = nextRuntimeCatalog ? normalizeRuntimeConfigInput(nextRuntimeCatalog) : undefined;\n if (nextRuntimeConfig) {\n setRuntimeCatalog(nextRuntimeCatalog);\n setRuntimeConfig(nextRuntimeConfig);\n }\n\n const nextCatalogKey = nextRuntimeConfig?.catalogKey ?? nextRuntimeCatalog?.catalogKey ?? catalogKey;\n\n const [\n nextSubscription,\n nextSubscriptionHistory,\n nextProducts,\n nextOrderHistory,\n nextPaymentHistory,\n nextCredits,\n nextEntitlements,\n ] = await Promise.all([\n subscriptionLoader({ catalogKey: nextCatalogKey }),\n subscriptionHistoryLoader({ catalogKey: nextCatalogKey }),\n productsLoader({ catalogKey: nextCatalogKey }),\n orderHistoryLoader({ catalogKey: nextCatalogKey }),\n paymentHistoryLoader({ catalogKey: nextCatalogKey }),\n creditsLoader({ catalogKey: nextCatalogKey }),\n entitlementsLoader({ catalogKey: nextCatalogKey }),\n ]);\n\n const subscriptionWithProduct = nextSubscription\n ? {\n ...nextSubscription,\n product: resolveBillingSubscriptionProduct(nextSubscription, nextRuntimeConfig ?? runtimeConfig),\n }\n : undefined;\n const normalizedCredits = deriveBillingCreditsState(nextCredits, nextProducts, nextRuntimeConfig?.conversionRules ?? runtimeConfig?.conversionRules);\n const normalizedEntitlements = nextEntitlements ?? deriveBillingEntitlements(subscriptionWithProduct, nextProducts, normalizedCredits, nextRuntimeConfig ?? runtimeConfig);\n const latestOrder = getLatestOrder(nextOrderHistory);\n const latestPayment = getLatestPayment(nextPaymentHistory);\n const fetchedPurchaseStatus = await purchaseStatusLoader({\n orderId: latestOrder?.orderId,\n paymentId: latestPayment?.paymentId,\n transactionId: latestPayment?.transactionId ?? latestOrder?.transactionId,\n }).catch(() => undefined);\n const normalizedPurchaseStatus = normalizeBillingPurchaseStatus(\n fetchedPurchaseStatus,\n latestOrder,\n latestPayment,\n );\n\n setSubscription(subscriptionWithProduct);\n setSubscriptionHistory(nextSubscriptionHistory);\n setProducts(nextProducts);\n setOrderHistory(nextOrderHistory);\n setPaymentHistory(nextPaymentHistory);\n setCredits(normalizedCredits);\n setEntitlements(normalizedEntitlements);\n setPurchaseStatus(normalizedPurchaseStatus);\n setStatus({ loading: false, refreshing: false, error: null, lastFetchedAt: new Date().toISOString() });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n setRuntimeConfigError(message);\n setStatus((current) => ({ ...current, loading: false, refreshing: false, error: message }));\n } finally {\n setRuntimeConfigLoading(false);\n }\n }, [apiClient, loaders, runtimeConfig, runtimeConfigLoader, runtimeCatalog]);\n\n const runAction = useCallback(\n async (payload: BillingActionPayload) => {\n const prepared = buildBillingActionPayload(payload, runtimeConfig);\n const executor = actionExecutor ?? ((input: BillingActionPayload) => apiClient.createAction(input));\n\n setPurchaseStatus((current) => ({\n actionKey: prepared.key,\n orderId: current?.orderId,\n paymentId: current?.paymentId,\n transactionId: current?.transactionId,\n status: 'pending',\n redirectTo: current?.redirectTo,\n updatedAt: new Date().toISOString(),\n }));\n setStatus((current) => ({ ...current, loading: true, refreshing: true, error: null }));\n\n try {\n const result = await executor(prepared);\n setPurchaseStatus((current) => ({\n actionKey: prepared.key,\n orderId: current?.orderId,\n paymentId: current?.paymentId,\n transactionId: current?.transactionId,\n status: result.status === 'failed' ? 'failed' : result.status === 'succeeded' ? 'paid' : 'pending',\n redirectTo: result.redirectTo ?? current?.redirectTo,\n updatedAt: new Date().toISOString(),\n }));\n if (result.redirectTo || result.nextAction) {\n // host handles the redirect/next action, we only persist the result\n }\n await refresh();\n return result;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n setPurchaseStatus((current) => ({\n actionKey: prepared.key,\n orderId: current?.orderId,\n paymentId: current?.paymentId,\n transactionId: current?.transactionId,\n status: 'failed',\n redirectTo: current?.redirectTo,\n updatedAt: new Date().toISOString(),\n }));\n setStatus((current) => ({ ...current, loading: false, refreshing: false, error: message }));\n throw error;\n }\n },\n [actionExecutor, apiClient, refresh, runtimeConfig],\n );\n\n useEffect(() => {\n if (!autoRefresh) return;\n if (runtimeConfigLoading) return;\n if (!runtimeConfig && !runtimeConfigError) {\n void refresh();\n }\n }, [autoRefresh, refresh, runtimeConfig, runtimeConfigError, runtimeConfigLoading]);\n\n const coreValue = useMemo(\n () =>\n buildCoreValue({\n apiClient,\n loaders,\n runtimeConfigLoader,\n actionExecutor,\n defaults,\n runtimeConfig,\n runtimeCatalog,\n runtimeConfigLoading,\n runtimeConfigError,\n subscription,\n subscriptionHistory,\n products,\n orderHistory,\n paymentHistory,\n credits,\n entitlements,\n purchaseStatus,\n status,\n refresh,\n runAction,\n setRuntimeConfig,\n setSubscription,\n setSubscriptionHistory,\n setProducts,\n setOrderHistory,\n setPaymentHistory,\n setCredits,\n setEntitlements,\n setPurchaseStatus,\n setStatus,\n }),\n [\n actionExecutor,\n apiClient,\n credits,\n defaults,\n entitlements,\n orderHistory,\n paymentHistory,\n products,\n purchaseStatus,\n refresh,\n runAction,\n runtimeConfig,\n runtimeConfigError,\n runtimeConfigLoader,\n runtimeConfigLoading,\n runtimeCatalog,\n loaders,\n status,\n subscription,\n subscriptionHistory,\n ],\n );\n\n return (\n <BillingCoreContext.Provider value={coreValue}>\n <SubscriptionProvider subscription={subscription} subscriptionHistory={subscriptionHistory} entitlements={entitlements} status={status}>\n <ProductProvider products={products} orderHistory={orderHistory} paymentHistory={paymentHistory} status={status}>\n <CreditsProvider credits={credits} status={status}>{children}</CreditsProvider>\n </ProductProvider>\n </SubscriptionProvider>\n </BillingCoreContext.Provider>\n );\n}\n\nexport function BillingCoreProvider(props: BillingCoreProviderProps) {\n return <BillingProvider {...props} />;\n}\n\nexport function SubscriptionProvider({\n children,\n availablePlans,\n subscription,\n subscriptionHistory,\n entitlements,\n status,\n}: BillingSubscriptionProviderProps) {\n const core = useOptionalContext(BillingCoreContext);\n const value = useMemo<BillingSubscriptionContextValue>(\n () => ({\n availablePlans: choose(availablePlans, core?.runtimeConfig?.items?.filter((item) => item.kind === 'subscription')),\n subscription: choose(subscription, core?.subscription),\n subscriptionHistory: choose(subscriptionHistory, core?.subscriptionHistory),\n entitlements: choose(entitlements, core?.entitlements),\n status: choose(status, core?.status),\n }),\n [availablePlans, core?.entitlements, core?.runtimeConfig?.items, core?.status, core?.subscription, core?.subscriptionHistory, entitlements, status, subscription, subscriptionHistory],\n );\n\n return <BillingSubscriptionContext.Provider value={value}>{children}</BillingSubscriptionContext.Provider>;\n}\n\nexport function ProductProvider({\n children,\n availableProducts,\n products,\n orderHistory,\n paymentHistory,\n status,\n}: BillingProductProviderProps) {\n const core = useOptionalContext(BillingCoreContext);\n const value = useMemo<BillingProductContextValue>(\n () => ({\n availableProducts: choose(availableProducts, core?.runtimeConfig?.items?.filter((item) => item.kind === 'product' || item.kind === 'credits')),\n products: choose(products, core?.products),\n orderHistory: choose(orderHistory, core?.orderHistory),\n paymentHistory: choose(paymentHistory, core?.paymentHistory),\n status: choose(status, core?.status),\n }),\n [availableProducts, core?.orderHistory, core?.paymentHistory, core?.products, core?.runtimeConfig?.items, core?.status, orderHistory, paymentHistory, products, status],\n );\n\n return <BillingProductContext.Provider value={value}>{children}</BillingProductContext.Provider>;\n}\n\nexport function CreditsProvider({ children, credits, status }: BillingCreditsProviderProps) {\n const core = useOptionalContext(BillingCoreContext);\n const value = useMemo<BillingCreditsContextValue>(\n () => ({\n credits: choose(credits, core?.credits),\n status: choose(status, core?.status),\n }),\n [credits, core?.credits, core?.status, status],\n );\n\n return <BillingCreditsContext.Provider value={value}>{children}</BillingCreditsContext.Provider>;\n}\n\nexport interface BillingCatalogState {\n catalog?: BillingRuntimeConfig | BillingCatalogConfig;\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingContext(): BillingCoreContextValue {\n return useRequiredCoreContext();\n}\n\nexport function useBillingCatalog(): BillingCatalogState {\n const core = useRequiredCoreContext();\n return useMemo(\n () => ({\n catalog: core.runtimeCatalog ?? core.runtimeConfig,\n loading: core.runtimeConfigLoading,\n error: core.runtimeConfigError,\n refresh: core.refresh,\n }),\n [core.refresh, core.runtimeCatalog, core.runtimeConfig, core.runtimeConfigError, core.runtimeConfigLoading],\n );\n}\n\nexport interface BillingItemState {\n item?: BillingProductSnapshot;\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingItem(itemKey: string): BillingItemState {\n const core = useRequiredCoreContext();\n return useMemo(() => {\n const item = resolveBillingItem(core.runtimeConfig?.items, itemKey);\n return {\n item: resolveBillingProductSnapshot(item),\n loading: core.runtimeConfigLoading,\n error: core.runtimeConfigError,\n refresh: core.refresh,\n };\n }, [core.refresh, core.runtimeConfig?.items, core.runtimeConfigError, core.runtimeConfigLoading, itemKey]);\n}\n\nexport interface BillingProductsState {\n products: BillingProductState[];\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingProducts(options: { userId?: string; catalogKey?: string; kind?: 'product' | 'credits' } = {}): BillingProductsState {\n const core = useRequiredCoreContext();\n const productContext = useOptionalContext(BillingProductContext);\n const products = choose(productContext?.products, core.products) ?? [];\n return useMemo(\n () => ({\n products: filterProductsByKind(products, options.kind),\n loading: core.runtimeConfigLoading || core.status.loading,\n error: core.runtimeConfigError ?? core.status.error,\n refresh: core.refresh,\n }),\n [core.refresh, core.runtimeConfigError, core.runtimeConfigLoading, core.status.error, core.status.loading, options.kind, products],\n );\n}\n\nexport interface BillingAvailablePlansState {\n plans: BillingItem[];\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingAvailablePlans(): BillingAvailablePlansState {\n const core = useRequiredCoreContext();\n const subscriptionContext = useOptionalContext(BillingSubscriptionContext);\n const plans = choose(subscriptionContext?.availablePlans, core.runtimeConfig?.items?.filter((item) => item.kind === 'subscription')) ?? [];\n return useMemo(\n () => ({\n plans,\n loading: core.runtimeConfigLoading || core.status.loading,\n error: core.runtimeConfigError ?? core.status.error,\n refresh: core.refresh,\n }),\n [core.refresh, core.runtimeConfig?.items, core.runtimeConfigError, core.runtimeConfigLoading, core.status.error, core.status.loading, plans],\n );\n}\n\nexport interface BillingAvailableProductsState {\n items: BillingItem[];\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingAvailableProducts(): BillingAvailableProductsState {\n const core = useRequiredCoreContext();\n const productContext = useOptionalContext(BillingProductContext);\n const items = choose(productContext?.availableProducts, core.runtimeConfig?.items?.filter((item) => item.kind === 'product' || item.kind === 'credits')) ?? [];\n return useMemo(\n () => ({\n items,\n loading: core.runtimeConfigLoading || core.status.loading,\n error: core.runtimeConfigError ?? core.status.error,\n refresh: core.refresh,\n }),\n [core.refresh, core.runtimeConfig?.items, core.runtimeConfigError, core.runtimeConfigLoading, core.status.error, core.status.loading, items],\n );\n}\n\nexport interface BillingOrderHistoryState {\n orders: BillingOrderHistoryItem[];\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingOrderHistory(_options: { userId?: string; catalogKey?: string; productKey?: string } = {}): BillingOrderHistoryState {\n const core = useRequiredCoreContext();\n const productContext = useOptionalContext(BillingProductContext);\n const orders = choose(productContext?.orderHistory, core.orderHistory) ?? [];\n return useMemo(\n () => ({\n orders,\n loading: core.runtimeConfigLoading || core.status.loading,\n error: core.runtimeConfigError ?? core.status.error,\n refresh: core.refresh,\n }),\n [core.refresh, core.runtimeConfigError, core.runtimeConfigLoading, core.status.error, core.status.loading, orders],\n );\n}\n\nexport interface BillingPaymentHistoryState {\n payments: BillingPaymentHistoryItem[];\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingPaymentHistory(_options: { userId?: string; catalogKey?: string } = {}): BillingPaymentHistoryState {\n const core = useRequiredCoreContext();\n const productContext = useOptionalContext(BillingProductContext);\n const payments = choose(productContext?.paymentHistory, core.paymentHistory) ?? [];\n return useMemo(\n () => ({\n payments,\n loading: core.runtimeConfigLoading || core.status.loading,\n error: core.runtimeConfigError ?? core.status.error,\n refresh: core.refresh,\n }),\n [core.refresh, core.runtimeConfigError, core.runtimeConfigLoading, core.status.error, core.status.loading, payments],\n );\n}\n\nexport interface BillingSubscriptionStateView {\n subscription?: BillingSubscriptionState;\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingSubscription(): BillingSubscriptionStateView {\n const core = useRequiredCoreContext();\n const subscriptionContext = useOptionalContext(BillingSubscriptionContext);\n return useMemo(\n () => ({\n subscription: choose(subscriptionContext?.subscription, core.subscription),\n loading: core.runtimeConfigLoading || core.status.loading,\n error: core.runtimeConfigError ?? core.status.error,\n refresh: core.refresh,\n }),\n [core.refresh, core.runtimeConfigError, core.runtimeConfigLoading, core.status.error, core.status.loading, core.subscription, subscriptionContext?.subscription],\n );\n}\n\nexport interface BillingSubscriptionProductState {\n product?: BillingProductSnapshot;\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingSubscriptionProduct(): BillingSubscriptionProductState {\n const core = useRequiredCoreContext();\n const subscriptionContext = useOptionalContext(BillingSubscriptionContext);\n const subscription = choose(subscriptionContext?.subscription, core.subscription);\n return useMemo(\n () => ({\n product: subscription?.product ?? resolveBillingSubscriptionProduct(subscription, core.runtimeConfig),\n loading: core.runtimeConfigLoading || core.status.loading,\n error: core.runtimeConfigError ?? core.status.error,\n refresh: core.refresh,\n }),\n [core.refresh, core.runtimeConfig, core.runtimeConfigError, core.runtimeConfigLoading, core.status.error, core.status.loading, subscription],\n );\n}\n\nexport interface BillingSubscriptionHistoryState {\n history: BillingSubscriptionHistoryItem[];\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingSubscriptionHistory(_options: { userId?: string; catalogKey?: string } = {}): BillingSubscriptionHistoryState {\n const core = useRequiredCoreContext();\n const subscriptionContext = useOptionalContext(BillingSubscriptionContext);\n const history = choose(subscriptionContext?.subscriptionHistory, core.subscriptionHistory) ?? [];\n return useMemo(\n () => ({\n history,\n loading: core.runtimeConfigLoading || core.status.loading,\n error: core.runtimeConfigError ?? core.status.error,\n refresh: core.refresh,\n }),\n [core.refresh, core.runtimeConfigError, core.runtimeConfigLoading, core.status.error, core.status.loading, history],\n );\n}\n\nexport interface BillingCreditsStateView {\n credits?: BillingCreditsState;\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingCredits(): BillingCreditsStateView {\n const core = useRequiredCoreContext();\n const creditsContext = useOptionalContext(BillingCreditsContext);\n const credits = choose(creditsContext?.credits, core.credits) ?? deriveBillingCreditsState(undefined, core.products, core.runtimeConfig?.conversionRules);\n return useMemo(\n () => ({\n credits,\n loading: core.runtimeConfigLoading || core.status.loading,\n error: core.runtimeConfigError ?? core.status.error,\n refresh: core.refresh,\n }),\n [core.refresh, core.runtimeConfig?.conversionRules, core.runtimeConfigError, core.runtimeConfigLoading, core.products, core.status.error, core.status.loading, credits],\n );\n}\n\nexport interface BillingEntitlementsStateView {\n entitlements?: BillingEntitlementState;\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingEntitlements(): BillingEntitlementsStateView {\n const core = useRequiredCoreContext();\n const subscriptionContext = useOptionalContext(BillingSubscriptionContext);\n const entitlements =\n choose(subscriptionContext?.entitlements, core.entitlements) ??\n deriveBillingEntitlements(subscriptionContext?.subscription ?? core.subscription, core.products, core.credits, core.runtimeConfig);\n return useMemo(\n () => ({\n entitlements,\n loading: core.runtimeConfigLoading || core.status.loading,\n error: core.runtimeConfigError ?? core.status.error,\n refresh: core.refresh,\n }),\n [core.credits, core.products, core.refresh, core.runtimeConfig, core.runtimeConfigError, core.runtimeConfigLoading, core.status.error, core.status.loading, entitlements, subscriptionContext?.subscription, core.subscription],\n );\n}\n\nexport interface BillingPurchaseStatusView {\n purchaseStatus?: BillingPurchaseStatus;\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingPurchaseStatus(): BillingPurchaseStatusView {\n const core = useRequiredCoreContext();\n const productContext = useOptionalContext(BillingProductContext);\n const order = getLatestOrder(choose(productContext?.orderHistory, core.orderHistory));\n const payment = getLatestPayment(choose(productContext?.paymentHistory, core.paymentHistory));\n const purchaseStatus = core.purchaseStatus ?? normalizeBillingPurchaseStatus(undefined, order, payment);\n return useMemo(\n () => ({\n purchaseStatus,\n loading: core.runtimeConfigLoading || core.status.loading,\n error: core.runtimeConfigError ?? core.status.error,\n refresh: core.refresh,\n }),\n [core.purchaseStatus, core.refresh, core.runtimeConfigError, core.runtimeConfigLoading, core.status.error, core.status.loading, order, payment, purchaseStatus],\n );\n}\n\nexport interface BillingStatusView {\n status: BillingStatusState;\n}\n\nexport function useBillingStatus(): BillingStatusView {\n const core = useRequiredCoreContext();\n return useMemo(() => ({ status: core.status }), [core.status]);\n}\n\nexport interface BillingRefreshView {\n refresh: () => Promise<void>;\n}\n\nexport function useBillingRefresh(): BillingRefreshView {\n const core = useRequiredCoreContext();\n return useMemo(() => ({ refresh: core.refresh }), [core.refresh]);\n}\n\nexport interface BillingPipelineResult {\n run: (payload: BillingActionPayload) => Promise<void>;\n loading: boolean;\n error: string | null;\n purchaseStatus?: BillingPurchaseStatus;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingPipeline(options: BillingPipelineOptions = {}): BillingPipelineResult {\n const core = useRequiredCoreContext();\n const purchaseStatusView = useBillingPurchaseStatus();\n\n const run = useCallback(\n async (payload: BillingActionPayload) => {\n const prepared = options.onBeforeAction ? await options.onBeforeAction(payload) : payload;\n try {\n const result = await core.runAction(prepared);\n if (options.onAfterAction) {\n await options.onAfterAction({ redirectTo: result.redirectTo, nextAction: result.nextAction });\n }\n } catch (error) {\n if (options.onError) {\n await options.onError(error);\n }\n throw error;\n }\n },\n [core, options],\n );\n\n return useMemo(\n () => ({\n run,\n loading: core.status.loading || core.runtimeConfigLoading,\n error: core.status.error ?? core.runtimeConfigError,\n purchaseStatus: purchaseStatusView.purchaseStatus,\n refresh: core.refresh,\n }),\n [core.refresh, core.runtimeConfigError, core.runtimeConfigLoading, core.status.error, core.status.loading, purchaseStatusView.purchaseStatus, run],\n );\n}\n\nexport interface BillingActionHookResult {\n run: (payload: BillingActionPayload) => Promise<void>;\n loading: boolean;\n error: string | null;\n}\n\nfunction useBillingActionRunner(kind: BillingActionKind, defaults?: Partial<BillingActionPayload>): BillingActionHookResult {\n const pipeline = useBillingPipeline();\n const run = useCallback(\n async (payload: BillingActionPayload) => {\n await pipeline.run({\n ...defaults,\n ...payload,\n kind,\n });\n },\n [defaults, kind, pipeline],\n );\n\n return useMemo(\n () => ({\n run,\n loading: pipeline.loading,\n error: pipeline.error,\n }),\n [pipeline.error, pipeline.loading, run],\n );\n}\n\nexport function useSubscribePlan(): BillingActionHookResult {\n return useBillingActionRunner('subscribe');\n}\n\nexport function useManageSubscription(): BillingActionHookResult {\n return useBillingActionRunner('manage');\n}\n\nexport function useUpgradePlan(): BillingActionHookResult {\n return useBillingActionRunner('upgrade');\n}\n\nexport function useCancelSubscription(): BillingActionHookResult {\n return useBillingActionRunner('cancel');\n}\n\nexport function usePurchaseCredits(): BillingActionHookResult {\n return useBillingActionRunner('purchase');\n}\n\nexport function usePurchaseProduct(): BillingActionHookResult {\n return useBillingActionRunner('purchase');\n}\n\nexport interface BillingProductStateView {\n product?: BillingProductState;\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingProduct(productKey: string): BillingProductStateView {\n const productsState = useBillingProducts();\n const product = productsState.products.find((item) => item.productKey === productKey);\n return useMemo(\n () => ({\n product,\n loading: productsState.loading,\n error: productsState.error,\n refresh: productsState.refresh,\n }),\n [product, productsState.error, productsState.loading, productsState.refresh],\n );\n}\n\nexport function useBillingCatalogConfig(): BillingCatalogState {\n return useBillingCatalog();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAIA,SAAS,uBAAuB;AASvB;AAPF,SAAS,aAAa;AAAA,EAC3B;AAAA,EACA;AACF,GAGG;AACD,SAAO,oBAAC,mBAAgB,SAAmB,UAAS;AACtD;;;ACZA,SAAS,kBAAkB;AA8B3B,SAAS,eAAe,SAA0D;AAChF,QAAM,OAAO,SAAS;AACtB,QAAM,OAAO,MAAM,QAAQ;AAC3B,QAAM,kBAAkB,QAAQ,IAAI;AACpC,QAAM,UAAU,QAAQ,MAAM,OAAO;AACrC,QAAM,OAAiB,CAAC,kBAAkB,UAAU,UAAU,UAAU;AAExE,SAAO;AAAA,IACL,IAAI,MAAM,MAAM;AAAA,IAChB;AAAA,IACA,OAAO,MAAM,SAAS;AAAA,IACtB,OAA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C7E;AACF;AAEO,SAAS,0BAA+C;AAC7D,SAAO,kBAAkB;AAC3B;","names":["jsx"]}
1
+ {"version":3,"sources":["../../src/react/provider.tsx","../../src/react/hooks.ts","../../src/billing/react.tsx"],"sourcesContent":["'use client';\n\nimport type { ReactNode } from 'react';\nimport type { Session } from 'next-auth';\nimport { SessionProvider } from 'next-auth/react';\n\nexport function AuthProvider({\n children,\n session,\n}: {\n children: ReactNode;\n session?: Session | null;\n}) {\n return <SessionProvider session={session}>{children}</SessionProvider>;\n}\n","'use client';\n\nimport { useSession } from 'next-auth/react';\nimport { buildAuthJumpHref } from '../core/redirect';\nimport type { AuthSession } from '../next/options';\n\nexport type AuthRole = 'guest' | 'user' | 'admin';\n\nexport interface AuthUserSummary {\n id: string | null;\n name: string;\n email: string | null;\n image: string | null;\n isAuthenticated: boolean;\n isAdmin: boolean;\n tokenBalance: number;\n isVip: boolean;\n role: AuthRole;\n}\n\nexport interface AuthActions {\n loginHref: string;\n signupHref: string;\n logoutHref: string;\n accountHref: string;\n adminHref: string;\n}\n\nexport interface AuthActionsOptions {\n redirect?: string | null;\n}\n\nfunction getUserSummary(session: AuthSession | null | undefined): AuthUserSummary {\n const user = session?.user;\n const name = user?.name || '登录';\n const isAuthenticated = Boolean(user);\n const isAdmin = Boolean(user?.isAdmin);\n const role: AuthRole = !isAuthenticated ? 'guest' : isAdmin ? 'admin' : 'user';\n\n return {\n id: user?.id ?? null,\n name,\n email: user?.email ?? null,\n image: user?.image ?? null,\n isAuthenticated,\n isAdmin,\n tokenBalance: Number(user?.tokenBalance ?? 2580),\n isVip: Boolean(user?.isVip ?? true),\n role,\n };\n}\n\nexport function useAuthSession() {\n return useSession() as ReturnType<typeof useSession> & {\n data: AuthSession | null | undefined;\n };\n}\n\nexport function useAuthUser(): AuthUserSummary {\n const { data: session } = useAuthSession();\n return getUserSummary(session ?? null);\n}\n\nexport function useAuthRole(): AuthRole {\n return useAuthUser().role;\n}\n\nexport function useAuthActions(options: AuthActionsOptions = {}): AuthActions {\n const user = useAuthUser();\n const redirect = options.redirect ?? null;\n\n return {\n loginHref: buildAuthJumpHref('login', redirect ?? undefined),\n signupHref: buildAuthJumpHref('signup', redirect ?? undefined),\n logoutHref: '/logout',\n accountHref: '/user/account',\n adminHref: '/admin',\n };\n}\n","'use client';\n\nimport {\n type Context,\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n type ReactNode,\n} from 'react';\n\nimport {\n buildBillingActionPayload,\n deriveBillingCreditsState,\n deriveBillingEntitlements,\n normalizeBillingPurchaseStatus,\n normalizeBillingCatalogConfig,\n normalizeBillingRuntimeConfig,\n resolveBillingItem,\n resolveBillingProductSnapshot,\n resolveBillingSubscriptionProduct,\n} from './runtime';\nimport type {\n BillingActionExecutor,\n BillingActionKind,\n BillingActionPayload,\n BillingApiClient,\n BillingCatalogConfig,\n BillingCoreContextValue,\n BillingCreditsContextValue,\n BillingCreditsState,\n BillingDefaults,\n BillingEntitlementState,\n BillingLoaders,\n BillingOrderHistoryItem,\n BillingPaymentHistoryItem,\n BillingItem,\n BillingProductState,\n BillingProductContextValue,\n BillingProductSnapshot,\n BillingPurchaseStatus,\n BillingRuntimeConfig,\n BillingStatusState,\n BillingSubscriptionContextValue,\n BillingSubscriptionHistoryItem,\n BillingSubscriptionPurchaseConfig,\n BillingSubscriptionState,\n BillingProductPurchaseConfig,\n} from './types';\n\nexport interface BillingProviderProps {\n children: ReactNode;\n apiClient: BillingApiClient;\n loaders?: BillingLoaders;\n runtimeConfigLoader?: BillingLoaders['runtimeConfigLoader'];\n actionExecutor?: BillingActionExecutor;\n defaults?: BillingDefaults;\n runtimeConfig?: BillingRuntimeConfig | BillingCatalogConfig;\n subscription?: BillingSubscriptionState;\n subscriptionHistory?: BillingSubscriptionHistoryItem[];\n products?: BillingProductState[];\n orderHistory?: BillingOrderHistoryItem[];\n paymentHistory?: BillingPaymentHistoryItem[];\n credits?: BillingCreditsState;\n entitlements?: BillingEntitlementState;\n status?: BillingStatusState;\n purchaseStatus?: BillingPurchaseStatus;\n autoRefresh?: boolean;\n}\n\nexport type BillingCoreProviderProps = BillingProviderProps;\nexport interface BillingSubscriptionProviderProps {\n children: ReactNode;\n availablePlans?: BillingItem[];\n subscription?: BillingSubscriptionState;\n subscriptionHistory?: BillingSubscriptionHistoryItem[];\n entitlements?: BillingEntitlementState;\n status?: BillingStatusState;\n}\n\nexport interface BillingProductProviderProps {\n children: ReactNode;\n availableProducts?: BillingItem[];\n products?: BillingProductState[];\n orderHistory?: BillingOrderHistoryItem[];\n paymentHistory?: BillingPaymentHistoryItem[];\n status?: BillingStatusState;\n}\n\nexport interface BillingCreditsProviderProps {\n children: ReactNode;\n credits?: BillingCreditsState;\n status?: BillingStatusState;\n}\n\nexport interface BillingPipelineOptions {\n onBeforeAction?: (payload: BillingActionPayload) => Promise<BillingActionPayload>;\n onAfterAction?: (result: { redirectTo?: string; nextAction?: string }) => Promise<void>;\n onError?: (error: unknown) => Promise<void>;\n}\n\nconst BillingCoreContext = createContext<BillingCoreContextValue | null>(null);\nconst BillingSubscriptionContext = createContext<BillingSubscriptionContextValue | null>(null);\nconst BillingProductContext = createContext<BillingProductContextValue | null>(null);\nconst BillingCreditsContext = createContext<BillingCreditsContextValue | null>(null);\n\nfunction useOptionalContext<T>(context: Context<T | null>): T | null {\n return useContext(context);\n}\n\nfunction useRequiredCoreContext(): BillingCoreContextValue {\n const context = useContext(BillingCoreContext);\n if (!context) {\n throw new Error('Billing hooks must be used inside BillingProvider or BillingCoreProvider.');\n }\n return context;\n}\n\nfunction choose<T>(primary: T | undefined, fallback: T | undefined): T | undefined {\n return primary ?? fallback;\n}\n\nfunction getLatestOrder(orders: BillingOrderHistoryItem[] | undefined): BillingOrderHistoryItem | undefined {\n return [...(orders ?? [])].sort((a, b) => {\n const left = Date.parse(b.updatedAt ?? b.createdAt ?? '') || 0;\n const right = Date.parse(a.updatedAt ?? a.createdAt ?? '') || 0;\n return left - right;\n })[0];\n}\n\nfunction getLatestPayment(payments: BillingPaymentHistoryItem[] | undefined): BillingPaymentHistoryItem | undefined {\n return [...(payments ?? [])].sort((a, b) => {\n const left = Date.parse(b.updatedAt ?? b.createdAt ?? '') || 0;\n const right = Date.parse(a.updatedAt ?? a.createdAt ?? '') || 0;\n return left - right;\n })[0];\n}\n\nfunction normalizeRuntimeConfigInput(config?: BillingRuntimeConfig | BillingCatalogConfig | null): BillingRuntimeConfig | undefined {\n if (!config) return undefined;\n return normalizeBillingRuntimeConfig(config);\n}\n\nfunction normalizeCatalogConfigInput(config?: BillingRuntimeConfig | BillingCatalogConfig | null): BillingCatalogConfig | undefined {\n if (!config) return undefined;\n return normalizeBillingCatalogConfig(config);\n}\n\nfunction buildCoreValue(input: {\n apiClient: BillingApiClient;\n loaders?: BillingLoaders;\n runtimeConfigLoader?: BillingLoaders['runtimeConfigLoader'];\n actionExecutor?: BillingActionExecutor;\n defaults?: BillingDefaults;\n runtimeConfig?: BillingRuntimeConfig | BillingCatalogConfig;\n runtimeCatalog?: BillingCatalogConfig;\n runtimeConfigLoading: boolean;\n runtimeConfigError: string | null;\n subscription?: BillingSubscriptionState;\n subscriptionHistory?: BillingSubscriptionHistoryItem[];\n products?: BillingProductState[];\n orderHistory?: BillingOrderHistoryItem[];\n paymentHistory?: BillingPaymentHistoryItem[];\n credits?: BillingCreditsState;\n entitlements?: BillingEntitlementState;\n purchaseStatus?: BillingPurchaseStatus;\n status: BillingStatusState;\n refresh: () => Promise<void>;\n runAction: (payload: BillingActionPayload) => Promise<{\n redirectTo?: string;\n nextAction?: string;\n status?: 'pending' | 'succeeded' | 'failed';\n }>;\n setRuntimeConfig: (config?: BillingRuntimeConfig) => void;\n setSubscription: (value?: BillingSubscriptionState) => void;\n setSubscriptionHistory: (value?: BillingSubscriptionHistoryItem[]) => void;\n setProducts: (value?: BillingProductState[]) => void;\n setOrderHistory: (value?: BillingOrderHistoryItem[]) => void;\n setPaymentHistory: (value?: BillingPaymentHistoryItem[]) => void;\n setCredits: (value?: BillingCreditsState) => void;\n setEntitlements: (value?: BillingEntitlementState) => void;\n setPurchaseStatus: (status?: BillingPurchaseStatus) => void;\n setStatus: (status: BillingStatusState | ((current: BillingStatusState) => BillingStatusState)) => void;\n}): BillingCoreContextValue {\n return {\n apiClient: input.apiClient,\n loaders: input.loaders,\n runtimeConfigLoader: input.runtimeConfigLoader,\n actionExecutor: input.actionExecutor,\n defaults: input.defaults,\n runtimeConfig: input.runtimeConfig,\n runtimeCatalog: input.runtimeCatalog,\n runtimeConfigLoading: input.runtimeConfigLoading,\n runtimeConfigError: input.runtimeConfigError,\n subscription: input.subscription,\n subscriptionHistory: input.subscriptionHistory,\n products: input.products,\n orderHistory: input.orderHistory,\n paymentHistory: input.paymentHistory,\n credits: input.credits,\n entitlements: input.entitlements,\n purchaseStatus: input.purchaseStatus,\n status: input.status,\n refresh: input.refresh,\n runAction: input.runAction,\n setRuntimeConfig: input.setRuntimeConfig,\n setSubscription: input.setSubscription,\n setSubscriptionHistory: input.setSubscriptionHistory,\n setProducts: input.setProducts,\n setOrderHistory: input.setOrderHistory,\n setPaymentHistory: input.setPaymentHistory,\n setCredits: input.setCredits,\n setEntitlements: input.setEntitlements,\n setPurchaseStatus: input.setPurchaseStatus,\n setStatus: input.setStatus,\n };\n}\n\nexport function BillingProvider({\n children,\n apiClient,\n loaders,\n runtimeConfigLoader,\n actionExecutor,\n defaults,\n runtimeConfig: runtimeConfigProp,\n subscription: subscriptionProp,\n subscriptionHistory: subscriptionHistoryProp,\n products: productsProp,\n orderHistory: orderHistoryProp,\n paymentHistory: paymentHistoryProp,\n credits: creditsProp,\n entitlements: entitlementsProp,\n status: statusProp,\n purchaseStatus: purchaseStatusProp,\n autoRefresh = true,\n}: BillingProviderProps) {\n const [runtimeConfig, setRuntimeConfig] = useState<BillingRuntimeConfig | undefined>(normalizeRuntimeConfigInput(runtimeConfigProp));\n const [runtimeCatalog, setRuntimeCatalog] = useState<BillingCatalogConfig | undefined>(normalizeCatalogConfigInput(runtimeConfigProp));\n const [runtimeConfigLoading, setRuntimeConfigLoading] = useState(false);\n const [runtimeConfigError, setRuntimeConfigError] = useState<string | null>(null);\n const [subscription, setSubscription] = useState<BillingSubscriptionState | undefined>(subscriptionProp);\n const [subscriptionHistory, setSubscriptionHistory] = useState<BillingSubscriptionHistoryItem[] | undefined>(subscriptionHistoryProp);\n const [products, setProducts] = useState<BillingProductState[] | undefined>(productsProp);\n const [orderHistory, setOrderHistory] = useState<BillingOrderHistoryItem[] | undefined>(orderHistoryProp);\n const [paymentHistory, setPaymentHistory] = useState<BillingPaymentHistoryItem[] | undefined>(paymentHistoryProp);\n const [credits, setCredits] = useState<BillingCreditsState | undefined>(creditsProp);\n const [entitlements, setEntitlements] = useState<BillingEntitlementState | undefined>(entitlementsProp);\n const [purchaseStatus, setPurchaseStatus] = useState<BillingPurchaseStatus | undefined>(purchaseStatusProp);\n const [status, setStatus] = useState<BillingStatusState>(\n statusProp ?? { loading: false, refreshing: false, error: null },\n );\n\n useEffect(() => {\n if (runtimeConfigProp) {\n setRuntimeConfig(normalizeRuntimeConfigInput(runtimeConfigProp));\n setRuntimeCatalog(normalizeCatalogConfigInput(runtimeConfigProp));\n }\n }, [runtimeConfigProp]);\n\n useEffect(() => {\n if (subscriptionProp) setSubscription(subscriptionProp);\n }, [subscriptionProp]);\n\n useEffect(() => {\n if (subscriptionHistoryProp) setSubscriptionHistory(subscriptionHistoryProp);\n }, [subscriptionHistoryProp]);\n\n useEffect(() => {\n if (productsProp) setProducts(productsProp);\n }, [productsProp]);\n\n useEffect(() => {\n if (orderHistoryProp) setOrderHistory(orderHistoryProp);\n }, [orderHistoryProp]);\n\n useEffect(() => {\n if (paymentHistoryProp) setPaymentHistory(paymentHistoryProp);\n }, [paymentHistoryProp]);\n\n useEffect(() => {\n if (creditsProp) setCredits(creditsProp);\n }, [creditsProp]);\n\n useEffect(() => {\n if (entitlementsProp) setEntitlements(entitlementsProp);\n }, [entitlementsProp]);\n\n useEffect(() => {\n if (purchaseStatusProp) setPurchaseStatus(purchaseStatusProp);\n }, [purchaseStatusProp]);\n\n useEffect(() => {\n if (statusProp) setStatus(statusProp);\n }, [statusProp]);\n\n const refresh = useCallback(async () => {\n const catalogKey = runtimeCatalog?.catalogKey ?? runtimeConfig?.catalogKey ?? 'default';\n const runtimeLoader = runtimeConfigLoader ?? apiClient.fetchRuntimeConfig;\n const resolvedLoaders = loaders ?? {};\n const subscriptionLoader = resolvedLoaders.subscriptionLoader ?? apiClient.fetchSubscription;\n const subscriptionHistoryLoader = resolvedLoaders.subscriptionHistoryLoader ?? apiClient.fetchSubscriptionHistory;\n const productsLoader = resolvedLoaders.productsLoader ?? apiClient.fetchProducts;\n const orderHistoryLoader = resolvedLoaders.orderHistoryLoader ?? apiClient.fetchOrderHistory;\n const paymentHistoryLoader = resolvedLoaders.paymentHistoryLoader ?? apiClient.fetchPaymentHistory;\n const purchaseStatusLoader = resolvedLoaders.purchaseStatusLoader ?? apiClient.fetchPurchaseStatus;\n const creditsLoader = resolvedLoaders.creditsLoader ?? apiClient.fetchCredits;\n const entitlementsLoader = resolvedLoaders.entitlementsLoader ?? apiClient.fetchEntitlements;\n\n setRuntimeConfigLoading(true);\n setRuntimeConfigError(null);\n setStatus((current) => ({ ...current, loading: true, refreshing: true, error: null }));\n\n try {\n const nextRuntimeCatalog = normalizeCatalogConfigInput(await runtimeLoader(catalogKey));\n const nextRuntimeConfig = nextRuntimeCatalog ? normalizeRuntimeConfigInput(nextRuntimeCatalog) : undefined;\n if (nextRuntimeConfig) {\n setRuntimeCatalog(nextRuntimeCatalog);\n setRuntimeConfig(nextRuntimeConfig);\n }\n\n const nextCatalogKey = nextRuntimeConfig?.catalogKey ?? nextRuntimeCatalog?.catalogKey ?? catalogKey;\n\n const [\n nextSubscription,\n nextSubscriptionHistory,\n nextProducts,\n nextOrderHistory,\n nextPaymentHistory,\n nextCredits,\n nextEntitlements,\n ] = await Promise.all([\n subscriptionLoader({ catalogKey: nextCatalogKey }),\n subscriptionHistoryLoader({ catalogKey: nextCatalogKey }),\n productsLoader({ catalogKey: nextCatalogKey }),\n orderHistoryLoader({ catalogKey: nextCatalogKey }),\n paymentHistoryLoader({ catalogKey: nextCatalogKey }),\n creditsLoader({ catalogKey: nextCatalogKey }),\n entitlementsLoader({ catalogKey: nextCatalogKey }),\n ]);\n\n const subscriptionWithProduct = nextSubscription\n ? {\n ...nextSubscription,\n product: resolveBillingSubscriptionProduct(nextSubscription, nextRuntimeConfig ?? runtimeConfig),\n }\n : undefined;\n const normalizedCredits = deriveBillingCreditsState(nextCredits, nextProducts, nextRuntimeConfig?.conversionRules ?? runtimeConfig?.conversionRules);\n const normalizedEntitlements = nextEntitlements ?? deriveBillingEntitlements(subscriptionWithProduct, nextProducts, normalizedCredits, nextRuntimeConfig ?? runtimeConfig);\n const latestOrder = getLatestOrder(nextOrderHistory);\n const latestPayment = getLatestPayment(nextPaymentHistory);\n const fetchedPurchaseStatus = await purchaseStatusLoader({\n orderId: latestOrder?.orderId,\n paymentId: latestPayment?.paymentId,\n transactionId: latestPayment?.transactionId ?? latestOrder?.transactionId,\n }).catch(() => undefined);\n const normalizedPurchaseStatus = normalizeBillingPurchaseStatus(\n fetchedPurchaseStatus,\n latestOrder,\n latestPayment,\n );\n\n setSubscription(subscriptionWithProduct);\n setSubscriptionHistory(nextSubscriptionHistory);\n setProducts(nextProducts);\n setOrderHistory(nextOrderHistory);\n setPaymentHistory(nextPaymentHistory);\n setCredits(normalizedCredits);\n setEntitlements(normalizedEntitlements);\n setPurchaseStatus(normalizedPurchaseStatus);\n setStatus({ loading: false, refreshing: false, error: null, lastFetchedAt: new Date().toISOString() });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n setRuntimeConfigError(message);\n setStatus((current) => ({ ...current, loading: false, refreshing: false, error: message }));\n } finally {\n setRuntimeConfigLoading(false);\n }\n }, [apiClient, loaders, runtimeConfig, runtimeConfigLoader, runtimeCatalog]);\n\n const runAction = useCallback(\n async (payload: BillingActionPayload) => {\n const prepared = buildBillingActionPayload(payload, runtimeConfig);\n const executor = actionExecutor ?? ((input: BillingActionPayload) => apiClient.createAction(input));\n\n setPurchaseStatus((current) => ({\n actionKey: prepared.key,\n orderId: current?.orderId,\n paymentId: current?.paymentId,\n transactionId: current?.transactionId,\n status: 'pending',\n redirectTo: current?.redirectTo,\n updatedAt: new Date().toISOString(),\n }));\n setStatus((current) => ({ ...current, loading: true, refreshing: true, error: null }));\n\n try {\n const result = await executor(prepared);\n setPurchaseStatus((current) => ({\n actionKey: prepared.key,\n orderId: current?.orderId,\n paymentId: current?.paymentId,\n transactionId: current?.transactionId,\n status: result.status === 'failed' ? 'failed' : result.status === 'succeeded' ? 'paid' : 'pending',\n redirectTo: result.redirectTo ?? current?.redirectTo,\n updatedAt: new Date().toISOString(),\n }));\n if (result.redirectTo || result.nextAction) {\n // host handles the redirect/next action, we only persist the result\n }\n await refresh();\n return result;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n setPurchaseStatus((current) => ({\n actionKey: prepared.key,\n orderId: current?.orderId,\n paymentId: current?.paymentId,\n transactionId: current?.transactionId,\n status: 'failed',\n redirectTo: current?.redirectTo,\n updatedAt: new Date().toISOString(),\n }));\n setStatus((current) => ({ ...current, loading: false, refreshing: false, error: message }));\n throw error;\n }\n },\n [actionExecutor, apiClient, refresh, runtimeConfig],\n );\n\n useEffect(() => {\n if (!autoRefresh) return;\n if (runtimeConfigLoading) return;\n if (!runtimeConfig && !runtimeConfigError) {\n void refresh();\n }\n }, [autoRefresh, refresh, runtimeConfig, runtimeConfigError, runtimeConfigLoading]);\n\n const coreValue = useMemo(\n () =>\n buildCoreValue({\n apiClient,\n loaders,\n runtimeConfigLoader,\n actionExecutor,\n defaults,\n runtimeConfig,\n runtimeCatalog,\n runtimeConfigLoading,\n runtimeConfigError,\n subscription,\n subscriptionHistory,\n products,\n orderHistory,\n paymentHistory,\n credits,\n entitlements,\n purchaseStatus,\n status,\n refresh,\n runAction,\n setRuntimeConfig,\n setSubscription,\n setSubscriptionHistory,\n setProducts,\n setOrderHistory,\n setPaymentHistory,\n setCredits,\n setEntitlements,\n setPurchaseStatus,\n setStatus,\n }),\n [\n actionExecutor,\n apiClient,\n credits,\n defaults,\n entitlements,\n orderHistory,\n paymentHistory,\n products,\n purchaseStatus,\n refresh,\n runAction,\n runtimeConfig,\n runtimeConfigError,\n runtimeConfigLoader,\n runtimeConfigLoading,\n runtimeCatalog,\n loaders,\n status,\n subscription,\n subscriptionHistory,\n ],\n );\n\n return (\n <BillingCoreContext.Provider value={coreValue}>\n <SubscriptionProvider subscription={subscription} subscriptionHistory={subscriptionHistory} entitlements={entitlements} status={status}>\n <ProductProvider products={products} orderHistory={orderHistory} paymentHistory={paymentHistory} status={status}>\n <CreditsProvider credits={credits} status={status}>{children}</CreditsProvider>\n </ProductProvider>\n </SubscriptionProvider>\n </BillingCoreContext.Provider>\n );\n}\n\nexport function BillingCoreProvider(props: BillingCoreProviderProps) {\n return <BillingProvider {...props} />;\n}\n\nexport function SubscriptionProvider({\n children,\n availablePlans,\n subscription,\n subscriptionHistory,\n entitlements,\n status,\n}: BillingSubscriptionProviderProps) {\n const core = useOptionalContext(BillingCoreContext);\n const value = useMemo<BillingSubscriptionContextValue>(\n () => ({\n availablePlans: choose(availablePlans, core?.runtimeConfig?.items?.filter((item) => item.kind === 'subscription')),\n subscription: choose(subscription, core?.subscription),\n subscriptionHistory: choose(subscriptionHistory, core?.subscriptionHistory),\n entitlements: choose(entitlements, core?.entitlements),\n status: choose(status, core?.status),\n }),\n [availablePlans, core?.entitlements, core?.runtimeConfig?.items, core?.status, core?.subscription, core?.subscriptionHistory, entitlements, status, subscription, subscriptionHistory],\n );\n\n return <BillingSubscriptionContext.Provider value={value}>{children}</BillingSubscriptionContext.Provider>;\n}\n\nexport function ProductProvider({\n children,\n availableProducts,\n products,\n orderHistory,\n paymentHistory,\n status,\n}: BillingProductProviderProps) {\n const core = useOptionalContext(BillingCoreContext);\n const value = useMemo<BillingProductContextValue>(\n () => ({\n availableProducts: choose(availableProducts, core?.runtimeConfig?.items?.filter((item) => item.kind === 'product')),\n products: choose(products, core?.products),\n orderHistory: choose(orderHistory, core?.orderHistory),\n paymentHistory: choose(paymentHistory, core?.paymentHistory),\n status: choose(status, core?.status),\n }),\n [availableProducts, core?.orderHistory, core?.paymentHistory, core?.products, core?.runtimeConfig?.items, core?.status, orderHistory, paymentHistory, products, status],\n );\n\n return <BillingProductContext.Provider value={value}>{children}</BillingProductContext.Provider>;\n}\n\nexport function CreditsProvider({ children, credits, status }: BillingCreditsProviderProps) {\n const core = useOptionalContext(BillingCoreContext);\n const value = useMemo<BillingCreditsContextValue>(\n () => ({\n credits: choose(credits, core?.credits),\n status: choose(status, core?.status),\n }),\n [credits, core?.credits, core?.status, status],\n );\n\n return <BillingCreditsContext.Provider value={value}>{children}</BillingCreditsContext.Provider>;\n}\n\nexport interface BillingCatalogState {\n catalog?: BillingRuntimeConfig | BillingCatalogConfig;\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingContext(): BillingCoreContextValue {\n return useRequiredCoreContext();\n}\n\nexport function useBillingCatalog(): BillingCatalogState {\n const core = useRequiredCoreContext();\n return useMemo(\n () => ({\n catalog: core.runtimeCatalog ?? core.runtimeConfig,\n loading: core.runtimeConfigLoading,\n error: core.runtimeConfigError,\n refresh: core.refresh,\n }),\n [core.refresh, core.runtimeCatalog, core.runtimeConfig, core.runtimeConfigError, core.runtimeConfigLoading],\n );\n}\n\nexport interface BillingItemState {\n item?: BillingProductSnapshot;\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingItem(itemKey: string): BillingItemState {\n const core = useRequiredCoreContext();\n return useMemo(() => {\n const item = resolveBillingItem(core.runtimeConfig?.items, itemKey);\n return {\n item: resolveBillingProductSnapshot(item),\n loading: core.runtimeConfigLoading,\n error: core.runtimeConfigError,\n refresh: core.refresh,\n };\n }, [core.refresh, core.runtimeConfig?.items, core.runtimeConfigError, core.runtimeConfigLoading, itemKey]);\n}\n\nexport interface BillingProductsState {\n products: BillingProductState[];\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingProducts(): BillingProductsState {\n const core = useRequiredCoreContext();\n const productContext = useOptionalContext(BillingProductContext);\n const products = choose(productContext?.products, core.products) ?? [];\n return useMemo(\n () => ({\n products,\n loading: core.runtimeConfigLoading || core.status.loading,\n error: core.runtimeConfigError ?? core.status.error,\n refresh: core.refresh,\n }),\n [core.refresh, core.runtimeConfigError, core.runtimeConfigLoading, core.status.error, core.status.loading, products],\n );\n}\n\nexport interface BillingAvailablePlansState {\n plans: BillingItem[];\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingAvailablePlans(): BillingAvailablePlansState {\n const core = useRequiredCoreContext();\n const subscriptionContext = useOptionalContext(BillingSubscriptionContext);\n const plans = choose(subscriptionContext?.availablePlans, core.runtimeConfig?.items?.filter((item) => item.kind === 'subscription')) ?? [];\n return useMemo(\n () => ({\n plans,\n loading: core.runtimeConfigLoading || core.status.loading,\n error: core.runtimeConfigError ?? core.status.error,\n refresh: core.refresh,\n }),\n [core.refresh, core.runtimeConfig?.items, core.runtimeConfigError, core.runtimeConfigLoading, core.status.error, core.status.loading, plans],\n );\n}\n\nexport interface BillingAvailableProductsState {\n items: BillingItem[];\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingAvailableProducts(): BillingAvailableProductsState {\n const core = useRequiredCoreContext();\n const productContext = useOptionalContext(BillingProductContext);\n const items = choose(productContext?.availableProducts, core.runtimeConfig?.items?.filter((item) => item.kind === 'product')) ?? [];\n return useMemo(\n () => ({\n items,\n loading: core.runtimeConfigLoading || core.status.loading,\n error: core.runtimeConfigError ?? core.status.error,\n refresh: core.refresh,\n }),\n [core.refresh, core.runtimeConfig?.items, core.runtimeConfigError, core.runtimeConfigLoading, core.status.error, core.status.loading, items],\n );\n}\n\nexport interface BillingOrderHistoryState {\n orders: BillingOrderHistoryItem[];\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingOrderHistory(_options: { userId?: string; catalogKey?: string; productKey?: string } = {}): BillingOrderHistoryState {\n const core = useRequiredCoreContext();\n const productContext = useOptionalContext(BillingProductContext);\n const orders = choose(productContext?.orderHistory, core.orderHistory) ?? [];\n return useMemo(\n () => ({\n orders,\n loading: core.runtimeConfigLoading || core.status.loading,\n error: core.runtimeConfigError ?? core.status.error,\n refresh: core.refresh,\n }),\n [core.refresh, core.runtimeConfigError, core.runtimeConfigLoading, core.status.error, core.status.loading, orders],\n );\n}\n\nexport interface BillingPaymentHistoryState {\n payments: BillingPaymentHistoryItem[];\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingPaymentHistory(_options: { userId?: string; catalogKey?: string } = {}): BillingPaymentHistoryState {\n const core = useRequiredCoreContext();\n const productContext = useOptionalContext(BillingProductContext);\n const payments = choose(productContext?.paymentHistory, core.paymentHistory) ?? [];\n return useMemo(\n () => ({\n payments,\n loading: core.runtimeConfigLoading || core.status.loading,\n error: core.runtimeConfigError ?? core.status.error,\n refresh: core.refresh,\n }),\n [core.refresh, core.runtimeConfigError, core.runtimeConfigLoading, core.status.error, core.status.loading, payments],\n );\n}\n\nexport interface BillingSubscriptionStateView {\n subscription?: BillingSubscriptionState;\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingSubscription(): BillingSubscriptionStateView {\n const core = useRequiredCoreContext();\n const subscriptionContext = useOptionalContext(BillingSubscriptionContext);\n return useMemo(\n () => ({\n subscription: choose(subscriptionContext?.subscription, core.subscription),\n loading: core.runtimeConfigLoading || core.status.loading,\n error: core.runtimeConfigError ?? core.status.error,\n refresh: core.refresh,\n }),\n [core.refresh, core.runtimeConfigError, core.runtimeConfigLoading, core.status.error, core.status.loading, core.subscription, subscriptionContext?.subscription],\n );\n}\n\nexport interface BillingSubscriptionProductState {\n product?: BillingProductSnapshot;\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingSubscriptionProduct(): BillingSubscriptionProductState {\n const core = useRequiredCoreContext();\n const subscriptionContext = useOptionalContext(BillingSubscriptionContext);\n const subscription = choose(subscriptionContext?.subscription, core.subscription);\n return useMemo(\n () => ({\n product: subscription?.product ?? resolveBillingSubscriptionProduct(subscription, core.runtimeConfig),\n loading: core.runtimeConfigLoading || core.status.loading,\n error: core.runtimeConfigError ?? core.status.error,\n refresh: core.refresh,\n }),\n [core.refresh, core.runtimeConfig, core.runtimeConfigError, core.runtimeConfigLoading, core.status.error, core.status.loading, subscription],\n );\n}\n\nexport interface BillingSubscriptionHistoryState {\n history: BillingSubscriptionHistoryItem[];\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingSubscriptionHistory(_options: { userId?: string; catalogKey?: string } = {}): BillingSubscriptionHistoryState {\n const core = useRequiredCoreContext();\n const subscriptionContext = useOptionalContext(BillingSubscriptionContext);\n const history = choose(subscriptionContext?.subscriptionHistory, core.subscriptionHistory) ?? [];\n return useMemo(\n () => ({\n history,\n loading: core.runtimeConfigLoading || core.status.loading,\n error: core.runtimeConfigError ?? core.status.error,\n refresh: core.refresh,\n }),\n [core.refresh, core.runtimeConfigError, core.runtimeConfigLoading, core.status.error, core.status.loading, history],\n );\n}\n\nexport interface BillingCreditsStateView {\n credits?: BillingCreditsState;\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingCredits(): BillingCreditsStateView {\n const core = useRequiredCoreContext();\n const creditsContext = useOptionalContext(BillingCreditsContext);\n const credits = choose(creditsContext?.credits, core.credits) ?? deriveBillingCreditsState(undefined, core.products, core.runtimeConfig?.conversionRules);\n return useMemo(\n () => ({\n credits,\n loading: core.runtimeConfigLoading || core.status.loading,\n error: core.runtimeConfigError ?? core.status.error,\n refresh: core.refresh,\n }),\n [core.refresh, core.runtimeConfig?.conversionRules, core.runtimeConfigError, core.runtimeConfigLoading, core.products, core.status.error, core.status.loading, credits],\n );\n}\n\nexport interface BillingEntitlementsStateView {\n entitlements?: BillingEntitlementState;\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingEntitlements(): BillingEntitlementsStateView {\n const core = useRequiredCoreContext();\n const subscriptionContext = useOptionalContext(BillingSubscriptionContext);\n const entitlements =\n choose(subscriptionContext?.entitlements, core.entitlements) ??\n deriveBillingEntitlements(subscriptionContext?.subscription ?? core.subscription, core.products, core.credits, core.runtimeConfig);\n return useMemo(\n () => ({\n entitlements,\n loading: core.runtimeConfigLoading || core.status.loading,\n error: core.runtimeConfigError ?? core.status.error,\n refresh: core.refresh,\n }),\n [core.credits, core.products, core.refresh, core.runtimeConfig, core.runtimeConfigError, core.runtimeConfigLoading, core.status.error, core.status.loading, entitlements, subscriptionContext?.subscription, core.subscription],\n );\n}\n\nexport interface BillingPurchaseStatusView {\n purchaseStatus?: BillingPurchaseStatus;\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingPurchaseStatus(): BillingPurchaseStatusView {\n const core = useRequiredCoreContext();\n const productContext = useOptionalContext(BillingProductContext);\n const order = getLatestOrder(choose(productContext?.orderHistory, core.orderHistory));\n const payment = getLatestPayment(choose(productContext?.paymentHistory, core.paymentHistory));\n const purchaseStatus = core.purchaseStatus ?? normalizeBillingPurchaseStatus(undefined, order, payment);\n return useMemo(\n () => ({\n purchaseStatus,\n loading: core.runtimeConfigLoading || core.status.loading,\n error: core.runtimeConfigError ?? core.status.error,\n refresh: core.refresh,\n }),\n [core.purchaseStatus, core.refresh, core.runtimeConfigError, core.runtimeConfigLoading, core.status.error, core.status.loading, order, payment, purchaseStatus],\n );\n}\n\nexport interface BillingStatusView {\n status: BillingStatusState;\n}\n\nexport function useBillingStatus(): BillingStatusView {\n const core = useRequiredCoreContext();\n return useMemo(() => ({ status: core.status }), [core.status]);\n}\n\nexport interface BillingRefreshView {\n refresh: () => Promise<void>;\n}\n\nexport function useBillingRefresh(): BillingRefreshView {\n const core = useRequiredCoreContext();\n return useMemo(() => ({ refresh: core.refresh }), [core.refresh]);\n}\n\nexport interface BillingPipelineResult {\n run: (payload: BillingActionPayload) => Promise<void>;\n loading: boolean;\n error: string | null;\n purchaseStatus?: BillingPurchaseStatus;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingPipeline(options: BillingPipelineOptions = {}): BillingPipelineResult {\n const core = useRequiredCoreContext();\n const purchaseStatusView = useBillingPurchaseStatus();\n\n const run = useCallback(\n async (payload: BillingActionPayload) => {\n const prepared = options.onBeforeAction ? await options.onBeforeAction(payload) : payload;\n try {\n const result = await core.runAction(prepared);\n if (options.onAfterAction) {\n await options.onAfterAction({ redirectTo: result.redirectTo, nextAction: result.nextAction });\n }\n } catch (error) {\n if (options.onError) {\n await options.onError(error);\n }\n throw error;\n }\n },\n [core, options],\n );\n\n return useMemo(\n () => ({\n run,\n loading: core.status.loading || core.runtimeConfigLoading,\n error: core.status.error ?? core.runtimeConfigError,\n purchaseStatus: purchaseStatusView.purchaseStatus,\n refresh: core.refresh,\n }),\n [core.refresh, core.runtimeConfigError, core.runtimeConfigLoading, core.status.error, core.status.loading, purchaseStatusView.purchaseStatus, run],\n );\n}\n\nexport interface BillingActionHookResult {\n run: (payload: BillingActionPayload) => Promise<void>;\n loading: boolean;\n error: string | null;\n}\n\nfunction useBillingActionRunner(kind: BillingActionKind, defaults?: Partial<BillingActionPayload>): BillingActionHookResult {\n const pipeline = useBillingPipeline();\n const run = useCallback(\n async (payload: BillingActionPayload) => {\n await pipeline.run({\n ...defaults,\n ...payload,\n kind,\n });\n },\n [defaults, kind, pipeline],\n );\n\n return useMemo(\n () => ({\n run,\n loading: pipeline.loading,\n error: pipeline.error,\n }),\n [pipeline.error, pipeline.loading, run],\n );\n}\n\nexport function useSubscribePlan(): BillingActionHookResult {\n return useBillingActionRunner('subscribe');\n}\n\nexport function useManageSubscription(): BillingActionHookResult {\n return useBillingActionRunner('manage');\n}\n\nexport function useUpgradePlan(): BillingActionHookResult {\n return useBillingActionRunner('upgrade');\n}\n\nexport function useCancelSubscription(): BillingActionHookResult {\n return useBillingActionRunner('cancel');\n}\n\nexport function usePurchaseProduct(): BillingActionHookResult {\n return useBillingActionRunner('purchase');\n}\n\nexport interface BillingProductStateView {\n product?: BillingProductState;\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingProduct(productKey: string): BillingProductStateView {\n const productsState = useBillingProducts();\n const product = productsState.products.find((item) => item.productKey === productKey);\n return useMemo(\n () => ({\n product,\n loading: productsState.loading,\n error: productsState.error,\n refresh: productsState.refresh,\n }),\n [product, productsState.error, productsState.loading, productsState.refresh],\n );\n}\n\nexport function useBillingCatalogConfig(): BillingCatalogState {\n return useBillingCatalog();\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAIA,SAAS,uBAAuB;AASvB;AAPF,SAAS,aAAa;AAAA,EAC3B;AAAA,EACA;AACF,GAGG;AACD,SAAO,oBAAC,mBAAgB,SAAmB,UAAS;AACtD;;;ACZA,SAAS,kBAAkB;AA8B3B,SAAS,eAAe,SAA0D;AAChF,QAAM,OAAO,SAAS;AACtB,QAAM,OAAO,MAAM,QAAQ;AAC3B,QAAM,kBAAkB,QAAQ,IAAI;AACpC,QAAM,UAAU,QAAQ,MAAM,OAAO;AACrC,QAAM,OAAiB,CAAC,kBAAkB,UAAU,UAAU,UAAU;AAExE,SAAO;AAAA,IACL,IAAI,MAAM,MAAM;AAAA,IAChB;AAAA,IACA,OAAO,MAAM,SAAS;AAAA,IACtB,OAAO,MAAM,SAAS;AAAA,IACtB;AAAA,IACA;AAAA,IACA,cAAc,OAAO,MAAM,gBAAgB,IAAI;AAAA,IAC/C,OAAO,QAAQ,MAAM,SAAS,IAAI;AAAA,IAClC;AAAA,EACF;AACF;AAEO,SAAS,iBAAiB;AAC/B,SAAO,WAAW;AAGpB;AAEO,SAAS,cAA+B;AAC7C,QAAM,EA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A,QACH;AAAA,MACF,CAAC;AAAA,IACH;AAAA,IACA,CAAC,UAAU,MAAM,QAAQ;AAAA,EAC3B;AAEA,SAAO;AAAA,IACL,OAAO;AAAA,MACL;AAAA,MACA,SAAS,SAAS;AAAA,MAClB,OAAO,SAAS;AAAA,IAClB;AAAA,IACA,CAAC,SAAS,OAAO,SAAS,SAAS,GAAG;AAAA,EACxC;AACF;AAEO,SAAS,mBAA4C;AAC1D,SAAO,uBAAuB,WAAW;AAC3C;AAEO,SAAS,wBAAiD;AAC/D,SAAO,uBAAuB,QAAQ;AACxC;AAEO,SAAS,iBAA0C;AACxD,SAAO,uBAAuB,SAAS;AACzC;AAEO,SAAS,wBAAiD;AAC/D,SAAO,uBAAuB,QAAQ;AACxC;AAEO,SAAS,qBAA8C;AAC5D,SAAO,uBAAuB,UAAU;AAC1C;AASO,SAAS,kBAAkB,YAA6C;AAC7E,QAAM,gBAAgB,mBAAmB;AACzC,QAAM,UAAU,cAAc,SAAS,KAAK,CAAC,SAAS,KAAK,eAAe,UAAU;AACpF,SAAO;AAAA,IACL,OAAO;AAAA,MACL;AAAA,MACA,SAAS,cAAc;AAAA,MACvB,OAAO,cAAc;AAAA,MACrB,SAAS,cAAc;AAAA,IACzB;AAAA,IACA,CAAC,SAAS,cAAc,OAAO,cAAc,SAAS,cAAc,OAAO;AAAA,EAC7E;AACF;AAEO,SAAS,0BAA+C;AAC7D,SAAO,kBAAkB;AAC3B;","names":["jsx"]}
@@ -61,7 +61,7 @@ npx @foldspace-fe/casdoor-next-auth-kit@latest check
61
61
  - `useBillingSubscription` / `useBillingSubscriptionHistory` / `useBillingSubscriptionProduct` — 查看当前订阅、订阅历史和当前订阅对应产品
62
62
  - `useBillingProducts` / `useBillingProduct` / `useBillingOrderHistory` / `useBillingPaymentHistory` — 查看商品状态、订单历史和支付历史
63
63
  - `useBillingCredits` / `useBillingEntitlements` / `useBillingPurchaseStatus` — 查看额度、权益和归一化购买状态
64
- - `useSubscribePlan` / `usePurchaseProduct` / `usePurchaseCredits` 发起订阅、虚拟商品购买和积分购买动作
64
+ - `useSubscribePlan` / `usePurchaseProduct` — 发起订阅和商品购买动作
65
65
  - `useBillingRefresh` / `useBillingPipeline` — 刷新 billing 状态和编排动作执行链路
66
66
 
67
67
  ## 路由模型
@@ -78,6 +78,215 @@ npx @foldspace-fe/casdoor-next-auth-kit@latest check
78
78
 
79
79
  入口路由(login/signup)负责将用户引导至授权壳,授权壳在同源 iframe 或内嵌组件中渲染 Casdoor 界面,避免用户感知到离开宿主应用。
80
80
 
81
+ ## 宿主工程 `proxy.ts` 配置要求
82
+
83
+ `proxy.ts` 是宿主工程的 Next.js middleware(通常放在项目根目录,在 `next.config.ts` 中通过 `middleware` 字段指向),不属于 `@foldspace-fe/casdoor-next-auth-kit` 的受管文件。它的核心职责是**认证守卫**——拦截未登录用户对业务页面的访问,将其重定向到登录页;同时放行所有公开路径和认证流程路径。
84
+
85
+ ### `proxy.ts` 的核心职责
86
+
87
+ 1. **放行公开路径** — 无需认证即可访问的页面和资源
88
+ 2. **认证守卫** — 对非公开路径验证会话 token,未登录时重定向到 `/auth/login`
89
+ 3. **不在认证路径上做 origin 重写** — origin 规范由宿主的边缘层(FRP / Ingress / 网关)和套件内部的 API 代理头部清理共同完成
90
+
91
+ ### 公开路径清单
92
+
93
+ 以下路径必须放行,不做认证检查:
94
+
95
+ ```ts
96
+ const PUBLIC_PATH_PREFIXES = [
97
+ '/_next', // Next.js 静态资源
98
+ '/api', // 宿主自有 API(不含认证守卫)
99
+ '/auth/api', // Casdoor API 代理(套件内部转发已做头部清理)
100
+ '/auth/login', // 登录入口
101
+ '/auth/signup', // 注册入口
102
+ '/login/oauth/authorize', // 登录授权壳
103
+ '/signup/oauth/authorize', // 注册授权壳
104
+ '/logout', // 注销
105
+ '/callback', // OAuth 回调
106
+ ];
107
+ ```
108
+
109
+ 以下精确路径也应放行:
110
+
111
+ ```ts
112
+ const PUBLIC_EXACT_PATHS = new Set([
113
+ '/',
114
+ '/favicon.ico',
115
+ '/robots.txt',
116
+ '/sitemap.xml',
117
+ '/manifest.json',
118
+ // 以及宿主业务需要的公开页面
119
+ ]);
120
+ ```
121
+
122
+ 静态资源文件(`.png`、`.jpg`、`.svg`、`.css`、`.js` 等)也应放行。
123
+
124
+ ### 会话 token 提取
125
+
126
+ `proxy.ts` 需要从 cookie 中提取 NextAuth 会话 token。套件导出了 `decodeSessionToken` 供宿主使用:
127
+
128
+ ```ts
129
+ import { decodeSessionToken } from '@foldspace-fe/casdoor-next-auth-kit';
130
+
131
+ const token = getSessionTokenFromCookies(request);
132
+ if (!token) {
133
+ // 重定向到登录页
134
+ }
135
+
136
+ const decoded = await decodeSessionToken({
137
+ token,
138
+ secret: process.env.NEXTAUTH_SECRET || 'dev-nextauth-secret',
139
+ });
140
+ if (!decoded) {
141
+ // token 无效或过期,重定向到登录页
142
+ }
143
+ ```
144
+
145
+ cookie 名称按优先级提取:
146
+
147
+ 1. `__Secure-next-auth.session-token`(生产环境,cookie secure 模式)
148
+ 2. `next-auth.session-token`(开发环境)
149
+ 3. 分片 cookie(`next-auth.session-token.0`、`.1`、…,按数字排序拼接)
150
+
151
+ ### 推荐的完整实现
152
+
153
+ ```ts
154
+ import { NextRequest, NextResponse } from 'next/server';
155
+ import { decodeSessionToken } from '@foldspace-fe/casdoor-next-auth-kit';
156
+
157
+ function getAppOrigin() {
158
+ const appUrl = process.env.APP_URL || process.env.NEXTAUTH_URL || '';
159
+ if (!appUrl) return null;
160
+ try { return new URL(appUrl).origin; } catch { return null; }
161
+ }
162
+
163
+ const PUBLIC_PATH_PREFIXES = [
164
+ '/_next',
165
+ '/api',
166
+ '/auth/api',
167
+ '/auth/login',
168
+ '/auth/signup',
169
+ '/login/oauth/authorize',
170
+ '/signup/oauth/authorize',
171
+ '/logout',
172
+ '/callback',
173
+ ];
174
+
175
+ const PUBLIC_EXACT_PATHS = new Set([
176
+ '/favicon.ico',
177
+ '/robots.txt',
178
+ '/sitemap.xml',
179
+ '/manifest.json',
180
+ ]);
181
+
182
+ function isPublicPath(pathname: string) {
183
+ if (pathname === '/') return true;
184
+ if (PUBLIC_EXACT_PATHS.has(pathname)) return true;
185
+ if (/\.(png|jpg|jpeg|svg|gif|webp|ico|css|js)$/.test(pathname)) return true;
186
+ if (pathname === '/static' || pathname.startsWith('/static/')) return true;
187
+ return PUBLIC_PATH_PREFIXES.some(
188
+ (prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`),
189
+ );
190
+ }
191
+
192
+ function getSessionTokenFromCookies(request: NextRequest): string | null {
193
+ const secureBaseName = '__Secure-next-auth.session-token';
194
+ const baseName = 'next-auth.session-token';
195
+
196
+ const direct =
197
+ request.cookies.get(secureBaseName)?.value ||
198
+ request.cookies.get(baseName)?.value;
199
+ if (direct) return direct;
200
+
201
+ const chunkCandidates = request.cookies
202
+ .getAll()
203
+ .filter((c) => c.name.startsWith(`${secureBaseName}.`) || c.name.startsWith(`${baseName}.`))
204
+ .sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }));
205
+
206
+ if (chunkCandidates.length === 0) return null;
207
+ return chunkCandidates.map((c) => c.value).join('');
208
+ }
209
+
210
+ export async function proxy(request: NextRequest) {
211
+ const { pathname, search } = request.nextUrl;
212
+
213
+ if (isPublicPath(pathname)) {
214
+ return NextResponse.next();
215
+ }
216
+
217
+ const token = getSessionTokenFromCookies(request);
218
+ if (!token) {
219
+ const loginUrl = new URL('/auth/login', request.url);
220
+ loginUrl.searchParams.set('redirect', `${pathname}${search}`);
221
+ return NextResponse.redirect(loginUrl);
222
+ }
223
+
224
+ const decoded = await decodeSessionToken({
225
+ token,
226
+ secret: process.env.NEXTAUTH_SECRET || 'dev-nextauth-secret',
227
+ });
228
+ if (!decoded) {
229
+ const loginUrl = new URL('/auth/login', request.url);
230
+ loginUrl.searchParams.set('redirect', `${pathname}${search}`);
231
+ return NextResponse.redirect(loginUrl);
232
+ }
233
+
234
+ return NextResponse.next();
235
+ }
236
+
237
+ export const config = { matcher: '/:path*' };
238
+ ```
239
+
240
+ > `/auth/api/*` 路径不需要宿主额外处理头部清理。套件的 `proxyRequest` 在转发给 Casdoor 时会自动删除 `origin`、`referer`、`x-forwarded-host`、`x-forwarded-port`、`x-forwarded-proto` 和 `forwarded`,确保上游只看到干净的请求头。
241
+
242
+ ### 实现要求
243
+
244
+ - 公开路径必须完整放行,不做认证检查也不做任何重写
245
+ - 认证守卫只在非公开路径生效,未登录时重定向到 `/auth/login` 并保留原始路径作为 `redirect` 参数
246
+ - 使用套件导出的 `decodeSessionToken` 验证会话,不要自己实现 JWT 解码
247
+ - 不要修改 `app/(auth-kit)` 下的受管路由壳
248
+ - 不要在 `proxy.ts` 里硬编码 Casdoor 域名
249
+ - 不要在认证路径上做 origin 307 重写——origin 规范由边缘层和套件代理头部清理共同完成
250
+
251
+ ### 与环境变量的关系
252
+
253
+ 宿主工程必须保证:
254
+
255
+ - `APP_URL` 和 `NEXTAUTH_URL` 一致
256
+ - 生产环境必须使用公网 HTTPS 地址
257
+ - 本地开发可以使用 `http://localhost:5177`
258
+
259
+ 推荐示例:
260
+
261
+ ```env
262
+ APP_URL=https://dev-chuangxiaoju.agent-lattice.cn
263
+ NEXTAUTH_URL=https://dev-chuangxiaoju.agent-lattice.cn
264
+ ```
265
+
266
+ 本地开发示例:
267
+
268
+ ```env
269
+ APP_URL=http://localhost:5177
270
+ NEXTAUTH_URL=http://localhost:5177
271
+ ```
272
+
273
+ ### 常见故障
274
+
275
+ 如果出现以下情况:
276
+
277
+ - 登录页能打开,但提交后 403
278
+ - `redirect_uri` 变成了 `http://.../callback`
279
+ - 本地正常,线上失败
280
+ - 反向代理后回调地址不对
281
+
282
+ 优先检查:
283
+
284
+ 1. `APP_URL` 是否为真实公网 HTTPS
285
+ 2. `NEXTAUTH_URL` 是否与 `APP_URL` 保持一致
286
+ 3. FRP / Ingress / 网关是否把外部 HTTPS 请求错误地暴露成了内部 HTTP
287
+ 4. 浏览器实际访问地址是否和授权回调地址一致
288
+ 5. 宿主边缘层是否对认证路径做了 origin 规范(HTTPS → 公网 origin)
289
+
81
290
  ## UX 边界
82
291
 
83
292
  - 保持 Casdoor 认证体验完全内嵌于宿主应用,用户不应感知到"跳转到另一个网站"
@@ -141,12 +350,40 @@ Billing headless 能力的方案、接口草案和设计图已经放在仓库文
141
350
  Billing 的宿主接入方式是:
142
351
 
143
352
  1. 在宿主应用里通过 `BillingProvider` 注入 `runtimeConfig` 或显式的 `availablePlans` / `availableProducts`
144
- 2. 使用 `useSubscribePlan`、`usePurchaseProduct`、`usePurchaseCredits` 发起动作
353
+ 2. 使用 `useSubscribePlan`、`usePurchaseProduct` 发起动作
145
354
  3. 使用 `useBillingSubscription`、`useBillingOrderHistory`、`useBillingPaymentHistory`、`useBillingCredits` 查看状态
146
355
  4. 使用 `useBillingPipeline` 或 `actionExecutor` 接入宿主自己的支付、跳转和后端编排逻辑
147
356
 
357
+ 购买动作只保留两类:
358
+
359
+ - `useSubscribePlan` 处理订阅购买
360
+ - `usePurchaseProduct` 处理一次性商品购买
361
+
362
+ `usePurchaseCredits` 已经移除,积分包也不再作为独立 kind 存在;如果宿主需要积分语义,应在 `product` 上通过 `creditGrant`、`metadata` 或宿主回调处理。
363
+
148
364
  Billing 只面向数字商品和 SaaS 订阅,不包含 UI 组件,也不包含物流、地址、发货或其他非商品功能。
149
365
 
366
+ ### 支付回调约定
367
+
368
+ Billing 支付成功后,Casdoor 会回跳到宿主站内的两个固定回调路径:
369
+
370
+ - `/auth/payment/success`:支付成功接收路由
371
+ - `/auth/payment/finished`:支付完成后的固定回调路径
372
+
373
+ 这两个路径都不是页面,都是宿主自己的回调壳。宿主通过 `.env` 配置对应处理器模块路径:
374
+
375
+ - `BILLING_PAYMENT_SUCCESS_HANDLER`
376
+ - `BILLING_PAYMENT_FINISHED_HANDLER`
377
+
378
+ 处理器会接收完整的 `Request`、`paymentId`、`orderId`、`params`、`searchParams` 和 `body`,由宿主自己完成订单补全、Webhook 钩子、积分发放和最终跳转。
379
+
380
+ 如果没有配置 handler,路由会打印日志并回退到默认落点:
381
+
382
+ - success 路由默认回退到 `/auth/payment/finished`
383
+ - finished 路由默认回退到 `/`
384
+
385
+ `BILLING_PAYMENT_SUCCESS_DEBUG=true` 时,会额外打印请求路径、query 和 body,方便排查回跳参数。
386
+
150
387
  ## 宿主项目集成要点
151
388
 
152
389
  - 优先使用套件提供的 React 钩子(如 `useAuthSession`、`useAuthActions`),而非直接导入 `next-auth/react`
@@ -156,3 +393,5 @@ Billing 只面向数字商品和 SaaS 订阅,不包含 UI 组件,也不包
156
393
  - Billing 相关接入优先导入 `@foldspace-fe/casdoor-next-auth-kit/react` 和 `@foldspace-fe/casdoor-next-auth-kit/billing`
157
394
  - Billing 的可购买列表优先由宿主配置注入,必要时再由 runtimeConfig 派生,而不是在页面里硬编码
158
395
  - Billing 只应基于 `references/swagger.json` 的个人相关端点和宿主编排实现,不要把管理侧 API 当成运行时依赖
396
+
397
+
@@ -1,4 +1,4 @@
1
- type BillingItemKind = 'subscription' | 'product' | 'credits';
1
+ type BillingItemKind = 'subscription' | 'product';
2
2
  type BillingInterval = 'month' | 'year';
3
3
  interface BillingConversionRule {
4
4
  productKey: string;
@@ -52,6 +52,27 @@ interface BillingCatalogConfig extends BillingRuntimeConfig {
52
52
  successPath?: string;
53
53
  cancelPath?: string;
54
54
  }
55
+ interface BillingPaymentSuccessContext {
56
+ request: Request;
57
+ url: URL;
58
+ searchParams: URLSearchParams;
59
+ params: Record<string, string>;
60
+ body: unknown;
61
+ paymentId: string | null;
62
+ orderId: string | null;
63
+ redirectTo: string | null;
64
+ }
65
+ type BillingPaymentSuccessHandlerResult = void | null | string | Response | {
66
+ redirectTo?: string | null;
67
+ };
68
+ type BillingPaymentSuccessHandler = (context: BillingPaymentSuccessContext) => BillingPaymentSuccessHandlerResult | Promise<BillingPaymentSuccessHandlerResult>;
69
+ type BillingPaymentFinishedHandler = BillingPaymentSuccessHandler;
70
+ interface BillingPaymentSuccessRouteOptions {
71
+ appUrl?: string;
72
+ fallbackRedirect?: string;
73
+ handler?: BillingPaymentSuccessHandler;
74
+ }
75
+ type BillingPaymentFinishedRouteOptions = BillingPaymentSuccessRouteOptions;
55
76
  type BillingActionKind = 'purchase' | 'subscribe' | 'manage' | 'upgrade' | 'cancel';
56
77
  interface BillingSubscriptionPurchaseConfig {
57
78
  productKey: string;
@@ -92,6 +113,8 @@ interface BillingProductSnapshot {
92
113
  planId?: string;
93
114
  priceId?: string;
94
115
  interval?: BillingInterval;
116
+ creditGrant?: BillingItem['creditGrant'];
117
+ creditRedeem?: BillingItem['creditRedeem'];
95
118
  metadata?: Record<string, string>;
96
119
  }
97
120
  interface BillingSubscriptionState {
@@ -118,11 +141,13 @@ interface BillingProductState {
118
141
  productKey: string;
119
142
  productId?: string;
120
143
  title?: string;
121
- kind: 'product' | 'credits';
144
+ kind: 'product';
122
145
  status?: 'active' | 'inactive' | 'archived';
123
146
  quantity?: number;
124
147
  owned?: boolean;
125
148
  creditsBalance?: number;
149
+ creditGrant?: BillingItem['creditGrant'];
150
+ creditRedeem?: BillingItem['creditRedeem'];
126
151
  updatedAt?: string;
127
152
  }
128
153
  interface BillingOrderHistoryItem {
@@ -130,7 +155,7 @@ interface BillingOrderHistoryItem {
130
155
  productKey?: string;
131
156
  productId?: string;
132
157
  productTitle?: string;
133
- kind?: 'subscription' | 'product' | 'credits';
158
+ kind?: 'subscription' | 'product';
134
159
  quantity?: number;
135
160
  amount?: number;
136
161
  currency?: string;
@@ -334,4 +359,4 @@ interface BillingCoreContextValue {
334
359
  setStatus: (status: BillingStatusState | ((current: BillingStatusState) => BillingStatusState)) => void;
335
360
  }
336
361
 
337
- export type { BillingSubscriptionPurchaseConfig as A, BillingActionPayload as B, BillingItem as a, BillingRuntimeConfig as b, BillingCatalogConfig as c, BillingApiClient as d, BillingLoaders as e, BillingActionExecutor as f, BillingDefaults as g, BillingSubscriptionState as h, BillingSubscriptionHistoryItem as i, BillingProductState as j, BillingOrderHistoryItem as k, BillingPaymentHistoryItem as l, BillingCreditsState as m, BillingEntitlementState as n, BillingStatusState as o, BillingPurchaseStatus as p, BillingProductSnapshot as q, BillingCoreContextValue as r, BillingActionKind as s, BillingConversionRule as t, BillingCreditsContextValue as u, BillingInterval as v, BillingItemKind as w, BillingProductContextValue as x, BillingProductPurchaseConfig as y, BillingSubscriptionContextValue as z };
362
+ export type { BillingPaymentSuccessHandler as A, BillingActionPayload as B, BillingPaymentSuccessHandlerResult as C, BillingPaymentSuccessRouteOptions as D, BillingProductContextValue as E, BillingProductPurchaseConfig as F, BillingSubscriptionContextValue as G, BillingSubscriptionPurchaseConfig as H, BillingItem as a, BillingRuntimeConfig as b, BillingCatalogConfig as c, BillingApiClient as d, BillingLoaders as e, BillingActionExecutor as f, BillingDefaults as g, BillingSubscriptionState as h, BillingSubscriptionHistoryItem as i, BillingProductState as j, BillingOrderHistoryItem as k, BillingPaymentHistoryItem as l, BillingCreditsState as m, BillingEntitlementState as n, BillingStatusState as o, BillingPurchaseStatus as p, BillingProductSnapshot as q, BillingCoreContextValue as r, BillingActionKind as s, BillingConversionRule as t, BillingCreditsContextValue as u, BillingInterval as v, BillingItemKind as w, BillingPaymentFinishedHandler as x, BillingPaymentFinishedRouteOptions as y, BillingPaymentSuccessContext as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldspace-fe/casdoor-next-auth-kit",
3
- "version": "0.1.7",
3
+ "version": "0.1.8",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "repository": {