@clerk/backend 3.0.0-canary-core3.v20251203181537 → 3.0.0-snapshot.v20251203203405
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.
- package/dist/api/endpoints/InstanceApi.d.ts +1 -1
- package/dist/api/endpoints/UserApi.d.ts +1 -1
- package/dist/api/endpoints/UserApi.d.ts.map +1 -1
- package/dist/{chunk-FKLCHJH3.mjs → chunk-ZUP5X55M.mjs} +4 -4
- package/dist/chunk-ZUP5X55M.mjs.map +1 -0
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/internal.js +3 -3
- package/dist/internal.js.map +1 -1
- package/dist/internal.mjs +1 -1
- package/dist/util/shared.d.ts +1 -1
- package/package.json +2 -2
- package/dist/chunk-FKLCHJH3.mjs.map +0 -1
package/dist/internal.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal.ts","../src/constants.ts","../src/createRedirect.ts","../src/util/shared.ts","../src/util/mergePreDefinedOptions.ts","../src/errors.ts","../src/runtime.ts","../src/util/rfc4648.ts","../src/jwt/algorithms.ts","../src/jwt/assertions.ts","../src/jwt/cryptoKeys.ts","../src/jwt/verifyJwt.ts","../src/util/optionsAssertions.ts","../src/tokens/authenticateContext.ts","../src/tokens/tokenTypes.ts","../src/tokens/authObjects.ts","../src/util/path.ts","../src/api/endpoints/AbstractApi.ts","../src/api/endpoints/ActorTokenApi.ts","../src/api/endpoints/AccountlessApplicationsAPI.ts","../src/api/endpoints/AllowlistIdentifierApi.ts","../src/api/endpoints/APIKeysApi.ts","../src/api/endpoints/BetaFeaturesApi.ts","../src/api/endpoints/BlocklistIdentifierApi.ts","../src/api/endpoints/ClientApi.ts","../src/api/endpoints/DomainApi.ts","../src/api/endpoints/EmailAddressApi.ts","../src/api/endpoints/IdPOAuthAccessTokenApi.ts","../src/api/endpoints/InstanceApi.ts","../src/api/endpoints/InvitationApi.ts","../src/api/endpoints/MachineApi.ts","../src/api/endpoints/M2MTokenApi.ts","../src/api/endpoints/JwksApi.ts","../src/api/endpoints/JwtTemplatesApi.ts","../src/api/endpoints/OrganizationApi.ts","../src/api/endpoints/OAuthApplicationsApi.ts","../src/api/endpoints/PhoneNumberApi.ts","../src/api/endpoints/ProxyCheckApi.ts","../src/api/endpoints/RedirectUrlApi.ts","../src/api/endpoints/SamlConnectionApi.ts","../src/api/endpoints/SessionApi.ts","../src/api/endpoints/SignInTokenApi.ts","../src/api/endpoints/SignUpApi.ts","../src/api/endpoints/TestingTokenApi.ts","../src/api/endpoints/UserApi.ts","../src/api/endpoints/WaitlistEntryApi.ts","../src/api/endpoints/WebhookApi.ts","../src/api/endpoints/BillingApi.ts","../src/api/request.ts","../../../node_modules/.pnpm/map-obj@5.0.2/node_modules/map-obj/index.js","../../../node_modules/.pnpm/change-case@5.4.4/node_modules/change-case/src/index.ts","../../../node_modules/.pnpm/snakecase-keys@9.0.2/node_modules/snakecase-keys/index.js","../src/api/resources/AccountlessApplication.ts","../src/api/resources/ActorToken.ts","../src/api/resources/AllowlistIdentifier.ts","../src/api/resources/APIKey.ts","../src/api/resources/BlocklistIdentifier.ts","../src/api/resources/Session.ts","../src/api/resources/Client.ts","../src/api/resources/CnameTarget.ts","../src/api/resources/Cookies.ts","../src/api/resources/DeletedObject.ts","../src/api/resources/Domain.ts","../src/api/resources/Email.ts","../src/api/resources/IdentificationLink.ts","../src/api/resources/Verification.ts","../src/api/resources/EmailAddress.ts","../src/api/resources/Feature.ts","../src/api/resources/CommercePlan.ts","../src/api/resources/CommerceSubscriptionItem.ts","../src/api/resources/CommerceSubscription.ts","../src/api/resources/ExternalAccount.ts","../src/api/resources/IdPOAuthAccessToken.ts","../src/api/resources/Instance.ts","../src/api/resources/InstanceRestrictions.ts","../src/api/resources/InstanceSettings.ts","../src/api/resources/Invitation.ts","../src/api/resources/JSON.ts","../src/api/resources/JwtTemplate.ts","../src/api/resources/M2MToken.ts","../src/api/resources/Machine.ts","../src/api/resources/MachineScope.ts","../src/api/resources/MachineSecretKey.ts","../src/api/resources/OauthAccessToken.ts","../src/api/resources/OAuthApplication.ts","../src/api/resources/Organization.ts","../src/api/resources/OrganizationInvitation.ts","../src/api/resources/OrganizationMembership.ts","../src/api/resources/OrganizationSettings.ts","../src/api/resources/PhoneNumber.ts","../src/api/resources/ProxyCheck.ts","../src/api/resources/RedirectUrl.ts","../src/api/resources/SamlConnection.ts","../src/api/resources/SignInTokens.ts","../src/api/resources/SignUpAttempt.ts","../src/api/resources/SMSMessage.ts","../src/api/resources/Token.ts","../src/api/resources/Web3Wallet.ts","../src/api/resources/User.ts","../src/api/resources/WaitlistEntry.ts","../src/api/resources/Deserializer.ts","../src/api/factory.ts","../src/tokens/machine.ts","../src/tokens/authStatus.ts","../src/tokens/clerkRequest.ts","../src/tokens/clerkUrl.ts","../src/tokens/cookie.ts","../src/tokens/keys.ts","../src/tokens/verify.ts","../src/tokens/handshake.ts","../src/tokens/organizationMatcher.ts","../src/tokens/request.ts","../src/tokens/factory.ts","../src/util/decorateObjectWithResources.ts"],"sourcesContent":["export { constants } from './constants';\nexport { createRedirect } from './createRedirect';\nexport type { RedirectFun } from './createRedirect';\n\nexport type { CreateAuthenticateRequestOptions } from './tokens/factory';\nexport { createAuthenticateRequest } from './tokens/factory';\n\nexport { debugRequestState } from './tokens/request';\n\nexport type {\n AuthenticateRequestOptions,\n OrganizationSyncOptions,\n InferAuthObjectFromToken,\n InferAuthObjectFromTokenArray,\n GetAuthFn,\n AuthOptions,\n GetAuthFnNoRequest,\n} from './tokens/types';\n\nexport { TokenType } from './tokens/tokenTypes';\nexport type { SessionTokenType, MachineTokenType } from './tokens/tokenTypes';\n\nexport type {\n SignedInAuthObjectOptions,\n SignedInAuthObject,\n SignedOutAuthObject,\n AuthenticatedMachineObject,\n UnauthenticatedMachineObject,\n} from './tokens/authObjects';\nexport {\n makeAuthObjectSerializable,\n signedOutAuthObject,\n signedInAuthObject,\n authenticatedMachineObject,\n unauthenticatedMachineObject,\n invalidTokenAuthObject,\n getAuthObjectFromJwt,\n getAuthObjectForAcceptedToken,\n} from './tokens/authObjects';\n\nexport { AuthStatus } from './tokens/authStatus';\nexport type {\n RequestState,\n SignedInState,\n SignedOutState,\n AuthenticatedState,\n UnauthenticatedState,\n} from './tokens/authStatus';\n\nexport { decorateObjectWithResources, stripPrivateDataFromObject } from './util/decorateObjectWithResources';\n\nexport { createClerkRequest } from './tokens/clerkRequest';\nexport type { ClerkRequest } from './tokens/clerkRequest';\n\nexport { reverificationError, reverificationErrorResponse } from '@clerk/shared/authorization-errors';\n\nexport { verifyMachineAuthToken } from './tokens/verify';\n\nexport { isMachineTokenByPrefix, isMachineTokenType, getMachineTokenType, isTokenTypeAccepted } from './tokens/machine';\n","export const API_URL = 'https://api.clerk.com';\nexport const API_VERSION = 'v1';\n\nexport const USER_AGENT = `${PACKAGE_NAME}@${PACKAGE_VERSION}`;\nexport const MAX_CACHE_LAST_UPDATED_AT_SECONDS = 5 * 60;\nexport const SUPPORTED_BAPI_VERSION = '2025-11-10';\n\nconst Attributes = {\n AuthToken: '__clerkAuthToken',\n AuthSignature: '__clerkAuthSignature',\n AuthStatus: '__clerkAuthStatus',\n AuthReason: '__clerkAuthReason',\n AuthMessage: '__clerkAuthMessage',\n ClerkUrl: '__clerkUrl',\n} as const;\n\nconst Cookies = {\n Session: '__session',\n Refresh: '__refresh',\n ClientUat: '__client_uat',\n Handshake: '__clerk_handshake',\n DevBrowser: '__clerk_db_jwt',\n RedirectCount: '__clerk_redirect_count',\n HandshakeNonce: '__clerk_handshake_nonce',\n} as const;\n\nconst QueryParameters = {\n ClerkSynced: '__clerk_synced',\n SuffixedCookies: 'suffixed_cookies',\n ClerkRedirectUrl: '__clerk_redirect_url',\n // use the reference to Cookies to indicate that it's the same value\n DevBrowser: Cookies.DevBrowser,\n Handshake: Cookies.Handshake,\n HandshakeHelp: '__clerk_help',\n LegacyDevBrowser: '__dev_session',\n HandshakeReason: '__clerk_hs_reason',\n HandshakeNonce: Cookies.HandshakeNonce,\n HandshakeFormat: 'format',\n} as const;\n\nconst Headers = {\n Accept: 'accept',\n AuthMessage: 'x-clerk-auth-message',\n Authorization: 'authorization',\n AuthReason: 'x-clerk-auth-reason',\n AuthSignature: 'x-clerk-auth-signature',\n AuthStatus: 'x-clerk-auth-status',\n AuthToken: 'x-clerk-auth-token',\n CacheControl: 'cache-control',\n ClerkRedirectTo: 'x-clerk-redirect-to',\n ClerkRequestData: 'x-clerk-request-data',\n ClerkUrl: 'x-clerk-clerk-url',\n CloudFrontForwardedProto: 'cloudfront-forwarded-proto',\n ContentType: 'content-type',\n ContentSecurityPolicy: 'content-security-policy',\n ContentSecurityPolicyReportOnly: 'content-security-policy-report-only',\n EnableDebug: 'x-clerk-debug',\n ForwardedHost: 'x-forwarded-host',\n ForwardedPort: 'x-forwarded-port',\n ForwardedProto: 'x-forwarded-proto',\n Host: 'host',\n Location: 'location',\n Nonce: 'x-nonce',\n Origin: 'origin',\n Referrer: 'referer',\n SecFetchDest: 'sec-fetch-dest',\n SecFetchSite: 'sec-fetch-site',\n UserAgent: 'user-agent',\n ReportingEndpoints: 'reporting-endpoints',\n} as const;\n\nconst ContentTypes = {\n Json: 'application/json',\n} as const;\n\n/**\n * @internal\n */\nexport const constants = {\n Attributes,\n Cookies,\n Headers,\n ContentTypes,\n QueryParameters,\n} as const;\n\nexport type Constants = typeof constants;\n","import { buildAccountsBaseUrl } from '@clerk/shared/buildAccountsBaseUrl';\nimport type { SessionStatusClaim } from '@clerk/shared/types';\n\nimport { constants } from './constants';\nimport { errorThrower, parsePublishableKey } from './util/shared';\n\nconst buildUrl = (\n _baseUrl: string | URL,\n _targetUrl: string | URL,\n _returnBackUrl?: string | URL | null,\n _devBrowserToken?: string | null,\n) => {\n if (_baseUrl === '') {\n return legacyBuildUrl(_targetUrl.toString(), _returnBackUrl?.toString());\n }\n\n const baseUrl = new URL(_baseUrl);\n const returnBackUrl = _returnBackUrl ? new URL(_returnBackUrl, baseUrl) : undefined;\n const res = new URL(_targetUrl, baseUrl);\n const isCrossOriginRedirect = `${baseUrl.hostname}:${baseUrl.port}` !== `${res.hostname}:${res.port}`;\n\n if (returnBackUrl) {\n if (isCrossOriginRedirect) {\n returnBackUrl.searchParams.delete(constants.QueryParameters.ClerkSynced);\n }\n\n res.searchParams.set('redirect_url', returnBackUrl.toString());\n }\n // For cross-origin redirects, we need to pass the dev browser token for URL session syncing\n if (isCrossOriginRedirect && _devBrowserToken) {\n res.searchParams.set(constants.QueryParameters.DevBrowser, _devBrowserToken);\n }\n return res.toString();\n};\n\n/**\n * In v5, we deprecated the top-level redirectToSignIn and redirectToSignUp functions\n * in favor of the new auth().redirectToSignIn helpers\n * In order to allow for a smooth transition, we need to support the legacy redirectToSignIn for now\n * as we will remove it in v6.\n * In order to make sure that the legacy function works as expected, we will use legacyBuildUrl\n * to build the url if baseUrl is not provided (which is the case for legacy redirectToSignIn)\n * This function can be safely removed when we remove the legacy redirectToSignIn function\n */\nconst legacyBuildUrl = (targetUrl: string, redirectUrl?: string) => {\n let url;\n if (!targetUrl.startsWith('http')) {\n if (!redirectUrl || !redirectUrl.startsWith('http')) {\n throw new Error('destination url or return back url should be an absolute path url!');\n }\n\n const baseURL = new URL(redirectUrl);\n url = new URL(targetUrl, baseURL.origin);\n } else {\n url = new URL(targetUrl);\n }\n\n if (redirectUrl) {\n url.searchParams.set('redirect_url', redirectUrl);\n }\n\n return url.toString();\n};\n\ntype RedirectAdapter<RedirectReturn> = (url: string) => RedirectReturn;\ntype RedirectToParams = { returnBackUrl?: string | URL | null };\nexport type RedirectFun<ReturnType> = (params?: RedirectToParams) => ReturnType;\n\n/**\n * @internal\n */\ntype CreateRedirect = <ReturnType>(params: {\n publishableKey: string;\n devBrowserToken?: string;\n redirectAdapter: RedirectAdapter<ReturnType>;\n baseUrl: URL | string;\n signInUrl?: URL | string;\n signUpUrl?: URL | string;\n sessionStatus?: SessionStatusClaim | null;\n}) => {\n redirectToSignIn: RedirectFun<ReturnType>;\n redirectToSignUp: RedirectFun<ReturnType>;\n};\n\nexport const createRedirect: CreateRedirect = params => {\n const { publishableKey, redirectAdapter, signInUrl, signUpUrl, baseUrl, sessionStatus } = params;\n const parsedPublishableKey = parsePublishableKey(publishableKey);\n const frontendApi = parsedPublishableKey?.frontendApi;\n const isDevelopment = parsedPublishableKey?.instanceType === 'development';\n const accountsBaseUrl = buildAccountsBaseUrl(frontendApi);\n const hasPendingStatus = sessionStatus === 'pending';\n\n const redirectToTasks = (url: string | URL, { returnBackUrl }: RedirectToParams) => {\n return redirectAdapter(\n buildUrl(baseUrl, `${url}/tasks`, returnBackUrl, isDevelopment ? params.devBrowserToken : null),\n );\n };\n\n const redirectToSignUp = ({ returnBackUrl }: RedirectToParams = {}) => {\n if (!signUpUrl && !accountsBaseUrl) {\n errorThrower.throwMissingPublishableKeyError();\n }\n\n const accountsSignUpUrl = `${accountsBaseUrl}/sign-up`;\n\n // Allows redirection to SignInOrUp path\n function buildSignUpUrl(signIn: string | URL | undefined) {\n if (!signIn) {\n return;\n }\n const url = new URL(signIn, baseUrl);\n url.pathname = `${url.pathname}/create`;\n return url.toString();\n }\n\n const targetUrl = signUpUrl || buildSignUpUrl(signInUrl) || accountsSignUpUrl;\n\n if (hasPendingStatus) {\n return redirectToTasks(targetUrl, { returnBackUrl });\n }\n\n return redirectAdapter(buildUrl(baseUrl, targetUrl, returnBackUrl, isDevelopment ? params.devBrowserToken : null));\n };\n\n const redirectToSignIn = ({ returnBackUrl }: RedirectToParams = {}) => {\n if (!signInUrl && !accountsBaseUrl) {\n errorThrower.throwMissingPublishableKeyError();\n }\n\n const accountsSignInUrl = `${accountsBaseUrl}/sign-in`;\n const targetUrl = signInUrl || accountsSignInUrl;\n\n if (hasPendingStatus) {\n return redirectToTasks(targetUrl, { returnBackUrl });\n }\n\n return redirectAdapter(buildUrl(baseUrl, targetUrl, returnBackUrl, isDevelopment ? params.devBrowserToken : null));\n };\n\n return { redirectToSignUp, redirectToSignIn };\n};\n","export { deprecated, deprecatedProperty } from '@clerk/shared/deprecated';\nexport {\n getCookieSuffix,\n getSuffixedCookieName,\n isDevelopmentFromSecretKey,\n isProductionFromSecretKey,\n parsePublishableKey,\n} from '@clerk/shared/keys';\nexport { retry } from '@clerk/shared/retry';\nexport { addClerkPrefix, getClerkJsMajorVersionOrTag, getScriptUrl } from '@clerk/shared/url';\n\nimport { buildErrorThrower } from '@clerk/shared/error';\nimport { createDevOrStagingUrlCache } from '@clerk/shared/keys';\n// TODO: replace packageName with `${PACKAGE_NAME}@${PACKAGE_VERSION}` from tsup.config.ts\nexport const errorThrower = buildErrorThrower({ packageName: '@clerk/backend' });\n\nexport const { isDevOrStagingUrl } = createDevOrStagingUrlCache();\n","export function mergePreDefinedOptions<T extends Record<string, any>>(preDefinedOptions: T, options: Partial<T>): T {\n return Object.keys(preDefinedOptions).reduce(\n (obj: T, key: string) => {\n return { ...obj, [key]: options[key] || obj[key] };\n },\n { ...preDefinedOptions },\n );\n}\n","export type TokenCarrier = 'header' | 'cookie';\n\nexport const TokenVerificationErrorCode = {\n InvalidSecretKey: 'clerk_key_invalid',\n};\n\nexport type TokenVerificationErrorCode = (typeof TokenVerificationErrorCode)[keyof typeof TokenVerificationErrorCode];\n\nexport const TokenVerificationErrorReason = {\n TokenExpired: 'token-expired',\n TokenInvalid: 'token-invalid',\n TokenInvalidAlgorithm: 'token-invalid-algorithm',\n TokenInvalidAuthorizedParties: 'token-invalid-authorized-parties',\n TokenInvalidSignature: 'token-invalid-signature',\n TokenNotActiveYet: 'token-not-active-yet',\n TokenIatInTheFuture: 'token-iat-in-the-future',\n TokenVerificationFailed: 'token-verification-failed',\n InvalidSecretKey: 'secret-key-invalid',\n LocalJWKMissing: 'jwk-local-missing',\n RemoteJWKFailedToLoad: 'jwk-remote-failed-to-load',\n RemoteJWKInvalid: 'jwk-remote-invalid',\n RemoteJWKMissing: 'jwk-remote-missing',\n JWKFailedToResolve: 'jwk-failed-to-resolve',\n JWKKidMismatch: 'jwk-kid-mismatch',\n};\n\nexport type TokenVerificationErrorReason =\n (typeof TokenVerificationErrorReason)[keyof typeof TokenVerificationErrorReason];\n\nexport const TokenVerificationErrorAction = {\n ContactSupport: 'Contact support@clerk.com',\n EnsureClerkJWT: 'Make sure that this is a valid Clerk-generated JWT.',\n SetClerkJWTKey: 'Set the CLERK_JWT_KEY environment variable.',\n SetClerkSecretKey: 'Set the CLERK_SECRET_KEY environment variable.',\n EnsureClockSync: 'Make sure your system clock is in sync (e.g. turn off and on automatic time synchronization).',\n};\n\nexport type TokenVerificationErrorAction =\n (typeof TokenVerificationErrorAction)[keyof typeof TokenVerificationErrorAction];\n\nexport class TokenVerificationError extends Error {\n action?: TokenVerificationErrorAction;\n reason: TokenVerificationErrorReason;\n tokenCarrier?: TokenCarrier;\n\n constructor({\n action,\n message,\n reason,\n }: {\n action?: TokenVerificationErrorAction;\n message: string;\n reason: TokenVerificationErrorReason;\n }) {\n super(message);\n\n Object.setPrototypeOf(this, TokenVerificationError.prototype);\n\n this.reason = reason;\n this.message = message;\n this.action = action;\n }\n\n public getFullMessage() {\n return `${[this.message, this.action].filter(m => m).join(' ')} (reason=${this.reason}, token-carrier=${\n this.tokenCarrier\n })`;\n }\n}\n\nexport class SignJWTError extends Error {}\n\nexport const MachineTokenVerificationErrorCode = {\n TokenInvalid: 'token-invalid',\n InvalidSecretKey: 'secret-key-invalid',\n UnexpectedError: 'unexpected-error',\n} as const;\n\nexport type MachineTokenVerificationErrorCode =\n (typeof MachineTokenVerificationErrorCode)[keyof typeof MachineTokenVerificationErrorCode];\n\nexport class MachineTokenVerificationError extends Error {\n code: MachineTokenVerificationErrorCode;\n long_message?: string;\n status: number;\n\n constructor({ message, code, status }: { message: string; code: MachineTokenVerificationErrorCode; status: number }) {\n super(message);\n Object.setPrototypeOf(this, MachineTokenVerificationError.prototype);\n\n this.code = code;\n this.status = status;\n }\n\n public getFullMessage() {\n return `${this.message} (code=${this.code}, status=${this.status})`;\n }\n}\n","/**\n * This file exports APIs that vary across runtimes (i.e. Node & Browser - V8 isolates)\n * as a singleton object.\n *\n * Runtime polyfills are written in VanillaJS for now to avoid TS complication. Moreover,\n * due to this issue https://github.com/microsoft/TypeScript/issues/44848, there is not a good way\n * to tell Typescript which conditional import to use during build type.\n *\n * The Runtime type definition ensures type safety for now.\n * Runtime js modules are copied into dist folder with bash script.\n *\n * TODO: Support TS runtime modules\n */\n\n// @ts-ignore - These are package subpaths\nimport { webcrypto as crypto } from '#crypto';\n\ntype Runtime = {\n crypto: Crypto;\n fetch: typeof globalThis.fetch;\n AbortController: typeof globalThis.AbortController;\n Blob: typeof globalThis.Blob;\n FormData: typeof globalThis.FormData;\n Headers: typeof globalThis.Headers;\n Request: typeof globalThis.Request;\n Response: typeof globalThis.Response;\n};\n\n// Invoking the global.fetch without binding it first to the globalObject fails in\n// Cloudflare Workers with an \"Illegal Invocation\" error.\n//\n// The globalThis object is supported for Node >= 12.0.\n//\n// https://github.com/supabase/supabase/issues/4417\nconst globalFetch = fetch.bind(globalThis);\n\nexport const runtime: Runtime = {\n crypto,\n get fetch() {\n // We need to use the globalFetch for Cloudflare Workers but the fetch for testing\n return process.env.NODE_ENV === 'test' ? fetch : globalFetch;\n },\n AbortController: globalThis.AbortController,\n Blob: globalThis.Blob,\n FormData: globalThis.FormData,\n Headers: globalThis.Headers,\n Request: globalThis.Request,\n Response: globalThis.Response,\n};\n","/**\n * The base64url helper was extracted from the rfc4648 package\n * in order to resolve CSJ/ESM interoperability issues\n *\n * https://github.com/swansontec/rfc4648.js\n *\n * For more context please refer to:\n * - https://github.com/evanw/esbuild/issues/1719\n * - https://github.com/evanw/esbuild/issues/532\n * - https://github.com/swansontec/rollup-plugin-mjs-entry\n */\nexport const base64url = {\n parse(string: string, opts?: ParseOptions): Uint8Array {\n return parse(string, base64UrlEncoding, opts);\n },\n\n stringify(data: ArrayLike<number>, opts?: StringifyOptions): string {\n return stringify(data, base64UrlEncoding, opts);\n },\n};\n\nconst base64UrlEncoding: Encoding = {\n chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bits: 6,\n};\n\ninterface Encoding {\n bits: number;\n chars: string;\n codes?: { [char: string]: number };\n}\n\ninterface ParseOptions {\n loose?: boolean;\n out?: new (size: number) => { [index: number]: number };\n}\n\ninterface StringifyOptions {\n pad?: boolean;\n}\n\nfunction parse(string: string, encoding: Encoding, opts: ParseOptions = {}): Uint8Array {\n // Build the character lookup table:\n if (!encoding.codes) {\n encoding.codes = {};\n for (let i = 0; i < encoding.chars.length; ++i) {\n encoding.codes[encoding.chars[i]] = i;\n }\n }\n\n // The string must have a whole number of bytes:\n if (!opts.loose && (string.length * encoding.bits) & 7) {\n throw new SyntaxError('Invalid padding');\n }\n\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n\n // If we get a whole number of bytes, there is too much padding:\n if (!opts.loose && !(((string.length - end) * encoding.bits) & 7)) {\n throw new SyntaxError('Invalid padding');\n }\n }\n\n // Allocate the output:\n const out = new (opts.out ?? Uint8Array)(((end * encoding.bits) / 8) | 0) as Uint8Array;\n\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = encoding.codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError('Invalid character ' + string[i]);\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << encoding.bits) | value;\n bits += encoding.bits;\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= encoding.bits || 0xff & (buffer << (8 - bits))) {\n throw new SyntaxError('Unexpected end of data');\n }\n\n return out;\n}\n\nfunction stringify(data: ArrayLike<number>, encoding: Encoding, opts: StringifyOptions = {}): string {\n const { pad = true } = opts;\n const mask = (1 << encoding.bits) - 1;\n let out = '';\n\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | (0xff & data[i]);\n bits += 8;\n\n // Write out as much as we can:\n while (bits > encoding.bits) {\n bits -= encoding.bits;\n out += encoding.chars[mask & (buffer >> bits)];\n }\n }\n\n // Partial character:\n if (bits) {\n out += encoding.chars[mask & (buffer << (encoding.bits - bits))];\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while ((out.length * encoding.bits) & 7) {\n out += '=';\n }\n }\n\n return out;\n}\n","const algToHash: Record<string, string> = {\n RS256: 'SHA-256',\n RS384: 'SHA-384',\n RS512: 'SHA-512',\n};\nconst RSA_ALGORITHM_NAME = 'RSASSA-PKCS1-v1_5';\n\nconst jwksAlgToCryptoAlg: Record<string, string> = {\n RS256: RSA_ALGORITHM_NAME,\n RS384: RSA_ALGORITHM_NAME,\n RS512: RSA_ALGORITHM_NAME,\n};\n\nexport const algs = Object.keys(algToHash);\n\nexport function getCryptoAlgorithm(algorithmName: string): RsaHashedImportParams {\n const hash = algToHash[algorithmName];\n const name = jwksAlgToCryptoAlg[algorithmName];\n\n if (!hash || !name) {\n throw new Error(`Unsupported algorithm ${algorithmName}, expected one of ${algs.join(',')}.`);\n }\n\n return {\n hash: { name: algToHash[algorithmName] },\n name: jwksAlgToCryptoAlg[algorithmName],\n };\n}\n","import { TokenVerificationError, TokenVerificationErrorAction, TokenVerificationErrorReason } from '../errors';\nimport { algs } from './algorithms';\n\nexport type IssuerResolver = string | ((iss: string) => boolean);\n\nconst isArrayString = (s: unknown): s is string[] => {\n return Array.isArray(s) && s.length > 0 && s.every(a => typeof a === 'string');\n};\n\nexport const assertAudienceClaim = (aud?: unknown, audience?: unknown) => {\n const audienceList = [audience].flat().filter(a => !!a);\n const audList = [aud].flat().filter(a => !!a);\n const shouldVerifyAudience = audienceList.length > 0 && audList.length > 0;\n\n if (!shouldVerifyAudience) {\n // Notice: Clerk JWTs use AZP claim instead of Audience\n //\n // return {\n // valid: false,\n // reason: `Invalid JWT audience claim (aud) ${JSON.stringify(\n // aud,\n // )}. Expected a string or a non-empty array of strings.`,\n // };\n return;\n }\n\n if (typeof aud === 'string') {\n if (!audienceList.includes(aud)) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT audience claim (aud) ${JSON.stringify(aud)}. Is not included in \"${JSON.stringify(\n audienceList,\n )}\".`,\n });\n }\n } else if (isArrayString(aud)) {\n if (!aud.some(a => audienceList.includes(a))) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT audience claim array (aud) ${JSON.stringify(aud)}. Is not included in \"${JSON.stringify(\n audienceList,\n )}\".`,\n });\n }\n }\n};\n\nexport const assertHeaderType = (typ?: unknown) => {\n if (typeof typ === 'undefined') {\n return;\n }\n\n if (typ !== 'JWT') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenInvalid,\n message: `Invalid JWT type ${JSON.stringify(typ)}. Expected \"JWT\".`,\n });\n }\n};\n\nexport const assertHeaderAlgorithm = (alg: string) => {\n if (!algs.includes(alg)) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenInvalidAlgorithm,\n message: `Invalid JWT algorithm ${JSON.stringify(alg)}. Supported: ${algs}.`,\n });\n }\n};\n\nexport const assertSubClaim = (sub?: string) => {\n if (typeof sub !== 'string') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Subject claim (sub) is required and must be a string. Received ${JSON.stringify(sub)}.`,\n });\n }\n};\n\nexport const assertAuthorizedPartiesClaim = (azp?: string, authorizedParties?: string[]) => {\n if (!azp || !authorizedParties || authorizedParties.length === 0) {\n return;\n }\n\n if (!authorizedParties.includes(azp)) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalidAuthorizedParties,\n message: `Invalid JWT Authorized party claim (azp) ${JSON.stringify(azp)}. Expected \"${authorizedParties}\".`,\n });\n }\n};\n\nexport const assertExpirationClaim = (exp: number, clockSkewInMs: number) => {\n if (typeof exp !== 'number') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT expiry date claim (exp) ${JSON.stringify(exp)}. Expected number.`,\n });\n }\n\n const currentDate = new Date(Date.now());\n const expiryDate = new Date(0);\n expiryDate.setUTCSeconds(exp);\n\n const expired = expiryDate.getTime() <= currentDate.getTime() - clockSkewInMs;\n if (expired) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenExpired,\n message: `JWT is expired. Expiry date: ${expiryDate.toUTCString()}, Current date: ${currentDate.toUTCString()}.`,\n });\n }\n};\n\nexport const assertActivationClaim = (nbf: number | undefined, clockSkewInMs: number) => {\n if (typeof nbf === 'undefined') {\n return;\n }\n\n if (typeof nbf !== 'number') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT not before date claim (nbf) ${JSON.stringify(nbf)}. Expected number.`,\n });\n }\n\n const currentDate = new Date(Date.now());\n const notBeforeDate = new Date(0);\n notBeforeDate.setUTCSeconds(nbf);\n\n const early = notBeforeDate.getTime() > currentDate.getTime() + clockSkewInMs;\n if (early) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenNotActiveYet,\n message: `JWT cannot be used prior to not before date claim (nbf). Not before date: ${notBeforeDate.toUTCString()}; Current date: ${currentDate.toUTCString()};`,\n });\n }\n};\n\nexport const assertIssuedAtClaim = (iat: number | undefined, clockSkewInMs: number) => {\n if (typeof iat === 'undefined') {\n return;\n }\n\n if (typeof iat !== 'number') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT issued at date claim (iat) ${JSON.stringify(iat)}. Expected number.`,\n });\n }\n\n const currentDate = new Date(Date.now());\n const issuedAtDate = new Date(0);\n issuedAtDate.setUTCSeconds(iat);\n\n const postIssued = issuedAtDate.getTime() > currentDate.getTime() + clockSkewInMs;\n if (postIssued) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenIatInTheFuture,\n message: `JWT issued at date claim (iat) is in the future. Issued at date: ${issuedAtDate.toUTCString()}; Current date: ${currentDate.toUTCString()};`,\n });\n }\n};\n","import { isomorphicAtob } from '@clerk/shared/isomorphicAtob';\n\nimport { runtime } from '../runtime';\n\n// https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#pkcs_8_import\nfunction pemToBuffer(secret: string): ArrayBuffer {\n const trimmed = secret\n .replace(/-----BEGIN.*?-----/g, '')\n .replace(/-----END.*?-----/g, '')\n .replace(/\\s/g, '');\n\n const decoded = isomorphicAtob(trimmed);\n\n const buffer = new ArrayBuffer(decoded.length);\n const bufView = new Uint8Array(buffer);\n\n for (let i = 0, strLen = decoded.length; i < strLen; i++) {\n bufView[i] = decoded.charCodeAt(i);\n }\n\n return bufView;\n}\n\nexport function importKey(\n key: JsonWebKey | string,\n algorithm: RsaHashedImportParams,\n keyUsage: 'verify' | 'sign',\n): Promise<CryptoKey> {\n if (typeof key === 'object') {\n return runtime.crypto.subtle.importKey('jwk', key, algorithm, false, [keyUsage]);\n }\n\n const keyData = pemToBuffer(key);\n const format = keyUsage === 'sign' ? 'pkcs8' : 'spki';\n\n return runtime.crypto.subtle.importKey(format, keyData, algorithm, false, [keyUsage]);\n}\n","import type { Jwt, JwtPayload } from '@clerk/shared/types';\n\nimport { TokenVerificationError, TokenVerificationErrorAction, TokenVerificationErrorReason } from '../errors';\nimport { runtime } from '../runtime';\nimport { base64url } from '../util/rfc4648';\nimport { getCryptoAlgorithm } from './algorithms';\nimport {\n assertActivationClaim,\n assertAudienceClaim,\n assertAuthorizedPartiesClaim,\n assertExpirationClaim,\n assertHeaderAlgorithm,\n assertHeaderType,\n assertIssuedAtClaim,\n assertSubClaim,\n} from './assertions';\nimport { importKey } from './cryptoKeys';\nimport type { JwtReturnType } from './types';\n\nconst DEFAULT_CLOCK_SKEW_IN_MS = 5 * 1000;\n\nexport async function hasValidSignature(jwt: Jwt, key: JsonWebKey | string): Promise<JwtReturnType<boolean, Error>> {\n const { header, signature, raw } = jwt;\n const encoder = new TextEncoder();\n const data = encoder.encode([raw.header, raw.payload].join('.'));\n const algorithm = getCryptoAlgorithm(header.alg);\n\n try {\n const cryptoKey = await importKey(key, algorithm, 'verify');\n\n const verified = await runtime.crypto.subtle.verify(algorithm.name, cryptoKey, signature, data);\n return { data: verified };\n } catch (error) {\n return {\n errors: [\n new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalidSignature,\n message: (error as Error)?.message,\n }),\n ],\n };\n }\n}\n\nexport function decodeJwt(token: string): JwtReturnType<Jwt, TokenVerificationError> {\n const tokenParts = (token || '').toString().split('.');\n if (tokenParts.length !== 3) {\n return {\n errors: [\n new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalid,\n message: `Invalid JWT form. A JWT consists of three parts separated by dots.`,\n }),\n ],\n };\n }\n\n const [rawHeader, rawPayload, rawSignature] = tokenParts;\n\n const decoder = new TextDecoder();\n\n // To verify a JWS with SubtleCrypto you need to be careful to encode and decode\n // the data properly between binary and base64url representation. Unfortunately\n // the standard implementation in the V8 of btoa() and atob() are difficult to\n // work with as they use \"a Unicode string containing only characters in the\n // range U+0000 to U+00FF, each representing a binary byte with values 0x00 to\n // 0xFF respectively\" as the representation of binary data.\n\n // A better solution to represent binary data in Javascript is to use ES6 TypedArray\n // and use a Javascript library to convert them to base64url that honors RFC 4648.\n\n // Side note: The difference between base64 and base64url is the characters selected\n // for value 62 and 63 in the standard, base64 encode them to + and / while base64url\n // encode - and _.\n\n // More info at https://stackoverflow.com/questions/54062583/how-to-verify-a-signed-jwt-with-subtlecrypto-of-the-web-crypto-API\n const header = JSON.parse(decoder.decode(base64url.parse(rawHeader, { loose: true })));\n const payload = JSON.parse(decoder.decode(base64url.parse(rawPayload, { loose: true })));\n\n const signature = base64url.parse(rawSignature, { loose: true });\n\n const data = {\n header,\n payload,\n signature,\n raw: {\n header: rawHeader,\n payload: rawPayload,\n signature: rawSignature,\n text: token,\n },\n } satisfies Jwt;\n\n return { data };\n}\n\n/**\n * @inline\n */\nexport type VerifyJwtOptions = {\n /**\n * A string or list of [audiences](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3). If passed, it is checked against the `aud` claim in the token.\n */\n audience?: string | string[];\n /**\n * An allowlist of origins to verify against, to protect your application from the subdomain cookie leaking attack.\n * @example\n * ```ts\n * ['http://localhost:3000', 'https://example.com']\n * ```\n */\n authorizedParties?: string[];\n /**\n * Specifies the allowed time difference (in milliseconds) between the Clerk server (which generates the token) and the clock of the user's application server when validating a token.\n * @default 5000\n */\n clockSkewInMs?: number;\n /**\n * @internal\n */\n key: JsonWebKey | string;\n};\n\nexport async function verifyJwt(\n token: string,\n options: VerifyJwtOptions,\n): Promise<JwtReturnType<JwtPayload, TokenVerificationError>> {\n const { audience, authorizedParties, clockSkewInMs, key } = options;\n const clockSkew = clockSkewInMs || DEFAULT_CLOCK_SKEW_IN_MS;\n\n const { data: decoded, errors } = decodeJwt(token);\n if (errors) {\n return { errors };\n }\n\n const { header, payload } = decoded;\n try {\n // Header verifications\n const { typ, alg } = header;\n\n assertHeaderType(typ);\n assertHeaderAlgorithm(alg);\n\n // Payload verifications\n const { azp, sub, aud, iat, exp, nbf } = payload;\n\n assertSubClaim(sub);\n assertAudienceClaim([aud], [audience]);\n assertAuthorizedPartiesClaim(azp, authorizedParties);\n assertExpirationClaim(exp, clockSkew);\n assertActivationClaim(nbf, clockSkew);\n assertIssuedAtClaim(iat, clockSkew);\n } catch (err) {\n return { errors: [err as TokenVerificationError] };\n }\n\n const { data: signatureValid, errors: signatureErrors } = await hasValidSignature(decoded, key);\n if (signatureErrors) {\n return {\n errors: [\n new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Error verifying JWT signature. ${signatureErrors[0]}`,\n }),\n ],\n };\n }\n\n if (!signatureValid) {\n return {\n errors: [\n new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalidSignature,\n message: 'JWT signature is invalid.',\n }),\n ],\n };\n }\n\n return { data: payload };\n}\n","import { parsePublishableKey } from './shared';\n\nexport function assertValidSecretKey(val: unknown): asserts val is string {\n if (!val || typeof val !== 'string') {\n throw Error('Missing Clerk Secret Key. Go to https://dashboard.clerk.com and get your key for your instance.');\n }\n\n //TODO: Check if the key is invalid and throw error\n}\n\nexport function assertValidPublishableKey(val: unknown): asserts val is string {\n parsePublishableKey(val as string | undefined, { fatal: true });\n}\n","import { buildAccountsBaseUrl } from '@clerk/shared/buildAccountsBaseUrl';\nimport type { Jwt } from '@clerk/shared/types';\nimport { isCurrentDevAccountPortalOrigin, isLegacyDevAccountPortalOrigin } from '@clerk/shared/url';\n\nimport { constants } from '../constants';\nimport { decodeJwt } from '../jwt/verifyJwt';\nimport { runtime } from '../runtime';\nimport { assertValidPublishableKey } from '../util/optionsAssertions';\nimport { getCookieSuffix, getSuffixedCookieName, parsePublishableKey } from '../util/shared';\nimport type { ClerkRequest } from './clerkRequest';\nimport { TokenType } from './tokenTypes';\nimport type { AuthenticateRequestOptions } from './types';\n\ninterface AuthenticateContext extends AuthenticateRequestOptions {\n // header-based values\n accept: string | undefined;\n forwardedHost: string | undefined;\n forwardedProto: string | undefined;\n host: string | undefined;\n origin: string | undefined;\n referrer: string | undefined;\n secFetchDest: string | undefined;\n tokenInHeader: string | undefined;\n userAgent: string | undefined;\n\n // cookie-based values\n clientUat: number;\n refreshTokenInCookie: string | undefined;\n sessionTokenInCookie: string | undefined;\n\n // handshake-related values\n devBrowserToken: string | undefined;\n handshakeNonce: string | undefined;\n handshakeRedirectLoopCounter: number;\n handshakeToken: string | undefined;\n\n // url derived from headers\n clerkUrl: URL;\n // enforce existence of the following props\n frontendApi: string;\n instanceType: string;\n publishableKey: string;\n}\n\n/**\n * All data required to authenticate a request.\n * This is the data we use to decide whether a request\n * is in a signed in or signed out state or if we need\n * to perform a handshake.\n */\nclass AuthenticateContext implements AuthenticateContext {\n /**\n * The original Clerk frontend API URL, extracted from publishable key before proxy URL override.\n * Used for backend operations like token validation and issuer checking.\n */\n private originalFrontendApi: string = '';\n\n /**\n * Retrieves the session token from either the cookie or the header.\n *\n * @returns {string | undefined} The session token if available, otherwise undefined.\n */\n public get sessionToken(): string | undefined {\n return this.sessionTokenInCookie || this.tokenInHeader;\n }\n\n public constructor(\n private cookieSuffix: string,\n private clerkRequest: ClerkRequest,\n options: AuthenticateRequestOptions,\n ) {\n if (options.acceptsToken === TokenType.M2MToken || options.acceptsToken === TokenType.ApiKey) {\n // For non-session tokens, we only want to set the header values.\n this.initHeaderValues();\n } else {\n // Even though the options are assigned to this later in this function\n // we set the publishableKey here because it is being used in cookies/headers/handshake-values\n // as part of getMultipleAppsCookie.\n this.initPublishableKeyValues(options);\n this.initHeaderValues();\n // initCookieValues should be used before initHandshakeValues because it depends on suffixedCookies\n this.initCookieValues();\n this.initHandshakeValues();\n }\n\n Object.assign(this, options);\n this.clerkUrl = this.clerkRequest.clerkUrl;\n }\n\n public usesSuffixedCookies(): boolean {\n const suffixedClientUat = this.getSuffixedCookie(constants.Cookies.ClientUat);\n const clientUat = this.getCookie(constants.Cookies.ClientUat);\n const suffixedSession = this.getSuffixedCookie(constants.Cookies.Session) || '';\n const session = this.getCookie(constants.Cookies.Session) || '';\n\n // In the case of malformed session cookies (eg missing the iss claim), we should\n // use the un-suffixed cookies to return signed-out state instead of triggering\n // handshake\n if (session && !this.tokenHasIssuer(session)) {\n return false;\n }\n\n // If there's a token in un-suffixed, and it doesn't belong to this\n // instance, then we must trust suffixed\n if (session && !this.tokenBelongsToInstance(session)) {\n return true;\n }\n\n // If there are no suffixed cookies use un-suffixed\n if (!suffixedClientUat && !suffixedSession) {\n return false;\n }\n\n const { data: sessionData } = decodeJwt(session);\n const sessionIat = sessionData?.payload.iat || 0;\n const { data: suffixedSessionData } = decodeJwt(suffixedSession);\n const suffixedSessionIat = suffixedSessionData?.payload.iat || 0;\n\n // Both indicate signed in, but un-suffixed is newer\n // Trust un-suffixed because it's newer\n if (suffixedClientUat !== '0' && clientUat !== '0' && sessionIat > suffixedSessionIat) {\n return false;\n }\n\n // Suffixed indicates signed out, but un-suffixed indicates signed in\n // Trust un-suffixed because it gets set with both new and old clerk.js,\n // so we can assume it's newer\n if (suffixedClientUat === '0' && clientUat !== '0') {\n return false;\n }\n\n // Suffixed indicates signed in, un-suffixed indicates signed out\n // This is the tricky one\n\n // In production, suffixed_uat should be set reliably, since it's\n // set by FAPI and not clerk.js. So in the scenario where a developer\n // downgrades, the state will look like this:\n // - un-suffixed session cookie: empty\n // - un-suffixed uat: 0\n // - suffixed session cookie: (possibly filled, possibly empty)\n // - suffixed uat: 0\n\n // Our SDK honors client_uat over the session cookie, so we don't\n // need a special case for production. We can rely on suffixed,\n // and the fact that the suffixed uat is set properly means and\n // suffixed session cookie will be ignored.\n\n // The important thing to make sure we have a test that confirms\n // the user ends up as signed out in this scenario, and the suffixed\n // session cookie is ignored\n\n // In development, suffixed_uat is not set reliably, since it's done\n // by clerk.js. If the developer downgrades to a pinned version of\n // clerk.js, the suffixed uat will no longer be updated\n\n // The best we can do is look to see if the suffixed token is expired.\n // This means that, if a developer downgrades, and then immediately\n // signs out, all in the span of 1 minute, then they will inadvertently\n // remain signed in for the rest of that minute. This is a known\n // limitation of the strategy but seems highly unlikely.\n if (this.instanceType !== 'production') {\n const isSuffixedSessionExpired = this.sessionExpired(suffixedSessionData);\n if (suffixedClientUat !== '0' && clientUat === '0' && isSuffixedSessionExpired) {\n return false;\n }\n }\n\n // If a suffixed session cookie exists but the corresponding client_uat cookie is missing, fallback to using\n // unsuffixed cookies.\n // This handles the scenario where an app has been deployed using an SDK version that supports suffixed\n // cookies, but FAPI for its Clerk instance has the feature disabled (eg: if we need to temporarily disable the feature).\n if (!suffixedClientUat && suffixedSession) {\n return false;\n }\n\n return true;\n }\n\n /**\n * Determines if the request came from a different origin based on the referrer header.\n * Used for cross-origin detection in multi-domain authentication flows.\n *\n * @returns {boolean} True if referrer exists and is from a different origin, false otherwise.\n */\n public isCrossOriginReferrer(): boolean {\n if (!this.referrer || !this.clerkUrl.origin) {\n return false;\n }\n\n try {\n const referrerOrigin = new URL(this.referrer).origin;\n return referrerOrigin !== this.clerkUrl.origin;\n } catch {\n // Invalid referrer URL format\n return false;\n }\n }\n\n /**\n * Determines if the referrer URL is from a Clerk domain (accounts portal or FAPI).\n * This includes both development and production account portal domains, as well as FAPI domains\n * used for redirect-based authentication flows.\n *\n * @returns {boolean} True if the referrer is from a Clerk accounts portal or FAPI domain, false otherwise\n */\n public isKnownClerkReferrer(): boolean {\n if (!this.referrer) {\n return false;\n }\n\n try {\n const referrerOrigin = new URL(this.referrer);\n const referrerHost = referrerOrigin.hostname;\n\n // Check if referrer is the FAPI domain itself (redirect-based auth flows)\n if (this.frontendApi) {\n const fapiHost = this.frontendApi.startsWith('http') ? new URL(this.frontendApi).hostname : this.frontendApi;\n if (referrerHost === fapiHost) {\n return true;\n }\n }\n\n // Check for development account portal patterns\n if (isLegacyDevAccountPortalOrigin(referrerHost) || isCurrentDevAccountPortalOrigin(referrerHost)) {\n return true;\n }\n\n // Check for production account portal by comparing with expected accounts URL\n const expectedAccountsUrl = buildAccountsBaseUrl(this.frontendApi);\n if (expectedAccountsUrl) {\n const expectedAccountsOrigin = new URL(expectedAccountsUrl).origin;\n if (referrerOrigin.origin === expectedAccountsOrigin) {\n return true;\n }\n }\n\n // Check for generic production accounts patterns (accounts.*)\n if (referrerHost.startsWith('accounts.')) {\n return true;\n }\n\n return false;\n } catch {\n // Invalid URL format\n return false;\n }\n }\n\n private initPublishableKeyValues(options: AuthenticateRequestOptions) {\n assertValidPublishableKey(options.publishableKey);\n this.publishableKey = options.publishableKey;\n\n const originalPk = parsePublishableKey(this.publishableKey, {\n fatal: true,\n domain: options.domain,\n isSatellite: options.isSatellite,\n });\n this.originalFrontendApi = originalPk.frontendApi;\n\n const pk = parsePublishableKey(this.publishableKey, {\n fatal: true,\n proxyUrl: options.proxyUrl,\n domain: options.domain,\n isSatellite: options.isSatellite,\n });\n this.instanceType = pk.instanceType;\n this.frontendApi = pk.frontendApi;\n }\n\n private initHeaderValues() {\n this.tokenInHeader = this.parseAuthorizationHeader(this.getHeader(constants.Headers.Authorization));\n this.origin = this.getHeader(constants.Headers.Origin);\n this.host = this.getHeader(constants.Headers.Host);\n this.forwardedHost = this.getHeader(constants.Headers.ForwardedHost);\n this.forwardedProto =\n this.getHeader(constants.Headers.CloudFrontForwardedProto) || this.getHeader(constants.Headers.ForwardedProto);\n this.referrer = this.getHeader(constants.Headers.Referrer);\n this.userAgent = this.getHeader(constants.Headers.UserAgent);\n this.secFetchDest = this.getHeader(constants.Headers.SecFetchDest);\n this.accept = this.getHeader(constants.Headers.Accept);\n }\n\n private initCookieValues() {\n // suffixedCookies needs to be set first because it's used in getMultipleAppsCookie\n this.sessionTokenInCookie = this.getSuffixedOrUnSuffixedCookie(constants.Cookies.Session);\n this.refreshTokenInCookie = this.getSuffixedCookie(constants.Cookies.Refresh);\n this.clientUat = Number.parseInt(this.getSuffixedOrUnSuffixedCookie(constants.Cookies.ClientUat) || '') || 0;\n }\n\n private initHandshakeValues() {\n this.devBrowserToken =\n this.getQueryParam(constants.QueryParameters.DevBrowser) ||\n this.getSuffixedOrUnSuffixedCookie(constants.Cookies.DevBrowser);\n // Using getCookie since we don't suffix the handshake token cookie\n this.handshakeToken =\n this.getQueryParam(constants.QueryParameters.Handshake) || this.getCookie(constants.Cookies.Handshake);\n this.handshakeRedirectLoopCounter = Number(this.getCookie(constants.Cookies.RedirectCount)) || 0;\n this.handshakeNonce =\n this.getQueryParam(constants.QueryParameters.HandshakeNonce) || this.getCookie(constants.Cookies.HandshakeNonce);\n }\n\n private getQueryParam(name: string) {\n return this.clerkRequest.clerkUrl.searchParams.get(name);\n }\n\n private getHeader(name: string) {\n return this.clerkRequest.headers.get(name) || undefined;\n }\n\n private getCookie(name: string) {\n return this.clerkRequest.cookies.get(name) || undefined;\n }\n\n private getSuffixedCookie(name: string) {\n return this.getCookie(getSuffixedCookieName(name, this.cookieSuffix)) || undefined;\n }\n\n private getSuffixedOrUnSuffixedCookie(cookieName: string) {\n if (this.usesSuffixedCookies()) {\n return this.getSuffixedCookie(cookieName);\n }\n return this.getCookie(cookieName);\n }\n\n private parseAuthorizationHeader(authorizationHeader: string | undefined | null): string | undefined {\n if (!authorizationHeader) {\n return undefined;\n }\n\n const [scheme, token] = authorizationHeader.split(' ', 2);\n\n if (!token) {\n // No scheme specified, treat the entire value as the token\n return scheme;\n }\n\n if (scheme === 'Bearer') {\n return token;\n }\n\n // Skip all other schemes\n return undefined;\n }\n\n private tokenHasIssuer(token: string): boolean {\n const { data, errors } = decodeJwt(token);\n if (errors) {\n return false;\n }\n return !!data.payload.iss;\n }\n\n private tokenBelongsToInstance(token: string): boolean {\n if (!token) {\n return false;\n }\n\n const { data, errors } = decodeJwt(token);\n if (errors) {\n return false;\n }\n const tokenIssuer = data.payload.iss.replace(/https?:\\/\\//gi, '');\n // Use original frontend API for token validation since tokens are issued by the actual Clerk API, not proxy\n return this.originalFrontendApi === tokenIssuer;\n }\n\n private sessionExpired(jwt: Jwt | undefined): boolean {\n return !!jwt && jwt?.payload.exp <= (Date.now() / 1000) >> 0;\n }\n}\n\nexport type { AuthenticateContext };\n\nexport const createAuthenticateContext = async (\n clerkRequest: ClerkRequest,\n options: AuthenticateRequestOptions,\n): Promise<AuthenticateContext> => {\n const cookieSuffix = options.publishableKey\n ? await getCookieSuffix(options.publishableKey, runtime.crypto.subtle)\n : '';\n return new AuthenticateContext(cookieSuffix, clerkRequest, options);\n};\n","export const TokenType = {\n SessionToken: 'session_token',\n ApiKey: 'api_key',\n M2MToken: 'm2m_token',\n OAuthToken: 'oauth_token',\n} as const;\n\n/**\n * @inline\n */\nexport type TokenType = (typeof TokenType)[keyof typeof TokenType];\n\n/**\n * @inline\n */\nexport type SessionTokenType = typeof TokenType.SessionToken;\n/**\n * @inline\n */\nexport type MachineTokenType = Exclude<TokenType, SessionTokenType>;\n","import { createCheckAuthorization } from '@clerk/shared/authorization';\nimport { __experimental_JWTPayloadToAuthObjectProperties } from '@clerk/shared/jwtPayloadParser';\nimport type {\n CheckAuthorizationFromSessionClaims,\n Jwt,\n JwtPayload,\n PendingSessionOptions,\n ServerGetToken,\n ServerGetTokenOptions,\n SessionStatusClaim,\n SharedSignedInAuthObjectProperties,\n} from '@clerk/shared/types';\n\nimport type { APIKey, CreateBackendApiOptions, IdPOAuthAccessToken, M2MToken } from '../api';\nimport { createBackendApiClient } from '../api';\nimport { isTokenTypeAccepted } from '../internal';\nimport type { AuthenticateContext } from './authenticateContext';\nimport { isMachineTokenType } from './machine';\nimport type { MachineTokenType, SessionTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\nimport type { AuthenticateRequestOptions, MachineAuthType } from './types';\n\n/**\n * @inline\n */\ntype AuthObjectDebugData = Record<string, any>;\n/**\n * @inline\n */\ntype AuthObjectDebug = () => AuthObjectDebugData;\n\ntype Claims = Record<string, any>;\n\n/**\n * @internal\n */\nexport type SignedInAuthObjectOptions = CreateBackendApiOptions & {\n token: string;\n};\n\n/**\n * @internal\n */\nexport type SignedInAuthObject = SharedSignedInAuthObjectProperties & {\n /**\n * The allowed token type.\n */\n tokenType: SessionTokenType;\n /**\n * A function that gets the current user's [session token](https://clerk.com/docs/guides/sessions/session-tokens) or a [custom JWT template](https://clerk.com/docs/guides/sessions/jwt-templates).\n */\n getToken: ServerGetToken;\n /**\n * A function that checks if the user has an organization role or custom permission.\n */\n has: CheckAuthorizationFromSessionClaims;\n /**\n * Used to help debug issues when using Clerk in development.\n */\n debug: AuthObjectDebug;\n isAuthenticated: true;\n};\n\n/**\n * @internal\n */\nexport type SignedOutAuthObject = {\n sessionClaims: null;\n sessionId: null;\n sessionStatus: SessionStatusClaim | null;\n actor: null;\n tokenType: SessionTokenType;\n userId: null;\n orgId: null;\n orgRole: null;\n orgSlug: null;\n orgPermissions: null;\n factorVerificationAge: null;\n getToken: ServerGetToken;\n has: CheckAuthorizationFromSessionClaims;\n debug: AuthObjectDebug;\n isAuthenticated: false;\n};\n\n/**\n * Extended properties specific to each machine token type.\n * While all machine token types share common properties (id, name, subject, etc),\n * this type defines the additional properties that are unique to each token type.\n *\n * @template TAuthenticated - Whether the machine object is authenticated or not\n */\ntype MachineObjectExtendedProperties<TAuthenticated extends boolean> = {\n api_key: TAuthenticated extends true\n ?\n | { name: string; claims: Claims | null; userId: string; orgId: null }\n | { name: string; claims: Claims | null; userId: null; orgId: string }\n : { name: null; claims: null; userId: null; orgId: null };\n m2m_token: {\n claims: TAuthenticated extends true ? Claims | null : null;\n machineId: TAuthenticated extends true ? string : null;\n };\n oauth_token: {\n userId: TAuthenticated extends true ? string : null;\n clientId: TAuthenticated extends true ? string : null;\n };\n};\n\n/**\n * @internal\n *\n * Uses `T extends any` to create a distributive conditional type.\n * This ensures that union types like `'api_key' | 'oauth_token'` are processed\n * individually, creating proper discriminated unions where each token type\n * gets its own distinct properties (e.g., oauth_token won't have claims).\n */\nexport type AuthenticatedMachineObject<T extends MachineTokenType = MachineTokenType> = T extends any\n ? {\n id: string;\n subject: string;\n scopes: string[];\n getToken: () => Promise<string>;\n has: CheckAuthorizationFromSessionClaims;\n debug: AuthObjectDebug;\n tokenType: T;\n isAuthenticated: true;\n } & MachineObjectExtendedProperties<true>[T]\n : never;\n\n/**\n * @internal\n *\n * Uses `T extends any` to create a distributive conditional type.\n * This ensures that union types like `'api_key' | 'oauth_token'` are processed\n * individually, creating proper discriminated unions where each token type\n * gets its own distinct properties (e.g., oauth_token won't have claims).\n */\nexport type UnauthenticatedMachineObject<T extends MachineTokenType = MachineTokenType> = T extends any\n ? {\n id: null;\n subject: null;\n scopes: null;\n getToken: () => Promise<null>;\n has: CheckAuthorizationFromSessionClaims;\n debug: AuthObjectDebug;\n tokenType: T;\n isAuthenticated: false;\n } & MachineObjectExtendedProperties<false>[T]\n : never;\n\nexport type InvalidTokenAuthObject = {\n isAuthenticated: false;\n tokenType: null;\n getToken: () => Promise<null>;\n has: () => false;\n debug: AuthObjectDebug;\n};\n\n/**\n * @interface\n */\nexport type AuthObject =\n | SignedInAuthObject\n | SignedOutAuthObject\n | AuthenticatedMachineObject\n | UnauthenticatedMachineObject\n | InvalidTokenAuthObject;\n\nconst createDebug = (data: AuthObjectDebugData | undefined) => {\n return () => {\n const res = { ...data };\n res.secretKey = (res.secretKey || '').substring(0, 7);\n res.jwtKey = (res.jwtKey || '').substring(0, 7);\n return { ...res };\n };\n};\n\n/**\n * @internal\n */\nexport function signedInAuthObject(\n authenticateContext: Partial<AuthenticateContext>,\n sessionToken: string,\n sessionClaims: JwtPayload,\n): SignedInAuthObject {\n const { actor, sessionId, sessionStatus, userId, orgId, orgRole, orgSlug, orgPermissions, factorVerificationAge } =\n __experimental_JWTPayloadToAuthObjectProperties(sessionClaims);\n const apiClient = createBackendApiClient(authenticateContext);\n const getToken = createGetToken({\n sessionId,\n sessionToken,\n fetcher: async (sessionId, template, expiresInSeconds) =>\n (await apiClient.sessions.getToken(sessionId, template || '', expiresInSeconds)).jwt,\n });\n return {\n tokenType: TokenType.SessionToken,\n actor,\n sessionClaims,\n sessionId,\n sessionStatus,\n userId,\n orgId,\n orgRole,\n orgSlug,\n orgPermissions,\n factorVerificationAge,\n getToken,\n has: createCheckAuthorization({\n orgId,\n orgRole,\n orgPermissions,\n userId,\n factorVerificationAge,\n features: (sessionClaims.fea as string) || '',\n plans: (sessionClaims.pla as string) || '',\n }),\n debug: createDebug({ ...authenticateContext, sessionToken }),\n isAuthenticated: true,\n };\n}\n\n/**\n * @internal\n */\nexport function signedOutAuthObject(\n debugData?: AuthObjectDebugData,\n initialSessionStatus?: SessionStatusClaim,\n): SignedOutAuthObject {\n return {\n tokenType: TokenType.SessionToken,\n sessionClaims: null,\n sessionId: null,\n sessionStatus: initialSessionStatus ?? null,\n userId: null,\n actor: null,\n orgId: null,\n orgRole: null,\n orgSlug: null,\n orgPermissions: null,\n factorVerificationAge: null,\n getToken: () => Promise.resolve(null),\n has: () => false,\n debug: createDebug(debugData),\n isAuthenticated: false,\n };\n}\n\n/**\n * @internal\n */\nexport function authenticatedMachineObject<T extends MachineTokenType>(\n tokenType: T,\n token: string,\n verificationResult: MachineAuthType,\n debugData?: AuthObjectDebugData,\n): AuthenticatedMachineObject<T> {\n const baseObject = {\n id: verificationResult.id,\n subject: verificationResult.subject,\n getToken: () => Promise.resolve(token),\n has: () => false,\n debug: createDebug(debugData),\n isAuthenticated: true,\n };\n\n // Type assertions are safe here since we know the verification result type matches the tokenType.\n // We need these assertions because TS can't infer the specific type\n // just from the tokenType discriminator.\n\n switch (tokenType) {\n case TokenType.ApiKey: {\n const result = verificationResult as APIKey;\n return {\n ...baseObject,\n tokenType,\n name: result.name,\n claims: result.claims,\n scopes: result.scopes,\n userId: result.subject.startsWith('user_') ? result.subject : null,\n orgId: result.subject.startsWith('org_') ? result.subject : null,\n } as unknown as AuthenticatedMachineObject<T>;\n }\n case TokenType.M2MToken: {\n const result = verificationResult as M2MToken;\n return {\n ...baseObject,\n tokenType,\n claims: result.claims,\n scopes: result.scopes,\n machineId: result.subject,\n } as unknown as AuthenticatedMachineObject<T>;\n }\n case TokenType.OAuthToken: {\n const result = verificationResult as IdPOAuthAccessToken;\n return {\n ...baseObject,\n tokenType,\n scopes: result.scopes,\n userId: result.subject,\n clientId: result.clientId,\n } as unknown as AuthenticatedMachineObject<T>;\n }\n default:\n throw new Error(`Invalid token type: ${tokenType}`);\n }\n}\n\n/**\n * @internal\n */\nexport function unauthenticatedMachineObject<T extends MachineTokenType>(\n tokenType: T,\n debugData?: AuthObjectDebugData,\n): UnauthenticatedMachineObject<T> {\n const baseObject = {\n id: null,\n subject: null,\n scopes: null,\n has: () => false,\n getToken: () => Promise.resolve(null),\n debug: createDebug(debugData),\n isAuthenticated: false,\n };\n\n switch (tokenType) {\n case TokenType.ApiKey: {\n return {\n ...baseObject,\n tokenType,\n name: null,\n claims: null,\n scopes: null,\n userId: null,\n orgId: null,\n } as unknown as UnauthenticatedMachineObject<T>;\n }\n case TokenType.M2MToken: {\n return {\n ...baseObject,\n tokenType,\n claims: null,\n scopes: null,\n machineId: null,\n } as unknown as UnauthenticatedMachineObject<T>;\n }\n case TokenType.OAuthToken: {\n return {\n ...baseObject,\n tokenType,\n scopes: null,\n userId: null,\n clientId: null,\n } as unknown as UnauthenticatedMachineObject<T>;\n }\n default:\n throw new Error(`Invalid token type: ${tokenType}`);\n }\n}\n\n/**\n * @internal\n */\nexport function invalidTokenAuthObject(): InvalidTokenAuthObject {\n return {\n isAuthenticated: false,\n tokenType: null,\n getToken: () => Promise.resolve(null),\n has: () => false,\n debug: () => ({}),\n };\n}\n\n/**\n * Auth objects moving through the server -> client boundary need to be serializable\n * as we need to ensure that they can be transferred via the network as pure strings.\n * Some frameworks like Remix or Next (/pages dir only) handle this serialization by simply\n * ignoring any non-serializable keys, however Nextjs /app directory is stricter and\n * throws an error if a non-serializable value is found.\n *\n * @internal\n */\nexport const makeAuthObjectSerializable = <T extends Record<string, unknown>>(obj: T): T => {\n // remove any non-serializable props from the returned object\n\n const { debug, getToken, has, ...rest } = obj as unknown as AuthObject;\n return rest as unknown as T;\n};\n\n/**\n * A function that fetches a session token from the Clerk API.\n *\n * @param sessionId - The ID of the session\n * @param template - The JWT template name to use for token generation\n * @param expiresInSeconds - Optional expiration time in seconds for the token\n * @returns A promise that resolves to the token string\n */\ntype TokenFetcher = (sessionId: string, template?: string, expiresInSeconds?: number) => Promise<string>;\n\n/**\n * Factory function type that creates a getToken function for auth objects.\n *\n * @param params - Configuration object containing session information and token fetcher\n * @returns A ServerGetToken function that can be used to retrieve tokens\n */\ntype CreateGetToken = (params: { sessionId: string; sessionToken: string; fetcher: TokenFetcher }) => ServerGetToken;\n\n/**\n * Creates a token retrieval function for authenticated sessions.\n *\n * This factory function returns a getToken function that can either return the raw session token\n * or generate a JWT using a specified template with optional custom expiration.\n *\n * @param params - Configuration object\n * @param params.sessionId - The session ID for token generation\n * @param params.sessionToken - The raw session token to return when no template is specified\n * @param params.fetcher - Function to fetch tokens from the Clerk API\n *\n * @returns A function that retrieves tokens based on the provided options\n */\nconst createGetToken: CreateGetToken = params => {\n const { fetcher, sessionToken, sessionId } = params || {};\n\n return async (options: ServerGetTokenOptions = {}) => {\n if (!sessionId) {\n return null;\n }\n\n if (options.template || options.expiresInSeconds !== undefined) {\n return fetcher(sessionId, options.template, options.expiresInSeconds);\n }\n\n return sessionToken;\n };\n};\n\n/**\n * @internal\n */\nexport const getAuthObjectFromJwt = (\n jwt: Jwt,\n { treatPendingAsSignedOut = true, ...options }: PendingSessionOptions & Partial<AuthenticateContext>,\n) => {\n const authObject = signedInAuthObject(options, jwt.raw.text, jwt.payload);\n\n if (treatPendingAsSignedOut && authObject.sessionStatus === 'pending') {\n return signedOutAuthObject(options, authObject.sessionStatus);\n }\n\n return authObject;\n};\n\n/**\n * @internal\n * Returns an auth object matching the requested token type(s).\n *\n * If the parsed token type does not match any in acceptsToken, returns:\n * - an invalid token auth object if the token is not in the accepted array\n * - an unauthenticated machine object for machine tokens, or\n * - a signed-out session object otherwise.\n *\n * This ensures the returned object always matches the developer's intent.\n */\nexport const getAuthObjectForAcceptedToken = ({\n authObject,\n acceptsToken = TokenType.SessionToken,\n}: {\n authObject: AuthObject;\n acceptsToken: AuthenticateRequestOptions['acceptsToken'];\n}): AuthObject => {\n // 1. any token: return as-is\n if (acceptsToken === 'any') {\n return authObject;\n }\n\n // 2. array of tokens: must match one of the accepted types\n if (Array.isArray(acceptsToken)) {\n if (!isTokenTypeAccepted(authObject.tokenType, acceptsToken)) {\n return invalidTokenAuthObject();\n }\n return authObject;\n }\n\n // 3. single token: must match exactly, else return appropriate unauthenticated object\n if (!isTokenTypeAccepted(authObject.tokenType, acceptsToken)) {\n if (isMachineTokenType(acceptsToken)) {\n return unauthenticatedMachineObject(acceptsToken, authObject.debug);\n }\n return signedOutAuthObject(authObject.debug);\n }\n\n // 4. default: return as-is\n return authObject;\n};\n","const SEPARATOR = '/';\nconst MULTIPLE_SEPARATOR_REGEX = new RegExp('(?<!:)' + SEPARATOR + '{1,}', 'g');\n\ntype PathString = string | null | undefined;\n\nexport function joinPaths(...args: PathString[]): string {\n return args\n .filter(p => p)\n .join(SEPARATOR)\n .replace(MULTIPLE_SEPARATOR_REGEX, SEPARATOR);\n}\n","import type { RequestFunction } from '../request';\n\nexport abstract class AbstractAPI {\n constructor(protected request: RequestFunction) {}\n\n protected requireId(id: string) {\n if (!id) {\n throw new Error('A valid resource ID is required.');\n }\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { ActorToken } from '../resources/ActorToken';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/actor_tokens';\n\ntype ActorTokenActorCreateParams = {\n /**\n * The ID of the actor.\n */\n sub: string;\n /**\n * Additional properties of the actor.\n */\n additionalProperties?: { [k: string]: any };\n};\n\ntype ActorTokenCreateParams = {\n /**\n * The ID of the user being impersonated.\n */\n userId: string;\n /**\n * The actor payload. It needs to include a sub property which should contain the ID of the actor.\n *\n * @remarks\n * This whole payload will be also included in the JWT session token.\n */\n actor: ActorTokenActorCreateParams;\n /**\n * Optional parameter to specify the life duration of the actor token in seconds.\n *\n * @remarks\n * By default, the duration is 1 hour.\n */\n expiresInSeconds?: number | undefined;\n /**\n * The maximum duration that the session which will be created by the generated actor token should last.\n *\n * @remarks\n * By default, the duration of a session created via an actor token, lasts 30 minutes.\n */\n sessionMaxDurationInSeconds?: number | undefined;\n};\n\nexport class ActorTokenAPI extends AbstractAPI {\n public async create(params: ActorTokenCreateParams) {\n return this.request<ActorToken>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async revoke(actorTokenId: string) {\n this.requireId(actorTokenId);\n return this.request<ActorToken>({\n method: 'POST',\n path: joinPaths(basePath, actorTokenId, 'revoke'),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { AccountlessApplication } from '../resources/AccountlessApplication';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/accountless_applications';\n\nexport class AccountlessApplicationAPI extends AbstractAPI {\n public async createAccountlessApplication(params?: { requestHeaders?: Headers }) {\n const headerParams = params?.requestHeaders ? Object.fromEntries(params.requestHeaders.entries()) : undefined;\n return this.request<AccountlessApplication>({\n method: 'POST',\n path: basePath,\n headerParams,\n });\n }\n\n public async completeAccountlessApplicationOnboarding(params?: { requestHeaders?: Headers }) {\n const headerParams = params?.requestHeaders ? Object.fromEntries(params.requestHeaders.entries()) : undefined;\n return this.request<AccountlessApplication>({\n method: 'POST',\n path: joinPaths(basePath, 'complete'),\n headerParams,\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { AllowlistIdentifier } from '../resources/AllowlistIdentifier';\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/allowlist_identifiers';\n\ntype AllowlistIdentifierCreateParams = {\n identifier: string;\n notify: boolean;\n};\n\nexport class AllowlistIdentifierAPI extends AbstractAPI {\n public async getAllowlistIdentifierList(params: ClerkPaginationRequest = {}) {\n return this.request<PaginatedResourceResponse<AllowlistIdentifier[]>>({\n method: 'GET',\n path: basePath,\n queryParams: { ...params, paginated: true },\n });\n }\n\n public async createAllowlistIdentifier(params: AllowlistIdentifierCreateParams) {\n return this.request<AllowlistIdentifier>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async deleteAllowlistIdentifier(allowlistIdentifierId: string) {\n this.requireId(allowlistIdentifierId);\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, allowlistIdentifierId),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\n\nimport type { PaginatedResourceResponse } from '../../api/resources/Deserializer';\nimport { joinPaths } from '../../util/path';\nimport { deprecated } from '../../util/shared';\nimport type { APIKey } from '../resources/APIKey';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/api_keys';\n\ntype GetAPIKeyListParams = ClerkPaginationRequest<{\n /**\n * The user or organization ID to query API keys by\n */\n subject: string;\n /**\n * Whether to include invalid API keys.\n *\n * @default false\n */\n includeInvalid?: boolean;\n}>;\n\ntype CreateAPIKeyParams = {\n /**\n * API key name\n */\n name: string;\n /**\n * The user or organization ID to associate the API key with\n */\n subject: string;\n /**\n * API key description\n */\n description?: string | null;\n claims?: Record<string, any> | null;\n scopes?: string[];\n createdBy?: string | null;\n secondsUntilExpiration?: number | null;\n};\n\ntype RevokeAPIKeyParams = {\n /**\n * API key ID\n */\n apiKeyId: string;\n /**\n * Reason for revocation\n */\n revocationReason?: string | null;\n};\n\nexport class APIKeysAPI extends AbstractAPI {\n async list(queryParams: GetAPIKeyListParams) {\n return this.request<PaginatedResourceResponse<APIKey[]>>({\n method: 'GET',\n path: basePath,\n queryParams,\n });\n }\n\n async create(params: CreateAPIKeyParams) {\n return this.request<APIKey>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n async revoke(params: RevokeAPIKeyParams) {\n const { apiKeyId, ...bodyParams } = params;\n\n this.requireId(apiKeyId);\n\n return this.request<APIKey>({\n method: 'POST',\n path: joinPaths(basePath, apiKeyId, 'revoke'),\n bodyParams,\n });\n }\n\n async getSecret(apiKeyId: string) {\n this.requireId(apiKeyId);\n\n return this.request<{ secret: string }>({\n method: 'GET',\n path: joinPaths(basePath, apiKeyId, 'secret'),\n });\n }\n\n async verify(secret: string) {\n return this.request<APIKey>({\n method: 'POST',\n path: joinPaths(basePath, 'verify'),\n bodyParams: { secret },\n });\n }\n\n /**\n * @deprecated Use `verify()` instead. This method will be removed in the next major release.\n */\n async verifySecret(secret: string) {\n deprecated('apiKeys.verifySecret()', 'Use `apiKeys.verify()` instead.');\n return this.verify(secret);\n }\n}\n","import { joinPaths } from '../../util/path';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/beta_features';\n\ntype ChangeDomainParams = {\n /**\n * The new home URL of the production instance e.g. https://www.example.com\n */\n homeUrl?: string;\n /**\n * Whether this is a domain for a secondary app, meaning that any subdomain\n * provided is significant and will be stored as part of the domain. This is\n * useful for supporting multiple apps (one primary and multiple secondaries)\n * on the same root domain (eTLD+1).\n */\n isSecondary?: boolean;\n};\n\nexport class BetaFeaturesAPI extends AbstractAPI {\n /**\n * Change the domain of a production instance.\n *\n * Changing the domain requires updating the DNS records accordingly, deploying new SSL certificates,\n * updating your Social Connection's redirect URLs and setting the new keys in your code.\n *\n * @remarks\n * WARNING: Changing your domain will invalidate all current user sessions (i.e. users will be logged out).\n * Also, while your application is being deployed, a small downtime is expected to occur.\n */\n public async changeDomain(params: ChangeDomainParams) {\n return this.request<void>({\n method: 'POST',\n path: joinPaths(basePath, 'change_domain'),\n bodyParams: params,\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { BlocklistIdentifier } from '../resources/BlocklistIdentifier';\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/blocklist_identifiers';\n\ntype BlocklistIdentifierCreateParams = {\n identifier: string;\n};\n\nexport class BlocklistIdentifierAPI extends AbstractAPI {\n public async getBlocklistIdentifierList(params: ClerkPaginationRequest = {}) {\n return this.request<PaginatedResourceResponse<BlocklistIdentifier[]>>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async createBlocklistIdentifier(params: BlocklistIdentifierCreateParams) {\n return this.request<BlocklistIdentifier>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async deleteBlocklistIdentifier(blocklistIdentifierId: string) {\n this.requireId(blocklistIdentifierId);\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, blocklistIdentifierId),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { Client } from '../resources/Client';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { HandshakePayload } from '../resources/HandshakePayload';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/clients';\n\ntype GetHandshakePayloadParams = {\n nonce: string;\n};\n\nexport class ClientAPI extends AbstractAPI {\n public async getClientList(params: ClerkPaginationRequest = {}) {\n return this.request<PaginatedResourceResponse<Client[]>>({\n method: 'GET',\n path: basePath,\n queryParams: { ...params, paginated: true },\n });\n }\n\n public async getClient(clientId: string) {\n this.requireId(clientId);\n return this.request<Client>({\n method: 'GET',\n path: joinPaths(basePath, clientId),\n });\n }\n\n public verifyClient(token: string) {\n return this.request<Client>({\n method: 'POST',\n path: joinPaths(basePath, 'verify'),\n bodyParams: { token },\n });\n }\n\n public async getHandshakePayload(queryParams: GetHandshakePayloadParams) {\n return this.request<HandshakePayload>({\n method: 'GET',\n path: joinPaths(basePath, 'handshake_payload'),\n queryParams,\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { Domain } from '../resources/Domain';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/domains';\n\ntype AddDomainParams = {\n /**\n * The new domain name. For development instances, can contain the port, i.e myhostname:3000. For production instances, must be a valid FQDN, i.e mysite.com. Cannot contain protocol scheme.\n */\n name: string;\n /**\n * Marks the new domain as satellite. Only true is accepted at the moment.\n */\n is_satellite: boolean;\n /**\n * The full URL of the proxy which will forward requests to the Clerk Frontend API for this domain. Applicable only to production instances.\n */\n proxy_url?: string | null;\n};\n\ntype UpdateDomainParams = Partial<Pick<AddDomainParams, 'name' | 'proxy_url'>> & {\n /**\n * The ID of the domain that will be updated.\n */\n domainId: string;\n /**\n * Whether this is a domain for a secondary app, meaning that any subdomain provided is significant\n * and will be stored as part of the domain. This is useful for supporting multiple apps\n * (one primary and multiple secondaries) on the same root domain (eTLD+1).\n */\n is_secondary?: boolean | null;\n};\n\nexport class DomainAPI extends AbstractAPI {\n public async list() {\n return this.request<PaginatedResourceResponse<Domain[]>>({\n method: 'GET',\n path: basePath,\n });\n }\n\n public async add(params: AddDomainParams) {\n return this.request<Domain>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async update(params: UpdateDomainParams) {\n const { domainId, ...bodyParams } = params;\n\n this.requireId(domainId);\n\n return this.request<Domain>({\n method: 'PATCH',\n path: joinPaths(basePath, domainId),\n bodyParams: bodyParams,\n });\n }\n\n /**\n * Deletes a satellite domain for the instance.\n * It is currently not possible to delete the instance's primary domain.\n */\n public async delete(satelliteDomainId: string) {\n return this.deleteDomain(satelliteDomainId);\n }\n\n /**\n * @deprecated Use `delete` instead\n */\n public async deleteDomain(satelliteDomainId: string) {\n this.requireId(satelliteDomainId);\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, satelliteDomainId),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { DeletedObject, EmailAddress } from '../resources';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/email_addresses';\n\ntype CreateEmailAddressParams = {\n userId: string;\n emailAddress: string;\n verified?: boolean;\n primary?: boolean;\n};\n\ntype UpdateEmailAddressParams = {\n verified?: boolean;\n primary?: boolean;\n};\n\nexport class EmailAddressAPI extends AbstractAPI {\n public async getEmailAddress(emailAddressId: string) {\n this.requireId(emailAddressId);\n\n return this.request<EmailAddress>({\n method: 'GET',\n path: joinPaths(basePath, emailAddressId),\n });\n }\n\n public async createEmailAddress(params: CreateEmailAddressParams) {\n return this.request<EmailAddress>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updateEmailAddress(emailAddressId: string, params: UpdateEmailAddressParams = {}) {\n this.requireId(emailAddressId);\n\n return this.request<EmailAddress>({\n method: 'PATCH',\n path: joinPaths(basePath, emailAddressId),\n bodyParams: params,\n });\n }\n\n public async deleteEmailAddress(emailAddressId: string) {\n this.requireId(emailAddressId);\n\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, emailAddressId),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport { deprecated } from '../../util/shared';\nimport type { IdPOAuthAccessToken } from '../resources';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/oauth_applications/access_tokens';\n\nexport class IdPOAuthAccessTokenApi extends AbstractAPI {\n async verify(accessToken: string) {\n return this.request<IdPOAuthAccessToken>({\n method: 'POST',\n path: joinPaths(basePath, 'verify'),\n bodyParams: { access_token: accessToken },\n });\n }\n\n /**\n * @deprecated Use `verify()` instead. This method will be removed in the next major release.\n */\n async verifyAccessToken(accessToken: string) {\n deprecated('idPOAuthAccessToken.verifyAccessToken()', 'Use `idPOAuthAccessToken.verify()` instead.');\n return this.verify(accessToken);\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { Instance } from '../resources/Instance';\nimport type { InstanceRestrictions } from '../resources/InstanceRestrictions';\nimport type { OrganizationSettings } from '../resources/OrganizationSettings';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/instance';\n\ntype UpdateParams = {\n /**\n * Toggles test mode for this instance, allowing the use of test email addresses and phone numbers.\n *\n * @remarks Defaults to true for development instances.\n */\n testMode?: boolean | null | undefined;\n /**\n * Whether the instance should be using the HIBP service to check passwords for breaches\n */\n hibp?: boolean | null | undefined;\n /**\n * The \"enhanced_email_deliverability\" feature will send emails from \"verifications@clerk.dev\" instead of your domain.\n *\n * @remarks This can be helpful if you do not have a high domain reputation.\n */\n enhancedEmailDeliverability?: boolean | null | undefined;\n supportEmail?: string | null | undefined;\n clerkJsVersion?: string | null | undefined;\n developmentOrigin?: string | null | undefined;\n /**\n * For browser-like stacks such as browser extensions, Electron, or Capacitor.js the instance allowed origins need to be updated with the request origin value.\n *\n * @remarks For Chrome extensions popup, background, or service worker pages the origin is chrome-extension://extension_uiid. For Electron apps the default origin is http://localhost:3000. For Capacitor, the origin is capacitor://localhost.\n */\n allowedOrigins?: Array<string> | undefined;\n /**\n * Whether the instance should use URL-based session syncing in development mode (i.e. without third-party cookies).\n */\n urlBasedSessionSyncing?: boolean | null | undefined;\n};\n\ntype UpdateRestrictionsParams = {\n allowlist?: boolean | null | undefined;\n blocklist?: boolean | null | undefined;\n blockEmailSubaddresses?: boolean | null | undefined;\n blockDisposableEmailDomains?: boolean | null | undefined;\n ignoreDotsForGmailAddresses?: boolean | null | undefined;\n};\n\ntype UpdateOrganizationSettingsParams = {\n enabled?: boolean | null | undefined;\n maxAllowedMemberships?: number | null | undefined;\n adminDeleteEnabled?: boolean | null | undefined;\n domainsEnabled?: boolean | null | undefined;\n /**\n * Specifies which [enrollment modes](https://clerk.com/docs/guides/organizations/verified-domains#enable-verified-domains) to enable for your Organization Domains.\n *\n * @remarks Supported modes are 'automatic_invitation' & 'automatic_suggestion'.\n */\n domainsEnrollmentModes?: Array<string> | undefined;\n /**\n * Specifies what the default organization role is for an organization creator.\n */\n creatorRoleId?: string | null | undefined;\n /**\n * Specifies what the default organization role is for the organization domains.\n */\n domainsDefaultRoleId?: string | null | undefined;\n};\n\nexport class InstanceAPI extends AbstractAPI {\n public async get() {\n return this.request<Instance>({\n method: 'GET',\n path: basePath,\n });\n }\n\n public async update(params: UpdateParams) {\n return this.request<void>({\n method: 'PATCH',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updateRestrictions(params: UpdateRestrictionsParams) {\n return this.request<InstanceRestrictions>({\n method: 'PATCH',\n path: joinPaths(basePath, 'restrictions'),\n bodyParams: params,\n });\n }\n\n public async updateOrganizationSettings(params: UpdateOrganizationSettingsParams) {\n return this.request<OrganizationSettings>({\n method: 'PATCH',\n path: joinPaths(basePath, 'organization_settings'),\n bodyParams: params,\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { InvitationStatus } from '../resources/Enums';\nimport type { Invitation } from '../resources/Invitation';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/invitations';\n\ntype TemplateSlug = 'invitation' | 'waitlist_invitation';\n\ntype CreateParams = {\n emailAddress: string;\n expiresInDays?: number;\n ignoreExisting?: boolean;\n notify?: boolean;\n publicMetadata?: UserPublicMetadata;\n redirectUrl?: string;\n templateSlug?: TemplateSlug;\n};\n\ntype CreateBulkParams = Array<CreateParams>;\n\ntype GetInvitationListParams = ClerkPaginationRequest<{\n /**\n * Filters invitations based on their status.\n *\n * @example\n * Get all revoked invitations\n * ```ts\n * import { createClerkClient } from '@clerk/backend';\n * const clerkClient = createClerkClient(...)\n * await clerkClient.invitations.getInvitationList({ status: 'revoked' })\n * ```\n */\n status?: InvitationStatus;\n /**\n * Filters invitations based on `email_address` or `id`.\n *\n * @example\n * Get all invitations for a specific email address\n * ```ts\n * import { createClerkClient } from '@clerk/backend';\n * const clerkClient = createClerkClient(...)\n * await clerkClient.invitations.getInvitationList({ query: 'user@example.com' })\n * ```\n */\n query?: string;\n}>;\n\nexport class InvitationAPI extends AbstractAPI {\n public async getInvitationList(params: GetInvitationListParams = {}) {\n return this.request<PaginatedResourceResponse<Invitation[]>>({\n method: 'GET',\n path: basePath,\n queryParams: { ...params, paginated: true },\n });\n }\n\n public async createInvitation(params: CreateParams) {\n return this.request<Invitation>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async createInvitationBulk(params: CreateBulkParams) {\n return this.request<Invitation>({\n method: 'POST',\n path: joinPaths(basePath, 'bulk'),\n bodyParams: params,\n });\n }\n\n public async revokeInvitation(invitationId: string) {\n this.requireId(invitationId);\n return this.request<Invitation>({\n method: 'POST',\n path: joinPaths(basePath, invitationId, 'revoke'),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { Machine } from '../resources/Machine';\nimport type { MachineScope } from '../resources/MachineScope';\nimport type { MachineSecretKey } from '../resources/MachineSecretKey';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/machines';\n\ntype CreateMachineParams = {\n /**\n * The name of the machine.\n */\n name: string;\n /**\n * Array of machine IDs that this machine will have access to.\n */\n scopedMachines?: string[];\n /**\n * The default time-to-live (TTL) in seconds for tokens created by this machine.\n */\n defaultTokenTtl?: number;\n};\n\ntype UpdateMachineParams = {\n /**\n * The ID of the machine to update.\n */\n machineId: string;\n /**\n * The name of the machine.\n */\n name?: string;\n /**\n * The default time-to-live (TTL) in seconds for tokens created by this machine.\n */\n defaultTokenTtl?: number;\n};\n\ntype GetMachineListParams = ClerkPaginationRequest<{\n /**\n * Sorts machines by name or created_at.\n * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order.\n */\n orderBy?: WithSign<'name' | 'created_at'>;\n /**\n * Returns machines that have a ID or name that matches the given query.\n */\n query?: string;\n}>;\n\ntype RotateMachineSecretKeyParams = {\n /**\n * The ID of the machine to rotate the secret key for.\n */\n machineId: string;\n /**\n * The time in seconds that the previous secret key will remain valid after rotation.\n */\n previousTokenTtl: number;\n};\n\nexport class MachineApi extends AbstractAPI {\n async get(machineId: string) {\n this.requireId(machineId);\n return this.request<Machine>({\n method: 'GET',\n path: joinPaths(basePath, machineId),\n });\n }\n\n async list(queryParams: GetMachineListParams = {}) {\n return this.request<PaginatedResourceResponse<Machine[]>>({\n method: 'GET',\n path: basePath,\n queryParams,\n });\n }\n\n async create(bodyParams: CreateMachineParams) {\n return this.request<Machine>({\n method: 'POST',\n path: basePath,\n bodyParams,\n });\n }\n\n async update(params: UpdateMachineParams) {\n const { machineId, ...bodyParams } = params;\n this.requireId(machineId);\n return this.request<Machine>({\n method: 'PATCH',\n path: joinPaths(basePath, machineId),\n bodyParams,\n });\n }\n\n async delete(machineId: string) {\n this.requireId(machineId);\n return this.request<Machine>({\n method: 'DELETE',\n path: joinPaths(basePath, machineId),\n });\n }\n\n async getSecretKey(machineId: string) {\n this.requireId(machineId);\n return this.request<MachineSecretKey>({\n method: 'GET',\n path: joinPaths(basePath, machineId, 'secret_key'),\n });\n }\n\n async rotateSecretKey(params: RotateMachineSecretKeyParams) {\n const { machineId, previousTokenTtl } = params;\n this.requireId(machineId);\n return this.request<MachineSecretKey>({\n method: 'POST',\n path: joinPaths(basePath, machineId, 'secret_key', 'rotate'),\n bodyParams: {\n previousTokenTtl,\n },\n });\n }\n\n /**\n * Creates a new machine scope, allowing the specified machine to access another machine.\n *\n * @param machineId - The ID of the machine that will have access to another machine.\n * @param toMachineId - The ID of the machine that will be scoped to the current machine.\n */\n async createScope(machineId: string, toMachineId: string) {\n this.requireId(machineId);\n return this.request<MachineScope>({\n method: 'POST',\n path: joinPaths(basePath, machineId, 'scopes'),\n bodyParams: {\n toMachineId,\n },\n });\n }\n\n /**\n * Deletes a machine scope, removing access from one machine to another.\n *\n * @param machineId - The ID of the machine that has access to another machine.\n * @param otherMachineId - The ID of the machine that is being accessed.\n */\n async deleteScope(machineId: string, otherMachineId: string) {\n this.requireId(machineId);\n return this.request<MachineScope>({\n method: 'DELETE',\n path: joinPaths(basePath, machineId, 'scopes', otherMachineId),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport { deprecated } from '../../util/shared';\nimport type { ClerkBackendApiRequestOptions } from '../request';\nimport type { M2MToken } from '../resources/M2MToken';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/m2m_tokens';\n\ntype CreateM2MTokenParams = {\n /**\n * Custom machine secret key for authentication.\n */\n machineSecretKey?: string;\n /**\n * Number of seconds until the token expires.\n *\n * @default null - Token does not expire\n */\n secondsUntilExpiration?: number | null;\n claims?: Record<string, unknown> | null;\n};\n\ntype RevokeM2MTokenParams = {\n /**\n * Custom machine secret key for authentication.\n */\n machineSecretKey?: string;\n /**\n * Machine-to-machine token ID to revoke.\n */\n m2mTokenId: string;\n revocationReason?: string | null;\n};\n\ntype VerifyM2MTokenParams = {\n /**\n * Custom machine secret key for authentication.\n */\n machineSecretKey?: string;\n /**\n * Machine-to-machine token to verify.\n */\n token: string;\n};\n\nexport class M2MTokenApi extends AbstractAPI {\n #createRequestOptions(options: ClerkBackendApiRequestOptions, machineSecretKey?: string) {\n if (machineSecretKey) {\n return {\n ...options,\n headerParams: {\n ...options.headerParams,\n Authorization: `Bearer ${machineSecretKey}`,\n },\n };\n }\n\n return options;\n }\n\n async createToken(params?: CreateM2MTokenParams) {\n const { claims = null, machineSecretKey, secondsUntilExpiration = null } = params || {};\n\n const requestOptions = this.#createRequestOptions(\n {\n method: 'POST',\n path: basePath,\n bodyParams: {\n secondsUntilExpiration,\n claims,\n },\n },\n machineSecretKey,\n );\n\n return this.request<M2MToken>(requestOptions);\n }\n\n async revokeToken(params: RevokeM2MTokenParams) {\n const { m2mTokenId, revocationReason = null, machineSecretKey } = params;\n\n this.requireId(m2mTokenId);\n\n const requestOptions = this.#createRequestOptions(\n {\n method: 'POST',\n path: joinPaths(basePath, m2mTokenId, 'revoke'),\n bodyParams: {\n revocationReason,\n },\n },\n machineSecretKey,\n );\n\n return this.request<M2MToken>(requestOptions);\n }\n\n async verify(params: VerifyM2MTokenParams) {\n const { token, machineSecretKey } = params;\n\n const requestOptions = this.#createRequestOptions(\n {\n method: 'POST',\n path: joinPaths(basePath, 'verify'),\n bodyParams: { token },\n },\n machineSecretKey,\n );\n\n return this.request<M2MToken>(requestOptions);\n }\n\n /**\n * @deprecated Use `verify()` instead. This method will be removed in the next major release.\n */\n async verifyToken(params: VerifyM2MTokenParams) {\n deprecated('m2m.verifyToken()', 'Use `m2m.verify()` instead.');\n return this.verify(params);\n }\n}\n","import type { JwksJSON } from '../resources/JSON';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/jwks';\n\nexport class JwksAPI extends AbstractAPI {\n public async getJwks() {\n return this.request<JwksJSON>({\n method: 'GET',\n path: basePath,\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\nimport { joinPaths } from 'src/util/path';\n\nimport type { DeletedObject, JwtTemplate } from '../resources';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/jwt_templates';\n\ntype Claims = object;\n\ntype CreateJWTTemplateParams = {\n /**\n * JWT template name\n */\n name: string;\n /**\n * JWT template claims in JSON format\n */\n claims: Claims;\n /**\n * JWT token lifetime\n */\n lifetime?: number | null | undefined;\n /**\n * JWT token allowed clock skew\n */\n allowedClockSkew?: number | null | undefined;\n /**\n * Whether a custom signing key/algorithm is also provided for this template\n */\n customSigningKey?: boolean | undefined;\n /**\n * The custom signing algorithm to use when minting JWTs. Required if `custom_signing_key` is `true`.\n */\n signingAlgorithm?: string | null | undefined;\n /**\n * The custom signing private key to use when minting JWTs. Required if `custom_signing_key` is `true`.\n */\n signingKey?: string | null | undefined;\n};\n\ntype UpdateJWTTemplateParams = CreateJWTTemplateParams & {\n /**\n * JWT template ID\n */\n templateId: string;\n};\n\nexport class JwtTemplatesApi extends AbstractAPI {\n public async list(params: ClerkPaginationRequest = {}) {\n return this.request<JwtTemplate[]>({\n method: 'GET',\n path: basePath,\n queryParams: { ...params, paginated: true },\n });\n }\n\n public async get(templateId: string) {\n this.requireId(templateId);\n\n return this.request<JwtTemplate>({\n method: 'GET',\n path: joinPaths(basePath, templateId),\n });\n }\n\n public async create(params: CreateJWTTemplateParams) {\n return this.request<JwtTemplate>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async update(params: UpdateJWTTemplateParams) {\n const { templateId, ...bodyParams } = params;\n\n this.requireId(templateId);\n return this.request<JwtTemplate>({\n method: 'PATCH',\n path: joinPaths(basePath, templateId),\n bodyParams,\n });\n }\n\n public async delete(templateId: string) {\n this.requireId(templateId);\n\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, templateId),\n });\n }\n}\n","import type { ClerkPaginationRequest, OrganizationEnrollmentMode } from '@clerk/shared/types';\n\nimport { runtime } from '../../runtime';\nimport { joinPaths } from '../../util/path';\nimport type {\n Organization,\n OrganizationDomain,\n OrganizationInvitation,\n OrganizationInvitationStatus,\n OrganizationMembership,\n} from '../resources';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { OrganizationMembershipRole } from '../resources/Enums';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/organizations';\n\ntype MetadataParams<TPublic = OrganizationPublicMetadata, TPrivate = OrganizationPrivateMetadata> = {\n publicMetadata?: TPublic;\n privateMetadata?: TPrivate;\n};\n\ntype GetOrganizationListParams = ClerkPaginationRequest<{\n includeMembersCount?: boolean;\n query?: string;\n orderBy?: WithSign<'name' | 'created_at' | 'members_count'>;\n organizationId?: string[];\n}>;\n\ntype CreateParams = {\n name: string;\n slug?: string;\n /* The User id for the user creating the organization. The user will become an administrator for the organization. */\n createdBy?: string;\n maxAllowedMemberships?: number;\n} & MetadataParams;\n\ntype GetOrganizationParams = ({ organizationId: string } | { slug: string }) & {\n includeMembersCount?: boolean;\n};\n\ntype UpdateParams = {\n name?: string;\n slug?: string;\n adminDeleteEnabled?: boolean;\n maxAllowedMemberships?: number;\n} & MetadataParams;\n\ntype UpdateLogoParams = {\n file: Blob | File;\n uploaderUserId?: string;\n};\n\ntype UpdateMetadataParams = MetadataParams;\n\ntype GetOrganizationMembershipListParams = ClerkPaginationRequest<{\n organizationId: string;\n\n /**\n * Sorts organizations memberships by phone_number, email_address, created_at, first_name, last_name or username.\n * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order.\n */\n orderBy?: WithSign<'phone_number' | 'email_address' | 'created_at' | 'first_name' | 'last_name' | 'username'>;\n\n /**\n * Returns users with the user ids specified. For each user id, the `+` and `-` can be\n * prepended to the id, which denote whether the respective user id should be included or\n * excluded from the result set. Accepts up to 100 user ids. Any user ids not found are ignored.\n */\n userId?: string[];\n\n /* Returns users with the specified email addresses. Accepts up to 100 email addresses. Any email addresses not found are ignored. */\n emailAddress?: string[];\n\n /* Returns users with the specified phone numbers. Accepts up to 100 phone numbers. Any phone numbers not found are ignored. */\n phoneNumber?: string[];\n\n /* Returns users with the specified usernames. Accepts up to 100 usernames. Any usernames not found are ignored. */\n username?: string[];\n\n /* Returns users with the specified web3 wallet addresses. Accepts up to 100 web3 wallet addresses. Any web3 wallet addressed not found are ignored. */\n web3Wallet?: string[];\n\n /* Returns users with the specified roles. Accepts up to 100 roles. Any roles not found are ignored. */\n role?: OrganizationMembershipRole[];\n\n /**\n * Returns users that match the given query.\n * For possible matches, we check the email addresses, phone numbers, usernames, web3 wallets, user ids, first and last names.\n * The query value doesn't need to match the exact value you are looking for, it is capable of partial matches as well.\n */\n query?: string;\n\n /**\n * Returns users with emails that match the given query, via case-insensitive partial match.\n * For example, `email_address_query=ello` will match a user with the email `HELLO@example.com`.\n */\n emailAddressQuery?: string;\n\n /**\n * Returns users with phone numbers that match the given query, via case-insensitive partial match.\n * For example, `phone_number_query=555` will match a user with the phone number `+1555xxxxxxx`.\n */\n phoneNumberQuery?: string;\n\n /**\n * Returns users with usernames that match the given query, via case-insensitive partial match.\n * For example, `username_query=CoolUser` will match a user with the username `SomeCoolUser`.\n */\n usernameQuery?: string;\n\n /* Returns users with names that match the given query, via case-insensitive partial match. */\n nameQuery?: string;\n\n /**\n * Returns users whose last session activity was before the given date (with millisecond precision).\n * Example: use 1700690400000 to retrieve users whose last session activity was before 2023-11-23.\n */\n lastActiveAtBefore?: number;\n /**\n * Returns users whose last session activity was after the given date (with millisecond precision).\n * Example: use 1700690400000 to retrieve users whose last session activity was after 2023-11-23.\n */\n lastActiveAtAfter?: number;\n\n /**\n * Returns users who have been created before the given date (with millisecond precision).\n * Example: use 1730160000000 to retrieve users who have been created before 2024-10-29.\n */\n createdAtBefore?: number;\n\n /**\n * Returns users who have been created after the given date (with millisecond precision).\n * Example: use 1730160000000 to retrieve users who have been created after 2024-10-29.\n */\n createdAtAfter?: number;\n}>;\n\ntype GetInstanceOrganizationMembershipListParams = ClerkPaginationRequest<{\n /**\n * Sorts organizations memberships by phone_number, email_address, created_at, first_name, last_name or username.\n * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order.\n */\n orderBy?: WithSign<'phone_number' | 'email_address' | 'created_at' | 'first_name' | 'last_name' | 'username'>;\n}>;\n\ntype CreateOrganizationMembershipParams = {\n organizationId: string;\n userId: string;\n role: OrganizationMembershipRole;\n};\n\ntype UpdateOrganizationMembershipParams = CreateOrganizationMembershipParams;\n\ntype UpdateOrganizationMembershipMetadataParams = {\n organizationId: string;\n userId: string;\n} & MetadataParams<OrganizationMembershipPublicMetadata>;\n\ntype DeleteOrganizationMembershipParams = {\n organizationId: string;\n userId: string;\n};\n\ntype CreateOrganizationInvitationParams = {\n organizationId: string;\n emailAddress: string;\n role: OrganizationMembershipRole;\n expiresInDays?: number;\n inviterUserId?: string;\n privateMetadata?: OrganizationInvitationPrivateMetadata;\n publicMetadata?: OrganizationInvitationPublicMetadata;\n redirectUrl?: string;\n};\n\ntype CreateBulkOrganizationInvitationParams = Array<{\n emailAddress: string;\n role: OrganizationMembershipRole;\n expiresInDays?: number;\n inviterUserId?: string;\n privateMetadata?: OrganizationInvitationPrivateMetadata;\n publicMetadata?: OrganizationInvitationPublicMetadata;\n redirectUrl?: string;\n}>;\n\ntype GetOrganizationInvitationListParams = ClerkPaginationRequest<{\n organizationId: string;\n status?: OrganizationInvitationStatus[];\n}>;\n\ntype GetOrganizationInvitationParams = {\n organizationId: string;\n invitationId: string;\n};\n\ntype RevokeOrganizationInvitationParams = {\n organizationId: string;\n invitationId: string;\n requestingUserId?: string;\n};\n\ntype GetOrganizationDomainListParams = {\n organizationId: string;\n limit?: number;\n offset?: number;\n};\n\ntype CreateOrganizationDomainParams = {\n organizationId: string;\n name: string;\n enrollmentMode: OrganizationEnrollmentMode;\n verified?: boolean;\n};\n\ntype UpdateOrganizationDomainParams = {\n organizationId: string;\n domainId: string;\n} & Partial<CreateOrganizationDomainParams>;\n\ntype DeleteOrganizationDomainParams = {\n organizationId: string;\n domainId: string;\n};\n\nexport class OrganizationAPI extends AbstractAPI {\n public async getOrganizationList(params?: GetOrganizationListParams) {\n return this.request<PaginatedResourceResponse<Organization[]>>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async createOrganization(params: CreateParams) {\n return this.request<Organization>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async getOrganization(params: GetOrganizationParams) {\n const { includeMembersCount } = params;\n const organizationIdOrSlug = 'organizationId' in params ? params.organizationId : params.slug;\n this.requireId(organizationIdOrSlug);\n\n return this.request<Organization>({\n method: 'GET',\n path: joinPaths(basePath, organizationIdOrSlug),\n queryParams: {\n includeMembersCount,\n },\n });\n }\n\n public async updateOrganization(organizationId: string, params: UpdateParams) {\n this.requireId(organizationId);\n return this.request<Organization>({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId),\n bodyParams: params,\n });\n }\n\n public async updateOrganizationLogo(organizationId: string, params: UpdateLogoParams) {\n this.requireId(organizationId);\n\n const formData = new runtime.FormData();\n formData.append('file', params?.file);\n if (params?.uploaderUserId) {\n formData.append('uploader_user_id', params?.uploaderUserId);\n }\n\n return this.request<Organization>({\n method: 'PUT',\n path: joinPaths(basePath, organizationId, 'logo'),\n formData,\n });\n }\n\n public async deleteOrganizationLogo(organizationId: string) {\n this.requireId(organizationId);\n\n return this.request<Organization>({\n method: 'DELETE',\n path: joinPaths(basePath, organizationId, 'logo'),\n });\n }\n\n public async updateOrganizationMetadata(organizationId: string, params: UpdateMetadataParams) {\n this.requireId(organizationId);\n\n return this.request<Organization>({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId, 'metadata'),\n bodyParams: params,\n });\n }\n\n public async deleteOrganization(organizationId: string) {\n return this.request<Organization>({\n method: 'DELETE',\n path: joinPaths(basePath, organizationId),\n });\n }\n\n public async getOrganizationMembershipList(params: GetOrganizationMembershipListParams) {\n const { organizationId, ...queryParams } = params;\n this.requireId(organizationId);\n\n return this.request<PaginatedResourceResponse<OrganizationMembership[]>>({\n method: 'GET',\n path: joinPaths(basePath, organizationId, 'memberships'),\n queryParams,\n });\n }\n\n public async getInstanceOrganizationMembershipList(params: GetInstanceOrganizationMembershipListParams) {\n return this.request<PaginatedResourceResponse<OrganizationMembership[]>>({\n method: 'GET',\n path: '/organization_memberships',\n queryParams: params,\n });\n }\n\n public async createOrganizationMembership(params: CreateOrganizationMembershipParams) {\n const { organizationId, ...bodyParams } = params;\n this.requireId(organizationId);\n\n return this.request<OrganizationMembership>({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'memberships'),\n bodyParams,\n });\n }\n\n public async updateOrganizationMembership(params: UpdateOrganizationMembershipParams) {\n const { organizationId, userId, ...bodyParams } = params;\n this.requireId(organizationId);\n\n return this.request<OrganizationMembership>({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId, 'memberships', userId),\n bodyParams,\n });\n }\n\n public async updateOrganizationMembershipMetadata(params: UpdateOrganizationMembershipMetadataParams) {\n const { organizationId, userId, ...bodyParams } = params;\n\n return this.request<OrganizationMembership>({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId, 'memberships', userId, 'metadata'),\n bodyParams,\n });\n }\n\n public async deleteOrganizationMembership(params: DeleteOrganizationMembershipParams) {\n const { organizationId, userId } = params;\n this.requireId(organizationId);\n\n return this.request<OrganizationMembership>({\n method: 'DELETE',\n path: joinPaths(basePath, organizationId, 'memberships', userId),\n });\n }\n\n public async getOrganizationInvitationList(params: GetOrganizationInvitationListParams) {\n const { organizationId, ...queryParams } = params;\n this.requireId(organizationId);\n\n return this.request<PaginatedResourceResponse<OrganizationInvitation[]>>({\n method: 'GET',\n path: joinPaths(basePath, organizationId, 'invitations'),\n queryParams,\n });\n }\n\n public async createOrganizationInvitation(params: CreateOrganizationInvitationParams) {\n const { organizationId, ...bodyParams } = params;\n this.requireId(organizationId);\n\n return this.request<OrganizationInvitation>({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'invitations'),\n bodyParams,\n });\n }\n\n public async createOrganizationInvitationBulk(\n organizationId: string,\n params: CreateBulkOrganizationInvitationParams,\n ) {\n this.requireId(organizationId);\n\n return this.request<OrganizationInvitation[]>({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'invitations', 'bulk'),\n bodyParams: params,\n });\n }\n\n public async getOrganizationInvitation(params: GetOrganizationInvitationParams) {\n const { organizationId, invitationId } = params;\n this.requireId(organizationId);\n this.requireId(invitationId);\n\n return this.request<OrganizationInvitation>({\n method: 'GET',\n path: joinPaths(basePath, organizationId, 'invitations', invitationId),\n });\n }\n\n public async revokeOrganizationInvitation(params: RevokeOrganizationInvitationParams) {\n const { organizationId, invitationId, ...bodyParams } = params;\n this.requireId(organizationId);\n\n return this.request<OrganizationInvitation>({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'invitations', invitationId, 'revoke'),\n bodyParams,\n });\n }\n\n public async getOrganizationDomainList(params: GetOrganizationDomainListParams) {\n const { organizationId, ...queryParams } = params;\n this.requireId(organizationId);\n\n return this.request<PaginatedResourceResponse<OrganizationDomain[]>>({\n method: 'GET',\n path: joinPaths(basePath, organizationId, 'domains'),\n queryParams,\n });\n }\n\n public async createOrganizationDomain(params: CreateOrganizationDomainParams) {\n const { organizationId, ...bodyParams } = params;\n this.requireId(organizationId);\n\n return this.request<OrganizationDomain>({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'domains'),\n bodyParams: {\n ...bodyParams,\n verified: bodyParams.verified ?? true,\n },\n });\n }\n\n public async updateOrganizationDomain(params: UpdateOrganizationDomainParams) {\n const { organizationId, domainId, ...bodyParams } = params;\n this.requireId(organizationId);\n this.requireId(domainId);\n\n return this.request<OrganizationDomain>({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId, 'domains', domainId),\n bodyParams,\n });\n }\n\n public async deleteOrganizationDomain(params: DeleteOrganizationDomainParams) {\n const { organizationId, domainId } = params;\n this.requireId(organizationId);\n this.requireId(domainId);\n\n return this.request<OrganizationDomain>({\n method: 'DELETE',\n path: joinPaths(basePath, organizationId, 'domains', domainId),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { DeletedObject } from '../resources';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { OAuthApplication } from '../resources/OAuthApplication';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/oauth_applications';\n\ntype CreateOAuthApplicationParams = {\n /**\n * The name of the new OAuth application.\n *\n * @remarks Max length: 256\n */\n name: string;\n /**\n * An array of redirect URIs of the new OAuth application\n */\n redirectUris?: Array<string> | null | undefined;\n /**\n * Define the allowed scopes for the new OAuth applications that dictate the user payload of the OAuth user info endpoint. Available scopes are `profile`, `email`, `public_metadata`, `private_metadata`. Provide the requested scopes as a string, separated by spaces.\n */\n scopes?: string | null | undefined;\n /**\n * If true, this client is public and you can use the Proof Key of Code Exchange (PKCE) flow.\n */\n public?: boolean | null | undefined;\n};\n\ntype UpdateOAuthApplicationParams = CreateOAuthApplicationParams & {\n /**\n * The ID of the OAuth application to update\n */\n oauthApplicationId: string;\n};\n\ntype GetOAuthApplicationListParams = ClerkPaginationRequest<{\n /**\n * Sorts OAuth applications by name or created_at.\n * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order.\n */\n orderBy?: WithSign<'name' | 'created_at'>;\n}>;\n\nexport class OAuthApplicationsApi extends AbstractAPI {\n public async list(params: GetOAuthApplicationListParams = {}) {\n return this.request<PaginatedResourceResponse<OAuthApplication[]>>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async get(oauthApplicationId: string) {\n this.requireId(oauthApplicationId);\n\n return this.request<OAuthApplication>({\n method: 'GET',\n path: joinPaths(basePath, oauthApplicationId),\n });\n }\n\n public async create(params: CreateOAuthApplicationParams) {\n return this.request<OAuthApplication>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async update(params: UpdateOAuthApplicationParams) {\n const { oauthApplicationId, ...bodyParams } = params;\n\n this.requireId(oauthApplicationId);\n\n return this.request<OAuthApplication>({\n method: 'PATCH',\n path: joinPaths(basePath, oauthApplicationId),\n bodyParams,\n });\n }\n\n public async delete(oauthApplicationId: string) {\n this.requireId(oauthApplicationId);\n\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, oauthApplicationId),\n });\n }\n\n public async rotateSecret(oauthApplicationId: string) {\n this.requireId(oauthApplicationId);\n\n return this.request<OAuthApplication>({\n method: 'POST',\n path: joinPaths(basePath, oauthApplicationId, 'rotate_secret'),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { DeletedObject, PhoneNumber } from '../resources';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/phone_numbers';\n\ntype CreatePhoneNumberParams = {\n userId: string;\n phoneNumber: string;\n verified?: boolean;\n primary?: boolean;\n reservedForSecondFactor?: boolean;\n};\n\ntype UpdatePhoneNumberParams = {\n verified?: boolean;\n primary?: boolean;\n reservedForSecondFactor?: boolean;\n};\n\nexport class PhoneNumberAPI extends AbstractAPI {\n public async getPhoneNumber(phoneNumberId: string) {\n this.requireId(phoneNumberId);\n\n return this.request<PhoneNumber>({\n method: 'GET',\n path: joinPaths(basePath, phoneNumberId),\n });\n }\n\n public async createPhoneNumber(params: CreatePhoneNumberParams) {\n return this.request<PhoneNumber>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updatePhoneNumber(phoneNumberId: string, params: UpdatePhoneNumberParams = {}) {\n this.requireId(phoneNumberId);\n\n return this.request<PhoneNumber>({\n method: 'PATCH',\n path: joinPaths(basePath, phoneNumberId),\n bodyParams: params,\n });\n }\n\n public async deletePhoneNumber(phoneNumberId: string) {\n this.requireId(phoneNumberId);\n\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, phoneNumberId),\n });\n }\n}\n","import type { ProxyCheck } from '../resources';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/proxy_checks';\n\ntype VerifyParams = {\n domainId: string;\n proxyUrl: string;\n};\n\nexport class ProxyCheckAPI extends AbstractAPI {\n public async verify(params: VerifyParams) {\n return this.request<ProxyCheck>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { RedirectUrl } from '../resources/RedirectUrl';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/redirect_urls';\n\ntype CreateRedirectUrlParams = {\n url: string;\n};\n\nexport class RedirectUrlAPI extends AbstractAPI {\n public async getRedirectUrlList() {\n return this.request<PaginatedResourceResponse<RedirectUrl[]>>({\n method: 'GET',\n path: basePath,\n queryParams: { paginated: true },\n });\n }\n\n public async getRedirectUrl(redirectUrlId: string) {\n this.requireId(redirectUrlId);\n return this.request<RedirectUrl>({\n method: 'GET',\n path: joinPaths(basePath, redirectUrlId),\n });\n }\n\n public async createRedirectUrl(params: CreateRedirectUrlParams) {\n return this.request<RedirectUrl>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async deleteRedirectUrl(redirectUrlId: string) {\n this.requireId(redirectUrlId);\n return this.request<RedirectUrl>({\n method: 'DELETE',\n path: joinPaths(basePath, redirectUrlId),\n });\n }\n}\n","import type { ClerkPaginationRequest, SamlIdpSlug } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { SamlConnection } from '../resources';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/saml_connections';\n\ntype SamlConnectionListParams = ClerkPaginationRequest<{\n /**\n * Returns SAML connections that have a name that matches the given query, via case-insensitive partial match.\n */\n query?: string;\n\n /**\n * Sorts SAML connections by phone_number, email_address, created_at, first_name, last_name or username.\n * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order.\n */\n orderBy?: WithSign<'phone_number' | 'email_address' | 'created_at' | 'first_name' | 'last_name' | 'username'>;\n\n /**\n * Returns SAML connections that have an associated organization ID to the given organizations.\n * For each organization id, the + and - can be prepended to the id, which denote whether the\n * respective organization should be included or excluded from the result set. Accepts up to 100 organization ids.\n */\n organizationId?: WithSign<string>[];\n}>;\n\ntype CreateSamlConnectionParams = {\n name: string;\n provider: SamlIdpSlug;\n domain: string;\n organizationId?: string;\n idpEntityId?: string;\n idpSsoUrl?: string;\n idpCertificate?: string;\n idpMetadataUrl?: string;\n idpMetadata?: string;\n attributeMapping?: {\n emailAddress?: string;\n firstName?: string;\n lastName?: string;\n userId?: string;\n };\n};\n\ntype UpdateSamlConnectionParams = {\n name?: string;\n provider?: SamlIdpSlug;\n domain?: string;\n organizationId?: string;\n idpEntityId?: string;\n idpSsoUrl?: string;\n idpCertificate?: string;\n idpMetadataUrl?: string;\n idpMetadata?: string;\n attributeMapping?: {\n emailAddress?: string;\n firstName?: string;\n lastName?: string;\n userId?: string;\n };\n active?: boolean;\n syncUserAttributes?: boolean;\n allowSubdomains?: boolean;\n allowIdpInitiated?: boolean;\n};\n\nexport class SamlConnectionAPI extends AbstractAPI {\n public async getSamlConnectionList(params: SamlConnectionListParams = {}) {\n return this.request<PaginatedResourceResponse<SamlConnection[]>>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async createSamlConnection(params: CreateSamlConnectionParams) {\n return this.request<SamlConnection>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n options: {\n deepSnakecaseBodyParamKeys: true,\n },\n });\n }\n\n public async getSamlConnection(samlConnectionId: string) {\n this.requireId(samlConnectionId);\n return this.request<SamlConnection>({\n method: 'GET',\n path: joinPaths(basePath, samlConnectionId),\n });\n }\n\n public async updateSamlConnection(samlConnectionId: string, params: UpdateSamlConnectionParams = {}) {\n this.requireId(samlConnectionId);\n\n return this.request<SamlConnection>({\n method: 'PATCH',\n path: joinPaths(basePath, samlConnectionId),\n bodyParams: params,\n options: {\n deepSnakecaseBodyParamKeys: true,\n },\n });\n }\n public async deleteSamlConnection(samlConnectionId: string) {\n this.requireId(samlConnectionId);\n return this.request<SamlConnection>({\n method: 'DELETE',\n path: joinPaths(basePath, samlConnectionId),\n });\n }\n}\n","import type { ClerkPaginationRequest, SessionStatus } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { Cookies } from '../resources/Cookies';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { Session } from '../resources/Session';\nimport type { Token } from '../resources/Token';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/sessions';\n\ntype SessionListParams = ClerkPaginationRequest<{\n clientId?: string;\n userId?: string;\n status?: SessionStatus;\n}>;\n\ntype RefreshTokenParams = {\n expired_token: string;\n refresh_token: string;\n request_origin: string;\n request_originating_ip?: string;\n request_headers?: Record<string, string[]>;\n suffixed_cookies?: boolean;\n format?: 'token' | 'cookie';\n};\n\ntype CreateSessionParams = {\n userId: string;\n};\n\nexport class SessionAPI extends AbstractAPI {\n public async getSessionList(params: SessionListParams = {}) {\n return this.request<PaginatedResourceResponse<Session[]>>({\n method: 'GET',\n path: basePath,\n queryParams: { ...params, paginated: true },\n });\n }\n\n public async getSession(sessionId: string) {\n this.requireId(sessionId);\n return this.request<Session>({\n method: 'GET',\n path: joinPaths(basePath, sessionId),\n });\n }\n\n public async createSession(params: CreateSessionParams) {\n return this.request<Session>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async revokeSession(sessionId: string) {\n this.requireId(sessionId);\n return this.request<Session>({\n method: 'POST',\n path: joinPaths(basePath, sessionId, 'revoke'),\n });\n }\n\n public async verifySession(sessionId: string, token: string) {\n this.requireId(sessionId);\n return this.request<Session>({\n method: 'POST',\n path: joinPaths(basePath, sessionId, 'verify'),\n bodyParams: { token },\n });\n }\n\n /**\n * Retrieves a session token or generates a JWT using a specified template.\n *\n * @param sessionId - The ID of the session for which to generate the token\n * @param template - Optional name of the JWT template configured in the Clerk Dashboard.\n * @param expiresInSeconds - Optional expiration time for the token in seconds.\n * If not provided, uses the default expiration.\n *\n * @returns A promise that resolves to the generated token\n *\n * @throws {Error} When sessionId is invalid or empty\n */\n public async getToken(sessionId: string, template?: string, expiresInSeconds?: number) {\n this.requireId(sessionId);\n\n const path = template\n ? joinPaths(basePath, sessionId, 'tokens', template)\n : joinPaths(basePath, sessionId, 'tokens');\n\n const requestOptions: any = {\n method: 'POST',\n path,\n };\n\n if (expiresInSeconds !== undefined) {\n requestOptions.bodyParams = { expires_in_seconds: expiresInSeconds };\n }\n\n return this.request<Token>(requestOptions);\n }\n\n public async refreshSession(sessionId: string, params: RefreshTokenParams & { format: 'token' }): Promise<Token>;\n public async refreshSession(sessionId: string, params: RefreshTokenParams & { format: 'cookie' }): Promise<Cookies>;\n public async refreshSession(sessionId: string, params: RefreshTokenParams): Promise<Token>;\n public async refreshSession(sessionId: string, params: RefreshTokenParams): Promise<Token | Cookies> {\n this.requireId(sessionId);\n const { suffixed_cookies, ...restParams } = params;\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, sessionId, 'refresh'),\n bodyParams: restParams,\n queryParams: { suffixed_cookies },\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { SignInToken } from '../resources/SignInTokens';\nimport { AbstractAPI } from './AbstractApi';\n\ntype CreateSignInTokensParams = {\n userId: string;\n expiresInSeconds: number;\n};\n\nconst basePath = '/sign_in_tokens';\n\nexport class SignInTokenAPI extends AbstractAPI {\n public async createSignInToken(params: CreateSignInTokensParams) {\n return this.request<SignInToken>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async revokeSignInToken(signInTokenId: string) {\n this.requireId(signInTokenId);\n return this.request<SignInToken>({\n method: 'POST',\n path: joinPaths(basePath, signInTokenId, 'revoke'),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { SignUpAttempt } from '../resources/SignUpAttempt';\nimport { AbstractAPI } from './AbstractApi';\n\ntype UpdateSignUpParams = {\n signUpAttemptId: string;\n externalId?: string | null;\n customAction?: boolean | null;\n};\n\nconst basePath = '/sign_ups';\n\nexport class SignUpAPI extends AbstractAPI {\n public async get(signUpAttemptId: string) {\n this.requireId(signUpAttemptId);\n\n return this.request<SignUpAttempt>({\n method: 'GET',\n path: joinPaths(basePath, signUpAttemptId),\n });\n }\n\n public async update(params: UpdateSignUpParams) {\n const { signUpAttemptId, ...bodyParams } = params;\n\n return this.request<SignUpAttempt>({\n method: 'PATCH',\n path: joinPaths(basePath, signUpAttemptId),\n bodyParams,\n });\n }\n}\n","import type { TestingToken } from '../resources/TestingToken';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/testing_tokens';\n\nexport class TestingTokenAPI extends AbstractAPI {\n public async createTestingToken() {\n return this.request<TestingToken>({\n method: 'POST',\n path: basePath,\n });\n }\n}\n","import type { ClerkPaginationRequest, OAuthProvider, OrganizationInvitationStatus } from '@clerk/shared/types';\n\nimport { runtime } from '../../runtime';\nimport { joinPaths } from '../../util/path';\nimport { deprecated } from '../../util/shared';\nimport type {\n DeletedObject,\n OauthAccessToken,\n OrganizationInvitation,\n OrganizationMembership,\n User,\n} from '../resources';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/users';\n\ntype UserCountParams = {\n emailAddress?: string[];\n phoneNumber?: string[];\n username?: string[];\n web3Wallet?: string[];\n query?: string;\n userId?: string[];\n externalId?: string[];\n};\n\ntype UserListParams = ClerkPaginationRequest<\n UserCountParams & {\n orderBy?: WithSign<\n | 'created_at'\n | 'updated_at'\n | 'email_address'\n | 'web3wallet'\n | 'first_name'\n | 'last_name'\n | 'phone_number'\n | 'username'\n | 'last_active_at'\n | 'last_sign_in_at'\n >;\n last_active_at_since?: number;\n organizationId?: string[];\n }\n>;\n\ntype UserMetadataParams = {\n publicMetadata?: UserPublicMetadata;\n privateMetadata?: UserPrivateMetadata;\n unsafeMetadata?: UserUnsafeMetadata;\n};\n\ntype PasswordHasher =\n | 'argon2i'\n | 'argon2id'\n | 'awscognito'\n | 'bcrypt'\n | 'bcrypt_sha256_django'\n | 'md5'\n | 'pbkdf2_sha256'\n | 'pbkdf2_sha256_django'\n | 'pbkdf2_sha1'\n | 'phpass'\n | 'scrypt_firebase'\n | 'scrypt_werkzeug'\n | 'sha256'\n | 'md5_phpass'\n | 'ldap_ssha';\n\ntype UserPasswordHashingParams = {\n passwordDigest: string;\n passwordHasher: PasswordHasher;\n};\n\ntype CreateUserParams = {\n externalId?: string;\n emailAddress?: string[];\n phoneNumber?: string[];\n username?: string;\n password?: string;\n firstName?: string;\n lastName?: string;\n /** The locale of the user in BCP-47 format. */\n locale?: string;\n skipPasswordChecks?: boolean;\n skipPasswordRequirement?: boolean;\n skipLegalChecks?: boolean;\n legalAcceptedAt?: Date;\n totpSecret?: string;\n backupCodes?: string[];\n createdAt?: Date;\n} & UserMetadataParams &\n (UserPasswordHashingParams | object);\n\ntype UpdateUserParams = {\n /** The first name to assign to the user. */\n firstName?: string;\n\n /** The last name of the user. */\n lastName?: string;\n\n /** The username to give to the user. It must be unique across your instance. */\n username?: string;\n\n /** The plaintext password to give the user. Must be at least 8 characters long, and can not be in any list of hacked passwords. */\n password?: string;\n\n /** Set it to true if you're updating the user's password and want to skip any password policy settings check. This parameter can only be used when providing a password. */\n skipPasswordChecks?: boolean;\n\n /** Set to true to sign out the user from all their active sessions once their password is updated. This parameter can only be used when providing a password. */\n signOutOfOtherSessions?: boolean;\n\n /** The ID of the email address to set as primary. It must be verified, and present on the current user. */\n primaryEmailAddressID?: string;\n\n /** If set to true, the user will be notified that their primary email address has changed. By default, no notification is sent. */\n notifyPrimaryEmailAddressChanged?: boolean;\n\n /** The ID of the phone number to set as primary. It must be verified, and present on the current user. */\n primaryPhoneNumberID?: string;\n\n /** The ID of the web3 wallets to set as primary. It must be verified, and present on the current user. */\n primaryWeb3WalletID?: string;\n\n /** The ID of the image to set as the user's profile image */\n profileImageID?: string;\n\n /**\n * In case TOTP is configured on the instance, you can provide the secret to enable it on the specific user without the need to reset it.\n * Please note that currently the supported options are:\n * - Period: 30 seconds\n * - Code length: 6 digits\n * - Algorithm: SHA1\n */\n totpSecret?: string;\n\n /** If Backup Codes are configured on the instance, you can provide them to enable it on the specific user without the need to reset them. You must provide the backup codes in plain format or the corresponding bcrypt digest. */\n backupCodes?: string[];\n\n /** The ID of the user as used in your external systems or your previous authentication solution. Must be unique across your instance. */\n externalId?: string;\n\n /** A custom timestamp denoting when the user signed up to the application, specified in RFC3339 format (e.g. 2012-10-20T07:15:20.902Z). */\n createdAt?: Date;\n\n /** When set to true all legal checks are skipped. It is not recommended to skip legal checks unless you are migrating a user to Clerk. */\n skipLegalChecks?: boolean;\n\n /** A custom timestamp denoting when the user accepted legal requirements, specified in RFC3339 format (e.g. 2012-10-20T07:15:20.902Z). */\n legalAcceptedAt?: Date;\n\n /** The locale of the user in BCP-47 format. */\n locale?: string;\n\n /** If true, the user can delete themselves with the Frontend API. */\n deleteSelfEnabled?: boolean;\n\n /** If true, the user can create organizations with the Frontend API. */\n createOrganizationEnabled?: boolean;\n\n /** The maximum number of organizations the user can create. 0 means unlimited. */\n createOrganizationsLimit?: number;\n} & UserMetadataParams &\n (UserPasswordHashingParams | object);\n\ntype GetOrganizationMembershipListParams = ClerkPaginationRequest<{\n userId: string;\n}>;\n\ntype GetOrganizationInvitationListParams = ClerkPaginationRequest<{\n userId: string;\n status?: OrganizationInvitationStatus;\n}>;\n\ntype VerifyPasswordParams = {\n userId: string;\n password: string;\n};\n\ntype VerifyTOTPParams = {\n userId: string;\n code: string;\n};\n\ntype DeleteUserPasskeyParams = {\n userId: string;\n passkeyIdentificationId: string;\n};\n\ntype DeleteWeb3WalletParams = {\n userId: string;\n web3WalletIdentificationId: string;\n};\n\ntype DeleteUserExternalAccountParams = {\n userId: string;\n externalAccountId: string;\n};\n\ntype UserID = {\n userId: string;\n};\n\nexport class UserAPI extends AbstractAPI {\n public async getUserList(params: UserListParams = {}) {\n const { limit, offset, orderBy, ...userCountParams } = params;\n // TODO(dimkl): Temporary change to populate totalCount using a 2nd BAPI call to /users/count endpoint\n // until we update the /users endpoint to be paginated in a next BAPI version.\n // In some edge cases the data.length != totalCount due to a creation of a user between the 2 api responses\n const [data, totalCount] = await Promise.all([\n this.request<User[]>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n }),\n this.getCount(userCountParams),\n ]);\n return { data, totalCount } as PaginatedResourceResponse<User[]>;\n }\n\n public async getUser(userId: string) {\n this.requireId(userId);\n return this.request<User>({\n method: 'GET',\n path: joinPaths(basePath, userId),\n });\n }\n\n public async createUser(params: CreateUserParams) {\n return this.request<User>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updateUser(userId: string, params: UpdateUserParams = {}) {\n this.requireId(userId);\n\n return this.request<User>({\n method: 'PATCH',\n path: joinPaths(basePath, userId),\n bodyParams: params,\n });\n }\n\n public async updateUserProfileImage(userId: string, params: { file: Blob | File }) {\n this.requireId(userId);\n\n const formData = new runtime.FormData();\n formData.append('file', params?.file);\n\n return this.request<User>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'profile_image'),\n formData,\n });\n }\n\n public async updateUserMetadata(userId: string, params: UserMetadataParams) {\n this.requireId(userId);\n\n return this.request<User>({\n method: 'PATCH',\n path: joinPaths(basePath, userId, 'metadata'),\n bodyParams: params,\n });\n }\n\n public async deleteUser(userId: string) {\n this.requireId(userId);\n return this.request<User>({\n method: 'DELETE',\n path: joinPaths(basePath, userId),\n });\n }\n\n public async getCount(params: UserCountParams = {}) {\n return this.request<number>({\n method: 'GET',\n path: joinPaths(basePath, 'count'),\n queryParams: params,\n });\n }\n\n /** @deprecated Use `getUserOauthAccessToken` without the `oauth_` provider prefix . */\n public async getUserOauthAccessToken(\n userId: string,\n provider: `oauth_${OAuthProvider}`,\n ): Promise<PaginatedResourceResponse<OauthAccessToken[]>>;\n public async getUserOauthAccessToken(\n userId: string,\n provider: OAuthProvider,\n ): Promise<PaginatedResourceResponse<OauthAccessToken[]>>;\n public async getUserOauthAccessToken(userId: string, provider: `oauth_${OAuthProvider}` | OAuthProvider) {\n this.requireId(userId);\n const hasPrefix = provider.startsWith('oauth_');\n const _provider = hasPrefix ? provider : `oauth_${provider}`;\n\n if (hasPrefix) {\n deprecated(\n 'getUserOauthAccessToken(userId, provider)',\n 'Remove the `oauth_` prefix from the `provider` argument.',\n );\n }\n\n return this.request<PaginatedResourceResponse<OauthAccessToken[]>>({\n method: 'GET',\n path: joinPaths(basePath, userId, 'oauth_access_tokens', _provider),\n queryParams: { paginated: true },\n });\n }\n\n public async disableUserMFA(userId: string) {\n this.requireId(userId);\n return this.request<UserID>({\n method: 'DELETE',\n path: joinPaths(basePath, userId, 'mfa'),\n });\n }\n\n public async getOrganizationMembershipList(params: GetOrganizationMembershipListParams) {\n const { userId, limit, offset } = params;\n this.requireId(userId);\n\n return this.request<PaginatedResourceResponse<OrganizationMembership[]>>({\n method: 'GET',\n path: joinPaths(basePath, userId, 'organization_memberships'),\n queryParams: { limit, offset },\n });\n }\n\n public async getOrganizationInvitationList(params: GetOrganizationInvitationListParams) {\n const { userId, ...queryParams } = params;\n this.requireId(userId);\n\n return this.request<PaginatedResourceResponse<OrganizationInvitation[]>>({\n method: 'GET',\n path: joinPaths(basePath, userId, 'organization_invitations'),\n queryParams,\n });\n }\n\n public async verifyPassword(params: VerifyPasswordParams) {\n const { userId, password } = params;\n this.requireId(userId);\n\n return this.request<{ verified: true }>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'verify_password'),\n bodyParams: { password },\n });\n }\n\n public async verifyTOTP(params: VerifyTOTPParams) {\n const { userId, code } = params;\n this.requireId(userId);\n\n return this.request<{ verified: true; code_type: 'totp' }>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'verify_totp'),\n bodyParams: { code },\n });\n }\n\n public async banUser(userId: string) {\n this.requireId(userId);\n return this.request<User>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'ban'),\n });\n }\n\n public async unbanUser(userId: string) {\n this.requireId(userId);\n return this.request<User>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'unban'),\n });\n }\n\n public async lockUser(userId: string) {\n this.requireId(userId);\n return this.request<User>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'lock'),\n });\n }\n\n public async unlockUser(userId: string) {\n this.requireId(userId);\n return this.request<User>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'unlock'),\n });\n }\n\n public async deleteUserProfileImage(userId: string) {\n this.requireId(userId);\n return this.request<User>({\n method: 'DELETE',\n path: joinPaths(basePath, userId, 'profile_image'),\n });\n }\n\n public async deleteUserPasskey(params: DeleteUserPasskeyParams) {\n this.requireId(params.userId);\n this.requireId(params.passkeyIdentificationId);\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, params.userId, 'passkeys', params.passkeyIdentificationId),\n });\n }\n\n public async deleteUserWeb3Wallet(params: DeleteWeb3WalletParams) {\n this.requireId(params.userId);\n this.requireId(params.web3WalletIdentificationId);\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, params.userId, 'web3_wallets', params.web3WalletIdentificationId),\n });\n }\n\n public async deleteUserExternalAccount(params: DeleteUserExternalAccountParams) {\n this.requireId(params.userId);\n this.requireId(params.externalAccountId);\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, params.userId, 'external_accounts', params.externalAccountId),\n });\n }\n\n public async deleteUserBackupCodes(userId: string) {\n this.requireId(userId);\n return this.request<UserID>({\n method: 'DELETE',\n path: joinPaths(basePath, userId, 'backup_code'),\n });\n }\n\n public async deleteUserTOTP(userId: string) {\n this.requireId(userId);\n return this.request<UserID>({\n method: 'DELETE',\n path: joinPaths(basePath, userId, 'totp'),\n });\n }\n\n public async __experimental_passwordCompromised(userId: string) {\n this.requireId(userId);\n return this.request<User>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'password_compromised'),\n bodyParams: {\n revokeAllSessions: false,\n },\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\nimport { joinPaths } from 'src/util/path';\n\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { WaitlistEntryStatus } from '../resources/Enums';\nimport type { WaitlistEntry } from '../resources/WaitlistEntry';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/waitlist_entries';\n\ntype WaitlistEntryListParams = ClerkPaginationRequest<{\n /**\n * Filter waitlist entries by `email_address` or `id`\n */\n query?: string;\n status?: WaitlistEntryStatus;\n orderBy?: WithSign<'created_at' | 'invited_at' | 'email_address'>;\n}>;\n\ntype WaitlistEntryCreateParams = {\n emailAddress: string;\n notify?: boolean;\n};\n\ntype WaitlistEntryInviteParams = {\n /**\n * When true, do not error if an invitation already exists. Default: false.\n */\n ignoreExisting?: boolean;\n};\n\nexport class WaitlistEntryAPI extends AbstractAPI {\n /**\n * List waitlist entries.\n * @param params Optional parameters (e.g., `query`, `status`, `orderBy`).\n */\n public async list(params: WaitlistEntryListParams = {}) {\n return this.request<PaginatedResourceResponse<WaitlistEntry>>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n /**\n * Create a waitlist entry.\n * @param params The parameters for creating a waitlist entry.\n */\n public async create(params: WaitlistEntryCreateParams) {\n return this.request<WaitlistEntry>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n /**\n * Invite a waitlist entry.\n * @param id The waitlist entry ID.\n * @param params Optional parameters (e.g., `ignoreExisting`).\n */\n public async invite(id: string, params: WaitlistEntryInviteParams = {}) {\n this.requireId(id);\n\n return this.request<WaitlistEntry>({\n method: 'POST',\n path: joinPaths(basePath, id, 'invite'),\n bodyParams: params,\n });\n }\n\n /**\n * Reject a waitlist entry.\n * @param id The waitlist entry ID.\n */\n public async reject(id: string) {\n this.requireId(id);\n\n return this.request<WaitlistEntry>({\n method: 'POST',\n path: joinPaths(basePath, id, 'reject'),\n });\n }\n\n /**\n * Delete a waitlist entry.\n * @param id The waitlist entry ID.\n */\n public async delete(id: string) {\n this.requireId(id);\n\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, id),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { WebhooksSvixJSON } from '../resources/JSON';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/webhooks';\n\nexport class WebhookAPI extends AbstractAPI {\n public async createSvixApp() {\n return this.request<WebhooksSvixJSON>({\n method: 'POST',\n path: joinPaths(basePath, 'svix'),\n });\n }\n\n public async generateSvixAuthURL() {\n return this.request<WebhooksSvixJSON>({\n method: 'POST',\n path: joinPaths(basePath, 'svix_url'),\n });\n }\n\n public async deleteSvixApp() {\n return this.request<void>({\n method: 'DELETE',\n path: joinPaths(basePath, 'svix'),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { BillingPlan } from '../resources/CommercePlan';\nimport type { BillingSubscription } from '../resources/CommerceSubscription';\nimport type { BillingSubscriptionItem } from '../resources/CommerceSubscriptionItem';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/billing';\nconst organizationBasePath = '/organizations';\nconst userBasePath = '/users';\n\ntype GetOrganizationListParams = ClerkPaginationRequest<{\n payerType: 'org' | 'user';\n}>;\n\ntype CancelSubscriptionItemParams = {\n /**\n * If true, the subscription item will be canceled immediately. If false or undefined, the subscription item will be canceled at the end of the current billing period.\n * @default undefined\n */\n endNow?: boolean;\n};\n\ntype ExtendSubscriptionItemFreeTrialParams = {\n /**\n * RFC3339 timestamp to extend the free trial to.\n * Must be in the future and not more than 365 days from the current trial end.\n */\n extendTo: Date;\n};\n\nexport class BillingAPI extends AbstractAPI {\n /**\n * @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.\n */\n public async getPlanList(params?: GetOrganizationListParams) {\n return this.request<PaginatedResourceResponse<BillingPlan[]>>({\n method: 'GET',\n path: joinPaths(basePath, 'plans'),\n queryParams: params,\n });\n }\n\n /**\n * @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.\n */\n public async cancelSubscriptionItem(subscriptionItemId: string, params?: CancelSubscriptionItemParams) {\n this.requireId(subscriptionItemId);\n return this.request<BillingSubscriptionItem>({\n method: 'DELETE',\n path: joinPaths(basePath, 'subscription_items', subscriptionItemId),\n queryParams: params,\n });\n }\n\n /**\n * @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.\n */\n public async extendSubscriptionItemFreeTrial(\n subscriptionItemId: string,\n params: ExtendSubscriptionItemFreeTrialParams,\n ) {\n this.requireId(subscriptionItemId);\n return this.request<BillingSubscriptionItem>({\n method: 'POST',\n path: joinPaths('/billing', 'subscription_items', subscriptionItemId, 'extend_free_trial'),\n bodyParams: params,\n });\n }\n\n /**\n * @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.\n */\n public async getOrganizationBillingSubscription(organizationId: string) {\n this.requireId(organizationId);\n return this.request<BillingSubscription>({\n method: 'GET',\n path: joinPaths(organizationBasePath, organizationId, 'billing', 'subscription'),\n });\n }\n\n /**\n * @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.\n */\n public async getUserBillingSubscription(userId: string) {\n this.requireId(userId);\n return this.request<BillingSubscription>({\n method: 'GET',\n path: joinPaths(userBasePath, userId, 'billing', 'subscription'),\n });\n }\n}\n","import { ClerkAPIResponseError, parseError } from '@clerk/shared/error';\nimport type { ClerkAPIError, ClerkAPIErrorJSON } from '@clerk/shared/types';\nimport snakecaseKeys from 'snakecase-keys';\n\nimport { API_URL, API_VERSION, constants, SUPPORTED_BAPI_VERSION, USER_AGENT } from '../constants';\nimport { runtime } from '../runtime';\nimport { assertValidSecretKey } from '../util/optionsAssertions';\nimport { joinPaths } from '../util/path';\nimport { deserialize } from './resources/Deserializer';\n\ntype ClerkBackendApiRequestOptionsUrlOrPath =\n | {\n url: string;\n path?: string;\n }\n | {\n url?: string;\n path: string;\n };\n\ntype ClerkBackendApiRequestOptionsBodyParams =\n | {\n bodyParams: Record<string, unknown> | Array<Record<string, unknown>>;\n options?: {\n /**\n * If true, snakecases the keys of the bodyParams object recursively.\n * @default false\n */\n deepSnakecaseBodyParamKeys?: boolean;\n };\n }\n | {\n bodyParams?: never;\n options?: {\n deepSnakecaseBodyParamKeys?: never;\n };\n };\n\nexport type ClerkBackendApiRequestOptions = {\n method: 'GET' | 'POST' | 'PATCH' | 'DELETE' | 'PUT';\n queryParams?: Record<string, unknown>;\n headerParams?: Record<string, string>;\n formData?: FormData;\n} & ClerkBackendApiRequestOptionsUrlOrPath &\n ClerkBackendApiRequestOptionsBodyParams;\n\nexport type ClerkBackendApiResponse<T> =\n | {\n data: T;\n errors: null;\n totalCount?: number;\n }\n | {\n data: null;\n errors: ClerkAPIError[];\n totalCount?: never;\n clerkTraceId?: string;\n status?: number;\n statusText?: string;\n retryAfter?: number;\n };\n\nexport type RequestFunction = ReturnType<typeof buildRequest>;\n\ntype BuildRequestOptions = {\n /* Secret Key */\n secretKey?: string;\n /* Backend API URL */\n apiUrl?: string;\n /* Backend API version */\n apiVersion?: string;\n /* Library/SDK name */\n userAgent?: string;\n /**\n * Allow requests without specifying a secret key. In most cases this should be set to `false`.\n * @default true\n */\n requireSecretKey?: boolean;\n /**\n * If true, omits the API version from the request URL path.\n * This is required for bapi-proxy endpoints, which do not use versioning in the URL.\n *\n * Note: API versioning for these endpoints is instead handled via the `Clerk-API-Version` HTTP header.\n *\n * @default false\n */\n skipApiVersionInUrl?: boolean;\n /* Machine secret key */\n machineSecretKey?: string;\n /**\n * If true, uses machineSecretKey for authorization instead of secretKey.\n *\n * Note: This is only used for machine-to-machine tokens.\n *\n * @default false\n */\n useMachineSecretKey?: boolean;\n};\n\nexport function buildRequest(options: BuildRequestOptions) {\n const requestFn = async <T>(requestOptions: ClerkBackendApiRequestOptions): Promise<ClerkBackendApiResponse<T>> => {\n const {\n secretKey,\n machineSecretKey,\n useMachineSecretKey = false,\n requireSecretKey = true,\n apiUrl = API_URL,\n apiVersion = API_VERSION,\n userAgent = USER_AGENT,\n skipApiVersionInUrl = false,\n } = options;\n const { path, method, queryParams, headerParams, bodyParams, formData, options: opts } = requestOptions;\n const { deepSnakecaseBodyParamKeys = false } = opts || {};\n\n if (requireSecretKey) {\n assertValidSecretKey(secretKey);\n }\n\n const url = skipApiVersionInUrl ? joinPaths(apiUrl, path) : joinPaths(apiUrl, apiVersion, path);\n\n // Build final URL with search parameters\n const finalUrl = new URL(url);\n\n if (queryParams) {\n // Snakecase query parameters\n const snakecasedQueryParams = snakecaseKeys({ ...queryParams });\n\n // Support array values for queryParams such as { foo: [42, 43] }\n for (const [key, val] of Object.entries(snakecasedQueryParams)) {\n if (val) {\n [val].flat().forEach(v => finalUrl.searchParams.append(key, v as string));\n }\n }\n }\n\n // Build headers\n const headers = new Headers({\n 'Clerk-API-Version': SUPPORTED_BAPI_VERSION,\n [constants.Headers.UserAgent]: userAgent,\n ...headerParams,\n });\n\n // If Authorization header already exists, preserve it.\n // Otherwise, use machine secret key if enabled, or fall back to regular secret key\n const authorizationHeader = constants.Headers.Authorization;\n if (!headers.has(authorizationHeader)) {\n if (useMachineSecretKey && machineSecretKey) {\n headers.set(authorizationHeader, `Bearer ${machineSecretKey}`);\n } else if (secretKey) {\n headers.set(authorizationHeader, `Bearer ${secretKey}`);\n }\n }\n\n let res: Response | undefined;\n try {\n if (formData) {\n res = await runtime.fetch(finalUrl.href, {\n method,\n headers,\n body: formData,\n });\n } else {\n // Enforce application/json for all non form-data requests\n headers.set('Content-Type', 'application/json');\n\n const buildBody = () => {\n const hasBody = method !== 'GET' && bodyParams && Object.keys(bodyParams).length > 0;\n if (!hasBody) {\n return null;\n }\n\n const formatKeys = (object: Parameters<typeof snakecaseKeys>[0]) =>\n snakecaseKeys(object, { deep: deepSnakecaseBodyParamKeys });\n\n return {\n body: JSON.stringify(Array.isArray(bodyParams) ? bodyParams.map(formatKeys) : formatKeys(bodyParams)),\n };\n };\n\n res = await runtime.fetch(finalUrl.href, {\n method,\n headers,\n ...buildBody(),\n });\n }\n\n // TODO: Parse JSON or Text response based on a response header\n const isJSONResponse =\n res?.headers && res.headers?.get(constants.Headers.ContentType) === constants.ContentTypes.Json;\n const responseBody = await (isJSONResponse ? res.json() : res.text());\n\n if (!res.ok) {\n return {\n data: null,\n errors: parseErrors(responseBody),\n status: res?.status,\n statusText: res?.statusText,\n clerkTraceId: getTraceId(responseBody, res?.headers),\n retryAfter: getRetryAfter(res?.headers),\n };\n }\n\n return {\n ...deserialize<T>(responseBody),\n errors: null,\n };\n } catch (err) {\n if (err instanceof Error) {\n return {\n data: null,\n errors: [\n {\n code: 'unexpected_error',\n message: err.message || 'Unexpected error',\n },\n ],\n clerkTraceId: getTraceId(err, res?.headers),\n };\n }\n\n return {\n data: null,\n errors: parseErrors(err),\n status: res?.status,\n statusText: res?.statusText,\n clerkTraceId: getTraceId(err, res?.headers),\n retryAfter: getRetryAfter(res?.headers),\n };\n }\n };\n\n return withLegacyRequestReturn(requestFn);\n}\n\n// Returns either clerk_trace_id if present in response json, otherwise defaults to CF-Ray header\n// If the request failed before receiving a response, returns undefined\nfunction getTraceId(data: unknown, headers?: Headers): string {\n if (data && typeof data === 'object' && 'clerk_trace_id' in data && typeof data.clerk_trace_id === 'string') {\n return data.clerk_trace_id;\n }\n\n const cfRay = headers?.get('cf-ray');\n return cfRay || '';\n}\n\nfunction getRetryAfter(headers?: Headers): number | undefined {\n const retryAfter = headers?.get('Retry-After');\n if (!retryAfter) {\n return;\n }\n\n const value = parseInt(retryAfter, 10);\n if (isNaN(value)) {\n return;\n }\n\n return value;\n}\n\nfunction parseErrors(data: unknown): ClerkAPIError[] {\n if (!!data && typeof data === 'object' && 'errors' in data) {\n const errors = data.errors as ClerkAPIErrorJSON[];\n return errors.length > 0 ? errors.map(parseError) : [];\n }\n return [];\n}\n\ntype LegacyRequestFunction = <T>(requestOptions: ClerkBackendApiRequestOptions) => Promise<T>;\n\n// TODO(dimkl): Will be probably be dropped in next major version\nfunction withLegacyRequestReturn(cb: any): LegacyRequestFunction {\n return async (...args) => {\n const { data, errors, totalCount, status, statusText, clerkTraceId, retryAfter } = await cb(...args);\n if (errors) {\n // instead of passing `data: errors`, we have set the `error.errors` because\n // the errors returned from callback is already parsed and passing them as `data`\n // will not be able to assign them to the instance\n const error = new ClerkAPIResponseError(statusText || '', {\n data: [],\n status,\n clerkTraceId,\n retryAfter,\n });\n error.errors = errors;\n throw error;\n }\n\n if (typeof totalCount !== 'undefined') {\n return { data, totalCount };\n }\n\n return data;\n };\n}\n","const isObject = value => typeof value === 'object' && value !== null;\n\n// Customized for this use-case\nconst isObjectCustom = value =>\n\tisObject(value)\n\t&& !(value instanceof RegExp)\n\t&& !(value instanceof Error)\n\t&& !(value instanceof Date)\n\t&& !(globalThis.Blob && value instanceof globalThis.Blob);\n\nexport const mapObjectSkip = Symbol('mapObjectSkip');\n\nconst _mapObject = (object, mapper, options, isSeen = new WeakMap()) => {\n\toptions = {\n\t\tdeep: false,\n\t\ttarget: {},\n\t\t...options,\n\t};\n\n\tif (isSeen.has(object)) {\n\t\treturn isSeen.get(object);\n\t}\n\n\tisSeen.set(object, options.target);\n\n\tconst {target} = options;\n\tdelete options.target;\n\n\tconst mapArray = array => array.map(element => isObjectCustom(element) ? _mapObject(element, mapper, options, isSeen) : element);\n\tif (Array.isArray(object)) {\n\t\treturn mapArray(object);\n\t}\n\n\tfor (const [key, value] of Object.entries(object)) {\n\t\tconst mapResult = mapper(key, value, object);\n\n\t\tif (mapResult === mapObjectSkip) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet [newKey, newValue, {shouldRecurse = true} = {}] = mapResult;\n\n\t\t// Drop `__proto__` keys.\n\t\tif (newKey === '__proto__') {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (options.deep && shouldRecurse && isObjectCustom(newValue)) {\n\t\t\tnewValue = Array.isArray(newValue)\n\t\t\t\t? mapArray(newValue)\n\t\t\t\t: _mapObject(newValue, mapper, options, isSeen);\n\t\t}\n\n\t\ttarget[newKey] = newValue;\n\t}\n\n\treturn target;\n};\n\nexport default function mapObject(object, mapper, options) {\n\tif (!isObject(object)) {\n\t\tthrow new TypeError(`Expected an object, got \\`${object}\\` (${typeof object})`);\n\t}\n\n\tif (Array.isArray(object)) {\n\t\tthrow new TypeError('Expected an object, got an array');\n\t}\n\n\treturn _mapObject(object, mapper, options);\n}\n","// Regexps involved with splitting words in various case formats.\nconst SPLIT_LOWER_UPPER_RE = /([\\p{Ll}\\d])(\\p{Lu})/gu;\nconst SPLIT_UPPER_UPPER_RE = /(\\p{Lu})([\\p{Lu}][\\p{Ll}])/gu;\n\n// Used to iterate over the initial split result and separate numbers.\nconst SPLIT_SEPARATE_NUMBER_RE = /(\\d)\\p{Ll}|(\\p{L})\\d/u;\n\n// Regexp involved with stripping non-word characters from the result.\nconst DEFAULT_STRIP_REGEXP = /[^\\p{L}\\d]+/giu;\n\n// The replacement value for splits.\nconst SPLIT_REPLACE_VALUE = \"$1\\0$2\";\n\n// The default characters to keep after transforming case.\nconst DEFAULT_PREFIX_SUFFIX_CHARACTERS = \"\";\n\n/**\n * Supported locale values. Use `false` to ignore locale.\n * Defaults to `undefined`, which uses the host environment.\n */\nexport type Locale = string[] | string | false | undefined;\n\n/**\n * Options used for converting strings to pascal/camel case.\n */\nexport interface PascalCaseOptions extends Options {\n mergeAmbiguousCharacters?: boolean;\n}\n\n/**\n * Options used for converting strings to any case.\n */\nexport interface Options {\n locale?: Locale;\n split?: (value: string) => string[];\n /** @deprecated Pass `split: splitSeparateNumbers` instead. */\n separateNumbers?: boolean;\n delimiter?: string;\n prefixCharacters?: string;\n suffixCharacters?: string;\n}\n\n/**\n * Split any cased input strings into an array of words.\n */\nexport function split(value: string) {\n let result = value.trim();\n\n result = result\n .replace(SPLIT_LOWER_UPPER_RE, SPLIT_REPLACE_VALUE)\n .replace(SPLIT_UPPER_UPPER_RE, SPLIT_REPLACE_VALUE);\n\n result = result.replace(DEFAULT_STRIP_REGEXP, \"\\0\");\n\n let start = 0;\n let end = result.length;\n\n // Trim the delimiter from around the output string.\n while (result.charAt(start) === \"\\0\") start++;\n if (start === end) return [];\n while (result.charAt(end - 1) === \"\\0\") end--;\n\n return result.slice(start, end).split(/\\0/g);\n}\n\n/**\n * Split the input string into an array of words, separating numbers.\n */\nexport function splitSeparateNumbers(value: string) {\n const words = split(value);\n for (let i = 0; i < words.length; i++) {\n const word = words[i];\n const match = SPLIT_SEPARATE_NUMBER_RE.exec(word);\n if (match) {\n const offset = match.index + (match[1] ?? match[2]).length;\n words.splice(i, 1, word.slice(0, offset), word.slice(offset));\n }\n }\n return words;\n}\n\n/**\n * Convert a string to space separated lower case (`foo bar`).\n */\nexport function noCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n return (\n prefix +\n words.map(lowerFactory(options?.locale)).join(options?.delimiter ?? \" \") +\n suffix\n );\n}\n\n/**\n * Convert a string to camel case (`fooBar`).\n */\nexport function camelCase(input: string, options?: PascalCaseOptions) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n const transform = options?.mergeAmbiguousCharacters\n ? capitalCaseTransformFactory(lower, upper)\n : pascalCaseTransformFactory(lower, upper);\n return (\n prefix +\n words\n .map((word, index) => {\n if (index === 0) return lower(word);\n return transform(word, index);\n })\n .join(options?.delimiter ?? \"\") +\n suffix\n );\n}\n\n/**\n * Convert a string to pascal case (`FooBar`).\n */\nexport function pascalCase(input: string, options?: PascalCaseOptions) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n const transform = options?.mergeAmbiguousCharacters\n ? capitalCaseTransformFactory(lower, upper)\n : pascalCaseTransformFactory(lower, upper);\n return prefix + words.map(transform).join(options?.delimiter ?? \"\") + suffix;\n}\n\n/**\n * Convert a string to pascal snake case (`Foo_Bar`).\n */\nexport function pascalSnakeCase(input: string, options?: Options) {\n return capitalCase(input, { delimiter: \"_\", ...options });\n}\n\n/**\n * Convert a string to capital case (`Foo Bar`).\n */\nexport function capitalCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n return (\n prefix +\n words\n .map(capitalCaseTransformFactory(lower, upper))\n .join(options?.delimiter ?? \" \") +\n suffix\n );\n}\n\n/**\n * Convert a string to constant case (`FOO_BAR`).\n */\nexport function constantCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n return (\n prefix +\n words.map(upperFactory(options?.locale)).join(options?.delimiter ?? \"_\") +\n suffix\n );\n}\n\n/**\n * Convert a string to dot case (`foo.bar`).\n */\nexport function dotCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \".\", ...options });\n}\n\n/**\n * Convert a string to kebab case (`foo-bar`).\n */\nexport function kebabCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \"-\", ...options });\n}\n\n/**\n * Convert a string to path case (`foo/bar`).\n */\nexport function pathCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \"/\", ...options });\n}\n\n/**\n * Convert a string to path case (`Foo bar`).\n */\nexport function sentenceCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n const transform = capitalCaseTransformFactory(lower, upper);\n return (\n prefix +\n words\n .map((word, index) => {\n if (index === 0) return transform(word);\n return lower(word);\n })\n .join(options?.delimiter ?? \" \") +\n suffix\n );\n}\n\n/**\n * Convert a string to snake case (`foo_bar`).\n */\nexport function snakeCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \"_\", ...options });\n}\n\n/**\n * Convert a string to header case (`Foo-Bar`).\n */\nexport function trainCase(input: string, options?: Options) {\n return capitalCase(input, { delimiter: \"-\", ...options });\n}\n\nfunction lowerFactory(locale: Locale): (input: string) => string {\n return locale === false\n ? (input: string) => input.toLowerCase()\n : (input: string) => input.toLocaleLowerCase(locale);\n}\n\nfunction upperFactory(locale: Locale): (input: string) => string {\n return locale === false\n ? (input: string) => input.toUpperCase()\n : (input: string) => input.toLocaleUpperCase(locale);\n}\n\nfunction capitalCaseTransformFactory(\n lower: (input: string) => string,\n upper: (input: string) => string,\n) {\n return (word: string) => `${upper(word[0])}${lower(word.slice(1))}`;\n}\n\nfunction pascalCaseTransformFactory(\n lower: (input: string) => string,\n upper: (input: string) => string,\n) {\n return (word: string, index: number) => {\n const char0 = word[0];\n const initial =\n index > 0 && char0 >= \"0\" && char0 <= \"9\" ? \"_\" + char0 : upper(char0);\n return initial + lower(word.slice(1));\n };\n}\n\nfunction splitPrefixSuffix(\n input: string,\n options: Options = {},\n): [string, string[], string] {\n const splitFn =\n options.split ?? (options.separateNumbers ? splitSeparateNumbers : split);\n const prefixCharacters =\n options.prefixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS;\n const suffixCharacters =\n options.suffixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS;\n let prefixIndex = 0;\n let suffixIndex = input.length;\n\n while (prefixIndex < input.length) {\n const char = input.charAt(prefixIndex);\n if (!prefixCharacters.includes(char)) break;\n prefixIndex++;\n }\n\n while (suffixIndex > prefixIndex) {\n const index = suffixIndex - 1;\n const char = input.charAt(index);\n if (!suffixCharacters.includes(char)) break;\n suffixIndex = index;\n }\n\n return [\n input.slice(0, prefixIndex),\n splitFn(input.slice(prefixIndex, suffixIndex)),\n input.slice(suffixIndex),\n ];\n}\n","'use strict'\n\nimport map from 'map-obj'\nimport { snakeCase } from 'change-case'\n\nconst PlainObjectConstructor = {}.constructor\n\nfunction snakecaseKeys (obj, options) {\n if (Array.isArray(obj)) {\n if (obj.some(item => item.constructor !== PlainObjectConstructor)) {\n throw new Error('obj must be array of plain objects')\n }\n\n options = { deep: true, exclude: [], parsingOptions: {}, ...options }\n const convertCase = options.snakeCase || ((key) => snakeCase(key, options.parsingOptions))\n\n // Handle arrays by mapping each element\n return obj.map(item => {\n return map(item, (key, val) => {\n return [\n matches(options.exclude, key) ? key : convertCase(key),\n val,\n mapperOptions(key, val, options)\n ]\n }, options)\n })\n } else {\n if (obj.constructor !== PlainObjectConstructor) {\n throw new Error('obj must be an plain object')\n }\n }\n\n options = { deep: true, exclude: [], parsingOptions: {}, ...options }\n\n const convertCase = options.snakeCase || ((key) => snakeCase(key, options.parsingOptions))\n\n return map(obj, (key, val) => {\n return [\n matches(options.exclude, key) ? key : convertCase(key),\n val,\n mapperOptions(key, val, options)\n ]\n }, options)\n}\n\nfunction matches (patterns, value) {\n return patterns.some(pattern => {\n return typeof pattern === 'string'\n ? pattern === value\n : pattern.test(value)\n })\n}\n\nfunction mapperOptions (key, val, options) {\n return options.shouldRecurse\n ? { shouldRecurse: options.shouldRecurse(key, val) }\n : undefined\n}\n\nexport default snakecaseKeys\n","import type { AccountlessApplicationJSON } from './JSON';\n\nexport class AccountlessApplication {\n constructor(\n readonly publishableKey: string,\n readonly secretKey: string,\n readonly claimUrl: string,\n readonly apiKeysUrl: string,\n ) {}\n\n static fromJSON(data: AccountlessApplicationJSON): AccountlessApplication {\n return new AccountlessApplication(data.publishable_key, data.secret_key, data.claim_url, data.api_keys_url);\n }\n}\n","import type { ActorTokenStatus } from './Enums';\nimport type { ActorTokenJSON } from './JSON';\n\nexport class ActorToken {\n constructor(\n readonly id: string,\n readonly status: ActorTokenStatus,\n readonly userId: string,\n readonly actor: Record<string, unknown> | null,\n readonly token: string | null | undefined,\n readonly url: string | null | undefined,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: ActorTokenJSON): ActorToken {\n return new ActorToken(\n data.id,\n data.status,\n data.user_id,\n data.actor,\n data.token,\n data.url,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { AllowlistIdentifierType } from './Enums';\nimport type { AllowlistIdentifierJSON } from './JSON';\n\n/**\n * The Backend `AllowlistIdentifier` object represents an identifier that has been added to the allowlist of your application. The Backend `AllowlistIdentifier` object is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Allow-list-Block-list#operation/ListAllowlistIdentifiers) and is not directly accessible from the Frontend API.\n */\nexport class AllowlistIdentifier {\n constructor(\n /**\n * A unique ID for the allowlist identifier.\n */\n readonly id: string,\n /**\n * The identifier that was added to the allowlist.\n */\n readonly identifier: string,\n /**\n * The type of the allowlist identifier.\n */\n readonly identifierType: AllowlistIdentifierType,\n /**\n * The date when the allowlist identifier was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the allowlist identifier was last updated.\n */\n readonly updatedAt: number,\n /**\n * The ID of the instance that this allowlist identifier belongs to.\n */\n readonly instanceId?: string,\n /**\n * The ID of the invitation sent to the identifier.\n */\n readonly invitationId?: string,\n ) {}\n\n static fromJSON(data: AllowlistIdentifierJSON): AllowlistIdentifier {\n return new AllowlistIdentifier(\n data.id,\n data.identifier,\n data.identifier_type,\n data.created_at,\n data.updated_at,\n data.instance_id,\n data.invitation_id,\n );\n }\n}\n","import type { APIKeyJSON } from './JSON';\n\nexport class APIKey {\n constructor(\n readonly id: string,\n readonly type: string,\n readonly name: string,\n readonly subject: string,\n readonly scopes: string[],\n readonly claims: Record<string, any> | null,\n readonly revoked: boolean,\n readonly revocationReason: string | null,\n readonly expired: boolean,\n readonly expiration: number | null,\n readonly createdBy: string | null,\n readonly description: string | null,\n readonly lastUsedAt: number | null,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly secret?: string,\n ) {}\n\n static fromJSON(data: APIKeyJSON) {\n return new APIKey(\n data.id,\n data.type,\n data.name,\n data.subject,\n data.scopes,\n data.claims,\n data.revoked,\n data.revocation_reason,\n data.expired,\n data.expiration,\n data.created_by,\n data.description,\n data.last_used_at,\n data.created_at,\n data.updated_at,\n data.secret,\n );\n }\n}\n","import type { BlocklistIdentifierType } from './Enums';\nimport type { BlocklistIdentifierJSON } from './JSON';\n\nexport class BlocklistIdentifier {\n constructor(\n readonly id: string,\n readonly identifier: string,\n readonly identifierType: BlocklistIdentifierType,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly instanceId?: string,\n ) {}\n\n static fromJSON(data: BlocklistIdentifierJSON): BlocklistIdentifier {\n return new BlocklistIdentifier(\n data.id,\n data.identifier,\n data.identifier_type,\n data.created_at,\n data.updated_at,\n data.instance_id,\n );\n }\n}\n","import type { SessionActivityJSON, SessionJSON } from './JSON';\n\n/**\n * The Backend `SessionActivity` object models the activity of a user session, capturing details such as the device type, browser information, and geographical location.\n */\nexport class SessionActivity {\n constructor(\n /**\n * The unique identifier for the session activity record.\n */\n readonly id: string,\n /**\n * Will be set to `true` if the session activity came from a mobile device. Set to `false` otherwise.\n */\n readonly isMobile: boolean,\n /**\n * The IP address from which this session activity originated.\n */\n readonly ipAddress?: string,\n /**\n * The city from which this session activity occurred. Resolved by IP address geo-location.\n */\n readonly city?: string,\n /**\n * The country from which this session activity occurred. Resolved by IP address geo-location.\n */\n readonly country?: string,\n /**\n * The version of the browser from which this session activity occurred.\n */\n readonly browserVersion?: string,\n /**\n * The name of the browser from which this session activity occurred.\n */\n readonly browserName?: string,\n /**\n * The type of the device which was used in this session activity.\n */\n readonly deviceType?: string,\n ) {}\n\n static fromJSON(data: SessionActivityJSON): SessionActivity {\n return new SessionActivity(\n data.id,\n data.is_mobile,\n data.ip_address,\n data.city,\n data.country,\n data.browser_version,\n data.browser_name,\n data.device_type,\n );\n }\n}\n\n/**\n * The Backend `Session` object is similar to the [`Session`](https://clerk.com/docs/reference/javascript/session) object as it is an abstraction over an HTTP session and models the period of information exchange between a user and the server. However, the Backend `Session` object is different as it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Sessions#operation/GetSessionList) and is not directly accessible from the Frontend API.\n */\nexport class Session {\n constructor(\n /**\n * The unique identifier for the `Session`.\n */\n readonly id: string,\n /**\n * The ID of the client associated with the `Session`.\n */\n readonly clientId: string,\n /**\n * The ID of the user associated with the `Session`.\n */\n readonly userId: string,\n /**\n * The current state of the `Session`.\n */\n readonly status: string,\n /**\n * The time the session was last active on the [`Client`](https://clerk.com/docs/reference/backend/types/backend-client).\n */\n readonly lastActiveAt: number,\n /**\n * The date when the `Session` will expire.\n */\n readonly expireAt: number,\n /**\n * The date when the `Session` will be abandoned.\n */\n readonly abandonAt: number,\n /**\n * The date when the `Session` was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the `Session` was last updated.\n */\n readonly updatedAt: number,\n /**\n * The ID of the last active organization.\n */\n readonly lastActiveOrganizationId?: string,\n /**\n * An object that provides additional information about this session, focused around user activity data.\n */\n readonly latestActivity?: SessionActivity,\n /**\n * The JWT actor for the session. Holds identifier for the user that is impersonating the current user. Read more about [impersonation](https://clerk.com/docs/guides/users/impersonation).\n */\n readonly actor: Record<string, unknown> | null = null,\n ) {}\n\n static fromJSON(data: SessionJSON): Session {\n return new Session(\n data.id,\n data.client_id,\n data.user_id,\n data.status,\n data.last_active_at,\n data.expire_at,\n data.abandon_at,\n data.created_at,\n data.updated_at,\n data.last_active_organization_id,\n data.latest_activity && SessionActivity.fromJSON(data.latest_activity),\n data.actor,\n );\n }\n}\n","import type { LastAuthenticationStrategy } from '@clerk/shared/types';\n\nimport type { ClientJSON } from './JSON';\nimport { Session } from './Session';\n\n/**\n * The Backend `Client` object is similar to the [`Client`](https://clerk.com/docs/reference/javascript/client) object as it holds information about the authenticated sessions in the current device. However, the Backend `Client` object is different from the `Client` object in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Clients#operation/GetClient) and is not directly accessible from the Frontend API.\n */\nexport class Client {\n constructor(\n /**\n * The unique identifier for the `Client`.\n */\n readonly id: string,\n /**\n * An array of [Session](https://clerk.com/docs/reference/backend/types/backend-session){{ target: '_blank' }} IDs associated with the `Client`.\n */\n readonly sessionIds: string[],\n /**\n * An array of [Session](https://clerk.com/docs/reference/backend/types/backend-session){{ target: '_blank' }} objects associated with the `Client`.\n */\n readonly sessions: Session[],\n /**\n * The ID of the [`SignIn`](https://clerk.com/docs/reference/javascript/sign-in){{ target: '_blank' }}.\n */\n readonly signInId: string | null,\n /**\n * The ID of the [`SignUp`](https://clerk.com/docs/reference/javascript/sign-up){{ target: '_blank' }}.\n */\n readonly signUpId: string | null,\n /**\n * The ID of the last active [Session](https://clerk.com/docs/reference/backend/types/backend-session).\n */\n readonly lastActiveSessionId: string | null,\n /**\n * The last authentication strategy used by the `Client`.\n */\n readonly lastAuthenticationStrategy: LastAuthenticationStrategy | null,\n /**\n * The date when the `Client` was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the `Client` was last updated.\n */\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: ClientJSON): Client {\n return new Client(\n data.id,\n data.session_ids,\n data.sessions.map(x => Session.fromJSON(x)),\n data.sign_in_id,\n data.sign_up_id,\n data.last_active_session_id,\n data.last_authentication_strategy,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { CnameTargetJSON } from './JSON';\n\nexport class CnameTarget {\n constructor(\n readonly host: string,\n readonly value: string,\n readonly required: boolean,\n ) {}\n\n static fromJSON(data: CnameTargetJSON): CnameTarget {\n return new CnameTarget(data.host, data.value, data.required);\n }\n}\n","import type { CookiesJSON } from './JSON';\n\nexport class Cookies {\n constructor(readonly cookies: string[]) {}\n\n static fromJSON(data: CookiesJSON): Cookies {\n return new Cookies(data.cookies);\n }\n}\n","import type { DeletedObjectJSON } from './JSON';\n\nexport class DeletedObject {\n constructor(\n readonly object: string,\n readonly id: string | null,\n readonly slug: string | null,\n readonly deleted: boolean,\n ) {}\n\n static fromJSON(data: DeletedObjectJSON) {\n return new DeletedObject(data.object, data.id || null, data.slug || null, data.deleted);\n }\n}\n","import { CnameTarget } from './CnameTarget';\nimport type { DomainJSON } from './JSON';\n\nexport class Domain {\n constructor(\n readonly id: string,\n readonly name: string,\n readonly isSatellite: boolean,\n readonly frontendApiUrl: string,\n readonly developmentOrigin: string,\n readonly cnameTargets: CnameTarget[],\n readonly accountsPortalUrl?: string | null,\n readonly proxyUrl?: string | null,\n ) {}\n\n static fromJSON(data: DomainJSON): Domain {\n return new Domain(\n data.id,\n data.name,\n data.is_satellite,\n data.frontend_api_url,\n data.development_origin,\n data.cname_targets && data.cname_targets.map(x => CnameTarget.fromJSON(x)),\n data.accounts_portal_url,\n data.proxy_url,\n );\n }\n}\n","import type { EmailJSON } from './JSON';\n\nexport class Email {\n constructor(\n readonly id: string,\n readonly fromEmailName: string,\n readonly emailAddressId: string | null,\n readonly toEmailAddress?: string,\n readonly subject?: string,\n readonly body?: string,\n readonly bodyPlain?: string | null,\n readonly status?: string,\n readonly slug?: string | null,\n readonly data?: Record<string, any> | null,\n readonly deliveredByClerk?: boolean,\n ) {}\n\n static fromJSON(data: EmailJSON): Email {\n return new Email(\n data.id,\n data.from_email_name,\n data.email_address_id,\n data.to_email_address,\n data.subject,\n data.body,\n data.body_plain,\n data.status,\n data.slug,\n data.data,\n data.delivered_by_clerk,\n );\n }\n}\n","import type { IdentificationLinkJSON } from './JSON';\n\n/**\n * Contains information about any identifications that might be linked to the email address.\n */\nexport class IdentificationLink {\n constructor(\n /**\n * The unique identifier for the identification link.\n */\n readonly id: string,\n /**\n * The type of the identification link, e.g., `\"email_address\"`, `\"phone_number\"`, etc.\n */\n readonly type: string,\n ) {}\n\n static fromJSON(data: IdentificationLinkJSON): IdentificationLink {\n return new IdentificationLink(data.id, data.type);\n }\n}\n","import type { VerificationStatus } from '@clerk/shared/types';\n\nimport type { OrganizationDomainVerificationJSON, VerificationJSON } from './JSON';\n\n/**\n * The Backend `Verification` object describes the state of the verification process of a sign-in or sign-up attempt.\n */\nexport class Verification {\n constructor(\n /**\n * The state of the verification.\n *\n * <ul>\n * <li>`unverified`: The verification has not been verified yet.</li>\n * <li>`verified`: The verification has been verified.</li>\n * <li>`transferable`: The verification is transferable to between sign-in and sign-up flows.</li>\n * <li>`failed`: The verification has failed.</li>\n * <li>`expired`: The verification has expired.</li>\n * </ul>\n */\n readonly status: VerificationStatus,\n /**\n * The strategy pertaining to the parent sign-up or sign-in attempt.\n */\n readonly strategy: string,\n /**\n * The redirect URL for an external verification.\n */\n readonly externalVerificationRedirectURL: URL | null = null,\n /**\n * The number of attempts related to the verification.\n */\n readonly attempts: number | null = null,\n /**\n * The time the verification will expire at.\n */\n readonly expireAt: number | null = null,\n /**\n * The [nonce](https://en.wikipedia.org/wiki/Cryptographic_nonce) pertaining to the verification.\n */\n readonly nonce: string | null = null,\n /**\n * The message that will be presented to the user's Web3 wallet for signing during authentication. This follows the [Sign-In with Ethereum (SIWE) protocol format](https://docs.login.xyz/general-information/siwe-overview/eip-4361#example-message-to-be-signed), which typically includes details like the requesting service, wallet address, terms acceptance, nonce, timestamp, and any additional resources.\n */\n readonly message: string | null = null,\n ) {}\n\n static fromJSON(data: VerificationJSON): Verification {\n return new Verification(\n data.status,\n data.strategy,\n data.external_verification_redirect_url ? new URL(data.external_verification_redirect_url) : null,\n data.attempts,\n data.expire_at,\n data.nonce,\n );\n }\n}\n\nexport class OrganizationDomainVerification {\n constructor(\n readonly status: string,\n readonly strategy: string,\n readonly attempts: number | null = null,\n readonly expireAt: number | null = null,\n ) {}\n\n static fromJSON(data: OrganizationDomainVerificationJSON): OrganizationDomainVerification {\n return new OrganizationDomainVerification(data.status, data.strategy, data.attempts, data.expires_at);\n }\n}\n","import { IdentificationLink } from './IdentificationLink';\nimport type { EmailAddressJSON } from './JSON';\nimport { Verification } from './Verification';\n\n/**\n * The Backend `EmailAddress` object is a model around an email address.\n *\n * Email addresses must be **verified** to ensure that they are assigned to their rightful owners. The `EmailAddress` object holds all necessary state around the verification process.\n *\n * For implementation examples for adding and verifying email addresses, see the [email link custom flow](https://clerk.com/docs/guides/development/custom-flows/authentication/email-links) and [email code custom flow](https://clerk.com/docs/guides/development/custom-flows/account-updates/add-email) guides.\n */\nexport class EmailAddress {\n constructor(\n /**\n * The unique identifier for the email address.\n */\n readonly id: string,\n /**\n * The value of the email address.\n */\n readonly emailAddress: string,\n /**\n * An object holding information on the verification of the email address.\n */\n readonly verification: Verification | null,\n /**\n * An array of objects containing information about any identifications that might be linked to the email address.\n */\n readonly linkedTo: IdentificationLink[],\n ) {}\n\n static fromJSON(data: EmailAddressJSON): EmailAddress {\n return new EmailAddress(\n data.id,\n data.email_address,\n data.verification && Verification.fromJSON(data.verification),\n data.linked_to.map(link => IdentificationLink.fromJSON(link)),\n );\n }\n}\n","import type { FeatureJSON } from './JSON';\n\n/**\n * The `Feature` object represents a feature of a subscription plan.\n *\n * @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.\n */\nexport class Feature {\n constructor(\n /**\n * The unique identifier for the feature.\n */\n readonly id: string,\n /**\n * The name of the feature.\n */\n readonly name: string,\n /**\n * The description of the feature.\n */\n readonly description: string | null,\n /**\n * The URL-friendly identifier of the feature.\n */\n readonly slug: string,\n /**\n * The URL of the feature's avatar image.\n */\n readonly avatarUrl: string | null,\n ) {}\n\n static fromJSON(data: FeatureJSON): Feature {\n return new Feature(data.id, data.name, data.description ?? null, data.slug, data.avatar_url ?? null);\n }\n}\n","import type { BillingMoneyAmount, BillingMoneyAmountJSON } from '@clerk/shared/types';\n\nimport { Feature } from './Feature';\nimport type { BillingPlanJSON } from './JSON';\n\n/**\n * The `BillingPlan` object is similar to the [`BillingPlanResource`](/docs/reference/javascript/types/billing-plan-resource) object as it holds information about a plan, as well as methods for managing it. However, the `BillingPlan` object is different in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/commerce/get/commerce/plans) and is not directly accessible from the Frontend API.\n *\n * @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.\n */\nexport class BillingPlan {\n constructor(\n /**\n * The unique identifier for the plan.\n */\n readonly id: string,\n /**\n * The name of the plan.\n */\n readonly name: string,\n /**\n * The URL-friendly identifier of the plan.\n */\n readonly slug: string,\n /**\n * The description of the plan.\n */\n readonly description: string | null,\n /**\n * Whether the plan is the default plan.\n */\n readonly isDefault: boolean,\n /**\n * Whether the plan is recurring.\n */\n readonly isRecurring: boolean,\n /**\n * Whether the plan has a base fee.\n */\n readonly hasBaseFee: boolean,\n /**\n * Whether the plan is displayed in the `<PriceTable/>` component.\n */\n readonly publiclyVisible: boolean,\n /**\n * The monthly fee of the plan.\n */\n readonly fee: BillingMoneyAmount,\n /**\n * The annual fee of the plan.\n */\n readonly annualFee: BillingMoneyAmount | null,\n /**\n * The annual fee of the plan on a monthly basis.\n */\n readonly annualMonthlyFee: BillingMoneyAmount | null,\n /**\n * The type of payer for the plan.\n */\n readonly forPayerType: 'org' | 'user',\n /**\n * The features the plan offers.\n */\n readonly features: Feature[],\n ) {}\n\n static fromJSON(data: BillingPlanJSON): BillingPlan {\n const formatAmountJSON = <T extends BillingMoneyAmountJSON | null>(\n fee: T,\n ): T extends null ? null : BillingMoneyAmount => {\n return (\n fee\n ? {\n amount: fee.amount,\n amountFormatted: fee.amount_formatted,\n currency: fee.currency,\n currencySymbol: fee.currency_symbol,\n }\n : null\n ) as T extends null ? null : BillingMoneyAmount;\n };\n return new BillingPlan(\n data.id,\n data.name,\n data.slug,\n data.description ?? null,\n data.is_default,\n data.is_recurring,\n data.has_base_fee,\n data.publicly_visible,\n formatAmountJSON(data.fee),\n formatAmountJSON(data.annual_fee),\n formatAmountJSON(data.annual_monthly_fee),\n data.for_payer_type,\n (data.features ?? []).map(feature => Feature.fromJSON(feature)),\n );\n }\n}\n","import type { BillingMoneyAmount, BillingMoneyAmountJSON } from '@clerk/shared/types';\n\nimport { BillingPlan } from './CommercePlan';\nimport type { BillingSubscriptionItemJSON } from './JSON';\n\n/**\n * The `BillingSubscriptionItem` object is similar to the [`BillingSubscriptionItemResource`](/docs/reference/javascript/types/billing-subscription-item-resource) object as it holds information about a subscription item, as well as methods for managing it. However, the `BillingSubscriptionItem` object is different in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/commerce/get/commerce/subscription_items) and is not directly accessible from the Frontend API.\n *\n * @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.\n */\nexport class BillingSubscriptionItem {\n constructor(\n /**\n * The unique identifier for the subscription item.\n */\n readonly id: string,\n /**\n * The status of the subscription item.\n */\n readonly status: BillingSubscriptionItemJSON['status'],\n /**\n * The plan period for the subscription item.\n */\n readonly planPeriod: 'month' | 'annual',\n /**\n * Unix timestamp (milliseconds) of when the current period starts.\n */\n readonly periodStart: number,\n /**\n * The next payment information.\n */\n readonly nextPayment:\n | {\n /**\n * The amount of the next payment.\n */\n amount: number;\n /**\n * Unix timestamp (milliseconds) of when the next payment is scheduled.\n */\n date: number;\n }\n | null\n | undefined,\n /**\n * The current amount for the subscription item.\n */\n readonly amount: BillingMoneyAmount | undefined,\n /**\n * The plan associated with this subscription item.\n */\n readonly plan: BillingPlan | null,\n /**\n * The plan ID.\n */\n readonly planId: string | null,\n /**\n * Unix timestamp (milliseconds) of when the subscription item was created.\n */\n readonly createdAt: number,\n /**\n * Unix timestamp (milliseconds) of when the subscription item was last updated.\n */\n readonly updatedAt: number,\n /**\n * Unix timestamp (milliseconds) of when the current period ends.\n */\n readonly periodEnd: number | null,\n /**\n * Unix timestamp (milliseconds) of when the subscription item was canceled.\n */\n readonly canceledAt: number | null,\n /**\n * Unix timestamp (milliseconds) of when the subscription item became past due.\n */\n readonly pastDueAt: number | null,\n /**\n * Unix timestamp (milliseconds) of when the subscription item ended.\n */\n readonly endedAt: number | null,\n /**\n * The payer ID.\n */\n readonly payerId: string | undefined,\n /**\n * Whether this subscription item is currently in a free trial period.\n */\n readonly isFreeTrial?: boolean,\n /**\n * The lifetime amount paid for this subscription item.\n */\n readonly lifetimePaid?: BillingMoneyAmount,\n ) {}\n\n static fromJSON(data: BillingSubscriptionItemJSON): BillingSubscriptionItem {\n function formatAmountJSON(\n amount: BillingMoneyAmountJSON | null | undefined,\n ): BillingMoneyAmount | null | undefined {\n if (!amount) {\n return amount;\n }\n\n return {\n amount: amount.amount,\n amountFormatted: amount.amount_formatted,\n currency: amount.currency,\n currencySymbol: amount.currency_symbol,\n };\n }\n\n return new BillingSubscriptionItem(\n data.id,\n data.status,\n data.plan_period,\n data.period_start,\n data.next_payment,\n formatAmountJSON(data.amount) ?? undefined,\n data.plan ? BillingPlan.fromJSON(data.plan) : null,\n data.plan_id ?? null,\n data.created_at,\n data.updated_at,\n data.period_end,\n data.canceled_at,\n data.past_due_at,\n data.ended_at,\n data.payer_id,\n data.is_free_trial,\n formatAmountJSON(data.lifetime_paid) ?? undefined,\n );\n }\n}\n","import type { BillingMoneyAmount } from '@clerk/shared/types';\n\nimport { BillingSubscriptionItem } from './CommerceSubscriptionItem';\nimport type { BillingSubscriptionJSON } from './JSON';\n\n/**\n * The `BillingSubscription` object is similar to the [`BillingSubscriptionResource`](/docs/reference/javascript/types/billing-subscription-resource) object as it holds information about a subscription, as well as methods for managing it. However, the `BillingSubscription` object is different in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/billing/get/organizations/%7Borganization_id%7D/billing/subscription) and is not directly accessible from the Frontend API.\n *\n * @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.\n */\nexport class BillingSubscription {\n constructor(\n /**\n * The unique identifier for the billing subscription.\n */\n readonly id: string,\n /**\n * The current status of the subscription.\n */\n readonly status: BillingSubscriptionJSON['status'],\n /**\n * The ID of the payer for this subscription.\n */\n readonly payerId: string,\n /**\n * Unix timestamp (milliseconds) of when the subscription was created.\n */\n readonly createdAt: number,\n /**\n * Unix timestamp (milliseconds) of when the subscription was last updated.\n */\n readonly updatedAt: number,\n /**\n * Unix timestamp (milliseconds) of when the subscription became active.\n */\n readonly activeAt: number | null,\n /**\n * Unix timestamp (milliseconds) of when the subscription became past due.\n */\n readonly pastDueAt: number | null,\n /**\n * Array of subscription items in this subscription.\n */\n readonly subscriptionItems: BillingSubscriptionItem[],\n /**\n * Information about the next scheduled payment.\n */\n readonly nextPayment: { date: number; amount: BillingMoneyAmount } | null,\n /**\n * Whether the payer is eligible for a free trial.\n */\n readonly eligibleForFreeTrial: boolean,\n ) {}\n\n static fromJSON(data: BillingSubscriptionJSON): BillingSubscription {\n const nextPayment = data.next_payment\n ? {\n date: data.next_payment.date,\n amount: {\n amount: data.next_payment.amount.amount,\n amountFormatted: data.next_payment.amount.amount_formatted,\n currency: data.next_payment.amount.currency,\n currencySymbol: data.next_payment.amount.currency_symbol,\n },\n }\n : null;\n\n return new BillingSubscription(\n data.id,\n data.status,\n data.payer_id,\n data.created_at,\n data.updated_at,\n data.active_at ?? null,\n data.past_due_at ?? null,\n (data.subscription_items ?? []).map(item => BillingSubscriptionItem.fromJSON(item)),\n nextPayment,\n data.eligible_for_free_trial ?? false,\n );\n }\n}\n","import type { ExternalAccountJSON } from './JSON';\nimport { Verification } from './Verification';\n\n/**\n * The Backend `ExternalAccount` object is a model around an identification obtained by an external provider (e.g. a social provider such as Google).\n *\n * External account must be verified, so that you can make sure they can be assigned to their rightful owners. The `ExternalAccount` object holds all necessary state around the verification process.\n */\nexport class ExternalAccount {\n constructor(\n /**\n * The unique identifier for this external account.\n */\n readonly id: string,\n /**\n * The provider name (e.g., `google`).\n */\n readonly provider: string,\n /**\n * The identification with which this external account is associated.\n */\n readonly identificationId: string,\n /**\n * The unique ID of the user in the provider.\n */\n readonly externalId: string,\n /**\n * The scopes that the user has granted access to.\n */\n readonly approvedScopes: string,\n /**\n * The user's email address.\n */\n readonly emailAddress: string,\n /**\n * The user's first name.\n */\n readonly firstName: string,\n /**\n * The user's last name.\n */\n readonly lastName: string,\n /**\n * The user's image URL.\n */\n readonly imageUrl: string,\n /**\n * The user's username.\n */\n readonly username: string | null,\n /**\n * The phone number related to this specific external account.\n */\n readonly phoneNumber: string | null,\n /**\n * Metadata that can be read from the Frontend API and Backend API and can be set only from the Backend API.\n */\n readonly publicMetadata: Record<string, unknown> | null = {},\n /**\n * A descriptive label to differentiate multiple external accounts of the same user for the same provider.\n */\n readonly label: string | null,\n /**\n * An object holding information on the verification of this external account.\n */\n readonly verification: Verification | null,\n ) {}\n\n static fromJSON(data: ExternalAccountJSON): ExternalAccount {\n return new ExternalAccount(\n data.id,\n data.provider,\n data.identification_id,\n data.provider_user_id,\n data.approved_scopes,\n data.email_address,\n data.first_name,\n data.last_name,\n data.image_url || '',\n data.username,\n data.phone_number,\n data.public_metadata,\n data.label,\n data.verification && Verification.fromJSON(data.verification),\n );\n }\n}\n","import type { IdPOAuthAccessTokenJSON } from './JSON';\n\nexport class IdPOAuthAccessToken {\n constructor(\n readonly id: string,\n readonly clientId: string,\n readonly type: string,\n readonly subject: string,\n readonly scopes: string[],\n readonly revoked: boolean,\n readonly revocationReason: string | null,\n readonly expired: boolean,\n readonly expiration: number | null,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: IdPOAuthAccessTokenJSON) {\n return new IdPOAuthAccessToken(\n data.id,\n data.client_id,\n data.type,\n data.subject,\n data.scopes,\n data.revoked,\n data.revocation_reason,\n data.expired,\n data.expiration,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { InstanceJSON } from './JSON';\n\nexport class Instance {\n constructor(\n readonly id: string,\n readonly environmentType: string,\n readonly allowedOrigins: Array<string> | null,\n ) {}\n\n static fromJSON(data: InstanceJSON): Instance {\n return new Instance(data.id, data.environment_type, data.allowed_origins);\n }\n}\n","import type { InstanceRestrictionsJSON } from './JSON';\n\nexport class InstanceRestrictions {\n constructor(\n readonly allowlist: boolean,\n readonly blocklist: boolean,\n readonly blockEmailSubaddresses: boolean,\n readonly blockDisposableEmailDomains: boolean,\n readonly ignoreDotsForGmailAddresses: boolean,\n ) {}\n\n static fromJSON(data: InstanceRestrictionsJSON): InstanceRestrictions {\n return new InstanceRestrictions(\n data.allowlist,\n data.blocklist,\n data.block_email_subaddresses,\n data.block_disposable_email_domains,\n data.ignore_dots_for_gmail_addresses,\n );\n }\n}\n","import type { InstanceSettingsJSON } from './JSON';\n\nexport class InstanceSettings {\n constructor(\n readonly id?: string | undefined,\n readonly restrictedToAllowlist?: boolean | undefined,\n readonly fromEmailAddress?: string | undefined,\n readonly progressiveSignUp?: boolean | undefined,\n readonly enhancedEmailDeliverability?: boolean | undefined,\n ) {}\n\n static fromJSON(data: InstanceSettingsJSON): InstanceSettings {\n return new InstanceSettings(\n data.id,\n data.restricted_to_allowlist,\n data.from_email_address,\n data.progressive_sign_up,\n data.enhanced_email_deliverability,\n );\n }\n}\n","import type { InvitationStatus } from './Enums';\nimport type { InvitationJSON } from './JSON';\n\n/**\n * The Backend `Invitation` object represents an invitation to join your application.\n */\nexport class Invitation {\n private _raw: InvitationJSON | null = null;\n\n public get raw(): InvitationJSON | null {\n return this._raw;\n }\n\n constructor(\n /**\n * The unique identifier for the `Invitation`.\n */\n readonly id: string,\n /**\n * The email address that the invitation was sent to.\n */\n readonly emailAddress: string,\n /**\n * [Metadata](https://clerk.com/docs/reference/javascript/types/metadata#user-public-metadata){{ target: '_blank' }} that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API. Once the user accepts the invitation and signs up, these metadata will end up in the user's public metadata.\n */\n readonly publicMetadata: Record<string, unknown> | null,\n /**\n * The date when the `Invitation` was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the `Invitation` was last updated.\n */\n readonly updatedAt: number,\n /**\n * The status of the `Invitation`.\n */\n readonly status: InvitationStatus,\n /**\n * The URL that the user can use to accept the invitation.\n */\n readonly url?: string,\n /**\n * Whether the `Invitation` has been revoked.\n */\n readonly revoked?: boolean,\n ) {}\n\n static fromJSON(data: InvitationJSON): Invitation {\n const res = new Invitation(\n data.id,\n data.email_address,\n data.public_metadata,\n data.created_at,\n data.updated_at,\n data.status,\n data.url,\n data.revoked,\n );\n res._raw = data;\n return res;\n }\n}\n","import type { LastAuthenticationStrategy, SignUpStatus, VerificationStatus } from '@clerk/shared/types';\n\nimport type {\n ActorTokenStatus,\n AllowlistIdentifierType,\n BlocklistIdentifierType,\n DomainsEnrollmentModes,\n InvitationStatus,\n OrganizationDomainVerificationStatus,\n OrganizationDomainVerificationStrategy,\n OrganizationEnrollmentMode,\n OrganizationInvitationStatus,\n OrganizationMembershipRole,\n SignInStatus,\n SignUpVerificationNextAction,\n WaitlistEntryStatus,\n} from './Enums';\n\nexport const ObjectType = {\n AccountlessApplication: 'accountless_application',\n ActorToken: 'actor_token',\n AllowlistIdentifier: 'allowlist_identifier',\n ApiKey: 'api_key',\n BlocklistIdentifier: 'blocklist_identifier',\n Client: 'client',\n Cookies: 'cookies',\n Domain: 'domain',\n Email: 'email',\n EmailAddress: 'email_address',\n ExternalAccount: 'external_account',\n FacebookAccount: 'facebook_account',\n GoogleAccount: 'google_account',\n Instance: 'instance',\n InstanceRestrictions: 'instance_restrictions',\n InstanceSettings: 'instance_settings',\n Invitation: 'invitation',\n Machine: 'machine',\n MachineScope: 'machine_scope',\n MachineSecretKey: 'machine_secret_key',\n M2MToken: 'machine_to_machine_token',\n JwtTemplate: 'jwt_template',\n OauthAccessToken: 'oauth_access_token',\n IdpOAuthAccessToken: 'clerk_idp_oauth_access_token',\n OAuthApplication: 'oauth_application',\n Organization: 'organization',\n OrganizationDomain: 'organization_domain',\n OrganizationInvitation: 'organization_invitation',\n OrganizationMembership: 'organization_membership',\n OrganizationSettings: 'organization_settings',\n PhoneNumber: 'phone_number',\n ProxyCheck: 'proxy_check',\n RedirectUrl: 'redirect_url',\n SamlConnection: 'saml_connection',\n Session: 'session',\n SignInAttempt: 'sign_in_attempt',\n SignInToken: 'sign_in_token',\n SignUpAttempt: 'sign_up_attempt',\n SmsMessage: 'sms_message',\n User: 'user',\n WaitlistEntry: 'waitlist_entry',\n Web3Wallet: 'web3_wallet',\n Token: 'token',\n TotalCount: 'total_count',\n TestingToken: 'testing_token',\n Role: 'role',\n Permission: 'permission',\n BillingPayer: 'commerce_payer',\n BillingPaymentAttempt: 'commerce_payment_attempt',\n BillingSubscription: 'commerce_subscription',\n BillingSubscriptionItem: 'commerce_subscription_item',\n BillingPlan: 'commerce_plan',\n Feature: 'feature',\n} as const;\n\nexport type ObjectType = (typeof ObjectType)[keyof typeof ObjectType];\n\nexport interface ClerkResourceJSON {\n /**\n * The type of the resource.\n */\n object: ObjectType;\n /**\n * The unique identifier for the resource.\n */\n id: string;\n}\n\nexport interface CookiesJSON {\n object: typeof ObjectType.Cookies;\n cookies: string[];\n}\n\nexport interface TokenJSON {\n object: typeof ObjectType.Token;\n jwt: string;\n}\n\nexport interface AccountlessApplicationJSON extends ClerkResourceJSON {\n object: typeof ObjectType.AccountlessApplication;\n publishable_key: string;\n secret_key: string;\n claim_url: string;\n api_keys_url: string;\n}\n\nexport interface ActorTokenJSON extends ClerkResourceJSON {\n object: typeof ObjectType.ActorToken;\n id: string;\n status: ActorTokenStatus;\n user_id: string;\n actor: Record<string, unknown> | null;\n token?: string | null;\n url?: string | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface AllowlistIdentifierJSON extends ClerkResourceJSON {\n object: typeof ObjectType.AllowlistIdentifier;\n identifier: string;\n identifier_type: AllowlistIdentifierType;\n instance_id?: string;\n invitation_id?: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface BlocklistIdentifierJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BlocklistIdentifier;\n identifier: string;\n identifier_type: BlocklistIdentifierType;\n instance_id?: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface ClientJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Client;\n session_ids: string[];\n sessions: SessionJSON[];\n sign_in_id: string | null;\n sign_up_id: string | null;\n last_active_session_id: string | null;\n last_authentication_strategy: LastAuthenticationStrategy | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface CnameTargetJSON {\n host: string;\n value: string;\n /**\n * Denotes whether this CNAME target is required to be set in order for the domain to be considered deployed.\n */\n required: boolean;\n}\n\nexport interface DomainJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Domain;\n id: string;\n name: string;\n is_satellite: boolean;\n frontend_api_url: string;\n /**\n * null for satellite domains\n */\n accounts_portal_url?: string | null;\n proxy_url?: string;\n development_origin: string;\n cname_targets: CnameTargetJSON[];\n}\n\nexport interface EmailJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Email;\n slug?: string | null;\n from_email_name: string;\n to_email_address?: string;\n email_address_id: string | null;\n user_id?: string | null;\n subject?: string;\n body?: string;\n body_plain?: string | null;\n status?: string;\n data?: Record<string, any> | null;\n delivered_by_clerk: boolean;\n}\n\nexport interface EmailAddressJSON extends ClerkResourceJSON {\n object: typeof ObjectType.EmailAddress;\n email_address: string;\n verification: VerificationJSON | null;\n linked_to: IdentificationLinkJSON[];\n}\n\nexport interface ExternalAccountJSON extends ClerkResourceJSON {\n object: typeof ObjectType.ExternalAccount;\n provider: string;\n identification_id: string;\n provider_user_id: string;\n approved_scopes: string;\n email_address: string;\n first_name: string;\n last_name: string;\n image_url?: string;\n username: string | null;\n phone_number: string | null;\n public_metadata?: Record<string, unknown> | null;\n label: string | null;\n verification: VerificationJSON | null;\n}\n\nexport interface JwksJSON {\n keys?: JwksKeyJSON[];\n}\n\nexport interface JwksKeyJSON {\n use: string;\n kty: string;\n kid: string;\n alg: string;\n n: string;\n e: string;\n}\n\nexport interface JwtTemplateJSON extends ClerkResourceJSON {\n object: typeof ObjectType.JwtTemplate;\n id: string;\n name: string;\n claims: object;\n lifetime: number;\n allowed_clock_skew: number;\n custom_signing_key: boolean;\n signing_algorithm: string;\n created_at: number;\n updated_at: number;\n}\nexport interface IdentificationLinkJSON extends ClerkResourceJSON {\n type: string;\n}\n\nexport interface OrganizationSettingsJSON extends ClerkResourceJSON {\n object: typeof ObjectType.OrganizationSettings;\n enabled: boolean;\n max_allowed_memberships: number;\n max_allowed_roles: number;\n max_allowed_permissions: number;\n creator_role: string;\n admin_delete_enabled: boolean;\n domains_enabled: boolean;\n slug_disabled: boolean;\n domains_enrollment_modes: Array<DomainsEnrollmentModes>;\n domains_default_role: string;\n}\n\nexport interface InstanceJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Instance;\n id: string;\n environment_type: string;\n allowed_origins: Array<string> | null;\n}\n\nexport interface InstanceRestrictionsJSON extends ClerkResourceJSON {\n object: typeof ObjectType.InstanceRestrictions;\n allowlist: boolean;\n blocklist: boolean;\n block_email_subaddresses: boolean;\n block_disposable_email_domains: boolean;\n ignore_dots_for_gmail_addresses: boolean;\n}\n\nexport interface InstanceSettingsJSON extends ClerkResourceJSON {\n object: typeof ObjectType.InstanceSettings;\n id: string;\n restricted_to_allowlist: boolean;\n from_email_address: string;\n progressive_sign_up: boolean;\n enhanced_email_deliverability: boolean;\n}\n\nexport interface InvitationJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Invitation;\n email_address: string;\n public_metadata: Record<string, unknown> | null;\n revoked?: boolean;\n status: InvitationStatus;\n url?: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface OauthAccessTokenJSON {\n external_account_id: string;\n object: typeof ObjectType.OauthAccessToken;\n token: string;\n provider: string;\n public_metadata: Record<string, unknown>;\n label: string | null;\n // Only set in OAuth 2.0 tokens\n scopes?: string[];\n // Only set in OAuth 1.0 tokens\n token_secret?: string;\n expires_at?: number;\n}\n\nexport interface OAuthApplicationJSON extends ClerkResourceJSON {\n object: typeof ObjectType.OAuthApplication;\n id: string;\n instance_id: string;\n name: string;\n client_id: string;\n client_uri: string | null;\n client_image_url: string | null;\n dynamically_registered: boolean;\n consent_screen_enabled: boolean;\n pkce_required: boolean;\n public: boolean;\n scopes: string;\n redirect_uris: Array<string>;\n authorize_url: string;\n token_fetch_url: string;\n user_info_url: string;\n discovery_url: string;\n token_introspection_url: string;\n created_at: number;\n updated_at: number;\n client_secret?: string;\n}\n\nexport interface OrganizationJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Organization;\n name: string;\n slug: string;\n image_url?: string;\n has_image: boolean;\n members_count?: number;\n pending_invitations_count?: number;\n max_allowed_memberships: number;\n admin_delete_enabled: boolean;\n public_metadata: OrganizationPublicMetadata | null;\n private_metadata?: OrganizationPrivateMetadata;\n created_by?: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface OrganizationDomainJSON extends ClerkResourceJSON {\n object: typeof ObjectType.OrganizationDomain;\n id: string;\n name: string;\n organization_id: string;\n enrollment_mode: OrganizationEnrollmentMode;\n verification: OrganizationDomainVerificationJSON | null;\n affiliation_email_address: string | null;\n created_at: number;\n updated_at: number;\n total_pending_invitations: number;\n total_pending_suggestions: number;\n}\n\nexport interface OrganizationDomainVerificationJSON {\n status: OrganizationDomainVerificationStatus;\n strategy: OrganizationDomainVerificationStrategy;\n attempts: number;\n expires_at: number;\n}\n\nexport interface OrganizationInvitationJSON extends ClerkResourceJSON {\n email_address: string;\n role: OrganizationMembershipRole;\n role_name: string;\n organization_id: string;\n public_organization_data?: PublicOrganizationDataJSON | null;\n status?: OrganizationInvitationStatus;\n public_metadata: OrganizationInvitationPublicMetadata;\n private_metadata: OrganizationInvitationPrivateMetadata;\n url: string | null;\n created_at: number;\n updated_at: number;\n expires_at: number;\n}\n\nexport interface OrganizationInvitationAcceptedJSON extends OrganizationInvitationJSON {\n status: 'accepted';\n user_id: string;\n}\n\n/**\n * @interface\n */\nexport interface PublicOrganizationDataJSON extends ClerkResourceJSON {\n /**\n * The name of the organization.\n */\n name: string;\n /**\n * The slug of the organization.\n */\n slug: string;\n /**\n * Holds the default organization profile image. Compatible with Clerk's [Image Optimization](https://clerk.com/docs/guides/development/image-optimization).\n */\n image_url?: string;\n /**\n * Whether the organization has a profile image.\n */\n has_image: boolean;\n}\n\nexport interface OrganizationMembershipJSON extends ClerkResourceJSON {\n object: typeof ObjectType.OrganizationMembership;\n public_metadata: OrganizationMembershipPublicMetadata;\n private_metadata?: OrganizationMembershipPrivateMetadata;\n role: OrganizationMembershipRole;\n permissions: string[];\n created_at: number;\n updated_at: number;\n organization: OrganizationJSON;\n public_user_data: OrganizationMembershipPublicUserDataJSON;\n}\n\nexport interface OrganizationMembershipPublicUserDataJSON {\n identifier: string;\n first_name: string | null;\n last_name: string | null;\n image_url: string;\n has_image: boolean;\n user_id: string;\n}\n\nexport interface PhoneNumberJSON extends ClerkResourceJSON {\n object: typeof ObjectType.PhoneNumber;\n phone_number: string;\n reserved_for_second_factor: boolean;\n default_second_factor: boolean;\n reserved: boolean;\n verification: VerificationJSON | null;\n linked_to: IdentificationLinkJSON[];\n backup_codes: string[];\n}\n\nexport type ProxyCheckJSON = {\n object: typeof ObjectType.ProxyCheck;\n id: string;\n domain_id: string;\n last_run_at: number | null;\n proxy_url: string;\n successful: boolean;\n created_at: number;\n updated_at: number;\n};\n\nexport interface RedirectUrlJSON extends ClerkResourceJSON {\n object: typeof ObjectType.RedirectUrl;\n url: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface SessionActivityJSON extends ClerkResourceJSON {\n id: string;\n device_type?: string;\n is_mobile: boolean;\n browser_name?: string;\n browser_version?: string;\n ip_address?: string;\n city?: string;\n country?: string;\n}\n\nexport interface SessionJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Session;\n client_id: string;\n user_id: string;\n status: string;\n last_active_organization_id?: string;\n actor: Record<string, unknown> | null;\n latest_activity?: SessionActivityJSON;\n last_active_at: number;\n expire_at: number;\n abandon_at: number;\n created_at: number;\n updated_at: number;\n}\n\n/**\n * Session webhook event payload extending `SessionJSON` interface with associated `User` information.\n * Used for `session.created`, `session.ended`, `session.removed`, and `session.revoked` webhook events.\n */\nexport interface SessionWebhookEventJSON extends SessionJSON {\n /**\n * The user associated with the session, or null if not available.\n */\n user: UserJSON | null;\n}\n\nexport interface SignInJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SignInToken;\n status: SignInStatus;\n identifier: string;\n created_session_id: string | null;\n}\n\nexport interface SignInTokenJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SignInToken;\n user_id: string;\n token: string;\n status: 'pending' | 'accepted' | 'revoked';\n url: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface SignUpJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SignUpAttempt;\n id: string;\n status: SignUpStatus;\n required_fields: string[];\n optional_fields: string[];\n missing_fields: string[];\n unverified_fields: string[];\n verifications: SignUpVerificationsJSON;\n username: string | null;\n email_address: string | null;\n phone_number: string | null;\n web3_wallet: string | null;\n password_enabled: boolean;\n first_name: string | null;\n last_name: string | null;\n public_metadata?: Record<string, unknown> | null;\n unsafe_metadata?: Record<string, unknown> | null;\n custom_action: boolean;\n external_id: string | null;\n created_session_id: string | null;\n created_user_id: string | null;\n abandon_at: number | null;\n legal_accepted_at: number | null;\n\n /**\n * @deprecated Please use `verifications.external_account` instead\n */\n external_account: object | null;\n}\n\nexport interface SignUpVerificationsJSON {\n email_address: SignUpVerificationJSON;\n phone_number: SignUpVerificationJSON;\n web3_wallet: SignUpVerificationJSON;\n external_account: VerificationJSON;\n}\n\nexport interface SignUpVerificationJSON {\n next_action: SignUpVerificationNextAction;\n supported_strategies: string[];\n}\n\nexport interface SMSMessageJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SmsMessage;\n from_phone_number: string;\n to_phone_number: string;\n phone_number_id: string | null;\n user_id?: string;\n message: string;\n status: string;\n slug?: string | null;\n data?: Record<string, any> | null;\n delivered_by_clerk: boolean;\n}\n\nexport interface UserJSON extends ClerkResourceJSON {\n object: typeof ObjectType.User;\n username: string | null;\n first_name: string | null;\n last_name: string | null;\n image_url: string;\n has_image: boolean;\n primary_email_address_id: string | null;\n primary_phone_number_id: string | null;\n primary_web3_wallet_id: string | null;\n password_enabled: boolean;\n two_factor_enabled: boolean;\n totp_enabled: boolean;\n backup_code_enabled: boolean;\n email_addresses: EmailAddressJSON[];\n phone_numbers: PhoneNumberJSON[];\n web3_wallets: Web3WalletJSON[];\n organization_memberships: OrganizationMembershipJSON[] | null;\n external_accounts: ExternalAccountJSON[];\n password_last_updated_at: number | null;\n public_metadata: UserPublicMetadata;\n private_metadata: UserPrivateMetadata;\n unsafe_metadata: UserUnsafeMetadata;\n external_id: string | null;\n last_sign_in_at: number | null;\n banned: boolean;\n locked: boolean;\n lockout_expires_in_seconds: number | null;\n verification_attempts_remaining: number | null;\n created_at: number;\n updated_at: number;\n last_active_at: number | null;\n create_organization_enabled: boolean;\n create_organizations_limit: number | null;\n delete_self_enabled: boolean;\n legal_accepted_at: number | null;\n /**\n * The locale of the user in BCP-47 format.\n */\n locale: string | null;\n}\n\nexport interface VerificationJSON extends ClerkResourceJSON {\n status: VerificationStatus;\n strategy: string;\n attempts: number | null;\n expire_at: number | null;\n verified_at_client?: string;\n external_verification_redirect_url?: string | null;\n nonce?: string | null;\n message?: string | null;\n}\n\nexport interface WaitlistEntryJSON extends ClerkResourceJSON {\n object: typeof ObjectType.WaitlistEntry;\n id: string;\n status: WaitlistEntryStatus;\n email_address: string;\n invitation: InvitationJSON | null;\n is_locked: boolean;\n created_at: number;\n updated_at: number;\n}\n\nexport interface Web3WalletJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Web3Wallet;\n web3_wallet: string;\n verification: VerificationJSON | null;\n}\n\nexport interface DeletedObjectJSON {\n object: string;\n id?: string;\n slug?: string;\n deleted: boolean;\n}\n\n/**\n * User deletion webhook event payload that extends `DeletedObjectJSON`.\n * Includes the `external_id` field to identify the deleted user in external systems.\n * Used for `user.deleted` webhook events.\n */\nexport interface UserDeletedJSON extends DeletedObjectJSON {\n /**\n * The external identifier associated with the deleted user, if one was set.\n */\n external_id?: string;\n}\n\nexport interface PaginatedResponseJSON {\n data: object[];\n total_count?: number;\n}\n\nexport interface SamlConnectionJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SamlConnection;\n name: string;\n domain: string;\n organization_id: string | null;\n idp_entity_id: string;\n idp_sso_url: string;\n idp_certificate: string;\n idp_metadata_url: string;\n idp_metadata: string;\n acs_url: string;\n sp_entity_id: string;\n sp_metadata_url: string;\n active: boolean;\n provider: string;\n user_count: number;\n sync_user_attributes: boolean;\n allow_subdomains: boolean;\n allow_idp_initiated: boolean;\n created_at: number;\n updated_at: number;\n attribute_mapping: AttributeMappingJSON;\n}\n\nexport interface AttributeMappingJSON {\n user_id: string;\n email_address: string;\n first_name: string;\n last_name: string;\n}\n\nexport interface TestingTokenJSON {\n object: typeof ObjectType.TestingToken;\n token: string;\n expires_at: number;\n}\n\nexport interface RoleJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Role;\n key: string;\n name: string;\n description: string;\n permissions: PermissionJSON[];\n is_creator_eligible: boolean;\n created_at: number;\n updated_at: number;\n}\n\nexport interface PermissionJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Permission;\n key: string;\n name: string;\n description: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface MachineJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Machine;\n id: string;\n name: string;\n instance_id: string;\n created_at: number;\n updated_at: number;\n default_token_ttl: number;\n scoped_machines: MachineJSON[];\n secret_key?: string;\n}\n\nexport interface MachineScopeJSON {\n object: typeof ObjectType.MachineScope;\n from_machine_id: string;\n to_machine_id: string;\n created_at?: number;\n deleted?: boolean;\n}\n\nexport interface MachineSecretKeyJSON {\n object: typeof ObjectType.MachineSecretKey;\n secret: string;\n}\n\nexport interface M2MTokenJSON extends ClerkResourceJSON {\n object: typeof ObjectType.M2MToken;\n token?: string;\n subject: string;\n scopes: string[];\n claims: Record<string, any> | null;\n revoked: boolean;\n revocation_reason: string | null;\n expired: boolean;\n expiration: number | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface APIKeyJSON extends ClerkResourceJSON {\n object: typeof ObjectType.ApiKey;\n type: string;\n name: string;\n secret?: string;\n subject: string;\n scopes: string[];\n claims: Record<string, any> | null;\n revoked: boolean;\n revocation_reason: string | null;\n expired: boolean;\n expiration: number | null;\n created_by: string | null;\n description: string | null;\n last_used_at: number | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface IdPOAuthAccessTokenJSON extends ClerkResourceJSON {\n object: typeof ObjectType.IdpOAuthAccessToken;\n client_id: string;\n type: string;\n subject: string;\n scopes: string[];\n revoked: boolean;\n revocation_reason: string | null;\n expired: boolean;\n expiration: number | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface BillingPayerJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingPayer;\n instance_id: string;\n user_id?: string;\n first_name?: string;\n last_name?: string;\n email: string;\n organization_id?: string;\n organization_name?: string;\n image_url: string;\n created_at: number;\n updated_at: number;\n}\n\ninterface BillingPayeeJSON {\n id: string;\n gateway_type: string;\n gateway_external_id: string;\n gateway_status: 'active' | 'pending' | 'restricted' | 'disconnected';\n}\n\ninterface BillingMoneyAmountJSON {\n amount: number;\n amount_formatted: string;\n currency: string;\n currency_symbol: string;\n}\n\ninterface BillingTotalsJSON {\n subtotal: BillingMoneyAmountJSON;\n tax_total: BillingMoneyAmountJSON;\n grand_total: BillingMoneyAmountJSON;\n}\n\nexport interface FeatureJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Feature;\n name: string;\n description?: string | null;\n slug: string;\n avatar_url?: string | null;\n}\n\n/**\n * @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.\n */\nexport interface BillingPlanJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingPlan;\n id: string;\n name: string;\n slug: string;\n description: string | null;\n is_default: boolean;\n is_recurring: boolean;\n has_base_fee: boolean;\n publicly_visible: boolean;\n fee: BillingMoneyAmountJSON;\n annual_fee: BillingMoneyAmountJSON | null;\n annual_monthly_fee: BillingMoneyAmountJSON | null;\n for_payer_type: 'org' | 'user';\n features?: FeatureJSON[];\n}\n\ntype BillingSubscriptionItemStatus =\n | 'abandoned'\n | 'active'\n | 'canceled'\n | 'ended'\n | 'expired'\n | 'incomplete'\n | 'past_due'\n | 'upcoming';\n\n/**\n * @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.\n */\nexport interface BillingSubscriptionItemJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingSubscriptionItem;\n status: BillingSubscriptionItemStatus;\n plan_period: 'month' | 'annual';\n payer_id?: string;\n period_start: number;\n period_end: number | null;\n is_free_trial?: boolean;\n ended_at: number | null;\n created_at: number;\n updated_at: number;\n canceled_at: number | null;\n past_due_at: number | null;\n lifetime_paid: BillingMoneyAmountJSON | null;\n next_payment?: {\n amount: number;\n date: number;\n } | null;\n amount: BillingMoneyAmountJSON;\n plan?: BillingPlanJSON | null;\n plan_id?: string | null;\n}\n\n/**\n * Webhooks specific interface for BillingSubscriptionItem.\n */\nexport interface BillingSubscriptionItemWebhookEventJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingSubscriptionItem;\n status: BillingSubscriptionItemStatus;\n credit: {\n amount: BillingMoneyAmountJSON;\n cycle_days_remaining: number;\n cycle_days_total: number;\n cycle_remaining_percent: number;\n };\n proration_date: string;\n plan_period: 'month' | 'annual';\n period_start: number;\n period_end?: number;\n canceled_at?: number;\n past_due_at?: number;\n lifetime_paid: number;\n next_payment_amount: number;\n next_payment_date: number;\n amount: BillingMoneyAmountJSON;\n plan?: {\n id: string;\n instance_id: string;\n product_id: string;\n name: string;\n slug: string;\n description?: string;\n is_default: boolean;\n is_recurring: boolean;\n amount: number;\n period: 'month' | 'annual';\n interval: number;\n has_base_fee: boolean;\n currency: string;\n annual_monthly_amount: number;\n publicly_visible: boolean;\n } | null;\n plan_id?: string | null;\n payer?: BillingPayerJSON;\n}\n\n/**\n * Webhooks specific interface for BillingPaymentAttempt.\n */\nexport interface BillingPaymentAttemptWebhookEventJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingPaymentAttempt;\n instance_id: string;\n payment_id: string;\n statement_id: string;\n gateway_external_id: string;\n status: 'pending' | 'paid' | 'failed';\n created_at: number;\n updated_at: number;\n paid_at?: number;\n failed_at?: number;\n failed_reason?: {\n code: string;\n decline_code: string;\n };\n billing_date: number;\n charge_type: 'checkout' | 'recurring';\n payee: BillingPayeeJSON;\n payer: BillingPayerJSON;\n totals: BillingTotalsJSON;\n payment_source: {\n id: string;\n gateway: string;\n gateway_external_id: string;\n gateway_external_account_id?: string;\n payment_method: string;\n status: 'active' | 'disconnected';\n card_type?: string;\n last4?: string;\n };\n subscription_items: BillingSubscriptionItemWebhookEventJSON[];\n}\n\n/**\n * Webhooks specific interface for BillingSubscription.\n */\nexport interface BillingSubscriptionWebhookEventJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingSubscription;\n status: 'abandoned' | 'active' | 'canceled' | 'ended' | 'expired' | 'incomplete' | 'past_due' | 'upcoming';\n active_at?: number;\n canceled_at?: number;\n created_at: number;\n ended_at?: number;\n past_due_at?: number;\n updated_at: number;\n latest_payment_id: string;\n payer_id: string;\n payer: BillingPayerJSON;\n payment_source_id: string;\n items: BillingSubscriptionItemWebhookEventJSON[];\n}\n\nexport interface BillingSubscriptionJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingSubscription;\n status: 'active' | 'past_due' | 'canceled' | 'ended' | 'abandoned' | 'incomplete';\n payer_id: string;\n created_at: number;\n updated_at: number;\n active_at: number | null;\n past_due_at: number | null;\n subscription_items: BillingSubscriptionItemJSON[];\n next_payment?: {\n date: number;\n amount: BillingMoneyAmountJSON;\n };\n eligible_for_free_trial?: boolean;\n}\n\nexport interface WebhooksSvixJSON {\n svix_url: string;\n}\n","import type { JwtTemplateJSON } from './JSON';\n\nexport class JwtTemplate {\n constructor(\n readonly id: string,\n readonly name: string,\n readonly claims: object,\n readonly lifetime: number,\n readonly allowedClockSkew: number,\n readonly customSigningKey: boolean,\n readonly signingAlgorithm: string,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: JwtTemplateJSON): JwtTemplate {\n return new JwtTemplate(\n data.id,\n data.name,\n data.claims,\n data.lifetime,\n data.allowed_clock_skew,\n data.custom_signing_key,\n data.signing_algorithm,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { M2MTokenJSON } from './JSON';\n\n/**\n * The Backend `M2MToken` object holds information about a machine-to-machine token.\n */\nexport class M2MToken {\n constructor(\n readonly id: string,\n readonly subject: string,\n readonly scopes: string[],\n readonly claims: Record<string, any> | null,\n readonly revoked: boolean,\n readonly revocationReason: string | null,\n readonly expired: boolean,\n readonly expiration: number | null,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly token?: string,\n ) {}\n\n static fromJSON(data: M2MTokenJSON): M2MToken {\n return new M2MToken(\n data.id,\n data.subject,\n data.scopes,\n data.claims,\n data.revoked,\n data.revocation_reason,\n data.expired,\n data.expiration,\n data.created_at,\n data.updated_at,\n data.token,\n );\n }\n}\n","import type { MachineJSON } from './JSON';\n\n/**\n * The Backend `Machine` object holds information about a machine.\n */\nexport class Machine {\n constructor(\n readonly id: string,\n readonly name: string,\n readonly instanceId: string,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly scopedMachines: Machine[],\n readonly defaultTokenTtl: number,\n readonly secretKey?: string,\n ) {}\n\n static fromJSON(data: MachineJSON): Machine {\n return new Machine(\n data.id,\n data.name,\n data.instance_id,\n data.created_at,\n data.updated_at,\n data.scoped_machines.map(\n m =>\n new Machine(\n m.id,\n m.name,\n m.instance_id,\n m.created_at,\n m.updated_at,\n [], // Nested machines don't have scoped_machines\n m.default_token_ttl,\n ),\n ),\n data.default_token_ttl,\n data.secret_key,\n );\n }\n}\n","import type { MachineScopeJSON } from './JSON';\n\n/**\n * The Backend `MachineScope` object holds information about a machine scope.\n */\nexport class MachineScope {\n constructor(\n readonly fromMachineId: string,\n readonly toMachineId: string,\n readonly createdAt?: number,\n readonly deleted?: boolean,\n ) {}\n\n static fromJSON(data: MachineScopeJSON): MachineScope {\n return new MachineScope(data.from_machine_id, data.to_machine_id, data.created_at, data.deleted);\n }\n}\n","import type { MachineSecretKeyJSON } from './JSON';\n\n/**\n * The Backend `MachineSecretKey` object holds information about a machine secret key.\n */\nexport class MachineSecretKey {\n constructor(readonly secret: string) {}\n\n static fromJSON(data: MachineSecretKeyJSON): MachineSecretKey {\n return new MachineSecretKey(data.secret);\n }\n}\n","import type { OauthAccessTokenJSON } from './JSON';\n\nexport class OauthAccessToken {\n constructor(\n readonly externalAccountId: string,\n readonly provider: string,\n readonly token: string,\n readonly publicMetadata: Record<string, unknown> = {},\n readonly label: string,\n readonly scopes?: string[],\n readonly tokenSecret?: string,\n readonly expiresAt?: number,\n ) {}\n\n static fromJSON(data: OauthAccessTokenJSON) {\n return new OauthAccessToken(\n data.external_account_id,\n data.provider,\n data.token,\n data.public_metadata,\n data.label || '',\n data.scopes,\n data.token_secret,\n data.expires_at,\n );\n }\n}\n","import type { OAuthApplicationJSON } from './JSON';\n\n/**\n * The Backend `OAuthApplication` object holds information about an OAuth application.\n */\nexport class OAuthApplication {\n constructor(\n /**\n * The unique identifier for the OAuth application.\n */\n readonly id: string,\n /**\n * The ID of the instance that this OAuth application belongs to.\n */\n readonly instanceId: string,\n /**\n * The name of the new OAuth application.\n */\n readonly name: string,\n /**\n * The ID of the client associated with the OAuth application.\n */\n readonly clientId: string,\n /**\n * The public-facing URL of the OAuth application, often shown on consent screens.\n */\n readonly clientUri: string | null,\n /**\n * The URL of the image or logo representing the OAuth application.\n */\n readonly clientImageUrl: string | null,\n /**\n * Specifies whether the OAuth application is dynamically registered.\n */\n readonly dynamicallyRegistered: boolean,\n /**\n * Specifies whether the consent screen should be displayed in the authentication flow. Cannot be disabled for dynamically registered OAuth applications.\n */\n readonly consentScreenEnabled: boolean,\n /**\n * Specifies whether the Proof Key of Code Exchange (PKCE) flow should be required in the authentication flow.\n */\n readonly pkceRequired: boolean,\n /**\n * Indicates whether the client is public. If true, the Proof Key of Code Exchange (PKCE) flow can be used.\n */\n readonly isPublic: boolean, // NOTE: `public` is reserved\n /**\n * Scopes for the new OAuth application.\n */\n readonly scopes: string,\n /**\n * An array of redirect URIs of the new OAuth application.\n */\n readonly redirectUris: Array<string>,\n /**\n * The URL used to authorize the user and obtain an authorization code.\n */\n readonly authorizeUrl: string,\n /**\n * The URL used by the client to exchange an authorization code for an access token.\n */\n readonly tokenFetchUrl: string,\n /**\n * The URL where the client can retrieve user information using an access token.\n */\n readonly userInfoUrl: string,\n /**\n * The OpenID Connect discovery endpoint URL for this OAuth application.\n */\n readonly discoveryUrl: string,\n /**\n * The URL used to introspect and validate issued access tokens.\n */\n readonly tokenIntrospectionUrl: string,\n /**\n * The date when the OAuth application was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the OAuth application was last updated.\n */\n readonly updatedAt: number,\n /**\n * The client secret associated with the OAuth application. Empty if public client.\n */\n readonly clientSecret?: string,\n ) {}\n\n static fromJSON(data: OAuthApplicationJSON) {\n return new OAuthApplication(\n data.id,\n data.instance_id,\n data.name,\n data.client_id,\n data.client_uri,\n data.client_image_url,\n data.dynamically_registered,\n data.consent_screen_enabled,\n data.pkce_required,\n data.public,\n data.scopes,\n data.redirect_uris,\n data.authorize_url,\n data.token_fetch_url,\n data.user_info_url,\n data.discovery_url,\n data.token_introspection_url,\n data.created_at,\n data.updated_at,\n data.client_secret,\n );\n }\n}\n","import type { OrganizationJSON } from './JSON';\n\n/**\n * The Backend `Organization` object is similar to the [`Organization`](https://clerk.com/docs/reference/javascript/organization) object as it holds information about an organization, as well as methods for managing it. However, the Backend `Organization` object is different in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Organizations#operation/ListOrganizations){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class Organization {\n private _raw: OrganizationJSON | null = null;\n\n public get raw(): OrganizationJSON | null {\n return this._raw;\n }\n\n constructor(\n /**\n * The unique identifier for the organization.\n */\n readonly id: string,\n /**\n * The name of the organization.\n */\n readonly name: string,\n /**\n * The URL-friendly identifier of the user's active organization. If supplied, it must be unique for the instance.\n */\n readonly slug: string,\n /**\n * Holds the organization's logo. Compatible with Clerk's [Image Optimization](https://clerk.com/docs/guides/development/image-optimization).\n */\n readonly imageUrl: string,\n /**\n * Whether the organization has an image.\n */\n readonly hasImage: boolean,\n /**\n * The date when the organization was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the organization was last updated.\n */\n readonly updatedAt: number,\n /**\n * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API.\n */\n readonly publicMetadata: OrganizationPublicMetadata | null = {},\n /**\n * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}.\n */\n readonly privateMetadata: OrganizationPrivateMetadata = {},\n /**\n * The maximum number of memberships allowed in the organization.\n */\n readonly maxAllowedMemberships: number,\n /**\n * Whether the organization allows admins to delete users.\n */\n readonly adminDeleteEnabled: boolean,\n /**\n * The number of members in the organization.\n */\n readonly membersCount?: number,\n /**\n * The ID of the user who created the organization.\n */\n readonly createdBy?: string,\n ) {}\n\n static fromJSON(data: OrganizationJSON): Organization {\n const res = new Organization(\n data.id,\n data.name,\n data.slug,\n data.image_url || '',\n data.has_image,\n data.created_at,\n data.updated_at,\n data.public_metadata,\n data.private_metadata,\n data.max_allowed_memberships,\n data.admin_delete_enabled,\n data.members_count,\n data.created_by,\n );\n res._raw = data;\n return res;\n }\n}\n","import type { OrganizationInvitationStatus, OrganizationMembershipRole } from './Enums';\nimport type { OrganizationInvitationJSON, PublicOrganizationDataJSON } from './JSON';\n\n/**\n * The Backend `OrganizationInvitation` object is similar to the [`OrganizationInvitation`](https://clerk.com/docs/reference/javascript/types/organization-invitation) object as it's the model around an organization invitation. However, the Backend `OrganizationInvitation` object is different in that it's used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Organization-Invitations#operation/CreateOrganizationInvitation){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class OrganizationInvitation {\n private _raw: OrganizationInvitationJSON | null = null;\n\n public get raw(): OrganizationInvitationJSON | null {\n return this._raw;\n }\n\n constructor(\n /**\n * The unique identifier for the `OrganizationInvitation`.\n */\n readonly id: string,\n /**\n * The email address of the user who is invited to the [`Organization`](https://clerk.com/docs/reference/backend/types/backend-organization).\n */\n readonly emailAddress: string,\n /**\n * The role of the invited user.\n */\n readonly role: OrganizationMembershipRole,\n /**\n * The name of the role of the invited user.\n */\n readonly roleName: string,\n /**\n * The ID of the [`Organization`](https://clerk.com/docs/reference/backend/types/backend-organization) that the user is invited to.\n */\n readonly organizationId: string,\n /**\n * The date when the invitation was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the invitation was last updated.\n */\n readonly updatedAt: number,\n /**\n * The date when the invitation expires.\n */\n readonly expiresAt: number,\n /**\n * The URL that the user can use to accept the invitation.\n */\n readonly url: string | null,\n /**\n * The status of the invitation.\n */\n readonly status?: OrganizationInvitationStatus,\n /**\n * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API.\n */\n readonly publicMetadata: OrganizationInvitationPublicMetadata = {},\n /**\n * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}.\n */\n readonly privateMetadata: OrganizationInvitationPrivateMetadata = {},\n /**\n * Public data about the organization that the user is invited to.\n */\n readonly publicOrganizationData?: PublicOrganizationDataJSON | null,\n ) {}\n\n static fromJSON(data: OrganizationInvitationJSON) {\n const res = new OrganizationInvitation(\n data.id,\n data.email_address,\n data.role,\n data.role_name,\n data.organization_id,\n data.created_at,\n data.updated_at,\n data.expires_at,\n data.url,\n data.status,\n data.public_metadata,\n data.private_metadata,\n data.public_organization_data,\n );\n res._raw = data;\n return res;\n }\n}\n","import { Organization } from '../resources';\nimport type { OrganizationMembershipRole } from './Enums';\nimport type { OrganizationMembershipJSON, OrganizationMembershipPublicUserDataJSON } from './JSON';\n\n/**\n * The Backend `OrganizationMembership` object is similar to the [`OrganizationMembership`](https://clerk.com/docs/reference/javascript/types/organization-membership) object as it's the model around an organization membership entity and describes the relationship between users and organizations. However, the Backend `OrganizationMembership` object is different in that it's used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Organization-Memberships#operation/CreateOrganizationMembership){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class OrganizationMembership {\n private _raw: OrganizationMembershipJSON | null = null;\n\n public get raw(): OrganizationMembershipJSON | null {\n return this._raw;\n }\n\n constructor(\n /**\n * The unique identifier for the membership.\n */\n readonly id: string,\n /**\n * The role of the user.\n */\n readonly role: OrganizationMembershipRole,\n /**\n * The permissions granted to the user in the organization.\n */\n readonly permissions: string[],\n /**\n * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API.\n */\n readonly publicMetadata: OrganizationMembershipPublicMetadata = {},\n /**\n * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}.\n */\n readonly privateMetadata: OrganizationMembershipPrivateMetadata = {},\n /**\n * The date when the membership was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the membership was last updated.\n */\n readonly updatedAt: number,\n /**\n * The organization that the user is a member of.\n */\n readonly organization: Organization,\n /**\n * Public information about the user that this membership belongs to.\n */\n readonly publicUserData?: OrganizationMembershipPublicUserData | null,\n ) {}\n\n static fromJSON(data: OrganizationMembershipJSON) {\n const res = new OrganizationMembership(\n data.id,\n data.role,\n data.permissions,\n data.public_metadata,\n data.private_metadata,\n data.created_at,\n data.updated_at,\n Organization.fromJSON(data.organization),\n OrganizationMembershipPublicUserData.fromJSON(data.public_user_data),\n );\n res._raw = data;\n return res;\n }\n}\n\n/**\n * @class\n */\nexport class OrganizationMembershipPublicUserData {\n constructor(\n /**\n * The identifier of the user.\n */\n readonly identifier: string,\n /**\n * The first name of the user.\n */\n readonly firstName: string | null,\n /**\n * The last name of the user.\n */\n readonly lastName: string | null,\n /**\n * Holds the default avatar or user's uploaded profile image. Compatible with Clerk's [Image Optimization](https://clerk.com/docs/guides/development/image-optimization).\n */\n readonly imageUrl: string,\n /**\n * Whether the user has a profile picture.\n */\n readonly hasImage: boolean,\n /**\n * The ID of the user that this public data belongs to.\n */\n readonly userId: string,\n ) {}\n\n static fromJSON(data: OrganizationMembershipPublicUserDataJSON) {\n return new OrganizationMembershipPublicUserData(\n data.identifier,\n data.first_name,\n data.last_name,\n data.image_url,\n data.has_image,\n data.user_id,\n );\n }\n}\n","import type { DomainsEnrollmentModes } from './Enums';\nimport type { OrganizationSettingsJSON } from './JSON';\n\nexport class OrganizationSettings {\n constructor(\n readonly enabled: boolean,\n readonly maxAllowedMemberships: number,\n readonly maxAllowedRoles: number,\n readonly maxAllowedPermissions: number,\n readonly creatorRole: string,\n readonly adminDeleteEnabled: boolean,\n readonly domainsEnabled: boolean,\n readonly slugDisabled: boolean,\n readonly domainsEnrollmentModes: Array<DomainsEnrollmentModes>,\n readonly domainsDefaultRole: string,\n ) {}\n\n static fromJSON(data: OrganizationSettingsJSON): OrganizationSettings {\n return new OrganizationSettings(\n data.enabled,\n data.max_allowed_memberships,\n data.max_allowed_roles,\n data.max_allowed_permissions,\n data.creator_role,\n data.admin_delete_enabled,\n data.domains_enabled,\n data.slug_disabled,\n data.domains_enrollment_modes,\n data.domains_default_role,\n );\n }\n}\n","import { IdentificationLink } from './IdentificationLink';\nimport type { PhoneNumberJSON } from './JSON';\nimport { Verification } from './Verification';\n\n/**\n * The Backend `PhoneNumber` object describes a phone number. Phone numbers can be used as a proof of identification for users, or simply as a means of contacting users.\n *\n * Phone numbers must be **verified** to ensure that they can be assigned to their rightful owners. The `PhoneNumber` object holds all the necessary state around the verification process.\n *\n * Finally, phone numbers can be used as part of [multi-factor authentication](https://clerk.com/docs/guides/configure/auth-strategies/sign-up-sign-in-options#multi-factor-authentication). During sign in, users can opt in to an extra verification step where they will receive an SMS message with a one-time code. This code must be entered to complete the sign in process.\n */\nexport class PhoneNumber {\n constructor(\n /**\n * The unique identifier for this phone number.\n */\n readonly id: string,\n /**\n * The value of this phone number, in [E.164 format](https://en.wikipedia.org/wiki/E.164).\n */\n readonly phoneNumber: string,\n /**\n * Set to `true` if this phone number is reserved for multi-factor authentication (2FA). Set to `false` otherwise.\n */\n readonly reservedForSecondFactor: boolean,\n /**\n * Set to `true` if this phone number is the default second factor. Set to `false` otherwise. A user must have exactly one default second factor, if multi-factor authentication (2FA) is enabled.\n */\n readonly defaultSecondFactor: boolean,\n /**\n * An object holding information on the verification of this phone number.\n */\n readonly verification: Verification | null,\n /**\n * An object containing information about any other identification that might be linked to this phone number.\n */\n readonly linkedTo: IdentificationLink[],\n ) {}\n\n static fromJSON(data: PhoneNumberJSON): PhoneNumber {\n return new PhoneNumber(\n data.id,\n data.phone_number,\n data.reserved_for_second_factor,\n data.default_second_factor,\n data.verification && Verification.fromJSON(data.verification),\n data.linked_to.map(link => IdentificationLink.fromJSON(link)),\n );\n }\n}\n","import type { ProxyCheckJSON } from './JSON';\n\nexport class ProxyCheck {\n constructor(\n readonly id: string,\n readonly domainId: string,\n readonly lastRunAt: number | null,\n readonly proxyUrl: string,\n readonly successful: boolean,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: ProxyCheckJSON): ProxyCheck {\n return new ProxyCheck(\n data.id,\n data.domain_id,\n data.last_run_at,\n data.proxy_url,\n data.successful,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { RedirectUrlJSON } from './JSON';\n\n/**\n * Redirect URLs are whitelisted URLs that facilitate secure authentication flows in native applications (e.g. React Native, Expo). In these contexts, Clerk ensures that security-critical nonces are passed only to the whitelisted URLs.\n\nThe Backend `RedirectUrl` object represents a redirect URL in your application. This object is used in the Backend API.\n */\nexport class RedirectUrl {\n constructor(\n /**\n * The unique identifier for the redirect URL.\n */\n readonly id: string,\n /**\n * The full URL value prefixed with `https://` or a custom scheme.\n * @example https://my-app.com/oauth-callback\n * @example my-app://oauth-callback\n */\n readonly url: string,\n /**\n * The date when the redirect URL was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the redirect URL was last updated.\n */\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: RedirectUrlJSON): RedirectUrl {\n return new RedirectUrl(data.id, data.url, data.created_at, data.updated_at);\n }\n}\n","import type { AttributeMappingJSON, SamlConnectionJSON } from './JSON';\n\n/**\n * The Backend `SamlConnection` object holds information about a SAML connection for an organization.\n */\nexport class SamlConnection {\n constructor(\n /**\n * The unique identifier for the connection.\n */\n readonly id: string,\n /**\n * The name to use as a label for the connection.\n */\n readonly name: string,\n /**\n * The domain of your organization. Sign in flows using an email with this domain will use the connection.\n */\n readonly domain: string,\n /**\n * The organization ID of the organization.\n */\n readonly organizationId: string | null,\n /**\n * The Entity ID as provided by the Identity Provider (IdP).\n */\n readonly idpEntityId: string | null,\n /**\n * The Single-Sign On URL as provided by the Identity Provider (IdP).\n */\n readonly idpSsoUrl: string | null,\n /**\n * The X.509 certificate as provided by the Identity Provider (IdP).\n */\n readonly idpCertificate: string | null,\n /**\n * The URL which serves the Identity Provider (IdP) metadata. If present, it takes priority over the corresponding individual properties.\n */\n readonly idpMetadataUrl: string | null,\n /**\n * The XML content of the Identity Provider (IdP) metadata file. If present, it takes priority over the corresponding individual properties.\n */\n readonly idpMetadata: string | null,\n /**\n * The Assertion Consumer Service (ACS) URL of the connection.\n */\n readonly acsUrl: string,\n /**\n * The Entity ID as provided by the Service Provider (Clerk).\n */\n readonly spEntityId: string,\n /**\n * The metadata URL as provided by the Service Provider (Clerk).\n */\n readonly spMetadataUrl: string,\n /**\n * Indicates whether the connection is active or not.\n */\n readonly active: boolean,\n /**\n * The Identity Provider (IdP) of the connection.\n */\n readonly provider: string,\n /**\n * The number of users associated with the connection.\n */\n readonly userCount: number,\n /**\n * Indicates whether the connection syncs user attributes between the Service Provider (SP) and Identity Provider (IdP) or not.\n */\n readonly syncUserAttributes: boolean,\n /**\n * Indicates whether users with an email address subdomain are allowed to use this connection in order to authenticate or not.\n */\n readonly allowSubdomains: boolean,\n /**\n * Indicates whether the connection allows Identity Provider (IdP) initiated flows or not.\n */\n readonly allowIdpInitiated: boolean,\n /**\n * The date when the connection was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the SAML connection was last updated.\n */\n readonly updatedAt: number,\n /**\n * Defines the attribute name mapping between the Identity Provider (IdP) and Clerk's [`User`](https://clerk.com/docs/reference/javascript/user) properties.\n */\n readonly attributeMapping: AttributeMapping,\n ) {}\n static fromJSON(data: SamlConnectionJSON): SamlConnection {\n return new SamlConnection(\n data.id,\n data.name,\n data.domain,\n data.organization_id,\n data.idp_entity_id,\n data.idp_sso_url,\n data.idp_certificate,\n data.idp_metadata_url,\n data.idp_metadata,\n data.acs_url,\n data.sp_entity_id,\n data.sp_metadata_url,\n data.active,\n data.provider,\n data.user_count,\n data.sync_user_attributes,\n data.allow_subdomains,\n data.allow_idp_initiated,\n data.created_at,\n data.updated_at,\n data.attribute_mapping && AttributeMapping.fromJSON(data.attribute_mapping),\n );\n }\n}\n\nclass AttributeMapping {\n constructor(\n /**\n * The user ID attribute name.\n */\n readonly userId: string,\n /**\n * The email address attribute name.\n */\n readonly emailAddress: string,\n /**\n * The first name attribute name.\n */\n readonly firstName: string,\n /**\n * The last name attribute name.\n */\n readonly lastName: string,\n ) {}\n\n static fromJSON(data: AttributeMappingJSON): AttributeMapping {\n return new AttributeMapping(data.user_id, data.email_address, data.first_name, data.last_name);\n }\n}\n","import type { SignInTokenJSON } from './JSON';\n\nexport class SignInToken {\n constructor(\n readonly id: string,\n readonly userId: string,\n readonly token: string,\n readonly status: string,\n readonly url: string,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: SignInTokenJSON): SignInToken {\n return new SignInToken(data.id, data.user_id, data.token, data.status, data.url, data.created_at, data.updated_at);\n }\n}\n","import type { SignUpStatus } from '@clerk/shared/types';\n\nimport type { SignUpVerificationNextAction } from './Enums';\nimport type { SignUpJSON, SignUpVerificationJSON, SignUpVerificationsJSON } from './JSON';\n\nexport class SignUpAttemptVerification {\n constructor(\n readonly nextAction: SignUpVerificationNextAction,\n readonly supportedStrategies: string[],\n ) {}\n\n static fromJSON(data: SignUpVerificationJSON): SignUpAttemptVerification {\n return new SignUpAttemptVerification(data.next_action, data.supported_strategies);\n }\n}\n\nexport class SignUpAttemptVerifications {\n constructor(\n readonly emailAddress: SignUpAttemptVerification | null,\n readonly phoneNumber: SignUpAttemptVerification | null,\n readonly web3Wallet: SignUpAttemptVerification | null,\n readonly externalAccount: object | null,\n ) {}\n\n static fromJSON(data: SignUpVerificationsJSON): SignUpAttemptVerifications {\n return new SignUpAttemptVerifications(\n data.email_address && SignUpAttemptVerification.fromJSON(data.email_address),\n data.phone_number && SignUpAttemptVerification.fromJSON(data.phone_number),\n data.web3_wallet && SignUpAttemptVerification.fromJSON(data.web3_wallet),\n data.external_account,\n );\n }\n}\n\nexport class SignUpAttempt {\n constructor(\n readonly id: string,\n readonly status: SignUpStatus,\n readonly requiredFields: string[],\n readonly optionalFields: string[],\n readonly missingFields: string[],\n readonly unverifiedFields: string[],\n readonly verifications: SignUpAttemptVerifications | null,\n readonly username: string | null,\n readonly emailAddress: string | null,\n readonly phoneNumber: string | null,\n readonly web3Wallet: string | null,\n readonly passwordEnabled: boolean,\n readonly firstName: string | null,\n readonly lastName: string | null,\n readonly customAction: boolean,\n readonly externalId: string | null,\n readonly createdSessionId: string | null,\n readonly createdUserId: string | null,\n readonly abandonAt: number | null,\n readonly legalAcceptedAt: number | null,\n readonly publicMetadata?: Record<string, unknown> | null,\n readonly unsafeMetadata?: Record<string, unknown> | null,\n ) {}\n\n static fromJSON(data: SignUpJSON): SignUpAttempt {\n return new SignUpAttempt(\n data.id,\n data.status,\n data.required_fields,\n data.optional_fields,\n data.missing_fields,\n data.unverified_fields,\n data.verifications ? SignUpAttemptVerifications.fromJSON(data.verifications) : null,\n data.username,\n data.email_address,\n data.phone_number,\n data.web3_wallet,\n data.password_enabled,\n data.first_name,\n data.last_name,\n data.custom_action,\n data.external_id,\n data.created_session_id,\n data.created_user_id,\n data.abandon_at,\n data.legal_accepted_at,\n data.public_metadata,\n data.unsafe_metadata,\n );\n }\n}\n","import type { SMSMessageJSON } from './JSON';\n\nexport class SMSMessage {\n constructor(\n readonly id: string,\n readonly fromPhoneNumber: string,\n readonly toPhoneNumber: string,\n readonly message: string,\n readonly status: string,\n readonly phoneNumberId: string | null,\n readonly data?: Record<string, any> | null,\n ) {}\n\n static fromJSON(data: SMSMessageJSON): SMSMessage {\n return new SMSMessage(\n data.id,\n data.from_phone_number,\n data.to_phone_number,\n data.message,\n data.status,\n data.phone_number_id,\n data.data,\n );\n }\n}\n","import type { TokenJSON } from './JSON';\n\nexport class Token {\n constructor(readonly jwt: string) {}\n\n static fromJSON(data: TokenJSON): Token {\n return new Token(data.jwt);\n }\n}\n","import type { Web3WalletJSON } from './JSON';\nimport { Verification } from './Verification';\n\n/**\n * The Backend `Web3Wallet` object describes a Web3 wallet address. The address can be used as a proof of identification for users.\n *\n * Web3 addresses must be verified to ensure that they can be assigned to their rightful owners. The verification is completed via Web3 wallet browser extensions, such as [Metamask](https://metamask.io/), [Coinbase Wallet](https://www.coinbase.com/wallet), and [OKX Wallet](https://www.okx.com/help/section/faq-web3-wallet). The `Web3Wallet3` object holds all the necessary state around the verification process.\n */\nexport class Web3Wallet {\n constructor(\n /**\n * The unique ID for the Web3 wallet.\n */\n readonly id: string,\n /**\n * The Web3 wallet address, made up of 0x + 40 hexadecimal characters.\n */\n readonly web3Wallet: string,\n /**\n * An object holding information on the verification of this Web3 wallet.\n */\n readonly verification: Verification | null,\n ) {}\n\n static fromJSON(data: Web3WalletJSON): Web3Wallet {\n return new Web3Wallet(data.id, data.web3_wallet, data.verification && Verification.fromJSON(data.verification));\n }\n}\n","import { EmailAddress } from './EmailAddress';\nimport { ExternalAccount } from './ExternalAccount';\nimport type { ExternalAccountJSON, UserJSON } from './JSON';\nimport { PhoneNumber } from './PhoneNumber';\nimport { Web3Wallet } from './Web3Wallet';\n\n/**\n * The Backend `User` object is similar to the `User` object as it holds information about a user of your application, such as their unique identifier, name, email addresses, phone numbers, and more. However, the Backend `User` object is different from the `User` object in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Users#operation/GetUser){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class User {\n private _raw: UserJSON | null = null;\n\n public get raw(): UserJSON | null {\n return this._raw;\n }\n\n constructor(\n /**\n * The unique identifier for the user.\n */\n readonly id: string,\n /**\n * A boolean indicating whether the user has a password on their account.\n */\n readonly passwordEnabled: boolean,\n /**\n * A boolean indicating whether the user has enabled TOTP by generating a TOTP secret and verifying it via an authenticator app.\n */\n readonly totpEnabled: boolean,\n /**\n * A boolean indicating whether the user has enabled Backup codes.\n */\n readonly backupCodeEnabled: boolean,\n /**\n * A boolean indicating whether the user has enabled two-factor authentication.\n */\n readonly twoFactorEnabled: boolean,\n /**\n * A boolean indicating whether the user is banned or not.\n */\n readonly banned: boolean,\n /**\n * A boolean indicating whether the user is banned or not.\n */\n readonly locked: boolean,\n /**\n * The date when the user was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the user was last updated.\n */\n readonly updatedAt: number,\n /**\n * The URL of the user's profile image.\n */\n readonly imageUrl: string,\n /**\n * A getter boolean to check if the user has uploaded an image or one was copied from OAuth. Returns `false` if Clerk is displaying an avatar for the user.\n */\n readonly hasImage: boolean,\n /**\n * The ID for the `EmailAddress` that the user has set as primary.\n */\n readonly primaryEmailAddressId: string | null,\n /**\n * The ID for the `PhoneNumber` that the user has set as primary.\n */\n readonly primaryPhoneNumberId: string | null,\n /**\n * The ID for the [`Web3Wallet`](https://clerk.com/docs/reference/backend/types/backend-web3-wallet) that the user signed up with.\n */\n readonly primaryWeb3WalletId: string | null,\n /**\n * The date when the user last signed in. May be empty if the user has never signed in.\n */\n readonly lastSignInAt: number | null,\n /**\n * The ID of the user as used in your external systems. Must be unique across your instance.\n */\n readonly externalId: string | null,\n /**\n * The user's username.\n */\n readonly username: string | null,\n /**\n * The user's first name.\n */\n readonly firstName: string | null,\n /**\n * The user's last name.\n */\n readonly lastName: string | null,\n /**\n * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API.\n */\n readonly publicMetadata: UserPublicMetadata = {},\n /**\n * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}.\n */\n readonly privateMetadata: UserPrivateMetadata = {},\n /**\n * Metadata that can be read and set from the Frontend API. It's considered unsafe because it can be modified from the frontend.\n */\n readonly unsafeMetadata: UserUnsafeMetadata = {},\n /**\n * An array of all the `EmailAddress` objects associated with the user. Includes the primary.\n */\n readonly emailAddresses: EmailAddress[] = [],\n /**\n * An array of all the `PhoneNumber` objects associated with the user. Includes the primary.\n */\n readonly phoneNumbers: PhoneNumber[] = [],\n /**\n * An array of all the `Web3Wallet` objects associated with the user. Includes the primary.\n */\n readonly web3Wallets: Web3Wallet[] = [],\n /**\n * An array of all the `ExternalAccount` objects associated with the user via OAuth. **Note**: This includes both verified & unverified external accounts.\n */\n readonly externalAccounts: ExternalAccount[] = [],\n /**\n * Date when the user was last active.\n */\n readonly lastActiveAt: number | null,\n /**\n * A boolean indicating whether the organization creation is enabled for the user or not.\n */\n readonly createOrganizationEnabled: boolean,\n /**\n * An integer indicating the number of organizations that can be created by the user. If the value is `0`, then the user can create unlimited organizations. Default is `null`.\n */\n readonly createOrganizationsLimit: number | null = null,\n /**\n * A boolean indicating whether the user can delete their own account.\n */\n readonly deleteSelfEnabled: boolean,\n /**\n * The unix timestamp of when the user accepted the legal requirements. `null` if [**Require express consent to legal documents**](https://clerk.com/docs/guides/secure/legal-compliance) is not enabled.\n */\n readonly legalAcceptedAt: number | null,\n\n /**\n * The locale of the user in BCP-47 format.\n */\n readonly locale: string | null,\n ) {}\n\n static fromJSON(data: UserJSON): User {\n const res = new User(\n data.id,\n data.password_enabled,\n data.totp_enabled,\n data.backup_code_enabled,\n data.two_factor_enabled,\n data.banned,\n data.locked,\n data.created_at,\n data.updated_at,\n data.image_url,\n data.has_image,\n data.primary_email_address_id,\n data.primary_phone_number_id,\n data.primary_web3_wallet_id,\n data.last_sign_in_at,\n data.external_id,\n data.username,\n data.first_name,\n data.last_name,\n data.public_metadata,\n data.private_metadata,\n data.unsafe_metadata,\n (data.email_addresses || []).map(x => EmailAddress.fromJSON(x)),\n (data.phone_numbers || []).map(x => PhoneNumber.fromJSON(x)),\n (data.web3_wallets || []).map(x => Web3Wallet.fromJSON(x)),\n (data.external_accounts || []).map((x: ExternalAccountJSON) => ExternalAccount.fromJSON(x)),\n data.last_active_at,\n data.create_organization_enabled,\n data.create_organizations_limit,\n data.delete_self_enabled,\n data.legal_accepted_at,\n data.locale,\n );\n res._raw = data;\n return res;\n }\n\n /**\n * The primary email address of the user.\n */\n get primaryEmailAddress() {\n return this.emailAddresses.find(({ id }) => id === this.primaryEmailAddressId) ?? null;\n }\n\n /**\n * The primary phone number of the user.\n */\n get primaryPhoneNumber() {\n return this.phoneNumbers.find(({ id }) => id === this.primaryPhoneNumberId) ?? null;\n }\n\n /**\n * The primary web3 wallet of the user.\n */\n get primaryWeb3Wallet() {\n return this.web3Wallets.find(({ id }) => id === this.primaryWeb3WalletId) ?? null;\n }\n\n /**\n * The full name of the user.\n */\n get fullName() {\n return [this.firstName, this.lastName].join(' ').trim() || null;\n }\n}\n","import type { WaitlistEntryStatus } from './Enums';\nimport { Invitation } from './Invitation';\nimport type { WaitlistEntryJSON } from './JSON';\n\nexport class WaitlistEntry {\n constructor(\n readonly id: string,\n readonly emailAddress: string,\n readonly status: WaitlistEntryStatus,\n readonly invitation: Invitation | null,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly isLocked?: boolean,\n ) {}\n\n static fromJSON(data: WaitlistEntryJSON): WaitlistEntry {\n return new WaitlistEntry(\n data.id,\n data.email_address,\n data.status,\n data.invitation && Invitation.fromJSON(data.invitation),\n data.created_at,\n data.updated_at,\n data.is_locked,\n );\n }\n}\n","import {\n ActorToken,\n AllowlistIdentifier,\n APIKey,\n BlocklistIdentifier,\n Client,\n Cookies,\n DeletedObject,\n Domain,\n Email,\n EmailAddress,\n IdPOAuthAccessToken,\n Instance,\n InstanceRestrictions,\n InstanceSettings,\n Invitation,\n JwtTemplate,\n M2MToken,\n Machine,\n MachineScope,\n MachineSecretKey,\n OauthAccessToken,\n OAuthApplication,\n Organization,\n OrganizationInvitation,\n OrganizationMembership,\n OrganizationSettings,\n PhoneNumber,\n ProxyCheck,\n RedirectUrl,\n SamlConnection,\n Session,\n SignInToken,\n SignUpAttempt,\n SMSMessage,\n Token,\n User,\n} from '.';\nimport { AccountlessApplication } from './AccountlessApplication';\nimport { BillingPlan } from './CommercePlan';\nimport { BillingSubscription } from './CommerceSubscription';\nimport { BillingSubscriptionItem } from './CommerceSubscriptionItem';\nimport { Feature } from './Feature';\nimport type { PaginatedResponseJSON } from './JSON';\nimport { ObjectType } from './JSON';\nimport { WaitlistEntry } from './WaitlistEntry';\n\ntype ResourceResponse<T> = {\n /**\n * An array that contains the fetched data.\n */\n data: T;\n};\n\n/**\n * An interface that describes the response of a method that returns a paginated list of resources.\n *\n * If the promise resolves, you will get back the [properties](#properties) listed below. `data` will be an array of the resource type you requested. You can use the `totalCount` property to determine how many total items exist remotely.\n *\n * Some methods that return this type allow pagination with the `limit` and `offset` parameters, in which case the first 10 items will be returned by default. For methods such as [`getAllowlistIdentifierList()`](https://clerk.com/docs/reference/backend/allowlist/get-allowlist-identifier-list), which do not take a `limit` or `offset`, all items will be returned.\n *\n * If the promise is rejected, you will receive a `ClerkAPIResponseError` or network error.\n *\n * @interface\n */\nexport type PaginatedResourceResponse<T> = ResourceResponse<T> & {\n /**\n * The total count of data that exist remotely.\n */\n totalCount: number;\n};\n\nexport function deserialize<U = any>(payload: unknown): PaginatedResourceResponse<U> | ResourceResponse<U> {\n let data, totalCount: number | undefined;\n\n if (Array.isArray(payload)) {\n const data = payload.map(item => jsonToObject(item)) as U;\n return { data };\n } else if (isPaginated(payload)) {\n data = payload.data.map(item => jsonToObject(item)) as U;\n totalCount = payload.total_count;\n\n return { data, totalCount };\n } else {\n return { data: jsonToObject(payload) };\n }\n}\n\nfunction isPaginated(payload: unknown): payload is PaginatedResponseJSON {\n if (!payload || typeof payload !== 'object' || !('data' in payload)) {\n return false;\n }\n\n return Array.isArray(payload.data) && payload.data !== undefined;\n}\n\nfunction getCount(item: PaginatedResponseJSON) {\n return item.total_count;\n}\n\n// TODO: Revise response deserialization\nfunction jsonToObject(item: any): any {\n // Special case: DeletedObject\n // TODO: Improve this check\n if (typeof item !== 'string' && 'object' in item && 'deleted' in item) {\n return DeletedObject.fromJSON(item);\n }\n\n switch (item.object) {\n case ObjectType.AccountlessApplication:\n return AccountlessApplication.fromJSON(item);\n case ObjectType.ActorToken:\n return ActorToken.fromJSON(item);\n case ObjectType.AllowlistIdentifier:\n return AllowlistIdentifier.fromJSON(item);\n case ObjectType.ApiKey:\n return APIKey.fromJSON(item);\n case ObjectType.BlocklistIdentifier:\n return BlocklistIdentifier.fromJSON(item);\n case ObjectType.Client:\n return Client.fromJSON(item);\n case ObjectType.Cookies:\n return Cookies.fromJSON(item);\n case ObjectType.Domain:\n return Domain.fromJSON(item);\n case ObjectType.EmailAddress:\n return EmailAddress.fromJSON(item);\n case ObjectType.Email:\n return Email.fromJSON(item);\n case ObjectType.IdpOAuthAccessToken:\n return IdPOAuthAccessToken.fromJSON(item);\n case ObjectType.Instance:\n return Instance.fromJSON(item);\n case ObjectType.InstanceRestrictions:\n return InstanceRestrictions.fromJSON(item);\n case ObjectType.InstanceSettings:\n return InstanceSettings.fromJSON(item);\n case ObjectType.Invitation:\n return Invitation.fromJSON(item);\n case ObjectType.JwtTemplate:\n return JwtTemplate.fromJSON(item);\n case ObjectType.Machine:\n return Machine.fromJSON(item);\n case ObjectType.MachineScope:\n return MachineScope.fromJSON(item);\n case ObjectType.MachineSecretKey:\n return MachineSecretKey.fromJSON(item);\n case ObjectType.M2MToken:\n return M2MToken.fromJSON(item);\n case ObjectType.OauthAccessToken:\n return OauthAccessToken.fromJSON(item);\n case ObjectType.OAuthApplication:\n return OAuthApplication.fromJSON(item);\n case ObjectType.Organization:\n return Organization.fromJSON(item);\n case ObjectType.OrganizationInvitation:\n return OrganizationInvitation.fromJSON(item);\n case ObjectType.OrganizationMembership:\n return OrganizationMembership.fromJSON(item);\n case ObjectType.OrganizationSettings:\n return OrganizationSettings.fromJSON(item);\n case ObjectType.PhoneNumber:\n return PhoneNumber.fromJSON(item);\n case ObjectType.ProxyCheck:\n return ProxyCheck.fromJSON(item);\n case ObjectType.RedirectUrl:\n return RedirectUrl.fromJSON(item);\n case ObjectType.SamlConnection:\n return SamlConnection.fromJSON(item);\n case ObjectType.SignInToken:\n return SignInToken.fromJSON(item);\n case ObjectType.SignUpAttempt:\n return SignUpAttempt.fromJSON(item);\n case ObjectType.Session:\n return Session.fromJSON(item);\n case ObjectType.SmsMessage:\n return SMSMessage.fromJSON(item);\n case ObjectType.Token:\n return Token.fromJSON(item);\n case ObjectType.TotalCount:\n return getCount(item);\n case ObjectType.User:\n return User.fromJSON(item);\n case ObjectType.WaitlistEntry:\n return WaitlistEntry.fromJSON(item);\n case ObjectType.BillingPlan:\n return BillingPlan.fromJSON(item);\n case ObjectType.BillingSubscription:\n return BillingSubscription.fromJSON(item);\n case ObjectType.BillingSubscriptionItem:\n return BillingSubscriptionItem.fromJSON(item);\n case ObjectType.Feature:\n return Feature.fromJSON(item);\n default:\n return item;\n }\n}\n","import {\n AccountlessApplicationAPI,\n ActorTokenAPI,\n AllowlistIdentifierAPI,\n APIKeysAPI,\n BetaFeaturesAPI,\n BlocklistIdentifierAPI,\n ClientAPI,\n DomainAPI,\n EmailAddressAPI,\n IdPOAuthAccessTokenApi,\n InstanceAPI,\n InvitationAPI,\n JwksAPI,\n JwtTemplatesApi,\n M2MTokenApi,\n MachineApi,\n OAuthApplicationsApi,\n OrganizationAPI,\n PhoneNumberAPI,\n ProxyCheckAPI,\n RedirectUrlAPI,\n SamlConnectionAPI,\n SessionAPI,\n SignInTokenAPI,\n SignUpAPI,\n TestingTokenAPI,\n UserAPI,\n WaitlistEntryAPI,\n WebhookAPI,\n} from './endpoints';\nimport { BillingAPI } from './endpoints/BillingApi';\nimport { buildRequest } from './request';\n\nexport type CreateBackendApiOptions = Parameters<typeof buildRequest>[0];\n\nexport type ApiClient = ReturnType<typeof createBackendApiClient>;\n\nexport function createBackendApiClient(options: CreateBackendApiOptions) {\n const request = buildRequest(options);\n\n return {\n __experimental_accountlessApplications: new AccountlessApplicationAPI(\n buildRequest({ ...options, requireSecretKey: false }),\n ),\n actorTokens: new ActorTokenAPI(request),\n allowlistIdentifiers: new AllowlistIdentifierAPI(request),\n apiKeys: new APIKeysAPI(\n buildRequest({\n ...options,\n skipApiVersionInUrl: true,\n }),\n ),\n betaFeatures: new BetaFeaturesAPI(request),\n blocklistIdentifiers: new BlocklistIdentifierAPI(request),\n /**\n * @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.\n */\n billing: new BillingAPI(request),\n clients: new ClientAPI(request),\n domains: new DomainAPI(request),\n emailAddresses: new EmailAddressAPI(request),\n idPOAuthAccessToken: new IdPOAuthAccessTokenApi(\n buildRequest({\n ...options,\n skipApiVersionInUrl: true,\n }),\n ),\n instance: new InstanceAPI(request),\n invitations: new InvitationAPI(request),\n jwks: new JwksAPI(request),\n jwtTemplates: new JwtTemplatesApi(request),\n machines: new MachineApi(request),\n m2m: new M2MTokenApi(\n buildRequest({\n ...options,\n skipApiVersionInUrl: true,\n requireSecretKey: false,\n useMachineSecretKey: true,\n }),\n ),\n oauthApplications: new OAuthApplicationsApi(request),\n organizations: new OrganizationAPI(request),\n phoneNumbers: new PhoneNumberAPI(request),\n proxyChecks: new ProxyCheckAPI(request),\n redirectUrls: new RedirectUrlAPI(request),\n samlConnections: new SamlConnectionAPI(request),\n sessions: new SessionAPI(request),\n signInTokens: new SignInTokenAPI(request),\n signUps: new SignUpAPI(request),\n testingTokens: new TestingTokenAPI(request),\n users: new UserAPI(request),\n waitlistEntries: new WaitlistEntryAPI(request),\n webhooks: new WebhookAPI(request),\n };\n}\n","import type { AuthenticateRequestOptions } from '../tokens/types';\nimport type { MachineTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\n\nexport const M2M_TOKEN_PREFIX = 'mt_';\nexport const OAUTH_TOKEN_PREFIX = 'oat_';\nexport const API_KEY_PREFIX = 'ak_';\n\nconst MACHINE_TOKEN_PREFIXES = [M2M_TOKEN_PREFIX, OAUTH_TOKEN_PREFIX, API_KEY_PREFIX] as const;\n\n/**\n * Checks if a token is a machine token by looking at its prefix.\n *\n * @remarks\n * In the future, this will support custom prefixes that can be prepended to the base prefixes\n * (e.g. \"org_a_m2m_\", \"org_a_oauth_access_\", \"org_a_api_key_\")\n *\n * @param token - The token string to check\n * @returns true if the token starts with a recognized machine token prefix\n */\nexport function isMachineTokenByPrefix(token: string): boolean {\n return MACHINE_TOKEN_PREFIXES.some(prefix => token.startsWith(prefix));\n}\n\n/**\n * Gets the specific type of machine token based on its prefix.\n *\n * @remarks\n * In the future, this will support custom prefixes that can be prepended to the base prefixes\n * (e.g. \"org_a_m2m_\", \"org_a_oauth_access_\", \"org_a_api_key_\")\n *\n * @param token - The token string to check\n * @returns The specific MachineTokenType\n * @throws Error if the token doesn't match any known machine token prefix\n */\nexport function getMachineTokenType(token: string): MachineTokenType {\n if (token.startsWith(M2M_TOKEN_PREFIX)) {\n return TokenType.M2MToken;\n }\n\n if (token.startsWith(OAUTH_TOKEN_PREFIX)) {\n return TokenType.OAuthToken;\n }\n\n if (token.startsWith(API_KEY_PREFIX)) {\n return TokenType.ApiKey;\n }\n\n throw new Error('Unknown machine token type');\n}\n\n/**\n * Check if a token type is accepted given a requested token type or list of token types.\n *\n * @param tokenType - The token type to check (can be null if the token is invalid)\n * @param acceptsToken - The requested token type or list of token types\n * @returns true if the token type is accepted\n */\nexport const isTokenTypeAccepted = (\n tokenType: TokenType | null,\n acceptsToken: NonNullable<AuthenticateRequestOptions['acceptsToken']>,\n): boolean => {\n if (!tokenType) {\n return false;\n }\n\n if (acceptsToken === 'any') {\n return true;\n }\n\n const tokenTypes = Array.isArray(acceptsToken) ? acceptsToken : [acceptsToken];\n return tokenTypes.includes(tokenType);\n};\n\n/**\n * Checks if a token type string is a machine token type (api_key, m2m_token, or oauth_token).\n *\n * @param type - The token type string to check\n * @returns true if the type is a machine token type\n */\nexport function isMachineTokenType(type: string): type is MachineTokenType {\n return type === TokenType.ApiKey || type === TokenType.M2MToken || type === TokenType.OAuthToken;\n}\n","import type { JwtPayload, PendingSessionOptions } from '@clerk/shared/types';\n\nimport { constants } from '../constants';\nimport type { TokenVerificationErrorReason } from '../errors';\nimport type { AuthenticateContext } from './authenticateContext';\nimport type {\n AuthenticatedMachineObject,\n InvalidTokenAuthObject,\n SignedInAuthObject,\n SignedOutAuthObject,\n UnauthenticatedMachineObject,\n} from './authObjects';\nimport {\n authenticatedMachineObject,\n invalidTokenAuthObject,\n signedInAuthObject,\n signedOutAuthObject,\n unauthenticatedMachineObject,\n} from './authObjects';\nimport type { MachineTokenType, SessionTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\nimport type { MachineAuthType } from './types';\n\nexport const AuthStatus = {\n SignedIn: 'signed-in',\n SignedOut: 'signed-out',\n Handshake: 'handshake',\n} as const;\n\nexport type AuthStatus = (typeof AuthStatus)[keyof typeof AuthStatus];\n\ntype ToAuth<T extends TokenType | null, Authenticated extends boolean> = T extends null\n ? () => InvalidTokenAuthObject\n : T extends SessionTokenType\n ? Authenticated extends true\n ? (opts?: PendingSessionOptions) => SignedInAuthObject\n : () => SignedOutAuthObject\n : Authenticated extends true\n ? () => AuthenticatedMachineObject<Exclude<T, SessionTokenType | null>>\n : () => UnauthenticatedMachineObject<Exclude<T, SessionTokenType | null>>;\n\nexport type AuthenticatedState<T extends TokenType = SessionTokenType> = {\n status: typeof AuthStatus.SignedIn;\n reason: null;\n message: null;\n proxyUrl?: string;\n publishableKey: string;\n isSatellite: boolean;\n domain: string;\n signInUrl: string;\n signUpUrl: string;\n afterSignInUrl: string;\n afterSignUpUrl: string;\n /**\n * @deprecated Use `isAuthenticated` instead.\n */\n isSignedIn: true;\n isAuthenticated: true;\n headers: Headers;\n token: string;\n tokenType: T;\n toAuth: ToAuth<T, true>;\n};\n\nexport type UnauthenticatedState<T extends TokenType | null = SessionTokenType> = {\n status: typeof AuthStatus.SignedOut;\n reason: AuthReason;\n message: string;\n proxyUrl?: string;\n publishableKey: string;\n isSatellite: boolean;\n domain: string;\n signInUrl: string;\n signUpUrl: string;\n afterSignInUrl: string;\n afterSignUpUrl: string;\n /**\n * @deprecated Use `isAuthenticated` instead.\n */\n isSignedIn: false;\n isAuthenticated: false;\n tokenType: T;\n headers: Headers;\n token: null;\n toAuth: ToAuth<T, false>;\n};\n\nexport type HandshakeState = Omit<UnauthenticatedState<SessionTokenType>, 'status' | 'toAuth' | 'tokenType'> & {\n tokenType: SessionTokenType;\n status: typeof AuthStatus.Handshake;\n headers: Headers;\n toAuth: () => null;\n};\n\n/**\n * @deprecated Use AuthenticatedState instead\n */\nexport type SignedInState = AuthenticatedState<SessionTokenType>;\n\n/**\n * @deprecated Use UnauthenticatedState instead\n */\nexport type SignedOutState = UnauthenticatedState<SessionTokenType>;\n\nexport const AuthErrorReason = {\n ClientUATWithoutSessionToken: 'client-uat-but-no-session-token',\n DevBrowserMissing: 'dev-browser-missing',\n DevBrowserSync: 'dev-browser-sync',\n PrimaryRespondsToSyncing: 'primary-responds-to-syncing',\n PrimaryDomainCrossOriginSync: 'primary-domain-cross-origin-sync',\n SatelliteCookieNeedsSyncing: 'satellite-needs-syncing',\n SessionTokenAndUATMissing: 'session-token-and-uat-missing',\n SessionTokenMissing: 'session-token-missing',\n SessionTokenExpired: 'session-token-expired',\n SessionTokenIATBeforeClientUAT: 'session-token-iat-before-client-uat',\n SessionTokenNBF: 'session-token-nbf',\n SessionTokenIatInTheFuture: 'session-token-iat-in-the-future',\n SessionTokenWithoutClientUAT: 'session-token-but-no-client-uat',\n ActiveOrganizationMismatch: 'active-organization-mismatch',\n TokenTypeMismatch: 'token-type-mismatch',\n UnexpectedError: 'unexpected-error',\n} as const;\n\nexport type AuthErrorReason = (typeof AuthErrorReason)[keyof typeof AuthErrorReason];\n\nexport type AuthReason = AuthErrorReason | TokenVerificationErrorReason;\n\nexport type RequestState<T extends TokenType | null = SessionTokenType> =\n | AuthenticatedState<T extends null ? never : T>\n | UnauthenticatedState<T>\n | (T extends SessionTokenType ? HandshakeState : never);\n\ntype BaseSignedInParams = {\n authenticateContext: AuthenticateContext;\n headers?: Headers;\n token: string;\n tokenType: TokenType;\n};\n\ntype SignedInParams =\n | (BaseSignedInParams & { tokenType: SessionTokenType; sessionClaims: JwtPayload })\n | (BaseSignedInParams & { tokenType: MachineTokenType; machineData: MachineAuthType });\n\nexport function signedIn<T extends TokenType>(params: SignedInParams & { tokenType: T }): AuthenticatedState<T> {\n const { authenticateContext, headers = new Headers(), token } = params;\n\n const toAuth = (({ treatPendingAsSignedOut = true } = {}) => {\n if (params.tokenType === TokenType.SessionToken) {\n const { sessionClaims } = params as { sessionClaims: JwtPayload };\n const authObject = signedInAuthObject(authenticateContext, token, sessionClaims);\n\n if (treatPendingAsSignedOut && authObject.sessionStatus === 'pending') {\n return signedOutAuthObject(undefined, authObject.sessionStatus);\n }\n\n return authObject;\n }\n\n const { machineData } = params as { machineData: MachineAuthType };\n return authenticatedMachineObject(params.tokenType, token, machineData, authenticateContext);\n }) as ToAuth<T, true>;\n\n return {\n status: AuthStatus.SignedIn,\n reason: null,\n message: null,\n proxyUrl: authenticateContext.proxyUrl || '',\n publishableKey: authenticateContext.publishableKey || '',\n isSatellite: authenticateContext.isSatellite || false,\n domain: authenticateContext.domain || '',\n signInUrl: authenticateContext.signInUrl || '',\n signUpUrl: authenticateContext.signUpUrl || '',\n afterSignInUrl: authenticateContext.afterSignInUrl || '',\n afterSignUpUrl: authenticateContext.afterSignUpUrl || '',\n isSignedIn: true,\n isAuthenticated: true,\n tokenType: params.tokenType,\n toAuth,\n headers,\n token,\n };\n}\n\ntype SignedOutParams = Omit<BaseSignedInParams, 'token'> & {\n reason: AuthReason;\n message?: string;\n};\n\nexport function signedOut<T extends TokenType>(params: SignedOutParams & { tokenType: T }): UnauthenticatedState<T> {\n const { authenticateContext, headers = new Headers(), reason, message = '', tokenType } = params;\n\n const toAuth = (() => {\n if (tokenType === TokenType.SessionToken) {\n return signedOutAuthObject({ ...authenticateContext, status: AuthStatus.SignedOut, reason, message });\n }\n\n return unauthenticatedMachineObject(tokenType, { reason, message, headers });\n }) as ToAuth<T, false>;\n\n return withDebugHeaders({\n status: AuthStatus.SignedOut,\n reason,\n message,\n proxyUrl: authenticateContext.proxyUrl || '',\n publishableKey: authenticateContext.publishableKey || '',\n isSatellite: authenticateContext.isSatellite || false,\n domain: authenticateContext.domain || '',\n signInUrl: authenticateContext.signInUrl || '',\n signUpUrl: authenticateContext.signUpUrl || '',\n afterSignInUrl: authenticateContext.afterSignInUrl || '',\n afterSignUpUrl: authenticateContext.afterSignUpUrl || '',\n isSignedIn: false,\n isAuthenticated: false,\n tokenType,\n toAuth,\n headers,\n token: null,\n });\n}\n\nexport function handshake(\n authenticateContext: AuthenticateContext,\n reason: AuthReason,\n message = '',\n headers: Headers,\n): HandshakeState {\n return withDebugHeaders({\n status: AuthStatus.Handshake,\n reason,\n message,\n publishableKey: authenticateContext.publishableKey || '',\n isSatellite: authenticateContext.isSatellite || false,\n domain: authenticateContext.domain || '',\n proxyUrl: authenticateContext.proxyUrl || '',\n signInUrl: authenticateContext.signInUrl || '',\n signUpUrl: authenticateContext.signUpUrl || '',\n afterSignInUrl: authenticateContext.afterSignInUrl || '',\n afterSignUpUrl: authenticateContext.afterSignUpUrl || '',\n isSignedIn: false,\n isAuthenticated: false,\n tokenType: TokenType.SessionToken,\n toAuth: () => null,\n headers,\n token: null,\n });\n}\n\nexport function signedOutInvalidToken(): UnauthenticatedState<null> {\n const authObject = invalidTokenAuthObject();\n return withDebugHeaders({\n status: AuthStatus.SignedOut,\n reason: AuthErrorReason.TokenTypeMismatch,\n message: '',\n proxyUrl: '',\n publishableKey: '',\n isSatellite: false,\n domain: '',\n signInUrl: '',\n signUpUrl: '',\n afterSignInUrl: '',\n afterSignUpUrl: '',\n isSignedIn: false,\n isAuthenticated: false,\n tokenType: null,\n toAuth: () => authObject,\n headers: new Headers(),\n token: null,\n });\n}\n\nconst withDebugHeaders = <T extends { headers: Headers; message?: string; reason?: AuthReason; status?: AuthStatus }>(\n requestState: T,\n): T => {\n const headers = new Headers(requestState.headers || {});\n\n if (requestState.message) {\n try {\n headers.set(constants.Headers.AuthMessage, requestState.message);\n } catch {\n // headers.set can throw if unicode strings are passed to it. In this case, simply do nothing\n }\n }\n\n if (requestState.reason) {\n try {\n headers.set(constants.Headers.AuthReason, requestState.reason);\n } catch {\n /* empty */\n }\n }\n\n if (requestState.status) {\n try {\n headers.set(constants.Headers.AuthStatus, requestState.status);\n } catch {\n /* empty */\n }\n }\n\n requestState.headers = headers;\n\n return requestState;\n};\n","import { parse } from 'cookie';\n\nimport { constants } from '../constants';\nimport type { ClerkUrl } from './clerkUrl';\nimport { createClerkUrl } from './clerkUrl';\n\n/**\n * A class that extends the native Request class,\n * adds cookies helpers and a normalised clerkUrl that is constructed by using the values found\n * in req.headers so it is able to work reliably when the app is running behind a proxy server.\n */\nclass ClerkRequest extends Request {\n readonly clerkUrl: ClerkUrl;\n readonly cookies: Map<string, string | undefined>;\n\n public constructor(input: ClerkRequest | Request | RequestInfo, init?: RequestInit) {\n // The usual way to duplicate a request object is to\n // pass the original request object to the Request constructor\n // both as the `input` and `init` parameters, eg: super(req, req)\n // However, this fails in certain environments like Vercel Edge Runtime\n // when a framework like Remix polyfills the global Request object.\n // This happens because `undici` performs the following instanceof check\n // which, instead of testing against the global Request object, tests against\n // the Request class defined in the same file (local Request class).\n // For more details, please refer to:\n // https://github.com/nodejs/undici/issues/2155\n // https://github.com/nodejs/undici/blob/7153a1c78d51840bbe16576ce353e481c3934701/lib/fetch/request.js#L854\n const url = typeof input !== 'string' && 'url' in input ? input.url : String(input);\n super(url, init || typeof input === 'string' ? undefined : input);\n this.clerkUrl = this.deriveUrlFromHeaders(this);\n this.cookies = this.parseCookies(this);\n }\n\n public toJSON() {\n return {\n url: this.clerkUrl.href,\n method: this.method,\n headers: JSON.stringify(Object.fromEntries(this.headers)),\n clerkUrl: this.clerkUrl.toString(),\n cookies: JSON.stringify(Object.fromEntries(this.cookies)),\n };\n }\n\n /**\n * Used to fix request.url using the x-forwarded-* headers\n * TODO add detailed description of the issues this solves\n */\n private deriveUrlFromHeaders(req: Request) {\n const initialUrl = new URL(req.url);\n const forwardedProto = req.headers.get(constants.Headers.ForwardedProto);\n const forwardedHost = req.headers.get(constants.Headers.ForwardedHost);\n const host = req.headers.get(constants.Headers.Host);\n const protocol = initialUrl.protocol;\n\n const resolvedHost = this.getFirstValueFromHeader(forwardedHost) ?? host;\n const resolvedProtocol = this.getFirstValueFromHeader(forwardedProto) ?? protocol?.replace(/[:/]/, '');\n const origin = resolvedHost && resolvedProtocol ? `${resolvedProtocol}://${resolvedHost}` : initialUrl.origin;\n\n if (origin === initialUrl.origin) {\n return createClerkUrl(initialUrl);\n }\n return createClerkUrl(initialUrl.pathname + initialUrl.search, origin);\n }\n\n private getFirstValueFromHeader(value?: string | null) {\n return value?.split(',')[0];\n }\n\n private parseCookies(req: Request) {\n const cookiesRecord = parse(this.decodeCookieValue(req.headers.get('cookie') || ''));\n return new Map(Object.entries(cookiesRecord));\n }\n\n private decodeCookieValue(str: string) {\n return str ? str.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent) : str;\n }\n}\n\nexport const createClerkRequest = (...args: ConstructorParameters<typeof ClerkRequest>): ClerkRequest => {\n return args[0] instanceof ClerkRequest ? args[0] : new ClerkRequest(...args);\n};\n\nexport type { ClerkRequest };\n","class ClerkUrl extends URL {\n public isCrossOrigin(other: URL | string) {\n return this.origin !== new URL(other.toString()).origin;\n }\n}\n\nexport type WithClerkUrl<T> = T & {\n /**\n * When a NextJs app is hosted on a platform different from Vercel\n * or inside a container (Netlify, Fly.io, AWS Amplify, docker etc),\n * req.url is always set to `localhost:3000` instead of the actual host of the app.\n *\n * The `authMiddleware` uses the value of the available req.headers in order to construct\n * and use the correct url internally. This url is then exposed as `experimental_clerkUrl`,\n * intended to be used within `beforeAuth` and `afterAuth` if needed.\n */\n clerkUrl: ClerkUrl;\n};\n\nexport const createClerkUrl = (...args: ConstructorParameters<typeof ClerkUrl>): ClerkUrl => {\n return new ClerkUrl(...args);\n};\n\nexport type { ClerkUrl };\n","export const getCookieName = (cookieDirective: string): string => {\n return cookieDirective.split(';')[0]?.split('=')[0];\n};\n\nexport const getCookieValue = (cookieDirective: string): string => {\n return cookieDirective.split(';')[0]?.split('=')[1];\n};\n","import {\n API_URL,\n API_VERSION,\n MAX_CACHE_LAST_UPDATED_AT_SECONDS,\n SUPPORTED_BAPI_VERSION,\n USER_AGENT,\n} from '../constants';\nimport {\n TokenVerificationError,\n TokenVerificationErrorAction,\n TokenVerificationErrorCode,\n TokenVerificationErrorReason,\n} from '../errors';\nimport { runtime } from '../runtime';\nimport { joinPaths } from '../util/path';\nimport { retry } from '../util/shared';\n\ntype JsonWebKeyWithKid = JsonWebKey & { kid: string };\n\ntype JsonWebKeyCache = Record<string, JsonWebKeyWithKid>;\n\nlet cache: JsonWebKeyCache = {};\nlet lastUpdatedAt = 0;\n\nfunction getFromCache(kid: string) {\n return cache[kid];\n}\n\nfunction getCacheValues() {\n return Object.values(cache);\n}\n\nfunction setInCache(cacheKey: string, jwk: JsonWebKeyWithKid, shouldExpire = true) {\n cache[cacheKey] = jwk;\n lastUpdatedAt = shouldExpire ? Date.now() : -1;\n}\n\nconst PEM_HEADER = '-----BEGIN PUBLIC KEY-----';\nconst PEM_TRAILER = '-----END PUBLIC KEY-----';\nconst RSA_PREFIX = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA';\nconst RSA_SUFFIX = 'IDAQAB';\n\ntype LoadClerkJwkFromPemOptions = {\n kid: string;\n pem?: string;\n};\n\n/**\n * Loads a local PEM key usually from process.env and transform it to JsonWebKey format.\n * The result is cached on the module level to avoid unnecessary computations in subsequent invocations.\n */\nexport function loadClerkJwkFromPem(params: LoadClerkJwkFromPemOptions): JsonWebKey {\n const { kid, pem } = params;\n\n // We use a cache key that includes the local prefix in order to avoid\n // cache conflicts when loadClerkJwkFromPem and loadClerkJWKFromRemote\n // are called with the same kid\n const prefixedKid = `local-${kid}`;\n const cachedJwk = getFromCache(prefixedKid);\n\n if (cachedJwk) {\n return cachedJwk;\n }\n\n if (!pem) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.SetClerkJWTKey,\n message: 'Missing local JWK.',\n reason: TokenVerificationErrorReason.LocalJWKMissing,\n });\n }\n\n const modulus = pem\n .replace(/\\r\\n|\\n|\\r/g, '')\n .replace(PEM_HEADER, '')\n .replace(PEM_TRAILER, '')\n .replace(RSA_PREFIX, '')\n .replace(RSA_SUFFIX, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n\n // https://datatracker.ietf.org/doc/html/rfc7517\n const jwk = { kid: prefixedKid, kty: 'RSA', alg: 'RS256', n: modulus, e: 'AQAB' };\n setInCache(prefixedKid, jwk, false); // local key never expires in cache\n return jwk;\n}\n\n/**\n * @internal\n */\nexport type LoadClerkJWKFromRemoteOptions = {\n /**\n * @internal\n */\n kid: string;\n /**\n * @deprecated This cache TTL will be removed in the next major version. Specifying a cache TTL is a no-op.\n */\n jwksCacheTtlInMs?: number;\n /**\n * A flag to ignore the JWKS cache and always fetch JWKS before each JWT verification.\n */\n skipJwksCache?: boolean;\n /**\n * The Clerk Secret Key from the [**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page in the Clerk Dashboard.\n */\n secretKey?: string;\n /**\n * The [Clerk Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} endpoint.\n * @default 'https://api.clerk.com'\n */\n apiUrl?: string;\n /**\n * The version passed to the Clerk API.\n * @default 'v1'\n */\n apiVersion?: string;\n};\n\n/**\n *\n * Loads a key from JWKS retrieved from the well-known Frontend API endpoint of the issuer.\n * The result is also cached on the module level to avoid network requests in subsequent invocations.\n * The cache lasts up to 5 minutes.\n *\n * @param {Object} options\n * @param {string} options.kid - The id of the key that the JWT was signed with\n * @param {string} options.alg - The algorithm of the JWT\n * @returns {JsonWebKey} key\n */\nexport async function loadClerkJWKFromRemote(params: LoadClerkJWKFromRemoteOptions): Promise<JsonWebKey> {\n const { secretKey, apiUrl = API_URL, apiVersion = API_VERSION, kid, skipJwksCache } = params;\n\n if (skipJwksCache || cacheHasExpired() || !getFromCache(kid)) {\n if (!secretKey) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.ContactSupport,\n message: 'Failed to load JWKS from Clerk Backend or Frontend API.',\n reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad,\n });\n }\n const fetcher = () => fetchJWKSFromBAPI(apiUrl, secretKey, apiVersion) as Promise<{ keys: JsonWebKeyWithKid[] }>;\n const { keys } = await retry(fetcher);\n\n if (!keys || !keys.length) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.ContactSupport,\n message: 'The JWKS endpoint did not contain any signing keys. Contact support@clerk.com.',\n reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad,\n });\n }\n\n keys.forEach(key => setInCache(key.kid, key));\n }\n\n const jwk = getFromCache(kid);\n\n if (!jwk) {\n const cacheValues = getCacheValues();\n const jwkKeys = cacheValues\n .map(jwk => jwk.kid)\n .sort()\n .join(', ');\n\n throw new TokenVerificationError({\n action: `Go to your Dashboard and validate your secret and public keys are correct. ${TokenVerificationErrorAction.ContactSupport} if the issue persists.`,\n message: `Unable to find a signing key in JWKS that matches the kid='${kid}' of the provided session token. Please make sure that the __session cookie or the HTTP authorization header contain a Clerk-generated session JWT. The following kid is available: ${jwkKeys}`,\n reason: TokenVerificationErrorReason.JWKKidMismatch,\n });\n }\n\n return jwk;\n}\n\nasync function fetchJWKSFromBAPI(apiUrl: string, key: string, apiVersion: string) {\n if (!key) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.SetClerkSecretKey,\n message:\n 'Missing Clerk Secret Key or API Key. Go to https://dashboard.clerk.com and get your key for your instance.',\n reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad,\n });\n }\n\n const url = new URL(apiUrl);\n url.pathname = joinPaths(url.pathname, apiVersion, '/jwks');\n\n const response = await runtime.fetch(url.href, {\n headers: {\n Authorization: `Bearer ${key}`,\n 'Clerk-API-Version': SUPPORTED_BAPI_VERSION,\n 'Content-Type': 'application/json',\n 'User-Agent': USER_AGENT,\n },\n });\n\n if (!response.ok) {\n const json = await response.json();\n const invalidSecretKeyError = getErrorObjectByCode(json?.errors, TokenVerificationErrorCode.InvalidSecretKey);\n\n if (invalidSecretKeyError) {\n const reason = TokenVerificationErrorReason.InvalidSecretKey;\n\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.ContactSupport,\n message: invalidSecretKeyError.message,\n reason,\n });\n }\n\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.ContactSupport,\n message: `Error loading Clerk JWKS from ${url.href} with code=${response.status}`,\n reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad,\n });\n }\n\n return response.json();\n}\n\nfunction cacheHasExpired() {\n // If lastUpdatedAt is -1, it means that we're using a local JWKS and it never expires\n if (lastUpdatedAt === -1) {\n return false;\n }\n\n // If the cache has expired, clear the value so we don't attempt to make decisions based on stale data\n const isExpired = Date.now() - lastUpdatedAt >= MAX_CACHE_LAST_UPDATED_AT_SECONDS * 1000;\n\n if (isExpired) {\n cache = {};\n }\n\n return isExpired;\n}\n\ntype ErrorFields = {\n message: string;\n long_message: string;\n code: string;\n};\n\nconst getErrorObjectByCode = (errors: ErrorFields[], code: string) => {\n if (!errors) {\n return null;\n }\n\n return errors.find((err: ErrorFields) => err.code === code);\n};\n","import { isClerkAPIResponseError } from '@clerk/shared/error';\nimport type { JwtPayload, Simplify } from '@clerk/shared/types';\n\nimport type { APIKey, IdPOAuthAccessToken, M2MToken } from '../api';\nimport { createBackendApiClient } from '../api/factory';\nimport {\n MachineTokenVerificationError,\n MachineTokenVerificationErrorCode,\n TokenVerificationError,\n TokenVerificationErrorAction,\n TokenVerificationErrorReason,\n} from '../errors';\nimport type { VerifyJwtOptions } from '../jwt';\nimport type { JwtReturnType, MachineTokenReturnType } from '../jwt/types';\nimport { decodeJwt, verifyJwt } from '../jwt/verifyJwt';\nimport type { LoadClerkJWKFromRemoteOptions } from './keys';\nimport { loadClerkJwkFromPem, loadClerkJWKFromRemote } from './keys';\nimport { API_KEY_PREFIX, M2M_TOKEN_PREFIX, OAUTH_TOKEN_PREFIX } from './machine';\nimport type { MachineTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\n\n/**\n * @interface\n */\nexport type VerifyTokenOptions = Simplify<\n Omit<VerifyJwtOptions, 'key'> &\n Omit<LoadClerkJWKFromRemoteOptions, 'kid'> & {\n /**\n * Used to verify the session token in a networkless manner. Supply the PEM public key from the **[**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page -> Show JWT public key -> PEM Public Key** section in the Clerk Dashboard. **It's recommended to use [the environment variable](https://clerk.com/docs/guides/development/clerk-environment-variables) instead.** For more information, refer to [Manual JWT verification](https://clerk.com/docs/guides/sessions/manual-jwt-verification).\n */\n jwtKey?: string;\n }\n>;\n\n/**\n * > [!WARNING]\n * > This is a lower-level method intended for more advanced use-cases. It's recommended to use [`authenticateRequest()`](https://clerk.com/docs/reference/backend/authenticate-request), which fully authenticates a token passed from the `request` object.\n *\n * Verifies a Clerk-generated token signature. Networkless if the `jwtKey` is provided. Otherwise, performs a network call to retrieve the JWKS from the [Backend API](https://clerk.com/docs/reference/backend-api/tag/JWKS#operation/GetJWKS){{ target: '_blank' }}.\n *\n * @param token - The token to verify.\n * @param options - Options for verifying the token. It is recommended to set these options as [environment variables](/docs/guides/development/clerk-environment-variables#api-and-sdk-configuration) where possible, and then pass them to the function. For example, you can set the `secretKey` option using the `CLERK_SECRET_KEY` environment variable, and then pass it to the function like this: `verifyToken(token, { secretKey: process.env.CLERK_SECRET_KEY })`.\n *\n * @displayFunctionSignature\n * @hideReturns\n *\n * @example\n *\n * The following example demonstrates how to use the [JavaScript Backend SDK](https://clerk.com/docs/reference/backend/overview) to verify the token signature.\n *\n * In the following example:\n *\n * 1. The **JWKS Public Key** from the Clerk Dashboard is set in the environment variable `CLERK_JWT_KEY`.\n * 1. The session token is retrieved from the `__session` cookie or the Authorization header.\n * 1. The token is verified in a networkless manner by passing the `jwtKey` prop.\n * 1. The `authorizedParties` prop is passed to verify that the session token is generated from the expected frontend application.\n * 1. If the token is valid, the response contains the verified token.\n *\n * ```ts\n * import { verifyToken } from '@clerk/backend'\n * import { cookies } from 'next/headers'\n *\n * export async function GET(request: Request) {\n * const cookieStore = cookies()\n * const sessToken = cookieStore.get('__session')?.value\n * const bearerToken = request.headers.get('Authorization')?.replace('Bearer ', '')\n * const token = sessToken || bearerToken\n *\n * if (!token) {\n * return Response.json({ error: 'Token not found. User must sign in.' }, { status: 401 })\n * }\n *\n * try {\n * const verifiedToken = await verifyToken(token, {\n * jwtKey: process.env.CLERK_JWT_KEY,\n * authorizedParties: ['http://localhost:3001', 'api.example.com'], // Replace with your authorized parties\n * })\n *\n * return Response.json({ verifiedToken })\n * } catch (error) {\n * return Response.json({ error: 'Token not verified.' }, { status: 401 })\n * }\n * }\n * ```\n *\n * If the token is valid, the response will contain a JSON object that looks something like this:\n *\n * ```json\n * {\n * \"verifiedToken\": {\n * \"azp\": \"http://localhost:3000\",\n * \"exp\": 1687906422,\n * \"iat\": 1687906362,\n * \"iss\": \"https://magical-marmoset-51.clerk.accounts.dev\",\n * \"nbf\": 1687906352,\n * \"sid\": \"sess_2Ro7e2IxrffdqBboq8KfB6eGbIy\",\n * \"sub\": \"user_2RfWKJREkjKbHZy0Wqa5qrHeAnb\"\n * }\n * }\n * ```\n */\nexport async function verifyToken(\n token: string,\n options: VerifyTokenOptions,\n): Promise<JwtReturnType<JwtPayload, TokenVerificationError>> {\n const { data: decodedResult, errors } = decodeJwt(token);\n if (errors) {\n return { errors };\n }\n\n const { header } = decodedResult;\n const { kid } = header;\n\n try {\n let key: JsonWebKey;\n\n if (options.jwtKey) {\n key = loadClerkJwkFromPem({ kid, pem: options.jwtKey });\n } else if (options.secretKey) {\n // Fetch JWKS from Backend API using the key\n key = await loadClerkJWKFromRemote({ ...options, kid });\n } else {\n return {\n errors: [\n new TokenVerificationError({\n action: TokenVerificationErrorAction.SetClerkJWTKey,\n message: 'Failed to resolve JWK during verification.',\n reason: TokenVerificationErrorReason.JWKFailedToResolve,\n }),\n ],\n };\n }\n\n return await verifyJwt(token, { ...options, key });\n } catch (error) {\n return { errors: [error as TokenVerificationError] };\n }\n}\n\n/**\n * Handles errors from Clerk API responses for machine tokens\n * @param tokenType - The type of machine token\n * @param err - The error from the Clerk API\n * @param notFoundMessage - Custom message for 404 errors\n */\nfunction handleClerkAPIError(\n tokenType: MachineTokenType,\n err: any,\n notFoundMessage: string,\n): MachineTokenReturnType<any, MachineTokenVerificationError> {\n if (isClerkAPIResponseError(err)) {\n let code: MachineTokenVerificationErrorCode;\n let message: string;\n\n switch (err.status) {\n case 401:\n code = MachineTokenVerificationErrorCode.InvalidSecretKey;\n message = err.errors[0]?.message || 'Invalid secret key';\n break;\n case 404:\n code = MachineTokenVerificationErrorCode.TokenInvalid;\n message = notFoundMessage;\n break;\n default:\n code = MachineTokenVerificationErrorCode.UnexpectedError;\n message = 'Unexpected error';\n }\n\n return {\n data: undefined,\n tokenType,\n errors: [\n new MachineTokenVerificationError({\n message,\n code,\n status: err.status,\n }),\n ],\n };\n }\n\n return {\n data: undefined,\n tokenType,\n errors: [\n new MachineTokenVerificationError({\n message: 'Unexpected error',\n code: MachineTokenVerificationErrorCode.UnexpectedError,\n status: err.status,\n }),\n ],\n };\n}\n\nasync function verifyM2MToken(\n token: string,\n options: VerifyTokenOptions & { machineSecretKey?: string },\n): Promise<MachineTokenReturnType<M2MToken, MachineTokenVerificationError>> {\n try {\n const client = createBackendApiClient(options);\n const verifiedToken = await client.m2m.verify({ token });\n return { data: verifiedToken, tokenType: TokenType.M2MToken, errors: undefined };\n } catch (err: any) {\n return handleClerkAPIError(TokenType.M2MToken, err, 'Machine token not found');\n }\n}\n\nasync function verifyOAuthToken(\n accessToken: string,\n options: VerifyTokenOptions,\n): Promise<MachineTokenReturnType<IdPOAuthAccessToken, MachineTokenVerificationError>> {\n try {\n const client = createBackendApiClient(options);\n const verifiedToken = await client.idPOAuthAccessToken.verify(accessToken);\n return { data: verifiedToken, tokenType: TokenType.OAuthToken, errors: undefined };\n } catch (err: any) {\n return handleClerkAPIError(TokenType.OAuthToken, err, 'OAuth token not found');\n }\n}\n\nasync function verifyAPIKey(\n secret: string,\n options: VerifyTokenOptions,\n): Promise<MachineTokenReturnType<APIKey, MachineTokenVerificationError>> {\n try {\n const client = createBackendApiClient(options);\n const verifiedToken = await client.apiKeys.verify(secret);\n return { data: verifiedToken, tokenType: TokenType.ApiKey, errors: undefined };\n } catch (err: any) {\n return handleClerkAPIError(TokenType.ApiKey, err, 'API key not found');\n }\n}\n\n/**\n * Verifies any type of machine token by detecting its type from the prefix.\n *\n * @param token - The token to verify (e.g. starts with \"m2m_\", \"oauth_\", \"api_key_\", etc.)\n * @param options - Options including secretKey for BAPI authorization\n */\nexport async function verifyMachineAuthToken(token: string, options: VerifyTokenOptions) {\n if (token.startsWith(M2M_TOKEN_PREFIX)) {\n return verifyM2MToken(token, options);\n }\n if (token.startsWith(OAUTH_TOKEN_PREFIX)) {\n return verifyOAuthToken(token, options);\n }\n if (token.startsWith(API_KEY_PREFIX)) {\n return verifyAPIKey(token, options);\n }\n\n throw new Error('Unknown machine token type');\n}\n","import { constants, SUPPORTED_BAPI_VERSION } from '../constants';\nimport { TokenVerificationError, TokenVerificationErrorAction, TokenVerificationErrorReason } from '../errors';\nimport type { VerifyJwtOptions } from '../jwt';\nimport { assertHeaderAlgorithm, assertHeaderType } from '../jwt/assertions';\nimport { decodeJwt, hasValidSignature } from '../jwt/verifyJwt';\nimport type { AuthenticateContext } from './authenticateContext';\nimport type { SignedInState, SignedOutState } from './authStatus';\nimport { AuthErrorReason, signedIn, signedOut } from './authStatus';\nimport { getCookieName, getCookieValue } from './cookie';\nimport { loadClerkJwkFromPem, loadClerkJWKFromRemote } from './keys';\nimport type { OrganizationMatcher } from './organizationMatcher';\nimport { TokenType } from './tokenTypes';\nimport type { OrganizationSyncOptions, OrganizationSyncTarget } from './types';\nimport type { VerifyTokenOptions } from './verify';\nimport { verifyToken } from './verify';\n\nasync function verifyHandshakeJwt(token: string, { key }: VerifyJwtOptions): Promise<{ handshake: string[] }> {\n const { data: decoded, errors } = decodeJwt(token);\n if (errors) {\n throw errors[0];\n }\n\n const { header, payload } = decoded;\n\n // Header verifications\n const { typ, alg } = header;\n\n assertHeaderType(typ);\n assertHeaderAlgorithm(alg);\n\n const { data: signatureValid, errors: signatureErrors } = await hasValidSignature(decoded, key);\n if (signatureErrors) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Error verifying handshake token. ${signatureErrors[0]}`,\n });\n }\n\n if (!signatureValid) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalidSignature,\n message: 'Handshake signature is invalid.',\n });\n }\n\n return payload as unknown as { handshake: string[] };\n}\n\n/**\n * Similar to our verifyToken flow for Clerk-issued JWTs, but this verification flow is for our signed handshake payload.\n * The handshake payload requires fewer verification steps.\n */\nexport async function verifyHandshakeToken(\n token: string,\n options: VerifyTokenOptions,\n): Promise<{ handshake: string[] }> {\n const { secretKey, apiUrl, apiVersion, jwksCacheTtlInMs, jwtKey, skipJwksCache } = options;\n\n const { data, errors } = decodeJwt(token);\n if (errors) {\n throw errors[0];\n }\n\n const { kid } = data.header;\n\n let key;\n\n if (jwtKey) {\n key = loadClerkJwkFromPem({ kid, pem: jwtKey });\n } else if (secretKey) {\n // Fetch JWKS from Backend API using the key\n key = await loadClerkJWKFromRemote({ secretKey, apiUrl, apiVersion, kid, jwksCacheTtlInMs, skipJwksCache });\n } else {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.SetClerkJWTKey,\n message: 'Failed to resolve JWK during handshake verification.',\n reason: TokenVerificationErrorReason.JWKFailedToResolve,\n });\n }\n\n return verifyHandshakeJwt(token, { key });\n}\n\nexport class HandshakeService {\n private readonly authenticateContext: AuthenticateContext;\n private readonly organizationMatcher: OrganizationMatcher;\n private readonly options: { organizationSyncOptions?: OrganizationSyncOptions };\n\n constructor(\n authenticateContext: AuthenticateContext,\n options: { organizationSyncOptions?: OrganizationSyncOptions },\n organizationMatcher: OrganizationMatcher,\n ) {\n this.authenticateContext = authenticateContext;\n this.options = options;\n this.organizationMatcher = organizationMatcher;\n }\n\n /**\n * Determines if a request is eligible for handshake based on its headers\n *\n * Currently, a request is only eligible for a handshake if we can say it's *probably* a request for a document, not a fetch or some other exotic request.\n * This heuristic should give us a reliable enough signal for browsers that support `Sec-Fetch-Dest` and for those that don't.\n *\n * @returns boolean indicating if the request is eligible for handshake\n */\n isRequestEligibleForHandshake(): boolean {\n const { accept, secFetchDest } = this.authenticateContext;\n\n // NOTE: we could also check sec-fetch-mode === navigate here, but according to the spec, sec-fetch-dest: document should indicate that the request is the data of a user navigation.\n // Also, we check for 'iframe' because it's the value set when a doc request is made by an iframe.\n if (secFetchDest === 'document' || secFetchDest === 'iframe') {\n return true;\n }\n\n if (!secFetchDest && accept?.startsWith('text/html')) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Builds the redirect headers for a handshake request\n * @param reason - The reason for the handshake (e.g. 'session-token-expired')\n * @returns Headers object containing the Location header for redirect\n * @throws Error if clerkUrl is missing in authenticateContext\n */\n buildRedirectToHandshake(reason: string): Headers {\n if (!this.authenticateContext?.clerkUrl) {\n throw new Error('Missing clerkUrl in authenticateContext');\n }\n\n const redirectUrl = this.removeDevBrowserFromURL(this.authenticateContext.clerkUrl);\n\n let baseUrl = this.authenticateContext.frontendApi.startsWith('http')\n ? this.authenticateContext.frontendApi\n : `https://${this.authenticateContext.frontendApi}`;\n\n baseUrl = baseUrl.replace(/\\/+$/, '') + '/';\n\n const url = new URL('v1/client/handshake', baseUrl);\n url.searchParams.append('redirect_url', redirectUrl?.href || '');\n url.searchParams.append('__clerk_api_version', SUPPORTED_BAPI_VERSION);\n url.searchParams.append(\n constants.QueryParameters.SuffixedCookies,\n this.authenticateContext.usesSuffixedCookies().toString(),\n );\n url.searchParams.append(constants.QueryParameters.HandshakeReason, reason);\n url.searchParams.append(constants.QueryParameters.HandshakeFormat, 'nonce');\n\n if (this.authenticateContext.instanceType === 'development' && this.authenticateContext.devBrowserToken) {\n url.searchParams.append(constants.QueryParameters.DevBrowser, this.authenticateContext.devBrowserToken);\n }\n\n const toActivate = this.getOrganizationSyncTarget(this.authenticateContext.clerkUrl, this.organizationMatcher);\n if (toActivate) {\n const params = this.getOrganizationSyncQueryParams(toActivate);\n params.forEach((value, key) => {\n url.searchParams.append(key, value);\n });\n }\n\n return new Headers({ [constants.Headers.Location]: url.href });\n }\n\n /**\n * Gets cookies from either a handshake nonce or a handshake token\n * @returns Promise resolving to string array of cookie directives\n */\n public async getCookiesFromHandshake(): Promise<string[]> {\n const cookiesToSet: string[] = [];\n\n if (this.authenticateContext.handshakeNonce) {\n try {\n const handshakePayload = await this.authenticateContext.apiClient?.clients.getHandshakePayload({\n nonce: this.authenticateContext.handshakeNonce,\n });\n if (handshakePayload) {\n cookiesToSet.push(...handshakePayload.directives);\n }\n } catch (error) {\n console.error('Clerk: HandshakeService: error getting handshake payload:', error);\n }\n } else if (this.authenticateContext.handshakeToken) {\n const handshakePayload = await verifyHandshakeToken(\n this.authenticateContext.handshakeToken,\n this.authenticateContext,\n );\n if (handshakePayload && Array.isArray(handshakePayload.handshake)) {\n cookiesToSet.push(...handshakePayload.handshake);\n }\n }\n\n return cookiesToSet;\n }\n\n /**\n * Resolves a handshake request by verifying the handshake token and setting appropriate cookies\n * @returns Promise resolving to either a SignedInState or SignedOutState\n * @throws Error if handshake verification fails or if there are issues with the session token\n */\n async resolveHandshake(): Promise<SignedInState | SignedOutState> {\n const headers = new Headers({\n 'Access-Control-Allow-Origin': 'null',\n 'Access-Control-Allow-Credentials': 'true',\n });\n\n const cookiesToSet = await this.getCookiesFromHandshake();\n\n let sessionToken = '';\n cookiesToSet.forEach((x: string) => {\n headers.append('Set-Cookie', x);\n if (getCookieName(x).startsWith(constants.Cookies.Session)) {\n sessionToken = getCookieValue(x);\n }\n });\n\n if (this.authenticateContext.instanceType === 'development') {\n const newUrl = new URL(this.authenticateContext.clerkUrl);\n newUrl.searchParams.delete(constants.QueryParameters.Handshake);\n newUrl.searchParams.delete(constants.QueryParameters.HandshakeHelp);\n newUrl.searchParams.delete(constants.QueryParameters.DevBrowser);\n newUrl.searchParams.delete(constants.QueryParameters.HandshakeNonce);\n headers.append(constants.Headers.Location, newUrl.toString());\n headers.set(constants.Headers.CacheControl, 'no-store');\n }\n\n if (sessionToken === '') {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext: this.authenticateContext,\n reason: AuthErrorReason.SessionTokenMissing,\n message: '',\n headers,\n });\n }\n\n const { data, errors: [error] = [] } = await verifyToken(sessionToken, this.authenticateContext);\n if (data) {\n return signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext: this.authenticateContext,\n sessionClaims: data,\n headers,\n token: sessionToken,\n });\n }\n\n if (\n this.authenticateContext.instanceType === 'development' &&\n (error?.reason === TokenVerificationErrorReason.TokenExpired ||\n error?.reason === TokenVerificationErrorReason.TokenNotActiveYet ||\n error?.reason === TokenVerificationErrorReason.TokenIatInTheFuture)\n ) {\n // Create a new error object with the same properties\n const developmentError = new TokenVerificationError({\n action: error.action,\n message: error.message,\n reason: error.reason,\n });\n // Set the tokenCarrier after construction\n developmentError.tokenCarrier = 'cookie';\n\n console.error(\n `Clerk: Clock skew detected. This usually means that your system clock is inaccurate. Clerk will attempt to account for the clock skew in development.\n\nTo resolve this issue, make sure your system's clock is set to the correct time (e.g. turn off and on automatic time synchronization).\n\n---\n\n${developmentError.getFullMessage()}`,\n );\n\n const { data: retryResult, errors: [retryError] = [] } = await verifyToken(sessionToken, {\n ...this.authenticateContext,\n clockSkewInMs: 86_400_000,\n });\n if (retryResult) {\n return signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext: this.authenticateContext,\n sessionClaims: retryResult,\n headers,\n token: sessionToken,\n });\n }\n\n throw new Error(retryError?.message || 'Clerk: Handshake retry failed.');\n }\n\n throw new Error(error?.message || 'Clerk: Handshake failed.');\n }\n\n /**\n * Handles handshake token verification errors in development mode\n * @param error - The TokenVerificationError that occurred\n * @throws Error with a descriptive message about the verification failure\n */\n handleTokenVerificationErrorInDevelopment(error: TokenVerificationError): void {\n // In development, the handshake token is being transferred in the URL as a query parameter, so there is no\n // possibility of collision with a handshake token of another app running on the same local domain\n // (etc one app on localhost:3000 and one on localhost:3001).\n // Therefore, if the handshake token is invalid, it is likely that the user has switched Clerk keys locally.\n // We make sure to throw a descriptive error message and then stop the handshake flow in every case,\n // to avoid the possibility of an infinite loop.\n if (error.reason === TokenVerificationErrorReason.TokenInvalidSignature) {\n const msg = `Clerk: Handshake token verification failed due to an invalid signature. If you have switched Clerk keys locally, clear your cookies and try again.`;\n throw new Error(msg);\n }\n throw new Error(`Clerk: Handshake token verification failed: ${error.getFullMessage()}.`);\n }\n\n /**\n * Checks if a redirect loop is detected and sets headers to track redirect count\n * @param headers - The Headers object to modify\n * @returns boolean indicating if a redirect loop was detected (true) or if the request can proceed (false)\n */\n checkAndTrackRedirectLoop(headers: Headers): boolean {\n if (this.authenticateContext.handshakeRedirectLoopCounter === 3) {\n return true;\n }\n\n const newCounterValue = this.authenticateContext.handshakeRedirectLoopCounter + 1;\n const cookieName = constants.Cookies.RedirectCount;\n headers.append('Set-Cookie', `${cookieName}=${newCounterValue}; SameSite=Lax; HttpOnly; Max-Age=2`);\n return false;\n }\n\n private removeDevBrowserFromURL(url: URL): URL {\n const updatedURL = new URL(url);\n updatedURL.searchParams.delete(constants.QueryParameters.DevBrowser);\n updatedURL.searchParams.delete(constants.QueryParameters.LegacyDevBrowser);\n return updatedURL;\n }\n\n private getOrganizationSyncTarget(url: URL, matchers: OrganizationMatcher): OrganizationSyncTarget | null {\n return matchers.findTarget(url);\n }\n\n private getOrganizationSyncQueryParams(toActivate: OrganizationSyncTarget): Map<string, string> {\n const ret = new Map();\n if (toActivate.type === 'personalAccount') {\n ret.set('organization_id', '');\n }\n if (toActivate.type === 'organization') {\n if (toActivate.organizationId) {\n ret.set('organization_id', toActivate.organizationId);\n }\n if (toActivate.organizationSlug) {\n ret.set('organization_id', toActivate.organizationSlug);\n }\n }\n return ret;\n }\n}\n","import type { MatchFunction } from '@clerk/shared/pathToRegexp';\nimport { match } from '@clerk/shared/pathToRegexp';\n\nimport type { OrganizationSyncOptions, OrganizationSyncTarget } from './types';\n\nexport class OrganizationMatcher {\n private readonly organizationPattern: MatchFunction | null;\n private readonly personalAccountPattern: MatchFunction | null;\n\n constructor(options?: OrganizationSyncOptions) {\n this.organizationPattern = this.createMatcher(options?.organizationPatterns);\n this.personalAccountPattern = this.createMatcher(options?.personalAccountPatterns);\n }\n\n private createMatcher(pattern?: string[]): MatchFunction | null {\n if (!pattern) {\n return null;\n }\n try {\n return match(pattern);\n } catch (e) {\n throw new Error(`Invalid pattern \"${pattern}\": ${e}`);\n }\n }\n\n findTarget(url: URL): OrganizationSyncTarget | null {\n const orgTarget = this.findOrganizationTarget(url);\n if (orgTarget) {\n return orgTarget;\n }\n\n return this.findPersonalAccountTarget(url);\n }\n\n private findOrganizationTarget(url: URL): OrganizationSyncTarget | null {\n if (!this.organizationPattern) {\n return null;\n }\n\n try {\n const result = this.organizationPattern(url.pathname);\n if (!result || !('params' in result)) {\n return null;\n }\n\n const params = result.params as { id?: string; slug?: string };\n if (params.id) {\n return { type: 'organization', organizationId: params.id };\n }\n if (params.slug) {\n return { type: 'organization', organizationSlug: params.slug };\n }\n\n return null;\n } catch (e) {\n console.error('Failed to match organization pattern:', e);\n return null;\n }\n }\n\n private findPersonalAccountTarget(url: URL): OrganizationSyncTarget | null {\n if (!this.personalAccountPattern) {\n return null;\n }\n\n try {\n const result = this.personalAccountPattern(url.pathname);\n return result ? { type: 'personalAccount' } : null;\n } catch (e) {\n console.error('Failed to match personal account pattern:', e);\n return null;\n }\n }\n}\n","import type { JwtPayload } from '@clerk/shared/types';\n\nimport { constants } from '../constants';\nimport type { TokenCarrier } from '../errors';\nimport { MachineTokenVerificationError, TokenVerificationError, TokenVerificationErrorReason } from '../errors';\nimport { decodeJwt } from '../jwt/verifyJwt';\nimport { assertValidSecretKey } from '../util/optionsAssertions';\nimport { isDevelopmentFromSecretKey } from '../util/shared';\nimport type { AuthenticateContext } from './authenticateContext';\nimport { createAuthenticateContext } from './authenticateContext';\nimport type { SignedInAuthObject } from './authObjects';\nimport type { HandshakeState, RequestState, SignedInState, SignedOutState, UnauthenticatedState } from './authStatus';\nimport { AuthErrorReason, handshake, signedIn, signedOut, signedOutInvalidToken } from './authStatus';\nimport { createClerkRequest } from './clerkRequest';\nimport { getCookieName, getCookieValue } from './cookie';\nimport { HandshakeService } from './handshake';\nimport { getMachineTokenType, isMachineTokenByPrefix, isTokenTypeAccepted } from './machine';\nimport { OrganizationMatcher } from './organizationMatcher';\nimport type { MachineTokenType, SessionTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\nimport type { AuthenticateRequestOptions } from './types';\nimport { verifyMachineAuthToken, verifyToken } from './verify';\n\nexport const RefreshTokenErrorReason = {\n NonEligibleNoCookie: 'non-eligible-no-refresh-cookie',\n NonEligibleNonGet: 'non-eligible-non-get',\n InvalidSessionToken: 'invalid-session-token',\n MissingApiClient: 'missing-api-client',\n MissingSessionToken: 'missing-session-token',\n MissingRefreshToken: 'missing-refresh-token',\n ExpiredSessionTokenDecodeFailed: 'expired-session-token-decode-failed',\n ExpiredSessionTokenMissingSidClaim: 'expired-session-token-missing-sid-claim',\n FetchError: 'fetch-error',\n UnexpectedSDKError: 'unexpected-sdk-error',\n UnexpectedBAPIError: 'unexpected-bapi-error',\n} as const;\n\nfunction assertSignInUrlExists(signInUrl: string | undefined, key: string): asserts signInUrl is string {\n if (!signInUrl && isDevelopmentFromSecretKey(key)) {\n throw new Error(`Missing signInUrl. Pass a signInUrl for dev instances if an app is satellite`);\n }\n}\n\nfunction assertProxyUrlOrDomain(proxyUrlOrDomain: string | undefined) {\n if (!proxyUrlOrDomain) {\n throw new Error(`Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl`);\n }\n}\n\nfunction assertSignInUrlFormatAndOrigin(_signInUrl: string, origin: string) {\n let signInUrl: URL;\n try {\n signInUrl = new URL(_signInUrl);\n } catch {\n throw new Error(`The signInUrl needs to have a absolute url format.`);\n }\n\n if (signInUrl.origin === origin) {\n throw new Error(`The signInUrl needs to be on a different origin than your satellite application.`);\n }\n}\n\nfunction assertMachineSecretOrSecretKey(authenticateContext: AuthenticateContext) {\n if (!authenticateContext.machineSecretKey && !authenticateContext.secretKey) {\n throw new Error(\n 'Machine token authentication requires either a Machine secret key or a Clerk secret key. ' +\n 'Ensure a Clerk secret key or Machine secret key is set.',\n );\n }\n}\n\nfunction isRequestEligibleForRefresh(\n err: TokenVerificationError,\n authenticateContext: { refreshTokenInCookie?: string },\n request: Request,\n) {\n return (\n err.reason === TokenVerificationErrorReason.TokenExpired &&\n !!authenticateContext.refreshTokenInCookie &&\n request.method === 'GET'\n );\n}\n\nfunction checkTokenTypeMismatch(\n parsedTokenType: MachineTokenType,\n acceptsToken: NonNullable<AuthenticateRequestOptions['acceptsToken']>,\n authenticateContext: AuthenticateContext,\n): UnauthenticatedState<MachineTokenType> | null {\n const mismatch = !isTokenTypeAccepted(parsedTokenType, acceptsToken);\n if (mismatch) {\n const tokenTypeToReturn = (typeof acceptsToken === 'string' ? acceptsToken : parsedTokenType) as MachineTokenType;\n return signedOut({\n tokenType: tokenTypeToReturn,\n authenticateContext,\n reason: AuthErrorReason.TokenTypeMismatch,\n });\n }\n return null;\n}\n\nfunction isTokenTypeInAcceptedArray(acceptsToken: TokenType[], authenticateContext: AuthenticateContext): boolean {\n let parsedTokenType: TokenType | null = null;\n const { tokenInHeader } = authenticateContext;\n if (tokenInHeader) {\n if (isMachineTokenByPrefix(tokenInHeader)) {\n parsedTokenType = getMachineTokenType(tokenInHeader);\n } else {\n parsedTokenType = TokenType.SessionToken;\n }\n }\n const typeToCheck = parsedTokenType ?? TokenType.SessionToken;\n return isTokenTypeAccepted(typeToCheck, acceptsToken);\n}\n\nexport interface AuthenticateRequest {\n /**\n * @example\n * clerkClient.authenticateRequest(request, { acceptsToken: ['session_token', 'api_key'] });\n */\n <T extends readonly TokenType[]>(\n request: Request,\n options: AuthenticateRequestOptions & { acceptsToken: T },\n ): Promise<RequestState<T[number] | null>>;\n\n /**\n * @example\n * clerkClient.authenticateRequest(request, { acceptsToken: 'session_token' });\n */\n <T extends TokenType>(\n request: Request,\n options: AuthenticateRequestOptions & { acceptsToken: T },\n ): Promise<RequestState<T>>;\n\n /**\n * @example\n * clerkClient.authenticateRequest(request, { acceptsToken: 'any' });\n */\n (request: Request, options: AuthenticateRequestOptions & { acceptsToken: 'any' }): Promise<RequestState<TokenType>>;\n\n /**\n * @example\n * clerkClient.authenticateRequest(request);\n */\n (request: Request, options?: AuthenticateRequestOptions): Promise<RequestState<SessionTokenType>>;\n}\n\nexport const authenticateRequest: AuthenticateRequest = (async (\n request: Request,\n options: AuthenticateRequestOptions,\n): Promise<RequestState<TokenType> | UnauthenticatedState<null>> => {\n const authenticateContext = await createAuthenticateContext(createClerkRequest(request), options);\n\n // Default tokenType is session_token for backwards compatibility.\n const acceptsToken = options.acceptsToken ?? TokenType.SessionToken;\n\n // machine-to-machine tokens can accept a machine secret or a secret key\n if (acceptsToken !== TokenType.M2MToken) {\n assertValidSecretKey(authenticateContext.secretKey);\n\n if (authenticateContext.isSatellite) {\n assertSignInUrlExists(authenticateContext.signInUrl, authenticateContext.secretKey);\n if (authenticateContext.signInUrl && authenticateContext.origin) {\n assertSignInUrlFormatAndOrigin(authenticateContext.signInUrl, authenticateContext.origin);\n }\n assertProxyUrlOrDomain(authenticateContext.proxyUrl || authenticateContext.domain);\n }\n }\n\n // Make sure a machine secret or instance secret key is provided if acceptsToken is m2m_token\n if (acceptsToken === TokenType.M2MToken) {\n assertMachineSecretOrSecretKey(authenticateContext);\n }\n\n const organizationMatcher = new OrganizationMatcher(options.organizationSyncOptions);\n const handshakeService = new HandshakeService(\n authenticateContext,\n { organizationSyncOptions: options.organizationSyncOptions },\n organizationMatcher,\n );\n\n async function refreshToken(\n authenticateContext: AuthenticateContext,\n ): Promise<{ data: string[]; error: null } | { data: null; error: any }> {\n // To perform a token refresh, apiClient must be defined.\n if (!options.apiClient) {\n return {\n data: null,\n error: {\n message: 'An apiClient is needed to perform token refresh.',\n cause: { reason: RefreshTokenErrorReason.MissingApiClient },\n },\n };\n }\n const { sessionToken: expiredSessionToken, refreshTokenInCookie: refreshToken } = authenticateContext;\n if (!expiredSessionToken) {\n return {\n data: null,\n error: {\n message: 'Session token must be provided.',\n cause: { reason: RefreshTokenErrorReason.MissingSessionToken },\n },\n };\n }\n if (!refreshToken) {\n return {\n data: null,\n error: {\n message: 'Refresh token must be provided.',\n cause: { reason: RefreshTokenErrorReason.MissingRefreshToken },\n },\n };\n }\n // The token refresh endpoint requires a sessionId, so we decode that from the expired token.\n const { data: decodeResult, errors: decodedErrors } = decodeJwt(expiredSessionToken);\n if (!decodeResult || decodedErrors) {\n return {\n data: null,\n error: {\n message: 'Unable to decode the expired session token.',\n cause: { reason: RefreshTokenErrorReason.ExpiredSessionTokenDecodeFailed, errors: decodedErrors },\n },\n };\n }\n\n if (!decodeResult?.payload?.sid) {\n return {\n data: null,\n error: {\n message: 'Expired session token is missing the `sid` claim.',\n cause: { reason: RefreshTokenErrorReason.ExpiredSessionTokenMissingSidClaim },\n },\n };\n }\n\n try {\n // Perform the actual token refresh.\n const response = await options.apiClient.sessions.refreshSession(decodeResult.payload.sid, {\n format: 'cookie',\n suffixed_cookies: authenticateContext.usesSuffixedCookies(),\n expired_token: expiredSessionToken || '',\n refresh_token: refreshToken || '',\n request_origin: authenticateContext.clerkUrl.origin,\n // The refresh endpoint expects headers as Record<string, string[]>, so we need to transform it.\n request_headers: Object.fromEntries(Array.from(request.headers.entries()).map(([k, v]) => [k, [v]])),\n });\n return { data: response.cookies, error: null };\n } catch (err: any) {\n if (err?.errors?.length) {\n if (err.errors[0].code === 'unexpected_error') {\n return {\n data: null,\n error: {\n message: `Fetch unexpected error`,\n cause: { reason: RefreshTokenErrorReason.FetchError, errors: err.errors },\n },\n };\n }\n return {\n data: null,\n error: {\n message: err.errors[0].code,\n cause: { reason: err.errors[0].code, errors: err.errors },\n },\n };\n } else {\n return {\n data: null,\n error: {\n message: `Unexpected Server/BAPI error`,\n cause: { reason: RefreshTokenErrorReason.UnexpectedBAPIError, errors: [err] },\n },\n };\n }\n }\n }\n\n async function attemptRefresh(\n authenticateContext: AuthenticateContext,\n ): Promise<\n | { data: { jwtPayload: JwtPayload; sessionToken: string; headers: Headers }; error: null }\n | { data: null; error: any }\n > {\n const { data: cookiesToSet, error } = await refreshToken(authenticateContext);\n if (!cookiesToSet || cookiesToSet.length === 0) {\n return { data: null, error };\n }\n\n const headers = new Headers();\n let sessionToken = '';\n cookiesToSet.forEach((x: string) => {\n headers.append('Set-Cookie', x);\n if (getCookieName(x).startsWith(constants.Cookies.Session)) {\n sessionToken = getCookieValue(x);\n }\n });\n\n // Since we're going to return a signedIn response, we need to decode the data from the new sessionToken.\n const { data: jwtPayload, errors } = await verifyToken(sessionToken, authenticateContext);\n if (errors) {\n return {\n data: null,\n error: {\n message: `Clerk: unable to verify refreshed session token.`,\n cause: { reason: RefreshTokenErrorReason.InvalidSessionToken, errors },\n },\n };\n }\n return { data: { jwtPayload, sessionToken, headers }, error: null };\n }\n\n function handleMaybeHandshakeStatus(\n authenticateContext: AuthenticateContext,\n reason: string,\n message: string,\n headers?: Headers,\n ): SignedInState | SignedOutState | HandshakeState {\n if (!handshakeService.isRequestEligibleForHandshake()) {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason,\n message,\n });\n }\n\n // Right now the only usage of passing in different headers is for multi-domain sync, which redirects somewhere else.\n // In the future if we want to decorate the handshake redirect with additional headers per call we need to tweak this logic.\n const handshakeHeaders = headers ?? handshakeService.buildRedirectToHandshake(reason);\n\n // Chrome aggressively caches inactive tabs. If we don't set the header here,\n // all 307 redirects will be cached and the handshake will end up in an infinite loop.\n if (handshakeHeaders.get(constants.Headers.Location)) {\n handshakeHeaders.set(constants.Headers.CacheControl, 'no-store');\n }\n\n // Introduce the mechanism to protect for infinite handshake redirect loops\n // using a cookie and returning true if it's infinite redirect loop or false if we can\n // proceed with triggering handshake.\n const isRedirectLoop = handshakeService.checkAndTrackRedirectLoop(handshakeHeaders);\n if (isRedirectLoop) {\n const msg = `Clerk: Refreshing the session token resulted in an infinite redirect loop. This usually means that your Clerk instance keys do not match - make sure to copy the correct publishable and secret keys from the Clerk dashboard.`;\n console.log(msg);\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason,\n message,\n });\n }\n\n return handshake(authenticateContext, reason, message, handshakeHeaders);\n }\n\n /**\n * Determines if a handshake must occur to resolve a mismatch between the organization as specified\n * by the URL (according to the options) and the actual active organization on the session.\n *\n * @returns {HandshakeState | SignedOutState | null} - The function can return the following:\n * - {HandshakeState}: If a handshake is needed to resolve the mismatched organization.\n * - {SignedOutState}: If a handshake is required but cannot be performed.\n * - {null}: If no action is required.\n */\n function handleMaybeOrganizationSyncHandshake(\n authenticateContext: AuthenticateContext,\n auth: SignedInAuthObject,\n ): HandshakeState | SignedOutState | null {\n const organizationSyncTarget = organizationMatcher.findTarget(authenticateContext.clerkUrl);\n if (!organizationSyncTarget) {\n return null;\n }\n let mustActivate = false;\n if (organizationSyncTarget.type === 'organization') {\n // Activate an org by slug?\n if (organizationSyncTarget.organizationSlug && organizationSyncTarget.organizationSlug !== auth.orgSlug) {\n mustActivate = true;\n }\n // Activate an org by ID?\n if (organizationSyncTarget.organizationId && organizationSyncTarget.organizationId !== auth.orgId) {\n mustActivate = true;\n }\n }\n // Activate the personal account?\n if (organizationSyncTarget.type === 'personalAccount' && auth.orgId) {\n mustActivate = true;\n }\n if (!mustActivate) {\n return null;\n }\n if (authenticateContext.handshakeRedirectLoopCounter >= 3) {\n // We have an organization that needs to be activated, but this isn't our first time redirecting.\n // This is because we attempted to activate the organization previously, but the organization\n // must not have been valid (either not found, or not valid for this user), and gave us back\n // a null organization. We won't re-try the handshake, and leave it to the server component to handle.\n console.warn(\n 'Clerk: Organization activation handshake loop detected. This is likely due to an invalid organization ID or slug. Skipping organization activation.',\n );\n return null;\n }\n const handshakeState = handleMaybeHandshakeStatus(\n authenticateContext,\n AuthErrorReason.ActiveOrganizationMismatch,\n '',\n );\n if (handshakeState.status !== 'handshake') {\n // Currently, this is only possible if we're in a redirect loop, but the above check should guard against that.\n return null;\n }\n return handshakeState;\n }\n\n async function authenticateRequestWithTokenInHeader() {\n const { tokenInHeader } = authenticateContext;\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { data, errors } = await verifyToken(tokenInHeader!, authenticateContext);\n if (errors) {\n throw errors[0];\n }\n // use `await` to force this try/catch handle the signedIn invocation\n return signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n sessionClaims: data,\n headers: new Headers(),\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n token: tokenInHeader!,\n });\n } catch (err) {\n return handleSessionTokenError(err, 'header');\n }\n }\n\n async function authenticateRequestWithTokenInCookie() {\n const hasActiveClient = authenticateContext.clientUat;\n const hasSessionToken = !!authenticateContext.sessionTokenInCookie;\n const hasDevBrowserToken = !!authenticateContext.devBrowserToken;\n\n /**\n * If we have a handshakeToken, resolve the handshake and attempt to return a definitive signed in or signed out state.\n */\n if (authenticateContext.handshakeNonce || authenticateContext.handshakeToken) {\n try {\n return await handshakeService.resolveHandshake();\n } catch (error) {\n // In production, the handshake token is being transferred as a cookie, so there is a possibility of collision\n // with a handshake token of another app running on the same etld+1 domain.\n // For example, if one app is running on sub1.clerk.com and another on sub2.clerk.com, the handshake token\n // cookie for both apps will be set on etld+1 (clerk.com) so there's a possibility that one app will accidentally\n // use the handshake token of a different app during the handshake flow.\n // In this scenario, verification will fail with TokenInvalidSignature. In contrast to the development case,\n // we need to allow the flow to continue so the app eventually retries another handshake with the correct token.\n // We need to make sure, however, that we don't allow the flow to continue indefinitely, so we throw an error after X\n // retries to avoid an infinite loop. An infinite loop can happen if the customer switched Clerk keys for their prod app.\n\n // Check the handleTokenVerificationErrorInDevelopment method for the development case.\n if (error instanceof TokenVerificationError && authenticateContext.instanceType === 'development') {\n handshakeService.handleTokenVerificationErrorInDevelopment(error);\n } else {\n console.error('Clerk: unable to resolve handshake:', error);\n }\n }\n }\n const isRequestEligibleForMultiDomainSync =\n authenticateContext.isSatellite && authenticateContext.secFetchDest === 'document';\n\n /**\n * Begin multi-domain sync flows\n */\n if (authenticateContext.instanceType === 'production' && isRequestEligibleForMultiDomainSync) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SatelliteCookieNeedsSyncing, '');\n }\n\n // Multi-domain development sync flow\n if (\n authenticateContext.instanceType === 'development' &&\n isRequestEligibleForMultiDomainSync &&\n !authenticateContext.clerkUrl.searchParams.has(constants.QueryParameters.ClerkSynced)\n ) {\n // initiate MD sync\n\n // signInUrl exists, checked at the top of `authenticateRequest`\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const redirectURL = new URL(authenticateContext.signInUrl!);\n redirectURL.searchParams.append(\n constants.QueryParameters.ClerkRedirectUrl,\n authenticateContext.clerkUrl.toString(),\n );\n const headers = new Headers({ [constants.Headers.Location]: redirectURL.toString() });\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SatelliteCookieNeedsSyncing, '', headers);\n }\n\n // Multi-domain development sync flow - primary responds to syncing\n // IMPORTANT: This must come BEFORE dev-browser-sync check to avoid the root domain\n // triggering its own handshakes when it's in the middle of handling a satellite sync request\n const redirectUrl = new URL(authenticateContext.clerkUrl).searchParams.get(\n constants.QueryParameters.ClerkRedirectUrl,\n );\n\n if (authenticateContext.instanceType === 'development' && !authenticateContext.isSatellite && redirectUrl) {\n // Dev MD sync from primary, redirect back to satellite w/ dev browser query param\n const redirectBackToSatelliteUrl = new URL(redirectUrl);\n\n if (authenticateContext.devBrowserToken) {\n redirectBackToSatelliteUrl.searchParams.append(\n constants.QueryParameters.DevBrowser,\n authenticateContext.devBrowserToken,\n );\n }\n redirectBackToSatelliteUrl.searchParams.append(constants.QueryParameters.ClerkSynced, 'true');\n\n const headers = new Headers({ [constants.Headers.Location]: redirectBackToSatelliteUrl.toString() });\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.PrimaryRespondsToSyncing, '', headers);\n }\n /**\n * End multi-domain sync flows\n */\n\n /**\n * Otherwise, check for \"known unknown\" auth states that we can resolve with a handshake.\n */\n if (\n authenticateContext.instanceType === 'development' &&\n authenticateContext.clerkUrl.searchParams.has(constants.QueryParameters.DevBrowser)\n ) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.DevBrowserSync, '');\n }\n\n if (authenticateContext.instanceType === 'development' && !hasDevBrowserToken) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.DevBrowserMissing, '');\n }\n\n if (!hasActiveClient && !hasSessionToken) {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: AuthErrorReason.SessionTokenAndUATMissing,\n });\n }\n\n // This can eagerly run handshake since client_uat is SameSite=Strict in dev\n if (!hasActiveClient && hasSessionToken) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SessionTokenWithoutClientUAT, '');\n }\n\n if (hasActiveClient && !hasSessionToken) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.ClientUATWithoutSessionToken, '');\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { data: decodeResult, errors: decodedErrors } = decodeJwt(authenticateContext.sessionTokenInCookie!);\n\n if (decodedErrors) {\n return handleSessionTokenError(decodedErrors[0], 'cookie');\n }\n\n if (decodeResult.payload.iat < authenticateContext.clientUat) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SessionTokenIATBeforeClientUAT, '');\n }\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { data, errors } = await verifyToken(authenticateContext.sessionTokenInCookie!, authenticateContext);\n if (errors) {\n throw errors[0];\n }\n\n const signedInRequestState = signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n sessionClaims: data,\n headers: new Headers(),\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n token: authenticateContext.sessionTokenInCookie!,\n });\n\n // Check for cross-origin requests from satellite domains to primary domain\n const shouldForceHandshakeForCrossDomain =\n !authenticateContext.isSatellite && // We're on primary\n authenticateContext.secFetchDest === 'document' && // Document navigation\n authenticateContext.isCrossOriginReferrer() && // Came from different domain\n !authenticateContext.isKnownClerkReferrer() && // Not from Clerk accounts portal or FAPI\n authenticateContext.handshakeRedirectLoopCounter === 0; // Not in a redirect loop\n\n if (shouldForceHandshakeForCrossDomain) {\n return handleMaybeHandshakeStatus(\n authenticateContext,\n AuthErrorReason.PrimaryDomainCrossOriginSync,\n 'Cross-origin request from satellite domain requires handshake',\n );\n }\n\n const authObject = signedInRequestState.toAuth();\n // Org sync if necessary\n if (authObject.userId) {\n const handshakeRequestState = handleMaybeOrganizationSyncHandshake(authenticateContext, authObject);\n if (handshakeRequestState) {\n return handshakeRequestState;\n }\n }\n\n return signedInRequestState;\n } catch (err) {\n return handleSessionTokenError(err, 'cookie');\n }\n\n // Unreachable\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: AuthErrorReason.UnexpectedError,\n });\n }\n\n async function handleSessionTokenError(\n err: unknown,\n tokenCarrier: TokenCarrier,\n ): Promise<SignedInState | SignedOutState | HandshakeState> {\n if (!(err instanceof TokenVerificationError)) {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: AuthErrorReason.UnexpectedError,\n });\n }\n\n let refreshError: string | null;\n\n if (isRequestEligibleForRefresh(err, authenticateContext, request)) {\n const { data, error } = await attemptRefresh(authenticateContext);\n if (data) {\n return signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n sessionClaims: data.jwtPayload,\n headers: data.headers,\n token: data.sessionToken,\n });\n }\n\n // If there's any error, simply fallback to the handshake flow including the reason as a query parameter.\n if (error?.cause?.reason) {\n refreshError = error.cause.reason;\n } else {\n refreshError = RefreshTokenErrorReason.UnexpectedSDKError;\n }\n } else {\n if (request.method !== 'GET') {\n refreshError = RefreshTokenErrorReason.NonEligibleNonGet;\n } else if (!authenticateContext.refreshTokenInCookie) {\n refreshError = RefreshTokenErrorReason.NonEligibleNoCookie;\n } else {\n //refresh error is not applicable if token verification error is not 'session-token-expired'\n refreshError = null;\n }\n }\n\n err.tokenCarrier = tokenCarrier;\n\n const reasonToHandshake = [\n TokenVerificationErrorReason.TokenExpired,\n TokenVerificationErrorReason.TokenNotActiveYet,\n TokenVerificationErrorReason.TokenIatInTheFuture,\n ].includes(err.reason);\n\n if (reasonToHandshake) {\n return handleMaybeHandshakeStatus(\n authenticateContext,\n convertTokenVerificationErrorReasonToAuthErrorReason({ tokenError: err.reason, refreshError }),\n err.getFullMessage(),\n );\n }\n\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: err.reason,\n message: err.getFullMessage(),\n });\n }\n\n function handleMachineError(tokenType: MachineTokenType, err: unknown): UnauthenticatedState<MachineTokenType> {\n if (!(err instanceof MachineTokenVerificationError)) {\n return signedOut({\n tokenType,\n authenticateContext,\n reason: AuthErrorReason.UnexpectedError,\n });\n }\n\n return signedOut({\n tokenType,\n authenticateContext,\n reason: err.code,\n message: err.getFullMessage(),\n });\n }\n\n async function authenticateMachineRequestWithTokenInHeader() {\n const { tokenInHeader } = authenticateContext;\n // Use session token error handling if no token in header (default behavior)\n if (!tokenInHeader) {\n return handleSessionTokenError(new Error('Missing token in header'), 'header');\n }\n\n // Handle case where tokenType is any and the token is not a machine token\n if (!isMachineTokenByPrefix(tokenInHeader)) {\n return signedOut({\n tokenType: acceptsToken as TokenType,\n authenticateContext,\n reason: AuthErrorReason.TokenTypeMismatch,\n message: '',\n });\n }\n\n const parsedTokenType = getMachineTokenType(tokenInHeader);\n const mismatchState = checkTokenTypeMismatch(parsedTokenType, acceptsToken, authenticateContext);\n if (mismatchState) {\n return mismatchState;\n }\n\n const { data, tokenType, errors } = await verifyMachineAuthToken(tokenInHeader, authenticateContext);\n if (errors) {\n return handleMachineError(tokenType, errors[0]);\n }\n return signedIn({\n tokenType,\n authenticateContext,\n machineData: data,\n token: tokenInHeader,\n });\n }\n\n async function authenticateAnyRequestWithTokenInHeader() {\n const { tokenInHeader } = authenticateContext;\n // Use session token error handling if no token in header (default behavior)\n if (!tokenInHeader) {\n return handleSessionTokenError(new Error('Missing token in header'), 'header');\n }\n\n // Handle as a machine token\n if (isMachineTokenByPrefix(tokenInHeader)) {\n const parsedTokenType = getMachineTokenType(tokenInHeader);\n const mismatchState = checkTokenTypeMismatch(parsedTokenType, acceptsToken, authenticateContext);\n if (mismatchState) {\n return mismatchState;\n }\n\n const { data, tokenType, errors } = await verifyMachineAuthToken(tokenInHeader, authenticateContext);\n if (errors) {\n return handleMachineError(tokenType, errors[0]);\n }\n\n return signedIn({\n tokenType,\n authenticateContext,\n machineData: data,\n token: tokenInHeader,\n });\n }\n\n // Handle as a regular session token\n const { data, errors } = await verifyToken(tokenInHeader, authenticateContext);\n if (errors) {\n return handleSessionTokenError(errors[0], 'header');\n }\n\n return signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n sessionClaims: data,\n token: tokenInHeader,\n });\n }\n\n // If acceptsToken is an array, early check if the token is in the accepted array\n // to avoid unnecessary verification calls\n if (Array.isArray(acceptsToken)) {\n if (!isTokenTypeInAcceptedArray(acceptsToken, authenticateContext)) {\n return signedOutInvalidToken();\n }\n }\n\n if (authenticateContext.tokenInHeader) {\n if (acceptsToken === 'any') {\n return authenticateAnyRequestWithTokenInHeader();\n }\n if (acceptsToken === TokenType.SessionToken) {\n return authenticateRequestWithTokenInHeader();\n }\n return authenticateMachineRequestWithTokenInHeader();\n }\n\n // Machine requests cannot have the token in the cookie, it must be in header.\n if (\n acceptsToken === TokenType.OAuthToken ||\n acceptsToken === TokenType.ApiKey ||\n acceptsToken === TokenType.M2MToken\n ) {\n return signedOut({\n tokenType: acceptsToken,\n authenticateContext,\n reason: 'No token in header',\n });\n }\n\n return authenticateRequestWithTokenInCookie();\n}) as AuthenticateRequest;\n\n/**\n * @internal\n */\nexport const debugRequestState = (params: RequestState) => {\n const { isSignedIn, isAuthenticated, proxyUrl, reason, message, publishableKey, isSatellite, domain } = params;\n return { isSignedIn, isAuthenticated, proxyUrl, reason, message, publishableKey, isSatellite, domain };\n};\n\nconst convertTokenVerificationErrorReasonToAuthErrorReason = ({\n tokenError,\n refreshError,\n}: {\n tokenError: TokenVerificationErrorReason;\n refreshError: string | null;\n}): string => {\n switch (tokenError) {\n case TokenVerificationErrorReason.TokenExpired:\n return `${AuthErrorReason.SessionTokenExpired}-refresh-${refreshError}`;\n case TokenVerificationErrorReason.TokenNotActiveYet:\n return AuthErrorReason.SessionTokenNBF;\n case TokenVerificationErrorReason.TokenIatInTheFuture:\n return AuthErrorReason.SessionTokenIatInTheFuture;\n default:\n return AuthErrorReason.UnexpectedError;\n }\n};\n","import type { ApiClient } from '../api';\nimport { mergePreDefinedOptions } from '../util/mergePreDefinedOptions';\nimport type { AuthenticateRequest } from './request';\nimport { authenticateRequest as authenticateRequestOriginal, debugRequestState } from './request';\nimport type { AuthenticateRequestOptions } from './types';\n\ntype RunTimeOptions = Omit<AuthenticateRequestOptions, 'apiUrl' | 'apiVersion'>;\ntype BuildTimeOptions = Partial<\n Pick<\n AuthenticateRequestOptions,\n | 'apiUrl'\n | 'apiVersion'\n | 'audience'\n | 'domain'\n | 'isSatellite'\n | 'jwtKey'\n | 'proxyUrl'\n | 'publishableKey'\n | 'secretKey'\n | 'machineSecretKey'\n >\n>;\n\nconst defaultOptions = {\n secretKey: '',\n machineSecretKey: '',\n jwtKey: '',\n apiUrl: undefined,\n apiVersion: undefined,\n proxyUrl: '',\n publishableKey: '',\n isSatellite: false,\n domain: '',\n audience: '',\n} satisfies BuildTimeOptions;\n\n/**\n * @internal\n */\nexport type CreateAuthenticateRequestOptions = {\n options: BuildTimeOptions;\n apiClient: ApiClient;\n};\n\n/**\n * @internal\n */\nexport function createAuthenticateRequest(params: CreateAuthenticateRequestOptions) {\n const buildTimeOptions = mergePreDefinedOptions(defaultOptions, params.options);\n const apiClient = params.apiClient;\n\n const authenticateRequest: AuthenticateRequest = (request: Request, options: RunTimeOptions = {}) => {\n const { apiUrl, apiVersion } = buildTimeOptions;\n const runTimeOptions = mergePreDefinedOptions(buildTimeOptions, options);\n return authenticateRequestOriginal(request, {\n ...options,\n ...runTimeOptions,\n // We should add all the omitted props from options here (eg apiUrl / apiVersion)\n // to avoid runtime options override them.\n apiUrl,\n apiVersion,\n apiClient,\n });\n };\n\n return {\n authenticateRequest,\n debugRequestState,\n };\n}\n","import type { CreateBackendApiOptions, Organization, Session, User } from '../api';\nimport { createBackendApiClient } from '../api';\nimport type { AuthObject, SignedInAuthObject, SignedOutAuthObject } from '../tokens/authObjects';\n\ntype DecorateAuthWithResourcesOptions = {\n loadSession?: boolean;\n loadUser?: boolean;\n loadOrganization?: boolean;\n};\n\ntype WithResources<T> = T & {\n session?: Session | null;\n user?: User | null;\n organization?: Organization | null;\n};\n\n/**\n * @internal\n */\nexport const decorateObjectWithResources = async <T extends object>(\n obj: T,\n authObj: AuthObject,\n opts: CreateBackendApiOptions & DecorateAuthWithResourcesOptions,\n): Promise<WithResources<T>> => {\n const { loadSession, loadUser, loadOrganization } = opts || {};\n const { userId, sessionId, orgId } = authObj as SignedInAuthObject | SignedOutAuthObject;\n\n const { sessions, users, organizations } = createBackendApiClient({ ...opts });\n\n const [sessionResp, userResp, organizationResp] = await Promise.all([\n loadSession && sessionId ? sessions.getSession(sessionId) : Promise.resolve(undefined),\n loadUser && userId ? users.getUser(userId) : Promise.resolve(undefined),\n loadOrganization && orgId ? organizations.getOrganization({ organizationId: orgId }) : Promise.resolve(undefined),\n ]);\n\n const resources = stripPrivateDataFromObject({\n session: sessionResp,\n user: userResp,\n organization: organizationResp,\n });\n return Object.assign(obj, resources);\n};\n\n/**\n * @internal\n */\nexport function stripPrivateDataFromObject<T extends WithResources<object>>(authObject: T): T {\n const user = authObject.user ? { ...authObject.user } : authObject.user;\n const organization = authObject.organization ? { ...authObject.organization } : authObject.organization;\n prunePrivateMetadata(user);\n prunePrivateMetadata(organization);\n return { ...authObject, user, organization };\n}\n\nfunction prunePrivateMetadata(resource?: { private_metadata: any } | { privateMetadata: any } | null) {\n // Delete sensitive private metadata from resource before rendering in SSR\n if (resource) {\n if ('privateMetadata' in resource) {\n delete resource['privateMetadata'];\n }\n if ('private_metadata' in resource) {\n delete resource['private_metadata'];\n }\n }\n\n return resource;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,UAAU;AAChB,IAAM,cAAc;AAEpB,IAAM,aAAa,GAAG,gBAAY,IAAI,oCAAe;AACrD,IAAM,oCAAoC,IAAI;AAC9C,IAAM,yBAAyB;AAEtC,IAAM,aAAa;AAAA,EACjB,WAAW;AAAA,EACX,eAAe;AAAA,EACf,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,UAAU;AACZ;AAEA,IAAM,UAAU;AAAA,EACd,SAAS;AAAA,EACT,SAAS;AAAA,EACT,WAAW;AAAA,EACX,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,gBAAgB;AAClB;AAEA,IAAM,kBAAkB;AAAA,EACtB,aAAa;AAAA,EACb,iBAAiB;AAAA,EACjB,kBAAkB;AAAA;AAAA,EAElB,YAAY,QAAQ;AAAA,EACpB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U;AACZ,QAAI,qBAAqB,UAAU;AACjC,aAAO,SAAS,iBAAiB;AAAA,IACnC;AACA,QAAI,sBAAsB,UAAU;AAClC,aAAO,SAAS,kBAAkB;AAAA,IACpC;AAAA,EACF;AAEA,SAAO;AACT;;;AjHZA,kCAAiE;","names":["Headers","import_keys","crypto","import_buildAccountsBaseUrl","import_url","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","import_error","match","convertCase","Cookies","data","Cookies","sessionId","jwk","import_error","authenticateContext","refreshToken","data","errors","authenticateRequest"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal.ts","../src/constants.ts","../src/createRedirect.ts","../src/util/shared.ts","../src/util/mergePreDefinedOptions.ts","../src/errors.ts","../src/runtime.ts","../src/util/rfc4648.ts","../src/jwt/algorithms.ts","../src/jwt/assertions.ts","../src/jwt/cryptoKeys.ts","../src/jwt/verifyJwt.ts","../src/util/optionsAssertions.ts","../src/tokens/authenticateContext.ts","../src/tokens/tokenTypes.ts","../src/tokens/authObjects.ts","../src/util/path.ts","../src/api/endpoints/AbstractApi.ts","../src/api/endpoints/ActorTokenApi.ts","../src/api/endpoints/AccountlessApplicationsAPI.ts","../src/api/endpoints/AllowlistIdentifierApi.ts","../src/api/endpoints/APIKeysApi.ts","../src/api/endpoints/BetaFeaturesApi.ts","../src/api/endpoints/BlocklistIdentifierApi.ts","../src/api/endpoints/ClientApi.ts","../src/api/endpoints/DomainApi.ts","../src/api/endpoints/EmailAddressApi.ts","../src/api/endpoints/IdPOAuthAccessTokenApi.ts","../src/api/endpoints/InstanceApi.ts","../src/api/endpoints/InvitationApi.ts","../src/api/endpoints/MachineApi.ts","../src/api/endpoints/M2MTokenApi.ts","../src/api/endpoints/JwksApi.ts","../src/api/endpoints/JwtTemplatesApi.ts","../src/api/endpoints/OrganizationApi.ts","../src/api/endpoints/OAuthApplicationsApi.ts","../src/api/endpoints/PhoneNumberApi.ts","../src/api/endpoints/ProxyCheckApi.ts","../src/api/endpoints/RedirectUrlApi.ts","../src/api/endpoints/SamlConnectionApi.ts","../src/api/endpoints/SessionApi.ts","../src/api/endpoints/SignInTokenApi.ts","../src/api/endpoints/SignUpApi.ts","../src/api/endpoints/TestingTokenApi.ts","../src/api/endpoints/UserApi.ts","../src/api/endpoints/WaitlistEntryApi.ts","../src/api/endpoints/WebhookApi.ts","../src/api/endpoints/BillingApi.ts","../src/api/request.ts","../../../node_modules/.pnpm/map-obj@5.0.2/node_modules/map-obj/index.js","../../../node_modules/.pnpm/change-case@5.4.4/node_modules/change-case/src/index.ts","../../../node_modules/.pnpm/snakecase-keys@9.0.2/node_modules/snakecase-keys/index.js","../src/api/resources/AccountlessApplication.ts","../src/api/resources/ActorToken.ts","../src/api/resources/AllowlistIdentifier.ts","../src/api/resources/APIKey.ts","../src/api/resources/BlocklistIdentifier.ts","../src/api/resources/Session.ts","../src/api/resources/Client.ts","../src/api/resources/CnameTarget.ts","../src/api/resources/Cookies.ts","../src/api/resources/DeletedObject.ts","../src/api/resources/Domain.ts","../src/api/resources/Email.ts","../src/api/resources/IdentificationLink.ts","../src/api/resources/Verification.ts","../src/api/resources/EmailAddress.ts","../src/api/resources/Feature.ts","../src/api/resources/CommercePlan.ts","../src/api/resources/CommerceSubscriptionItem.ts","../src/api/resources/CommerceSubscription.ts","../src/api/resources/ExternalAccount.ts","../src/api/resources/IdPOAuthAccessToken.ts","../src/api/resources/Instance.ts","../src/api/resources/InstanceRestrictions.ts","../src/api/resources/InstanceSettings.ts","../src/api/resources/Invitation.ts","../src/api/resources/JSON.ts","../src/api/resources/JwtTemplate.ts","../src/api/resources/M2MToken.ts","../src/api/resources/Machine.ts","../src/api/resources/MachineScope.ts","../src/api/resources/MachineSecretKey.ts","../src/api/resources/OauthAccessToken.ts","../src/api/resources/OAuthApplication.ts","../src/api/resources/Organization.ts","../src/api/resources/OrganizationInvitation.ts","../src/api/resources/OrganizationMembership.ts","../src/api/resources/OrganizationSettings.ts","../src/api/resources/PhoneNumber.ts","../src/api/resources/ProxyCheck.ts","../src/api/resources/RedirectUrl.ts","../src/api/resources/SamlConnection.ts","../src/api/resources/SignInTokens.ts","../src/api/resources/SignUpAttempt.ts","../src/api/resources/SMSMessage.ts","../src/api/resources/Token.ts","../src/api/resources/Web3Wallet.ts","../src/api/resources/User.ts","../src/api/resources/WaitlistEntry.ts","../src/api/resources/Deserializer.ts","../src/api/factory.ts","../src/tokens/machine.ts","../src/tokens/authStatus.ts","../src/tokens/clerkRequest.ts","../src/tokens/clerkUrl.ts","../src/tokens/cookie.ts","../src/tokens/keys.ts","../src/tokens/verify.ts","../src/tokens/handshake.ts","../src/tokens/organizationMatcher.ts","../src/tokens/request.ts","../src/tokens/factory.ts","../src/util/decorateObjectWithResources.ts"],"sourcesContent":["export { constants } from './constants';\nexport { createRedirect } from './createRedirect';\nexport type { RedirectFun } from './createRedirect';\n\nexport type { CreateAuthenticateRequestOptions } from './tokens/factory';\nexport { createAuthenticateRequest } from './tokens/factory';\n\nexport { debugRequestState } from './tokens/request';\n\nexport type {\n AuthenticateRequestOptions,\n OrganizationSyncOptions,\n InferAuthObjectFromToken,\n InferAuthObjectFromTokenArray,\n GetAuthFn,\n AuthOptions,\n GetAuthFnNoRequest,\n} from './tokens/types';\n\nexport { TokenType } from './tokens/tokenTypes';\nexport type { SessionTokenType, MachineTokenType } from './tokens/tokenTypes';\n\nexport type {\n SignedInAuthObjectOptions,\n SignedInAuthObject,\n SignedOutAuthObject,\n AuthenticatedMachineObject,\n UnauthenticatedMachineObject,\n} from './tokens/authObjects';\nexport {\n makeAuthObjectSerializable,\n signedOutAuthObject,\n signedInAuthObject,\n authenticatedMachineObject,\n unauthenticatedMachineObject,\n invalidTokenAuthObject,\n getAuthObjectFromJwt,\n getAuthObjectForAcceptedToken,\n} from './tokens/authObjects';\n\nexport { AuthStatus } from './tokens/authStatus';\nexport type {\n RequestState,\n SignedInState,\n SignedOutState,\n AuthenticatedState,\n UnauthenticatedState,\n} from './tokens/authStatus';\n\nexport { decorateObjectWithResources, stripPrivateDataFromObject } from './util/decorateObjectWithResources';\n\nexport { createClerkRequest } from './tokens/clerkRequest';\nexport type { ClerkRequest } from './tokens/clerkRequest';\n\nexport { reverificationError, reverificationErrorResponse } from '@clerk/shared/authorization-errors';\n\nexport { verifyMachineAuthToken } from './tokens/verify';\n\nexport { isMachineTokenByPrefix, isMachineTokenType, getMachineTokenType, isTokenTypeAccepted } from './tokens/machine';\n","export const API_URL = 'https://api.clerk.com';\nexport const API_VERSION = 'v1';\n\nexport const USER_AGENT = `${PACKAGE_NAME}@${PACKAGE_VERSION}`;\nexport const MAX_CACHE_LAST_UPDATED_AT_SECONDS = 5 * 60;\nexport const SUPPORTED_BAPI_VERSION = '2025-11-10';\n\nconst Attributes = {\n AuthToken: '__clerkAuthToken',\n AuthSignature: '__clerkAuthSignature',\n AuthStatus: '__clerkAuthStatus',\n AuthReason: '__clerkAuthReason',\n AuthMessage: '__clerkAuthMessage',\n ClerkUrl: '__clerkUrl',\n} as const;\n\nconst Cookies = {\n Session: '__session',\n Refresh: '__refresh',\n ClientUat: '__client_uat',\n Handshake: '__clerk_handshake',\n DevBrowser: '__clerk_db_jwt',\n RedirectCount: '__clerk_redirect_count',\n HandshakeNonce: '__clerk_handshake_nonce',\n} as const;\n\nconst QueryParameters = {\n ClerkSynced: '__clerk_synced',\n SuffixedCookies: 'suffixed_cookies',\n ClerkRedirectUrl: '__clerk_redirect_url',\n // use the reference to Cookies to indicate that it's the same value\n DevBrowser: Cookies.DevBrowser,\n Handshake: Cookies.Handshake,\n HandshakeHelp: '__clerk_help',\n LegacyDevBrowser: '__dev_session',\n HandshakeReason: '__clerk_hs_reason',\n HandshakeNonce: Cookies.HandshakeNonce,\n HandshakeFormat: 'format',\n} as const;\n\nconst Headers = {\n Accept: 'accept',\n AuthMessage: 'x-clerk-auth-message',\n Authorization: 'authorization',\n AuthReason: 'x-clerk-auth-reason',\n AuthSignature: 'x-clerk-auth-signature',\n AuthStatus: 'x-clerk-auth-status',\n AuthToken: 'x-clerk-auth-token',\n CacheControl: 'cache-control',\n ClerkRedirectTo: 'x-clerk-redirect-to',\n ClerkRequestData: 'x-clerk-request-data',\n ClerkUrl: 'x-clerk-clerk-url',\n CloudFrontForwardedProto: 'cloudfront-forwarded-proto',\n ContentType: 'content-type',\n ContentSecurityPolicy: 'content-security-policy',\n ContentSecurityPolicyReportOnly: 'content-security-policy-report-only',\n EnableDebug: 'x-clerk-debug',\n ForwardedHost: 'x-forwarded-host',\n ForwardedPort: 'x-forwarded-port',\n ForwardedProto: 'x-forwarded-proto',\n Host: 'host',\n Location: 'location',\n Nonce: 'x-nonce',\n Origin: 'origin',\n Referrer: 'referer',\n SecFetchDest: 'sec-fetch-dest',\n SecFetchSite: 'sec-fetch-site',\n UserAgent: 'user-agent',\n ReportingEndpoints: 'reporting-endpoints',\n} as const;\n\nconst ContentTypes = {\n Json: 'application/json',\n} as const;\n\n/**\n * @internal\n */\nexport const constants = {\n Attributes,\n Cookies,\n Headers,\n ContentTypes,\n QueryParameters,\n} as const;\n\nexport type Constants = typeof constants;\n","import { buildAccountsBaseUrl } from '@clerk/shared/buildAccountsBaseUrl';\nimport type { SessionStatusClaim } from '@clerk/shared/types';\n\nimport { constants } from './constants';\nimport { errorThrower, parsePublishableKey } from './util/shared';\n\nconst buildUrl = (\n _baseUrl: string | URL,\n _targetUrl: string | URL,\n _returnBackUrl?: string | URL | null,\n _devBrowserToken?: string | null,\n) => {\n if (_baseUrl === '') {\n return legacyBuildUrl(_targetUrl.toString(), _returnBackUrl?.toString());\n }\n\n const baseUrl = new URL(_baseUrl);\n const returnBackUrl = _returnBackUrl ? new URL(_returnBackUrl, baseUrl) : undefined;\n const res = new URL(_targetUrl, baseUrl);\n const isCrossOriginRedirect = `${baseUrl.hostname}:${baseUrl.port}` !== `${res.hostname}:${res.port}`;\n\n if (returnBackUrl) {\n if (isCrossOriginRedirect) {\n returnBackUrl.searchParams.delete(constants.QueryParameters.ClerkSynced);\n }\n\n res.searchParams.set('redirect_url', returnBackUrl.toString());\n }\n // For cross-origin redirects, we need to pass the dev browser token for URL session syncing\n if (isCrossOriginRedirect && _devBrowserToken) {\n res.searchParams.set(constants.QueryParameters.DevBrowser, _devBrowserToken);\n }\n return res.toString();\n};\n\n/**\n * In v5, we deprecated the top-level redirectToSignIn and redirectToSignUp functions\n * in favor of the new auth().redirectToSignIn helpers\n * In order to allow for a smooth transition, we need to support the legacy redirectToSignIn for now\n * as we will remove it in v6.\n * In order to make sure that the legacy function works as expected, we will use legacyBuildUrl\n * to build the url if baseUrl is not provided (which is the case for legacy redirectToSignIn)\n * This function can be safely removed when we remove the legacy redirectToSignIn function\n */\nconst legacyBuildUrl = (targetUrl: string, redirectUrl?: string) => {\n let url;\n if (!targetUrl.startsWith('http')) {\n if (!redirectUrl || !redirectUrl.startsWith('http')) {\n throw new Error('destination url or return back url should be an absolute path url!');\n }\n\n const baseURL = new URL(redirectUrl);\n url = new URL(targetUrl, baseURL.origin);\n } else {\n url = new URL(targetUrl);\n }\n\n if (redirectUrl) {\n url.searchParams.set('redirect_url', redirectUrl);\n }\n\n return url.toString();\n};\n\ntype RedirectAdapter<RedirectReturn> = (url: string) => RedirectReturn;\ntype RedirectToParams = { returnBackUrl?: string | URL | null };\nexport type RedirectFun<ReturnType> = (params?: RedirectToParams) => ReturnType;\n\n/**\n * @internal\n */\ntype CreateRedirect = <ReturnType>(params: {\n publishableKey: string;\n devBrowserToken?: string;\n redirectAdapter: RedirectAdapter<ReturnType>;\n baseUrl: URL | string;\n signInUrl?: URL | string;\n signUpUrl?: URL | string;\n sessionStatus?: SessionStatusClaim | null;\n}) => {\n redirectToSignIn: RedirectFun<ReturnType>;\n redirectToSignUp: RedirectFun<ReturnType>;\n};\n\nexport const createRedirect: CreateRedirect = params => {\n const { publishableKey, redirectAdapter, signInUrl, signUpUrl, baseUrl, sessionStatus } = params;\n const parsedPublishableKey = parsePublishableKey(publishableKey);\n const frontendApi = parsedPublishableKey?.frontendApi;\n const isDevelopment = parsedPublishableKey?.instanceType === 'development';\n const accountsBaseUrl = buildAccountsBaseUrl(frontendApi);\n const hasPendingStatus = sessionStatus === 'pending';\n\n const redirectToTasks = (url: string | URL, { returnBackUrl }: RedirectToParams) => {\n return redirectAdapter(\n buildUrl(baseUrl, `${url}/tasks`, returnBackUrl, isDevelopment ? params.devBrowserToken : null),\n );\n };\n\n const redirectToSignUp = ({ returnBackUrl }: RedirectToParams = {}) => {\n if (!signUpUrl && !accountsBaseUrl) {\n errorThrower.throwMissingPublishableKeyError();\n }\n\n const accountsSignUpUrl = `${accountsBaseUrl}/sign-up`;\n\n // Allows redirection to SignInOrUp path\n function buildSignUpUrl(signIn: string | URL | undefined) {\n if (!signIn) {\n return;\n }\n const url = new URL(signIn, baseUrl);\n url.pathname = `${url.pathname}/create`;\n return url.toString();\n }\n\n const targetUrl = signUpUrl || buildSignUpUrl(signInUrl) || accountsSignUpUrl;\n\n if (hasPendingStatus) {\n return redirectToTasks(targetUrl, { returnBackUrl });\n }\n\n return redirectAdapter(buildUrl(baseUrl, targetUrl, returnBackUrl, isDevelopment ? params.devBrowserToken : null));\n };\n\n const redirectToSignIn = ({ returnBackUrl }: RedirectToParams = {}) => {\n if (!signInUrl && !accountsBaseUrl) {\n errorThrower.throwMissingPublishableKeyError();\n }\n\n const accountsSignInUrl = `${accountsBaseUrl}/sign-in`;\n const targetUrl = signInUrl || accountsSignInUrl;\n\n if (hasPendingStatus) {\n return redirectToTasks(targetUrl, { returnBackUrl });\n }\n\n return redirectAdapter(buildUrl(baseUrl, targetUrl, returnBackUrl, isDevelopment ? params.devBrowserToken : null));\n };\n\n return { redirectToSignUp, redirectToSignIn };\n};\n","export { deprecated, deprecatedProperty } from '@clerk/shared/deprecated';\nexport {\n getCookieSuffix,\n getSuffixedCookieName,\n isDevelopmentFromSecretKey,\n isProductionFromSecretKey,\n parsePublishableKey,\n} from '@clerk/shared/keys';\nexport { retry } from '@clerk/shared/retry';\nexport { addClerkPrefix, getClerkJsMajorVersionOrTag, getScriptUrl } from '@clerk/shared/url';\n\nimport { buildErrorThrower } from '@clerk/shared/error';\nimport { createDevOrStagingUrlCache } from '@clerk/shared/keys';\n// TODO: replace packageName with `${PACKAGE_NAME}@${PACKAGE_VERSION}` from tsup.config.ts\nexport const errorThrower = buildErrorThrower({ packageName: '@clerk/backend' });\n\nexport const { isDevOrStagingUrl } = createDevOrStagingUrlCache();\n","export function mergePreDefinedOptions<T extends Record<string, any>>(preDefinedOptions: T, options: Partial<T>): T {\n return Object.keys(preDefinedOptions).reduce(\n (obj: T, key: string) => {\n return { ...obj, [key]: options[key] || obj[key] };\n },\n { ...preDefinedOptions },\n );\n}\n","export type TokenCarrier = 'header' | 'cookie';\n\nexport const TokenVerificationErrorCode = {\n InvalidSecretKey: 'clerk_key_invalid',\n};\n\nexport type TokenVerificationErrorCode = (typeof TokenVerificationErrorCode)[keyof typeof TokenVerificationErrorCode];\n\nexport const TokenVerificationErrorReason = {\n TokenExpired: 'token-expired',\n TokenInvalid: 'token-invalid',\n TokenInvalidAlgorithm: 'token-invalid-algorithm',\n TokenInvalidAuthorizedParties: 'token-invalid-authorized-parties',\n TokenInvalidSignature: 'token-invalid-signature',\n TokenNotActiveYet: 'token-not-active-yet',\n TokenIatInTheFuture: 'token-iat-in-the-future',\n TokenVerificationFailed: 'token-verification-failed',\n InvalidSecretKey: 'secret-key-invalid',\n LocalJWKMissing: 'jwk-local-missing',\n RemoteJWKFailedToLoad: 'jwk-remote-failed-to-load',\n RemoteJWKInvalid: 'jwk-remote-invalid',\n RemoteJWKMissing: 'jwk-remote-missing',\n JWKFailedToResolve: 'jwk-failed-to-resolve',\n JWKKidMismatch: 'jwk-kid-mismatch',\n};\n\nexport type TokenVerificationErrorReason =\n (typeof TokenVerificationErrorReason)[keyof typeof TokenVerificationErrorReason];\n\nexport const TokenVerificationErrorAction = {\n ContactSupport: 'Contact support@clerk.com',\n EnsureClerkJWT: 'Make sure that this is a valid Clerk-generated JWT.',\n SetClerkJWTKey: 'Set the CLERK_JWT_KEY environment variable.',\n SetClerkSecretKey: 'Set the CLERK_SECRET_KEY environment variable.',\n EnsureClockSync: 'Make sure your system clock is in sync (e.g. turn off and on automatic time synchronization).',\n};\n\nexport type TokenVerificationErrorAction =\n (typeof TokenVerificationErrorAction)[keyof typeof TokenVerificationErrorAction];\n\nexport class TokenVerificationError extends Error {\n action?: TokenVerificationErrorAction;\n reason: TokenVerificationErrorReason;\n tokenCarrier?: TokenCarrier;\n\n constructor({\n action,\n message,\n reason,\n }: {\n action?: TokenVerificationErrorAction;\n message: string;\n reason: TokenVerificationErrorReason;\n }) {\n super(message);\n\n Object.setPrototypeOf(this, TokenVerificationError.prototype);\n\n this.reason = reason;\n this.message = message;\n this.action = action;\n }\n\n public getFullMessage() {\n return `${[this.message, this.action].filter(m => m).join(' ')} (reason=${this.reason}, token-carrier=${\n this.tokenCarrier\n })`;\n }\n}\n\nexport class SignJWTError extends Error {}\n\nexport const MachineTokenVerificationErrorCode = {\n TokenInvalid: 'token-invalid',\n InvalidSecretKey: 'secret-key-invalid',\n UnexpectedError: 'unexpected-error',\n} as const;\n\nexport type MachineTokenVerificationErrorCode =\n (typeof MachineTokenVerificationErrorCode)[keyof typeof MachineTokenVerificationErrorCode];\n\nexport class MachineTokenVerificationError extends Error {\n code: MachineTokenVerificationErrorCode;\n long_message?: string;\n status: number;\n\n constructor({ message, code, status }: { message: string; code: MachineTokenVerificationErrorCode; status: number }) {\n super(message);\n Object.setPrototypeOf(this, MachineTokenVerificationError.prototype);\n\n this.code = code;\n this.status = status;\n }\n\n public getFullMessage() {\n return `${this.message} (code=${this.code}, status=${this.status})`;\n }\n}\n","/**\n * This file exports APIs that vary across runtimes (i.e. Node & Browser - V8 isolates)\n * as a singleton object.\n *\n * Runtime polyfills are written in VanillaJS for now to avoid TS complication. Moreover,\n * due to this issue https://github.com/microsoft/TypeScript/issues/44848, there is not a good way\n * to tell Typescript which conditional import to use during build type.\n *\n * The Runtime type definition ensures type safety for now.\n * Runtime js modules are copied into dist folder with bash script.\n *\n * TODO: Support TS runtime modules\n */\n\n// @ts-ignore - These are package subpaths\nimport { webcrypto as crypto } from '#crypto';\n\ntype Runtime = {\n crypto: Crypto;\n fetch: typeof globalThis.fetch;\n AbortController: typeof globalThis.AbortController;\n Blob: typeof globalThis.Blob;\n FormData: typeof globalThis.FormData;\n Headers: typeof globalThis.Headers;\n Request: typeof globalThis.Request;\n Response: typeof globalThis.Response;\n};\n\n// Invoking the global.fetch without binding it first to the globalObject fails in\n// Cloudflare Workers with an \"Illegal Invocation\" error.\n//\n// The globalThis object is supported for Node >= 12.0.\n//\n// https://github.com/supabase/supabase/issues/4417\nconst globalFetch = fetch.bind(globalThis);\n\nexport const runtime: Runtime = {\n crypto,\n get fetch() {\n // We need to use the globalFetch for Cloudflare Workers but the fetch for testing\n return process.env.NODE_ENV === 'test' ? fetch : globalFetch;\n },\n AbortController: globalThis.AbortController,\n Blob: globalThis.Blob,\n FormData: globalThis.FormData,\n Headers: globalThis.Headers,\n Request: globalThis.Request,\n Response: globalThis.Response,\n};\n","/**\n * The base64url helper was extracted from the rfc4648 package\n * in order to resolve CSJ/ESM interoperability issues\n *\n * https://github.com/swansontec/rfc4648.js\n *\n * For more context please refer to:\n * - https://github.com/evanw/esbuild/issues/1719\n * - https://github.com/evanw/esbuild/issues/532\n * - https://github.com/swansontec/rollup-plugin-mjs-entry\n */\nexport const base64url = {\n parse(string: string, opts?: ParseOptions): Uint8Array {\n return parse(string, base64UrlEncoding, opts);\n },\n\n stringify(data: ArrayLike<number>, opts?: StringifyOptions): string {\n return stringify(data, base64UrlEncoding, opts);\n },\n};\n\nconst base64UrlEncoding: Encoding = {\n chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bits: 6,\n};\n\ninterface Encoding {\n bits: number;\n chars: string;\n codes?: { [char: string]: number };\n}\n\ninterface ParseOptions {\n loose?: boolean;\n out?: new (size: number) => { [index: number]: number };\n}\n\ninterface StringifyOptions {\n pad?: boolean;\n}\n\nfunction parse(string: string, encoding: Encoding, opts: ParseOptions = {}): Uint8Array {\n // Build the character lookup table:\n if (!encoding.codes) {\n encoding.codes = {};\n for (let i = 0; i < encoding.chars.length; ++i) {\n encoding.codes[encoding.chars[i]] = i;\n }\n }\n\n // The string must have a whole number of bytes:\n if (!opts.loose && (string.length * encoding.bits) & 7) {\n throw new SyntaxError('Invalid padding');\n }\n\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n\n // If we get a whole number of bytes, there is too much padding:\n if (!opts.loose && !(((string.length - end) * encoding.bits) & 7)) {\n throw new SyntaxError('Invalid padding');\n }\n }\n\n // Allocate the output:\n const out = new (opts.out ?? Uint8Array)(((end * encoding.bits) / 8) | 0) as Uint8Array;\n\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = encoding.codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError('Invalid character ' + string[i]);\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << encoding.bits) | value;\n bits += encoding.bits;\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= encoding.bits || 0xff & (buffer << (8 - bits))) {\n throw new SyntaxError('Unexpected end of data');\n }\n\n return out;\n}\n\nfunction stringify(data: ArrayLike<number>, encoding: Encoding, opts: StringifyOptions = {}): string {\n const { pad = true } = opts;\n const mask = (1 << encoding.bits) - 1;\n let out = '';\n\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | (0xff & data[i]);\n bits += 8;\n\n // Write out as much as we can:\n while (bits > encoding.bits) {\n bits -= encoding.bits;\n out += encoding.chars[mask & (buffer >> bits)];\n }\n }\n\n // Partial character:\n if (bits) {\n out += encoding.chars[mask & (buffer << (encoding.bits - bits))];\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while ((out.length * encoding.bits) & 7) {\n out += '=';\n }\n }\n\n return out;\n}\n","const algToHash: Record<string, string> = {\n RS256: 'SHA-256',\n RS384: 'SHA-384',\n RS512: 'SHA-512',\n};\nconst RSA_ALGORITHM_NAME = 'RSASSA-PKCS1-v1_5';\n\nconst jwksAlgToCryptoAlg: Record<string, string> = {\n RS256: RSA_ALGORITHM_NAME,\n RS384: RSA_ALGORITHM_NAME,\n RS512: RSA_ALGORITHM_NAME,\n};\n\nexport const algs = Object.keys(algToHash);\n\nexport function getCryptoAlgorithm(algorithmName: string): RsaHashedImportParams {\n const hash = algToHash[algorithmName];\n const name = jwksAlgToCryptoAlg[algorithmName];\n\n if (!hash || !name) {\n throw new Error(`Unsupported algorithm ${algorithmName}, expected one of ${algs.join(',')}.`);\n }\n\n return {\n hash: { name: algToHash[algorithmName] },\n name: jwksAlgToCryptoAlg[algorithmName],\n };\n}\n","import { TokenVerificationError, TokenVerificationErrorAction, TokenVerificationErrorReason } from '../errors';\nimport { algs } from './algorithms';\n\nexport type IssuerResolver = string | ((iss: string) => boolean);\n\nconst isArrayString = (s: unknown): s is string[] => {\n return Array.isArray(s) && s.length > 0 && s.every(a => typeof a === 'string');\n};\n\nexport const assertAudienceClaim = (aud?: unknown, audience?: unknown) => {\n const audienceList = [audience].flat().filter(a => !!a);\n const audList = [aud].flat().filter(a => !!a);\n const shouldVerifyAudience = audienceList.length > 0 && audList.length > 0;\n\n if (!shouldVerifyAudience) {\n // Notice: Clerk JWTs use AZP claim instead of Audience\n //\n // return {\n // valid: false,\n // reason: `Invalid JWT audience claim (aud) ${JSON.stringify(\n // aud,\n // )}. Expected a string or a non-empty array of strings.`,\n // };\n return;\n }\n\n if (typeof aud === 'string') {\n if (!audienceList.includes(aud)) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT audience claim (aud) ${JSON.stringify(aud)}. Is not included in \"${JSON.stringify(\n audienceList,\n )}\".`,\n });\n }\n } else if (isArrayString(aud)) {\n if (!aud.some(a => audienceList.includes(a))) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT audience claim array (aud) ${JSON.stringify(aud)}. Is not included in \"${JSON.stringify(\n audienceList,\n )}\".`,\n });\n }\n }\n};\n\nexport const assertHeaderType = (typ?: unknown) => {\n if (typeof typ === 'undefined') {\n return;\n }\n\n if (typ !== 'JWT') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenInvalid,\n message: `Invalid JWT type ${JSON.stringify(typ)}. Expected \"JWT\".`,\n });\n }\n};\n\nexport const assertHeaderAlgorithm = (alg: string) => {\n if (!algs.includes(alg)) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenInvalidAlgorithm,\n message: `Invalid JWT algorithm ${JSON.stringify(alg)}. Supported: ${algs}.`,\n });\n }\n};\n\nexport const assertSubClaim = (sub?: string) => {\n if (typeof sub !== 'string') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Subject claim (sub) is required and must be a string. Received ${JSON.stringify(sub)}.`,\n });\n }\n};\n\nexport const assertAuthorizedPartiesClaim = (azp?: string, authorizedParties?: string[]) => {\n if (!azp || !authorizedParties || authorizedParties.length === 0) {\n return;\n }\n\n if (!authorizedParties.includes(azp)) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalidAuthorizedParties,\n message: `Invalid JWT Authorized party claim (azp) ${JSON.stringify(azp)}. Expected \"${authorizedParties}\".`,\n });\n }\n};\n\nexport const assertExpirationClaim = (exp: number, clockSkewInMs: number) => {\n if (typeof exp !== 'number') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT expiry date claim (exp) ${JSON.stringify(exp)}. Expected number.`,\n });\n }\n\n const currentDate = new Date(Date.now());\n const expiryDate = new Date(0);\n expiryDate.setUTCSeconds(exp);\n\n const expired = expiryDate.getTime() <= currentDate.getTime() - clockSkewInMs;\n if (expired) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenExpired,\n message: `JWT is expired. Expiry date: ${expiryDate.toUTCString()}, Current date: ${currentDate.toUTCString()}.`,\n });\n }\n};\n\nexport const assertActivationClaim = (nbf: number | undefined, clockSkewInMs: number) => {\n if (typeof nbf === 'undefined') {\n return;\n }\n\n if (typeof nbf !== 'number') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT not before date claim (nbf) ${JSON.stringify(nbf)}. Expected number.`,\n });\n }\n\n const currentDate = new Date(Date.now());\n const notBeforeDate = new Date(0);\n notBeforeDate.setUTCSeconds(nbf);\n\n const early = notBeforeDate.getTime() > currentDate.getTime() + clockSkewInMs;\n if (early) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenNotActiveYet,\n message: `JWT cannot be used prior to not before date claim (nbf). Not before date: ${notBeforeDate.toUTCString()}; Current date: ${currentDate.toUTCString()};`,\n });\n }\n};\n\nexport const assertIssuedAtClaim = (iat: number | undefined, clockSkewInMs: number) => {\n if (typeof iat === 'undefined') {\n return;\n }\n\n if (typeof iat !== 'number') {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Invalid JWT issued at date claim (iat) ${JSON.stringify(iat)}. Expected number.`,\n });\n }\n\n const currentDate = new Date(Date.now());\n const issuedAtDate = new Date(0);\n issuedAtDate.setUTCSeconds(iat);\n\n const postIssued = issuedAtDate.getTime() > currentDate.getTime() + clockSkewInMs;\n if (postIssued) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenIatInTheFuture,\n message: `JWT issued at date claim (iat) is in the future. Issued at date: ${issuedAtDate.toUTCString()}; Current date: ${currentDate.toUTCString()};`,\n });\n }\n};\n","import { isomorphicAtob } from '@clerk/shared/isomorphicAtob';\n\nimport { runtime } from '../runtime';\n\n// https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#pkcs_8_import\nfunction pemToBuffer(secret: string): ArrayBuffer {\n const trimmed = secret\n .replace(/-----BEGIN.*?-----/g, '')\n .replace(/-----END.*?-----/g, '')\n .replace(/\\s/g, '');\n\n const decoded = isomorphicAtob(trimmed);\n\n const buffer = new ArrayBuffer(decoded.length);\n const bufView = new Uint8Array(buffer);\n\n for (let i = 0, strLen = decoded.length; i < strLen; i++) {\n bufView[i] = decoded.charCodeAt(i);\n }\n\n return bufView;\n}\n\nexport function importKey(\n key: JsonWebKey | string,\n algorithm: RsaHashedImportParams,\n keyUsage: 'verify' | 'sign',\n): Promise<CryptoKey> {\n if (typeof key === 'object') {\n return runtime.crypto.subtle.importKey('jwk', key, algorithm, false, [keyUsage]);\n }\n\n const keyData = pemToBuffer(key);\n const format = keyUsage === 'sign' ? 'pkcs8' : 'spki';\n\n return runtime.crypto.subtle.importKey(format, keyData, algorithm, false, [keyUsage]);\n}\n","import type { Jwt, JwtPayload } from '@clerk/shared/types';\n\nimport { TokenVerificationError, TokenVerificationErrorAction, TokenVerificationErrorReason } from '../errors';\nimport { runtime } from '../runtime';\nimport { base64url } from '../util/rfc4648';\nimport { getCryptoAlgorithm } from './algorithms';\nimport {\n assertActivationClaim,\n assertAudienceClaim,\n assertAuthorizedPartiesClaim,\n assertExpirationClaim,\n assertHeaderAlgorithm,\n assertHeaderType,\n assertIssuedAtClaim,\n assertSubClaim,\n} from './assertions';\nimport { importKey } from './cryptoKeys';\nimport type { JwtReturnType } from './types';\n\nconst DEFAULT_CLOCK_SKEW_IN_MS = 5 * 1000;\n\nexport async function hasValidSignature(jwt: Jwt, key: JsonWebKey | string): Promise<JwtReturnType<boolean, Error>> {\n const { header, signature, raw } = jwt;\n const encoder = new TextEncoder();\n const data = encoder.encode([raw.header, raw.payload].join('.'));\n const algorithm = getCryptoAlgorithm(header.alg);\n\n try {\n const cryptoKey = await importKey(key, algorithm, 'verify');\n\n const verified = await runtime.crypto.subtle.verify(algorithm.name, cryptoKey, signature, data);\n return { data: verified };\n } catch (error) {\n return {\n errors: [\n new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalidSignature,\n message: (error as Error)?.message,\n }),\n ],\n };\n }\n}\n\nexport function decodeJwt(token: string): JwtReturnType<Jwt, TokenVerificationError> {\n const tokenParts = (token || '').toString().split('.');\n if (tokenParts.length !== 3) {\n return {\n errors: [\n new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalid,\n message: `Invalid JWT form. A JWT consists of three parts separated by dots.`,\n }),\n ],\n };\n }\n\n const [rawHeader, rawPayload, rawSignature] = tokenParts;\n\n const decoder = new TextDecoder();\n\n // To verify a JWS with SubtleCrypto you need to be careful to encode and decode\n // the data properly between binary and base64url representation. Unfortunately\n // the standard implementation in the V8 of btoa() and atob() are difficult to\n // work with as they use \"a Unicode string containing only characters in the\n // range U+0000 to U+00FF, each representing a binary byte with values 0x00 to\n // 0xFF respectively\" as the representation of binary data.\n\n // A better solution to represent binary data in Javascript is to use ES6 TypedArray\n // and use a Javascript library to convert them to base64url that honors RFC 4648.\n\n // Side note: The difference between base64 and base64url is the characters selected\n // for value 62 and 63 in the standard, base64 encode them to + and / while base64url\n // encode - and _.\n\n // More info at https://stackoverflow.com/questions/54062583/how-to-verify-a-signed-jwt-with-subtlecrypto-of-the-web-crypto-API\n const header = JSON.parse(decoder.decode(base64url.parse(rawHeader, { loose: true })));\n const payload = JSON.parse(decoder.decode(base64url.parse(rawPayload, { loose: true })));\n\n const signature = base64url.parse(rawSignature, { loose: true });\n\n const data = {\n header,\n payload,\n signature,\n raw: {\n header: rawHeader,\n payload: rawPayload,\n signature: rawSignature,\n text: token,\n },\n } satisfies Jwt;\n\n return { data };\n}\n\n/**\n * @inline\n */\nexport type VerifyJwtOptions = {\n /**\n * A string or list of [audiences](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3). If passed, it is checked against the `aud` claim in the token.\n */\n audience?: string | string[];\n /**\n * An allowlist of origins to verify against, to protect your application from the subdomain cookie leaking attack.\n * @example\n * ```ts\n * ['http://localhost:3000', 'https://example.com']\n * ```\n */\n authorizedParties?: string[];\n /**\n * Specifies the allowed time difference (in milliseconds) between the Clerk server (which generates the token) and the clock of the user's application server when validating a token.\n * @default 5000\n */\n clockSkewInMs?: number;\n /**\n * @internal\n */\n key: JsonWebKey | string;\n};\n\nexport async function verifyJwt(\n token: string,\n options: VerifyJwtOptions,\n): Promise<JwtReturnType<JwtPayload, TokenVerificationError>> {\n const { audience, authorizedParties, clockSkewInMs, key } = options;\n const clockSkew = clockSkewInMs || DEFAULT_CLOCK_SKEW_IN_MS;\n\n const { data: decoded, errors } = decodeJwt(token);\n if (errors) {\n return { errors };\n }\n\n const { header, payload } = decoded;\n try {\n // Header verifications\n const { typ, alg } = header;\n\n assertHeaderType(typ);\n assertHeaderAlgorithm(alg);\n\n // Payload verifications\n const { azp, sub, aud, iat, exp, nbf } = payload;\n\n assertSubClaim(sub);\n assertAudienceClaim([aud], [audience]);\n assertAuthorizedPartiesClaim(azp, authorizedParties);\n assertExpirationClaim(exp, clockSkew);\n assertActivationClaim(nbf, clockSkew);\n assertIssuedAtClaim(iat, clockSkew);\n } catch (err) {\n return { errors: [err as TokenVerificationError] };\n }\n\n const { data: signatureValid, errors: signatureErrors } = await hasValidSignature(decoded, key);\n if (signatureErrors) {\n return {\n errors: [\n new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Error verifying JWT signature. ${signatureErrors[0]}`,\n }),\n ],\n };\n }\n\n if (!signatureValid) {\n return {\n errors: [\n new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalidSignature,\n message: 'JWT signature is invalid.',\n }),\n ],\n };\n }\n\n return { data: payload };\n}\n","import { parsePublishableKey } from './shared';\n\nexport function assertValidSecretKey(val: unknown): asserts val is string {\n if (!val || typeof val !== 'string') {\n throw Error('Missing Clerk Secret Key. Go to https://dashboard.clerk.com and get your key for your instance.');\n }\n\n //TODO: Check if the key is invalid and throw error\n}\n\nexport function assertValidPublishableKey(val: unknown): asserts val is string {\n parsePublishableKey(val as string | undefined, { fatal: true });\n}\n","import { buildAccountsBaseUrl } from '@clerk/shared/buildAccountsBaseUrl';\nimport type { Jwt } from '@clerk/shared/types';\nimport { isCurrentDevAccountPortalOrigin, isLegacyDevAccountPortalOrigin } from '@clerk/shared/url';\n\nimport { constants } from '../constants';\nimport { decodeJwt } from '../jwt/verifyJwt';\nimport { runtime } from '../runtime';\nimport { assertValidPublishableKey } from '../util/optionsAssertions';\nimport { getCookieSuffix, getSuffixedCookieName, parsePublishableKey } from '../util/shared';\nimport type { ClerkRequest } from './clerkRequest';\nimport { TokenType } from './tokenTypes';\nimport type { AuthenticateRequestOptions } from './types';\n\ninterface AuthenticateContext extends AuthenticateRequestOptions {\n // header-based values\n accept: string | undefined;\n forwardedHost: string | undefined;\n forwardedProto: string | undefined;\n host: string | undefined;\n origin: string | undefined;\n referrer: string | undefined;\n secFetchDest: string | undefined;\n tokenInHeader: string | undefined;\n userAgent: string | undefined;\n\n // cookie-based values\n clientUat: number;\n refreshTokenInCookie: string | undefined;\n sessionTokenInCookie: string | undefined;\n\n // handshake-related values\n devBrowserToken: string | undefined;\n handshakeNonce: string | undefined;\n handshakeRedirectLoopCounter: number;\n handshakeToken: string | undefined;\n\n // url derived from headers\n clerkUrl: URL;\n // enforce existence of the following props\n frontendApi: string;\n instanceType: string;\n publishableKey: string;\n}\n\n/**\n * All data required to authenticate a request.\n * This is the data we use to decide whether a request\n * is in a signed in or signed out state or if we need\n * to perform a handshake.\n */\nclass AuthenticateContext implements AuthenticateContext {\n /**\n * The original Clerk frontend API URL, extracted from publishable key before proxy URL override.\n * Used for backend operations like token validation and issuer checking.\n */\n private originalFrontendApi: string = '';\n\n /**\n * Retrieves the session token from either the cookie or the header.\n *\n * @returns {string | undefined} The session token if available, otherwise undefined.\n */\n public get sessionToken(): string | undefined {\n return this.sessionTokenInCookie || this.tokenInHeader;\n }\n\n public constructor(\n private cookieSuffix: string,\n private clerkRequest: ClerkRequest,\n options: AuthenticateRequestOptions,\n ) {\n if (options.acceptsToken === TokenType.M2MToken || options.acceptsToken === TokenType.ApiKey) {\n // For non-session tokens, we only want to set the header values.\n this.initHeaderValues();\n } else {\n // Even though the options are assigned to this later in this function\n // we set the publishableKey here because it is being used in cookies/headers/handshake-values\n // as part of getMultipleAppsCookie.\n this.initPublishableKeyValues(options);\n this.initHeaderValues();\n // initCookieValues should be used before initHandshakeValues because it depends on suffixedCookies\n this.initCookieValues();\n this.initHandshakeValues();\n }\n\n Object.assign(this, options);\n this.clerkUrl = this.clerkRequest.clerkUrl;\n }\n\n public usesSuffixedCookies(): boolean {\n const suffixedClientUat = this.getSuffixedCookie(constants.Cookies.ClientUat);\n const clientUat = this.getCookie(constants.Cookies.ClientUat);\n const suffixedSession = this.getSuffixedCookie(constants.Cookies.Session) || '';\n const session = this.getCookie(constants.Cookies.Session) || '';\n\n // In the case of malformed session cookies (eg missing the iss claim), we should\n // use the un-suffixed cookies to return signed-out state instead of triggering\n // handshake\n if (session && !this.tokenHasIssuer(session)) {\n return false;\n }\n\n // If there's a token in un-suffixed, and it doesn't belong to this\n // instance, then we must trust suffixed\n if (session && !this.tokenBelongsToInstance(session)) {\n return true;\n }\n\n // If there are no suffixed cookies use un-suffixed\n if (!suffixedClientUat && !suffixedSession) {\n return false;\n }\n\n const { data: sessionData } = decodeJwt(session);\n const sessionIat = sessionData?.payload.iat || 0;\n const { data: suffixedSessionData } = decodeJwt(suffixedSession);\n const suffixedSessionIat = suffixedSessionData?.payload.iat || 0;\n\n // Both indicate signed in, but un-suffixed is newer\n // Trust un-suffixed because it's newer\n if (suffixedClientUat !== '0' && clientUat !== '0' && sessionIat > suffixedSessionIat) {\n return false;\n }\n\n // Suffixed indicates signed out, but un-suffixed indicates signed in\n // Trust un-suffixed because it gets set with both new and old clerk.js,\n // so we can assume it's newer\n if (suffixedClientUat === '0' && clientUat !== '0') {\n return false;\n }\n\n // Suffixed indicates signed in, un-suffixed indicates signed out\n // This is the tricky one\n\n // In production, suffixed_uat should be set reliably, since it's\n // set by FAPI and not clerk.js. So in the scenario where a developer\n // downgrades, the state will look like this:\n // - un-suffixed session cookie: empty\n // - un-suffixed uat: 0\n // - suffixed session cookie: (possibly filled, possibly empty)\n // - suffixed uat: 0\n\n // Our SDK honors client_uat over the session cookie, so we don't\n // need a special case for production. We can rely on suffixed,\n // and the fact that the suffixed uat is set properly means and\n // suffixed session cookie will be ignored.\n\n // The important thing to make sure we have a test that confirms\n // the user ends up as signed out in this scenario, and the suffixed\n // session cookie is ignored\n\n // In development, suffixed_uat is not set reliably, since it's done\n // by clerk.js. If the developer downgrades to a pinned version of\n // clerk.js, the suffixed uat will no longer be updated\n\n // The best we can do is look to see if the suffixed token is expired.\n // This means that, if a developer downgrades, and then immediately\n // signs out, all in the span of 1 minute, then they will inadvertently\n // remain signed in for the rest of that minute. This is a known\n // limitation of the strategy but seems highly unlikely.\n if (this.instanceType !== 'production') {\n const isSuffixedSessionExpired = this.sessionExpired(suffixedSessionData);\n if (suffixedClientUat !== '0' && clientUat === '0' && isSuffixedSessionExpired) {\n return false;\n }\n }\n\n // If a suffixed session cookie exists but the corresponding client_uat cookie is missing, fallback to using\n // unsuffixed cookies.\n // This handles the scenario where an app has been deployed using an SDK version that supports suffixed\n // cookies, but FAPI for its Clerk instance has the feature disabled (eg: if we need to temporarily disable the feature).\n if (!suffixedClientUat && suffixedSession) {\n return false;\n }\n\n return true;\n }\n\n /**\n * Determines if the request came from a different origin based on the referrer header.\n * Used for cross-origin detection in multi-domain authentication flows.\n *\n * @returns {boolean} True if referrer exists and is from a different origin, false otherwise.\n */\n public isCrossOriginReferrer(): boolean {\n if (!this.referrer || !this.clerkUrl.origin) {\n return false;\n }\n\n try {\n const referrerOrigin = new URL(this.referrer).origin;\n return referrerOrigin !== this.clerkUrl.origin;\n } catch {\n // Invalid referrer URL format\n return false;\n }\n }\n\n /**\n * Determines if the referrer URL is from a Clerk domain (accounts portal or FAPI).\n * This includes both development and production account portal domains, as well as FAPI domains\n * used for redirect-based authentication flows.\n *\n * @returns {boolean} True if the referrer is from a Clerk accounts portal or FAPI domain, false otherwise\n */\n public isKnownClerkReferrer(): boolean {\n if (!this.referrer) {\n return false;\n }\n\n try {\n const referrerOrigin = new URL(this.referrer);\n const referrerHost = referrerOrigin.hostname;\n\n // Check if referrer is the FAPI domain itself (redirect-based auth flows)\n if (this.frontendApi) {\n const fapiHost = this.frontendApi.startsWith('http') ? new URL(this.frontendApi).hostname : this.frontendApi;\n if (referrerHost === fapiHost) {\n return true;\n }\n }\n\n // Check for development account portal patterns\n if (isLegacyDevAccountPortalOrigin(referrerHost) || isCurrentDevAccountPortalOrigin(referrerHost)) {\n return true;\n }\n\n // Check for production account portal by comparing with expected accounts URL\n const expectedAccountsUrl = buildAccountsBaseUrl(this.frontendApi);\n if (expectedAccountsUrl) {\n const expectedAccountsOrigin = new URL(expectedAccountsUrl).origin;\n if (referrerOrigin.origin === expectedAccountsOrigin) {\n return true;\n }\n }\n\n // Check for generic production accounts patterns (accounts.*)\n if (referrerHost.startsWith('accounts.')) {\n return true;\n }\n\n return false;\n } catch {\n // Invalid URL format\n return false;\n }\n }\n\n private initPublishableKeyValues(options: AuthenticateRequestOptions) {\n assertValidPublishableKey(options.publishableKey);\n this.publishableKey = options.publishableKey;\n\n const originalPk = parsePublishableKey(this.publishableKey, {\n fatal: true,\n domain: options.domain,\n isSatellite: options.isSatellite,\n });\n this.originalFrontendApi = originalPk.frontendApi;\n\n const pk = parsePublishableKey(this.publishableKey, {\n fatal: true,\n proxyUrl: options.proxyUrl,\n domain: options.domain,\n isSatellite: options.isSatellite,\n });\n this.instanceType = pk.instanceType;\n this.frontendApi = pk.frontendApi;\n }\n\n private initHeaderValues() {\n this.tokenInHeader = this.parseAuthorizationHeader(this.getHeader(constants.Headers.Authorization));\n this.origin = this.getHeader(constants.Headers.Origin);\n this.host = this.getHeader(constants.Headers.Host);\n this.forwardedHost = this.getHeader(constants.Headers.ForwardedHost);\n this.forwardedProto =\n this.getHeader(constants.Headers.CloudFrontForwardedProto) || this.getHeader(constants.Headers.ForwardedProto);\n this.referrer = this.getHeader(constants.Headers.Referrer);\n this.userAgent = this.getHeader(constants.Headers.UserAgent);\n this.secFetchDest = this.getHeader(constants.Headers.SecFetchDest);\n this.accept = this.getHeader(constants.Headers.Accept);\n }\n\n private initCookieValues() {\n // suffixedCookies needs to be set first because it's used in getMultipleAppsCookie\n this.sessionTokenInCookie = this.getSuffixedOrUnSuffixedCookie(constants.Cookies.Session);\n this.refreshTokenInCookie = this.getSuffixedCookie(constants.Cookies.Refresh);\n this.clientUat = Number.parseInt(this.getSuffixedOrUnSuffixedCookie(constants.Cookies.ClientUat) || '') || 0;\n }\n\n private initHandshakeValues() {\n this.devBrowserToken =\n this.getQueryParam(constants.QueryParameters.DevBrowser) ||\n this.getSuffixedOrUnSuffixedCookie(constants.Cookies.DevBrowser);\n // Using getCookie since we don't suffix the handshake token cookie\n this.handshakeToken =\n this.getQueryParam(constants.QueryParameters.Handshake) || this.getCookie(constants.Cookies.Handshake);\n this.handshakeRedirectLoopCounter = Number(this.getCookie(constants.Cookies.RedirectCount)) || 0;\n this.handshakeNonce =\n this.getQueryParam(constants.QueryParameters.HandshakeNonce) || this.getCookie(constants.Cookies.HandshakeNonce);\n }\n\n private getQueryParam(name: string) {\n return this.clerkRequest.clerkUrl.searchParams.get(name);\n }\n\n private getHeader(name: string) {\n return this.clerkRequest.headers.get(name) || undefined;\n }\n\n private getCookie(name: string) {\n return this.clerkRequest.cookies.get(name) || undefined;\n }\n\n private getSuffixedCookie(name: string) {\n return this.getCookie(getSuffixedCookieName(name, this.cookieSuffix)) || undefined;\n }\n\n private getSuffixedOrUnSuffixedCookie(cookieName: string) {\n if (this.usesSuffixedCookies()) {\n return this.getSuffixedCookie(cookieName);\n }\n return this.getCookie(cookieName);\n }\n\n private parseAuthorizationHeader(authorizationHeader: string | undefined | null): string | undefined {\n if (!authorizationHeader) {\n return undefined;\n }\n\n const [scheme, token] = authorizationHeader.split(' ', 2);\n\n if (!token) {\n // No scheme specified, treat the entire value as the token\n return scheme;\n }\n\n if (scheme === 'Bearer') {\n return token;\n }\n\n // Skip all other schemes\n return undefined;\n }\n\n private tokenHasIssuer(token: string): boolean {\n const { data, errors } = decodeJwt(token);\n if (errors) {\n return false;\n }\n return !!data.payload.iss;\n }\n\n private tokenBelongsToInstance(token: string): boolean {\n if (!token) {\n return false;\n }\n\n const { data, errors } = decodeJwt(token);\n if (errors) {\n return false;\n }\n const tokenIssuer = data.payload.iss.replace(/https?:\\/\\//gi, '');\n // Use original frontend API for token validation since tokens are issued by the actual Clerk API, not proxy\n return this.originalFrontendApi === tokenIssuer;\n }\n\n private sessionExpired(jwt: Jwt | undefined): boolean {\n return !!jwt && jwt?.payload.exp <= (Date.now() / 1000) >> 0;\n }\n}\n\nexport type { AuthenticateContext };\n\nexport const createAuthenticateContext = async (\n clerkRequest: ClerkRequest,\n options: AuthenticateRequestOptions,\n): Promise<AuthenticateContext> => {\n const cookieSuffix = options.publishableKey\n ? await getCookieSuffix(options.publishableKey, runtime.crypto.subtle)\n : '';\n return new AuthenticateContext(cookieSuffix, clerkRequest, options);\n};\n","export const TokenType = {\n SessionToken: 'session_token',\n ApiKey: 'api_key',\n M2MToken: 'm2m_token',\n OAuthToken: 'oauth_token',\n} as const;\n\n/**\n * @inline\n */\nexport type TokenType = (typeof TokenType)[keyof typeof TokenType];\n\n/**\n * @inline\n */\nexport type SessionTokenType = typeof TokenType.SessionToken;\n/**\n * @inline\n */\nexport type MachineTokenType = Exclude<TokenType, SessionTokenType>;\n","import { createCheckAuthorization } from '@clerk/shared/authorization';\nimport { __experimental_JWTPayloadToAuthObjectProperties } from '@clerk/shared/jwtPayloadParser';\nimport type {\n CheckAuthorizationFromSessionClaims,\n Jwt,\n JwtPayload,\n PendingSessionOptions,\n ServerGetToken,\n ServerGetTokenOptions,\n SessionStatusClaim,\n SharedSignedInAuthObjectProperties,\n} from '@clerk/shared/types';\n\nimport type { APIKey, CreateBackendApiOptions, IdPOAuthAccessToken, M2MToken } from '../api';\nimport { createBackendApiClient } from '../api';\nimport { isTokenTypeAccepted } from '../internal';\nimport type { AuthenticateContext } from './authenticateContext';\nimport { isMachineTokenType } from './machine';\nimport type { MachineTokenType, SessionTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\nimport type { AuthenticateRequestOptions, MachineAuthType } from './types';\n\n/**\n * @inline\n */\ntype AuthObjectDebugData = Record<string, any>;\n/**\n * @inline\n */\ntype AuthObjectDebug = () => AuthObjectDebugData;\n\ntype Claims = Record<string, any>;\n\n/**\n * @internal\n */\nexport type SignedInAuthObjectOptions = CreateBackendApiOptions & {\n token: string;\n};\n\n/**\n * @internal\n */\nexport type SignedInAuthObject = SharedSignedInAuthObjectProperties & {\n /**\n * The allowed token type.\n */\n tokenType: SessionTokenType;\n /**\n * A function that gets the current user's [session token](https://clerk.com/docs/guides/sessions/session-tokens) or a [custom JWT template](https://clerk.com/docs/guides/sessions/jwt-templates).\n */\n getToken: ServerGetToken;\n /**\n * A function that checks if the user has an organization role or custom permission.\n */\n has: CheckAuthorizationFromSessionClaims;\n /**\n * Used to help debug issues when using Clerk in development.\n */\n debug: AuthObjectDebug;\n isAuthenticated: true;\n};\n\n/**\n * @internal\n */\nexport type SignedOutAuthObject = {\n sessionClaims: null;\n sessionId: null;\n sessionStatus: SessionStatusClaim | null;\n actor: null;\n tokenType: SessionTokenType;\n userId: null;\n orgId: null;\n orgRole: null;\n orgSlug: null;\n orgPermissions: null;\n factorVerificationAge: null;\n getToken: ServerGetToken;\n has: CheckAuthorizationFromSessionClaims;\n debug: AuthObjectDebug;\n isAuthenticated: false;\n};\n\n/**\n * Extended properties specific to each machine token type.\n * While all machine token types share common properties (id, name, subject, etc),\n * this type defines the additional properties that are unique to each token type.\n *\n * @template TAuthenticated - Whether the machine object is authenticated or not\n */\ntype MachineObjectExtendedProperties<TAuthenticated extends boolean> = {\n api_key: TAuthenticated extends true\n ?\n | { name: string; claims: Claims | null; userId: string; orgId: null }\n | { name: string; claims: Claims | null; userId: null; orgId: string }\n : { name: null; claims: null; userId: null; orgId: null };\n m2m_token: {\n claims: TAuthenticated extends true ? Claims | null : null;\n machineId: TAuthenticated extends true ? string : null;\n };\n oauth_token: {\n userId: TAuthenticated extends true ? string : null;\n clientId: TAuthenticated extends true ? string : null;\n };\n};\n\n/**\n * @internal\n *\n * Uses `T extends any` to create a distributive conditional type.\n * This ensures that union types like `'api_key' | 'oauth_token'` are processed\n * individually, creating proper discriminated unions where each token type\n * gets its own distinct properties (e.g., oauth_token won't have claims).\n */\nexport type AuthenticatedMachineObject<T extends MachineTokenType = MachineTokenType> = T extends any\n ? {\n id: string;\n subject: string;\n scopes: string[];\n getToken: () => Promise<string>;\n has: CheckAuthorizationFromSessionClaims;\n debug: AuthObjectDebug;\n tokenType: T;\n isAuthenticated: true;\n } & MachineObjectExtendedProperties<true>[T]\n : never;\n\n/**\n * @internal\n *\n * Uses `T extends any` to create a distributive conditional type.\n * This ensures that union types like `'api_key' | 'oauth_token'` are processed\n * individually, creating proper discriminated unions where each token type\n * gets its own distinct properties (e.g., oauth_token won't have claims).\n */\nexport type UnauthenticatedMachineObject<T extends MachineTokenType = MachineTokenType> = T extends any\n ? {\n id: null;\n subject: null;\n scopes: null;\n getToken: () => Promise<null>;\n has: CheckAuthorizationFromSessionClaims;\n debug: AuthObjectDebug;\n tokenType: T;\n isAuthenticated: false;\n } & MachineObjectExtendedProperties<false>[T]\n : never;\n\nexport type InvalidTokenAuthObject = {\n isAuthenticated: false;\n tokenType: null;\n getToken: () => Promise<null>;\n has: () => false;\n debug: AuthObjectDebug;\n};\n\n/**\n * @interface\n */\nexport type AuthObject =\n | SignedInAuthObject\n | SignedOutAuthObject\n | AuthenticatedMachineObject\n | UnauthenticatedMachineObject\n | InvalidTokenAuthObject;\n\nconst createDebug = (data: AuthObjectDebugData | undefined) => {\n return () => {\n const res = { ...data };\n res.secretKey = (res.secretKey || '').substring(0, 7);\n res.jwtKey = (res.jwtKey || '').substring(0, 7);\n return { ...res };\n };\n};\n\n/**\n * @internal\n */\nexport function signedInAuthObject(\n authenticateContext: Partial<AuthenticateContext>,\n sessionToken: string,\n sessionClaims: JwtPayload,\n): SignedInAuthObject {\n const { actor, sessionId, sessionStatus, userId, orgId, orgRole, orgSlug, orgPermissions, factorVerificationAge } =\n __experimental_JWTPayloadToAuthObjectProperties(sessionClaims);\n const apiClient = createBackendApiClient(authenticateContext);\n const getToken = createGetToken({\n sessionId,\n sessionToken,\n fetcher: async (sessionId, template, expiresInSeconds) =>\n (await apiClient.sessions.getToken(sessionId, template || '', expiresInSeconds)).jwt,\n });\n return {\n tokenType: TokenType.SessionToken,\n actor,\n sessionClaims,\n sessionId,\n sessionStatus,\n userId,\n orgId,\n orgRole,\n orgSlug,\n orgPermissions,\n factorVerificationAge,\n getToken,\n has: createCheckAuthorization({\n orgId,\n orgRole,\n orgPermissions,\n userId,\n factorVerificationAge,\n features: (sessionClaims.fea as string) || '',\n plans: (sessionClaims.pla as string) || '',\n }),\n debug: createDebug({ ...authenticateContext, sessionToken }),\n isAuthenticated: true,\n };\n}\n\n/**\n * @internal\n */\nexport function signedOutAuthObject(\n debugData?: AuthObjectDebugData,\n initialSessionStatus?: SessionStatusClaim,\n): SignedOutAuthObject {\n return {\n tokenType: TokenType.SessionToken,\n sessionClaims: null,\n sessionId: null,\n sessionStatus: initialSessionStatus ?? null,\n userId: null,\n actor: null,\n orgId: null,\n orgRole: null,\n orgSlug: null,\n orgPermissions: null,\n factorVerificationAge: null,\n getToken: () => Promise.resolve(null),\n has: () => false,\n debug: createDebug(debugData),\n isAuthenticated: false,\n };\n}\n\n/**\n * @internal\n */\nexport function authenticatedMachineObject<T extends MachineTokenType>(\n tokenType: T,\n token: string,\n verificationResult: MachineAuthType,\n debugData?: AuthObjectDebugData,\n): AuthenticatedMachineObject<T> {\n const baseObject = {\n id: verificationResult.id,\n subject: verificationResult.subject,\n getToken: () => Promise.resolve(token),\n has: () => false,\n debug: createDebug(debugData),\n isAuthenticated: true,\n };\n\n // Type assertions are safe here since we know the verification result type matches the tokenType.\n // We need these assertions because TS can't infer the specific type\n // just from the tokenType discriminator.\n\n switch (tokenType) {\n case TokenType.ApiKey: {\n const result = verificationResult as APIKey;\n return {\n ...baseObject,\n tokenType,\n name: result.name,\n claims: result.claims,\n scopes: result.scopes,\n userId: result.subject.startsWith('user_') ? result.subject : null,\n orgId: result.subject.startsWith('org_') ? result.subject : null,\n } as unknown as AuthenticatedMachineObject<T>;\n }\n case TokenType.M2MToken: {\n const result = verificationResult as M2MToken;\n return {\n ...baseObject,\n tokenType,\n claims: result.claims,\n scopes: result.scopes,\n machineId: result.subject,\n } as unknown as AuthenticatedMachineObject<T>;\n }\n case TokenType.OAuthToken: {\n const result = verificationResult as IdPOAuthAccessToken;\n return {\n ...baseObject,\n tokenType,\n scopes: result.scopes,\n userId: result.subject,\n clientId: result.clientId,\n } as unknown as AuthenticatedMachineObject<T>;\n }\n default:\n throw new Error(`Invalid token type: ${tokenType}`);\n }\n}\n\n/**\n * @internal\n */\nexport function unauthenticatedMachineObject<T extends MachineTokenType>(\n tokenType: T,\n debugData?: AuthObjectDebugData,\n): UnauthenticatedMachineObject<T> {\n const baseObject = {\n id: null,\n subject: null,\n scopes: null,\n has: () => false,\n getToken: () => Promise.resolve(null),\n debug: createDebug(debugData),\n isAuthenticated: false,\n };\n\n switch (tokenType) {\n case TokenType.ApiKey: {\n return {\n ...baseObject,\n tokenType,\n name: null,\n claims: null,\n scopes: null,\n userId: null,\n orgId: null,\n } as unknown as UnauthenticatedMachineObject<T>;\n }\n case TokenType.M2MToken: {\n return {\n ...baseObject,\n tokenType,\n claims: null,\n scopes: null,\n machineId: null,\n } as unknown as UnauthenticatedMachineObject<T>;\n }\n case TokenType.OAuthToken: {\n return {\n ...baseObject,\n tokenType,\n scopes: null,\n userId: null,\n clientId: null,\n } as unknown as UnauthenticatedMachineObject<T>;\n }\n default:\n throw new Error(`Invalid token type: ${tokenType}`);\n }\n}\n\n/**\n * @internal\n */\nexport function invalidTokenAuthObject(): InvalidTokenAuthObject {\n return {\n isAuthenticated: false,\n tokenType: null,\n getToken: () => Promise.resolve(null),\n has: () => false,\n debug: () => ({}),\n };\n}\n\n/**\n * Auth objects moving through the server -> client boundary need to be serializable\n * as we need to ensure that they can be transferred via the network as pure strings.\n * Some frameworks like Remix or Next (/pages dir only) handle this serialization by simply\n * ignoring any non-serializable keys, however Nextjs /app directory is stricter and\n * throws an error if a non-serializable value is found.\n *\n * @internal\n */\nexport const makeAuthObjectSerializable = <T extends Record<string, unknown>>(obj: T): T => {\n // remove any non-serializable props from the returned object\n\n const { debug, getToken, has, ...rest } = obj as unknown as AuthObject;\n return rest as unknown as T;\n};\n\n/**\n * A function that fetches a session token from the Clerk API.\n *\n * @param sessionId - The ID of the session\n * @param template - The JWT template name to use for token generation\n * @param expiresInSeconds - Optional expiration time in seconds for the token\n * @returns A promise that resolves to the token string\n */\ntype TokenFetcher = (sessionId: string, template?: string, expiresInSeconds?: number) => Promise<string>;\n\n/**\n * Factory function type that creates a getToken function for auth objects.\n *\n * @param params - Configuration object containing session information and token fetcher\n * @returns A ServerGetToken function that can be used to retrieve tokens\n */\ntype CreateGetToken = (params: { sessionId: string; sessionToken: string; fetcher: TokenFetcher }) => ServerGetToken;\n\n/**\n * Creates a token retrieval function for authenticated sessions.\n *\n * This factory function returns a getToken function that can either return the raw session token\n * or generate a JWT using a specified template with optional custom expiration.\n *\n * @param params - Configuration object\n * @param params.sessionId - The session ID for token generation\n * @param params.sessionToken - The raw session token to return when no template is specified\n * @param params.fetcher - Function to fetch tokens from the Clerk API\n *\n * @returns A function that retrieves tokens based on the provided options\n */\nconst createGetToken: CreateGetToken = params => {\n const { fetcher, sessionToken, sessionId } = params || {};\n\n return async (options: ServerGetTokenOptions = {}) => {\n if (!sessionId) {\n return null;\n }\n\n if (options.template || options.expiresInSeconds !== undefined) {\n return fetcher(sessionId, options.template, options.expiresInSeconds);\n }\n\n return sessionToken;\n };\n};\n\n/**\n * @internal\n */\nexport const getAuthObjectFromJwt = (\n jwt: Jwt,\n { treatPendingAsSignedOut = true, ...options }: PendingSessionOptions & Partial<AuthenticateContext>,\n) => {\n const authObject = signedInAuthObject(options, jwt.raw.text, jwt.payload);\n\n if (treatPendingAsSignedOut && authObject.sessionStatus === 'pending') {\n return signedOutAuthObject(options, authObject.sessionStatus);\n }\n\n return authObject;\n};\n\n/**\n * @internal\n * Returns an auth object matching the requested token type(s).\n *\n * If the parsed token type does not match any in acceptsToken, returns:\n * - an invalid token auth object if the token is not in the accepted array\n * - an unauthenticated machine object for machine tokens, or\n * - a signed-out session object otherwise.\n *\n * This ensures the returned object always matches the developer's intent.\n */\nexport const getAuthObjectForAcceptedToken = ({\n authObject,\n acceptsToken = TokenType.SessionToken,\n}: {\n authObject: AuthObject;\n acceptsToken: AuthenticateRequestOptions['acceptsToken'];\n}): AuthObject => {\n // 1. any token: return as-is\n if (acceptsToken === 'any') {\n return authObject;\n }\n\n // 2. array of tokens: must match one of the accepted types\n if (Array.isArray(acceptsToken)) {\n if (!isTokenTypeAccepted(authObject.tokenType, acceptsToken)) {\n return invalidTokenAuthObject();\n }\n return authObject;\n }\n\n // 3. single token: must match exactly, else return appropriate unauthenticated object\n if (!isTokenTypeAccepted(authObject.tokenType, acceptsToken)) {\n if (isMachineTokenType(acceptsToken)) {\n return unauthenticatedMachineObject(acceptsToken, authObject.debug);\n }\n return signedOutAuthObject(authObject.debug);\n }\n\n // 4. default: return as-is\n return authObject;\n};\n","const SEPARATOR = '/';\nconst MULTIPLE_SEPARATOR_REGEX = new RegExp('(?<!:)' + SEPARATOR + '{1,}', 'g');\n\ntype PathString = string | null | undefined;\n\nexport function joinPaths(...args: PathString[]): string {\n return args\n .filter(p => p)\n .join(SEPARATOR)\n .replace(MULTIPLE_SEPARATOR_REGEX, SEPARATOR);\n}\n","import type { RequestFunction } from '../request';\n\nexport abstract class AbstractAPI {\n constructor(protected request: RequestFunction) {}\n\n protected requireId(id: string) {\n if (!id) {\n throw new Error('A valid resource ID is required.');\n }\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { ActorToken } from '../resources/ActorToken';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/actor_tokens';\n\ntype ActorTokenActorCreateParams = {\n /**\n * The ID of the actor.\n */\n sub: string;\n /**\n * Additional properties of the actor.\n */\n additionalProperties?: { [k: string]: any };\n};\n\ntype ActorTokenCreateParams = {\n /**\n * The ID of the user being impersonated.\n */\n userId: string;\n /**\n * The actor payload. It needs to include a sub property which should contain the ID of the actor.\n *\n * @remarks\n * This whole payload will be also included in the JWT session token.\n */\n actor: ActorTokenActorCreateParams;\n /**\n * Optional parameter to specify the life duration of the actor token in seconds.\n *\n * @remarks\n * By default, the duration is 1 hour.\n */\n expiresInSeconds?: number | undefined;\n /**\n * The maximum duration that the session which will be created by the generated actor token should last.\n *\n * @remarks\n * By default, the duration of a session created via an actor token, lasts 30 minutes.\n */\n sessionMaxDurationInSeconds?: number | undefined;\n};\n\nexport class ActorTokenAPI extends AbstractAPI {\n public async create(params: ActorTokenCreateParams) {\n return this.request<ActorToken>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async revoke(actorTokenId: string) {\n this.requireId(actorTokenId);\n return this.request<ActorToken>({\n method: 'POST',\n path: joinPaths(basePath, actorTokenId, 'revoke'),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { AccountlessApplication } from '../resources/AccountlessApplication';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/accountless_applications';\n\nexport class AccountlessApplicationAPI extends AbstractAPI {\n public async createAccountlessApplication(params?: { requestHeaders?: Headers }) {\n const headerParams = params?.requestHeaders ? Object.fromEntries(params.requestHeaders.entries()) : undefined;\n return this.request<AccountlessApplication>({\n method: 'POST',\n path: basePath,\n headerParams,\n });\n }\n\n public async completeAccountlessApplicationOnboarding(params?: { requestHeaders?: Headers }) {\n const headerParams = params?.requestHeaders ? Object.fromEntries(params.requestHeaders.entries()) : undefined;\n return this.request<AccountlessApplication>({\n method: 'POST',\n path: joinPaths(basePath, 'complete'),\n headerParams,\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { AllowlistIdentifier } from '../resources/AllowlistIdentifier';\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/allowlist_identifiers';\n\ntype AllowlistIdentifierCreateParams = {\n identifier: string;\n notify: boolean;\n};\n\nexport class AllowlistIdentifierAPI extends AbstractAPI {\n public async getAllowlistIdentifierList(params: ClerkPaginationRequest = {}) {\n return this.request<PaginatedResourceResponse<AllowlistIdentifier[]>>({\n method: 'GET',\n path: basePath,\n queryParams: { ...params, paginated: true },\n });\n }\n\n public async createAllowlistIdentifier(params: AllowlistIdentifierCreateParams) {\n return this.request<AllowlistIdentifier>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async deleteAllowlistIdentifier(allowlistIdentifierId: string) {\n this.requireId(allowlistIdentifierId);\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, allowlistIdentifierId),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\n\nimport type { PaginatedResourceResponse } from '../../api/resources/Deserializer';\nimport { joinPaths } from '../../util/path';\nimport { deprecated } from '../../util/shared';\nimport type { APIKey } from '../resources/APIKey';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/api_keys';\n\ntype GetAPIKeyListParams = ClerkPaginationRequest<{\n /**\n * The user or organization ID to query API keys by\n */\n subject: string;\n /**\n * Whether to include invalid API keys.\n *\n * @default false\n */\n includeInvalid?: boolean;\n}>;\n\ntype CreateAPIKeyParams = {\n /**\n * API key name\n */\n name: string;\n /**\n * The user or organization ID to associate the API key with\n */\n subject: string;\n /**\n * API key description\n */\n description?: string | null;\n claims?: Record<string, any> | null;\n scopes?: string[];\n createdBy?: string | null;\n secondsUntilExpiration?: number | null;\n};\n\ntype RevokeAPIKeyParams = {\n /**\n * API key ID\n */\n apiKeyId: string;\n /**\n * Reason for revocation\n */\n revocationReason?: string | null;\n};\n\nexport class APIKeysAPI extends AbstractAPI {\n async list(queryParams: GetAPIKeyListParams) {\n return this.request<PaginatedResourceResponse<APIKey[]>>({\n method: 'GET',\n path: basePath,\n queryParams,\n });\n }\n\n async create(params: CreateAPIKeyParams) {\n return this.request<APIKey>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n async revoke(params: RevokeAPIKeyParams) {\n const { apiKeyId, ...bodyParams } = params;\n\n this.requireId(apiKeyId);\n\n return this.request<APIKey>({\n method: 'POST',\n path: joinPaths(basePath, apiKeyId, 'revoke'),\n bodyParams,\n });\n }\n\n async getSecret(apiKeyId: string) {\n this.requireId(apiKeyId);\n\n return this.request<{ secret: string }>({\n method: 'GET',\n path: joinPaths(basePath, apiKeyId, 'secret'),\n });\n }\n\n async verify(secret: string) {\n return this.request<APIKey>({\n method: 'POST',\n path: joinPaths(basePath, 'verify'),\n bodyParams: { secret },\n });\n }\n\n /**\n * @deprecated Use `verify()` instead. This method will be removed in the next major release.\n */\n async verifySecret(secret: string) {\n deprecated('apiKeys.verifySecret()', 'Use `apiKeys.verify()` instead.');\n return this.verify(secret);\n }\n}\n","import { joinPaths } from '../../util/path';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/beta_features';\n\ntype ChangeDomainParams = {\n /**\n * The new home URL of the production instance e.g. https://www.example.com\n */\n homeUrl?: string;\n /**\n * Whether this is a domain for a secondary app, meaning that any subdomain\n * provided is significant and will be stored as part of the domain. This is\n * useful for supporting multiple apps (one primary and multiple secondaries)\n * on the same root domain (eTLD+1).\n */\n isSecondary?: boolean;\n};\n\nexport class BetaFeaturesAPI extends AbstractAPI {\n /**\n * Change the domain of a production instance.\n *\n * Changing the domain requires updating the DNS records accordingly, deploying new SSL certificates,\n * updating your Social Connection's redirect URLs and setting the new keys in your code.\n *\n * @remarks\n * WARNING: Changing your domain will invalidate all current user sessions (i.e. users will be logged out).\n * Also, while your application is being deployed, a small downtime is expected to occur.\n */\n public async changeDomain(params: ChangeDomainParams) {\n return this.request<void>({\n method: 'POST',\n path: joinPaths(basePath, 'change_domain'),\n bodyParams: params,\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { BlocklistIdentifier } from '../resources/BlocklistIdentifier';\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/blocklist_identifiers';\n\ntype BlocklistIdentifierCreateParams = {\n identifier: string;\n};\n\nexport class BlocklistIdentifierAPI extends AbstractAPI {\n public async getBlocklistIdentifierList(params: ClerkPaginationRequest = {}) {\n return this.request<PaginatedResourceResponse<BlocklistIdentifier[]>>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async createBlocklistIdentifier(params: BlocklistIdentifierCreateParams) {\n return this.request<BlocklistIdentifier>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async deleteBlocklistIdentifier(blocklistIdentifierId: string) {\n this.requireId(blocklistIdentifierId);\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, blocklistIdentifierId),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { Client } from '../resources/Client';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { HandshakePayload } from '../resources/HandshakePayload';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/clients';\n\ntype GetHandshakePayloadParams = {\n nonce: string;\n};\n\nexport class ClientAPI extends AbstractAPI {\n public async getClientList(params: ClerkPaginationRequest = {}) {\n return this.request<PaginatedResourceResponse<Client[]>>({\n method: 'GET',\n path: basePath,\n queryParams: { ...params, paginated: true },\n });\n }\n\n public async getClient(clientId: string) {\n this.requireId(clientId);\n return this.request<Client>({\n method: 'GET',\n path: joinPaths(basePath, clientId),\n });\n }\n\n public verifyClient(token: string) {\n return this.request<Client>({\n method: 'POST',\n path: joinPaths(basePath, 'verify'),\n bodyParams: { token },\n });\n }\n\n public async getHandshakePayload(queryParams: GetHandshakePayloadParams) {\n return this.request<HandshakePayload>({\n method: 'GET',\n path: joinPaths(basePath, 'handshake_payload'),\n queryParams,\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { Domain } from '../resources/Domain';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/domains';\n\ntype AddDomainParams = {\n /**\n * The new domain name. For development instances, can contain the port, i.e myhostname:3000. For production instances, must be a valid FQDN, i.e mysite.com. Cannot contain protocol scheme.\n */\n name: string;\n /**\n * Marks the new domain as satellite. Only true is accepted at the moment.\n */\n is_satellite: boolean;\n /**\n * The full URL of the proxy which will forward requests to the Clerk Frontend API for this domain. Applicable only to production instances.\n */\n proxy_url?: string | null;\n};\n\ntype UpdateDomainParams = Partial<Pick<AddDomainParams, 'name' | 'proxy_url'>> & {\n /**\n * The ID of the domain that will be updated.\n */\n domainId: string;\n /**\n * Whether this is a domain for a secondary app, meaning that any subdomain provided is significant\n * and will be stored as part of the domain. This is useful for supporting multiple apps\n * (one primary and multiple secondaries) on the same root domain (eTLD+1).\n */\n is_secondary?: boolean | null;\n};\n\nexport class DomainAPI extends AbstractAPI {\n public async list() {\n return this.request<PaginatedResourceResponse<Domain[]>>({\n method: 'GET',\n path: basePath,\n });\n }\n\n public async add(params: AddDomainParams) {\n return this.request<Domain>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async update(params: UpdateDomainParams) {\n const { domainId, ...bodyParams } = params;\n\n this.requireId(domainId);\n\n return this.request<Domain>({\n method: 'PATCH',\n path: joinPaths(basePath, domainId),\n bodyParams: bodyParams,\n });\n }\n\n /**\n * Deletes a satellite domain for the instance.\n * It is currently not possible to delete the instance's primary domain.\n */\n public async delete(satelliteDomainId: string) {\n return this.deleteDomain(satelliteDomainId);\n }\n\n /**\n * @deprecated Use `delete` instead\n */\n public async deleteDomain(satelliteDomainId: string) {\n this.requireId(satelliteDomainId);\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, satelliteDomainId),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { DeletedObject, EmailAddress } from '../resources';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/email_addresses';\n\ntype CreateEmailAddressParams = {\n userId: string;\n emailAddress: string;\n verified?: boolean;\n primary?: boolean;\n};\n\ntype UpdateEmailAddressParams = {\n verified?: boolean;\n primary?: boolean;\n};\n\nexport class EmailAddressAPI extends AbstractAPI {\n public async getEmailAddress(emailAddressId: string) {\n this.requireId(emailAddressId);\n\n return this.request<EmailAddress>({\n method: 'GET',\n path: joinPaths(basePath, emailAddressId),\n });\n }\n\n public async createEmailAddress(params: CreateEmailAddressParams) {\n return this.request<EmailAddress>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updateEmailAddress(emailAddressId: string, params: UpdateEmailAddressParams = {}) {\n this.requireId(emailAddressId);\n\n return this.request<EmailAddress>({\n method: 'PATCH',\n path: joinPaths(basePath, emailAddressId),\n bodyParams: params,\n });\n }\n\n public async deleteEmailAddress(emailAddressId: string) {\n this.requireId(emailAddressId);\n\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, emailAddressId),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport { deprecated } from '../../util/shared';\nimport type { IdPOAuthAccessToken } from '../resources';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/oauth_applications/access_tokens';\n\nexport class IdPOAuthAccessTokenApi extends AbstractAPI {\n async verify(accessToken: string) {\n return this.request<IdPOAuthAccessToken>({\n method: 'POST',\n path: joinPaths(basePath, 'verify'),\n bodyParams: { access_token: accessToken },\n });\n }\n\n /**\n * @deprecated Use `verify()` instead. This method will be removed in the next major release.\n */\n async verifyAccessToken(accessToken: string) {\n deprecated('idPOAuthAccessToken.verifyAccessToken()', 'Use `idPOAuthAccessToken.verify()` instead.');\n return this.verify(accessToken);\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { Instance } from '../resources/Instance';\nimport type { InstanceRestrictions } from '../resources/InstanceRestrictions';\nimport type { OrganizationSettings } from '../resources/OrganizationSettings';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/instance';\n\ntype UpdateParams = {\n /**\n * Toggles test mode for this instance, allowing the use of test email addresses and phone numbers.\n *\n * @remarks Defaults to true for development instances.\n */\n testMode?: boolean | null | undefined;\n /**\n * Whether the instance should be using the HIBP service to check passwords for breaches\n */\n hibp?: boolean | null | undefined;\n /**\n * The \"enhanced_email_deliverability\" feature will send emails from \"verifications@clerk.dev\" instead of your domain.\n *\n * @remarks This can be helpful if you do not have a high domain reputation.\n */\n enhancedEmailDeliverability?: boolean | null | undefined;\n supportEmail?: string | null | undefined;\n clerkJsVersion?: string | null | undefined;\n developmentOrigin?: string | null | undefined;\n /**\n * For browser-like stacks such as browser extensions, Electron, or Capacitor.js the instance allowed origins need to be updated with the request origin value.\n *\n * @remarks For Chrome extensions popup, background, or service worker pages the origin is chrome-extension://extension_uiid. For Electron apps the default origin is http://localhost:3000. For Capacitor, the origin is capacitor://localhost.\n */\n allowedOrigins?: Array<string> | undefined;\n /**\n * Whether the instance should use URL-based session syncing in development mode (i.e. without third-party cookies).\n */\n urlBasedSessionSyncing?: boolean | null | undefined;\n};\n\ntype UpdateRestrictionsParams = {\n allowlist?: boolean | null | undefined;\n blocklist?: boolean | null | undefined;\n blockEmailSubaddresses?: boolean | null | undefined;\n blockDisposableEmailDomains?: boolean | null | undefined;\n ignoreDotsForGmailAddresses?: boolean | null | undefined;\n};\n\ntype UpdateOrganizationSettingsParams = {\n enabled?: boolean | null | undefined;\n maxAllowedMemberships?: number | null | undefined;\n adminDeleteEnabled?: boolean | null | undefined;\n domainsEnabled?: boolean | null | undefined;\n /**\n * Specifies which [enrollment modes](https://clerk.com/docs/guides/organizations/verified-domains#enrollment-mode) to enable for your Organization Domains.\n *\n * @remarks Supported modes are 'automatic_invitation' & 'automatic_suggestion'.\n */\n domainsEnrollmentModes?: Array<string> | undefined;\n /**\n * Specifies what the default organization role is for an organization creator.\n */\n creatorRoleId?: string | null | undefined;\n /**\n * Specifies what the default organization role is for the organization domains.\n */\n domainsDefaultRoleId?: string | null | undefined;\n};\n\nexport class InstanceAPI extends AbstractAPI {\n public async get() {\n return this.request<Instance>({\n method: 'GET',\n path: basePath,\n });\n }\n\n public async update(params: UpdateParams) {\n return this.request<void>({\n method: 'PATCH',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updateRestrictions(params: UpdateRestrictionsParams) {\n return this.request<InstanceRestrictions>({\n method: 'PATCH',\n path: joinPaths(basePath, 'restrictions'),\n bodyParams: params,\n });\n }\n\n public async updateOrganizationSettings(params: UpdateOrganizationSettingsParams) {\n return this.request<OrganizationSettings>({\n method: 'PATCH',\n path: joinPaths(basePath, 'organization_settings'),\n bodyParams: params,\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { InvitationStatus } from '../resources/Enums';\nimport type { Invitation } from '../resources/Invitation';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/invitations';\n\ntype TemplateSlug = 'invitation' | 'waitlist_invitation';\n\ntype CreateParams = {\n emailAddress: string;\n expiresInDays?: number;\n ignoreExisting?: boolean;\n notify?: boolean;\n publicMetadata?: UserPublicMetadata;\n redirectUrl?: string;\n templateSlug?: TemplateSlug;\n};\n\ntype CreateBulkParams = Array<CreateParams>;\n\ntype GetInvitationListParams = ClerkPaginationRequest<{\n /**\n * Filters invitations based on their status.\n *\n * @example\n * Get all revoked invitations\n * ```ts\n * import { createClerkClient } from '@clerk/backend';\n * const clerkClient = createClerkClient(...)\n * await clerkClient.invitations.getInvitationList({ status: 'revoked' })\n * ```\n */\n status?: InvitationStatus;\n /**\n * Filters invitations based on `email_address` or `id`.\n *\n * @example\n * Get all invitations for a specific email address\n * ```ts\n * import { createClerkClient } from '@clerk/backend';\n * const clerkClient = createClerkClient(...)\n * await clerkClient.invitations.getInvitationList({ query: 'user@example.com' })\n * ```\n */\n query?: string;\n}>;\n\nexport class InvitationAPI extends AbstractAPI {\n public async getInvitationList(params: GetInvitationListParams = {}) {\n return this.request<PaginatedResourceResponse<Invitation[]>>({\n method: 'GET',\n path: basePath,\n queryParams: { ...params, paginated: true },\n });\n }\n\n public async createInvitation(params: CreateParams) {\n return this.request<Invitation>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async createInvitationBulk(params: CreateBulkParams) {\n return this.request<Invitation>({\n method: 'POST',\n path: joinPaths(basePath, 'bulk'),\n bodyParams: params,\n });\n }\n\n public async revokeInvitation(invitationId: string) {\n this.requireId(invitationId);\n return this.request<Invitation>({\n method: 'POST',\n path: joinPaths(basePath, invitationId, 'revoke'),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { Machine } from '../resources/Machine';\nimport type { MachineScope } from '../resources/MachineScope';\nimport type { MachineSecretKey } from '../resources/MachineSecretKey';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/machines';\n\ntype CreateMachineParams = {\n /**\n * The name of the machine.\n */\n name: string;\n /**\n * Array of machine IDs that this machine will have access to.\n */\n scopedMachines?: string[];\n /**\n * The default time-to-live (TTL) in seconds for tokens created by this machine.\n */\n defaultTokenTtl?: number;\n};\n\ntype UpdateMachineParams = {\n /**\n * The ID of the machine to update.\n */\n machineId: string;\n /**\n * The name of the machine.\n */\n name?: string;\n /**\n * The default time-to-live (TTL) in seconds for tokens created by this machine.\n */\n defaultTokenTtl?: number;\n};\n\ntype GetMachineListParams = ClerkPaginationRequest<{\n /**\n * Sorts machines by name or created_at.\n * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order.\n */\n orderBy?: WithSign<'name' | 'created_at'>;\n /**\n * Returns machines that have a ID or name that matches the given query.\n */\n query?: string;\n}>;\n\ntype RotateMachineSecretKeyParams = {\n /**\n * The ID of the machine to rotate the secret key for.\n */\n machineId: string;\n /**\n * The time in seconds that the previous secret key will remain valid after rotation.\n */\n previousTokenTtl: number;\n};\n\nexport class MachineApi extends AbstractAPI {\n async get(machineId: string) {\n this.requireId(machineId);\n return this.request<Machine>({\n method: 'GET',\n path: joinPaths(basePath, machineId),\n });\n }\n\n async list(queryParams: GetMachineListParams = {}) {\n return this.request<PaginatedResourceResponse<Machine[]>>({\n method: 'GET',\n path: basePath,\n queryParams,\n });\n }\n\n async create(bodyParams: CreateMachineParams) {\n return this.request<Machine>({\n method: 'POST',\n path: basePath,\n bodyParams,\n });\n }\n\n async update(params: UpdateMachineParams) {\n const { machineId, ...bodyParams } = params;\n this.requireId(machineId);\n return this.request<Machine>({\n method: 'PATCH',\n path: joinPaths(basePath, machineId),\n bodyParams,\n });\n }\n\n async delete(machineId: string) {\n this.requireId(machineId);\n return this.request<Machine>({\n method: 'DELETE',\n path: joinPaths(basePath, machineId),\n });\n }\n\n async getSecretKey(machineId: string) {\n this.requireId(machineId);\n return this.request<MachineSecretKey>({\n method: 'GET',\n path: joinPaths(basePath, machineId, 'secret_key'),\n });\n }\n\n async rotateSecretKey(params: RotateMachineSecretKeyParams) {\n const { machineId, previousTokenTtl } = params;\n this.requireId(machineId);\n return this.request<MachineSecretKey>({\n method: 'POST',\n path: joinPaths(basePath, machineId, 'secret_key', 'rotate'),\n bodyParams: {\n previousTokenTtl,\n },\n });\n }\n\n /**\n * Creates a new machine scope, allowing the specified machine to access another machine.\n *\n * @param machineId - The ID of the machine that will have access to another machine.\n * @param toMachineId - The ID of the machine that will be scoped to the current machine.\n */\n async createScope(machineId: string, toMachineId: string) {\n this.requireId(machineId);\n return this.request<MachineScope>({\n method: 'POST',\n path: joinPaths(basePath, machineId, 'scopes'),\n bodyParams: {\n toMachineId,\n },\n });\n }\n\n /**\n * Deletes a machine scope, removing access from one machine to another.\n *\n * @param machineId - The ID of the machine that has access to another machine.\n * @param otherMachineId - The ID of the machine that is being accessed.\n */\n async deleteScope(machineId: string, otherMachineId: string) {\n this.requireId(machineId);\n return this.request<MachineScope>({\n method: 'DELETE',\n path: joinPaths(basePath, machineId, 'scopes', otherMachineId),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport { deprecated } from '../../util/shared';\nimport type { ClerkBackendApiRequestOptions } from '../request';\nimport type { M2MToken } from '../resources/M2MToken';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/m2m_tokens';\n\ntype CreateM2MTokenParams = {\n /**\n * Custom machine secret key for authentication.\n */\n machineSecretKey?: string;\n /**\n * Number of seconds until the token expires.\n *\n * @default null - Token does not expire\n */\n secondsUntilExpiration?: number | null;\n claims?: Record<string, unknown> | null;\n};\n\ntype RevokeM2MTokenParams = {\n /**\n * Custom machine secret key for authentication.\n */\n machineSecretKey?: string;\n /**\n * Machine-to-machine token ID to revoke.\n */\n m2mTokenId: string;\n revocationReason?: string | null;\n};\n\ntype VerifyM2MTokenParams = {\n /**\n * Custom machine secret key for authentication.\n */\n machineSecretKey?: string;\n /**\n * Machine-to-machine token to verify.\n */\n token: string;\n};\n\nexport class M2MTokenApi extends AbstractAPI {\n #createRequestOptions(options: ClerkBackendApiRequestOptions, machineSecretKey?: string) {\n if (machineSecretKey) {\n return {\n ...options,\n headerParams: {\n ...options.headerParams,\n Authorization: `Bearer ${machineSecretKey}`,\n },\n };\n }\n\n return options;\n }\n\n async createToken(params?: CreateM2MTokenParams) {\n const { claims = null, machineSecretKey, secondsUntilExpiration = null } = params || {};\n\n const requestOptions = this.#createRequestOptions(\n {\n method: 'POST',\n path: basePath,\n bodyParams: {\n secondsUntilExpiration,\n claims,\n },\n },\n machineSecretKey,\n );\n\n return this.request<M2MToken>(requestOptions);\n }\n\n async revokeToken(params: RevokeM2MTokenParams) {\n const { m2mTokenId, revocationReason = null, machineSecretKey } = params;\n\n this.requireId(m2mTokenId);\n\n const requestOptions = this.#createRequestOptions(\n {\n method: 'POST',\n path: joinPaths(basePath, m2mTokenId, 'revoke'),\n bodyParams: {\n revocationReason,\n },\n },\n machineSecretKey,\n );\n\n return this.request<M2MToken>(requestOptions);\n }\n\n async verify(params: VerifyM2MTokenParams) {\n const { token, machineSecretKey } = params;\n\n const requestOptions = this.#createRequestOptions(\n {\n method: 'POST',\n path: joinPaths(basePath, 'verify'),\n bodyParams: { token },\n },\n machineSecretKey,\n );\n\n return this.request<M2MToken>(requestOptions);\n }\n\n /**\n * @deprecated Use `verify()` instead. This method will be removed in the next major release.\n */\n async verifyToken(params: VerifyM2MTokenParams) {\n deprecated('m2m.verifyToken()', 'Use `m2m.verify()` instead.');\n return this.verify(params);\n }\n}\n","import type { JwksJSON } from '../resources/JSON';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/jwks';\n\nexport class JwksAPI extends AbstractAPI {\n public async getJwks() {\n return this.request<JwksJSON>({\n method: 'GET',\n path: basePath,\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\nimport { joinPaths } from 'src/util/path';\n\nimport type { DeletedObject, JwtTemplate } from '../resources';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/jwt_templates';\n\ntype Claims = object;\n\ntype CreateJWTTemplateParams = {\n /**\n * JWT template name\n */\n name: string;\n /**\n * JWT template claims in JSON format\n */\n claims: Claims;\n /**\n * JWT token lifetime\n */\n lifetime?: number | null | undefined;\n /**\n * JWT token allowed clock skew\n */\n allowedClockSkew?: number | null | undefined;\n /**\n * Whether a custom signing key/algorithm is also provided for this template\n */\n customSigningKey?: boolean | undefined;\n /**\n * The custom signing algorithm to use when minting JWTs. Required if `custom_signing_key` is `true`.\n */\n signingAlgorithm?: string | null | undefined;\n /**\n * The custom signing private key to use when minting JWTs. Required if `custom_signing_key` is `true`.\n */\n signingKey?: string | null | undefined;\n};\n\ntype UpdateJWTTemplateParams = CreateJWTTemplateParams & {\n /**\n * JWT template ID\n */\n templateId: string;\n};\n\nexport class JwtTemplatesApi extends AbstractAPI {\n public async list(params: ClerkPaginationRequest = {}) {\n return this.request<JwtTemplate[]>({\n method: 'GET',\n path: basePath,\n queryParams: { ...params, paginated: true },\n });\n }\n\n public async get(templateId: string) {\n this.requireId(templateId);\n\n return this.request<JwtTemplate>({\n method: 'GET',\n path: joinPaths(basePath, templateId),\n });\n }\n\n public async create(params: CreateJWTTemplateParams) {\n return this.request<JwtTemplate>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async update(params: UpdateJWTTemplateParams) {\n const { templateId, ...bodyParams } = params;\n\n this.requireId(templateId);\n return this.request<JwtTemplate>({\n method: 'PATCH',\n path: joinPaths(basePath, templateId),\n bodyParams,\n });\n }\n\n public async delete(templateId: string) {\n this.requireId(templateId);\n\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, templateId),\n });\n }\n}\n","import type { ClerkPaginationRequest, OrganizationEnrollmentMode } from '@clerk/shared/types';\n\nimport { runtime } from '../../runtime';\nimport { joinPaths } from '../../util/path';\nimport type {\n Organization,\n OrganizationDomain,\n OrganizationInvitation,\n OrganizationInvitationStatus,\n OrganizationMembership,\n} from '../resources';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { OrganizationMembershipRole } from '../resources/Enums';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/organizations';\n\ntype MetadataParams<TPublic = OrganizationPublicMetadata, TPrivate = OrganizationPrivateMetadata> = {\n publicMetadata?: TPublic;\n privateMetadata?: TPrivate;\n};\n\ntype GetOrganizationListParams = ClerkPaginationRequest<{\n includeMembersCount?: boolean;\n query?: string;\n orderBy?: WithSign<'name' | 'created_at' | 'members_count'>;\n organizationId?: string[];\n}>;\n\ntype CreateParams = {\n name: string;\n slug?: string;\n /* The User id for the user creating the organization. The user will become an administrator for the organization. */\n createdBy?: string;\n maxAllowedMemberships?: number;\n} & MetadataParams;\n\ntype GetOrganizationParams = ({ organizationId: string } | { slug: string }) & {\n includeMembersCount?: boolean;\n};\n\ntype UpdateParams = {\n name?: string;\n slug?: string;\n adminDeleteEnabled?: boolean;\n maxAllowedMemberships?: number;\n} & MetadataParams;\n\ntype UpdateLogoParams = {\n file: Blob | File;\n uploaderUserId?: string;\n};\n\ntype UpdateMetadataParams = MetadataParams;\n\ntype GetOrganizationMembershipListParams = ClerkPaginationRequest<{\n organizationId: string;\n\n /**\n * Sorts organizations memberships by phone_number, email_address, created_at, first_name, last_name or username.\n * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order.\n */\n orderBy?: WithSign<'phone_number' | 'email_address' | 'created_at' | 'first_name' | 'last_name' | 'username'>;\n\n /**\n * Returns users with the user ids specified. For each user id, the `+` and `-` can be\n * prepended to the id, which denote whether the respective user id should be included or\n * excluded from the result set. Accepts up to 100 user ids. Any user ids not found are ignored.\n */\n userId?: string[];\n\n /* Returns users with the specified email addresses. Accepts up to 100 email addresses. Any email addresses not found are ignored. */\n emailAddress?: string[];\n\n /* Returns users with the specified phone numbers. Accepts up to 100 phone numbers. Any phone numbers not found are ignored. */\n phoneNumber?: string[];\n\n /* Returns users with the specified usernames. Accepts up to 100 usernames. Any usernames not found are ignored. */\n username?: string[];\n\n /* Returns users with the specified web3 wallet addresses. Accepts up to 100 web3 wallet addresses. Any web3 wallet addressed not found are ignored. */\n web3Wallet?: string[];\n\n /* Returns users with the specified roles. Accepts up to 100 roles. Any roles not found are ignored. */\n role?: OrganizationMembershipRole[];\n\n /**\n * Returns users that match the given query.\n * For possible matches, we check the email addresses, phone numbers, usernames, web3 wallets, user ids, first and last names.\n * The query value doesn't need to match the exact value you are looking for, it is capable of partial matches as well.\n */\n query?: string;\n\n /**\n * Returns users with emails that match the given query, via case-insensitive partial match.\n * For example, `email_address_query=ello` will match a user with the email `HELLO@example.com`.\n */\n emailAddressQuery?: string;\n\n /**\n * Returns users with phone numbers that match the given query, via case-insensitive partial match.\n * For example, `phone_number_query=555` will match a user with the phone number `+1555xxxxxxx`.\n */\n phoneNumberQuery?: string;\n\n /**\n * Returns users with usernames that match the given query, via case-insensitive partial match.\n * For example, `username_query=CoolUser` will match a user with the username `SomeCoolUser`.\n */\n usernameQuery?: string;\n\n /* Returns users with names that match the given query, via case-insensitive partial match. */\n nameQuery?: string;\n\n /**\n * Returns users whose last session activity was before the given date (with millisecond precision).\n * Example: use 1700690400000 to retrieve users whose last session activity was before 2023-11-23.\n */\n lastActiveAtBefore?: number;\n /**\n * Returns users whose last session activity was after the given date (with millisecond precision).\n * Example: use 1700690400000 to retrieve users whose last session activity was after 2023-11-23.\n */\n lastActiveAtAfter?: number;\n\n /**\n * Returns users who have been created before the given date (with millisecond precision).\n * Example: use 1730160000000 to retrieve users who have been created before 2024-10-29.\n */\n createdAtBefore?: number;\n\n /**\n * Returns users who have been created after the given date (with millisecond precision).\n * Example: use 1730160000000 to retrieve users who have been created after 2024-10-29.\n */\n createdAtAfter?: number;\n}>;\n\ntype GetInstanceOrganizationMembershipListParams = ClerkPaginationRequest<{\n /**\n * Sorts organizations memberships by phone_number, email_address, created_at, first_name, last_name or username.\n * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order.\n */\n orderBy?: WithSign<'phone_number' | 'email_address' | 'created_at' | 'first_name' | 'last_name' | 'username'>;\n}>;\n\ntype CreateOrganizationMembershipParams = {\n organizationId: string;\n userId: string;\n role: OrganizationMembershipRole;\n};\n\ntype UpdateOrganizationMembershipParams = CreateOrganizationMembershipParams;\n\ntype UpdateOrganizationMembershipMetadataParams = {\n organizationId: string;\n userId: string;\n} & MetadataParams<OrganizationMembershipPublicMetadata>;\n\ntype DeleteOrganizationMembershipParams = {\n organizationId: string;\n userId: string;\n};\n\ntype CreateOrganizationInvitationParams = {\n organizationId: string;\n emailAddress: string;\n role: OrganizationMembershipRole;\n expiresInDays?: number;\n inviterUserId?: string;\n privateMetadata?: OrganizationInvitationPrivateMetadata;\n publicMetadata?: OrganizationInvitationPublicMetadata;\n redirectUrl?: string;\n};\n\ntype CreateBulkOrganizationInvitationParams = Array<{\n emailAddress: string;\n role: OrganizationMembershipRole;\n expiresInDays?: number;\n inviterUserId?: string;\n privateMetadata?: OrganizationInvitationPrivateMetadata;\n publicMetadata?: OrganizationInvitationPublicMetadata;\n redirectUrl?: string;\n}>;\n\ntype GetOrganizationInvitationListParams = ClerkPaginationRequest<{\n organizationId: string;\n status?: OrganizationInvitationStatus[];\n}>;\n\ntype GetOrganizationInvitationParams = {\n organizationId: string;\n invitationId: string;\n};\n\ntype RevokeOrganizationInvitationParams = {\n organizationId: string;\n invitationId: string;\n requestingUserId?: string;\n};\n\ntype GetOrganizationDomainListParams = {\n organizationId: string;\n limit?: number;\n offset?: number;\n};\n\ntype CreateOrganizationDomainParams = {\n organizationId: string;\n name: string;\n enrollmentMode: OrganizationEnrollmentMode;\n verified?: boolean;\n};\n\ntype UpdateOrganizationDomainParams = {\n organizationId: string;\n domainId: string;\n} & Partial<CreateOrganizationDomainParams>;\n\ntype DeleteOrganizationDomainParams = {\n organizationId: string;\n domainId: string;\n};\n\nexport class OrganizationAPI extends AbstractAPI {\n public async getOrganizationList(params?: GetOrganizationListParams) {\n return this.request<PaginatedResourceResponse<Organization[]>>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async createOrganization(params: CreateParams) {\n return this.request<Organization>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async getOrganization(params: GetOrganizationParams) {\n const { includeMembersCount } = params;\n const organizationIdOrSlug = 'organizationId' in params ? params.organizationId : params.slug;\n this.requireId(organizationIdOrSlug);\n\n return this.request<Organization>({\n method: 'GET',\n path: joinPaths(basePath, organizationIdOrSlug),\n queryParams: {\n includeMembersCount,\n },\n });\n }\n\n public async updateOrganization(organizationId: string, params: UpdateParams) {\n this.requireId(organizationId);\n return this.request<Organization>({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId),\n bodyParams: params,\n });\n }\n\n public async updateOrganizationLogo(organizationId: string, params: UpdateLogoParams) {\n this.requireId(organizationId);\n\n const formData = new runtime.FormData();\n formData.append('file', params?.file);\n if (params?.uploaderUserId) {\n formData.append('uploader_user_id', params?.uploaderUserId);\n }\n\n return this.request<Organization>({\n method: 'PUT',\n path: joinPaths(basePath, organizationId, 'logo'),\n formData,\n });\n }\n\n public async deleteOrganizationLogo(organizationId: string) {\n this.requireId(organizationId);\n\n return this.request<Organization>({\n method: 'DELETE',\n path: joinPaths(basePath, organizationId, 'logo'),\n });\n }\n\n public async updateOrganizationMetadata(organizationId: string, params: UpdateMetadataParams) {\n this.requireId(organizationId);\n\n return this.request<Organization>({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId, 'metadata'),\n bodyParams: params,\n });\n }\n\n public async deleteOrganization(organizationId: string) {\n return this.request<Organization>({\n method: 'DELETE',\n path: joinPaths(basePath, organizationId),\n });\n }\n\n public async getOrganizationMembershipList(params: GetOrganizationMembershipListParams) {\n const { organizationId, ...queryParams } = params;\n this.requireId(organizationId);\n\n return this.request<PaginatedResourceResponse<OrganizationMembership[]>>({\n method: 'GET',\n path: joinPaths(basePath, organizationId, 'memberships'),\n queryParams,\n });\n }\n\n public async getInstanceOrganizationMembershipList(params: GetInstanceOrganizationMembershipListParams) {\n return this.request<PaginatedResourceResponse<OrganizationMembership[]>>({\n method: 'GET',\n path: '/organization_memberships',\n queryParams: params,\n });\n }\n\n public async createOrganizationMembership(params: CreateOrganizationMembershipParams) {\n const { organizationId, ...bodyParams } = params;\n this.requireId(organizationId);\n\n return this.request<OrganizationMembership>({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'memberships'),\n bodyParams,\n });\n }\n\n public async updateOrganizationMembership(params: UpdateOrganizationMembershipParams) {\n const { organizationId, userId, ...bodyParams } = params;\n this.requireId(organizationId);\n\n return this.request<OrganizationMembership>({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId, 'memberships', userId),\n bodyParams,\n });\n }\n\n public async updateOrganizationMembershipMetadata(params: UpdateOrganizationMembershipMetadataParams) {\n const { organizationId, userId, ...bodyParams } = params;\n\n return this.request<OrganizationMembership>({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId, 'memberships', userId, 'metadata'),\n bodyParams,\n });\n }\n\n public async deleteOrganizationMembership(params: DeleteOrganizationMembershipParams) {\n const { organizationId, userId } = params;\n this.requireId(organizationId);\n\n return this.request<OrganizationMembership>({\n method: 'DELETE',\n path: joinPaths(basePath, organizationId, 'memberships', userId),\n });\n }\n\n public async getOrganizationInvitationList(params: GetOrganizationInvitationListParams) {\n const { organizationId, ...queryParams } = params;\n this.requireId(organizationId);\n\n return this.request<PaginatedResourceResponse<OrganizationInvitation[]>>({\n method: 'GET',\n path: joinPaths(basePath, organizationId, 'invitations'),\n queryParams,\n });\n }\n\n public async createOrganizationInvitation(params: CreateOrganizationInvitationParams) {\n const { organizationId, ...bodyParams } = params;\n this.requireId(organizationId);\n\n return this.request<OrganizationInvitation>({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'invitations'),\n bodyParams,\n });\n }\n\n public async createOrganizationInvitationBulk(\n organizationId: string,\n params: CreateBulkOrganizationInvitationParams,\n ) {\n this.requireId(organizationId);\n\n return this.request<OrganizationInvitation[]>({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'invitations', 'bulk'),\n bodyParams: params,\n });\n }\n\n public async getOrganizationInvitation(params: GetOrganizationInvitationParams) {\n const { organizationId, invitationId } = params;\n this.requireId(organizationId);\n this.requireId(invitationId);\n\n return this.request<OrganizationInvitation>({\n method: 'GET',\n path: joinPaths(basePath, organizationId, 'invitations', invitationId),\n });\n }\n\n public async revokeOrganizationInvitation(params: RevokeOrganizationInvitationParams) {\n const { organizationId, invitationId, ...bodyParams } = params;\n this.requireId(organizationId);\n\n return this.request<OrganizationInvitation>({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'invitations', invitationId, 'revoke'),\n bodyParams,\n });\n }\n\n public async getOrganizationDomainList(params: GetOrganizationDomainListParams) {\n const { organizationId, ...queryParams } = params;\n this.requireId(organizationId);\n\n return this.request<PaginatedResourceResponse<OrganizationDomain[]>>({\n method: 'GET',\n path: joinPaths(basePath, organizationId, 'domains'),\n queryParams,\n });\n }\n\n public async createOrganizationDomain(params: CreateOrganizationDomainParams) {\n const { organizationId, ...bodyParams } = params;\n this.requireId(organizationId);\n\n return this.request<OrganizationDomain>({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'domains'),\n bodyParams: {\n ...bodyParams,\n verified: bodyParams.verified ?? true,\n },\n });\n }\n\n public async updateOrganizationDomain(params: UpdateOrganizationDomainParams) {\n const { organizationId, domainId, ...bodyParams } = params;\n this.requireId(organizationId);\n this.requireId(domainId);\n\n return this.request<OrganizationDomain>({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId, 'domains', domainId),\n bodyParams,\n });\n }\n\n public async deleteOrganizationDomain(params: DeleteOrganizationDomainParams) {\n const { organizationId, domainId } = params;\n this.requireId(organizationId);\n this.requireId(domainId);\n\n return this.request<OrganizationDomain>({\n method: 'DELETE',\n path: joinPaths(basePath, organizationId, 'domains', domainId),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { DeletedObject } from '../resources';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { OAuthApplication } from '../resources/OAuthApplication';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/oauth_applications';\n\ntype CreateOAuthApplicationParams = {\n /**\n * The name of the new OAuth application.\n *\n * @remarks Max length: 256\n */\n name: string;\n /**\n * An array of redirect URIs of the new OAuth application\n */\n redirectUris?: Array<string> | null | undefined;\n /**\n * Define the allowed scopes for the new OAuth applications that dictate the user payload of the OAuth user info endpoint. Available scopes are `profile`, `email`, `public_metadata`, `private_metadata`. Provide the requested scopes as a string, separated by spaces.\n */\n scopes?: string | null | undefined;\n /**\n * If true, this client is public and you can use the Proof Key of Code Exchange (PKCE) flow.\n */\n public?: boolean | null | undefined;\n};\n\ntype UpdateOAuthApplicationParams = CreateOAuthApplicationParams & {\n /**\n * The ID of the OAuth application to update\n */\n oauthApplicationId: string;\n};\n\ntype GetOAuthApplicationListParams = ClerkPaginationRequest<{\n /**\n * Sorts OAuth applications by name or created_at.\n * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order.\n */\n orderBy?: WithSign<'name' | 'created_at'>;\n}>;\n\nexport class OAuthApplicationsApi extends AbstractAPI {\n public async list(params: GetOAuthApplicationListParams = {}) {\n return this.request<PaginatedResourceResponse<OAuthApplication[]>>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async get(oauthApplicationId: string) {\n this.requireId(oauthApplicationId);\n\n return this.request<OAuthApplication>({\n method: 'GET',\n path: joinPaths(basePath, oauthApplicationId),\n });\n }\n\n public async create(params: CreateOAuthApplicationParams) {\n return this.request<OAuthApplication>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async update(params: UpdateOAuthApplicationParams) {\n const { oauthApplicationId, ...bodyParams } = params;\n\n this.requireId(oauthApplicationId);\n\n return this.request<OAuthApplication>({\n method: 'PATCH',\n path: joinPaths(basePath, oauthApplicationId),\n bodyParams,\n });\n }\n\n public async delete(oauthApplicationId: string) {\n this.requireId(oauthApplicationId);\n\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, oauthApplicationId),\n });\n }\n\n public async rotateSecret(oauthApplicationId: string) {\n this.requireId(oauthApplicationId);\n\n return this.request<OAuthApplication>({\n method: 'POST',\n path: joinPaths(basePath, oauthApplicationId, 'rotate_secret'),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { DeletedObject, PhoneNumber } from '../resources';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/phone_numbers';\n\ntype CreatePhoneNumberParams = {\n userId: string;\n phoneNumber: string;\n verified?: boolean;\n primary?: boolean;\n reservedForSecondFactor?: boolean;\n};\n\ntype UpdatePhoneNumberParams = {\n verified?: boolean;\n primary?: boolean;\n reservedForSecondFactor?: boolean;\n};\n\nexport class PhoneNumberAPI extends AbstractAPI {\n public async getPhoneNumber(phoneNumberId: string) {\n this.requireId(phoneNumberId);\n\n return this.request<PhoneNumber>({\n method: 'GET',\n path: joinPaths(basePath, phoneNumberId),\n });\n }\n\n public async createPhoneNumber(params: CreatePhoneNumberParams) {\n return this.request<PhoneNumber>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updatePhoneNumber(phoneNumberId: string, params: UpdatePhoneNumberParams = {}) {\n this.requireId(phoneNumberId);\n\n return this.request<PhoneNumber>({\n method: 'PATCH',\n path: joinPaths(basePath, phoneNumberId),\n bodyParams: params,\n });\n }\n\n public async deletePhoneNumber(phoneNumberId: string) {\n this.requireId(phoneNumberId);\n\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, phoneNumberId),\n });\n }\n}\n","import type { ProxyCheck } from '../resources';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/proxy_checks';\n\ntype VerifyParams = {\n domainId: string;\n proxyUrl: string;\n};\n\nexport class ProxyCheckAPI extends AbstractAPI {\n public async verify(params: VerifyParams) {\n return this.request<ProxyCheck>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { RedirectUrl } from '../resources/RedirectUrl';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/redirect_urls';\n\ntype CreateRedirectUrlParams = {\n url: string;\n};\n\nexport class RedirectUrlAPI extends AbstractAPI {\n public async getRedirectUrlList() {\n return this.request<PaginatedResourceResponse<RedirectUrl[]>>({\n method: 'GET',\n path: basePath,\n queryParams: { paginated: true },\n });\n }\n\n public async getRedirectUrl(redirectUrlId: string) {\n this.requireId(redirectUrlId);\n return this.request<RedirectUrl>({\n method: 'GET',\n path: joinPaths(basePath, redirectUrlId),\n });\n }\n\n public async createRedirectUrl(params: CreateRedirectUrlParams) {\n return this.request<RedirectUrl>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async deleteRedirectUrl(redirectUrlId: string) {\n this.requireId(redirectUrlId);\n return this.request<RedirectUrl>({\n method: 'DELETE',\n path: joinPaths(basePath, redirectUrlId),\n });\n }\n}\n","import type { ClerkPaginationRequest, SamlIdpSlug } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { SamlConnection } from '../resources';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/saml_connections';\n\ntype SamlConnectionListParams = ClerkPaginationRequest<{\n /**\n * Returns SAML connections that have a name that matches the given query, via case-insensitive partial match.\n */\n query?: string;\n\n /**\n * Sorts SAML connections by phone_number, email_address, created_at, first_name, last_name or username.\n * By prepending one of those values with + or -, we can choose to sort in ascending (ASC) or descending (DESC) order.\n */\n orderBy?: WithSign<'phone_number' | 'email_address' | 'created_at' | 'first_name' | 'last_name' | 'username'>;\n\n /**\n * Returns SAML connections that have an associated organization ID to the given organizations.\n * For each organization id, the + and - can be prepended to the id, which denote whether the\n * respective organization should be included or excluded from the result set. Accepts up to 100 organization ids.\n */\n organizationId?: WithSign<string>[];\n}>;\n\ntype CreateSamlConnectionParams = {\n name: string;\n provider: SamlIdpSlug;\n domain: string;\n organizationId?: string;\n idpEntityId?: string;\n idpSsoUrl?: string;\n idpCertificate?: string;\n idpMetadataUrl?: string;\n idpMetadata?: string;\n attributeMapping?: {\n emailAddress?: string;\n firstName?: string;\n lastName?: string;\n userId?: string;\n };\n};\n\ntype UpdateSamlConnectionParams = {\n name?: string;\n provider?: SamlIdpSlug;\n domain?: string;\n organizationId?: string;\n idpEntityId?: string;\n idpSsoUrl?: string;\n idpCertificate?: string;\n idpMetadataUrl?: string;\n idpMetadata?: string;\n attributeMapping?: {\n emailAddress?: string;\n firstName?: string;\n lastName?: string;\n userId?: string;\n };\n active?: boolean;\n syncUserAttributes?: boolean;\n allowSubdomains?: boolean;\n allowIdpInitiated?: boolean;\n};\n\nexport class SamlConnectionAPI extends AbstractAPI {\n public async getSamlConnectionList(params: SamlConnectionListParams = {}) {\n return this.request<PaginatedResourceResponse<SamlConnection[]>>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async createSamlConnection(params: CreateSamlConnectionParams) {\n return this.request<SamlConnection>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n options: {\n deepSnakecaseBodyParamKeys: true,\n },\n });\n }\n\n public async getSamlConnection(samlConnectionId: string) {\n this.requireId(samlConnectionId);\n return this.request<SamlConnection>({\n method: 'GET',\n path: joinPaths(basePath, samlConnectionId),\n });\n }\n\n public async updateSamlConnection(samlConnectionId: string, params: UpdateSamlConnectionParams = {}) {\n this.requireId(samlConnectionId);\n\n return this.request<SamlConnection>({\n method: 'PATCH',\n path: joinPaths(basePath, samlConnectionId),\n bodyParams: params,\n options: {\n deepSnakecaseBodyParamKeys: true,\n },\n });\n }\n public async deleteSamlConnection(samlConnectionId: string) {\n this.requireId(samlConnectionId);\n return this.request<SamlConnection>({\n method: 'DELETE',\n path: joinPaths(basePath, samlConnectionId),\n });\n }\n}\n","import type { ClerkPaginationRequest, SessionStatus } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { Cookies } from '../resources/Cookies';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { Session } from '../resources/Session';\nimport type { Token } from '../resources/Token';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/sessions';\n\ntype SessionListParams = ClerkPaginationRequest<{\n clientId?: string;\n userId?: string;\n status?: SessionStatus;\n}>;\n\ntype RefreshTokenParams = {\n expired_token: string;\n refresh_token: string;\n request_origin: string;\n request_originating_ip?: string;\n request_headers?: Record<string, string[]>;\n suffixed_cookies?: boolean;\n format?: 'token' | 'cookie';\n};\n\ntype CreateSessionParams = {\n userId: string;\n};\n\nexport class SessionAPI extends AbstractAPI {\n public async getSessionList(params: SessionListParams = {}) {\n return this.request<PaginatedResourceResponse<Session[]>>({\n method: 'GET',\n path: basePath,\n queryParams: { ...params, paginated: true },\n });\n }\n\n public async getSession(sessionId: string) {\n this.requireId(sessionId);\n return this.request<Session>({\n method: 'GET',\n path: joinPaths(basePath, sessionId),\n });\n }\n\n public async createSession(params: CreateSessionParams) {\n return this.request<Session>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async revokeSession(sessionId: string) {\n this.requireId(sessionId);\n return this.request<Session>({\n method: 'POST',\n path: joinPaths(basePath, sessionId, 'revoke'),\n });\n }\n\n public async verifySession(sessionId: string, token: string) {\n this.requireId(sessionId);\n return this.request<Session>({\n method: 'POST',\n path: joinPaths(basePath, sessionId, 'verify'),\n bodyParams: { token },\n });\n }\n\n /**\n * Retrieves a session token or generates a JWT using a specified template.\n *\n * @param sessionId - The ID of the session for which to generate the token\n * @param template - Optional name of the JWT template configured in the Clerk Dashboard.\n * @param expiresInSeconds - Optional expiration time for the token in seconds.\n * If not provided, uses the default expiration.\n *\n * @returns A promise that resolves to the generated token\n *\n * @throws {Error} When sessionId is invalid or empty\n */\n public async getToken(sessionId: string, template?: string, expiresInSeconds?: number) {\n this.requireId(sessionId);\n\n const path = template\n ? joinPaths(basePath, sessionId, 'tokens', template)\n : joinPaths(basePath, sessionId, 'tokens');\n\n const requestOptions: any = {\n method: 'POST',\n path,\n };\n\n if (expiresInSeconds !== undefined) {\n requestOptions.bodyParams = { expires_in_seconds: expiresInSeconds };\n }\n\n return this.request<Token>(requestOptions);\n }\n\n public async refreshSession(sessionId: string, params: RefreshTokenParams & { format: 'token' }): Promise<Token>;\n public async refreshSession(sessionId: string, params: RefreshTokenParams & { format: 'cookie' }): Promise<Cookies>;\n public async refreshSession(sessionId: string, params: RefreshTokenParams): Promise<Token>;\n public async refreshSession(sessionId: string, params: RefreshTokenParams): Promise<Token | Cookies> {\n this.requireId(sessionId);\n const { suffixed_cookies, ...restParams } = params;\n return this.request({\n method: 'POST',\n path: joinPaths(basePath, sessionId, 'refresh'),\n bodyParams: restParams,\n queryParams: { suffixed_cookies },\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { SignInToken } from '../resources/SignInTokens';\nimport { AbstractAPI } from './AbstractApi';\n\ntype CreateSignInTokensParams = {\n userId: string;\n expiresInSeconds: number;\n};\n\nconst basePath = '/sign_in_tokens';\n\nexport class SignInTokenAPI extends AbstractAPI {\n public async createSignInToken(params: CreateSignInTokensParams) {\n return this.request<SignInToken>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async revokeSignInToken(signInTokenId: string) {\n this.requireId(signInTokenId);\n return this.request<SignInToken>({\n method: 'POST',\n path: joinPaths(basePath, signInTokenId, 'revoke'),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { SignUpAttempt } from '../resources/SignUpAttempt';\nimport { AbstractAPI } from './AbstractApi';\n\ntype UpdateSignUpParams = {\n signUpAttemptId: string;\n externalId?: string | null;\n customAction?: boolean | null;\n};\n\nconst basePath = '/sign_ups';\n\nexport class SignUpAPI extends AbstractAPI {\n public async get(signUpAttemptId: string) {\n this.requireId(signUpAttemptId);\n\n return this.request<SignUpAttempt>({\n method: 'GET',\n path: joinPaths(basePath, signUpAttemptId),\n });\n }\n\n public async update(params: UpdateSignUpParams) {\n const { signUpAttemptId, ...bodyParams } = params;\n\n return this.request<SignUpAttempt>({\n method: 'PATCH',\n path: joinPaths(basePath, signUpAttemptId),\n bodyParams,\n });\n }\n}\n","import type { TestingToken } from '../resources/TestingToken';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/testing_tokens';\n\nexport class TestingTokenAPI extends AbstractAPI {\n public async createTestingToken() {\n return this.request<TestingToken>({\n method: 'POST',\n path: basePath,\n });\n }\n}\n","import type { ClerkPaginationRequest, OAuthProvider, OrganizationInvitationStatus } from '@clerk/shared/types';\n\nimport { runtime } from '../../runtime';\nimport { joinPaths } from '../../util/path';\nimport { deprecated } from '../../util/shared';\nimport type {\n DeletedObject,\n OauthAccessToken,\n OrganizationInvitation,\n OrganizationMembership,\n User,\n} from '../resources';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/users';\n\ntype UserCountParams = {\n emailAddress?: string[];\n phoneNumber?: string[];\n username?: string[];\n web3Wallet?: string[];\n query?: string;\n userId?: string[];\n externalId?: string[];\n};\n\ntype UserListParams = ClerkPaginationRequest<\n UserCountParams & {\n orderBy?: WithSign<\n | 'created_at'\n | 'updated_at'\n | 'email_address'\n | 'web3wallet'\n | 'first_name'\n | 'last_name'\n | 'phone_number'\n | 'username'\n | 'last_active_at'\n | 'last_sign_in_at'\n >;\n last_active_at_since?: number;\n organizationId?: string[];\n }\n>;\n\ntype UserMetadataParams = {\n publicMetadata?: UserPublicMetadata;\n privateMetadata?: UserPrivateMetadata;\n unsafeMetadata?: UserUnsafeMetadata;\n};\n\ntype PasswordHasher =\n | 'argon2i'\n | 'argon2id'\n | 'awscognito'\n | 'bcrypt'\n | 'bcrypt_sha256_django'\n | 'md5'\n | 'pbkdf2_sha256'\n | 'pbkdf2_sha256_django'\n | 'pbkdf2_sha1'\n | 'phpass'\n | 'scrypt_firebase'\n | 'scrypt_werkzeug'\n | 'sha256'\n | 'md5_phpass'\n | 'ldap_ssha';\n\ntype UserPasswordHashingParams = {\n passwordDigest: string;\n passwordHasher: PasswordHasher;\n};\n\ntype CreateUserParams = {\n externalId?: string;\n emailAddress?: string[];\n phoneNumber?: string[];\n username?: string;\n password?: string;\n firstName?: string;\n lastName?: string;\n /** The locale of the user in BCP-47 format. */\n locale?: string;\n skipPasswordChecks?: boolean;\n skipPasswordRequirement?: boolean;\n skipLegalChecks?: boolean;\n legalAcceptedAt?: Date;\n totpSecret?: string;\n backupCodes?: string[];\n createdAt?: Date;\n} & UserMetadataParams &\n (UserPasswordHashingParams | object);\n\ntype UpdateUserParams = {\n /** The first name to assign to the user. */\n firstName?: string;\n\n /** The last name of the user. */\n lastName?: string;\n\n /** The username to give to the user. It must be unique across your instance. */\n username?: string;\n\n /** The plaintext password to give the user. Must be at least 8 characters long, and can not be in any list of hacked passwords. */\n password?: string;\n\n /** Set it to true if you're updating the user's password and want to skip any password policy settings check. This parameter can only be used when providing a password. */\n skipPasswordChecks?: boolean;\n\n /** Set to true to sign out the user from all their active sessions once their password is updated. This parameter can only be used when providing a password. */\n signOutOfOtherSessions?: boolean;\n\n /** The ID of the email address to set as primary. It must be verified, and present on the current user. */\n primaryEmailAddressID?: string;\n\n /** If set to true, the user will be notified that their primary email address has changed. By default, no notification is sent. */\n notifyPrimaryEmailAddressChanged?: boolean;\n\n /** The ID of the phone number to set as primary. It must be verified, and present on the current user. */\n primaryPhoneNumberID?: string;\n\n /** The ID of the web3 wallets to set as primary. It must be verified, and present on the current user. */\n primaryWeb3WalletID?: string;\n\n /** The ID of the image to set as the user's profile image */\n profileImageID?: string;\n\n /**\n * In case TOTP is configured on the instance, you can provide the secret to enable it on the specific user without the need to reset it.\n * Please note that currently the supported options are:\n * - Period: 30 seconds\n * - Code length: 6 digits\n * - Algorithm: SHA1\n */\n totpSecret?: string;\n\n /** If Backup Codes are configured on the instance, you can provide them to enable it on the specific user without the need to reset them. You must provide the backup codes in plain format or the corresponding bcrypt digest. */\n backupCodes?: string[];\n\n /** The ID of the user as used in your external systems or your previous authentication solution. Must be unique across your instance. */\n externalId?: string;\n\n /** A custom timestamp denoting when the user signed up to the application, specified in RFC3339 format (e.g. 2012-10-20T07:15:20.902Z). */\n createdAt?: Date;\n\n /** When set to true all legal checks are skipped. It is not recommended to skip legal checks unless you are migrating a user to Clerk. */\n skipLegalChecks?: boolean;\n\n /** A custom timestamp denoting when the user accepted legal requirements, specified in RFC3339 format (e.g. 2012-10-20T07:15:20.902Z). */\n legalAcceptedAt?: Date;\n\n /** The locale of the user in BCP-47 format. */\n locale?: string;\n\n /** If true, the user can delete themselves with the Frontend API. */\n deleteSelfEnabled?: boolean;\n\n /** If true, the user can create organizations with the Frontend API. */\n createOrganizationEnabled?: boolean;\n\n /** The maximum number of organizations the user can create. 0 means unlimited. */\n createOrganizationsLimit?: number;\n} & UserMetadataParams &\n (UserPasswordHashingParams | object);\n\ntype GetOrganizationMembershipListParams = ClerkPaginationRequest<{\n userId: string;\n}>;\n\ntype GetOrganizationInvitationListParams = ClerkPaginationRequest<{\n userId: string;\n status?: OrganizationInvitationStatus;\n}>;\n\ntype VerifyPasswordParams = {\n userId: string;\n password: string;\n};\n\ntype VerifyTOTPParams = {\n userId: string;\n code: string;\n};\n\ntype DeleteUserPasskeyParams = {\n userId: string;\n passkeyIdentificationId: string;\n};\n\ntype DeleteWeb3WalletParams = {\n userId: string;\n web3WalletIdentificationId: string;\n};\n\ntype DeleteUserExternalAccountParams = {\n userId: string;\n externalAccountId: string;\n};\n\ntype UserID = {\n userId: string;\n};\n\nexport class UserAPI extends AbstractAPI {\n public async getUserList(params: UserListParams = {}) {\n const { limit, offset, orderBy, ...userCountParams } = params;\n // TODO(dimkl): Temporary change to populate totalCount using a 2nd BAPI call to /users/count endpoint\n // until we update the /users endpoint to be paginated in a next BAPI version.\n // In some edge cases the data.length != totalCount due to a creation of a user between the 2 api responses\n const [data, totalCount] = await Promise.all([\n this.request<User[]>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n }),\n this.getCount(userCountParams),\n ]);\n return { data, totalCount } as PaginatedResourceResponse<User[]>;\n }\n\n public async getUser(userId: string) {\n this.requireId(userId);\n return this.request<User>({\n method: 'GET',\n path: joinPaths(basePath, userId),\n });\n }\n\n public async createUser(params: CreateUserParams) {\n return this.request<User>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updateUser(userId: string, params: UpdateUserParams = {}) {\n this.requireId(userId);\n\n return this.request<User>({\n method: 'PATCH',\n path: joinPaths(basePath, userId),\n bodyParams: params,\n });\n }\n\n public async updateUserProfileImage(userId: string, params: { file: Blob | File }) {\n this.requireId(userId);\n\n const formData = new runtime.FormData();\n formData.append('file', params?.file);\n\n return this.request<User>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'profile_image'),\n formData,\n });\n }\n\n public async updateUserMetadata(userId: string, params: UserMetadataParams) {\n this.requireId(userId);\n\n return this.request<User>({\n method: 'PATCH',\n path: joinPaths(basePath, userId, 'metadata'),\n bodyParams: params,\n });\n }\n\n public async deleteUser(userId: string) {\n this.requireId(userId);\n return this.request<User>({\n method: 'DELETE',\n path: joinPaths(basePath, userId),\n });\n }\n\n public async getCount(params: UserCountParams = {}) {\n return this.request<number>({\n method: 'GET',\n path: joinPaths(basePath, 'count'),\n queryParams: params,\n });\n }\n\n /** @deprecated Use `getUserOauthAccessToken` without the `oauth_` provider prefix . */\n public async getUserOauthAccessToken(\n userId: string,\n provider: `oauth_${OAuthProvider}`,\n ): Promise<PaginatedResourceResponse<OauthAccessToken[]>>;\n public async getUserOauthAccessToken(\n userId: string,\n provider: OAuthProvider,\n ): Promise<PaginatedResourceResponse<OauthAccessToken[]>>;\n public async getUserOauthAccessToken(userId: string, provider: `oauth_${OAuthProvider}` | OAuthProvider) {\n this.requireId(userId);\n const hasPrefix = provider.startsWith('oauth_');\n const _provider = hasPrefix ? provider : `oauth_${provider}`;\n\n if (hasPrefix) {\n deprecated(\n 'getUserOauthAccessToken(userId, provider)',\n 'Remove the `oauth_` prefix from the `provider` argument.',\n );\n }\n\n return this.request<PaginatedResourceResponse<OauthAccessToken[]>>({\n method: 'GET',\n path: joinPaths(basePath, userId, 'oauth_access_tokens', _provider),\n queryParams: { paginated: true },\n });\n }\n\n public async disableUserMFA(userId: string) {\n this.requireId(userId);\n return this.request<UserID>({\n method: 'DELETE',\n path: joinPaths(basePath, userId, 'mfa'),\n });\n }\n\n public async getOrganizationMembershipList(params: GetOrganizationMembershipListParams) {\n const { userId, limit, offset } = params;\n this.requireId(userId);\n\n return this.request<PaginatedResourceResponse<OrganizationMembership[]>>({\n method: 'GET',\n path: joinPaths(basePath, userId, 'organization_memberships'),\n queryParams: { limit, offset },\n });\n }\n\n public async getOrganizationInvitationList(params: GetOrganizationInvitationListParams) {\n const { userId, ...queryParams } = params;\n this.requireId(userId);\n\n return this.request<PaginatedResourceResponse<OrganizationInvitation[]>>({\n method: 'GET',\n path: joinPaths(basePath, userId, 'organization_invitations'),\n queryParams,\n });\n }\n\n public async verifyPassword(params: VerifyPasswordParams) {\n const { userId, password } = params;\n this.requireId(userId);\n\n return this.request<{ verified: true }>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'verify_password'),\n bodyParams: { password },\n });\n }\n\n public async verifyTOTP(params: VerifyTOTPParams) {\n const { userId, code } = params;\n this.requireId(userId);\n\n return this.request<{ verified: true; code_type: 'totp' }>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'verify_totp'),\n bodyParams: { code },\n });\n }\n\n public async banUser(userId: string) {\n this.requireId(userId);\n return this.request<User>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'ban'),\n });\n }\n\n public async unbanUser(userId: string) {\n this.requireId(userId);\n return this.request<User>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'unban'),\n });\n }\n\n public async lockUser(userId: string) {\n this.requireId(userId);\n return this.request<User>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'lock'),\n });\n }\n\n public async unlockUser(userId: string) {\n this.requireId(userId);\n return this.request<User>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'unlock'),\n });\n }\n\n public async deleteUserProfileImage(userId: string) {\n this.requireId(userId);\n return this.request<User>({\n method: 'DELETE',\n path: joinPaths(basePath, userId, 'profile_image'),\n });\n }\n\n public async deleteUserPasskey(params: DeleteUserPasskeyParams) {\n this.requireId(params.userId);\n this.requireId(params.passkeyIdentificationId);\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, params.userId, 'passkeys', params.passkeyIdentificationId),\n });\n }\n\n public async deleteUserWeb3Wallet(params: DeleteWeb3WalletParams) {\n this.requireId(params.userId);\n this.requireId(params.web3WalletIdentificationId);\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, params.userId, 'web3_wallets', params.web3WalletIdentificationId),\n });\n }\n\n public async deleteUserExternalAccount(params: DeleteUserExternalAccountParams) {\n this.requireId(params.userId);\n this.requireId(params.externalAccountId);\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, params.userId, 'external_accounts', params.externalAccountId),\n });\n }\n\n public async deleteUserBackupCodes(userId: string) {\n this.requireId(userId);\n return this.request<UserID>({\n method: 'DELETE',\n path: joinPaths(basePath, userId, 'backup_code'),\n });\n }\n\n public async deleteUserTOTP(userId: string) {\n this.requireId(userId);\n return this.request<UserID>({\n method: 'DELETE',\n path: joinPaths(basePath, userId, 'totp'),\n });\n }\n\n public async __experimental_passwordUntrusted(userId: string) {\n this.requireId(userId);\n return this.request<User>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'password_untrusted'),\n bodyParams: {\n revokeAllSessions: false,\n },\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\nimport { joinPaths } from 'src/util/path';\n\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { WaitlistEntryStatus } from '../resources/Enums';\nimport type { WaitlistEntry } from '../resources/WaitlistEntry';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/waitlist_entries';\n\ntype WaitlistEntryListParams = ClerkPaginationRequest<{\n /**\n * Filter waitlist entries by `email_address` or `id`\n */\n query?: string;\n status?: WaitlistEntryStatus;\n orderBy?: WithSign<'created_at' | 'invited_at' | 'email_address'>;\n}>;\n\ntype WaitlistEntryCreateParams = {\n emailAddress: string;\n notify?: boolean;\n};\n\ntype WaitlistEntryInviteParams = {\n /**\n * When true, do not error if an invitation already exists. Default: false.\n */\n ignoreExisting?: boolean;\n};\n\nexport class WaitlistEntryAPI extends AbstractAPI {\n /**\n * List waitlist entries.\n * @param params Optional parameters (e.g., `query`, `status`, `orderBy`).\n */\n public async list(params: WaitlistEntryListParams = {}) {\n return this.request<PaginatedResourceResponse<WaitlistEntry>>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n /**\n * Create a waitlist entry.\n * @param params The parameters for creating a waitlist entry.\n */\n public async create(params: WaitlistEntryCreateParams) {\n return this.request<WaitlistEntry>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n /**\n * Invite a waitlist entry.\n * @param id The waitlist entry ID.\n * @param params Optional parameters (e.g., `ignoreExisting`).\n */\n public async invite(id: string, params: WaitlistEntryInviteParams = {}) {\n this.requireId(id);\n\n return this.request<WaitlistEntry>({\n method: 'POST',\n path: joinPaths(basePath, id, 'invite'),\n bodyParams: params,\n });\n }\n\n /**\n * Reject a waitlist entry.\n * @param id The waitlist entry ID.\n */\n public async reject(id: string) {\n this.requireId(id);\n\n return this.request<WaitlistEntry>({\n method: 'POST',\n path: joinPaths(basePath, id, 'reject'),\n });\n }\n\n /**\n * Delete a waitlist entry.\n * @param id The waitlist entry ID.\n */\n public async delete(id: string) {\n this.requireId(id);\n\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, id),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\nimport type { WebhooksSvixJSON } from '../resources/JSON';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/webhooks';\n\nexport class WebhookAPI extends AbstractAPI {\n public async createSvixApp() {\n return this.request<WebhooksSvixJSON>({\n method: 'POST',\n path: joinPaths(basePath, 'svix'),\n });\n }\n\n public async generateSvixAuthURL() {\n return this.request<WebhooksSvixJSON>({\n method: 'POST',\n path: joinPaths(basePath, 'svix_url'),\n });\n }\n\n public async deleteSvixApp() {\n return this.request<void>({\n method: 'DELETE',\n path: joinPaths(basePath, 'svix'),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { BillingPlan } from '../resources/CommercePlan';\nimport type { BillingSubscription } from '../resources/CommerceSubscription';\nimport type { BillingSubscriptionItem } from '../resources/CommerceSubscriptionItem';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/billing';\nconst organizationBasePath = '/organizations';\nconst userBasePath = '/users';\n\ntype GetOrganizationListParams = ClerkPaginationRequest<{\n payerType: 'org' | 'user';\n}>;\n\ntype CancelSubscriptionItemParams = {\n /**\n * If true, the subscription item will be canceled immediately. If false or undefined, the subscription item will be canceled at the end of the current billing period.\n * @default undefined\n */\n endNow?: boolean;\n};\n\ntype ExtendSubscriptionItemFreeTrialParams = {\n /**\n * RFC3339 timestamp to extend the free trial to.\n * Must be in the future and not more than 365 days from the current trial end.\n */\n extendTo: Date;\n};\n\nexport class BillingAPI extends AbstractAPI {\n /**\n * @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.\n */\n public async getPlanList(params?: GetOrganizationListParams) {\n return this.request<PaginatedResourceResponse<BillingPlan[]>>({\n method: 'GET',\n path: joinPaths(basePath, 'plans'),\n queryParams: params,\n });\n }\n\n /**\n * @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.\n */\n public async cancelSubscriptionItem(subscriptionItemId: string, params?: CancelSubscriptionItemParams) {\n this.requireId(subscriptionItemId);\n return this.request<BillingSubscriptionItem>({\n method: 'DELETE',\n path: joinPaths(basePath, 'subscription_items', subscriptionItemId),\n queryParams: params,\n });\n }\n\n /**\n * @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.\n */\n public async extendSubscriptionItemFreeTrial(\n subscriptionItemId: string,\n params: ExtendSubscriptionItemFreeTrialParams,\n ) {\n this.requireId(subscriptionItemId);\n return this.request<BillingSubscriptionItem>({\n method: 'POST',\n path: joinPaths('/billing', 'subscription_items', subscriptionItemId, 'extend_free_trial'),\n bodyParams: params,\n });\n }\n\n /**\n * @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.\n */\n public async getOrganizationBillingSubscription(organizationId: string) {\n this.requireId(organizationId);\n return this.request<BillingSubscription>({\n method: 'GET',\n path: joinPaths(organizationBasePath, organizationId, 'billing', 'subscription'),\n });\n }\n\n /**\n * @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.\n */\n public async getUserBillingSubscription(userId: string) {\n this.requireId(userId);\n return this.request<BillingSubscription>({\n method: 'GET',\n path: joinPaths(userBasePath, userId, 'billing', 'subscription'),\n });\n }\n}\n","import { ClerkAPIResponseError, parseError } from '@clerk/shared/error';\nimport type { ClerkAPIError, ClerkAPIErrorJSON } from '@clerk/shared/types';\nimport snakecaseKeys from 'snakecase-keys';\n\nimport { API_URL, API_VERSION, constants, SUPPORTED_BAPI_VERSION, USER_AGENT } from '../constants';\nimport { runtime } from '../runtime';\nimport { assertValidSecretKey } from '../util/optionsAssertions';\nimport { joinPaths } from '../util/path';\nimport { deserialize } from './resources/Deserializer';\n\ntype ClerkBackendApiRequestOptionsUrlOrPath =\n | {\n url: string;\n path?: string;\n }\n | {\n url?: string;\n path: string;\n };\n\ntype ClerkBackendApiRequestOptionsBodyParams =\n | {\n bodyParams: Record<string, unknown> | Array<Record<string, unknown>>;\n options?: {\n /**\n * If true, snakecases the keys of the bodyParams object recursively.\n * @default false\n */\n deepSnakecaseBodyParamKeys?: boolean;\n };\n }\n | {\n bodyParams?: never;\n options?: {\n deepSnakecaseBodyParamKeys?: never;\n };\n };\n\nexport type ClerkBackendApiRequestOptions = {\n method: 'GET' | 'POST' | 'PATCH' | 'DELETE' | 'PUT';\n queryParams?: Record<string, unknown>;\n headerParams?: Record<string, string>;\n formData?: FormData;\n} & ClerkBackendApiRequestOptionsUrlOrPath &\n ClerkBackendApiRequestOptionsBodyParams;\n\nexport type ClerkBackendApiResponse<T> =\n | {\n data: T;\n errors: null;\n totalCount?: number;\n }\n | {\n data: null;\n errors: ClerkAPIError[];\n totalCount?: never;\n clerkTraceId?: string;\n status?: number;\n statusText?: string;\n retryAfter?: number;\n };\n\nexport type RequestFunction = ReturnType<typeof buildRequest>;\n\ntype BuildRequestOptions = {\n /* Secret Key */\n secretKey?: string;\n /* Backend API URL */\n apiUrl?: string;\n /* Backend API version */\n apiVersion?: string;\n /* Library/SDK name */\n userAgent?: string;\n /**\n * Allow requests without specifying a secret key. In most cases this should be set to `false`.\n * @default true\n */\n requireSecretKey?: boolean;\n /**\n * If true, omits the API version from the request URL path.\n * This is required for bapi-proxy endpoints, which do not use versioning in the URL.\n *\n * Note: API versioning for these endpoints is instead handled via the `Clerk-API-Version` HTTP header.\n *\n * @default false\n */\n skipApiVersionInUrl?: boolean;\n /* Machine secret key */\n machineSecretKey?: string;\n /**\n * If true, uses machineSecretKey for authorization instead of secretKey.\n *\n * Note: This is only used for machine-to-machine tokens.\n *\n * @default false\n */\n useMachineSecretKey?: boolean;\n};\n\nexport function buildRequest(options: BuildRequestOptions) {\n const requestFn = async <T>(requestOptions: ClerkBackendApiRequestOptions): Promise<ClerkBackendApiResponse<T>> => {\n const {\n secretKey,\n machineSecretKey,\n useMachineSecretKey = false,\n requireSecretKey = true,\n apiUrl = API_URL,\n apiVersion = API_VERSION,\n userAgent = USER_AGENT,\n skipApiVersionInUrl = false,\n } = options;\n const { path, method, queryParams, headerParams, bodyParams, formData, options: opts } = requestOptions;\n const { deepSnakecaseBodyParamKeys = false } = opts || {};\n\n if (requireSecretKey) {\n assertValidSecretKey(secretKey);\n }\n\n const url = skipApiVersionInUrl ? joinPaths(apiUrl, path) : joinPaths(apiUrl, apiVersion, path);\n\n // Build final URL with search parameters\n const finalUrl = new URL(url);\n\n if (queryParams) {\n // Snakecase query parameters\n const snakecasedQueryParams = snakecaseKeys({ ...queryParams });\n\n // Support array values for queryParams such as { foo: [42, 43] }\n for (const [key, val] of Object.entries(snakecasedQueryParams)) {\n if (val) {\n [val].flat().forEach(v => finalUrl.searchParams.append(key, v as string));\n }\n }\n }\n\n // Build headers\n const headers = new Headers({\n 'Clerk-API-Version': SUPPORTED_BAPI_VERSION,\n [constants.Headers.UserAgent]: userAgent,\n ...headerParams,\n });\n\n // If Authorization header already exists, preserve it.\n // Otherwise, use machine secret key if enabled, or fall back to regular secret key\n const authorizationHeader = constants.Headers.Authorization;\n if (!headers.has(authorizationHeader)) {\n if (useMachineSecretKey && machineSecretKey) {\n headers.set(authorizationHeader, `Bearer ${machineSecretKey}`);\n } else if (secretKey) {\n headers.set(authorizationHeader, `Bearer ${secretKey}`);\n }\n }\n\n let res: Response | undefined;\n try {\n if (formData) {\n res = await runtime.fetch(finalUrl.href, {\n method,\n headers,\n body: formData,\n });\n } else {\n // Enforce application/json for all non form-data requests\n headers.set('Content-Type', 'application/json');\n\n const buildBody = () => {\n const hasBody = method !== 'GET' && bodyParams && Object.keys(bodyParams).length > 0;\n if (!hasBody) {\n return null;\n }\n\n const formatKeys = (object: Parameters<typeof snakecaseKeys>[0]) =>\n snakecaseKeys(object, { deep: deepSnakecaseBodyParamKeys });\n\n return {\n body: JSON.stringify(Array.isArray(bodyParams) ? bodyParams.map(formatKeys) : formatKeys(bodyParams)),\n };\n };\n\n res = await runtime.fetch(finalUrl.href, {\n method,\n headers,\n ...buildBody(),\n });\n }\n\n // TODO: Parse JSON or Text response based on a response header\n const isJSONResponse =\n res?.headers && res.headers?.get(constants.Headers.ContentType) === constants.ContentTypes.Json;\n const responseBody = await (isJSONResponse ? res.json() : res.text());\n\n if (!res.ok) {\n return {\n data: null,\n errors: parseErrors(responseBody),\n status: res?.status,\n statusText: res?.statusText,\n clerkTraceId: getTraceId(responseBody, res?.headers),\n retryAfter: getRetryAfter(res?.headers),\n };\n }\n\n return {\n ...deserialize<T>(responseBody),\n errors: null,\n };\n } catch (err) {\n if (err instanceof Error) {\n return {\n data: null,\n errors: [\n {\n code: 'unexpected_error',\n message: err.message || 'Unexpected error',\n },\n ],\n clerkTraceId: getTraceId(err, res?.headers),\n };\n }\n\n return {\n data: null,\n errors: parseErrors(err),\n status: res?.status,\n statusText: res?.statusText,\n clerkTraceId: getTraceId(err, res?.headers),\n retryAfter: getRetryAfter(res?.headers),\n };\n }\n };\n\n return withLegacyRequestReturn(requestFn);\n}\n\n// Returns either clerk_trace_id if present in response json, otherwise defaults to CF-Ray header\n// If the request failed before receiving a response, returns undefined\nfunction getTraceId(data: unknown, headers?: Headers): string {\n if (data && typeof data === 'object' && 'clerk_trace_id' in data && typeof data.clerk_trace_id === 'string') {\n return data.clerk_trace_id;\n }\n\n const cfRay = headers?.get('cf-ray');\n return cfRay || '';\n}\n\nfunction getRetryAfter(headers?: Headers): number | undefined {\n const retryAfter = headers?.get('Retry-After');\n if (!retryAfter) {\n return;\n }\n\n const value = parseInt(retryAfter, 10);\n if (isNaN(value)) {\n return;\n }\n\n return value;\n}\n\nfunction parseErrors(data: unknown): ClerkAPIError[] {\n if (!!data && typeof data === 'object' && 'errors' in data) {\n const errors = data.errors as ClerkAPIErrorJSON[];\n return errors.length > 0 ? errors.map(parseError) : [];\n }\n return [];\n}\n\ntype LegacyRequestFunction = <T>(requestOptions: ClerkBackendApiRequestOptions) => Promise<T>;\n\n// TODO(dimkl): Will be probably be dropped in next major version\nfunction withLegacyRequestReturn(cb: any): LegacyRequestFunction {\n return async (...args) => {\n const { data, errors, totalCount, status, statusText, clerkTraceId, retryAfter } = await cb(...args);\n if (errors) {\n // instead of passing `data: errors`, we have set the `error.errors` because\n // the errors returned from callback is already parsed and passing them as `data`\n // will not be able to assign them to the instance\n const error = new ClerkAPIResponseError(statusText || '', {\n data: [],\n status,\n clerkTraceId,\n retryAfter,\n });\n error.errors = errors;\n throw error;\n }\n\n if (typeof totalCount !== 'undefined') {\n return { data, totalCount };\n }\n\n return data;\n };\n}\n","const isObject = value => typeof value === 'object' && value !== null;\n\n// Customized for this use-case\nconst isObjectCustom = value =>\n\tisObject(value)\n\t&& !(value instanceof RegExp)\n\t&& !(value instanceof Error)\n\t&& !(value instanceof Date)\n\t&& !(globalThis.Blob && value instanceof globalThis.Blob);\n\nexport const mapObjectSkip = Symbol('mapObjectSkip');\n\nconst _mapObject = (object, mapper, options, isSeen = new WeakMap()) => {\n\toptions = {\n\t\tdeep: false,\n\t\ttarget: {},\n\t\t...options,\n\t};\n\n\tif (isSeen.has(object)) {\n\t\treturn isSeen.get(object);\n\t}\n\n\tisSeen.set(object, options.target);\n\n\tconst {target} = options;\n\tdelete options.target;\n\n\tconst mapArray = array => array.map(element => isObjectCustom(element) ? _mapObject(element, mapper, options, isSeen) : element);\n\tif (Array.isArray(object)) {\n\t\treturn mapArray(object);\n\t}\n\n\tfor (const [key, value] of Object.entries(object)) {\n\t\tconst mapResult = mapper(key, value, object);\n\n\t\tif (mapResult === mapObjectSkip) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet [newKey, newValue, {shouldRecurse = true} = {}] = mapResult;\n\n\t\t// Drop `__proto__` keys.\n\t\tif (newKey === '__proto__') {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (options.deep && shouldRecurse && isObjectCustom(newValue)) {\n\t\t\tnewValue = Array.isArray(newValue)\n\t\t\t\t? mapArray(newValue)\n\t\t\t\t: _mapObject(newValue, mapper, options, isSeen);\n\t\t}\n\n\t\ttarget[newKey] = newValue;\n\t}\n\n\treturn target;\n};\n\nexport default function mapObject(object, mapper, options) {\n\tif (!isObject(object)) {\n\t\tthrow new TypeError(`Expected an object, got \\`${object}\\` (${typeof object})`);\n\t}\n\n\tif (Array.isArray(object)) {\n\t\tthrow new TypeError('Expected an object, got an array');\n\t}\n\n\treturn _mapObject(object, mapper, options);\n}\n","// Regexps involved with splitting words in various case formats.\nconst SPLIT_LOWER_UPPER_RE = /([\\p{Ll}\\d])(\\p{Lu})/gu;\nconst SPLIT_UPPER_UPPER_RE = /(\\p{Lu})([\\p{Lu}][\\p{Ll}])/gu;\n\n// Used to iterate over the initial split result and separate numbers.\nconst SPLIT_SEPARATE_NUMBER_RE = /(\\d)\\p{Ll}|(\\p{L})\\d/u;\n\n// Regexp involved with stripping non-word characters from the result.\nconst DEFAULT_STRIP_REGEXP = /[^\\p{L}\\d]+/giu;\n\n// The replacement value for splits.\nconst SPLIT_REPLACE_VALUE = \"$1\\0$2\";\n\n// The default characters to keep after transforming case.\nconst DEFAULT_PREFIX_SUFFIX_CHARACTERS = \"\";\n\n/**\n * Supported locale values. Use `false` to ignore locale.\n * Defaults to `undefined`, which uses the host environment.\n */\nexport type Locale = string[] | string | false | undefined;\n\n/**\n * Options used for converting strings to pascal/camel case.\n */\nexport interface PascalCaseOptions extends Options {\n mergeAmbiguousCharacters?: boolean;\n}\n\n/**\n * Options used for converting strings to any case.\n */\nexport interface Options {\n locale?: Locale;\n split?: (value: string) => string[];\n /** @deprecated Pass `split: splitSeparateNumbers` instead. */\n separateNumbers?: boolean;\n delimiter?: string;\n prefixCharacters?: string;\n suffixCharacters?: string;\n}\n\n/**\n * Split any cased input strings into an array of words.\n */\nexport function split(value: string) {\n let result = value.trim();\n\n result = result\n .replace(SPLIT_LOWER_UPPER_RE, SPLIT_REPLACE_VALUE)\n .replace(SPLIT_UPPER_UPPER_RE, SPLIT_REPLACE_VALUE);\n\n result = result.replace(DEFAULT_STRIP_REGEXP, \"\\0\");\n\n let start = 0;\n let end = result.length;\n\n // Trim the delimiter from around the output string.\n while (result.charAt(start) === \"\\0\") start++;\n if (start === end) return [];\n while (result.charAt(end - 1) === \"\\0\") end--;\n\n return result.slice(start, end).split(/\\0/g);\n}\n\n/**\n * Split the input string into an array of words, separating numbers.\n */\nexport function splitSeparateNumbers(value: string) {\n const words = split(value);\n for (let i = 0; i < words.length; i++) {\n const word = words[i];\n const match = SPLIT_SEPARATE_NUMBER_RE.exec(word);\n if (match) {\n const offset = match.index + (match[1] ?? match[2]).length;\n words.splice(i, 1, word.slice(0, offset), word.slice(offset));\n }\n }\n return words;\n}\n\n/**\n * Convert a string to space separated lower case (`foo bar`).\n */\nexport function noCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n return (\n prefix +\n words.map(lowerFactory(options?.locale)).join(options?.delimiter ?? \" \") +\n suffix\n );\n}\n\n/**\n * Convert a string to camel case (`fooBar`).\n */\nexport function camelCase(input: string, options?: PascalCaseOptions) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n const transform = options?.mergeAmbiguousCharacters\n ? capitalCaseTransformFactory(lower, upper)\n : pascalCaseTransformFactory(lower, upper);\n return (\n prefix +\n words\n .map((word, index) => {\n if (index === 0) return lower(word);\n return transform(word, index);\n })\n .join(options?.delimiter ?? \"\") +\n suffix\n );\n}\n\n/**\n * Convert a string to pascal case (`FooBar`).\n */\nexport function pascalCase(input: string, options?: PascalCaseOptions) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n const transform = options?.mergeAmbiguousCharacters\n ? capitalCaseTransformFactory(lower, upper)\n : pascalCaseTransformFactory(lower, upper);\n return prefix + words.map(transform).join(options?.delimiter ?? \"\") + suffix;\n}\n\n/**\n * Convert a string to pascal snake case (`Foo_Bar`).\n */\nexport function pascalSnakeCase(input: string, options?: Options) {\n return capitalCase(input, { delimiter: \"_\", ...options });\n}\n\n/**\n * Convert a string to capital case (`Foo Bar`).\n */\nexport function capitalCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n return (\n prefix +\n words\n .map(capitalCaseTransformFactory(lower, upper))\n .join(options?.delimiter ?? \" \") +\n suffix\n );\n}\n\n/**\n * Convert a string to constant case (`FOO_BAR`).\n */\nexport function constantCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n return (\n prefix +\n words.map(upperFactory(options?.locale)).join(options?.delimiter ?? \"_\") +\n suffix\n );\n}\n\n/**\n * Convert a string to dot case (`foo.bar`).\n */\nexport function dotCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \".\", ...options });\n}\n\n/**\n * Convert a string to kebab case (`foo-bar`).\n */\nexport function kebabCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \"-\", ...options });\n}\n\n/**\n * Convert a string to path case (`foo/bar`).\n */\nexport function pathCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \"/\", ...options });\n}\n\n/**\n * Convert a string to path case (`Foo bar`).\n */\nexport function sentenceCase(input: string, options?: Options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n const transform = capitalCaseTransformFactory(lower, upper);\n return (\n prefix +\n words\n .map((word, index) => {\n if (index === 0) return transform(word);\n return lower(word);\n })\n .join(options?.delimiter ?? \" \") +\n suffix\n );\n}\n\n/**\n * Convert a string to snake case (`foo_bar`).\n */\nexport function snakeCase(input: string, options?: Options) {\n return noCase(input, { delimiter: \"_\", ...options });\n}\n\n/**\n * Convert a string to header case (`Foo-Bar`).\n */\nexport function trainCase(input: string, options?: Options) {\n return capitalCase(input, { delimiter: \"-\", ...options });\n}\n\nfunction lowerFactory(locale: Locale): (input: string) => string {\n return locale === false\n ? (input: string) => input.toLowerCase()\n : (input: string) => input.toLocaleLowerCase(locale);\n}\n\nfunction upperFactory(locale: Locale): (input: string) => string {\n return locale === false\n ? (input: string) => input.toUpperCase()\n : (input: string) => input.toLocaleUpperCase(locale);\n}\n\nfunction capitalCaseTransformFactory(\n lower: (input: string) => string,\n upper: (input: string) => string,\n) {\n return (word: string) => `${upper(word[0])}${lower(word.slice(1))}`;\n}\n\nfunction pascalCaseTransformFactory(\n lower: (input: string) => string,\n upper: (input: string) => string,\n) {\n return (word: string, index: number) => {\n const char0 = word[0];\n const initial =\n index > 0 && char0 >= \"0\" && char0 <= \"9\" ? \"_\" + char0 : upper(char0);\n return initial + lower(word.slice(1));\n };\n}\n\nfunction splitPrefixSuffix(\n input: string,\n options: Options = {},\n): [string, string[], string] {\n const splitFn =\n options.split ?? (options.separateNumbers ? splitSeparateNumbers : split);\n const prefixCharacters =\n options.prefixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS;\n const suffixCharacters =\n options.suffixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS;\n let prefixIndex = 0;\n let suffixIndex = input.length;\n\n while (prefixIndex < input.length) {\n const char = input.charAt(prefixIndex);\n if (!prefixCharacters.includes(char)) break;\n prefixIndex++;\n }\n\n while (suffixIndex > prefixIndex) {\n const index = suffixIndex - 1;\n const char = input.charAt(index);\n if (!suffixCharacters.includes(char)) break;\n suffixIndex = index;\n }\n\n return [\n input.slice(0, prefixIndex),\n splitFn(input.slice(prefixIndex, suffixIndex)),\n input.slice(suffixIndex),\n ];\n}\n","'use strict'\n\nimport map from 'map-obj'\nimport { snakeCase } from 'change-case'\n\nconst PlainObjectConstructor = {}.constructor\n\nfunction snakecaseKeys (obj, options) {\n if (Array.isArray(obj)) {\n if (obj.some(item => item.constructor !== PlainObjectConstructor)) {\n throw new Error('obj must be array of plain objects')\n }\n\n options = { deep: true, exclude: [], parsingOptions: {}, ...options }\n const convertCase = options.snakeCase || ((key) => snakeCase(key, options.parsingOptions))\n\n // Handle arrays by mapping each element\n return obj.map(item => {\n return map(item, (key, val) => {\n return [\n matches(options.exclude, key) ? key : convertCase(key),\n val,\n mapperOptions(key, val, options)\n ]\n }, options)\n })\n } else {\n if (obj.constructor !== PlainObjectConstructor) {\n throw new Error('obj must be an plain object')\n }\n }\n\n options = { deep: true, exclude: [], parsingOptions: {}, ...options }\n\n const convertCase = options.snakeCase || ((key) => snakeCase(key, options.parsingOptions))\n\n return map(obj, (key, val) => {\n return [\n matches(options.exclude, key) ? key : convertCase(key),\n val,\n mapperOptions(key, val, options)\n ]\n }, options)\n}\n\nfunction matches (patterns, value) {\n return patterns.some(pattern => {\n return typeof pattern === 'string'\n ? pattern === value\n : pattern.test(value)\n })\n}\n\nfunction mapperOptions (key, val, options) {\n return options.shouldRecurse\n ? { shouldRecurse: options.shouldRecurse(key, val) }\n : undefined\n}\n\nexport default snakecaseKeys\n","import type { AccountlessApplicationJSON } from './JSON';\n\nexport class AccountlessApplication {\n constructor(\n readonly publishableKey: string,\n readonly secretKey: string,\n readonly claimUrl: string,\n readonly apiKeysUrl: string,\n ) {}\n\n static fromJSON(data: AccountlessApplicationJSON): AccountlessApplication {\n return new AccountlessApplication(data.publishable_key, data.secret_key, data.claim_url, data.api_keys_url);\n }\n}\n","import type { ActorTokenStatus } from './Enums';\nimport type { ActorTokenJSON } from './JSON';\n\nexport class ActorToken {\n constructor(\n readonly id: string,\n readonly status: ActorTokenStatus,\n readonly userId: string,\n readonly actor: Record<string, unknown> | null,\n readonly token: string | null | undefined,\n readonly url: string | null | undefined,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: ActorTokenJSON): ActorToken {\n return new ActorToken(\n data.id,\n data.status,\n data.user_id,\n data.actor,\n data.token,\n data.url,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { AllowlistIdentifierType } from './Enums';\nimport type { AllowlistIdentifierJSON } from './JSON';\n\n/**\n * The Backend `AllowlistIdentifier` object represents an identifier that has been added to the allowlist of your application. The Backend `AllowlistIdentifier` object is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Allow-list-Block-list#operation/ListAllowlistIdentifiers) and is not directly accessible from the Frontend API.\n */\nexport class AllowlistIdentifier {\n constructor(\n /**\n * A unique ID for the allowlist identifier.\n */\n readonly id: string,\n /**\n * The identifier that was added to the allowlist.\n */\n readonly identifier: string,\n /**\n * The type of the allowlist identifier.\n */\n readonly identifierType: AllowlistIdentifierType,\n /**\n * The date when the allowlist identifier was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the allowlist identifier was last updated.\n */\n readonly updatedAt: number,\n /**\n * The ID of the instance that this allowlist identifier belongs to.\n */\n readonly instanceId?: string,\n /**\n * The ID of the invitation sent to the identifier.\n */\n readonly invitationId?: string,\n ) {}\n\n static fromJSON(data: AllowlistIdentifierJSON): AllowlistIdentifier {\n return new AllowlistIdentifier(\n data.id,\n data.identifier,\n data.identifier_type,\n data.created_at,\n data.updated_at,\n data.instance_id,\n data.invitation_id,\n );\n }\n}\n","import type { APIKeyJSON } from './JSON';\n\nexport class APIKey {\n constructor(\n readonly id: string,\n readonly type: string,\n readonly name: string,\n readonly subject: string,\n readonly scopes: string[],\n readonly claims: Record<string, any> | null,\n readonly revoked: boolean,\n readonly revocationReason: string | null,\n readonly expired: boolean,\n readonly expiration: number | null,\n readonly createdBy: string | null,\n readonly description: string | null,\n readonly lastUsedAt: number | null,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly secret?: string,\n ) {}\n\n static fromJSON(data: APIKeyJSON) {\n return new APIKey(\n data.id,\n data.type,\n data.name,\n data.subject,\n data.scopes,\n data.claims,\n data.revoked,\n data.revocation_reason,\n data.expired,\n data.expiration,\n data.created_by,\n data.description,\n data.last_used_at,\n data.created_at,\n data.updated_at,\n data.secret,\n );\n }\n}\n","import type { BlocklistIdentifierType } from './Enums';\nimport type { BlocklistIdentifierJSON } from './JSON';\n\nexport class BlocklistIdentifier {\n constructor(\n readonly id: string,\n readonly identifier: string,\n readonly identifierType: BlocklistIdentifierType,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly instanceId?: string,\n ) {}\n\n static fromJSON(data: BlocklistIdentifierJSON): BlocklistIdentifier {\n return new BlocklistIdentifier(\n data.id,\n data.identifier,\n data.identifier_type,\n data.created_at,\n data.updated_at,\n data.instance_id,\n );\n }\n}\n","import type { SessionActivityJSON, SessionJSON } from './JSON';\n\n/**\n * The Backend `SessionActivity` object models the activity of a user session, capturing details such as the device type, browser information, and geographical location.\n */\nexport class SessionActivity {\n constructor(\n /**\n * The unique identifier for the session activity record.\n */\n readonly id: string,\n /**\n * Will be set to `true` if the session activity came from a mobile device. Set to `false` otherwise.\n */\n readonly isMobile: boolean,\n /**\n * The IP address from which this session activity originated.\n */\n readonly ipAddress?: string,\n /**\n * The city from which this session activity occurred. Resolved by IP address geo-location.\n */\n readonly city?: string,\n /**\n * The country from which this session activity occurred. Resolved by IP address geo-location.\n */\n readonly country?: string,\n /**\n * The version of the browser from which this session activity occurred.\n */\n readonly browserVersion?: string,\n /**\n * The name of the browser from which this session activity occurred.\n */\n readonly browserName?: string,\n /**\n * The type of the device which was used in this session activity.\n */\n readonly deviceType?: string,\n ) {}\n\n static fromJSON(data: SessionActivityJSON): SessionActivity {\n return new SessionActivity(\n data.id,\n data.is_mobile,\n data.ip_address,\n data.city,\n data.country,\n data.browser_version,\n data.browser_name,\n data.device_type,\n );\n }\n}\n\n/**\n * The Backend `Session` object is similar to the [`Session`](https://clerk.com/docs/reference/javascript/session) object as it is an abstraction over an HTTP session and models the period of information exchange between a user and the server. However, the Backend `Session` object is different as it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Sessions#operation/GetSessionList) and is not directly accessible from the Frontend API.\n */\nexport class Session {\n constructor(\n /**\n * The unique identifier for the `Session`.\n */\n readonly id: string,\n /**\n * The ID of the client associated with the `Session`.\n */\n readonly clientId: string,\n /**\n * The ID of the user associated with the `Session`.\n */\n readonly userId: string,\n /**\n * The current state of the `Session`.\n */\n readonly status: string,\n /**\n * The time the session was last active on the [`Client`](https://clerk.com/docs/reference/backend/types/backend-client).\n */\n readonly lastActiveAt: number,\n /**\n * The date when the `Session` will expire.\n */\n readonly expireAt: number,\n /**\n * The date when the `Session` will be abandoned.\n */\n readonly abandonAt: number,\n /**\n * The date when the `Session` was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the `Session` was last updated.\n */\n readonly updatedAt: number,\n /**\n * The ID of the last active organization.\n */\n readonly lastActiveOrganizationId?: string,\n /**\n * An object that provides additional information about this session, focused around user activity data.\n */\n readonly latestActivity?: SessionActivity,\n /**\n * The JWT actor for the session. Holds identifier for the user that is impersonating the current user. Read more about [impersonation](https://clerk.com/docs/guides/users/impersonation).\n */\n readonly actor: Record<string, unknown> | null = null,\n ) {}\n\n static fromJSON(data: SessionJSON): Session {\n return new Session(\n data.id,\n data.client_id,\n data.user_id,\n data.status,\n data.last_active_at,\n data.expire_at,\n data.abandon_at,\n data.created_at,\n data.updated_at,\n data.last_active_organization_id,\n data.latest_activity && SessionActivity.fromJSON(data.latest_activity),\n data.actor,\n );\n }\n}\n","import type { LastAuthenticationStrategy } from '@clerk/shared/types';\n\nimport type { ClientJSON } from './JSON';\nimport { Session } from './Session';\n\n/**\n * The Backend `Client` object is similar to the [`Client`](https://clerk.com/docs/reference/javascript/client) object as it holds information about the authenticated sessions in the current device. However, the Backend `Client` object is different from the `Client` object in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Clients#operation/GetClient) and is not directly accessible from the Frontend API.\n */\nexport class Client {\n constructor(\n /**\n * The unique identifier for the `Client`.\n */\n readonly id: string,\n /**\n * An array of [Session](https://clerk.com/docs/reference/backend/types/backend-session){{ target: '_blank' }} IDs associated with the `Client`.\n */\n readonly sessionIds: string[],\n /**\n * An array of [Session](https://clerk.com/docs/reference/backend/types/backend-session){{ target: '_blank' }} objects associated with the `Client`.\n */\n readonly sessions: Session[],\n /**\n * The ID of the [`SignIn`](https://clerk.com/docs/reference/javascript/sign-in){{ target: '_blank' }}.\n */\n readonly signInId: string | null,\n /**\n * The ID of the [`SignUp`](https://clerk.com/docs/reference/javascript/sign-up){{ target: '_blank' }}.\n */\n readonly signUpId: string | null,\n /**\n * The ID of the last active [Session](https://clerk.com/docs/reference/backend/types/backend-session).\n */\n readonly lastActiveSessionId: string | null,\n /**\n * The last authentication strategy used by the `Client`.\n */\n readonly lastAuthenticationStrategy: LastAuthenticationStrategy | null,\n /**\n * The date when the `Client` was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the `Client` was last updated.\n */\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: ClientJSON): Client {\n return new Client(\n data.id,\n data.session_ids,\n data.sessions.map(x => Session.fromJSON(x)),\n data.sign_in_id,\n data.sign_up_id,\n data.last_active_session_id,\n data.last_authentication_strategy,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { CnameTargetJSON } from './JSON';\n\nexport class CnameTarget {\n constructor(\n readonly host: string,\n readonly value: string,\n readonly required: boolean,\n ) {}\n\n static fromJSON(data: CnameTargetJSON): CnameTarget {\n return new CnameTarget(data.host, data.value, data.required);\n }\n}\n","import type { CookiesJSON } from './JSON';\n\nexport class Cookies {\n constructor(readonly cookies: string[]) {}\n\n static fromJSON(data: CookiesJSON): Cookies {\n return new Cookies(data.cookies);\n }\n}\n","import type { DeletedObjectJSON } from './JSON';\n\nexport class DeletedObject {\n constructor(\n readonly object: string,\n readonly id: string | null,\n readonly slug: string | null,\n readonly deleted: boolean,\n ) {}\n\n static fromJSON(data: DeletedObjectJSON) {\n return new DeletedObject(data.object, data.id || null, data.slug || null, data.deleted);\n }\n}\n","import { CnameTarget } from './CnameTarget';\nimport type { DomainJSON } from './JSON';\n\nexport class Domain {\n constructor(\n readonly id: string,\n readonly name: string,\n readonly isSatellite: boolean,\n readonly frontendApiUrl: string,\n readonly developmentOrigin: string,\n readonly cnameTargets: CnameTarget[],\n readonly accountsPortalUrl?: string | null,\n readonly proxyUrl?: string | null,\n ) {}\n\n static fromJSON(data: DomainJSON): Domain {\n return new Domain(\n data.id,\n data.name,\n data.is_satellite,\n data.frontend_api_url,\n data.development_origin,\n data.cname_targets && data.cname_targets.map(x => CnameTarget.fromJSON(x)),\n data.accounts_portal_url,\n data.proxy_url,\n );\n }\n}\n","import type { EmailJSON } from './JSON';\n\nexport class Email {\n constructor(\n readonly id: string,\n readonly fromEmailName: string,\n readonly emailAddressId: string | null,\n readonly toEmailAddress?: string,\n readonly subject?: string,\n readonly body?: string,\n readonly bodyPlain?: string | null,\n readonly status?: string,\n readonly slug?: string | null,\n readonly data?: Record<string, any> | null,\n readonly deliveredByClerk?: boolean,\n ) {}\n\n static fromJSON(data: EmailJSON): Email {\n return new Email(\n data.id,\n data.from_email_name,\n data.email_address_id,\n data.to_email_address,\n data.subject,\n data.body,\n data.body_plain,\n data.status,\n data.slug,\n data.data,\n data.delivered_by_clerk,\n );\n }\n}\n","import type { IdentificationLinkJSON } from './JSON';\n\n/**\n * Contains information about any identifications that might be linked to the email address.\n */\nexport class IdentificationLink {\n constructor(\n /**\n * The unique identifier for the identification link.\n */\n readonly id: string,\n /**\n * The type of the identification link, e.g., `\"email_address\"`, `\"phone_number\"`, etc.\n */\n readonly type: string,\n ) {}\n\n static fromJSON(data: IdentificationLinkJSON): IdentificationLink {\n return new IdentificationLink(data.id, data.type);\n }\n}\n","import type { VerificationStatus } from '@clerk/shared/types';\n\nimport type { OrganizationDomainVerificationJSON, VerificationJSON } from './JSON';\n\n/**\n * The Backend `Verification` object describes the state of the verification process of a sign-in or sign-up attempt.\n */\nexport class Verification {\n constructor(\n /**\n * The state of the verification.\n *\n * <ul>\n * <li>`unverified`: The verification has not been verified yet.</li>\n * <li>`verified`: The verification has been verified.</li>\n * <li>`transferable`: The verification is transferable to between sign-in and sign-up flows.</li>\n * <li>`failed`: The verification has failed.</li>\n * <li>`expired`: The verification has expired.</li>\n * </ul>\n */\n readonly status: VerificationStatus,\n /**\n * The strategy pertaining to the parent sign-up or sign-in attempt.\n */\n readonly strategy: string,\n /**\n * The redirect URL for an external verification.\n */\n readonly externalVerificationRedirectURL: URL | null = null,\n /**\n * The number of attempts related to the verification.\n */\n readonly attempts: number | null = null,\n /**\n * The time the verification will expire at.\n */\n readonly expireAt: number | null = null,\n /**\n * The [nonce](https://en.wikipedia.org/wiki/Cryptographic_nonce) pertaining to the verification.\n */\n readonly nonce: string | null = null,\n /**\n * The message that will be presented to the user's Web3 wallet for signing during authentication. This follows the [Sign-In with Ethereum (SIWE) protocol format](https://docs.login.xyz/general-information/siwe-overview/eip-4361#example-message-to-be-signed), which typically includes details like the requesting service, wallet address, terms acceptance, nonce, timestamp, and any additional resources.\n */\n readonly message: string | null = null,\n ) {}\n\n static fromJSON(data: VerificationJSON): Verification {\n return new Verification(\n data.status,\n data.strategy,\n data.external_verification_redirect_url ? new URL(data.external_verification_redirect_url) : null,\n data.attempts,\n data.expire_at,\n data.nonce,\n );\n }\n}\n\nexport class OrganizationDomainVerification {\n constructor(\n readonly status: string,\n readonly strategy: string,\n readonly attempts: number | null = null,\n readonly expireAt: number | null = null,\n ) {}\n\n static fromJSON(data: OrganizationDomainVerificationJSON): OrganizationDomainVerification {\n return new OrganizationDomainVerification(data.status, data.strategy, data.attempts, data.expires_at);\n }\n}\n","import { IdentificationLink } from './IdentificationLink';\nimport type { EmailAddressJSON } from './JSON';\nimport { Verification } from './Verification';\n\n/**\n * The Backend `EmailAddress` object is a model around an email address.\n *\n * Email addresses must be **verified** to ensure that they are assigned to their rightful owners. The `EmailAddress` object holds all necessary state around the verification process.\n *\n * For implementation examples for adding and verifying email addresses, see the [email link custom flow](https://clerk.com/docs/guides/development/custom-flows/authentication/email-links) and [email code custom flow](https://clerk.com/docs/guides/development/custom-flows/account-updates/add-email) guides.\n */\nexport class EmailAddress {\n constructor(\n /**\n * The unique identifier for the email address.\n */\n readonly id: string,\n /**\n * The value of the email address.\n */\n readonly emailAddress: string,\n /**\n * An object holding information on the verification of the email address.\n */\n readonly verification: Verification | null,\n /**\n * An array of objects containing information about any identifications that might be linked to the email address.\n */\n readonly linkedTo: IdentificationLink[],\n ) {}\n\n static fromJSON(data: EmailAddressJSON): EmailAddress {\n return new EmailAddress(\n data.id,\n data.email_address,\n data.verification && Verification.fromJSON(data.verification),\n data.linked_to.map(link => IdentificationLink.fromJSON(link)),\n );\n }\n}\n","import type { FeatureJSON } from './JSON';\n\n/**\n * The `Feature` object represents a feature of a subscription plan.\n *\n * @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.\n */\nexport class Feature {\n constructor(\n /**\n * The unique identifier for the feature.\n */\n readonly id: string,\n /**\n * The name of the feature.\n */\n readonly name: string,\n /**\n * The description of the feature.\n */\n readonly description: string | null,\n /**\n * The URL-friendly identifier of the feature.\n */\n readonly slug: string,\n /**\n * The URL of the feature's avatar image.\n */\n readonly avatarUrl: string | null,\n ) {}\n\n static fromJSON(data: FeatureJSON): Feature {\n return new Feature(data.id, data.name, data.description ?? null, data.slug, data.avatar_url ?? null);\n }\n}\n","import type { BillingMoneyAmount, BillingMoneyAmountJSON } from '@clerk/shared/types';\n\nimport { Feature } from './Feature';\nimport type { BillingPlanJSON } from './JSON';\n\n/**\n * The `BillingPlan` object is similar to the [`BillingPlanResource`](/docs/reference/javascript/types/billing-plan-resource) object as it holds information about a plan, as well as methods for managing it. However, the `BillingPlan` object is different in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/commerce/get/commerce/plans) and is not directly accessible from the Frontend API.\n *\n * @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.\n */\nexport class BillingPlan {\n constructor(\n /**\n * The unique identifier for the plan.\n */\n readonly id: string,\n /**\n * The name of the plan.\n */\n readonly name: string,\n /**\n * The URL-friendly identifier of the plan.\n */\n readonly slug: string,\n /**\n * The description of the plan.\n */\n readonly description: string | null,\n /**\n * Whether the plan is the default plan.\n */\n readonly isDefault: boolean,\n /**\n * Whether the plan is recurring.\n */\n readonly isRecurring: boolean,\n /**\n * Whether the plan has a base fee.\n */\n readonly hasBaseFee: boolean,\n /**\n * Whether the plan is displayed in the `<PriceTable/>` component.\n */\n readonly publiclyVisible: boolean,\n /**\n * The monthly fee of the plan.\n */\n readonly fee: BillingMoneyAmount,\n /**\n * The annual fee of the plan.\n */\n readonly annualFee: BillingMoneyAmount | null,\n /**\n * The annual fee of the plan on a monthly basis.\n */\n readonly annualMonthlyFee: BillingMoneyAmount | null,\n /**\n * The type of payer for the plan.\n */\n readonly forPayerType: 'org' | 'user',\n /**\n * The features the plan offers.\n */\n readonly features: Feature[],\n ) {}\n\n static fromJSON(data: BillingPlanJSON): BillingPlan {\n const formatAmountJSON = <T extends BillingMoneyAmountJSON | null>(\n fee: T,\n ): T extends null ? null : BillingMoneyAmount => {\n return (\n fee\n ? {\n amount: fee.amount,\n amountFormatted: fee.amount_formatted,\n currency: fee.currency,\n currencySymbol: fee.currency_symbol,\n }\n : null\n ) as T extends null ? null : BillingMoneyAmount;\n };\n return new BillingPlan(\n data.id,\n data.name,\n data.slug,\n data.description ?? null,\n data.is_default,\n data.is_recurring,\n data.has_base_fee,\n data.publicly_visible,\n formatAmountJSON(data.fee),\n formatAmountJSON(data.annual_fee),\n formatAmountJSON(data.annual_monthly_fee),\n data.for_payer_type,\n (data.features ?? []).map(feature => Feature.fromJSON(feature)),\n );\n }\n}\n","import type { BillingMoneyAmount, BillingMoneyAmountJSON } from '@clerk/shared/types';\n\nimport { BillingPlan } from './CommercePlan';\nimport type { BillingSubscriptionItemJSON } from './JSON';\n\n/**\n * The `BillingSubscriptionItem` object is similar to the [`BillingSubscriptionItemResource`](/docs/reference/javascript/types/billing-subscription-item-resource) object as it holds information about a subscription item, as well as methods for managing it. However, the `BillingSubscriptionItem` object is different in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/commerce/get/commerce/subscription_items) and is not directly accessible from the Frontend API.\n *\n * @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.\n */\nexport class BillingSubscriptionItem {\n constructor(\n /**\n * The unique identifier for the subscription item.\n */\n readonly id: string,\n /**\n * The status of the subscription item.\n */\n readonly status: BillingSubscriptionItemJSON['status'],\n /**\n * The plan period for the subscription item.\n */\n readonly planPeriod: 'month' | 'annual',\n /**\n * Unix timestamp (milliseconds) of when the current period starts.\n */\n readonly periodStart: number,\n /**\n * The next payment information.\n */\n readonly nextPayment:\n | {\n /**\n * The amount of the next payment.\n */\n amount: number;\n /**\n * Unix timestamp (milliseconds) of when the next payment is scheduled.\n */\n date: number;\n }\n | null\n | undefined,\n /**\n * The current amount for the subscription item.\n */\n readonly amount: BillingMoneyAmount | undefined,\n /**\n * The plan associated with this subscription item.\n */\n readonly plan: BillingPlan | null,\n /**\n * The plan ID.\n */\n readonly planId: string | null,\n /**\n * Unix timestamp (milliseconds) of when the subscription item was created.\n */\n readonly createdAt: number,\n /**\n * Unix timestamp (milliseconds) of when the subscription item was last updated.\n */\n readonly updatedAt: number,\n /**\n * Unix timestamp (milliseconds) of when the current period ends.\n */\n readonly periodEnd: number | null,\n /**\n * Unix timestamp (milliseconds) of when the subscription item was canceled.\n */\n readonly canceledAt: number | null,\n /**\n * Unix timestamp (milliseconds) of when the subscription item became past due.\n */\n readonly pastDueAt: number | null,\n /**\n * Unix timestamp (milliseconds) of when the subscription item ended.\n */\n readonly endedAt: number | null,\n /**\n * The payer ID.\n */\n readonly payerId: string | undefined,\n /**\n * Whether this subscription item is currently in a free trial period.\n */\n readonly isFreeTrial?: boolean,\n /**\n * The lifetime amount paid for this subscription item.\n */\n readonly lifetimePaid?: BillingMoneyAmount,\n ) {}\n\n static fromJSON(data: BillingSubscriptionItemJSON): BillingSubscriptionItem {\n function formatAmountJSON(\n amount: BillingMoneyAmountJSON | null | undefined,\n ): BillingMoneyAmount | null | undefined {\n if (!amount) {\n return amount;\n }\n\n return {\n amount: amount.amount,\n amountFormatted: amount.amount_formatted,\n currency: amount.currency,\n currencySymbol: amount.currency_symbol,\n };\n }\n\n return new BillingSubscriptionItem(\n data.id,\n data.status,\n data.plan_period,\n data.period_start,\n data.next_payment,\n formatAmountJSON(data.amount) ?? undefined,\n data.plan ? BillingPlan.fromJSON(data.plan) : null,\n data.plan_id ?? null,\n data.created_at,\n data.updated_at,\n data.period_end,\n data.canceled_at,\n data.past_due_at,\n data.ended_at,\n data.payer_id,\n data.is_free_trial,\n formatAmountJSON(data.lifetime_paid) ?? undefined,\n );\n }\n}\n","import type { BillingMoneyAmount } from '@clerk/shared/types';\n\nimport { BillingSubscriptionItem } from './CommerceSubscriptionItem';\nimport type { BillingSubscriptionJSON } from './JSON';\n\n/**\n * The `BillingSubscription` object is similar to the [`BillingSubscriptionResource`](/docs/reference/javascript/types/billing-subscription-resource) object as it holds information about a subscription, as well as methods for managing it. However, the `BillingSubscription` object is different in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/billing/get/organizations/%7Borganization_id%7D/billing/subscription) and is not directly accessible from the Frontend API.\n *\n * @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.\n */\nexport class BillingSubscription {\n constructor(\n /**\n * The unique identifier for the billing subscription.\n */\n readonly id: string,\n /**\n * The current status of the subscription.\n */\n readonly status: BillingSubscriptionJSON['status'],\n /**\n * The ID of the payer for this subscription.\n */\n readonly payerId: string,\n /**\n * Unix timestamp (milliseconds) of when the subscription was created.\n */\n readonly createdAt: number,\n /**\n * Unix timestamp (milliseconds) of when the subscription was last updated.\n */\n readonly updatedAt: number,\n /**\n * Unix timestamp (milliseconds) of when the subscription became active.\n */\n readonly activeAt: number | null,\n /**\n * Unix timestamp (milliseconds) of when the subscription became past due.\n */\n readonly pastDueAt: number | null,\n /**\n * Array of subscription items in this subscription.\n */\n readonly subscriptionItems: BillingSubscriptionItem[],\n /**\n * Information about the next scheduled payment.\n */\n readonly nextPayment: { date: number; amount: BillingMoneyAmount } | null,\n /**\n * Whether the payer is eligible for a free trial.\n */\n readonly eligibleForFreeTrial: boolean,\n ) {}\n\n static fromJSON(data: BillingSubscriptionJSON): BillingSubscription {\n const nextPayment = data.next_payment\n ? {\n date: data.next_payment.date,\n amount: {\n amount: data.next_payment.amount.amount,\n amountFormatted: data.next_payment.amount.amount_formatted,\n currency: data.next_payment.amount.currency,\n currencySymbol: data.next_payment.amount.currency_symbol,\n },\n }\n : null;\n\n return new BillingSubscription(\n data.id,\n data.status,\n data.payer_id,\n data.created_at,\n data.updated_at,\n data.active_at ?? null,\n data.past_due_at ?? null,\n (data.subscription_items ?? []).map(item => BillingSubscriptionItem.fromJSON(item)),\n nextPayment,\n data.eligible_for_free_trial ?? false,\n );\n }\n}\n","import type { ExternalAccountJSON } from './JSON';\nimport { Verification } from './Verification';\n\n/**\n * The Backend `ExternalAccount` object is a model around an identification obtained by an external provider (e.g. a social provider such as Google).\n *\n * External account must be verified, so that you can make sure they can be assigned to their rightful owners. The `ExternalAccount` object holds all necessary state around the verification process.\n */\nexport class ExternalAccount {\n constructor(\n /**\n * The unique identifier for this external account.\n */\n readonly id: string,\n /**\n * The provider name (e.g., `google`).\n */\n readonly provider: string,\n /**\n * The identification with which this external account is associated.\n */\n readonly identificationId: string,\n /**\n * The unique ID of the user in the provider.\n */\n readonly externalId: string,\n /**\n * The scopes that the user has granted access to.\n */\n readonly approvedScopes: string,\n /**\n * The user's email address.\n */\n readonly emailAddress: string,\n /**\n * The user's first name.\n */\n readonly firstName: string,\n /**\n * The user's last name.\n */\n readonly lastName: string,\n /**\n * The user's image URL.\n */\n readonly imageUrl: string,\n /**\n * The user's username.\n */\n readonly username: string | null,\n /**\n * The phone number related to this specific external account.\n */\n readonly phoneNumber: string | null,\n /**\n * Metadata that can be read from the Frontend API and Backend API and can be set only from the Backend API.\n */\n readonly publicMetadata: Record<string, unknown> | null = {},\n /**\n * A descriptive label to differentiate multiple external accounts of the same user for the same provider.\n */\n readonly label: string | null,\n /**\n * An object holding information on the verification of this external account.\n */\n readonly verification: Verification | null,\n ) {}\n\n static fromJSON(data: ExternalAccountJSON): ExternalAccount {\n return new ExternalAccount(\n data.id,\n data.provider,\n data.identification_id,\n data.provider_user_id,\n data.approved_scopes,\n data.email_address,\n data.first_name,\n data.last_name,\n data.image_url || '',\n data.username,\n data.phone_number,\n data.public_metadata,\n data.label,\n data.verification && Verification.fromJSON(data.verification),\n );\n }\n}\n","import type { IdPOAuthAccessTokenJSON } from './JSON';\n\nexport class IdPOAuthAccessToken {\n constructor(\n readonly id: string,\n readonly clientId: string,\n readonly type: string,\n readonly subject: string,\n readonly scopes: string[],\n readonly revoked: boolean,\n readonly revocationReason: string | null,\n readonly expired: boolean,\n readonly expiration: number | null,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: IdPOAuthAccessTokenJSON) {\n return new IdPOAuthAccessToken(\n data.id,\n data.client_id,\n data.type,\n data.subject,\n data.scopes,\n data.revoked,\n data.revocation_reason,\n data.expired,\n data.expiration,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { InstanceJSON } from './JSON';\n\nexport class Instance {\n constructor(\n readonly id: string,\n readonly environmentType: string,\n readonly allowedOrigins: Array<string> | null,\n ) {}\n\n static fromJSON(data: InstanceJSON): Instance {\n return new Instance(data.id, data.environment_type, data.allowed_origins);\n }\n}\n","import type { InstanceRestrictionsJSON } from './JSON';\n\nexport class InstanceRestrictions {\n constructor(\n readonly allowlist: boolean,\n readonly blocklist: boolean,\n readonly blockEmailSubaddresses: boolean,\n readonly blockDisposableEmailDomains: boolean,\n readonly ignoreDotsForGmailAddresses: boolean,\n ) {}\n\n static fromJSON(data: InstanceRestrictionsJSON): InstanceRestrictions {\n return new InstanceRestrictions(\n data.allowlist,\n data.blocklist,\n data.block_email_subaddresses,\n data.block_disposable_email_domains,\n data.ignore_dots_for_gmail_addresses,\n );\n }\n}\n","import type { InstanceSettingsJSON } from './JSON';\n\nexport class InstanceSettings {\n constructor(\n readonly id?: string | undefined,\n readonly restrictedToAllowlist?: boolean | undefined,\n readonly fromEmailAddress?: string | undefined,\n readonly progressiveSignUp?: boolean | undefined,\n readonly enhancedEmailDeliverability?: boolean | undefined,\n ) {}\n\n static fromJSON(data: InstanceSettingsJSON): InstanceSettings {\n return new InstanceSettings(\n data.id,\n data.restricted_to_allowlist,\n data.from_email_address,\n data.progressive_sign_up,\n data.enhanced_email_deliverability,\n );\n }\n}\n","import type { InvitationStatus } from './Enums';\nimport type { InvitationJSON } from './JSON';\n\n/**\n * The Backend `Invitation` object represents an invitation to join your application.\n */\nexport class Invitation {\n private _raw: InvitationJSON | null = null;\n\n public get raw(): InvitationJSON | null {\n return this._raw;\n }\n\n constructor(\n /**\n * The unique identifier for the `Invitation`.\n */\n readonly id: string,\n /**\n * The email address that the invitation was sent to.\n */\n readonly emailAddress: string,\n /**\n * [Metadata](https://clerk.com/docs/reference/javascript/types/metadata#user-public-metadata){{ target: '_blank' }} that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API. Once the user accepts the invitation and signs up, these metadata will end up in the user's public metadata.\n */\n readonly publicMetadata: Record<string, unknown> | null,\n /**\n * The date when the `Invitation` was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the `Invitation` was last updated.\n */\n readonly updatedAt: number,\n /**\n * The status of the `Invitation`.\n */\n readonly status: InvitationStatus,\n /**\n * The URL that the user can use to accept the invitation.\n */\n readonly url?: string,\n /**\n * Whether the `Invitation` has been revoked.\n */\n readonly revoked?: boolean,\n ) {}\n\n static fromJSON(data: InvitationJSON): Invitation {\n const res = new Invitation(\n data.id,\n data.email_address,\n data.public_metadata,\n data.created_at,\n data.updated_at,\n data.status,\n data.url,\n data.revoked,\n );\n res._raw = data;\n return res;\n }\n}\n","import type { LastAuthenticationStrategy, SignUpStatus, VerificationStatus } from '@clerk/shared/types';\n\nimport type {\n ActorTokenStatus,\n AllowlistIdentifierType,\n BlocklistIdentifierType,\n DomainsEnrollmentModes,\n InvitationStatus,\n OrganizationDomainVerificationStatus,\n OrganizationDomainVerificationStrategy,\n OrganizationEnrollmentMode,\n OrganizationInvitationStatus,\n OrganizationMembershipRole,\n SignInStatus,\n SignUpVerificationNextAction,\n WaitlistEntryStatus,\n} from './Enums';\n\nexport const ObjectType = {\n AccountlessApplication: 'accountless_application',\n ActorToken: 'actor_token',\n AllowlistIdentifier: 'allowlist_identifier',\n ApiKey: 'api_key',\n BlocklistIdentifier: 'blocklist_identifier',\n Client: 'client',\n Cookies: 'cookies',\n Domain: 'domain',\n Email: 'email',\n EmailAddress: 'email_address',\n ExternalAccount: 'external_account',\n FacebookAccount: 'facebook_account',\n GoogleAccount: 'google_account',\n Instance: 'instance',\n InstanceRestrictions: 'instance_restrictions',\n InstanceSettings: 'instance_settings',\n Invitation: 'invitation',\n Machine: 'machine',\n MachineScope: 'machine_scope',\n MachineSecretKey: 'machine_secret_key',\n M2MToken: 'machine_to_machine_token',\n JwtTemplate: 'jwt_template',\n OauthAccessToken: 'oauth_access_token',\n IdpOAuthAccessToken: 'clerk_idp_oauth_access_token',\n OAuthApplication: 'oauth_application',\n Organization: 'organization',\n OrganizationDomain: 'organization_domain',\n OrganizationInvitation: 'organization_invitation',\n OrganizationMembership: 'organization_membership',\n OrganizationSettings: 'organization_settings',\n PhoneNumber: 'phone_number',\n ProxyCheck: 'proxy_check',\n RedirectUrl: 'redirect_url',\n SamlConnection: 'saml_connection',\n Session: 'session',\n SignInAttempt: 'sign_in_attempt',\n SignInToken: 'sign_in_token',\n SignUpAttempt: 'sign_up_attempt',\n SmsMessage: 'sms_message',\n User: 'user',\n WaitlistEntry: 'waitlist_entry',\n Web3Wallet: 'web3_wallet',\n Token: 'token',\n TotalCount: 'total_count',\n TestingToken: 'testing_token',\n Role: 'role',\n Permission: 'permission',\n BillingPayer: 'commerce_payer',\n BillingPaymentAttempt: 'commerce_payment_attempt',\n BillingSubscription: 'commerce_subscription',\n BillingSubscriptionItem: 'commerce_subscription_item',\n BillingPlan: 'commerce_plan',\n Feature: 'feature',\n} as const;\n\nexport type ObjectType = (typeof ObjectType)[keyof typeof ObjectType];\n\nexport interface ClerkResourceJSON {\n /**\n * The type of the resource.\n */\n object: ObjectType;\n /**\n * The unique identifier for the resource.\n */\n id: string;\n}\n\nexport interface CookiesJSON {\n object: typeof ObjectType.Cookies;\n cookies: string[];\n}\n\nexport interface TokenJSON {\n object: typeof ObjectType.Token;\n jwt: string;\n}\n\nexport interface AccountlessApplicationJSON extends ClerkResourceJSON {\n object: typeof ObjectType.AccountlessApplication;\n publishable_key: string;\n secret_key: string;\n claim_url: string;\n api_keys_url: string;\n}\n\nexport interface ActorTokenJSON extends ClerkResourceJSON {\n object: typeof ObjectType.ActorToken;\n id: string;\n status: ActorTokenStatus;\n user_id: string;\n actor: Record<string, unknown> | null;\n token?: string | null;\n url?: string | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface AllowlistIdentifierJSON extends ClerkResourceJSON {\n object: typeof ObjectType.AllowlistIdentifier;\n identifier: string;\n identifier_type: AllowlistIdentifierType;\n instance_id?: string;\n invitation_id?: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface BlocklistIdentifierJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BlocklistIdentifier;\n identifier: string;\n identifier_type: BlocklistIdentifierType;\n instance_id?: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface ClientJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Client;\n session_ids: string[];\n sessions: SessionJSON[];\n sign_in_id: string | null;\n sign_up_id: string | null;\n last_active_session_id: string | null;\n last_authentication_strategy: LastAuthenticationStrategy | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface CnameTargetJSON {\n host: string;\n value: string;\n /**\n * Denotes whether this CNAME target is required to be set in order for the domain to be considered deployed.\n */\n required: boolean;\n}\n\nexport interface DomainJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Domain;\n id: string;\n name: string;\n is_satellite: boolean;\n frontend_api_url: string;\n /**\n * null for satellite domains\n */\n accounts_portal_url?: string | null;\n proxy_url?: string;\n development_origin: string;\n cname_targets: CnameTargetJSON[];\n}\n\nexport interface EmailJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Email;\n slug?: string | null;\n from_email_name: string;\n to_email_address?: string;\n email_address_id: string | null;\n user_id?: string | null;\n subject?: string;\n body?: string;\n body_plain?: string | null;\n status?: string;\n data?: Record<string, any> | null;\n delivered_by_clerk: boolean;\n}\n\nexport interface EmailAddressJSON extends ClerkResourceJSON {\n object: typeof ObjectType.EmailAddress;\n email_address: string;\n verification: VerificationJSON | null;\n linked_to: IdentificationLinkJSON[];\n}\n\nexport interface ExternalAccountJSON extends ClerkResourceJSON {\n object: typeof ObjectType.ExternalAccount;\n provider: string;\n identification_id: string;\n provider_user_id: string;\n approved_scopes: string;\n email_address: string;\n first_name: string;\n last_name: string;\n image_url?: string;\n username: string | null;\n phone_number: string | null;\n public_metadata?: Record<string, unknown> | null;\n label: string | null;\n verification: VerificationJSON | null;\n}\n\nexport interface JwksJSON {\n keys?: JwksKeyJSON[];\n}\n\nexport interface JwksKeyJSON {\n use: string;\n kty: string;\n kid: string;\n alg: string;\n n: string;\n e: string;\n}\n\nexport interface JwtTemplateJSON extends ClerkResourceJSON {\n object: typeof ObjectType.JwtTemplate;\n id: string;\n name: string;\n claims: object;\n lifetime: number;\n allowed_clock_skew: number;\n custom_signing_key: boolean;\n signing_algorithm: string;\n created_at: number;\n updated_at: number;\n}\nexport interface IdentificationLinkJSON extends ClerkResourceJSON {\n type: string;\n}\n\nexport interface OrganizationSettingsJSON extends ClerkResourceJSON {\n object: typeof ObjectType.OrganizationSettings;\n enabled: boolean;\n max_allowed_memberships: number;\n max_allowed_roles: number;\n max_allowed_permissions: number;\n creator_role: string;\n admin_delete_enabled: boolean;\n domains_enabled: boolean;\n slug_disabled: boolean;\n domains_enrollment_modes: Array<DomainsEnrollmentModes>;\n domains_default_role: string;\n}\n\nexport interface InstanceJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Instance;\n id: string;\n environment_type: string;\n allowed_origins: Array<string> | null;\n}\n\nexport interface InstanceRestrictionsJSON extends ClerkResourceJSON {\n object: typeof ObjectType.InstanceRestrictions;\n allowlist: boolean;\n blocklist: boolean;\n block_email_subaddresses: boolean;\n block_disposable_email_domains: boolean;\n ignore_dots_for_gmail_addresses: boolean;\n}\n\nexport interface InstanceSettingsJSON extends ClerkResourceJSON {\n object: typeof ObjectType.InstanceSettings;\n id: string;\n restricted_to_allowlist: boolean;\n from_email_address: string;\n progressive_sign_up: boolean;\n enhanced_email_deliverability: boolean;\n}\n\nexport interface InvitationJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Invitation;\n email_address: string;\n public_metadata: Record<string, unknown> | null;\n revoked?: boolean;\n status: InvitationStatus;\n url?: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface OauthAccessTokenJSON {\n external_account_id: string;\n object: typeof ObjectType.OauthAccessToken;\n token: string;\n provider: string;\n public_metadata: Record<string, unknown>;\n label: string | null;\n // Only set in OAuth 2.0 tokens\n scopes?: string[];\n // Only set in OAuth 1.0 tokens\n token_secret?: string;\n expires_at?: number;\n}\n\nexport interface OAuthApplicationJSON extends ClerkResourceJSON {\n object: typeof ObjectType.OAuthApplication;\n id: string;\n instance_id: string;\n name: string;\n client_id: string;\n client_uri: string | null;\n client_image_url: string | null;\n dynamically_registered: boolean;\n consent_screen_enabled: boolean;\n pkce_required: boolean;\n public: boolean;\n scopes: string;\n redirect_uris: Array<string>;\n authorize_url: string;\n token_fetch_url: string;\n user_info_url: string;\n discovery_url: string;\n token_introspection_url: string;\n created_at: number;\n updated_at: number;\n client_secret?: string;\n}\n\nexport interface OrganizationJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Organization;\n name: string;\n slug: string;\n image_url?: string;\n has_image: boolean;\n members_count?: number;\n pending_invitations_count?: number;\n max_allowed_memberships: number;\n admin_delete_enabled: boolean;\n public_metadata: OrganizationPublicMetadata | null;\n private_metadata?: OrganizationPrivateMetadata;\n created_by?: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface OrganizationDomainJSON extends ClerkResourceJSON {\n object: typeof ObjectType.OrganizationDomain;\n id: string;\n name: string;\n organization_id: string;\n enrollment_mode: OrganizationEnrollmentMode;\n verification: OrganizationDomainVerificationJSON | null;\n affiliation_email_address: string | null;\n created_at: number;\n updated_at: number;\n total_pending_invitations: number;\n total_pending_suggestions: number;\n}\n\nexport interface OrganizationDomainVerificationJSON {\n status: OrganizationDomainVerificationStatus;\n strategy: OrganizationDomainVerificationStrategy;\n attempts: number;\n expires_at: number;\n}\n\nexport interface OrganizationInvitationJSON extends ClerkResourceJSON {\n email_address: string;\n role: OrganizationMembershipRole;\n role_name: string;\n organization_id: string;\n public_organization_data?: PublicOrganizationDataJSON | null;\n status?: OrganizationInvitationStatus;\n public_metadata: OrganizationInvitationPublicMetadata;\n private_metadata: OrganizationInvitationPrivateMetadata;\n url: string | null;\n created_at: number;\n updated_at: number;\n expires_at: number;\n}\n\nexport interface OrganizationInvitationAcceptedJSON extends OrganizationInvitationJSON {\n status: 'accepted';\n user_id: string;\n}\n\n/**\n * @interface\n */\nexport interface PublicOrganizationDataJSON extends ClerkResourceJSON {\n /**\n * The name of the organization.\n */\n name: string;\n /**\n * The slug of the organization.\n */\n slug: string;\n /**\n * Holds the default organization profile image. Compatible with Clerk's [Image Optimization](https://clerk.com/docs/guides/development/image-optimization).\n */\n image_url?: string;\n /**\n * Whether the organization has a profile image.\n */\n has_image: boolean;\n}\n\nexport interface OrganizationMembershipJSON extends ClerkResourceJSON {\n object: typeof ObjectType.OrganizationMembership;\n public_metadata: OrganizationMembershipPublicMetadata;\n private_metadata?: OrganizationMembershipPrivateMetadata;\n role: OrganizationMembershipRole;\n permissions: string[];\n created_at: number;\n updated_at: number;\n organization: OrganizationJSON;\n public_user_data: OrganizationMembershipPublicUserDataJSON;\n}\n\nexport interface OrganizationMembershipPublicUserDataJSON {\n identifier: string;\n first_name: string | null;\n last_name: string | null;\n image_url: string;\n has_image: boolean;\n user_id: string;\n}\n\nexport interface PhoneNumberJSON extends ClerkResourceJSON {\n object: typeof ObjectType.PhoneNumber;\n phone_number: string;\n reserved_for_second_factor: boolean;\n default_second_factor: boolean;\n reserved: boolean;\n verification: VerificationJSON | null;\n linked_to: IdentificationLinkJSON[];\n backup_codes: string[];\n}\n\nexport type ProxyCheckJSON = {\n object: typeof ObjectType.ProxyCheck;\n id: string;\n domain_id: string;\n last_run_at: number | null;\n proxy_url: string;\n successful: boolean;\n created_at: number;\n updated_at: number;\n};\n\nexport interface RedirectUrlJSON extends ClerkResourceJSON {\n object: typeof ObjectType.RedirectUrl;\n url: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface SessionActivityJSON extends ClerkResourceJSON {\n id: string;\n device_type?: string;\n is_mobile: boolean;\n browser_name?: string;\n browser_version?: string;\n ip_address?: string;\n city?: string;\n country?: string;\n}\n\nexport interface SessionJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Session;\n client_id: string;\n user_id: string;\n status: string;\n last_active_organization_id?: string;\n actor: Record<string, unknown> | null;\n latest_activity?: SessionActivityJSON;\n last_active_at: number;\n expire_at: number;\n abandon_at: number;\n created_at: number;\n updated_at: number;\n}\n\n/**\n * Session webhook event payload extending `SessionJSON` interface with associated `User` information.\n * Used for `session.created`, `session.ended`, `session.removed`, and `session.revoked` webhook events.\n */\nexport interface SessionWebhookEventJSON extends SessionJSON {\n /**\n * The user associated with the session, or null if not available.\n */\n user: UserJSON | null;\n}\n\nexport interface SignInJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SignInToken;\n status: SignInStatus;\n identifier: string;\n created_session_id: string | null;\n}\n\nexport interface SignInTokenJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SignInToken;\n user_id: string;\n token: string;\n status: 'pending' | 'accepted' | 'revoked';\n url: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface SignUpJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SignUpAttempt;\n id: string;\n status: SignUpStatus;\n required_fields: string[];\n optional_fields: string[];\n missing_fields: string[];\n unverified_fields: string[];\n verifications: SignUpVerificationsJSON;\n username: string | null;\n email_address: string | null;\n phone_number: string | null;\n web3_wallet: string | null;\n password_enabled: boolean;\n first_name: string | null;\n last_name: string | null;\n public_metadata?: Record<string, unknown> | null;\n unsafe_metadata?: Record<string, unknown> | null;\n custom_action: boolean;\n external_id: string | null;\n created_session_id: string | null;\n created_user_id: string | null;\n abandon_at: number | null;\n legal_accepted_at: number | null;\n\n /**\n * @deprecated Please use `verifications.external_account` instead\n */\n external_account: object | null;\n}\n\nexport interface SignUpVerificationsJSON {\n email_address: SignUpVerificationJSON;\n phone_number: SignUpVerificationJSON;\n web3_wallet: SignUpVerificationJSON;\n external_account: VerificationJSON;\n}\n\nexport interface SignUpVerificationJSON {\n next_action: SignUpVerificationNextAction;\n supported_strategies: string[];\n}\n\nexport interface SMSMessageJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SmsMessage;\n from_phone_number: string;\n to_phone_number: string;\n phone_number_id: string | null;\n user_id?: string;\n message: string;\n status: string;\n slug?: string | null;\n data?: Record<string, any> | null;\n delivered_by_clerk: boolean;\n}\n\nexport interface UserJSON extends ClerkResourceJSON {\n object: typeof ObjectType.User;\n username: string | null;\n first_name: string | null;\n last_name: string | null;\n image_url: string;\n has_image: boolean;\n primary_email_address_id: string | null;\n primary_phone_number_id: string | null;\n primary_web3_wallet_id: string | null;\n password_enabled: boolean;\n two_factor_enabled: boolean;\n totp_enabled: boolean;\n backup_code_enabled: boolean;\n email_addresses: EmailAddressJSON[];\n phone_numbers: PhoneNumberJSON[];\n web3_wallets: Web3WalletJSON[];\n organization_memberships: OrganizationMembershipJSON[] | null;\n external_accounts: ExternalAccountJSON[];\n password_last_updated_at: number | null;\n public_metadata: UserPublicMetadata;\n private_metadata: UserPrivateMetadata;\n unsafe_metadata: UserUnsafeMetadata;\n external_id: string | null;\n last_sign_in_at: number | null;\n banned: boolean;\n locked: boolean;\n lockout_expires_in_seconds: number | null;\n verification_attempts_remaining: number | null;\n created_at: number;\n updated_at: number;\n last_active_at: number | null;\n create_organization_enabled: boolean;\n create_organizations_limit: number | null;\n delete_self_enabled: boolean;\n legal_accepted_at: number | null;\n /**\n * The locale of the user in BCP-47 format.\n */\n locale: string | null;\n}\n\nexport interface VerificationJSON extends ClerkResourceJSON {\n status: VerificationStatus;\n strategy: string;\n attempts: number | null;\n expire_at: number | null;\n verified_at_client?: string;\n external_verification_redirect_url?: string | null;\n nonce?: string | null;\n message?: string | null;\n}\n\nexport interface WaitlistEntryJSON extends ClerkResourceJSON {\n object: typeof ObjectType.WaitlistEntry;\n id: string;\n status: WaitlistEntryStatus;\n email_address: string;\n invitation: InvitationJSON | null;\n is_locked: boolean;\n created_at: number;\n updated_at: number;\n}\n\nexport interface Web3WalletJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Web3Wallet;\n web3_wallet: string;\n verification: VerificationJSON | null;\n}\n\nexport interface DeletedObjectJSON {\n object: string;\n id?: string;\n slug?: string;\n deleted: boolean;\n}\n\n/**\n * User deletion webhook event payload that extends `DeletedObjectJSON`.\n * Includes the `external_id` field to identify the deleted user in external systems.\n * Used for `user.deleted` webhook events.\n */\nexport interface UserDeletedJSON extends DeletedObjectJSON {\n /**\n * The external identifier associated with the deleted user, if one was set.\n */\n external_id?: string;\n}\n\nexport interface PaginatedResponseJSON {\n data: object[];\n total_count?: number;\n}\n\nexport interface SamlConnectionJSON extends ClerkResourceJSON {\n object: typeof ObjectType.SamlConnection;\n name: string;\n domain: string;\n organization_id: string | null;\n idp_entity_id: string;\n idp_sso_url: string;\n idp_certificate: string;\n idp_metadata_url: string;\n idp_metadata: string;\n acs_url: string;\n sp_entity_id: string;\n sp_metadata_url: string;\n active: boolean;\n provider: string;\n user_count: number;\n sync_user_attributes: boolean;\n allow_subdomains: boolean;\n allow_idp_initiated: boolean;\n created_at: number;\n updated_at: number;\n attribute_mapping: AttributeMappingJSON;\n}\n\nexport interface AttributeMappingJSON {\n user_id: string;\n email_address: string;\n first_name: string;\n last_name: string;\n}\n\nexport interface TestingTokenJSON {\n object: typeof ObjectType.TestingToken;\n token: string;\n expires_at: number;\n}\n\nexport interface RoleJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Role;\n key: string;\n name: string;\n description: string;\n permissions: PermissionJSON[];\n is_creator_eligible: boolean;\n created_at: number;\n updated_at: number;\n}\n\nexport interface PermissionJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Permission;\n key: string;\n name: string;\n description: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface MachineJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Machine;\n id: string;\n name: string;\n instance_id: string;\n created_at: number;\n updated_at: number;\n default_token_ttl: number;\n scoped_machines: MachineJSON[];\n secret_key?: string;\n}\n\nexport interface MachineScopeJSON {\n object: typeof ObjectType.MachineScope;\n from_machine_id: string;\n to_machine_id: string;\n created_at?: number;\n deleted?: boolean;\n}\n\nexport interface MachineSecretKeyJSON {\n object: typeof ObjectType.MachineSecretKey;\n secret: string;\n}\n\nexport interface M2MTokenJSON extends ClerkResourceJSON {\n object: typeof ObjectType.M2MToken;\n token?: string;\n subject: string;\n scopes: string[];\n claims: Record<string, any> | null;\n revoked: boolean;\n revocation_reason: string | null;\n expired: boolean;\n expiration: number | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface APIKeyJSON extends ClerkResourceJSON {\n object: typeof ObjectType.ApiKey;\n type: string;\n name: string;\n secret?: string;\n subject: string;\n scopes: string[];\n claims: Record<string, any> | null;\n revoked: boolean;\n revocation_reason: string | null;\n expired: boolean;\n expiration: number | null;\n created_by: string | null;\n description: string | null;\n last_used_at: number | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface IdPOAuthAccessTokenJSON extends ClerkResourceJSON {\n object: typeof ObjectType.IdpOAuthAccessToken;\n client_id: string;\n type: string;\n subject: string;\n scopes: string[];\n revoked: boolean;\n revocation_reason: string | null;\n expired: boolean;\n expiration: number | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface BillingPayerJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingPayer;\n instance_id: string;\n user_id?: string;\n first_name?: string;\n last_name?: string;\n email: string;\n organization_id?: string;\n organization_name?: string;\n image_url: string;\n created_at: number;\n updated_at: number;\n}\n\ninterface BillingPayeeJSON {\n id: string;\n gateway_type: string;\n gateway_external_id: string;\n gateway_status: 'active' | 'pending' | 'restricted' | 'disconnected';\n}\n\ninterface BillingMoneyAmountJSON {\n amount: number;\n amount_formatted: string;\n currency: string;\n currency_symbol: string;\n}\n\ninterface BillingTotalsJSON {\n subtotal: BillingMoneyAmountJSON;\n tax_total: BillingMoneyAmountJSON;\n grand_total: BillingMoneyAmountJSON;\n}\n\nexport interface FeatureJSON extends ClerkResourceJSON {\n object: typeof ObjectType.Feature;\n name: string;\n description?: string | null;\n slug: string;\n avatar_url?: string | null;\n}\n\n/**\n * @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.\n */\nexport interface BillingPlanJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingPlan;\n id: string;\n name: string;\n slug: string;\n description: string | null;\n is_default: boolean;\n is_recurring: boolean;\n has_base_fee: boolean;\n publicly_visible: boolean;\n fee: BillingMoneyAmountJSON;\n annual_fee: BillingMoneyAmountJSON | null;\n annual_monthly_fee: BillingMoneyAmountJSON | null;\n for_payer_type: 'org' | 'user';\n features?: FeatureJSON[];\n}\n\ntype BillingSubscriptionItemStatus =\n | 'abandoned'\n | 'active'\n | 'canceled'\n | 'ended'\n | 'expired'\n | 'incomplete'\n | 'past_due'\n | 'upcoming';\n\n/**\n * @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.\n */\nexport interface BillingSubscriptionItemJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingSubscriptionItem;\n status: BillingSubscriptionItemStatus;\n plan_period: 'month' | 'annual';\n payer_id?: string;\n period_start: number;\n period_end: number | null;\n is_free_trial?: boolean;\n ended_at: number | null;\n created_at: number;\n updated_at: number;\n canceled_at: number | null;\n past_due_at: number | null;\n lifetime_paid: BillingMoneyAmountJSON | null;\n next_payment?: {\n amount: number;\n date: number;\n } | null;\n amount: BillingMoneyAmountJSON;\n plan?: BillingPlanJSON | null;\n plan_id?: string | null;\n}\n\n/**\n * Webhooks specific interface for BillingSubscriptionItem.\n */\nexport interface BillingSubscriptionItemWebhookEventJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingSubscriptionItem;\n status: BillingSubscriptionItemStatus;\n credit: {\n amount: BillingMoneyAmountJSON;\n cycle_days_remaining: number;\n cycle_days_total: number;\n cycle_remaining_percent: number;\n };\n proration_date: string;\n plan_period: 'month' | 'annual';\n period_start: number;\n period_end?: number;\n canceled_at?: number;\n past_due_at?: number;\n lifetime_paid: number;\n next_payment_amount: number;\n next_payment_date: number;\n amount: BillingMoneyAmountJSON;\n plan?: {\n id: string;\n instance_id: string;\n product_id: string;\n name: string;\n slug: string;\n description?: string;\n is_default: boolean;\n is_recurring: boolean;\n amount: number;\n period: 'month' | 'annual';\n interval: number;\n has_base_fee: boolean;\n currency: string;\n annual_monthly_amount: number;\n publicly_visible: boolean;\n } | null;\n plan_id?: string | null;\n payer?: BillingPayerJSON;\n}\n\n/**\n * Webhooks specific interface for BillingPaymentAttempt.\n */\nexport interface BillingPaymentAttemptWebhookEventJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingPaymentAttempt;\n instance_id: string;\n payment_id: string;\n statement_id: string;\n gateway_external_id: string;\n status: 'pending' | 'paid' | 'failed';\n created_at: number;\n updated_at: number;\n paid_at?: number;\n failed_at?: number;\n failed_reason?: {\n code: string;\n decline_code: string;\n };\n billing_date: number;\n charge_type: 'checkout' | 'recurring';\n payee: BillingPayeeJSON;\n payer: BillingPayerJSON;\n totals: BillingTotalsJSON;\n payment_source: {\n id: string;\n gateway: string;\n gateway_external_id: string;\n gateway_external_account_id?: string;\n payment_method: string;\n status: 'active' | 'disconnected';\n card_type?: string;\n last4?: string;\n };\n subscription_items: BillingSubscriptionItemWebhookEventJSON[];\n}\n\n/**\n * Webhooks specific interface for BillingSubscription.\n */\nexport interface BillingSubscriptionWebhookEventJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingSubscription;\n status: 'abandoned' | 'active' | 'canceled' | 'ended' | 'expired' | 'incomplete' | 'past_due' | 'upcoming';\n active_at?: number;\n canceled_at?: number;\n created_at: number;\n ended_at?: number;\n past_due_at?: number;\n updated_at: number;\n latest_payment_id: string;\n payer_id: string;\n payer: BillingPayerJSON;\n payment_source_id: string;\n items: BillingSubscriptionItemWebhookEventJSON[];\n}\n\nexport interface BillingSubscriptionJSON extends ClerkResourceJSON {\n object: typeof ObjectType.BillingSubscription;\n status: 'active' | 'past_due' | 'canceled' | 'ended' | 'abandoned' | 'incomplete';\n payer_id: string;\n created_at: number;\n updated_at: number;\n active_at: number | null;\n past_due_at: number | null;\n subscription_items: BillingSubscriptionItemJSON[];\n next_payment?: {\n date: number;\n amount: BillingMoneyAmountJSON;\n };\n eligible_for_free_trial?: boolean;\n}\n\nexport interface WebhooksSvixJSON {\n svix_url: string;\n}\n","import type { JwtTemplateJSON } from './JSON';\n\nexport class JwtTemplate {\n constructor(\n readonly id: string,\n readonly name: string,\n readonly claims: object,\n readonly lifetime: number,\n readonly allowedClockSkew: number,\n readonly customSigningKey: boolean,\n readonly signingAlgorithm: string,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: JwtTemplateJSON): JwtTemplate {\n return new JwtTemplate(\n data.id,\n data.name,\n data.claims,\n data.lifetime,\n data.allowed_clock_skew,\n data.custom_signing_key,\n data.signing_algorithm,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { M2MTokenJSON } from './JSON';\n\n/**\n * The Backend `M2MToken` object holds information about a machine-to-machine token.\n */\nexport class M2MToken {\n constructor(\n readonly id: string,\n readonly subject: string,\n readonly scopes: string[],\n readonly claims: Record<string, any> | null,\n readonly revoked: boolean,\n readonly revocationReason: string | null,\n readonly expired: boolean,\n readonly expiration: number | null,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly token?: string,\n ) {}\n\n static fromJSON(data: M2MTokenJSON): M2MToken {\n return new M2MToken(\n data.id,\n data.subject,\n data.scopes,\n data.claims,\n data.revoked,\n data.revocation_reason,\n data.expired,\n data.expiration,\n data.created_at,\n data.updated_at,\n data.token,\n );\n }\n}\n","import type { MachineJSON } from './JSON';\n\n/**\n * The Backend `Machine` object holds information about a machine.\n */\nexport class Machine {\n constructor(\n readonly id: string,\n readonly name: string,\n readonly instanceId: string,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly scopedMachines: Machine[],\n readonly defaultTokenTtl: number,\n readonly secretKey?: string,\n ) {}\n\n static fromJSON(data: MachineJSON): Machine {\n return new Machine(\n data.id,\n data.name,\n data.instance_id,\n data.created_at,\n data.updated_at,\n data.scoped_machines.map(\n m =>\n new Machine(\n m.id,\n m.name,\n m.instance_id,\n m.created_at,\n m.updated_at,\n [], // Nested machines don't have scoped_machines\n m.default_token_ttl,\n ),\n ),\n data.default_token_ttl,\n data.secret_key,\n );\n }\n}\n","import type { MachineScopeJSON } from './JSON';\n\n/**\n * The Backend `MachineScope` object holds information about a machine scope.\n */\nexport class MachineScope {\n constructor(\n readonly fromMachineId: string,\n readonly toMachineId: string,\n readonly createdAt?: number,\n readonly deleted?: boolean,\n ) {}\n\n static fromJSON(data: MachineScopeJSON): MachineScope {\n return new MachineScope(data.from_machine_id, data.to_machine_id, data.created_at, data.deleted);\n }\n}\n","import type { MachineSecretKeyJSON } from './JSON';\n\n/**\n * The Backend `MachineSecretKey` object holds information about a machine secret key.\n */\nexport class MachineSecretKey {\n constructor(readonly secret: string) {}\n\n static fromJSON(data: MachineSecretKeyJSON): MachineSecretKey {\n return new MachineSecretKey(data.secret);\n }\n}\n","import type { OauthAccessTokenJSON } from './JSON';\n\nexport class OauthAccessToken {\n constructor(\n readonly externalAccountId: string,\n readonly provider: string,\n readonly token: string,\n readonly publicMetadata: Record<string, unknown> = {},\n readonly label: string,\n readonly scopes?: string[],\n readonly tokenSecret?: string,\n readonly expiresAt?: number,\n ) {}\n\n static fromJSON(data: OauthAccessTokenJSON) {\n return new OauthAccessToken(\n data.external_account_id,\n data.provider,\n data.token,\n data.public_metadata,\n data.label || '',\n data.scopes,\n data.token_secret,\n data.expires_at,\n );\n }\n}\n","import type { OAuthApplicationJSON } from './JSON';\n\n/**\n * The Backend `OAuthApplication` object holds information about an OAuth application.\n */\nexport class OAuthApplication {\n constructor(\n /**\n * The unique identifier for the OAuth application.\n */\n readonly id: string,\n /**\n * The ID of the instance that this OAuth application belongs to.\n */\n readonly instanceId: string,\n /**\n * The name of the new OAuth application.\n */\n readonly name: string,\n /**\n * The ID of the client associated with the OAuth application.\n */\n readonly clientId: string,\n /**\n * The public-facing URL of the OAuth application, often shown on consent screens.\n */\n readonly clientUri: string | null,\n /**\n * The URL of the image or logo representing the OAuth application.\n */\n readonly clientImageUrl: string | null,\n /**\n * Specifies whether the OAuth application is dynamically registered.\n */\n readonly dynamicallyRegistered: boolean,\n /**\n * Specifies whether the consent screen should be displayed in the authentication flow. Cannot be disabled for dynamically registered OAuth applications.\n */\n readonly consentScreenEnabled: boolean,\n /**\n * Specifies whether the Proof Key of Code Exchange (PKCE) flow should be required in the authentication flow.\n */\n readonly pkceRequired: boolean,\n /**\n * Indicates whether the client is public. If true, the Proof Key of Code Exchange (PKCE) flow can be used.\n */\n readonly isPublic: boolean, // NOTE: `public` is reserved\n /**\n * Scopes for the new OAuth application.\n */\n readonly scopes: string,\n /**\n * An array of redirect URIs of the new OAuth application.\n */\n readonly redirectUris: Array<string>,\n /**\n * The URL used to authorize the user and obtain an authorization code.\n */\n readonly authorizeUrl: string,\n /**\n * The URL used by the client to exchange an authorization code for an access token.\n */\n readonly tokenFetchUrl: string,\n /**\n * The URL where the client can retrieve user information using an access token.\n */\n readonly userInfoUrl: string,\n /**\n * The OpenID Connect discovery endpoint URL for this OAuth application.\n */\n readonly discoveryUrl: string,\n /**\n * The URL used to introspect and validate issued access tokens.\n */\n readonly tokenIntrospectionUrl: string,\n /**\n * The date when the OAuth application was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the OAuth application was last updated.\n */\n readonly updatedAt: number,\n /**\n * The client secret associated with the OAuth application. Empty if public client.\n */\n readonly clientSecret?: string,\n ) {}\n\n static fromJSON(data: OAuthApplicationJSON) {\n return new OAuthApplication(\n data.id,\n data.instance_id,\n data.name,\n data.client_id,\n data.client_uri,\n data.client_image_url,\n data.dynamically_registered,\n data.consent_screen_enabled,\n data.pkce_required,\n data.public,\n data.scopes,\n data.redirect_uris,\n data.authorize_url,\n data.token_fetch_url,\n data.user_info_url,\n data.discovery_url,\n data.token_introspection_url,\n data.created_at,\n data.updated_at,\n data.client_secret,\n );\n }\n}\n","import type { OrganizationJSON } from './JSON';\n\n/**\n * The Backend `Organization` object is similar to the [`Organization`](https://clerk.com/docs/reference/javascript/organization) object as it holds information about an organization, as well as methods for managing it. However, the Backend `Organization` object is different in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Organizations#operation/ListOrganizations){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class Organization {\n private _raw: OrganizationJSON | null = null;\n\n public get raw(): OrganizationJSON | null {\n return this._raw;\n }\n\n constructor(\n /**\n * The unique identifier for the organization.\n */\n readonly id: string,\n /**\n * The name of the organization.\n */\n readonly name: string,\n /**\n * The URL-friendly identifier of the user's active organization. If supplied, it must be unique for the instance.\n */\n readonly slug: string,\n /**\n * Holds the organization's logo. Compatible with Clerk's [Image Optimization](https://clerk.com/docs/guides/development/image-optimization).\n */\n readonly imageUrl: string,\n /**\n * Whether the organization has an image.\n */\n readonly hasImage: boolean,\n /**\n * The date when the organization was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the organization was last updated.\n */\n readonly updatedAt: number,\n /**\n * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API.\n */\n readonly publicMetadata: OrganizationPublicMetadata | null = {},\n /**\n * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}.\n */\n readonly privateMetadata: OrganizationPrivateMetadata = {},\n /**\n * The maximum number of memberships allowed in the organization.\n */\n readonly maxAllowedMemberships: number,\n /**\n * Whether the organization allows admins to delete users.\n */\n readonly adminDeleteEnabled: boolean,\n /**\n * The number of members in the organization.\n */\n readonly membersCount?: number,\n /**\n * The ID of the user who created the organization.\n */\n readonly createdBy?: string,\n ) {}\n\n static fromJSON(data: OrganizationJSON): Organization {\n const res = new Organization(\n data.id,\n data.name,\n data.slug,\n data.image_url || '',\n data.has_image,\n data.created_at,\n data.updated_at,\n data.public_metadata,\n data.private_metadata,\n data.max_allowed_memberships,\n data.admin_delete_enabled,\n data.members_count,\n data.created_by,\n );\n res._raw = data;\n return res;\n }\n}\n","import type { OrganizationInvitationStatus, OrganizationMembershipRole } from './Enums';\nimport type { OrganizationInvitationJSON, PublicOrganizationDataJSON } from './JSON';\n\n/**\n * The Backend `OrganizationInvitation` object is similar to the [`OrganizationInvitation`](https://clerk.com/docs/reference/javascript/types/organization-invitation) object as it's the model around an organization invitation. However, the Backend `OrganizationInvitation` object is different in that it's used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Organization-Invitations#operation/CreateOrganizationInvitation){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class OrganizationInvitation {\n private _raw: OrganizationInvitationJSON | null = null;\n\n public get raw(): OrganizationInvitationJSON | null {\n return this._raw;\n }\n\n constructor(\n /**\n * The unique identifier for the `OrganizationInvitation`.\n */\n readonly id: string,\n /**\n * The email address of the user who is invited to the [`Organization`](https://clerk.com/docs/reference/backend/types/backend-organization).\n */\n readonly emailAddress: string,\n /**\n * The role of the invited user.\n */\n readonly role: OrganizationMembershipRole,\n /**\n * The name of the role of the invited user.\n */\n readonly roleName: string,\n /**\n * The ID of the [`Organization`](https://clerk.com/docs/reference/backend/types/backend-organization) that the user is invited to.\n */\n readonly organizationId: string,\n /**\n * The date when the invitation was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the invitation was last updated.\n */\n readonly updatedAt: number,\n /**\n * The date when the invitation expires.\n */\n readonly expiresAt: number,\n /**\n * The URL that the user can use to accept the invitation.\n */\n readonly url: string | null,\n /**\n * The status of the invitation.\n */\n readonly status?: OrganizationInvitationStatus,\n /**\n * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API.\n */\n readonly publicMetadata: OrganizationInvitationPublicMetadata = {},\n /**\n * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}.\n */\n readonly privateMetadata: OrganizationInvitationPrivateMetadata = {},\n /**\n * Public data about the organization that the user is invited to.\n */\n readonly publicOrganizationData?: PublicOrganizationDataJSON | null,\n ) {}\n\n static fromJSON(data: OrganizationInvitationJSON) {\n const res = new OrganizationInvitation(\n data.id,\n data.email_address,\n data.role,\n data.role_name,\n data.organization_id,\n data.created_at,\n data.updated_at,\n data.expires_at,\n data.url,\n data.status,\n data.public_metadata,\n data.private_metadata,\n data.public_organization_data,\n );\n res._raw = data;\n return res;\n }\n}\n","import { Organization } from '../resources';\nimport type { OrganizationMembershipRole } from './Enums';\nimport type { OrganizationMembershipJSON, OrganizationMembershipPublicUserDataJSON } from './JSON';\n\n/**\n * The Backend `OrganizationMembership` object is similar to the [`OrganizationMembership`](https://clerk.com/docs/reference/javascript/types/organization-membership) object as it's the model around an organization membership entity and describes the relationship between users and organizations. However, the Backend `OrganizationMembership` object is different in that it's used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Organization-Memberships#operation/CreateOrganizationMembership){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class OrganizationMembership {\n private _raw: OrganizationMembershipJSON | null = null;\n\n public get raw(): OrganizationMembershipJSON | null {\n return this._raw;\n }\n\n constructor(\n /**\n * The unique identifier for the membership.\n */\n readonly id: string,\n /**\n * The role of the user.\n */\n readonly role: OrganizationMembershipRole,\n /**\n * The permissions granted to the user in the organization.\n */\n readonly permissions: string[],\n /**\n * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API.\n */\n readonly publicMetadata: OrganizationMembershipPublicMetadata = {},\n /**\n * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}.\n */\n readonly privateMetadata: OrganizationMembershipPrivateMetadata = {},\n /**\n * The date when the membership was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the membership was last updated.\n */\n readonly updatedAt: number,\n /**\n * The organization that the user is a member of.\n */\n readonly organization: Organization,\n /**\n * Public information about the user that this membership belongs to.\n */\n readonly publicUserData?: OrganizationMembershipPublicUserData | null,\n ) {}\n\n static fromJSON(data: OrganizationMembershipJSON) {\n const res = new OrganizationMembership(\n data.id,\n data.role,\n data.permissions,\n data.public_metadata,\n data.private_metadata,\n data.created_at,\n data.updated_at,\n Organization.fromJSON(data.organization),\n OrganizationMembershipPublicUserData.fromJSON(data.public_user_data),\n );\n res._raw = data;\n return res;\n }\n}\n\n/**\n * @class\n */\nexport class OrganizationMembershipPublicUserData {\n constructor(\n /**\n * The identifier of the user.\n */\n readonly identifier: string,\n /**\n * The first name of the user.\n */\n readonly firstName: string | null,\n /**\n * The last name of the user.\n */\n readonly lastName: string | null,\n /**\n * Holds the default avatar or user's uploaded profile image. Compatible with Clerk's [Image Optimization](https://clerk.com/docs/guides/development/image-optimization).\n */\n readonly imageUrl: string,\n /**\n * Whether the user has a profile picture.\n */\n readonly hasImage: boolean,\n /**\n * The ID of the user that this public data belongs to.\n */\n readonly userId: string,\n ) {}\n\n static fromJSON(data: OrganizationMembershipPublicUserDataJSON) {\n return new OrganizationMembershipPublicUserData(\n data.identifier,\n data.first_name,\n data.last_name,\n data.image_url,\n data.has_image,\n data.user_id,\n );\n }\n}\n","import type { DomainsEnrollmentModes } from './Enums';\nimport type { OrganizationSettingsJSON } from './JSON';\n\nexport class OrganizationSettings {\n constructor(\n readonly enabled: boolean,\n readonly maxAllowedMemberships: number,\n readonly maxAllowedRoles: number,\n readonly maxAllowedPermissions: number,\n readonly creatorRole: string,\n readonly adminDeleteEnabled: boolean,\n readonly domainsEnabled: boolean,\n readonly slugDisabled: boolean,\n readonly domainsEnrollmentModes: Array<DomainsEnrollmentModes>,\n readonly domainsDefaultRole: string,\n ) {}\n\n static fromJSON(data: OrganizationSettingsJSON): OrganizationSettings {\n return new OrganizationSettings(\n data.enabled,\n data.max_allowed_memberships,\n data.max_allowed_roles,\n data.max_allowed_permissions,\n data.creator_role,\n data.admin_delete_enabled,\n data.domains_enabled,\n data.slug_disabled,\n data.domains_enrollment_modes,\n data.domains_default_role,\n );\n }\n}\n","import { IdentificationLink } from './IdentificationLink';\nimport type { PhoneNumberJSON } from './JSON';\nimport { Verification } from './Verification';\n\n/**\n * The Backend `PhoneNumber` object describes a phone number. Phone numbers can be used as a proof of identification for users, or simply as a means of contacting users.\n *\n * Phone numbers must be **verified** to ensure that they can be assigned to their rightful owners. The `PhoneNumber` object holds all the necessary state around the verification process.\n *\n * Finally, phone numbers can be used as part of [multi-factor authentication](https://clerk.com/docs/guides/configure/auth-strategies/sign-up-sign-in-options#multi-factor-authentication). During sign in, users can opt in to an extra verification step where they will receive an SMS message with a one-time code. This code must be entered to complete the sign in process.\n */\nexport class PhoneNumber {\n constructor(\n /**\n * The unique identifier for this phone number.\n */\n readonly id: string,\n /**\n * The value of this phone number, in [E.164 format](https://en.wikipedia.org/wiki/E.164).\n */\n readonly phoneNumber: string,\n /**\n * Set to `true` if this phone number is reserved for multi-factor authentication (2FA). Set to `false` otherwise.\n */\n readonly reservedForSecondFactor: boolean,\n /**\n * Set to `true` if this phone number is the default second factor. Set to `false` otherwise. A user must have exactly one default second factor, if multi-factor authentication (2FA) is enabled.\n */\n readonly defaultSecondFactor: boolean,\n /**\n * An object holding information on the verification of this phone number.\n */\n readonly verification: Verification | null,\n /**\n * An object containing information about any other identification that might be linked to this phone number.\n */\n readonly linkedTo: IdentificationLink[],\n ) {}\n\n static fromJSON(data: PhoneNumberJSON): PhoneNumber {\n return new PhoneNumber(\n data.id,\n data.phone_number,\n data.reserved_for_second_factor,\n data.default_second_factor,\n data.verification && Verification.fromJSON(data.verification),\n data.linked_to.map(link => IdentificationLink.fromJSON(link)),\n );\n }\n}\n","import type { ProxyCheckJSON } from './JSON';\n\nexport class ProxyCheck {\n constructor(\n readonly id: string,\n readonly domainId: string,\n readonly lastRunAt: number | null,\n readonly proxyUrl: string,\n readonly successful: boolean,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: ProxyCheckJSON): ProxyCheck {\n return new ProxyCheck(\n data.id,\n data.domain_id,\n data.last_run_at,\n data.proxy_url,\n data.successful,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { RedirectUrlJSON } from './JSON';\n\n/**\n * Redirect URLs are whitelisted URLs that facilitate secure authentication flows in native applications (e.g. React Native, Expo). In these contexts, Clerk ensures that security-critical nonces are passed only to the whitelisted URLs.\n\nThe Backend `RedirectUrl` object represents a redirect URL in your application. This object is used in the Backend API.\n */\nexport class RedirectUrl {\n constructor(\n /**\n * The unique identifier for the redirect URL.\n */\n readonly id: string,\n /**\n * The full URL value prefixed with `https://` or a custom scheme.\n * @example https://my-app.com/oauth-callback\n * @example my-app://oauth-callback\n */\n readonly url: string,\n /**\n * The date when the redirect URL was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the redirect URL was last updated.\n */\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: RedirectUrlJSON): RedirectUrl {\n return new RedirectUrl(data.id, data.url, data.created_at, data.updated_at);\n }\n}\n","import type { AttributeMappingJSON, SamlConnectionJSON } from './JSON';\n\n/**\n * The Backend `SamlConnection` object holds information about a SAML connection for an organization.\n */\nexport class SamlConnection {\n constructor(\n /**\n * The unique identifier for the connection.\n */\n readonly id: string,\n /**\n * The name to use as a label for the connection.\n */\n readonly name: string,\n /**\n * The domain of your organization. Sign in flows using an email with this domain will use the connection.\n */\n readonly domain: string,\n /**\n * The organization ID of the organization.\n */\n readonly organizationId: string | null,\n /**\n * The Entity ID as provided by the Identity Provider (IdP).\n */\n readonly idpEntityId: string | null,\n /**\n * The Single-Sign On URL as provided by the Identity Provider (IdP).\n */\n readonly idpSsoUrl: string | null,\n /**\n * The X.509 certificate as provided by the Identity Provider (IdP).\n */\n readonly idpCertificate: string | null,\n /**\n * The URL which serves the Identity Provider (IdP) metadata. If present, it takes priority over the corresponding individual properties.\n */\n readonly idpMetadataUrl: string | null,\n /**\n * The XML content of the Identity Provider (IdP) metadata file. If present, it takes priority over the corresponding individual properties.\n */\n readonly idpMetadata: string | null,\n /**\n * The Assertion Consumer Service (ACS) URL of the connection.\n */\n readonly acsUrl: string,\n /**\n * The Entity ID as provided by the Service Provider (Clerk).\n */\n readonly spEntityId: string,\n /**\n * The metadata URL as provided by the Service Provider (Clerk).\n */\n readonly spMetadataUrl: string,\n /**\n * Indicates whether the connection is active or not.\n */\n readonly active: boolean,\n /**\n * The Identity Provider (IdP) of the connection.\n */\n readonly provider: string,\n /**\n * The number of users associated with the connection.\n */\n readonly userCount: number,\n /**\n * Indicates whether the connection syncs user attributes between the Service Provider (SP) and Identity Provider (IdP) or not.\n */\n readonly syncUserAttributes: boolean,\n /**\n * Indicates whether users with an email address subdomain are allowed to use this connection in order to authenticate or not.\n */\n readonly allowSubdomains: boolean,\n /**\n * Indicates whether the connection allows Identity Provider (IdP) initiated flows or not.\n */\n readonly allowIdpInitiated: boolean,\n /**\n * The date when the connection was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the SAML connection was last updated.\n */\n readonly updatedAt: number,\n /**\n * Defines the attribute name mapping between the Identity Provider (IdP) and Clerk's [`User`](https://clerk.com/docs/reference/javascript/user) properties.\n */\n readonly attributeMapping: AttributeMapping,\n ) {}\n static fromJSON(data: SamlConnectionJSON): SamlConnection {\n return new SamlConnection(\n data.id,\n data.name,\n data.domain,\n data.organization_id,\n data.idp_entity_id,\n data.idp_sso_url,\n data.idp_certificate,\n data.idp_metadata_url,\n data.idp_metadata,\n data.acs_url,\n data.sp_entity_id,\n data.sp_metadata_url,\n data.active,\n data.provider,\n data.user_count,\n data.sync_user_attributes,\n data.allow_subdomains,\n data.allow_idp_initiated,\n data.created_at,\n data.updated_at,\n data.attribute_mapping && AttributeMapping.fromJSON(data.attribute_mapping),\n );\n }\n}\n\nclass AttributeMapping {\n constructor(\n /**\n * The user ID attribute name.\n */\n readonly userId: string,\n /**\n * The email address attribute name.\n */\n readonly emailAddress: string,\n /**\n * The first name attribute name.\n */\n readonly firstName: string,\n /**\n * The last name attribute name.\n */\n readonly lastName: string,\n ) {}\n\n static fromJSON(data: AttributeMappingJSON): AttributeMapping {\n return new AttributeMapping(data.user_id, data.email_address, data.first_name, data.last_name);\n }\n}\n","import type { SignInTokenJSON } from './JSON';\n\nexport class SignInToken {\n constructor(\n readonly id: string,\n readonly userId: string,\n readonly token: string,\n readonly status: string,\n readonly url: string,\n readonly createdAt: number,\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: SignInTokenJSON): SignInToken {\n return new SignInToken(data.id, data.user_id, data.token, data.status, data.url, data.created_at, data.updated_at);\n }\n}\n","import type { SignUpStatus } from '@clerk/shared/types';\n\nimport type { SignUpVerificationNextAction } from './Enums';\nimport type { SignUpJSON, SignUpVerificationJSON, SignUpVerificationsJSON } from './JSON';\n\nexport class SignUpAttemptVerification {\n constructor(\n readonly nextAction: SignUpVerificationNextAction,\n readonly supportedStrategies: string[],\n ) {}\n\n static fromJSON(data: SignUpVerificationJSON): SignUpAttemptVerification {\n return new SignUpAttemptVerification(data.next_action, data.supported_strategies);\n }\n}\n\nexport class SignUpAttemptVerifications {\n constructor(\n readonly emailAddress: SignUpAttemptVerification | null,\n readonly phoneNumber: SignUpAttemptVerification | null,\n readonly web3Wallet: SignUpAttemptVerification | null,\n readonly externalAccount: object | null,\n ) {}\n\n static fromJSON(data: SignUpVerificationsJSON): SignUpAttemptVerifications {\n return new SignUpAttemptVerifications(\n data.email_address && SignUpAttemptVerification.fromJSON(data.email_address),\n data.phone_number && SignUpAttemptVerification.fromJSON(data.phone_number),\n data.web3_wallet && SignUpAttemptVerification.fromJSON(data.web3_wallet),\n data.external_account,\n );\n }\n}\n\nexport class SignUpAttempt {\n constructor(\n readonly id: string,\n readonly status: SignUpStatus,\n readonly requiredFields: string[],\n readonly optionalFields: string[],\n readonly missingFields: string[],\n readonly unverifiedFields: string[],\n readonly verifications: SignUpAttemptVerifications | null,\n readonly username: string | null,\n readonly emailAddress: string | null,\n readonly phoneNumber: string | null,\n readonly web3Wallet: string | null,\n readonly passwordEnabled: boolean,\n readonly firstName: string | null,\n readonly lastName: string | null,\n readonly customAction: boolean,\n readonly externalId: string | null,\n readonly createdSessionId: string | null,\n readonly createdUserId: string | null,\n readonly abandonAt: number | null,\n readonly legalAcceptedAt: number | null,\n readonly publicMetadata?: Record<string, unknown> | null,\n readonly unsafeMetadata?: Record<string, unknown> | null,\n ) {}\n\n static fromJSON(data: SignUpJSON): SignUpAttempt {\n return new SignUpAttempt(\n data.id,\n data.status,\n data.required_fields,\n data.optional_fields,\n data.missing_fields,\n data.unverified_fields,\n data.verifications ? SignUpAttemptVerifications.fromJSON(data.verifications) : null,\n data.username,\n data.email_address,\n data.phone_number,\n data.web3_wallet,\n data.password_enabled,\n data.first_name,\n data.last_name,\n data.custom_action,\n data.external_id,\n data.created_session_id,\n data.created_user_id,\n data.abandon_at,\n data.legal_accepted_at,\n data.public_metadata,\n data.unsafe_metadata,\n );\n }\n}\n","import type { SMSMessageJSON } from './JSON';\n\nexport class SMSMessage {\n constructor(\n readonly id: string,\n readonly fromPhoneNumber: string,\n readonly toPhoneNumber: string,\n readonly message: string,\n readonly status: string,\n readonly phoneNumberId: string | null,\n readonly data?: Record<string, any> | null,\n ) {}\n\n static fromJSON(data: SMSMessageJSON): SMSMessage {\n return new SMSMessage(\n data.id,\n data.from_phone_number,\n data.to_phone_number,\n data.message,\n data.status,\n data.phone_number_id,\n data.data,\n );\n }\n}\n","import type { TokenJSON } from './JSON';\n\nexport class Token {\n constructor(readonly jwt: string) {}\n\n static fromJSON(data: TokenJSON): Token {\n return new Token(data.jwt);\n }\n}\n","import type { Web3WalletJSON } from './JSON';\nimport { Verification } from './Verification';\n\n/**\n * The Backend `Web3Wallet` object describes a Web3 wallet address. The address can be used as a proof of identification for users.\n *\n * Web3 addresses must be verified to ensure that they can be assigned to their rightful owners. The verification is completed via Web3 wallet browser extensions, such as [Metamask](https://metamask.io/), [Coinbase Wallet](https://www.coinbase.com/wallet), and [OKX Wallet](https://www.okx.com/help/section/faq-web3-wallet). The `Web3Wallet3` object holds all the necessary state around the verification process.\n */\nexport class Web3Wallet {\n constructor(\n /**\n * The unique ID for the Web3 wallet.\n */\n readonly id: string,\n /**\n * The Web3 wallet address, made up of 0x + 40 hexadecimal characters.\n */\n readonly web3Wallet: string,\n /**\n * An object holding information on the verification of this Web3 wallet.\n */\n readonly verification: Verification | null,\n ) {}\n\n static fromJSON(data: Web3WalletJSON): Web3Wallet {\n return new Web3Wallet(data.id, data.web3_wallet, data.verification && Verification.fromJSON(data.verification));\n }\n}\n","import { EmailAddress } from './EmailAddress';\nimport { ExternalAccount } from './ExternalAccount';\nimport type { ExternalAccountJSON, UserJSON } from './JSON';\nimport { PhoneNumber } from './PhoneNumber';\nimport { Web3Wallet } from './Web3Wallet';\n\n/**\n * The Backend `User` object is similar to the `User` object as it holds information about a user of your application, such as their unique identifier, name, email addresses, phone numbers, and more. However, the Backend `User` object is different from the `User` object in that it is used in the [Backend API](https://clerk.com/docs/reference/backend-api/tag/Users#operation/GetUser){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class User {\n private _raw: UserJSON | null = null;\n\n public get raw(): UserJSON | null {\n return this._raw;\n }\n\n constructor(\n /**\n * The unique identifier for the user.\n */\n readonly id: string,\n /**\n * A boolean indicating whether the user has a password on their account.\n */\n readonly passwordEnabled: boolean,\n /**\n * A boolean indicating whether the user has enabled TOTP by generating a TOTP secret and verifying it via an authenticator app.\n */\n readonly totpEnabled: boolean,\n /**\n * A boolean indicating whether the user has enabled Backup codes.\n */\n readonly backupCodeEnabled: boolean,\n /**\n * A boolean indicating whether the user has enabled two-factor authentication.\n */\n readonly twoFactorEnabled: boolean,\n /**\n * A boolean indicating whether the user is banned or not.\n */\n readonly banned: boolean,\n /**\n * A boolean indicating whether the user is banned or not.\n */\n readonly locked: boolean,\n /**\n * The date when the user was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the user was last updated.\n */\n readonly updatedAt: number,\n /**\n * The URL of the user's profile image.\n */\n readonly imageUrl: string,\n /**\n * A getter boolean to check if the user has uploaded an image or one was copied from OAuth. Returns `false` if Clerk is displaying an avatar for the user.\n */\n readonly hasImage: boolean,\n /**\n * The ID for the `EmailAddress` that the user has set as primary.\n */\n readonly primaryEmailAddressId: string | null,\n /**\n * The ID for the `PhoneNumber` that the user has set as primary.\n */\n readonly primaryPhoneNumberId: string | null,\n /**\n * The ID for the [`Web3Wallet`](https://clerk.com/docs/reference/backend/types/backend-web3-wallet) that the user signed up with.\n */\n readonly primaryWeb3WalletId: string | null,\n /**\n * The date when the user last signed in. May be empty if the user has never signed in.\n */\n readonly lastSignInAt: number | null,\n /**\n * The ID of the user as used in your external systems. Must be unique across your instance.\n */\n readonly externalId: string | null,\n /**\n * The user's username.\n */\n readonly username: string | null,\n /**\n * The user's first name.\n */\n readonly firstName: string | null,\n /**\n * The user's last name.\n */\n readonly lastName: string | null,\n /**\n * Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} and can be set only from the Backend API.\n */\n readonly publicMetadata: UserPublicMetadata = {},\n /**\n * Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}.\n */\n readonly privateMetadata: UserPrivateMetadata = {},\n /**\n * Metadata that can be read and set from the Frontend API. It's considered unsafe because it can be modified from the frontend.\n */\n readonly unsafeMetadata: UserUnsafeMetadata = {},\n /**\n * An array of all the `EmailAddress` objects associated with the user. Includes the primary.\n */\n readonly emailAddresses: EmailAddress[] = [],\n /**\n * An array of all the `PhoneNumber` objects associated with the user. Includes the primary.\n */\n readonly phoneNumbers: PhoneNumber[] = [],\n /**\n * An array of all the `Web3Wallet` objects associated with the user. Includes the primary.\n */\n readonly web3Wallets: Web3Wallet[] = [],\n /**\n * An array of all the `ExternalAccount` objects associated with the user via OAuth. **Note**: This includes both verified & unverified external accounts.\n */\n readonly externalAccounts: ExternalAccount[] = [],\n /**\n * Date when the user was last active.\n */\n readonly lastActiveAt: number | null,\n /**\n * A boolean indicating whether the organization creation is enabled for the user or not.\n */\n readonly createOrganizationEnabled: boolean,\n /**\n * An integer indicating the number of organizations that can be created by the user. If the value is `0`, then the user can create unlimited organizations. Default is `null`.\n */\n readonly createOrganizationsLimit: number | null = null,\n /**\n * A boolean indicating whether the user can delete their own account.\n */\n readonly deleteSelfEnabled: boolean,\n /**\n * The unix timestamp of when the user accepted the legal requirements. `null` if [**Require express consent to legal documents**](https://clerk.com/docs/guides/secure/legal-compliance) is not enabled.\n */\n readonly legalAcceptedAt: number | null,\n\n /**\n * The locale of the user in BCP-47 format.\n */\n readonly locale: string | null,\n ) {}\n\n static fromJSON(data: UserJSON): User {\n const res = new User(\n data.id,\n data.password_enabled,\n data.totp_enabled,\n data.backup_code_enabled,\n data.two_factor_enabled,\n data.banned,\n data.locked,\n data.created_at,\n data.updated_at,\n data.image_url,\n data.has_image,\n data.primary_email_address_id,\n data.primary_phone_number_id,\n data.primary_web3_wallet_id,\n data.last_sign_in_at,\n data.external_id,\n data.username,\n data.first_name,\n data.last_name,\n data.public_metadata,\n data.private_metadata,\n data.unsafe_metadata,\n (data.email_addresses || []).map(x => EmailAddress.fromJSON(x)),\n (data.phone_numbers || []).map(x => PhoneNumber.fromJSON(x)),\n (data.web3_wallets || []).map(x => Web3Wallet.fromJSON(x)),\n (data.external_accounts || []).map((x: ExternalAccountJSON) => ExternalAccount.fromJSON(x)),\n data.last_active_at,\n data.create_organization_enabled,\n data.create_organizations_limit,\n data.delete_self_enabled,\n data.legal_accepted_at,\n data.locale,\n );\n res._raw = data;\n return res;\n }\n\n /**\n * The primary email address of the user.\n */\n get primaryEmailAddress() {\n return this.emailAddresses.find(({ id }) => id === this.primaryEmailAddressId) ?? null;\n }\n\n /**\n * The primary phone number of the user.\n */\n get primaryPhoneNumber() {\n return this.phoneNumbers.find(({ id }) => id === this.primaryPhoneNumberId) ?? null;\n }\n\n /**\n * The primary web3 wallet of the user.\n */\n get primaryWeb3Wallet() {\n return this.web3Wallets.find(({ id }) => id === this.primaryWeb3WalletId) ?? null;\n }\n\n /**\n * The full name of the user.\n */\n get fullName() {\n return [this.firstName, this.lastName].join(' ').trim() || null;\n }\n}\n","import type { WaitlistEntryStatus } from './Enums';\nimport { Invitation } from './Invitation';\nimport type { WaitlistEntryJSON } from './JSON';\n\nexport class WaitlistEntry {\n constructor(\n readonly id: string,\n readonly emailAddress: string,\n readonly status: WaitlistEntryStatus,\n readonly invitation: Invitation | null,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly isLocked?: boolean,\n ) {}\n\n static fromJSON(data: WaitlistEntryJSON): WaitlistEntry {\n return new WaitlistEntry(\n data.id,\n data.email_address,\n data.status,\n data.invitation && Invitation.fromJSON(data.invitation),\n data.created_at,\n data.updated_at,\n data.is_locked,\n );\n }\n}\n","import {\n ActorToken,\n AllowlistIdentifier,\n APIKey,\n BlocklistIdentifier,\n Client,\n Cookies,\n DeletedObject,\n Domain,\n Email,\n EmailAddress,\n IdPOAuthAccessToken,\n Instance,\n InstanceRestrictions,\n InstanceSettings,\n Invitation,\n JwtTemplate,\n M2MToken,\n Machine,\n MachineScope,\n MachineSecretKey,\n OauthAccessToken,\n OAuthApplication,\n Organization,\n OrganizationInvitation,\n OrganizationMembership,\n OrganizationSettings,\n PhoneNumber,\n ProxyCheck,\n RedirectUrl,\n SamlConnection,\n Session,\n SignInToken,\n SignUpAttempt,\n SMSMessage,\n Token,\n User,\n} from '.';\nimport { AccountlessApplication } from './AccountlessApplication';\nimport { BillingPlan } from './CommercePlan';\nimport { BillingSubscription } from './CommerceSubscription';\nimport { BillingSubscriptionItem } from './CommerceSubscriptionItem';\nimport { Feature } from './Feature';\nimport type { PaginatedResponseJSON } from './JSON';\nimport { ObjectType } from './JSON';\nimport { WaitlistEntry } from './WaitlistEntry';\n\ntype ResourceResponse<T> = {\n /**\n * An array that contains the fetched data.\n */\n data: T;\n};\n\n/**\n * An interface that describes the response of a method that returns a paginated list of resources.\n *\n * If the promise resolves, you will get back the [properties](#properties) listed below. `data` will be an array of the resource type you requested. You can use the `totalCount` property to determine how many total items exist remotely.\n *\n * Some methods that return this type allow pagination with the `limit` and `offset` parameters, in which case the first 10 items will be returned by default. For methods such as [`getAllowlistIdentifierList()`](https://clerk.com/docs/reference/backend/allowlist/get-allowlist-identifier-list), which do not take a `limit` or `offset`, all items will be returned.\n *\n * If the promise is rejected, you will receive a `ClerkAPIResponseError` or network error.\n *\n * @interface\n */\nexport type PaginatedResourceResponse<T> = ResourceResponse<T> & {\n /**\n * The total count of data that exist remotely.\n */\n totalCount: number;\n};\n\nexport function deserialize<U = any>(payload: unknown): PaginatedResourceResponse<U> | ResourceResponse<U> {\n let data, totalCount: number | undefined;\n\n if (Array.isArray(payload)) {\n const data = payload.map(item => jsonToObject(item)) as U;\n return { data };\n } else if (isPaginated(payload)) {\n data = payload.data.map(item => jsonToObject(item)) as U;\n totalCount = payload.total_count;\n\n return { data, totalCount };\n } else {\n return { data: jsonToObject(payload) };\n }\n}\n\nfunction isPaginated(payload: unknown): payload is PaginatedResponseJSON {\n if (!payload || typeof payload !== 'object' || !('data' in payload)) {\n return false;\n }\n\n return Array.isArray(payload.data) && payload.data !== undefined;\n}\n\nfunction getCount(item: PaginatedResponseJSON) {\n return item.total_count;\n}\n\n// TODO: Revise response deserialization\nfunction jsonToObject(item: any): any {\n // Special case: DeletedObject\n // TODO: Improve this check\n if (typeof item !== 'string' && 'object' in item && 'deleted' in item) {\n return DeletedObject.fromJSON(item);\n }\n\n switch (item.object) {\n case ObjectType.AccountlessApplication:\n return AccountlessApplication.fromJSON(item);\n case ObjectType.ActorToken:\n return ActorToken.fromJSON(item);\n case ObjectType.AllowlistIdentifier:\n return AllowlistIdentifier.fromJSON(item);\n case ObjectType.ApiKey:\n return APIKey.fromJSON(item);\n case ObjectType.BlocklistIdentifier:\n return BlocklistIdentifier.fromJSON(item);\n case ObjectType.Client:\n return Client.fromJSON(item);\n case ObjectType.Cookies:\n return Cookies.fromJSON(item);\n case ObjectType.Domain:\n return Domain.fromJSON(item);\n case ObjectType.EmailAddress:\n return EmailAddress.fromJSON(item);\n case ObjectType.Email:\n return Email.fromJSON(item);\n case ObjectType.IdpOAuthAccessToken:\n return IdPOAuthAccessToken.fromJSON(item);\n case ObjectType.Instance:\n return Instance.fromJSON(item);\n case ObjectType.InstanceRestrictions:\n return InstanceRestrictions.fromJSON(item);\n case ObjectType.InstanceSettings:\n return InstanceSettings.fromJSON(item);\n case ObjectType.Invitation:\n return Invitation.fromJSON(item);\n case ObjectType.JwtTemplate:\n return JwtTemplate.fromJSON(item);\n case ObjectType.Machine:\n return Machine.fromJSON(item);\n case ObjectType.MachineScope:\n return MachineScope.fromJSON(item);\n case ObjectType.MachineSecretKey:\n return MachineSecretKey.fromJSON(item);\n case ObjectType.M2MToken:\n return M2MToken.fromJSON(item);\n case ObjectType.OauthAccessToken:\n return OauthAccessToken.fromJSON(item);\n case ObjectType.OAuthApplication:\n return OAuthApplication.fromJSON(item);\n case ObjectType.Organization:\n return Organization.fromJSON(item);\n case ObjectType.OrganizationInvitation:\n return OrganizationInvitation.fromJSON(item);\n case ObjectType.OrganizationMembership:\n return OrganizationMembership.fromJSON(item);\n case ObjectType.OrganizationSettings:\n return OrganizationSettings.fromJSON(item);\n case ObjectType.PhoneNumber:\n return PhoneNumber.fromJSON(item);\n case ObjectType.ProxyCheck:\n return ProxyCheck.fromJSON(item);\n case ObjectType.RedirectUrl:\n return RedirectUrl.fromJSON(item);\n case ObjectType.SamlConnection:\n return SamlConnection.fromJSON(item);\n case ObjectType.SignInToken:\n return SignInToken.fromJSON(item);\n case ObjectType.SignUpAttempt:\n return SignUpAttempt.fromJSON(item);\n case ObjectType.Session:\n return Session.fromJSON(item);\n case ObjectType.SmsMessage:\n return SMSMessage.fromJSON(item);\n case ObjectType.Token:\n return Token.fromJSON(item);\n case ObjectType.TotalCount:\n return getCount(item);\n case ObjectType.User:\n return User.fromJSON(item);\n case ObjectType.WaitlistEntry:\n return WaitlistEntry.fromJSON(item);\n case ObjectType.BillingPlan:\n return BillingPlan.fromJSON(item);\n case ObjectType.BillingSubscription:\n return BillingSubscription.fromJSON(item);\n case ObjectType.BillingSubscriptionItem:\n return BillingSubscriptionItem.fromJSON(item);\n case ObjectType.Feature:\n return Feature.fromJSON(item);\n default:\n return item;\n }\n}\n","import {\n AccountlessApplicationAPI,\n ActorTokenAPI,\n AllowlistIdentifierAPI,\n APIKeysAPI,\n BetaFeaturesAPI,\n BlocklistIdentifierAPI,\n ClientAPI,\n DomainAPI,\n EmailAddressAPI,\n IdPOAuthAccessTokenApi,\n InstanceAPI,\n InvitationAPI,\n JwksAPI,\n JwtTemplatesApi,\n M2MTokenApi,\n MachineApi,\n OAuthApplicationsApi,\n OrganizationAPI,\n PhoneNumberAPI,\n ProxyCheckAPI,\n RedirectUrlAPI,\n SamlConnectionAPI,\n SessionAPI,\n SignInTokenAPI,\n SignUpAPI,\n TestingTokenAPI,\n UserAPI,\n WaitlistEntryAPI,\n WebhookAPI,\n} from './endpoints';\nimport { BillingAPI } from './endpoints/BillingApi';\nimport { buildRequest } from './request';\n\nexport type CreateBackendApiOptions = Parameters<typeof buildRequest>[0];\n\nexport type ApiClient = ReturnType<typeof createBackendApiClient>;\n\nexport function createBackendApiClient(options: CreateBackendApiOptions) {\n const request = buildRequest(options);\n\n return {\n __experimental_accountlessApplications: new AccountlessApplicationAPI(\n buildRequest({ ...options, requireSecretKey: false }),\n ),\n actorTokens: new ActorTokenAPI(request),\n allowlistIdentifiers: new AllowlistIdentifierAPI(request),\n apiKeys: new APIKeysAPI(\n buildRequest({\n ...options,\n skipApiVersionInUrl: true,\n }),\n ),\n betaFeatures: new BetaFeaturesAPI(request),\n blocklistIdentifiers: new BlocklistIdentifierAPI(request),\n /**\n * @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.\n */\n billing: new BillingAPI(request),\n clients: new ClientAPI(request),\n domains: new DomainAPI(request),\n emailAddresses: new EmailAddressAPI(request),\n idPOAuthAccessToken: new IdPOAuthAccessTokenApi(\n buildRequest({\n ...options,\n skipApiVersionInUrl: true,\n }),\n ),\n instance: new InstanceAPI(request),\n invitations: new InvitationAPI(request),\n jwks: new JwksAPI(request),\n jwtTemplates: new JwtTemplatesApi(request),\n machines: new MachineApi(request),\n m2m: new M2MTokenApi(\n buildRequest({\n ...options,\n skipApiVersionInUrl: true,\n requireSecretKey: false,\n useMachineSecretKey: true,\n }),\n ),\n oauthApplications: new OAuthApplicationsApi(request),\n organizations: new OrganizationAPI(request),\n phoneNumbers: new PhoneNumberAPI(request),\n proxyChecks: new ProxyCheckAPI(request),\n redirectUrls: new RedirectUrlAPI(request),\n samlConnections: new SamlConnectionAPI(request),\n sessions: new SessionAPI(request),\n signInTokens: new SignInTokenAPI(request),\n signUps: new SignUpAPI(request),\n testingTokens: new TestingTokenAPI(request),\n users: new UserAPI(request),\n waitlistEntries: new WaitlistEntryAPI(request),\n webhooks: new WebhookAPI(request),\n };\n}\n","import type { AuthenticateRequestOptions } from '../tokens/types';\nimport type { MachineTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\n\nexport const M2M_TOKEN_PREFIX = 'mt_';\nexport const OAUTH_TOKEN_PREFIX = 'oat_';\nexport const API_KEY_PREFIX = 'ak_';\n\nconst MACHINE_TOKEN_PREFIXES = [M2M_TOKEN_PREFIX, OAUTH_TOKEN_PREFIX, API_KEY_PREFIX] as const;\n\n/**\n * Checks if a token is a machine token by looking at its prefix.\n *\n * @remarks\n * In the future, this will support custom prefixes that can be prepended to the base prefixes\n * (e.g. \"org_a_m2m_\", \"org_a_oauth_access_\", \"org_a_api_key_\")\n *\n * @param token - The token string to check\n * @returns true if the token starts with a recognized machine token prefix\n */\nexport function isMachineTokenByPrefix(token: string): boolean {\n return MACHINE_TOKEN_PREFIXES.some(prefix => token.startsWith(prefix));\n}\n\n/**\n * Gets the specific type of machine token based on its prefix.\n *\n * @remarks\n * In the future, this will support custom prefixes that can be prepended to the base prefixes\n * (e.g. \"org_a_m2m_\", \"org_a_oauth_access_\", \"org_a_api_key_\")\n *\n * @param token - The token string to check\n * @returns The specific MachineTokenType\n * @throws Error if the token doesn't match any known machine token prefix\n */\nexport function getMachineTokenType(token: string): MachineTokenType {\n if (token.startsWith(M2M_TOKEN_PREFIX)) {\n return TokenType.M2MToken;\n }\n\n if (token.startsWith(OAUTH_TOKEN_PREFIX)) {\n return TokenType.OAuthToken;\n }\n\n if (token.startsWith(API_KEY_PREFIX)) {\n return TokenType.ApiKey;\n }\n\n throw new Error('Unknown machine token type');\n}\n\n/**\n * Check if a token type is accepted given a requested token type or list of token types.\n *\n * @param tokenType - The token type to check (can be null if the token is invalid)\n * @param acceptsToken - The requested token type or list of token types\n * @returns true if the token type is accepted\n */\nexport const isTokenTypeAccepted = (\n tokenType: TokenType | null,\n acceptsToken: NonNullable<AuthenticateRequestOptions['acceptsToken']>,\n): boolean => {\n if (!tokenType) {\n return false;\n }\n\n if (acceptsToken === 'any') {\n return true;\n }\n\n const tokenTypes = Array.isArray(acceptsToken) ? acceptsToken : [acceptsToken];\n return tokenTypes.includes(tokenType);\n};\n\n/**\n * Checks if a token type string is a machine token type (api_key, m2m_token, or oauth_token).\n *\n * @param type - The token type string to check\n * @returns true if the type is a machine token type\n */\nexport function isMachineTokenType(type: string): type is MachineTokenType {\n return type === TokenType.ApiKey || type === TokenType.M2MToken || type === TokenType.OAuthToken;\n}\n","import type { JwtPayload, PendingSessionOptions } from '@clerk/shared/types';\n\nimport { constants } from '../constants';\nimport type { TokenVerificationErrorReason } from '../errors';\nimport type { AuthenticateContext } from './authenticateContext';\nimport type {\n AuthenticatedMachineObject,\n InvalidTokenAuthObject,\n SignedInAuthObject,\n SignedOutAuthObject,\n UnauthenticatedMachineObject,\n} from './authObjects';\nimport {\n authenticatedMachineObject,\n invalidTokenAuthObject,\n signedInAuthObject,\n signedOutAuthObject,\n unauthenticatedMachineObject,\n} from './authObjects';\nimport type { MachineTokenType, SessionTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\nimport type { MachineAuthType } from './types';\n\nexport const AuthStatus = {\n SignedIn: 'signed-in',\n SignedOut: 'signed-out',\n Handshake: 'handshake',\n} as const;\n\nexport type AuthStatus = (typeof AuthStatus)[keyof typeof AuthStatus];\n\ntype ToAuth<T extends TokenType | null, Authenticated extends boolean> = T extends null\n ? () => InvalidTokenAuthObject\n : T extends SessionTokenType\n ? Authenticated extends true\n ? (opts?: PendingSessionOptions) => SignedInAuthObject\n : () => SignedOutAuthObject\n : Authenticated extends true\n ? () => AuthenticatedMachineObject<Exclude<T, SessionTokenType | null>>\n : () => UnauthenticatedMachineObject<Exclude<T, SessionTokenType | null>>;\n\nexport type AuthenticatedState<T extends TokenType = SessionTokenType> = {\n status: typeof AuthStatus.SignedIn;\n reason: null;\n message: null;\n proxyUrl?: string;\n publishableKey: string;\n isSatellite: boolean;\n domain: string;\n signInUrl: string;\n signUpUrl: string;\n afterSignInUrl: string;\n afterSignUpUrl: string;\n /**\n * @deprecated Use `isAuthenticated` instead.\n */\n isSignedIn: true;\n isAuthenticated: true;\n headers: Headers;\n token: string;\n tokenType: T;\n toAuth: ToAuth<T, true>;\n};\n\nexport type UnauthenticatedState<T extends TokenType | null = SessionTokenType> = {\n status: typeof AuthStatus.SignedOut;\n reason: AuthReason;\n message: string;\n proxyUrl?: string;\n publishableKey: string;\n isSatellite: boolean;\n domain: string;\n signInUrl: string;\n signUpUrl: string;\n afterSignInUrl: string;\n afterSignUpUrl: string;\n /**\n * @deprecated Use `isAuthenticated` instead.\n */\n isSignedIn: false;\n isAuthenticated: false;\n tokenType: T;\n headers: Headers;\n token: null;\n toAuth: ToAuth<T, false>;\n};\n\nexport type HandshakeState = Omit<UnauthenticatedState<SessionTokenType>, 'status' | 'toAuth' | 'tokenType'> & {\n tokenType: SessionTokenType;\n status: typeof AuthStatus.Handshake;\n headers: Headers;\n toAuth: () => null;\n};\n\n/**\n * @deprecated Use AuthenticatedState instead\n */\nexport type SignedInState = AuthenticatedState<SessionTokenType>;\n\n/**\n * @deprecated Use UnauthenticatedState instead\n */\nexport type SignedOutState = UnauthenticatedState<SessionTokenType>;\n\nexport const AuthErrorReason = {\n ClientUATWithoutSessionToken: 'client-uat-but-no-session-token',\n DevBrowserMissing: 'dev-browser-missing',\n DevBrowserSync: 'dev-browser-sync',\n PrimaryRespondsToSyncing: 'primary-responds-to-syncing',\n PrimaryDomainCrossOriginSync: 'primary-domain-cross-origin-sync',\n SatelliteCookieNeedsSyncing: 'satellite-needs-syncing',\n SessionTokenAndUATMissing: 'session-token-and-uat-missing',\n SessionTokenMissing: 'session-token-missing',\n SessionTokenExpired: 'session-token-expired',\n SessionTokenIATBeforeClientUAT: 'session-token-iat-before-client-uat',\n SessionTokenNBF: 'session-token-nbf',\n SessionTokenIatInTheFuture: 'session-token-iat-in-the-future',\n SessionTokenWithoutClientUAT: 'session-token-but-no-client-uat',\n ActiveOrganizationMismatch: 'active-organization-mismatch',\n TokenTypeMismatch: 'token-type-mismatch',\n UnexpectedError: 'unexpected-error',\n} as const;\n\nexport type AuthErrorReason = (typeof AuthErrorReason)[keyof typeof AuthErrorReason];\n\nexport type AuthReason = AuthErrorReason | TokenVerificationErrorReason;\n\nexport type RequestState<T extends TokenType | null = SessionTokenType> =\n | AuthenticatedState<T extends null ? never : T>\n | UnauthenticatedState<T>\n | (T extends SessionTokenType ? HandshakeState : never);\n\ntype BaseSignedInParams = {\n authenticateContext: AuthenticateContext;\n headers?: Headers;\n token: string;\n tokenType: TokenType;\n};\n\ntype SignedInParams =\n | (BaseSignedInParams & { tokenType: SessionTokenType; sessionClaims: JwtPayload })\n | (BaseSignedInParams & { tokenType: MachineTokenType; machineData: MachineAuthType });\n\nexport function signedIn<T extends TokenType>(params: SignedInParams & { tokenType: T }): AuthenticatedState<T> {\n const { authenticateContext, headers = new Headers(), token } = params;\n\n const toAuth = (({ treatPendingAsSignedOut = true } = {}) => {\n if (params.tokenType === TokenType.SessionToken) {\n const { sessionClaims } = params as { sessionClaims: JwtPayload };\n const authObject = signedInAuthObject(authenticateContext, token, sessionClaims);\n\n if (treatPendingAsSignedOut && authObject.sessionStatus === 'pending') {\n return signedOutAuthObject(undefined, authObject.sessionStatus);\n }\n\n return authObject;\n }\n\n const { machineData } = params as { machineData: MachineAuthType };\n return authenticatedMachineObject(params.tokenType, token, machineData, authenticateContext);\n }) as ToAuth<T, true>;\n\n return {\n status: AuthStatus.SignedIn,\n reason: null,\n message: null,\n proxyUrl: authenticateContext.proxyUrl || '',\n publishableKey: authenticateContext.publishableKey || '',\n isSatellite: authenticateContext.isSatellite || false,\n domain: authenticateContext.domain || '',\n signInUrl: authenticateContext.signInUrl || '',\n signUpUrl: authenticateContext.signUpUrl || '',\n afterSignInUrl: authenticateContext.afterSignInUrl || '',\n afterSignUpUrl: authenticateContext.afterSignUpUrl || '',\n isSignedIn: true,\n isAuthenticated: true,\n tokenType: params.tokenType,\n toAuth,\n headers,\n token,\n };\n}\n\ntype SignedOutParams = Omit<BaseSignedInParams, 'token'> & {\n reason: AuthReason;\n message?: string;\n};\n\nexport function signedOut<T extends TokenType>(params: SignedOutParams & { tokenType: T }): UnauthenticatedState<T> {\n const { authenticateContext, headers = new Headers(), reason, message = '', tokenType } = params;\n\n const toAuth = (() => {\n if (tokenType === TokenType.SessionToken) {\n return signedOutAuthObject({ ...authenticateContext, status: AuthStatus.SignedOut, reason, message });\n }\n\n return unauthenticatedMachineObject(tokenType, { reason, message, headers });\n }) as ToAuth<T, false>;\n\n return withDebugHeaders({\n status: AuthStatus.SignedOut,\n reason,\n message,\n proxyUrl: authenticateContext.proxyUrl || '',\n publishableKey: authenticateContext.publishableKey || '',\n isSatellite: authenticateContext.isSatellite || false,\n domain: authenticateContext.domain || '',\n signInUrl: authenticateContext.signInUrl || '',\n signUpUrl: authenticateContext.signUpUrl || '',\n afterSignInUrl: authenticateContext.afterSignInUrl || '',\n afterSignUpUrl: authenticateContext.afterSignUpUrl || '',\n isSignedIn: false,\n isAuthenticated: false,\n tokenType,\n toAuth,\n headers,\n token: null,\n });\n}\n\nexport function handshake(\n authenticateContext: AuthenticateContext,\n reason: AuthReason,\n message = '',\n headers: Headers,\n): HandshakeState {\n return withDebugHeaders({\n status: AuthStatus.Handshake,\n reason,\n message,\n publishableKey: authenticateContext.publishableKey || '',\n isSatellite: authenticateContext.isSatellite || false,\n domain: authenticateContext.domain || '',\n proxyUrl: authenticateContext.proxyUrl || '',\n signInUrl: authenticateContext.signInUrl || '',\n signUpUrl: authenticateContext.signUpUrl || '',\n afterSignInUrl: authenticateContext.afterSignInUrl || '',\n afterSignUpUrl: authenticateContext.afterSignUpUrl || '',\n isSignedIn: false,\n isAuthenticated: false,\n tokenType: TokenType.SessionToken,\n toAuth: () => null,\n headers,\n token: null,\n });\n}\n\nexport function signedOutInvalidToken(): UnauthenticatedState<null> {\n const authObject = invalidTokenAuthObject();\n return withDebugHeaders({\n status: AuthStatus.SignedOut,\n reason: AuthErrorReason.TokenTypeMismatch,\n message: '',\n proxyUrl: '',\n publishableKey: '',\n isSatellite: false,\n domain: '',\n signInUrl: '',\n signUpUrl: '',\n afterSignInUrl: '',\n afterSignUpUrl: '',\n isSignedIn: false,\n isAuthenticated: false,\n tokenType: null,\n toAuth: () => authObject,\n headers: new Headers(),\n token: null,\n });\n}\n\nconst withDebugHeaders = <T extends { headers: Headers; message?: string; reason?: AuthReason; status?: AuthStatus }>(\n requestState: T,\n): T => {\n const headers = new Headers(requestState.headers || {});\n\n if (requestState.message) {\n try {\n headers.set(constants.Headers.AuthMessage, requestState.message);\n } catch {\n // headers.set can throw if unicode strings are passed to it. In this case, simply do nothing\n }\n }\n\n if (requestState.reason) {\n try {\n headers.set(constants.Headers.AuthReason, requestState.reason);\n } catch {\n /* empty */\n }\n }\n\n if (requestState.status) {\n try {\n headers.set(constants.Headers.AuthStatus, requestState.status);\n } catch {\n /* empty */\n }\n }\n\n requestState.headers = headers;\n\n return requestState;\n};\n","import { parse } from 'cookie';\n\nimport { constants } from '../constants';\nimport type { ClerkUrl } from './clerkUrl';\nimport { createClerkUrl } from './clerkUrl';\n\n/**\n * A class that extends the native Request class,\n * adds cookies helpers and a normalised clerkUrl that is constructed by using the values found\n * in req.headers so it is able to work reliably when the app is running behind a proxy server.\n */\nclass ClerkRequest extends Request {\n readonly clerkUrl: ClerkUrl;\n readonly cookies: Map<string, string | undefined>;\n\n public constructor(input: ClerkRequest | Request | RequestInfo, init?: RequestInit) {\n // The usual way to duplicate a request object is to\n // pass the original request object to the Request constructor\n // both as the `input` and `init` parameters, eg: super(req, req)\n // However, this fails in certain environments like Vercel Edge Runtime\n // when a framework like Remix polyfills the global Request object.\n // This happens because `undici` performs the following instanceof check\n // which, instead of testing against the global Request object, tests against\n // the Request class defined in the same file (local Request class).\n // For more details, please refer to:\n // https://github.com/nodejs/undici/issues/2155\n // https://github.com/nodejs/undici/blob/7153a1c78d51840bbe16576ce353e481c3934701/lib/fetch/request.js#L854\n const url = typeof input !== 'string' && 'url' in input ? input.url : String(input);\n super(url, init || typeof input === 'string' ? undefined : input);\n this.clerkUrl = this.deriveUrlFromHeaders(this);\n this.cookies = this.parseCookies(this);\n }\n\n public toJSON() {\n return {\n url: this.clerkUrl.href,\n method: this.method,\n headers: JSON.stringify(Object.fromEntries(this.headers)),\n clerkUrl: this.clerkUrl.toString(),\n cookies: JSON.stringify(Object.fromEntries(this.cookies)),\n };\n }\n\n /**\n * Used to fix request.url using the x-forwarded-* headers\n * TODO add detailed description of the issues this solves\n */\n private deriveUrlFromHeaders(req: Request) {\n const initialUrl = new URL(req.url);\n const forwardedProto = req.headers.get(constants.Headers.ForwardedProto);\n const forwardedHost = req.headers.get(constants.Headers.ForwardedHost);\n const host = req.headers.get(constants.Headers.Host);\n const protocol = initialUrl.protocol;\n\n const resolvedHost = this.getFirstValueFromHeader(forwardedHost) ?? host;\n const resolvedProtocol = this.getFirstValueFromHeader(forwardedProto) ?? protocol?.replace(/[:/]/, '');\n const origin = resolvedHost && resolvedProtocol ? `${resolvedProtocol}://${resolvedHost}` : initialUrl.origin;\n\n if (origin === initialUrl.origin) {\n return createClerkUrl(initialUrl);\n }\n return createClerkUrl(initialUrl.pathname + initialUrl.search, origin);\n }\n\n private getFirstValueFromHeader(value?: string | null) {\n return value?.split(',')[0];\n }\n\n private parseCookies(req: Request) {\n const cookiesRecord = parse(this.decodeCookieValue(req.headers.get('cookie') || ''));\n return new Map(Object.entries(cookiesRecord));\n }\n\n private decodeCookieValue(str: string) {\n return str ? str.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent) : str;\n }\n}\n\nexport const createClerkRequest = (...args: ConstructorParameters<typeof ClerkRequest>): ClerkRequest => {\n return args[0] instanceof ClerkRequest ? args[0] : new ClerkRequest(...args);\n};\n\nexport type { ClerkRequest };\n","class ClerkUrl extends URL {\n public isCrossOrigin(other: URL | string) {\n return this.origin !== new URL(other.toString()).origin;\n }\n}\n\nexport type WithClerkUrl<T> = T & {\n /**\n * When a NextJs app is hosted on a platform different from Vercel\n * or inside a container (Netlify, Fly.io, AWS Amplify, docker etc),\n * req.url is always set to `localhost:3000` instead of the actual host of the app.\n *\n * The `authMiddleware` uses the value of the available req.headers in order to construct\n * and use the correct url internally. This url is then exposed as `experimental_clerkUrl`,\n * intended to be used within `beforeAuth` and `afterAuth` if needed.\n */\n clerkUrl: ClerkUrl;\n};\n\nexport const createClerkUrl = (...args: ConstructorParameters<typeof ClerkUrl>): ClerkUrl => {\n return new ClerkUrl(...args);\n};\n\nexport type { ClerkUrl };\n","export const getCookieName = (cookieDirective: string): string => {\n return cookieDirective.split(';')[0]?.split('=')[0];\n};\n\nexport const getCookieValue = (cookieDirective: string): string => {\n return cookieDirective.split(';')[0]?.split('=')[1];\n};\n","import {\n API_URL,\n API_VERSION,\n MAX_CACHE_LAST_UPDATED_AT_SECONDS,\n SUPPORTED_BAPI_VERSION,\n USER_AGENT,\n} from '../constants';\nimport {\n TokenVerificationError,\n TokenVerificationErrorAction,\n TokenVerificationErrorCode,\n TokenVerificationErrorReason,\n} from '../errors';\nimport { runtime } from '../runtime';\nimport { joinPaths } from '../util/path';\nimport { retry } from '../util/shared';\n\ntype JsonWebKeyWithKid = JsonWebKey & { kid: string };\n\ntype JsonWebKeyCache = Record<string, JsonWebKeyWithKid>;\n\nlet cache: JsonWebKeyCache = {};\nlet lastUpdatedAt = 0;\n\nfunction getFromCache(kid: string) {\n return cache[kid];\n}\n\nfunction getCacheValues() {\n return Object.values(cache);\n}\n\nfunction setInCache(cacheKey: string, jwk: JsonWebKeyWithKid, shouldExpire = true) {\n cache[cacheKey] = jwk;\n lastUpdatedAt = shouldExpire ? Date.now() : -1;\n}\n\nconst PEM_HEADER = '-----BEGIN PUBLIC KEY-----';\nconst PEM_TRAILER = '-----END PUBLIC KEY-----';\nconst RSA_PREFIX = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA';\nconst RSA_SUFFIX = 'IDAQAB';\n\ntype LoadClerkJwkFromPemOptions = {\n kid: string;\n pem?: string;\n};\n\n/**\n * Loads a local PEM key usually from process.env and transform it to JsonWebKey format.\n * The result is cached on the module level to avoid unnecessary computations in subsequent invocations.\n */\nexport function loadClerkJwkFromPem(params: LoadClerkJwkFromPemOptions): JsonWebKey {\n const { kid, pem } = params;\n\n // We use a cache key that includes the local prefix in order to avoid\n // cache conflicts when loadClerkJwkFromPem and loadClerkJWKFromRemote\n // are called with the same kid\n const prefixedKid = `local-${kid}`;\n const cachedJwk = getFromCache(prefixedKid);\n\n if (cachedJwk) {\n return cachedJwk;\n }\n\n if (!pem) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.SetClerkJWTKey,\n message: 'Missing local JWK.',\n reason: TokenVerificationErrorReason.LocalJWKMissing,\n });\n }\n\n const modulus = pem\n .replace(/\\r\\n|\\n|\\r/g, '')\n .replace(PEM_HEADER, '')\n .replace(PEM_TRAILER, '')\n .replace(RSA_PREFIX, '')\n .replace(RSA_SUFFIX, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n\n // https://datatracker.ietf.org/doc/html/rfc7517\n const jwk = { kid: prefixedKid, kty: 'RSA', alg: 'RS256', n: modulus, e: 'AQAB' };\n setInCache(prefixedKid, jwk, false); // local key never expires in cache\n return jwk;\n}\n\n/**\n * @internal\n */\nexport type LoadClerkJWKFromRemoteOptions = {\n /**\n * @internal\n */\n kid: string;\n /**\n * @deprecated This cache TTL will be removed in the next major version. Specifying a cache TTL is a no-op.\n */\n jwksCacheTtlInMs?: number;\n /**\n * A flag to ignore the JWKS cache and always fetch JWKS before each JWT verification.\n */\n skipJwksCache?: boolean;\n /**\n * The Clerk Secret Key from the [**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page in the Clerk Dashboard.\n */\n secretKey?: string;\n /**\n * The [Clerk Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }} endpoint.\n * @default 'https://api.clerk.com'\n */\n apiUrl?: string;\n /**\n * The version passed to the Clerk API.\n * @default 'v1'\n */\n apiVersion?: string;\n};\n\n/**\n *\n * Loads a key from JWKS retrieved from the well-known Frontend API endpoint of the issuer.\n * The result is also cached on the module level to avoid network requests in subsequent invocations.\n * The cache lasts up to 5 minutes.\n *\n * @param {Object} options\n * @param {string} options.kid - The id of the key that the JWT was signed with\n * @param {string} options.alg - The algorithm of the JWT\n * @returns {JsonWebKey} key\n */\nexport async function loadClerkJWKFromRemote(params: LoadClerkJWKFromRemoteOptions): Promise<JsonWebKey> {\n const { secretKey, apiUrl = API_URL, apiVersion = API_VERSION, kid, skipJwksCache } = params;\n\n if (skipJwksCache || cacheHasExpired() || !getFromCache(kid)) {\n if (!secretKey) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.ContactSupport,\n message: 'Failed to load JWKS from Clerk Backend or Frontend API.',\n reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad,\n });\n }\n const fetcher = () => fetchJWKSFromBAPI(apiUrl, secretKey, apiVersion) as Promise<{ keys: JsonWebKeyWithKid[] }>;\n const { keys } = await retry(fetcher);\n\n if (!keys || !keys.length) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.ContactSupport,\n message: 'The JWKS endpoint did not contain any signing keys. Contact support@clerk.com.',\n reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad,\n });\n }\n\n keys.forEach(key => setInCache(key.kid, key));\n }\n\n const jwk = getFromCache(kid);\n\n if (!jwk) {\n const cacheValues = getCacheValues();\n const jwkKeys = cacheValues\n .map(jwk => jwk.kid)\n .sort()\n .join(', ');\n\n throw new TokenVerificationError({\n action: `Go to your Dashboard and validate your secret and public keys are correct. ${TokenVerificationErrorAction.ContactSupport} if the issue persists.`,\n message: `Unable to find a signing key in JWKS that matches the kid='${kid}' of the provided session token. Please make sure that the __session cookie or the HTTP authorization header contain a Clerk-generated session JWT. The following kid is available: ${jwkKeys}`,\n reason: TokenVerificationErrorReason.JWKKidMismatch,\n });\n }\n\n return jwk;\n}\n\nasync function fetchJWKSFromBAPI(apiUrl: string, key: string, apiVersion: string) {\n if (!key) {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.SetClerkSecretKey,\n message:\n 'Missing Clerk Secret Key or API Key. Go to https://dashboard.clerk.com and get your key for your instance.',\n reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad,\n });\n }\n\n const url = new URL(apiUrl);\n url.pathname = joinPaths(url.pathname, apiVersion, '/jwks');\n\n const response = await runtime.fetch(url.href, {\n headers: {\n Authorization: `Bearer ${key}`,\n 'Clerk-API-Version': SUPPORTED_BAPI_VERSION,\n 'Content-Type': 'application/json',\n 'User-Agent': USER_AGENT,\n },\n });\n\n if (!response.ok) {\n const json = await response.json();\n const invalidSecretKeyError = getErrorObjectByCode(json?.errors, TokenVerificationErrorCode.InvalidSecretKey);\n\n if (invalidSecretKeyError) {\n const reason = TokenVerificationErrorReason.InvalidSecretKey;\n\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.ContactSupport,\n message: invalidSecretKeyError.message,\n reason,\n });\n }\n\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.ContactSupport,\n message: `Error loading Clerk JWKS from ${url.href} with code=${response.status}`,\n reason: TokenVerificationErrorReason.RemoteJWKFailedToLoad,\n });\n }\n\n return response.json();\n}\n\nfunction cacheHasExpired() {\n // If lastUpdatedAt is -1, it means that we're using a local JWKS and it never expires\n if (lastUpdatedAt === -1) {\n return false;\n }\n\n // If the cache has expired, clear the value so we don't attempt to make decisions based on stale data\n const isExpired = Date.now() - lastUpdatedAt >= MAX_CACHE_LAST_UPDATED_AT_SECONDS * 1000;\n\n if (isExpired) {\n cache = {};\n }\n\n return isExpired;\n}\n\ntype ErrorFields = {\n message: string;\n long_message: string;\n code: string;\n};\n\nconst getErrorObjectByCode = (errors: ErrorFields[], code: string) => {\n if (!errors) {\n return null;\n }\n\n return errors.find((err: ErrorFields) => err.code === code);\n};\n","import { isClerkAPIResponseError } from '@clerk/shared/error';\nimport type { JwtPayload, Simplify } from '@clerk/shared/types';\n\nimport type { APIKey, IdPOAuthAccessToken, M2MToken } from '../api';\nimport { createBackendApiClient } from '../api/factory';\nimport {\n MachineTokenVerificationError,\n MachineTokenVerificationErrorCode,\n TokenVerificationError,\n TokenVerificationErrorAction,\n TokenVerificationErrorReason,\n} from '../errors';\nimport type { VerifyJwtOptions } from '../jwt';\nimport type { JwtReturnType, MachineTokenReturnType } from '../jwt/types';\nimport { decodeJwt, verifyJwt } from '../jwt/verifyJwt';\nimport type { LoadClerkJWKFromRemoteOptions } from './keys';\nimport { loadClerkJwkFromPem, loadClerkJWKFromRemote } from './keys';\nimport { API_KEY_PREFIX, M2M_TOKEN_PREFIX, OAUTH_TOKEN_PREFIX } from './machine';\nimport type { MachineTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\n\n/**\n * @interface\n */\nexport type VerifyTokenOptions = Simplify<\n Omit<VerifyJwtOptions, 'key'> &\n Omit<LoadClerkJWKFromRemoteOptions, 'kid'> & {\n /**\n * Used to verify the session token in a networkless manner. Supply the PEM public key from the **[**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page -> Show JWT public key -> PEM Public Key** section in the Clerk Dashboard. **It's recommended to use [the environment variable](https://clerk.com/docs/guides/development/clerk-environment-variables) instead.** For more information, refer to [Manual JWT verification](https://clerk.com/docs/guides/sessions/manual-jwt-verification).\n */\n jwtKey?: string;\n }\n>;\n\n/**\n * > [!WARNING]\n * > This is a lower-level method intended for more advanced use-cases. It's recommended to use [`authenticateRequest()`](https://clerk.com/docs/reference/backend/authenticate-request), which fully authenticates a token passed from the `request` object.\n *\n * Verifies a Clerk-generated token signature. Networkless if the `jwtKey` is provided. Otherwise, performs a network call to retrieve the JWKS from the [Backend API](https://clerk.com/docs/reference/backend-api/tag/JWKS#operation/GetJWKS){{ target: '_blank' }}.\n *\n * @param token - The token to verify.\n * @param options - Options for verifying the token. It is recommended to set these options as [environment variables](/docs/guides/development/clerk-environment-variables#api-and-sdk-configuration) where possible, and then pass them to the function. For example, you can set the `secretKey` option using the `CLERK_SECRET_KEY` environment variable, and then pass it to the function like this: `verifyToken(token, { secretKey: process.env.CLERK_SECRET_KEY })`.\n *\n * @displayFunctionSignature\n * @hideReturns\n *\n * @example\n *\n * The following example demonstrates how to use the [JavaScript Backend SDK](https://clerk.com/docs/reference/backend/overview) to verify the token signature.\n *\n * In the following example:\n *\n * 1. The **JWKS Public Key** from the Clerk Dashboard is set in the environment variable `CLERK_JWT_KEY`.\n * 1. The session token is retrieved from the `__session` cookie or the Authorization header.\n * 1. The token is verified in a networkless manner by passing the `jwtKey` prop.\n * 1. The `authorizedParties` prop is passed to verify that the session token is generated from the expected frontend application.\n * 1. If the token is valid, the response contains the verified token.\n *\n * ```ts\n * import { verifyToken } from '@clerk/backend'\n * import { cookies } from 'next/headers'\n *\n * export async function GET(request: Request) {\n * const cookieStore = cookies()\n * const sessToken = cookieStore.get('__session')?.value\n * const bearerToken = request.headers.get('Authorization')?.replace('Bearer ', '')\n * const token = sessToken || bearerToken\n *\n * if (!token) {\n * return Response.json({ error: 'Token not found. User must sign in.' }, { status: 401 })\n * }\n *\n * try {\n * const verifiedToken = await verifyToken(token, {\n * jwtKey: process.env.CLERK_JWT_KEY,\n * authorizedParties: ['http://localhost:3001', 'api.example.com'], // Replace with your authorized parties\n * })\n *\n * return Response.json({ verifiedToken })\n * } catch (error) {\n * return Response.json({ error: 'Token not verified.' }, { status: 401 })\n * }\n * }\n * ```\n *\n * If the token is valid, the response will contain a JSON object that looks something like this:\n *\n * ```json\n * {\n * \"verifiedToken\": {\n * \"azp\": \"http://localhost:3000\",\n * \"exp\": 1687906422,\n * \"iat\": 1687906362,\n * \"iss\": \"https://magical-marmoset-51.clerk.accounts.dev\",\n * \"nbf\": 1687906352,\n * \"sid\": \"sess_2Ro7e2IxrffdqBboq8KfB6eGbIy\",\n * \"sub\": \"user_2RfWKJREkjKbHZy0Wqa5qrHeAnb\"\n * }\n * }\n * ```\n */\nexport async function verifyToken(\n token: string,\n options: VerifyTokenOptions,\n): Promise<JwtReturnType<JwtPayload, TokenVerificationError>> {\n const { data: decodedResult, errors } = decodeJwt(token);\n if (errors) {\n return { errors };\n }\n\n const { header } = decodedResult;\n const { kid } = header;\n\n try {\n let key: JsonWebKey;\n\n if (options.jwtKey) {\n key = loadClerkJwkFromPem({ kid, pem: options.jwtKey });\n } else if (options.secretKey) {\n // Fetch JWKS from Backend API using the key\n key = await loadClerkJWKFromRemote({ ...options, kid });\n } else {\n return {\n errors: [\n new TokenVerificationError({\n action: TokenVerificationErrorAction.SetClerkJWTKey,\n message: 'Failed to resolve JWK during verification.',\n reason: TokenVerificationErrorReason.JWKFailedToResolve,\n }),\n ],\n };\n }\n\n return await verifyJwt(token, { ...options, key });\n } catch (error) {\n return { errors: [error as TokenVerificationError] };\n }\n}\n\n/**\n * Handles errors from Clerk API responses for machine tokens\n * @param tokenType - The type of machine token\n * @param err - The error from the Clerk API\n * @param notFoundMessage - Custom message for 404 errors\n */\nfunction handleClerkAPIError(\n tokenType: MachineTokenType,\n err: any,\n notFoundMessage: string,\n): MachineTokenReturnType<any, MachineTokenVerificationError> {\n if (isClerkAPIResponseError(err)) {\n let code: MachineTokenVerificationErrorCode;\n let message: string;\n\n switch (err.status) {\n case 401:\n code = MachineTokenVerificationErrorCode.InvalidSecretKey;\n message = err.errors[0]?.message || 'Invalid secret key';\n break;\n case 404:\n code = MachineTokenVerificationErrorCode.TokenInvalid;\n message = notFoundMessage;\n break;\n default:\n code = MachineTokenVerificationErrorCode.UnexpectedError;\n message = 'Unexpected error';\n }\n\n return {\n data: undefined,\n tokenType,\n errors: [\n new MachineTokenVerificationError({\n message,\n code,\n status: err.status,\n }),\n ],\n };\n }\n\n return {\n data: undefined,\n tokenType,\n errors: [\n new MachineTokenVerificationError({\n message: 'Unexpected error',\n code: MachineTokenVerificationErrorCode.UnexpectedError,\n status: err.status,\n }),\n ],\n };\n}\n\nasync function verifyM2MToken(\n token: string,\n options: VerifyTokenOptions & { machineSecretKey?: string },\n): Promise<MachineTokenReturnType<M2MToken, MachineTokenVerificationError>> {\n try {\n const client = createBackendApiClient(options);\n const verifiedToken = await client.m2m.verify({ token });\n return { data: verifiedToken, tokenType: TokenType.M2MToken, errors: undefined };\n } catch (err: any) {\n return handleClerkAPIError(TokenType.M2MToken, err, 'Machine token not found');\n }\n}\n\nasync function verifyOAuthToken(\n accessToken: string,\n options: VerifyTokenOptions,\n): Promise<MachineTokenReturnType<IdPOAuthAccessToken, MachineTokenVerificationError>> {\n try {\n const client = createBackendApiClient(options);\n const verifiedToken = await client.idPOAuthAccessToken.verify(accessToken);\n return { data: verifiedToken, tokenType: TokenType.OAuthToken, errors: undefined };\n } catch (err: any) {\n return handleClerkAPIError(TokenType.OAuthToken, err, 'OAuth token not found');\n }\n}\n\nasync function verifyAPIKey(\n secret: string,\n options: VerifyTokenOptions,\n): Promise<MachineTokenReturnType<APIKey, MachineTokenVerificationError>> {\n try {\n const client = createBackendApiClient(options);\n const verifiedToken = await client.apiKeys.verify(secret);\n return { data: verifiedToken, tokenType: TokenType.ApiKey, errors: undefined };\n } catch (err: any) {\n return handleClerkAPIError(TokenType.ApiKey, err, 'API key not found');\n }\n}\n\n/**\n * Verifies any type of machine token by detecting its type from the prefix.\n *\n * @param token - The token to verify (e.g. starts with \"m2m_\", \"oauth_\", \"api_key_\", etc.)\n * @param options - Options including secretKey for BAPI authorization\n */\nexport async function verifyMachineAuthToken(token: string, options: VerifyTokenOptions) {\n if (token.startsWith(M2M_TOKEN_PREFIX)) {\n return verifyM2MToken(token, options);\n }\n if (token.startsWith(OAUTH_TOKEN_PREFIX)) {\n return verifyOAuthToken(token, options);\n }\n if (token.startsWith(API_KEY_PREFIX)) {\n return verifyAPIKey(token, options);\n }\n\n throw new Error('Unknown machine token type');\n}\n","import { constants, SUPPORTED_BAPI_VERSION } from '../constants';\nimport { TokenVerificationError, TokenVerificationErrorAction, TokenVerificationErrorReason } from '../errors';\nimport type { VerifyJwtOptions } from '../jwt';\nimport { assertHeaderAlgorithm, assertHeaderType } from '../jwt/assertions';\nimport { decodeJwt, hasValidSignature } from '../jwt/verifyJwt';\nimport type { AuthenticateContext } from './authenticateContext';\nimport type { SignedInState, SignedOutState } from './authStatus';\nimport { AuthErrorReason, signedIn, signedOut } from './authStatus';\nimport { getCookieName, getCookieValue } from './cookie';\nimport { loadClerkJwkFromPem, loadClerkJWKFromRemote } from './keys';\nimport type { OrganizationMatcher } from './organizationMatcher';\nimport { TokenType } from './tokenTypes';\nimport type { OrganizationSyncOptions, OrganizationSyncTarget } from './types';\nimport type { VerifyTokenOptions } from './verify';\nimport { verifyToken } from './verify';\n\nasync function verifyHandshakeJwt(token: string, { key }: VerifyJwtOptions): Promise<{ handshake: string[] }> {\n const { data: decoded, errors } = decodeJwt(token);\n if (errors) {\n throw errors[0];\n }\n\n const { header, payload } = decoded;\n\n // Header verifications\n const { typ, alg } = header;\n\n assertHeaderType(typ);\n assertHeaderAlgorithm(alg);\n\n const { data: signatureValid, errors: signatureErrors } = await hasValidSignature(decoded, key);\n if (signatureErrors) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenVerificationFailed,\n message: `Error verifying handshake token. ${signatureErrors[0]}`,\n });\n }\n\n if (!signatureValid) {\n throw new TokenVerificationError({\n reason: TokenVerificationErrorReason.TokenInvalidSignature,\n message: 'Handshake signature is invalid.',\n });\n }\n\n return payload as unknown as { handshake: string[] };\n}\n\n/**\n * Similar to our verifyToken flow for Clerk-issued JWTs, but this verification flow is for our signed handshake payload.\n * The handshake payload requires fewer verification steps.\n */\nexport async function verifyHandshakeToken(\n token: string,\n options: VerifyTokenOptions,\n): Promise<{ handshake: string[] }> {\n const { secretKey, apiUrl, apiVersion, jwksCacheTtlInMs, jwtKey, skipJwksCache } = options;\n\n const { data, errors } = decodeJwt(token);\n if (errors) {\n throw errors[0];\n }\n\n const { kid } = data.header;\n\n let key;\n\n if (jwtKey) {\n key = loadClerkJwkFromPem({ kid, pem: jwtKey });\n } else if (secretKey) {\n // Fetch JWKS from Backend API using the key\n key = await loadClerkJWKFromRemote({ secretKey, apiUrl, apiVersion, kid, jwksCacheTtlInMs, skipJwksCache });\n } else {\n throw new TokenVerificationError({\n action: TokenVerificationErrorAction.SetClerkJWTKey,\n message: 'Failed to resolve JWK during handshake verification.',\n reason: TokenVerificationErrorReason.JWKFailedToResolve,\n });\n }\n\n return verifyHandshakeJwt(token, { key });\n}\n\nexport class HandshakeService {\n private readonly authenticateContext: AuthenticateContext;\n private readonly organizationMatcher: OrganizationMatcher;\n private readonly options: { organizationSyncOptions?: OrganizationSyncOptions };\n\n constructor(\n authenticateContext: AuthenticateContext,\n options: { organizationSyncOptions?: OrganizationSyncOptions },\n organizationMatcher: OrganizationMatcher,\n ) {\n this.authenticateContext = authenticateContext;\n this.options = options;\n this.organizationMatcher = organizationMatcher;\n }\n\n /**\n * Determines if a request is eligible for handshake based on its headers\n *\n * Currently, a request is only eligible for a handshake if we can say it's *probably* a request for a document, not a fetch or some other exotic request.\n * This heuristic should give us a reliable enough signal for browsers that support `Sec-Fetch-Dest` and for those that don't.\n *\n * @returns boolean indicating if the request is eligible for handshake\n */\n isRequestEligibleForHandshake(): boolean {\n const { accept, secFetchDest } = this.authenticateContext;\n\n // NOTE: we could also check sec-fetch-mode === navigate here, but according to the spec, sec-fetch-dest: document should indicate that the request is the data of a user navigation.\n // Also, we check for 'iframe' because it's the value set when a doc request is made by an iframe.\n if (secFetchDest === 'document' || secFetchDest === 'iframe') {\n return true;\n }\n\n if (!secFetchDest && accept?.startsWith('text/html')) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Builds the redirect headers for a handshake request\n * @param reason - The reason for the handshake (e.g. 'session-token-expired')\n * @returns Headers object containing the Location header for redirect\n * @throws Error if clerkUrl is missing in authenticateContext\n */\n buildRedirectToHandshake(reason: string): Headers {\n if (!this.authenticateContext?.clerkUrl) {\n throw new Error('Missing clerkUrl in authenticateContext');\n }\n\n const redirectUrl = this.removeDevBrowserFromURL(this.authenticateContext.clerkUrl);\n\n let baseUrl = this.authenticateContext.frontendApi.startsWith('http')\n ? this.authenticateContext.frontendApi\n : `https://${this.authenticateContext.frontendApi}`;\n\n baseUrl = baseUrl.replace(/\\/+$/, '') + '/';\n\n const url = new URL('v1/client/handshake', baseUrl);\n url.searchParams.append('redirect_url', redirectUrl?.href || '');\n url.searchParams.append('__clerk_api_version', SUPPORTED_BAPI_VERSION);\n url.searchParams.append(\n constants.QueryParameters.SuffixedCookies,\n this.authenticateContext.usesSuffixedCookies().toString(),\n );\n url.searchParams.append(constants.QueryParameters.HandshakeReason, reason);\n url.searchParams.append(constants.QueryParameters.HandshakeFormat, 'nonce');\n\n if (this.authenticateContext.instanceType === 'development' && this.authenticateContext.devBrowserToken) {\n url.searchParams.append(constants.QueryParameters.DevBrowser, this.authenticateContext.devBrowserToken);\n }\n\n const toActivate = this.getOrganizationSyncTarget(this.authenticateContext.clerkUrl, this.organizationMatcher);\n if (toActivate) {\n const params = this.getOrganizationSyncQueryParams(toActivate);\n params.forEach((value, key) => {\n url.searchParams.append(key, value);\n });\n }\n\n return new Headers({ [constants.Headers.Location]: url.href });\n }\n\n /**\n * Gets cookies from either a handshake nonce or a handshake token\n * @returns Promise resolving to string array of cookie directives\n */\n public async getCookiesFromHandshake(): Promise<string[]> {\n const cookiesToSet: string[] = [];\n\n if (this.authenticateContext.handshakeNonce) {\n try {\n const handshakePayload = await this.authenticateContext.apiClient?.clients.getHandshakePayload({\n nonce: this.authenticateContext.handshakeNonce,\n });\n if (handshakePayload) {\n cookiesToSet.push(...handshakePayload.directives);\n }\n } catch (error) {\n console.error('Clerk: HandshakeService: error getting handshake payload:', error);\n }\n } else if (this.authenticateContext.handshakeToken) {\n const handshakePayload = await verifyHandshakeToken(\n this.authenticateContext.handshakeToken,\n this.authenticateContext,\n );\n if (handshakePayload && Array.isArray(handshakePayload.handshake)) {\n cookiesToSet.push(...handshakePayload.handshake);\n }\n }\n\n return cookiesToSet;\n }\n\n /**\n * Resolves a handshake request by verifying the handshake token and setting appropriate cookies\n * @returns Promise resolving to either a SignedInState or SignedOutState\n * @throws Error if handshake verification fails or if there are issues with the session token\n */\n async resolveHandshake(): Promise<SignedInState | SignedOutState> {\n const headers = new Headers({\n 'Access-Control-Allow-Origin': 'null',\n 'Access-Control-Allow-Credentials': 'true',\n });\n\n const cookiesToSet = await this.getCookiesFromHandshake();\n\n let sessionToken = '';\n cookiesToSet.forEach((x: string) => {\n headers.append('Set-Cookie', x);\n if (getCookieName(x).startsWith(constants.Cookies.Session)) {\n sessionToken = getCookieValue(x);\n }\n });\n\n if (this.authenticateContext.instanceType === 'development') {\n const newUrl = new URL(this.authenticateContext.clerkUrl);\n newUrl.searchParams.delete(constants.QueryParameters.Handshake);\n newUrl.searchParams.delete(constants.QueryParameters.HandshakeHelp);\n newUrl.searchParams.delete(constants.QueryParameters.DevBrowser);\n newUrl.searchParams.delete(constants.QueryParameters.HandshakeNonce);\n headers.append(constants.Headers.Location, newUrl.toString());\n headers.set(constants.Headers.CacheControl, 'no-store');\n }\n\n if (sessionToken === '') {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext: this.authenticateContext,\n reason: AuthErrorReason.SessionTokenMissing,\n message: '',\n headers,\n });\n }\n\n const { data, errors: [error] = [] } = await verifyToken(sessionToken, this.authenticateContext);\n if (data) {\n return signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext: this.authenticateContext,\n sessionClaims: data,\n headers,\n token: sessionToken,\n });\n }\n\n if (\n this.authenticateContext.instanceType === 'development' &&\n (error?.reason === TokenVerificationErrorReason.TokenExpired ||\n error?.reason === TokenVerificationErrorReason.TokenNotActiveYet ||\n error?.reason === TokenVerificationErrorReason.TokenIatInTheFuture)\n ) {\n // Create a new error object with the same properties\n const developmentError = new TokenVerificationError({\n action: error.action,\n message: error.message,\n reason: error.reason,\n });\n // Set the tokenCarrier after construction\n developmentError.tokenCarrier = 'cookie';\n\n console.error(\n `Clerk: Clock skew detected. This usually means that your system clock is inaccurate. Clerk will attempt to account for the clock skew in development.\n\nTo resolve this issue, make sure your system's clock is set to the correct time (e.g. turn off and on automatic time synchronization).\n\n---\n\n${developmentError.getFullMessage()}`,\n );\n\n const { data: retryResult, errors: [retryError] = [] } = await verifyToken(sessionToken, {\n ...this.authenticateContext,\n clockSkewInMs: 86_400_000,\n });\n if (retryResult) {\n return signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext: this.authenticateContext,\n sessionClaims: retryResult,\n headers,\n token: sessionToken,\n });\n }\n\n throw new Error(retryError?.message || 'Clerk: Handshake retry failed.');\n }\n\n throw new Error(error?.message || 'Clerk: Handshake failed.');\n }\n\n /**\n * Handles handshake token verification errors in development mode\n * @param error - The TokenVerificationError that occurred\n * @throws Error with a descriptive message about the verification failure\n */\n handleTokenVerificationErrorInDevelopment(error: TokenVerificationError): void {\n // In development, the handshake token is being transferred in the URL as a query parameter, so there is no\n // possibility of collision with a handshake token of another app running on the same local domain\n // (etc one app on localhost:3000 and one on localhost:3001).\n // Therefore, if the handshake token is invalid, it is likely that the user has switched Clerk keys locally.\n // We make sure to throw a descriptive error message and then stop the handshake flow in every case,\n // to avoid the possibility of an infinite loop.\n if (error.reason === TokenVerificationErrorReason.TokenInvalidSignature) {\n const msg = `Clerk: Handshake token verification failed due to an invalid signature. If you have switched Clerk keys locally, clear your cookies and try again.`;\n throw new Error(msg);\n }\n throw new Error(`Clerk: Handshake token verification failed: ${error.getFullMessage()}.`);\n }\n\n /**\n * Checks if a redirect loop is detected and sets headers to track redirect count\n * @param headers - The Headers object to modify\n * @returns boolean indicating if a redirect loop was detected (true) or if the request can proceed (false)\n */\n checkAndTrackRedirectLoop(headers: Headers): boolean {\n if (this.authenticateContext.handshakeRedirectLoopCounter === 3) {\n return true;\n }\n\n const newCounterValue = this.authenticateContext.handshakeRedirectLoopCounter + 1;\n const cookieName = constants.Cookies.RedirectCount;\n headers.append('Set-Cookie', `${cookieName}=${newCounterValue}; SameSite=Lax; HttpOnly; Max-Age=2`);\n return false;\n }\n\n private removeDevBrowserFromURL(url: URL): URL {\n const updatedURL = new URL(url);\n updatedURL.searchParams.delete(constants.QueryParameters.DevBrowser);\n updatedURL.searchParams.delete(constants.QueryParameters.LegacyDevBrowser);\n return updatedURL;\n }\n\n private getOrganizationSyncTarget(url: URL, matchers: OrganizationMatcher): OrganizationSyncTarget | null {\n return matchers.findTarget(url);\n }\n\n private getOrganizationSyncQueryParams(toActivate: OrganizationSyncTarget): Map<string, string> {\n const ret = new Map();\n if (toActivate.type === 'personalAccount') {\n ret.set('organization_id', '');\n }\n if (toActivate.type === 'organization') {\n if (toActivate.organizationId) {\n ret.set('organization_id', toActivate.organizationId);\n }\n if (toActivate.organizationSlug) {\n ret.set('organization_id', toActivate.organizationSlug);\n }\n }\n return ret;\n }\n}\n","import type { MatchFunction } from '@clerk/shared/pathToRegexp';\nimport { match } from '@clerk/shared/pathToRegexp';\n\nimport type { OrganizationSyncOptions, OrganizationSyncTarget } from './types';\n\nexport class OrganizationMatcher {\n private readonly organizationPattern: MatchFunction | null;\n private readonly personalAccountPattern: MatchFunction | null;\n\n constructor(options?: OrganizationSyncOptions) {\n this.organizationPattern = this.createMatcher(options?.organizationPatterns);\n this.personalAccountPattern = this.createMatcher(options?.personalAccountPatterns);\n }\n\n private createMatcher(pattern?: string[]): MatchFunction | null {\n if (!pattern) {\n return null;\n }\n try {\n return match(pattern);\n } catch (e) {\n throw new Error(`Invalid pattern \"${pattern}\": ${e}`);\n }\n }\n\n findTarget(url: URL): OrganizationSyncTarget | null {\n const orgTarget = this.findOrganizationTarget(url);\n if (orgTarget) {\n return orgTarget;\n }\n\n return this.findPersonalAccountTarget(url);\n }\n\n private findOrganizationTarget(url: URL): OrganizationSyncTarget | null {\n if (!this.organizationPattern) {\n return null;\n }\n\n try {\n const result = this.organizationPattern(url.pathname);\n if (!result || !('params' in result)) {\n return null;\n }\n\n const params = result.params as { id?: string; slug?: string };\n if (params.id) {\n return { type: 'organization', organizationId: params.id };\n }\n if (params.slug) {\n return { type: 'organization', organizationSlug: params.slug };\n }\n\n return null;\n } catch (e) {\n console.error('Failed to match organization pattern:', e);\n return null;\n }\n }\n\n private findPersonalAccountTarget(url: URL): OrganizationSyncTarget | null {\n if (!this.personalAccountPattern) {\n return null;\n }\n\n try {\n const result = this.personalAccountPattern(url.pathname);\n return result ? { type: 'personalAccount' } : null;\n } catch (e) {\n console.error('Failed to match personal account pattern:', e);\n return null;\n }\n }\n}\n","import type { JwtPayload } from '@clerk/shared/types';\n\nimport { constants } from '../constants';\nimport type { TokenCarrier } from '../errors';\nimport { MachineTokenVerificationError, TokenVerificationError, TokenVerificationErrorReason } from '../errors';\nimport { decodeJwt } from '../jwt/verifyJwt';\nimport { assertValidSecretKey } from '../util/optionsAssertions';\nimport { isDevelopmentFromSecretKey } from '../util/shared';\nimport type { AuthenticateContext } from './authenticateContext';\nimport { createAuthenticateContext } from './authenticateContext';\nimport type { SignedInAuthObject } from './authObjects';\nimport type { HandshakeState, RequestState, SignedInState, SignedOutState, UnauthenticatedState } from './authStatus';\nimport { AuthErrorReason, handshake, signedIn, signedOut, signedOutInvalidToken } from './authStatus';\nimport { createClerkRequest } from './clerkRequest';\nimport { getCookieName, getCookieValue } from './cookie';\nimport { HandshakeService } from './handshake';\nimport { getMachineTokenType, isMachineTokenByPrefix, isTokenTypeAccepted } from './machine';\nimport { OrganizationMatcher } from './organizationMatcher';\nimport type { MachineTokenType, SessionTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\nimport type { AuthenticateRequestOptions } from './types';\nimport { verifyMachineAuthToken, verifyToken } from './verify';\n\nexport const RefreshTokenErrorReason = {\n NonEligibleNoCookie: 'non-eligible-no-refresh-cookie',\n NonEligibleNonGet: 'non-eligible-non-get',\n InvalidSessionToken: 'invalid-session-token',\n MissingApiClient: 'missing-api-client',\n MissingSessionToken: 'missing-session-token',\n MissingRefreshToken: 'missing-refresh-token',\n ExpiredSessionTokenDecodeFailed: 'expired-session-token-decode-failed',\n ExpiredSessionTokenMissingSidClaim: 'expired-session-token-missing-sid-claim',\n FetchError: 'fetch-error',\n UnexpectedSDKError: 'unexpected-sdk-error',\n UnexpectedBAPIError: 'unexpected-bapi-error',\n} as const;\n\nfunction assertSignInUrlExists(signInUrl: string | undefined, key: string): asserts signInUrl is string {\n if (!signInUrl && isDevelopmentFromSecretKey(key)) {\n throw new Error(`Missing signInUrl. Pass a signInUrl for dev instances if an app is satellite`);\n }\n}\n\nfunction assertProxyUrlOrDomain(proxyUrlOrDomain: string | undefined) {\n if (!proxyUrlOrDomain) {\n throw new Error(`Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl`);\n }\n}\n\nfunction assertSignInUrlFormatAndOrigin(_signInUrl: string, origin: string) {\n let signInUrl: URL;\n try {\n signInUrl = new URL(_signInUrl);\n } catch {\n throw new Error(`The signInUrl needs to have a absolute url format.`);\n }\n\n if (signInUrl.origin === origin) {\n throw new Error(`The signInUrl needs to be on a different origin than your satellite application.`);\n }\n}\n\nfunction assertMachineSecretOrSecretKey(authenticateContext: AuthenticateContext) {\n if (!authenticateContext.machineSecretKey && !authenticateContext.secretKey) {\n throw new Error(\n 'Machine token authentication requires either a Machine secret key or a Clerk secret key. ' +\n 'Ensure a Clerk secret key or Machine secret key is set.',\n );\n }\n}\n\nfunction isRequestEligibleForRefresh(\n err: TokenVerificationError,\n authenticateContext: { refreshTokenInCookie?: string },\n request: Request,\n) {\n return (\n err.reason === TokenVerificationErrorReason.TokenExpired &&\n !!authenticateContext.refreshTokenInCookie &&\n request.method === 'GET'\n );\n}\n\nfunction checkTokenTypeMismatch(\n parsedTokenType: MachineTokenType,\n acceptsToken: NonNullable<AuthenticateRequestOptions['acceptsToken']>,\n authenticateContext: AuthenticateContext,\n): UnauthenticatedState<MachineTokenType> | null {\n const mismatch = !isTokenTypeAccepted(parsedTokenType, acceptsToken);\n if (mismatch) {\n const tokenTypeToReturn = (typeof acceptsToken === 'string' ? acceptsToken : parsedTokenType) as MachineTokenType;\n return signedOut({\n tokenType: tokenTypeToReturn,\n authenticateContext,\n reason: AuthErrorReason.TokenTypeMismatch,\n });\n }\n return null;\n}\n\nfunction isTokenTypeInAcceptedArray(acceptsToken: TokenType[], authenticateContext: AuthenticateContext): boolean {\n let parsedTokenType: TokenType | null = null;\n const { tokenInHeader } = authenticateContext;\n if (tokenInHeader) {\n if (isMachineTokenByPrefix(tokenInHeader)) {\n parsedTokenType = getMachineTokenType(tokenInHeader);\n } else {\n parsedTokenType = TokenType.SessionToken;\n }\n }\n const typeToCheck = parsedTokenType ?? TokenType.SessionToken;\n return isTokenTypeAccepted(typeToCheck, acceptsToken);\n}\n\nexport interface AuthenticateRequest {\n /**\n * @example\n * clerkClient.authenticateRequest(request, { acceptsToken: ['session_token', 'api_key'] });\n */\n <T extends readonly TokenType[]>(\n request: Request,\n options: AuthenticateRequestOptions & { acceptsToken: T },\n ): Promise<RequestState<T[number] | null>>;\n\n /**\n * @example\n * clerkClient.authenticateRequest(request, { acceptsToken: 'session_token' });\n */\n <T extends TokenType>(\n request: Request,\n options: AuthenticateRequestOptions & { acceptsToken: T },\n ): Promise<RequestState<T>>;\n\n /**\n * @example\n * clerkClient.authenticateRequest(request, { acceptsToken: 'any' });\n */\n (request: Request, options: AuthenticateRequestOptions & { acceptsToken: 'any' }): Promise<RequestState<TokenType>>;\n\n /**\n * @example\n * clerkClient.authenticateRequest(request);\n */\n (request: Request, options?: AuthenticateRequestOptions): Promise<RequestState<SessionTokenType>>;\n}\n\nexport const authenticateRequest: AuthenticateRequest = (async (\n request: Request,\n options: AuthenticateRequestOptions,\n): Promise<RequestState<TokenType> | UnauthenticatedState<null>> => {\n const authenticateContext = await createAuthenticateContext(createClerkRequest(request), options);\n\n // Default tokenType is session_token for backwards compatibility.\n const acceptsToken = options.acceptsToken ?? TokenType.SessionToken;\n\n // machine-to-machine tokens can accept a machine secret or a secret key\n if (acceptsToken !== TokenType.M2MToken) {\n assertValidSecretKey(authenticateContext.secretKey);\n\n if (authenticateContext.isSatellite) {\n assertSignInUrlExists(authenticateContext.signInUrl, authenticateContext.secretKey);\n if (authenticateContext.signInUrl && authenticateContext.origin) {\n assertSignInUrlFormatAndOrigin(authenticateContext.signInUrl, authenticateContext.origin);\n }\n assertProxyUrlOrDomain(authenticateContext.proxyUrl || authenticateContext.domain);\n }\n }\n\n // Make sure a machine secret or instance secret key is provided if acceptsToken is m2m_token\n if (acceptsToken === TokenType.M2MToken) {\n assertMachineSecretOrSecretKey(authenticateContext);\n }\n\n const organizationMatcher = new OrganizationMatcher(options.organizationSyncOptions);\n const handshakeService = new HandshakeService(\n authenticateContext,\n { organizationSyncOptions: options.organizationSyncOptions },\n organizationMatcher,\n );\n\n async function refreshToken(\n authenticateContext: AuthenticateContext,\n ): Promise<{ data: string[]; error: null } | { data: null; error: any }> {\n // To perform a token refresh, apiClient must be defined.\n if (!options.apiClient) {\n return {\n data: null,\n error: {\n message: 'An apiClient is needed to perform token refresh.',\n cause: { reason: RefreshTokenErrorReason.MissingApiClient },\n },\n };\n }\n const { sessionToken: expiredSessionToken, refreshTokenInCookie: refreshToken } = authenticateContext;\n if (!expiredSessionToken) {\n return {\n data: null,\n error: {\n message: 'Session token must be provided.',\n cause: { reason: RefreshTokenErrorReason.MissingSessionToken },\n },\n };\n }\n if (!refreshToken) {\n return {\n data: null,\n error: {\n message: 'Refresh token must be provided.',\n cause: { reason: RefreshTokenErrorReason.MissingRefreshToken },\n },\n };\n }\n // The token refresh endpoint requires a sessionId, so we decode that from the expired token.\n const { data: decodeResult, errors: decodedErrors } = decodeJwt(expiredSessionToken);\n if (!decodeResult || decodedErrors) {\n return {\n data: null,\n error: {\n message: 'Unable to decode the expired session token.',\n cause: { reason: RefreshTokenErrorReason.ExpiredSessionTokenDecodeFailed, errors: decodedErrors },\n },\n };\n }\n\n if (!decodeResult?.payload?.sid) {\n return {\n data: null,\n error: {\n message: 'Expired session token is missing the `sid` claim.',\n cause: { reason: RefreshTokenErrorReason.ExpiredSessionTokenMissingSidClaim },\n },\n };\n }\n\n try {\n // Perform the actual token refresh.\n const response = await options.apiClient.sessions.refreshSession(decodeResult.payload.sid, {\n format: 'cookie',\n suffixed_cookies: authenticateContext.usesSuffixedCookies(),\n expired_token: expiredSessionToken || '',\n refresh_token: refreshToken || '',\n request_origin: authenticateContext.clerkUrl.origin,\n // The refresh endpoint expects headers as Record<string, string[]>, so we need to transform it.\n request_headers: Object.fromEntries(Array.from(request.headers.entries()).map(([k, v]) => [k, [v]])),\n });\n return { data: response.cookies, error: null };\n } catch (err: any) {\n if (err?.errors?.length) {\n if (err.errors[0].code === 'unexpected_error') {\n return {\n data: null,\n error: {\n message: `Fetch unexpected error`,\n cause: { reason: RefreshTokenErrorReason.FetchError, errors: err.errors },\n },\n };\n }\n return {\n data: null,\n error: {\n message: err.errors[0].code,\n cause: { reason: err.errors[0].code, errors: err.errors },\n },\n };\n } else {\n return {\n data: null,\n error: {\n message: `Unexpected Server/BAPI error`,\n cause: { reason: RefreshTokenErrorReason.UnexpectedBAPIError, errors: [err] },\n },\n };\n }\n }\n }\n\n async function attemptRefresh(\n authenticateContext: AuthenticateContext,\n ): Promise<\n | { data: { jwtPayload: JwtPayload; sessionToken: string; headers: Headers }; error: null }\n | { data: null; error: any }\n > {\n const { data: cookiesToSet, error } = await refreshToken(authenticateContext);\n if (!cookiesToSet || cookiesToSet.length === 0) {\n return { data: null, error };\n }\n\n const headers = new Headers();\n let sessionToken = '';\n cookiesToSet.forEach((x: string) => {\n headers.append('Set-Cookie', x);\n if (getCookieName(x).startsWith(constants.Cookies.Session)) {\n sessionToken = getCookieValue(x);\n }\n });\n\n // Since we're going to return a signedIn response, we need to decode the data from the new sessionToken.\n const { data: jwtPayload, errors } = await verifyToken(sessionToken, authenticateContext);\n if (errors) {\n return {\n data: null,\n error: {\n message: `Clerk: unable to verify refreshed session token.`,\n cause: { reason: RefreshTokenErrorReason.InvalidSessionToken, errors },\n },\n };\n }\n return { data: { jwtPayload, sessionToken, headers }, error: null };\n }\n\n function handleMaybeHandshakeStatus(\n authenticateContext: AuthenticateContext,\n reason: string,\n message: string,\n headers?: Headers,\n ): SignedInState | SignedOutState | HandshakeState {\n if (!handshakeService.isRequestEligibleForHandshake()) {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason,\n message,\n });\n }\n\n // Right now the only usage of passing in different headers is for multi-domain sync, which redirects somewhere else.\n // In the future if we want to decorate the handshake redirect with additional headers per call we need to tweak this logic.\n const handshakeHeaders = headers ?? handshakeService.buildRedirectToHandshake(reason);\n\n // Chrome aggressively caches inactive tabs. If we don't set the header here,\n // all 307 redirects will be cached and the handshake will end up in an infinite loop.\n if (handshakeHeaders.get(constants.Headers.Location)) {\n handshakeHeaders.set(constants.Headers.CacheControl, 'no-store');\n }\n\n // Introduce the mechanism to protect for infinite handshake redirect loops\n // using a cookie and returning true if it's infinite redirect loop or false if we can\n // proceed with triggering handshake.\n const isRedirectLoop = handshakeService.checkAndTrackRedirectLoop(handshakeHeaders);\n if (isRedirectLoop) {\n const msg = `Clerk: Refreshing the session token resulted in an infinite redirect loop. This usually means that your Clerk instance keys do not match - make sure to copy the correct publishable and secret keys from the Clerk dashboard.`;\n console.log(msg);\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason,\n message,\n });\n }\n\n return handshake(authenticateContext, reason, message, handshakeHeaders);\n }\n\n /**\n * Determines if a handshake must occur to resolve a mismatch between the organization as specified\n * by the URL (according to the options) and the actual active organization on the session.\n *\n * @returns {HandshakeState | SignedOutState | null} - The function can return the following:\n * - {HandshakeState}: If a handshake is needed to resolve the mismatched organization.\n * - {SignedOutState}: If a handshake is required but cannot be performed.\n * - {null}: If no action is required.\n */\n function handleMaybeOrganizationSyncHandshake(\n authenticateContext: AuthenticateContext,\n auth: SignedInAuthObject,\n ): HandshakeState | SignedOutState | null {\n const organizationSyncTarget = organizationMatcher.findTarget(authenticateContext.clerkUrl);\n if (!organizationSyncTarget) {\n return null;\n }\n let mustActivate = false;\n if (organizationSyncTarget.type === 'organization') {\n // Activate an org by slug?\n if (organizationSyncTarget.organizationSlug && organizationSyncTarget.organizationSlug !== auth.orgSlug) {\n mustActivate = true;\n }\n // Activate an org by ID?\n if (organizationSyncTarget.organizationId && organizationSyncTarget.organizationId !== auth.orgId) {\n mustActivate = true;\n }\n }\n // Activate the personal account?\n if (organizationSyncTarget.type === 'personalAccount' && auth.orgId) {\n mustActivate = true;\n }\n if (!mustActivate) {\n return null;\n }\n if (authenticateContext.handshakeRedirectLoopCounter >= 3) {\n // We have an organization that needs to be activated, but this isn't our first time redirecting.\n // This is because we attempted to activate the organization previously, but the organization\n // must not have been valid (either not found, or not valid for this user), and gave us back\n // a null organization. We won't re-try the handshake, and leave it to the server component to handle.\n console.warn(\n 'Clerk: Organization activation handshake loop detected. This is likely due to an invalid organization ID or slug. Skipping organization activation.',\n );\n return null;\n }\n const handshakeState = handleMaybeHandshakeStatus(\n authenticateContext,\n AuthErrorReason.ActiveOrganizationMismatch,\n '',\n );\n if (handshakeState.status !== 'handshake') {\n // Currently, this is only possible if we're in a redirect loop, but the above check should guard against that.\n return null;\n }\n return handshakeState;\n }\n\n async function authenticateRequestWithTokenInHeader() {\n const { tokenInHeader } = authenticateContext;\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { data, errors } = await verifyToken(tokenInHeader!, authenticateContext);\n if (errors) {\n throw errors[0];\n }\n // use `await` to force this try/catch handle the signedIn invocation\n return signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n sessionClaims: data,\n headers: new Headers(),\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n token: tokenInHeader!,\n });\n } catch (err) {\n return handleSessionTokenError(err, 'header');\n }\n }\n\n async function authenticateRequestWithTokenInCookie() {\n const hasActiveClient = authenticateContext.clientUat;\n const hasSessionToken = !!authenticateContext.sessionTokenInCookie;\n const hasDevBrowserToken = !!authenticateContext.devBrowserToken;\n\n /**\n * If we have a handshakeToken, resolve the handshake and attempt to return a definitive signed in or signed out state.\n */\n if (authenticateContext.handshakeNonce || authenticateContext.handshakeToken) {\n try {\n return await handshakeService.resolveHandshake();\n } catch (error) {\n // In production, the handshake token is being transferred as a cookie, so there is a possibility of collision\n // with a handshake token of another app running on the same etld+1 domain.\n // For example, if one app is running on sub1.clerk.com and another on sub2.clerk.com, the handshake token\n // cookie for both apps will be set on etld+1 (clerk.com) so there's a possibility that one app will accidentally\n // use the handshake token of a different app during the handshake flow.\n // In this scenario, verification will fail with TokenInvalidSignature. In contrast to the development case,\n // we need to allow the flow to continue so the app eventually retries another handshake with the correct token.\n // We need to make sure, however, that we don't allow the flow to continue indefinitely, so we throw an error after X\n // retries to avoid an infinite loop. An infinite loop can happen if the customer switched Clerk keys for their prod app.\n\n // Check the handleTokenVerificationErrorInDevelopment method for the development case.\n if (error instanceof TokenVerificationError && authenticateContext.instanceType === 'development') {\n handshakeService.handleTokenVerificationErrorInDevelopment(error);\n } else {\n console.error('Clerk: unable to resolve handshake:', error);\n }\n }\n }\n const isRequestEligibleForMultiDomainSync =\n authenticateContext.isSatellite && authenticateContext.secFetchDest === 'document';\n\n /**\n * Begin multi-domain sync flows\n */\n if (authenticateContext.instanceType === 'production' && isRequestEligibleForMultiDomainSync) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SatelliteCookieNeedsSyncing, '');\n }\n\n // Multi-domain development sync flow\n if (\n authenticateContext.instanceType === 'development' &&\n isRequestEligibleForMultiDomainSync &&\n !authenticateContext.clerkUrl.searchParams.has(constants.QueryParameters.ClerkSynced)\n ) {\n // initiate MD sync\n\n // signInUrl exists, checked at the top of `authenticateRequest`\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const redirectURL = new URL(authenticateContext.signInUrl!);\n redirectURL.searchParams.append(\n constants.QueryParameters.ClerkRedirectUrl,\n authenticateContext.clerkUrl.toString(),\n );\n const headers = new Headers({ [constants.Headers.Location]: redirectURL.toString() });\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SatelliteCookieNeedsSyncing, '', headers);\n }\n\n // Multi-domain development sync flow - primary responds to syncing\n // IMPORTANT: This must come BEFORE dev-browser-sync check to avoid the root domain\n // triggering its own handshakes when it's in the middle of handling a satellite sync request\n const redirectUrl = new URL(authenticateContext.clerkUrl).searchParams.get(\n constants.QueryParameters.ClerkRedirectUrl,\n );\n\n if (authenticateContext.instanceType === 'development' && !authenticateContext.isSatellite && redirectUrl) {\n // Dev MD sync from primary, redirect back to satellite w/ dev browser query param\n const redirectBackToSatelliteUrl = new URL(redirectUrl);\n\n if (authenticateContext.devBrowserToken) {\n redirectBackToSatelliteUrl.searchParams.append(\n constants.QueryParameters.DevBrowser,\n authenticateContext.devBrowserToken,\n );\n }\n redirectBackToSatelliteUrl.searchParams.append(constants.QueryParameters.ClerkSynced, 'true');\n\n const headers = new Headers({ [constants.Headers.Location]: redirectBackToSatelliteUrl.toString() });\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.PrimaryRespondsToSyncing, '', headers);\n }\n /**\n * End multi-domain sync flows\n */\n\n /**\n * Otherwise, check for \"known unknown\" auth states that we can resolve with a handshake.\n */\n if (\n authenticateContext.instanceType === 'development' &&\n authenticateContext.clerkUrl.searchParams.has(constants.QueryParameters.DevBrowser)\n ) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.DevBrowserSync, '');\n }\n\n if (authenticateContext.instanceType === 'development' && !hasDevBrowserToken) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.DevBrowserMissing, '');\n }\n\n if (!hasActiveClient && !hasSessionToken) {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: AuthErrorReason.SessionTokenAndUATMissing,\n });\n }\n\n // This can eagerly run handshake since client_uat is SameSite=Strict in dev\n if (!hasActiveClient && hasSessionToken) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SessionTokenWithoutClientUAT, '');\n }\n\n if (hasActiveClient && !hasSessionToken) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.ClientUATWithoutSessionToken, '');\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { data: decodeResult, errors: decodedErrors } = decodeJwt(authenticateContext.sessionTokenInCookie!);\n\n if (decodedErrors) {\n return handleSessionTokenError(decodedErrors[0], 'cookie');\n }\n\n if (decodeResult.payload.iat < authenticateContext.clientUat) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SessionTokenIATBeforeClientUAT, '');\n }\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { data, errors } = await verifyToken(authenticateContext.sessionTokenInCookie!, authenticateContext);\n if (errors) {\n throw errors[0];\n }\n\n const signedInRequestState = signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n sessionClaims: data,\n headers: new Headers(),\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n token: authenticateContext.sessionTokenInCookie!,\n });\n\n // Check for cross-origin requests from satellite domains to primary domain\n const shouldForceHandshakeForCrossDomain =\n !authenticateContext.isSatellite && // We're on primary\n authenticateContext.secFetchDest === 'document' && // Document navigation\n authenticateContext.isCrossOriginReferrer() && // Came from different domain\n !authenticateContext.isKnownClerkReferrer() && // Not from Clerk accounts portal or FAPI\n authenticateContext.handshakeRedirectLoopCounter === 0; // Not in a redirect loop\n\n if (shouldForceHandshakeForCrossDomain) {\n return handleMaybeHandshakeStatus(\n authenticateContext,\n AuthErrorReason.PrimaryDomainCrossOriginSync,\n 'Cross-origin request from satellite domain requires handshake',\n );\n }\n\n const authObject = signedInRequestState.toAuth();\n // Org sync if necessary\n if (authObject.userId) {\n const handshakeRequestState = handleMaybeOrganizationSyncHandshake(authenticateContext, authObject);\n if (handshakeRequestState) {\n return handshakeRequestState;\n }\n }\n\n return signedInRequestState;\n } catch (err) {\n return handleSessionTokenError(err, 'cookie');\n }\n\n // Unreachable\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: AuthErrorReason.UnexpectedError,\n });\n }\n\n async function handleSessionTokenError(\n err: unknown,\n tokenCarrier: TokenCarrier,\n ): Promise<SignedInState | SignedOutState | HandshakeState> {\n if (!(err instanceof TokenVerificationError)) {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: AuthErrorReason.UnexpectedError,\n });\n }\n\n let refreshError: string | null;\n\n if (isRequestEligibleForRefresh(err, authenticateContext, request)) {\n const { data, error } = await attemptRefresh(authenticateContext);\n if (data) {\n return signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n sessionClaims: data.jwtPayload,\n headers: data.headers,\n token: data.sessionToken,\n });\n }\n\n // If there's any error, simply fallback to the handshake flow including the reason as a query parameter.\n if (error?.cause?.reason) {\n refreshError = error.cause.reason;\n } else {\n refreshError = RefreshTokenErrorReason.UnexpectedSDKError;\n }\n } else {\n if (request.method !== 'GET') {\n refreshError = RefreshTokenErrorReason.NonEligibleNonGet;\n } else if (!authenticateContext.refreshTokenInCookie) {\n refreshError = RefreshTokenErrorReason.NonEligibleNoCookie;\n } else {\n //refresh error is not applicable if token verification error is not 'session-token-expired'\n refreshError = null;\n }\n }\n\n err.tokenCarrier = tokenCarrier;\n\n const reasonToHandshake = [\n TokenVerificationErrorReason.TokenExpired,\n TokenVerificationErrorReason.TokenNotActiveYet,\n TokenVerificationErrorReason.TokenIatInTheFuture,\n ].includes(err.reason);\n\n if (reasonToHandshake) {\n return handleMaybeHandshakeStatus(\n authenticateContext,\n convertTokenVerificationErrorReasonToAuthErrorReason({ tokenError: err.reason, refreshError }),\n err.getFullMessage(),\n );\n }\n\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: err.reason,\n message: err.getFullMessage(),\n });\n }\n\n function handleMachineError(tokenType: MachineTokenType, err: unknown): UnauthenticatedState<MachineTokenType> {\n if (!(err instanceof MachineTokenVerificationError)) {\n return signedOut({\n tokenType,\n authenticateContext,\n reason: AuthErrorReason.UnexpectedError,\n });\n }\n\n return signedOut({\n tokenType,\n authenticateContext,\n reason: err.code,\n message: err.getFullMessage(),\n });\n }\n\n async function authenticateMachineRequestWithTokenInHeader() {\n const { tokenInHeader } = authenticateContext;\n // Use session token error handling if no token in header (default behavior)\n if (!tokenInHeader) {\n return handleSessionTokenError(new Error('Missing token in header'), 'header');\n }\n\n // Handle case where tokenType is any and the token is not a machine token\n if (!isMachineTokenByPrefix(tokenInHeader)) {\n return signedOut({\n tokenType: acceptsToken as TokenType,\n authenticateContext,\n reason: AuthErrorReason.TokenTypeMismatch,\n message: '',\n });\n }\n\n const parsedTokenType = getMachineTokenType(tokenInHeader);\n const mismatchState = checkTokenTypeMismatch(parsedTokenType, acceptsToken, authenticateContext);\n if (mismatchState) {\n return mismatchState;\n }\n\n const { data, tokenType, errors } = await verifyMachineAuthToken(tokenInHeader, authenticateContext);\n if (errors) {\n return handleMachineError(tokenType, errors[0]);\n }\n return signedIn({\n tokenType,\n authenticateContext,\n machineData: data,\n token: tokenInHeader,\n });\n }\n\n async function authenticateAnyRequestWithTokenInHeader() {\n const { tokenInHeader } = authenticateContext;\n // Use session token error handling if no token in header (default behavior)\n if (!tokenInHeader) {\n return handleSessionTokenError(new Error('Missing token in header'), 'header');\n }\n\n // Handle as a machine token\n if (isMachineTokenByPrefix(tokenInHeader)) {\n const parsedTokenType = getMachineTokenType(tokenInHeader);\n const mismatchState = checkTokenTypeMismatch(parsedTokenType, acceptsToken, authenticateContext);\n if (mismatchState) {\n return mismatchState;\n }\n\n const { data, tokenType, errors } = await verifyMachineAuthToken(tokenInHeader, authenticateContext);\n if (errors) {\n return handleMachineError(tokenType, errors[0]);\n }\n\n return signedIn({\n tokenType,\n authenticateContext,\n machineData: data,\n token: tokenInHeader,\n });\n }\n\n // Handle as a regular session token\n const { data, errors } = await verifyToken(tokenInHeader, authenticateContext);\n if (errors) {\n return handleSessionTokenError(errors[0], 'header');\n }\n\n return signedIn({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n sessionClaims: data,\n token: tokenInHeader,\n });\n }\n\n // If acceptsToken is an array, early check if the token is in the accepted array\n // to avoid unnecessary verification calls\n if (Array.isArray(acceptsToken)) {\n if (!isTokenTypeInAcceptedArray(acceptsToken, authenticateContext)) {\n return signedOutInvalidToken();\n }\n }\n\n if (authenticateContext.tokenInHeader) {\n if (acceptsToken === 'any') {\n return authenticateAnyRequestWithTokenInHeader();\n }\n if (acceptsToken === TokenType.SessionToken) {\n return authenticateRequestWithTokenInHeader();\n }\n return authenticateMachineRequestWithTokenInHeader();\n }\n\n // Machine requests cannot have the token in the cookie, it must be in header.\n if (\n acceptsToken === TokenType.OAuthToken ||\n acceptsToken === TokenType.ApiKey ||\n acceptsToken === TokenType.M2MToken\n ) {\n return signedOut({\n tokenType: acceptsToken,\n authenticateContext,\n reason: 'No token in header',\n });\n }\n\n return authenticateRequestWithTokenInCookie();\n}) as AuthenticateRequest;\n\n/**\n * @internal\n */\nexport const debugRequestState = (params: RequestState) => {\n const { isSignedIn, isAuthenticated, proxyUrl, reason, message, publishableKey, isSatellite, domain } = params;\n return { isSignedIn, isAuthenticated, proxyUrl, reason, message, publishableKey, isSatellite, domain };\n};\n\nconst convertTokenVerificationErrorReasonToAuthErrorReason = ({\n tokenError,\n refreshError,\n}: {\n tokenError: TokenVerificationErrorReason;\n refreshError: string | null;\n}): string => {\n switch (tokenError) {\n case TokenVerificationErrorReason.TokenExpired:\n return `${AuthErrorReason.SessionTokenExpired}-refresh-${refreshError}`;\n case TokenVerificationErrorReason.TokenNotActiveYet:\n return AuthErrorReason.SessionTokenNBF;\n case TokenVerificationErrorReason.TokenIatInTheFuture:\n return AuthErrorReason.SessionTokenIatInTheFuture;\n default:\n return AuthErrorReason.UnexpectedError;\n }\n};\n","import type { ApiClient } from '../api';\nimport { mergePreDefinedOptions } from '../util/mergePreDefinedOptions';\nimport type { AuthenticateRequest } from './request';\nimport { authenticateRequest as authenticateRequestOriginal, debugRequestState } from './request';\nimport type { AuthenticateRequestOptions } from './types';\n\ntype RunTimeOptions = Omit<AuthenticateRequestOptions, 'apiUrl' | 'apiVersion'>;\ntype BuildTimeOptions = Partial<\n Pick<\n AuthenticateRequestOptions,\n | 'apiUrl'\n | 'apiVersion'\n | 'audience'\n | 'domain'\n | 'isSatellite'\n | 'jwtKey'\n | 'proxyUrl'\n | 'publishableKey'\n | 'secretKey'\n | 'machineSecretKey'\n >\n>;\n\nconst defaultOptions = {\n secretKey: '',\n machineSecretKey: '',\n jwtKey: '',\n apiUrl: undefined,\n apiVersion: undefined,\n proxyUrl: '',\n publishableKey: '',\n isSatellite: false,\n domain: '',\n audience: '',\n} satisfies BuildTimeOptions;\n\n/**\n * @internal\n */\nexport type CreateAuthenticateRequestOptions = {\n options: BuildTimeOptions;\n apiClient: ApiClient;\n};\n\n/**\n * @internal\n */\nexport function createAuthenticateRequest(params: CreateAuthenticateRequestOptions) {\n const buildTimeOptions = mergePreDefinedOptions(defaultOptions, params.options);\n const apiClient = params.apiClient;\n\n const authenticateRequest: AuthenticateRequest = (request: Request, options: RunTimeOptions = {}) => {\n const { apiUrl, apiVersion } = buildTimeOptions;\n const runTimeOptions = mergePreDefinedOptions(buildTimeOptions, options);\n return authenticateRequestOriginal(request, {\n ...options,\n ...runTimeOptions,\n // We should add all the omitted props from options here (eg apiUrl / apiVersion)\n // to avoid runtime options override them.\n apiUrl,\n apiVersion,\n apiClient,\n });\n };\n\n return {\n authenticateRequest,\n debugRequestState,\n };\n}\n","import type { CreateBackendApiOptions, Organization, Session, User } from '../api';\nimport { createBackendApiClient } from '../api';\nimport type { AuthObject, SignedInAuthObject, SignedOutAuthObject } from '../tokens/authObjects';\n\ntype DecorateAuthWithResourcesOptions = {\n loadSession?: boolean;\n loadUser?: boolean;\n loadOrganization?: boolean;\n};\n\ntype WithResources<T> = T & {\n session?: Session | null;\n user?: User | null;\n organization?: Organization | null;\n};\n\n/**\n * @internal\n */\nexport const decorateObjectWithResources = async <T extends object>(\n obj: T,\n authObj: AuthObject,\n opts: CreateBackendApiOptions & DecorateAuthWithResourcesOptions,\n): Promise<WithResources<T>> => {\n const { loadSession, loadUser, loadOrganization } = opts || {};\n const { userId, sessionId, orgId } = authObj as SignedInAuthObject | SignedOutAuthObject;\n\n const { sessions, users, organizations } = createBackendApiClient({ ...opts });\n\n const [sessionResp, userResp, organizationResp] = await Promise.all([\n loadSession && sessionId ? sessions.getSession(sessionId) : Promise.resolve(undefined),\n loadUser && userId ? users.getUser(userId) : Promise.resolve(undefined),\n loadOrganization && orgId ? organizations.getOrganization({ organizationId: orgId }) : Promise.resolve(undefined),\n ]);\n\n const resources = stripPrivateDataFromObject({\n session: sessionResp,\n user: userResp,\n organization: organizationResp,\n });\n return Object.assign(obj, resources);\n};\n\n/**\n * @internal\n */\nexport function stripPrivateDataFromObject<T extends WithResources<object>>(authObject: T): T {\n const user = authObject.user ? { ...authObject.user } : authObject.user;\n const organization = authObject.organization ? { ...authObject.organization } : authObject.organization;\n prunePrivateMetadata(user);\n prunePrivateMetadata(organization);\n return { ...authObject, user, organization };\n}\n\nfunction prunePrivateMetadata(resource?: { private_metadata: any } | { privateMetadata: any } | null) {\n // Delete sensitive private metadata from resource before rendering in SSR\n if (resource) {\n if ('privateMetadata' in resource) {\n delete resource['privateMetadata'];\n }\n if ('private_metadata' in resource) {\n delete resource['private_metadata'];\n }\n }\n\n return resource;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,UAAU;AAChB,IAAM,cAAc;AAEpB,IAAM,aAAa,GAAG,gBAAY,IAAI,gCAAe;AACrD,IAAM,oCAAoC,IAAI;AAC9C,IAAM,yBAAyB;AAEtC,IAAM,aAAa;AAAA,EACjB,WAAW;AAAA,EACX,eAAe;AAAA,EACf,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,UAAU;AACZ;AAEA,IAAM,UAAU;AAAA,EACd,SAAS;AAAA,EACT,SAAS;AAAA,EACT,WAAW;AAAA,EACX,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,gBAAgB;AAClB;AAEA,IAAM,kBAAkB;AAAA,EACtB,aAAa;AAAA,EACb,iBAAiB;AAAA,EACjB,kBAAkB;AAAA;AAAA,EAElB,YAAY,QAAQ;AAAA,EACpB,WAAW,QAAQ;AAAA,EACnB,eAAe;AAAA,EACf,kBAAkB;AAAA,EAClB,iBAAiB;AAAA,EACjB,gBAAgB,QAAQ;AAAA,EACxB,iBAAiB;AACnB;AAEA,IAAM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ACrB,yBAAyB;AAAA,EACzB,aAAa;AAAA,EACb,SAAS;AACX;;;ACtEO,IAAM,cAAN,MAAM,aAAY;AAAA,EACvB,YACW,IACA,MACA,QACA,UACA,kBACA,kBACA,kBACA,WACA,WACT;AATS;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA,EACR;AAAA,EAEH,OAAO,SAAS,MAAoC;AAClD,WAAO,IAAI;AAAA,MACT,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,IACP;AAAA,EACF;AACF;;;ACvBO,IAAM,WAAN,MAAM,UAAS;AAAA,EACpB,YACW,IACA,SACA,QACA,QACA,SACA,kBACA,SACA,YACA,WACA,WACA,OACT;AAXS;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA,EACR;AAAA,EAEH,OAAO,SAAS,MAA8B;AAC5C,WAAO,IAAI;AAAA,MACT,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,IACP;AAAA,EACF;AACF;;;AC9BO,IAAM,UAAN,MAAM,SAAQ;AAAA,EACnB,YACW,IACA,MACA,YACA,WACA,WACA,gBACA,iBACA,WACT;AARS;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA,EACR;AAAA,EAEH,OAAO,SAAS,MAA4B;AAC1C,WAAO,IAAI;AAAA,MACT,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK,gBAAgB;AAAA,QACnB,OACE,IAAI;AAAA,UACF,EAAE;AAAA,UACF,EAAE;AAAA,UACF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EACF;AAEA,SAAO;AACT;;;AjHZA,kCAAiE;","names":["Headers","import_keys","crypto","import_buildAccountsBaseUrl","import_url","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","import_error","match","convertCase","Cookies","data","Cookies","sessionId","jwk","import_error","authenticateContext","refreshToken","data","errors","authenticateRequest"]}
|