@foldspace-fe/casdoor-next-auth-kit 0.1.15 → 0.1.17

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 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,iB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AkC;AACvC,YAAM,SAAS,IAAI;AAAA,QACjB,GAAG;AAAA,QACH,GAAG;AAAA,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"]}
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 buildBillingPurchaseRequest,\n deriveBillingCreditsState,\n deriveBillingEntitlements,\n filterBillingPurchasableItems,\n normalizeBillingPurchaseStatus,\n normalizeBillingCatalogConfig,\n normalizeBillingRuntimeConfig,\n resolveBillingItem,\n resolveBillingPurchasable,\n resolveBillingProductSnapshot,\n resolveBillingSubscriptionProduct,\n} from './runtime';\nimport {\n buildCasdoorBuyProductRequest,\n normalizeCasdoorBuyProductResponse,\n normalizeCasdoorProductId,\n} from './casdoor-purchase.js';\nimport type {\n BillingActionExecutor,\n BillingActionKind,\n BillingActionExecutionResult,\n BillingActionPayload,\n BillingApiClient,\n BillingCatalogConfig,\n BillingCasdoorBuyProductRequest,\n BillingCasdoorProductDetail,\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 BillingPurchaseHooks,\n BillingPurchaseStatus,\n BillingRuntimeConfig,\n BillingStatusState,\n BillingSubscriptionContextValue,\n BillingSubscriptionHistoryItem,\n BillingSubscriptionState,\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 purchaseHooks?: BillingPurchaseHooks;\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\nasync function runPurchaseHook<T>(\n name: string,\n hook: ((context: T) => void | Promise<void>) | undefined,\n context: T | undefined,\n): Promise<void> {\n if (!hook || context === undefined) {\n return;\n }\n\n try {\n await hook(context);\n } catch (error) {\n console.error(`[casdoor-next-auth-kit] billing ${name} hook failed`, error);\n }\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 extractCasdoorResponseData<TData>(response: { data?: TData } | TData | undefined): TData | undefined {\n if (!response) return undefined;\n if (typeof response === 'object' && response !== null && 'data' in response) {\n return (response as { data?: TData }).data;\n }\n return response as TData;\n}\n\nasync function runCasdoorProductPurchase(\n purchaseRequest: NonNullable<ReturnType<typeof buildBillingPurchaseRequest>>,\n apiClient: BillingApiClient,\n loaders: BillingLoaders | undefined,\n): Promise<BillingActionExecutionResult | null> {\n const buyProductLoader = loaders?.buyProductLoader ?? apiClient.buyProduct;\n if (!buyProductLoader) {\n return null;\n }\n\n const productLoader = loaders?.productLoader ?? apiClient.fetchProduct;\n const organizationNamesLoader = loaders?.organizationNamesLoader ?? apiClient.fetchOrganizationNames;\n\n let productDetail: BillingCasdoorProductDetail | undefined;\n if (productLoader) {\n const productResponse = await productLoader({ id: purchaseRequest.productId }).catch(() => undefined);\n productDetail = extractCasdoorResponseData<BillingCasdoorProductDetail>(productResponse);\n }\n\n if (!productDetail) {\n if (purchaseRequest.productOwner && purchaseRequest.productName) {\n productDetail = {\n owner: purchaseRequest.productOwner,\n name: purchaseRequest.productName,\n };\n } else {\n try {\n const normalized = normalizeCasdoorProductId(purchaseRequest.productId);\n productDetail = {\n owner: normalized.owner,\n name: normalized.name,\n };\n } catch {\n return null;\n }\n }\n }\n\n if (organizationNamesLoader && productDetail.owner) {\n const organizationResponse = await organizationNamesLoader({ owner: productDetail.owner }).catch(() => undefined);\n void extractCasdoorResponseData(organizationResponse);\n }\n\n const buyRequest: BillingCasdoorBuyProductRequest = buildCasdoorBuyProductRequest(\n purchaseRequest,\n productDetail,\n purchaseRequest.providerName,\n );\n\n const response = await buyProductLoader(buyRequest);\n return normalizeCasdoorBuyProductResponse(response, purchaseRequest.returnTo ?? productDetail.returnUrl ?? productDetail.successUrl);\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 purchaseHooks?: BillingPurchaseHooks;\n status: BillingStatusState;\n refresh: () => Promise<void>;\n runAction: (payload: BillingActionPayload) => Promise<BillingActionExecutionResult>;\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 availablePlans: filterBillingPurchasableItems(\n input.runtimeConfig?.items?.filter((item) => item.kind === 'subscription'),\n input.runtimeConfig ?? input.runtimeCatalog,\n ),\n availableProducts: filterBillingPurchasableItems(\n input.runtimeConfig?.items?.filter((item) => item.kind === 'product'),\n input.runtimeConfig ?? input.runtimeCatalog,\n ),\n credits: input.credits,\n entitlements: input.entitlements,\n purchaseStatus: input.purchaseStatus,\n purchaseHooks: input.purchaseHooks,\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 purchaseHooks,\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 const isPurchaseFlow = prepared.kind === 'purchase' || prepared.kind === 'subscribe';\n const purchasable = isPurchaseFlow\n ? resolveBillingPurchasable(runtimeConfig, prepared.key) ?? resolveBillingPurchasable(runtimeConfig, prepared.productId)\n : undefined;\n const purchaseRequest = isPurchaseFlow ? buildBillingPurchaseRequest(prepared, runtimeConfig) : null;\n\n if (isPurchaseFlow && !purchasable) {\n throw new Error(`Billing item \"${prepared.key}\" is not purchasable in the current runtime config.`);\n }\n\n await runPurchaseHook('onPurchaseStart', purchaseHooks?.onPurchaseStart, purchaseRequest ?? undefined);\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 let result: BillingActionExecutionResult;\n let usedCasdoorPurchaseFlow = false;\n if (isPurchaseFlow && purchaseRequest) {\n const casdoorResult = await runCasdoorProductPurchase(\n purchaseRequest as NonNullable<ReturnType<typeof buildBillingPurchaseRequest>>,\n apiClient,\n loaders,\n );\n if (casdoorResult) {\n result = casdoorResult;\n usedCasdoorPurchaseFlow = true;\n } else {\n result = await executor(prepared);\n }\n } else {\n result = await executor(prepared);\n }\n\n if (result.status === 'failed') {\n await runPurchaseHook(\n 'onPurchaseError',\n purchaseHooks?.onPurchaseError,\n purchaseRequest\n ? {\n request: purchaseRequest,\n orderId: result.orderId ?? null,\n paymentId: result.paymentId ?? null,\n status: 'failed',\n message: result.message ?? 'Purchase failed.',\n errorCode: result.errorCode,\n redirectTo: result.redirectTo ?? null,\n rawResult: result.rawResult ?? result,\n }\n : undefined,\n );\n\n setPurchaseStatus((current) => ({\n actionKey: prepared.key,\n orderId: result.orderId ?? current?.orderId,\n paymentId: result.paymentId ?? current?.paymentId,\n transactionId: result.transactionId ?? current?.transactionId,\n status: 'failed',\n redirectTo: result.redirectTo ?? current?.redirectTo,\n updatedAt: new Date().toISOString(),\n }));\n setStatus((current) => ({\n ...current,\n loading: false,\n refreshing: false,\n error: result.message ?? current.error ?? 'Purchase failed.',\n }));\n\n await runPurchaseHook(\n 'onPurchaseComplete',\n purchaseHooks?.onPurchaseComplete,\n purchaseRequest\n ? {\n request: purchaseRequest,\n orderId: result.orderId ?? null,\n paymentId: result.paymentId ?? null,\n status: 'failed',\n redirectTo: result.redirectTo ?? null,\n }\n : undefined,\n );\n\n await refresh();\n return result;\n }\n\n await runPurchaseHook(\n 'onOrderCreated',\n purchaseHooks?.onOrderCreated,\n purchaseRequest && purchasable\n ? {\n request: purchaseRequest,\n purchasable,\n orderId: result.orderId ?? null,\n paymentId: result.paymentId ?? null,\n redirectTo: result.redirectTo ?? null,\n rawResult: result.rawResult ?? result,\n }\n : undefined,\n );\n\n setPurchaseStatus((current) => ({\n actionKey: prepared.key,\n orderId: current?.orderId,\n paymentId: current?.paymentId,\n transactionId: current?.transactionId,\n status:\n usedCasdoorPurchaseFlow && result.status !== 'failed'\n ? 'requires_payment'\n : result.status === 'failed'\n ? 'failed'\n : result.status === 'succeeded'\n ? 'paid'\n : '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\n await runPurchaseHook(\n 'onPurchaseComplete',\n purchaseHooks?.onPurchaseComplete,\n purchaseRequest\n ? {\n request: purchaseRequest,\n orderId: result.orderId ?? null,\n paymentId: result.paymentId ?? null,\n status: 'succeeded',\n redirectTo: result.redirectTo ?? null,\n }\n : undefined,\n );\n\n await refresh();\n return result;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n await runPurchaseHook(\n 'onPurchaseError',\n purchaseHooks?.onPurchaseError,\n purchaseRequest\n ? {\n request: purchaseRequest,\n orderId: null,\n paymentId: null,\n status: 'failed',\n message,\n redirectTo: null,\n rawResult: error,\n }\n : undefined,\n );\n await runPurchaseHook(\n 'onPurchaseComplete',\n purchaseHooks?.onPurchaseComplete,\n purchaseRequest\n ? {\n request: purchaseRequest,\n orderId: null,\n paymentId: null,\n status: 'failed',\n redirectTo: null,\n }\n : undefined,\n );\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, loaders, purchaseHooks, 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 purchaseHooks,\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 purchaseHooks,\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 runtimeConfig = core?.runtimeConfig ?? core?.runtimeCatalog;\n const visiblePlans = choose(availablePlans, core?.availablePlans);\n const value = useMemo<BillingSubscriptionContextValue>(\n () => ({\n availablePlans: choose(\n visiblePlans ? filterBillingPurchasableItems(visiblePlans, runtimeConfig) : undefined,\n filterBillingPurchasableItems(core?.runtimeConfig?.items?.filter((item) => item.kind === 'subscription'), runtimeConfig),\n ),\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?.availablePlans, core?.entitlements, core?.runtimeCatalog, core?.runtimeConfig, core?.status, core?.subscription, core?.subscriptionHistory, entitlements, runtimeConfig, status, subscription, subscriptionHistory, visiblePlans],\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 runtimeConfig = core?.runtimeConfig ?? core?.runtimeCatalog;\n const visibleProducts = choose(availableProducts, core?.availableProducts);\n const value = useMemo<BillingProductContextValue>(\n () => ({\n availableProducts: choose(\n visibleProducts ? filterBillingPurchasableItems(visibleProducts, runtimeConfig) : undefined,\n filterBillingPurchasableItems(core?.runtimeConfig?.items?.filter((item) => item.kind === 'product'), runtimeConfig),\n ),\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?.availableProducts, core?.orderHistory, core?.paymentHistory, core?.products, core?.runtimeCatalog, core?.runtimeConfig, core?.status, orderHistory, paymentHistory, products, runtimeConfig, status, visibleProducts],\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 BillingProductDetailState {\n product?: BillingCasdoorProductDetail;\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingProductDetail(productId: string): BillingProductDetailState {\n const core = useRequiredCoreContext();\n const productLoader = core.loaders?.productLoader ?? core.apiClient.fetchProduct;\n const [product, setProduct] = useState<BillingCasdoorProductDetail | undefined>();\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const refresh = useCallback(async () => {\n if (!productLoader || !productId) {\n setProduct(undefined);\n setError(productId ? 'Missing Casdoor product loader.' : null);\n setLoading(false);\n return;\n }\n\n setLoading(true);\n setError(null);\n try {\n const response = await productLoader({ id: productId });\n const detail = extractCasdoorResponseData<BillingCasdoorProductDetail>(response);\n setProduct(detail);\n setError(null);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n setProduct(undefined);\n setError(message);\n } finally {\n setLoading(false);\n }\n }, [productId, productLoader]);\n\n useEffect(() => {\n void refresh();\n }, [refresh]);\n\n return useMemo(\n () => ({\n product,\n loading: loading || core.runtimeConfigLoading || core.status.loading,\n error: error ?? core.runtimeConfigError ?? core.status.error,\n refresh,\n }),\n [core.runtimeConfigError, core.runtimeConfigLoading, core.status.error, core.status.loading, error, loading, product, refresh],\n );\n}\n\nexport interface BillingProductPurchaseOptionsState {\n product?: BillingCasdoorProductDetail;\n providers: BillingCasdoorProductDetail['providers'];\n providerObjs: BillingCasdoorProductDetail['providerObjs'];\n providerName?: string;\n selectedProvider?: NonNullable<BillingCasdoorProductDetail['providerObjs']>[number];\n setProviderName: (providerName?: string) => void;\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingProductPurchaseOptions(productId: string, preferredProviderName?: string): BillingProductPurchaseOptionsState {\n const detailState = useBillingProductDetail(productId);\n const [providerName, setProviderName] = useState<string | undefined>(preferredProviderName);\n\n useEffect(() => {\n if (preferredProviderName) {\n setProviderName(preferredProviderName);\n return;\n }\n\n const product = detailState.product;\n const fallbackProvider = product?.providers?.[0] ?? product?.providerObjs?.[0]?.name;\n if (!providerName || (product && !product.providers?.includes(providerName) && !product.providerObjs?.some((item) => item.name === providerName))) {\n setProviderName(fallbackProvider);\n }\n }, [detailState.product, preferredProviderName, providerName]);\n\n return useMemo(\n () => ({\n product: detailState.product,\n providers: detailState.product?.providers ?? [],\n providerObjs: detailState.product?.providerObjs ?? [],\n providerName,\n selectedProvider: detailState.product?.providerObjs?.find((item) => item.name === providerName),\n setProviderName,\n loading: detailState.loading,\n error: detailState.error,\n refresh: detailState.refresh,\n }),\n [detailState.error, detailState.loading, detailState.product, detailState.refresh, providerName],\n );\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.availablePlans) ?? [];\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.availablePlans, core.refresh, 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.availableProducts) ?? [];\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.availableProducts, core.refresh, 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;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ACxC;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"]}
@@ -9,6 +9,8 @@ metadata:
9
9
 
10
10
  本 skill 用于维护可复用的 `@foldspace-fe/casdoor-next-auth-kit` 认证套件仓库,以及消费该套件的宿主项目。当用户需要修改认证流程、路由壳模板、React 认证钩子、或执行宿主项目的 skill 安装流程时,应激活此 skill。
11
11
 
12
+ 本项目的核心价值,是把 Casdoor 原本依赖三方页面和分散接入的能力,整合到宿主工程内部统一管理,保持登录、购买、回跳和状态展示的一致体验,同时把安全边界和可控性留在宿主自己手里。
13
+
12
14
  ### 修改前必读
13
15
 
14
16
  在改下面这些内容之前,先确认当前行为、生成结果和文档说明都已对齐:
@@ -28,6 +30,8 @@ metadata:
28
30
 
29
31
  如果任一答案不确定,先补齐实现和文档,再继续改需求。
30
32
 
33
+ 在完成明显代码改动后,建议先跑 `pnpm lint`、`pnpm type-check` 和 `pnpm build`,再考虑提交或发布;这样可以尽早发现格式、类型和打包层面的回归。
34
+
31
35
  ## 源码仓库
32
36
 
33
37
  - 仓库路径:`/root/projects/foldspace-stack/casdoor-next-auth-kit`
@@ -62,6 +66,8 @@ npx @foldspace-fe/casdoor-next-auth-kit@latest check
62
66
 
63
67
  如果宿主项目使用的是本地 `file:` 依赖或工作区链接,先在本仓库执行 `pnpm build`,再回到宿主项目执行 `pnpm install` 或 `npx @foldspace-fe/casdoor-next-auth-kit@latest update`,否则可能看到旧产物。
64
68
 
69
+ 仓库发布到 npm 时使用 GitHub Actions Trusted Publisher / OIDC,不再依赖 `NPM_TOKEN`;CI 里需要保留 `id-token: write`,并让 `npm publish` 直接走受信发布流程。正式发布默认打到 `latest`,不要把 `next` 当作主版本标签。
70
+
65
71
  ## 套件提供的功能
66
72
 
67
73
  - `AuthProvider` — React 认证上下文 Provider,包裹整个应用提供会话状态
@@ -74,13 +80,13 @@ npx @foldspace-fe/casdoor-next-auth-kit@latest check
74
80
  - 无头电商代理处理器 — 将电商相关 API 请求代理到后端服务
75
81
  - 宿主路由壳模板 — 为宿主项目生成 Next.js 路由页面模板,统一认证 UI 体验
76
82
  - 数据库契约和同步接口 — 定义宿主项目必须实现的用户数据字段和同步行为
77
- - `BillingProvider` / `BillingCoreProvider` — headless billing runtime 的根 Provider
83
+ - `BillingProvider` / `BillingCoreProvider` — headless billing runtime 的根 Provider,支持 `purchasableIds` 白名单、`purchasables` 显式条目、Casdoor 商品购买适配器和购买回调 hooks
78
84
  - `SubscriptionProvider` / `ProductProvider` / `CreditsProvider` — 分域 billing Provider,按需注入订阅、商品和额度状态
79
- - `useBillingAvailablePlans` / `useBillingAvailableProducts` — 从配置或注入的 catalog 中读取可订阅套餐和可购买商品列表
85
+ - `useBillingAvailablePlans` / `useBillingAvailableProducts` — 从配置或注入的 catalog 中读取可订阅套餐和可购买商品列表,并自动过滤白名单外条目
80
86
  - `useBillingSubscription` / `useBillingSubscriptionHistory` / `useBillingSubscriptionProduct` — 查看当前订阅、订阅历史和当前订阅对应产品
81
- - `useBillingProducts` / `useBillingProduct` / `useBillingOrderHistory` / `useBillingPaymentHistory` — 查看商品状态、订单历史和支付历史
87
+ - `useBillingProducts` / `useBillingProduct` / `useBillingProductDetail` / `useBillingProductPurchaseOptions` / `useBillingOrderHistory` / `useBillingPaymentHistory` — 查看商品状态、商品详情、商品购买选项、订单历史和支付历史
82
88
  - `useBillingCredits` / `useBillingEntitlements` / `useBillingPurchaseStatus` — 查看额度、权益和归一化购买状态
83
- - `useSubscribePlan` / `usePurchaseProduct` — 发起订阅和商品购买动作
89
+ - `useSubscribePlan` / `usePurchaseProduct` — 发起订阅和商品购买动作,单次购买只针对一个具体条目;商品购买会先走商品详情解析,再组装 Casdoor 的下单参数
84
90
  - `useBillingRefresh` / `useBillingPipeline` — 刷新 billing 状态和编排动作执行链路
85
91
 
86
92
  ## 路由模型
@@ -95,12 +101,17 @@ npx @foldspace-fe/casdoor-next-auth-kit@latest check
95
101
  - `/callback/error` — 回调错误提示页,默认以视口居中、小尺寸卡片呈现错误信息,包含明显的错误状态视觉锚点,并提供“清空当前域 Cookie”按钮,帮助用户清理残留认证 cookie 后重新登录
96
102
  - `/logout` — 注销路由,优先用 `Clear-Site-Data: "cookies"` 清空当前域 cookie,再补一轮 `Set-Cookie` 删除兜底,并跳转到首页或 `AuthKitConfig.logoutRedirectPath`;如果目标路径和当前页相同,则按刷新处理
97
103
  - `/auth/api/*` — Casdoor API 代理,所有个人操作的 API 请求通过此路径转发
104
+ - billing 的购买页、二维码扫描区和支付状态面板都由宿主工程自己控制,套件只提供 headless hooks、Casdoor 购买适配器、支付回调 handler 和纯数据模型;`packages/auth-kit/src/core/index-html.ts` 不参与 billing 页面生成
98
105
 
99
106
  入口路由(login/signup)负责将用户引导至授权壳,授权壳在同源 iframe 或内嵌组件中渲染 Casdoor 界面,避免用户感知到离开宿主应用。
100
107
 
101
108
  如果宿主希望注销后回到自定义配置页,可以在 `AuthKitConfig` 中设置 `logoutRedirectPath`,默认值为 `/`。
102
109
  若想通过环境变量控制默认值,可设置 `NEXT_PUBLIC_AUTH_LOGOUT_REDIRECT_PATH=/` 或其他同源路径。
103
110
 
111
+ Billing 的购买白名单可以通过 `BillingCatalogConfig.purchasableIds` 或宿主注入的 `purchasables` 显式配置。宿主只需要在自己的项目里维护允许购买的少量条目,Casdoor 里可以继续保留更大的商品集合。
112
+
113
+ 商品购买的包内适配器会优先读取 Casdoor 商品详情,再按 `owner/name` 解析商品 ID,并自动选择可用 provider 后调用 `buy-product` 兼容接口;宿主只需要提供允许购买的商品 id 和相应的 Casdoor 接口 loader。loader 约定使用 Casdoor 的标准响应 envelope,然后从 `data` 中取出商品、组织、账号、应用或支付记录。`buy-product` 如果返回 `status: "error"`,包内会把 `msg` 里的错误信息和错误码透传到宿主的 `onPurchaseError` / `onPurchaseComplete`。`useBillingProductDetail` 会把商品详情里的 `providers` 和 `providerObjs` 暴露给宿主,`useBillingProductPurchaseOptions` 可以直接拿到商品详情、当前 provider 选择、当前选中 provider 对象和 setter,适合商品详情页按支付方式展示不同购买参数;宿主选中的 `providerName` 也可以直接传给 `purchaseProduct.run({ key, providerName })`,让包内适配器按这个 provider 下单。这个 hook 只是给单选场景提供默认态,如果宿主想同时渲染两个不同的支付入口,直接遍历 `providerObjs` 就行,`selectedProvider` 不会限制 UI 结构。`productId` 推荐写成 `owner/name` 形式,例如 `qixiaoju/创小剧积分包-50`,和 `GET /api/get-product?id=qixiaoju/创小剧积分包-50` 的查询值保持一致。支付结果轮询和 `get-account` / `get-application` / `get-payment` 这类浏览器侧查询,优先请求 `/auth/api/*` 同域代理;只有服务端或明确启用 CORS 的特殊场景,才考虑直接连 `NEXT_PUBLIC_CASDOOR_SERVER_URL` origin 的 `/api/*`。
114
+
104
115
  ## 宿主工程 `proxy.ts` 配置要求
105
116
 
106
117
  `proxy.ts` 是宿主工程的 Next.js middleware(通常放在项目根目录,在 `next.config.ts` 中通过 `middleware` 字段指向),不属于 `@foldspace-fe/casdoor-next-auth-kit` 的受管文件。它的核心职责是**认证守卫**——拦截未登录用户对业务页面的访问,将其重定向到登录页;同时放行所有公开路径和认证流程路径。
@@ -406,6 +417,8 @@ Billing 支付成功后,Casdoor 会回跳到宿主站内的两个固定回调
406
417
 
407
418
  宿主可以直接改这两个默认生成文件里的 custom block 来完成订单补全、Webhook 钩子、积分发放和最终跳转,而不需要额外手工创建 `@/lib/billing/*`。
408
419
 
420
+ 默认回调上下文会同时带上 `paymentOwner`、`paymentName`、`paymentId`、`orderId`、`redirectTo`、`status` 和完整 query 参数,宿主在 custom block 里可以直接做订单系统对接和后置处理。
421
+
409
422
  默认生成的 billing handler 文件必须保持“拿来就能编译”,文件里如果没有业务逻辑,也要保留可运行的空实现和明确日志,不允许生成只写注释或只留导入的半成品。
410
423
 
411
424
  默认生成的 callback error page 也必须保持可编译,并在错误提示外额外提供本地清 cookie 按钮;按钮逻辑必须只在浏览器端执行,不能依赖服务端接口。