@clerk/shared 4.0.0-snapshot.v20251215203425 → 4.0.0-snapshot.v20251215210631

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["React","SWRConfig","React","newObj: Record<string, unknown>","differentKeysObject: Record<string, unknown>","usePagesOrInfinite: UsePagesOrInfiniteSignature","fetchPage: ValueOrSetter<number>","eventMethodCalled","hookParams: GetAPIKeysParams","params","undefinedPaginatedResource","eventMethodCalled","getCurrentOrganizationMembership","eventMethodCalled","React","hookName","useSession: UseSession","eventMethodCalled","hookName","eventMethodCalled","hookName","eventMethodCalled","React","useDeepEqualMemo: UseDeepEqualMemo","deepEqual","isClerkAPIResponseError","reverificationError","isReverificationHint","createDeferredPromise","validateReverificationConfig","ClerkRuntimeError","useReverification: UseReverification","eventMethodCalled","hookName","eventMethodCalled","eventMethodCalled","swr","queryKey","swr","swr","swr","queryKey","React","Elements: FunctionComponent<PropsWithChildren<ElementsProps>>","ctx","keySet: { [key: string]: boolean }","ClientElement: FunctionComponent<PrivateElementProps>","readyCallback: UnknownCallback | undefined","newElement: StripeElement | null","ServerElement: FunctionComponent<PrivateElementProps>","PaymentElement: FunctionComponent<\n PaymentElementProps & {\n fallback?: ReactNode;\n }\n>","stripePublishableKey","externalGatewayId","StripePaymentElement","React"],"sources":["../../../src/react/hooks/createContextAndHook.ts","../../../src/react/providers/SWRConfigCompat.swr.tsx","../../../src/react/contexts.tsx","../../../src/react/stable-keys.ts","../../../src/react/hooks/createCacheKeys.ts","../../../src/react/hooks/usePagesOrInfinite.shared.ts","../../../src/react/hooks/usePreviousValue.ts","../../../src/react/hooks/usePagesOrInfinite.swr.tsx","../../../src/react/hooks/useAPIKeys.swr.tsx","../../../src/react/hooks/useClerk.ts","../../../src/react/hooks/useAttemptToEnableOrganizations.ts","../../../src/react/hooks/useOrganization.tsx","../../../src/react/hooks/useOrganizationList.tsx","../../../src/react/hooks/useSafeLayoutEffect.tsx","../../../src/react/hooks/useSession.ts","../../../src/react/hooks/useSessionList.ts","../../../src/react/hooks/useUser.ts","../../../src/react/hooks/useDeepEqualMemo.ts","../../../src/react/hooks/useReverification.ts","../../../src/react/hooks/useBillingHookEnabled.ts","../../../src/react/hooks/createBillingPaginatedHook.tsx","../../../src/react/hooks/useStatements.tsx","../../../src/react/hooks/usePaymentAttempts.tsx","../../../src/react/hooks/usePaymentMethods.tsx","../../../src/react/hooks/usePlans.tsx","../../../src/react/hooks/useSubscription.shared.ts","../../../src/react/hooks/useSubscription.swr.tsx","../../../src/react/hooks/useCheckout.ts","../../../src/react/hooks/useStatementQuery.shared.ts","../../../src/react/hooks/useStatementQuery.swr.tsx","../../../src/react/hooks/usePlanDetailsQuery.shared.ts","../../../src/react/hooks/usePlanDetailsQuery.swr.tsx","../../../src/react/hooks/usePaymentAttemptQuery.shared.ts","../../../src/react/hooks/usePaymentAttemptQuery.swr.tsx","../../../src/react/stripe-react/utils.ts","../../../src/react/stripe-react/index.tsx","../../../src/react/billing/useInitializePaymentMethod.swr.tsx","../../../src/react/billing/useStripeClerkLibs.swr.tsx","../../../src/react/billing/useStripeLoader.swr.tsx","../../../src/react/billing/payment-element.tsx","../../../src/react/portal-root-manager.ts","../../../src/react/PortalProvider.tsx"],"sourcesContent":["'use client';\nimport React from 'react';\n\n/**\n * Assert that the context value exists, otherwise throw an error.\n *\n * @internal\n */\nexport function assertContextExists(contextVal: unknown, msgOrCtx: string | React.Context<any>): asserts contextVal {\n if (!contextVal) {\n throw typeof msgOrCtx === 'string' ? new Error(msgOrCtx) : new Error(`${msgOrCtx.displayName} not found`);\n }\n}\n\ntype Options = { assertCtxFn?: (v: unknown, msg: string) => void };\ntype ContextOf<T> = React.Context<{ value: T } | undefined>;\ntype UseCtxFn<T> = () => T;\n\n/**\n * Create and return a Context and two hooks that return the context value.\n * The Context type is derived from the type passed in by the user.\n *\n * The first hook returned guarantees that the context exists so the returned value is always `CtxValue`\n * The second hook makes no guarantees, so the returned value can be `CtxValue | undefined`\n *\n * @internal\n */\nexport const createContextAndHook = <CtxVal>(\n displayName: string,\n options?: Options,\n): [ContextOf<CtxVal>, UseCtxFn<CtxVal>, UseCtxFn<CtxVal | Partial<CtxVal>>] => {\n const { assertCtxFn = assertContextExists } = options || {};\n const Ctx = React.createContext<{ value: CtxVal } | undefined>(undefined);\n Ctx.displayName = displayName;\n\n const useCtx = () => {\n const ctx = React.useContext(Ctx);\n assertCtxFn(ctx, `${displayName} not found`);\n return (ctx as any).value as CtxVal;\n };\n\n const useCtxWithoutGuarantee = () => {\n const ctx = React.useContext(Ctx);\n return ctx ? ctx.value : {};\n };\n\n return [Ctx, useCtx, useCtxWithoutGuarantee];\n};\n","import React, { type PropsWithChildren } from 'react';\nimport { SWRConfig } from 'swr';\n\n/**\n * @internal\n */\nexport function SWRConfigCompat({ swrConfig, children }: PropsWithChildren<{ swrConfig?: any }>) {\n // TODO: Replace SWRConfig with the react-query equivalent.\n return <SWRConfig value={swrConfig}>{children}</SWRConfig>;\n}\n","'use client';\n\nimport type { PropsWithChildren } from 'react';\nimport React from 'react';\n\nimport type {\n BillingSubscriptionPlanPeriod,\n ClerkOptions,\n ClientResource,\n ForPayerType,\n LoadedClerk,\n OrganizationResource,\n SignedInSessionResource,\n UserResource,\n} from '../types';\nimport { createContextAndHook } from './hooks/createContextAndHook';\nimport { SWRConfigCompat } from './providers/SWRConfigCompat';\n\nconst [ClerkInstanceContext, useClerkInstanceContext] = createContextAndHook<LoadedClerk>('ClerkInstanceContext');\nconst [UserContext, useUserContext] = createContextAndHook<UserResource | null | undefined>('UserContext');\nconst [ClientContext, useClientContext] = createContextAndHook<ClientResource | null | undefined>('ClientContext');\nconst [SessionContext, useSessionContext] = createContextAndHook<SignedInSessionResource | null | undefined>(\n 'SessionContext',\n);\n\nconst OptionsContext = React.createContext<ClerkOptions>({});\n\n/**\n * @interface\n */\nexport type UseCheckoutOptions = {\n /**\n * Specifies if the checkout is for an Organization.\n *\n * @default 'user'\n */\n for?: ForPayerType;\n /**\n * The billing period for the Plan.\n */\n planPeriod: BillingSubscriptionPlanPeriod;\n /**\n * The ID of the Subscription Plan to check out (e.g. `cplan_xxx`).\n */\n planId: string;\n};\n\nconst [CheckoutContext, useCheckoutContext] = createContextAndHook<UseCheckoutOptions>('CheckoutContext');\n\nconst __experimental_CheckoutProvider = ({ children, ...rest }: PropsWithChildren<UseCheckoutOptions>) => {\n return <CheckoutContext.Provider value={{ value: rest }}>{children}</CheckoutContext.Provider>;\n};\n\n/**\n * @internal\n */\nfunction useOptionsContext(): ClerkOptions {\n const context = React.useContext(OptionsContext);\n if (context === undefined) {\n throw new Error('useOptions must be used within an OptionsContext');\n }\n return context;\n}\n\ntype OrganizationContextProps = {\n organization: OrganizationResource | null | undefined;\n};\nconst [OrganizationContextInternal, useOrganizationContext] = createContextAndHook<{\n organization: OrganizationResource | null | undefined;\n}>('OrganizationContext');\n\nconst OrganizationProvider = ({\n children,\n organization,\n swrConfig,\n}: PropsWithChildren<\n OrganizationContextProps & {\n // Exporting inferred types directly from SWR will result in error while building declarations\n swrConfig?: any;\n }\n>) => {\n return (\n <SWRConfigCompat swrConfig={swrConfig}>\n <OrganizationContextInternal.Provider\n value={{\n value: { organization },\n }}\n >\n {children}\n </OrganizationContextInternal.Provider>\n </SWRConfigCompat>\n );\n};\n\n/**\n * @internal\n */\nfunction useAssertWrappedByClerkProvider(displayNameOrFn: string | (() => void)): void {\n const ctx = React.useContext(ClerkInstanceContext);\n\n if (!ctx) {\n if (typeof displayNameOrFn === 'function') {\n displayNameOrFn();\n return;\n }\n\n throw new Error(\n `${displayNameOrFn} can only be used within the <ClerkProvider /> component.\n\nPossible fixes:\n1. Ensure that the <ClerkProvider /> is correctly wrapping your application where this component is used.\n2. Check for multiple versions of the \\`@clerk/shared\\` package in your project. Use a tool like \\`npm ls @clerk/shared\\` to identify multiple versions, and update your dependencies to only rely on one.\n\nLearn more: https://clerk.com/docs/components/clerk-provider`.trim(),\n );\n }\n}\n\nexport {\n __experimental_CheckoutProvider,\n ClerkInstanceContext,\n ClientContext,\n OptionsContext,\n OrganizationProvider,\n SessionContext,\n useAssertWrappedByClerkProvider,\n useCheckoutContext,\n useClerkInstanceContext,\n useClientContext,\n useOptionsContext,\n useOrganizationContext,\n UserContext,\n useSessionContext,\n useUserContext,\n};\n","// Keys for `useOrganizationList`\nconst USER_MEMBERSHIPS_KEY = 'userMemberships';\nconst USER_INVITATIONS_KEY = 'userInvitations';\nconst USER_SUGGESTIONS_KEY = 'userSuggestions';\n\n// Keys for `useOrganization`\nconst DOMAINS_KEY = 'domains';\nconst MEMBERSHIP_REQUESTS_KEY = 'membershipRequests';\nconst MEMBERSHIPS_KEY = 'memberships';\nconst INVITATIONS_KEY = 'invitations';\n\n// Keys for `useAPIKeys`\nconst API_KEYS_KEY = 'apiKeys';\n\n// Keys for `usePlans`\nconst PLANS_KEY = 'billing-plans';\n\n// Keys for `useSubscription`\nconst SUBSCRIPTION_KEY = 'billing-subscription';\n\n// Keys for `usePaymentMethods`\nconst PAYMENT_METHODS_KEY = 'billing-payment-methods';\n\n// Keys for `usePaymentAttempts`\nconst PAYMENT_ATTEMPTS_KEY = 'billing-payment-attempts';\n\n// Keys for `useStatements`\nconst STATEMENTS_KEY = 'billing-statements';\n\nexport const STABLE_KEYS = {\n // Keys for `useOrganizationList`\n USER_MEMBERSHIPS_KEY,\n USER_INVITATIONS_KEY,\n USER_SUGGESTIONS_KEY,\n\n // Keys for `useOrganization`\n DOMAINS_KEY,\n MEMBERSHIP_REQUESTS_KEY,\n MEMBERSHIPS_KEY,\n INVITATIONS_KEY,\n\n // Keys for billing\n PLANS_KEY,\n SUBSCRIPTION_KEY,\n PAYMENT_METHODS_KEY,\n PAYMENT_ATTEMPTS_KEY,\n STATEMENTS_KEY,\n\n // Keys for `useAPIKeys`\n API_KEYS_KEY,\n} as const;\n\nexport type ResourceCacheStableKey = (typeof STABLE_KEYS)[keyof typeof STABLE_KEYS];\n\n/**\n * Internal stable keys for queries only used by our UI components.\n * These keys are not used by the hooks themselves.\n */\n\nconst PAYMENT_ATTEMPT_KEY = 'billing-payment-attempt';\nconst BILLING_PLANS_KEY = 'billing-plan';\nconst BILLING_STATEMENTS_KEY = 'billing-statement';\nexport const INTERNAL_STABLE_KEYS = {\n PAYMENT_ATTEMPT_KEY,\n BILLING_PLANS_KEY,\n BILLING_STATEMENTS_KEY,\n} as const;\n\nexport type __internal_ResourceCacheStableKey = (typeof INTERNAL_STABLE_KEYS)[keyof typeof INTERNAL_STABLE_KEYS];\n","import type { __internal_ResourceCacheStableKey, ResourceCacheStableKey } from '../stable-keys';\nimport type { QueryKeyWithArgs } from './usePageOrInfinite.types';\n\n/**\n * @internal\n */\nexport function createCacheKeys<\n Params,\n T extends Record<string, unknown> = Record<string, unknown>,\n U extends Record<string, unknown> | undefined = undefined,\n>(params: {\n stablePrefix: ResourceCacheStableKey | __internal_ResourceCacheStableKey;\n authenticated: boolean;\n tracked: T;\n untracked: U extends { args: Params } ? U : never;\n}) {\n return {\n queryKey: [params.stablePrefix, params.authenticated, params.tracked, params.untracked] as const,\n invalidationKey: [params.stablePrefix, params.authenticated, params.tracked] as const,\n stableKey: params.stablePrefix,\n authenticated: params.authenticated,\n };\n}\n\n/**\n * @internal\n */\nexport function toSWRQuery<T extends { queryKey: QueryKeyWithArgs<unknown> }>(keys: T) {\n const { queryKey } = keys;\n return {\n type: queryKey[0],\n ...queryKey[2],\n ...(queryKey[3] as { args: Record<string, unknown> }).args,\n };\n}\n","import { useRef } from 'react';\n\nimport type { PagesOrInfiniteOptions } from '../types';\n\n/**\n * A hook that safely merges user-provided pagination options with default values.\n * It caches initial pagination values (page and size) until component unmount to prevent unwanted rerenders.\n *\n * @internal\n *\n * @example\n * ```typescript\n * // Example 1: With user-provided options\n * const userOptions = { initialPage: 2, pageSize: 20, infinite: true };\n * const defaults = { initialPage: 1, pageSize: 10, infinite: false };\n * useWithSafeValues(userOptions, defaults);\n * // Returns { initialPage: 2, pageSize: 20, infinite: true }\n *\n * // Example 2: With boolean true (use defaults)\n * const params = true;\n * const defaults = { initialPage: 1, pageSize: 10, infinite: false };\n * useWithSafeValues(params, defaults);\n * // Returns { initialPage: 1, pageSize: 10, infinite: false }\n *\n * // Example 3: With undefined options (fallback to defaults)\n * const params = undefined;\n * const defaults = { initialPage: 1, pageSize: 10, infinite: false };\n * useWithSafeValues(params, defaults);\n * // Returns { initialPage: 1, pageSize: 10, infinite: false }\n * ```\n */\nexport const useWithSafeValues = <T extends PagesOrInfiniteOptions>(params: T | true | undefined, defaultValues: T) => {\n const shouldUseDefaults = typeof params === 'boolean' && params;\n\n // Cache initialPage and initialPageSize until unmount\n const initialPageRef = useRef(\n shouldUseDefaults ? defaultValues.initialPage : (params?.initialPage ?? defaultValues.initialPage),\n );\n const pageSizeRef = useRef(shouldUseDefaults ? defaultValues.pageSize : (params?.pageSize ?? defaultValues.pageSize));\n\n const newObj: Record<string, unknown> = {};\n for (const key of Object.keys(defaultValues)) {\n // @ts-ignore - indexing into generic param to preserve unknown keys from defaults/params\n newObj[key] = shouldUseDefaults ? defaultValues[key] : (params?.[key] ?? defaultValues[key]);\n }\n\n return {\n ...newObj,\n initialPage: initialPageRef.current,\n pageSize: pageSizeRef.current,\n } as T;\n};\n\n/**\n * Returns an object containing only the keys from the first object that are not present in the second object.\n * Useful for extracting unique parameters that should be passed to a request while excluding common cache keys.\n *\n * @internal\n *\n * @example\n * ```typescript\n * // Example 1: Basic usage\n * const obj1 = { name: 'John', age: 30, city: 'NY' };\n * const obj2 = { name: 'John', age: 30 };\n * getDifferentKeys(obj1, obj2); // Returns { city: 'NY' }\n *\n * // Example 2: With cache keys\n * const requestParams = { page: 1, limit: 10, userId: '123' };\n * const cacheKeys = { userId: '123' };\n * getDifferentKeys(requestParams, cacheKeys); // Returns { page: 1, limit: 10 }\n * ```\n */\nexport function getDifferentKeys(\n obj1: Record<string, unknown>,\n obj2: Record<string, unknown>,\n): Record<string, unknown> {\n const keysSet = new Set(Object.keys(obj2));\n const differentKeysObject: Record<string, unknown> = {};\n\n for (const key1 of Object.keys(obj1)) {\n if (!keysSet.has(key1)) {\n differentKeysObject[key1] = obj1[key1];\n }\n }\n\n return differentKeysObject;\n}\n","import { useRef } from 'react';\n\ntype Primitive = string | number | boolean | bigint | symbol | null | undefined;\n\n/**\n * A hook that retains the previous value of a primitive type.\n * It uses a ref to prevent causing unnecessary re-renders.\n *\n * @internal\n *\n * @example\n * ```\n * Render 1: value = 'A' → returns null\n * Render 2: value = 'B' → returns 'A'\n * Render 3: value = 'B' → returns 'A'\n * Render 4: value = 'B' → returns 'A'\n * Render 5: value = 'C' → returns 'B'\n * ```\n */\nexport function usePreviousValue<T extends Primitive>(value: T) {\n const currentRef = useRef(value);\n const previousRef = useRef<T | null>(null);\n\n if (currentRef.current !== value) {\n previousRef.current = currentRef.current;\n currentRef.current = value;\n }\n\n return previousRef.current;\n}\n","'use client';\n\nimport { useCallback, useMemo, useRef, useState } from 'react';\n\nimport { useSWR, useSWRInfinite } from '../clerk-swr';\nimport type { CacheSetter, ValueOrSetter } from '../types';\nimport { toSWRQuery } from './createCacheKeys';\nimport type { UsePagesOrInfiniteSignature } from './usePageOrInfinite.types';\nimport { getDifferentKeys, useWithSafeValues } from './usePagesOrInfinite.shared';\nimport { usePreviousValue } from './usePreviousValue';\n\nconst cachingSWROptions = {\n dedupingInterval: 1000 * 60,\n focusThrottleInterval: 1000 * 60 * 2,\n} satisfies Parameters<typeof useSWR>[2];\n\nconst cachingSWRInfiniteOptions = {\n ...cachingSWROptions,\n revalidateFirstPage: false,\n} satisfies Parameters<typeof useSWRInfinite>[2];\n\n/**\n * A flexible pagination hook that supports both traditional pagination and infinite loading.\n * It provides a unified API for handling paginated data fetching, with built-in caching through SWR.\n * The hook can operate in two modes:\n * - Traditional pagination: Fetches one page at a time with page navigation\n * - Infinite loading: Accumulates data as more pages are loaded.\n *\n * Features:\n * - Cache management with SWR\n * - Loading and error states\n * - Page navigation helpers\n * - Data revalidation and updates\n * - Support for keeping previous data while loading.\n *\n * @internal\n */\nexport const usePagesOrInfinite: UsePagesOrInfiniteSignature = params => {\n const { fetcher, config, keys } = params;\n const [paginatedPage, setPaginatedPage] = useState(config.initialPage ?? 1);\n\n // Cache initialPage and initialPageSize until unmount\n const initialPageRef = useRef(config.initialPage ?? 1);\n const pageSizeRef = useRef(config.pageSize ?? 10);\n\n const enabled = config.enabled ?? true;\n const cacheMode = config.__experimental_mode === 'cache';\n const triggerInfinite = config.infinite ?? false;\n const keepPreviousData = config.keepPreviousData ?? false;\n const isSignedIn = config.isSignedIn;\n\n const pagesCacheKey = {\n ...toSWRQuery(keys),\n initialPage: paginatedPage,\n pageSize: pageSizeRef.current,\n };\n\n const previousIsSignedIn = usePreviousValue(isSignedIn);\n\n // cacheMode being `true` indicates that the cache key is defined, but the fetcher is not.\n // This allows to ready the cache instead of firing a request.\n const shouldFetch = !triggerInfinite && enabled && (!cacheMode ? !!fetcher : true);\n\n // Attention:\n //\n // This complex logic is necessary to ensure that the cached data is not used when the user is signed out.\n // `useSWR` with `key` set to `null` and `keepPreviousData` set to `true` will return the previous cached data until the hook unmounts.\n // So for hooks that render authenticated data, we need to ensure that the cached data is not used when the user is signed out.\n //\n // 1. Fetcher should not fire if user is signed out on mount. (fetcher does not run, loading states are not triggered)\n // 2. If user was signed in and then signed out, cached data should become null. (fetcher runs and returns null, loading states are triggered)\n //\n // We achieve (2) by setting the key to the cache key when the user transitions to signed out and forcing the fetcher to return null.\n const swrKey =\n typeof isSignedIn === 'boolean'\n ? previousIsSignedIn === true && isSignedIn === false\n ? pagesCacheKey\n : isSignedIn\n ? shouldFetch\n ? pagesCacheKey\n : null\n : null\n : shouldFetch\n ? pagesCacheKey\n : null;\n\n const swrFetcher =\n !cacheMode && !!fetcher\n ? (cacheKeyParams: Record<string, unknown>) => {\n if (isSignedIn === false || shouldFetch === false) {\n return null;\n }\n const requestParams = getDifferentKeys(cacheKeyParams, { type: keys.queryKey[0], ...keys.queryKey[2] });\n // @ts-ignore - fetcher expects Params subset; narrowing at call-site\n return fetcher(requestParams);\n }\n : null;\n\n const {\n data: swrData,\n isValidating: swrIsValidating,\n isLoading: swrIsLoading,\n error: swrError,\n mutate: swrMutate,\n } = useSWR(swrKey, swrFetcher, { keepPreviousData, ...cachingSWROptions });\n\n // Attention:\n //\n // Cache behavior for infinite loading when signing out:\n //\n // Unlike `useSWR` above (which requires complex transition handling), `useSWRInfinite` has simpler sign-out semantics:\n // 1. When user is signed out on mount, the key getter returns `null`, preventing any fetches.\n // 2. When user transitions from signed in to signed out, the key getter returns `null` for all page indices.\n // 3. When `useSWRInfinite`'s key getter returns `null`, SWR will not fetch data and considers that page invalid.\n // 4. Unlike paginated mode, `useSWRInfinite` does not support `keepPreviousData`, so there's no previous data retention.\n //\n // This simpler behavior works because:\n // - `useSWRInfinite` manages multiple pages internally, each with its own cache key\n // - When the key getter returns `null`, all page fetches are prevented and pages become invalid\n // - Without `keepPreviousData`, the hook will naturally reflect the empty/invalid state\n //\n // Result: No special transition logic needed - just return `null` from key getter when `isSignedIn === false`.\n const {\n data: swrInfiniteData,\n isLoading: swrInfiniteIsLoading,\n isValidating: swrInfiniteIsValidating,\n error: swrInfiniteError,\n size,\n setSize,\n mutate: swrInfiniteMutate,\n } = useSWRInfinite(\n pageIndex => {\n if (!triggerInfinite || !enabled || isSignedIn === false) {\n return null;\n }\n\n return {\n ...toSWRQuery(keys),\n initialPage: initialPageRef.current + pageIndex,\n pageSize: pageSizeRef.current,\n };\n },\n cacheKeyParams => {\n // @ts-ignore - fetcher expects Params subset; narrowing at call-site\n const requestParams = getDifferentKeys(cacheKeyParams, { type: keys.queryKey[0], ...keys.queryKey[2] });\n // @ts-ignore - fetcher expects Params subset; narrowing at call-site\n return fetcher?.(requestParams);\n },\n cachingSWRInfiniteOptions,\n );\n\n const page = useMemo(() => {\n if (triggerInfinite) {\n return size;\n }\n return paginatedPage;\n }, [triggerInfinite, size, paginatedPage]);\n\n const fetchPage: ValueOrSetter<number> = useCallback(\n numberOrgFn => {\n if (triggerInfinite) {\n void setSize(numberOrgFn);\n return;\n }\n return setPaginatedPage(numberOrgFn);\n },\n [setSize, triggerInfinite],\n );\n\n const data = useMemo(() => {\n if (triggerInfinite) {\n return swrInfiniteData?.map(a => a?.data).flat() ?? [];\n }\n return swrData?.data ?? [];\n }, [triggerInfinite, swrData, swrInfiniteData]);\n\n const count = useMemo(() => {\n if (triggerInfinite) {\n return swrInfiniteData?.[swrInfiniteData?.length - 1]?.total_count || 0;\n }\n return swrData?.total_count ?? 0;\n }, [triggerInfinite, swrData, swrInfiniteData]);\n\n const isLoading = triggerInfinite ? swrInfiniteIsLoading : swrIsLoading;\n const isFetching = triggerInfinite ? swrInfiniteIsValidating : swrIsValidating;\n const error = (triggerInfinite ? swrInfiniteError : swrError) ?? null;\n const isError = !!error;\n\n const fetchNext = useCallback(() => {\n fetchPage(n => Math.max(0, n + 1));\n }, [fetchPage]);\n\n const fetchPrevious = useCallback(() => {\n fetchPage(n => Math.max(0, n - 1));\n }, [fetchPage]);\n\n const offsetCount = (initialPageRef.current - 1) * pageSizeRef.current;\n\n const pageCount = Math.ceil((count - offsetCount) / pageSizeRef.current);\n const hasNextPage = count - offsetCount * pageSizeRef.current > page * pageSizeRef.current;\n const hasPreviousPage = (page - 1) * pageSizeRef.current > offsetCount * pageSizeRef.current;\n\n const setData: CacheSetter = triggerInfinite\n ? value =>\n swrInfiniteMutate(value, {\n revalidate: false,\n })\n : value =>\n swrMutate(value, {\n revalidate: false,\n });\n\n const revalidate = triggerInfinite ? () => swrInfiniteMutate() : () => swrMutate();\n\n return {\n data,\n count,\n error,\n isLoading,\n isFetching,\n isError,\n page,\n pageCount,\n fetchPage,\n fetchNext,\n fetchPrevious,\n hasNextPage,\n hasPreviousPage,\n // Let the hook return type define this type\n revalidate: revalidate as any,\n // Let the hook return type define this type\n setData: setData as any,\n };\n};\n\nexport { useWithSafeValues };\n","import { useCallback } from 'react';\nimport { useSWRConfig } from 'swr';\n\nimport { eventMethodCalled } from '../../telemetry/events/method-called';\nimport type { APIKeyResource, GetAPIKeysParams } from '../../types';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext } from '../contexts';\nimport { STABLE_KEYS } from '../stable-keys';\nimport type { PaginatedHookConfig, PaginatedResources } from '../types';\nimport { createCacheKeys } from './createCacheKeys';\nimport { usePagesOrInfinite, useWithSafeValues } from './usePagesOrInfinite';\n\n/**\n * @internal\n */\nexport type UseAPIKeysParams = PaginatedHookConfig<\n GetAPIKeysParams & {\n /**\n * If `true`, a request will be triggered when the hook is mounted.\n *\n * @default true\n */\n enabled?: boolean;\n }\n>;\n\n/**\n * @internal\n */\nexport type UseAPIKeysReturn<T extends UseAPIKeysParams> = PaginatedResources<\n APIKeyResource,\n T extends { infinite: true } ? true : false\n>;\n\n/**\n * @internal\n *\n * The `useAPIKeys()` hook provides access to paginated API keys for the current user or organization.\n *\n * @example\n * ### Basic usage with default pagination\n *\n * ```tsx\n * const { data, isLoading, page, pageCount, fetchNext, fetchPrevious } = useAPIKeys({\n * subject: 'user_123',\n * pageSize: 10,\n * initialPage: 1,\n * });\n * ```\n *\n * @example\n * ### With search query\n *\n * ```tsx\n * const [searchValue, setSearchValue] = useState('');\n * const debouncedSearch = useDebounce(searchValue, 500);\n *\n * const { data, isLoading } = useAPIKeys({\n * subject: 'user_123',\n * query: debouncedSearch.trim(),\n * pageSize: 10,\n * });\n * ```\n *\n * @example\n * ### Infinite scroll\n *\n * ```tsx\n * const { data, isLoading, fetchNext, hasNextPage } = useAPIKeys({\n * subject: 'user_123',\n * infinite: true,\n * });\n * ```\n */\nexport function useAPIKeys<T extends UseAPIKeysParams>(params?: T): UseAPIKeysReturn<T> {\n useAssertWrappedByClerkProvider('useAPIKeys');\n\n const safeValues = useWithSafeValues(params, {\n initialPage: 1,\n pageSize: 10,\n keepPreviousData: false,\n infinite: false,\n subject: '',\n query: '',\n enabled: true,\n } as UseAPIKeysParams);\n\n const clerk = useClerkInstanceContext();\n\n clerk.telemetry?.record(eventMethodCalled('useAPIKeys'));\n\n const hookParams: GetAPIKeysParams = {\n initialPage: safeValues.initialPage,\n pageSize: safeValues.pageSize,\n ...(safeValues.subject ? { subject: safeValues.subject } : {}),\n ...(safeValues.query ? { query: safeValues.query } : {}),\n };\n\n const isEnabled = (safeValues.enabled ?? true) && clerk.loaded;\n\n const result = usePagesOrInfinite({\n fetcher: clerk.apiKeys?.getAll\n ? (params: GetAPIKeysParams) => clerk.apiKeys.getAll({ ...params, subject: safeValues.subject })\n : undefined,\n config: {\n keepPreviousData: safeValues.keepPreviousData,\n infinite: safeValues.infinite,\n enabled: isEnabled,\n isSignedIn: Boolean(clerk.user),\n initialPage: safeValues.initialPage,\n pageSize: safeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: STABLE_KEYS.API_KEYS_KEY,\n authenticated: Boolean(clerk.user),\n tracked: {\n subject: safeValues.subject,\n },\n untracked: {\n args: hookParams,\n },\n }),\n }) as UseAPIKeysReturn<T>;\n\n const { mutate } = useSWRConfig();\n\n // Invalidate all cache entries for this user or organization\n const invalidateAll = useCallback(() => {\n return mutate(key => {\n if (!key || typeof key !== 'object') {\n return false;\n }\n // Match all apiKeys cache entries for this user or organization, regardless of page, pageSize, or query\n return 'type' in key && key.type === 'apiKeys' && 'subject' in key && key.subject === safeValues.subject;\n });\n }, [mutate, safeValues.subject]);\n\n return {\n ...result,\n revalidate: invalidateAll as any,\n };\n}\n","import type { LoadedClerk } from '../../types';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext } from '../contexts';\n\n/**\n * > [!WARNING]\n * > This hook should only be used for advanced use cases, such as building a completely custom OAuth flow or as an escape hatch to access to the `Clerk` object.\n *\n * The `useClerk()` hook provides access to the [`Clerk`](https://clerk.com/docs/reference/javascript/clerk) object, allowing you to build alternatives to any Clerk Component.\n *\n * @function\n *\n * @returns The `useClerk()` hook returns the `Clerk` object, which includes all the methods and properties listed in the [`Clerk` reference](https://clerk.com/docs/reference/javascript/clerk).\n *\n * @example\n *\n * The following example uses the `useClerk()` hook to access the `clerk` object. The `clerk` object is used to call the [`openSignIn()`](https://clerk.com/docs/reference/javascript/clerk#sign-in) method to open the sign-in modal.\n *\n * <Tabs items='React,Next.js'>\n * <Tab>\n *\n * ```tsx {{ filename: 'src/Home.tsx' }}\n * import { useClerk } from '@clerk/react'\n *\n * export default function Home() {\n * const clerk = useClerk()\n *\n * return <button onClick={() => clerk.openSignIn({})}>Sign in</button>\n * }\n * ```\n *\n * </Tab>\n * <Tab>\n *\n * {@include ../../../docs/use-clerk.md#nextjs-01}\n *\n * </Tab>\n * </Tabs>\n */\nexport const useClerk = (): LoadedClerk => {\n useAssertWrappedByClerkProvider('useClerk');\n return useClerkInstanceContext();\n};\n","import { useEffect, useRef } from 'react';\n\nimport { useClerk } from './useClerk';\n\n/**\n * Attempts to enable the organizations environment setting for a given caller\n *\n * @internal\n */\nexport function useAttemptToEnableOrganizations(caller: 'useOrganization' | 'useOrganizationList') {\n const clerk = useClerk();\n const hasAttempted = useRef(false);\n\n useEffect(() => {\n // Guard to not run this effect twice on Clerk resource update\n if (hasAttempted.current) {\n return;\n }\n\n hasAttempted.current = true;\n // Optional chaining is important for `@clerk/clerk-react` usage with older clerk-js versions that don't have the method\n clerk.__internal_attemptToEnableEnvironmentSetting?.({\n for: 'organizations',\n caller,\n });\n }, [clerk, caller]);\n}\n","import { getCurrentOrganizationMembership } from '../../organization';\nimport { eventMethodCalled } from '../../telemetry/events/method-called';\nimport type {\n GetDomainsParams,\n GetInvitationsParams,\n GetMembershipRequestParams,\n GetMembersParams,\n OrganizationDomainResource,\n OrganizationInvitationResource,\n OrganizationMembershipRequestResource,\n OrganizationMembershipResource,\n OrganizationResource,\n} from '../../types';\nimport {\n useAssertWrappedByClerkProvider,\n useClerkInstanceContext,\n useOrganizationContext,\n useSessionContext,\n} from '../contexts';\nimport { STABLE_KEYS } from '../stable-keys';\nimport type { PaginatedHookConfig, PaginatedResources, PaginatedResourcesWithDefault } from '../types';\nimport { createCacheKeys } from './createCacheKeys';\nimport { useAttemptToEnableOrganizations } from './useAttemptToEnableOrganizations';\nimport { usePagesOrInfinite, useWithSafeValues } from './usePagesOrInfinite';\n\n/**\n * @interface\n */\nexport type UseOrganizationParams = {\n /**\n * If set to `true`, all default properties will be used.<br />\n * Otherwise, accepts an object with the following optional properties:\n * <ul>\n * <li>`enrollmentMode`: A string that filters the domains by the provided [enrollment mode](https://clerk.com/docs/guides/organizations/add-members/verified-domains#enable-verified-domains).</li>\n * <li>Any of the properties described in [Shared properties](#shared-properties).</li>\n * </ul>\n */\n domains?: true | PaginatedHookConfig<GetDomainsParams>;\n /**\n * If set to `true`, all default properties will be used.<br />\n * Otherwise, accepts an object with the following optional properties:\n * <ul>\n * <li>`status`: A string that filters the membership requests by the provided status.</li>\n * <li>Any of the properties described in [Shared properties](#shared-properties).</li>\n * </ul>\n */\n membershipRequests?: true | PaginatedHookConfig<GetMembershipRequestParams>;\n /**\n * If set to `true`, all default properties will be used.<br />\n * Otherwise, accepts an object with the following optional properties:\n * <ul>\n * <li>`role`: An array of [`OrganizationCustomRoleKey`](https://clerk.com/docs/reference/javascript/types/organization-custom-role-key).</li>\n * <li>`query`: A string that filters the memberships by the provided string.</li>\n * <li>Any of the properties described in [Shared properties](#shared-properties).</li>\n * </ul>\n */\n memberships?: true | PaginatedHookConfig<GetMembersParams>;\n /**\n * If set to `true`, all default properties will be used.<br />\n * Otherwise, accepts an object with the following optional properties:\n * <ul>\n * <li>`status`: A string that filters the invitations by the provided status.</li>\n * <li>Any of the properties described in [Shared properties](#shared-properties).</li>\n * </ul>\n */\n invitations?: true | PaginatedHookConfig<GetInvitationsParams>;\n};\n\n/**\n * @interface\n */\nexport type UseOrganizationReturn<T extends UseOrganizationParams> =\n | {\n /**\n * A boolean that indicates whether Clerk has completed initialization. Initially `false`, becomes `true` once Clerk loads.\n */\n isLoaded: false;\n /**\n * The currently Active Organization.\n */\n organization: undefined;\n /**\n * The current Organization membership.\n */\n membership: undefined;\n /**\n * Includes a paginated list of the Organization's domains.\n */\n domains: PaginatedResourcesWithDefault<OrganizationDomainResource>;\n /**\n * Includes a paginated list of the Organization's membership requests.\n */\n membershipRequests: PaginatedResourcesWithDefault<OrganizationMembershipRequestResource>;\n /**\n * Includes a paginated list of the Organization's memberships.\n */\n memberships: PaginatedResourcesWithDefault<OrganizationMembershipResource>;\n /**\n * Includes a paginated list of the Organization's invitations.\n */\n invitations: PaginatedResourcesWithDefault<OrganizationInvitationResource>;\n }\n | {\n isLoaded: true;\n organization: OrganizationResource;\n membership: undefined;\n domains: PaginatedResourcesWithDefault<OrganizationDomainResource>;\n membershipRequests: PaginatedResourcesWithDefault<OrganizationMembershipRequestResource>;\n memberships: PaginatedResourcesWithDefault<OrganizationMembershipResource>;\n invitations: PaginatedResourcesWithDefault<OrganizationInvitationResource>;\n }\n | {\n isLoaded: boolean;\n organization: OrganizationResource | null;\n membership: OrganizationMembershipResource | null | undefined;\n domains: PaginatedResources<\n OrganizationDomainResource,\n T['membershipRequests'] extends { infinite: true } ? true : false\n > | null;\n membershipRequests: PaginatedResources<\n OrganizationMembershipRequestResource,\n T['membershipRequests'] extends { infinite: true } ? true : false\n > | null;\n memberships: PaginatedResources<\n OrganizationMembershipResource,\n T['memberships'] extends { infinite: true } ? true : false\n > | null;\n invitations: PaginatedResources<\n OrganizationInvitationResource,\n T['invitations'] extends { infinite: true } ? true : false\n > | null;\n };\n\nconst undefinedPaginatedResource = {\n data: undefined,\n count: undefined,\n error: undefined,\n isLoading: false,\n isFetching: false,\n isError: false,\n page: undefined,\n pageCount: undefined,\n fetchPage: undefined,\n fetchNext: undefined,\n fetchPrevious: undefined,\n hasNextPage: false,\n hasPreviousPage: false,\n revalidate: undefined,\n setData: undefined,\n} as const;\n\n/**\n * The `useOrganization()` hook retrieves attributes of the currently Active Organization.\n *\n * @example\n * ### Expand and paginate attributes\n *\n * To keep network usage to a minimum, developers are required to opt-in by specifying which resource they need to fetch and paginate through. By default, the `memberships`, `invitations`, `membershipRequests`, and `domains` attributes are not populated. You must pass `true` or an object with the desired properties to fetch and paginate the data.\n *\n * ```tsx\n * // invitations.data will never be populated.\n * const { invitations } = useOrganization()\n *\n * // Use default values to fetch invitations, such as initialPage = 1 and pageSize = 10\n * const { invitations } = useOrganization({\n * invitations: true,\n * })\n *\n * // Pass your own values to fetch invitations\n * const { invitations } = useOrganization({\n * invitations: {\n * pageSize: 20,\n * initialPage: 2, // skips the first page\n * },\n * })\n *\n * // Aggregate pages in order to render an infinite list\n * const { invitations } = useOrganization({\n * invitations: {\n * infinite: true,\n * },\n * })\n * ```\n *\n * @example\n * ### Infinite pagination\n *\n * The following example demonstrates how to use the `infinite` property to fetch and append new data to the existing list. The `memberships` attribute will be populated with the first page of the Organization's memberships. When the \"Load more\" button is clicked, the `fetchNext` helper function will be called to append the next page of memberships to the list.\n *\n * ```tsx\n * import { useOrganization } from '@clerk/react'\n *\n * export default function MemberList() {\n * const { memberships } = useOrganization({\n * memberships: {\n * infinite: true, // Append new data to the existing list\n * keepPreviousData: true, // Persist the cached data until the new data has been fetched\n * },\n * })\n *\n * if (!memberships) {\n * // Handle loading state\n * return null\n * }\n *\n * return (\n * <div>\n * <h2>Organization members</h2>\n * <ul>\n * {memberships.data?.map((membership) => (\n * <li key={membership.id}>\n * {membership.publicUserData.firstName} {membership.publicUserData.lastName} <\n * {membership.publicUserData.identifier}> :: {membership.role}\n * </li>\n * ))}\n * </ul>\n *\n * <button\n * disabled={!memberships.hasNextPage} // Disable the button if there are no more available pages to be fetched\n * onClick={memberships.fetchNext}\n * >\n * Load more\n * </button>\n * </div>\n * )\n * }\n * ```\n *\n * @example\n * ### Simple pagination\n *\n * The following example demonstrates how to use the `fetchPrevious` and `fetchNext` helper functions to paginate through the data. The `memberships` attribute will be populated with the first page of the Organization's memberships. When the \"Previous page\" or \"Next page\" button is clicked, the `fetchPrevious` or `fetchNext` helper function will be called to fetch the previous or next page of memberships.\n *\n * Notice the difference between this example's pagination and the infinite pagination example above.\n *\n * ```tsx\n * import { useOrganization } from '@clerk/react'\n *\n * export default function MemberList() {\n * const { memberships } = useOrganization({\n * memberships: {\n * keepPreviousData: true, // Persist the cached data until the new data has been fetched\n * },\n * })\n *\n * if (!memberships) {\n * // Handle loading state\n * return null\n * }\n *\n * return (\n * <div>\n * <h2>Organization members</h2>\n * <ul>\n * {memberships.data?.map((membership) => (\n * <li key={membership.id}>\n * {membership.publicUserData.firstName} {membership.publicUserData.lastName} <\n * {membership.publicUserData.identifier}> :: {membership.role}\n * </li>\n * ))}\n * </ul>\n *\n * <button disabled={!memberships.hasPreviousPage} onClick={memberships.fetchPrevious}>\n * Previous page\n * </button>\n *\n * <button disabled={!memberships.hasNextPage} onClick={memberships.fetchNext}>\n * Next page\n * </button>\n * </div>\n * )\n * }\n * ```\n */\nexport function useOrganization<T extends UseOrganizationParams>(params?: T): UseOrganizationReturn<T> {\n const {\n domains: domainListParams,\n membershipRequests: membershipRequestsListParams,\n memberships: membersListParams,\n invitations: invitationsListParams,\n } = params || {};\n\n useAssertWrappedByClerkProvider('useOrganization');\n useAttemptToEnableOrganizations('useOrganization');\n\n const { organization } = useOrganizationContext();\n const session = useSessionContext();\n\n const domainSafeValues = useWithSafeValues(domainListParams, {\n initialPage: 1,\n pageSize: 10,\n keepPreviousData: false,\n infinite: false,\n enrollmentMode: undefined,\n });\n\n const membershipRequestSafeValues = useWithSafeValues(membershipRequestsListParams, {\n initialPage: 1,\n pageSize: 10,\n status: 'pending',\n keepPreviousData: false,\n infinite: false,\n });\n\n const membersSafeValues = useWithSafeValues(membersListParams, {\n initialPage: 1,\n pageSize: 10,\n role: undefined,\n keepPreviousData: false,\n infinite: false,\n query: undefined,\n });\n\n const invitationsSafeValues = useWithSafeValues(invitationsListParams, {\n initialPage: 1,\n pageSize: 10,\n status: ['pending'],\n keepPreviousData: false,\n infinite: false,\n });\n\n const clerk = useClerkInstanceContext();\n\n clerk.telemetry?.record(eventMethodCalled('useOrganization'));\n\n const domainParams =\n typeof domainListParams === 'undefined'\n ? undefined\n : {\n initialPage: domainSafeValues.initialPage,\n pageSize: domainSafeValues.pageSize,\n enrollmentMode: domainSafeValues.enrollmentMode,\n };\n\n const membershipRequestParams =\n typeof membershipRequestsListParams === 'undefined'\n ? undefined\n : {\n initialPage: membershipRequestSafeValues.initialPage,\n pageSize: membershipRequestSafeValues.pageSize,\n status: membershipRequestSafeValues.status,\n };\n\n const membersParams =\n typeof membersListParams === 'undefined'\n ? undefined\n : {\n initialPage: membersSafeValues.initialPage,\n pageSize: membersSafeValues.pageSize,\n role: membersSafeValues.role,\n query: membersSafeValues.query,\n };\n\n const invitationsParams =\n typeof invitationsListParams === 'undefined'\n ? undefined\n : {\n initialPage: invitationsSafeValues.initialPage,\n pageSize: invitationsSafeValues.pageSize,\n status: invitationsSafeValues.status,\n };\n\n const domains = usePagesOrInfinite({\n fetcher: organization?.getDomains,\n config: {\n keepPreviousData: domainSafeValues.keepPreviousData,\n infinite: domainSafeValues.infinite,\n enabled: !!domainParams,\n isSignedIn: Boolean(organization),\n initialPage: domainSafeValues.initialPage,\n pageSize: domainSafeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: STABLE_KEYS.DOMAINS_KEY,\n authenticated: Boolean(organization),\n tracked: {\n organizationId: organization?.id,\n },\n untracked: {\n args: domainParams,\n },\n }),\n });\n\n const membershipRequests = usePagesOrInfinite({\n fetcher: organization?.getMembershipRequests,\n config: {\n keepPreviousData: membershipRequestSafeValues.keepPreviousData,\n infinite: membershipRequestSafeValues.infinite,\n enabled: !!membershipRequestParams,\n isSignedIn: Boolean(organization),\n initialPage: membershipRequestSafeValues.initialPage,\n pageSize: membershipRequestSafeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: STABLE_KEYS.MEMBERSHIP_REQUESTS_KEY,\n authenticated: Boolean(organization),\n tracked: {\n organizationId: organization?.id,\n },\n untracked: {\n args: membershipRequestParams,\n },\n }),\n });\n\n const memberships = usePagesOrInfinite({\n fetcher: organization?.getMemberships,\n config: {\n keepPreviousData: membersSafeValues.keepPreviousData,\n infinite: membersSafeValues.infinite,\n enabled: !!membersParams,\n isSignedIn: Boolean(organization),\n initialPage: membersSafeValues.initialPage,\n pageSize: membersSafeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: STABLE_KEYS.MEMBERSHIPS_KEY,\n authenticated: Boolean(organization),\n tracked: {\n organizationId: organization?.id,\n },\n untracked: {\n args: membersParams,\n },\n }),\n });\n\n const invitations = usePagesOrInfinite({\n fetcher: organization?.getInvitations,\n config: {\n keepPreviousData: invitationsSafeValues.keepPreviousData,\n infinite: invitationsSafeValues.infinite,\n enabled: !!invitationsParams,\n isSignedIn: Boolean(organization),\n initialPage: invitationsSafeValues.initialPage,\n pageSize: invitationsSafeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: STABLE_KEYS.INVITATIONS_KEY,\n authenticated: Boolean(organization),\n tracked: {\n organizationId: organization?.id,\n },\n untracked: {\n args: invitationsParams,\n },\n }),\n });\n\n if (organization === undefined) {\n return {\n isLoaded: false,\n organization: undefined,\n membership: undefined,\n domains: undefinedPaginatedResource,\n membershipRequests: undefinedPaginatedResource,\n memberships: undefinedPaginatedResource,\n invitations: undefinedPaginatedResource,\n };\n }\n\n if (organization === null) {\n return {\n isLoaded: true,\n organization: null,\n membership: null,\n domains: null,\n membershipRequests: null,\n memberships: null,\n invitations: null,\n };\n }\n\n /** In SSR context we include only the organization object when loadOrg is set to true. */\n if (!clerk.loaded && organization) {\n return {\n isLoaded: true,\n organization,\n membership: undefined,\n domains: undefinedPaginatedResource,\n membershipRequests: undefinedPaginatedResource,\n memberships: undefinedPaginatedResource,\n invitations: undefinedPaginatedResource,\n };\n }\n\n return {\n isLoaded: clerk.loaded,\n organization,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n membership: getCurrentOrganizationMembership(session!.user.organizationMemberships, organization.id), // your membership in the current org\n domains,\n membershipRequests,\n memberships,\n invitations,\n };\n}\n","import { eventMethodCalled } from '../../telemetry/events/method-called';\nimport type {\n CreateOrganizationParams,\n GetUserOrganizationInvitationsParams,\n GetUserOrganizationMembershipParams,\n GetUserOrganizationSuggestionsParams,\n OrganizationMembershipResource,\n OrganizationResource,\n OrganizationSuggestionResource,\n SetActive,\n UserOrganizationInvitationResource,\n} from '../../types';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext, useUserContext } from '../contexts';\nimport { STABLE_KEYS } from '../stable-keys';\nimport type { PaginatedHookConfig, PaginatedResources, PaginatedResourcesWithDefault } from '../types';\nimport { createCacheKeys } from './createCacheKeys';\nimport { useAttemptToEnableOrganizations } from './useAttemptToEnableOrganizations';\nimport { usePagesOrInfinite, useWithSafeValues } from './usePagesOrInfinite';\n\n/**\n * @interface\n */\nexport type UseOrganizationListParams = {\n /**\n * If set to `true`, all default properties will be used.<br />\n * Otherwise, accepts an object with the following optional properties:\n *\n * <ul>\n * <li>Any of the properties described in [Shared properties](#shared-properties).</li>\n * </ul>\n */\n userMemberships?: true | PaginatedHookConfig<GetUserOrganizationMembershipParams>;\n /**\n * If set to `true`, all default properties will be used.<br />\n * Otherwise, accepts an object with the following optional properties:\n *\n * <ul>\n * <li>`status`: A string that filters the invitations by the provided status.</li>\n * <li>Any of the properties described in [Shared properties](#shared-properties).</li>\n * </ul>\n */\n userInvitations?: true | PaginatedHookConfig<GetUserOrganizationInvitationsParams>;\n /**\n * If set to `true`, all default properties will be used.<br />\n * Otherwise, accepts an object with the following optional properties:\n *\n * <ul>\n * <li>`status`: A string that filters the suggestions by the provided status.</li>\n * <li>Any of the properties described in [Shared properties](#shared-properties).</li>\n * </ul>\n */\n userSuggestions?: true | PaginatedHookConfig<GetUserOrganizationSuggestionsParams>;\n};\n\nconst undefinedPaginatedResource = {\n data: undefined,\n count: undefined,\n error: undefined,\n isLoading: false,\n isFetching: false,\n isError: false,\n page: undefined,\n pageCount: undefined,\n fetchPage: undefined,\n fetchNext: undefined,\n fetchPrevious: undefined,\n hasNextPage: false,\n hasPreviousPage: false,\n revalidate: undefined,\n setData: undefined,\n} as const;\n\n/**\n * @interface\n */\nexport type UseOrganizationListReturn<T extends UseOrganizationListParams> =\n | {\n /**\n * A boolean that indicates whether Clerk has completed initialization and there is an authenticated user. Initially `false`, becomes `true` once Clerk loads with a user.\n */\n isLoaded: false;\n /**\n * A function that returns a `Promise` which resolves to the newly created `Organization`.\n */\n createOrganization: undefined;\n /**\n * A function that sets the active session and/or Organization.\n */\n setActive: undefined;\n /**\n * Returns `PaginatedResources` which includes a list of the user's Organization memberships.\n */\n userMemberships: PaginatedResourcesWithDefault<OrganizationMembershipResource>;\n /**\n * Returns `PaginatedResources` which includes a list of the user's Organization invitations.\n */\n userInvitations: PaginatedResourcesWithDefault<UserOrganizationInvitationResource>;\n /**\n * Returns `PaginatedResources` which includes a list of suggestions for Organizations that the user can join.\n */\n userSuggestions: PaginatedResourcesWithDefault<OrganizationSuggestionResource>;\n }\n | {\n isLoaded: boolean;\n createOrganization: (CreateOrganizationParams: CreateOrganizationParams) => Promise<OrganizationResource>;\n setActive: SetActive;\n userMemberships: PaginatedResources<\n OrganizationMembershipResource,\n T['userMemberships'] extends { infinite: true } ? true : false\n >;\n userInvitations: PaginatedResources<\n UserOrganizationInvitationResource,\n T['userInvitations'] extends { infinite: true } ? true : false\n >;\n userSuggestions: PaginatedResources<\n OrganizationSuggestionResource,\n T['userSuggestions'] extends { infinite: true } ? true : false\n >;\n };\n\n/**\n * The `useOrganizationList()` hook provides access to the current user's organization memberships, invitations, and suggestions. It also includes methods for creating new organizations and managing the active organization.\n *\n * @example\n * ### Expanding and paginating attributes\n *\n * To keep network usage to a minimum, developers are required to opt-in by specifying which resource they need to fetch and paginate through. So by default, the `userMemberships`, `userInvitations`, and `userSuggestions` attributes are not populated. You must pass true or an object with the desired properties to fetch and paginate the data.\n *\n * ```tsx\n * // userMemberships.data will never be populated\n * const { userMemberships } = useOrganizationList()\n *\n * // Use default values to fetch userMemberships, such as initialPage = 1 and pageSize = 10\n * const { userMemberships } = useOrganizationList({\n * userMemberships: true,\n * })\n *\n * // Pass your own values to fetch userMemberships\n * const { userMemberships } = useOrganizationList({\n * userMemberships: {\n * pageSize: 20,\n * initialPage: 2, // skips the first page\n * },\n * })\n *\n * // Aggregate pages in order to render an infinite list\n * const { userMemberships } = useOrganizationList({\n * userMemberships: {\n * infinite: true,\n * },\n * })\n * ```\n *\n * @example\n * ### Infinite pagination\n *\n * The following example demonstrates how to use the `infinite` property to fetch and append new data to the existing list. The `userMemberships` attribute will be populated with the first page of the user's Organization memberships. When the \"Load more\" button is clicked, the `fetchNext` helper function will be called to append the next page of memberships to the list.\n *\n * ```tsx {{ filename: 'src/components/JoinedOrganizations.tsx' }}\n * import { useOrganizationList } from '@clerk/react'\n * import React from 'react'\n *\n * const JoinedOrganizations = () => {\n * const { isLoaded, setActive, userMemberships } = useOrganizationList({\n * userMemberships: {\n * infinite: true,\n * },\n * })\n *\n * if (!isLoaded) {\n * return <>Loading</>\n * }\n *\n * return (\n * <>\n * <ul>\n * {userMemberships.data?.map((mem) => (\n * <li key={mem.id}>\n * <span>{mem.organization.name}</span>\n * <button onClick={() => setActive({ organization: mem.organization.id })}>Select</button>\n * </li>\n * ))}\n * </ul>\n *\n * <button disabled={!userMemberships.hasNextPage} onClick={() => userMemberships.fetchNext()}>\n * Load more\n * </button>\n * </>\n * )\n * }\n *\n * export default JoinedOrganizations\n * ```\n *\n * @example\n * ### Simple pagination\n *\n * The following example demonstrates how to use the `fetchPrevious` and `fetchNext` helper functions to paginate through the data. The `userInvitations` attribute will be populated with the first page of invitations. When the \"Previous page\" or \"Next page\" button is clicked, the `fetchPrevious` or `fetchNext` helper function will be called to fetch the previous or next page of invitations.\n *\n * Notice the difference between this example's pagination and the infinite pagination example above.\n *\n * ```tsx {{ filename: 'src/components/UserInvitationsTable.tsx' }}\n * import { useOrganizationList } from '@clerk/react'\n * import React from 'react'\n *\n * const UserInvitationsTable = () => {\n * const { isLoaded, userInvitations } = useOrganizationList({\n * userInvitations: {\n * infinite: true,\n * keepPreviousData: true,\n * },\n * })\n *\n * if (!isLoaded || userInvitations.isLoading) {\n * return <>Loading</>\n * }\n *\n * return (\n * <>\n * <table>\n * <thead>\n * <tr>\n * <th>Email</th>\n * <th>Org name</th>\n * </tr>\n * </thead>\n *\n * <tbody>\n * {userInvitations.data?.map((inv) => (\n * <tr key={inv.id}>\n * <th>{inv.emailAddress}</th>\n * <th>{inv.publicOrganizationData.name}</th>\n * </tr>\n * ))}\n * </tbody>\n * </table>\n *\n * <button disabled={!userInvitations.hasPreviousPage} onClick={userInvitations.fetchPrevious}>\n * Prev\n * </button>\n * <button disabled={!userInvitations.hasNextPage} onClick={userInvitations.fetchNext}>\n * Next\n * </button>\n * </>\n * )\n * }\n *\n * export default UserInvitationsTable\n * ```\n */\nexport function useOrganizationList<T extends UseOrganizationListParams>(params?: T): UseOrganizationListReturn<T> {\n const { userMemberships, userInvitations, userSuggestions } = params || {};\n\n useAssertWrappedByClerkProvider('useOrganizationList');\n useAttemptToEnableOrganizations('useOrganizationList');\n\n const userMembershipsSafeValues = useWithSafeValues(userMemberships, {\n initialPage: 1,\n pageSize: 10,\n keepPreviousData: false,\n infinite: false,\n });\n\n const userInvitationsSafeValues = useWithSafeValues(userInvitations, {\n initialPage: 1,\n pageSize: 10,\n status: 'pending',\n keepPreviousData: false,\n infinite: false,\n });\n\n const userSuggestionsSafeValues = useWithSafeValues(userSuggestions, {\n initialPage: 1,\n pageSize: 10,\n status: 'pending',\n keepPreviousData: false,\n infinite: false,\n });\n\n const clerk = useClerkInstanceContext();\n const user = useUserContext();\n\n clerk.telemetry?.record(eventMethodCalled('useOrganizationList'));\n\n const userMembershipsParams =\n typeof userMemberships === 'undefined'\n ? undefined\n : {\n initialPage: userMembershipsSafeValues.initialPage,\n pageSize: userMembershipsSafeValues.pageSize,\n };\n\n const userInvitationsParams =\n typeof userInvitations === 'undefined'\n ? undefined\n : {\n initialPage: userInvitationsSafeValues.initialPage,\n pageSize: userInvitationsSafeValues.pageSize,\n status: userInvitationsSafeValues.status,\n };\n\n const userSuggestionsParams =\n typeof userSuggestions === 'undefined'\n ? undefined\n : {\n initialPage: userSuggestionsSafeValues.initialPage,\n pageSize: userSuggestionsSafeValues.pageSize,\n status: userSuggestionsSafeValues.status,\n };\n\n const isClerkLoaded = !!(clerk.loaded && user);\n\n const memberships = usePagesOrInfinite({\n fetcher: user?.getOrganizationMemberships,\n config: {\n keepPreviousData: userMembershipsSafeValues.keepPreviousData,\n infinite: userMembershipsSafeValues.infinite,\n enabled: !!userMembershipsParams,\n isSignedIn: Boolean(user),\n initialPage: userMembershipsSafeValues.initialPage,\n pageSize: userMembershipsSafeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: STABLE_KEYS.USER_MEMBERSHIPS_KEY,\n authenticated: Boolean(user),\n tracked: {\n userId: user?.id,\n },\n untracked: {\n args: userMembershipsParams,\n },\n }),\n });\n\n const invitations = usePagesOrInfinite({\n fetcher: user?.getOrganizationInvitations,\n config: {\n keepPreviousData: userInvitationsSafeValues.keepPreviousData,\n infinite: userInvitationsSafeValues.infinite,\n // In useOrganizationList, you need to opt in by passing an object or `true`.\n enabled: !!userInvitationsParams,\n isSignedIn: Boolean(user),\n initialPage: userInvitationsSafeValues.initialPage,\n pageSize: userInvitationsSafeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: STABLE_KEYS.USER_INVITATIONS_KEY,\n authenticated: Boolean(user),\n tracked: {\n userId: user?.id,\n },\n untracked: {\n args: userInvitationsParams,\n },\n }),\n });\n\n const suggestions = usePagesOrInfinite({\n fetcher: user?.getOrganizationSuggestions,\n config: {\n keepPreviousData: userSuggestionsSafeValues.keepPreviousData,\n infinite: userSuggestionsSafeValues.infinite,\n enabled: !!userSuggestionsParams,\n isSignedIn: Boolean(user),\n initialPage: userSuggestionsSafeValues.initialPage,\n pageSize: userSuggestionsSafeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: STABLE_KEYS.USER_SUGGESTIONS_KEY,\n authenticated: Boolean(user),\n tracked: {\n userId: user?.id,\n },\n untracked: {\n args: userSuggestionsParams,\n },\n }),\n });\n\n // TODO: Properly check for SSR user values\n if (!isClerkLoaded) {\n return {\n isLoaded: false,\n createOrganization: undefined,\n setActive: undefined,\n userMemberships: undefinedPaginatedResource,\n userInvitations: undefinedPaginatedResource,\n userSuggestions: undefinedPaginatedResource,\n };\n }\n\n return {\n isLoaded: isClerkLoaded,\n setActive: clerk.setActive,\n createOrganization: clerk.createOrganization,\n userMemberships: memberships,\n userInvitations: invitations,\n userSuggestions: suggestions,\n };\n}\n","import React from 'react';\n\n/**\n * @internal\n */\nexport const useSafeLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;\n","import { eventMethodCalled } from '../../telemetry/events/method-called';\nimport type { UseSessionReturn } from '../../types';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext, useSessionContext } from '../contexts';\n\ntype UseSession = () => UseSessionReturn;\n\nconst hookName = `useSession`;\n/**\n * The `useSession()` hook provides access to the current user's [`Session`](https://clerk.com/docs/reference/javascript/session) object, as well as helpers for setting the active session.\n *\n * @unionReturnHeadings\n * [\"Initialization\", \"Signed out\", \"Signed in\"]\n *\n * @function\n *\n * @param [options] - An object containing options for the `useSession()` hook.\n * @example\n * ### Access the `Session` object\n *\n * The following example uses the `useSession()` hook to access the `Session` object, which has the `lastActiveAt` property. The `lastActiveAt` property is a `Date` object used to show the time the session was last active.\n *\n * <Tabs items='React,Next.js'>\n * <Tab>\n *\n * ```tsx {{ filename: 'src/Home.tsx' }}\n * import { useSession } from '@clerk/react'\n *\n * export default function Home() {\n * const { isLoaded, session, isSignedIn } = useSession()\n *\n * if (!isLoaded) {\n * // Handle loading state\n * return null\n * }\n * if (!isSignedIn) {\n * // Handle signed out state\n * return null\n * }\n *\n * return (\n * <div>\n * <p>This session has been active since {session.lastActiveAt.toLocaleString()}</p>\n * </div>\n * )\n * }\n * ```\n *\n * </Tab>\n * <Tab>\n *\n * {@include ../../../docs/use-session.md#nextjs-01}\n *\n * </Tab>\n * </Tabs>\n */\nexport const useSession: UseSession = () => {\n useAssertWrappedByClerkProvider(hookName);\n\n const session = useSessionContext();\n const clerk = useClerkInstanceContext();\n\n clerk.telemetry?.record(eventMethodCalled(hookName));\n\n if (session === undefined) {\n return { isLoaded: false, isSignedIn: undefined, session: undefined };\n }\n\n if (session === null) {\n return { isLoaded: true, isSignedIn: false, session: null };\n }\n\n return { isLoaded: true, isSignedIn: clerk.isSignedIn, session };\n};\n","import { eventMethodCalled } from '../../telemetry/events/method-called';\nimport type { UseSessionListReturn } from '../../types';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext, useClientContext } from '../contexts';\n\nconst hookName = 'useSessionList';\n/**\n * The `useSessionList()` hook returns an array of [`Session`](https://clerk.com/docs/reference/javascript/session) objects that have been registered on the client device.\n *\n * @unionReturnHeadings\n * [\"Initialization\", \"Loaded\"]\n *\n * @function\n *\n * @example\n * ### Get a list of sessions\n *\n * The following example uses `useSessionList()` to get a list of sessions that have been registered on the client device. The `sessions` property is used to show the number of times the user has visited the page.\n *\n * <Tabs items='React,Next.js'>\n * <Tab>\n *\n * ```tsx {{ filename: 'src/Home.tsx' }}\n * import { useSessionList } from '@clerk/react'\n *\n * export default function Home() {\n * const { isLoaded, sessions } = useSessionList()\n *\n * if (!isLoaded) {\n * // Handle loading state\n * return null\n * }\n *\n * return (\n * <div>\n * <p>Welcome back. You've been here {sessions.length} times before.</p>\n * </div>\n * )\n * }\n * ```\n *\n * </Tab>\n * <Tab>\n *\n * {@include ../../../docs/use-session-list.md#nextjs-01}\n *\n * </Tab>\n * </Tabs>\n */\nexport const useSessionList = (): UseSessionListReturn => {\n useAssertWrappedByClerkProvider(hookName);\n\n const isomorphicClerk = useClerkInstanceContext();\n const client = useClientContext();\n const clerk = useClerkInstanceContext();\n\n clerk.telemetry?.record(eventMethodCalled(hookName));\n\n if (!client) {\n return { isLoaded: false, sessions: undefined, setActive: undefined };\n }\n\n return {\n isLoaded: true,\n sessions: client.sessions,\n setActive: isomorphicClerk.setActive,\n };\n};\n","import { eventMethodCalled } from '../../telemetry/events/method-called';\nimport type { UseUserReturn } from '../../types';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext, useUserContext } from '../contexts';\n\nconst hookName = 'useUser';\n/**\n * The `useUser()` hook provides access to the current user's [`User`](https://clerk.com/docs/reference/javascript/user) object, which contains all the data for a single user in your application and provides methods to manage their account. This hook also allows you to check if the user is signed in and if Clerk has loaded and initialized.\n *\n * @unionReturnHeadings\n * [\"Initialization\", \"Signed out\", \"Signed in\"]\n *\n * @example\n * ### Get the current user\n *\n * The following example uses the `useUser()` hook to access the [`User`](https://clerk.com/docs/reference/javascript/user) object, which contains the current user's data such as their full name. The `isLoaded` and `isSignedIn` properties are used to handle the loading state and to check if the user is signed in, respectively.\n *\n * ```tsx {{ filename: 'src/Example.tsx' }}\n * import { useUser } from '@clerk/react'\n *\n * export default function Example() {\n * const { isSignedIn, user, isLoaded } = useUser()\n *\n * if (!isLoaded) {\n * return <div>Loading...</div>\n * }\n *\n * if (!isSignedIn) {\n * return <div>Sign in to view this page</div>\n * }\n *\n * return <div>Hello {user.firstName}!</div>\n * }\n * ```\n *\n * @example\n * ### Update user data\n *\n * The following example uses the `useUser()` hook to access the [`User`](https://clerk.com/docs/reference/javascript/user) object, which calls the [`update()`](https://clerk.com/docs/reference/javascript/user#update) method to update the current user's information.\n *\n * <Tabs items='React,Next.js'>\n * <Tab>\n *\n * ```tsx {{ filename: 'src/Home.tsx' }}\n * import { useUser } from '@clerk/react'\n *\n * export default function Home() {\n * const { isSignedIn, isLoaded, user } = useUser()\n *\n * if (!isLoaded) {\n * // Handle loading state\n * return null\n * }\n *\n * if (!isSignedIn) return null\n *\n * const updateUser = async () => {\n * await user.update({\n * firstName: 'John',\n * lastName: 'Doe',\n * })\n * }\n *\n * return (\n * <>\n * <button onClick={updateUser}>Update your name</button>\n * <p>user.firstName: {user.firstName}</p>\n * <p>user.lastName: {user.lastName}</p>\n * </>\n * )\n * }\n * ```\n * </Tab>\n * <Tab>\n *\n * {@include ../../../docs/use-user.md#nextjs-01}\n *\n * </Tab>\n * </Tabs>\n *\n * @example\n * ### Reload user data\n *\n * The following example uses the `useUser()` hook to access the [`User`](https://clerk.com/docs/reference/javascript/user) object, which calls the [`reload()`](https://clerk.com/docs/reference/javascript/user#reload) method to get the latest user's information.\n *\n * <Tabs items='React,Next.js'>\n * <Tab>\n *\n * ```tsx {{ filename: 'src/Home.tsx' }}\n * import { useUser } from '@clerk/react'\n *\n * export default function Home() {\n * const { isSignedIn, isLoaded, user } = useUser();\n *\n * if (!isLoaded) {\n * // Handle loading state\n * return null;\n * }\n *\n * if (!isSignedIn) return null;\n *\n * const updateUser = async () => {\n * // Update data via an API endpoint\n * const updateMetadata = await fetch('/api/updateMetadata', {\n * method: 'POST',\n * body: JSON.stringify({\n * role: 'admin'\n * })\n * });\n *\n * // Check if the update was successful\n * if ((await updateMetadata.json()).message !== 'success') {\n * throw new Error('Error updating');\n * }\n *\n * // If the update was successful, reload the user data\n * await user.reload();\n * };\n *\n * return (\n * <>\n * <button onClick={updateUser}>Update your metadata</button>\n * <p>user role: {user.publicMetadata.role}</p>\n * </>\n * );\n * }\n * ```\n *\n * </Tab>\n * <Tab>\n *\n * {@include ../../../docs/use-user.md#nextjs-02}\n *\n * </Tab>\n * </Tabs>\n */\nexport function useUser(): UseUserReturn {\n useAssertWrappedByClerkProvider(hookName);\n\n const user = useUserContext();\n const clerk = useClerkInstanceContext();\n\n clerk.telemetry?.record(eventMethodCalled(hookName));\n\n if (user === undefined) {\n return { isLoaded: false, isSignedIn: undefined, user: undefined };\n }\n\n if (user === null) {\n return { isLoaded: true, isSignedIn: false, user: null };\n }\n\n return { isLoaded: true, isSignedIn: true, user };\n}\n","import { dequal as deepEqual } from 'dequal';\nimport React from 'react';\n\ntype UseMemoFactory<T> = () => T;\ntype UseMemoDependencyArray = Exclude<Parameters<typeof React.useMemo>[1], 'undefined'>;\ntype UseDeepEqualMemo = <T>(factory: UseMemoFactory<T>, dependencyArray: UseMemoDependencyArray) => T;\n\nconst useDeepEqualMemoize = <T>(value: T) => {\n const ref = React.useRef<T>(value);\n if (!deepEqual(value, ref.current)) {\n ref.current = value;\n }\n return React.useMemo(() => ref.current, [ref.current]);\n};\n\n/**\n * @internal\n */\nexport const useDeepEqualMemo: UseDeepEqualMemo = (factory, dependencyArray) => {\n return React.useMemo(factory, useDeepEqualMemoize(dependencyArray));\n};\n\n/**\n * @internal\n */\nexport const isDeeplyEqual = deepEqual;\n","import { useCallback, useRef } from 'react';\n\nimport { validateReverificationConfig } from '../../authorization';\nimport { isReverificationHint, reverificationError } from '../../authorization-errors';\nimport { ClerkRuntimeError, isClerkAPIResponseError } from '../../error';\nimport { eventMethodCalled } from '../../telemetry';\nimport type { Clerk, SessionVerificationLevel } from '../../types';\nimport { createDeferredPromise } from '../../utils/createDeferredPromise';\nimport { useClerk } from './useClerk';\nimport { useSafeLayoutEffect } from './useSafeLayoutEffect';\n\nconst CLERK_API_REVERIFICATION_ERROR_CODE = 'session_reverification_required';\n\n/**\n *\n */\nasync function resolveResult<T>(result: Promise<T> | T): Promise<T | ReturnType<typeof reverificationError>> {\n try {\n const r = await result;\n if (r instanceof Response) {\n return r.json();\n }\n return r;\n } catch (e) {\n // Treat fapi assurance as an assurance hint\n if (isClerkAPIResponseError(e) && e.errors.find(({ code }) => code === CLERK_API_REVERIFICATION_ERROR_CODE)) {\n return reverificationError();\n }\n\n // rethrow\n throw e;\n }\n}\n\ntype ExcludeClerkError<T> = T extends { clerk_error: any } ? never : T;\n\n/**\n * @interface\n */\nexport type NeedsReverificationParameters = {\n /**\n * Marks the reverification process as cancelled and rejects the original request.\n */\n cancel: () => void;\n /**\n * Marks the reverification process as complete and retries the original request.\n */\n complete: () => void;\n /**\n * The verification level required for the reverification process.\n */\n level: SessionVerificationLevel | undefined;\n};\n\n/**\n * The optional options object.\n *\n * @interface\n */\nexport type UseReverificationOptions = {\n /**\n * Handler for the reverification process. Opts out of using the default UI. Use this to build a custom UI.\n *\n * @param properties - Callbacks and info to control the reverification flow.\n * @param properties.cancel - A function that will cancel the reverification process.\n * @param properties.complete - A function that will retry the original request after reverification.\n * @param properties.level - The level returned with the reverification hint.\n */\n onNeedsReverification?: (properties: NeedsReverificationParameters) => void;\n};\n\n/**\n * @interface\n */\ntype UseReverificationResult<Fetcher extends (...args: any[]) => Promise<any> | undefined> = (\n ...args: Parameters<Fetcher>\n) => Promise<ExcludeClerkError<Awaited<ReturnType<Fetcher>>>>;\n\n/**\n * @interface\n */\ntype UseReverification = <\n Fetcher extends (...args: any[]) => Promise<any> | undefined,\n Options extends UseReverificationOptions = UseReverificationOptions,\n>(\n /**\n * A function that returns a promise.\n */\n fetcher: Fetcher,\n /**\n * Optional configuration object extending [`UseReverificationOptions`](https://clerk.com/docs/reference/hooks/use-reverification#use-reverification-options).\n */\n options?: Options,\n) => UseReverificationResult<Fetcher>;\n\ntype CreateReverificationHandlerParams = UseReverificationOptions & {\n openUIComponent: Clerk['__internal_openReverification'];\n telemetry: Clerk['telemetry'];\n};\n\n/**\n *\n */\nfunction createReverificationHandler(params: CreateReverificationHandlerParams) {\n /**\n *\n */\n function assertReverification<Fetcher extends (...args: any[]) => Promise<any> | undefined>(\n fetcher: Fetcher,\n ): (...args: Parameters<Fetcher>) => Promise<ExcludeClerkError<Awaited<ReturnType<Fetcher>>>> {\n return (async (...args: Parameters<Fetcher>) => {\n let result = await resolveResult(fetcher(...args));\n\n if (isReverificationHint(result)) {\n /**\n * Create a promise\n */\n const resolvers = createDeferredPromise();\n\n const isValidMetadata = validateReverificationConfig(result.clerk_error.metadata?.reverification);\n\n const level = isValidMetadata ? isValidMetadata().level : undefined;\n\n const cancel = () => {\n resolvers.reject(\n new ClerkRuntimeError('User cancelled attempted verification', {\n code: 'reverification_cancelled',\n }),\n );\n };\n\n const complete = () => {\n resolvers.resolve(true);\n };\n\n if (params.onNeedsReverification === undefined) {\n /**\n * On success resolve the pending promise\n * On cancel reject the pending promise\n */\n params.openUIComponent?.({\n level: level,\n afterVerification: complete,\n afterVerificationCancelled: cancel,\n });\n } else {\n params.onNeedsReverification({\n cancel,\n complete,\n level,\n });\n }\n\n /**\n * Wait until the promise from above have been resolved or rejected\n */\n await resolvers.promise;\n\n /**\n * After the promise resolved successfully try the original request one more time\n */\n result = await resolveResult(fetcher(...args));\n }\n\n return result;\n }) as ExcludeClerkError<Awaited<ReturnType<Fetcher>>>;\n }\n\n return assertReverification;\n}\n\n/**\n * > [!WARNING]\n * >\n * > Depending on the SDK you're using, this feature requires `@clerk/nextjs@6.12.7` or later, `@clerk/react@5.25.1` or later, and `@clerk/clerk-js@5.57.1` or later.\n *\n * The `useReverification()` hook is used to handle a session's reverification flow. If a request requires reverification, a modal will display, prompting the user to verify their credentials. Upon successful verification, the original request will automatically retry.\n *\n * @function\n *\n * @returns The `useReverification()` hook returns an array with the \"enhanced\" fetcher.\n *\n * @example\n * ### Handle cancellation of the reverification process\n *\n * The following example demonstrates how to handle scenarios where a user cancels the reverification flow, such as closing the modal, which might result in `myData` being `null`.\n *\n * In the following example, `myFetcher` would be a function in your backend that fetches data from the route that requires reverification. See the [guide on how to require reverification](https://clerk.com/docs/guides/secure/reverification) for more information.\n *\n * ```tsx {{ filename: 'src/components/MyButton.tsx' }}\n * import { useReverification } from '@clerk/react'\n * import { isReverificationCancelledError } from '@clerk/react/error'\n *\n * type MyData = {\n * balance: number\n * }\n *\n * export function MyButton() {\n * const fetchMyData = () => fetch('/api/balance').then(res=> res.json() as Promise<MyData>)\n * const enhancedFetcher = useReverification(fetchMyData);\n *\n * const handleClick = async () => {\n * try {\n * const myData = await enhancedFetcher()\n * // ^ is types as `MyData`\n * } catch (e) {\n * // Handle error returned from the fetcher here\n *\n * // You can also handle cancellation with the following\n * if (isReverificationCancelledError(err)) {\n * // Handle the cancellation error here\n * }\n * }\n * }\n *\n * return <button onClick={handleClick}>Update User</button>\n * }\n * ```\n */\nexport const useReverification: UseReverification = (fetcher, options) => {\n const { __internal_openReverification, telemetry } = useClerk();\n const fetcherRef = useRef(fetcher);\n const optionsRef = useRef(options);\n\n telemetry?.record(\n eventMethodCalled('useReverification', {\n onNeedsReverification: Boolean(options?.onNeedsReverification),\n }),\n );\n\n // Keep fetcher and options ref in sync\n useSafeLayoutEffect(() => {\n fetcherRef.current = fetcher;\n optionsRef.current = options;\n });\n\n return useCallback(\n (...args) => {\n const handler = createReverificationHandler({\n openUIComponent: __internal_openReverification,\n telemetry,\n ...optionsRef.current,\n })(fetcherRef.current);\n return handler(...args);\n },\n [__internal_openReverification, telemetry],\n );\n};\n","import type { ForPayerType } from '../../types/billing';\nimport { useClerkInstanceContext, useOrganizationContext, useUserContext } from '../contexts';\n\n/**\n * @internal\n */\nexport function useBillingHookEnabled(params?: { for?: ForPayerType; enabled?: boolean; authenticated?: boolean }) {\n const clerk = useClerkInstanceContext();\n\n const enabledFromParam = params?.enabled ?? true;\n\n // @ts-expect-error `__internal_environment` is not typed\n const environment = clerk.__internal_environment as unknown as EnvironmentResource | null | undefined;\n\n const user = useUserContext();\n const { organization } = useOrganizationContext();\n\n const isOrganization = params?.for === 'organization';\n const billingEnabled = isOrganization\n ? environment?.commerceSettings.billing.organization.enabled\n : environment?.commerceSettings.billing.user.enabled;\n\n const requireUserAndOrganizationWhenAuthenticated =\n (params?.authenticated ?? true) ? (isOrganization ? Boolean(organization?.id) : true) && Boolean(user?.id) : true;\n\n return billingEnabled && enabledFromParam && clerk.loaded && requireUserAndOrganizationWhenAuthenticated;\n}\n","import { eventMethodCalled } from '../../telemetry/events/method-called';\nimport type { ClerkPaginatedResponse, ClerkResource, ForPayerType } from '../../types';\nimport {\n useAssertWrappedByClerkProvider,\n useClerkInstanceContext,\n useOrganizationContext,\n useUserContext,\n} from '../contexts';\nimport type { ResourceCacheStableKey } from '../stable-keys';\nimport type { PagesOrInfiniteOptions, PaginatedHookConfig, PaginatedResources } from '../types';\nimport { createCacheKeys } from './createCacheKeys';\nimport { useBillingHookEnabled } from './useBillingHookEnabled';\nimport { usePagesOrInfinite, useWithSafeValues } from './usePagesOrInfinite';\n\n/**\n * @internal\n */\ntype BillingHookConfig<TResource extends ClerkResource, TParams extends PagesOrInfiniteOptions> = {\n hookName: string;\n resourceType: ResourceCacheStableKey;\n useFetcher: (\n param: ForPayerType,\n ) => ((params: TParams & { orgId?: string }) => Promise<ClerkPaginatedResponse<TResource>>) | undefined;\n options?: {\n unauthenticated?: boolean;\n };\n};\n\n/**\n * @interface\n */\nexport interface HookParams\n extends PaginatedHookConfig<\n PagesOrInfiniteOptions & {\n /**\n * If `true`, a request will be triggered when the hook is mounted.\n *\n * @default true\n */\n enabled?: boolean;\n /**\n * On `cache` mode, no request will be triggered when the hook is mounted and the data will be fetched from the cache.\n *\n * @default undefined\n *\n * @hidden\n *\n * @experimental\n */\n __experimental_mode?: 'cache';\n }\n > {\n /**\n * Specifies whether to fetch for the current user or Organization.\n *\n * @default 'user'\n */\n for?: ForPayerType;\n}\n\n/**\n * A hook factory that creates paginated data fetching hooks for commerce-related resources.\n * It provides a standardized way to create hooks that can fetch either user or Organization resources\n * with built-in pagination support.\n *\n * The generated hooks handle:\n * - Clerk authentication context\n * - Resource-specific data fetching\n * - Pagination (both traditional and infinite scroll)\n * - Telemetry tracking\n * - Type safety for the specific resource.\n *\n * @internal\n */\nexport function createBillingPaginatedHook<TResource extends ClerkResource, TParams extends PagesOrInfiniteOptions>({\n hookName,\n resourceType,\n useFetcher,\n options,\n}: BillingHookConfig<TResource, TParams>) {\n return function useBillingHook<T extends HookParams>(\n params?: T,\n ): PaginatedResources<TResource, T extends { infinite: true } ? true : false> {\n const { for: _for, enabled: externalEnabled, ...paginationParams } = params || ({} as Partial<T>);\n\n const safeFor = _for || 'user';\n\n useAssertWrappedByClerkProvider(hookName);\n\n const fetchFn = useFetcher(safeFor);\n\n const safeValues = useWithSafeValues(paginationParams, {\n initialPage: 1,\n pageSize: 10,\n keepPreviousData: false,\n infinite: false,\n __experimental_mode: undefined,\n } as unknown as T);\n\n const clerk = useClerkInstanceContext();\n\n const user = useUserContext();\n const { organization } = useOrganizationContext();\n\n clerk.telemetry?.record(eventMethodCalled(hookName));\n\n const isForOrganization = safeFor === 'organization';\n\n const billingEnabled = useBillingHookEnabled({\n for: safeFor,\n enabled: externalEnabled,\n authenticated: !options?.unauthenticated,\n });\n\n const hookParams =\n typeof paginationParams === 'undefined'\n ? undefined\n : ({\n initialPage: safeValues.initialPage,\n pageSize: safeValues.pageSize,\n ...(options?.unauthenticated ? {} : isForOrganization ? { orgId: organization?.id } : {}),\n } as TParams);\n\n const isEnabled = !!hookParams && clerk.loaded && !!billingEnabled;\n\n return usePagesOrInfinite({\n fetcher: fetchFn,\n config: {\n keepPreviousData: safeValues.keepPreviousData,\n infinite: safeValues.infinite,\n enabled: isEnabled,\n ...(options?.unauthenticated ? {} : { isSignedIn: user !== null }),\n __experimental_mode: safeValues.__experimental_mode,\n initialPage: safeValues.initialPage,\n pageSize: safeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: resourceType,\n authenticated: !options?.unauthenticated,\n tracked: options?.unauthenticated\n ? ({ for: safeFor } as const)\n : ({\n userId: user?.id,\n ...(isForOrganization ? { [__CLERK_USE_RQ__ ? 'orgId' : '_orgId']: organization?.id } : {}),\n } as const),\n untracked: {\n args: hookParams as TParams,\n },\n }),\n });\n };\n}\n","import type { BillingStatementResource, GetStatementsParams } from '../../types';\nimport { useClerkInstanceContext } from '../contexts';\nimport { STABLE_KEYS } from '../stable-keys';\nimport { createBillingPaginatedHook } from './createBillingPaginatedHook';\n\n/**\n * @internal\n */\nexport const useStatements = createBillingPaginatedHook<BillingStatementResource, GetStatementsParams>({\n hookName: 'useStatements',\n resourceType: STABLE_KEYS.STATEMENTS_KEY,\n useFetcher: () => {\n const clerk = useClerkInstanceContext();\n if (clerk.loaded) {\n return clerk.billing.getStatements;\n }\n return undefined;\n },\n});\n\n/**\n * @interface\n */\nexport type UseStatementsReturn = ReturnType<typeof useStatements>;\n","import type { BillingPaymentResource, GetPaymentAttemptsParams } from '../../types';\nimport { useClerkInstanceContext } from '../contexts';\nimport { STABLE_KEYS } from '../stable-keys';\nimport { createBillingPaginatedHook } from './createBillingPaginatedHook';\n\n/**\n * @internal\n */\nexport const usePaymentAttempts = createBillingPaginatedHook<BillingPaymentResource, GetPaymentAttemptsParams>({\n hookName: 'usePaymentAttempts',\n resourceType: STABLE_KEYS.PAYMENT_ATTEMPTS_KEY,\n useFetcher: () => {\n const clerk = useClerkInstanceContext();\n if (clerk.loaded) {\n return clerk.billing.getPaymentAttempts;\n }\n return undefined;\n },\n});\n\n/**\n * @interface\n */\nexport type UsePaymentAttemptsReturn = ReturnType<typeof usePaymentAttempts>;\n","import type { BillingPaymentMethodResource, GetPaymentMethodsParams } from '../../types';\nimport { useOrganizationContext, useUserContext } from '../contexts';\nimport { STABLE_KEYS } from '../stable-keys';\nimport { createBillingPaginatedHook } from './createBillingPaginatedHook';\n\n/**\n * @internal\n */\nexport const usePaymentMethods = createBillingPaginatedHook<BillingPaymentMethodResource, GetPaymentMethodsParams>({\n hookName: 'usePaymentMethods',\n resourceType: STABLE_KEYS.PAYMENT_METHODS_KEY,\n useFetcher: resource => {\n const { organization } = useOrganizationContext();\n const user = useUserContext();\n\n if (resource === 'organization') {\n return organization?.getPaymentMethods;\n }\n return user?.getPaymentMethods;\n },\n});\n\n/**\n * @interface\n */\nexport type UsePaymentMethodsReturn = ReturnType<typeof usePaymentMethods>;\n","import type { BillingPlanResource, GetPlansParams } from '../../types';\nimport { useClerkInstanceContext } from '../contexts';\nimport { STABLE_KEYS } from '../stable-keys';\nimport { createBillingPaginatedHook } from './createBillingPaginatedHook';\n\n/**\n * @internal\n */\nexport const usePlans = createBillingPaginatedHook<BillingPlanResource, GetPlansParams>({\n hookName: 'usePlans',\n resourceType: STABLE_KEYS.PLANS_KEY,\n useFetcher: _for => {\n const clerk = useClerkInstanceContext();\n if (!clerk.loaded) {\n return undefined;\n }\n return params => clerk.billing.getPlans({ ...params, for: _for });\n },\n options: {\n unauthenticated: true,\n },\n});\n\n/**\n * @interface\n */\nexport type UsePlansReturn = ReturnType<typeof usePlans>;\n","import { useMemo } from 'react';\n\nimport type { ForPayerType } from '../../types';\nimport { STABLE_KEYS } from '../stable-keys';\nimport { createCacheKeys } from './createCacheKeys';\n\nexport function useSubscriptionCacheKeys(params: {\n userId: string | undefined;\n orgId: string | undefined;\n for?: ForPayerType;\n}) {\n const { userId, orgId, for: forType } = params;\n return useMemo(() => {\n const isOrganization = forType === 'organization';\n\n const safeOrgId = isOrganization ? orgId : undefined;\n return createCacheKeys({\n stablePrefix: STABLE_KEYS.SUBSCRIPTION_KEY,\n authenticated: true,\n tracked: {\n userId,\n orgId: safeOrgId,\n },\n untracked: {\n args: { orgId: safeOrgId },\n },\n });\n }, [userId, orgId, forType]);\n}\n","import { useCallback } from 'react';\n\nimport { eventMethodCalled } from '../../telemetry/events';\nimport type { EnvironmentResource } from '../../types';\nimport { useSWR } from '../clerk-swr';\nimport {\n useAssertWrappedByClerkProvider,\n useClerkInstanceContext,\n useOrganizationContext,\n useUserContext,\n} from '../contexts';\nimport { useSubscriptionCacheKeys } from './useSubscription.shared';\nimport type { SubscriptionResult, UseSubscriptionParams } from './useSubscription.types';\n\nconst hookName = 'useSubscription';\n\n/**\n * This is the existing implementation of useSubscription using SWR.\n * It is kept here for backwards compatibility until our next major version.\n *\n * @internal\n */\nexport function useSubscription(params?: UseSubscriptionParams): SubscriptionResult {\n useAssertWrappedByClerkProvider(hookName);\n\n const clerk = useClerkInstanceContext();\n const user = useUserContext();\n const { organization } = useOrganizationContext();\n\n // @ts-expect-error `__internal_environment` is not typed\n const environment = clerk.__internal_environment as unknown as EnvironmentResource | null | undefined;\n\n clerk.telemetry?.record(eventMethodCalled(hookName));\n\n const isOrganization = params?.for === 'organization';\n const billingEnabled = isOrganization\n ? environment?.commerceSettings.billing.organization.enabled\n : environment?.commerceSettings.billing.user.enabled;\n const isEnabled = (params?.enabled ?? true) && billingEnabled;\n\n const { queryKey } = useSubscriptionCacheKeys({\n userId: user?.id,\n orgId: organization?.id,\n for: params?.for,\n });\n\n const swr = useSWR(\n isEnabled ? { queryKey } : null,\n ({ queryKey }) => {\n const args = queryKey[3].args;\n\n if (queryKey[2].userId) {\n return clerk.billing.getSubscription(args);\n }\n return null;\n },\n {\n dedupingInterval: 1_000 * 60,\n keepPreviousData: params?.keepPreviousData,\n },\n );\n\n const revalidate = useCallback(() => {\n void swr.mutate();\n }, [swr]);\n\n return {\n data: swr.data,\n error: swr.error,\n isLoading: swr.isLoading,\n isFetching: swr.isValidating,\n revalidate,\n };\n}\n","import { useCallback, useSyncExternalStore } from 'react';\n\nimport type { CheckoutSignalValue } from '../../types/clerk';\nimport type { __experimental_CheckoutProvider } from '../contexts';\nimport { useCheckoutContext, useClerkInstanceContext, useOrganizationContext } from '../contexts';\nimport { useUser } from './useUser';\n\ntype UseCheckoutParams = Parameters<typeof __experimental_CheckoutProvider>[0];\n\n/**\n * @function\n *\n * @param [options] - An object containing the configuration for the checkout flow.\n *\n * **Required** if the hook is used without a `<CheckoutProvider />` wrapping the component tree.\n */\nexport const useCheckout = (options?: UseCheckoutParams): CheckoutSignalValue => {\n const contextOptions = useCheckoutContext();\n const { for: forOrganization, planId, planPeriod } = options || contextOptions;\n const { organization } = useOrganizationContext();\n const { isLoaded, user } = useUser();\n const clerk = useClerkInstanceContext();\n\n if (user === null && isLoaded) {\n throw new Error('Clerk: Ensure that `useCheckout` is inside a component wrapped with `<SignedIn />`.');\n }\n\n if (isLoaded && forOrganization === 'organization' && organization === null) {\n throw new Error(\n 'Clerk: Ensure your flow checks for an active organization. Retrieve `orgId` from `useAuth()` and confirm it is defined. For SSR, see: https://clerk.com/docs/reference/backend/types/auth-object#how-to-access-the-auth-object',\n );\n }\n\n const signal = useCallback(() => {\n return clerk.__experimental_checkout({ planId, planPeriod, for: forOrganization });\n }, [user?.id, organization?.id, planId, planPeriod, forOrganization]);\n\n const subscribe = useCallback(\n (callback: () => void) => {\n if (!clerk.loaded) {\n return () => {};\n }\n\n return clerk.__internal_state.__internal_effect(() => {\n signal();\n callback();\n });\n },\n [signal, clerk.loaded, clerk.__internal_state],\n );\n\n const getSnapshot = useCallback(() => {\n return signal();\n }, [signal]);\n\n const value = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n return value;\n};\n","import { useMemo } from 'react';\n\nimport type { ForPayerType } from '../../types';\nimport { INTERNAL_STABLE_KEYS } from '../stable-keys';\nimport { createCacheKeys } from './createCacheKeys';\n\nexport function useStatementQueryCacheKeys(params: {\n statementId: string | null;\n userId: string | null;\n orgId: string | null;\n for?: ForPayerType;\n}) {\n const { statementId, userId, orgId, for: forType } = params;\n return useMemo(() => {\n return createCacheKeys({\n stablePrefix: INTERNAL_STABLE_KEYS.BILLING_STATEMENTS_KEY,\n authenticated: true,\n tracked: {\n statementId,\n forType,\n userId,\n orgId,\n },\n untracked: {\n args: {\n id: statementId ?? undefined,\n orgId: orgId ?? undefined,\n },\n },\n });\n }, [statementId, forType, userId, orgId]);\n}\n","import { useSWR } from '../clerk-swr';\nimport { useClerkInstanceContext, useOrganizationContext, useUserContext } from '../contexts';\nimport { useStatementQueryCacheKeys } from './useStatementQuery.shared';\nimport type { StatementQueryResult, UseStatementQueryParams } from './useStatementQuery.types';\n\n/**\n * This is the existing implementation of useStatementQuery using SWR.\n * It is kept here for backwards compatibility until our next major version.\n *\n * @internal\n */\nexport function __internal_useStatementQuery(params: UseStatementQueryParams = {}): StatementQueryResult {\n const { statementId = null, enabled = true, keepPreviousData = false, for: forType = 'user' } = params;\n const clerk = useClerkInstanceContext();\n const user = useUserContext();\n const { organization } = useOrganizationContext();\n\n const organizationId = forType === 'organization' ? (organization?.id ?? null) : null;\n const userId = user?.id ?? null;\n\n const { queryKey } = useStatementQueryCacheKeys({\n statementId,\n userId,\n orgId: organizationId,\n for: forType,\n });\n\n const queryEnabled = Boolean(statementId) && enabled && (forType !== 'organization' || Boolean(organizationId));\n\n const swr = useSWR(\n queryEnabled ? queryKey : null,\n () => {\n if (!statementId) {\n throw new Error('statementId is required to fetch a statement');\n }\n return clerk.billing.getStatement({ id: statementId, orgId: organizationId ?? undefined });\n },\n {\n dedupingInterval: 1_000 * 60,\n keepPreviousData,\n },\n );\n\n return {\n data: swr.data,\n error: (swr.error ?? null) as StatementQueryResult['error'],\n isLoading: swr.isLoading,\n isFetching: swr.isValidating,\n };\n}\n","import { useMemo } from 'react';\n\nimport { INTERNAL_STABLE_KEYS } from '../stable-keys';\nimport { createCacheKeys } from './createCacheKeys';\n\nexport function usePlanDetailsQueryCacheKeys(params: { planId: string | null }) {\n const { planId } = params;\n return useMemo(() => {\n return createCacheKeys({\n stablePrefix: INTERNAL_STABLE_KEYS.BILLING_PLANS_KEY,\n authenticated: false,\n tracked: {\n planId: planId ?? null,\n },\n untracked: {\n args: {\n id: planId ?? undefined,\n },\n },\n });\n }, [planId]);\n}\n","import { useSWR } from '../clerk-swr';\nimport { useClerkInstanceContext } from '../contexts';\nimport { usePlanDetailsQueryCacheKeys } from './usePlanDetailsQuery.shared';\nimport type { PlanDetailsQueryResult, UsePlanDetailsQueryParams } from './usePlanDetailsQuery.types';\n\n/**\n * This is the existing implementation of usePlanDetailsQuery using SWR.\n * It is kept here for backwards compatibility until our next major version.\n *\n * @internal\n */\nfunction usePlanDetailsQuery(params: UsePlanDetailsQueryParams = {}): PlanDetailsQueryResult {\n const { planId, initialPlan = null, enabled = true, keepPreviousData = true } = params;\n const clerk = useClerkInstanceContext();\n\n const targetPlanId = planId ?? initialPlan?.id ?? null;\n\n const { queryKey } = usePlanDetailsQueryCacheKeys({ planId: targetPlanId });\n\n const queryEnabled = Boolean(targetPlanId) && enabled;\n\n const swr = useSWR(\n queryEnabled ? queryKey : null,\n () => {\n if (!targetPlanId) {\n throw new Error('planId is required to fetch plan details');\n }\n return clerk.billing.getPlan({ id: targetPlanId });\n },\n {\n dedupingInterval: 1_000 * 60,\n keepPreviousData,\n fallbackData: initialPlan ?? undefined,\n },\n );\n\n return {\n data: swr.data,\n error: (swr.error ?? null) as PlanDetailsQueryResult['error'],\n isLoading: swr.isLoading,\n isFetching: swr.isValidating,\n };\n}\n\nexport { usePlanDetailsQuery as __internal_usePlanDetailsQuery };\n","import { useMemo } from 'react';\n\nimport type { ForPayerType } from '../../types';\nimport { INTERNAL_STABLE_KEYS } from '../stable-keys';\nimport { createCacheKeys } from './createCacheKeys';\n\nexport function usePaymentAttemptQueryCacheKeys(params: {\n paymentAttemptId: string;\n userId: string | null;\n orgId: string | null;\n for?: ForPayerType;\n}) {\n const { paymentAttemptId, userId, orgId, for: forType } = params;\n return useMemo(() => {\n return createCacheKeys({\n stablePrefix: INTERNAL_STABLE_KEYS.PAYMENT_ATTEMPT_KEY,\n authenticated: true,\n tracked: {\n paymentAttemptId,\n forType,\n userId,\n orgId,\n },\n untracked: {\n args: {\n id: paymentAttemptId ?? undefined,\n orgId: orgId ?? undefined,\n },\n },\n });\n }, [paymentAttemptId, forType, userId, orgId]);\n}\n","import { useSWR } from '../clerk-swr';\nimport { useClerkInstanceContext, useOrganizationContext, useUserContext } from '../contexts';\nimport { usePaymentAttemptQueryCacheKeys } from './usePaymentAttemptQuery.shared';\nimport type { PaymentAttemptQueryResult, UsePaymentAttemptQueryParams } from './usePaymentAttemptQuery.types';\n\n/**\n * This is the existing implementation of usePaymentAttemptQuery using SWR.\n * It is kept here for backwards compatibility until our next major version.\n *\n * @internal\n */\nexport function __internal_usePaymentAttemptQuery(params: UsePaymentAttemptQueryParams): PaymentAttemptQueryResult {\n const { paymentAttemptId, enabled = true, keepPreviousData = false, for: forType = 'user' } = params;\n const clerk = useClerkInstanceContext();\n const user = useUserContext();\n const { organization } = useOrganizationContext();\n\n const organizationId = forType === 'organization' ? (organization?.id ?? null) : null;\n const userId = user?.id ?? null;\n\n const { queryKey } = usePaymentAttemptQueryCacheKeys({\n paymentAttemptId,\n userId,\n orgId: organizationId,\n for: forType,\n });\n\n const queryEnabled = Boolean(paymentAttemptId) && enabled && (forType !== 'organization' || Boolean(organizationId));\n\n const swr = useSWR(\n queryEnabled ? { queryKey } : null,\n ({ queryKey }) => {\n const args = queryKey[3].args;\n return clerk.billing.getPaymentAttempt(args);\n },\n {\n dedupingInterval: 1_000 * 60,\n keepPreviousData,\n },\n );\n\n return {\n data: swr.data,\n error: (swr.error ?? null) as PaymentAttemptQueryResult['error'],\n isLoading: swr.isLoading,\n isFetching: swr.isValidating,\n };\n}\n","import type { StripeElement } from '@stripe/stripe-js';\nimport { useEffect, useRef } from 'react';\n\nexport const usePrevious = <T>(value: T): T => {\n const ref = useRef(value);\n\n useEffect(() => {\n ref.current = value;\n }, [value]);\n\n return ref.current;\n};\n\nexport const useAttachEvent = <A extends unknown[]>(\n element: StripeElement | null,\n event: string,\n cb?: (...args: A) => any,\n) => {\n const cbDefined = !!cb;\n const cbRef = useRef(cb);\n\n // In many integrations the callback prop changes on each render.\n // Using a ref saves us from calling element.on/.off every render.\n useEffect(() => {\n cbRef.current = cb;\n }, [cb]);\n\n useEffect(() => {\n if (!cbDefined || !element) {\n return () => {};\n }\n\n const decoratedCb = (...args: A): void => {\n if (cbRef.current) {\n cbRef.current(...args);\n }\n };\n\n (element as any).on(event, decoratedCb);\n\n return () => {\n (element as any).off(event, decoratedCb);\n };\n }, [cbDefined, event, element, cbRef]);\n};\n","/**\n * Original source: https://github.com/stripe/react-stripe-js.\n *\n * The current version of this file is a fork of the original version.\n * The main difference is that we have kept only the necessary parts of the file.\n * This is because we don't need it and it's not used in the Clerk codebase.\n *\n * The original version of this file is licensed under the MIT license.\n * Https://github.com/stripe/react-stripe-js/blob/master/LICENSE.\n */\n\nimport type { ElementProps, PaymentElementProps } from '@stripe/react-stripe-js';\nimport type {\n Stripe,\n StripeElement,\n StripeElements,\n StripeElementsOptions,\n StripeElementType,\n} from '@stripe/stripe-js';\nimport type { FunctionComponent, PropsWithChildren, ReactNode } from 'react';\nimport React, { useState } from 'react';\n\nimport { useAttachEvent, usePrevious } from './utils';\n\ninterface ElementsContextValue {\n elements: StripeElements | null;\n stripe: Stripe | null;\n}\n\nconst ElementsContext = React.createContext<ElementsContextValue | null>(null);\nElementsContext.displayName = 'ElementsContext';\n\nconst parseElementsContext = (ctx: ElementsContextValue | null, useCase: string): ElementsContextValue => {\n if (!ctx) {\n throw new Error(\n `Could not find Elements context; You need to wrap the part of your app that ${useCase} in an <Elements> provider.`,\n );\n }\n\n return ctx;\n};\n\ninterface ElementsProps {\n /**\n * A [Stripe object](https://stripe.com/docs/js/initializing) or a `Promise` resolving to a `Stripe` object.\n * The easiest way to initialize a `Stripe` object is with the the [Stripe.js wrapper module](https://github.com/stripe/stripe-js/blob/master/README.md#readme).\n * Once this prop has been set, it can not be changed.\n *\n * You can also pass in `null` or a `Promise` resolving to `null` if you are performing an initial server-side render or when generating a static site.\n */\n stripe: PromiseLike<Stripe | null> | Stripe | null;\n\n /**\n * Optional [Elements configuration options](https://stripe.com/docs/js/elements_object/create).\n * Once the stripe prop has been set, these options cannot be changed.\n */\n options?: StripeElementsOptions;\n}\n\ntype UnknownOptions = { [k: string]: unknown };\n\ninterface PrivateElementsProps {\n stripe: unknown;\n options?: UnknownOptions;\n children?: ReactNode;\n}\n\n/**\n * The `Elements` provider allows you to use [Element components](https://stripe.com/docs/stripe-js/react#element-components) and access the [Stripe object](https://stripe.com/docs/js/initializing) in any nested component.\n * Render an `Elements` provider at the root of your React app so that it is available everywhere you need it.\n *\n * To use the `Elements` provider, call `loadStripe` from `@stripe/stripe-js` with your publishable key.\n * The `loadStripe` function will asynchronously load the Stripe.js script and initialize a `Stripe` object.\n * Pass the returned `Promise` to `Elements`.\n *\n * @docs https://stripe.com/docs/stripe-js/react#elements-provider\n */\nconst Elements: FunctionComponent<PropsWithChildren<ElementsProps>> = (({\n stripe: rawStripeProp,\n options,\n children,\n}: PrivateElementsProps) => {\n const parsed = React.useMemo(() => parseStripeProp(rawStripeProp), [rawStripeProp]);\n\n // For a sync stripe instance, initialize into context\n const [ctx, setContext] = React.useState<ElementsContextValue>(() => ({\n stripe: parsed.tag === 'sync' ? parsed.stripe : null,\n elements: parsed.tag === 'sync' ? parsed.stripe.elements(options) : null,\n }));\n\n React.useEffect(() => {\n let isMounted = true;\n\n const safeSetContext = (stripe: Stripe) => {\n setContext(ctx => {\n // no-op if we already have a stripe instance (https://github.com/stripe/react-stripe-js/issues/296)\n if (ctx.stripe) {\n return ctx;\n }\n return {\n stripe,\n elements: stripe.elements(options),\n };\n });\n };\n\n // For an async stripePromise, store it in context once resolved\n if (parsed.tag === 'async' && !ctx.stripe) {\n parsed.stripePromise.then(stripe => {\n if (stripe && isMounted) {\n // Only update Elements context if the component is still mounted\n // and stripe is not null. We allow stripe to be null to make\n // handling SSR easier.\n safeSetContext(stripe);\n }\n });\n } else if (parsed.tag === 'sync' && !ctx.stripe) {\n // Or, handle a sync stripe instance going from null -> populated\n safeSetContext(parsed.stripe);\n }\n\n return () => {\n isMounted = false;\n };\n }, [parsed, ctx, options]);\n\n // Warn on changes to stripe prop\n const prevStripe = usePrevious(rawStripeProp);\n React.useEffect(() => {\n if (prevStripe !== null && prevStripe !== rawStripeProp) {\n console.warn('Unsupported prop change on Elements: You cannot change the `stripe` prop after setting it.');\n }\n }, [prevStripe, rawStripeProp]);\n\n // Apply updates to elements when options prop has relevant changes\n const prevOptions = usePrevious(options);\n React.useEffect(() => {\n if (!ctx.elements) {\n return;\n }\n\n const updates = extractAllowedOptionsUpdates(options, prevOptions, ['clientSecret', 'fonts']);\n\n if (updates) {\n ctx.elements.update(updates);\n }\n }, [options, prevOptions, ctx.elements]);\n\n return <ElementsContext.Provider value={ctx}>{children}</ElementsContext.Provider>;\n}) as FunctionComponent<PropsWithChildren<ElementsProps>>;\n\nconst useElementsContextWithUseCase = (useCaseMessage: string): ElementsContextValue => {\n const ctx = React.useContext(ElementsContext);\n return parseElementsContext(ctx, useCaseMessage);\n};\n\nconst useElements = (): StripeElements | null => {\n const { elements } = useElementsContextWithUseCase('calls useElements()');\n return elements;\n};\n\nconst INVALID_STRIPE_ERROR =\n 'Invalid prop `stripe` supplied to `Elements`. We recommend using the `loadStripe` utility from `@stripe/stripe-js`. See https://stripe.com/docs/stripe-js/react#elements-props-stripe for details.';\n\n// We are using types to enforce the `stripe` prop in this lib, but in a real\n// integration `stripe` could be anything, so we need to do some sanity\n// validation to prevent type errors.\nconst validateStripe = (maybeStripe: unknown, errorMsg = INVALID_STRIPE_ERROR): null | Stripe => {\n if (maybeStripe === null || isStripe(maybeStripe)) {\n return maybeStripe;\n }\n\n throw new Error(errorMsg);\n};\n\ntype ParsedStripeProp =\n | { tag: 'empty' }\n | { tag: 'sync'; stripe: Stripe }\n | { tag: 'async'; stripePromise: Promise<Stripe | null> };\n\nconst parseStripeProp = (raw: unknown, errorMsg = INVALID_STRIPE_ERROR): ParsedStripeProp => {\n if (isPromise(raw)) {\n return {\n tag: 'async',\n stripePromise: Promise.resolve(raw).then(result => validateStripe(result, errorMsg)),\n };\n }\n\n const stripe = validateStripe(raw, errorMsg);\n\n if (stripe === null) {\n return { tag: 'empty' };\n }\n\n return { tag: 'sync', stripe };\n};\n\nconst isUnknownObject = (raw: unknown): raw is { [key in PropertyKey]: unknown } => {\n return raw !== null && typeof raw === 'object';\n};\n\nconst isPromise = (raw: unknown): raw is PromiseLike<unknown> => {\n return isUnknownObject(raw) && typeof raw.then === 'function';\n};\n\n// We are using types to enforce the `stripe` prop in this lib,\n// but in an untyped integration `stripe` could be anything, so we need\n// to do some sanity validation to prevent type errors.\nconst isStripe = (raw: unknown): raw is Stripe => {\n return (\n isUnknownObject(raw) &&\n typeof raw.elements === 'function' &&\n typeof raw.createToken === 'function' &&\n typeof raw.createPaymentMethod === 'function' &&\n typeof raw.confirmCardPayment === 'function'\n );\n};\n\nconst extractAllowedOptionsUpdates = (\n options: unknown | void,\n prevOptions: unknown | void,\n immutableKeys: string[],\n): UnknownOptions | null => {\n if (!isUnknownObject(options)) {\n return null;\n }\n\n return Object.keys(options).reduce((newOptions: null | UnknownOptions, key) => {\n const isUpdated = !isUnknownObject(prevOptions) || !isEqual(options[key], prevOptions[key]);\n\n if (immutableKeys.includes(key)) {\n if (isUpdated) {\n console.warn(`Unsupported prop change: options.${key} is not a mutable property.`);\n }\n\n return newOptions;\n }\n\n if (!isUpdated) {\n return newOptions;\n }\n\n return { ...(newOptions || {}), [key]: options[key] };\n }, null);\n};\n\nconst PLAIN_OBJECT_STR = '[object Object]';\n\nconst isEqual = (left: unknown, right: unknown): boolean => {\n if (!isUnknownObject(left) || !isUnknownObject(right)) {\n return left === right;\n }\n\n const leftArray = Array.isArray(left);\n const rightArray = Array.isArray(right);\n\n if (leftArray !== rightArray) {\n return false;\n }\n\n const leftPlainObject = Object.prototype.toString.call(left) === PLAIN_OBJECT_STR;\n const rightPlainObject = Object.prototype.toString.call(right) === PLAIN_OBJECT_STR;\n\n if (leftPlainObject !== rightPlainObject) {\n return false;\n }\n\n // not sure what sort of special object this is (regexp is one option), so\n // fallback to reference check.\n if (!leftPlainObject && !leftArray) {\n return left === right;\n }\n\n const leftKeys = Object.keys(left);\n const rightKeys = Object.keys(right);\n\n if (leftKeys.length !== rightKeys.length) {\n return false;\n }\n\n const keySet: { [key: string]: boolean } = {};\n for (let i = 0; i < leftKeys.length; i += 1) {\n keySet[leftKeys[i]] = true;\n }\n for (let i = 0; i < rightKeys.length; i += 1) {\n keySet[rightKeys[i]] = true;\n }\n const allKeys = Object.keys(keySet);\n if (allKeys.length !== leftKeys.length) {\n return false;\n }\n\n const l = left;\n const r = right;\n const pred = (key: string): boolean => {\n return isEqual(l[key], r[key]);\n };\n\n return allKeys.every(pred);\n};\n\nconst useStripe = (): Stripe | null => {\n const { stripe } = useElementsOrCheckoutSdkContextWithUseCase('calls useStripe()');\n return stripe;\n};\n\nconst useElementsOrCheckoutSdkContextWithUseCase = (useCaseString: string): ElementsContextValue => {\n const elementsContext = React.useContext(ElementsContext);\n\n return parseElementsContext(elementsContext, useCaseString);\n};\n\ntype UnknownCallback = (...args: unknown[]) => any;\n\ninterface PrivateElementProps {\n id?: string;\n className?: string;\n fallback?: ReactNode;\n onChange?: UnknownCallback;\n onBlur?: UnknownCallback;\n onFocus?: UnknownCallback;\n onEscape?: UnknownCallback;\n onReady?: UnknownCallback;\n onClick?: UnknownCallback;\n onLoadError?: UnknownCallback;\n onLoaderStart?: UnknownCallback;\n onNetworksChange?: UnknownCallback;\n onConfirm?: UnknownCallback;\n onCancel?: UnknownCallback;\n onShippingAddressChange?: UnknownCallback;\n onShippingRateChange?: UnknownCallback;\n options?: UnknownOptions;\n}\n\nconst capitalized = (str: string) => str.charAt(0).toUpperCase() + str.slice(1);\n\nconst createElementComponent = (type: StripeElementType, isServer: boolean): FunctionComponent<ElementProps> => {\n const displayName = `${capitalized(type)}Element`;\n\n const ClientElement: FunctionComponent<PrivateElementProps> = ({\n id,\n className,\n fallback,\n options = {},\n onBlur,\n onFocus,\n onReady,\n onChange,\n onEscape,\n onClick,\n onLoadError,\n onLoaderStart,\n onNetworksChange,\n onConfirm,\n onCancel,\n onShippingAddressChange,\n onShippingRateChange,\n }) => {\n const ctx = useElementsOrCheckoutSdkContextWithUseCase(`mounts <${displayName}>`);\n const elements = 'elements' in ctx ? ctx.elements : null;\n const [element, setElement] = React.useState<StripeElement | null>(null);\n const elementRef = React.useRef<StripeElement | null>(null);\n const domNode = React.useRef<HTMLDivElement | null>(null);\n const [isReady, setReady] = useState(false);\n\n // For every event where the merchant provides a callback, call element.on\n // with that callback. If the merchant ever changes the callback, removes\n // the old callback with element.off and then call element.on with the new one.\n useAttachEvent(element, 'blur', onBlur);\n useAttachEvent(element, 'focus', onFocus);\n useAttachEvent(element, 'escape', onEscape);\n useAttachEvent(element, 'click', onClick);\n useAttachEvent(element, 'loaderror', onLoadError);\n useAttachEvent(element, 'loaderstart', onLoaderStart);\n useAttachEvent(element, 'networkschange', onNetworksChange);\n useAttachEvent(element, 'confirm', onConfirm);\n useAttachEvent(element, 'cancel', onCancel);\n useAttachEvent(element, 'shippingaddresschange', onShippingAddressChange);\n useAttachEvent(element, 'shippingratechange', onShippingRateChange);\n useAttachEvent(element, 'change', onChange);\n\n let readyCallback: UnknownCallback | undefined;\n if (onReady) {\n // For other Elements, pass through the Element itself.\n readyCallback = () => {\n setReady(true);\n onReady(element);\n };\n }\n\n useAttachEvent(element, 'ready', readyCallback);\n\n React.useLayoutEffect(() => {\n if (elementRef.current === null && domNode.current !== null && elements) {\n let newElement: StripeElement | null = null;\n if (elements) {\n newElement = elements.create(type as any, options);\n }\n\n // Store element in a ref to ensure it's _immediately_ available in cleanup hooks in StrictMode\n elementRef.current = newElement;\n // Store element in state to facilitate event listener attachment\n setElement(newElement);\n\n if (newElement) {\n newElement.mount(domNode.current);\n }\n }\n }, [elements, options]);\n\n const prevOptions = usePrevious(options);\n React.useEffect(() => {\n if (!elementRef.current) {\n return;\n }\n\n const updates = extractAllowedOptionsUpdates(options, prevOptions, ['paymentRequest']);\n\n if (updates && 'update' in elementRef.current) {\n elementRef.current.update(updates);\n }\n }, [options, prevOptions]);\n\n React.useLayoutEffect(() => {\n return () => {\n if (elementRef.current && typeof elementRef.current.destroy === 'function') {\n try {\n elementRef.current.destroy();\n elementRef.current = null;\n } catch {\n // Do nothing\n }\n }\n };\n }, []);\n\n return (\n <>\n {!isReady && fallback}\n <div\n id={id}\n style={{\n height: isReady ? 'unset' : '0px',\n visibility: isReady ? 'visible' : 'hidden',\n }}\n className={className}\n ref={domNode}\n />\n </>\n );\n };\n\n // Only render the Element wrapper in a server environment.\n const ServerElement: FunctionComponent<PrivateElementProps> = props => {\n useElementsOrCheckoutSdkContextWithUseCase(`mounts <${displayName}>`);\n const { id, className } = props;\n return (\n <div\n id={id}\n className={className}\n />\n );\n };\n\n const Element = isServer ? ServerElement : ClientElement;\n Element.displayName = displayName;\n (Element as any).__elementType = type;\n\n return Element as FunctionComponent<ElementProps>;\n};\n\nconst isServer = typeof window === 'undefined';\nconst PaymentElement: FunctionComponent<\n PaymentElementProps & {\n fallback?: ReactNode;\n }\n> = createElementComponent('payment', isServer);\n\nexport { Elements, PaymentElement, useElements, useStripe };\n","import { useEffect } from 'react';\nimport useSWRMutation from 'swr/mutation';\n\nimport type { BillingInitializedPaymentMethodResource, ForPayerType } from '../../types';\nimport { useOrganizationContext, useUserContext } from '../contexts';\n\ntype InitializePaymentMethodOptions = {\n for?: ForPayerType;\n};\n\nexport type UseInitializePaymentMethodResult = {\n initializedPaymentMethod: BillingInitializedPaymentMethodResource | undefined;\n initializePaymentMethod: () => Promise<BillingInitializedPaymentMethodResource | undefined>;\n};\n\n/**\n * This is the existing implementation of the payment method initializer using SWR.\n * It is kept here for backwards compatibility until our next major version.\n *\n * @internal\n */\nfunction useInitializePaymentMethod(options?: InitializePaymentMethodOptions): UseInitializePaymentMethodResult {\n const { for: forType = 'user' } = options ?? {};\n const { organization } = useOrganizationContext();\n const user = useUserContext();\n\n const resource = forType === 'organization' ? organization : user;\n\n const { data, trigger } = useSWRMutation(\n resource?.id\n ? {\n key: 'billing-payment-method-initialize',\n resourceId: resource.id,\n for: forType,\n }\n : null,\n () => {\n return resource?.initializePaymentMethod({\n gateway: 'stripe',\n });\n },\n );\n\n useEffect(() => {\n if (!resource?.id) {\n return;\n }\n\n trigger().catch(() => {\n // ignore errors\n });\n }, [resource?.id, trigger]);\n\n return {\n initializedPaymentMethod: data,\n initializePaymentMethod: trigger,\n };\n}\n\nexport { useInitializePaymentMethod as __internal_useInitializePaymentMethod };\n","import type { loadStripe } from '@stripe/stripe-js';\n\nimport { useSWR } from '../clerk-swr';\nimport { useClerk } from '../hooks/useClerk';\n\ntype LoadStripeFn = typeof loadStripe;\n\ntype StripeClerkLibs = {\n loadStripe: LoadStripeFn;\n};\n\nexport type UseStripeClerkLibsResult = StripeClerkLibs | null;\n\n/**\n * This is the existing implementation of the Stripe libraries loader using SWR.\n * It is kept here for backwards compatibility until our next major version.\n *\n * @internal\n */\nfunction useStripeClerkLibs(): UseStripeClerkLibsResult {\n const clerk = useClerk();\n\n const swr = useSWR(\n 'clerk-stripe-sdk',\n async () => {\n const loadStripe = (await clerk.__internal_loadStripeJs()) as LoadStripeFn;\n return { loadStripe };\n },\n {\n keepPreviousData: true,\n revalidateOnFocus: false,\n dedupingInterval: Infinity,\n },\n );\n\n return swr.data ?? null;\n}\n\nexport { useStripeClerkLibs as __internal_useStripeClerkLibs };\n","import type { Stripe } from '@stripe/stripe-js';\n\nimport { useSWR } from '../clerk-swr';\nimport type { UseStripeClerkLibsResult } from './useStripeClerkLibs';\n\ntype StripeLoaderOptions = {\n stripeClerkLibs: UseStripeClerkLibsResult;\n externalGatewayId?: string;\n stripePublishableKey?: string;\n};\n\nexport type UseStripeLoaderResult = Stripe | null | undefined;\n\n/**\n * This is the existing implementation of the Stripe instance loader using SWR.\n * It is kept here for backwards compatibility until our next major version.\n *\n * @internal\n */\nfunction useStripeLoader(options: StripeLoaderOptions): UseStripeLoaderResult {\n const { stripeClerkLibs, externalGatewayId, stripePublishableKey } = options;\n\n const swr = useSWR(\n stripeClerkLibs && externalGatewayId && stripePublishableKey\n ? {\n key: 'stripe-sdk',\n externalGatewayId,\n stripePublishableKey,\n }\n : null,\n ({ stripePublishableKey, externalGatewayId }) => {\n return stripeClerkLibs?.loadStripe(stripePublishableKey, {\n stripeAccount: externalGatewayId,\n });\n },\n {\n keepPreviousData: true,\n revalidateOnFocus: false,\n dedupingInterval: 1_000 * 60,\n },\n );\n\n return swr.data;\n}\n\nexport { useStripeLoader as __internal_useStripeLoader };\n","import type { Stripe, StripeElements, StripeElementsOptions } from '@stripe/stripe-js';\nimport React, { type PropsWithChildren, type ReactNode, useCallback, useMemo, useState } from 'react';\n\nimport type { BillingCheckoutResource, CheckoutFlowResource, EnvironmentResource, ForPayerType } from '../../types';\nimport { createContextAndHook } from '../hooks/createContextAndHook';\nimport type { useCheckout } from '../hooks/useCheckout';\nimport { useClerk } from '../hooks/useClerk';\nimport { Elements, PaymentElement as StripePaymentElement, useElements, useStripe } from '../stripe-react';\nimport {\n __internal_useInitializePaymentMethod as useInitializePaymentMethod,\n type UseInitializePaymentMethodResult,\n} from './useInitializePaymentMethod';\nimport { __internal_useStripeClerkLibs as useStripeClerkLibs } from './useStripeClerkLibs';\nimport { __internal_useStripeLoader as useStripeLoader, type UseStripeLoaderResult } from './useStripeLoader';\n\ntype PaymentElementError = {\n gateway: 'stripe';\n error: {\n /**\n * For some errors that could be handled programmatically, a short string indicating the [error code](https://stripe.com/docs/error-codes) reported.\n */\n code?: string;\n message?: string;\n type: string;\n };\n};\n\nconst useInternalEnvironment = () => {\n const clerk = useClerk();\n // @ts-expect-error `__internal_environment` is not typed\n return clerk.__internal_environment as unknown as EnvironmentResource | null | undefined;\n};\n\nconst useLocalization = () => {\n const clerk = useClerk();\n\n let locale = 'en';\n try {\n const localization = clerk.__internal_getOption('localization');\n locale = localization?.locale || 'en';\n } catch {\n // ignore errors\n }\n\n // Normalize locale to 2-letter language code for Stripe compatibility\n const normalizedLocale = locale.split('-')[0];\n\n return normalizedLocale;\n};\n\nconst usePaymentSourceUtils = (forResource: ForPayerType = 'user') => {\n const stripeClerkLibs = useStripeClerkLibs();\n const environment = useInternalEnvironment();\n\n const { initializedPaymentMethod, initializePaymentMethod }: UseInitializePaymentMethodResult =\n useInitializePaymentMethod({ for: forResource });\n\n const stripePublishableKey = environment?.commerceSettings.billing.stripePublishableKey ?? undefined;\n\n const stripe: UseStripeLoaderResult = useStripeLoader({\n stripeClerkLibs,\n externalGatewayId: initializedPaymentMethod?.externalGatewayId,\n stripePublishableKey,\n });\n\n const externalClientSecret = initializedPaymentMethod?.externalClientSecret;\n const paymentMethodOrder = initializedPaymentMethod?.paymentMethodOrder;\n\n return {\n stripe,\n initializePaymentMethod,\n externalClientSecret,\n paymentMethodOrder,\n };\n};\n\ntype internalStripeAppearance = {\n colorPrimary: string;\n colorBackground: string;\n colorText: string;\n colorTextSecondary: string;\n colorSuccess: string;\n colorDanger: string;\n colorWarning: string;\n fontWeightNormal: string;\n fontWeightMedium: string;\n fontWeightBold: string;\n fontSizeXl: string;\n fontSizeLg: string;\n fontSizeSm: string;\n fontSizeXs: string;\n borderRadius: string;\n spacingUnit: string;\n};\n\n/**\n * @interface\n */\nexport type PaymentElementProviderProps = {\n /**\n * An optional checkout resource object. When provided, the payment element is scoped to the specific checkout session.\n */\n checkout?: CheckoutFlowResource | BillingCheckoutResource | ReturnType<typeof useCheckout>['checkout'];\n /**\n * An optional object to customize the appearance of the Stripe Payment Element. This allows you to match the form's styling to your application's theme.\n */\n stripeAppearance?: internalStripeAppearance;\n /**\n * Specifies whether to fetch for the current user or Organization.\n *\n * @default 'user'\n */\n for?: ForPayerType;\n /**\n * An optional description to display to the user within the payment element UI.\n */\n paymentDescription?: string;\n};\n\nconst [PaymentElementContext, usePaymentElementContext] = createContextAndHook<\n ReturnType<typeof usePaymentSourceUtils> &\n PaymentElementProviderProps & {\n setIsPaymentElementReady: (isPaymentElementReady: boolean) => void;\n isPaymentElementReady: boolean;\n }\n>('PaymentElementContext');\n\nconst [StripeUtilsContext, useStripeUtilsContext] = createContextAndHook<{\n stripe: Stripe | undefined | null;\n elements: StripeElements | undefined | null;\n}>('StripeUtilsContext');\n\nconst ValidateStripeUtils = ({ children }: PropsWithChildren) => {\n const stripe = useStripe();\n const elements = useElements();\n\n return <StripeUtilsContext.Provider value={{ value: { stripe, elements } }}>{children}</StripeUtilsContext.Provider>;\n};\n\nconst DummyStripeUtils = ({ children }: PropsWithChildren) => {\n return <StripeUtilsContext.Provider value={{ value: {} as any }}>{children}</StripeUtilsContext.Provider>;\n};\n\nconst PropsProvider = ({ children, ...props }: PropsWithChildren<PaymentElementProviderProps>) => {\n const utils = usePaymentSourceUtils(props.for);\n const [isPaymentElementReady, setIsPaymentElementReady] = useState(false);\n return (\n <PaymentElementContext.Provider\n value={{\n value: {\n ...props,\n ...utils,\n setIsPaymentElementReady,\n isPaymentElementReady,\n },\n }}\n >\n {children}\n </PaymentElementContext.Provider>\n );\n};\n\nconst PaymentElementProvider = ({ children, ...props }: PropsWithChildren<PaymentElementProviderProps>) => {\n return (\n <PropsProvider {...props}>\n <PaymentElementInternalRoot>{children}</PaymentElementInternalRoot>\n </PropsProvider>\n );\n};\n\nconst PaymentElementInternalRoot = (props: PropsWithChildren) => {\n const { stripe, externalClientSecret, stripeAppearance } = usePaymentElementContext();\n const locale = useLocalization();\n\n if (stripe && externalClientSecret) {\n return (\n <Elements\n // This key is used to reset the payment intent, since Stripe doesn't provide a way to reset the payment intent.\n key={externalClientSecret}\n stripe={stripe}\n options={{\n loader: 'never',\n clientSecret: externalClientSecret,\n appearance: {\n variables: stripeAppearance,\n },\n locale: locale as StripeElementsOptions['locale'],\n }}\n >\n <ValidateStripeUtils>{props.children}</ValidateStripeUtils>\n </Elements>\n );\n }\n\n return <DummyStripeUtils>{props.children}</DummyStripeUtils>;\n};\n\n/**\n * @interface\n */\nexport type PaymentElementProps = {\n /**\n * Optional fallback content, such as a loading skeleton, to display while the payment form is being initialized.\n */\n fallback?: ReactNode;\n};\n\nconst PaymentElement = ({ fallback }: PaymentElementProps) => {\n const {\n setIsPaymentElementReady,\n paymentMethodOrder,\n checkout,\n stripe,\n externalClientSecret,\n paymentDescription,\n for: _for,\n } = usePaymentElementContext();\n const environment = useInternalEnvironment();\n\n const applePay = useMemo(() => {\n if (!checkout || !checkout.totals || !checkout.plan) {\n return undefined;\n }\n\n return {\n recurringPaymentRequest: {\n paymentDescription: paymentDescription || '',\n managementURL:\n _for === 'organization'\n ? environment?.displayConfig.organizationProfileUrl || ''\n : environment?.displayConfig.userProfileUrl || '',\n regularBilling: {\n amount: checkout.totals.totalDueNow?.amount || checkout.totals.grandTotal.amount,\n label: checkout.plan.name,\n recurringPaymentIntervalUnit: checkout.planPeriod === 'annual' ? 'year' : 'month',\n },\n },\n } as const;\n }, [checkout, paymentDescription, _for, environment]);\n\n const options = useMemo(() => {\n return {\n layout: {\n type: 'tabs',\n defaultCollapsed: false,\n },\n paymentMethodOrder,\n applePay,\n } as const;\n }, [applePay, paymentMethodOrder]);\n\n const onReady = useCallback(() => {\n setIsPaymentElementReady(true);\n }, [setIsPaymentElementReady]);\n\n if (!stripe || !externalClientSecret) {\n return <>{fallback}</>;\n }\n\n return (\n <StripePaymentElement\n fallback={fallback}\n onReady={onReady}\n options={options}\n />\n );\n};\n\nconst throwLibsMissingError = () => {\n throw new Error(\n 'Clerk: Unable to submit, Stripe libraries are not yet loaded. Be sure to check `isFormReady` before calling `submit`.',\n );\n};\n\n/**\n * @interface\n */\nexport type UsePaymentElementReturn = {\n /**\n * A function that submits the payment form data to the payment provider. It returns a promise that resolves with either a `data` object containing a payment token on success, or an `error` object on failure.\n */\n submit: () => Promise<\n | {\n data: { gateway: 'stripe'; paymentToken: string };\n error: null;\n }\n | {\n data: null;\n error: PaymentElementError;\n }\n >;\n /**\n * A function that resets the payment form to its initial, empty state.\n */\n reset: () => Promise<void>;\n /**\n * A boolean that indicates if the payment form UI has been rendered and is ready for user input. This is useful for disabling a submit button until the form is interactive.\n */\n isFormReady: boolean;\n} & (\n | {\n /**\n * An object containing information about the initialized payment provider. It is `undefined` until `isProviderReady` is `true`.\n */\n provider: {\n name: 'stripe';\n };\n /**\n * A boolean that indicates if the underlying payment provider (e.g. Stripe) has been fully initialized.\n */\n isProviderReady: true;\n }\n | {\n provider: undefined;\n isProviderReady: false;\n }\n);\n\nconst usePaymentElement = (): UsePaymentElementReturn => {\n const { isPaymentElementReady, initializePaymentMethod } = usePaymentElementContext();\n const { stripe, elements } = useStripeUtilsContext();\n const { externalClientSecret } = usePaymentElementContext();\n\n const submit = useCallback(async () => {\n if (!stripe || !elements) {\n return throwLibsMissingError();\n }\n\n const { setupIntent, error } = await stripe.confirmSetup({\n elements,\n confirmParams: {\n return_url: window.location.href,\n },\n redirect: 'if_required',\n });\n if (error) {\n return {\n data: null,\n error: {\n gateway: 'stripe',\n error: {\n code: error.code,\n message: error.message,\n type: error.type,\n },\n },\n } as const;\n }\n return {\n data: { gateway: 'stripe', paymentToken: setupIntent.payment_method as string },\n error: null,\n } as const;\n }, [stripe, elements]);\n\n const reset = useCallback(async () => {\n if (!stripe || !elements) {\n return throwLibsMissingError();\n }\n\n await initializePaymentMethod();\n }, [stripe, elements, initializePaymentMethod]);\n\n const isProviderReady = Boolean(stripe && externalClientSecret);\n\n if (!isProviderReady) {\n return {\n submit: throwLibsMissingError,\n reset: throwLibsMissingError,\n isFormReady: false,\n provider: undefined,\n isProviderReady: false,\n };\n }\n return {\n submit,\n reset,\n isFormReady: isPaymentElementReady,\n provider: {\n name: 'stripe',\n },\n isProviderReady: isProviderReady,\n };\n};\n\nexport {\n PaymentElement as __experimental_PaymentElement,\n PaymentElementProvider as __experimental_PaymentElementProvider,\n usePaymentElement as __experimental_usePaymentElement,\n};\n","/**\n * PortalRootManager manages a stack of portal root containers.\n * This allows PortalProvider to work across separate React trees\n * (e.g., when Clerk modals are rendered in a different tree via Components.tsx).\n */\nclass PortalRootManager {\n private stack: Array<() => HTMLElement | null> = [];\n\n /**\n * Push a new portal root getter onto the stack.\n * @param getContainer Function that returns the container element\n */\n push(getContainer: () => HTMLElement | null): void {\n this.stack.push(getContainer);\n }\n\n /**\n * Pop the most recent portal root from the stack.\n */\n pop(): void {\n this.stack.pop();\n }\n\n /**\n * Get the current (topmost) portal root container.\n * @returns The container element or null if no provider is active\n */\n getCurrent(): HTMLElement | null {\n if (this.stack.length === 0) {\n return null;\n }\n const getContainer = this.stack[this.stack.length - 1];\n return getContainer();\n }\n}\n\nexport const portalRootManager = new PortalRootManager();\n","'use client';\n\nimport React, { useEffect, useRef } from 'react';\n\nimport { createContextAndHook } from './hooks/createContextAndHook';\nimport { portalRootManager } from './portal-root-manager';\n\ntype PortalProviderProps = React.PropsWithChildren<{\n /**\n * Function that returns the container element where portals should be rendered.\n * This allows Clerk components to render inside external dialogs/popovers\n * (e.g., Radix Dialog, React Aria Components) instead of document.body.\n */\n getContainer: () => HTMLElement | null;\n}>;\n\nconst [PortalContext, , usePortalContextWithoutGuarantee] = createContextAndHook<{\n getContainer: () => HTMLElement | null;\n}>('PortalProvider');\n\n/**\n * PortalProvider allows you to specify a custom container for all Clerk floating UI elements\n * (popovers, modals, tooltips, etc.) that use portals.\n *\n * This is particularly useful when using Clerk components inside external UI libraries\n * like Radix Dialog or React Aria Components, where portaled elements need to render\n * within the dialog's container to remain interactable.\n *\n * @example\n * ```tsx\n * function Example() {\n * const containerRef = useRef(null);\n * return (\n * <RadixDialog ref={containerRef}>\n * <PortalProvider getContainer={() => containerRef.current}>\n * <UserButton />\n * </PortalProvider>\n * </RadixDialog>\n * );\n * }\n * ```\n */\nexport const PortalProvider = ({ children, getContainer }: PortalProviderProps) => {\n const getContainerRef = useRef(getContainer);\n getContainerRef.current = getContainer;\n\n // Register with the manager for cross-tree access (e.g., modals in Components.tsx)\n useEffect(() => {\n const getContainerWrapper = () => getContainerRef.current();\n portalRootManager.push(getContainerWrapper);\n return () => {\n portalRootManager.pop();\n };\n }, []);\n\n // Provide context for same-tree access (e.g., UserButton popover)\n const contextValue = React.useMemo(() => ({ value: { getContainer } }), [getContainer]);\n\n return <PortalContext.Provider value={contextValue}>{children}</PortalContext.Provider>;\n};\n\n/**\n * Hook to get the current portal root container.\n * First checks React context (for same-tree components),\n * then falls back to PortalRootManager (for cross-tree like modals).\n */\nexport const usePortalRoot = (): (() => HTMLElement | null) => {\n // Try to get from context first (for components in the same React tree)\n const contextValue = usePortalContextWithoutGuarantee();\n\n if (contextValue && 'getContainer' in contextValue && contextValue.getContainer) {\n return contextValue.getContainer;\n }\n\n // Fall back to manager (for components in different React trees, like modals)\n return portalRootManager.getCurrent.bind(portalRootManager);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQA,SAAgB,oBAAoB,YAAqB,UAA2D;AAClH,KAAI,CAAC,WACH,OAAM,OAAO,aAAa,WAAW,IAAI,MAAM,SAAS,mBAAG,IAAI,MAAM,GAAG,SA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AAE,cAAc,EAAE,GAAG,CAAC,aAAa,CAAC;AAEvF,QAAO,4CAAC,cAAc,YAAS,OAAO,gBAAe,SAAkC;;;;;;;AAQzF,MAAa,sBAAkD;CAE7D,MAAM,eAAe,kCAAkC;AAEvD,KAAI,gBAAgB,kBAAkB,gBAAgB,aAAa,aACjE,QAAO,aAAa;AAItB,QAAO,kBAAkB,WAAW,KAAK,kBAAkB"}
1
+ {"version":3,"file":"index.js","names":["React","SWRConfig","React","newObj: Record<string, unknown>","differentKeysObject: Record<string, unknown>","usePagesOrInfinite: UsePagesOrInfiniteSignature","fetchPage: ValueOrSetter<number>","eventMethodCalled","hookParams: GetAPIKeysParams","params","undefinedPaginatedResource","eventMethodCalled","getCurrentOrganizationMembership","eventMethodCalled","React","hookName","useSession: UseSession","eventMethodCalled","hookName","eventMethodCalled","hookName","eventMethodCalled","React","useDeepEqualMemo: UseDeepEqualMemo","deepEqual","isClerkAPIResponseError","reverificationError","isReverificationHint","createDeferredPromise","validateReverificationConfig","ClerkRuntimeError","useReverification: UseReverification","eventMethodCalled","hookName","eventMethodCalled","eventMethodCalled","swr","queryKey","swr","swr","swr","queryKey","React","Elements: FunctionComponent<PropsWithChildren<ElementsProps>>","ctx","keySet: { [key: string]: boolean }","ClientElement: FunctionComponent<PrivateElementProps>","readyCallback: UnknownCallback | undefined","newElement: StripeElement | null","ServerElement: FunctionComponent<PrivateElementProps>","PaymentElement: FunctionComponent<\n PaymentElementProps & {\n fallback?: ReactNode;\n }\n>","stripePublishableKey","externalGatewayId","StripePaymentElement","React"],"sources":["../../../src/react/hooks/createContextAndHook.ts","../../../src/react/providers/SWRConfigCompat.swr.tsx","../../../src/react/contexts.tsx","../../../src/react/stable-keys.ts","../../../src/react/hooks/createCacheKeys.ts","../../../src/react/hooks/usePagesOrInfinite.shared.ts","../../../src/react/hooks/usePreviousValue.ts","../../../src/react/hooks/usePagesOrInfinite.swr.tsx","../../../src/react/hooks/useAPIKeys.swr.tsx","../../../src/react/hooks/useClerk.ts","../../../src/react/hooks/useAttemptToEnableOrganizations.ts","../../../src/react/hooks/useOrganization.tsx","../../../src/react/hooks/useOrganizationList.tsx","../../../src/react/hooks/useSafeLayoutEffect.tsx","../../../src/react/hooks/useSession.ts","../../../src/react/hooks/useSessionList.ts","../../../src/react/hooks/useUser.ts","../../../src/react/hooks/useDeepEqualMemo.ts","../../../src/react/hooks/useReverification.ts","../../../src/react/hooks/useBillingHookEnabled.ts","../../../src/react/hooks/createBillingPaginatedHook.tsx","../../../src/react/hooks/useStatements.tsx","../../../src/react/hooks/usePaymentAttempts.tsx","../../../src/react/hooks/usePaymentMethods.tsx","../../../src/react/hooks/usePlans.tsx","../../../src/react/hooks/useSubscription.shared.ts","../../../src/react/hooks/useSubscription.swr.tsx","../../../src/react/hooks/useCheckout.ts","../../../src/react/hooks/useStatementQuery.shared.ts","../../../src/react/hooks/useStatementQuery.swr.tsx","../../../src/react/hooks/usePlanDetailsQuery.shared.ts","../../../src/react/hooks/usePlanDetailsQuery.swr.tsx","../../../src/react/hooks/usePaymentAttemptQuery.shared.ts","../../../src/react/hooks/usePaymentAttemptQuery.swr.tsx","../../../src/react/stripe-react/utils.ts","../../../src/react/stripe-react/index.tsx","../../../src/react/billing/useInitializePaymentMethod.swr.tsx","../../../src/react/billing/useStripeClerkLibs.swr.tsx","../../../src/react/billing/useStripeLoader.swr.tsx","../../../src/react/billing/payment-element.tsx","../../../src/react/portal-root-manager.ts","../../../src/react/PortalProvider.tsx"],"sourcesContent":["'use client';\nimport React from 'react';\n\n/**\n * Assert that the context value exists, otherwise throw an error.\n *\n * @internal\n */\nexport function assertContextExists(contextVal: unknown, msgOrCtx: string | React.Context<any>): asserts contextVal {\n if (!contextVal) {\n throw typeof msgOrCtx === 'string' ? new Error(msgOrCtx) : new Error(`${msgOrCtx.displayName} not found`);\n }\n}\n\ntype Options = { assertCtxFn?: (v: unknown, msg: string) => void };\ntype ContextOf<T> = React.Context<{ value: T } | undefined>;\ntype UseCtxFn<T> = () => T;\n\n/**\n * Create and return a Context and two hooks that return the context value.\n * The Context type is derived from the type passed in by the user.\n *\n * The first hook returned guarantees that the context exists so the returned value is always `CtxValue`\n * The second hook makes no guarantees, so the returned value can be `CtxValue | undefined`\n *\n * @internal\n */\nexport const createContextAndHook = <CtxVal>(\n displayName: string,\n options?: Options,\n): [ContextOf<CtxVal>, UseCtxFn<CtxVal>, UseCtxFn<CtxVal | Partial<CtxVal>>] => {\n const { assertCtxFn = assertContextExists } = options || {};\n const Ctx = React.createContext<{ value: CtxVal } | undefined>(undefined);\n Ctx.displayName = displayName;\n\n const useCtx = () => {\n const ctx = React.useContext(Ctx);\n assertCtxFn(ctx, `${displayName} not found`);\n return (ctx as any).value as CtxVal;\n };\n\n const useCtxWithoutGuarantee = () => {\n const ctx = React.useContext(Ctx);\n return ctx ? ctx.value : {};\n };\n\n return [Ctx, useCtx, useCtxWithoutGuarantee];\n};\n","import React, { type PropsWithChildren } from 'react';\nimport { SWRConfig } from 'swr';\n\n/**\n * @internal\n */\nexport function SWRConfigCompat({ swrConfig, children }: PropsWithChildren<{ swrConfig?: any }>) {\n // TODO: Replace SWRConfig with the react-query equivalent.\n return <SWRConfig value={swrConfig}>{children}</SWRConfig>;\n}\n","'use client';\n\nimport type { PropsWithChildren } from 'react';\nimport React from 'react';\n\nimport type {\n BillingSubscriptionPlanPeriod,\n ClerkOptions,\n ClientResource,\n ForPayerType,\n LoadedClerk,\n OrganizationResource,\n SignedInSessionResource,\n UserResource,\n} from '../types';\nimport { createContextAndHook } from './hooks/createContextAndHook';\nimport { SWRConfigCompat } from './providers/SWRConfigCompat';\n\nconst [ClerkInstanceContext, useClerkInstanceContext] = createContextAndHook<LoadedClerk>('ClerkInstanceContext');\nconst [UserContext, useUserContext] = createContextAndHook<UserResource | null | undefined>('UserContext');\nconst [ClientContext, useClientContext] = createContextAndHook<ClientResource | null | undefined>('ClientContext');\nconst [SessionContext, useSessionContext] = createContextAndHook<SignedInSessionResource | null | undefined>(\n 'SessionContext',\n);\n\nconst OptionsContext = React.createContext<ClerkOptions>({});\n\n/**\n * @interface\n */\nexport type UseCheckoutOptions = {\n /**\n * Specifies if the checkout is for an Organization.\n *\n * @default 'user'\n */\n for?: ForPayerType;\n /**\n * The billing period for the Plan.\n */\n planPeriod: BillingSubscriptionPlanPeriod;\n /**\n * The ID of the Subscription Plan to check out (e.g. `cplan_xxx`).\n */\n planId: string;\n};\n\nconst [CheckoutContext, useCheckoutContext] = createContextAndHook<UseCheckoutOptions>('CheckoutContext');\n\nconst __experimental_CheckoutProvider = ({ children, ...rest }: PropsWithChildren<UseCheckoutOptions>) => {\n return <CheckoutContext.Provider value={{ value: rest }}>{children}</CheckoutContext.Provider>;\n};\n\n/**\n * @internal\n */\nfunction useOptionsContext(): ClerkOptions {\n const context = React.useContext(OptionsContext);\n if (context === undefined) {\n throw new Error('useOptions must be used within an OptionsContext');\n }\n return context;\n}\n\ntype OrganizationContextProps = {\n organization: OrganizationResource | null | undefined;\n};\nconst [OrganizationContextInternal, useOrganizationContext] = createContextAndHook<{\n organization: OrganizationResource | null | undefined;\n}>('OrganizationContext');\n\nconst OrganizationProvider = ({\n children,\n organization,\n swrConfig,\n}: PropsWithChildren<\n OrganizationContextProps & {\n // Exporting inferred types directly from SWR will result in error while building declarations\n swrConfig?: any;\n }\n>) => {\n return (\n <SWRConfigCompat swrConfig={swrConfig}>\n <OrganizationContextInternal.Provider\n value={{\n value: { organization },\n }}\n >\n {children}\n </OrganizationContextInternal.Provider>\n </SWRConfigCompat>\n );\n};\n\n/**\n * @internal\n */\nfunction useAssertWrappedByClerkProvider(displayNameOrFn: string | (() => void)): void {\n const ctx = React.useContext(ClerkInstanceContext);\n\n if (!ctx) {\n if (typeof displayNameOrFn === 'function') {\n displayNameOrFn();\n return;\n }\n\n throw new Error(\n `${displayNameOrFn} can only be used within the <ClerkProvider /> component.\n\nPossible fixes:\n1. Ensure that the <ClerkProvider /> is correctly wrapping your application where this component is used.\n2. Check for multiple versions of the \\`@clerk/shared\\` package in your project. Use a tool like \\`npm ls @clerk/shared\\` to identify multiple versions, and update your dependencies to only rely on one.\n\nLearn more: https://clerk.com/docs/components/clerk-provider`.trim(),\n );\n }\n}\n\nexport {\n __experimental_CheckoutProvider,\n ClerkInstanceContext,\n ClientContext,\n OptionsContext,\n OrganizationProvider,\n SessionContext,\n useAssertWrappedByClerkProvider,\n useCheckoutContext,\n useClerkInstanceContext,\n useClientContext,\n useOptionsContext,\n useOrganizationContext,\n UserContext,\n useSessionContext,\n useUserContext,\n};\n","// Keys for `useOrganizationList`\nconst USER_MEMBERSHIPS_KEY = 'userMemberships';\nconst USER_INVITATIONS_KEY = 'userInvitations';\nconst USER_SUGGESTIONS_KEY = 'userSuggestions';\n\n// Keys for `useOrganization`\nconst DOMAINS_KEY = 'domains';\nconst MEMBERSHIP_REQUESTS_KEY = 'membershipRequests';\nconst MEMBERSHIPS_KEY = 'memberships';\nconst INVITATIONS_KEY = 'invitations';\n\n// Keys for `useAPIKeys`\nconst API_KEYS_KEY = 'apiKeys';\n\n// Keys for `usePlans`\nconst PLANS_KEY = 'billing-plans';\n\n// Keys for `useSubscription`\nconst SUBSCRIPTION_KEY = 'billing-subscription';\n\n// Keys for `usePaymentMethods`\nconst PAYMENT_METHODS_KEY = 'billing-payment-methods';\n\n// Keys for `usePaymentAttempts`\nconst PAYMENT_ATTEMPTS_KEY = 'billing-payment-attempts';\n\n// Keys for `useStatements`\nconst STATEMENTS_KEY = 'billing-statements';\n\nexport const STABLE_KEYS = {\n // Keys for `useOrganizationList`\n USER_MEMBERSHIPS_KEY,\n USER_INVITATIONS_KEY,\n USER_SUGGESTIONS_KEY,\n\n // Keys for `useOrganization`\n DOMAINS_KEY,\n MEMBERSHIP_REQUESTS_KEY,\n MEMBERSHIPS_KEY,\n INVITATIONS_KEY,\n\n // Keys for billing\n PLANS_KEY,\n SUBSCRIPTION_KEY,\n PAYMENT_METHODS_KEY,\n PAYMENT_ATTEMPTS_KEY,\n STATEMENTS_KEY,\n\n // Keys for `useAPIKeys`\n API_KEYS_KEY,\n} as const;\n\nexport type ResourceCacheStableKey = (typeof STABLE_KEYS)[keyof typeof STABLE_KEYS];\n\n/**\n * Internal stable keys for queries only used by our UI components.\n * These keys are not used by the hooks themselves.\n */\n\nconst PAYMENT_ATTEMPT_KEY = 'billing-payment-attempt';\nconst BILLING_PLANS_KEY = 'billing-plan';\nconst BILLING_STATEMENTS_KEY = 'billing-statement';\nexport const INTERNAL_STABLE_KEYS = {\n PAYMENT_ATTEMPT_KEY,\n BILLING_PLANS_KEY,\n BILLING_STATEMENTS_KEY,\n} as const;\n\nexport type __internal_ResourceCacheStableKey = (typeof INTERNAL_STABLE_KEYS)[keyof typeof INTERNAL_STABLE_KEYS];\n","import type { __internal_ResourceCacheStableKey, ResourceCacheStableKey } from '../stable-keys';\nimport type { QueryKeyWithArgs } from './usePageOrInfinite.types';\n\n/**\n * @internal\n */\nexport function createCacheKeys<\n Params,\n T extends Record<string, unknown> = Record<string, unknown>,\n U extends Record<string, unknown> | undefined = undefined,\n>(params: {\n stablePrefix: ResourceCacheStableKey | __internal_ResourceCacheStableKey;\n authenticated: boolean;\n tracked: T;\n untracked: U extends { args: Params } ? U : never;\n}) {\n return {\n queryKey: [params.stablePrefix, params.authenticated, params.tracked, params.untracked] as const,\n invalidationKey: [params.stablePrefix, params.authenticated, params.tracked] as const,\n stableKey: params.stablePrefix,\n authenticated: params.authenticated,\n };\n}\n\n/**\n * @internal\n */\nexport function toSWRQuery<T extends { queryKey: QueryKeyWithArgs<unknown> }>(keys: T) {\n const { queryKey } = keys;\n return {\n type: queryKey[0],\n ...queryKey[2],\n ...(queryKey[3] as { args: Record<string, unknown> }).args,\n };\n}\n","import { useRef } from 'react';\n\nimport type { PagesOrInfiniteOptions } from '../types';\n\n/**\n * A hook that safely merges user-provided pagination options with default values.\n * It caches initial pagination values (page and size) until component unmount to prevent unwanted rerenders.\n *\n * @internal\n *\n * @example\n * ```typescript\n * // Example 1: With user-provided options\n * const userOptions = { initialPage: 2, pageSize: 20, infinite: true };\n * const defaults = { initialPage: 1, pageSize: 10, infinite: false };\n * useWithSafeValues(userOptions, defaults);\n * // Returns { initialPage: 2, pageSize: 20, infinite: true }\n *\n * // Example 2: With boolean true (use defaults)\n * const params = true;\n * const defaults = { initialPage: 1, pageSize: 10, infinite: false };\n * useWithSafeValues(params, defaults);\n * // Returns { initialPage: 1, pageSize: 10, infinite: false }\n *\n * // Example 3: With undefined options (fallback to defaults)\n * const params = undefined;\n * const defaults = { initialPage: 1, pageSize: 10, infinite: false };\n * useWithSafeValues(params, defaults);\n * // Returns { initialPage: 1, pageSize: 10, infinite: false }\n * ```\n */\nexport const useWithSafeValues = <T extends PagesOrInfiniteOptions>(params: T | true | undefined, defaultValues: T) => {\n const shouldUseDefaults = typeof params === 'boolean' && params;\n\n // Cache initialPage and initialPageSize until unmount\n const initialPageRef = useRef(\n shouldUseDefaults ? defaultValues.initialPage : (params?.initialPage ?? defaultValues.initialPage),\n );\n const pageSizeRef = useRef(shouldUseDefaults ? defaultValues.pageSize : (params?.pageSize ?? defaultValues.pageSize));\n\n const newObj: Record<string, unknown> = {};\n for (const key of Object.keys(defaultValues)) {\n // @ts-ignore - indexing into generic param to preserve unknown keys from defaults/params\n newObj[key] = shouldUseDefaults ? defaultValues[key] : (params?.[key] ?? defaultValues[key]);\n }\n\n return {\n ...newObj,\n initialPage: initialPageRef.current,\n pageSize: pageSizeRef.current,\n } as T;\n};\n\n/**\n * Returns an object containing only the keys from the first object that are not present in the second object.\n * Useful for extracting unique parameters that should be passed to a request while excluding common cache keys.\n *\n * @internal\n *\n * @example\n * ```typescript\n * // Example 1: Basic usage\n * const obj1 = { name: 'John', age: 30, city: 'NY' };\n * const obj2 = { name: 'John', age: 30 };\n * getDifferentKeys(obj1, obj2); // Returns { city: 'NY' }\n *\n * // Example 2: With cache keys\n * const requestParams = { page: 1, limit: 10, userId: '123' };\n * const cacheKeys = { userId: '123' };\n * getDifferentKeys(requestParams, cacheKeys); // Returns { page: 1, limit: 10 }\n * ```\n */\nexport function getDifferentKeys(\n obj1: Record<string, unknown>,\n obj2: Record<string, unknown>,\n): Record<string, unknown> {\n const keysSet = new Set(Object.keys(obj2));\n const differentKeysObject: Record<string, unknown> = {};\n\n for (const key1 of Object.keys(obj1)) {\n if (!keysSet.has(key1)) {\n differentKeysObject[key1] = obj1[key1];\n }\n }\n\n return differentKeysObject;\n}\n","import { useRef } from 'react';\n\ntype Primitive = string | number | boolean | bigint | symbol | null | undefined;\n\n/**\n * A hook that retains the previous value of a primitive type.\n * It uses a ref to prevent causing unnecessary re-renders.\n *\n * @internal\n *\n * @example\n * ```\n * Render 1: value = 'A' → returns null\n * Render 2: value = 'B' → returns 'A'\n * Render 3: value = 'B' → returns 'A'\n * Render 4: value = 'B' → returns 'A'\n * Render 5: value = 'C' → returns 'B'\n * ```\n */\nexport function usePreviousValue<T extends Primitive>(value: T) {\n const currentRef = useRef(value);\n const previousRef = useRef<T | null>(null);\n\n if (currentRef.current !== value) {\n previousRef.current = currentRef.current;\n currentRef.current = value;\n }\n\n return previousRef.current;\n}\n","'use client';\n\nimport { useCallback, useMemo, useRef, useState } from 'react';\n\nimport { useSWR, useSWRInfinite } from '../clerk-swr';\nimport type { CacheSetter, ValueOrSetter } from '../types';\nimport { toSWRQuery } from './createCacheKeys';\nimport type { UsePagesOrInfiniteSignature } from './usePageOrInfinite.types';\nimport { getDifferentKeys, useWithSafeValues } from './usePagesOrInfinite.shared';\nimport { usePreviousValue } from './usePreviousValue';\n\nconst cachingSWROptions = {\n dedupingInterval: 1000 * 60,\n focusThrottleInterval: 1000 * 60 * 2,\n} satisfies Parameters<typeof useSWR>[2];\n\nconst cachingSWRInfiniteOptions = {\n ...cachingSWROptions,\n revalidateFirstPage: false,\n} satisfies Parameters<typeof useSWRInfinite>[2];\n\n/**\n * A flexible pagination hook that supports both traditional pagination and infinite loading.\n * It provides a unified API for handling paginated data fetching, with built-in caching through SWR.\n * The hook can operate in two modes:\n * - Traditional pagination: Fetches one page at a time with page navigation\n * - Infinite loading: Accumulates data as more pages are loaded.\n *\n * Features:\n * - Cache management with SWR\n * - Loading and error states\n * - Page navigation helpers\n * - Data revalidation and updates\n * - Support for keeping previous data while loading.\n *\n * @internal\n */\nexport const usePagesOrInfinite: UsePagesOrInfiniteSignature = params => {\n const { fetcher, config, keys } = params;\n const [paginatedPage, setPaginatedPage] = useState(config.initialPage ?? 1);\n\n // Cache initialPage and initialPageSize until unmount\n const initialPageRef = useRef(config.initialPage ?? 1);\n const pageSizeRef = useRef(config.pageSize ?? 10);\n\n const enabled = config.enabled ?? true;\n const cacheMode = config.__experimental_mode === 'cache';\n const triggerInfinite = config.infinite ?? false;\n const keepPreviousData = config.keepPreviousData ?? false;\n const isSignedIn = config.isSignedIn;\n\n const pagesCacheKey = {\n ...toSWRQuery(keys),\n initialPage: paginatedPage,\n pageSize: pageSizeRef.current,\n };\n\n const previousIsSignedIn = usePreviousValue(isSignedIn);\n\n // cacheMode being `true` indicates that the cache key is defined, but the fetcher is not.\n // This allows to ready the cache instead of firing a request.\n const shouldFetch = !triggerInfinite && enabled && (!cacheMode ? !!fetcher : true);\n\n // Attention:\n //\n // This complex logic is necessary to ensure that the cached data is not used when the user is signed out.\n // `useSWR` with `key` set to `null` and `keepPreviousData` set to `true` will return the previous cached data until the hook unmounts.\n // So for hooks that render authenticated data, we need to ensure that the cached data is not used when the user is signed out.\n //\n // 1. Fetcher should not fire if user is signed out on mount. (fetcher does not run, loading states are not triggered)\n // 2. If user was signed in and then signed out, cached data should become null. (fetcher runs and returns null, loading states are triggered)\n //\n // We achieve (2) by setting the key to the cache key when the user transitions to signed out and forcing the fetcher to return null.\n const swrKey =\n typeof isSignedIn === 'boolean'\n ? previousIsSignedIn === true && isSignedIn === false\n ? pagesCacheKey\n : isSignedIn\n ? shouldFetch\n ? pagesCacheKey\n : null\n : null\n : shouldFetch\n ? pagesCacheKey\n : null;\n\n const swrFetcher =\n !cacheMode && !!fetcher\n ? (cacheKeyParams: Record<string, unknown>) => {\n if (isSignedIn === false || shouldFetch === false) {\n return null;\n }\n const requestParams = getDifferentKeys(cacheKeyParams, { type: keys.queryKey[0], ...keys.queryKey[2] });\n // @ts-ignore - fetcher expects Params subset; narrowing at call-site\n return fetcher(requestParams);\n }\n : null;\n\n const {\n data: swrData,\n isValidating: swrIsValidating,\n isLoading: swrIsLoading,\n error: swrError,\n mutate: swrMutate,\n } = useSWR(swrKey, swrFetcher, { keepPreviousData, ...cachingSWROptions });\n\n // Attention:\n //\n // Cache behavior for infinite loading when signing out:\n //\n // Unlike `useSWR` above (which requires complex transition handling), `useSWRInfinite` has simpler sign-out semantics:\n // 1. When user is signed out on mount, the key getter returns `null`, preventing any fetches.\n // 2. When user transitions from signed in to signed out, the key getter returns `null` for all page indices.\n // 3. When `useSWRInfinite`'s key getter returns `null`, SWR will not fetch data and considers that page invalid.\n // 4. Unlike paginated mode, `useSWRInfinite` does not support `keepPreviousData`, so there's no previous data retention.\n //\n // This simpler behavior works because:\n // - `useSWRInfinite` manages multiple pages internally, each with its own cache key\n // - When the key getter returns `null`, all page fetches are prevented and pages become invalid\n // - Without `keepPreviousData`, the hook will naturally reflect the empty/invalid state\n //\n // Result: No special transition logic needed - just return `null` from key getter when `isSignedIn === false`.\n const {\n data: swrInfiniteData,\n isLoading: swrInfiniteIsLoading,\n isValidating: swrInfiniteIsValidating,\n error: swrInfiniteError,\n size,\n setSize,\n mutate: swrInfiniteMutate,\n } = useSWRInfinite(\n pageIndex => {\n if (!triggerInfinite || !enabled || isSignedIn === false) {\n return null;\n }\n\n return {\n ...toSWRQuery(keys),\n initialPage: initialPageRef.current + pageIndex,\n pageSize: pageSizeRef.current,\n };\n },\n cacheKeyParams => {\n // @ts-ignore - fetcher expects Params subset; narrowing at call-site\n const requestParams = getDifferentKeys(cacheKeyParams, { type: keys.queryKey[0], ...keys.queryKey[2] });\n // @ts-ignore - fetcher expects Params subset; narrowing at call-site\n return fetcher?.(requestParams);\n },\n cachingSWRInfiniteOptions,\n );\n\n const page = useMemo(() => {\n if (triggerInfinite) {\n return size;\n }\n return paginatedPage;\n }, [triggerInfinite, size, paginatedPage]);\n\n const fetchPage: ValueOrSetter<number> = useCallback(\n numberOrgFn => {\n if (triggerInfinite) {\n void setSize(numberOrgFn);\n return;\n }\n return setPaginatedPage(numberOrgFn);\n },\n [setSize, triggerInfinite],\n );\n\n const data = useMemo(() => {\n if (triggerInfinite) {\n return swrInfiniteData?.map(a => a?.data).flat() ?? [];\n }\n return swrData?.data ?? [];\n }, [triggerInfinite, swrData, swrInfiniteData]);\n\n const count = useMemo(() => {\n if (triggerInfinite) {\n return swrInfiniteData?.[swrInfiniteData?.length - 1]?.total_count || 0;\n }\n return swrData?.total_count ?? 0;\n }, [triggerInfinite, swrData, swrInfiniteData]);\n\n const isLoading = triggerInfinite ? swrInfiniteIsLoading : swrIsLoading;\n const isFetching = triggerInfinite ? swrInfiniteIsValidating : swrIsValidating;\n const error = (triggerInfinite ? swrInfiniteError : swrError) ?? null;\n const isError = !!error;\n\n const fetchNext = useCallback(() => {\n fetchPage(n => Math.max(0, n + 1));\n }, [fetchPage]);\n\n const fetchPrevious = useCallback(() => {\n fetchPage(n => Math.max(0, n - 1));\n }, [fetchPage]);\n\n const offsetCount = (initialPageRef.current - 1) * pageSizeRef.current;\n\n const pageCount = Math.ceil((count - offsetCount) / pageSizeRef.current);\n const hasNextPage = count - offsetCount * pageSizeRef.current > page * pageSizeRef.current;\n const hasPreviousPage = (page - 1) * pageSizeRef.current > offsetCount * pageSizeRef.current;\n\n const setData: CacheSetter = triggerInfinite\n ? value =>\n swrInfiniteMutate(value, {\n revalidate: false,\n })\n : value =>\n swrMutate(value, {\n revalidate: false,\n });\n\n const revalidate = triggerInfinite ? () => swrInfiniteMutate() : () => swrMutate();\n\n return {\n data,\n count,\n error,\n isLoading,\n isFetching,\n isError,\n page,\n pageCount,\n fetchPage,\n fetchNext,\n fetchPrevious,\n hasNextPage,\n hasPreviousPage,\n // Let the hook return type define this type\n revalidate: revalidate as any,\n // Let the hook return type define this type\n setData: setData as any,\n };\n};\n\nexport { useWithSafeValues };\n","import { useCallback } from 'react';\nimport { useSWRConfig } from 'swr';\n\nimport { eventMethodCalled } from '../../telemetry/events/method-called';\nimport type { APIKeyResource, GetAPIKeysParams } from '../../types';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext } from '../contexts';\nimport { STABLE_KEYS } from '../stable-keys';\nimport type { PaginatedHookConfig, PaginatedResources } from '../types';\nimport { createCacheKeys } from './createCacheKeys';\nimport { usePagesOrInfinite, useWithSafeValues } from './usePagesOrInfinite';\n\n/**\n * @internal\n */\nexport type UseAPIKeysParams = PaginatedHookConfig<\n GetAPIKeysParams & {\n /**\n * If `true`, a request will be triggered when the hook is mounted.\n *\n * @default true\n */\n enabled?: boolean;\n }\n>;\n\n/**\n * @internal\n */\nexport type UseAPIKeysReturn<T extends UseAPIKeysParams> = PaginatedResources<\n APIKeyResource,\n T extends { infinite: true } ? true : false\n>;\n\n/**\n * @internal\n *\n * The `useAPIKeys()` hook provides access to paginated API keys for the current user or organization.\n *\n * @example\n * ### Basic usage with default pagination\n *\n * ```tsx\n * const { data, isLoading, page, pageCount, fetchNext, fetchPrevious } = useAPIKeys({\n * subject: 'user_123',\n * pageSize: 10,\n * initialPage: 1,\n * });\n * ```\n *\n * @example\n * ### With search query\n *\n * ```tsx\n * const [searchValue, setSearchValue] = useState('');\n * const debouncedSearch = useDebounce(searchValue, 500);\n *\n * const { data, isLoading } = useAPIKeys({\n * subject: 'user_123',\n * query: debouncedSearch.trim(),\n * pageSize: 10,\n * });\n * ```\n *\n * @example\n * ### Infinite scroll\n *\n * ```tsx\n * const { data, isLoading, fetchNext, hasNextPage } = useAPIKeys({\n * subject: 'user_123',\n * infinite: true,\n * });\n * ```\n */\nexport function useAPIKeys<T extends UseAPIKeysParams>(params?: T): UseAPIKeysReturn<T> {\n useAssertWrappedByClerkProvider('useAPIKeys');\n\n const safeValues = useWithSafeValues(params, {\n initialPage: 1,\n pageSize: 10,\n keepPreviousData: false,\n infinite: false,\n subject: '',\n query: '',\n enabled: true,\n } as UseAPIKeysParams);\n\n const clerk = useClerkInstanceContext();\n\n clerk.telemetry?.record(eventMethodCalled('useAPIKeys'));\n\n const hookParams: GetAPIKeysParams = {\n initialPage: safeValues.initialPage,\n pageSize: safeValues.pageSize,\n ...(safeValues.subject ? { subject: safeValues.subject } : {}),\n ...(safeValues.query ? { query: safeValues.query } : {}),\n };\n\n const isEnabled = (safeValues.enabled ?? true) && clerk.loaded;\n\n const result = usePagesOrInfinite({\n fetcher: clerk.apiKeys?.getAll\n ? (params: GetAPIKeysParams) => clerk.apiKeys.getAll({ ...params, subject: safeValues.subject })\n : undefined,\n config: {\n keepPreviousData: safeValues.keepPreviousData,\n infinite: safeValues.infinite,\n enabled: isEnabled,\n isSignedIn: Boolean(clerk.user),\n initialPage: safeValues.initialPage,\n pageSize: safeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: STABLE_KEYS.API_KEYS_KEY,\n authenticated: Boolean(clerk.user),\n tracked: {\n subject: safeValues.subject,\n },\n untracked: {\n args: hookParams,\n },\n }),\n }) as UseAPIKeysReturn<T>;\n\n const { mutate } = useSWRConfig();\n\n // Invalidate all cache entries for this user or organization\n const invalidateAll = useCallback(() => {\n return mutate(key => {\n if (!key || typeof key !== 'object') {\n return false;\n }\n // Match all apiKeys cache entries for this user or organization, regardless of page, pageSize, or query\n return 'type' in key && key.type === 'apiKeys' && 'subject' in key && key.subject === safeValues.subject;\n });\n }, [mutate, safeValues.subject]);\n\n return {\n ...result,\n revalidate: invalidateAll as any,\n };\n}\n","import type { LoadedClerk } from '../../types';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext } from '../contexts';\n\n/**\n * > [!WARNING]\n * > This hook should only be used for advanced use cases, such as building a completely custom OAuth flow or as an escape hatch to access to the `Clerk` object.\n *\n * The `useClerk()` hook provides access to the [`Clerk`](https://clerk.com/docs/reference/javascript/clerk) object, allowing you to build alternatives to any Clerk Component.\n *\n * @function\n *\n * @returns The `useClerk()` hook returns the `Clerk` object, which includes all the methods and properties listed in the [`Clerk` reference](https://clerk.com/docs/reference/javascript/clerk).\n *\n * @example\n *\n * The following example uses the `useClerk()` hook to access the `clerk` object. The `clerk` object is used to call the [`openSignIn()`](https://clerk.com/docs/reference/javascript/clerk#sign-in) method to open the sign-in modal.\n *\n * <Tabs items='React,Next.js'>\n * <Tab>\n *\n * ```tsx {{ filename: 'src/Home.tsx' }}\n * import { useClerk } from '@clerk/react'\n *\n * export default function Home() {\n * const clerk = useClerk()\n *\n * return <button onClick={() => clerk.openSignIn({})}>Sign in</button>\n * }\n * ```\n *\n * </Tab>\n * <Tab>\n *\n * {@include ../../../docs/use-clerk.md#nextjs-01}\n *\n * </Tab>\n * </Tabs>\n */\nexport const useClerk = (): LoadedClerk => {\n useAssertWrappedByClerkProvider('useClerk');\n return useClerkInstanceContext();\n};\n","import { useEffect, useRef } from 'react';\n\nimport { useClerk } from './useClerk';\n\n/**\n * Attempts to enable the organizations environment setting for a given caller\n *\n * @internal\n */\nexport function useAttemptToEnableOrganizations(caller: 'useOrganization' | 'useOrganizationList') {\n const clerk = useClerk();\n const hasAttempted = useRef(false);\n\n useEffect(() => {\n // Guard to not run this effect twice on Clerk resource update\n if (hasAttempted.current) {\n return;\n }\n\n hasAttempted.current = true;\n // Optional chaining is important for `@clerk/clerk-react` usage with older clerk-js versions that don't have the method\n clerk.__internal_attemptToEnableEnvironmentSetting?.({\n for: 'organizations',\n caller,\n });\n }, [clerk, caller]);\n}\n","import { getCurrentOrganizationMembership } from '../../organization';\nimport { eventMethodCalled } from '../../telemetry/events/method-called';\nimport type {\n GetDomainsParams,\n GetInvitationsParams,\n GetMembershipRequestParams,\n GetMembersParams,\n OrganizationDomainResource,\n OrganizationInvitationResource,\n OrganizationMembershipRequestResource,\n OrganizationMembershipResource,\n OrganizationResource,\n} from '../../types';\nimport {\n useAssertWrappedByClerkProvider,\n useClerkInstanceContext,\n useOrganizationContext,\n useSessionContext,\n} from '../contexts';\nimport { STABLE_KEYS } from '../stable-keys';\nimport type { PaginatedHookConfig, PaginatedResources, PaginatedResourcesWithDefault } from '../types';\nimport { createCacheKeys } from './createCacheKeys';\nimport { useAttemptToEnableOrganizations } from './useAttemptToEnableOrganizations';\nimport { usePagesOrInfinite, useWithSafeValues } from './usePagesOrInfinite';\n\n/**\n * @interface\n */\nexport type UseOrganizationParams = {\n /**\n * If set to `true`, all default properties will be used.<br />\n * Otherwise, accepts an object with the following optional properties:\n * <ul>\n * <li>`enrollmentMode`: A string that filters the domains by the provided [enrollment mode](https://clerk.com/docs/guides/organizations/add-members/verified-domains#enable-verified-domains).</li>\n * <li>Any of the properties described in [Shared properties](#shared-properties).</li>\n * </ul>\n */\n domains?: true | PaginatedHookConfig<GetDomainsParams>;\n /**\n * If set to `true`, all default properties will be used.<br />\n * Otherwise, accepts an object with the following optional properties:\n * <ul>\n * <li>`status`: A string that filters the membership requests by the provided status.</li>\n * <li>Any of the properties described in [Shared properties](#shared-properties).</li>\n * </ul>\n */\n membershipRequests?: true | PaginatedHookConfig<GetMembershipRequestParams>;\n /**\n * If set to `true`, all default properties will be used.<br />\n * Otherwise, accepts an object with the following optional properties:\n * <ul>\n * <li>`role`: An array of [`OrganizationCustomRoleKey`](https://clerk.com/docs/reference/javascript/types/organization-custom-role-key).</li>\n * <li>`query`: A string that filters the memberships by the provided string.</li>\n * <li>Any of the properties described in [Shared properties](#shared-properties).</li>\n * </ul>\n */\n memberships?: true | PaginatedHookConfig<GetMembersParams>;\n /**\n * If set to `true`, all default properties will be used.<br />\n * Otherwise, accepts an object with the following optional properties:\n * <ul>\n * <li>`status`: A string that filters the invitations by the provided status.</li>\n * <li>Any of the properties described in [Shared properties](#shared-properties).</li>\n * </ul>\n */\n invitations?: true | PaginatedHookConfig<GetInvitationsParams>;\n};\n\n/**\n * @interface\n */\nexport type UseOrganizationReturn<T extends UseOrganizationParams> =\n | {\n /**\n * A boolean that indicates whether Clerk has completed initialization. Initially `false`, becomes `true` once Clerk loads.\n */\n isLoaded: false;\n /**\n * The currently Active Organization.\n */\n organization: undefined;\n /**\n * The current Organization membership.\n */\n membership: undefined;\n /**\n * Includes a paginated list of the Organization's domains.\n */\n domains: PaginatedResourcesWithDefault<OrganizationDomainResource>;\n /**\n * Includes a paginated list of the Organization's membership requests.\n */\n membershipRequests: PaginatedResourcesWithDefault<OrganizationMembershipRequestResource>;\n /**\n * Includes a paginated list of the Organization's memberships.\n */\n memberships: PaginatedResourcesWithDefault<OrganizationMembershipResource>;\n /**\n * Includes a paginated list of the Organization's invitations.\n */\n invitations: PaginatedResourcesWithDefault<OrganizationInvitationResource>;\n }\n | {\n isLoaded: true;\n organization: OrganizationResource;\n membership: undefined;\n domains: PaginatedResourcesWithDefault<OrganizationDomainResource>;\n membershipRequests: PaginatedResourcesWithDefault<OrganizationMembershipRequestResource>;\n memberships: PaginatedResourcesWithDefault<OrganizationMembershipResource>;\n invitations: PaginatedResourcesWithDefault<OrganizationInvitationResource>;\n }\n | {\n isLoaded: boolean;\n organization: OrganizationResource | null;\n membership: OrganizationMembershipResource | null | undefined;\n domains: PaginatedResources<\n OrganizationDomainResource,\n T['membershipRequests'] extends { infinite: true } ? true : false\n > | null;\n membershipRequests: PaginatedResources<\n OrganizationMembershipRequestResource,\n T['membershipRequests'] extends { infinite: true } ? true : false\n > | null;\n memberships: PaginatedResources<\n OrganizationMembershipResource,\n T['memberships'] extends { infinite: true } ? true : false\n > | null;\n invitations: PaginatedResources<\n OrganizationInvitationResource,\n T['invitations'] extends { infinite: true } ? true : false\n > | null;\n };\n\nconst undefinedPaginatedResource = {\n data: undefined,\n count: undefined,\n error: undefined,\n isLoading: false,\n isFetching: false,\n isError: false,\n page: undefined,\n pageCount: undefined,\n fetchPage: undefined,\n fetchNext: undefined,\n fetchPrevious: undefined,\n hasNextPage: false,\n hasPreviousPage: false,\n revalidate: undefined,\n setData: undefined,\n} as const;\n\n/**\n * The `useOrganization()` hook retrieves attributes of the currently Active Organization.\n *\n * @example\n * ### Expand and paginate attributes\n *\n * To keep network usage to a minimum, developers are required to opt-in by specifying which resource they need to fetch and paginate through. By default, the `memberships`, `invitations`, `membershipRequests`, and `domains` attributes are not populated. You must pass `true` or an object with the desired properties to fetch and paginate the data.\n *\n * ```tsx\n * // invitations.data will never be populated.\n * const { invitations } = useOrganization()\n *\n * // Use default values to fetch invitations, such as initialPage = 1 and pageSize = 10\n * const { invitations } = useOrganization({\n * invitations: true,\n * })\n *\n * // Pass your own values to fetch invitations\n * const { invitations } = useOrganization({\n * invitations: {\n * pageSize: 20,\n * initialPage: 2, // skips the first page\n * },\n * })\n *\n * // Aggregate pages in order to render an infinite list\n * const { invitations } = useOrganization({\n * invitations: {\n * infinite: true,\n * },\n * })\n * ```\n *\n * @example\n * ### Infinite pagination\n *\n * The following example demonstrates how to use the `infinite` property to fetch and append new data to the existing list. The `memberships` attribute will be populated with the first page of the Organization's memberships. When the \"Load more\" button is clicked, the `fetchNext` helper function will be called to append the next page of memberships to the list.\n *\n * ```tsx\n * import { useOrganization } from '@clerk/react'\n *\n * export default function MemberList() {\n * const { memberships } = useOrganization({\n * memberships: {\n * infinite: true, // Append new data to the existing list\n * keepPreviousData: true, // Persist the cached data until the new data has been fetched\n * },\n * })\n *\n * if (!memberships) {\n * // Handle loading state\n * return null\n * }\n *\n * return (\n * <div>\n * <h2>Organization members</h2>\n * <ul>\n * {memberships.data?.map((membership) => (\n * <li key={membership.id}>\n * {membership.publicUserData.firstName} {membership.publicUserData.lastName} <\n * {membership.publicUserData.identifier}> :: {membership.role}\n * </li>\n * ))}\n * </ul>\n *\n * <button\n * disabled={!memberships.hasNextPage} // Disable the button if there are no more available pages to be fetched\n * onClick={memberships.fetchNext}\n * >\n * Load more\n * </button>\n * </div>\n * )\n * }\n * ```\n *\n * @example\n * ### Simple pagination\n *\n * The following example demonstrates how to use the `fetchPrevious` and `fetchNext` helper functions to paginate through the data. The `memberships` attribute will be populated with the first page of the Organization's memberships. When the \"Previous page\" or \"Next page\" button is clicked, the `fetchPrevious` or `fetchNext` helper function will be called to fetch the previous or next page of memberships.\n *\n * Notice the difference between this example's pagination and the infinite pagination example above.\n *\n * ```tsx\n * import { useOrganization } from '@clerk/react'\n *\n * export default function MemberList() {\n * const { memberships } = useOrganization({\n * memberships: {\n * keepPreviousData: true, // Persist the cached data until the new data has been fetched\n * },\n * })\n *\n * if (!memberships) {\n * // Handle loading state\n * return null\n * }\n *\n * return (\n * <div>\n * <h2>Organization members</h2>\n * <ul>\n * {memberships.data?.map((membership) => (\n * <li key={membership.id}>\n * {membership.publicUserData.firstName} {membership.publicUserData.lastName} <\n * {membership.publicUserData.identifier}> :: {membership.role}\n * </li>\n * ))}\n * </ul>\n *\n * <button disabled={!memberships.hasPreviousPage} onClick={memberships.fetchPrevious}>\n * Previous page\n * </button>\n *\n * <button disabled={!memberships.hasNextPage} onClick={memberships.fetchNext}>\n * Next page\n * </button>\n * </div>\n * )\n * }\n * ```\n */\nexport function useOrganization<T extends UseOrganizationParams>(params?: T): UseOrganizationReturn<T> {\n const {\n domains: domainListParams,\n membershipRequests: membershipRequestsListParams,\n memberships: membersListParams,\n invitations: invitationsListParams,\n } = params || {};\n\n useAssertWrappedByClerkProvider('useOrganization');\n useAttemptToEnableOrganizations('useOrganization');\n\n const { organization } = useOrganizationContext();\n const session = useSessionContext();\n\n const domainSafeValues = useWithSafeValues(domainListParams, {\n initialPage: 1,\n pageSize: 10,\n keepPreviousData: false,\n infinite: false,\n enrollmentMode: undefined,\n });\n\n const membershipRequestSafeValues = useWithSafeValues(membershipRequestsListParams, {\n initialPage: 1,\n pageSize: 10,\n status: 'pending',\n keepPreviousData: false,\n infinite: false,\n });\n\n const membersSafeValues = useWithSafeValues(membersListParams, {\n initialPage: 1,\n pageSize: 10,\n role: undefined,\n keepPreviousData: false,\n infinite: false,\n query: undefined,\n });\n\n const invitationsSafeValues = useWithSafeValues(invitationsListParams, {\n initialPage: 1,\n pageSize: 10,\n status: ['pending'],\n keepPreviousData: false,\n infinite: false,\n });\n\n const clerk = useClerkInstanceContext();\n\n clerk.telemetry?.record(eventMethodCalled('useOrganization'));\n\n const domainParams =\n typeof domainListParams === 'undefined'\n ? undefined\n : {\n initialPage: domainSafeValues.initialPage,\n pageSize: domainSafeValues.pageSize,\n enrollmentMode: domainSafeValues.enrollmentMode,\n };\n\n const membershipRequestParams =\n typeof membershipRequestsListParams === 'undefined'\n ? undefined\n : {\n initialPage: membershipRequestSafeValues.initialPage,\n pageSize: membershipRequestSafeValues.pageSize,\n status: membershipRequestSafeValues.status,\n };\n\n const membersParams =\n typeof membersListParams === 'undefined'\n ? undefined\n : {\n initialPage: membersSafeValues.initialPage,\n pageSize: membersSafeValues.pageSize,\n role: membersSafeValues.role,\n query: membersSafeValues.query,\n };\n\n const invitationsParams =\n typeof invitationsListParams === 'undefined'\n ? undefined\n : {\n initialPage: invitationsSafeValues.initialPage,\n pageSize: invitationsSafeValues.pageSize,\n status: invitationsSafeValues.status,\n };\n\n const domains = usePagesOrInfinite({\n fetcher: organization?.getDomains,\n config: {\n keepPreviousData: domainSafeValues.keepPreviousData,\n infinite: domainSafeValues.infinite,\n enabled: !!domainParams,\n isSignedIn: Boolean(organization),\n initialPage: domainSafeValues.initialPage,\n pageSize: domainSafeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: STABLE_KEYS.DOMAINS_KEY,\n authenticated: Boolean(organization),\n tracked: {\n organizationId: organization?.id,\n },\n untracked: {\n args: domainParams,\n },\n }),\n });\n\n const membershipRequests = usePagesOrInfinite({\n fetcher: organization?.getMembershipRequests,\n config: {\n keepPreviousData: membershipRequestSafeValues.keepPreviousData,\n infinite: membershipRequestSafeValues.infinite,\n enabled: !!membershipRequestParams,\n isSignedIn: Boolean(organization),\n initialPage: membershipRequestSafeValues.initialPage,\n pageSize: membershipRequestSafeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: STABLE_KEYS.MEMBERSHIP_REQUESTS_KEY,\n authenticated: Boolean(organization),\n tracked: {\n organizationId: organization?.id,\n },\n untracked: {\n args: membershipRequestParams,\n },\n }),\n });\n\n const memberships = usePagesOrInfinite({\n fetcher: organization?.getMemberships,\n config: {\n keepPreviousData: membersSafeValues.keepPreviousData,\n infinite: membersSafeValues.infinite,\n enabled: !!membersParams,\n isSignedIn: Boolean(organization),\n initialPage: membersSafeValues.initialPage,\n pageSize: membersSafeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: STABLE_KEYS.MEMBERSHIPS_KEY,\n authenticated: Boolean(organization),\n tracked: {\n organizationId: organization?.id,\n },\n untracked: {\n args: membersParams,\n },\n }),\n });\n\n const invitations = usePagesOrInfinite({\n fetcher: organization?.getInvitations,\n config: {\n keepPreviousData: invitationsSafeValues.keepPreviousData,\n infinite: invitationsSafeValues.infinite,\n enabled: !!invitationsParams,\n isSignedIn: Boolean(organization),\n initialPage: invitationsSafeValues.initialPage,\n pageSize: invitationsSafeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: STABLE_KEYS.INVITATIONS_KEY,\n authenticated: Boolean(organization),\n tracked: {\n organizationId: organization?.id,\n },\n untracked: {\n args: invitationsParams,\n },\n }),\n });\n\n if (organization === undefined) {\n return {\n isLoaded: false,\n organization: undefined,\n membership: undefined,\n domains: undefinedPaginatedResource,\n membershipRequests: undefinedPaginatedResource,\n memberships: undefinedPaginatedResource,\n invitations: undefinedPaginatedResource,\n };\n }\n\n if (organization === null) {\n return {\n isLoaded: true,\n organization: null,\n membership: null,\n domains: null,\n membershipRequests: null,\n memberships: null,\n invitations: null,\n };\n }\n\n /** In SSR context we include only the organization object when loadOrg is set to true. */\n if (!clerk.loaded && organization) {\n return {\n isLoaded: true,\n organization,\n membership: undefined,\n domains: undefinedPaginatedResource,\n membershipRequests: undefinedPaginatedResource,\n memberships: undefinedPaginatedResource,\n invitations: undefinedPaginatedResource,\n };\n }\n\n return {\n isLoaded: clerk.loaded,\n organization,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n membership: getCurrentOrganizationMembership(session!.user.organizationMemberships, organization.id), // your membership in the current org\n domains,\n membershipRequests,\n memberships,\n invitations,\n };\n}\n","import { eventMethodCalled } from '../../telemetry/events/method-called';\nimport type {\n CreateOrganizationParams,\n GetUserOrganizationInvitationsParams,\n GetUserOrganizationMembershipParams,\n GetUserOrganizationSuggestionsParams,\n OrganizationMembershipResource,\n OrganizationResource,\n OrganizationSuggestionResource,\n SetActive,\n UserOrganizationInvitationResource,\n} from '../../types';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext, useUserContext } from '../contexts';\nimport { STABLE_KEYS } from '../stable-keys';\nimport type { PaginatedHookConfig, PaginatedResources, PaginatedResourcesWithDefault } from '../types';\nimport { createCacheKeys } from './createCacheKeys';\nimport { useAttemptToEnableOrganizations } from './useAttemptToEnableOrganizations';\nimport { usePagesOrInfinite, useWithSafeValues } from './usePagesOrInfinite';\n\n/**\n * @interface\n */\nexport type UseOrganizationListParams = {\n /**\n * If set to `true`, all default properties will be used.<br />\n * Otherwise, accepts an object with the following optional properties:\n *\n * <ul>\n * <li>Any of the properties described in [Shared properties](#shared-properties).</li>\n * </ul>\n */\n userMemberships?: true | PaginatedHookConfig<GetUserOrganizationMembershipParams>;\n /**\n * If set to `true`, all default properties will be used.<br />\n * Otherwise, accepts an object with the following optional properties:\n *\n * <ul>\n * <li>`status`: A string that filters the invitations by the provided status.</li>\n * <li>Any of the properties described in [Shared properties](#shared-properties).</li>\n * </ul>\n */\n userInvitations?: true | PaginatedHookConfig<GetUserOrganizationInvitationsParams>;\n /**\n * If set to `true`, all default properties will be used.<br />\n * Otherwise, accepts an object with the following optional properties:\n *\n * <ul>\n * <li>`status`: A string that filters the suggestions by the provided status.</li>\n * <li>Any of the properties described in [Shared properties](#shared-properties).</li>\n * </ul>\n */\n userSuggestions?: true | PaginatedHookConfig<GetUserOrganizationSuggestionsParams>;\n};\n\nconst undefinedPaginatedResource = {\n data: undefined,\n count: undefined,\n error: undefined,\n isLoading: false,\n isFetching: false,\n isError: false,\n page: undefined,\n pageCount: undefined,\n fetchPage: undefined,\n fetchNext: undefined,\n fetchPrevious: undefined,\n hasNextPage: false,\n hasPreviousPage: false,\n revalidate: undefined,\n setData: undefined,\n} as const;\n\n/**\n * @interface\n */\nexport type UseOrganizationListReturn<T extends UseOrganizationListParams> =\n | {\n /**\n * A boolean that indicates whether Clerk has completed initialization and there is an authenticated user. Initially `false`, becomes `true` once Clerk loads with a user.\n */\n isLoaded: false;\n /**\n * A function that returns a `Promise` which resolves to the newly created `Organization`.\n */\n createOrganization: undefined;\n /**\n * A function that sets the active session and/or Organization.\n */\n setActive: undefined;\n /**\n * Returns `PaginatedResources` which includes a list of the user's Organization memberships.\n */\n userMemberships: PaginatedResourcesWithDefault<OrganizationMembershipResource>;\n /**\n * Returns `PaginatedResources` which includes a list of the user's Organization invitations.\n */\n userInvitations: PaginatedResourcesWithDefault<UserOrganizationInvitationResource>;\n /**\n * Returns `PaginatedResources` which includes a list of suggestions for Organizations that the user can join.\n */\n userSuggestions: PaginatedResourcesWithDefault<OrganizationSuggestionResource>;\n }\n | {\n isLoaded: boolean;\n createOrganization: (CreateOrganizationParams: CreateOrganizationParams) => Promise<OrganizationResource>;\n setActive: SetActive;\n userMemberships: PaginatedResources<\n OrganizationMembershipResource,\n T['userMemberships'] extends { infinite: true } ? true : false\n >;\n userInvitations: PaginatedResources<\n UserOrganizationInvitationResource,\n T['userInvitations'] extends { infinite: true } ? true : false\n >;\n userSuggestions: PaginatedResources<\n OrganizationSuggestionResource,\n T['userSuggestions'] extends { infinite: true } ? true : false\n >;\n };\n\n/**\n * The `useOrganizationList()` hook provides access to the current user's organization memberships, invitations, and suggestions. It also includes methods for creating new organizations and managing the active organization.\n *\n * @example\n * ### Expanding and paginating attributes\n *\n * To keep network usage to a minimum, developers are required to opt-in by specifying which resource they need to fetch and paginate through. So by default, the `userMemberships`, `userInvitations`, and `userSuggestions` attributes are not populated. You must pass true or an object with the desired properties to fetch and paginate the data.\n *\n * ```tsx\n * // userMemberships.data will never be populated\n * const { userMemberships } = useOrganizationList()\n *\n * // Use default values to fetch userMemberships, such as initialPage = 1 and pageSize = 10\n * const { userMemberships } = useOrganizationList({\n * userMemberships: true,\n * })\n *\n * // Pass your own values to fetch userMemberships\n * const { userMemberships } = useOrganizationList({\n * userMemberships: {\n * pageSize: 20,\n * initialPage: 2, // skips the first page\n * },\n * })\n *\n * // Aggregate pages in order to render an infinite list\n * const { userMemberships } = useOrganizationList({\n * userMemberships: {\n * infinite: true,\n * },\n * })\n * ```\n *\n * @example\n * ### Infinite pagination\n *\n * The following example demonstrates how to use the `infinite` property to fetch and append new data to the existing list. The `userMemberships` attribute will be populated with the first page of the user's Organization memberships. When the \"Load more\" button is clicked, the `fetchNext` helper function will be called to append the next page of memberships to the list.\n *\n * ```tsx {{ filename: 'src/components/JoinedOrganizations.tsx' }}\n * import { useOrganizationList } from '@clerk/react'\n * import React from 'react'\n *\n * const JoinedOrganizations = () => {\n * const { isLoaded, setActive, userMemberships } = useOrganizationList({\n * userMemberships: {\n * infinite: true,\n * },\n * })\n *\n * if (!isLoaded) {\n * return <>Loading</>\n * }\n *\n * return (\n * <>\n * <ul>\n * {userMemberships.data?.map((mem) => (\n * <li key={mem.id}>\n * <span>{mem.organization.name}</span>\n * <button onClick={() => setActive({ organization: mem.organization.id })}>Select</button>\n * </li>\n * ))}\n * </ul>\n *\n * <button disabled={!userMemberships.hasNextPage} onClick={() => userMemberships.fetchNext()}>\n * Load more\n * </button>\n * </>\n * )\n * }\n *\n * export default JoinedOrganizations\n * ```\n *\n * @example\n * ### Simple pagination\n *\n * The following example demonstrates how to use the `fetchPrevious` and `fetchNext` helper functions to paginate through the data. The `userInvitations` attribute will be populated with the first page of invitations. When the \"Previous page\" or \"Next page\" button is clicked, the `fetchPrevious` or `fetchNext` helper function will be called to fetch the previous or next page of invitations.\n *\n * Notice the difference between this example's pagination and the infinite pagination example above.\n *\n * ```tsx {{ filename: 'src/components/UserInvitationsTable.tsx' }}\n * import { useOrganizationList } from '@clerk/react'\n * import React from 'react'\n *\n * const UserInvitationsTable = () => {\n * const { isLoaded, userInvitations } = useOrganizationList({\n * userInvitations: {\n * infinite: true,\n * keepPreviousData: true,\n * },\n * })\n *\n * if (!isLoaded || userInvitations.isLoading) {\n * return <>Loading</>\n * }\n *\n * return (\n * <>\n * <table>\n * <thead>\n * <tr>\n * <th>Email</th>\n * <th>Org name</th>\n * </tr>\n * </thead>\n *\n * <tbody>\n * {userInvitations.data?.map((inv) => (\n * <tr key={inv.id}>\n * <th>{inv.emailAddress}</th>\n * <th>{inv.publicOrganizationData.name}</th>\n * </tr>\n * ))}\n * </tbody>\n * </table>\n *\n * <button disabled={!userInvitations.hasPreviousPage} onClick={userInvitations.fetchPrevious}>\n * Prev\n * </button>\n * <button disabled={!userInvitations.hasNextPage} onClick={userInvitations.fetchNext}>\n * Next\n * </button>\n * </>\n * )\n * }\n *\n * export default UserInvitationsTable\n * ```\n */\nexport function useOrganizationList<T extends UseOrganizationListParams>(params?: T): UseOrganizationListReturn<T> {\n const { userMemberships, userInvitations, userSuggestions } = params || {};\n\n useAssertWrappedByClerkProvider('useOrganizationList');\n useAttemptToEnableOrganizations('useOrganizationList');\n\n const userMembershipsSafeValues = useWithSafeValues(userMemberships, {\n initialPage: 1,\n pageSize: 10,\n keepPreviousData: false,\n infinite: false,\n });\n\n const userInvitationsSafeValues = useWithSafeValues(userInvitations, {\n initialPage: 1,\n pageSize: 10,\n status: 'pending',\n keepPreviousData: false,\n infinite: false,\n });\n\n const userSuggestionsSafeValues = useWithSafeValues(userSuggestions, {\n initialPage: 1,\n pageSize: 10,\n status: 'pending',\n keepPreviousData: false,\n infinite: false,\n });\n\n const clerk = useClerkInstanceContext();\n const user = useUserContext();\n\n clerk.telemetry?.record(eventMethodCalled('useOrganizationList'));\n\n const userMembershipsParams =\n typeof userMemberships === 'undefined'\n ? undefined\n : {\n initialPage: userMembershipsSafeValues.initialPage,\n pageSize: userMembershipsSafeValues.pageSize,\n };\n\n const userInvitationsParams =\n typeof userInvitations === 'undefined'\n ? undefined\n : {\n initialPage: userInvitationsSafeValues.initialPage,\n pageSize: userInvitationsSafeValues.pageSize,\n status: userInvitationsSafeValues.status,\n };\n\n const userSuggestionsParams =\n typeof userSuggestions === 'undefined'\n ? undefined\n : {\n initialPage: userSuggestionsSafeValues.initialPage,\n pageSize: userSuggestionsSafeValues.pageSize,\n status: userSuggestionsSafeValues.status,\n };\n\n const isClerkLoaded = !!(clerk.loaded && user);\n\n const memberships = usePagesOrInfinite({\n fetcher: user?.getOrganizationMemberships,\n config: {\n keepPreviousData: userMembershipsSafeValues.keepPreviousData,\n infinite: userMembershipsSafeValues.infinite,\n enabled: !!userMembershipsParams,\n isSignedIn: Boolean(user),\n initialPage: userMembershipsSafeValues.initialPage,\n pageSize: userMembershipsSafeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: STABLE_KEYS.USER_MEMBERSHIPS_KEY,\n authenticated: Boolean(user),\n tracked: {\n userId: user?.id,\n },\n untracked: {\n args: userMembershipsParams,\n },\n }),\n });\n\n const invitations = usePagesOrInfinite({\n fetcher: user?.getOrganizationInvitations,\n config: {\n keepPreviousData: userInvitationsSafeValues.keepPreviousData,\n infinite: userInvitationsSafeValues.infinite,\n // In useOrganizationList, you need to opt in by passing an object or `true`.\n enabled: !!userInvitationsParams,\n isSignedIn: Boolean(user),\n initialPage: userInvitationsSafeValues.initialPage,\n pageSize: userInvitationsSafeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: STABLE_KEYS.USER_INVITATIONS_KEY,\n authenticated: Boolean(user),\n tracked: {\n userId: user?.id,\n },\n untracked: {\n args: userInvitationsParams,\n },\n }),\n });\n\n const suggestions = usePagesOrInfinite({\n fetcher: user?.getOrganizationSuggestions,\n config: {\n keepPreviousData: userSuggestionsSafeValues.keepPreviousData,\n infinite: userSuggestionsSafeValues.infinite,\n enabled: !!userSuggestionsParams,\n isSignedIn: Boolean(user),\n initialPage: userSuggestionsSafeValues.initialPage,\n pageSize: userSuggestionsSafeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: STABLE_KEYS.USER_SUGGESTIONS_KEY,\n authenticated: Boolean(user),\n tracked: {\n userId: user?.id,\n },\n untracked: {\n args: userSuggestionsParams,\n },\n }),\n });\n\n // TODO: Properly check for SSR user values\n if (!isClerkLoaded) {\n return {\n isLoaded: false,\n createOrganization: undefined,\n setActive: undefined,\n userMemberships: undefinedPaginatedResource,\n userInvitations: undefinedPaginatedResource,\n userSuggestions: undefinedPaginatedResource,\n };\n }\n\n return {\n isLoaded: isClerkLoaded,\n setActive: clerk.setActive,\n createOrganization: clerk.createOrganization,\n userMemberships: memberships,\n userInvitations: invitations,\n userSuggestions: suggestions,\n };\n}\n","import React from 'react';\n\n/**\n * @internal\n */\nexport const useSafeLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;\n","import { eventMethodCalled } from '../../telemetry/events/method-called';\nimport type { UseSessionReturn } from '../../types';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext, useSessionContext } from '../contexts';\n\ntype UseSession = () => UseSessionReturn;\n\nconst hookName = `useSession`;\n/**\n * The `useSession()` hook provides access to the current user's [`Session`](https://clerk.com/docs/reference/javascript/session) object, as well as helpers for setting the active session.\n *\n * @unionReturnHeadings\n * [\"Initialization\", \"Signed out\", \"Signed in\"]\n *\n * @function\n *\n * @param [options] - An object containing options for the `useSession()` hook.\n * @example\n * ### Access the `Session` object\n *\n * The following example uses the `useSession()` hook to access the `Session` object, which has the `lastActiveAt` property. The `lastActiveAt` property is a `Date` object used to show the time the session was last active.\n *\n * <Tabs items='React,Next.js'>\n * <Tab>\n *\n * ```tsx {{ filename: 'src/Home.tsx' }}\n * import { useSession } from '@clerk/react'\n *\n * export default function Home() {\n * const { isLoaded, session, isSignedIn } = useSession()\n *\n * if (!isLoaded) {\n * // Handle loading state\n * return null\n * }\n * if (!isSignedIn) {\n * // Handle signed out state\n * return null\n * }\n *\n * return (\n * <div>\n * <p>This session has been active since {session.lastActiveAt.toLocaleString()}</p>\n * </div>\n * )\n * }\n * ```\n *\n * </Tab>\n * <Tab>\n *\n * {@include ../../../docs/use-session.md#nextjs-01}\n *\n * </Tab>\n * </Tabs>\n */\nexport const useSession: UseSession = () => {\n useAssertWrappedByClerkProvider(hookName);\n\n const session = useSessionContext();\n const clerk = useClerkInstanceContext();\n\n clerk.telemetry?.record(eventMethodCalled(hookName));\n\n if (session === undefined) {\n return { isLoaded: false, isSignedIn: undefined, session: undefined };\n }\n\n if (session === null) {\n return { isLoaded: true, isSignedIn: false, session: null };\n }\n\n return { isLoaded: true, isSignedIn: clerk.isSignedIn, session };\n};\n","import { eventMethodCalled } from '../../telemetry/events/method-called';\nimport type { UseSessionListReturn } from '../../types';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext, useClientContext } from '../contexts';\n\nconst hookName = 'useSessionList';\n/**\n * The `useSessionList()` hook returns an array of [`Session`](https://clerk.com/docs/reference/javascript/session) objects that have been registered on the client device.\n *\n * @unionReturnHeadings\n * [\"Initialization\", \"Loaded\"]\n *\n * @function\n *\n * @example\n * ### Get a list of sessions\n *\n * The following example uses `useSessionList()` to get a list of sessions that have been registered on the client device. The `sessions` property is used to show the number of times the user has visited the page.\n *\n * <Tabs items='React,Next.js'>\n * <Tab>\n *\n * ```tsx {{ filename: 'src/Home.tsx' }}\n * import { useSessionList } from '@clerk/react'\n *\n * export default function Home() {\n * const { isLoaded, sessions } = useSessionList()\n *\n * if (!isLoaded) {\n * // Handle loading state\n * return null\n * }\n *\n * return (\n * <div>\n * <p>Welcome back. You've been here {sessions.length} times before.</p>\n * </div>\n * )\n * }\n * ```\n *\n * </Tab>\n * <Tab>\n *\n * {@include ../../../docs/use-session-list.md#nextjs-01}\n *\n * </Tab>\n * </Tabs>\n */\nexport const useSessionList = (): UseSessionListReturn => {\n useAssertWrappedByClerkProvider(hookName);\n\n const isomorphicClerk = useClerkInstanceContext();\n const client = useClientContext();\n const clerk = useClerkInstanceContext();\n\n clerk.telemetry?.record(eventMethodCalled(hookName));\n\n if (!client) {\n return { isLoaded: false, sessions: undefined, setActive: undefined };\n }\n\n return {\n isLoaded: true,\n sessions: client.sessions,\n setActive: isomorphicClerk.setActive,\n };\n};\n","import { eventMethodCalled } from '../../telemetry/events/method-called';\nimport type { UseUserReturn } from '../../types';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext, useUserContext } from '../contexts';\n\nconst hookName = 'useUser';\n/**\n * The `useUser()` hook provides access to the current user's [`User`](https://clerk.com/docs/reference/javascript/user) object, which contains all the data for a single user in your application and provides methods to manage their account. This hook also allows you to check if the user is signed in and if Clerk has loaded and initialized.\n *\n * @unionReturnHeadings\n * [\"Initialization\", \"Signed out\", \"Signed in\"]\n *\n * @example\n * ### Get the current user\n *\n * The following example uses the `useUser()` hook to access the [`User`](https://clerk.com/docs/reference/javascript/user) object, which contains the current user's data such as their full name. The `isLoaded` and `isSignedIn` properties are used to handle the loading state and to check if the user is signed in, respectively.\n *\n * ```tsx {{ filename: 'src/Example.tsx' }}\n * import { useUser } from '@clerk/react'\n *\n * export default function Example() {\n * const { isSignedIn, user, isLoaded } = useUser()\n *\n * if (!isLoaded) {\n * return <div>Loading...</div>\n * }\n *\n * if (!isSignedIn) {\n * return <div>Sign in to view this page</div>\n * }\n *\n * return <div>Hello {user.firstName}!</div>\n * }\n * ```\n *\n * @example\n * ### Update user data\n *\n * The following example uses the `useUser()` hook to access the [`User`](https://clerk.com/docs/reference/javascript/user) object, which calls the [`update()`](https://clerk.com/docs/reference/javascript/user#update) method to update the current user's information.\n *\n * <Tabs items='React,Next.js'>\n * <Tab>\n *\n * ```tsx {{ filename: 'src/Home.tsx' }}\n * import { useUser } from '@clerk/react'\n *\n * export default function Home() {\n * const { isSignedIn, isLoaded, user } = useUser()\n *\n * if (!isLoaded) {\n * // Handle loading state\n * return null\n * }\n *\n * if (!isSignedIn) return null\n *\n * const updateUser = async () => {\n * await user.update({\n * firstName: 'John',\n * lastName: 'Doe',\n * })\n * }\n *\n * return (\n * <>\n * <button onClick={updateUser}>Update your name</button>\n * <p>user.firstName: {user.firstName}</p>\n * <p>user.lastName: {user.lastName}</p>\n * </>\n * )\n * }\n * ```\n * </Tab>\n * <Tab>\n *\n * {@include ../../../docs/use-user.md#nextjs-01}\n *\n * </Tab>\n * </Tabs>\n *\n * @example\n * ### Reload user data\n *\n * The following example uses the `useUser()` hook to access the [`User`](https://clerk.com/docs/reference/javascript/user) object, which calls the [`reload()`](https://clerk.com/docs/reference/javascript/user#reload) method to get the latest user's information.\n *\n * <Tabs items='React,Next.js'>\n * <Tab>\n *\n * ```tsx {{ filename: 'src/Home.tsx' }}\n * import { useUser } from '@clerk/react'\n *\n * export default function Home() {\n * const { isSignedIn, isLoaded, user } = useUser();\n *\n * if (!isLoaded) {\n * // Handle loading state\n * return null;\n * }\n *\n * if (!isSignedIn) return null;\n *\n * const updateUser = async () => {\n * // Update data via an API endpoint\n * const updateMetadata = await fetch('/api/updateMetadata', {\n * method: 'POST',\n * body: JSON.stringify({\n * role: 'admin'\n * })\n * });\n *\n * // Check if the update was successful\n * if ((await updateMetadata.json()).message !== 'success') {\n * throw new Error('Error updating');\n * }\n *\n * // If the update was successful, reload the user data\n * await user.reload();\n * };\n *\n * return (\n * <>\n * <button onClick={updateUser}>Update your metadata</button>\n * <p>user role: {user.publicMetadata.role}</p>\n * </>\n * );\n * }\n * ```\n *\n * </Tab>\n * <Tab>\n *\n * {@include ../../../docs/use-user.md#nextjs-02}\n *\n * </Tab>\n * </Tabs>\n */\nexport function useUser(): UseUserReturn {\n useAssertWrappedByClerkProvider(hookName);\n\n const user = useUserContext();\n const clerk = useClerkInstanceContext();\n\n clerk.telemetry?.record(eventMethodCalled(hookName));\n\n if (user === undefined) {\n return { isLoaded: false, isSignedIn: undefined, user: undefined };\n }\n\n if (user === null) {\n return { isLoaded: true, isSignedIn: false, user: null };\n }\n\n return { isLoaded: true, isSignedIn: true, user };\n}\n","import { dequal as deepEqual } from 'dequal';\nimport React from 'react';\n\ntype UseMemoFactory<T> = () => T;\ntype UseMemoDependencyArray = Exclude<Parameters<typeof React.useMemo>[1], 'undefined'>;\ntype UseDeepEqualMemo = <T>(factory: UseMemoFactory<T>, dependencyArray: UseMemoDependencyArray) => T;\n\nconst useDeepEqualMemoize = <T>(value: T) => {\n const ref = React.useRef<T>(value);\n if (!deepEqual(value, ref.current)) {\n ref.current = value;\n }\n return React.useMemo(() => ref.current, [ref.current]);\n};\n\n/**\n * @internal\n */\nexport const useDeepEqualMemo: UseDeepEqualMemo = (factory, dependencyArray) => {\n return React.useMemo(factory, useDeepEqualMemoize(dependencyArray));\n};\n\n/**\n * @internal\n */\nexport const isDeeplyEqual = deepEqual;\n","import { useCallback, useRef } from 'react';\n\nimport { validateReverificationConfig } from '../../authorization';\nimport { isReverificationHint, reverificationError } from '../../authorization-errors';\nimport { ClerkRuntimeError, isClerkAPIResponseError } from '../../error';\nimport { eventMethodCalled } from '../../telemetry';\nimport type { Clerk, SessionVerificationLevel } from '../../types';\nimport { createDeferredPromise } from '../../utils/createDeferredPromise';\nimport { useClerk } from './useClerk';\nimport { useSafeLayoutEffect } from './useSafeLayoutEffect';\n\nconst CLERK_API_REVERIFICATION_ERROR_CODE = 'session_reverification_required';\n\n/**\n *\n */\nasync function resolveResult<T>(result: Promise<T> | T): Promise<T | ReturnType<typeof reverificationError>> {\n try {\n const r = await result;\n if (r instanceof Response) {\n return r.json();\n }\n return r;\n } catch (e) {\n // Treat fapi assurance as an assurance hint\n if (isClerkAPIResponseError(e) && e.errors.find(({ code }) => code === CLERK_API_REVERIFICATION_ERROR_CODE)) {\n return reverificationError();\n }\n\n // rethrow\n throw e;\n }\n}\n\ntype ExcludeClerkError<T> = T extends { clerk_error: any } ? never : T;\n\n/**\n * @interface\n */\nexport type NeedsReverificationParameters = {\n /**\n * Marks the reverification process as cancelled and rejects the original request.\n */\n cancel: () => void;\n /**\n * Marks the reverification process as complete and retries the original request.\n */\n complete: () => void;\n /**\n * The verification level required for the reverification process.\n */\n level: SessionVerificationLevel | undefined;\n};\n\n/**\n * The optional options object.\n *\n * @interface\n */\nexport type UseReverificationOptions = {\n /**\n * Handler for the reverification process. Opts out of using the default UI. Use this to build a custom UI.\n *\n * @param properties - Callbacks and info to control the reverification flow.\n * @param properties.cancel - A function that will cancel the reverification process.\n * @param properties.complete - A function that will retry the original request after reverification.\n * @param properties.level - The level returned with the reverification hint.\n */\n onNeedsReverification?: (properties: NeedsReverificationParameters) => void;\n};\n\n/**\n * @interface\n */\ntype UseReverificationResult<Fetcher extends (...args: any[]) => Promise<any> | undefined> = (\n ...args: Parameters<Fetcher>\n) => Promise<ExcludeClerkError<Awaited<ReturnType<Fetcher>>>>;\n\n/**\n * @interface\n */\ntype UseReverification = <\n Fetcher extends (...args: any[]) => Promise<any> | undefined,\n Options extends UseReverificationOptions = UseReverificationOptions,\n>(\n /**\n * A function that returns a promise.\n */\n fetcher: Fetcher,\n /**\n * Optional configuration object extending [`UseReverificationOptions`](https://clerk.com/docs/reference/hooks/use-reverification#use-reverification-options).\n */\n options?: Options,\n) => UseReverificationResult<Fetcher>;\n\ntype CreateReverificationHandlerParams = UseReverificationOptions & {\n openUIComponent: Clerk['__internal_openReverification'];\n telemetry: Clerk['telemetry'];\n};\n\n/**\n *\n */\nfunction createReverificationHandler(params: CreateReverificationHandlerParams) {\n /**\n *\n */\n function assertReverification<Fetcher extends (...args: any[]) => Promise<any> | undefined>(\n fetcher: Fetcher,\n ): (...args: Parameters<Fetcher>) => Promise<ExcludeClerkError<Awaited<ReturnType<Fetcher>>>> {\n return (async (...args: Parameters<Fetcher>) => {\n let result = await resolveResult(fetcher(...args));\n\n if (isReverificationHint(result)) {\n /**\n * Create a promise\n */\n const resolvers = createDeferredPromise();\n\n const isValidMetadata = validateReverificationConfig(result.clerk_error.metadata?.reverification);\n\n const level = isValidMetadata ? isValidMetadata().level : undefined;\n\n const cancel = () => {\n resolvers.reject(\n new ClerkRuntimeError('User cancelled attempted verification', {\n code: 'reverification_cancelled',\n }),\n );\n };\n\n const complete = () => {\n resolvers.resolve(true);\n };\n\n if (params.onNeedsReverification === undefined) {\n /**\n * On success resolve the pending promise\n * On cancel reject the pending promise\n */\n params.openUIComponent?.({\n level: level,\n afterVerification: complete,\n afterVerificationCancelled: cancel,\n });\n } else {\n params.onNeedsReverification({\n cancel,\n complete,\n level,\n });\n }\n\n /**\n * Wait until the promise from above have been resolved or rejected\n */\n await resolvers.promise;\n\n /**\n * After the promise resolved successfully try the original request one more time\n */\n result = await resolveResult(fetcher(...args));\n }\n\n return result;\n }) as ExcludeClerkError<Awaited<ReturnType<Fetcher>>>;\n }\n\n return assertReverification;\n}\n\n/**\n * > [!WARNING]\n * >\n * > Depending on the SDK you're using, this feature requires `@clerk/nextjs@6.12.7` or later, `@clerk/react@5.25.1` or later, and `@clerk/clerk-js@5.57.1` or later.\n *\n * The `useReverification()` hook is used to handle a session's reverification flow. If a request requires reverification, a modal will display, prompting the user to verify their credentials. Upon successful verification, the original request will automatically retry.\n *\n * @function\n *\n * @returns The `useReverification()` hook returns an array with the \"enhanced\" fetcher.\n *\n * @example\n * ### Handle cancellation of the reverification process\n *\n * The following example demonstrates how to handle scenarios where a user cancels the reverification flow, such as closing the modal, which might result in `myData` being `null`.\n *\n * In the following example, `myFetcher` would be a function in your backend that fetches data from the route that requires reverification. See the [guide on how to require reverification](https://clerk.com/docs/guides/secure/reverification) for more information.\n *\n * ```tsx {{ filename: 'src/components/MyButton.tsx' }}\n * import { useReverification } from '@clerk/react'\n * import { isReverificationCancelledError } from '@clerk/react/error'\n *\n * type MyData = {\n * balance: number\n * }\n *\n * export function MyButton() {\n * const fetchMyData = () => fetch('/api/balance').then(res=> res.json() as Promise<MyData>)\n * const enhancedFetcher = useReverification(fetchMyData);\n *\n * const handleClick = async () => {\n * try {\n * const myData = await enhancedFetcher()\n * // ^ is types as `MyData`\n * } catch (e) {\n * // Handle error returned from the fetcher here\n *\n * // You can also handle cancellation with the following\n * if (isReverificationCancelledError(err)) {\n * // Handle the cancellation error here\n * }\n * }\n * }\n *\n * return <button onClick={handleClick}>Update User</button>\n * }\n * ```\n */\nexport const useReverification: UseReverification = (fetcher, options) => {\n const { __internal_openReverification, telemetry } = useClerk();\n const fetcherRef = useRef(fetcher);\n const optionsRef = useRef(options);\n\n telemetry?.record(\n eventMethodCalled('useReverification', {\n onNeedsReverification: Boolean(options?.onNeedsReverification),\n }),\n );\n\n // Keep fetcher and options ref in sync\n useSafeLayoutEffect(() => {\n fetcherRef.current = fetcher;\n optionsRef.current = options;\n });\n\n return useCallback(\n (...args) => {\n const handler = createReverificationHandler({\n openUIComponent: __internal_openReverification,\n telemetry,\n ...optionsRef.current,\n })(fetcherRef.current);\n return handler(...args);\n },\n [__internal_openReverification, telemetry],\n );\n};\n","import type { ForPayerType } from '../../types/billing';\nimport { useClerkInstanceContext, useOrganizationContext, useUserContext } from '../contexts';\n\n/**\n * @internal\n */\nexport function useBillingHookEnabled(params?: { for?: ForPayerType; enabled?: boolean; authenticated?: boolean }) {\n const clerk = useClerkInstanceContext();\n\n const enabledFromParam = params?.enabled ?? true;\n\n // @ts-expect-error `__internal_environment` is not typed\n const environment = clerk.__internal_environment as unknown as EnvironmentResource | null | undefined;\n\n const user = useUserContext();\n const { organization } = useOrganizationContext();\n\n const isOrganization = params?.for === 'organization';\n const billingEnabled = isOrganization\n ? environment?.commerceSettings.billing.organization.enabled\n : environment?.commerceSettings.billing.user.enabled;\n\n const requireUserAndOrganizationWhenAuthenticated =\n (params?.authenticated ?? true) ? (isOrganization ? Boolean(organization?.id) : true) && Boolean(user?.id) : true;\n\n return billingEnabled && enabledFromParam && clerk.loaded && requireUserAndOrganizationWhenAuthenticated;\n}\n","import { eventMethodCalled } from '../../telemetry/events/method-called';\nimport type { ClerkPaginatedResponse, ClerkResource, ForPayerType } from '../../types';\nimport {\n useAssertWrappedByClerkProvider,\n useClerkInstanceContext,\n useOrganizationContext,\n useUserContext,\n} from '../contexts';\nimport type { ResourceCacheStableKey } from '../stable-keys';\nimport type { PagesOrInfiniteOptions, PaginatedHookConfig, PaginatedResources } from '../types';\nimport { createCacheKeys } from './createCacheKeys';\nimport { useBillingHookEnabled } from './useBillingHookEnabled';\nimport { usePagesOrInfinite, useWithSafeValues } from './usePagesOrInfinite';\n\n/**\n * @internal\n */\ntype BillingHookConfig<TResource extends ClerkResource, TParams extends PagesOrInfiniteOptions> = {\n hookName: string;\n resourceType: ResourceCacheStableKey;\n useFetcher: (\n param: ForPayerType,\n ) => ((params: TParams & { orgId?: string }) => Promise<ClerkPaginatedResponse<TResource>>) | undefined;\n options?: {\n unauthenticated?: boolean;\n };\n};\n\n/**\n * @interface\n */\nexport interface HookParams\n extends PaginatedHookConfig<\n PagesOrInfiniteOptions & {\n /**\n * If `true`, a request will be triggered when the hook is mounted.\n *\n * @default true\n */\n enabled?: boolean;\n /**\n * On `cache` mode, no request will be triggered when the hook is mounted and the data will be fetched from the cache.\n *\n * @default undefined\n *\n * @hidden\n *\n * @experimental\n */\n __experimental_mode?: 'cache';\n }\n > {\n /**\n * Specifies whether to fetch for the current user or Organization.\n *\n * @default 'user'\n */\n for?: ForPayerType;\n}\n\n/**\n * A hook factory that creates paginated data fetching hooks for commerce-related resources.\n * It provides a standardized way to create hooks that can fetch either user or Organization resources\n * with built-in pagination support.\n *\n * The generated hooks handle:\n * - Clerk authentication context\n * - Resource-specific data fetching\n * - Pagination (both traditional and infinite scroll)\n * - Telemetry tracking\n * - Type safety for the specific resource.\n *\n * @internal\n */\nexport function createBillingPaginatedHook<TResource extends ClerkResource, TParams extends PagesOrInfiniteOptions>({\n hookName,\n resourceType,\n useFetcher,\n options,\n}: BillingHookConfig<TResource, TParams>) {\n return function useBillingHook<T extends HookParams>(\n params?: T,\n ): PaginatedResources<TResource, T extends { infinite: true } ? true : false> {\n const { for: _for, enabled: externalEnabled, ...paginationParams } = params || ({} as Partial<T>);\n\n const safeFor = _for || 'user';\n\n useAssertWrappedByClerkProvider(hookName);\n\n const fetchFn = useFetcher(safeFor);\n\n const safeValues = useWithSafeValues(paginationParams, {\n initialPage: 1,\n pageSize: 10,\n keepPreviousData: false,\n infinite: false,\n __experimental_mode: undefined,\n } as unknown as T);\n\n const clerk = useClerkInstanceContext();\n\n const user = useUserContext();\n const { organization } = useOrganizationContext();\n\n clerk.telemetry?.record(eventMethodCalled(hookName));\n\n const isForOrganization = safeFor === 'organization';\n\n const billingEnabled = useBillingHookEnabled({\n for: safeFor,\n enabled: externalEnabled,\n authenticated: !options?.unauthenticated,\n });\n\n const hookParams =\n typeof paginationParams === 'undefined'\n ? undefined\n : ({\n initialPage: safeValues.initialPage,\n pageSize: safeValues.pageSize,\n ...(options?.unauthenticated ? {} : isForOrganization ? { orgId: organization?.id } : {}),\n } as TParams);\n\n const isEnabled = !!hookParams && clerk.loaded && !!billingEnabled;\n\n return usePagesOrInfinite({\n fetcher: fetchFn,\n config: {\n keepPreviousData: safeValues.keepPreviousData,\n infinite: safeValues.infinite,\n enabled: isEnabled,\n ...(options?.unauthenticated ? {} : { isSignedIn: user !== null }),\n __experimental_mode: safeValues.__experimental_mode,\n initialPage: safeValues.initialPage,\n pageSize: safeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: resourceType,\n authenticated: !options?.unauthenticated,\n tracked: options?.unauthenticated\n ? ({ for: safeFor } as const)\n : ({\n userId: user?.id,\n ...(isForOrganization ? { [__CLERK_USE_RQ__ ? 'orgId' : '_orgId']: organization?.id } : {}),\n } as const),\n untracked: {\n args: hookParams as TParams,\n },\n }),\n });\n };\n}\n","import type { BillingStatementResource, GetStatementsParams } from '../../types';\nimport { useClerkInstanceContext } from '../contexts';\nimport { STABLE_KEYS } from '../stable-keys';\nimport { createBillingPaginatedHook } from './createBillingPaginatedHook';\n\n/**\n * @internal\n */\nexport const useStatements = createBillingPaginatedHook<BillingStatementResource, GetStatementsParams>({\n hookName: 'useStatements',\n resourceType: STABLE_KEYS.STATEMENTS_KEY,\n useFetcher: () => {\n const clerk = useClerkInstanceContext();\n if (clerk.loaded) {\n return clerk.billing.getStatements;\n }\n return undefined;\n },\n});\n\n/**\n * @interface\n */\nexport type UseStatementsReturn = ReturnType<typeof useStatements>;\n","import type { BillingPaymentResource, GetPaymentAttemptsParams } from '../../types';\nimport { useClerkInstanceContext } from '../contexts';\nimport { STABLE_KEYS } from '../stable-keys';\nimport { createBillingPaginatedHook } from './createBillingPaginatedHook';\n\n/**\n * @internal\n */\nexport const usePaymentAttempts = createBillingPaginatedHook<BillingPaymentResource, GetPaymentAttemptsParams>({\n hookName: 'usePaymentAttempts',\n resourceType: STABLE_KEYS.PAYMENT_ATTEMPTS_KEY,\n useFetcher: () => {\n const clerk = useClerkInstanceContext();\n if (clerk.loaded) {\n return clerk.billing.getPaymentAttempts;\n }\n return undefined;\n },\n});\n\n/**\n * @interface\n */\nexport type UsePaymentAttemptsReturn = ReturnType<typeof usePaymentAttempts>;\n","import type { BillingPaymentMethodResource, GetPaymentMethodsParams } from '../../types';\nimport { useOrganizationContext, useUserContext } from '../contexts';\nimport { STABLE_KEYS } from '../stable-keys';\nimport { createBillingPaginatedHook } from './createBillingPaginatedHook';\n\n/**\n * @internal\n */\nexport const usePaymentMethods = createBillingPaginatedHook<BillingPaymentMethodResource, GetPaymentMethodsParams>({\n hookName: 'usePaymentMethods',\n resourceType: STABLE_KEYS.PAYMENT_METHODS_KEY,\n useFetcher: resource => {\n const { organization } = useOrganizationContext();\n const user = useUserContext();\n\n if (resource === 'organization') {\n return organization?.getPaymentMethods;\n }\n return user?.getPaymentMethods;\n },\n});\n\n/**\n * @interface\n */\nexport type UsePaymentMethodsReturn = ReturnType<typeof usePaymentMethods>;\n","import type { BillingPlanResource, GetPlansParams } from '../../types';\nimport { useClerkInstanceContext } from '../contexts';\nimport { STABLE_KEYS } from '../stable-keys';\nimport { createBillingPaginatedHook } from './createBillingPaginatedHook';\n\n/**\n * @internal\n */\nexport const usePlans = createBillingPaginatedHook<BillingPlanResource, GetPlansParams>({\n hookName: 'usePlans',\n resourceType: STABLE_KEYS.PLANS_KEY,\n useFetcher: _for => {\n const clerk = useClerkInstanceContext();\n if (!clerk.loaded) {\n return undefined;\n }\n return params => clerk.billing.getPlans({ ...params, for: _for });\n },\n options: {\n unauthenticated: true,\n },\n});\n\n/**\n * @interface\n */\nexport type UsePlansReturn = ReturnType<typeof usePlans>;\n","import { useMemo } from 'react';\n\nimport type { ForPayerType } from '../../types';\nimport { STABLE_KEYS } from '../stable-keys';\nimport { createCacheKeys } from './createCacheKeys';\n\nexport function useSubscriptionCacheKeys(params: {\n userId: string | undefined;\n orgId: string | undefined;\n for?: ForPayerType;\n}) {\n const { userId, orgId, for: forType } = params;\n return useMemo(() => {\n const isOrganization = forType === 'organization';\n\n const safeOrgId = isOrganization ? orgId : undefined;\n return createCacheKeys({\n stablePrefix: STABLE_KEYS.SUBSCRIPTION_KEY,\n authenticated: true,\n tracked: {\n userId,\n orgId: safeOrgId,\n },\n untracked: {\n args: { orgId: safeOrgId },\n },\n });\n }, [userId, orgId, forType]);\n}\n","import { useCallback } from 'react';\n\nimport { eventMethodCalled } from '../../telemetry/events';\nimport type { EnvironmentResource } from '../../types';\nimport { useSWR } from '../clerk-swr';\nimport {\n useAssertWrappedByClerkProvider,\n useClerkInstanceContext,\n useOrganizationContext,\n useUserContext,\n} from '../contexts';\nimport { useSubscriptionCacheKeys } from './useSubscription.shared';\nimport type { SubscriptionResult, UseSubscriptionParams } from './useSubscription.types';\n\nconst hookName = 'useSubscription';\n\n/**\n * This is the existing implementation of useSubscription using SWR.\n * It is kept here for backwards compatibility until our next major version.\n *\n * @internal\n */\nexport function useSubscription(params?: UseSubscriptionParams): SubscriptionResult {\n useAssertWrappedByClerkProvider(hookName);\n\n const clerk = useClerkInstanceContext();\n const user = useUserContext();\n const { organization } = useOrganizationContext();\n\n // @ts-expect-error `__internal_environment` is not typed\n const environment = clerk.__internal_environment as unknown as EnvironmentResource | null | undefined;\n\n clerk.telemetry?.record(eventMethodCalled(hookName));\n\n const isOrganization = params?.for === 'organization';\n const billingEnabled = isOrganization\n ? environment?.commerceSettings.billing.organization.enabled\n : environment?.commerceSettings.billing.user.enabled;\n const isEnabled = (params?.enabled ?? true) && billingEnabled;\n\n const { queryKey } = useSubscriptionCacheKeys({\n userId: user?.id,\n orgId: organization?.id,\n for: params?.for,\n });\n\n const swr = useSWR(\n isEnabled ? { queryKey } : null,\n ({ queryKey }) => {\n const args = queryKey[3].args;\n\n if (queryKey[2].userId) {\n return clerk.billing.getSubscription(args);\n }\n return null;\n },\n {\n dedupingInterval: 1_000 * 60,\n keepPreviousData: params?.keepPreviousData,\n },\n );\n\n const revalidate = useCallback(() => {\n void swr.mutate();\n }, [swr]);\n\n return {\n data: swr.data,\n error: swr.error,\n isLoading: swr.isLoading,\n isFetching: swr.isValidating,\n revalidate,\n };\n}\n","import { useCallback, useSyncExternalStore } from 'react';\n\nimport type { CheckoutSignalValue } from '../../types/clerk';\nimport type { __experimental_CheckoutProvider } from '../contexts';\nimport { useCheckoutContext, useClerkInstanceContext, useOrganizationContext } from '../contexts';\nimport { useUser } from './useUser';\n\ntype UseCheckoutParams = Parameters<typeof __experimental_CheckoutProvider>[0];\n\n/**\n * @function\n *\n * @param [options] - An object containing the configuration for the checkout flow.\n *\n * **Required** if the hook is used without a `<CheckoutProvider />` wrapping the component tree.\n */\nexport const useCheckout = (options?: UseCheckoutParams): CheckoutSignalValue => {\n const contextOptions = useCheckoutContext();\n const { for: forOrganization, planId, planPeriod } = options || contextOptions;\n const { organization } = useOrganizationContext();\n const { isLoaded, user } = useUser();\n const clerk = useClerkInstanceContext();\n\n if (user === null && isLoaded) {\n throw new Error('Clerk: Ensure that `useCheckout` is inside a component wrapped with `<SignedIn />`.');\n }\n\n if (isLoaded && forOrganization === 'organization' && organization === null) {\n throw new Error(\n 'Clerk: Ensure your flow checks for an active organization. Retrieve `orgId` from `useAuth()` and confirm it is defined. For SSR, see: https://clerk.com/docs/reference/backend/types/auth-object#how-to-access-the-auth-object',\n );\n }\n\n const signal = useCallback(() => {\n return clerk.__experimental_checkout({ planId, planPeriod, for: forOrganization });\n }, [user?.id, organization?.id, planId, planPeriod, forOrganization]);\n\n const subscribe = useCallback(\n (callback: () => void) => {\n if (!clerk.loaded) {\n return () => {};\n }\n\n return clerk.__internal_state.__internal_effect(() => {\n signal();\n callback();\n });\n },\n [signal, clerk.loaded, clerk.__internal_state],\n );\n\n const getSnapshot = useCallback(() => {\n return signal();\n }, [signal]);\n\n const value = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n return value;\n};\n","import { useMemo } from 'react';\n\nimport type { ForPayerType } from '../../types';\nimport { INTERNAL_STABLE_KEYS } from '../stable-keys';\nimport { createCacheKeys } from './createCacheKeys';\n\nexport function useStatementQueryCacheKeys(params: {\n statementId: string | null;\n userId: string | null;\n orgId: string | null;\n for?: ForPayerType;\n}) {\n const { statementId, userId, orgId, for: forType } = params;\n return useMemo(() => {\n return createCacheKeys({\n stablePrefix: INTERNAL_STABLE_KEYS.BILLING_STATEMENTS_KEY,\n authenticated: true,\n tracked: {\n statementId,\n forType,\n userId,\n orgId,\n },\n untracked: {\n args: {\n id: statementId ?? undefined,\n orgId: orgId ?? undefined,\n },\n },\n });\n }, [statementId, forType, userId, orgId]);\n}\n","import { useSWR } from '../clerk-swr';\nimport { useClerkInstanceContext, useOrganizationContext, useUserContext } from '../contexts';\nimport { useStatementQueryCacheKeys } from './useStatementQuery.shared';\nimport type { StatementQueryResult, UseStatementQueryParams } from './useStatementQuery.types';\n\n/**\n * This is the existing implementation of useStatementQuery using SWR.\n * It is kept here for backwards compatibility until our next major version.\n *\n * @internal\n */\nexport function __internal_useStatementQuery(params: UseStatementQueryParams = {}): StatementQueryResult {\n const { statementId = null, enabled = true, keepPreviousData = false, for: forType = 'user' } = params;\n const clerk = useClerkInstanceContext();\n const user = useUserContext();\n const { organization } = useOrganizationContext();\n\n const organizationId = forType === 'organization' ? (organization?.id ?? null) : null;\n const userId = user?.id ?? null;\n\n const { queryKey } = useStatementQueryCacheKeys({\n statementId,\n userId,\n orgId: organizationId,\n for: forType,\n });\n\n const queryEnabled = Boolean(statementId) && enabled && (forType !== 'organization' || Boolean(organizationId));\n\n const swr = useSWR(\n queryEnabled ? queryKey : null,\n () => {\n if (!statementId) {\n throw new Error('statementId is required to fetch a statement');\n }\n return clerk.billing.getStatement({ id: statementId, orgId: organizationId ?? undefined });\n },\n {\n dedupingInterval: 1_000 * 60,\n keepPreviousData,\n },\n );\n\n return {\n data: swr.data,\n error: (swr.error ?? null) as StatementQueryResult['error'],\n isLoading: swr.isLoading,\n isFetching: swr.isValidating,\n };\n}\n","import { useMemo } from 'react';\n\nimport { INTERNAL_STABLE_KEYS } from '../stable-keys';\nimport { createCacheKeys } from './createCacheKeys';\n\nexport function usePlanDetailsQueryCacheKeys(params: { planId: string | null }) {\n const { planId } = params;\n return useMemo(() => {\n return createCacheKeys({\n stablePrefix: INTERNAL_STABLE_KEYS.BILLING_PLANS_KEY,\n authenticated: false,\n tracked: {\n planId: planId ?? null,\n },\n untracked: {\n args: {\n id: planId ?? undefined,\n },\n },\n });\n }, [planId]);\n}\n","import { useSWR } from '../clerk-swr';\nimport { useClerkInstanceContext } from '../contexts';\nimport { usePlanDetailsQueryCacheKeys } from './usePlanDetailsQuery.shared';\nimport type { PlanDetailsQueryResult, UsePlanDetailsQueryParams } from './usePlanDetailsQuery.types';\n\n/**\n * This is the existing implementation of usePlanDetailsQuery using SWR.\n * It is kept here for backwards compatibility until our next major version.\n *\n * @internal\n */\nfunction usePlanDetailsQuery(params: UsePlanDetailsQueryParams = {}): PlanDetailsQueryResult {\n const { planId, initialPlan = null, enabled = true, keepPreviousData = true } = params;\n const clerk = useClerkInstanceContext();\n\n const targetPlanId = planId ?? initialPlan?.id ?? null;\n\n const { queryKey } = usePlanDetailsQueryCacheKeys({ planId: targetPlanId });\n\n const queryEnabled = Boolean(targetPlanId) && enabled;\n\n const swr = useSWR(\n queryEnabled ? queryKey : null,\n () => {\n if (!targetPlanId) {\n throw new Error('planId is required to fetch plan details');\n }\n return clerk.billing.getPlan({ id: targetPlanId });\n },\n {\n dedupingInterval: 1_000 * 60,\n keepPreviousData,\n fallbackData: initialPlan ?? undefined,\n },\n );\n\n return {\n data: swr.data,\n error: (swr.error ?? null) as PlanDetailsQueryResult['error'],\n isLoading: swr.isLoading,\n isFetching: swr.isValidating,\n };\n}\n\nexport { usePlanDetailsQuery as __internal_usePlanDetailsQuery };\n","import { useMemo } from 'react';\n\nimport type { ForPayerType } from '../../types';\nimport { INTERNAL_STABLE_KEYS } from '../stable-keys';\nimport { createCacheKeys } from './createCacheKeys';\n\nexport function usePaymentAttemptQueryCacheKeys(params: {\n paymentAttemptId: string;\n userId: string | null;\n orgId: string | null;\n for?: ForPayerType;\n}) {\n const { paymentAttemptId, userId, orgId, for: forType } = params;\n return useMemo(() => {\n return createCacheKeys({\n stablePrefix: INTERNAL_STABLE_KEYS.PAYMENT_ATTEMPT_KEY,\n authenticated: true,\n tracked: {\n paymentAttemptId,\n forType,\n userId,\n orgId,\n },\n untracked: {\n args: {\n id: paymentAttemptId ?? undefined,\n orgId: orgId ?? undefined,\n },\n },\n });\n }, [paymentAttemptId, forType, userId, orgId]);\n}\n","import { useSWR } from '../clerk-swr';\nimport { useClerkInstanceContext, useOrganizationContext, useUserContext } from '../contexts';\nimport { usePaymentAttemptQueryCacheKeys } from './usePaymentAttemptQuery.shared';\nimport type { PaymentAttemptQueryResult, UsePaymentAttemptQueryParams } from './usePaymentAttemptQuery.types';\n\n/**\n * This is the existing implementation of usePaymentAttemptQuery using SWR.\n * It is kept here for backwards compatibility until our next major version.\n *\n * @internal\n */\nexport function __internal_usePaymentAttemptQuery(params: UsePaymentAttemptQueryParams): PaymentAttemptQueryResult {\n const { paymentAttemptId, enabled = true, keepPreviousData = false, for: forType = 'user' } = params;\n const clerk = useClerkInstanceContext();\n const user = useUserContext();\n const { organization } = useOrganizationContext();\n\n const organizationId = forType === 'organization' ? (organization?.id ?? null) : null;\n const userId = user?.id ?? null;\n\n const { queryKey } = usePaymentAttemptQueryCacheKeys({\n paymentAttemptId,\n userId,\n orgId: organizationId,\n for: forType,\n });\n\n const queryEnabled = Boolean(paymentAttemptId) && enabled && (forType !== 'organization' || Boolean(organizationId));\n\n const swr = useSWR(\n queryEnabled ? { queryKey } : null,\n ({ queryKey }) => {\n const args = queryKey[3].args;\n return clerk.billing.getPaymentAttempt(args);\n },\n {\n dedupingInterval: 1_000 * 60,\n keepPreviousData,\n },\n );\n\n return {\n data: swr.data,\n error: (swr.error ?? null) as PaymentAttemptQueryResult['error'],\n isLoading: swr.isLoading,\n isFetching: swr.isValidating,\n };\n}\n","import type { StripeElement } from '@stripe/stripe-js';\nimport { useEffect, useRef } from 'react';\n\nexport const usePrevious = <T>(value: T): T => {\n const ref = useRef(value);\n\n useEffect(() => {\n ref.current = value;\n }, [value]);\n\n return ref.current;\n};\n\nexport const useAttachEvent = <A extends unknown[]>(\n element: StripeElement | null,\n event: string,\n cb?: (...args: A) => any,\n) => {\n const cbDefined = !!cb;\n const cbRef = useRef(cb);\n\n // In many integrations the callback prop changes on each render.\n // Using a ref saves us from calling element.on/.off every render.\n useEffect(() => {\n cbRef.current = cb;\n }, [cb]);\n\n useEffect(() => {\n if (!cbDefined || !element) {\n return () => {};\n }\n\n const decoratedCb = (...args: A): void => {\n if (cbRef.current) {\n cbRef.current(...args);\n }\n };\n\n (element as any).on(event, decoratedCb);\n\n return () => {\n (element as any).off(event, decoratedCb);\n };\n }, [cbDefined, event, element, cbRef]);\n};\n","/**\n * Original source: https://github.com/stripe/react-stripe-js.\n *\n * The current version of this file is a fork of the original version.\n * The main difference is that we have kept only the necessary parts of the file.\n * This is because we don't need it and it's not used in the Clerk codebase.\n *\n * The original version of this file is licensed under the MIT license.\n * Https://github.com/stripe/react-stripe-js/blob/master/LICENSE.\n */\n\nimport type { ElementProps, PaymentElementProps } from '@stripe/react-stripe-js';\nimport type {\n Stripe,\n StripeElement,\n StripeElements,\n StripeElementsOptions,\n StripeElementType,\n} from '@stripe/stripe-js';\nimport type { FunctionComponent, PropsWithChildren, ReactNode } from 'react';\nimport React, { useState } from 'react';\n\nimport { useAttachEvent, usePrevious } from './utils';\n\ninterface ElementsContextValue {\n elements: StripeElements | null;\n stripe: Stripe | null;\n}\n\nconst ElementsContext = React.createContext<ElementsContextValue | null>(null);\nElementsContext.displayName = 'ElementsContext';\n\nconst parseElementsContext = (ctx: ElementsContextValue | null, useCase: string): ElementsContextValue => {\n if (!ctx) {\n throw new Error(\n `Could not find Elements context; You need to wrap the part of your app that ${useCase} in an <Elements> provider.`,\n );\n }\n\n return ctx;\n};\n\ninterface ElementsProps {\n /**\n * A [Stripe object](https://stripe.com/docs/js/initializing) or a `Promise` resolving to a `Stripe` object.\n * The easiest way to initialize a `Stripe` object is with the the [Stripe.js wrapper module](https://github.com/stripe/stripe-js/blob/master/README.md#readme).\n * Once this prop has been set, it can not be changed.\n *\n * You can also pass in `null` or a `Promise` resolving to `null` if you are performing an initial server-side render or when generating a static site.\n */\n stripe: PromiseLike<Stripe | null> | Stripe | null;\n\n /**\n * Optional [Elements configuration options](https://stripe.com/docs/js/elements_object/create).\n * Once the stripe prop has been set, these options cannot be changed.\n */\n options?: StripeElementsOptions;\n}\n\ntype UnknownOptions = { [k: string]: unknown };\n\ninterface PrivateElementsProps {\n stripe: unknown;\n options?: UnknownOptions;\n children?: ReactNode;\n}\n\n/**\n * The `Elements` provider allows you to use [Element components](https://stripe.com/docs/stripe-js/react#element-components) and access the [Stripe object](https://stripe.com/docs/js/initializing) in any nested component.\n * Render an `Elements` provider at the root of your React app so that it is available everywhere you need it.\n *\n * To use the `Elements` provider, call `loadStripe` from `@stripe/stripe-js` with your publishable key.\n * The `loadStripe` function will asynchronously load the Stripe.js script and initialize a `Stripe` object.\n * Pass the returned `Promise` to `Elements`.\n *\n * @docs https://stripe.com/docs/stripe-js/react#elements-provider\n */\nconst Elements: FunctionComponent<PropsWithChildren<ElementsProps>> = (({\n stripe: rawStripeProp,\n options,\n children,\n}: PrivateElementsProps) => {\n const parsed = React.useMemo(() => parseStripeProp(rawStripeProp), [rawStripeProp]);\n\n // For a sync stripe instance, initialize into context\n const [ctx, setContext] = React.useState<ElementsContextValue>(() => ({\n stripe: parsed.tag === 'sync' ? parsed.stripe : null,\n elements: parsed.tag === 'sync' ? parsed.stripe.elements(options) : null,\n }));\n\n React.useEffect(() => {\n let isMounted = true;\n\n const safeSetContext = (stripe: Stripe) => {\n setContext(ctx => {\n // no-op if we already have a stripe instance (https://github.com/stripe/react-stripe-js/issues/296)\n if (ctx.stripe) {\n return ctx;\n }\n return {\n stripe,\n elements: stripe.elements(options),\n };\n });\n };\n\n // For an async stripePromise, store it in context once resolved\n if (parsed.tag === 'async' && !ctx.stripe) {\n parsed.stripePromise.then(stripe => {\n if (stripe && isMounted) {\n // Only update Elements context if the component is still mounted\n // and stripe is not null. We allow stripe to be null to make\n // handling SSR easier.\n safeSetContext(stripe);\n }\n });\n } else if (parsed.tag === 'sync' && !ctx.stripe) {\n // Or, handle a sync stripe instance going from null -> populated\n safeSetContext(parsed.stripe);\n }\n\n return () => {\n isMounted = false;\n };\n }, [parsed, ctx, options]);\n\n // Warn on changes to stripe prop\n const prevStripe = usePrevious(rawStripeProp);\n React.useEffect(() => {\n if (prevStripe !== null && prevStripe !== rawStripeProp) {\n console.warn('Unsupported prop change on Elements: You cannot change the `stripe` prop after setting it.');\n }\n }, [prevStripe, rawStripeProp]);\n\n // Apply updates to elements when options prop has relevant changes\n const prevOptions = usePrevious(options);\n React.useEffect(() => {\n if (!ctx.elements) {\n return;\n }\n\n const updates = extractAllowedOptionsUpdates(options, prevOptions, ['clientSecret', 'fonts']);\n\n if (updates) {\n ctx.elements.update(updates);\n }\n }, [options, prevOptions, ctx.elements]);\n\n return <ElementsContext.Provider value={ctx}>{children}</ElementsContext.Provider>;\n}) as FunctionComponent<PropsWithChildren<ElementsProps>>;\n\nconst useElementsContextWithUseCase = (useCaseMessage: string): ElementsContextValue => {\n const ctx = React.useContext(ElementsContext);\n return parseElementsContext(ctx, useCaseMessage);\n};\n\nconst useElements = (): StripeElements | null => {\n const { elements } = useElementsContextWithUseCase('calls useElements()');\n return elements;\n};\n\nconst INVALID_STRIPE_ERROR =\n 'Invalid prop `stripe` supplied to `Elements`. We recommend using the `loadStripe` utility from `@stripe/stripe-js`. See https://stripe.com/docs/stripe-js/react#elements-props-stripe for details.';\n\n// We are using types to enforce the `stripe` prop in this lib, but in a real\n// integration `stripe` could be anything, so we need to do some sanity\n// validation to prevent type errors.\nconst validateStripe = (maybeStripe: unknown, errorMsg = INVALID_STRIPE_ERROR): null | Stripe => {\n if (maybeStripe === null || isStripe(maybeStripe)) {\n return maybeStripe;\n }\n\n throw new Error(errorMsg);\n};\n\ntype ParsedStripeProp =\n | { tag: 'empty' }\n | { tag: 'sync'; stripe: Stripe }\n | { tag: 'async'; stripePromise: Promise<Stripe | null> };\n\nconst parseStripeProp = (raw: unknown, errorMsg = INVALID_STRIPE_ERROR): ParsedStripeProp => {\n if (isPromise(raw)) {\n return {\n tag: 'async',\n stripePromise: Promise.resolve(raw).then(result => validateStripe(result, errorMsg)),\n };\n }\n\n const stripe = validateStripe(raw, errorMsg);\n\n if (stripe === null) {\n return { tag: 'empty' };\n }\n\n return { tag: 'sync', stripe };\n};\n\nconst isUnknownObject = (raw: unknown): raw is { [key in PropertyKey]: unknown } => {\n return raw !== null && typeof raw === 'object';\n};\n\nconst isPromise = (raw: unknown): raw is PromiseLike<unknown> => {\n return isUnknownObject(raw) && typeof raw.then === 'function';\n};\n\n// We are using types to enforce the `stripe` prop in this lib,\n// but in an untyped integration `stripe` could be anything, so we need\n// to do some sanity validation to prevent type errors.\nconst isStripe = (raw: unknown): raw is Stripe => {\n return (\n isUnknownObject(raw) &&\n typeof raw.elements === 'function' &&\n typeof raw.createToken === 'function' &&\n typeof raw.createPaymentMethod === 'function' &&\n typeof raw.confirmCardPayment === 'function'\n );\n};\n\nconst extractAllowedOptionsUpdates = (\n options: unknown | void,\n prevOptions: unknown | void,\n immutableKeys: string[],\n): UnknownOptions | null => {\n if (!isUnknownObject(options)) {\n return null;\n }\n\n return Object.keys(options).reduce((newOptions: null | UnknownOptions, key) => {\n const isUpdated = !isUnknownObject(prevOptions) || !isEqual(options[key], prevOptions[key]);\n\n if (immutableKeys.includes(key)) {\n if (isUpdated) {\n console.warn(`Unsupported prop change: options.${key} is not a mutable property.`);\n }\n\n return newOptions;\n }\n\n if (!isUpdated) {\n return newOptions;\n }\n\n return { ...(newOptions || {}), [key]: options[key] };\n }, null);\n};\n\nconst PLAIN_OBJECT_STR = '[object Object]';\n\nconst isEqual = (left: unknown, right: unknown): boolean => {\n if (!isUnknownObject(left) || !isUnknownObject(right)) {\n return left === right;\n }\n\n const leftArray = Array.isArray(left);\n const rightArray = Array.isArray(right);\n\n if (leftArray !== rightArray) {\n return false;\n }\n\n const leftPlainObject = Object.prototype.toString.call(left) === PLAIN_OBJECT_STR;\n const rightPlainObject = Object.prototype.toString.call(right) === PLAIN_OBJECT_STR;\n\n if (leftPlainObject !== rightPlainObject) {\n return false;\n }\n\n // not sure what sort of special object this is (regexp is one option), so\n // fallback to reference check.\n if (!leftPlainObject && !leftArray) {\n return left === right;\n }\n\n const leftKeys = Object.keys(left);\n const rightKeys = Object.keys(right);\n\n if (leftKeys.length !== rightKeys.length) {\n return false;\n }\n\n const keySet: { [key: string]: boolean } = {};\n for (let i = 0; i < leftKeys.length; i += 1) {\n keySet[leftKeys[i]] = true;\n }\n for (let i = 0; i < rightKeys.length; i += 1) {\n keySet[rightKeys[i]] = true;\n }\n const allKeys = Object.keys(keySet);\n if (allKeys.length !== leftKeys.length) {\n return false;\n }\n\n const l = left;\n const r = right;\n const pred = (key: string): boolean => {\n return isEqual(l[key], r[key]);\n };\n\n return allKeys.every(pred);\n};\n\nconst useStripe = (): Stripe | null => {\n const { stripe } = useElementsOrCheckoutSdkContextWithUseCase('calls useStripe()');\n return stripe;\n};\n\nconst useElementsOrCheckoutSdkContextWithUseCase = (useCaseString: string): ElementsContextValue => {\n const elementsContext = React.useContext(ElementsContext);\n\n return parseElementsContext(elementsContext, useCaseString);\n};\n\ntype UnknownCallback = (...args: unknown[]) => any;\n\ninterface PrivateElementProps {\n id?: string;\n className?: string;\n fallback?: ReactNode;\n onChange?: UnknownCallback;\n onBlur?: UnknownCallback;\n onFocus?: UnknownCallback;\n onEscape?: UnknownCallback;\n onReady?: UnknownCallback;\n onClick?: UnknownCallback;\n onLoadError?: UnknownCallback;\n onLoaderStart?: UnknownCallback;\n onNetworksChange?: UnknownCallback;\n onConfirm?: UnknownCallback;\n onCancel?: UnknownCallback;\n onShippingAddressChange?: UnknownCallback;\n onShippingRateChange?: UnknownCallback;\n options?: UnknownOptions;\n}\n\nconst capitalized = (str: string) => str.charAt(0).toUpperCase() + str.slice(1);\n\nconst createElementComponent = (type: StripeElementType, isServer: boolean): FunctionComponent<ElementProps> => {\n const displayName = `${capitalized(type)}Element`;\n\n const ClientElement: FunctionComponent<PrivateElementProps> = ({\n id,\n className,\n fallback,\n options = {},\n onBlur,\n onFocus,\n onReady,\n onChange,\n onEscape,\n onClick,\n onLoadError,\n onLoaderStart,\n onNetworksChange,\n onConfirm,\n onCancel,\n onShippingAddressChange,\n onShippingRateChange,\n }) => {\n const ctx = useElementsOrCheckoutSdkContextWithUseCase(`mounts <${displayName}>`);\n const elements = 'elements' in ctx ? ctx.elements : null;\n const [element, setElement] = React.useState<StripeElement | null>(null);\n const elementRef = React.useRef<StripeElement | null>(null);\n const domNode = React.useRef<HTMLDivElement | null>(null);\n const [isReady, setReady] = useState(false);\n\n // For every event where the merchant provides a callback, call element.on\n // with that callback. If the merchant ever changes the callback, removes\n // the old callback with element.off and then call element.on with the new one.\n useAttachEvent(element, 'blur', onBlur);\n useAttachEvent(element, 'focus', onFocus);\n useAttachEvent(element, 'escape', onEscape);\n useAttachEvent(element, 'click', onClick);\n useAttachEvent(element, 'loaderror', onLoadError);\n useAttachEvent(element, 'loaderstart', onLoaderStart);\n useAttachEvent(element, 'networkschange', onNetworksChange);\n useAttachEvent(element, 'confirm', onConfirm);\n useAttachEvent(element, 'cancel', onCancel);\n useAttachEvent(element, 'shippingaddresschange', onShippingAddressChange);\n useAttachEvent(element, 'shippingratechange', onShippingRateChange);\n useAttachEvent(element, 'change', onChange);\n\n let readyCallback: UnknownCallback | undefined;\n if (onReady) {\n // For other Elements, pass through the Element itself.\n readyCallback = () => {\n setReady(true);\n onReady(element);\n };\n }\n\n useAttachEvent(element, 'ready', readyCallback);\n\n React.useLayoutEffect(() => {\n if (elementRef.current === null && domNode.current !== null && elements) {\n let newElement: StripeElement | null = null;\n if (elements) {\n newElement = elements.create(type as any, options);\n }\n\n // Store element in a ref to ensure it's _immediately_ available in cleanup hooks in StrictMode\n elementRef.current = newElement;\n // Store element in state to facilitate event listener attachment\n setElement(newElement);\n\n if (newElement) {\n newElement.mount(domNode.current);\n }\n }\n }, [elements, options]);\n\n const prevOptions = usePrevious(options);\n React.useEffect(() => {\n if (!elementRef.current) {\n return;\n }\n\n const updates = extractAllowedOptionsUpdates(options, prevOptions, ['paymentRequest']);\n\n if (updates && 'update' in elementRef.current) {\n elementRef.current.update(updates);\n }\n }, [options, prevOptions]);\n\n React.useLayoutEffect(() => {\n return () => {\n if (elementRef.current && typeof elementRef.current.destroy === 'function') {\n try {\n elementRef.current.destroy();\n elementRef.current = null;\n } catch {\n // Do nothing\n }\n }\n };\n }, []);\n\n return (\n <>\n {!isReady && fallback}\n <div\n id={id}\n style={{\n height: isReady ? 'unset' : '0px',\n visibility: isReady ? 'visible' : 'hidden',\n }}\n className={className}\n ref={domNode}\n />\n </>\n );\n };\n\n // Only render the Element wrapper in a server environment.\n const ServerElement: FunctionComponent<PrivateElementProps> = props => {\n useElementsOrCheckoutSdkContextWithUseCase(`mounts <${displayName}>`);\n const { id, className } = props;\n return (\n <div\n id={id}\n className={className}\n />\n );\n };\n\n const Element = isServer ? ServerElement : ClientElement;\n Element.displayName = displayName;\n (Element as any).__elementType = type;\n\n return Element as FunctionComponent<ElementProps>;\n};\n\nconst isServer = typeof window === 'undefined';\nconst PaymentElement: FunctionComponent<\n PaymentElementProps & {\n fallback?: ReactNode;\n }\n> = createElementComponent('payment', isServer);\n\nexport { Elements, PaymentElement, useElements, useStripe };\n","import { useEffect } from 'react';\nimport useSWRMutation from 'swr/mutation';\n\nimport type { BillingInitializedPaymentMethodResource, ForPayerType } from '../../types';\nimport { useOrganizationContext, useUserContext } from '../contexts';\n\ntype InitializePaymentMethodOptions = {\n for?: ForPayerType;\n};\n\nexport type UseInitializePaymentMethodResult = {\n initializedPaymentMethod: BillingInitializedPaymentMethodResource | undefined;\n initializePaymentMethod: () => Promise<BillingInitializedPaymentMethodResource | undefined>;\n};\n\n/**\n * This is the existing implementation of the payment method initializer using SWR.\n * It is kept here for backwards compatibility until our next major version.\n *\n * @internal\n */\nfunction useInitializePaymentMethod(options?: InitializePaymentMethodOptions): UseInitializePaymentMethodResult {\n const { for: forType = 'user' } = options ?? {};\n const { organization } = useOrganizationContext();\n const user = useUserContext();\n\n const resource = forType === 'organization' ? organization : user;\n\n const { data, trigger } = useSWRMutation(\n resource?.id\n ? {\n key: 'billing-payment-method-initialize',\n resourceId: resource.id,\n for: forType,\n }\n : null,\n () => {\n return resource?.initializePaymentMethod({\n gateway: 'stripe',\n });\n },\n );\n\n useEffect(() => {\n if (!resource?.id) {\n return;\n }\n\n trigger().catch(() => {\n // ignore errors\n });\n }, [resource?.id, trigger]);\n\n return {\n initializedPaymentMethod: data,\n initializePaymentMethod: trigger,\n };\n}\n\nexport { useInitializePaymentMethod as __internal_useInitializePaymentMethod };\n","import type { loadStripe } from '@stripe/stripe-js';\n\nimport { useSWR } from '../clerk-swr';\nimport { useClerk } from '../hooks/useClerk';\n\ntype LoadStripeFn = typeof loadStripe;\n\ntype StripeClerkLibs = {\n loadStripe: LoadStripeFn;\n};\n\nexport type UseStripeClerkLibsResult = StripeClerkLibs | null;\n\n/**\n * This is the existing implementation of the Stripe libraries loader using SWR.\n * It is kept here for backwards compatibility until our next major version.\n *\n * @internal\n */\nfunction useStripeClerkLibs(): UseStripeClerkLibsResult {\n const clerk = useClerk();\n\n const swr = useSWR(\n 'clerk-stripe-sdk',\n async () => {\n const loadStripe = (await clerk.__internal_loadStripeJs()) as LoadStripeFn;\n return { loadStripe };\n },\n {\n keepPreviousData: true,\n revalidateOnFocus: false,\n dedupingInterval: Infinity,\n },\n );\n\n return swr.data ?? null;\n}\n\nexport { useStripeClerkLibs as __internal_useStripeClerkLibs };\n","import type { Stripe } from '@stripe/stripe-js';\n\nimport { useSWR } from '../clerk-swr';\nimport type { UseStripeClerkLibsResult } from './useStripeClerkLibs';\n\ntype StripeLoaderOptions = {\n stripeClerkLibs: UseStripeClerkLibsResult;\n externalGatewayId?: string;\n stripePublishableKey?: string;\n};\n\nexport type UseStripeLoaderResult = Stripe | null | undefined;\n\n/**\n * This is the existing implementation of the Stripe instance loader using SWR.\n * It is kept here for backwards compatibility until our next major version.\n *\n * @internal\n */\nfunction useStripeLoader(options: StripeLoaderOptions): UseStripeLoaderResult {\n const { stripeClerkLibs, externalGatewayId, stripePublishableKey } = options;\n\n const swr = useSWR(\n stripeClerkLibs && externalGatewayId && stripePublishableKey\n ? {\n key: 'stripe-sdk',\n externalGatewayId,\n stripePublishableKey,\n }\n : null,\n ({ stripePublishableKey, externalGatewayId }) => {\n return stripeClerkLibs?.loadStripe(stripePublishableKey, {\n stripeAccount: externalGatewayId,\n });\n },\n {\n keepPreviousData: true,\n revalidateOnFocus: false,\n dedupingInterval: 1_000 * 60,\n },\n );\n\n return swr.data;\n}\n\nexport { useStripeLoader as __internal_useStripeLoader };\n","import type { Stripe, StripeElements, StripeElementsOptions } from '@stripe/stripe-js';\nimport React, { type PropsWithChildren, type ReactNode, useCallback, useMemo, useState } from 'react';\n\nimport type { BillingCheckoutResource, CheckoutFlowResource, EnvironmentResource, ForPayerType } from '../../types';\nimport { createContextAndHook } from '../hooks/createContextAndHook';\nimport type { useCheckout } from '../hooks/useCheckout';\nimport { useClerk } from '../hooks/useClerk';\nimport { Elements, PaymentElement as StripePaymentElement, useElements, useStripe } from '../stripe-react';\nimport {\n __internal_useInitializePaymentMethod as useInitializePaymentMethod,\n type UseInitializePaymentMethodResult,\n} from './useInitializePaymentMethod';\nimport { __internal_useStripeClerkLibs as useStripeClerkLibs } from './useStripeClerkLibs';\nimport { __internal_useStripeLoader as useStripeLoader, type UseStripeLoaderResult } from './useStripeLoader';\n\ntype PaymentElementError = {\n gateway: 'stripe';\n error: {\n /**\n * For some errors that could be handled programmatically, a short string indicating the [error code](https://stripe.com/docs/error-codes) reported.\n */\n code?: string;\n message?: string;\n type: string;\n };\n};\n\nconst useInternalEnvironment = () => {\n const clerk = useClerk();\n // @ts-expect-error `__internal_environment` is not typed\n return clerk.__internal_environment as unknown as EnvironmentResource | null | undefined;\n};\n\nconst useLocalization = () => {\n const clerk = useClerk();\n\n let locale = 'en';\n try {\n const localization = clerk.__internal_getOption('localization');\n locale = localization?.locale || 'en';\n } catch {\n // ignore errors\n }\n\n // Normalize locale to 2-letter language code for Stripe compatibility\n const normalizedLocale = locale.split('-')[0];\n\n return normalizedLocale;\n};\n\nconst usePaymentSourceUtils = (forResource: ForPayerType = 'user') => {\n const stripeClerkLibs = useStripeClerkLibs();\n const environment = useInternalEnvironment();\n\n const { initializedPaymentMethod, initializePaymentMethod }: UseInitializePaymentMethodResult =\n useInitializePaymentMethod({ for: forResource });\n\n const stripePublishableKey = environment?.commerceSettings.billing.stripePublishableKey ?? undefined;\n\n const stripe: UseStripeLoaderResult = useStripeLoader({\n stripeClerkLibs,\n externalGatewayId: initializedPaymentMethod?.externalGatewayId,\n stripePublishableKey,\n });\n\n const externalClientSecret = initializedPaymentMethod?.externalClientSecret;\n const paymentMethodOrder = initializedPaymentMethod?.paymentMethodOrder;\n\n return {\n stripe,\n initializePaymentMethod,\n externalClientSecret,\n paymentMethodOrder,\n };\n};\n\ntype internalStripeAppearance = {\n colorPrimary: string;\n colorBackground: string;\n colorText: string;\n colorTextSecondary: string;\n colorSuccess: string;\n colorDanger: string;\n colorWarning: string;\n fontWeightNormal: string;\n fontWeightMedium: string;\n fontWeightBold: string;\n fontSizeXl: string;\n fontSizeLg: string;\n fontSizeSm: string;\n fontSizeXs: string;\n borderRadius: string;\n spacingUnit: string;\n};\n\n/**\n * @interface\n */\nexport type PaymentElementProviderProps = {\n /**\n * An optional checkout resource object. When provided, the payment element is scoped to the specific checkout session.\n */\n checkout?: CheckoutFlowResource | BillingCheckoutResource | ReturnType<typeof useCheckout>['checkout'];\n /**\n * An optional object to customize the appearance of the Stripe Payment Element. This allows you to match the form's styling to your application's theme.\n */\n stripeAppearance?: internalStripeAppearance;\n /**\n * Specifies whether to fetch for the current user or Organization.\n *\n * @default 'user'\n */\n for?: ForPayerType;\n /**\n * An optional description to display to the user within the payment element UI.\n */\n paymentDescription?: string;\n};\n\nconst [PaymentElementContext, usePaymentElementContext] = createContextAndHook<\n ReturnType<typeof usePaymentSourceUtils> &\n PaymentElementProviderProps & {\n setIsPaymentElementReady: (isPaymentElementReady: boolean) => void;\n isPaymentElementReady: boolean;\n }\n>('PaymentElementContext');\n\nconst [StripeUtilsContext, useStripeUtilsContext] = createContextAndHook<{\n stripe: Stripe | undefined | null;\n elements: StripeElements | undefined | null;\n}>('StripeUtilsContext');\n\nconst ValidateStripeUtils = ({ children }: PropsWithChildren) => {\n const stripe = useStripe();\n const elements = useElements();\n\n return <StripeUtilsContext.Provider value={{ value: { stripe, elements } }}>{children}</StripeUtilsContext.Provider>;\n};\n\nconst DummyStripeUtils = ({ children }: PropsWithChildren) => {\n return <StripeUtilsContext.Provider value={{ value: {} as any }}>{children}</StripeUtilsContext.Provider>;\n};\n\nconst PropsProvider = ({ children, ...props }: PropsWithChildren<PaymentElementProviderProps>) => {\n const utils = usePaymentSourceUtils(props.for);\n const [isPaymentElementReady, setIsPaymentElementReady] = useState(false);\n return (\n <PaymentElementContext.Provider\n value={{\n value: {\n ...props,\n ...utils,\n setIsPaymentElementReady,\n isPaymentElementReady,\n },\n }}\n >\n {children}\n </PaymentElementContext.Provider>\n );\n};\n\nconst PaymentElementProvider = ({ children, ...props }: PropsWithChildren<PaymentElementProviderProps>) => {\n return (\n <PropsProvider {...props}>\n <PaymentElementInternalRoot>{children}</PaymentElementInternalRoot>\n </PropsProvider>\n );\n};\n\nconst PaymentElementInternalRoot = (props: PropsWithChildren) => {\n const { stripe, externalClientSecret, stripeAppearance } = usePaymentElementContext();\n const locale = useLocalization();\n\n if (stripe && externalClientSecret) {\n return (\n <Elements\n // This key is used to reset the payment intent, since Stripe doesn't provide a way to reset the payment intent.\n key={externalClientSecret}\n stripe={stripe}\n options={{\n loader: 'never',\n clientSecret: externalClientSecret,\n appearance: {\n variables: stripeAppearance,\n },\n locale: locale as StripeElementsOptions['locale'],\n }}\n >\n <ValidateStripeUtils>{props.children}</ValidateStripeUtils>\n </Elements>\n );\n }\n\n return <DummyStripeUtils>{props.children}</DummyStripeUtils>;\n};\n\n/**\n * @interface\n */\nexport type PaymentElementProps = {\n /**\n * Optional fallback content, such as a loading skeleton, to display while the payment form is being initialized.\n */\n fallback?: ReactNode;\n};\n\nconst PaymentElement = ({ fallback }: PaymentElementProps) => {\n const {\n setIsPaymentElementReady,\n paymentMethodOrder,\n checkout,\n stripe,\n externalClientSecret,\n paymentDescription,\n for: _for,\n } = usePaymentElementContext();\n const environment = useInternalEnvironment();\n\n const applePay = useMemo(() => {\n if (!checkout || !checkout.totals || !checkout.plan) {\n return undefined;\n }\n\n return {\n recurringPaymentRequest: {\n paymentDescription: paymentDescription || '',\n managementURL:\n _for === 'organization'\n ? environment?.displayConfig.organizationProfileUrl || ''\n : environment?.displayConfig.userProfileUrl || '',\n regularBilling: {\n amount: checkout.totals.totalDueNow?.amount || checkout.totals.grandTotal.amount,\n label: checkout.plan.name,\n recurringPaymentIntervalUnit: checkout.planPeriod === 'annual' ? 'year' : 'month',\n },\n },\n } as const;\n }, [checkout, paymentDescription, _for, environment]);\n\n const options = useMemo(() => {\n return {\n layout: {\n type: 'tabs',\n defaultCollapsed: false,\n },\n paymentMethodOrder,\n applePay,\n } as const;\n }, [applePay, paymentMethodOrder]);\n\n const onReady = useCallback(() => {\n setIsPaymentElementReady(true);\n }, [setIsPaymentElementReady]);\n\n if (!stripe || !externalClientSecret) {\n return <>{fallback}</>;\n }\n\n return (\n <StripePaymentElement\n fallback={fallback}\n onReady={onReady}\n options={options}\n />\n );\n};\n\nconst throwLibsMissingError = () => {\n throw new Error(\n 'Clerk: Unable to submit, Stripe libraries are not yet loaded. Be sure to check `isFormReady` before calling `submit`.',\n );\n};\n\n/**\n * @interface\n */\nexport type UsePaymentElementReturn = {\n /**\n * A function that submits the payment form data to the payment provider. It returns a promise that resolves with either a `data` object containing a payment token on success, or an `error` object on failure.\n */\n submit: () => Promise<\n | {\n data: { gateway: 'stripe'; paymentToken: string };\n error: null;\n }\n | {\n data: null;\n error: PaymentElementError;\n }\n >;\n /**\n * A function that resets the payment form to its initial, empty state.\n */\n reset: () => Promise<void>;\n /**\n * A boolean that indicates if the payment form UI has been rendered and is ready for user input. This is useful for disabling a submit button until the form is interactive.\n */\n isFormReady: boolean;\n} & (\n | {\n /**\n * An object containing information about the initialized payment provider. It is `undefined` until `isProviderReady` is `true`.\n */\n provider: {\n name: 'stripe';\n };\n /**\n * A boolean that indicates if the underlying payment provider (e.g. Stripe) has been fully initialized.\n */\n isProviderReady: true;\n }\n | {\n provider: undefined;\n isProviderReady: false;\n }\n);\n\nconst usePaymentElement = (): UsePaymentElementReturn => {\n const { isPaymentElementReady, initializePaymentMethod } = usePaymentElementContext();\n const { stripe, elements } = useStripeUtilsContext();\n const { externalClientSecret } = usePaymentElementContext();\n\n const submit = useCallback(async () => {\n if (!stripe || !elements) {\n return throwLibsMissingError();\n }\n\n const { setupIntent, error } = await stripe.confirmSetup({\n elements,\n confirmParams: {\n return_url: window.location.href,\n },\n redirect: 'if_required',\n });\n if (error) {\n return {\n data: null,\n error: {\n gateway: 'stripe',\n error: {\n code: error.code,\n message: error.message,\n type: error.type,\n },\n },\n } as const;\n }\n return {\n data: { gateway: 'stripe', paymentToken: setupIntent.payment_method as string },\n error: null,\n } as const;\n }, [stripe, elements]);\n\n const reset = useCallback(async () => {\n if (!stripe || !elements) {\n return throwLibsMissingError();\n }\n\n await initializePaymentMethod();\n }, [stripe, elements, initializePaymentMethod]);\n\n const isProviderReady = Boolean(stripe && externalClientSecret);\n\n if (!isProviderReady) {\n return {\n submit: throwLibsMissingError,\n reset: throwLibsMissingError,\n isFormReady: false,\n provider: undefined,\n isProviderReady: false,\n };\n }\n return {\n submit,\n reset,\n isFormReady: isPaymentElementReady,\n provider: {\n name: 'stripe',\n },\n isProviderReady: isProviderReady,\n };\n};\n\nexport {\n PaymentElement as __experimental_PaymentElement,\n PaymentElementProvider as __experimental_PaymentElementProvider,\n usePaymentElement as __experimental_usePaymentElement,\n};\n","/**\n * PortalRootManager manages a stack of portal root containers.\n * This allows PortalProvider to work across separate React trees\n * (e.g., when Clerk modals are rendered in a different tree via Components.tsx).\n */\nclass PortalRootManager {\n private stack: Array<() => HTMLElement | null> = [];\n\n /**\n * Push a new portal root getter onto the stack.\n * @param getContainer Function that returns the container element\n */\n push(getContainer: () => HTMLElement | null): void {\n this.stack.push(getContainer);\n }\n\n /**\n * Pop the most recent portal root from the stack.\n */\n pop(): void {\n this.stack.pop();\n }\n\n /**\n * Get the current (topmost) portal root container.\n * @returns The container element or null if no provider is active\n */\n getCurrent(): HTMLElement | null {\n if (this.stack.length === 0) {\n return null;\n }\n const getContainer = this.stack[this.stack.length - 1];\n return getContainer();\n }\n}\n\nexport const portalRootManager = new PortalRootManager();\n","'use client';\n\nimport React, { useEffect, useRef } from 'react';\n\nimport { createContextAndHook } from './hooks/createContextAndHook';\nimport { portalRootManager } from './portal-root-manager';\n\ntype PortalProviderProps = React.PropsWithChildren<{\n /**\n * Function that returns the container element where portals should be rendered.\n * This allows Clerk components to render inside external dialogs/popovers\n * (e.g., Radix Dialog, React Aria Components) instead of document.body.\n */\n getContainer: () => HTMLElement | null;\n}>;\n\nconst [PortalContext, , usePortalContextWithoutGuarantee] = createContextAndHook<{\n getContainer: () => HTMLElement | null;\n}>('PortalProvider');\n\n/**\n * PortalProvider allows you to specify a custom container for all Clerk floating UI elements\n * (popovers, modals, tooltips, etc.) that use portals.\n *\n * This is particularly useful when using Clerk components inside external UI libraries\n * like Radix Dialog or React Aria Components, where portaled elements need to render\n * within the dialog's container to remain interactable.\n *\n * @example\n * ```tsx\n * function Example() {\n * const containerRef = useRef(null);\n * return (\n * <RadixDialog ref={containerRef}>\n * <PortalProvider getContainer={() => containerRef.current}>\n * <UserButton />\n * </PortalProvider>\n * </RadixDialog>\n * );\n * }\n * ```\n */\nexport const UNSAFE_PortalProvider = ({ children, getContainer }: PortalProviderProps) => {\n const getContainerRef = useRef(getContainer);\n getContainerRef.current = getContainer;\n\n // Register with the manager for cross-tree access (e.g., modals in Components.tsx)\n useEffect(() => {\n const getContainerWrapper = () => getContainerRef.current();\n portalRootManager.push(getContainerWrapper);\n return () => {\n portalRootManager.pop();\n };\n }, []);\n\n // Provide context for same-tree access (e.g., UserButton popover)\n const contextValue = React.useMemo(() => ({ value: { getContainer } }), [getContainer]);\n\n return <PortalContext.Provider value={contextValue}>{children}</PortalContext.Provider>;\n};\n\n/**\n * Hook to get the current portal root container.\n * First checks React context (for same-tree components),\n * then falls back to PortalRootManager (for cross-tree like modals).\n */\nexport const usePortalRoot = (): (() => HTMLElement | null) => {\n // Try to get from context first (for components in the same React tree)\n const contextValue = usePortalContextWithoutGuarantee();\n\n if (contextValue && 'getContainer' in contextValue && contextValue.getContainer) {\n return contextValue.getContainer;\n }\n\n // Fall back to manager (for components in different React trees, like modals)\n return portalRootManager.getCurrent.bind(portalRootManager);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQA,SAAgB,oB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