@clerk/shared
Version:
Internal package utils used by the Clerk SDKs
1,142 lines (1,141 loc) • 114 kB
text/typescript
import { ClerkGlobalHookError } from "../errors/globalHookError.mjs";
import { ClerkUIConstructor } from "../ui/types.mjs";
import { ClerkPaginationParams } from "./pagination.mjs";
import { Autocomplete, DeepPartial, DeepSnakeToCamel, Without } from "./utils.mjs";
import { BillingCheckoutResource, BillingNamespace, BillingPlanResource, BillingSubscriptionPlanPeriod, CheckoutFlowResource, ForPayerType } from "./billing.mjs";
import { OAuthProvider, OAuthScope } from "./oauth.mjs";
import { Web3Strategy } from "./strategies.mjs";
import { AfterMultiSessionSingleSignOutUrl, AfterSignOutUrl, NewSubscriptionRedirectUrl, RedirectOptions, RedirectUrlProp, SignInFallbackRedirectUrl, SignInForceRedirectUrl, SignUpFallbackRedirectUrl, SignUpForceRedirectUrl } from "./redirects.mjs";
import { ClerkAPIResponseError } from "./errors.mjs";
import { SignInResource } from "./signIn.mjs";
import { ClientJSONSnapshot, EnvironmentJSONSnapshot } from "./snapshots.mjs";
import { SessionVerificationLevel } from "./sessionVerification.mjs";
import { UserResource } from "./user.mjs";
import { SessionResource, SessionTask, SignedInSessionResource } from "./session.mjs";
import { OrganizationResource } from "./organization.mjs";
import { OrganizationCustomRoleKey } from "./organizationMembership.mjs";
import { DisplayThemeJSON } from "./json.mjs";
import { SignUpResource } from "./signUp.mjs";
import { ClientResource } from "./client.mjs";
import { CustomMenuItem } from "./customMenuItems.mjs";
import { CustomPage } from "./customPages.mjs";
import { InstanceType } from "./instance.mjs";
import { LocalizationResource } from "./localization.mjs";
import { DomainOrProxyUrl, MultiDomainAndOrProxy } from "./multiDomain.mjs";
import { OAuthApplicationNamespace } from "./oauthApplication.mjs";
import { OAuthTransport } from "./oauthTransport.mjs";
import { JoinWaitlistParams, WaitlistResource } from "./waitlist.mjs";
import { State } from "./state.mjs";
import { TelemetryCollector } from "./telemetry.mjs";
import { APIKeysNamespace } from "./apiKeys.mjs";
//#region src/types/clerk.d.ts
/**
* Global appearance type registry that can be augmented by packages that depend on `@clerk/ui`.
* Framework packages (like `@clerk/react`, `@clerk/nextjs`) should augment this interface
* to provide proper appearance types without creating circular dependencies.
*/
declare global {
interface ClerkAppearanceRegistry {}
}
/**
* Appearance theme type that gets overridden by framework packages.
* Defaults to `any` in @clerk/shared.
* Becomes fully typed when a framework package augments ClerkAppearanceRegistry with Theme.
*/
type ClerkAppearanceTheme = ClerkAppearanceRegistry['theme'];
type __experimental_CheckoutStatus = 'needs_initialization' | 'needs_confirmation' | 'completed';
type __experimental_CheckoutCacheState = Readonly<{
isStarting: boolean;
isConfirming: boolean;
error: ClerkAPIResponseError | null;
checkout: BillingCheckoutResource | null;
fetchStatus: 'idle' | 'fetching' | 'error';
status: __experimental_CheckoutStatus;
}>;
type __experimental_CheckoutOptions = {
for?: ForPayerType;
planPeriod: BillingSubscriptionPlanPeriod;
planId: string;
seatsQuantity?: number;
priceId?: string;
};
type CheckoutErrors = {
/**
* The raw, unparsed errors from the Clerk API.
*/
raw: unknown[] | null;
/**
* Parsed errors that are not related to any specific field.
* Does not include any errors that could be parsed as a field error
*/
global: ClerkGlobalHookError[] | null;
};
/**
* @interface
*/
interface CheckoutSignalValue {
/**
* Represents the errors that occurred during the last fetch of the parent resource.
*/
errors: CheckoutErrors;
/**
* The fetch status of the underlying `Checkout` resource.
*/
fetchStatus: 'idle' | 'fetching';
/**
* An instance representing the currently active `Checkout`.
*/
checkout: CheckoutFlowResource;
}
interface CheckoutSignal {
(): CheckoutSignalValue;
}
type __experimental_CheckoutFunction = (options: __experimental_CheckoutOptions) => CheckoutSignalValue;
/**
* @inline
*/
type SDKMetadata = {
/**
* The npm package name of the SDK.
*/
name: string;
/**
* The npm package version of the SDK.
*/
version: string;
/**
* Typically this will be the `NODE_ENV` that the SDK is currently running in.
*/
environment?: string;
};
/**
* A callback function that is called when Clerk resources change.
* @inline
*/
type ListenerCallback = (emission: Resources) => void;
/**
* Optional configuration for the `addListener()` method.
* @param skipInitialEmit - If `true`, the callback will not be called immediately after registration. Defaults to `false`.
* @inline
*/
type ListenerOptions = {
skipInitialEmit?: boolean;
};
type UnsubscribeCallback = () => void;
/**
* A function to decorate URLs for Safari ITP workaround.
*
* Safari's Intelligent Tracking Prevention (ITP) caps cookies set via fetch/XHR requests to 7 days.
* This function returns a URL that goes through the `/v1/client/touch` endpoint when the ITP fix is needed,
* allowing the cookie to be refreshed via a full page navigation.
*
* @param url - The destination URL to potentially decorate
* @returns The decorated URL if ITP fix is needed, otherwise the original URL unchanged
*
* @example
* ```typescript
* const url = decorateUrl('/dashboard');
* // When ITP fix is needed: 'https://clerk.example.com/v1/client/touch?redirect_url=https://app.example.com/dashboard'
* // When not needed: '/dashboard'
*
* // decorateUrl may return an external URL when Safari ITP fix is needed
* if (url.startsWith('https')) {
* window.location.href = url; // External redirect
* } else {
* router.push(url); // Client-side navigation
* }
* ```
*/
type DecorateUrl = (url: string) => string;
type SetActiveNavigate = (params: {
session: SessionResource;
/**
* Decorate the destination URL to enable Safari ITP cookie refresh when needed.
*
* @see {@link DecorateUrl}
*/
decorateUrl: DecorateUrl;
}) => void | Promise<unknown>;
/**
* A callback that runs after sign out completes.
* @inline */
type SignOutCallback = () => void | Promise<any>;
/**
* Configuration options.
*/
type SignOutOptions = {
/**
* Specify a specific session to sign out. Useful for multi-session applications.
*/
sessionId?: string;
/**
* Specify a redirect URL to navigate to after sign-out is complete.
*/
redirectUrl?: string;
};
/**
* @inline
*/
interface SignOut {
(options?: SignOutOptions): Promise<void>;
(signOutCallback?: SignOutCallback, options?: SignOutOptions): Promise<void>;
}
type ClerkEvent = keyof ClerkEventPayload;
type EventHandler<E extends ClerkEvent> = (payload: ClerkEventPayload[E]) => void;
type ClerkEventPayload = {
status: ClerkStatus;
};
/**
* Registers an event listener for a specific Clerk event.
*
* @param event - The event name to subscribe to.
* @param handler - The callback function to execute when the event is dispatched.
* @param opt - Optional configuration.
* @param opt.notify - If true and the event was previously dispatched, handler will be called immediately with the latest payload.
*/
type OnEventListener = <E extends ClerkEvent>(event: E, handler: EventHandler<E>, opt?: {
notify: boolean;
}) => void;
/**
* Unregisters an event listener for a specific Clerk event.
*
* @param event - The event name to unsubscribe from.
* @param handler - The callback function to remove.
*/
type OffEventListener = <E extends ClerkEvent>(event: E, handler: EventHandler<E>) => void;
/**
* @inline
*/
type ClerkStatus = 'degraded' | 'error' | 'loading' | 'ready';
/**
* The `Clerk` class serves as the central interface for working with Clerk's authentication and user management functionality in your application. As a top-level class in the Clerk SDK, it provides access to key methods and properties for managing users, sessions, API keys, billing, organizations, and more.
*/
interface Clerk {
/**
* The Clerk SDK version number.
*/
version: string | undefined;
/**
* The version of `@clerk/ui` that is currently loaded, or `undefined` if the prebuilt UI has not been loaded yet.
*/
uiVersion: string | undefined;
/**
* If present, contains information about the SDK that the host application is using.
* For example, if Clerk is loaded through `@clerk/nextjs`, this would be `{ name: '@clerk/nextjs', version: '1.0.0' }`. You don't need to set this value yourself unless you're [developing an SDK](https://clerk.com/docs/guides/development/sdk-development/overview).
*/
sdkMetadata: SDKMetadata | undefined;
/**
* Indicates whether the `Clerk` object is ready for use. Set to `false` when the `status` is `"loading"`. Set to `true` when the `status` is `"ready"` or `"degraded"`.
*/
loaded: boolean;
/**
* The status of the `Clerk` instance. Possible values are:
* <ul>
* <li>`"error"`: Set when hotloading `clerk-js` or `Clerk.load()` failed.</li>
* <li>`"loading"`: Set during initialization.</li>
* <li>`"ready"`: Set when Clerk is fully operational.</li>
* <li>`"degraded"`: Set when Clerk is partially operational.</li>
* </ul>
*/
status: ClerkStatus;
/**
* @internal
*/
__internal_getOption<K extends keyof ClerkOptions>(key: K): ClerkOptions[K];
/**
* @internal
* Primary `window.location.href` navigation chokepoint for `@clerk/clerk-js` and `@clerk/ui`.
* By default the resolved URL is validated against the customer-supplied
* `allowedRedirectProtocols` option (static defaults ∪ the customer extension).
* Disallowed protocols and scheme-relative inputs (`//host`) are rejected with a console warning.
* Pass `useStaticAllowlistOnly: true` to opt out of the customer extension.
*/
__internal_windowNavigate: (to: URL | string, opts?: {
useStaticAllowlistOnly?: boolean;
}) => void;
frontendApi: string;
/** Your Clerk [Publishable Key](!publishable-key). */
publishableKey: string;
/** **Required for applications that run behind a reverse proxy**. Your Clerk app's proxy URL. Can be either a relative path (`/__clerk`) or a full URL (`https://<your-domain>/__clerk`). */
proxyUrl: string | undefined;
/** The current Clerk app's domain. Prefixed with `clerk.` on production if not already prefixed. Returns `""` when ran on the server. */
domain: string;
/** Indicates whether the instance is a satellite app. */
isSatellite: boolean;
/** Indicates whether the Clerk instance is running in a production or development environment. */
instanceType: InstanceType | undefined;
/**
* Indicates whether the instance is being loaded in a standard browser environment. Set to `false` on native platforms where cookies cannot be set. When `undefined`, Clerk assumes a standard browser.
* @inline
*/
isStandardBrowser: boolean | undefined;
/**
* Indicates whether the current user has a valid signed-in client session.
*/
isSignedIn: boolean;
/** The `Client` object for the current window. */
client: ClientResource | undefined;
/** The currently active `Session`, which is guaranteed to be one of the sessions in `Client.sessions`. If there is no active session, this field will be `null`. If the session is loading, this field will be `undefined`. */
session: SignedInSessionResource | null | undefined;
/** A shortcut to the last active `Session.user.organizationMemberships` which holds an instance of a `Organization` object. If the session is `null` or `undefined`, the user field will match. */
organization: OrganizationResource | null | undefined;
/** A shortcut to `Session.user` which holds the currently active `User` object. If the session is `null` or `undefined`, the user field will match. */
user: UserResource | null | undefined;
/**
* Last emitted resources, maintains a stable reference to the resources between emits.
*
* @internal
*/
__internal_lastEmittedResources: Resources | undefined;
/**
* Entrypoint for Clerk's Signal API containing resource signals along with accessible versions of `computed()` and
* `effect()` that can be used to subscribe to changes from Signals.
*
* @hidden
* @experimental This experimental API is subject to change.
*/
__internal_state: State;
/**
* The `Billing` object used for managing billing.
*
* @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.
*/
billing: BillingNamespace;
/**
* [Telemetry](https://clerk.com/docs/guides/how-clerk-works/security/clerk-telemetry) configuration.
*/
telemetry: TelemetryCollector | undefined;
/**
* @hidden
*/
__internal_country?: string | null;
/**
* Signs out the current user on single-session instances, or all users on multi-session instances.
*/
signOut: SignOut;
/**
* Opens the Clerk SignIn component in a modal.
*
* @param props - Optional sign in configuration parameters.
*/
openSignIn: (props?: SignInModalProps) => void;
/**
* Closes the Clerk SignIn modal.
*/
closeSignIn: () => void;
/**
* Opens the Clerk Checkout component in a drawer.
*
* @param props - Optional checkout configuration parameters.
* @hidden
*/
__internal_openCheckout: (props?: __internal_CheckoutProps) => void;
/**
* Closes the Clerk Checkout drawer.
* @hidden
*/
__internal_closeCheckout: () => void;
/**
* Opens the Clerk PlanDetails drawer component in a drawer.
*
* @param props - `plan` or `planId` parameters are required.
* @hidden
*/
__internal_openPlanDetails: (props: __internal_PlanDetailsProps) => void;
/**
* Closes the Clerk PlanDetails drawer.
* @hidden
*/
__internal_closePlanDetails: () => void;
/**
* Opens the Clerk SubscriptionDetails drawer component in a drawer.
*
* @param props - Optional configuration parameters.
* @hidden
*/
__internal_openSubscriptionDetails: (props?: __internal_SubscriptionDetailsProps) => void;
/**
* Closes the Clerk SubscriptionDetails drawer.
* @hidden
*/
__internal_closeSubscriptionDetails: () => void;
/**
* Opens the Clerk UserVerification component in a modal.
*
* @param props - Optional user verification configuration parameters.
* @hidden
*/
__internal_openReverification: (props?: __internal_UserVerificationModalProps) => void;
/**
* Closes the Clerk user verification modal.
* @hidden
*/
__internal_closeReverification: () => void;
/**
* Attempts to enable a environment setting from a development instance, prompting if disabled.
* @hidden
*/
__internal_attemptToEnableEnvironmentSetting: (options: __internal_AttemptToEnableEnvironmentSettingParams) => __internal_AttemptToEnableEnvironmentSettingResult;
/**
* Opens the Clerk Enable Organizations prompt for development instance
* @hidden
*/
__internal_openEnableOrganizationsPrompt: (props: __internal_EnableOrganizationsPromptProps) => void;
/**
* Closes the Clerk Enable Organizations modal.
* @hidden
*/
__internal_closeEnableOrganizationsPrompt: () => void;
/**
* Opens the Google One Tap component.
*
* @param props - Optional props that will be passed to the GoogleOneTap component.
*/
openGoogleOneTap: (props?: GoogleOneTapProps) => void;
/**
* Opens the Google One Tap component.
* If the component is not already open, results in a noop.
*/
closeGoogleOneTap: () => void;
/**
* Opens the Clerk SignUp component in a modal.
*
* @param props - Optional props that will be passed to the SignUp component.
*/
openSignUp: (props?: SignUpModalProps) => void;
/**
* Closes the Clerk SignUp modal.
*/
closeSignUp: () => void;
/**
* Opens the Clerk UserProfile modal.
*
* @param props - Optional props that will be passed to the UserProfile component.
*/
openUserProfile: (props?: UserProfileModalProps) => void;
/**
* Closes the Clerk UserProfile modal.
*/
closeUserProfile: () => void;
/**
* Opens the Clerk OrganizationProfile modal.
*
* @param props - Optional props that will be passed to the OrganizationProfile component.
*/
openOrganizationProfile: (props?: OrganizationProfileModalProps) => void;
/**
* Closes the Clerk OrganizationProfile modal.
*/
closeOrganizationProfile: () => void;
/**
* Opens the Clerk CreateOrganization modal.
*
* @param props - Optional props that will be passed to the CreateOrganization component.
*/
openCreateOrganization: (props?: CreateOrganizationModalProps) => void;
/**
* Closes the Clerk CreateOrganization modal.
*/
closeCreateOrganization: () => void;
/**
* Opens the Clerk Waitlist modal.
*
* @param props - Optional props that will be passed to the Waitlist component.
*/
openWaitlist: (props?: WaitlistModalProps) => void;
/**
* Closes the Clerk Waitlist modal.
*/
closeWaitlist: () => void;
/**
* Mounts a sign in flow component at the target element.
*
* @param targetNode - Target node to mount the SignIn component.
* @param signInProps - sign in configuration parameters.
*/
mountSignIn: (targetNode: HTMLDivElement, signInProps?: SignInProps) => void;
/**
* Unmount a sign in flow component from the target element.
* If there is no component mounted at the target node, results in a noop.
*
* @param targetNode - Target node to unmount the SignIn component from.
*/
unmountSignIn: (targetNode: HTMLDivElement) => void;
/**
* Mounts a sign up flow component at the target element.
*
* @param targetNode - Target node to mount the SignUp component.
* @param signUpProps - sign up configuration parameters.
*/
mountSignUp: (targetNode: HTMLDivElement, signUpProps?: SignUpProps) => void;
/**
* Unmount a sign up flow component from the target element.
* If there is no component mounted at the target node, results in a noop.
*
* @param targetNode - Target node to unmount the SignUp component from.
*/
unmountSignUp: (targetNode: HTMLDivElement) => void;
/**
* Mount a user avatar component at the target element.
*
* @param targetNode - Target node to mount the UserAvatar component.
*/
mountUserAvatar: (targetNode: HTMLDivElement, userAvatarProps?: UserAvatarProps) => void;
/**
* Unmount a user avatar component at the target element.
* If there is no component mounted at the target node, results in a noop.
*
* @param targetNode - Target node to unmount the UserAvatar component from.
*/
unmountUserAvatar: (targetNode: HTMLDivElement) => void;
/**
* Mount a user button component at the target element.
*
* @param targetNode - Target node to mount the UserButton component.
* @param userButtonProps - User button configuration parameters.
*/
mountUserButton: (targetNode: HTMLDivElement, userButtonProps?: UserButtonProps) => void;
/**
* Unmount a user button component at the target element.
* If there is no component mounted at the target node, results in a noop.
*
* @param targetNode - Target node to unmount the UserButton component from.
*/
unmountUserButton: (targetNode: HTMLDivElement) => void;
/**
* Mount a user profile component at the target element.
*
* @param targetNode - Target to mount the UserProfile component.
* @param userProfileProps - User profile configuration parameters.
*/
mountUserProfile: (targetNode: HTMLDivElement, userProfileProps?: UserProfileProps) => void;
/**
* Unmount a user profile component at the target element.
* If there is no component mounted at the target node, results in a noop.
*
* @param targetNode - Target node to unmount the UserProfile component from.
*/
unmountUserProfile: (targetNode: HTMLDivElement) => void;
/**
* Mount an Organization profile component at the target element.
*
* @param targetNode - Target to mount the OrganizationProfile component.
* @param props - Configuration parameters.
*/
mountOrganizationProfile: (targetNode: HTMLDivElement, props?: OrganizationProfileProps) => void;
/**
* Unmount the Organization profile component from the target node.
*
* @param targetNode - Target node to unmount the OrganizationProfile component from.
*/
unmountOrganizationProfile: (targetNode: HTMLDivElement) => void;
/**
* Mount a CreateOrganization component at the target element.
*
* @param targetNode - Target to mount the CreateOrganization component.
* @param props - Configuration parameters.
*/
mountCreateOrganization: (targetNode: HTMLDivElement, props?: CreateOrganizationProps) => void;
/**
* Unmount the CreateOrganization component from the target node.
*
* @param targetNode - Target node to unmount the CreateOrganization component from.
*/
unmountCreateOrganization: (targetNode: HTMLDivElement) => void;
/**
* Mount an Organization switcher component at the target element.
*
* @param targetNode - Target to mount the OrganizationSwitcher component.
* @param props - Configuration parameters.
*/
mountOrganizationSwitcher: (targetNode: HTMLDivElement, props?: OrganizationSwitcherProps) => void;
/**
* Unmount the Organization switcher component from the target node.*
*
* @param targetNode - Target node to unmount the OrganizationSwitcher component from.
*/
unmountOrganizationSwitcher: (targetNode: HTMLDivElement) => void;
/**
* Prefetches the data displayed by an Organization switcher.
* It can be used when `mountOrganizationSwitcher({ asStandalone: true})`, to avoid unwanted loading states.
*
* @experimental This experimental API is subject to change.
*
* @param props - Optional user verification configuration parameters.
*/
__experimental_prefetchOrganizationSwitcher: () => void;
/**
* Mount an Organization list component at the target element.
*
* @param targetNode - Target to mount the OrganizationList component.
* @param props - Configuration parameters.
*/
mountOrganizationList: (targetNode: HTMLDivElement, props?: OrganizationListProps) => void;
/**
* Unmount the Organization list component from the target node.*
*
* @param targetNode - Target node to unmount the OrganizationList component from.
*/
unmountOrganizationList: (targetNode: HTMLDivElement) => void;
/**
* Mount a waitlist at the target element.
*
* @param targetNode - Target to mount the Waitlist component.
* @param props - Configuration parameters.
*/
mountWaitlist: (targetNode: HTMLDivElement, props?: WaitlistProps) => void;
/**
* Unmount the Waitlist component from the target node.
*
* @param targetNode - Target node to unmount the Waitlist component from.
*/
unmountWaitlist: (targetNode: HTMLDivElement) => void;
/**
* Mounts a pricing table component at the target element.
*
* @param targetNode - Target node to mount the PricingTable component.
* @param props - configuration parameters.
*/
mountPricingTable: (targetNode: HTMLDivElement, props?: PricingTableProps) => void;
/**
* Unmount a pricing table component from the target element.
* If there is no component mounted at the target node, results in a noop.
*
* @param targetNode - Target node to unmount the PricingTable component from.
*/
unmountPricingTable: (targetNode: HTMLDivElement) => void;
/**
* Mount an API keys component at the target element.
*
* @param targetNode - Target to mount the APIKeys component.
* @param props - Configuration parameters.
*/
mountAPIKeys: (targetNode: HTMLDivElement, props?: APIKeysProps) => void;
/**
* Unmount an API keys component from the target element.
* If there is no component mounted at the target node, results in a noop.
*
* @param targetNode - Target node to unmount the APIKeys component from.
*/
unmountAPIKeys: (targetNode: HTMLDivElement) => void;
/**
* Mount a configure SSO component at the target element.
*
* @param targetNode - Target to mount the ConfigureSSO component.
* @param props - Configuration parameters.
* @hidden
*/
__internal_mountConfigureSSO: (targetNode: HTMLDivElement, props?: ConfigureSSOProps) => void;
/**
* Unmount a configure SSO component from the target element.
* If there is no component mounted at the target node, results in a noop.
*
* @param targetNode - Target node to unmount the ConfigureSSO component from.
* @hidden
*/
__internal_unmountConfigureSSO: (targetNode: HTMLDivElement) => void;
/**
* Mounts a OAuth consent component at the target element.
*
* @param targetNode - Target node to mount the OAuth consent component.
* @param oauthConsentProps - OAuth consent configuration parameters.
* @hidden
*/
__internal_mountOAuthConsent: (targetNode: HTMLDivElement, oauthConsentProps?: __internal_OAuthConsentProps) => void;
/**
* Unmounts a OAuth consent component from the target element.
*
* @param targetNode - Target node to unmount the OAuth consent component from.
* @hidden
*/
__internal_unmountOAuthConsent: (targetNode: HTMLDivElement) => void;
/**
* Mounts a OAuth consent component at the target element.
*
* @param targetNode - Target node to mount the OAuth consent component.
* @param oauthConsentProps - OAuth consent configuration parameters.
*/
mountOAuthConsent: (targetNode: HTMLDivElement, oauthConsentProps?: OAuthConsentProps) => void;
/**
* Unmounts a OAuth consent component from the target element.
*
* @param targetNode - Target node to unmount the OAuth consent component from.
*/
unmountOAuthConsent: (targetNode: HTMLDivElement) => void;
/**
* Mounts a TaskChooseOrganization component at the target element.
*
* @param targetNode - Target node to mount the TaskChooseOrganization component.
* @param props - configuration parameters.
*/
mountTaskChooseOrganization: (targetNode: HTMLDivElement, props?: TaskChooseOrganizationProps) => void;
/**
* Unmount a TaskChooseOrganization component from the target element.
* If there is no component mounted at the target node, results in a noop.
*
* @param targetNode - Target node to unmount the TaskChooseOrganization component from.
*/
unmountTaskChooseOrganization: (targetNode: HTMLDivElement) => void;
/**
* Mounts a TaskResetPassword component at the target element.
*
* @param targetNode - Target node to mount the TaskResetPassword component.
* @param props - configuration parameters.
*/
mountTaskResetPassword: (targetNode: HTMLDivElement, props?: TaskResetPasswordProps) => void;
/**
* Unmount a TaskResetPassword component from the target element.
* If there is no component mounted at the target node, results in a noop.
*
* @param targetNode - Target node to unmount the TaskResetPassword component from.
*/
unmountTaskResetPassword: (targetNode: HTMLDivElement) => void;
/**
* Mounts a TaskSetupMFA component at the target element.
* This component allows users to set up multi-factor authentication.
*
* @param targetNode - Target node to mount the TaskSetupMFA component.
* @param props - configuration parameters.
*/
mountTaskSetupMFA: (targetNode: HTMLDivElement, props?: TaskSetupMFAProps) => void;
/**
* Unmount a TaskSetupMFA component from the target element.
* If there is no component mounted at the target node, results in a noop.
*
* @param targetNode - Target node to unmount the TaskSetupMFA component from.
*/
unmountTaskSetupMFA: (targetNode: HTMLDivElement) => void;
/**
* @internal
* Loads Stripe libraries for commerce functionality
*/
__internal_loadStripeJs: () => Promise<any>;
/**
* Register a listener that triggers a callback whenever a change in the [`Client`](https://clerk.com/docs/reference/objects/client), [`Session`](https://clerk.com/docs/reference/objects/session), [`User`](https://clerk.com/docs/reference/objects/user), or [`Organization`](https://clerk.com/docs/reference/objects/organization) resources occurs. This method is primarily used to build frontend SDKs like [`@clerk/react`](https://www.npmjs.com/package/@clerk/react).
*
* Allows hooking up at different steps in the sign up, sign in processes.
*
* Some important checkpoints:
* - When there is an active session, `user === session.user`.
* - When there is no active session, user and session will both be `null`.
* - When a session is loading, user and session will be `undefined`.
*
* @param callback - The function to call when Clerk resources change.
* @param options - Optional configuration.
* @param options.skipInitialEmit - If `true`, the callback will not be called immediately after registration. Defaults to `false`.
* @returns - An `UnsubscribeCallback` function that can be used to remove the listener from the `Clerk` object.
*/
addListener: (callback: ListenerCallback, options?: ListenerOptions) => UnsubscribeCallback;
/**
* Registers an event handler for a specific Clerk event.
*
* @param event - The event name to subscribe to.
* @param handler - The callback function to execute when the event is triggered.
* @param opt - An object to control the behavior of the event handler. If true, and the event was previously dispatched, handler will be called immediately with the latest payload.
* @param opt.notify - If `true` and the event was previously dispatched, the handler will be called immediately with the latest payload.
*/
on: OnEventListener;
/**
* Removes an event handler for a specific Clerk event.
*
* @param event - The event name to unsubscribe from
* @param handler - The callback function to remove.
*/
off: OffEventListener;
/**
* Registers an internal listener that triggers a callback each time `Clerk.navigate` is called.
* Its purpose is to notify modal UI components when a navigation event occurs, allowing them to close if necessary.
*
* @internal
*/
__internal_addNavigationListener: (callback: () => void) => UnsubscribeCallback;
/**
* A method used to set the current session and/or Organization for the client. Accepts a [`SetActiveParams`](https://clerk.com/docs/reference/types/set-active-params) object.
*
* If the session param is `null`, the active session is deleted.
* In a similar fashion, if the organization param is `null`, the current organization is removed as active.
*/
setActive: SetActive;
/**
* Helper method which will use the custom push navigation function of your application to navigate to the provided URL or relative path.
*
* Returns a promise that can be `await`ed in order to listen for the navigation to finish. The inner value should not be relied on, as it can change based on the framework it's used within.
*/
navigate: CustomNavigation;
/**
* Decorates the provided URL with the auth token for development instances.
*
* @param to - The route to create a URL towards.
*/
buildUrlWithAuth(to: string): string;
/**
* Returns the configured URL where [`<SignIn/>`](https://clerk.com/docs/reference/components/authentication/sign-in) is mounted or a custom sign-in page is rendered.
*
* @param opts - Options used to control the redirect in the constructed URL.
*/
buildSignInUrl(opts?: RedirectOptions): string;
/**
* Returns the configured URL where [`<SignUp/>`](https://clerk.com/docs/reference/components/authentication/sign-up) is mounted or a custom sign-up page is rendered.
*
* @param opts - Options used to control the redirect in the constructed URL.
*/
buildSignUpUrl(opts?: RedirectOptions): string;
/**
* Returns the configured URL where [`<UserProfile />`](https://clerk.com/docs/reference/components/user/user-profile) is mounted or a custom user-profile page is rendered.
*/
buildUserProfileUrl(): string;
/**
* Returns the configured URL where [`<CreateOrganization />`](https://clerk.com/docs/reference/components/organization/create-organization) is mounted or a custom create-organization page is rendered.
*/
buildCreateOrganizationUrl(): string;
/**
* Returns the configured URL where [`<OrganizationProfile />`](https://clerk.com/docs/reference/components/organization/organization-profile) is mounted or a custom organization-profile page is rendered.
*/
buildOrganizationProfileUrl(): string;
/**
* Returns the configured URL where [session tasks](https://clerk.com/docs/guides/configure/session-tasks) are mounted.
*/
buildTasksUrl(): string;
/**
* Returns the configured `afterSignInUrl` of the instance.
* @param params - Optional query parameters to append to the URL.
*/
buildAfterSignInUrl({
params
}?: {
params?: URLSearchParams;
}): string;
/**
* Returns the configured `afterSignUpUrl` of the instance.
* @param params - Optional query parameters to append to the URL.
*/
buildAfterSignUpUrl({
params
}?: {
params?: URLSearchParams;
}): string;
/**
* Returns the configured `afterSignOutUrl` of the instance.
*/
buildAfterSignOutUrl(): string;
/**
* Returns the configured `newSubscriptionRedirectUrl` of the instance.
*/
buildNewSubscriptionRedirectUrl(): string;
/**
* Returns the configured `afterMultiSessionSingleSignOutUrl` of the instance.
*/
buildAfterMultiSessionSingleSignOutUrl(): string;
/**
* Returns the configured URL where [`<Waitlist />`](https://clerk.com/docs/reference/components/authentication/waitlist) is mounted or a custom waitlist page is rendered.
*
* @param opts - Options to control the waitlist URL.
* @param opts.initialValues - Initial values to prefill the waitlist form.
*/
buildWaitlistUrl(opts?: {
initialValues?: Record<string, string>;
}): string;
/**
*
* Redirects to the provided URL after appending authentication credentials. For development instances, this method decorates the URL with an auth token to maintain authentication state. For production instances, the standard session cookie is used.
*
* Returns a promise that can be `await`ed in order to listen for the navigation to finish. The inner value should not be relied on, as it can change based on the framework it's used within.
*
* @param to - The URL to redirect to.
*/
redirectWithAuth(to: string): Promise<unknown>;
/**
* Redirects to the sign-in URL, as configured in your application's instance settings. This method uses the [`navigate()`](https://clerk.com/docs/reference/objects/clerk#navigate) method under the hood.
*
* Returns a promise that can be `await`ed in order to listen for the navigation to finish. The inner value should not be relied on, as it can change based on the framework it's used within.
*
* @param opts - Options to control the redirect.
*/
redirectToSignIn(opts?: SignInRedirectOptions): Promise<unknown>;
/**
* Redirects to the sign-up URL, as configured in your application's instance settings. This method uses the [`navigate()`](https://clerk.com/docs/reference/objects/clerk#navigate) method under the hood.
*
* Returns a promise that can be `await`ed in order to listen for the navigation to finish. The inner value should not be relied on, as it can change based on the framework it's used within.
*
* @param opts - Options to control the redirect.
*/
redirectToSignUp(opts?: SignUpRedirectOptions): Promise<unknown>;
/**
* Redirects to the configured URL where [`<UserProfile />`](https://clerk.com/docs/reference/components/user/user-profile) is mounted.
*
* Returns a promise that can be `await`ed in order to listen for the navigation to finish. The inner value should not be relied on, as it can change based on the framework it's used within.
*/
redirectToUserProfile: () => Promise<unknown>;
/**
* Redirects to the configured URL where [`<OrganizationProfile />`](https://clerk.com/docs/reference/components/organization/organization-profile) is mounted. This method uses the [`navigate()`](https://clerk.com/docs/reference/objects/clerk#navigate) method under the hood.
*
* Returns a promise that can be `await`ed in order to listen for the navigation to finish. The inner value should not be relied on, as it can change based on the framework it's used within.
*/
redirectToOrganizationProfile: () => Promise<unknown>;
/**
* Redirects to the configured URL where [`<CreateOrganization />`](https://clerk.com/docs/reference/components/organization/create-organization) is mounted. This method uses the [`navigate()`](https://clerk.com/docs/reference/objects/clerk#navigate) method under the hood.
*
* Returns a promise that can be `await`ed in order to listen for the navigation to finish. The inner value should not be relied on, as it can change based on the framework it's used within.
*/
redirectToCreateOrganization: () => Promise<unknown>;
/**
* Redirects to the configured `afterSignIn` URL.
*/
redirectToAfterSignIn: () => void;
/**
* Redirects to the configured `afterSignUp` URL.
*/
redirectToAfterSignUp: () => void;
/**
* Redirects to the configured `afterSignOut` URL.
*/
redirectToAfterSignOut: () => void;
/**
* Redirects to the configured URL where [`<Waitlist />`](https://clerk.com/docs/reference/components/authentication/waitlist) is mounted.
*/
redirectToWaitlist: () => void;
/**
* Redirects to the configured URL where [session tasks](https://clerk.com/docs/reference/objects/session) are mounted.
*
* @param opts - Options to control the redirect (e.g., redirect URL after tasks are complete).
*/
redirectToTasks(opts?: TasksRedirectOptions): Promise<unknown>;
/**
* Completes a Google One Tap redirection flow started by [`authenticateWithGoogleOneTap()`](https://clerk.com/docs/reference/objects/clerk#authenticate-with-google-one-tap). This method should be called after the user is redirected back from visiting the Google One Tap prompt.
*
* @param signInOrUp - The resource returned from the initial `authenticateWithGoogleOneTap()` call (before redirect).
* @param params - Additional props that define where the user will be redirected to at the end of a successful Google One Tap flow.
* @param customNavigate - A function that overrides Clerk's default navigation behavior, allowing custom handling of navigation during sign-up and sign-in flows.
*/
handleGoogleOneTapCallback: (signInOrUp: SignInResource | SignUpResource, params: HandleOAuthCallbackParams, customNavigate?: (to: string) => Promise<unknown>) => Promise<unknown>;
/**
* Whether an OAuth transport (e.g. for Electron) has been registered.
*
* @internal
*/
__internal_hasOAuthTransport: boolean;
/**
* The registered OAuth transport, or null when none is registered.
*
* @internal
*/
__internal_oauthTransport: OAuthTransport | null;
/**
* Completes an OAuth/SAML callback using a sign-in or sign-up resource already in hand
* (generalization of `handleGoogleOneTapCallback`).
*
* @internal
*/
__internal_handleResourceCallback: (signInOrUp: SignInResource | SignUpResource, params: HandleOAuthCallbackParams, customNavigate?: (to: string) => Promise<unknown>) => Promise<unknown>;
/**
* Completes a custom OAuth or SAML redirect flow that was started by calling [`SignIn.authenticateWithRedirect(params)`](https://clerk.com/docs/reference/objects/sign-in) or [`SignUp.authenticateWithRedirect(params)`](https://clerk.com/docs/reference/objects/sign-up).
*
* @param params - Additional props that define where the user will be redirected to at the end of a successful OAuth or SAML flow.
* @param customNavigate - A function that overrides Clerk's default navigation behavior, allowing custom handling of navigation during sign-up and sign-in flows.
*/
handleRedirectCallback: (params: HandleOAuthCallbackParams | HandleSamlCallbackParams, customNavigate?: (to: string) => Promise<unknown>) => Promise<unknown>;
/**
* Completes an email link verification flow started by `Clerk.client.signIn.createEmailLinkFlow` or `Clerk.client.signUp.createEmailLinkFlow`, by processing the verification results from the redirect URL query parameters. This method should be called after the user is redirected back from visiting the verification link in their email.
* @param params - Allows you to define the URLs where the user should be redirected to on successful verification or pending/completed sign-up or sign-in attempts. If the email link is successfully verified on another device, there's a callback function parameter that allows custom code execution.
* @param customNavigate - A function that overrides Clerk's default navigation behavior, allowing custom handling of navigation during sign-up and sign-in flows.
*/
handleEmailLinkVerification: (params: HandleEmailLinkVerificationParams, customNavigate?: (to: string) => Promise<unknown>) => Promise<unknown>;
/**
* Starts a sign-in flow that uses MetaMask to authenticate the user using their Metamask wallet address.
*/
authenticateWithMetamask: (params?: AuthenticateWithMetamaskParams) => Promise<unknown>;
/**
* Starts a sign-in flow that uses Coinbase Smart Wallet to authenticate the user using their Coinbase wallet address.
*/
authenticateWithCoinbaseWallet: (params?: AuthenticateWithCoinbaseWalletParams) => Promise<unknown>;
/**
* Starts a sign-in flow that uses OKX Wallet to authenticate the user using their OKX wallet address.
*/
authenticateWithOKXWallet: (params?: AuthenticateWithOKXWalletParams) => Promise<unknown>;
/**
* Starts a sign-in flow that uses Base to authenticate the user using their Web3 wallet address.
*/
authenticateWithBase: (params?: AuthenticateWithBaseParams) => Promise<unknown>;
/**
* Starts a sign-in flow that uses Solana to authenticate the user using their Solana wallet address.
*/
authenticateWithSolana: (params: AuthenticateWithSolanaParams) => Promise<unknown>;
/**
* Starts a sign-in flow that uses a Web3 Wallet browser extension to authenticate the user using their Ethereum wallet address.
*/
authenticateWithWeb3: (params: ClerkAuthenticateWithWeb3Params) => Promise<unknown>;
/**
* Authenticates user using a Google token generated from Google identity services.
*/
authenticateWithGoogleOneTap: (params: AuthenticateWithGoogleOneTapParams) => Promise<SignInResource | SignUpResource>;
/**
* Creates an Organization programmatically, adding the current user as admin. Returns an [`Organization`](https://clerk.com/docs/reference/objects/organization) object.
*
* > [!NOTE]
* > For React-based apps, consider using the [`<CreateOrganization />`](https://clerk.com/docs/reference/components/organization/create-organization) component.
*/
createOrganization: (params: CreateOrganizationParams) => Promise<OrganizationResource>;
/**
* Gets a single [Organization](https://clerk.com/docs/reference/objects/organization) by ID.
*
* @param organizationId - The ID of the Organization to get.
*/
getOrganization: (organizationId: string) => Promise<OrganizationResource>;
/**
* Handles a 401 response from the Frontend API by refreshing the [`Client`](https://clerk.com/docs/reference/objects/client) and [`Session`](https://clerk.com/docs/reference/objects/session) object accordingly.
*/
handleUnauthenticated: () => Promise<unknown>;
/**
* Create a new waitlist entry programmatically. Requires that you set your app's sign-up mode to [**Waitlist**](https://clerk.com/docs/guides/secure/restricting-access#waitlist) in the Clerk Dashboard.
*/
joinWaitlist: (params: JoinWaitlistParams) => Promise<WaitlistResource>;
/**
* This is an optional function.
* This function is used to load cached Client and Environment resources if Clerk fails to load them from the Frontend API.
*
* @internal
*/
__internal_getCachedResources: (() => Promise<{
client: ClientJSONSnapshot | null;
environment: EnvironmentJSONSnapshot | null;
}>) | undefined;
/**
* This function is used to reload the initial resources (Environment/Client) from the Frontend API.
*
* @internal
*/
__internal_reloadInitialResources: () => Promise<void>;
/**
* Internal flag indicating whether a `setActive` call is in progress. Used to prevent navigations from being
* initiated outside of the Clerk class.
*
* @hidden
*/
__internal_setActiveInProgress: boolean;
/**
* The `APIKeys` object used for managing API keys.
*/
apiKeys: APIKeysNamespace;
/**
* OAuth application helpers (e.g., consent metadata for custom consent UIs).
*/
oauthApplication: OAuthApplicationNamespace;
/**
* Checkout API
*
* @experimental
* This API is in early access and may change in future releases.
*/
__experimental_checkout: __experimental_CheckoutFunction;
}
/** @generateWithEmptyComment */
type HandleOAuthCallbackParams = TransferableOption & SignInForceRedirectUrl & SignInFallbackRedirectUrl & SignUpForceRedirectUrl & SignUpFallbackRedirectUrl & {
/**
* The full URL or path where the [`<SignIn />`](https://clerk.com/docs/reference/components/authentication/sign-in) component is mounted.
*/
signInUrl?: string;
/**
* The full URL or path where the [`<SignUp />`](https://clerk.com/docs/reference/components/authentication/sign-up) component is mounted.
*/
signUpUrl?: string;
/**
* The full URL or path to navigate to during sign in, if [first factor verification](!first-factor-verification) is required.
*/
firstFactorUrl?: string;
/**
* The full URL or path to navigate to during sign in, if [multi-factor authentication](https://clerk.com/docs/guides/configure/auth-strategies/sign-up-sign-in-options#multi-factor-authentication) is enabled.
*/
secondFactorUrl?: string;
/**
* The full URL or path to navigate to during sign in, if the user is required to reset their password.
*/
resetPasswordUrl?: string;
/**
* The full URL or path to navigate to if the sign up requires additional information.
*/
continueSignUpUrl?: string | null;
/**
* The full URL or path to navigate to after requesting email verification.
*/
verifyEmailAddressUrl?: string | null;
/**
* The full URL or path to navigate to after requesting phone verification.
*/
verifyPhoneNumberUrl?: string | null;
/**
* The full URL or path to navigate to if the sign-in is gated by a Clerk Protect challenge
* (`protect_check`). Defaults to the `protect-check` route on the mounted sign-in component.
*/
signInProtectCheckUrl?: string | null;
/**
* The full URL or path to navigate to if the sign-up is gated by a Clerk Protect challenge
* (`protect_check`). Defaults to the `protect-check` route on the mounted sign-up component.
*/
signUpProtectCheckUrl?: string | null;
/**
* The underlying resource to optionally reload before processing an OAuth callback.
*/
reloadResource?: 'signIn' | 'signUp';
/**
* Metadata that can be read and set from the frontend. Once the sign-up is complete, the value of this field will be automatically copied to the newly created user's unsafe metadata. One common use case for this attribute is to use it to implement custom fields that can be collected during sign-up and will automatically be attached to the created `User` object.
*/
unsafeMetadata?: SignUpUnsafeMetadata;
/**
* Internal navigation hook used by Clerk UI to preserve custom post-activation routing
* when completing an OAuth callback in-process (transport flows). Not set by the web
* redirect/popup paths.
*
* @internal
*/
__internal_navigateOnSetActive?: (opts: {
session: SessionResource;
redirectUrl: string;
decorateUrl: (url: string) => string;
}) => Promise<unknown>;
};
type HandleSamlCallbackParams = HandleOAuthCallbackParams;
/**
* A function used to navigate to a given URL after certain steps in the Clerk processes.
*
* @param to - The URL or relative path to navigate to.
* @param options - Optional configuration.
* @param options.replace? - If `true`, replace the current history entry instead of pushing a new one.
* @param options.metadata? - Optional router metadata.
*/
type CustomNavigation = (to: string, options?: NavigateOptions) => Promise<unknown> | void;
type ClerkThemeOptions = DeepSnakeToCamel<DeepPartial<DisplayThemeJSON>>;
/**
* Navigation options used to replace or push history changes.
* Both `routerPush` & `routerReplace` OR none options should be passed.
*/
type ClerkOptionsNavigation = {
/**
* A function which takes the destination path as an argument and performs a "push" navigation.
*/
routerPush?: never;
/**
* A function which takes the destination path as an argument and performs a "replace" navigation.
*/
routerReplace?: never;
/**
* If `true`, the router will log debug information to the console.
*/
routerDebug?: boolean;
} | {
/**
* A function which takes the destination path as an argument and performs a "push" navigation.
*/
routerPush: RouterFn;
/**
* A function which takes the destination path as an argument and performs a "replace" navigation.
*/
routerReplace: RouterFn;
/**
* If `true`, the router will log debug information to the console.
*/
routerDebug?: boolean;
};
/** @generateWithEmptyComment */
type ClerkUnsafeOptions = {
/**
* Disables the `Clerk has bee