@foldspace-fe/casdoor-next-auth-kit 0.1.22 → 0.1.24

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.
Files changed (36) hide show
  1. package/README.md +70 -0
  2. package/dist/auth-role-C35sP1i6.d.ts +40 -0
  3. package/dist/callback-Da3JC_EN.d.ts +18 -0
  4. package/dist/casdoor/index.d.ts +3 -8
  5. package/dist/casdoor/index.js +6 -4
  6. package/dist/{chunk-GLK4IW22.js → chunk-CSQFNYTS.js} +25 -11
  7. package/dist/chunk-CSQFNYTS.js.map +1 -0
  8. package/dist/{chunk-MWXY4JSL.js → chunk-IPJT66SK.js} +19 -11
  9. package/dist/{chunk-MWXY4JSL.js.map → chunk-IPJT66SK.js.map} +1 -1
  10. package/dist/chunk-JCQ5P7QZ.js +74 -0
  11. package/dist/chunk-JCQ5P7QZ.js.map +1 -0
  12. package/dist/chunk-YHPSOLXM.js +904 -0
  13. package/dist/chunk-YHPSOLXM.js.map +1 -0
  14. package/dist/cli-templates-IhA9gjyF.d.ts +31 -0
  15. package/dist/cli-templates.d.ts +2 -0
  16. package/dist/cli-templates.js +7 -0
  17. package/dist/cli-templates.js.map +1 -0
  18. package/dist/cli.js +52 -557
  19. package/dist/cli.js.map +1 -1
  20. package/dist/index.d.ts +8 -14
  21. package/dist/index.js +56 -6
  22. package/dist/next/index.d.ts +3 -3
  23. package/dist/next/index.js +7 -5
  24. package/dist/{options-D2YQdRWu.d.ts → options-CpWDszxZ.d.ts} +5 -2
  25. package/dist/react/index.d.ts +5 -4
  26. package/dist/react/index.js +4 -18
  27. package/dist/react/index.js.map +1 -1
  28. package/dist/skills/casdoor-next-auth-kit/SKILL.md +49 -1
  29. package/dist/{types-BJv6j3NZ.d.ts → types-COXcI8tx.d.ts} +3 -1
  30. package/package.json +1 -1
  31. package/dist/callback-rEWxVGyL.d.ts +0 -12
  32. package/dist/chunk-FW4WDHNS.js +0 -332
  33. package/dist/chunk-FW4WDHNS.js.map +0 -1
  34. package/dist/chunk-GLK4IW22.js.map +0 -1
  35. package/dist/chunk-T2M5MVPE.js +0 -20
  36. package/dist/chunk-T2M5MVPE.js.map +0 -1
@@ -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 buildBillingPurchaseRequest,\n deriveBillingCreditsState,\n deriveBillingEntitlements,\n filterBillingPurchasableItems,\n normalizeCasdoorOrderHistoryItem,\n normalizeCasdoorPaymentHistoryItem,\n normalizeCasdoorSubscriptionDetail,\n normalizeCasdoorSubscriptionHistoryItem,\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 BillingCasdoorOrderDetail,\n BillingCasdoorOrdersResponse,\n BillingCasdoorPlanDetail,\n BillingCasdoorPricingDetail,\n BillingCasdoorProductDetail,\n BillingCasdoorQueryState,\n BillingCasdoorSubscriptionDetail,\n BillingCasdoorSubscriptionsResponse,\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\nfunction useBillingCasdoorQuery<TData, TArgs extends Record<string, unknown>>(\n loader: ((args: TArgs) => Promise<{ data?: TData } | TData>) | undefined,\n buildArgs: () => TArgs,\n deps: readonly unknown[],\n missingLoaderMessage: string,\n): BillingCasdoorQueryState<TData> {\n const [data, setData] = useState<TData | undefined>();\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const refresh = useCallback(async () => {\n if (!loader) {\n setData(undefined);\n setError(missingLoaderMessage);\n setLoading(false);\n return;\n }\n\n setLoading(true);\n setError(null);\n try {\n const response = await loader(buildArgs());\n const extracted = extractCasdoorResponseData<TData>(response);\n setData(extracted);\n setError(null);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n setData(undefined);\n setError(message);\n } finally {\n setLoading(false);\n }\n }, [buildArgs, loader, missingLoaderMessage]);\n\n useEffect(() => {\n void refresh();\n }, [refresh, ...deps]);\n\n return useMemo(\n () => ({\n data,\n loading,\n error,\n refresh,\n }),\n [data, error, loading, refresh],\n );\n}\n\nfunction pickCurrentCasdoorSubscription(records: BillingCasdoorSubscriptionDetail[]): BillingCasdoorSubscriptionDetail | undefined {\n if (!records.length) return undefined;\n const active = records.find((record) => {\n const status = (record.state ?? '').toLowerCase();\n return status.includes('active') || status.includes('trial');\n });\n if (active) return active;\n return [...records].sort((left, right) => {\n const leftTime = Date.parse(left.endTime ?? left.createdTime ?? '') || 0;\n const rightTime = Date.parse(right.endTime ?? right.createdTime ?? '') || 0;\n return rightTime - leftTime;\n })[0];\n}\n\nfunction pickLatestCasdoorOrder(records: BillingCasdoorOrderDetail[]): BillingCasdoorOrderDetail | undefined {\n if (!records.length) return undefined;\n return [...records].sort((left, right) => {\n const leftTime = Date.parse((left as { updatedTime?: string }).updatedTime ?? left.createdTime ?? '') || 0;\n const rightTime = Date.parse((right as { updatedTime?: string }).updatedTime ?? right.createdTime ?? '') || 0;\n return rightTime - leftTime;\n })[0];\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 subscriptionsLoader = resolvedLoaders.subscriptionsLoader ?? apiClient.fetchSubscriptions;\n const productsLoader = resolvedLoaders.productsLoader ?? apiClient.fetchProducts;\n const orderHistoryLoader = resolvedLoaders.orderHistoryLoader ?? apiClient.fetchOrderHistory;\n const ordersLoader = resolvedLoaders.ordersLoader ?? apiClient.fetchOrders;\n const paymentHistoryLoader = resolvedLoaders.paymentHistoryLoader ?? apiClient.fetchPaymentHistory;\n const paymentLoader = resolvedLoaders.paymentLoader ?? apiClient.fetchPayment;\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 const nextSubscriptionsResponsePromise: Promise<BillingCasdoorSubscriptionsResponse | undefined> = subscriptionsLoader\n ? subscriptionsLoader({}).catch(() => undefined)\n : Promise.resolve(undefined);\n const nextOrdersResponsePromise: Promise<BillingCasdoorOrdersResponse | undefined> = ordersLoader\n ? ordersLoader({}).catch(() => undefined)\n : Promise.resolve(undefined);\n\n const [\n nextSubscription,\n nextSubscriptionHistory,\n nextSubscriptionsResponse,\n nextProducts,\n nextOrderHistory,\n nextOrdersResponse,\n nextPaymentHistory,\n nextCredits,\n nextEntitlements,\n ] = await Promise.all([\n subscriptionLoader({ catalogKey: nextCatalogKey }),\n subscriptionHistoryLoader({ catalogKey: nextCatalogKey }),\n nextSubscriptionsResponsePromise,\n productsLoader({ catalogKey: nextCatalogKey }),\n orderHistoryLoader({ catalogKey: nextCatalogKey }),\n nextOrdersResponsePromise,\n paymentHistoryLoader({ catalogKey: nextCatalogKey }),\n creditsLoader({ catalogKey: nextCatalogKey }),\n entitlementsLoader({ catalogKey: nextCatalogKey }),\n ]);\n\n const casdoorSubscriptions = extractCasdoorResponseData<BillingCasdoorSubscriptionDetail[]>(nextSubscriptionsResponse) ?? [];\n const casdoorOrders = extractCasdoorResponseData<BillingCasdoorOrderDetail[]>(nextOrdersResponse) ?? [];\n const derivedSubscriptionHistory = nextSubscriptionHistory ?? casdoorSubscriptions.map(normalizeCasdoorSubscriptionHistoryItem);\n const derivedOrderHistory = nextOrderHistory ?? casdoorOrders.map(normalizeCasdoorOrderHistoryItem);\n\n let resolvedPaymentHistory = nextPaymentHistory;\n if ((!resolvedPaymentHistory || resolvedPaymentHistory.length === 0) && casdoorOrders.length && paymentLoader) {\n const latestCasdoorOrder = pickLatestCasdoorOrder(casdoorOrders);\n const paymentId = latestCasdoorOrder?.payment ?? latestCasdoorOrder?.transaction;\n if (paymentId) {\n const paymentResponse = await paymentLoader({ id: paymentId }).catch(() => undefined);\n const paymentDetail = extractCasdoorResponseData<{\n name?: string;\n order?: string;\n outOrderId?: string;\n product?: string;\n productName?: string;\n productDisplayName?: string;\n price?: number;\n currency?: string;\n state?: string;\n transactionId?: string;\n createdTime?: string;\n updatedTime?: string;\n }>(paymentResponse);\n if (paymentDetail?.name) {\n resolvedPaymentHistory = [\n normalizeCasdoorPaymentHistoryItem({\n name: paymentDetail.name,\n order: paymentDetail.order,\n outOrderId: paymentDetail.outOrderId,\n product: paymentDetail.product ?? paymentDetail.productName,\n productName: paymentDetail.productName,\n productDisplayName: paymentDetail.productDisplayName,\n price: paymentDetail.price,\n currency: paymentDetail.currency,\n state: paymentDetail.state,\n transactionId: paymentDetail.transactionId,\n createdTime: paymentDetail.createdTime,\n updatedTime: paymentDetail.updatedTime,\n }),\n ];\n }\n }\n }\n\n const subscriptionWithProduct = nextSubscription\n ? {\n ...nextSubscription,\n product: resolveBillingSubscriptionProduct(nextSubscription, nextRuntimeConfig ?? runtimeConfig),\n }\n : (() => {\n const derivedSubscription = normalizeCasdoorSubscriptionDetail(pickCurrentCasdoorSubscription(casdoorSubscriptions));\n return derivedSubscription\n ? {\n ...derivedSubscription,\n product: resolveBillingSubscriptionProduct(derivedSubscription, nextRuntimeConfig ?? runtimeConfig),\n }\n : undefined;\n })();\n\n const normalizedCredits = deriveBillingCreditsState(nextCredits, nextProducts, nextRuntimeConfig?.conversionRules ?? runtimeConfig?.conversionRules);\n const normalizedEntitlements = nextEntitlements ?? deriveBillingEntitlements(subscriptionWithProduct, nextProducts, normalizedCredits, nextRuntimeConfig ?? runtimeConfig);\n const latestOrder = getLatestOrder(derivedOrderHistory);\n const latestPayment = getLatestPayment(resolvedPaymentHistory);\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(derivedSubscriptionHistory);\n setProducts(nextProducts);\n setOrderHistory(derivedOrderHistory);\n setPaymentHistory(resolvedPaymentHistory);\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 type BillingPricingState = BillingCasdoorQueryState<BillingCasdoorPricingDetail>;\nexport type BillingPlanState = BillingCasdoorQueryState<BillingCasdoorPlanDetail>;\nexport type BillingOrderState = BillingCasdoorQueryState<BillingCasdoorOrderDetail>;\nexport type BillingOrdersState = BillingCasdoorQueryState<BillingCasdoorOrderDetail[]>;\nexport type BillingSubscriptionRecordState = BillingCasdoorQueryState<BillingCasdoorSubscriptionDetail>;\nexport type BillingSubscriptionsState = BillingCasdoorQueryState<BillingCasdoorSubscriptionDetail[]>;\n\nexport function useBillingPricing(pricingId: string): BillingPricingState {\n const core = useRequiredCoreContext();\n const loader = core.loaders?.pricingLoader ?? core.apiClient.fetchPricing;\n return useBillingCasdoorQuery(\n loader,\n useCallback(() => ({ id: pricingId }), [pricingId]),\n [pricingId, loader],\n 'Missing billing pricing loader.',\n );\n}\n\nexport function useBillingPlan(planId: string, includeOption = false): BillingPlanState {\n const core = useRequiredCoreContext();\n const loader = core.loaders?.planLoader ?? core.apiClient.fetchPlan;\n return useBillingCasdoorQuery(\n loader,\n useCallback(() => ({ id: planId, includeOption }), [includeOption, planId]),\n [includeOption, loader, planId],\n 'Missing billing plan loader.',\n );\n}\n\nexport function useBillingOrder(orderId: string): BillingOrderState {\n const core = useRequiredCoreContext();\n const loader = core.loaders?.orderLoader ?? core.apiClient.fetchOrder;\n return useBillingCasdoorQuery(\n loader,\n useCallback(() => ({ id: orderId }), [orderId]),\n [loader, orderId],\n 'Missing billing order loader.',\n );\n}\n\nexport function useBillingSubscriptionRecord(subscriptionId: string): BillingSubscriptionRecordState {\n const core = useRequiredCoreContext();\n const loader = core.loaders?.subscriptionRecordLoader ?? core.apiClient.fetchSubscriptionRecord;\n return useBillingCasdoorQuery(\n loader,\n useCallback(() => ({ id: subscriptionId }), [subscriptionId]),\n [loader, subscriptionId],\n 'Missing billing subscription loader.',\n );\n}\n\nexport function useBillingOrders(options: { owner?: string; user?: string; product?: string } = {}): BillingOrdersState {\n const core = useRequiredCoreContext();\n const loader = core.loaders?.ordersLoader ?? core.apiClient.fetchOrders;\n const owner = options.owner;\n const user = options.user;\n const product = options.product;\n return useBillingCasdoorQuery(\n loader,\n useCallback(() => ({ owner, user, product }), [owner, product, user]),\n [loader, owner, product, user],\n 'Missing billing orders loader.',\n );\n}\n\nexport function useBillingSubscriptions(options: { owner?: string; user?: string } = {}): BillingSubscriptionsState {\n const core = useRequiredCoreContext();\n const loader = core.loaders?.subscriptionsLoader ?? core.apiClient.fetchSubscriptions;\n const owner = options.owner;\n const user = options.user;\n return useBillingCasdoorQuery(\n loader,\n useCallback(() => ({ owner, user }), [owner, user]),\n [loader, owner, user],\n 'Missing billing subscriptions loader.',\n );\n}\n\nexport interface BillingPricingPlansState {\n pricing?: BillingCasdoorPricingDetail;\n plans: BillingCasdoorPlanDetail[];\n selectedPlanName?: string;\n selectedPlan?: BillingCasdoorPlanDetail;\n setSelectedPlanName: (planName?: string) => void;\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingPricingPlans(\n pricingId: string,\n includeOption = false,\n preferredPlanName?: string,\n): BillingPricingPlansState {\n const pricingState = useBillingPricing(pricingId);\n const core = useRequiredCoreContext();\n const [selectedPlanName, setSelectedPlanName] = useState<string | undefined>(preferredPlanName);\n const planLoader = core.loaders?.planLoader ?? core.apiClient.fetchPlan;\n const [plans, setPlans] = useState<BillingCasdoorPlanDetail[]>([]);\n const [planLoading, setPlanLoading] = useState(false);\n const [planError, setPlanError] = useState<string | null>(null);\n\n useEffect(() => {\n if (preferredPlanName) {\n setSelectedPlanName(preferredPlanName);\n }\n }, [preferredPlanName]);\n\n useEffect(() => {\n const nextPlanName = selectedPlanName ?? pricingState.data?.plans?.[0];\n if (!nextPlanName || (selectedPlanName && pricingState.data?.plans && !pricingState.data.plans.includes(selectedPlanName))) {\n setSelectedPlanName(pricingState.data?.plans?.[0]);\n return;\n }\n if (!selectedPlanName && nextPlanName) {\n setSelectedPlanName(nextPlanName);\n }\n }, [pricingState.data?.plans, selectedPlanName]);\n\n const refreshPlans = useCallback(async () => {\n if (!planLoader) {\n setPlans([]);\n setPlanError('Missing billing plan loader.');\n setPlanLoading(false);\n return;\n }\n\n const planNames = pricingState.data?.plans ?? [];\n if (!planNames.length) {\n setPlans([]);\n setPlanError(null);\n setPlanLoading(false);\n return;\n }\n\n setPlanLoading(true);\n setPlanError(null);\n try {\n const results = await Promise.all(\n planNames.map(async (planName) => {\n const response = await planLoader({ id: planName, includeOption });\n return extractCasdoorResponseData<BillingCasdoorPlanDetail>(response);\n }),\n );\n setPlans(results.filter((plan): plan is BillingCasdoorPlanDetail => Boolean(plan)));\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n setPlans([]);\n setPlanError(message);\n } finally {\n setPlanLoading(false);\n }\n }, [includeOption, planLoader, pricingState.data?.plans]);\n\n useEffect(() => {\n void refreshPlans();\n }, [refreshPlans]);\n\n const selectedPlan = useMemo(\n () => plans.find((plan) => plan.name === selectedPlanName) ?? (plans.length === 1 ? plans[0] : undefined),\n [plans, selectedPlanName],\n );\n\n return useMemo(\n () => ({\n pricing: pricingState.data,\n plans,\n selectedPlanName,\n selectedPlan,\n setSelectedPlanName,\n loading: pricingState.loading || planLoading,\n error: pricingState.error ?? planError,\n refresh: async () => {\n await pricingState.refresh();\n await refreshPlans();\n },\n }),\n [planError, planLoading, plans, pricingState, refreshPlans, selectedPlan, selectedPlanName],\n );\n}\n\nexport interface BillingSubscriptionPurchaseOptionsState {\n pricing?: BillingCasdoorPricingDetail;\n plans: BillingCasdoorPlanDetail[];\n selectedPlanName?: string;\n selectedPlan?: BillingCasdoorPlanDetail;\n setSelectedPlanName: (planName?: string) => void;\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingSubscriptionPurchaseOptions(\n pricingId: string,\n includeOption = false,\n preferredPlanName?: string,\n): BillingSubscriptionPurchaseOptionsState {\n const pricingPlans = useBillingPricingPlans(pricingId, includeOption, preferredPlanName);\n return useMemo(\n () => ({\n pricing: pricingPlans.pricing,\n plans: pricingPlans.plans,\n selectedPlanName: pricingPlans.selectedPlanName,\n selectedPlan: pricingPlans.selectedPlan,\n setSelectedPlanName: pricingPlans.setSelectedPlanName,\n loading: pricingPlans.loading,\n error: pricingPlans.error,\n refresh: pricingPlans.refresh,\n }),\n [pricingPlans],\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,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AA,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 { buildAuthUserSummary, type AuthSummaryRole } from '../core/auth-role';\nimport type { AuthSession } from '../next/options';\n\nexport type AuthRole = AuthSummaryRole;\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\nexport function getUserSummary(session: AuthSession | null | undefined): AuthUserSummary {\n return buildAuthUserSummary(session?.user);\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 normalizeCasdoorOrderHistoryItem,\n normalizeCasdoorPaymentHistoryItem,\n normalizeCasdoorSubscriptionDetail,\n normalizeCasdoorSubscriptionHistoryItem,\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 BillingCasdoorOrderDetail,\n BillingCasdoorOrdersResponse,\n BillingCasdoorPlanDetail,\n BillingCasdoorPricingDetail,\n BillingCasdoorProductDetail,\n BillingCasdoorQueryState,\n BillingCasdoorSubscriptionDetail,\n BillingCasdoorSubscriptionsResponse,\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\nfunction useBillingCasdoorQuery<TData, TArgs extends Record<string, unknown>>(\n loader: ((args: TArgs) => Promise<{ data?: TData } | TData>) | undefined,\n buildArgs: () => TArgs,\n deps: readonly unknown[],\n missingLoaderMessage: string,\n): BillingCasdoorQueryState<TData> {\n const [data, setData] = useState<TData | undefined>();\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const refresh = useCallback(async () => {\n if (!loader) {\n setData(undefined);\n setError(missingLoaderMessage);\n setLoading(false);\n return;\n }\n\n setLoading(true);\n setError(null);\n try {\n const response = await loader(buildArgs());\n const extracted = extractCasdoorResponseData<TData>(response);\n setData(extracted);\n setError(null);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n setData(undefined);\n setError(message);\n } finally {\n setLoading(false);\n }\n }, [buildArgs, loader, missingLoaderMessage]);\n\n useEffect(() => {\n void refresh();\n }, [refresh, ...deps]);\n\n return useMemo(\n () => ({\n data,\n loading,\n error,\n refresh,\n }),\n [data, error, loading, refresh],\n );\n}\n\nfunction pickCurrentCasdoorSubscription(records: BillingCasdoorSubscriptionDetail[]): BillingCasdoorSubscriptionDetail | undefined {\n if (!records.length) return undefined;\n const active = records.find((record) => {\n const status = (record.state ?? '').toLowerCase();\n return status.includes('active') || status.includes('trial');\n });\n if (active) return active;\n return [...records].sort((left, right) => {\n const leftTime = Date.parse(left.endTime ?? left.createdTime ?? '') || 0;\n const rightTime = Date.parse(right.endTime ?? right.createdTime ?? '') || 0;\n return rightTime - leftTime;\n })[0];\n}\n\nfunction pickLatestCasdoorOrder(records: BillingCasdoorOrderDetail[]): BillingCasdoorOrderDetail | undefined {\n if (!records.length) return undefined;\n return [...records].sort((left, right) => {\n const leftTime = Date.parse((left as { updatedTime?: string }).updatedTime ?? left.createdTime ?? '') || 0;\n const rightTime = Date.parse((right as { updatedTime?: string }).updatedTime ?? right.createdTime ?? '') || 0;\n return rightTime - leftTime;\n })[0];\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 subscriptionsLoader = resolvedLoaders.subscriptionsLoader ?? apiClient.fetchSubscriptions;\n const productsLoader = resolvedLoaders.productsLoader ?? apiClient.fetchProducts;\n const orderHistoryLoader = resolvedLoaders.orderHistoryLoader ?? apiClient.fetchOrderHistory;\n const ordersLoader = resolvedLoaders.ordersLoader ?? apiClient.fetchOrders;\n const paymentHistoryLoader = resolvedLoaders.paymentHistoryLoader ?? apiClient.fetchPaymentHistory;\n const paymentLoader = resolvedLoaders.paymentLoader ?? apiClient.fetchPayment;\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 const nextSubscriptionsResponsePromise: Promise<BillingCasdoorSubscriptionsResponse | undefined> = subscriptionsLoader\n ? subscriptionsLoader({}).catch(() => undefined)\n : Promise.resolve(undefined);\n const nextOrdersResponsePromise: Promise<BillingCasdoorOrdersResponse | undefined> = ordersLoader\n ? ordersLoader({}).catch(() => undefined)\n : Promise.resolve(undefined);\n\n const [\n nextSubscription,\n nextSubscriptionHistory,\n nextSubscriptionsResponse,\n nextProducts,\n nextOrderHistory,\n nextOrdersResponse,\n nextPaymentHistory,\n nextCredits,\n nextEntitlements,\n ] = await Promise.all([\n subscriptionLoader({ catalogKey: nextCatalogKey }),\n subscriptionHistoryLoader({ catalogKey: nextCatalogKey }),\n nextSubscriptionsResponsePromise,\n productsLoader({ catalogKey: nextCatalogKey }),\n orderHistoryLoader({ catalogKey: nextCatalogKey }),\n nextOrdersResponsePromise,\n paymentHistoryLoader({ catalogKey: nextCatalogKey }),\n creditsLoader({ catalogKey: nextCatalogKey }),\n entitlementsLoader({ catalogKey: nextCatalogKey }),\n ]);\n\n const casdoorSubscriptions = extractCasdoorResponseData<BillingCasdoorSubscriptionDetail[]>(nextSubscriptionsResponse) ?? [];\n const casdoorOrders = extractCasdoorResponseData<BillingCasdoorOrderDetail[]>(nextOrdersResponse) ?? [];\n const derivedSubscriptionHistory = nextSubscriptionHistory ?? casdoorSubscriptions.map(normalizeCasdoorSubscriptionHistoryItem);\n const derivedOrderHistory = nextOrderHistory ?? casdoorOrders.map(normalizeCasdoorOrderHistoryItem);\n\n let resolvedPaymentHistory = nextPaymentHistory;\n if ((!resolvedPaymentHistory || resolvedPaymentHistory.length === 0) && casdoorOrders.length && paymentLoader) {\n const latestCasdoorOrder = pickLatestCasdoorOrder(casdoorOrders);\n const paymentId = latestCasdoorOrder?.payment ?? latestCasdoorOrder?.transaction;\n if (paymentId) {\n const paymentResponse = await paymentLoader({ id: paymentId }).catch(() => undefined);\n const paymentDetail = extractCasdoorResponseData<{\n name?: string;\n order?: string;\n outOrderId?: string;\n product?: string;\n productName?: string;\n productDisplayName?: string;\n price?: number;\n currency?: string;\n state?: string;\n transactionId?: string;\n createdTime?: string;\n updatedTime?: string;\n }>(paymentResponse);\n if (paymentDetail?.name) {\n resolvedPaymentHistory = [\n normalizeCasdoorPaymentHistoryItem({\n name: paymentDetail.name,\n order: paymentDetail.order,\n outOrderId: paymentDetail.outOrderId,\n product: paymentDetail.product ?? paymentDetail.productName,\n productName: paymentDetail.productName,\n productDisplayName: paymentDetail.productDisplayName,\n price: paymentDetail.price,\n currency: paymentDetail.currency,\n state: paymentDetail.state,\n transactionId: paymentDetail.transactionId,\n createdTime: paymentDetail.createdTime,\n updatedTime: paymentDetail.updatedTime,\n }),\n ];\n }\n }\n }\n\n const subscriptionWithProduct = nextSubscription\n ? {\n ...nextSubscription,\n product: resolveBillingSubscriptionProduct(nextSubscription, nextRuntimeConfig ?? runtimeConfig),\n }\n : (() => {\n const derivedSubscription = normalizeCasdoorSubscriptionDetail(pickCurrentCasdoorSubscription(casdoorSubscriptions));\n return derivedSubscription\n ? {\n ...derivedSubscription,\n product: resolveBillingSubscriptionProduct(derivedSubscription, nextRuntimeConfig ?? runtimeConfig),\n }\n : undefined;\n })();\n\n const normalizedCredits = deriveBillingCreditsState(nextCredits, nextProducts, nextRuntimeConfig?.conversionRules ?? runtimeConfig?.conversionRules);\n const normalizedEntitlements = nextEntitlements ?? deriveBillingEntitlements(subscriptionWithProduct, nextProducts, normalizedCredits, nextRuntimeConfig ?? runtimeConfig);\n const latestOrder = getLatestOrder(derivedOrderHistory);\n const latestPayment = getLatestPayment(resolvedPaymentHistory);\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(derivedSubscriptionHistory);\n setProducts(nextProducts);\n setOrderHistory(derivedOrderHistory);\n setPaymentHistory(resolvedPaymentHistory);\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 type BillingPricingState = BillingCasdoorQueryState<BillingCasdoorPricingDetail>;\nexport type BillingPlanState = BillingCasdoorQueryState<BillingCasdoorPlanDetail>;\nexport type BillingOrderState = BillingCasdoorQueryState<BillingCasdoorOrderDetail>;\nexport type BillingOrdersState = BillingCasdoorQueryState<BillingCasdoorOrderDetail[]>;\nexport type BillingSubscriptionRecordState = BillingCasdoorQueryState<BillingCasdoorSubscriptionDetail>;\nexport type BillingSubscriptionsState = BillingCasdoorQueryState<BillingCasdoorSubscriptionDetail[]>;\n\nexport function useBillingPricing(pricingId: string): BillingPricingState {\n const core = useRequiredCoreContext();\n const loader = core.loaders?.pricingLoader ?? core.apiClient.fetchPricing;\n return useBillingCasdoorQuery(\n loader,\n useCallback(() => ({ id: pricingId }), [pricingId]),\n [pricingId, loader],\n 'Missing billing pricing loader.',\n );\n}\n\nexport function useBillingPlan(planId: string, includeOption = false): BillingPlanState {\n const core = useRequiredCoreContext();\n const loader = core.loaders?.planLoader ?? core.apiClient.fetchPlan;\n return useBillingCasdoorQuery(\n loader,\n useCallback(() => ({ id: planId, includeOption }), [includeOption, planId]),\n [includeOption, loader, planId],\n 'Missing billing plan loader.',\n );\n}\n\nexport function useBillingOrder(orderId: string): BillingOrderState {\n const core = useRequiredCoreContext();\n const loader = core.loaders?.orderLoader ?? core.apiClient.fetchOrder;\n return useBillingCasdoorQuery(\n loader,\n useCallback(() => ({ id: orderId }), [orderId]),\n [loader, orderId],\n 'Missing billing order loader.',\n );\n}\n\nexport function useBillingSubscriptionRecord(subscriptionId: string): BillingSubscriptionRecordState {\n const core = useRequiredCoreContext();\n const loader = core.loaders?.subscriptionRecordLoader ?? core.apiClient.fetchSubscriptionRecord;\n return useBillingCasdoorQuery(\n loader,\n useCallback(() => ({ id: subscriptionId }), [subscriptionId]),\n [loader, subscriptionId],\n 'Missing billing subscription loader.',\n );\n}\n\nexport function useBillingOrders(options: { owner?: string; user?: string; product?: string } = {}): BillingOrdersState {\n const core = useRequiredCoreContext();\n const loader = core.loaders?.ordersLoader ?? core.apiClient.fetchOrders;\n const owner = options.owner;\n const user = options.user;\n const product = options.product;\n return useBillingCasdoorQuery(\n loader,\n useCallback(() => ({ owner, user, product }), [owner, product, user]),\n [loader, owner, product, user],\n 'Missing billing orders loader.',\n );\n}\n\nexport function useBillingSubscriptions(options: { owner?: string; user?: string } = {}): BillingSubscriptionsState {\n const core = useRequiredCoreContext();\n const loader = core.loaders?.subscriptionsLoader ?? core.apiClient.fetchSubscriptions;\n const owner = options.owner;\n const user = options.user;\n return useBillingCasdoorQuery(\n loader,\n useCallback(() => ({ owner, user }), [owner, user]),\n [loader, owner, user],\n 'Missing billing subscriptions loader.',\n );\n}\n\nexport interface BillingPricingPlansState {\n pricing?: BillingCasdoorPricingDetail;\n plans: BillingCasdoorPlanDetail[];\n selectedPlanName?: string;\n selectedPlan?: BillingCasdoorPlanDetail;\n setSelectedPlanName: (planName?: string) => void;\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingPricingPlans(\n pricingId: string,\n includeOption = false,\n preferredPlanName?: string,\n): BillingPricingPlansState {\n const pricingState = useBillingPricing(pricingId);\n const core = useRequiredCoreContext();\n const [selectedPlanName, setSelectedPlanName] = useState<string | undefined>(preferredPlanName);\n const planLoader = core.loaders?.planLoader ?? core.apiClient.fetchPlan;\n const [plans, setPlans] = useState<BillingCasdoorPlanDetail[]>([]);\n const [planLoading, setPlanLoading] = useState(false);\n const [planError, setPlanError] = useState<string | null>(null);\n\n useEffect(() => {\n if (preferredPlanName) {\n setSelectedPlanName(preferredPlanName);\n }\n }, [preferredPlanName]);\n\n useEffect(() => {\n const nextPlanName = selectedPlanName ?? pricingState.data?.plans?.[0];\n if (!nextPlanName || (selectedPlanName && pricingState.data?.plans && !pricingState.data.plans.includes(selectedPlanName))) {\n setSelectedPlanName(pricingState.data?.plans?.[0]);\n return;\n }\n if (!selectedPlanName && nextPlanName) {\n setSelectedPlanName(nextPlanName);\n }\n }, [pricingState.data?.plans, selectedPlanName]);\n\n const refreshPlans = useCallback(async () => {\n if (!planLoader) {\n setPlans([]);\n setPlanError('Missing billing plan loader.');\n setPlanLoading(false);\n return;\n }\n\n const planNames = pricingState.data?.plans ?? [];\n if (!planNames.length) {\n setPlans([]);\n setPlanError(null);\n setPlanLoading(false);\n return;\n }\n\n setPlanLoading(true);\n setPlanError(null);\n try {\n const results = await Promise.all(\n planNames.map(async (planName) => {\n const response = await planLoader({ id: planName, includeOption });\n return extractCasdoorResponseData<BillingCasdoorPlanDetail>(response);\n }),\n );\n setPlans(results.filter((plan): plan is BillingCasdoorPlanDetail => Boolean(plan)));\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n setPlans([]);\n setPlanError(message);\n } finally {\n setPlanLoading(false);\n }\n }, [includeOption, planLoader, pricingState.data?.plans]);\n\n useEffect(() => {\n void refreshPlans();\n }, [refreshPlans]);\n\n const selectedPlan = useMemo(\n () => plans.find((plan) => plan.name === selectedPlanName) ?? (plans.length === 1 ? plans[0] : undefined),\n [plans, selectedPlanName],\n );\n\n return useMemo(\n () => ({\n pricing: pricingState.data,\n plans,\n selectedPlanName,\n selectedPlan,\n setSelectedPlanName,\n loading: pricingState.loading || planLoading,\n error: pricingState.error ?? planError,\n refresh: async () => {\n await pricingState.refresh();\n await refreshPlans();\n },\n }),\n [planError, planLoading, plans, pricingState, refreshPlans, selectedPlan, selectedPlanName],\n );\n}\n\nexport interface BillingSubscriptionPurchaseOptionsState {\n pricing?: BillingCasdoorPricingDetail;\n plans: BillingCasdoorPlanDetail[];\n selectedPlanName?: string;\n selectedPlan?: BillingCasdoorPlanDetail;\n setSelectedPlanName: (planName?: string) => void;\n loading: boolean;\n error: string | null;\n refresh: () => Promise<void>;\n}\n\nexport function useBillingSubscriptionPurchaseOptions(\n pricingId: string,\n includeOption = false,\n preferredPlanName?: string,\n): BillingSubscriptionPurchaseOptionsState {\n const pricingPlans = useBillingPricingPlans(pricingId, includeOption, preferredPlanName);\n return useMemo(\n () => ({\n pricing: pricingPlans.pricing,\n plans: pricingPlans.plans,\n selectedPlanName: pricingPlans.selectedPlanName,\n selectedPlan: pricingPlans.selectedPlan,\n setSelectedPlanName: pricingPlans.setSelectedPlanName,\n loading: pricingPlans.loading,\n error: pricingPlans.error,\n refresh: pricingPlans.refresh,\n }),\n [pricingPlans],\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;;;ACZA,SAAS,kBAAkB;AA+BpB,SAAS,eAAe,SAA0D;AACvF,SAAO,qBAAqB,SAAS,IAAI;AAC3C;AAEO,SAAS,iBAAiB;AAC/B,SAAO,WAAW;AAGpB;AAEO,SAAS,cAA+B;AAC7C,QAAM,EAAE,MAAM,QAAQ,IAAI,eAAe;AACzC,SAAO,eAAe,WAAW,IAAI;AACvC;AAEO,SAAS,cAAwB;AACtC,SAAO,YAAY,EAAE;AACvB;AAEO,SAAS,eAAe,UAA8B,CAAC,GAAgB;AAC5E,QAAM,OAAO,YAAY;AACzB,QAAM,WAAW,QAAQ,YAAY;AAErC,SAAO;AAAA,IACL,WAAW,kBAAkB,SAAS,YAAY,MAAS;AAAA,IAC3D,YAAY,kBAAkB,UAAU,YAAY,MAAS;AAAA,IAC7D,YAAY;AAAA,IACZ,aAAa;AAAA,IACb,WAAW;AAAA,EACb;AACF;;;AC7DA;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAo3BG,gBAAAA,YAAA;AAlwBV,I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AAM;AAAA,IACV,OAAO,YAAkC;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"]}
@@ -74,6 +74,7 @@ npx @foldspace-fe/casdoor-next-auth-kit@latest check
74
74
  - `useAuthSession` — 获取当前 NextAuth 会话对象
75
75
  - `useAuthUser` — 获取当前登录用户信息(含 Casdoor 用户字段)
76
76
  - `useAuthRole` — 获取当前用户的角色信息,用于权限判断
77
+ - `role` 是一等认证字段,Casdoor profile、callback、JWT/session、`useAuthUser`、`useAuthRole` 和生成的 `auth-config.ts` 会一起维护它;`isAdmin` 仍然保留兼容推导,但不要只依赖它
77
78
  - `useAuthActions` — 提供登录、注册、注销等认证操作方法
78
79
  - Casdoor 登录 / 注册入口处理器 — 处理用户进入认证流程的初始交互
79
80
  - callback / logout / nextauth 路由处理器 — 处理 OAuth 回调、注销和 NextAuth 路由请求
@@ -113,7 +114,53 @@ npx @foldspace-fe/casdoor-next-auth-kit@latest check
113
114
  如果宿主希望注销后回到自定义配置页,可以在 `AuthKitConfig` 中设置 `logoutRedirectPath`,默认值为 `/`。
114
115
  若想通过环境变量控制默认值,可设置 `NEXT_PUBLIC_AUTH_LOGOUT_REDIRECT_PATH=/` 或其他同源路径。
115
116
 
116
- Billing 的购买白名单可以通过 `BillingCatalogConfig.purchasableIds` 或宿主注入的 `purchasables` 显式配置。宿主只需要在自己的项目里维护允许购买的少量条目,Casdoor 里可以继续保留更大的商品集合。
117
+ Billing 的购买白名单可以通过 `BillingCatalogConfig.purchasableIds` 或宿主注入的 `purchasables` 显式配置。宿主只需要在自己的项目里维护允许购买的少量条目,Casdoor 里可以继续保留更大的商品集合。订阅的 `pricing / plan` 不是 env 配置项,而是通过 `buildBillingSubscriptionCatalog()` 的 `mapPlan` 映射成 catalog 数据;env 模板里放的是白名单示例,不是定价本身。
118
+
119
+ 如果宿主要同时配订阅和商品,推荐直接按这个结构写:
120
+
121
+ ```ts
122
+ const membershipPlans = [
123
+ {
124
+ id: 'plan-basic',
125
+ code: 'membership-monthly',
126
+ name: 'Membership Monthly',
127
+ level: 'BASIC',
128
+ priceCents: 99900,
129
+ giftPoints: 10000,
130
+ billingCycle: 'MONTH',
131
+ benefits: {
132
+ faceLibrary: true,
133
+ monthlyReports: true,
134
+ },
135
+ },
136
+ ];
137
+
138
+ const subscriptionCatalog = buildBillingSubscriptionCatalog(membershipPlans, {
139
+ catalogKey: 'main',
140
+ title: 'Billing Catalog',
141
+ mapPlan: (plan) => ({
142
+ source: plan,
143
+ key: plan.code,
144
+ title: plan.name,
145
+ description: `${plan.level} membership`,
146
+ productId: 'qixiaoju/创小剧会员订阅',
147
+ planId: plan.id,
148
+ priceId: `pricing_${plan.code}`,
149
+ interval: 'month',
150
+ priceValue: plan.priceCents,
151
+ metadata: {
152
+ level: plan.level,
153
+ giftPoints: String(plan.giftPoints),
154
+ billingCycle: plan.billingCycle,
155
+ },
156
+ }),
157
+ });
158
+
159
+ const billingCatalog = {
160
+ ...subscriptionCatalog,
161
+ purchasableIds: [...subscriptionCatalog.purchasableIds, 'credits-50'],
162
+ };
163
+ ```
117
164
 
118
165
  商品购买的包内适配器会优先读取 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/*`。
119
166
 
@@ -364,6 +411,7 @@ NEXTAUTH_URL=http://localhost:5177
364
411
  - `prisma/auth-kit.prisma`
365
412
  - `.env`、`.env.local`、`.env.production`、`.env.example`
366
413
  - `.agents/skills/casdoor-next-auth-kit/SKILL.md`
414
+ - 其中 `NEXT_PUBLIC_BILLING_PURCHASABLE_IDS` 的默认示例值会写成 `membership-monthly,credits-50`
367
415
  4. 如果 `check` 仍然报缺失,优先排查这些问题
368
416
  - 宿主项目还没重新安装到新的包产物,先回到本仓库执行 `pnpm build`
369
417
  - 宿主项目没重新安装依赖,执行 `pnpm install` 后再跑一次 `update`
@@ -21,12 +21,14 @@ interface OAuthTokens {
21
21
  token_type?: string;
22
22
  [key: string]: unknown;
23
23
  }
24
+ type AuthUserRole = 'user' | 'admin';
24
25
  interface AuthUser {
25
26
  id: string;
26
27
  name: string | null;
27
28
  email: string | null;
28
29
  image: string | null;
29
30
  isAdmin: boolean;
31
+ role: AuthUserRole;
30
32
  tokenBalance: number;
31
33
  isVip: boolean;
32
34
  }
@@ -119,4 +121,4 @@ interface PrismaSchemaModelDefinition {
119
121
  blockAttributes?: string[];
120
122
  }
121
123
 
122
- export type { AuthKitConfig as A, CasdoorUserInfo as C, ManagedEnvFile as M, OAuthTokens as O, PrismaSchemaModelDefinition as P, AuthBusinessAdapter as a, AuthPersistenceAdapter as b, AuthUser as c, ManagedEnvVariableDefinition as d, AuthIndexHtmlOptions as e, AuthDatabaseContract as f, AuthDatabaseFieldRequirement as g, AuthDatabaseTableRequirement as h, AuthRuntimeContext as i, PrismaSchemaFieldDefinition as j };
124
+ export type { AuthUserRole as A, CasdoorUserInfo as C, ManagedEnvFile as M, OAuthTokens as O, PrismaSchemaModelDefinition as P, AuthUser as a, AuthKitConfig as b, AuthBusinessAdapter as c, AuthPersistenceAdapter as d, AuthIndexHtmlOptions as e, AuthDatabaseContract as f, AuthDatabaseFieldRequirement as g, AuthDatabaseTableRequirement as h, AuthRuntimeContext as i, ManagedEnvVariableDefinition as j, PrismaSchemaFieldDefinition as k };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldspace-fe/casdoor-next-auth-kit",
3
- "version": "0.1.22",
3
+ "version": "0.1.24",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "repository": {
@@ -1,12 +0,0 @@
1
- import { NextRequest, NextResponse } from 'next/server';
2
- import { A as AuthKitConfig, a as AuthBusinessAdapter, b as AuthPersistenceAdapter } from './types-BJv6j3NZ.js';
3
-
4
- interface CallbackHandlerOptions {
5
- config: AuthKitConfig;
6
- adapter?: AuthBusinessAdapter;
7
- persistence?: AuthPersistenceAdapter;
8
- }
9
- declare function createCallbackResponse(request: NextRequest, options: CallbackHandlerOptions): Promise<NextResponse>;
10
- declare function createCallbackHandler(options: CallbackHandlerOptions): (request: NextRequest) => Promise<NextResponse<unknown>>;
11
-
12
- export { type CallbackHandlerOptions as C, createCallbackResponse as a, createCallbackHandler as c };