@clerk/backend 3.11.7 → 3.11.8-canary.v20260716200053

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../node_modules/.pnpm/cookie@1.1.1/node_modules/cookie/src/index.ts","../src/constants.ts","../src/createRedirect.ts","../src/util/mergePreDefinedOptions.ts","../src/tokens/request.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/AgentTaskApi.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/EmailApi.ts","../src/api/endpoints/EnterpriseConnectionApi.ts","../src/api/endpoints/IdPOAuthAccessTokenApi.ts","../src/api/endpoints/InstanceApi.ts","../src/api/endpoints/InvitationApi.ts","../src/api/endpoints/MachineApi.ts","../src/api/resources/IdPOAuthAccessToken.ts","../src/api/resources/M2MToken.ts","../src/tokens/keys.ts","../src/tokens/machine.ts","../src/jwt/verifyMachineJwt.ts","../src/api/endpoints/M2MTokenApi.ts","../src/api/endpoints/JwksApi.ts","../src/api/endpoints/JwtTemplatesApi.ts","../src/api/endpoints/OrganizationApi.ts","../src/api/endpoints/OrganizationPermissionApi.ts","../src/api/endpoints/OrganizationRoleApi.ts","../src/api/endpoints/OAuthApplicationsApi.ts","../src/api/endpoints/PhoneNumberApi.ts","../src/api/endpoints/ProxyCheckApi.ts","../src/api/endpoints/RedirectUrlApi.ts","../src/api/endpoints/RoleSetApi.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/AgentTask.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/EnterpriseAccount.ts","../src/api/resources/EnterpriseConnection.ts","../src/api/resources/ExternalAccount.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/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/Permission.ts","../src/api/resources/PhoneNumber.ts","../src/api/resources/ProxyCheck.ts","../src/api/resources/RedirectUrl.ts","../src/api/resources/Role.ts","../src/api/resources/RoleSet.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/authStatus.ts","../src/tokens/clerkRequest.ts","../src/tokens/clerkUrl.ts","../src/tokens/cookie.ts","../src/tokens/verify.ts","../src/tokens/handshake.ts","../src/tokens/organizationMatcher.ts","../src/tokens/factory.ts","../src/util/decorateObjectWithResources.ts","../src/internal.ts"],"sourcesContent":["/**\n * RegExp to match cookie-name in RFC 6265 sec 4.1.1\n * This refers out to the obsoleted definition of token in RFC 2616 sec 2.2\n * which has been replaced by the token definition in RFC 7230 appendix B.\n *\n * cookie-name = token\n * token = 1*tchar\n * tchar = \"!\" / \"#\" / \"$\" / \"%\" / \"&\" / \"'\" /\n * \"*\" / \"+\" / \"-\" / \".\" / \"^\" / \"_\" /\n * \"`\" / \"|\" / \"~\" / DIGIT / ALPHA\n *\n * Note: Allowing more characters - https://github.com/jshttp/cookie/issues/191\n * Allow same range as cookie value, except `=`, which delimits end of name.\n */\nconst cookieNameRegExp = /^[\\u0021-\\u003A\\u003C\\u003E-\\u007E]+$/;\n\n/**\n * RegExp to match cookie-value in RFC 6265 sec 4.1.1\n *\n * cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )\n * cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E\n * ; US-ASCII characters excluding CTLs,\n * ; whitespace DQUOTE, comma, semicolon,\n * ; and backslash\n *\n * Allowing more characters: https://github.com/jshttp/cookie/issues/191\n * Comma, backslash, and DQUOTE are not part of the parsing algorithm.\n */\nconst cookieValueRegExp = /^[\\u0021-\\u003A\\u003C-\\u007E]*$/;\n\n/**\n * RegExp to match domain-value in RFC 6265 sec 4.1.1\n *\n * domain-value = <subdomain>\n * ; defined in [RFC1034], Section 3.5, as\n * ; enhanced by [RFC1123], Section 2.1\n * <subdomain> = <label> | <subdomain> \".\" <label>\n * <label> = <let-dig> [ [ <ldh-str> ] <let-dig> ]\n * Labels must be 63 characters or less.\n * 'let-dig' not 'letter' in the first char, per RFC1123\n * <ldh-str> = <let-dig-hyp> | <let-dig-hyp> <ldh-str>\n * <let-dig-hyp> = <let-dig> | \"-\"\n * <let-dig> = <letter> | <digit>\n * <letter> = any one of the 52 alphabetic characters A through Z in\n * upper case and a through z in lower case\n * <digit> = any one of the ten digits 0 through 9\n *\n * Keep support for leading dot: https://github.com/jshttp/cookie/issues/173\n *\n * > (Note that a leading %x2E (\".\"), if present, is ignored even though that\n * character is not permitted, but a trailing %x2E (\".\"), if present, will\n * cause the user agent to ignore the attribute.)\n */\nconst domainValueRegExp =\n /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i;\n\n/**\n * RegExp to match path-value in RFC 6265 sec 4.1.1\n *\n * path-value = <any CHAR except CTLs or \";\">\n * CHAR = %x01-7F\n * ; defined in RFC 5234 appendix B.1\n */\nconst pathValueRegExp = /^[\\u0020-\\u003A\\u003D-\\u007E]*$/;\n\n/**\n * RegExp to match max-age-value in RFC 6265 sec 5.6.2\n */\nconst maxAgeRegExp = /^-?\\d+$/;\n\nconst __toString = Object.prototype.toString;\n\nconst NullObject = /* @__PURE__ */ (() => {\n const C = function () {};\n C.prototype = Object.create(null);\n return C;\n})() as unknown as { new (): any };\n\n/**\n * Parse options.\n */\nexport interface ParseOptions {\n /**\n * Specifies a function that will be used to decode a [cookie-value](https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1).\n * Since the value of a cookie has a limited character set (and must be a simple string), this function can be used to decode\n * a previously-encoded cookie value into a JavaScript string.\n *\n * The default function is the global `decodeURIComponent`, wrapped in a `try..catch`. If an error\n * is thrown it will return the cookie's original value. If you provide your own encode/decode\n * scheme you must ensure errors are appropriately handled.\n *\n * @default decode\n */\n decode?: (str: string) => string | undefined;\n}\n\n/**\n * Cookies object.\n */\nexport type Cookies = Record<string, string | undefined>;\n\n/**\n * Parse a `Cookie` header.\n *\n * Parse the given cookie header string into an object\n * The object has the various cookies as keys(names) => values\n */\nexport function parseCookie(str: string, options?: ParseOptions): Cookies {\n const obj: Cookies = new NullObject();\n const len = str.length;\n // RFC 6265 sec 4.1.1, RFC 2616 2.2 defines a cookie name consists of one char minimum, plus '='.\n if (len < 2) return obj;\n\n const dec = options?.decode || decode;\n let index = 0;\n\n do {\n const eqIdx = eqIndex(str, index, len);\n if (eqIdx === -1) break; // No more cookie pairs.\n\n const endIdx = endIndex(str, index, len);\n\n if (eqIdx > endIdx) {\n // backtrack on prior semicolon\n index = str.lastIndexOf(\";\", eqIdx - 1) + 1;\n continue;\n }\n\n const key = valueSlice(str, index, eqIdx);\n\n // only assign once\n if (obj[key] === undefined) {\n obj[key] = dec(valueSlice(str, eqIdx + 1, endIdx));\n }\n\n index = endIdx + 1;\n } while (index < len);\n\n return obj;\n}\n\nexport interface StringifyOptions {\n /**\n * Specifies a function that will be used to encode a [cookie-value](https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1).\n * Since value of a cookie has a limited character set (and must be a simple string), this function can be used to encode\n * a value into a string suited for a cookie's value, and should mirror `decode` when parsing.\n *\n * @default encodeURIComponent\n */\n encode?: (str: string) => string;\n}\n\n/**\n * Stringifies an object into an HTTP `Cookie` header.\n */\nexport function stringifyCookie(\n cookie: Cookies,\n options?: StringifyOptions,\n): string {\n const enc = options?.encode || encodeURIComponent;\n const cookieStrings: string[] = [];\n\n for (const name of Object.keys(cookie)) {\n const val = cookie[name];\n if (val === undefined) continue;\n\n if (!cookieNameRegExp.test(name)) {\n throw new TypeError(`cookie name is invalid: ${name}`);\n }\n\n const value = enc(val);\n\n if (!cookieValueRegExp.test(value)) {\n throw new TypeError(`cookie val is invalid: ${val}`);\n }\n\n cookieStrings.push(`${name}=${value}`);\n }\n\n return cookieStrings.join(\"; \");\n}\n\n/**\n * Set-Cookie object.\n */\nexport interface SetCookie {\n /**\n * Specifies the name of the cookie.\n */\n name: string;\n /**\n * Specifies the string to be the value for the cookie.\n */\n value: string | undefined;\n /**\n * Specifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.2).\n *\n * The [cookie storage model specification](https://tools.ietf.org/html/rfc6265#section-5.3) states that if both `expires` and\n * `maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this,\n * so if both are set, they should point to the same date and time.\n */\n maxAge?: number;\n /**\n * Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.1).\n * When no expiration is set, clients consider this a \"non-persistent cookie\" and delete it when the current session is over.\n *\n * The [cookie storage model specification](https://tools.ietf.org/html/rfc6265#section-5.3) states that if both `expires` and\n * `maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this,\n * so if both are set, they should point to the same date and time.\n */\n expires?: Date;\n /**\n * Specifies the value for the [`Domain` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.3).\n * When no domain is set, clients consider the cookie to apply to the current domain only.\n */\n domain?: string;\n /**\n * Specifies the value for the [`Path` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.4).\n * When no path is set, the path is considered the [\"default path\"](https://tools.ietf.org/html/rfc6265#section-5.1.4).\n */\n path?: string;\n /**\n * Enables the [`HttpOnly` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.6).\n * When enabled, clients will not allow client-side JavaScript to see the cookie in `document.cookie`.\n */\n httpOnly?: boolean;\n /**\n * Enables the [`Secure` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.5).\n * When enabled, clients will only send the cookie back if the browser has an HTTPS connection.\n */\n secure?: boolean;\n /**\n * Enables the [`Partitioned` `Set-Cookie` attribute](https://tools.ietf.org/html/draft-cutler-httpbis-partitioned-cookies/).\n * When enabled, clients will only send the cookie back when the current domain _and_ top-level domain matches.\n *\n * This is an attribute that has not yet been fully standardized, and may change in the future.\n * This also means clients may ignore this attribute until they understand it. More information\n * about can be found in [the proposal](https://github.com/privacycg/CHIPS).\n */\n partitioned?: boolean;\n /**\n * Specifies the value for the [`Priority` `Set-Cookie` attribute](https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1).\n *\n * - `'low'` will set the `Priority` attribute to `Low`.\n * - `'medium'` will set the `Priority` attribute to `Medium`, the default priority when not set.\n * - `'high'` will set the `Priority` attribute to `High`.\n *\n * More information about priority levels can be found in [the specification](https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1).\n */\n priority?: \"low\" | \"medium\" | \"high\";\n /**\n * Specifies the value for the [`SameSite` `Set-Cookie` attribute](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-09#section-5.4.7).\n *\n * - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement.\n * - `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement.\n * - `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie.\n * - `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement.\n *\n * More information about enforcement levels can be found in [the specification](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-09#section-5.4.7).\n */\n sameSite?: boolean | \"lax\" | \"strict\" | \"none\";\n}\n\n/**\n * Backward compatibility serialize options.\n */\nexport type SerializeOptions = StringifyOptions &\n Omit<SetCookie, \"name\" | \"value\">;\n\n/**\n * Serialize data into a cookie header.\n *\n * Serialize a name value pair into a cookie string suitable for\n * http headers. An optional options object specifies cookie parameters.\n *\n * serialize('foo', 'bar', { httpOnly: true })\n * => \"foo=bar; httpOnly\"\n */\nexport function stringifySetCookie(\n cookie: SetCookie,\n options?: StringifyOptions,\n): string;\nexport function stringifySetCookie(\n name: string,\n val: string,\n options?: SerializeOptions,\n): string;\nexport function stringifySetCookie(\n _name: string | SetCookie,\n _val?: string | StringifyOptions,\n _opts?: SerializeOptions,\n): string {\n const cookie =\n typeof _name === \"object\"\n ? _name\n : { ..._opts, name: _name, value: String(_val) };\n const options = typeof _val === \"object\" ? _val : _opts;\n const enc = options?.encode || encodeURIComponent;\n\n if (!cookieNameRegExp.test(cookie.name)) {\n throw new TypeError(`argument name is invalid: ${cookie.name}`);\n }\n\n const value = cookie.value ? enc(cookie.value) : \"\";\n\n if (!cookieValueRegExp.test(value)) {\n throw new TypeError(`argument val is invalid: ${cookie.value}`);\n }\n\n let str = cookie.name + \"=\" + value;\n\n if (cookie.maxAge !== undefined) {\n if (!Number.isInteger(cookie.maxAge)) {\n throw new TypeError(`option maxAge is invalid: ${cookie.maxAge}`);\n }\n\n str += \"; Max-Age=\" + cookie.maxAge;\n }\n\n if (cookie.domain) {\n if (!domainValueRegExp.test(cookie.domain)) {\n throw new TypeError(`option domain is invalid: ${cookie.domain}`);\n }\n\n str += \"; Domain=\" + cookie.domain;\n }\n\n if (cookie.path) {\n if (!pathValueRegExp.test(cookie.path)) {\n throw new TypeError(`option path is invalid: ${cookie.path}`);\n }\n\n str += \"; Path=\" + cookie.path;\n }\n\n if (cookie.expires) {\n if (!isDate(cookie.expires) || !Number.isFinite(cookie.expires.valueOf())) {\n throw new TypeError(`option expires is invalid: ${cookie.expires}`);\n }\n\n str += \"; Expires=\" + cookie.expires.toUTCString();\n }\n\n if (cookie.httpOnly) {\n str += \"; HttpOnly\";\n }\n\n if (cookie.secure) {\n str += \"; Secure\";\n }\n\n if (cookie.partitioned) {\n str += \"; Partitioned\";\n }\n\n if (cookie.priority) {\n const priority =\n typeof cookie.priority === \"string\"\n ? cookie.priority.toLowerCase()\n : undefined;\n switch (priority) {\n case \"low\":\n str += \"; Priority=Low\";\n break;\n case \"medium\":\n str += \"; Priority=Medium\";\n break;\n case \"high\":\n str += \"; Priority=High\";\n break;\n default:\n throw new TypeError(`option priority is invalid: ${cookie.priority}`);\n }\n }\n\n if (cookie.sameSite) {\n const sameSite =\n typeof cookie.sameSite === \"string\"\n ? cookie.sameSite.toLowerCase()\n : cookie.sameSite;\n switch (sameSite) {\n case true:\n case \"strict\":\n str += \"; SameSite=Strict\";\n break;\n case \"lax\":\n str += \"; SameSite=Lax\";\n break;\n case \"none\":\n str += \"; SameSite=None\";\n break;\n default:\n throw new TypeError(`option sameSite is invalid: ${cookie.sameSite}`);\n }\n }\n\n return str;\n}\n\n/**\n * Deserialize a `Set-Cookie` header into an object.\n *\n * deserialize('foo=bar; httpOnly')\n * => { name: 'foo', value: 'bar', httpOnly: true }\n */\nexport function parseSetCookie(str: string, options?: ParseOptions): SetCookie {\n const dec = options?.decode || decode;\n const len = str.length;\n const endIdx = endIndex(str, 0, len);\n const eqIdx = eqIndex(str, 0, endIdx);\n const setCookie: SetCookie =\n eqIdx === -1\n ? { name: \"\", value: dec(valueSlice(str, 0, endIdx)) }\n : {\n name: valueSlice(str, 0, eqIdx),\n value: dec(valueSlice(str, eqIdx + 1, endIdx)),\n };\n\n let index = endIdx + 1;\n while (index < len) {\n const endIdx = endIndex(str, index, len);\n const eqIdx = eqIndex(str, index, endIdx);\n const attr =\n eqIdx === -1\n ? valueSlice(str, index, endIdx)\n : valueSlice(str, index, eqIdx);\n const val = eqIdx === -1 ? undefined : valueSlice(str, eqIdx + 1, endIdx);\n\n switch (attr.toLowerCase()) {\n case \"httponly\":\n setCookie.httpOnly = true;\n break;\n case \"secure\":\n setCookie.secure = true;\n break;\n case \"partitioned\":\n setCookie.partitioned = true;\n break;\n case \"domain\":\n setCookie.domain = val;\n break;\n case \"path\":\n setCookie.path = val;\n break;\n case \"max-age\":\n if (val && maxAgeRegExp.test(val)) setCookie.maxAge = Number(val);\n break;\n case \"expires\":\n if (!val) break;\n const date = new Date(val);\n if (Number.isFinite(date.valueOf())) setCookie.expires = date;\n break;\n case \"priority\":\n if (!val) break;\n const priority = val.toLowerCase();\n if (\n priority === \"low\" ||\n priority === \"medium\" ||\n priority === \"high\"\n ) {\n setCookie.priority = priority;\n }\n break;\n case \"samesite\":\n if (!val) break;\n const sameSite = val.toLowerCase();\n if (\n sameSite === \"lax\" ||\n sameSite === \"strict\" ||\n sameSite === \"none\"\n ) {\n setCookie.sameSite = sameSite;\n }\n break;\n }\n\n index = endIdx + 1;\n }\n\n return setCookie;\n}\n\n/**\n * Find the `;` character between `min` and `len` in str.\n */\nfunction endIndex(str: string, min: number, len: number) {\n const index = str.indexOf(\";\", min);\n return index === -1 ? len : index;\n}\n\n/**\n * Find the `=` character between `min` and `max` in str.\n */\nfunction eqIndex(str: string, min: number, max: number) {\n const index = str.indexOf(\"=\", min);\n return index < max ? index : -1;\n}\n\n/**\n * Slice out a value between startPod to max.\n */\nfunction valueSlice(str: string, min: number, max: number) {\n let start = min;\n let end = max;\n\n do {\n const code = str.charCodeAt(start);\n if (code !== 0x20 /* */ && code !== 0x09 /* \\t */) break;\n } while (++start < end);\n\n while (end > start) {\n const code = str.charCodeAt(end - 1);\n if (code !== 0x20 /* */ && code !== 0x09 /* \\t */) break;\n end--;\n }\n\n return str.slice(start, end);\n}\n\n/**\n * URL-decode string value. Optimized to skip native call when no %.\n */\nfunction decode(str: string): string {\n if (str.indexOf(\"%\") === -1) return str;\n\n try {\n return decodeURIComponent(str);\n } catch (e) {\n return str;\n }\n}\n\n/**\n * Determine if value is a Date.\n */\nfunction isDate(val: any): val is Date {\n return __toString.call(val) === \"[object Date]\";\n}\n\n/**\n * Backward compatibility exports.\n */\nexport { stringifySetCookie as serialize, parseCookie as parse };\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 = '2026-05-12';\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 Session: '__session',\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 * Sync status values for the __clerk_synced query parameter.\n * Used to coordinate satellite domain authentication flows.\n */\nexport const ClerkSyncStatus = {\n /** Not synced - satellite needs handshake after returning from primary sign-in */\n NeedsSync: 'false',\n /** Sync completed - prevents re-sync loop after handshake completes */\n Completed: 'true',\n} as const;\n\n/**\n * @internal\n */\nexport const constants = {\n Attributes,\n Cookies,\n Headers,\n ContentTypes,\n QueryParameters,\n ClerkSyncStatus,\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 { ClerkSyncStatus, 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 _isSatellite?: boolean,\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 // For satellite apps redirecting to primary sign-in, add sync trigger to returnBackUrl\n // This ensures handshake is triggered when the user returns after signing in\n if (isCrossOriginRedirect && _isSatellite) {\n returnBackUrl.searchParams.set(constants.QueryParameters.ClerkSynced, ClerkSyncStatus.NeedsSync);\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 isSatellite?: boolean;\n}) => {\n redirectToSignIn: RedirectFun<ReturnType>;\n redirectToSignUp: RedirectFun<ReturnType>;\n};\n\nexport const createRedirect: CreateRedirect = params => {\n const { publishableKey, redirectAdapter, signInUrl, signUpUrl, baseUrl, sessionStatus, isSatellite } = 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, isSatellite),\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(\n buildUrl(baseUrl, targetUrl, returnBackUrl, isDevelopment ? params.devBrowserToken : null, isSatellite),\n );\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(\n buildUrl(baseUrl, targetUrl, returnBackUrl, isDevelopment ? params.devBrowserToken : null, isSatellite),\n );\n };\n\n return { redirectToSignUp, redirectToSignIn };\n};\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","import { logger } from '@clerk/shared/logger';\nimport 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, isMachineJwt, isMachineToken, 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 (isMachineToken(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 = getHandshakeRedirectLoopMessage(reason);\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 function getHandshakeRedirectLoopMessage(reason: string): string {\n if (reason === AuthErrorReason.SatelliteCookieNeedsSyncing) {\n return `Clerk: Satellite-domain authentication resulted in an infinite redirect loop. Check that this request is using a configured primary or satellite domain for the production instance. For preview deployments, use a development/staging Clerk instance or a supported configured preview-domain setup.`;\n }\n return `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 }\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 // Reject machine JWTs (OAuth or M2M) that may appear in headers when expecting session tokens.\n // These are valid Clerk-signed JWTs and will pass verify() verification,\n // but should not be accepted as session tokens.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n if (isMachineJwt(tokenInHeader!)) {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: AuthErrorReason.TokenTypeMismatch,\n message: '',\n });\n }\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 &&\n authenticateContext.secFetchDest === 'document' &&\n authenticateContext.method === 'GET';\n\n /**\n * Begin multi-domain sync flows\n *\n * Sync status values (__clerk_synced query param):\n * - 'false' (NeedsSync): Trigger sync - satellite returning from primary sign-in\n * - 'true' (Completed): Sync done - prevents re-sync loop\n *\n * With satelliteAutoSync=false or unset (Core 3 default):\n * - Skip handshake on first visit if no cookies exist (return signedOut immediately)\n * - Trigger handshake when __clerk_synced=false is present (post sign-in redirect)\n * - Allow normal token verification flow when cookies exist (enables refresh)\n */\n\n // Check sync status param (__clerk_synced=false triggers sync, __clerk_synced=true means completed)\n const syncedParam = authenticateContext.clerkUrl.searchParams.get(constants.QueryParameters.ClerkSynced);\n const needsSync = syncedParam === constants.ClerkSyncStatus.NeedsSync;\n const syncCompleted = syncedParam === constants.ClerkSyncStatus.Completed;\n\n // Check if cookies exist (session token or active client UAT)\n const hasCookies = hasSessionToken || hasActiveClient;\n\n // Determine if we should skip handshake for satellites with no cookies\n // satelliteAutoSync defaults to false (Core 3), so we skip unless explicitly set to true\n const shouldSkipSatelliteHandshake = authenticateContext.satelliteAutoSync !== true && !hasCookies && !needsSync;\n\n if (authenticateContext.instanceType === 'production' && isRequestEligibleForMultiDomainSync && !syncCompleted) {\n // With satelliteAutoSync=false: skip handshake if no cookies and no sync trigger\n if (shouldSkipSatelliteHandshake) {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: AuthErrorReason.SessionTokenAndUATMissing,\n });\n }\n\n // If cookies exist, fall through to normal token verification flow (enables refresh)\n // Only trigger handshake if no cookies exist (or sync was explicitly requested)\n if (!hasCookies || needsSync) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SatelliteCookieNeedsSyncing, '');\n }\n // Fall through to normal token verification flow when cookies exist\n }\n\n // Multi-domain development sync flow\n if (authenticateContext.instanceType === 'development' && isRequestEligibleForMultiDomainSync && !syncCompleted) {\n // With satelliteAutoSync=false: skip sync if no cookies and no sync trigger\n if (shouldSkipSatelliteHandshake) {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: AuthErrorReason.SessionTokenAndUATMissing,\n });\n }\n\n // If cookies exist, fall through to normal flow (enables refresh)\n if (!hasCookies || needsSync) {\n // initiate MD sync\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(\n authenticateContext,\n AuthErrorReason.SatelliteCookieNeedsSyncing,\n '',\n headers,\n );\n }\n // Fall through to normal token verification flow when cookies exist\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 // Use set (not append) to ensure completion status overwrites any existing NeedsSync value\n // This prevents sync loops when the redirect URL already contains __clerk_synced=false\n redirectBackToSatelliteUrl.searchParams.set(\n constants.QueryParameters.ClerkSynced,\n constants.ClerkSyncStatus.Completed,\n );\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 // Machine JWTs pass verifyToken() but must not be accepted as session tokens (mirrors header path).\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n if (isMachineJwt(authenticateContext.sessionTokenInCookie!)) {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: AuthErrorReason.TokenTypeMismatch,\n message: '',\n });\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 if (!data.azp) {\n // Warn once per process rather than per request: a single azp-less cookie\n // token is reused across every authenticated request until it refreshes,\n // so an unguarded console.warn floods production logs (see issue #8231).\n logger.warnOnce(\n 'Clerk: Session token from cookie is missing the azp claim. In a future version of Clerk, this token will be considered invalid. Please contact Clerk support if you see this warning.',\n );\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.method === 'GET' && // Only GET navigations (POST form submissions set sec-fetch-dest: document too)\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 (!isMachineToken(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 (isMachineToken(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' || Array.isArray(acceptsToken)) {\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 { 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 { getAutoProxyUrlFromEnvironment } from '@clerk/shared/proxy';\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 method: string;\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 * Gets 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 // Auto-detect proxy for supported platform deployments using environment\n // variables (e.g. VERCEL_TARGET_ENV, VERCEL_PROJECT_PRODUCTION_URL) instead\n // of request headers, which avoids X-Forwarded-Host spoofing concerns.\n const autoProxyPath = getAutoProxyUrlFromEnvironment({\n publishableKey: options.publishableKey ?? '',\n hasProxyUrl: !!options.proxyUrl,\n hasDomain: !!options.domain,\n });\n if (autoProxyPath) {\n options = { ...options, proxyUrl: `${clerkRequest.clerkUrl.origin}${autoProxyPath}` };\n }\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 // Resolve relative proxyUrl to absolute using the request's public origin.\n if (this.proxyUrl?.startsWith('/')) {\n this.proxyUrl = `${this.clerkUrl.origin}${this.proxyUrl}`;\n }\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 // If proxyUrl is a relative path (e.g. '/__clerk'), resolve it against the\n // request's public origin (derived from x-forwarded-* headers by ClerkRequest).\n // This lets SDKs pass just the path instead of duplicating forwarded-header parsing.\n let resolvedProxyUrl = options.proxyUrl;\n if (resolvedProxyUrl?.startsWith('/')) {\n resolvedProxyUrl = `${this.clerkRequest.clerkUrl.origin}${resolvedProxyUrl}`;\n }\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: resolvedProxyUrl,\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.method = this.clerkRequest.method;\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 // Session and machine tokens are live bearer credentials, so only ever expose a\n // short, non-reconstructable prefix here, the same way secretKey/jwtKey are handled\n // above. Otherwise enabling debug logging would write usable tokens to logs.\n // This also covers the bearer fields carried on AuthenticateContext, which is spread\n // wholesale into the debug payload by signedInAuthObject: the refresh token is the\n // most sensitive of these, and the dev-browser/handshake tokens are short-lived but\n // still credentials.\n res.sessionToken = (res.sessionToken || '').substring(0, 7);\n res.tokenInHeader = (res.tokenInHeader || '').substring(0, 7);\n res.sessionTokenInCookie = (res.sessionTokenInCookie || '').substring(0, 7);\n res.refreshTokenInCookie = (res.refreshTokenInCookie || '').substring(0, 7);\n res.devBrowserToken = (res.devBrowserToken || '').substring(0, 7);\n res.handshakeToken = (res.handshakeToken || '').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 - The 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 or generate a JWT using a specified template with 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');\nconst MAX_DECODES = 10;\n\ntype PathString = string | null | undefined;\n\nfunction isDotSegment(segment: string): boolean {\n let candidate = segment;\n for (let i = 0; i <= MAX_DECODES; i++) {\n // After decoding, check if any slash-separated part is a dot segment\n if (candidate.split(/[/\\\\]/).some(p => p === '.' || p === '..')) {\n return true;\n }\n if (i === MAX_DECODES) {\n throw new Error(`joinPaths: too many layers of encoding in ${segment}`);\n }\n try {\n const next = decodeURIComponent(candidate);\n if (next === candidate) {\n break;\n } // stable — no more encoding\n candidate = next;\n } catch {\n break;\n }\n }\n return false;\n}\n\nexport function joinPaths(...args: PathString[]): string {\n const result = args\n .filter(p => p)\n .join(SEPARATOR)\n .replace(MULTIPLE_SEPARATOR_REGEX, SEPARATOR);\n\n for (const segment of result.split(SEPARATOR)) {\n if (isDotSegment(segment)) {\n throw new Error(`joinPaths: \".\" and \"..\" path segments are not allowed (received \"${result}\")`);\n }\n }\n\n return result;\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 * The lifetime 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 { AgentTask } from '../resources/AgentTask';\nimport { AbstractAPI } from './AbstractApi';\n\n/** @generateWithEmptyComment */\nexport type CreateAgentTaskParams = {\n /** The user to create an Agent Task for. Provide either a `userId` or an `identifier` (e.g. an email address, phone number, or username). */\n onBehalfOf:\n | {\n /** The identifier of the user to create an Agent Task for. */\n identifier: string;\n userId?: never;\n }\n | {\n /** The ID of the user to create an Agent Task for. */\n userId: string;\n identifier?: never;\n };\n /** The permissions the Agent Task will have. Currently, `'*'` is the only supported value, which grants all permissions. */\n permissions: string;\n /** The name of the agent creating the task. Used to derive a stable `agent_id` for the Agent Task. */\n agentName: string;\n /** The description of the Agent Task to create. */\n taskDescription: string;\n /** The URL the user lands on after the Agent Task is accepted. In production instances, must be a valid absolute URL with an `https` scheme. In development instances, `http` is also permitted. The URL's domain must belong to one of the instance's associated domains (primary or satellite); otherwise, the redirect will be rejected when the task ticket is consumed. */\n redirectUrl: string;\n /** The maximum duration that the session created by the Agent Task should last. By default, the duration is `1800` (30 minutes). */\n sessionMaxDurationInSeconds?: number;\n};\n\nconst basePath = '/agents/tasks';\n\n/** @generateWithEmptyComment */\nexport class AgentTaskAPI extends AbstractAPI {\n /**\n * Creates an Agent Task that generates a URL which, when visited, creates a session for the specified user. This is useful for automated testing or agent-driven flows where full authentication isn't practical.\n * @returns The created [`AgentTask`](https://clerk.com/docs/reference/backend/types/backend-agent-task) object.\n */\n public async create(params: CreateAgentTaskParams) {\n return this.request<AgentTask>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n options: {\n deepSnakecaseBodyParamKeys: true,\n },\n });\n }\n\n /**\n * Revokes the given Agent Task.\n * @param agentTaskId - The ID of the Agent Task to revoke.\n * @returns The revoked [`AgentTask`](https://clerk.com/docs/reference/backend/types/backend-agent-task) object.\n */\n public async revoke(agentTaskId: string) {\n this.requireId(agentTaskId);\n return this.request<Omit<AgentTask, 'url'>>({\n method: 'POST',\n path: joinPaths(basePath, agentTaskId, '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\ntype AccountlessApplicationParams = {\n requestHeaders?: Headers;\n source?: string;\n};\n\nexport class AccountlessApplicationAPI extends AbstractAPI {\n public async createAccountlessApplication(params?: AccountlessApplicationParams): Promise<AccountlessApplication> {\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 queryParams: {\n source: params?.source,\n },\n });\n }\n\n public async completeAccountlessApplicationOnboarding(\n params?: AccountlessApplicationParams,\n ): Promise<AccountlessApplication> {\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 queryParams: {\n source: params?.source,\n },\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\n/** @generateWithEmptyComment */\nexport type AllowlistIdentifierCreateParams = {\n /** The identifier to add to the allowlist. Can be an email address, a domain in wildcard email format (e.g. `*@example.com`), a phone number in international E.164 format (e.g. `+15555555555`), or a Web3 wallet address. */\n identifier: string;\n /** Whether to notify the user that their identifier has been added to the allowlist. Notifies the user if the `identifier` is an email address or phone number. */\n notify: boolean;\n};\n\n/** @generateWithEmptyComment */\nexport class AllowlistIdentifierAPI extends AbstractAPI {\n /**\n * Gets the list of allowlist identifiers for the instance. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`AllowlistIdentifier`](https://clerk.com/docs/reference/backend/types/backend-allowlist-identifier) objects and a `totalCount` property containing the total number of allowlist identifiers for the instance.\n */\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 /**\n * Creates a new allowlist identifier.\n * @returns The created [`AllowlistIdentifier`](https://clerk.com/docs/reference/backend/types/backend-allowlist-identifier) object.\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 /**\n * Deletes an allowlist identifier.\n * @param allowlistIdentifierId - The ID of the allowlist identifier to delete.\n * @returns The [`DeletedObject`](https://clerk.com/docs/reference/backend/types/deleted-object) object.\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 type { APIKey } from '../resources/APIKey';\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/api_keys';\n\n/** @generateWithEmptyComment */\nexport type GetAPIKeyListParams = ClerkPaginationRequest<{\n /** The user or Organization ID to query API keys by. */\n subject: string;\n /** Whether to include invalid API keys (revoked or expired). Defaults to `false`. */\n includeInvalid?: boolean;\n}>;\n\n/** @generateWithEmptyComment */\nexport type CreateAPIKeyParams = {\n /** A descriptive name for the API key (e.g., \"Production API Key\", \"Development Key\"). */\n name: string;\n /** The user or Organization ID to associate the API key with. */\n subject: string;\n /** The description of the API key. */\n description?: string | null;\n /** Custom claims to store additional information about the API key. */\n claims?: Record<string, any> | null;\n /** Scopes to limit the API key's access to specific resources. */\n scopes?: string[];\n /** The user ID of the user who created the API key. */\n createdBy?: string | null;\n /** The number of seconds until the API key expires. Defaults to `null` (never expires). */\n secondsUntilExpiration?: number | null;\n};\n\n/** @generateWithEmptyComment */\nexport type RevokeAPIKeyParams = {\n /** The ID of the API key to revoke. */\n apiKeyId: string;\n /** The reason for revoking the API key. Useful for your records. */\n revocationReason?: string | null;\n};\n\n/** @generateWithEmptyComment */\nexport type UpdateAPIKeyParams = {\n /** The ID of the API key to update. */\n apiKeyId: string;\n /** The user or Organization ID to associate the API key with. */\n subject: string;\n /** The description of the API key. */\n description?: string | null;\n /** Custom claims to store additional information about the API key. */\n claims?: Record<string, any> | null;\n /** Scopes to limit the API key's access to specific resources. */\n scopes?: string[];\n /** The number of seconds until the API key expires. Defaults to `null` (never expires). */\n secondsUntilExpiration?: number | null;\n};\n\n/** @generateWithEmptyComment */\nexport class APIKeysAPI extends AbstractAPI {\n /**\n * Gets a list of API keys for the given user or Organization. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`APIKey`](https://clerk.com/docs/reference/backend/types/backend-api-key) objects and a `totalCount` property containing the total number of API keys for the user or Organization.\n */\n async list(queryParams: GetAPIKeyListParams) {\n return this.request<PaginatedResourceResponse<APIKey[]>>({\n method: 'GET',\n path: basePath,\n queryParams,\n });\n }\n\n /**\n * Creates a new API key for the given user or Organization.\n * @returns The created [`APIKey`](https://clerk.com/docs/reference/backend/types/backend-api-key) object.\n */\n async create(params: CreateAPIKeyParams) {\n return this.request<APIKey>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n /**\n * Gets the given [`APIKey`](https://clerk.com/docs/reference/backend/types/backend-api-key) object.\n * @param apiKeyId - The ID of the API key to get.\n */\n async get(apiKeyId: string) {\n this.requireId(apiKeyId);\n\n return this.request<APIKey>({\n method: 'GET',\n path: joinPaths(basePath, apiKeyId),\n });\n }\n\n /**\n * Updates the given API key.\n * @returns The updated [`APIKey`](https://clerk.com/docs/reference/backend/types/backend-api-key) object.\n */\n async update(params: UpdateAPIKeyParams) {\n const { apiKeyId, ...bodyParams } = params;\n\n this.requireId(apiKeyId);\n\n return this.request<APIKey>({\n method: 'PATCH',\n path: joinPaths(basePath, apiKeyId),\n bodyParams,\n });\n }\n\n /**\n * Deletes the given API key.\n * @param apiKeyId - The ID of the API key to delete.\n * @returns The [`DeletedObject`](https://clerk.com/docs/reference/backend/types/deleted-object) object.\n */\n async delete(apiKeyId: string) {\n this.requireId(apiKeyId);\n\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, apiKeyId),\n });\n }\n\n /**\n * Revokes the given API key. This will immediately invalidate the API key and prevent it from being used to authenticate any future requests.\n * @returns The revoked [`APIKey`](https://clerk.com/docs/reference/backend/types/backend-api-key) object.\n */\n async revoke(params: RevokeAPIKeyParams) {\n const { apiKeyId, revocationReason = null } = params;\n\n this.requireId(apiKeyId);\n\n return this.request<APIKey>({\n method: 'POST',\n path: joinPaths(basePath, apiKeyId, 'revoke'),\n bodyParams: { revocationReason },\n });\n }\n\n /**\n * Gets the secret of the given API key.\n * @param apiKeyId - The ID of the API key to get the secret of.\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 /**\n * Verifies the given API key.\n * - If the API key is valid, the method returns the API key object with its properties.\n * - If the API key is invalid, revoked, or expired, the method will throw an error.\n * @param secret - The secret of the API key to verify.\n * @returns The verified [`APIKey`](https://clerk.com/docs/reference/backend/types/backend-api-key) object.\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","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\n/** @generateWithEmptyComment */\nexport class ClientAPI extends AbstractAPI {\n /**\n * @deprecated This method is deprecated and will be removed in a future version.\n */\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 /**\n * Gets the given [`Client`](https://clerk.com/docs/reference/backend/types/backend-client).\n * @param clientId - The ID of the client to get.\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 /**\n * Verifies the client in the given token.\n * @param token - The token to verify.\n * @returns The verified [`Client`](https://clerk.com/docs/reference/backend/types/backend-client).\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 /**\n * Retrieves the handshake payload for a given nonce. Used internally by Clerk's SDKs to resolve\n * session cookies during the handshake flow.\n *\n * @internal\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\n/** @generateWithEmptyComment */\nexport type AddDomainParams = {\n /**\n * The new domain name. For development instances, can contain the port, e.g. `myhostname:3000`. For production instances, must be a valid FQDN, e.g. `mysite.com`. Cannot contain protocol scheme.\n */\n name: string;\n /** Whether the new domain is a satellite domain. Only `true` is accepted at the moment. */\n is_satellite: boolean;\n /** The proxy URL for the domain. Applicable only to production instances. */\n proxy_url?: string | null;\n};\n\n/** @generateWithEmptyComment */\nexport type UpdateDomainParams = Partial<Pick<AddDomainParams, 'name' | 'proxy_url'>> & {\n /** The ID of the domain that will be updated. */\n domainId: string;\n /** Whether this is a domain for a secondary app, meaning that any subdomain provided is significant and will be stored as part of the domain. This is useful for supporting multiple apps (one primary and multiple secondaries) on the same root domain (eTLD+1). */\n is_secondary?: boolean | null;\n};\n\n/** @generateWithEmptyComment */\nexport class DomainAPI extends AbstractAPI {\n /**\n * Gets the list of domains for the instance. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`Domain`](https://clerk.com/docs/reference/backend/types/domain) objects and a `totalCount` property containing the total number of domains for the instance.\n */\n public async list() {\n return this.request<PaginatedResourceResponse<Domain[]>>({\n method: 'GET',\n path: basePath,\n });\n }\n\n /**\n * Adds a new domain to the instance. Useful in the case of multi-domain instances, allows adding [satellite domains](https://clerk.com/docs/guides/dashboard/dns-domains/satellite-domains) to an instance.\n * @returns The created [`Domain`](https://clerk.com/docs/reference/backend/types/domain) object.\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 /**\n * Updates a domain for the instance. Both primary and satellite domains can be updated. If you choose to use Clerk via proxy, use this endpoint to specify the `proxy_url`. Whenever you decide you'd rather switch to DNS setup for Clerk, simply set `proxy_url` to `null` for the domain.\n *\n * When you update a production instance's primary domain name, you have to make sure that you've completed all the necessary setup steps for DNS and emails to work. Expect downtime otherwise. Updating a primary domain's name will also update the instance's home origin, affecting the default application paths.\n * @returns The updated [`Domain`](https://clerk.com/docs/reference/backend/types/domain) object.\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. It is currently not possible to delete the instance's primary domain.\n * @param satelliteDomainId - The ID of the satellite domain to delete.\n * @returns The [`DeletedObject`](https://clerk.com/docs/reference/backend/types/deleted-object).\n */\n public async delete(satelliteDomainId: string) {\n return this.deleteDomain(satelliteDomainId);\n }\n\n /**\n * Deletes a satellite domain for the instance.\n * @param satelliteDomainId - The ID of the satellite domain to delete.\n * @returns The [`DeletedObject`](https://clerk.com/docs/reference/backend/types/deleted-object).\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\n/** @generateWithEmptyComment */\nexport type CreateEmailAddressParams = {\n /** The ID of the user to create the email address for. */\n userId: string;\n /** The email address to create. */\n emailAddress: string;\n /** Whether the email address should be verified. Defaults to `false`. */\n verified?: boolean;\n /** Whether the email address should be the primary email address. Defaults to `false`, unless it is the first email address added to the user. */\n primary?: boolean;\n};\n\n/** @inline */\nexport type UpdateEmailAddressParams = {\n /** Whether the email address should be verified. Defaults to `false`. */\n verified?: boolean;\n /** Whether the email address should be the primary email address. Defaults to `false`, unless it is the first email address added to the user. */\n primary?: boolean;\n};\n\n/** @generateWithEmptyComment */\nexport class EmailAddressAPI extends AbstractAPI {\n /**\n * Gets the given [`EmailAddress`](https://clerk.com/docs/reference/backend/types/backend-email-address).\n * @param emailAddressId - The ID of the email address to get.\n */\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 /**\n * Creates a new email address for the given user.\n * @returns The created [`EmailAddress`](https://clerk.com/docs/reference/backend/types/backend-email-address) object.\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 /**\n * Updates the given email address.\n * @param emailAddressId - The ID of the email address to update.\n * @param params - The parameters to update the email address.\n * @returns The updated [`EmailAddress`](https://clerk.com/docs/reference/backend/types/backend-email-address) object.\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 /**\n * Deletes the given email address.\n * @param emailAddressId - The ID of the email address to delete.\n * @returns The [`DeletedObject`](https://clerk.com/docs/reference/backend/types/deleted-object) object.\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 type { Email } from '../resources/Email';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/email';\n\n/**\n * A subset of mailbox object as specified in RFC 5322 §3.4. Specifically, a\n * `name-addr` with an optional `display-name` and a required `addr-spec`.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc5322#section-3.4}\n */\ntype Mailbox = {\n /**\n * (Optional) Display name for the mailbox. Currently accepted by the API but\n * not yet rendered server-side, so it has no effect on the delivered email\n * for now.\n */\n name?: string;\n\n /**\n * The `addr-spec` of the mailbox, i.e. the email address itself.\n */\n address: string;\n};\n\n/**\n * The recipient of the email. Provide exactly one of the two mutually exclusive\n * forms:\n *\n * - a literal mailbox: an `address` (plus an optional `name`), or\n * - a `userId`: the ID of a Clerk user whose primary email address Clerk\n * resolves server-side, from the instance the secret key belongs to.\n */\ntype EmailRecipient =\n | {\n /**\n * The `addr-spec` of the recipient mailbox, i.e. the email address itself.\n */\n address: string;\n /**\n * (Optional) Display name for the recipient mailbox. Currently accepted\n * by the API but not yet rendered server-side.\n */\n name?: string;\n userId?: never;\n }\n | {\n /**\n * The ID of the Clerk user to send to. Clerk resolves the user's primary\n * email address from the instance context. Mutually exclusive with\n * `address`.\n */\n userId: string;\n address?: never;\n name?: never;\n };\n\n/**\n * The body of the email. At least one of `html` and `text` must be provided; if\n * both are provided, the `html` version takes precedence. Encoded as a union so\n * that omitting both is a compile-time error rather than a server-side one.\n */\ntype EmailContent =\n | {\n /**\n * The HTML body of the email. Takes precedence over `text` when both are\n * provided.\n */\n html: string;\n /**\n * (Optional) The plain text body of the email.\n */\n text?: string;\n }\n | {\n /**\n * (Optional) The HTML body of the email. Takes precedence over `text`\n * when both are provided.\n */\n html?: string;\n /**\n * The plain text body of the email.\n */\n text: string;\n };\n\nexport type CreateEmailParams = {\n /**\n * The recipient of the email. Currently only a single recipient is supported.\n * Provide either an `address` (with an optional `name`) or the `userId` of a\n * Clerk user; the two forms are mutually exclusive.\n */\n to: EmailRecipient;\n\n /**\n * The sender of the email. See {@link Mailbox} for the accepted format. Note\n * that the API does not yet render the `name` field of the `from` mailbox.\n */\n from: Mailbox;\n\n /**\n * (Optional) The mailbox to include in the `reply-to` header of the email.\n */\n replyTo?: Mailbox;\n\n subject: string;\n} & EmailContent;\n\nexport class EmailApi extends AbstractAPI {\n /**\n * @experimental This method calls an internal, not-yet-public endpoint and is\n * subject to change. It is advised to [pin](https://clerk.com/docs/pinning)\n * the SDK version to avoid breaking changes.\n *\n * Sends a transactional email.\n */\n public async create(params: CreateEmailParams) {\n return this.request<Email>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n options: {\n // Snakecase nested keys too, so a `to: { userId }` recipient is sent as\n // `to: { user_id }` on the wire (the default only snakecases top-level\n // keys, which would leave the nested `userId` untouched).\n deepSnakecaseBodyParamKeys: true,\n },\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { EnterpriseConnection } from '../resources';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/enterprise_connections';\n\n/** @generateWithEmptyComment */\nexport type EnterpriseConnectionListParams = ClerkPaginationRequest<{\n /**\n * Filters enterprise connections by Organization ID.\n */\n organizationId?: string;\n /**\n * Filters enterprise connections by active status. If `true`, only active connections are returned. If `false`, only inactive connections are returned. If omitted, all connections are returned.\n */\n active?: boolean;\n}>;\n\n/** @inline */\nexport interface EnterpriseConnectionOidcParams {\n /** The OAuth (OIDC) authorization URL. */\n authUrl?: string;\n /** The OAuth (OIDC) client ID. */\n clientId?: string;\n /** The OAuth (OIDC) client secret. */\n clientSecret?: string;\n /** The OAuth (OIDC) discovery URL. */\n discoveryUrl?: string;\n /** Whether the OAuth (OIDC) requires PKCE. Must be `true` for public clients with no client secret. */\n requiresPkce?: boolean;\n /** The OAuth (OIDC) token URL. */\n tokenUrl?: string;\n /** The OAuth (OIDC) user info URL. */\n userInfoUrl?: string;\n}\n\n/** @inline */\nexport interface EnterpriseConnectionSamlAttributeMappingParams {\n /** The attribute mapping for the user ID. */\n userId?: string | null;\n /** The attribute mapping for the email address. */\n emailAddress?: string | null;\n /** The attribute mapping for the first name. */\n firstName?: string | null;\n /** The attribute mapping for the last name. */\n lastName?: string | null;\n}\n\n/** @inline */\nexport interface EnterpriseConnectionSamlParams {\n /** Whether the SAML connection allows Identity Provider (IdP) initiated flows. */\n allowIdpInitiated?: boolean;\n /** Whether the SAML connection allows users with an email address subdomain to use it. */\n allowSubdomains?: boolean;\n /** The attribute mapping for the SAML connection. */\n attributeMapping?: EnterpriseConnectionSamlAttributeMappingParams;\n /** Whether the SAML connection requires force authentication. */\n forceAuthn?: boolean;\n /** The IdP certificate (PEM) for the SAML connection. */\n idpCertificate?: string;\n /** The IdP Entity ID for the SAML connection. */\n idpEntityId?: string;\n /** The raw IdP metadata XML for the SAML connection. */\n idpMetadata?: string;\n /** The IdP metadata URL for the SAML connection. */\n idpMetadataUrl?: string;\n /** The IdP Single-Sign On URL for the SAML connection. */\n idpSsoUrl?: string;\n}\n\n/** @generateWithEmptyComment */\nexport type CreateEnterpriseConnectionParams = {\n /** The name of the enterprise connection. */\n name?: string;\n /** The [Verified Domains](https://clerk.com/docs/guides/organizations/add-members/verified-domains) of the enterprise connection. */\n domains?: string[];\n /** The organization ID of the enterprise connection. */\n organizationId?: string;\n /** Whether the enterprise connection should be active. */\n active?: boolean;\n /** Whether the enterprise connection should sync user attributes between the IdP and Clerk. */\n syncUserAttributes?: boolean;\n /** Configuration for if the enterprise connection uses OAuth (OIDC). */\n oidc?: EnterpriseConnectionOidcParams;\n /** Configuration for if the enterprise connection uses SAML. */\n saml?: EnterpriseConnectionSamlParams;\n};\n\n/** @inline */\nexport type UpdateEnterpriseConnectionParams = {\n /** The name of the enterprise connection. */\n name?: string;\n /** The [Verified Domains](https://clerk.com/docs/guides/organizations/add-members/verified-domains) of the enterprise connection. */\n domains?: string[];\n /** The organization ID of the enterprise connection. */\n organizationId?: string;\n /** Whether the enterprise connection should be active. */\n active?: boolean;\n /** Whether the enterprise connection should sync user attributes between the IdP and Clerk. */\n syncUserAttributes?: boolean;\n /** The identity provider (IdP) of the enterprise connection. For example, `'saml_custom'` or `'oidc_custom'`. */\n provider?: string;\n /** Configuration for if the enterprise connection uses OAuth (OIDC). */\n oidc?: EnterpriseConnectionOidcParams;\n /** Configuration for if the enterprise connection uses SAML. */\n saml?: EnterpriseConnectionSamlParams;\n};\n\n/** @generateWithEmptyComment */\nexport class EnterpriseConnectionAPI extends AbstractAPI {\n /**\n * Creates a new enterprise connection.\n * @returns The created [`EnterpriseConnection`](https://clerk.com/docs/reference/backend/types/backend-enterprise-connection) object.\n */\n public async createEnterpriseConnection(params: CreateEnterpriseConnectionParams) {\n return this.request<EnterpriseConnection>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n options: {\n deepSnakecaseBodyParamKeys: true,\n },\n });\n }\n\n /**\n * Updates the given enterprise connection.\n * @param enterpriseConnectionId - The ID of the enterprise connection to update.\n * @param params - The parameters to update the enterprise connection.\n * @returns The updated [`EnterpriseConnection`](https://clerk.com/docs/reference/backend/types/backend-enterprise-connection) object.\n */\n public async updateEnterpriseConnection(enterpriseConnectionId: string, params: UpdateEnterpriseConnectionParams) {\n this.requireId(enterpriseConnectionId);\n return this.request<EnterpriseConnection>({\n method: 'PATCH',\n path: joinPaths(basePath, enterpriseConnectionId),\n bodyParams: params,\n options: {\n deepSnakecaseBodyParamKeys: true,\n },\n });\n }\n\n /**\n * Gets the list of enterprise connections for the instance. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`EnterpriseConnection`](https://clerk.com/docs/reference/backend/types/backend-enterprise-connection) objects and a `totalCount` property containing the total number of enterprise connections for the instance.\n */\n public async getEnterpriseConnectionList(params: EnterpriseConnectionListParams = {}) {\n return this.request<PaginatedResourceResponse<EnterpriseConnection[]>>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n /**\n * Gets the given enterprise connection.\n * @param enterpriseConnectionId - The ID of the enterprise connection to get.\n * @returns The [`EnterpriseConnection`](https://clerk.com/docs/reference/backend/types/backend-enterprise-connection) object.\n */\n public async getEnterpriseConnection(enterpriseConnectionId: string) {\n this.requireId(enterpriseConnectionId);\n return this.request<EnterpriseConnection>({\n method: 'GET',\n path: joinPaths(basePath, enterpriseConnectionId),\n });\n }\n\n /**\n * Deletes the given enterprise connection.\n * @param enterpriseConnectionId - The ID of the enterprise connection to delete.\n * @returns The deleted [`EnterpriseConnection`](https://clerk.com/docs/reference/backend/types/backend-enterprise-connection) object.\n */\n public async deleteEnterpriseConnection(enterpriseConnectionId: string) {\n this.requireId(enterpriseConnectionId);\n return this.request<EnterpriseConnection>({\n method: 'DELETE',\n path: joinPaths(basePath, enterpriseConnectionId),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\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","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\n/** @generateWithEmptyComment */\nexport type UpdateParams = {\n /** Toggles [test mode](https://clerk.com/docs/guides/development/testing/test-emails-and-phones#set-up-test-mode) for this instance, allowing the use of test email addresses and phone numbers. Defaults to `true` for development instances. */\n testMode?: boolean | null | undefined;\n /** Whether the instance should be using the Have I Been Pwned (HIBP) service to check passwords for breaches. */\n hibp?: boolean | null | undefined;\n /** Whether the instance should send emails from \"verifications@clerk.dev\" instead of your domain. This can be helpful if you do not have a high domain reputation. */\n enhancedEmailDeliverability?: boolean | null | undefined;\n /** The support email for the instance. */\n supportEmail?: string | null | undefined;\n /** The npm version for `@clerk/clerk-js`. */\n clerkJsVersion?: string | null | undefined;\n /** The development origin for the instance. */\n developmentOrigin?: string | null | undefined;\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. 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.js, the origin is `capacitor://localhost`. */\n allowedOrigins?: Array<string> | undefined;\n /** Whether the instance should use URL-based session syncing in development mode (i.e. without third-party cookies). */\n urlBasedSessionSyncing?: boolean | null | undefined;\n /** Overrides the sign-in strategy that is preferred when a password is required. The value is only consulted when a password is required, and is dormant otherwise. Pass an empty string to clear the override. Passing `null` or `undefined` leaves the current value unchanged. */\n preferredSignInStrategyWhenPasswordRequired?: 'password' | 'otp' | '' | null | undefined;\n};\n\n/** @generateWithEmptyComment */\nexport type UpdateRestrictionsParams = {\n /** Whether the instance should have [**Allowlist**](https://clerk.com/docs/guides/secure/restricting-access#allowlist) enabled. */\n allowlist?: boolean | null | undefined;\n /** Whether the instance should have [**Blocklist**](https://clerk.com/docs/guides/secure/restricting-access#blocklist) enabled. */\n blocklist?: boolean | null | undefined;\n /** Whether the instance should have [**Block email subaddresses**](https://clerk.com/docs/guides/secure/restricting-access#block-email-subaddresses) enabled. */\n blockEmailSubaddresses?: boolean | null | undefined;\n /** Whether the instance should have [**Block sign-ups that use disposable email domains**](https://clerk.com/docs/guides/secure/restricting-access#block-sign-ups-that-use-disposable-email-addresses) enabled. */\n blockDisposableEmailDomains?: boolean | null | undefined;\n /** Whether the instance should [ignore dots for Gmail addresses](https://clerk.com/docs/guides/secure/restricting-access#block-email-subaddresses). */\n ignoreDotsForGmailAddresses?: boolean | null | undefined;\n};\n\n/** @generateWithEmptyComment */\nexport type UpdateOrganizationSettingsParams = {\n /** Whether the instance should enable [Organizations](https://clerk.com/docs/guides/organizations/overview). */\n enabled?: boolean | null | undefined;\n /** The maximum number of [memberships allowed](https://clerk.com/docs/guides/organizations/configure#membership-limits) per Organization. */\n maxAllowedMemberships?: number | null | undefined;\n /** Whether [Organization admins](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions#default-roles) are allowed to delete Organizations. */\n adminDeleteEnabled?: boolean | null | undefined;\n /** Whether [Verified Domains](https://clerk.com/docs/guides/organizations/add-members/verified-domains) are enabled for Organizations. */\n domainsEnabled?: boolean | null | undefined;\n /** Specifies which [enrollment modes](https://clerk.com/docs/guides/organizations/add-members/verified-domains#enable-verified-domains) to enable for your Organization's [Verified Domains](https://clerk.com/docs/guides/organizations/add-members/verified-domains). Supported modes are `'automatic_invitation'` & `'automatic_suggestion'`. */\n domainsEnrollmentModes?: Array<string> | undefined;\n /** Specifies what the default Organization [Role](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) is for an Organization creator. */\n creatorRoleId?: string | null | undefined;\n /** Specifies what the default Organization [Role](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) is for the Organization's [Verified Domains](https://clerk.com/docs/guides/organizations/add-members/verified-domains). */\n domainsDefaultRoleId?: string | null | undefined;\n};\n\n/** @generateWithEmptyComment */\nexport class InstanceAPI extends AbstractAPI {\n /**\n * Gets the current [`Instance`](https://clerk.com/docs/reference/backend/types/backend-instance).\n */\n public async get() {\n return this.request<Instance>({\n method: 'GET',\n path: basePath,\n });\n }\n\n /**\n * Updates the current instance.\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 /**\n * Updates the [restriction](https://clerk.com/docs/guides/secure/restricting-access) settings for the current instance.\n * @returns The updated [`InstanceRestrictions`](https://clerk.com/docs/reference/backend/types/backend-instance-restrictions) object.\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 /**\n * Gets the [Organization-related settings](https://clerk.com/docs/guides/organizations/configure) for the current instance.\n * @returns The [`OrganizationSettings`](https://clerk.com/docs/reference/backend/types/backend-organization-settings) object.\n */\n public async getOrganizationSettings() {\n return this.request<OrganizationSettings>({\n method: 'GET',\n path: joinPaths(basePath, 'organization_settings'),\n });\n }\n\n /**\n * Updates the [Organization-related settings](https://clerk.com/docs/guides/organizations/configure) for the current instance.\n * @returns The updated [`OrganizationSettings`](https://clerk.com/docs/reference/backend/types/backend-organization-settings) object.\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';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/invitations';\n\n/** @inline */\nexport type TemplateSlug = 'invitation' | 'waitlist_invitation';\n\n/** @generateWithEmptyComment */\nexport type CreateParams = {\n /** The email address of the user to invite. */\n emailAddress: string;\n /** The number of days until the invitation expires. Defaults to `30`. */\n expiresInDays?: number;\n /** Whether an invitation should be created if there is already an existing invitation for this email address, or if the email address already exists in the application. Defaults to `false`. */\n ignoreExisting?: boolean;\n /** Whether an email invitation should be sent to the given email address. Defaults to `true`. */\n notify?: boolean;\n /** Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}. Once the user accepts the invitation and signs up, these metadata will end up in the user's public metadata ([`User.publicMetadata`](https://clerk.com/docs/reference/backend/types/backend-user)). */\n publicMetadata?: UserPublicMetadata;\n /** The full URL or path where the user will land after accepting the invitation. See the [custom flow guide for handling application invitations](https://clerk.com/docs/guides/development/custom-flows/authentication/application-invitations). */\n redirectUrl?: string;\n /** The template slug to use for the invitation. Defaults to `invitation`. */\n templateSlug?: TemplateSlug;\n};\n\n/** @generateWithEmptyComment */\nexport type CreateBulkParams = Array<CreateParams>;\n\n/** @generateWithEmptyComment */\nexport type GetInvitationListParams = ClerkPaginationRequest<{\n /**\n * Filters the invitations in a particular order. Prefix a value with `+` to sort in ascending order, or `-` to sort in descending order. Defaults to `-created_at`.\n *\n * @example\n * ```ts\n * // Newest first\n * await clerkClient.invitations.getInvitationList({ orderBy: '-created_at' });\n *\n * // Alphabetical by email\n * await clerkClient.invitations.getInvitationList({ orderBy: 'email_address' });\n * ```\n */\n orderBy?: WithSign<'created_at' | 'email_address' | 'expires_at'>;\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\n/** @generateWithEmptyComment */\nexport class InvitationAPI extends AbstractAPI {\n /**\n * Gets a list of non-revoked invitations for the instance, sorted by descending creation date. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`Invitation`](https://clerk.com/docs/reference/backend/types/backend-invitation) objects and a `totalCount` property containing the total number of invitations.\n */\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 /**\n * Creates a new invitation for the given email address, and sends the invitation email.\n *\n * If an email address has already been invited or already exists in your application, trying to create a new invitation will return an error. To bypass this error and create a new invitation anyways, set `ignoreExisting` to `true`.\n * @returns The newly created [`Invitation`](https://clerk.com/docs/reference/backend/types/backend-invitation).\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 /**\n * Creates multiple invitations for the given email addresses, and sends the invitation emails.\n *\n * If an email address has already been invited or already exists in your application, trying to create a new invitation will return an error. To bypass this error and create a new invitation anyways, set `ignoreExisting` to `true`.\n * @returns An array of each created [`Invitation`](https://clerk.com/docs/reference/backend/types/backend-invitation) object.\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 /**\n * Revokes the given invitation.\n *\n * Revoking an invitation makes the invitation email link unusable. However, it doesn't prevent the user from signing up if they follow the sign up flow.\n *\n * Only active (i.e. non-revoked) invitations can be revoked.\n * @param invitationId - The ID of the invitation to revoke.\n * @returns The revoked [`Invitation`](https://clerk.com/docs/reference/backend/types/backend-invitation).\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\n/** @generateWithEmptyComment */\nexport type CreateMachineParams = {\n /** The name of the machine. */\n name: string;\n /** An array of machine IDs that the new machine will have access to. Maximum of 150 scopes per machine. */\n scopedMachines?: string[];\n /** The default time-to-live (TTL) in seconds for tokens created by this machine. Must be at least 1 second. */\n defaultTokenTtl?: number;\n};\n\n/** @generateWithEmptyComment */\nexport type UpdateMachineParams = {\n /** The ID of the machine to update. */\n machineId: string;\n /** The name of the machine. */\n name?: string;\n /** The default time-to-live (TTL) in seconds for tokens created by this machine. Must be at least 1 second. */\n defaultTokenTtl?: number;\n};\n\n/** @generateWithEmptyComment */\nexport type GetMachineListParams = ClerkPaginationRequest<{\n /** Filters machines in a particular order. Prefix a value with `+` to sort in ascending order, or `-` to sort in descending order. Defaults to `-created_at`. */\n orderBy?: WithSign<'name' | 'created_at'>;\n /** Filters machines by ID or name. */\n query?: string;\n}>;\n\n/** @generateWithEmptyComment */\nexport type RotateMachineSecretKeyParams = {\n /** The ID of the machine to rotate the secret key for. */\n machineId: string;\n /** The time in seconds that the previous secret key will remain valid after rotation. This ensures a graceful transition period for updating applications with the new secret key. Set to `0` to immediately expire the previous key. Maximum value is `28800` seconds (8 hours). */\n previousTokenTtl: number;\n};\n\n/** @generateWithEmptyComment */\nexport class MachineApi extends AbstractAPI {\n /**\n * Gets the given machine.\n * @param machineId - The ID of the machine to get.\n * @returns The [`Machine`](https://clerk.com/docs/reference/backend/types/backend-machine) object.\n */\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 /**\n * Gets a list of machines for the instance. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`Machine`](https://clerk.com/docs/reference/backend/types/backend-machine) objects and a `totalCount` property containing the total number of machines for the instance.\n */\n async list(queryParams: GetMachineListParams = {}) {\n return this.request<PaginatedResourceResponse<Machine[]>>({\n method: 'GET',\n path: basePath,\n queryParams,\n });\n }\n\n /**\n * Creates a new machine.\n * @returns The created [`Machine`](https://clerk.com/docs/reference/backend/types/backend-machine) object.\n */\n async create(bodyParams: CreateMachineParams) {\n return this.request<Machine>({\n method: 'POST',\n path: basePath,\n bodyParams,\n });\n }\n\n /**\n * Updates the given machine.\n * @returns The updated [`Machine`](https://clerk.com/docs/reference/backend/types/backend-machine) object.\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 /**\n * Deletes the given machine.\n * @param machineId - The ID of the machine to delete.\n * @returns The [`Machine`](https://clerk.com/docs/reference/backend/types/backend-machine) object.\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 /**\n * Gets the secret key for the given machine.\n * @param machineId - The ID of the machine to get the secret key for.\n * @returns The machine's secret key.\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 /**\n * Rotates the secret key for the given machine.\n * @returns The new secret key.\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. Maximum of 150 scopes per machine.\n *\n * @param machineId - The ID of the machine that will have access to the target machine.\n * @param toMachineId - The ID of the machine that will be accessible by the source machine.\n * @returns The created [`MachineScope`](https://clerk.com/docs/reference/backend/types/backend-machine-scope) object.\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 the given machine scope, removing access from one machine to another.\n *\n * @param machineId - The ID of the machine that has access to the target machine.\n * @param otherMachineId - The ID of the machine that will no longer be accessible by the source machine.\n * @returns The deleted [`MachineScope`](https://clerk.com/docs/reference/backend/types/backend-machine-scope) object.\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 type { JwtPayload } from '@clerk/shared/types';\n\nimport type { IdPOAuthAccessTokenJSON } from './JSON';\n\ntype OAuthJwtPayload = JwtPayload & {\n jti?: string;\n client_id?: string;\n scope?: string;\n scp?: string[];\n};\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 /** The Unix timestamp (in milliseconds) when the access token expires. */\n readonly expiration: number | null,\n /** The Unix timestamp (in milliseconds) when the access token was created. */\n readonly createdAt: number,\n /** The Unix timestamp (in milliseconds) when the access token was last updated. */\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 /**\n * Creates an IdPOAuthAccessToken from a JWT payload.\n * Maps standard JWT claims and OAuth-specific fields to token properties.\n */\n static fromJwtPayload(payload: JwtPayload, clockSkewInMs = 5000): IdPOAuthAccessToken {\n const oauthPayload = payload as OAuthJwtPayload;\n\n // Map JWT claims to IdPOAuthAccessToken fields\n return new IdPOAuthAccessToken(\n oauthPayload.jti ?? '',\n oauthPayload.client_id ?? '',\n 'oauth_token',\n payload.sub,\n oauthPayload.scp ?? oauthPayload.scope?.split(' ') ?? [],\n false,\n null,\n payload.exp * 1000 <= Date.now() - clockSkewInMs,\n payload.exp * 1000, // milliseconds: expiration, converted from JWT exp claim\n payload.iat * 1000, // milliseconds: createdAt, converted from JWT iat claim\n payload.iat * 1000, // milliseconds: updatedAt, no JWT equivalent, defaults to iat\n );\n }\n}\n","import type { M2MTokenJSON } from './JSON';\n\n// Minimal JWT claims present in M2M tokens. M2M tokens are not session JWTs\n// and do not carry session-specific claims like `sid` or `__raw`.\ntype M2MJwtPayload = {\n sub: string;\n exp: number;\n iat: number;\n jti?: string;\n aud?: string[];\n scopes?: string;\n [key: string]: unknown;\n};\n\n// Structural claims that Clerk's machine-token service always adds when it mints\n// an M2M JWT. These are mapped onto dedicated `M2MToken` fields, so they are\n// stripped from `claims`. Everything else is a user-supplied custom claim and is\n// surfaced through `claims`, including `aud` and `scopes`, which the backend\n// treats as custom claims (they are neither reserved nor auto-added).\nconst M2M_RESERVED_JWT_CLAIMS = new Set(['iss', 'sub', 'exp', 'nbf', 'iat', 'jti']);\n\n/**\n * Reconstructs the custom claims that were attached at token creation by\n * stripping the structural claims (see `M2M_RESERVED_JWT_CLAIMS`) from the\n * verified payload. Returns `null` when no custom claims are present, matching\n * the opaque-token path where a token created without claims verifies back to\n * `claims: null`.\n */\nfunction extractCustomClaims(payload: M2MJwtPayload): Record<string, any> | null {\n const claims: Record<string, any> = {};\n for (const key of Object.keys(payload)) {\n if (!M2M_RESERVED_JWT_CLAIMS.has(key)) {\n claims[key] = payload[key];\n }\n }\n return Object.keys(claims).length > 0 ? claims : null;\n}\n\n/**\n * The Backend `M2MToken` object holds information about a [machine-to-machine token](https://clerk.com/docs/guides/development/machine-auth/m2m-tokens).\n */\nexport class M2MToken {\n constructor(\n /** The ID of the M2M token. */\n readonly id: string,\n /** The subject of the M2M token. */\n readonly subject: string,\n /** The scopes of the M2M token. */\n readonly scopes: string[],\n /** The claims of the M2M token. */\n readonly claims: Record<string, any> | null,\n /** Whether the M2M token has been revoked. */\n readonly revoked: boolean,\n /** The reason for revoking the M2M token. */\n readonly revocationReason: string | null,\n /** Whether the M2M token has expired. */\n readonly expired: boolean,\n /** The Unix timestamp (in milliseconds) when the M2M token expires. */\n readonly expiration: number | null,\n /** The Unix timestamp (in milliseconds) when the M2M token was created. */\n readonly createdAt: number,\n /** The Unix timestamp (in milliseconds) when the M2M token was last updated. */\n readonly updatedAt: number,\n /** The token string. */\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 static fromJwtPayload(payload: M2MJwtPayload, clockSkewInMs = 5000): M2MToken {\n return new M2MToken(\n payload.jti ?? '', // jti should always be present in Clerk-issued M2M JWTs\n payload.sub,\n payload.scopes?.split(' ') ?? payload.aud ?? [],\n extractCustomClaims(payload),\n false,\n null,\n payload.exp * 1000 <= Date.now() - clockSkewInMs,\n payload.exp * 1000, // milliseconds — expiration, converted from JWT exp claim\n payload.iat * 1000, // milliseconds — createdAt, converted from JWT iat claim\n payload.iat * 1000, // milliseconds — updatedAt, no JWT equivalent; defaults to iat\n );\n }\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 { decodeJwt } from '../jwt/verifyJwt';\nimport type { AuthenticateRequestOptions } from '../tokens/types';\nimport type { MachineTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\n\nexport const M2M_TOKEN_PREFIX = 'mt_';\nexport const M2M_SUBJECT_PREFIX = 'mch_';\nexport const OAUTH_TOKEN_PREFIX = 'oat_';\nexport const API_KEY_PREFIX = 'ak_';\n\n// Token-category tag in the protected JOSE header of instance-signed M2M JWTs,\n// used to distinguish them from other JWT classes signed by the same instance\n// key. Kept in sync with clerk_go (pkg/jwt) and cloudflare-workers.\nexport const JWT_CATEGORY_M2M_TOKEN = 'cl_B7d4PD333AAA';\n\nconst MACHINE_TOKEN_PREFIXES = [M2M_TOKEN_PREFIX, OAUTH_TOKEN_PREFIX, API_KEY_PREFIX] as const;\n\nexport const JwtFormatRegExp = /^[a-zA-Z0-9\\-_]+\\.[a-zA-Z0-9\\-_]+\\.[a-zA-Z0-9\\-_]+$/;\n\nexport function isJwtFormat(token: string): boolean {\n return JwtFormatRegExp.test(token);\n}\n\n/**\n * Valid OAuth 2.0 JWT access token type values per RFC 9068.\n * @see https://www.rfc-editor.org/rfc/rfc9068.html#section-2.1\n */\nexport const OAUTH_ACCESS_TOKEN_TYPES = ['at+jwt', 'application/at+jwt'];\n\n/**\n * Checks if a token is an OAuth 2.0 JWT access token.\n * Validates the JWT format and verifies the header 'typ' field matches RFC 9068 values.\n *\n * @param token - The token string to check\n * @returns true if the token is a valid OAuth JWT access token\n * @see https://www.rfc-editor.org/rfc/rfc9068.html#section-2.1\n */\nexport function isOAuthJwt(token: string): boolean {\n if (!isJwtFormat(token)) {\n return false;\n }\n try {\n const { data, errors } = decodeJwt(token);\n return (\n !errors &&\n !!data &&\n OAUTH_ACCESS_TOKEN_TYPES.includes(data.header.typ as (typeof OAUTH_ACCESS_TOKEN_TYPES)[number])\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Checks if a token is an M2M JWT token.\n * Validates the JWT format and verifies the payload 'sub' field starts with 'mch_'.\n *\n * @param token - The token string to check\n * @returns true if the token is a valid M2M JWT token\n */\nexport function isM2MJwt(token: string): boolean {\n if (!isJwtFormat(token)) {\n return false;\n }\n try {\n const { data, errors } = decodeJwt(token);\n return !errors && !!data && typeof data.payload.sub === 'string' && data.payload.sub.startsWith(M2M_SUBJECT_PREFIX);\n } catch {\n return false;\n }\n}\n\n/**\n * Checks if a token is a machine JWT (OAuth JWT or M2M JWT).\n * Useful for rejecting machine JWTs when expecting session tokens.\n *\n * @param token - The token string to check\n * @returns true if the token is an OAuth or M2M JWT\n */\nexport function isMachineJwt(token: string): boolean {\n return isOAuthJwt(token) || isM2MJwt(token);\n}\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 * Checks if a token is a machine token by looking at its prefix or if it's an OAuth/M2M JWT.\n *\n * @param token - The token string to check\n * @returns true if the token is a machine token\n */\nexport function isMachineToken(token: string): boolean {\n return isMachineTokenByPrefix(token) || isOAuthJwt(token) || isM2MJwt(token);\n}\n\n/**\n * Gets the specific type of machine token based on its prefix or JWT claims.\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 type\n */\nexport function getMachineTokenType(token: string): MachineTokenType {\n // M2M: prefix OR JWT with mch_ subject\n if (token.startsWith(M2M_TOKEN_PREFIX) || isM2MJwt(token)) {\n return TokenType.M2MToken;\n }\n\n // OAuth: prefix OR JWT with at+jwt typ\n if (token.startsWith(OAUTH_TOKEN_PREFIX) || isOAuthJwt(token)) {\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\nconst MACHINE_TOKEN_TYPES = new Set<string>([TokenType.ApiKey, TokenType.M2MToken, TokenType.OAuthToken]);\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 MACHINE_TOKEN_TYPES.has(type);\n}\n","import type { Jwt, JwtPayload } from '@clerk/shared/types';\n\nimport { IdPOAuthAccessToken } from '../api/resources/IdPOAuthAccessToken';\nimport { M2MToken } from '../api/resources/M2MToken';\nimport {\n MachineTokenVerificationError,\n MachineTokenVerificationErrorCode,\n TokenVerificationErrorAction,\n} from '../errors';\nimport type { MachineTokenReturnType } from '../jwt/types';\nimport { verifyJwt } from '../jwt/verifyJwt';\nimport type { LoadClerkJWKFromRemoteOptions } from '../tokens/keys';\nimport { loadClerkJwkFromPem, loadClerkJWKFromRemote } from '../tokens/keys';\nimport { JWT_CATEGORY_M2M_TOKEN, OAUTH_ACCESS_TOKEN_TYPES } from '../tokens/machine';\nimport { TokenType } from '../tokens/tokenTypes';\n\nexport type JwtMachineVerifyOptions = Pick<LoadClerkJWKFromRemoteOptions, 'secretKey' | 'apiUrl' | 'skipJwksCache'> & {\n jwtKey?: string;\n clockSkewInMs?: number;\n};\n\n/**\n * Resolves the signing key and verifies a machine JWT's signature and claims.\n *\n * Networkless when `jwtKey` (PEM) is provided; performs a JWKS fetch when only `secretKey` is set.\n * Returns a discriminated union so callers can branch on `'error' in result` without try/catch.\n *\n * Note: uses `MachineTokenVerificationError`, not `TokenVerificationError` — the two error types\n * are intentionally separate because session-token errors carry handshake metadata that machine\n * tokens don't need.\n */\nasync function resolveKeyAndVerifyJwt(\n token: string,\n kid: string,\n options: JwtMachineVerifyOptions,\n headerType?: string[],\n): Promise<{ payload: JwtPayload } | { error: MachineTokenVerificationError }> {\n try {\n let key: JsonWebKey;\n\n if (options.jwtKey) {\n key = loadClerkJwkFromPem({ kid, pem: options.jwtKey });\n } else if (options.secretKey) {\n key = await loadClerkJWKFromRemote({ ...options, kid });\n } else {\n return {\n error: new MachineTokenVerificationError({\n action: TokenVerificationErrorAction.SetClerkJWTKey,\n message: 'Failed to resolve JWK during verification.',\n code: MachineTokenVerificationErrorCode.TokenVerificationFailed,\n }),\n };\n }\n\n const { data: payload, errors: verifyErrors } = await verifyJwt(token, {\n ...options,\n key,\n ...(headerType ? { headerType } : {}),\n });\n\n if (verifyErrors) {\n return {\n error: new MachineTokenVerificationError({\n code: MachineTokenVerificationErrorCode.TokenVerificationFailed,\n message: verifyErrors[0].message,\n }),\n };\n }\n\n return { payload };\n } catch (error) {\n return {\n error: new MachineTokenVerificationError({\n code: MachineTokenVerificationErrorCode.TokenVerificationFailed,\n message: (error as Error).message,\n }),\n };\n }\n}\n\n/**\n * Verifies a pre-decoded M2M JWT (identified by `sub` starting with `mch_`).\n */\nexport async function verifyM2MJwt(\n token: string,\n decoded: Jwt,\n options: JwtMachineVerifyOptions,\n): Promise<MachineTokenReturnType<M2MToken, MachineTokenVerificationError>> {\n // Reject JWTs of another class (e.g. session, jwt-template) signed by the same\n // instance key. Absent `cat` is still accepted during the rollout window; tighten\n // to strict equality once pre-rollout M2M JWTs have expired (USER-5437).\n const cat = decoded.header.cat;\n if (cat !== undefined && cat !== JWT_CATEGORY_M2M_TOKEN) {\n return {\n data: undefined,\n tokenType: TokenType.M2MToken,\n errors: [\n new MachineTokenVerificationError({\n code: MachineTokenVerificationErrorCode.TokenInvalid,\n message: 'Invalid M2M JWT category.',\n }),\n ],\n };\n }\n\n const result = await resolveKeyAndVerifyJwt(token, decoded.header.kid, options);\n\n if ('error' in result) {\n return { data: undefined, tokenType: TokenType.M2MToken, errors: [result.error] };\n }\n\n return {\n data: M2MToken.fromJwtPayload(result.payload, options.clockSkewInMs),\n tokenType: TokenType.M2MToken,\n errors: undefined,\n };\n}\n\n/**\n * Verifies a pre-decoded OAuth access token JWT (identified by `typ: at+jwt` or `application/at+jwt`).\n */\nexport async function verifyOAuthJwt(\n token: string,\n decoded: Jwt,\n options: JwtMachineVerifyOptions,\n): Promise<MachineTokenReturnType<IdPOAuthAccessToken, MachineTokenVerificationError>> {\n const result = await resolveKeyAndVerifyJwt(token, decoded.header.kid, options, OAUTH_ACCESS_TOKEN_TYPES);\n\n if ('error' in result) {\n return { data: undefined, tokenType: TokenType.OAuthToken, errors: [result.error] };\n }\n\n return {\n data: IdPOAuthAccessToken.fromJwtPayload(result.payload, options.clockSkewInMs),\n tokenType: TokenType.OAuthToken,\n errors: undefined,\n };\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\n\nimport { MachineTokenVerificationError, MachineTokenVerificationErrorCode } from '../../errors';\nimport { decodeJwt } from '../../jwt/verifyJwt';\nimport type { JwtMachineVerifyOptions } from '../../jwt/verifyMachineJwt';\nimport { verifyM2MJwt } from '../../jwt/verifyMachineJwt';\nimport { isM2MJwt } from '../../tokens/machine';\nimport { joinPaths } from '../../util/path';\nimport type { ClerkBackendApiRequestOptions, RequestFunction } from '../request';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { M2MToken } from '../resources/M2MToken';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/m2m_tokens';\n\n/** @inline */\nexport type M2MTokenFormat = 'opaque' | 'jwt';\n\n/** @generateWithEmptyComment */\nexport type GetM2MTokenListParams = ClerkPaginationRequest<{\n /** The custom machine secret key for authentication. If not provided, the SDK will use the value from the environment variables. */\n machineSecretKey?: string;\n /** The machine ID to query M2M tokens by. */\n subject: string;\n /** Whether to include revoked M2M tokens. Defaults to `false`. */\n revoked?: boolean;\n /** Whether to include expired M2M tokens. Defaults to `false`. */\n expired?: boolean;\n}>;\n\n/** @generateWithEmptyComment */\nexport type CreateM2MTokenParams = {\n /** The custom machine secret key for authentication. If not provided, the SDK will use the value from the environment variables. */\n machineSecretKey?: string;\n /** The number of seconds until the token expires. Defaults to `null`, meaning the token does not expire. */\n secondsUntilExpiration?: number | null;\n /** Custom claims to include in the M2M token payload. */\n claims?: Record<string, unknown> | null;\n /**\n * Enables server-side token reuse for opaque tokens. Only applies to opaque tokens (`token_format: 'opaque'`). JWT tokens (`token_format: 'jwt'`) are stateless and are never deduplicated. When set, if a non-revoked, non-expired M2M token already exists for this machine with identical `claims` and `scopes` and at least this many seconds of remaining lifetime, that existing token is returned and no new token is minted.\n *\n * Use this when caching tokens in application memory across requests is impractical — for example, in serverless functions, short-lived job workers, or autoscaling containers that churn faster than the token TTL. Pooling at the server collapses many redundant create calls into reuse of a single live token, which is the recommended pattern for high-volume M2M traffic.\n *\n * Must be strictly less than the effective token lifetime — that is, `seconds_until_expiration` when provided, or the machine's default TTL otherwise. A value greater than or equal to the lifetime is rejected with a `400` error, since no freshly-minted token would ever satisfy the requirement.\n */\n minRemainingTtlSeconds?: number;\n /**\n * The format of the M2M token to create. Defaults to `'opaque'`. Set to `'jwt'` to create a [JSON Web Token](/docs/guides/how-clerk-works/tokens-and-signatures#json-web-tokens-jwts) that can be verified locally without a network request. For a detailed comparison of the two formats, see [Token formats](/docs/guides/development/machine-auth/token-formats).\n */\n tokenFormat?: M2MTokenFormat;\n};\n\n/** @generateWithEmptyComment */\nexport type RevokeM2MTokenParams = {\n /** The custom machine secret key for authentication. If not provided, the SDK will use the value from the environment variables. */\n machineSecretKey?: string;\n /** The ID of the M2M token to revoke. */\n m2mTokenId: string;\n /** The reason for revoking the M2M token. Useful for your records. */\n revocationReason?: string | null;\n};\n\n/** @generateWithEmptyComment */\nexport type VerifyM2MTokenParams = {\n /** The custom machine secret key for authentication. If not provided, the SDK will use the value from the environment variables. */\n machineSecretKey?: string;\n /** The M2M token to verify. */\n token: string;\n};\n\n/** @generateWithEmptyComment */\nexport class M2MTokenApi extends AbstractAPI {\n #verifyOptions: JwtMachineVerifyOptions;\n\n /**\n * @param verifyOptions - JWT verification options (secretKey, apiUrl, etc.).\n * Passed explicitly because BuildRequestOptions are captured inside the buildRequest closure\n * and are not accessible from the RequestFunction itself.\n */\n constructor(request: RequestFunction, verifyOptions: JwtMachineVerifyOptions = {}) {\n super(request);\n this.#verifyOptions = verifyOptions;\n }\n\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 /**\n * Gets a list of M2M tokens for the given machine. By default, the list is returned in descending order by creation date (newest first). This endpoint can be authenticated by either a Machine Secret Key or by a Clerk [Secret Key](!secret-key).\n * - When fetching M2M tokens with a Machine Secret Key, only tokens associated with the authenticated machine can be retrieved.\n * - When fetching M2M tokens with a Clerk Secret Key, tokens for any machine in the instance can be retrieved.\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`M2MToken`](https://clerk.com/docs/reference/backend/types/backend-m2m-token) objects and a `totalCount` property containing the total number of M2M tokens for the machine.\n */\n async list(queryParams: GetM2MTokenListParams) {\n const { machineSecretKey, ...params } = queryParams;\n\n const requestOptions = this.#createRequestOptions(\n {\n method: 'GET',\n path: basePath,\n queryParams: params,\n },\n machineSecretKey,\n );\n\n return this.request<PaginatedResourceResponse<M2MToken[]>>(requestOptions);\n }\n\n /**\n * Creates a new [M2M token](https://clerk.com/docs/guides/development/machine-auth/m2m-tokens) for the given machine. Must be authenticated by a Machine Secret Key.\n * @returns The created [`M2MToken`](https://clerk.com/docs/reference/backend/types/backend-m2m-token) object.\n */\n async createToken(params?: CreateM2MTokenParams) {\n const {\n claims = null,\n machineSecretKey,\n minRemainingTtlSeconds,\n secondsUntilExpiration = null,\n tokenFormat = 'opaque',\n } = params || {};\n\n const requestOptions = this.#createRequestOptions(\n {\n method: 'POST',\n path: basePath,\n bodyParams: {\n secondsUntilExpiration,\n claims,\n minRemainingTtlSeconds,\n tokenFormat,\n },\n },\n machineSecretKey,\n );\n\n return this.request<M2MToken>(requestOptions);\n }\n\n /**\n * Revokes an [M2M token](https://clerk.com/docs/guides/development/machine-auth/m2m-tokens). This endpoint can be authenticated by either a Machine Secret Key or by a Clerk [Secret Key](!secret-key).\n * - When revoking M2M tokens with a Machine Secret Key, the token will be revoked using the machine secret key.\n * - When revoking M2M tokens with a Clerk Secret Key, the token will be revoked using the instance secret key.\n * @returns The revoked [`M2MToken`](https://clerk.com/docs/reference/backend/types/backend-m2m-token) object.\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 #verifyJwtFormat(token: string): Promise<M2MToken> {\n let decoded;\n try {\n const { data, errors } = decodeJwt(token);\n if (errors) {\n throw errors[0];\n }\n decoded = data;\n } catch (e) {\n throw new MachineTokenVerificationError({\n code: MachineTokenVerificationErrorCode.TokenInvalid,\n message: (e as Error).message,\n });\n }\n\n const result = await verifyM2MJwt(token, decoded, this.#verifyOptions);\n if (result.errors) {\n throw result.errors[0];\n }\n return result.data;\n }\n\n /**\n * Verifies a [M2M token](https://clerk.com/docs/guides/development/machine-auth/m2m-tokens). Must be authenticated by a Machine Secret Key.\n * @returns The verified [`M2MToken`](https://clerk.com/docs/reference/backend/types/backend-m2m-token) object.\n */\n async verify(params: VerifyM2MTokenParams) {\n const { token, machineSecretKey } = params;\n\n if (isM2MJwt(token)) {\n return this.#verifyJwtFormat(token);\n }\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","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';\n\nimport { joinPaths } from '../../util/path';\nimport type { DeletedObject, JwtTemplate } from '../resources';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\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<PaginatedResourceResponse<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 { deprecated } from '../../util/shared';\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\n/** @inline */\nexport type MetadataParams<TPublic = OrganizationPublicMetadata, TPrivate = OrganizationPrivateMetadata> = {\n /** Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}, but can be set only from the Backend API. */\n publicMetadata?: TPublic;\n /** Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}. */\n privateMetadata?: TPrivate;\n};\n\n/** @generateWithEmptyComment */\nexport type GetOrganizationListParams = ClerkPaginationRequest<{\n /** Whether to include the number of members in the Organization. */\n includeMembersCount?: boolean;\n /** Filters Organizations by ID, name, or slug. Uses exact match for ID and partial match for name and slug. */\n query?: string;\n /** Filters Organizations in a particular order. Prefix a value with `+` to sort in ascending order, or `-` to sort in descending order. Defaults to `-created_at`. */\n orderBy?: WithSign<'name' | 'created_at' | 'members_count'>;\n /** Filters Organizations by ID. Accepts up to 100 Organization IDs. */\n organizationId?: string[];\n}>;\n\n/** @generateWithEmptyComment */\nexport type CreateParams = {\n /** The name of the Organization. */\n name: string;\n /** The slug of the Organization. */\n slug?: string;\n /** The ID of the user creating the Organization. The user will become an [admin](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions#default-roles) for the Organization. */\n createdBy?: string;\n /** The maximum number of memberships allowed in the Organization. `0` means unlimited. */\n maxAllowedMemberships?: number;\n} & MetadataParams;\n\n/** @generateWithEmptyComment */\nexport type GetOrganizationParams = (\n | {\n /** The ID of the Organization to get. */\n organizationId: string;\n }\n | {\n /** The slug of the Organization to get. */\n slug: string;\n }\n) & {\n /** Whether to include the number of members in the Organization. */\n includeMembersCount?: boolean;\n};\n\n/** @inline */\nexport type UpdateParams = {\n /** The name to update the Organization with. */\n name?: string;\n /** The slug to update the Organization with. */\n slug?: string;\n /** Whether the Organization allows admins to delete users. */\n adminDeleteEnabled?: boolean;\n /** The maximum number of memberships allowed in the Organization. `0` means unlimited. */\n maxAllowedMemberships?: number;\n /**\n * @deprecated Updating metadata via [`updateOrganization()`](https://clerk.com/docs/reference/backend/organization/update-organization) is deprecated. Use [`updateOrganizationMetadata()`](https://clerk.com/docs/reference/backend/organization/update-organization-metadata) for partial updates (deep merge) or [`replaceOrganizationMetadata()`](https://clerk.com/docs/reference/backend/organization/replace-organization-metadata) for full replacement.\n */\n publicMetadata?: OrganizationPublicMetadata;\n /**\n * @deprecated Updating metadata via [`updateOrganization()`](https://clerk.com/docs/reference/backend/organization/update-organization) is deprecated. Use [`updateOrganizationMetadata()`](https://clerk.com/docs/reference/backend/organization/update-organization-metadata) for partial updates (deep merge) or [`replaceOrganizationMetadata()`](https://clerk.com/docs/reference/backend/organization/replace-organization-metadata) for full replacement.\n */\n privateMetadata?: OrganizationPrivateMetadata;\n};\n\n/** @inline */\nexport type UpdateLogoParams = {\n /** The file to upload as the logo. */\n file: Blob | File;\n /** The ID of the user uploading the logo. */\n uploaderUserId?: string;\n};\n\n/** @inline */\nexport type UpdateMetadataParams = MetadataParams;\n\n/** @generateWithEmptyComment */\nexport type GetOrganizationMembershipListParams = ClerkPaginationRequest<{\n /** The ID of the Organization to get the list of memberships for. */\n organizationId: string;\n /**\n * Filters Organization memberships in a particular order. Prefix a value with `+` to sort in ascending order, or `-` to sort in descending order. Defaults to `-created_at`.\n */\n orderBy?: WithSign<'phone_number' | 'email_address' | 'created_at' | 'first_name' | 'last_name' | 'username'>;\n /**\n * Filters Organization memberships by user ID. Accepts up to 100 user IDs.\n */\n userId?: string[];\n /** Filters Organization memberships by email address. Accepts up to 100 email addresses. */\n emailAddress?: string[];\n /** Filters Organization memberships by phone number. Accepts up to 100 phone numbers. */\n phoneNumber?: string[];\n /** Filters Organization memberships by username. Accepts up to 100 usernames. */\n username?: string[];\n /** Filters Organization memberships by web3 wallet address. Accepts up to 100 web3 wallet addresses. */\n web3Wallet?: string[];\n /** Filters Organization memberships by Role. Accepts up to 100 Roles. */\n role?: OrganizationMembershipRole[];\n /**\n * Filters Organization memberships matching the given query across email addresses, phone numbers, usernames, Web3 wallet addresses, user IDs, first names, and last names. Partial matches supported. For example, `query=hello` will match a user with the email `HELLO@example.com`.\n */\n query?: string;\n /**\n * Filters Organization memberships by email address. Accepts up to 100 email addresses. Partial matches supported. For example, `emailAddressQuery=ello` will match a user with the email `HELLO@example.com`.\n */\n emailAddressQuery?: string;\n\n /**\n * Filters Organization memberships by phone number. Accepts up to 100 phone numbers. Partial matches supported. For example, `phoneNumberQuery=555` will match a user with the phone number `+1555xxxxxxx`.\n */\n phoneNumberQuery?: string;\n /**\n * Filters Organization memberships by username. Accepts up to 100 usernames. Partial matches supported. For example, `usernameQuery=CoolUser` will match a user with the username `SomeCoolUser`.\n */\n usernameQuery?: string;\n /** Filters Organization memberships by name. Accepts up to 100 names. Partial matches supported. For example, `nameQuery=John Doe` will match a user with the name `John Doe`. */\n nameQuery?: string;\n /**\n * Filters Organization memberships by last session activity before the given date (with millisecond precision). For example, use `1700690400000` to get users whose last session activity was before 2023-11-23.\n */\n lastActiveAtBefore?: number;\n /**\n * Filters Organization memberships by last session activity after the given date (with millisecond precision). For example, use `1700690400000` to get users whose last session activity was after 2023-11-23.\n */\n lastActiveAtAfter?: number;\n /**\n * Filters Organization memberships by creation date before the given date (with millisecond precision). For example, use `1730160000000` to get users who have been created before 2024-10-29.\n */\n createdAtBefore?: number;\n /**\n * Filters Organization memberships by creation date after the given date (with millisecond precision). For example, use `1730160000000` to get users who have been created after 2024-10-29.\n */\n createdAtAfter?: number;\n}>;\n\n/** @generateWithEmptyComment */\nexport type GetInstanceOrganizationMembershipListParams = ClerkPaginationRequest<{\n /**\n * Filters Organization memberships in a particular order. Prefix a value with `+` to sort in ascending order, or `-` to sort in descending order. Defaults to `-created_at`.\n */\n orderBy?: WithSign<'phone_number' | 'email_address' | 'created_at' | 'first_name' | 'last_name' | 'username'>;\n}>;\n\n/** @generateWithEmptyComment */\nexport type CreateOrganizationMembershipParams = {\n /** The ID of the Organization the user is being added to. */\n organizationId: string;\n /** The ID of the user to be added to the Organization. */\n userId: string;\n /** The [Role](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) to assign to the user. */\n role: OrganizationMembershipRole;\n};\n\n/** @generateWithEmptyComment */\nexport type UpdateOrganizationMembershipParams = CreateOrganizationMembershipParams;\n\n/** @generateWithEmptyComment */\nexport type UpdateOrganizationMembershipMetadataParams = {\n /** The ID of the Organization the membership belongs to. */\n organizationId: string;\n /** The ID of the user the membership belongs to. */\n userId: string;\n} & MetadataParams<OrganizationMembershipPublicMetadata>;\n\n/** @generateWithEmptyComment */\nexport type DeleteOrganizationMembershipParams = {\n /** The ID of the Organization to remove the user from. */\n organizationId: string;\n /** The ID of the user to remove from the Organization. */\n userId: string;\n};\n\n/** @generateWithEmptyComment */\nexport type CreateOrganizationInvitationParams = {\n /** The ID of the Organization the user is being invited to. */\n organizationId: string;\n /** The email address of the user being invited. */\n emailAddress: string;\n /** The [Role](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) to assign to the user. */\n role: OrganizationMembershipRole;\n /** The number of days until the invitation expires. Defaults to `30`. */\n expiresInDays?: number;\n /** The ID of the user creating the invitation. */\n inviterUserId?: string;\n /** Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}. */\n privateMetadata?: OrganizationInvitationPrivateMetadata;\n /** Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}, but can be set only from the Backend API. */\n publicMetadata?: OrganizationInvitationPublicMetadata;\n /** The full URL or path where the user will land after accepting the invitation. */\n redirectUrl?: string;\n};\n\n/** @inline */\nexport type CreateBulkOrganizationInvitationParams = Array<Omit<CreateOrganizationInvitationParams, 'organizationId'>>;\n\n/** @generateWithEmptyComment */\nexport type GetOrganizationInvitationListParams = ClerkPaginationRequest<{\n /** The ID of the Organization to get the list of invitations for. */\n organizationId: string;\n /** Filters Organization invitations by status. Accepts up to 100 statuses. */\n status?: OrganizationInvitationStatus[];\n}>;\n\n/** @generateWithEmptyComment */\nexport type GetOrganizationInvitationParams = {\n /** The ID of the Organization to get the invitation for. */\n organizationId: string;\n /** The ID of the Organization invitation to get. */\n invitationId: string;\n};\n\n/** @generateWithEmptyComment */\nexport type RevokeOrganizationInvitationParams = {\n /** The ID of the Organization to revoke the invitation from. */\n organizationId: string;\n /** The ID of the Organization invitation to revoke. */\n invitationId: string;\n /** The ID of the user revoking the invitation. */\n requestingUserId?: string;\n};\n\n/** @generateWithEmptyComment */\nexport type GetOrganizationDomainListParams = {\n /** The ID of the Organization to get the list of domains for. */\n organizationId: string;\n /** Maximum number of items returned per request. Must be an integer greater than zero and less than `501`. Can be used for paginating the results together with offset. Defaults to `10`. */\n limit?: number;\n /** Skip the first `offset` items when paginating. Needs to be an integer greater or equal to zero. To be used in conjunction with `limit`. Defaults to `0`. */\n offset?: number;\n};\n\n/** @generateWithEmptyComment */\nexport type CreateOrganizationDomainParams = {\n /** The ID of the Organization to create the domain for. */\n organizationId: string;\n /** The name of the domain. */\n name: string;\n /** The enrollment mode that determines how matching users are added to the Organization.\n *\n * <ul>\n * <li>`manual_invitation`: No automatic enrollment. Users with a matching email domain are not given any [invitation](https://clerk.com/docs/guides/organizations/add-members/verified-domains#automatic-invitations) or [suggestion](https://clerk.com/docs/guides/organizations/add-members/verified-domains#automatic-suggestions); an [admin](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions#default-roles) must invite them manually.</li>\n * <li>`automatic_invitation`: Users with a matching email domain automatically receive a pending [invitation](https://clerk.com/docs/reference/types/organization-invitation) (assigned the Organization's default role) which they can accept to join.</li>\n * <li>`automatic_suggestion`: Users with a matching email domain automatically receive a [suggestion](https://clerk.com/docs/guides/organizations/add-members/verified-domains#automatic-suggestions) to join, which they can request.</li>\n * </ul>\n */\n enrollmentMode: OrganizationEnrollmentMode;\n /** Whether the domain is verified. Defaults to `true`. */\n verified?: boolean;\n};\n\n/** @generateWithEmptyComment */\nexport type UpdateOrganizationDomainParams = {\n /** The ID of the Organization to update the domain for. */\n organizationId: string;\n /** The ID of the domain to update. */\n domainId: string;\n} & Partial<CreateOrganizationDomainParams>;\n\n/** @generateWithEmptyComment */\nexport type DeleteOrganizationDomainParams = {\n /** The ID of the Organization to delete the domain for. */\n organizationId: string;\n /** The ID of the domain to delete. */\n domainId: string;\n};\n\n/** @generateWithEmptyComment */\nexport class OrganizationAPI extends AbstractAPI {\n /**\n * Gets the list of Organizations for the instance. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`Organization`](https://clerk.com/docs/reference/backend/types/backend-organization) objects and a `totalCount` property containing the total number of Organizations for the instance.\n */\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 /** Creates an [`Organization`](https://clerk.com/docs/reference/backend/types/backend-organization). */\n public async createOrganization(params: CreateParams) {\n return this.request<Organization>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n /** Gets an [Organization](https://clerk.com/docs/reference/backend/types/backend-organization). */\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 /**\n * Updates an [Organization](https://clerk.com/docs/reference/backend/types/backend-organization).\n * @param organizationId - The ID of the Organization to update.\n * @param params - The parameters to update the Organization with.\n * @returns The updated [Organization](https://clerk.com/docs/reference/backend/types/backend-organization).\n */\n public async updateOrganization(organizationId: string, params: UpdateParams) {\n this.requireId(organizationId);\n\n const { publicMetadata, privateMetadata, ...rest } = params;\n const hasMetadata = publicMetadata !== undefined || privateMetadata !== undefined;\n const hasRest = Object.keys(rest).length > 0;\n\n if (hasMetadata) {\n deprecated(\n 'updateOrganization(organizationId, { publicMetadata | privateMetadata })',\n 'Use updateOrganizationMetadata for partial updates (merge) or replaceOrganizationMetadata for full replacement.',\n );\n }\n\n if (!hasMetadata) {\n return this.request<Organization>({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId),\n bodyParams: rest,\n });\n }\n\n if (hasRest) {\n await this.request<Organization>({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId),\n bodyParams: rest,\n });\n }\n\n return this.request<Organization>({\n method: 'PUT',\n path: joinPaths(basePath, organizationId, 'metadata'),\n bodyParams: { publicMetadata, privateMetadata },\n });\n }\n\n /**\n * Updates the logo of the given Organization.\n * @param organizationId - The ID of the Organization to update the logo for.\n * @param params - The parameters to update the logo with.\n * @returns The updated [`Organization`](https://clerk.com/docs/reference/backend/types/backend-organization).\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 /**\n * Deletes the logo of the given Organization.\n * @param organizationId - The ID of the Organization to delete the logo for.\n * @returns The deleted [`Organization`](https://clerk.com/docs/reference/backend/types/backend-organization).\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 /**\n * Updates the metadata for the given Organization, by merging existing values with the provided parameters.\n *\n * A \"deep\" merge will be performed - \"deep\" means that any nested JSON objects will be merged as well. You can remove metadata keys at any level by setting their value to `null`.\n *\n * @param organizationId - The ID of the Organization to update the metadata for.\n * @param params - The parameters to update the metadata with.\n * @returns The updated [`Organization`](https://clerk.com/docs/reference/backend/types/backend-organization).\n *\n * > [!TIP]\n * > If you want to fully replace the existing metadata instead of merging, use [`replaceOrganizationMetadata()`](https://clerk.com/docs/reference/backend/organization/replace-organization-metadata).\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 /**\n * Replaces the metadata associated with the specified Organization. Unlike [`updateOrganizationMetadata()`](/docs/reference/backend/organization/update-organization-metadata), which deep-merges into the existing metadata, this method uses replace semantics: when a metadata field is provided, its previous value is overwritten in full with no merging at any level.\n *\n * The distinction is at two layers:\n * - **Top-level field omission preserves the existing value.** Each top-level field (`publicMetadata`, `privateMetadata`) is handled independently. If you don't include a field in the request, the stored value for that field is left untouched.\n * - **The value inside a provided field is replaced in full.** When you do include a field, its previous content is discarded — any nested keys present before but absent in the new value are dropped. There is no merge.\n *\n * For the provided field, you can also send:\n * - `{}` (empty object) to clear the field.\n * - `null` to overwrite the field with a JSON `null` value. Prefer `{}` unless you specifically need a stored `null`.\n * @param organizationId - The ID of the Organization to replace the metadata for.\n * @param params - The metadata to replace.\n * @returns The updated [`Organization`](https://clerk.com/docs/reference/backend/types/backend-organization).\n */\n public async replaceOrganizationMetadata(organizationId: string, params: MetadataParams) {\n this.requireId(organizationId);\n\n return this.request<Organization>({\n method: 'PUT',\n path: joinPaths(basePath, organizationId, 'metadata'),\n bodyParams: params,\n });\n }\n\n /**\n * Deletes the given Organization.\n * @param organizationId - The ID of the Organization to delete.\n * @returns The deleted [`Organization`](https://clerk.com/docs/reference/backend/types/backend-organization).\n */\n public async deleteOrganization(organizationId: string) {\n this.requireId(organizationId);\n\n return this.request<Organization>({\n method: 'DELETE',\n path: joinPaths(basePath, organizationId),\n });\n }\n\n /**\n * Gets the list of Organization memberships for the specified Organization. By default, the list is returned in descending order by creation date (newest first).\n *\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`OrganizationMembership`](https://clerk.com/docs/reference/backend/types/backend-organization-membership) objects and a `totalCount` property containing the total number of Organization memberships for the Organization.\n *\n * > [!TIP]\n * > To get the list of Organization memberships **for your instance**, use [`getInstanceOrganizationMembershipList()`](/docs/reference/backend/organization/get-instance-organization-membership-list).\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 /**\n * Gets the list of Organization memberships for the instance. By default, the list is returned in descending order by creation date (newest first).\n *\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`OrganizationMembership`](https://clerk.com/docs/reference/backend/types/backend-organization-membership) objects and a `totalCount` property containing the total number of Organization memberships for the instance.\n *\n * > [!TIP]\n * > To get the list of Organization memberships **for a specific Organization**, use [`getOrganizationMembershipList()`](/docs/reference/backend/organization/get-organization-membership-list).\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 /**\n * Creates a membership to an Organization for a user directly (circumventing the need for an invitation).\n * @returns The newly created [`OrganizationMembership`](https://clerk.com/docs/reference/backend/types/backend-organization-membership) object.\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 /**\n * Updates a user's [`OrganizationMembership`](https://clerk.com/docs/reference/backend/types/backend-organization-membership).\n * @returns The updated [`OrganizationMembership`](https://clerk.com/docs/reference/backend/types/backend-organization-membership) object.\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 /**\n * Updates the metadata for the given Organization membership, by merging existing values with the provided parameters.\n *\n * A \"deep\" merge will be performed - \"deep\" means that any nested JSON objects will be merged as well. You can remove metadata keys at any level by setting their value to `null`.\n *\n * @returns The updated [`OrganizationMembership`](https://clerk.com/docs/reference/backend/types/backend-organization-membership).\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 /**\n * Removes a user from the given Organization.\n * @param organizationId - The ID of the Organization to remove the user from.\n * @param userId - The ID of the user to remove from the Organization.\n * @returns The deleted [`OrganizationMembership`](https://clerk.com/docs/reference/backend/types/backend-organization-membership).\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 /**\n * Gets the list of Organization invitations for the specified Organization.\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`OrganizationInvitation`](https://clerk.com/docs/reference/backend/types/backend-organization-invitation) objects and a `totalCount` property containing the total number of Organization invitations for the Organization.\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 /**\n * Creates an invitation for a user to join an Organization.\n * @returns The newly created [`OrganizationInvitation`](https://clerk.com/docs/reference/backend/types/backend-organization-invitation) object.\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 /** Creates multiple invitations for users to join an Organization.\n * @param organizationId - The ID of the Organization to create the invitations for.\n * @param params - The parameters to create the invitations with.\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`OrganizationInvitation`](https://clerk.com/docs/reference/backend/types/backend-organization-invitation) objects and a `totalCount` property containing the total number of Organization invitations.\n */\n public async createOrganizationInvitationBulk(\n organizationId: string,\n params: CreateBulkOrganizationInvitationParams,\n ) {\n this.requireId(organizationId);\n\n return this.request<PaginatedResourceResponse<OrganizationInvitation[]>>({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'invitations', 'bulk'),\n bodyParams: params,\n });\n }\n\n /** Gets an [`OrganizationInvitation`](https://clerk.com/docs/reference/backend/types/backend-organization-invitation). */\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 /**\n * Revokes an invitation from a user for the given Organization.\n * @returns The revoked [`OrganizationInvitation`](https://clerk.com/docs/reference/backend/types/backend-organization-invitation).\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 /**\n * Gets the list of [Verified Domains](https://clerk.com/docs/guides/organizations/add-members/verified-domains) for the given Organization. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`OrganizationDomain`](https://clerk.com/docs/reference/backend/types/backend-organization-domain) objects and a `totalCount` property containing the total number of Verified Domains for the Organization.\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 /**\n * Creates a new [Verified Domain](https://clerk.com/docs/guides/organizations/add-members/verified-domains) for the given Organization. By default, the domain is verified, but can be optionally set to unverified.\n * @returns The newly created [`OrganizationDomain`](https://clerk.com/docs/reference/backend/types/backend-organization-domain) object.\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 /**\n * Updates a [Verified Domain](https://clerk.com/docs/guides/organizations/add-members/verified-domains) for the given Organization.\n * @returns The updated [`OrganizationDomain`](https://clerk.com/docs/reference/backend/types/backend-organization-domain) object.\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 /**\n * Deletes a [Verified Domain](https://clerk.com/docs/guides/organizations/add-members/verified-domains) for the given Organization.\n * @returns The deleted [`OrganizationDomain`](https://clerk.com/docs/reference/backend/types/backend-organization-domain) object.\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/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { Permission } from '../resources/Permission';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/organization_permissions';\n\ntype GetOrganizationPermissionListParams = ClerkPaginationRequest<{\n /**\n * Returns organization permissions with ID, name, or key that match the given query.\n * Uses exact match for permission ID and partial match for name and key.\n */\n query?: string;\n /**\n * Allows to return organization permissions in a particular order.\n * At the moment, you can order the returned permissions by their `created_at`, `name`, or `key`.\n */\n orderBy?: WithSign<'created_at' | 'name' | 'key'>;\n}>;\n\ntype CreateOrganizationPermissionParams = {\n /**\n * The name of the permission.\n */\n name: string;\n /**\n * The key of the permission. Must have the format `org:feature:action`, for example `org:billing:manage`.\n * Cannot begin with `org:sys_` as that prefix is reserved for system permissions.\n */\n key: string;\n /**\n * A description of the permission.\n */\n description?: string;\n};\n\ntype UpdateOrganizationPermissionParams = {\n permissionId: string;\n} & Partial<CreateOrganizationPermissionParams>;\n\nexport class OrganizationPermissionAPI extends AbstractAPI {\n public async getOrganizationPermissionList(params: GetOrganizationPermissionListParams = {}) {\n return this.request<PaginatedResourceResponse<Permission[]>>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async getOrganizationPermission(permissionId: string) {\n this.requireId(permissionId);\n return this.request<Permission>({\n method: 'GET',\n path: joinPaths(basePath, permissionId),\n });\n }\n\n public async createOrganizationPermission(params: CreateOrganizationPermissionParams) {\n return this.request<Permission>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updateOrganizationPermission(params: UpdateOrganizationPermissionParams) {\n const { permissionId, ...bodyParams } = params;\n this.requireId(permissionId);\n return this.request<Permission>({\n method: 'PATCH',\n path: joinPaths(basePath, permissionId),\n bodyParams,\n });\n }\n\n public async deleteOrganizationPermission(permissionId: string) {\n this.requireId(permissionId);\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, permissionId),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { Role } from '../resources/Role';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/organization_roles';\n\ntype GetOrganizationRoleListParams = ClerkPaginationRequest<{\n /**\n * Returns organization roles with ID, name, or key that match the given query.\n * Uses exact match for organization role ID and partial match for name and key.\n */\n query?: string;\n /**\n * Allows to return organization roles in a particular order.\n * At the moment, you can order the returned organization roles by their `created_at`, `name`, or `key`.\n */\n orderBy?: WithSign<'created_at' | 'name' | 'key'>;\n}>;\n\ntype CreateOrganizationRoleParams = {\n /**\n * The name of the new organization role.\n */\n name: string;\n /**\n * A unique key for the organization role. Must start with `org:` and contain only lowercase\n * alphanumeric characters and underscores.\n */\n key: string;\n /**\n * Optional description for the role.\n */\n description?: string | null;\n /**\n * Array of permission IDs to assign to the role.\n */\n permissions?: string[] | null;\n /**\n * Whether this role should be included in the initial role set.\n */\n includeInInitialRoleSet?: boolean | null;\n};\n\ntype UpdateOrganizationRoleParams = {\n organizationRoleId: string;\n /**\n * The new name for the organization role.\n */\n name?: string | null;\n /**\n * A unique key for the organization role. Must start with `org:` and contain only lowercase\n * alphanumeric characters and underscores.\n */\n key?: string | null;\n /**\n * Optional description for the role.\n */\n description?: string | null;\n /**\n * Array of permission IDs to assign to the role. If provided, this will replace the existing permissions.\n */\n permissions?: string[] | null;\n};\n\ntype OrganizationRolePermissionParams = {\n organizationRoleId: string;\n permissionId: string;\n};\n\nexport class OrganizationRoleAPI extends AbstractAPI {\n public async getOrganizationRoleList(params: GetOrganizationRoleListParams = {}) {\n return this.request<PaginatedResourceResponse<Role[]>>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async getOrganizationRole(organizationRoleId: string) {\n this.requireId(organizationRoleId);\n return this.request<Role>({\n method: 'GET',\n path: joinPaths(basePath, organizationRoleId),\n });\n }\n\n public async createOrganizationRole(params: CreateOrganizationRoleParams) {\n return this.request<Role>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updateOrganizationRole(params: UpdateOrganizationRoleParams) {\n const { organizationRoleId, ...bodyParams } = params;\n this.requireId(organizationRoleId);\n return this.request<Role>({\n method: 'PATCH',\n path: joinPaths(basePath, organizationRoleId),\n bodyParams,\n });\n }\n\n public async deleteOrganizationRole(organizationRoleId: string) {\n this.requireId(organizationRoleId);\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, organizationRoleId),\n });\n }\n\n public async assignPermissionToOrganizationRole(params: OrganizationRolePermissionParams) {\n const { organizationRoleId, permissionId } = params;\n this.requireId(organizationRoleId);\n this.requireId(permissionId);\n return this.request<Role>({\n method: 'POST',\n path: joinPaths(basePath, organizationRoleId, 'permissions', permissionId),\n });\n }\n\n public async removePermissionFromOrganizationRole(params: OrganizationRolePermissionParams) {\n const { organizationRoleId, permissionId } = params;\n this.requireId(organizationRoleId);\n this.requireId(permissionId);\n return this.request<Role>({\n method: 'DELETE',\n path: joinPaths(basePath, organizationRoleId, 'permissions', permissionId),\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\n/** @generateWithEmptyComment */\nexport type CreateOAuthApplicationParams = {\n /**\n * A descriptive name for the OAuth application (e.g., \"My Web App\", \"My Mobile App\"). Maximum length: 256 characters.\n */\n name: string;\n /** An array of redirect URIs for the OAuth application. */\n redirectUris?: Array<string> | null | undefined;\n /** Scopes for the OAuth application 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 scopes?: string | null | undefined;\n /** Whether the OAuth application is public. If `true`, the Proof Key of Code Exchange (PKCE) flow can be used. */\n public?: boolean | null | undefined;\n};\n\n/** @generateWithEmptyComment */\nexport type UpdateOAuthApplicationParams = CreateOAuthApplicationParams & {\n /** The ID of the OAuth application to update. */\n oauthApplicationId: string;\n};\n\n/** @generateWithEmptyComment */\nexport type RevokeOAuthApplicationTokenParams = {\n /** The ID of the OAuth application for which to revoke the token. */\n oauthApplicationId: string;\n /** The opaque OAuth access token or refresh token to revoke. */\n token: string;\n};\n\n/** @generateWithEmptyComment */\nexport type GetOAuthApplicationListParams = ClerkPaginationRequest<{\n /**\n * Returns OAuth applications in a particular order. Prefix a value with `+` to sort in ascending order, or `-` to sort in descending order. Defaults to `-created_at`.\n */\n orderBy?: WithSign<'name' | 'created_at'>;\n}>;\n\n/** @generateWithEmptyComment */\nexport class OAuthApplicationsApi extends AbstractAPI {\n /**\n * Gets a list of OAuth applications for the instance. By default, the list is returned in descending order by creation date (newest first).\n * @param params - The parameters to get the OAuth applications with.\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`OAuthApplication`](https://clerk.com/docs/reference/backend/types/backend-oauth-application) objects and a `totalCount` property containing the total number of OAuth applications.\n */\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 /**\n * Gets the given OAuth application.\n * @param oauthApplicationId - The ID of the OAuth application to get.\n * @returns The [`OAuthApplication`](https://clerk.com/docs/reference/backend/types/backend-oauth-application) object.\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 /**\n * Creates a new OAuth application.\n * @param params - The parameters to create the OAuth application with.\n * @returns The created [`OAuthApplication`](https://clerk.com/docs/reference/backend/types/backend-oauth-application) object.\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 /**\n * Updates the given OAuth application.\n * @returns The updated [`OAuthApplication`](https://clerk.com/docs/reference/backend/types/backend-oauth-application) object.\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 /**\n * Deletes the given OAuth application.\n * @param oauthApplicationId - The ID of the OAuth application to delete.\n * @returns The [`DeletedObject`](https://clerk.com/docs/reference/backend/types/deleted-object) object.\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 /**\n * Rotates the secret of the given OAuth application. When the client secret is rotated, ensure that you update it in your authorized OAuth clients.\n * @param oauthApplicationId - The ID of the OAuth application to rotate the secret of.\n * @returns The [`OAuthApplication`](https://clerk.com/docs/reference/backend/types/backend-oauth-application) object.\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 /**\n * Revokes both the [OAuth access token](!oauth-access-token) and refresh token for the associated grant for the given [`OAuthApplication`](/docs/reference/backend/types/backend-oauth-application). The request may specify either token.\n */\n public async revokeToken(params: RevokeOAuthApplicationTokenParams) {\n const { oauthApplicationId, ...bodyParams } = params;\n\n this.requireId(oauthApplicationId);\n\n return this.request<void>({\n method: 'POST',\n path: joinPaths(basePath, oauthApplicationId, 'revoke_token'),\n bodyParams,\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\n/** @generateWithEmptyComment */\nexport type CreatePhoneNumberParams = {\n /** The ID of the user to create the phone number for. */\n userId: string;\n /** The phone number to assign to the specified user. Must be in [E.164 format](https://en.wikipedia.org/wiki/E.164). */\n phoneNumber: string;\n /** Whether the phone number should be verified. Defaults to `false`. */\n verified?: boolean;\n /** Whether the phone number should be the primary phone number. Defaults to `false`, unless it is the first phone number added to the user. */\n primary?: boolean;\n /** Whether the phone number should be reserved for [multi-factor authentication](https://clerk.com/docs/guides/configure/auth-strategies/sign-up-sign-in-options#multi-factor-authentication). The phone number must also be verified. If there are no other reserved [second factors](!second-factor-verification), the phone number will be set as the default second factor. Defaults to `false`. */\n reservedForSecondFactor?: boolean;\n};\n\n/** @inline */\nexport type UpdatePhoneNumberParams = {\n /** Whether the phone number should be verified. Defaults to `false`. */\n verified?: boolean;\n /** Whether the phone number should be the primary phone number. Defaults to `false`, unless it is the first phone number added to the user. */\n primary?: boolean;\n /** Whether the phone number should be reserved for [multi-factor authentication](https://clerk.com/docs/guides/configure/auth-strategies/sign-up-sign-in-options#multi-factor-authentication). The phone number must also be verified. If there are no other reserved [second factors](!second-factor-verification), the phone number will be set as the default second factor. Defaults to `false`. */\n reservedForSecondFactor?: boolean;\n};\n\n/** @generateWithEmptyComment */\nexport class PhoneNumberAPI extends AbstractAPI {\n /**\n * Gets the given [`PhoneNumber`](https://clerk.com/docs/reference/backend/types/backend-phone-number).\n * @param phoneNumberId - The ID of the phone number to get.\n */\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 /**\n * Creates a new phone number for the given user.\n * @returns The created [`PhoneNumber`](https://clerk.com/docs/reference/backend/types/backend-phone-number) object.\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 /**\n * Updates the given phone number.\n * @param phoneNumberId - The ID of the phone number to update.\n * @param params - The parameters to update the phone number.\n * @returns The updated [`PhoneNumber`](https://clerk.com/docs/reference/backend/types/backend-phone-number) object.\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 /**\n * Deletes the given phone number.\n * @param phoneNumberId - The ID of the phone number to delete.\n * @returns The [`DeletedObject`](https://clerk.com/docs/reference/backend/types/deleted-object) object.\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\n/** @generateWithEmptyComment */\nexport type CreateRedirectUrlParams = {\n /** The full URL value prefixed with `https://` or a custom scheme. For example, `https://my-app.com/oauth-callback` or `my-app://oauth-callback`. */\n url: string;\n};\n\n/** @generateWithEmptyComment */\nexport class RedirectUrlAPI extends AbstractAPI {\n /**\n * Gets a list of whitelisted redirect URLs for the instance. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`RedirectUrl`](https://clerk.com/docs/reference/backend/types/backend-redirect-url) objects and a `totalCount` property containing the total number of redirect URLs.\n */\n public async getRedirectUrlList() {\n return this.request<PaginatedResourceResponse<RedirectUrl[]>>({\n method: 'GET',\n path: basePath,\n queryParams: { paginated: true },\n });\n }\n\n /**\n * Gets the given [`RedirectUrl`](https://clerk.com/docs/reference/backend/types/backend-redirect-url).\n * @param redirectUrlId - The ID of the redirect URL to get.\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 /**\n * Creates a new redirect URL for the instance.\n * @returns The created [`RedirectUrl`](https://clerk.com/docs/reference/backend/types/backend-redirect-url) object.\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 /**\n * Deletes the given redirect URL.\n * @param redirectUrlId - The ID of the redirect URL to delete.\n * @returns The deleted [`RedirectUrl`](https://clerk.com/docs/reference/backend/types/backend-redirect-url) object.\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 } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { RoleSet } from '../resources/RoleSet';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/role_sets';\n\ntype GetRoleSetListParams = ClerkPaginationRequest<{\n /**\n * Returns role sets with ID, name, or key that match the given query.\n * Uses exact match for role set ID and partial match for name and key.\n */\n query?: string;\n /**\n * Allows to return role sets in a particular order.\n * At the moment, you can order the returned role sets by their `created_at`, `name`, or `key`.\n */\n orderBy?: WithSign<'created_at' | 'name' | 'key'>;\n}>;\n\ntype CreateRoleSetParams = {\n /**\n * The name of the new role set.\n */\n name: string;\n /**\n * A unique key for the role set. Must start with `role_set:` and contain only lowercase\n * alphanumeric characters and underscores. If not provided, a key will be generated from the name.\n */\n key?: string;\n /**\n * Optional description for the role set.\n */\n description?: string | null;\n /**\n * The key of the role to use as the default role for new organization members.\n * Must be one of the roles in the `roles` array.\n */\n defaultRoleKey: string;\n /**\n * The key of the role to assign to organization creators.\n * Must be one of the roles in the `roles` array.\n */\n creatorRoleKey: string;\n /**\n * The type of the role set. `initial` role sets are the default for new organizations.\n * Only one role set can be `initial` per instance.\n */\n type?: 'initial' | 'custom';\n /**\n * Array of role keys to include in the role set. Must contain at least one role and no more than 10 roles.\n */\n roles: string[];\n};\n\ntype UpdateRoleSetParams = {\n roleSetKeyOrId: string;\n /**\n * The new name for the role set.\n */\n name?: string | null;\n /**\n * A unique key for the role set. Must start with `role_set:` and contain only lowercase\n * alphanumeric characters and underscores.\n */\n key?: string | null;\n /**\n * Optional description for the role set.\n */\n description?: string | null;\n /**\n * Set to `initial` to make this the default role set for new organizations.\n * Only one role set can be `initial` per instance; setting this will change any existing initial role set to `custom`.\n */\n type?: 'initial' | null;\n /**\n * The key of the role to use as the default role for new organization members. Must be an existing role in the role set.\n */\n defaultRoleKey?: string | null;\n /**\n * The key of the role to assign to organization creators. Must be an existing role in the role set.\n */\n creatorRoleKey?: string | null;\n};\n\ntype AddRolesToRoleSetParams = {\n roleSetKeyOrId: string;\n /**\n * Array of role keys to add to the role set. Must contain at least one role and no more than 10 roles.\n */\n roleKeys: string[];\n /**\n * Optionally update the default role to one of the newly added roles.\n */\n defaultRoleKey?: string;\n /**\n * Optionally update the creator role to one of the newly added roles.\n */\n creatorRoleKey?: string;\n};\n\ntype ReplaceRoleInRoleSetParams = {\n roleSetKeyOrId: string;\n /**\n * The key of the role to remove from the role set.\n */\n roleKey: string;\n /**\n * The key of the role to reassign members to.\n */\n toRoleKey: string;\n};\n\ntype ReplaceRoleSetParams = {\n roleSetKeyOrId: string;\n /**\n * The key of the destination role set.\n */\n destRoleSetKey: string;\n /**\n * Mappings from source role keys to destination role keys.\n * Required if members have roles that need to be reassigned.\n */\n reassignmentMappings?: Record<string, string>;\n};\n\nexport class RoleSetAPI extends AbstractAPI {\n public async getRoleSetList(params: GetRoleSetListParams = {}) {\n return this.request<PaginatedResourceResponse<RoleSet[]>>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async getRoleSet(roleSetKeyOrId: string) {\n this.requireId(roleSetKeyOrId);\n return this.request<RoleSet>({\n method: 'GET',\n path: joinPaths(basePath, roleSetKeyOrId),\n });\n }\n\n public async createRoleSet(params: CreateRoleSetParams) {\n return this.request<RoleSet>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updateRoleSet(params: UpdateRoleSetParams) {\n const { roleSetKeyOrId, ...bodyParams } = params;\n this.requireId(roleSetKeyOrId);\n return this.request<RoleSet>({\n method: 'PATCH',\n path: joinPaths(basePath, roleSetKeyOrId),\n bodyParams,\n });\n }\n\n public async addRolesToRoleSet(params: AddRolesToRoleSetParams) {\n const { roleSetKeyOrId, ...bodyParams } = params;\n this.requireId(roleSetKeyOrId);\n return this.request<RoleSet>({\n method: 'POST',\n path: joinPaths(basePath, roleSetKeyOrId, 'roles'),\n bodyParams,\n });\n }\n\n public async replaceRoleInRoleSet(params: ReplaceRoleInRoleSetParams) {\n const { roleSetKeyOrId, ...bodyParams } = params;\n this.requireId(roleSetKeyOrId);\n return this.request<RoleSet>({\n method: 'POST',\n path: joinPaths(basePath, roleSetKeyOrId, 'roles', 'replace'),\n bodyParams,\n });\n }\n\n public async replaceRoleSet(params: ReplaceRoleSetParams) {\n const { roleSetKeyOrId, ...bodyParams } = params;\n this.requireId(roleSetKeyOrId);\n return this.request<DeletedObject>({\n method: 'POST',\n path: joinPaths(basePath, roleSetKeyOrId, 'replace'),\n bodyParams,\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\n/** @generateWithEmptyComment */\nexport type SessionListParams = ClerkPaginationRequest<{\n /** The ID of the client to get sessions for. */\n clientId?: string;\n /** The ID of the user to get sessions for. */\n userId?: string;\n /** The status of the sessions to get. */\n status?: SessionStatus;\n}>;\n\n/** @inline */\nexport type RefreshTokenParams = {\n /** The expired token to refresh. */\n expired_token: string;\n /** The refresh token to refresh. */\n refresh_token: string;\n /** The origin of the request. */\n request_origin: string;\n /** The originating IP address of the request. */\n request_originating_ip?: string;\n /** The headers of the request. */\n request_headers?: Record<string, string[]>;\n /** Whether to use suffixed cookies. */\n suffixed_cookies?: boolean;\n /** The format of the token to refresh. */\n format?: 'token' | 'cookie';\n};\n\n/** @generateWithEmptyComment */\nexport type CreateSessionParams = {\n /** The ID of the user to create a session for. */\n userId: string;\n};\n\n/** @generateWithEmptyComment */\nexport class SessionAPI extends AbstractAPI {\n /**\n * Gets a list of sessions for either the specified client or user. Requires either `clientId` or `userId` to be provided. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`Session`](https://clerk.com/docs/reference/backend/types/backend-session) objects and a `totalCount` property containing the total number of sessions.\n */\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 /**\n * Gets the given [`Session`](https://clerk.com/docs/reference/backend/types/backend-session).\n * @param sessionId - The ID of the session to get.\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 /**\n * Creates a new session for the given user.\n * @returns The created [`Session`](https://clerk.com/docs/reference/backend/types/backend-session).\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 /**\n * Revokes the given session. The user will be signed out from the client the session is associated with.\n * @param sessionId - The ID of the session to revoke.\n * @returns The revoked [`Session`](https://clerk.com/docs/reference/backend/types/backend-session).\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 * Gets a session token or generates a JWT using a specified template that is defined in the [**JWT templates**](https://dashboard.clerk.com/~/jwt-templates) page in the Clerk Dashboard.\n *\n * @param sessionId - The ID of the session to get the token for.\n * @param template - The name of the JWT template configured in the Clerk Dashboard to generate a new token from.\n * @param expiresInSeconds - The expiration time for the token in seconds. If not provided, uses the default expiration.\n *\n * @returns The generated token.\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 /**\n * Refreshes the given session.\n * @param sessionId - The ID of the session to refresh.\n * @param params - The parameters to refresh the session.\n * @returns The refreshed token.\n */\n public async refreshSession(\n sessionId: string,\n params: RefreshTokenParams & {\n /** The format of the token to refresh. */\n format: 'token';\n },\n ): 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\n/** @generateWithEmptyComment */\nexport type CreateSignInTokensParams = {\n /** The ID of the user to create the sign-in token for. */\n userId: string;\n /** The number of seconds until the sign-in token expires. By default, the duration is `2592000` (30 days). */\n expiresInSeconds: number;\n};\n\nconst basePath = '/sign_in_tokens';\n\n/** @generateWithEmptyComment */\nexport class SignInTokenAPI extends AbstractAPI {\n /**\n * Creates a new sign-in token for the given user. By default, sign-in tokens expire in 30 days. You can optionally specify a custom expiration time in seconds using the `expiresInSeconds` parameter.\n * @returns The created [`SignInToken`](https://clerk.com/docs/reference/backend/types/backend-sign-in-token) object.\n */\n public async createSignInToken(params: CreateSignInTokensParams) {\n return this.request<SignInToken>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n /**\n * Revokes the given sign-in token.\n * @param signInTokenId - The ID of the sign-in token to revoke.\n * @returns The revoked [`SignInToken`](https://clerk.com/docs/reference/backend/types/backend-sign-in-token) object.\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\n/** @generateWithEmptyComment */\nexport class TestingTokenAPI extends AbstractAPI {\n /**\n * Creates a [Testing Token](https://clerk.com/docs/guides/development/testing/overview#testing-tokens) for the instance.\n * @returns The created [`TestingToken`](https://clerk.com/docs/reference/backend/types/backend-testing-token) object.\n */\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 EmailAddress,\n OauthAccessToken,\n OrganizationInvitation,\n OrganizationMembership,\n PhoneNumber,\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\n/** @generateWithEmptyComment */\nexport type UserCountParams = {\n /** Counts users with emails that match the given query, via case-insensitive partial match. For example, `emailAddress=hello` will match a user with the email `HELLO@example.com`. Accepts up to 100 email addresses. */\n emailAddress?: string[];\n /** Counts users with phone numbers that match the given query, via case-insensitive partial match. For example, `phoneNumber=555` will match a user with the phone number `+1555xxxxxxx`. Accepts up to 100 phone numbers. */\n phoneNumber?: string[];\n /** Counts users with usernames that match the given query, via case-insensitive partial match. For example, `username=CoolUser` will match a user with the username `SomeCoolUser`. Accepts up to 100 usernames. */\n username?: string[];\n /** Counts users with Web3 wallet addresses that match the given query, via case-insensitive partial match. For example, `web3Wallet=0x1234567890` will match a user with the Web3 wallet address `0x1234567890`. Accepts up to 100 Web3 wallet addresses. */\n web3Wallet?: string[];\n /** Counts users matching the given query across email addresses, phone numbers, usernames, Web3 wallet addresses, user IDs, first names, and last names. Partial matches supported. For example, `query=hello` will match a user with the email `HELLO@example.com`. */\n query?: string;\n /** Counts users with the specified user IDs. Accepts up to 100 user IDs. */\n userId?: string[];\n /** Counts users with the specified external IDs. Accepts up to 100 external IDs. */\n externalId?: string[];\n};\n\n/** @generateWithEmptyComment */\nexport type UserListParams = ClerkPaginationRequest<{\n /** Filters users with the specified email addresses. Accepts up to 100 email addresses. */\n emailAddress?: string[];\n /** Filters users with the specified phone numbers. Accepts up to 100 phone numbers. */\n phoneNumber?: string[];\n /** Filters users with the specified usernames. Accepts up to 100 usernames. */\n username?: string[];\n /** Filters users with the specified Web3 wallet addresses. Accepts up to 100 Web3 wallet addresses. */\n web3Wallet?: string[];\n /** Filters users matching the given query across email addresses, phone numbers, usernames, Web3 wallet addresses, user IDs, first names, and last names. Partial matches supported. */\n query?: string;\n /** Filters users with the specified user IDs. Accepts up to 100 user IDs. */\n userId?: string[];\n /** Filters users with the specified external IDs. Accepts up to 100 external IDs. */\n externalId?: string[];\n /** Filters users in a particular order. Prefix a value with `+` to sort in ascending order, or `-` to sort in descending order. Defaults to `-created_at`.*/\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 /**\n * @deprecated Use `lastActiveAtAfter` instead. This parameter will be removed in a future version.\n */\n last_active_at_since?: number;\n /** Filters users who were last active before the given date (with millisecond precision). */\n lastActiveAtBefore?: number;\n /** Filters users who were last active after the given date (with millisecond precision). */\n lastActiveAtAfter?: number;\n /** Filters users who were created before the given date (with millisecond precision). */\n createdAtBefore?: number;\n /** Filters users who were created after the given date (with millisecond precision). */\n createdAtAfter?: number;\n /** Filters users who were last signed in after the given date (with millisecond precision). */\n lastSignInAtAfter?: number;\n /** Filters users who were last signed in before the given date (with millisecond precision). */\n lastSignInAtBefore?: number;\n /** Filters users who are members of the specified Organizations. Accepts up to 100 Organization IDs. */\n organizationId?: string[];\n}>;\n\n/** @inline */\nexport type UserMetadataParams = {\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 publicMetadata?: UserPublicMetadata;\n /** Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}. */\n privateMetadata?: UserPrivateMetadata;\n /** Metadata that can be read and set from the Frontend API. It's considered unsafe because it can be modified from the Frontend API. */\n unsafeMetadata?: UserUnsafeMetadata;\n};\n\n/** @inline */\nexport type 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\n/** @inline */\nexport type UserPasswordHashingParams = {\n /** In case you already have the password digests and not the passwords, you can use them for the newly created user via this property. The digests should be generated with one of the supported algorithms. The hashing algorithm can be specified using the `password_hasher` property. */\n passwordDigest: string;\n /**\n * The hashing algorithm that was used to generate the password digest. Must be one of the supported algorithms. For password hashers considered insecure (currently, `md5`, `md5_salted`, `sha256`, `sha256_salted`, `sha512_symfony`), the corresponding user password hashes will be transparently migrated to `bcrypt` (a secure hasher) upon the user's first successful password sign in. Insecure schemes are marked with `(insecure)` in the list below.\n *\n * <ul>\n * <li>`awscognito`</li>\n * <ul>\n * <li>When set, `password_digest` must be in the format of `awscognito#<userpoolid>#<clientid>#<identifier>`.</li>\n * <li> Upon a successful migration, `password_hasher` will be updated to `bcrypt`, and `password_digest` will be updated to a `bcrypt` hash. </li>\n * <li> See the [migration guide](/docs/guides/development/migrating/cognito) for usage details. </li>\n * </ul>\n * <li> [`bcrypt`](https://en.wikipedia.org/wiki/Bcrypt) </li>\n * <ul>\n * <li> When set, `password_digest` must be in the format of `$<algorithm version>$<cost>$<salt & hash>`. </li>\n * </ul>\n * <li> [`bcrypt_sha256_django`](https://docs.djangoproject.com/en/4.0/topics/auth/passwords/) </li>\n * <ul>\n * <li> This is the Django-specific variant of Bcrypt, using SHA256 hashing function. When set, `password_digest` must be in the format of (as exported from Django): `bcrypt_sha256$$<algorithm version>$<cost>$<salt & hash>`. </li>\n * </ul>\n * <li> [`bcrypt_peppered`](https://github.com/heartcombo/devise) </li>\n * <ul>\n * <li> Used in implementations such as Devise for Ruby on Rails applications. Identical to `bcrypt` except that a `pepper` string is appended to the input before hashing. When set, `password_digest` must be in the format of `$<algorithm version>$<cost>$<salt & hash>$<pepper>`. </li>\n * </ul>\n * <li> [`md5` (insecure)](https://en.wikipedia.org/wiki/MD5) </li>\n * <ul>\n * <li> When set, `password_digest` must be in the format of `5f4dcc3b5aa765d61d8327deb882cf99`. </li>\n * </ul>\n * <li> [`md5_salted` (insecure)](https://en.wikipedia.org/wiki/MD5) </li>\n * <ul>\n * <li> When set, `password_digest` must be in the format of `salt$hash`. </li>\n * <li> _salt:_ The salt used to generate the above hash. </li>\n * <li> _hash:_ A 32-length hex string. </li>\n * </ul>\n * <li> [`pbkdf2_sha1`](https://en.wikipedia.org/wiki/PBKDF2) </li>\n * <ul>\n * <li> When set, `password_digest` must be in the format of `pbkdf2_sha1$<iterations>$<salt>$<hash-as-hex-string>` or `pbkdf2_sha1$<iterations>$<salt-as-hex-string>$<hash-as-hex-string>$<key-length>`. </li>\n * <li> Accepts the salt as a hex-encoded string. If the salt is not a valid hex string, the raw bytes will be used instead. Accepts the hash as a hex-encoded string. Optionally accepts the key length as the last parameter (defaults to 32). </li>\n * </ul>\n * <li> [`pbkdf2_sha256`](https://en.wikipedia.org/wiki/PBKDF2) </li>\n * <ul>\n * <li> This is the PBKDF2 algorithm using the SHA256 hashing function. When set, `password_digest` must be in the format of `pbkdf2_sha256$<iterations>$<salt>$<hash>`. </li>\n * <li> Both the salt and the hash are expected to be base64-encoded. </li>\n * </ul>\n * <li> [`pbkdf2_sha512`](https://en.wikipedia.org/wiki/PBKDF2) </li>\n * <ul>\n * <li> This is the PBKDF2 algorithm using the SHA512 hashing function. When set, `password_digest` must be in the format of `pbkdf2_sha512$<iterations>$<salt>$<hash>`. </li>\n * <li> The salt is expected to be an unencoded string literal, and the hash should be hex-encoded. </li>\n * </ul>\n * <li> [`pbkdf2_sha512_hex`](https://en.wikipedia.org/wiki/PBKDF2) </li>\n * <ul>\n * <li> This is the PBKDF2 algorithm using the SHA512 hashing function. When set, `password_digest` must be in the format of `pbkdf2_sha512_hex$<iterations>$<salt>$<hash>`. </li>\n * <li> Both the salt and the hash are expected to be hex-encoded. </li>\n * </ul>\n * <li> [`pbkdf2_sha256_django`](https://docs.djangoproject.com/en/4.0/topics/auth/passwords/) </li>\n * <ul>\n * <li> This is the Django-specific variant of PBKDF2. When set, `password_digest` must be in the format of (as exported from Django): `pbkdf2_sha256$<iterations>$<salt>$<hash>`. </li>\n * <li> The salt is expected to be un-encoded, the hash is expected base64-encoded. </li>\n * </ul>\n * <li> [`phpass`](https://www.openwall.com/phpass/) </li>\n * <ul>\n * <li> Portable public domain password hashing framework for use in PHP applications. When set, `password_digest` must be in the format of `$P$<rounds><salt><encoded-checksum>`. </li>\n * <li> `$P$` is the prefix used to identify `phpass` hashes. </li>\n * <li> _rounds:_ A single character encoding a 6-bit integer representing the number of rounds used. </li>\n * <li> _salt:_ Eight characters drawn from `[./0-9A-Za-z]`, providing a 48-bit salt. </li>\n * <li> _encoded-checksum:_ 22 characters drawn from the same set, encoding the 128-bit checksum with MD5. </li>\n * </ul>\n * <li> [`scrypt_firebase`](https://firebaseopensource.com/projects/firebase/scrypt/) </li>\n * <ul>\n * <li> The Firebase-specific variant of scrypt. When set, `password_digest` must be in the format of `<hash>$<salt>$<signer key>$<salt separator>$<rounds>$<memory cost>`. </li>\n * <li> _hash:_ The actual Base64 hash. This can be retrieved when exporting the user from Firebase. </li>\n * <li> _salt:_ The salt used to generate the above hash. Again, this is given when exporting the user from Firebase. </li>\n * <li> _signer key:_ The base64 encoded signer key. </li>\n * <li> _salt separator:_ The base64 encoded salt separator. </li>\n * <li> _rounds:_ The number of rounds the algorithm needs to run. </li>\n * <li> _memory cost:_ The cost of the algorithm run. </li>\n * </ul>\n * <li> [`scrypt_werkzeug`](https://werkzeug.palletsprojects.com/en/3.0.x/utils/#werkzeug.security.generate_password_hash) </li>\n * <ul>\n * <li> The Werkzeug-specific variant of scrypt. When set, `password_digest` must be in the format of `$<algorithm args>$<salt>$<hash>`. </li>\n * <li> _algorithm args:_ The algorithm used to generate the hash. </li>\n * <li> _salt:_ The salt used to generate the above hash. </li>\n * <li> _hash:_ The actual Base64 hash. </li>\n * </ul>\n * <li> [`sha256` (insecure)](https://en.wikipedia.org/wiki/SHA-2) </li>\n * <ul>\n * <li> When set, `password_digest` must be a 64-length hex string. For example: `9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08`. </li>\n * </ul>\n * <li> [`sha256_salted` (insecure)](https://en.wikipedia.org/wiki/SHA-2) </li>\n * <ul>\n * <li> When set, `password_digest` must be in the format of `salt$hash`. </li>\n * <li> _salt:_ The salt used to generate the above hash. </li>\n * <li> _hash:_ A 64-length hex string. </li>\n * </ul>\n * <li> [`argon2`](https://argon2.online/) variants: `argon2i` and `argon2id`. </li>\n * <ul>\n * <li> Parts are demarcated by the `$` character, with the first part identifying the algorithm variant The middle part is a comma-separated list of the encoding options (memory, iterations, parallelism). The final part is the actual digest. </li>\n * <li> When set, `password_digest` must be in the format of `$argon2i$v=19$m=4096,t=3,p=1$4t6CL3P7YiHBtwESXawI8Hm20zJj4cs7/4/G3c187e0$m7RQFczcKr5bIR0IIxbpO2P0tyrLjf3eUW3M3QSwnLc`. </li>\n * <li> For the argon2id case, the value of the algorithm in the first part of the digest is `argon2id`: `$argon2id$v=19$m=64,t=4,p=8$Z2liZXJyaXNo$iGXEpMBTDYQ8G/71tF0qGjxRHEmR3gpGULcE93zUJVU`. </li>\n * </ul>\n * <li> [`sha512_symfony` (insecure)](https://symfony.com/doc/current/security/passwords.html) </li>\n * <ul>\n * <li> The legacy Symfony `MessageDigestPasswordEncoder` algorithm. We currently only support the SHA512 variant. When set, `password_digest` must be in the format of `sha512_symfony$iterations$salt$hash`. </li>\n * <li> _iterations:_ A number greater than 0. </li>\n * <li> _salt:_ The salt used to generate the above hash. </li>\n * <li> _hash:_ The actual Base64 hash. </li>\n * </ul>\n * </ul>\n *\n * If you need support for any particular hashing algorithm, [contact support](https://clerk.com/contact/support).\n */\n passwordHasher: PasswordHasher;\n};\n\n/** @generateWithEmptyComment */\nexport type CreateUserParams = {\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 /** The email address(es) to assign to the user. Must be unique across your instance. The first email address will be set as the users primary email address. */\n emailAddress?: string[];\n /** The phone number(s) to assign to the user. Must be unique across your instance. The first phone number will be set as the users primary phone number. */\n phoneNumber?: string[];\n /** The username to assign to the user. Must be unique across your instance. */\n username?: string;\n /** The plaintext password to give the user. Must be at least 8 characters long, and can't be in any list of hacked passwords. */\n password?: string;\n /** The first name to assign to the user. */\n firstName?: string;\n /** The last name to assign to the user. */\n lastName?: string;\n /** The locale of the user in BCP-47 format (e.g. `'en-US'`, `'fr-FR'`). */\n locale?: string;\n /** When set to `true`, all password checks are skipped. It is recommended to use this method only when migrating plaintext passwords to Clerk. Upon migration the user base should be prompted to pick stronger password. */\n skipPasswordChecks?: boolean;\n /** When set to `true`, password is not required anymore when creating the user and can be omitted. This is useful when you are trying to create a user that doesn't have a password, in an instance that is using passwords. **You cannot use this flag if password is the only way for a user to sign into your instance.** */\n skipPasswordRequirement?: boolean;\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 /** 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 * If TOTP is enabled on the instance, you can provide the secret to enable it on the newly created user without the need to reset it. Currently, the supported options are:\n * <ul>\n * <li>Period: 30 seconds</li>\n * <li>Code length: 6 digits</li>\n * <li>Algorithm: SHA1</li>\n * </ul>\n */\n totpSecret?: string;\n /** If backup codes are enabled on the instance, you can provide them to enable it on the newly created 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 /** 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 /** When set to `true`, the user is created already banned and cannot sign in. */\n banned?: boolean;\n /** When set to `true`, the user is created already locked. Requires the [user lockout feature](https://clerk.com/docs/guides/secure/user-lockout#lock-a-user-programmatically) to be enabled on the instance. */\n locked?: boolean;\n} & UserMetadataParams &\n (UserPasswordHashingParams | object);\n\n/** @inline */\nexport type UpdateUserParams = {\n /** The first name to assign to the user. */\n firstName?: string;\n /** The last name to assign to the user. */\n lastName?: string;\n /** The username to assign to the user. Must be unique across your instance. */\n username?: string;\n /** The plaintext password to assign to the user. Must be at least 8 characters long, and can not be in any list of hacked passwords. */\n password?: string;\n /** When set to `true`, all password checks are skipped. It is recommended to use this method only when migrating plaintext passwords to Clerk. Upon migration the user base should be prompted to pick stronger password. */\n skipPasswordChecks?: boolean;\n /** When set to `true`, the user is signed out from all their active sessions once their password is updated. */\n signOutOfOtherSessions?: boolean;\n /** The ID of the email address to set as primary. Must be verified and present on the given user. */\n primaryEmailAddressID?: string;\n /** When set to `true`, the user is notified that their primary email address has changed. */\n notifyPrimaryEmailAddressChanged?: boolean;\n /** The ID of the phone number to set as primary. Must be verified and present on the given user. */\n primaryPhoneNumberID?: string;\n /** The ID of the web3 wallets to set as primary. Must be verified and present on the given user. */\n primaryWeb3WalletID?: string;\n /** The ID of the image to set as the user's profile image. */\n profileImageID?: string;\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. Currently, the supported options are:\n * <ul>\n * <li> Period: 30 seconds </li>\n * <li> Code length: 6 digits </li>\n * <li> Algorithm: SHA1 </li>\n * </ul>\n */\n totpSecret?: string;\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 /** The ID of the user as used in your external systems or your previous authentication solution. Must be unique across your entire instance. */\n externalId?: string;\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 /** 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 /** 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 /** The locale of the user in BCP-47 format (e.g. `'en-US'`). */\n locale?: string;\n /** If `true`, the user can delete themselves with the Frontend API. */\n deleteSelfEnabled?: boolean;\n /** If `true`, the user can create Organizations with the Frontend API. */\n createOrganizationEnabled?: boolean;\n /** The maximum number of Organizations the user can create. `0` means unlimited. */\n createOrganizationsLimit?: number;\n /**\n * @deprecated Updating metadata via `updateUser()` is deprecated. Use [`updateUserMetadata()`](https://clerk.com/docs/reference/backend/user/update-user-metadata) for partial updates (deep merge) or [`replaceUserMetadata()`](https://clerk.com/docs/reference/backend/user/replace-user-metadata) for full replacement.\n */\n publicMetadata?: UserPublicMetadata;\n /**\n * @deprecated Updating metadata via `updateUser()` is deprecated. Use [`updateUserMetadata()`](https://clerk.com/docs/reference/backend/user/update-user-metadata) for partial updates (deep merge) or [`replaceUserMetadata()`](https://clerk.com/docs/reference/backend/user/replace-user-metadata) for full replacement.\n */\n privateMetadata?: UserPrivateMetadata;\n /**\n * @deprecated Updating metadata via `updateUser()` is deprecated. Use [`updateUserMetadata()`](https://clerk.com/docs/reference/backend/user/update-user-metadata) for partial updates (deep merge) or [`replaceUserMetadata()`](https://clerk.com/docs/reference/backend/user/replace-user-metadata) for full replacement.\n */\n unsafeMetadata?: UserUnsafeMetadata;\n} & (UserPasswordHashingParams | object);\n\n/** @generateWithEmptyComment */\nexport type GetOrganizationMembershipListParams = ClerkPaginationRequest<{\n /** The ID of the user to get the list of Organization memberships for. */\n userId: string;\n}>;\n\n/** @generateWithEmptyComment */\nexport type GetOrganizationInvitationListParams = ClerkPaginationRequest<{\n /** The ID of the user to get the list of Organization invitations for. */\n userId: string;\n /** Filters the invitations by the provided status. */\n status?: OrganizationInvitationStatus;\n}>;\n\n/** @generateWithEmptyComment */\nexport type VerifyPasswordParams = {\n /** The ID of the user to verify the password for. */\n userId: string;\n /** The password to verify. */\n password: string;\n};\n\n/** @generateWithEmptyComment */\nexport type VerifyTOTPParams = {\n /** The ID of the user to verify the TOTP for. */\n userId: string;\n /** The TOTP or backup code to verify. */\n code: string;\n};\n\n/** @generateWithEmptyComment */\nexport type DeleteUserPasskeyParams = {\n /** The ID of the user to delete the passkey for. */\n userId: string;\n /** The ID of the passkey identification to delete. */\n passkeyIdentificationId: string;\n};\n\n/** @generateWithEmptyComment */\nexport type DeleteWeb3WalletParams = {\n /** The ID of the user to delete the Web3 wallet for. */\n userId: string;\n /** The ID of the Web3 wallet identification to delete. */\n web3WalletIdentificationId: string;\n};\n\n/** @generateWithEmptyComment */\nexport type DeleteUserExternalAccountParams = {\n /** The ID of the user to delete the external account for. */\n userId: string;\n /** The ID of the external account to delete. */\n externalAccountId: string;\n};\n\n/** @inline */\nexport type SetPasswordCompromisedParams = {\n /** Whether to revoke all sessions of the user. Defaults to `false`. */\n revokeAllSessions?: boolean;\n};\n\ntype ReplaceUserEmailAddressParams = {\n /** The new email address. Must adhere to the RFC 5322 specification for email address format. */\n emailAddress: string;\n};\n\ntype ReplaceUserPhoneNumberParams = {\n /** The new phone number. Must adhere to the E.164 standard for phone number format. */\n phoneNumber: string;\n};\n\ntype UserID = {\n userId: string;\n};\n\n/** @generateWithEmptyComment */\nexport class UserAPI extends AbstractAPI {\n /**\n * Retrieves the list of users in your instance. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property that contains an array of [`User`](https://clerk.com/docs/reference/backend/types/backend-user) objects, and a `totalCount` property that indicates the total number of users in your instance.\n */\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 /**\n * Gets a [`User`](https://clerk.com/docs/reference/backend/types/backend-user) for the specified user ID.\n * @param userId - The ID of the user to retrieve.\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 /**\n * Creates a [`User`](https://clerk.com/docs/reference/backend/types/backend-user) in your instance.\n *\n * Your settings in the [Clerk Dashboard](https://dashboard.clerk.com) determine how you should setup your user model. Anything **Required** will need to be provided when creating a user. Trying to add a field that isn't enabled will result in an error.\n *\n * Any email address and phone number created using this method will be automatically verified.\n *\n * > [!CAUTION]\n * >\n * > This endpoint is [rate limited](/docs/guides/how-clerk-works/system-limits). For development instances, a rate limit rule of **100 requests per 10 seconds** is applied.\n * > For production instances, that limit goes up to **1000 requests per 10 seconds**.\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 /** Updates the given [`User`](https://clerk.com/docs/reference/backend/types/backend-user).\n * @param userId - The ID of the user to update.\n * @param params - The user attributes to update.\n */\n public async updateUser(userId: string, params: UpdateUserParams = {}) {\n this.requireId(userId);\n\n const { publicMetadata, privateMetadata, unsafeMetadata, ...rest } = params as UpdateUserParams &\n UserMetadataParams;\n const hasMetadata = publicMetadata !== undefined || privateMetadata !== undefined || unsafeMetadata !== undefined;\n const hasRest = Object.keys(rest).length > 0;\n\n if (hasMetadata) {\n deprecated(\n 'updateUser(userId, { publicMetadata | privateMetadata | unsafeMetadata })',\n 'Use updateUserMetadata for partial updates (merge) or replaceUserMetadata for full replacement.',\n );\n }\n\n if (!hasMetadata) {\n return this.request<User>({\n method: 'PATCH',\n path: joinPaths(basePath, userId),\n bodyParams: rest,\n });\n }\n\n if (hasRest) {\n await this.request<User>({\n method: 'PATCH',\n path: joinPaths(basePath, userId),\n bodyParams: rest,\n });\n }\n\n return this.request<User>({\n method: 'PUT',\n path: joinPaths(basePath, userId, 'metadata'),\n bodyParams: { publicMetadata, privateMetadata, unsafeMetadata },\n });\n }\n\n public async replaceUserEmailAddress(userId: string, params: ReplaceUserEmailAddressParams) {\n this.requireId(userId);\n\n return this.request<EmailAddress>({\n method: 'PUT',\n path: joinPaths(basePath, userId, 'email_address'),\n bodyParams: params,\n });\n }\n\n public async replaceUserPhoneNumber(userId: string, params: ReplaceUserPhoneNumberParams) {\n this.requireId(userId);\n\n return this.request<PhoneNumber>({\n method: 'PUT',\n path: joinPaths(basePath, userId, 'phone_number'),\n bodyParams: params,\n });\n }\n\n /**\n * Updates the profile image for the given user. To remove the profile image, see [`deleteUserProfileImage()`](https://clerk.com/docs/reference/backend/user/delete-user-profile-image).\n * @param userId - The ID of the user to update the profile image for.\n * @param params - The file to set as the user's profile image.\n * @returns The updated [`User`](https://clerk.com/docs/reference/backend/types/backend-user).\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 /**\n * Updates the metadata for the given user, by merging existing values with the provided parameters.\n *\n * A \"deep\" merge will be performed - \"deep\" means that any nested JSON objects will be merged as well. You can remove metadata keys at any level by setting their value to `null`.\n *\n * > [!TIP]\n * > If you want to fully replace the existing metadata instead of merging, use [`replaceUserMetadata()`](/docs/reference/backend/user/replace-user-metadata).\n * @param userId - The ID of the user to update.\n * @param params - The metadata to update.\n * @returns The updated [`User`](https://clerk.com/docs/reference/backend/types/backend-user).\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 /**\n * Replaces the metadata associated with the specified user. Unlike [`updateUserMetadata()`](/docs/reference/backend/user/update-user-metadata), which deep-merges into the existing metadata, this method uses replace semantics: when a metadata field is provided, its previous value is overwritten in full with no merging at any level.\n *\n * The distinction is at two layers:\n * - **Top-level field omission preserves the existing value.** Each top-level field (`publicMetadata`, `privateMetadata`, `unsafeMetadata`) is handled independently. If you don't include a field in the request, the stored value for that field is left untouched.\n * - **The value inside a provided field is replaced in full.** When you do include a field, its previous content is discarded — any nested keys present before but absent in the new value are dropped. There is no merge.\n *\n * For the provided field, you can also send:\n * - `{}` (empty object) to clear the field.\n * - `null` to overwrite the field with a JSON `null` value. Prefer `{}` unless you specifically need a stored `null`.\n * @param userId - The ID of the user to replace the metadata for.\n * @param params - The metadata to replace.\n * @returns The updated [`User`](https://clerk.com/docs/reference/backend/types/backend-user).\n */\n public async replaceUserMetadata(userId: string, params: UserMetadataParams) {\n this.requireId(userId);\n\n return this.request<User>({\n method: 'PUT',\n path: joinPaths(basePath, userId, 'metadata'),\n bodyParams: params,\n });\n }\n\n /**\n * Deletes the given [`User`](https://clerk.com/docs/reference/backend/types/backend-user).\n * @param userId - The ID of the user to delete.\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 /**\n * Gets the total number of users in your instance.\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 /**\n * Gets the corresponding [OAuth access token](!oauth-access-token) for a user that has previously authenticated with the given OAuth provider.\n * @param userId - The ID of the user to get the OAuth access tokens for.\n * @param provider - The OAuth provider to get the access tokens for. If using a custom OAuth provider, prefix the provider name with `custom_` (e.g. `oauth_custom_google`).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property that contains an array of [`OauthAccessToken`](https://clerk.com/docs/reference/backend/types/backend-oauth-access-token) objects, and a `totalCount` property that indicates the total number of OAuth access tokens for the specified user and provider.\n */\n public async getUserOauthAccessToken(\n userId: string,\n provider: OAuthProvider,\n ): Promise<PaginatedResourceResponse<OauthAccessToken[]>>;\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(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 /**\n * Disable all of a user's MFA methods (e.g. [OTP](!otp) sent via SMS, TOTP on their authenticator app) at once.\n * @param userId - The ID of the user to disable MFA for.\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 /**\n * Gets a list of the given user's Organization memberships. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property that contains an array of [`OrganizationMembership`](https://clerk.com/docs/reference/backend/types/backend-organization-membership) objects, and a `totalCount` property that indicates the total number of Organization memberships for the user.\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 /**\n * Gets a list of the given user's Organization invitations. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property that contains an array of [`OrganizationInvitation`](https://clerk.com/docs/reference/backend/types/backend-organization-invitation) objects, and a `totalCount` property that indicates the total number of Organization invitations for the user.\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 /** Check that the user's password matches the supplied input. Useful for custom auth flows and re-verification. */\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 /** Verify that the provided TOTP or backup code is valid for the user. Verifying a backup code will result it in being consumed (i.e. it will become invalid). Useful for custom auth flows and re-verification. */\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 /**\n * Marks the given [`User`](https://clerk.com/docs/reference/backend/types/backend-user) as banned, which means that all their sessions are revoked and they are not allowed to sign in again.\n * @param userId - The ID of the user to ban.\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 /**\n * Removes the ban mark from the given [`User`](https://clerk.com/docs/reference/backend/types/backend-user), allowing them to sign in again.\n * @param userId - The ID of the user to unban.\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 /**\n * Locks the given [`User`](https://clerk.com/docs/reference/backend/types/backend-user), which means that they are not allowed to sign in again until the lock expires or is manually unlocked. By default, lockout duration is 1 hour, but it can be configured in the application's [**Attack protection**](https://dashboard.clerk.com/~/protect/attack-protection) settings. See the [guide on user locks](https://clerk.com/docs/guides/secure/user-lockout).\n * @param userId - The ID of the user to lock.\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 /** Removes a sign-in lock from the given [`User`](https://clerk.com/docs/reference/backend/types/backend-user), allowing them to sign in again. See the [guide on user locks](https://clerk.com/docs/guides/secure/user-lockout).\n * @param userId - The ID of the user to unlock.\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 /**\n * Deletes a user's profile image.\n * @param userId - The ID of the user to delete the profile image for.\n * @returns The updated [`User`](https://clerk.com/docs/reference/backend/types/backend-user).\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 /**\n * Deletes the passkey identification for a given user and notifies them through email.\n * @returns The [`DeletedObject`](https://clerk.com/docs/reference/backend/types/deleted-object) object.\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 /**\n * Deletes a Web3 wallet identification for the given user.\n * @returns The [`DeletedObject`](https://clerk.com/docs/reference/backend/types/deleted-object) object.\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 /**\n * Deletes an external account for the given user.\n * @returns The [`DeletedObject`](https://clerk.com/docs/reference/backend/types/deleted-object) object.\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 /**\n * Deletes all backup codes for the given user.\n * @param userId - The ID of the user to delete backup codes for.\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 /**\n * Deletes all of the TOTP secrets for the given user.\n * @param userId - The ID of the user to delete the TOTP secrets for.\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 /**\n * Sets the given user's password as compromised. The user will be prompted to reset their password on their next sign-in. See the [guide on password protection and rules](/docs/guides/secure/password-protection-and-rules#reject-compromised-passwords) for more information.\n * @param userId - The ID of the user to set the password as compromised for.\n * @param params - Other parameters for the request.\n * @returns The updated [`User`](https://clerk.com/docs/reference/backend/types/backend-user).\n */\n public async setPasswordCompromised(\n userId: string,\n params: SetPasswordCompromisedParams = {\n revokeAllSessions: false,\n },\n ) {\n this.requireId(userId);\n return this.request<User>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'password', 'set_compromised'),\n bodyParams: params,\n });\n }\n\n /**\n * Unsets the given user's password as compromised. The user will no longer be prompted to reset their password on their next sign-in. See the [guide on password protection and rules](/docs/guides/secure/password-protection-and-rules#reject-compromised-passwords) for more information.\n * @param userId - The ID of the user to unset the password as compromised for.\n * @returns The updated [`User`](https://clerk.com/docs/reference/backend/types/backend-user).\n */\n public async unsetPasswordCompromised(userId: string) {\n this.requireId(userId);\n return this.request<User>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'password', 'unset_compromised'),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\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\n/** @generateWithEmptyComment */\nexport type WaitlistEntryListParams = ClerkPaginationRequest<{\n /** Filters waitlist entries by `email_address` or `id`. */\n query?: string;\n /** Filters waitlist entries by status. */\n status?: WaitlistEntryStatus;\n /** Filters waitlist entries in a particular order. Prefix a value with `+` to sort in ascending order, or `-` to sort in descending order. Defaults to `-created_at`. */\n orderBy?: WithSign<'created_at' | 'invited_at' | 'email_address'>;\n}>;\n\n/** @generateWithEmptyComment */\nexport type WaitlistEntryCreateParams = {\n /** The email address to add to the waitlist. */\n emailAddress: string;\n /** Whether to notify the user that their email address has been added to the waitlist. Notifies the user if the `emailAddress` is an email address. Defaults to `true`. */\n notify?: boolean;\n};\n\n/** @generateWithEmptyComment */\nexport type WaitlistEntryBulkCreateParams = Array<WaitlistEntryCreateParams>;\n\n/** @inline */\nexport type WaitlistEntryInviteParams = {\n /** Whether to ignore an existing invitation. Defaults to `false`. */\n ignoreExisting?: boolean;\n};\n\n/** @generateWithEmptyComment */\nexport class WaitlistEntryAPI extends AbstractAPI {\n /**\n * Gets a list of waitlist entries for the instance. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`WaitlistEntry`](https://clerk.com/docs/reference/backend/types/backend-waitlist-entry) objects and a `totalCount` property containing the total number of waitlist entries for the instance.\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 for the given email address. If the email address is already on the waitlist, no new entry will be created and the existing waitlist entry will be returned.\n * @returns The created or existing [`WaitlistEntry`](https://clerk.com/docs/reference/backend/types/backend-waitlist-entry) object.\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 * Creates multiple waitlist entries for the given email addresses. If an email address is already on the waitlist, no new entry will be created and the existing waitlist entry will be returned.\n * @returns An array of created or existing [`WaitlistEntry`](https://clerk.com/docs/reference/backend/types/backend-waitlist-entry) objects.\n */\n public async createBulk(params: WaitlistEntryBulkCreateParams) {\n return this.request<WaitlistEntry[]>({\n method: 'POST',\n path: joinPaths(basePath, 'bulk'),\n bodyParams: params,\n });\n }\n\n /**\n * Invites the given waitlist entry.\n * @param id - The waitlist entry ID.\n * @param params - Optional parameters for inviting the waitlist entry.\n * @returns The invited [`WaitlistEntry`](https://clerk.com/docs/reference/backend/types/backend-waitlist-entry) object.\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 * Rejects the given waitlist entry.\n * @param id - The ID of the waitlist entry to reject.\n * @returns The rejected [`WaitlistEntry`](https://clerk.com/docs/reference/backend/types/backend-waitlist-entry) object.\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 * Deletes the given pending waitlist entry.\n * @param id - The ID of the waitlist entry to delete.\n * @returns The [`DeletedObject`](https://clerk.com/docs/reference/backend/types/deleted-object) object.\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\n/** @generateWithEmptyComment */\nexport type GetPlanListParams = ClerkPaginationRequest<{\n /**\n * Filters plans by the type of payer.\n */\n payerType: 'org' | 'user';\n}>;\n\n/** @inline */\nexport type CancelSubscriptionItemParams = {\n /**\n * Whether the Subscription Item should be canceled immediately. If `false`, the Subscription Item will be canceled at the end of the current billing period.\n */\n endNow?: boolean;\n};\n\n/** @inline */\nexport type ExtendSubscriptionItemFreeTrialParams = {\n /**\n * The date to extend the free trial to. Must be in the future and not more than 365 days from the current trial end date.\n */\n extendTo: Date;\n};\n\n/** @generateWithEmptyComment */\nexport class BillingAPI extends AbstractAPI {\n /**\n * Gets the list of Billing Plans for the instance. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`BillingPlan`](https://clerk.com/docs/reference/backend/types/billing-plan) objects and a `totalCount` property containing the total number of Billing Plans for the instance.\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?: GetPlanListParams) {\n return this.request<PaginatedResourceResponse<BillingPlan[]>>({\n method: 'GET',\n path: joinPaths(basePath, 'plans'),\n queryParams: params,\n });\n }\n\n /**\n * Cancels the given Subscription Item.\n * @param subscriptionItemId - The ID of the Subscription Item to cancel.\n * @param params - The parameters for the request.\n * @returns The cancelled [`BillingSubscriptionItem`](https://clerk.com/docs/reference/backend/types/billing-subscription-item) object.\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 * Extends the free trial for the given Subscription Item.\n * @param subscriptionItemId - The ID of the Subscription Item to extend the free trial for.\n * @param params - The parameters for the request.\n * @returns The updated [`BillingSubscriptionItem`](https://clerk.com/docs/reference/backend/types/billing-subscription-item) object.\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 * Gets the [`BillingSubscription`](https://clerk.com/docs/reference/backend/types/billing-subscription) for the given Organization.\n * @param organizationId - The ID of the Organization to get the Billing Subscription for.\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 * Gets the [`BillingSubscription`](https://clerk.com/docs/reference/backend/types/billing-subscription) for the given User.\n * @param userId - The ID of the User to get the Billing Subscription for.\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 if (res.status === 204) {\n return {\n data: undefined as T,\n errors: null,\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 { AgentTaskJSON } from './JSON';\n\n/**\n * The Backend `AgentTask` object represents an Agent Task resource. Agent Tasks are used for testing purposes and allow creating sessions for users without requiring full authentication flows.\n */\nexport class AgentTask {\n constructor(\n /** The identifier for the agent, unique per `agent_name` within an instance. */\n readonly agentId: string,\n /** @deprecated Use `agentTaskId` instead. */\n readonly taskId: string,\n /** The unique identifier for this Agent Task. */\n readonly agentTaskId: string,\n /** The Frontend API URL that, when visited, creates a session for the user. Only returned by [`create()`](https://clerk.com/docs/reference/backend/agent-tasks/create); omitted from [`revoke()`](https://clerk.com/docs/reference/backend/agent-tasks/revoke). */\n readonly url: string,\n ) {}\n\n /**\n * Creates an AgentTask instance from a JSON object.\n *\n * @param data - The JSON object containing Agent Task data\n * @returns A new AgentTask instance\n */\n static fromJSON(data: AgentTaskJSON): AgentTask {\n const agentTaskId = data.agent_task_id ?? data.task_id ?? '';\n return new AgentTask(data.agent_id, agentTaskId, agentTaskId, data.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/model/AllowlistIdentifier){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class AllowlistIdentifier {\n constructor(\n /**\n * The unique identifier for the allowlist identifier.\n */\n readonly id: string,\n /** The identifier that was added to the allowlist. */\n readonly identifier: string,\n /** The type of the allowlist identifier. */\n readonly identifierType: AllowlistIdentifierType,\n /** The Unix timestamp when the allowlist identifier was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the allowlist identifier was last updated. */\n readonly updatedAt: number,\n /** The ID of the instance that this allowlist identifier belongs to. */\n readonly instanceId?: string,\n /** The ID of the invitation sent to the identifier. */\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\n/**\n * The Backend `APIKey` object holds information about an API key.\n */\nexport class APIKey {\n constructor(\n /** The unique identifier for the API key. */\n readonly id: string,\n /** The type of the API key. Currently always `'api_key'`. */\n readonly type: string,\n /** The API key's name. */\n readonly name: string,\n /** The user or organization ID that the API key is associated with. */\n readonly subject: string,\n /** An array of scopes that define what the API key can access. */\n readonly scopes: string[],\n /** Custom claims associated with the API key. */\n readonly claims: Record<string, any> | null,\n /** Whether the API key has been revoked. */\n readonly revoked: boolean,\n /** The reason for revoking the API key, if it has been revoked. */\n readonly revocationReason: string | null,\n /** Whether the API key has expired. */\n readonly expired: boolean,\n /** The Unix timestamp (in milliseconds) when the API key expires. `null` if the API key never expires. */\n readonly expiration: number | null,\n /** The user ID for the user creating the API key. */\n readonly createdBy: string | null,\n /** A description for the API key. */\n readonly description: string | null,\n /** The Unix timestamp (in milliseconds) when the API key was last used to authenticate a request. */\n readonly lastUsedAt: number | null,\n /** The Unix timestamp (in milliseconds) when the API key was created. */\n readonly createdAt: number,\n /** The Unix timestamp (in milliseconds) when the API key was last updated. */\n readonly updatedAt: number,\n /** The API key secret. */\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 /** The unique identifier for the session activity record. */\n readonly id: string,\n /** Whether the session activity came from a mobile device. */\n readonly isMobile: boolean,\n /** The IP address from which this session activity originated. */\n readonly ipAddress?: string,\n /** The city from which this session activity occurred. Resolved by IP address geo-location. */\n readonly city?: string,\n /** The country from which this session activity occurred. Resolved by IP address geo-location. */\n readonly country?: string,\n /** The version of the browser from which this session activity occurred. */\n readonly browserVersion?: string,\n /** The name of the browser from which this session activity occurred. */\n readonly browserName?: string,\n /** The type of the device which was used in this session activity. */\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/objects/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/model/Session){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class Session {\n constructor(\n /** The unique identifier for the `Session`. */\n readonly id: string,\n /** The ID of the client associated with the `Session`. */\n readonly clientId: string,\n /** The ID of the user associated with the `Session`. */\n readonly userId: string,\n /** The current state of the `Session`. */\n readonly status: string,\n /** The time the session was last active on the [`Client`](https://clerk.com/docs/reference/backend/types/backend-client). */\n readonly lastActiveAt: number,\n /** The Unix timestamp when the `Session` will expire. */\n readonly expireAt: number,\n /** The Unix timestamp when the `Session` will be abandoned. */\n readonly abandonAt: number,\n /** The Unix timestamp when the `Session` was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the `Session` was last updated. */\n readonly updatedAt: number,\n /** The ID of the last [Active Organization](!active-organization). */\n readonly lastActiveOrganizationId?: string,\n /** An object that provides additional information about this session, focused around user activity data. */\n readonly latestActivity?: SessionActivity,\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 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/objects/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/model/Client){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class Client {\n constructor(\n /** The unique identifier for the `Client`. */\n readonly id: string,\n /** An array of [Session](https://clerk.com/docs/reference/backend/types/backend-session) IDs associated with the `Client`. */\n readonly sessionIds: string[],\n /** An array of [`Session`](https://clerk.com/docs/reference/backend/types/backend-session) objects associated with the `Client`. */\n readonly sessions: Session[],\n /** The ID of the associated [`SignIn`](https://clerk.com/docs/reference/objects/sign-in). */\n readonly signInId: string | null,\n /** The ID of the associated [`SignUp`](https://clerk.com/docs/reference/objects/sign-up). */\n readonly signUpId: string | null,\n /** The ID of the last active [`Session`](https://clerk.com/docs/reference/backend/types/backend-session). */\n readonly lastActiveSessionId: string | null,\n /** The last authentication strategy used by the `Client`. */\n readonly lastAuthenticationStrategy: LastAuthenticationStrategy | null,\n /** The Unix timestamp when the `Client` was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the `Client` was last updated. */\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\n/**\n * The `DeletedObject` object represents an item that has been deleted from the database. It is used to represent the result of a delete operation.\n */\nexport class DeletedObject {\n constructor(\n /** The type of object that has been deleted. */\n readonly object: string,\n /** The unique identifier for the deleted object. */\n readonly id: string | null,\n /** The URL-friendly identifier for the deleted object. */\n readonly slug: string | null,\n /** Whether the object has been deleted. */\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\n/** The `Domain` object represents a domain that is managed by the instance. */\nexport class Domain {\n constructor(\n /** The unique identifier of the domain. */\n readonly id: string,\n /** The name of the domain. */\n readonly name: string,\n /** Whether the domain is a satellite domain. */\n readonly isSatellite: boolean,\n /** The Frontend API URL for the domain. */\n readonly frontendApiUrl: string,\n /** The development origin for the domain. */\n readonly developmentOrigin: string,\n /** The CNAME targets for the domain. */\n readonly cnameTargets: CnameTarget[],\n /** The [Account Portal](https://clerk.com/docs/guides/account-portal/overview) URL for the domain. */\n readonly accountsPortalUrl?: string | null,\n /** The [proxy URL](https://clerk.com/docs/guides/dashboard/dns-domains/proxy-fapi) for the domain. */\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 readonly userId?: string | null,\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 data.user_id,\n );\n }\n}\n","import type { IdentificationLinkJSON } from './JSON';\n\n/**\n * The `IdentificationLink` object contains information about any identifications that might be linked to the identifier (email address, phone number, etc.).\n */\nexport class IdentificationLink {\n constructor(\n /** The unique identifier for the identification link. */\n readonly id: string,\n /** The type of the identification link, e.g., `\"email_address\"`, `\"phone_number\"`, etc. */\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 /** The strategy pertaining to the parent sign-up or sign-in attempt. */\n readonly strategy: string,\n /** The redirect URL for an external verification. */\n readonly externalVerificationRedirectURL: URL | null = null,\n /** The number of attempts related to the verification. */\n readonly attempts: number | null = null,\n /** The Unix timestamp when the verification will expire. */\n readonly expireAt: number | null = null,\n /** The [nonce](https://en.wikipedia.org/wiki/Cryptographic_nonce) pertaining to the verification. */\n readonly nonce: string | null = null,\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 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\n/** @inline */\nexport class OrganizationDomainVerification {\n constructor(\n /** The current status of the verification. */\n readonly status: string,\n /** The strategy used to verify the domain. */\n readonly strategy: string,\n /** The number of verification attempts that have been made. */\n readonly attempts: number | null = null,\n /** The Unix timestamp when the current verification attempt expires. */\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 /** The unique identifier for the email address. */\n readonly id: string,\n /** The value of the email address. */\n readonly emailAddress: string,\n /** An object holding information on the verification of the email address. */\n readonly verification: Verification | null,\n /** An array of objects containing information about any identifications that might be linked to the email address. */\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 /** The unique identifier for the Feature. */\n readonly id: string,\n /** The name of the Feature. */\n readonly name: string,\n /** The description of the Feature. */\n readonly description: string | null,\n /** The URL-friendly identifier of the Feature. */\n readonly slug: string,\n /** The URL of the Feature's avatar image. */\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`](https://clerk.com/docs/reference/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/billing/GET/billing/plans){{ target: '_blank' }} 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 /** The unique identifier for the Plan. */\n readonly id: string,\n /** The name of the Plan. */\n readonly name: string,\n /** The URL-friendly identifier of the Plan. */\n readonly slug: string,\n /** The description of the Plan. */\n readonly description: string | null,\n /** Whether the Plan is the default Plan. */\n readonly isDefault: boolean,\n /** Whether the Plan is recurring. */\n readonly isRecurring: boolean,\n /** Whether the Plan has a base fee. */\n readonly hasBaseFee: boolean,\n /** Whether the Plan is displayed in the [`<PricingTable />`](https://clerk.com/docs/nextjs/reference/components/billing/pricing-table) component. */\n readonly publiclyVisible: boolean,\n /** The monthly fee of the Plan. */\n readonly fee: BillingMoneyAmount | null,\n /** The annual fee of the Plan. */\n readonly annualFee: BillingMoneyAmount | null,\n /** The annual fee of the Plan on a monthly basis. */\n readonly annualMonthlyFee: BillingMoneyAmount | null,\n /** The type of payer for the Plan. */\n readonly forPayerType: 'org' | 'user',\n /** The [Features](https://clerk.com/docs/reference/backend/types/feature) the Plan offers. */\n readonly features: Feature[],\n /** The URL of the Plan's avatar image. */\n readonly avatarUrl: string | null,\n /** The number of free trial days for this plan. */\n readonly freeTrialDays: number | null,\n /** Whether free trial is enabled for this plan. */\n readonly freeTrialEnabled: boolean,\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\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 data.avatar_url,\n data.free_trial_days,\n data.free_trial_enabled,\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`](https://clerk.com/docs/reference/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/billing/GET/billing/subscription_items){{ target: '_blank' }} 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 /** The unique identifier for the Subscription Item. */\n readonly id: string,\n /** The status of the Subscription Item. */\n readonly status: BillingSubscriptionItemJSON['status'],\n /** The period of the Plan associated with this Subscription Item. */\n readonly planPeriod: 'month' | 'annual',\n /** The Unix timestamp (milliseconds) of when the current period starts. */\n readonly periodStart: number,\n /** Information about the next scheduled payment for this Subscription Item. */\n readonly nextPayment:\n | {\n /** The amount of the next payment. */\n amount: number;\n /** The Unix timestamp (milliseconds) of when the next payment is scheduled. */\n date: number;\n }\n | null\n | undefined,\n /** The current amount for the Subscription Item. */\n readonly amount: BillingMoneyAmount | undefined,\n /** The Plan associated with this Subscription Item. */\n readonly plan: BillingPlan | null,\n /** The ID of the Plan associated with this Subscription Item. */\n readonly planId: string | null,\n /** The Unix timestamp (milliseconds) of when the Subscription Item was created. */\n readonly createdAt: number,\n /** The Unix timestamp (milliseconds) of when the Subscription Item was last updated. */\n readonly updatedAt: number,\n /** The Unix timestamp (milliseconds) of when the current period ends. */\n readonly periodEnd: number | null,\n /** The Unix timestamp (milliseconds) of when the Subscription Item was canceled. */\n readonly canceledAt: number | null,\n /** The Unix timestamp (milliseconds) of when the Subscription Item became past due. */\n readonly pastDueAt: number | null,\n /** The Unix timestamp (milliseconds) of when the Subscription Item ended. */\n readonly endedAt: number | null,\n /** The ID of the payer for this Subscription Item. */\n readonly payerId: string | undefined,\n /** Whether this Subscription Item is currently in a free trial period. */\n readonly isFreeTrial?: boolean,\n /** The lifetime amount paid for this Subscription Item. */\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`](https://clerk.com/docs/reference/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){{ target: '_blank' }} 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 /** The unique identifier for the Subscription. */\n readonly id: string,\n /** The current status of the Subscription. */\n readonly status: BillingSubscriptionJSON['status'],\n /** The ID of the payer for this Subscription. */\n readonly payerId: string,\n /** The Unix timestamp (milliseconds) of when the Subscription was created. */\n readonly createdAt: number,\n /** The Unix timestamp (milliseconds) of when the Subscription was last updated. */\n readonly updatedAt: number,\n /** The Unix timestamp (milliseconds) of when the Subscription became active. */\n readonly activeAt: number | null,\n /** The Unix timestamp (milliseconds) of when the Subscription became past due. */\n readonly pastDueAt: number | null,\n /** All of the Subscription Items in this Subscription. */\n readonly subscriptionItems: BillingSubscriptionItem[],\n /** Information about the next scheduled payment for this Subscription. */\n readonly nextPayment: {\n /** The Unix timestamp (milliseconds) of when the next payment is scheduled. */\n date: number;\n /** The amount of the next payment. */\n amount: BillingMoneyAmount;\n } | null,\n /** Whether the payer is eligible for a free trial. */\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 { EnterpriseAccountConnectionJSON, EnterpriseAccountJSON } from './JSON';\nimport { Verification } from './Verification';\n\n/**\n * The Backend `EnterpriseAccountConnection` object represents an enterprise SSO connection associated with an enterprise account.\n */\nexport class EnterpriseAccountConnection {\n constructor(\n /** The unique identifier for this enterprise connection. */\n readonly id: string,\n /** Whether the connection is currently active. */\n readonly active: boolean,\n /** Whether IdP-initiated SSO is allowed. */\n readonly allowIdpInitiated: boolean,\n /** Whether subdomains are allowed for this connection. */\n readonly allowSubdomains: boolean,\n /** Whether additional identifications are disabled for users authenticating via this connection. */\n readonly disableAdditionalIdentifications: boolean,\n /** The domain associated with this connection. */\n readonly domain: string,\n /** The public URL of the connection's logo, if available. */\n readonly logoPublicUrl: string | null,\n /** The name of the enterprise connection. */\n readonly name: string,\n /** The SSO protocol used (e.g., `saml` or `oauth`). */\n readonly protocol: string,\n /** The SSO provider (e.g., `saml_custom`, `saml_okta`). */\n readonly provider: string,\n /** Whether user attributes are synced from the IdP. */\n readonly syncUserAttributes: boolean,\n /** The Unix timestamp when this connection was created. */\n readonly createdAt: number,\n /** The Unix timestamp when this connection was last updated. */\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: EnterpriseAccountConnectionJSON): EnterpriseAccountConnection {\n return new EnterpriseAccountConnection(\n data.id,\n data.active,\n data.allow_idp_initiated,\n data.allow_subdomains,\n data.disable_additional_identifications,\n data.domain,\n data.logo_public_url,\n data.name,\n data.protocol,\n data.provider,\n data.sync_user_attributes,\n data.created_at,\n data.updated_at,\n );\n }\n}\n\n/**\n * The Backend `EnterpriseAccount` object represents an identification obtained via enterprise SSO (SAML or OIDC).\n */\nexport class EnterpriseAccount {\n constructor(\n /**\n * The unique identifier for this enterprise account.\n */\n readonly id: string,\n /**\n * Whether this enterprise account is currently active.\n */\n readonly active: boolean,\n /**\n * The email address associated with this enterprise account.\n */\n readonly emailAddress: string,\n /**\n * The enterprise connection through which this account was authenticated.\n */\n readonly enterpriseConnection: EnterpriseAccountConnection | null,\n /**\n * The user's first name as provided by the IdP.\n */\n readonly firstName: string | null,\n /**\n * The user's last name as provided by the IdP.\n */\n readonly lastName: string | null,\n /**\n * The SSO protocol used (e.g., `saml` or `oauth`).\n */\n readonly protocol: string,\n /**\n * The SSO provider (e.g., `saml_custom`, `saml_okta`).\n */\n readonly provider: string,\n /**\n * The unique ID of the user in the provider.\n */\n readonly providerUserId: 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>,\n /**\n * An object holding information on the verification of this enterprise account.\n */\n readonly verification: Verification | null,\n /**\n * The date when the user last authenticated via this enterprise account.\n */\n readonly lastAuthenticatedAt: number | null,\n /**\n * The ID of the enterprise connection associated with this account.\n */\n readonly enterpriseConnectionId: string | null,\n ) {}\n\n static fromJSON(data: EnterpriseAccountJSON): EnterpriseAccount {\n return new EnterpriseAccount(\n data.id,\n data.active,\n data.email_address,\n data.enterprise_connection && EnterpriseAccountConnection.fromJSON(data.enterprise_connection),\n data.first_name,\n data.last_name,\n data.protocol,\n data.provider,\n data.provider_user_id,\n data.public_metadata,\n data.verification && Verification.fromJSON(data.verification),\n data.last_authenticated_at,\n data.enterprise_connection_id,\n );\n }\n}\n","import type {\n EnterpriseConnectionJSON,\n EnterpriseConnectionOauthConfigJSON,\n EnterpriseConnectionSamlConnectionJSON,\n} from './JSON';\n\n/**\n * The Backend `EnterpriseConnectionSamlConnection` object holds information about a SAML enterprise connection for an instance or organization.\n */\nexport class EnterpriseConnectionSamlConnection {\n constructor(\n /** The unique identifier for the SAML connection. */\n readonly id: string,\n /** The name to use as a label for the connection. */\n readonly name: string,\n /** The Entity ID as provided by the Identity Provider (IdP). */\n readonly idpEntityId: string,\n /** The Single-Sign On URL as provided by the Identity Provider (IdP). */\n readonly idpSsoUrl: string,\n /** The X.509 certificate as provided by the Identity Provider (IdP). */\n readonly idpCertificate: string,\n /** The Unix timestamp when the Identity Provider (IdP) certificate was issued. */\n readonly idpCertificateIssuedAt: number,\n /** The Unix timestamp when the Identity Provider (IdP) certificate expires. */\n readonly idpCertificateExpiresAt: number,\n /** The URL which serves the Identity Provider (IdP) metadata. */\n readonly idpMetadataUrl: string,\n /** The XML content of the Identity Provider (IdP) metadata file. */\n readonly idpMetadata: string,\n /** The Assertion Consumer Service (ACS) URL of the connection. */\n readonly acsUrl: string,\n /** The Entity ID as provided by the Service Provider (Clerk). */\n readonly spEntityId: string,\n /** The metadata URL as provided by the Service Provider (Clerk). */\n readonly spMetadataUrl: string,\n /** Whether the connection syncs user attributes between the IdP and Clerk. */\n readonly syncUserAttributes: boolean,\n /** Whether users with an email address subdomain are allowed to use this connection. */\n readonly allowSubdomains: boolean,\n /** Whether IdP-initiated SSO is allowed. */\n readonly allowIdpInitiated: boolean,\n ) {}\n\n static fromJSON(data: EnterpriseConnectionSamlConnectionJSON): EnterpriseConnectionSamlConnection {\n return new EnterpriseConnectionSamlConnection(\n data.id,\n data.name,\n data.idp_entity_id,\n data.idp_sso_url,\n data.idp_certificate,\n data.idp_certificate_issued_at,\n data.idp_certificate_expires_at,\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.sync_user_attributes,\n data.allow_subdomains,\n data.allow_idp_initiated,\n );\n }\n}\n\n/**\n * OAuth configuration included on a Backend API {@link EnterpriseConnection} response.\n */\nexport class EnterpriseConnectionOauthConfig {\n constructor(\n /**\n * The unique identifier for the OAuth configuration.\n */\n readonly id: string,\n /**\n * The name to use as a label for the configuration.\n */\n readonly name: string,\n /**\n * The OAuth client ID.\n */\n readonly clientId: string,\n /**\n * The OpenID Connect discovery URL.\n */\n readonly discoveryUrl: string,\n /**\n * The public URL of the OAuth provider logo, if available.\n */\n readonly logoPublicUrl: string,\n /**\n * The date when the configuration was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the configuration was last updated.\n */\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: EnterpriseConnectionOauthConfigJSON): EnterpriseConnectionOauthConfig {\n return new EnterpriseConnectionOauthConfig(\n data.id,\n data.name,\n data.client_id,\n data.discovery_url,\n data.logo_public_url,\n data.created_at,\n data.updated_at,\n );\n }\n}\n\n/**\n * The Backend `EnterpriseConnection` object holds information about an enterprise connection (SAML or OAuth) for an instance or organization.\n */\nexport class EnterpriseConnection {\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 the enterprise. Sign-in flows using an email with this domain may use the connection.\n */\n readonly domains: Array<string>,\n /**\n * The Organization ID if the connection is scoped to an organization.\n */\n readonly organizationId: string | null,\n /**\n * Whether the connection is active or not.\n */\n readonly active: boolean,\n /**\n * Whether the connection syncs user attributes between the IdP and Clerk or not.\n */\n readonly syncUserAttributes: boolean,\n /**\n * Whether users with an email address subdomain are allowed to use this connection or not.\n */\n readonly allowSubdomains: boolean,\n /**\n * Whether additional identifications are disabled for this connection.\n */\n readonly disableAdditionalIdentifications: boolean,\n /**\n * The date when the connection was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the connection was last updated.\n */\n readonly updatedAt: number,\n /**\n * SAML connection details when the enterprise connection uses SAML.\n */\n readonly samlConnection: EnterpriseConnectionSamlConnection | null,\n /**\n * OAuth (OIDC) configuration when the enterprise connection uses OAuth.\n */\n readonly oauthConfig: EnterpriseConnectionOauthConfig | null,\n ) {}\n\n static fromJSON(data: EnterpriseConnectionJSON): EnterpriseConnection {\n return new EnterpriseConnection(\n data.id,\n data.name,\n data.domains,\n data.organization_id,\n data.active,\n data.sync_user_attributes,\n data.allow_subdomains,\n data.disable_additional_identifications,\n data.created_at,\n data.updated_at,\n data.saml_connection != null ? EnterpriseConnectionSamlConnection.fromJSON(data.saml_connection) : null,\n data.oauth_config != null ? EnterpriseConnectionOauthConfig.fromJSON(data.oauth_config) : null,\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 /** The unique identifier for this external account. */\n readonly id: string,\n /** The provider name (e.g., `google`). */\n readonly provider: string,\n /** The unique ID of the user in the provider. */\n readonly providerUserId: string,\n /** The identification with which this external account is associated. */\n readonly identificationId: string,\n /** @deprecated Use `identificationId` instead. */\n readonly externalId: string,\n /** The scopes that the user has granted access to. */\n readonly approvedScopes: string,\n /** The user's email address. */\n readonly emailAddress: string,\n /** The user's first name. */\n readonly firstName: string,\n /** The user's last name. */\n readonly lastName: string,\n /** The user's image URL. */\n readonly imageUrl: string,\n /** The user's username. */\n readonly username: string | null,\n /** The phone number related to this specific external account. */\n readonly phoneNumber: string | null,\n /** Metadata that can be read from the Frontend API and Backend API and can be set only from the [Backend API](https://clerk.com/docs/reference/backend-api). */\n readonly publicMetadata: Record<string, unknown> | null = {},\n /** A descriptive label to differentiate multiple external accounts of the same user for the same provider. */\n readonly label: string | null,\n /** An object holding information on the verification of this external account. */\n readonly verification: Verification | null,\n /**\n * The `eac_`-prefixed id of the external account resource, which is the id\n * `users.deleteUserExternalAccount()` expects. Only returned for Google and\n * Facebook accounts; for other providers it is `undefined` and `id` already\n * holds the `eac_` value. Use `externalAccountId ?? id` to get a deletable id.\n */\n readonly externalAccountId?: string,\n ) {}\n\n static fromJSON(data: ExternalAccountJSON): ExternalAccount {\n return new ExternalAccount(\n data.id,\n data.provider,\n data.provider_user_id,\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 data.external_account_id,\n );\n }\n}\n","import type { InstanceJSON } from './JSON';\n\n/** @generateWithEmptyComment */\nexport class Instance {\n constructor(\n /** The unique identifier for the instance. */\n readonly id: string,\n /** The type of instance environment, either `'production'` or `'development'`. */\n readonly environmentType: string,\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. 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.js, the origin is `capacitor://localhost`. */\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\n/** The `InstanceRestrictions` object represents the [restrictions](https://clerk.com/docs/guides/secure/restricting-access) settings for the current instance. */\nexport class InstanceRestrictions {\n constructor(\n /** Whether the instance has [**Allowlist**](https://clerk.com/docs/guides/secure/restricting-access#allowlist) enabled. */\n readonly allowlist: boolean,\n /** Whether the instance has [**Blocklist**](https://clerk.com/docs/guides/secure/restricting-access#blocklist) enabled. */\n readonly blocklist: boolean,\n /** Whether the instance has [**Block email subaddresses**](https://clerk.com/docs/guides/secure/restricting-access#block-email-subaddresses) enabled. */\n readonly blockEmailSubaddresses: boolean,\n /** Whether the instance has [**Block sign-ups that use disposable email domains**](https://clerk.com/docs/guides/secure/restricting-access#block-sign-ups-that-use-disposable-email-addresses) enabled. */\n readonly blockDisposableEmailDomains: boolean,\n /** Whether the instance has [**Ignore dots for Gmail addresses**](https://clerk.com/docs/guides/secure/restricting-access#block-email-subaddresses) enabled. */\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 /** The unique identifier for the `Invitation`. */\n readonly id: string,\n /** The email address that the invitation was sent to. */\n readonly emailAddress: string,\n /** [Metadata](https://clerk.com/docs/reference/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 readonly publicMetadata: Record<string, unknown> | null,\n /** The Unix timestamp when the `Invitation` was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the `Invitation` was last updated. */\n readonly updatedAt: number,\n /** The status of the `Invitation`. */\n readonly status: InvitationStatus,\n /** The URL that the user can use to accept the invitation. */\n readonly url?: string,\n /** Whether the `Invitation` has been revoked. */\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 AgentTask: 'agent_task',\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 EnterpriseAccount: 'enterprise_account',\n EnterpriseConnection: 'enterprise_connection',\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 RoleSet: 'role_set',\n RoleSetItem: 'role_set_item',\n RoleSetMigration: 'role_set_migration',\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 EnterpriseAccountConnectionJSON extends ClerkResourceJSON {\n active: boolean;\n allow_idp_initiated: boolean;\n allow_subdomains: boolean;\n disable_additional_identifications: boolean;\n domain: string;\n logo_public_url: string | null;\n name: string;\n protocol: string;\n provider: string;\n sync_user_attributes: boolean;\n created_at: number;\n updated_at: number;\n}\n\nexport interface EnterpriseAccountJSON extends ClerkResourceJSON {\n object: typeof ObjectType.EnterpriseAccount;\n active: boolean;\n email_address: string;\n enterprise_connection: EnterpriseAccountConnectionJSON | null;\n first_name: string | null;\n last_name: string | null;\n protocol: string;\n provider: string;\n provider_user_id: string | null;\n public_metadata: Record<string, unknown>;\n verification: VerificationJSON | null;\n last_authenticated_at: number | null;\n enterprise_connection_id: string | null;\n}\n\nexport interface ExternalAccountJSON extends ClerkResourceJSON {\n object: typeof ObjectType.ExternalAccount;\n /**\n * The `eac_`-prefixed external account id. Only present for Google and Facebook accounts.\n */\n external_account_id?: string;\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 // Only present for OIDC-compliant OAuth 2.0 providers when available\n id_token?: string;\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 last_active_at?: number;\n missing_member_with_elevated_permissions?: boolean;\n role_set_key?: string | null;\n}\n\nexport interface RoleSetItemJSON {\n object: typeof ObjectType.RoleSetItem;\n id: string;\n name: string;\n key: string;\n description: string | null;\n members_count?: number | null;\n has_members?: boolean | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface RoleSetMigrationJSON {\n object: typeof ObjectType.RoleSetMigration;\n id: string;\n organization_id: string | null;\n instance_id: string;\n source_role_set_id: string;\n dest_role_set_id: string | null;\n trigger_type: string;\n status: string;\n migrated_members: number;\n mappings: Record<string, string> | null;\n started_at?: number;\n completed_at?: number;\n created_at: number;\n updated_at: number;\n}\n\nexport interface RoleSetJSON {\n object: typeof ObjectType.RoleSet;\n id: string;\n name: string;\n key: string;\n description: string | null;\n roles: RoleSetItemJSON[];\n default_role: RoleSetItemJSON | null;\n creator_role: RoleSetItemJSON | null;\n type: 'initial' | 'custom';\n role_set_migration: RoleSetMigrationJSON | null;\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/** @inline */\nexport interface PublicOrganizationDataJSON extends ClerkResourceJSON {\n /** The name of the Organization. */\n name: string;\n /** The slug of the Organization. */\n slug: string;\n /** Holds the default Organization profile image. Compatible with Clerk's [Image Optimization](https://clerk.com/docs/guides/development/image-optimization). */\n image_url?: string;\n /** Whether the Organization has a profile image. */\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 AgentTaskJSON extends ClerkResourceJSON {\n object: typeof ObjectType.AgentTask;\n agent_id: string;\n agent_task_id: string;\n /**\n * @deprecated Use `agent_task_id` instead.\n */\n task_id: string;\n url: string;\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 enterprise_accounts: EnterpriseAccountJSON[];\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 EnterpriseConnectionSamlConnectionJSON {\n id: string;\n name: string;\n idp_entity_id: string;\n idp_sso_url: string;\n idp_certificate: string;\n idp_certificate_issued_at: number;\n idp_certificate_expires_at: number;\n idp_metadata_url: string;\n idp_metadata: string;\n acs_url: string;\n sp_entity_id: string;\n sp_metadata_url: string;\n sync_user_attributes: boolean;\n allow_subdomains: boolean;\n allow_idp_initiated: boolean;\n}\n\nexport interface EnterpriseConnectionOauthConfigJSON {\n id: string;\n name: string;\n client_id: string;\n discovery_url: string;\n logo_public_url: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface EnterpriseConnectionJSON extends ClerkResourceJSON {\n object: typeof ObjectType.EnterpriseConnection;\n name: string;\n domains: string[];\n organization_id: string | null;\n active: boolean;\n sync_user_attributes: boolean;\n allow_subdomains: boolean;\n disable_additional_identifications: boolean;\n created_at: number;\n updated_at: number;\n saml_connection?: EnterpriseConnectionSamlConnectionJSON | null;\n oauth_config?: EnterpriseConnectionOauthConfigJSON | null;\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_certificate_issued_at: number;\n idp_certificate_expires_at: number;\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 | null;\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 | null;\n annual_fee: BillingMoneyAmountJSON | null;\n annual_monthly_fee: BillingMoneyAmountJSON | null;\n for_payer_type: 'org' | 'user';\n features?: FeatureJSON[];\n free_trial_days: number | null;\n free_trial_enabled: boolean;\n avatar_url: string | null;\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 | null;\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 { MachineJSON } from './JSON';\n\n/**\n * The Backend `Machine` object holds information about a machine.\n */\nexport class Machine {\n constructor(\n /** The unique identifier for the machine. */\n readonly id: string,\n /** The name of the machine. */\n readonly name: string,\n /** The ID of the instance the machine belongs to. */\n readonly instanceId: string,\n /** The Unix timestamp when the machine was created. */\n readonly createdAt: number,\n /** The Unix timestamp when the machine was last updated. */\n readonly updatedAt: number,\n /** The machines that the current machine has access to. */\n readonly scopedMachines: Machine[],\n /** The default time-to-live (TTL) in seconds for tokens created by this machine. */\n readonly defaultTokenTtl: number,\n /** The secret key for the machine. */\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 /** The ID of the machine that has access to the target machine. */\n readonly fromMachineId: string,\n /** The ID of the machine that is being accessed. */\n readonly toMachineId: string,\n /** The Unix timestamp when the machine scope was created. */\n readonly createdAt?: number,\n /** Whether the machine scope has been deleted. */\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\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\n/**\n * The Backend `OauthAccessToken` object holds information about an OAuth access token associated with a user that has previously authenticated with a particular OAuth provider.\n */\nexport class OauthAccessToken {\n constructor(\n /** The ID of the external account associated with this token. */\n readonly externalAccountId: string,\n /** The OAuth provider (e.g., `google`, `github`). */\n readonly provider: string,\n /** The OAuth access token. */\n readonly token: string,\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 readonly publicMetadata: Record<string, unknown> = {},\n /** A descriptive label to differentiate multiple access tokens of the same user for the same provider. */\n readonly label: string,\n /** The scopes granted for this access token. */\n readonly scopes?: string[],\n /** The token secret, if applicable (e.g., for OAuth 1.0 providers). */\n readonly tokenSecret?: string,\n /** The Unix timestamp when the access token expires. */\n readonly expiresAt?: number,\n /** The user's OIDC ID Token, if available. This token contains user identity information as a JWT and is returned when the provider supports [OpenID Connect (OIDC)](/docs/guides/configure/auth-strategies/oauth/overview). Not all OAuth providers implement OIDC, so this field may be `undefined` for some providers. */\n readonly idToken?: string,\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 data.id_token,\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 /** The unique identifier for the OAuth application. */\n readonly id: string,\n /** The ID of the instance that this OAuth application belongs to. */\n readonly instanceId: string,\n /** The name of the new OAuth application. */\n readonly name: string,\n /** The ID of the client associated with the OAuth application. */\n readonly clientId: string,\n /** The public-facing URL of the OAuth application, often shown on consent screens. */\n readonly clientUri: string | null,\n /** The URL of the image or logo representing the OAuth application. */\n readonly clientImageUrl: string | null,\n /** Whether the OAuth application is dynamically registered. */\n readonly dynamicallyRegistered: boolean,\n /** Whether the consent screen should be displayed in the authentication flow. Cannot be disabled for dynamically registered OAuth applications. */\n readonly consentScreenEnabled: boolean,\n /** Whether the Proof Key of Code Exchange (PKCE) flow should be required in the authentication flow. */\n readonly pkceRequired: boolean,\n /** Whether the client is public. If true, the Proof Key of Code Exchange (PKCE) flow can be used. */\n readonly isPublic: boolean, // NOTE: `public` is reserved\n /** Scopes for the new OAuth application. */\n readonly scopes: string,\n /** An array of redirect URIs of the new OAuth application. */\n readonly redirectUris: Array<string>,\n /** The URL used to authorize the user and obtain an authorization code. */\n readonly authorizeUrl: string,\n /** The URL used by the client to exchange an authorization code for an access token. */\n readonly tokenFetchUrl: string,\n /** The URL where the client can retrieve user information using an access token. */\n readonly userInfoUrl: string,\n /** The OpenID Connect discovery endpoint URL for this OAuth application. */\n readonly discoveryUrl: string,\n /** The URL used to introspect and validate issued access tokens. */\n readonly tokenIntrospectionUrl: string,\n /** The Unix timestamp when the OAuth application was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the OAuth application was last updated. */\n readonly updatedAt: number,\n /** The client secret associated with the OAuth application. Empty if public client. */\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/objects/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/model/Organization){{ 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 /** The unique identifier for the Organization. */\n readonly id: string,\n /** The name of the Organization. */\n readonly name: string,\n /** The URL-friendly identifier of the user's active Organization. If supplied, it must be unique for the instance. */\n readonly slug: string,\n /** Holds the Organization's logo. Compatible with Clerk's [Image Optimization](https://clerk.com/docs/guides/development/image-optimization). */\n readonly imageUrl: string,\n /** Whether the Organization has an image. */\n readonly hasImage: boolean,\n /** The Unix timestamp when the Organization was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the Organization was last updated. */\n readonly updatedAt: number,\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 readonly publicMetadata: OrganizationPublicMetadata | null = {},\n /** Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}. */\n readonly privateMetadata: OrganizationPrivateMetadata = {},\n /** The maximum number of memberships allowed in the Organization. */\n readonly maxAllowedMemberships: number,\n /** Whether the Organization allows admins to delete users. */\n readonly adminDeleteEnabled: boolean,\n /** The number of members in the Organization. */\n readonly membersCount?: number,\n /** The ID of the user who created the Organization. */\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/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/model/OrganizationInvitation){{ 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 /** The unique identifier for the `OrganizationInvitation`. */\n readonly id: string,\n /** The email address of the user who is invited to the [`Organization`](https://clerk.com/docs/reference/backend/types/backend-organization). */\n readonly emailAddress: string,\n /** The [Role](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) of the invited user. */\n readonly role: OrganizationMembershipRole,\n /** The name of the [Role](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) of the invited user. */\n readonly roleName: string,\n /** The ID of the [`Organization`](https://clerk.com/docs/reference/backend/types/backend-organization) that the user is invited to. */\n readonly organizationId: string,\n /** The Unix timestamp when the invitation was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the invitation was last updated. */\n readonly updatedAt: number,\n /** The Unix timestamp when the invitation expires. */\n readonly expiresAt: number,\n /** The URL that the user can use to accept the invitation. */\n readonly url: string | null,\n /** The status of the invitation. */\n readonly status?: OrganizationInvitationStatus,\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 readonly publicMetadata: OrganizationInvitationPublicMetadata = {},\n /** Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}. */\n readonly privateMetadata: OrganizationInvitationPrivateMetadata = {},\n /** Public data about the Organization that the user is invited to. */\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/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/model/OrganizationMembership){{ 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 /** The unique identifier for the membership. */\n readonly id: string,\n /** The [Role](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) of the user. */\n readonly role: OrganizationMembershipRole,\n /** The [Permissions](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) granted to the user in the Organization. */\n readonly permissions: string[],\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 readonly publicMetadata: OrganizationMembershipPublicMetadata = {},\n /** Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}. */\n readonly privateMetadata: OrganizationMembershipPrivateMetadata = {},\n /** The Unix timestamp when the membership was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the membership was last updated. */\n readonly updatedAt: number,\n /** The Organization that the user is a member of. */\n readonly organization: Organization,\n /** Public information about the user that this membership belongs to. */\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\n/** The `OrganizationSettings` object represents the [Organization-related settings](https://clerk.com/docs/guides/organizations/configure) for the current instance. */\nexport class OrganizationSettings {\n constructor(\n /** Whether the instance has [Organizations](https://clerk.com/docs/guides/organizations/overview) enabled. */\n readonly enabled: boolean,\n /** The maximum number of [memberships allowed](https://clerk.com/docs/guides/organizations/configure#membership-limits) per Organization. */\n readonly maxAllowedMemberships: number,\n /** The maximum number of Roles allowed per Organization. */\n readonly maxAllowedRoles: number,\n /** The maximum number of Permissions allowed per Organization. */\n readonly maxAllowedPermissions: number,\n /** The default [Role](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) for an Organization creator. */\n readonly creatorRole: string,\n /** Whether [admins](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions#default-roles) are allowed to delete Organizations. */\n readonly adminDeleteEnabled: boolean,\n /** Whether the instance has [Verified Domains](https://clerk.com/docs/guides/organizations/add-members/verified-domains) enabled. */\n readonly domainsEnabled: boolean,\n /** Whether the instance has [Organization slugs](https://clerk.com/docs/guides/organizations/configure#organization-slugs) disabled. */\n readonly slugDisabled: boolean,\n /**\n * The [enrollment modes](https://clerk.com/docs/guides/organizations/add-members/verified-domains#enable-verified-domains) available for Verified Domains.\n *\n * <ul>\n * <li>`manual_invitation`: No automatic enrollment. Users with a matching email domain are not given any [invitation](https://clerk.com/docs/guides/organizations/add-members/verified-domains#automatic-invitations) or [suggestion](https://clerk.com/docs/guides/organizations/add-members/verified-domains#automatic-suggestions); an [admin](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions#default-roles) must invite them manually.</li>\n * <li>`automatic_invitation`: Users with a matching email domain automatically receive a pending [invitation](https://clerk.com/docs/reference/types/organization-invitation) (assigned the Organization's default Role) which they can accept to join.</li>\n * <li>`automatic_suggestion`: Users with a matching email domain automatically receive a [suggestion](https://clerk.com/docs/guides/organizations/add-members/verified-domains#automatic-suggestions) to join, which they can request.</li>\n * </ul>\n */\n readonly domainsEnrollmentModes: Array<DomainsEnrollmentModes>,\n /** The default [Role](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) for the Organization's [Verified Domains](https://clerk.com/docs/guides/organizations/add-members/verified-domains). */\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 type { PermissionJSON } from './JSON';\n\n/**\n * The Backend `Permission` object represents an organization permission that can be assigned to organization roles.\n */\nexport class Permission {\n constructor(\n /** The unique identifier for the permission. */\n readonly id: string,\n /** The name of the permission. */\n readonly name: string,\n /** The unique key of the permission, in the format `org:feature:action`. */\n readonly key: string,\n /** A description of the permission. */\n readonly description: string,\n /** The Unix timestamp when the permission was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the permission was last updated. */\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: PermissionJSON): Permission {\n return new Permission(data.id, data.name, data.key, data.description, data.created_at, data.updated_at);\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 /** The unique identifier for this phone number. */\n readonly id: string,\n /** The value of this phone number, in [E.164 format](https://en.wikipedia.org/wiki/E.164). */\n readonly phoneNumber: string,\n /** Whether the phone number is reserved for multi-factor authentication (2FA). */\n readonly reservedForSecondFactor: boolean,\n /** Whether the phone number is the default second factor. A user must have exactly one default second factor, if multi-factor authentication (2FA) is enabled. */\n readonly defaultSecondFactor: boolean,\n /** An object holding information on the verification of this phone number. */\n readonly verification: Verification | null,\n /** An object containing information about any other identification that might be linked to this phone number. */\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 /** The unique identifier for the redirect URL. */\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 /** The Unix timestamp when the redirect URL was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the redirect URL was last updated. */\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 { RoleJSON } from './JSON';\nimport { Permission } from './Permission';\n\n/**\n * The Backend `Role` object represents an Organization [Role](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) that can be assigned to Organization members.\n */\nexport class Role {\n constructor(\n /** The unique identifier for the Role. */\n readonly id: string,\n /** The name of the Role. */\n readonly name: string,\n /** The unique key of the Role, in the format `org:role`. */\n readonly key: string,\n /** A description of the Role. */\n readonly description: string | null,\n /** The [Permissions](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) assigned to the Role. */\n readonly permissions: Permission[],\n /** Whether this Role is eligible to be an Organization creator Role. */\n readonly isCreatorEligible: boolean,\n /** The Unix timestamp when the Role was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the Role was last updated. */\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: RoleJSON): Role {\n return new Role(\n data.id,\n data.name,\n data.key,\n data.description,\n (data.permissions ?? []).map(permission => Permission.fromJSON(permission)),\n data.is_creator_eligible,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { RoleSetItemJSON, RoleSetJSON, RoleSetMigrationJSON } from './JSON';\n\n/**\n * The Backend `RoleSetItem` object represents a [Role](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) that belongs to a {@link RoleSet}.\n */\nexport class RoleSetItem {\n constructor(\n /** The unique identifier for the Role. */\n readonly id: string,\n /** The name of the Role. */\n readonly name: string,\n /** The unique key of the Role. */\n readonly key: string,\n /** A description of the Role. */\n readonly description: string | null,\n /** The Unix timestamp when the Role was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the Role was last updated. */\n readonly updatedAt: number,\n /** The number of Organization members that have this Role. */\n readonly membersCount?: number | null,\n /** Whether any Organization members have this Role. */\n readonly hasMembers?: boolean | null,\n ) {}\n\n static fromJSON(data: RoleSetItemJSON): RoleSetItem {\n return new RoleSetItem(\n data.id,\n data.name,\n data.key,\n data.description,\n data.created_at,\n data.updated_at,\n data.members_count,\n data.has_members,\n );\n }\n}\n\n/**\n * The Backend `RoleSetMigration` object holds information about an in-progress migration between role sets.\n */\nexport class RoleSetMigration {\n constructor(\n readonly id: string,\n readonly organizationId: string | null,\n readonly instanceId: string,\n readonly sourceRoleSetId: string,\n readonly destRoleSetId: string | null,\n readonly triggerType: string,\n readonly status: string,\n readonly migratedMembers: number,\n readonly mappings: Record<string, string> | null,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly startedAt?: number,\n readonly completedAt?: number,\n ) {}\n\n static fromJSON(data: RoleSetMigrationJSON): RoleSetMigration {\n return new RoleSetMigration(\n data.id,\n data.organization_id,\n data.instance_id,\n data.source_role_set_id,\n data.dest_role_set_id,\n data.trigger_type,\n data.status,\n data.migrated_members,\n data.mappings,\n data.created_at,\n data.updated_at,\n data.started_at,\n data.completed_at,\n );\n }\n}\n\n/**\n * The Backend `RoleSet` object represents a collection of roles that can be assigned to organization members.\n */\nexport class RoleSet {\n constructor(\n /**\n * The unique identifier for the role set.\n */\n readonly id: string,\n /**\n * The name of the role set.\n */\n readonly name: string,\n /**\n * The unique key of the role set.\n */\n readonly key: string,\n /**\n * A description of the role set.\n */\n readonly description: string | null,\n /**\n * The roles that belong to the role set.\n */\n readonly roles: RoleSetItem[],\n /**\n * The default role assigned to new organization members.\n */\n readonly defaultRole: RoleSetItem | null,\n /**\n * The role assigned to the creator of an organization.\n */\n readonly creatorRole: RoleSetItem | null,\n /**\n * The type of the role set. `initial` role sets are the default for new organizations.\n */\n readonly type: 'initial' | 'custom',\n /**\n * Active migration information, only present when a migration is in progress.\n */\n readonly roleSetMigration: RoleSetMigration | null,\n /**\n * The date when the role set was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the role set was last updated.\n */\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: RoleSetJSON): RoleSet {\n return new RoleSet(\n data.id,\n data.name,\n data.key,\n data.description,\n (data.roles ?? []).map(role => RoleSetItem.fromJSON(role)),\n data.default_role ? RoleSetItem.fromJSON(data.default_role) : null,\n data.creator_role ? RoleSetItem.fromJSON(data.creator_role) : null,\n data.type,\n data.role_set_migration ? RoleSetMigration.fromJSON(data.role_set_migration) : null,\n data.created_at,\n data.updated_at,\n );\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 * @deprecated Use [`EnterpriseConnection`](https://clerk.com/docs/reference/backend/types/backend-enterprise-connection) instead.\n */\nexport class SamlConnection {\n constructor(\n /** The unique identifier for the connection. */\n readonly id: string,\n /** The name to use as a label for the connection. */\n readonly name: string,\n /** The domain of your Organization. Sign in flows using an email with this domain will use the connection. */\n readonly domain: string,\n /** The Organization ID of the Organization. */\n readonly organizationId: string | null,\n /** The Entity ID as provided by the Identity Provider (IdP). */\n readonly idpEntityId: string | null,\n /** The Single-Sign On URL as provided by the Identity Provider (IdP). */\n readonly idpSsoUrl: string | null,\n /** The X.509 certificate as provided by the Identity Provider (IdP). */\n readonly idpCertificate: string | null,\n /** The Unix timestamp when the Identity Provider (IdP) certificate was issued. */\n readonly idpCertificateIssuedAt: number,\n /** The Unix timestamp when the Identity Provider (IdP) certificate expires. */\n readonly idpCertificateExpiresAt: number,\n /** The URL which serves the Identity Provider (IdP) metadata. If present, it takes priority over the corresponding individual properties. */\n readonly idpMetadataUrl: string | null,\n /** The XML content of the Identity Provider (IdP) metadata file. If present, it takes priority over the corresponding individual properties. */\n readonly idpMetadata: string | null,\n /** The Assertion Consumer Service (ACS) URL of the connection. */\n readonly acsUrl: string,\n /** The Entity ID as provided by the Service Provider (Clerk). */\n readonly spEntityId: string,\n /** The metadata URL as provided by the Service Provider (Clerk). */\n readonly spMetadataUrl: string,\n /** Whether the connection is active or not. */\n readonly active: boolean,\n /** The Identity Provider (IdP) of the connection. */\n readonly provider: string,\n /** The number of users associated with the connection. */\n readonly userCount: number,\n /** Whether the connection syncs user attributes between the Service Provider (SP) and Identity Provider (IdP) or not. */\n readonly syncUserAttributes: boolean,\n /** Whether users with an email address subdomain are allowed to use this connection in order to authenticate or not. */\n readonly allowSubdomains: boolean,\n /** Whether the connection allows Identity Provider (IdP) initiated flows or not. */\n readonly allowIdpInitiated: boolean,\n /** The Unix timestamp when the connection was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the connection was last updated. */\n readonly updatedAt: number,\n /** Defines the attribute name mapping between the Identity Provider (IdP) and Clerk's [`User`](https://clerk.com/docs/reference/objects/user) properties. */\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_certificate_issued_at,\n data.idp_certificate_expires_at,\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\n/**\n * The Backend `SignInToken` object holds information about a sign-in token.\n */\nexport class SignInToken {\n constructor(\n /** The unique identifier for the token. */\n readonly id: string,\n /** The ID of the user the token is for. */\n readonly userId: string,\n /** The token itself. */\n readonly token: string,\n /** The status of the token. */\n readonly status: string,\n /** The URL the token is for. */\n readonly url: string,\n /** The Unix timestamp when the token was created. */\n readonly createdAt: number,\n /** The Unix timestamp when the token was last updated. */\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 /** The unique ID for the Web3 wallet. */\n readonly id: string,\n /** The Web3 wallet address, made up of 0x + 40 hexadecimal characters. */\n readonly web3Wallet: string,\n /** An object holding information on the verification of this Web3 wallet. */\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 { EnterpriseAccount } from './EnterpriseAccount';\nimport { ExternalAccount } from './ExternalAccount';\nimport type { EnterpriseAccountJSON, 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/model/User){{ 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 /** The unique identifier for the user. */\n readonly id: string,\n /** Whether the user has a password on their account. */\n readonly passwordEnabled: boolean,\n /** Whether the user has enabled TOTP by generating a TOTP secret and verifying it via an authenticator app. */\n readonly totpEnabled: boolean,\n /** Whether the user has enabled Backup codes. */\n readonly backupCodeEnabled: boolean,\n /** Whether the user has enabled two-factor authentication. */\n readonly twoFactorEnabled: boolean,\n /** Whether the user is banned or not. */\n readonly banned: boolean,\n /** Whether the user is [locked](https://clerk.com/docs/guides/secure/user-lockout) or not. */\n readonly locked: boolean,\n /** The Unix timestamp when the user was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the user was last updated. */\n readonly updatedAt: number,\n /** The URL of the user's profile image. */\n readonly imageUrl: string,\n /** Whether the user has uploaded an image or one was copied from OAuth. Returns `false` if Clerk is displaying an avatar for the user. */\n readonly hasImage: boolean,\n /** The ID for the `EmailAddress` that the user has set as primary. */\n readonly primaryEmailAddressId: string | null,\n /** The ID for the `PhoneNumber` that the user has set as primary. */\n readonly primaryPhoneNumberId: string | null,\n /** The ID for the [`Web3Wallet`](https://clerk.com/docs/reference/backend/types/backend-web3-wallet) that the user signed up with. */\n readonly primaryWeb3WalletId: string | null,\n /** The Unix timestamp when the user last signed in. May be empty if the user has never signed in. */\n readonly lastSignInAt: number | null,\n /** The ID of the user as used in your external systems. Must be unique across your instance. */\n readonly externalId: string | null,\n /** The user's username. */\n readonly username: string | null,\n /** The user's first name. */\n readonly firstName: string | null,\n /** The user's last name. */\n readonly lastName: string | null,\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 readonly publicMetadata: UserPublicMetadata = {},\n /** Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}. */\n readonly privateMetadata: UserPrivateMetadata = {},\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 readonly unsafeMetadata: UserUnsafeMetadata = {},\n /** An array of all the `EmailAddress` objects associated with the user. Includes the primary. */\n readonly emailAddresses: EmailAddress[] = [],\n /** An array of all the `PhoneNumber` objects associated with the user. Includes the primary. */\n readonly phoneNumbers: PhoneNumber[] = [],\n /** An array of all the `Web3Wallet` objects associated with the user. Includes the primary. */\n readonly web3Wallets: Web3Wallet[] = [],\n /** An array of all the `ExternalAccount` objects associated with the user via OAuth. **Note**: This includes both verified & unverified external accounts. */\n readonly externalAccounts: ExternalAccount[] = [],\n /** An array of all the `EnterpriseAccount` objects associated with the user via enterprise SSO. */\n readonly enterpriseAccounts: EnterpriseAccount[] = [],\n /** The Unix timestamp when the user was last active. */\n readonly lastActiveAt: number | null,\n /** Whether the Organization creation is enabled for the user or not. */\n readonly createOrganizationEnabled: boolean,\n /** 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 readonly createOrganizationsLimit: number | null = null,\n /** Whether the user can delete their own account. */\n readonly deleteSelfEnabled: boolean,\n /** The Unix timestamp 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 readonly legalAcceptedAt: number | null,\n\n /** The locale of the user in BCP-47 format. */\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.enterprise_accounts || []).map((x: EnterpriseAccountJSON) => EnterpriseAccount.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\n/**\n * The Backend `WaitlistEntry` object holds information about a [waitlist entry](https://clerk.com/docs/guides/secure/restricting-access#waitlist).\n */\nexport class WaitlistEntry {\n constructor(\n /** The unique identifier for the waitlist entry. */\n readonly id: string,\n /** The email address to add to the waitlist. */\n readonly emailAddress: string,\n /** The status of the waitlist entry. */\n readonly status: WaitlistEntryStatus,\n /** The invitation associated with the waitlist entry. */\n readonly invitation: Invitation | null,\n /** The Unix timestamp when the waitlist entry was created. */\n readonly createdAt: number,\n /** The Unix timestamp when the waitlist entry was last updated. */\n readonly updatedAt: number,\n /** Whether the waitlist entry is locked. */\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 AgentTask,\n AllowlistIdentifier,\n APIKey,\n BlocklistIdentifier,\n Client,\n Cookies,\n DeletedObject,\n Domain,\n Email,\n EmailAddress,\n EnterpriseAccount,\n EnterpriseConnection,\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 Permission,\n PhoneNumber,\n ProxyCheck,\n RedirectUrl,\n Role,\n RoleSet,\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 (isM2MTokenResponse(payload)) {\n // Handle M2M token list responses with m2m_tokens property\n data = payload.m2m_tokens.map(item => jsonToObject(item)) as U;\n totalCount = payload.total_count;\n\n return { data, totalCount };\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\n/**\n * Detects M2M token list responses from the Backend API.\n *\n * The Clerk Backend API returns M2M token lists with `m2m_tokens` and `total_count` properties.\n * This function identifies those responses and normalizes them to the standard `data` and\n * `totalCount` format for consistency with other paginated API methods across the SDK.\n *\n * This approach avoids making breaking changes to BAPI Proxy or supporting both response\n * formats. Once BAPI Proxy is updated to return the standard `data` property format,\n * this function can be safely removed.\n *\n * @see https://clerk.com/docs/reference/backend-api/tag/m2m-tokens/GET/m2m_tokens\n */\nfunction isM2MTokenResponse(payload: unknown): payload is { m2m_tokens: unknown[]; total_count: number } {\n if (!payload || typeof payload !== 'object' || !('m2m_tokens' in payload)) {\n return false;\n }\n\n return Array.isArray(payload.m2m_tokens);\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.EnterpriseAccount:\n return EnterpriseAccount.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.Permission:\n return Permission.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.Role:\n return Role.fromJSON(item);\n case ObjectType.RoleSet:\n return RoleSet.fromJSON(item);\n case ObjectType.EnterpriseConnection:\n return EnterpriseConnection.fromJSON(item);\n case ObjectType.SamlConnection:\n return SamlConnection.fromJSON(item);\n case ObjectType.SignInToken:\n return SignInToken.fromJSON(item);\n case ObjectType.AgentTask:\n return AgentTask.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 AgentTaskAPI,\n AllowlistIdentifierAPI,\n APIKeysAPI,\n BetaFeaturesAPI,\n BlocklistIdentifierAPI,\n ClientAPI,\n DomainAPI,\n EmailAddressAPI,\n EmailApi,\n EnterpriseConnectionAPI,\n IdPOAuthAccessTokenApi,\n InstanceAPI,\n InvitationAPI,\n JwksAPI,\n JwtTemplatesApi,\n M2MTokenApi,\n MachineApi,\n OAuthApplicationsApi,\n OrganizationAPI,\n OrganizationPermissionAPI,\n OrganizationRoleAPI,\n PhoneNumberAPI,\n ProxyCheckAPI,\n RedirectUrlAPI,\n RoleSetAPI,\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 jwtKey?: string;\n};\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 /**\n * @experimental This is an experimental API for the Agent Tasks feature that is available under a private 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 agentTasks: new AgentTaskAPI(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 /**\n * @experimental This calls an internal, not-yet-public endpoint for sending\n * transactional emails and is subject to change. It is advised to\n * [pin](https://clerk.com/docs/pinning) the SDK version to avoid breaking changes.\n */\n emails: new EmailApi(request),\n enterpriseConnections: new EnterpriseConnectionAPI(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 secretKey: options.secretKey,\n apiUrl: options.apiUrl,\n jwtKey: options.jwtKey,\n },\n ),\n oauthApplications: new OAuthApplicationsApi(request),\n organizations: new OrganizationAPI(request),\n organizationPermissions: new OrganizationPermissionAPI(request),\n organizationRoles: new OrganizationRoleAPI(request),\n phoneNumbers: new PhoneNumberAPI(request),\n proxyChecks: new ProxyCheckAPI(request),\n redirectUrls: new RedirectUrlAPI(request),\n roleSets: new RoleSetAPI(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 * @deprecated Use `enterpriseConnections` instead.\n */\n samlConnections: new SamlConnectionAPI(request),\n };\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\ntype BootstrapSignedOutParams = {\n signInUrl?: string;\n signUpUrl?: string;\n isSatellite?: boolean;\n domain?: string;\n proxyUrl?: string;\n reason?: AuthReason;\n message?: string;\n headers?: Headers;\n};\n\n/**\n * Returns a synthetic `UnauthenticatedState` without requiring a publishable key or an\n * `AuthenticateContext`. Intended for framework integrations that need to run\n * authorization logic for a request that arrived before real Clerk keys are available\n * (e.g. the Next.js keyless bootstrap window). The returned state has\n * `status: 'signed-out'` and `toAuth()` returns a standard signed-out session auth object.\n *\n * `signInUrl` / `signUpUrl` are carried through so that `redirectToSignIn` /\n * `redirectToSignUp` can resolve to the application's own routes during bootstrap.\n * `isSatellite` / `domain` / `proxyUrl` are carried through so that cross-origin\n * satellite redirects produced by `createRedirect` include the `__clerk_status=needs-sync`\n * marker required for the return-trip handshake.\n */\nexport function createBootstrapSignedOutState({\n signInUrl = '',\n signUpUrl = '',\n isSatellite = false,\n domain = '',\n proxyUrl = '',\n reason = AuthErrorReason.SessionTokenAndUATMissing,\n message = '',\n headers = new Headers(),\n}: BootstrapSignedOutParams = {}): UnauthenticatedState<SessionTokenType> {\n return withDebugHeaders({\n status: AuthStatus.SignedOut,\n reason,\n message,\n proxyUrl,\n publishableKey: '',\n isSatellite,\n domain,\n signInUrl,\n signUpUrl,\n afterSignInUrl: '',\n afterSignUpUrl: '',\n isSignedIn: false,\n isAuthenticated: false,\n tokenType: TokenType.SessionToken,\n toAuth: () => signedOutAuthObject({ status: AuthStatus.SignedOut, reason, message }),\n 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 // When cloning a Request by passing it as init, hide its `signal` and `body`.\n // Undici's Request constructor in Node 24 performs a strict instanceof check on\n // the signal and rejects ones from a different realm (e.g. NextRequest). The\n // `body` is hidden because forwarding it makes the clone share the original's\n // single-use ReadableStream; once either side is read the other throws\n // \"Body is unusable\" downstream (issue #8305). Auth only reads the method,\n // headers, cookies, and URL, so the clone never needs a body. Using a Proxy\n // keeps property access lazy so environments that don't implement optional\n // getters (e.g. Cloudflare Workers' Request lacks `cache`) still work.\n let cloneInit: RequestInit | undefined;\n if (init) {\n cloneInit = init;\n } else if (typeof input !== 'string') {\n cloneInit = new Proxy(input as Request, {\n get(target, prop) {\n if (prop === 'signal' || prop === 'body') {\n return undefined;\n }\n return Reflect.get(target, prop, target);\n },\n }) as unknown as RequestInit;\n }\n super(url, cloneInit);\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\n try {\n return createClerkUrl(initialUrl.pathname + initialUrl.search, origin);\n } catch {\n return createClerkUrl(initialUrl);\n }\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 // Use duck typing instead of instanceof to avoid issues with polyfilled Request classes\n // (e.g., in TanStack Start or other environments with multiple Request class instances)\n // ClerkRequest has unique properties 'clerkUrl' and 'cookies' that distinguish it from Request\n const isClerkRequest = args[0] && typeof args[0] === 'object' && 'clerkUrl' in args[0] && 'cookies' in args[0];\n\n return isClerkRequest ? (args[0] as ClerkRequest) : 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 { isClerkAPIResponseError } from '@clerk/shared/error';\nimport type { Jwt, 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 { verifyM2MJwt, verifyOAuthJwt } from '../jwt/verifyMachineJwt';\nimport type { LoadClerkJWKFromRemoteOptions } from './keys';\nimport { loadClerkJwkFromPem, loadClerkJWKFromRemote } from './keys';\nimport {\n API_KEY_PREFIX,\n isJwtFormat,\n JWT_CATEGORY_M2M_TOKEN,\n M2M_SUBJECT_PREFIX,\n M2M_TOKEN_PREFIX,\n OAUTH_ACCESS_TOKEN_TYPES,\n OAUTH_TOKEN_PREFIX,\n} 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/GET/jwks){{ 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 // Reject machine JWTs (e.g. M2M) tagged with a non-session category but signed by the same\n // instance key, regardless of transport. Reciprocal of the machine verifier's `cat` check.\n if (header.cat === JWT_CATEGORY_M2M_TOKEN) {\n return {\n errors: [\n new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenInvalid,\n message: 'Invalid session token category.',\n }),\n ],\n };\n }\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 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\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,\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 or JWT claims.\n * For JWTs, decodes once and routes based on claims to avoid redundant decoding.\n *\n * @param token - The token to verify (e.g. starts with \"mt_\", \"oat_\", \"ak_\", or a JWT)\n * @param options - Options including secretKey for BAPI authorization\n */\nexport async function verifyMachineAuthToken(token: string, options: VerifyTokenOptions) {\n if (isJwtFormat(token)) {\n let decodedResult: Jwt;\n try {\n const { data, errors: decodeErrors } = decodeJwt(token);\n if (decodeErrors) {\n throw decodeErrors[0];\n }\n decodedResult = data;\n } catch (e) {\n return {\n data: undefined,\n tokenType: TokenType.M2MToken,\n errors: [\n new MachineTokenVerificationError({\n code: MachineTokenVerificationErrorCode.TokenInvalid,\n message: (e as Error).message,\n }),\n ],\n } as MachineTokenReturnType<never, MachineTokenVerificationError>;\n }\n\n if (typeof decodedResult.payload.sub === 'string' && decodedResult.payload.sub.startsWith(M2M_SUBJECT_PREFIX)) {\n return verifyM2MJwt(token, decodedResult, options);\n }\n\n // OAuth JWT: typ is at+jwt or application/at+jwt\n if (OAUTH_ACCESS_TOKEN_TYPES.includes(decodedResult.header.typ as string)) {\n return verifyOAuthJwt(token, decodedResult, options);\n }\n\n return {\n data: undefined,\n tokenType: TokenType.OAuthToken,\n errors: [\n new MachineTokenVerificationError({\n code: MachineTokenVerificationErrorCode.TokenVerificationFailed,\n message: `Invalid JWT type: ${decodedResult.header.typ ?? 'missing'}. Expected one of: ${OAUTH_ACCESS_TOKEN_TYPES.join(', ')} for OAuth, or sub starting with 'mch_' for M2M`,\n }),\n ],\n } as MachineTokenReturnType<never, MachineTokenVerificationError>;\n }\n\n // Opaque token routing by prefix\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, method, secFetchDest } = this.authenticateContext;\n\n // Handshake involves a redirect to FAPI which only accepts GET requests.\n // Non-GET requests (e.g. POST form submissions) also set sec-fetch-dest: document,\n // but redirecting them would result in a 405 Method Not Allowed from FAPI.\n if (method !== 'GET') {\n return false;\n }\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.sessionToken) {\n url.searchParams.append(constants.QueryParameters.Session, this.authenticateContext.sessionToken);\n }\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 { 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; _raw?: 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 // Backend resources (`User`, `Organization`) retain the full Backend API\n // payload on the enumerable `_raw` property, which still contains\n // `private_metadata`. The payload is also nested (e.g. a `User`'s\n // `organization_memberships[*]` each carry their own `private_metadata`\n // and a nested `organization.private_metadata`), so redact recursively on\n // a deep clone — leaving the original resource (and its `raw` getter)\n // untouched.\n if ('_raw' in resource && resource['_raw']) {\n resource['_raw'] = redactPrivateMetadataDeep(resource['_raw']);\n }\n }\n\n return resource;\n}\n\n/**\n * Returns a deep clone of `value` with every `private_metadata` / `privateMetadata`\n * property removed at any depth.\n */\nfunction redactPrivateMetadataDeep(value: any): any {\n if (Array.isArray(value)) {\n return value.map(redactPrivateMetadataDeep);\n }\n if (value && typeof value === 'object') {\n const clone: Record<string, any> = {};\n for (const key of Object.keys(value)) {\n if (key === 'private_metadata' || key === 'privateMetadata') {\n continue;\n }\n clone[key] = redactPrivateMetadataDeep(value[key]);\n }\n return clone;\n }\n return value;\n}\n","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, createBootstrapSignedOutState } 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 {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B,mCAAmC;","names":["endIdx","eqIdx","Headers","buildAccountsBaseUrl","buildAccountsBaseUrl","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","jwk","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","match","convertCase","Cookies","data","Cookies","sessionId","authenticateContext","refreshToken","data","errors","authenticateRequest"]}
1
+ {"version":3,"sources":["../../../node_modules/.pnpm/cookie@1.1.1/node_modules/cookie/src/index.ts","../src/constants.ts","../src/createRedirect.ts","../src/util/mergePreDefinedOptions.ts","../src/tokens/request.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/AgentTaskApi.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/EmailApi.ts","../src/api/endpoints/EnterpriseConnectionApi.ts","../src/api/endpoints/IdPOAuthAccessTokenApi.ts","../src/api/endpoints/InstanceApi.ts","../src/api/endpoints/InvitationApi.ts","../src/api/endpoints/MachineApi.ts","../src/api/resources/IdPOAuthAccessToken.ts","../src/api/resources/M2MToken.ts","../src/tokens/keys.ts","../src/tokens/machine.ts","../src/jwt/verifyMachineJwt.ts","../src/api/endpoints/M2MTokenApi.ts","../src/api/endpoints/JwksApi.ts","../src/api/endpoints/JwtTemplatesApi.ts","../src/api/endpoints/OrganizationApi.ts","../src/api/endpoints/OrganizationPermissionApi.ts","../src/api/endpoints/OrganizationRoleApi.ts","../src/api/endpoints/OAuthApplicationsApi.ts","../src/api/endpoints/PhoneNumberApi.ts","../src/api/endpoints/ProxyCheckApi.ts","../src/api/endpoints/RedirectUrlApi.ts","../src/api/endpoints/RoleSetApi.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/AgentTask.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/EnterpriseAccount.ts","../src/api/resources/EnterpriseConnection.ts","../src/api/resources/ExternalAccount.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/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/Permission.ts","../src/api/resources/PhoneNumber.ts","../src/api/resources/ProxyCheck.ts","../src/api/resources/RedirectUrl.ts","../src/api/resources/Role.ts","../src/api/resources/RoleSet.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/authStatus.ts","../src/tokens/clerkRequest.ts","../src/tokens/clerkUrl.ts","../src/tokens/cookie.ts","../src/tokens/verify.ts","../src/tokens/handshake.ts","../src/tokens/organizationMatcher.ts","../src/tokens/factory.ts","../src/util/decorateObjectWithResources.ts","../src/internal.ts"],"sourcesContent":["/**\n * RegExp to match cookie-name in RFC 6265 sec 4.1.1\n * This refers out to the obsoleted definition of token in RFC 2616 sec 2.2\n * which has been replaced by the token definition in RFC 7230 appendix B.\n *\n * cookie-name = token\n * token = 1*tchar\n * tchar = \"!\" / \"#\" / \"$\" / \"%\" / \"&\" / \"'\" /\n * \"*\" / \"+\" / \"-\" / \".\" / \"^\" / \"_\" /\n * \"`\" / \"|\" / \"~\" / DIGIT / ALPHA\n *\n * Note: Allowing more characters - https://github.com/jshttp/cookie/issues/191\n * Allow same range as cookie value, except `=`, which delimits end of name.\n */\nconst cookieNameRegExp = /^[\\u0021-\\u003A\\u003C\\u003E-\\u007E]+$/;\n\n/**\n * RegExp to match cookie-value in RFC 6265 sec 4.1.1\n *\n * cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )\n * cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E\n * ; US-ASCII characters excluding CTLs,\n * ; whitespace DQUOTE, comma, semicolon,\n * ; and backslash\n *\n * Allowing more characters: https://github.com/jshttp/cookie/issues/191\n * Comma, backslash, and DQUOTE are not part of the parsing algorithm.\n */\nconst cookieValueRegExp = /^[\\u0021-\\u003A\\u003C-\\u007E]*$/;\n\n/**\n * RegExp to match domain-value in RFC 6265 sec 4.1.1\n *\n * domain-value = <subdomain>\n * ; defined in [RFC1034], Section 3.5, as\n * ; enhanced by [RFC1123], Section 2.1\n * <subdomain> = <label> | <subdomain> \".\" <label>\n * <label> = <let-dig> [ [ <ldh-str> ] <let-dig> ]\n * Labels must be 63 characters or less.\n * 'let-dig' not 'letter' in the first char, per RFC1123\n * <ldh-str> = <let-dig-hyp> | <let-dig-hyp> <ldh-str>\n * <let-dig-hyp> = <let-dig> | \"-\"\n * <let-dig> = <letter> | <digit>\n * <letter> = any one of the 52 alphabetic characters A through Z in\n * upper case and a through z in lower case\n * <digit> = any one of the ten digits 0 through 9\n *\n * Keep support for leading dot: https://github.com/jshttp/cookie/issues/173\n *\n * > (Note that a leading %x2E (\".\"), if present, is ignored even though that\n * character is not permitted, but a trailing %x2E (\".\"), if present, will\n * cause the user agent to ignore the attribute.)\n */\nconst domainValueRegExp =\n /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i;\n\n/**\n * RegExp to match path-value in RFC 6265 sec 4.1.1\n *\n * path-value = <any CHAR except CTLs or \";\">\n * CHAR = %x01-7F\n * ; defined in RFC 5234 appendix B.1\n */\nconst pathValueRegExp = /^[\\u0020-\\u003A\\u003D-\\u007E]*$/;\n\n/**\n * RegExp to match max-age-value in RFC 6265 sec 5.6.2\n */\nconst maxAgeRegExp = /^-?\\d+$/;\n\nconst __toString = Object.prototype.toString;\n\nconst NullObject = /* @__PURE__ */ (() => {\n const C = function () {};\n C.prototype = Object.create(null);\n return C;\n})() as unknown as { new (): any };\n\n/**\n * Parse options.\n */\nexport interface ParseOptions {\n /**\n * Specifies a function that will be used to decode a [cookie-value](https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1).\n * Since the value of a cookie has a limited character set (and must be a simple string), this function can be used to decode\n * a previously-encoded cookie value into a JavaScript string.\n *\n * The default function is the global `decodeURIComponent`, wrapped in a `try..catch`. If an error\n * is thrown it will return the cookie's original value. If you provide your own encode/decode\n * scheme you must ensure errors are appropriately handled.\n *\n * @default decode\n */\n decode?: (str: string) => string | undefined;\n}\n\n/**\n * Cookies object.\n */\nexport type Cookies = Record<string, string | undefined>;\n\n/**\n * Parse a `Cookie` header.\n *\n * Parse the given cookie header string into an object\n * The object has the various cookies as keys(names) => values\n */\nexport function parseCookie(str: string, options?: ParseOptions): Cookies {\n const obj: Cookies = new NullObject();\n const len = str.length;\n // RFC 6265 sec 4.1.1, RFC 2616 2.2 defines a cookie name consists of one char minimum, plus '='.\n if (len < 2) return obj;\n\n const dec = options?.decode || decode;\n let index = 0;\n\n do {\n const eqIdx = eqIndex(str, index, len);\n if (eqIdx === -1) break; // No more cookie pairs.\n\n const endIdx = endIndex(str, index, len);\n\n if (eqIdx > endIdx) {\n // backtrack on prior semicolon\n index = str.lastIndexOf(\";\", eqIdx - 1) + 1;\n continue;\n }\n\n const key = valueSlice(str, index, eqIdx);\n\n // only assign once\n if (obj[key] === undefined) {\n obj[key] = dec(valueSlice(str, eqIdx + 1, endIdx));\n }\n\n index = endIdx + 1;\n } while (index < len);\n\n return obj;\n}\n\nexport interface StringifyOptions {\n /**\n * Specifies a function that will be used to encode a [cookie-value](https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1).\n * Since value of a cookie has a limited character set (and must be a simple string), this function can be used to encode\n * a value into a string suited for a cookie's value, and should mirror `decode` when parsing.\n *\n * @default encodeURIComponent\n */\n encode?: (str: string) => string;\n}\n\n/**\n * Stringifies an object into an HTTP `Cookie` header.\n */\nexport function stringifyCookie(\n cookie: Cookies,\n options?: StringifyOptions,\n): string {\n const enc = options?.encode || encodeURIComponent;\n const cookieStrings: string[] = [];\n\n for (const name of Object.keys(cookie)) {\n const val = cookie[name];\n if (val === undefined) continue;\n\n if (!cookieNameRegExp.test(name)) {\n throw new TypeError(`cookie name is invalid: ${name}`);\n }\n\n const value = enc(val);\n\n if (!cookieValueRegExp.test(value)) {\n throw new TypeError(`cookie val is invalid: ${val}`);\n }\n\n cookieStrings.push(`${name}=${value}`);\n }\n\n return cookieStrings.join(\"; \");\n}\n\n/**\n * Set-Cookie object.\n */\nexport interface SetCookie {\n /**\n * Specifies the name of the cookie.\n */\n name: string;\n /**\n * Specifies the string to be the value for the cookie.\n */\n value: string | undefined;\n /**\n * Specifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.2).\n *\n * The [cookie storage model specification](https://tools.ietf.org/html/rfc6265#section-5.3) states that if both `expires` and\n * `maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this,\n * so if both are set, they should point to the same date and time.\n */\n maxAge?: number;\n /**\n * Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.1).\n * When no expiration is set, clients consider this a \"non-persistent cookie\" and delete it when the current session is over.\n *\n * The [cookie storage model specification](https://tools.ietf.org/html/rfc6265#section-5.3) states that if both `expires` and\n * `maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this,\n * so if both are set, they should point to the same date and time.\n */\n expires?: Date;\n /**\n * Specifies the value for the [`Domain` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.3).\n * When no domain is set, clients consider the cookie to apply to the current domain only.\n */\n domain?: string;\n /**\n * Specifies the value for the [`Path` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.4).\n * When no path is set, the path is considered the [\"default path\"](https://tools.ietf.org/html/rfc6265#section-5.1.4).\n */\n path?: string;\n /**\n * Enables the [`HttpOnly` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.6).\n * When enabled, clients will not allow client-side JavaScript to see the cookie in `document.cookie`.\n */\n httpOnly?: boolean;\n /**\n * Enables the [`Secure` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.5).\n * When enabled, clients will only send the cookie back if the browser has an HTTPS connection.\n */\n secure?: boolean;\n /**\n * Enables the [`Partitioned` `Set-Cookie` attribute](https://tools.ietf.org/html/draft-cutler-httpbis-partitioned-cookies/).\n * When enabled, clients will only send the cookie back when the current domain _and_ top-level domain matches.\n *\n * This is an attribute that has not yet been fully standardized, and may change in the future.\n * This also means clients may ignore this attribute until they understand it. More information\n * about can be found in [the proposal](https://github.com/privacycg/CHIPS).\n */\n partitioned?: boolean;\n /**\n * Specifies the value for the [`Priority` `Set-Cookie` attribute](https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1).\n *\n * - `'low'` will set the `Priority` attribute to `Low`.\n * - `'medium'` will set the `Priority` attribute to `Medium`, the default priority when not set.\n * - `'high'` will set the `Priority` attribute to `High`.\n *\n * More information about priority levels can be found in [the specification](https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1).\n */\n priority?: \"low\" | \"medium\" | \"high\";\n /**\n * Specifies the value for the [`SameSite` `Set-Cookie` attribute](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-09#section-5.4.7).\n *\n * - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement.\n * - `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement.\n * - `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie.\n * - `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement.\n *\n * More information about enforcement levels can be found in [the specification](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-09#section-5.4.7).\n */\n sameSite?: boolean | \"lax\" | \"strict\" | \"none\";\n}\n\n/**\n * Backward compatibility serialize options.\n */\nexport type SerializeOptions = StringifyOptions &\n Omit<SetCookie, \"name\" | \"value\">;\n\n/**\n * Serialize data into a cookie header.\n *\n * Serialize a name value pair into a cookie string suitable for\n * http headers. An optional options object specifies cookie parameters.\n *\n * serialize('foo', 'bar', { httpOnly: true })\n * => \"foo=bar; httpOnly\"\n */\nexport function stringifySetCookie(\n cookie: SetCookie,\n options?: StringifyOptions,\n): string;\nexport function stringifySetCookie(\n name: string,\n val: string,\n options?: SerializeOptions,\n): string;\nexport function stringifySetCookie(\n _name: string | SetCookie,\n _val?: string | StringifyOptions,\n _opts?: SerializeOptions,\n): string {\n const cookie =\n typeof _name === \"object\"\n ? _name\n : { ..._opts, name: _name, value: String(_val) };\n const options = typeof _val === \"object\" ? _val : _opts;\n const enc = options?.encode || encodeURIComponent;\n\n if (!cookieNameRegExp.test(cookie.name)) {\n throw new TypeError(`argument name is invalid: ${cookie.name}`);\n }\n\n const value = cookie.value ? enc(cookie.value) : \"\";\n\n if (!cookieValueRegExp.test(value)) {\n throw new TypeError(`argument val is invalid: ${cookie.value}`);\n }\n\n let str = cookie.name + \"=\" + value;\n\n if (cookie.maxAge !== undefined) {\n if (!Number.isInteger(cookie.maxAge)) {\n throw new TypeError(`option maxAge is invalid: ${cookie.maxAge}`);\n }\n\n str += \"; Max-Age=\" + cookie.maxAge;\n }\n\n if (cookie.domain) {\n if (!domainValueRegExp.test(cookie.domain)) {\n throw new TypeError(`option domain is invalid: ${cookie.domain}`);\n }\n\n str += \"; Domain=\" + cookie.domain;\n }\n\n if (cookie.path) {\n if (!pathValueRegExp.test(cookie.path)) {\n throw new TypeError(`option path is invalid: ${cookie.path}`);\n }\n\n str += \"; Path=\" + cookie.path;\n }\n\n if (cookie.expires) {\n if (!isDate(cookie.expires) || !Number.isFinite(cookie.expires.valueOf())) {\n throw new TypeError(`option expires is invalid: ${cookie.expires}`);\n }\n\n str += \"; Expires=\" + cookie.expires.toUTCString();\n }\n\n if (cookie.httpOnly) {\n str += \"; HttpOnly\";\n }\n\n if (cookie.secure) {\n str += \"; Secure\";\n }\n\n if (cookie.partitioned) {\n str += \"; Partitioned\";\n }\n\n if (cookie.priority) {\n const priority =\n typeof cookie.priority === \"string\"\n ? cookie.priority.toLowerCase()\n : undefined;\n switch (priority) {\n case \"low\":\n str += \"; Priority=Low\";\n break;\n case \"medium\":\n str += \"; Priority=Medium\";\n break;\n case \"high\":\n str += \"; Priority=High\";\n break;\n default:\n throw new TypeError(`option priority is invalid: ${cookie.priority}`);\n }\n }\n\n if (cookie.sameSite) {\n const sameSite =\n typeof cookie.sameSite === \"string\"\n ? cookie.sameSite.toLowerCase()\n : cookie.sameSite;\n switch (sameSite) {\n case true:\n case \"strict\":\n str += \"; SameSite=Strict\";\n break;\n case \"lax\":\n str += \"; SameSite=Lax\";\n break;\n case \"none\":\n str += \"; SameSite=None\";\n break;\n default:\n throw new TypeError(`option sameSite is invalid: ${cookie.sameSite}`);\n }\n }\n\n return str;\n}\n\n/**\n * Deserialize a `Set-Cookie` header into an object.\n *\n * deserialize('foo=bar; httpOnly')\n * => { name: 'foo', value: 'bar', httpOnly: true }\n */\nexport function parseSetCookie(str: string, options?: ParseOptions): SetCookie {\n const dec = options?.decode || decode;\n const len = str.length;\n const endIdx = endIndex(str, 0, len);\n const eqIdx = eqIndex(str, 0, endIdx);\n const setCookie: SetCookie =\n eqIdx === -1\n ? { name: \"\", value: dec(valueSlice(str, 0, endIdx)) }\n : {\n name: valueSlice(str, 0, eqIdx),\n value: dec(valueSlice(str, eqIdx + 1, endIdx)),\n };\n\n let index = endIdx + 1;\n while (index < len) {\n const endIdx = endIndex(str, index, len);\n const eqIdx = eqIndex(str, index, endIdx);\n const attr =\n eqIdx === -1\n ? valueSlice(str, index, endIdx)\n : valueSlice(str, index, eqIdx);\n const val = eqIdx === -1 ? undefined : valueSlice(str, eqIdx + 1, endIdx);\n\n switch (attr.toLowerCase()) {\n case \"httponly\":\n setCookie.httpOnly = true;\n break;\n case \"secure\":\n setCookie.secure = true;\n break;\n case \"partitioned\":\n setCookie.partitioned = true;\n break;\n case \"domain\":\n setCookie.domain = val;\n break;\n case \"path\":\n setCookie.path = val;\n break;\n case \"max-age\":\n if (val && maxAgeRegExp.test(val)) setCookie.maxAge = Number(val);\n break;\n case \"expires\":\n if (!val) break;\n const date = new Date(val);\n if (Number.isFinite(date.valueOf())) setCookie.expires = date;\n break;\n case \"priority\":\n if (!val) break;\n const priority = val.toLowerCase();\n if (\n priority === \"low\" ||\n priority === \"medium\" ||\n priority === \"high\"\n ) {\n setCookie.priority = priority;\n }\n break;\n case \"samesite\":\n if (!val) break;\n const sameSite = val.toLowerCase();\n if (\n sameSite === \"lax\" ||\n sameSite === \"strict\" ||\n sameSite === \"none\"\n ) {\n setCookie.sameSite = sameSite;\n }\n break;\n }\n\n index = endIdx + 1;\n }\n\n return setCookie;\n}\n\n/**\n * Find the `;` character between `min` and `len` in str.\n */\nfunction endIndex(str: string, min: number, len: number) {\n const index = str.indexOf(\";\", min);\n return index === -1 ? len : index;\n}\n\n/**\n * Find the `=` character between `min` and `max` in str.\n */\nfunction eqIndex(str: string, min: number, max: number) {\n const index = str.indexOf(\"=\", min);\n return index < max ? index : -1;\n}\n\n/**\n * Slice out a value between startPod to max.\n */\nfunction valueSlice(str: string, min: number, max: number) {\n let start = min;\n let end = max;\n\n do {\n const code = str.charCodeAt(start);\n if (code !== 0x20 /* */ && code !== 0x09 /* \\t */) break;\n } while (++start < end);\n\n while (end > start) {\n const code = str.charCodeAt(end - 1);\n if (code !== 0x20 /* */ && code !== 0x09 /* \\t */) break;\n end--;\n }\n\n return str.slice(start, end);\n}\n\n/**\n * URL-decode string value. Optimized to skip native call when no %.\n */\nfunction decode(str: string): string {\n if (str.indexOf(\"%\") === -1) return str;\n\n try {\n return decodeURIComponent(str);\n } catch (e) {\n return str;\n }\n}\n\n/**\n * Determine if value is a Date.\n */\nfunction isDate(val: any): val is Date {\n return __toString.call(val) === \"[object Date]\";\n}\n\n/**\n * Backward compatibility exports.\n */\nexport { stringifySetCookie as serialize, parseCookie as parse };\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 = '2026-05-12';\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 Session: '__session',\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 * Sync status values for the __clerk_synced query parameter.\n * Used to coordinate satellite domain authentication flows.\n */\nexport const ClerkSyncStatus = {\n /** Not synced - satellite needs handshake after returning from primary sign-in */\n NeedsSync: 'false',\n /** Sync completed - prevents re-sync loop after handshake completes */\n Completed: 'true',\n} as const;\n\n/**\n * @internal\n */\nexport const constants = {\n Attributes,\n Cookies,\n Headers,\n ContentTypes,\n QueryParameters,\n ClerkSyncStatus,\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 { ClerkSyncStatus, 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 _isSatellite?: boolean,\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 // For satellite apps redirecting to primary sign-in, add sync trigger to returnBackUrl\n // This ensures handshake is triggered when the user returns after signing in\n if (isCrossOriginRedirect && _isSatellite) {\n returnBackUrl.searchParams.set(constants.QueryParameters.ClerkSynced, ClerkSyncStatus.NeedsSync);\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 isSatellite?: boolean;\n}) => {\n redirectToSignIn: RedirectFun<ReturnType>;\n redirectToSignUp: RedirectFun<ReturnType>;\n};\n\nexport const createRedirect: CreateRedirect = params => {\n const { publishableKey, redirectAdapter, signInUrl, signUpUrl, baseUrl, sessionStatus, isSatellite } = 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, isSatellite),\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(\n buildUrl(baseUrl, targetUrl, returnBackUrl, isDevelopment ? params.devBrowserToken : null, isSatellite),\n );\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(\n buildUrl(baseUrl, targetUrl, returnBackUrl, isDevelopment ? params.devBrowserToken : null, isSatellite),\n );\n };\n\n return { redirectToSignUp, redirectToSignIn };\n};\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","import { logger } from '@clerk/shared/logger';\nimport 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, isMachineJwt, isMachineToken, 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 (isMachineToken(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 = getHandshakeRedirectLoopMessage(reason);\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 function getHandshakeRedirectLoopMessage(reason: string): string {\n if (reason === AuthErrorReason.SatelliteCookieNeedsSyncing) {\n return `Clerk: Satellite-domain authentication resulted in an infinite redirect loop. Check that this request is using a configured primary or satellite domain for the production instance. For preview deployments, use a development/staging Clerk instance or a supported configured preview-domain setup.`;\n }\n return `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 }\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 // Reject machine JWTs (OAuth or M2M) that may appear in headers when expecting session tokens.\n // These are valid Clerk-signed JWTs and will pass verify() verification,\n // but should not be accepted as session tokens.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n if (isMachineJwt(tokenInHeader!)) {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: AuthErrorReason.TokenTypeMismatch,\n message: '',\n });\n }\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 &&\n authenticateContext.secFetchDest === 'document' &&\n authenticateContext.method === 'GET';\n\n /**\n * Begin multi-domain sync flows\n *\n * Sync status values (__clerk_synced query param):\n * - 'false' (NeedsSync): Trigger sync - satellite returning from primary sign-in\n * - 'true' (Completed): Sync done - prevents re-sync loop\n *\n * With satelliteAutoSync=false or unset (Core 3 default):\n * - Skip handshake on first visit if no cookies exist (return signedOut immediately)\n * - Trigger handshake when __clerk_synced=false is present (post sign-in redirect)\n * - Allow normal token verification flow when cookies exist (enables refresh)\n */\n\n // Check sync status param (__clerk_synced=false triggers sync, __clerk_synced=true means completed)\n const syncedParam = authenticateContext.clerkUrl.searchParams.get(constants.QueryParameters.ClerkSynced);\n const needsSync = syncedParam === constants.ClerkSyncStatus.NeedsSync;\n const syncCompleted = syncedParam === constants.ClerkSyncStatus.Completed;\n\n // Check if cookies exist (session token or active client UAT)\n const hasCookies = hasSessionToken || hasActiveClient;\n\n // Determine if we should skip handshake for satellites with no cookies\n // satelliteAutoSync defaults to false (Core 3), so we skip unless explicitly set to true\n const shouldSkipSatelliteHandshake = authenticateContext.satelliteAutoSync !== true && !hasCookies && !needsSync;\n\n if (authenticateContext.instanceType === 'production' && isRequestEligibleForMultiDomainSync && !syncCompleted) {\n // With satelliteAutoSync=false: skip handshake if no cookies and no sync trigger\n if (shouldSkipSatelliteHandshake) {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: AuthErrorReason.SessionTokenAndUATMissing,\n });\n }\n\n // If cookies exist, fall through to normal token verification flow (enables refresh)\n // Only trigger handshake if no cookies exist (or sync was explicitly requested)\n if (!hasCookies || needsSync) {\n return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SatelliteCookieNeedsSyncing, '');\n }\n // Fall through to normal token verification flow when cookies exist\n }\n\n // Multi-domain development sync flow\n if (authenticateContext.instanceType === 'development' && isRequestEligibleForMultiDomainSync && !syncCompleted) {\n // With satelliteAutoSync=false: skip sync if no cookies and no sync trigger\n if (shouldSkipSatelliteHandshake) {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: AuthErrorReason.SessionTokenAndUATMissing,\n });\n }\n\n // If cookies exist, fall through to normal flow (enables refresh)\n if (!hasCookies || needsSync) {\n // initiate MD sync\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(\n authenticateContext,\n AuthErrorReason.SatelliteCookieNeedsSyncing,\n '',\n headers,\n );\n }\n // Fall through to normal token verification flow when cookies exist\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 // Use set (not append) to ensure completion status overwrites any existing NeedsSync value\n // This prevents sync loops when the redirect URL already contains __clerk_synced=false\n redirectBackToSatelliteUrl.searchParams.set(\n constants.QueryParameters.ClerkSynced,\n constants.ClerkSyncStatus.Completed,\n );\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 // Machine JWTs pass verifyToken() but must not be accepted as session tokens (mirrors header path).\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n if (isMachineJwt(authenticateContext.sessionTokenInCookie!)) {\n return signedOut({\n tokenType: TokenType.SessionToken,\n authenticateContext,\n reason: AuthErrorReason.TokenTypeMismatch,\n message: '',\n });\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 if (!data.azp) {\n // Warn once per process rather than per request: a single azp-less cookie\n // token is reused across every authenticated request until it refreshes,\n // so an unguarded console.warn floods production logs (see issue #8231).\n logger.warnOnce(\n 'Clerk: Session token from cookie is missing the azp claim. In a future version of Clerk, this token will be considered invalid. Please contact Clerk support if you see this warning.',\n );\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.method === 'GET' && // Only GET navigations (POST form submissions set sec-fetch-dest: document too)\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 (!isMachineToken(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 (isMachineToken(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' || Array.isArray(acceptsToken)) {\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 { 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 { getAutoProxyUrlFromEnvironment } from '@clerk/shared/proxy';\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 method: string;\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 * Gets 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 // Auto-detect proxy for supported platform deployments using environment\n // variables (e.g. VERCEL_TARGET_ENV, VERCEL_PROJECT_PRODUCTION_URL) instead\n // of request headers, which avoids X-Forwarded-Host spoofing concerns.\n const autoProxyPath = getAutoProxyUrlFromEnvironment({\n publishableKey: options.publishableKey ?? '',\n hasProxyUrl: !!options.proxyUrl,\n hasDomain: !!options.domain,\n });\n if (autoProxyPath) {\n options = { ...options, proxyUrl: `${clerkRequest.clerkUrl.origin}${autoProxyPath}` };\n }\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 // Resolve relative proxyUrl to absolute using the request's public origin.\n if (this.proxyUrl?.startsWith('/')) {\n this.proxyUrl = `${this.clerkUrl.origin}${this.proxyUrl}`;\n }\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 // If proxyUrl is a relative path (e.g. '/__clerk'), resolve it against the\n // request's public origin (derived from x-forwarded-* headers by ClerkRequest).\n // This lets SDKs pass just the path instead of duplicating forwarded-header parsing.\n let resolvedProxyUrl = options.proxyUrl;\n if (resolvedProxyUrl?.startsWith('/')) {\n resolvedProxyUrl = `${this.clerkRequest.clerkUrl.origin}${resolvedProxyUrl}`;\n }\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: resolvedProxyUrl,\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.method = this.clerkRequest.method;\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 // Session and machine tokens are live bearer credentials, so only ever expose a\n // short, non-reconstructable prefix here, the same way secretKey/jwtKey are handled\n // above. Otherwise enabling debug logging would write usable tokens to logs.\n // This also covers the bearer fields carried on AuthenticateContext, which is spread\n // wholesale into the debug payload by signedInAuthObject: the refresh token is the\n // most sensitive of these, and the dev-browser/handshake tokens are short-lived but\n // still credentials.\n res.sessionToken = (res.sessionToken || '').substring(0, 7);\n res.tokenInHeader = (res.tokenInHeader || '').substring(0, 7);\n res.sessionTokenInCookie = (res.sessionTokenInCookie || '').substring(0, 7);\n res.refreshTokenInCookie = (res.refreshTokenInCookie || '').substring(0, 7);\n res.devBrowserToken = (res.devBrowserToken || '').substring(0, 7);\n res.handshakeToken = (res.handshakeToken || '').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 - The 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 or generate a JWT using a specified template with 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');\nconst MAX_DECODES = 10;\n\ntype PathString = string | null | undefined;\n\nfunction isDotSegment(segment: string): boolean {\n let candidate = segment;\n for (let i = 0; i <= MAX_DECODES; i++) {\n // After decoding, check if any slash-separated part is a dot segment\n if (candidate.split(/[/\\\\]/).some(p => p === '.' || p === '..')) {\n return true;\n }\n if (i === MAX_DECODES) {\n throw new Error(`joinPaths: too many layers of encoding in ${segment}`);\n }\n try {\n const next = decodeURIComponent(candidate);\n if (next === candidate) {\n break;\n } // stable — no more encoding\n candidate = next;\n } catch {\n break;\n }\n }\n return false;\n}\n\nexport function joinPaths(...args: PathString[]): string {\n const result = args\n .filter(p => p)\n .join(SEPARATOR)\n .replace(MULTIPLE_SEPARATOR_REGEX, SEPARATOR);\n\n for (const segment of result.split(SEPARATOR)) {\n if (isDotSegment(segment)) {\n throw new Error(`joinPaths: \".\" and \"..\" path segments are not allowed (received \"${result}\")`);\n }\n }\n\n return result;\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 * The lifetime 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 { AgentTask } from '../resources/AgentTask';\nimport { AbstractAPI } from './AbstractApi';\n\n/** @generateWithEmptyComment */\nexport type CreateAgentTaskParams = {\n /** The user to create an Agent Task for. Provide either a `userId` or an `identifier` (e.g. an email address, phone number, or username). */\n onBehalfOf:\n | {\n /** The identifier of the user to create an Agent Task for. */\n identifier: string;\n userId?: never;\n }\n | {\n /** The ID of the user to create an Agent Task for. */\n userId: string;\n identifier?: never;\n };\n /** The permissions the Agent Task will have. Currently, `'*'` is the only supported value, which grants all permissions. */\n permissions: string;\n /** The name of the agent creating the task. Used to derive a stable `agent_id` for the Agent Task. */\n agentName: string;\n /** The description of the Agent Task to create. */\n taskDescription: string;\n /** The URL the user lands on after the Agent Task is accepted. In production instances, must be a valid absolute URL with an `https` scheme. In development instances, `http` is also permitted. The URL's domain must belong to one of the instance's associated domains (primary or satellite); otherwise, the redirect will be rejected when the task ticket is consumed. */\n redirectUrl: string;\n /** The maximum duration that the session created by the Agent Task should last. By default, the duration is `1800` (30 minutes). */\n sessionMaxDurationInSeconds?: number;\n};\n\nconst basePath = '/agents/tasks';\n\n/** @generateWithEmptyComment */\nexport class AgentTaskAPI extends AbstractAPI {\n /**\n * Creates an Agent Task that generates a URL which, when visited, creates a session for the specified user. This is useful for automated testing or agent-driven flows where full authentication isn't practical.\n * @returns The created [`AgentTask`](https://clerk.com/docs/reference/backend/types/backend-agent-task) object.\n */\n public async create(params: CreateAgentTaskParams) {\n return this.request<AgentTask>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n options: {\n deepSnakecaseBodyParamKeys: true,\n },\n });\n }\n\n /**\n * Revokes the given Agent Task.\n * @param agentTaskId - The ID of the Agent Task to revoke.\n * @returns The revoked [`AgentTask`](https://clerk.com/docs/reference/backend/types/backend-agent-task) object.\n */\n public async revoke(agentTaskId: string) {\n this.requireId(agentTaskId);\n return this.request<Omit<AgentTask, 'url'>>({\n method: 'POST',\n path: joinPaths(basePath, agentTaskId, '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\ntype AccountlessApplicationParams = {\n requestHeaders?: Headers;\n source?: string;\n};\n\nexport class AccountlessApplicationAPI extends AbstractAPI {\n public async createAccountlessApplication(params?: AccountlessApplicationParams): Promise<AccountlessApplication> {\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 queryParams: {\n source: params?.source,\n },\n });\n }\n\n public async completeAccountlessApplicationOnboarding(\n params?: AccountlessApplicationParams,\n ): Promise<AccountlessApplication> {\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 queryParams: {\n source: params?.source,\n },\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\n/** @generateWithEmptyComment */\nexport type AllowlistIdentifierCreateParams = {\n /** The identifier to add to the allowlist. Can be an email address, a domain in wildcard email format (e.g. `*@example.com`), a phone number in international E.164 format (e.g. `+15555555555`), or a Web3 wallet address. */\n identifier: string;\n /** Whether to notify the user that their identifier has been added to the allowlist. Notifies the user if the `identifier` is an email address or phone number. */\n notify: boolean;\n};\n\n/** @generateWithEmptyComment */\nexport class AllowlistIdentifierAPI extends AbstractAPI {\n /**\n * Gets the list of allowlist identifiers for the instance. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`AllowlistIdentifier`](https://clerk.com/docs/reference/backend/types/backend-allowlist-identifier) objects and a `totalCount` property containing the total number of allowlist identifiers for the instance.\n */\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 /**\n * Creates a new allowlist identifier.\n * @returns The created [`AllowlistIdentifier`](https://clerk.com/docs/reference/backend/types/backend-allowlist-identifier) object.\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 /**\n * Deletes an allowlist identifier.\n * @param allowlistIdentifierId - The ID of the allowlist identifier to delete.\n * @returns The [`DeletedObject`](https://clerk.com/docs/reference/backend/types/deleted-object) object.\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 type { APIKey } from '../resources/APIKey';\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/api_keys';\n\n/** @generateWithEmptyComment */\nexport type GetAPIKeyListParams = ClerkPaginationRequest<{\n /** The user or Organization ID to query API keys by. */\n subject: string;\n /** Whether to include invalid API keys (revoked or expired). Defaults to `false`. */\n includeInvalid?: boolean;\n}>;\n\n/** @generateWithEmptyComment */\nexport type CreateAPIKeyParams = {\n /** A descriptive name for the API key (e.g., \"Production API Key\", \"Development Key\"). */\n name: string;\n /** The user or Organization ID to associate the API key with. */\n subject: string;\n /** The description of the API key. */\n description?: string | null;\n /** Custom claims to store additional information about the API key. */\n claims?: Record<string, any> | null;\n /** Scopes to limit the API key's access to specific resources. */\n scopes?: string[];\n /** The user ID of the user who created the API key. */\n createdBy?: string | null;\n /** The number of seconds until the API key expires. Defaults to `null` (never expires). */\n secondsUntilExpiration?: number | null;\n};\n\n/** @generateWithEmptyComment */\nexport type RevokeAPIKeyParams = {\n /** The ID of the API key to revoke. */\n apiKeyId: string;\n /** The reason for revoking the API key. Useful for your records. */\n revocationReason?: string | null;\n};\n\n/** @generateWithEmptyComment */\nexport type UpdateAPIKeyParams = {\n /** The ID of the API key to update. */\n apiKeyId: string;\n /** The user or Organization ID to associate the API key with. */\n subject: string;\n /** The description of the API key. */\n description?: string | null;\n /** Custom claims to store additional information about the API key. */\n claims?: Record<string, any> | null;\n /** Scopes to limit the API key's access to specific resources. */\n scopes?: string[];\n /** The number of seconds until the API key expires. Defaults to `null` (never expires). */\n secondsUntilExpiration?: number | null;\n};\n\n/** @generateWithEmptyComment */\nexport class APIKeysAPI extends AbstractAPI {\n /**\n * Gets a list of API keys for the given user or Organization. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`APIKey`](https://clerk.com/docs/reference/backend/types/backend-api-key) objects and a `totalCount` property containing the total number of API keys for the user or Organization.\n */\n async list(queryParams: GetAPIKeyListParams) {\n return this.request<PaginatedResourceResponse<APIKey[]>>({\n method: 'GET',\n path: basePath,\n queryParams,\n });\n }\n\n /**\n * Creates a new API key for the given user or Organization.\n * @returns The created [`APIKey`](https://clerk.com/docs/reference/backend/types/backend-api-key) object.\n */\n async create(params: CreateAPIKeyParams) {\n return this.request<APIKey>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n /**\n * Gets the given [`APIKey`](https://clerk.com/docs/reference/backend/types/backend-api-key) object.\n * @param apiKeyId - The ID of the API key to get.\n */\n async get(apiKeyId: string) {\n this.requireId(apiKeyId);\n\n return this.request<APIKey>({\n method: 'GET',\n path: joinPaths(basePath, apiKeyId),\n });\n }\n\n /**\n * Updates the given API key.\n * @returns The updated [`APIKey`](https://clerk.com/docs/reference/backend/types/backend-api-key) object.\n */\n async update(params: UpdateAPIKeyParams) {\n const { apiKeyId, ...bodyParams } = params;\n\n this.requireId(apiKeyId);\n\n return this.request<APIKey>({\n method: 'PATCH',\n path: joinPaths(basePath, apiKeyId),\n bodyParams,\n });\n }\n\n /**\n * Deletes the given API key.\n * @param apiKeyId - The ID of the API key to delete.\n * @returns The [`DeletedObject`](https://clerk.com/docs/reference/backend/types/deleted-object) object.\n */\n async delete(apiKeyId: string) {\n this.requireId(apiKeyId);\n\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, apiKeyId),\n });\n }\n\n /**\n * Revokes the given API key. This will immediately invalidate the API key and prevent it from being used to authenticate any future requests.\n * @returns The revoked [`APIKey`](https://clerk.com/docs/reference/backend/types/backend-api-key) object.\n */\n async revoke(params: RevokeAPIKeyParams) {\n const { apiKeyId, revocationReason = null } = params;\n\n this.requireId(apiKeyId);\n\n return this.request<APIKey>({\n method: 'POST',\n path: joinPaths(basePath, apiKeyId, 'revoke'),\n bodyParams: { revocationReason },\n });\n }\n\n /**\n * Gets the secret of the given API key.\n * @param apiKeyId - The ID of the API key to get the secret of.\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 /**\n * Verifies the given API key.\n * - If the API key is valid, the method returns the API key object with its properties.\n * - If the API key is invalid, revoked, or expired, the method will throw an error.\n * @param secret - The secret of the API key to verify.\n * @returns The verified [`APIKey`](https://clerk.com/docs/reference/backend/types/backend-api-key) object.\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","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\n/** @generateWithEmptyComment */\nexport class ClientAPI extends AbstractAPI {\n /**\n * @deprecated This method is deprecated and will be removed in a future version.\n */\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 /**\n * Gets the given [`Client`](https://clerk.com/docs/reference/backend/types/backend-client).\n * @param clientId - The ID of the client to get.\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 /**\n * Verifies the client in the given token.\n * @param token - The token to verify.\n * @returns The verified [`Client`](https://clerk.com/docs/reference/backend/types/backend-client).\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 /**\n * Retrieves the handshake payload for a given nonce. Used internally by Clerk's SDKs to resolve\n * session cookies during the handshake flow.\n *\n * @internal\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\n/** @generateWithEmptyComment */\nexport type AddDomainParams = {\n /**\n * The new domain name. For development instances, can contain the port, e.g. `myhostname:3000`. For production instances, must be a valid FQDN, e.g. `mysite.com`. Cannot contain protocol scheme.\n */\n name: string;\n /** Whether the new domain is a satellite domain. Only `true` is accepted at the moment. */\n is_satellite: boolean;\n /** The proxy URL for the domain. Applicable only to production instances. */\n proxy_url?: string | null;\n};\n\n/** @generateWithEmptyComment */\nexport type UpdateDomainParams = Partial<Pick<AddDomainParams, 'name' | 'proxy_url'>> & {\n /** The ID of the domain that will be updated. */\n domainId: string;\n /** Whether this is a domain for a secondary app, meaning that any subdomain provided is significant and will be stored as part of the domain. This is useful for supporting multiple apps (one primary and multiple secondaries) on the same root domain (eTLD+1). */\n is_secondary?: boolean | null;\n};\n\n/** @generateWithEmptyComment */\nexport class DomainAPI extends AbstractAPI {\n /**\n * Gets the list of domains for the instance. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`Domain`](https://clerk.com/docs/reference/backend/types/domain) objects and a `totalCount` property containing the total number of domains for the instance.\n */\n public async list() {\n return this.request<PaginatedResourceResponse<Domain[]>>({\n method: 'GET',\n path: basePath,\n });\n }\n\n /**\n * Adds a new domain to the instance. Useful in the case of multi-domain instances, allows adding [satellite domains](https://clerk.com/docs/guides/dashboard/dns-domains/satellite-domains) to an instance.\n * @returns The created [`Domain`](https://clerk.com/docs/reference/backend/types/domain) object.\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 /**\n * Updates a domain for the instance. Both primary and satellite domains can be updated. If you choose to use Clerk via proxy, use this endpoint to specify the `proxy_url`. Whenever you decide you'd rather switch to DNS setup for Clerk, simply set `proxy_url` to `null` for the domain.\n *\n * When you update a production instance's primary domain name, you have to make sure that you've completed all the necessary setup steps for DNS and emails to work. Expect downtime otherwise. Updating a primary domain's name will also update the instance's home origin, affecting the default application paths.\n * @returns The updated [`Domain`](https://clerk.com/docs/reference/backend/types/domain) object.\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. It is currently not possible to delete the instance's primary domain.\n * @param satelliteDomainId - The ID of the satellite domain to delete.\n * @returns The [`DeletedObject`](https://clerk.com/docs/reference/backend/types/deleted-object).\n */\n public async delete(satelliteDomainId: string) {\n return this.deleteDomain(satelliteDomainId);\n }\n\n /**\n * Deletes a satellite domain for the instance.\n * @param satelliteDomainId - The ID of the satellite domain to delete.\n * @returns The [`DeletedObject`](https://clerk.com/docs/reference/backend/types/deleted-object).\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\n/** @generateWithEmptyComment */\nexport type CreateEmailAddressParams = {\n /** The ID of the user to create the email address for. */\n userId: string;\n /** The email address to create. */\n emailAddress: string;\n /** Whether the email address should be verified. Defaults to `false`. */\n verified?: boolean;\n /** Whether the email address should be the primary email address. Defaults to `false`, unless it is the first email address added to the user. */\n primary?: boolean;\n};\n\n/** @inline */\nexport type UpdateEmailAddressParams = {\n /** Whether the email address should be verified. Defaults to `false`. */\n verified?: boolean;\n /** Whether the email address should be the primary email address. Defaults to `false`, unless it is the first email address added to the user. */\n primary?: boolean;\n};\n\n/** @generateWithEmptyComment */\nexport class EmailAddressAPI extends AbstractAPI {\n /**\n * Gets the given [`EmailAddress`](https://clerk.com/docs/reference/backend/types/backend-email-address).\n * @param emailAddressId - The ID of the email address to get.\n */\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 /**\n * Creates a new email address for the given user.\n * @returns The created [`EmailAddress`](https://clerk.com/docs/reference/backend/types/backend-email-address) object.\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 /**\n * Updates the given email address.\n * @param emailAddressId - The ID of the email address to update.\n * @param params - The parameters to update the email address.\n * @returns The updated [`EmailAddress`](https://clerk.com/docs/reference/backend/types/backend-email-address) object.\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 /**\n * Deletes the given email address.\n * @param emailAddressId - The ID of the email address to delete.\n * @returns The [`DeletedObject`](https://clerk.com/docs/reference/backend/types/deleted-object) object.\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 type { Email } from '../resources/Email';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/email';\n\n/**\n * A subset of mailbox object as specified in RFC 5322 §3.4. Specifically, a\n * `name-addr` with an optional `display-name` and a required `addr-spec`.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc5322#section-3.4}\n */\ntype Mailbox = {\n /**\n * (Optional) Display name for the mailbox. Currently accepted by the API but\n * not yet rendered server-side, so it has no effect on the delivered email\n * for now.\n */\n name?: string;\n\n /**\n * The `addr-spec` of the mailbox, i.e. the email address itself.\n */\n address: string;\n};\n\n/**\n * The recipient of the email. Provide exactly one of the two mutually exclusive\n * forms:\n *\n * - a literal mailbox: an `address` (plus an optional `name`), or\n * - a `userId`: the ID of a Clerk user whose primary email address Clerk\n * resolves server-side, from the instance the secret key belongs to.\n */\ntype EmailRecipient =\n | {\n /**\n * The `addr-spec` of the recipient mailbox, i.e. the email address itself.\n */\n address: string;\n /**\n * (Optional) Display name for the recipient mailbox. Currently accepted\n * by the API but not yet rendered server-side.\n */\n name?: string;\n userId?: never;\n }\n | {\n /**\n * The ID of the Clerk user to send to. Clerk resolves the user's primary\n * email address from the instance context. Mutually exclusive with\n * `address`.\n */\n userId: string;\n address?: never;\n name?: never;\n };\n\n/**\n * The body of the email. At least one of `html` and `text` must be provided; if\n * both are provided, the `html` version takes precedence. Encoded as a union so\n * that omitting both is a compile-time error rather than a server-side one.\n */\ntype EmailContent =\n | {\n /**\n * The HTML body of the email. Takes precedence over `text` when both are\n * provided.\n */\n html: string;\n /**\n * (Optional) The plain text body of the email.\n */\n text?: string;\n }\n | {\n /**\n * (Optional) The HTML body of the email. Takes precedence over `text`\n * when both are provided.\n */\n html?: string;\n /**\n * The plain text body of the email.\n */\n text: string;\n };\n\nexport type CreateEmailParams = {\n /**\n * The recipient of the email. Currently only a single recipient is supported.\n * Provide either an `address` (with an optional `name`) or the `userId` of a\n * Clerk user; the two forms are mutually exclusive.\n */\n to: EmailRecipient;\n\n /**\n * The sender of the email. See {@link Mailbox} for the accepted format. Note\n * that the API does not yet render the `name` field of the `from` mailbox.\n */\n from: Mailbox;\n\n /**\n * (Optional) The mailbox to include in the `reply-to` header of the email.\n */\n replyTo?: Mailbox;\n\n subject: string;\n} & EmailContent;\n\nexport class EmailApi extends AbstractAPI {\n /**\n * @experimental This method calls an internal, not-yet-public endpoint and is\n * subject to change. It is advised to [pin](https://clerk.com/docs/pinning)\n * the SDK version to avoid breaking changes.\n *\n * Sends a transactional email.\n */\n public async create(params: CreateEmailParams) {\n return this.request<Email>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n options: {\n // Snakecase nested keys too, so a `to: { userId }` recipient is sent as\n // `to: { user_id }` on the wire (the default only snakecases top-level\n // keys, which would leave the nested `userId` untouched).\n deepSnakecaseBodyParamKeys: true,\n },\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { EnterpriseConnection } from '../resources';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/enterprise_connections';\n\n/** @generateWithEmptyComment */\nexport type EnterpriseConnectionListParams = ClerkPaginationRequest<{\n /**\n * Filters enterprise connections by Organization ID.\n */\n organizationId?: string;\n /**\n * Filters enterprise connections by active status. If `true`, only active connections are returned. If `false`, only inactive connections are returned. If omitted, all connections are returned.\n */\n active?: boolean;\n}>;\n\n/** @inline */\nexport interface EnterpriseConnectionOidcParams {\n /** The OAuth (OIDC) authorization URL. */\n authUrl?: string;\n /** The OAuth (OIDC) client ID. */\n clientId?: string;\n /** The OAuth (OIDC) client secret. */\n clientSecret?: string;\n /** The OAuth (OIDC) discovery URL. */\n discoveryUrl?: string;\n /** Whether the OAuth (OIDC) requires PKCE. Must be `true` for public clients with no client secret. */\n requiresPkce?: boolean;\n /** The OAuth (OIDC) token URL. */\n tokenUrl?: string;\n /** The OAuth (OIDC) user info URL. */\n userInfoUrl?: string;\n}\n\n/** @inline */\nexport interface EnterpriseConnectionSamlAttributeMappingParams {\n /** The attribute mapping for the user ID. */\n userId?: string | null;\n /** The attribute mapping for the email address. */\n emailAddress?: string | null;\n /** The attribute mapping for the first name. */\n firstName?: string | null;\n /** The attribute mapping for the last name. */\n lastName?: string | null;\n}\n\n/** @inline */\nexport interface EnterpriseConnectionSamlParams {\n /** Whether the SAML connection allows Identity Provider (IdP) initiated flows. */\n allowIdpInitiated?: boolean;\n /** Whether the SAML connection allows users with an email address subdomain to use it. */\n allowSubdomains?: boolean;\n /** The attribute mapping for the SAML connection. */\n attributeMapping?: EnterpriseConnectionSamlAttributeMappingParams;\n /** Whether the SAML connection requires force authentication. */\n forceAuthn?: boolean;\n /** The IdP certificate (PEM) for the SAML connection. */\n idpCertificate?: string;\n /** The IdP Entity ID for the SAML connection. */\n idpEntityId?: string;\n /** The raw IdP metadata XML for the SAML connection. */\n idpMetadata?: string;\n /** The IdP metadata URL for the SAML connection. */\n idpMetadataUrl?: string;\n /** The IdP Single-Sign On URL for the SAML connection. */\n idpSsoUrl?: string;\n}\n\n/** @generateWithEmptyComment */\nexport type CreateEnterpriseConnectionParams = {\n /** The name of the enterprise connection. */\n name?: string;\n /** The [Verified Domains](https://clerk.com/docs/guides/organizations/add-members/verified-domains) of the enterprise connection. */\n domains?: string[];\n /** The organization ID of the enterprise connection. */\n organizationId?: string;\n /** Whether the enterprise connection should be active. */\n active?: boolean;\n /** Whether the enterprise connection should sync user attributes between the IdP and Clerk. */\n syncUserAttributes?: boolean;\n /** Configuration for if the enterprise connection uses OAuth (OIDC). */\n oidc?: EnterpriseConnectionOidcParams;\n /** Configuration for if the enterprise connection uses SAML. */\n saml?: EnterpriseConnectionSamlParams;\n};\n\n/** @inline */\nexport type UpdateEnterpriseConnectionParams = {\n /** The name of the enterprise connection. */\n name?: string;\n /** The [Verified Domains](https://clerk.com/docs/guides/organizations/add-members/verified-domains) of the enterprise connection. */\n domains?: string[];\n /** The organization ID of the enterprise connection. */\n organizationId?: string;\n /** Whether the enterprise connection should be active. */\n active?: boolean;\n /** Whether the enterprise connection should sync user attributes between the IdP and Clerk. */\n syncUserAttributes?: boolean;\n /** The identity provider (IdP) of the enterprise connection. For example, `'saml_custom'` or `'oidc_custom'`. */\n provider?: string;\n /** Configuration for if the enterprise connection uses OAuth (OIDC). */\n oidc?: EnterpriseConnectionOidcParams;\n /** Configuration for if the enterprise connection uses SAML. */\n saml?: EnterpriseConnectionSamlParams;\n};\n\n/** @generateWithEmptyComment */\nexport class EnterpriseConnectionAPI extends AbstractAPI {\n /**\n * Creates a new enterprise connection.\n * @returns The created [`EnterpriseConnection`](https://clerk.com/docs/reference/backend/types/backend-enterprise-connection) object.\n */\n public async createEnterpriseConnection(params: CreateEnterpriseConnectionParams) {\n return this.request<EnterpriseConnection>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n options: {\n deepSnakecaseBodyParamKeys: true,\n },\n });\n }\n\n /**\n * Updates the given enterprise connection.\n * @param enterpriseConnectionId - The ID of the enterprise connection to update.\n * @param params - The parameters to update the enterprise connection.\n * @returns The updated [`EnterpriseConnection`](https://clerk.com/docs/reference/backend/types/backend-enterprise-connection) object.\n */\n public async updateEnterpriseConnection(enterpriseConnectionId: string, params: UpdateEnterpriseConnectionParams) {\n this.requireId(enterpriseConnectionId);\n return this.request<EnterpriseConnection>({\n method: 'PATCH',\n path: joinPaths(basePath, enterpriseConnectionId),\n bodyParams: params,\n options: {\n deepSnakecaseBodyParamKeys: true,\n },\n });\n }\n\n /**\n * Gets the list of enterprise connections for the instance. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`EnterpriseConnection`](https://clerk.com/docs/reference/backend/types/backend-enterprise-connection) objects and a `totalCount` property containing the total number of enterprise connections for the instance.\n */\n public async getEnterpriseConnectionList(params: EnterpriseConnectionListParams = {}) {\n return this.request<PaginatedResourceResponse<EnterpriseConnection[]>>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n /**\n * Gets the given enterprise connection.\n * @param enterpriseConnectionId - The ID of the enterprise connection to get.\n * @returns The [`EnterpriseConnection`](https://clerk.com/docs/reference/backend/types/backend-enterprise-connection) object.\n */\n public async getEnterpriseConnection(enterpriseConnectionId: string) {\n this.requireId(enterpriseConnectionId);\n return this.request<EnterpriseConnection>({\n method: 'GET',\n path: joinPaths(basePath, enterpriseConnectionId),\n });\n }\n\n /**\n * Deletes the given enterprise connection.\n * @param enterpriseConnectionId - The ID of the enterprise connection to delete.\n * @returns The deleted [`EnterpriseConnection`](https://clerk.com/docs/reference/backend/types/backend-enterprise-connection) object.\n */\n public async deleteEnterpriseConnection(enterpriseConnectionId: string) {\n this.requireId(enterpriseConnectionId);\n return this.request<EnterpriseConnection>({\n method: 'DELETE',\n path: joinPaths(basePath, enterpriseConnectionId),\n });\n }\n}\n","import { joinPaths } from '../../util/path';\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","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\n/** @generateWithEmptyComment */\nexport type UpdateParams = {\n /** Toggles [test mode](https://clerk.com/docs/guides/development/testing/test-emails-and-phones#set-up-test-mode) for this instance, allowing the use of test email addresses and phone numbers. Defaults to `true` for development instances. */\n testMode?: boolean | null | undefined;\n /** Whether the instance should be using the Have I Been Pwned (HIBP) service to check passwords for breaches. */\n hibp?: boolean | null | undefined;\n /** Whether the instance should send emails from \"verifications@clerk.dev\" instead of your domain. This can be helpful if you do not have a high domain reputation. */\n enhancedEmailDeliverability?: boolean | null | undefined;\n /** The support email for the instance. */\n supportEmail?: string | null | undefined;\n /** The npm version for `@clerk/clerk-js`. */\n clerkJsVersion?: string | null | undefined;\n /** The development origin for the instance. */\n developmentOrigin?: string | null | undefined;\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. 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.js, the origin is `capacitor://localhost`. */\n allowedOrigins?: Array<string> | undefined;\n /** Whether the instance should use URL-based session syncing in development mode (i.e. without third-party cookies). */\n urlBasedSessionSyncing?: boolean | null | undefined;\n /** Overrides the sign-in strategy that is preferred when a password is required. The value is only consulted when a password is required, and is dormant otherwise. Pass an empty string to clear the override. Passing `null` or `undefined` leaves the current value unchanged. */\n preferredSignInStrategyWhenPasswordRequired?: 'password' | 'otp' | '' | null | undefined;\n};\n\n/** @generateWithEmptyComment */\nexport type UpdateRestrictionsParams = {\n /** Whether the instance should have [**Allowlist**](https://clerk.com/docs/guides/secure/restricting-access#allowlist) enabled. */\n allowlist?: boolean | null | undefined;\n /** Whether the instance should have [**Blocklist**](https://clerk.com/docs/guides/secure/restricting-access#blocklist) enabled. */\n blocklist?: boolean | null | undefined;\n /** Whether the instance should have [**Block email subaddresses**](https://clerk.com/docs/guides/secure/restricting-access#block-email-subaddresses) enabled. */\n blockEmailSubaddresses?: boolean | null | undefined;\n /** Whether the instance should have [**Block sign-ups that use disposable email domains**](https://clerk.com/docs/guides/secure/restricting-access#block-sign-ups-that-use-disposable-email-addresses) enabled. */\n blockDisposableEmailDomains?: boolean | null | undefined;\n /** Whether the instance should [ignore dots for Gmail addresses](https://clerk.com/docs/guides/secure/restricting-access#block-email-subaddresses). */\n ignoreDotsForGmailAddresses?: boolean | null | undefined;\n};\n\n/** @generateWithEmptyComment */\nexport type UpdateOrganizationSettingsParams = {\n /** Whether the instance should enable [Organizations](https://clerk.com/docs/guides/organizations/overview). */\n enabled?: boolean | null | undefined;\n /** The maximum number of [memberships allowed](https://clerk.com/docs/guides/organizations/configure#membership-limits) per Organization. */\n maxAllowedMemberships?: number | null | undefined;\n /** Whether [Organization admins](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions#default-roles) are allowed to delete Organizations. */\n adminDeleteEnabled?: boolean | null | undefined;\n /** Whether [Verified Domains](https://clerk.com/docs/guides/organizations/add-members/verified-domains) are enabled for Organizations. */\n domainsEnabled?: boolean | null | undefined;\n /** Specifies which [enrollment modes](https://clerk.com/docs/guides/organizations/add-members/verified-domains#enable-verified-domains) to enable for your Organization's [Verified Domains](https://clerk.com/docs/guides/organizations/add-members/verified-domains). Supported modes are `'automatic_invitation'` & `'automatic_suggestion'`. */\n domainsEnrollmentModes?: Array<string> | undefined;\n /** Specifies what the default Organization [Role](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) is for an Organization creator. */\n creatorRoleId?: string | null | undefined;\n /** Specifies what the default Organization [Role](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) is for the Organization's [Verified Domains](https://clerk.com/docs/guides/organizations/add-members/verified-domains). */\n domainsDefaultRoleId?: string | null | undefined;\n};\n\n/** @generateWithEmptyComment */\nexport class InstanceAPI extends AbstractAPI {\n /**\n * Gets the current [`Instance`](https://clerk.com/docs/reference/backend/types/backend-instance).\n */\n public async get() {\n return this.request<Instance>({\n method: 'GET',\n path: basePath,\n });\n }\n\n /**\n * Updates the current instance.\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 /**\n * Updates the [restriction](https://clerk.com/docs/guides/secure/restricting-access) settings for the current instance.\n * @returns The updated [`InstanceRestrictions`](https://clerk.com/docs/reference/backend/types/backend-instance-restrictions) object.\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 /**\n * Gets the [Organization-related settings](https://clerk.com/docs/guides/organizations/configure) for the current instance.\n * @returns The [`OrganizationSettings`](https://clerk.com/docs/reference/backend/types/backend-organization-settings) object.\n */\n public async getOrganizationSettings() {\n return this.request<OrganizationSettings>({\n method: 'GET',\n path: joinPaths(basePath, 'organization_settings'),\n });\n }\n\n /**\n * Updates the [Organization-related settings](https://clerk.com/docs/guides/organizations/configure) for the current instance.\n * @returns The updated [`OrganizationSettings`](https://clerk.com/docs/reference/backend/types/backend-organization-settings) object.\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';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/invitations';\n\n/** @inline */\nexport type TemplateSlug = 'invitation' | 'waitlist_invitation';\n\n/** @generateWithEmptyComment */\nexport type CreateParams = {\n /** The email address of the user to invite. */\n emailAddress: string;\n /** The number of days until the invitation expires. Defaults to `30`. */\n expiresInDays?: number;\n /** Whether an invitation should be created if there is already an existing invitation for this email address, or if the email address already exists in the application. Defaults to `false`. */\n ignoreExisting?: boolean;\n /** Whether an email invitation should be sent to the given email address. Defaults to `true`. */\n notify?: boolean;\n /** Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}. Once the user accepts the invitation and signs up, these metadata will end up in the user's public metadata ([`User.publicMetadata`](https://clerk.com/docs/reference/backend/types/backend-user)). */\n publicMetadata?: UserPublicMetadata;\n /** The full URL or path where the user will land after accepting the invitation. See the [custom flow guide for handling application invitations](https://clerk.com/docs/guides/development/custom-flows/authentication/application-invitations). */\n redirectUrl?: string;\n /** The template slug to use for the invitation. Defaults to `invitation`. */\n templateSlug?: TemplateSlug;\n};\n\n/** @generateWithEmptyComment */\nexport type CreateBulkParams = Array<CreateParams>;\n\n/** @generateWithEmptyComment */\nexport type GetInvitationListParams = ClerkPaginationRequest<{\n /**\n * Filters the invitations in a particular order. Prefix a value with `+` to sort in ascending order, or `-` to sort in descending order. Defaults to `-created_at`.\n *\n * @example\n * ```ts\n * // Newest first\n * await clerkClient.invitations.getInvitationList({ orderBy: '-created_at' });\n *\n * // Alphabetical by email\n * await clerkClient.invitations.getInvitationList({ orderBy: 'email_address' });\n * ```\n */\n orderBy?: WithSign<'created_at' | 'email_address' | 'expires_at'>;\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\n/** @generateWithEmptyComment */\nexport class InvitationAPI extends AbstractAPI {\n /**\n * Gets a list of non-revoked invitations for the instance, sorted by descending creation date. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`Invitation`](https://clerk.com/docs/reference/backend/types/backend-invitation) objects and a `totalCount` property containing the total number of invitations.\n */\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 /**\n * Creates a new invitation for the given email address, and sends the invitation email.\n *\n * If an email address has already been invited or already exists in your application, trying to create a new invitation will return an error. To bypass this error and create a new invitation anyways, set `ignoreExisting` to `true`.\n * @returns The newly created [`Invitation`](https://clerk.com/docs/reference/backend/types/backend-invitation).\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 /**\n * Creates multiple invitations for the given email addresses, and sends the invitation emails.\n *\n * If an email address has already been invited or already exists in your application, trying to create a new invitation will return an error. To bypass this error and create a new invitation anyways, set `ignoreExisting` to `true`.\n * @returns An array of each created [`Invitation`](https://clerk.com/docs/reference/backend/types/backend-invitation) object.\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 /**\n * Revokes the given invitation.\n *\n * Revoking an invitation makes the invitation email link unusable. However, it doesn't prevent the user from signing up if they follow the sign up flow.\n *\n * Only active (i.e. non-revoked) invitations can be revoked.\n * @param invitationId - The ID of the invitation to revoke.\n * @returns The revoked [`Invitation`](https://clerk.com/docs/reference/backend/types/backend-invitation).\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\n/** @generateWithEmptyComment */\nexport type CreateMachineParams = {\n /** The name of the machine. */\n name: string;\n /** An array of machine IDs that the new machine will have access to. Maximum of 150 scopes per machine. */\n scopedMachines?: string[];\n /** The default time-to-live (TTL) in seconds for tokens created by this machine. Must be at least 1 second. */\n defaultTokenTtl?: number;\n};\n\n/** @generateWithEmptyComment */\nexport type UpdateMachineParams = {\n /** The ID of the machine to update. */\n machineId: string;\n /** The name of the machine. */\n name?: string;\n /** The default time-to-live (TTL) in seconds for tokens created by this machine. Must be at least 1 second. */\n defaultTokenTtl?: number;\n};\n\n/** @generateWithEmptyComment */\nexport type GetMachineListParams = ClerkPaginationRequest<{\n /** Filters machines in a particular order. Prefix a value with `+` to sort in ascending order, or `-` to sort in descending order. Defaults to `-created_at`. */\n orderBy?: WithSign<'name' | 'created_at'>;\n /** Filters machines by ID or name. */\n query?: string;\n}>;\n\n/** @generateWithEmptyComment */\nexport type RotateMachineSecretKeyParams = {\n /** The ID of the machine to rotate the secret key for. */\n machineId: string;\n /** The time in seconds that the previous secret key will remain valid after rotation. This ensures a graceful transition period for updating applications with the new secret key. Set to `0` to immediately expire the previous key. Maximum value is `28800` seconds (8 hours). */\n previousTokenTtl: number;\n};\n\n/** @generateWithEmptyComment */\nexport class MachineApi extends AbstractAPI {\n /**\n * Gets the given machine.\n * @param machineId - The ID of the machine to get.\n * @returns The [`Machine`](https://clerk.com/docs/reference/backend/types/backend-machine) object.\n */\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 /**\n * Gets a list of machines for the instance. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`Machine`](https://clerk.com/docs/reference/backend/types/backend-machine) objects and a `totalCount` property containing the total number of machines for the instance.\n */\n async list(queryParams: GetMachineListParams = {}) {\n return this.request<PaginatedResourceResponse<Machine[]>>({\n method: 'GET',\n path: basePath,\n queryParams,\n });\n }\n\n /**\n * Creates a new machine.\n * @returns The created [`Machine`](https://clerk.com/docs/reference/backend/types/backend-machine) object.\n */\n async create(bodyParams: CreateMachineParams) {\n return this.request<Machine>({\n method: 'POST',\n path: basePath,\n bodyParams,\n });\n }\n\n /**\n * Updates the given machine.\n * @returns The updated [`Machine`](https://clerk.com/docs/reference/backend/types/backend-machine) object.\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 /**\n * Deletes the given machine.\n * @param machineId - The ID of the machine to delete.\n * @returns The [`Machine`](https://clerk.com/docs/reference/backend/types/backend-machine) object.\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 /**\n * Gets the secret key for the given machine.\n * @param machineId - The ID of the machine to get the secret key for.\n * @returns The machine's secret key.\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 /**\n * Rotates the secret key for the given machine.\n * @returns The new secret key.\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. Maximum of 150 scopes per machine.\n *\n * @param machineId - The ID of the machine that will have access to the target machine.\n * @param toMachineId - The ID of the machine that will be accessible by the source machine.\n * @returns The created [`MachineScope`](https://clerk.com/docs/reference/backend/types/backend-machine-scope) object.\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 the given machine scope, removing access from one machine to another.\n *\n * @param machineId - The ID of the machine that has access to the target machine.\n * @param otherMachineId - The ID of the machine that will no longer be accessible by the source machine.\n * @returns The deleted [`MachineScope`](https://clerk.com/docs/reference/backend/types/backend-machine-scope) object.\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 type { JwtPayload } from '@clerk/shared/types';\n\nimport type { IdPOAuthAccessTokenJSON } from './JSON';\n\ntype OAuthJwtPayload = JwtPayload & {\n jti?: string;\n client_id?: string;\n scope?: string;\n scp?: string[];\n};\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 /** The Unix timestamp (in milliseconds) when the access token expires. */\n readonly expiration: number | null,\n /** The Unix timestamp (in milliseconds) when the access token was created. */\n readonly createdAt: number,\n /** The Unix timestamp (in milliseconds) when the access token was last updated. */\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 /**\n * Creates an IdPOAuthAccessToken from a JWT payload.\n * Maps standard JWT claims and OAuth-specific fields to token properties.\n */\n static fromJwtPayload(payload: JwtPayload, clockSkewInMs = 5000): IdPOAuthAccessToken {\n const oauthPayload = payload as OAuthJwtPayload;\n\n // Map JWT claims to IdPOAuthAccessToken fields\n return new IdPOAuthAccessToken(\n oauthPayload.jti ?? '',\n oauthPayload.client_id ?? '',\n 'oauth_token',\n payload.sub,\n oauthPayload.scp ?? oauthPayload.scope?.split(' ') ?? [],\n false,\n null,\n payload.exp * 1000 <= Date.now() - clockSkewInMs,\n payload.exp * 1000, // milliseconds: expiration, converted from JWT exp claim\n payload.iat * 1000, // milliseconds: createdAt, converted from JWT iat claim\n payload.iat * 1000, // milliseconds: updatedAt, no JWT equivalent, defaults to iat\n );\n }\n}\n","import type { M2MTokenJSON } from './JSON';\n\n// Minimal JWT claims present in M2M tokens. M2M tokens are not session JWTs\n// and do not carry session-specific claims like `sid` or `__raw`.\ntype M2MJwtPayload = {\n sub: string;\n exp: number;\n iat: number;\n jti?: string;\n aud?: string[];\n scopes?: string;\n [key: string]: unknown;\n};\n\n// Structural claims that Clerk's machine-token service always adds when it mints\n// an M2M JWT. These are mapped onto dedicated `M2MToken` fields, so they are\n// stripped from `claims`. Everything else is a user-supplied custom claim and is\n// surfaced through `claims`, including `aud` and `scopes`, which the backend\n// treats as custom claims (they are neither reserved nor auto-added).\nconst M2M_RESERVED_JWT_CLAIMS = new Set(['iss', 'sub', 'exp', 'nbf', 'iat', 'jti']);\n\n/**\n * Reconstructs the custom claims that were attached at token creation by\n * stripping the structural claims (see `M2M_RESERVED_JWT_CLAIMS`) from the\n * verified payload. Returns `null` when no custom claims are present, matching\n * the opaque-token path where a token created without claims verifies back to\n * `claims: null`.\n */\nfunction extractCustomClaims(payload: M2MJwtPayload): Record<string, any> | null {\n const claims: Record<string, any> = {};\n for (const key of Object.keys(payload)) {\n if (!M2M_RESERVED_JWT_CLAIMS.has(key)) {\n claims[key] = payload[key];\n }\n }\n return Object.keys(claims).length > 0 ? claims : null;\n}\n\n/**\n * The Backend `M2MToken` object holds information about a [machine-to-machine token](https://clerk.com/docs/guides/development/machine-auth/m2m-tokens).\n */\nexport class M2MToken {\n constructor(\n /** The ID of the M2M token. */\n readonly id: string,\n /** The subject of the M2M token. */\n readonly subject: string,\n /** The scopes of the M2M token. */\n readonly scopes: string[],\n /** The claims of the M2M token. */\n readonly claims: Record<string, any> | null,\n /** Whether the M2M token has been revoked. */\n readonly revoked: boolean,\n /** The reason for revoking the M2M token. */\n readonly revocationReason: string | null,\n /** Whether the M2M token has expired. */\n readonly expired: boolean,\n /** The Unix timestamp (in milliseconds) when the M2M token expires. */\n readonly expiration: number | null,\n /** The Unix timestamp (in milliseconds) when the M2M token was created. */\n readonly createdAt: number,\n /** The Unix timestamp (in milliseconds) when the M2M token was last updated. */\n readonly updatedAt: number,\n /** The token string. */\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 static fromJwtPayload(payload: M2MJwtPayload, clockSkewInMs = 5000): M2MToken {\n return new M2MToken(\n payload.jti ?? '', // jti should always be present in Clerk-issued M2M JWTs\n payload.sub,\n payload.scopes?.split(' ') ?? payload.aud ?? [],\n extractCustomClaims(payload),\n false,\n null,\n payload.exp * 1000 <= Date.now() - clockSkewInMs,\n payload.exp * 1000, // milliseconds — expiration, converted from JWT exp claim\n payload.iat * 1000, // milliseconds — createdAt, converted from JWT iat claim\n payload.iat * 1000, // milliseconds — updatedAt, no JWT equivalent; defaults to iat\n );\n }\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 { decodeJwt } from '../jwt/verifyJwt';\nimport type { AuthenticateRequestOptions } from '../tokens/types';\nimport type { MachineTokenType } from './tokenTypes';\nimport { TokenType } from './tokenTypes';\n\nexport const M2M_TOKEN_PREFIX = 'mt_';\nexport const M2M_SUBJECT_PREFIX = 'mch_';\nexport const OAUTH_TOKEN_PREFIX = 'oat_';\nexport const API_KEY_PREFIX = 'ak_';\n\n// Token-category tag in the protected JOSE header of instance-signed M2M JWTs,\n// used to distinguish them from other JWT classes signed by the same instance\n// key. Kept in sync with clerk_go (pkg/jwt) and cloudflare-workers.\nexport const JWT_CATEGORY_M2M_TOKEN = 'cl_B7d4PD333AAA';\n\nconst MACHINE_TOKEN_PREFIXES = [M2M_TOKEN_PREFIX, OAUTH_TOKEN_PREFIX, API_KEY_PREFIX] as const;\n\nexport const JwtFormatRegExp = /^[a-zA-Z0-9\\-_]+\\.[a-zA-Z0-9\\-_]+\\.[a-zA-Z0-9\\-_]+$/;\n\nexport function isJwtFormat(token: string): boolean {\n return JwtFormatRegExp.test(token);\n}\n\n/**\n * Valid OAuth 2.0 JWT access token type values per RFC 9068.\n * @see https://www.rfc-editor.org/rfc/rfc9068.html#section-2.1\n */\nexport const OAUTH_ACCESS_TOKEN_TYPES = ['at+jwt', 'application/at+jwt'];\n\n/**\n * Checks if a token is an OAuth 2.0 JWT access token.\n * Validates the JWT format and verifies the header 'typ' field matches RFC 9068 values.\n *\n * @param token - The token string to check\n * @returns true if the token is a valid OAuth JWT access token\n * @see https://www.rfc-editor.org/rfc/rfc9068.html#section-2.1\n */\nexport function isOAuthJwt(token: string): boolean {\n if (!isJwtFormat(token)) {\n return false;\n }\n try {\n const { data, errors } = decodeJwt(token);\n return (\n !errors &&\n !!data &&\n OAUTH_ACCESS_TOKEN_TYPES.includes(data.header.typ as (typeof OAUTH_ACCESS_TOKEN_TYPES)[number])\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Checks if a token is an M2M JWT token.\n * Validates the JWT format and verifies the payload 'sub' field starts with 'mch_'.\n *\n * @param token - The token string to check\n * @returns true if the token is a valid M2M JWT token\n */\nexport function isM2MJwt(token: string): boolean {\n if (!isJwtFormat(token)) {\n return false;\n }\n try {\n const { data, errors } = decodeJwt(token);\n return !errors && !!data && typeof data.payload.sub === 'string' && data.payload.sub.startsWith(M2M_SUBJECT_PREFIX);\n } catch {\n return false;\n }\n}\n\n/**\n * Checks if a token is a machine JWT (OAuth JWT or M2M JWT).\n * Useful for rejecting machine JWTs when expecting session tokens.\n *\n * @param token - The token string to check\n * @returns true if the token is an OAuth or M2M JWT\n */\nexport function isMachineJwt(token: string): boolean {\n return isOAuthJwt(token) || isM2MJwt(token);\n}\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 * Checks if a token is a machine token by looking at its prefix or if it's an OAuth/M2M JWT.\n *\n * @param token - The token string to check\n * @returns true if the token is a machine token\n */\nexport function isMachineToken(token: string): boolean {\n return isMachineTokenByPrefix(token) || isOAuthJwt(token) || isM2MJwt(token);\n}\n\n/**\n * Gets the specific type of machine token based on its prefix or JWT claims.\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 type\n */\nexport function getMachineTokenType(token: string): MachineTokenType {\n // M2M: prefix OR JWT with mch_ subject\n if (token.startsWith(M2M_TOKEN_PREFIX) || isM2MJwt(token)) {\n return TokenType.M2MToken;\n }\n\n // OAuth: prefix OR JWT with at+jwt typ\n if (token.startsWith(OAUTH_TOKEN_PREFIX) || isOAuthJwt(token)) {\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\nconst MACHINE_TOKEN_TYPES = new Set<string>([TokenType.ApiKey, TokenType.M2MToken, TokenType.OAuthToken]);\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 MACHINE_TOKEN_TYPES.has(type);\n}\n","import type { Jwt, JwtPayload } from '@clerk/shared/types';\n\nimport { IdPOAuthAccessToken } from '../api/resources/IdPOAuthAccessToken';\nimport { M2MToken } from '../api/resources/M2MToken';\nimport {\n MachineTokenVerificationError,\n MachineTokenVerificationErrorCode,\n TokenVerificationErrorAction,\n} from '../errors';\nimport type { MachineTokenReturnType } from '../jwt/types';\nimport { verifyJwt } from '../jwt/verifyJwt';\nimport type { LoadClerkJWKFromRemoteOptions } from '../tokens/keys';\nimport { loadClerkJwkFromPem, loadClerkJWKFromRemote } from '../tokens/keys';\nimport { JWT_CATEGORY_M2M_TOKEN, OAUTH_ACCESS_TOKEN_TYPES } from '../tokens/machine';\nimport { TokenType } from '../tokens/tokenTypes';\n\nexport type JwtMachineVerifyOptions = Pick<LoadClerkJWKFromRemoteOptions, 'secretKey' | 'apiUrl' | 'skipJwksCache'> & {\n jwtKey?: string;\n clockSkewInMs?: number;\n};\n\n/**\n * Resolves the signing key and verifies a machine JWT's signature and claims.\n *\n * Networkless when `jwtKey` (PEM) is provided; performs a JWKS fetch when only `secretKey` is set.\n * Returns a discriminated union so callers can branch on `'error' in result` without try/catch.\n *\n * Note: uses `MachineTokenVerificationError`, not `TokenVerificationError` — the two error types\n * are intentionally separate because session-token errors carry handshake metadata that machine\n * tokens don't need.\n */\nasync function resolveKeyAndVerifyJwt(\n token: string,\n kid: string,\n options: JwtMachineVerifyOptions,\n headerType?: string[],\n): Promise<{ payload: JwtPayload } | { error: MachineTokenVerificationError }> {\n try {\n let key: JsonWebKey;\n\n if (options.jwtKey) {\n key = loadClerkJwkFromPem({ kid, pem: options.jwtKey });\n } else if (options.secretKey) {\n key = await loadClerkJWKFromRemote({ ...options, kid });\n } else {\n return {\n error: new MachineTokenVerificationError({\n action: TokenVerificationErrorAction.SetClerkJWTKey,\n message: 'Failed to resolve JWK during verification.',\n code: MachineTokenVerificationErrorCode.TokenVerificationFailed,\n }),\n };\n }\n\n const { data: payload, errors: verifyErrors } = await verifyJwt(token, {\n ...options,\n key,\n ...(headerType ? { headerType } : {}),\n });\n\n if (verifyErrors) {\n return {\n error: new MachineTokenVerificationError({\n code: MachineTokenVerificationErrorCode.TokenVerificationFailed,\n message: verifyErrors[0].message,\n }),\n };\n }\n\n return { payload };\n } catch (error) {\n return {\n error: new MachineTokenVerificationError({\n code: MachineTokenVerificationErrorCode.TokenVerificationFailed,\n message: (error as Error).message,\n }),\n };\n }\n}\n\n/**\n * Verifies a pre-decoded M2M JWT (identified by `sub` starting with `mch_`).\n */\nexport async function verifyM2MJwt(\n token: string,\n decoded: Jwt,\n options: JwtMachineVerifyOptions,\n): Promise<MachineTokenReturnType<M2MToken, MachineTokenVerificationError>> {\n // Reject JWTs of another class (e.g. session, jwt-template) signed by the same\n // instance key. Absent `cat` is still accepted during the rollout window; tighten\n // to strict equality once pre-rollout M2M JWTs have expired (USER-5437).\n const cat = decoded.header.cat;\n if (cat !== undefined && cat !== JWT_CATEGORY_M2M_TOKEN) {\n return {\n data: undefined,\n tokenType: TokenType.M2MToken,\n errors: [\n new MachineTokenVerificationError({\n code: MachineTokenVerificationErrorCode.TokenInvalid,\n message: 'Invalid M2M JWT category.',\n }),\n ],\n };\n }\n\n const result = await resolveKeyAndVerifyJwt(token, decoded.header.kid, options);\n\n if ('error' in result) {\n return { data: undefined, tokenType: TokenType.M2MToken, errors: [result.error] };\n }\n\n return {\n data: M2MToken.fromJwtPayload(result.payload, options.clockSkewInMs),\n tokenType: TokenType.M2MToken,\n errors: undefined,\n };\n}\n\n/**\n * Verifies a pre-decoded OAuth access token JWT (identified by `typ: at+jwt` or `application/at+jwt`).\n */\nexport async function verifyOAuthJwt(\n token: string,\n decoded: Jwt,\n options: JwtMachineVerifyOptions,\n): Promise<MachineTokenReturnType<IdPOAuthAccessToken, MachineTokenVerificationError>> {\n const result = await resolveKeyAndVerifyJwt(token, decoded.header.kid, options, OAUTH_ACCESS_TOKEN_TYPES);\n\n if ('error' in result) {\n return { data: undefined, tokenType: TokenType.OAuthToken, errors: [result.error] };\n }\n\n return {\n data: IdPOAuthAccessToken.fromJwtPayload(result.payload, options.clockSkewInMs),\n tokenType: TokenType.OAuthToken,\n errors: undefined,\n };\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\n\nimport { MachineTokenVerificationError, MachineTokenVerificationErrorCode } from '../../errors';\nimport { decodeJwt } from '../../jwt/verifyJwt';\nimport type { JwtMachineVerifyOptions } from '../../jwt/verifyMachineJwt';\nimport { verifyM2MJwt } from '../../jwt/verifyMachineJwt';\nimport { isM2MJwt } from '../../tokens/machine';\nimport { joinPaths } from '../../util/path';\nimport type { ClerkBackendApiRequestOptions, RequestFunction } from '../request';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { M2MToken } from '../resources/M2MToken';\nimport { AbstractAPI } from './AbstractApi';\n\nconst basePath = '/m2m_tokens';\n\n/** @inline */\nexport type M2MTokenFormat = 'opaque' | 'jwt';\n\n/** @generateWithEmptyComment */\nexport type GetM2MTokenListParams = ClerkPaginationRequest<{\n /** The custom machine secret key for authentication. If not provided, the SDK will use the value from the environment variables. */\n machineSecretKey?: string;\n /** The machine ID to query M2M tokens by. */\n subject: string;\n /** Whether to include revoked M2M tokens. Defaults to `false`. */\n revoked?: boolean;\n /** Whether to include expired M2M tokens. Defaults to `false`. */\n expired?: boolean;\n}>;\n\n/** @generateWithEmptyComment */\nexport type CreateM2MTokenParams = {\n /** The custom machine secret key for authentication. If not provided, the SDK will use the value from the environment variables. */\n machineSecretKey?: string;\n /** The number of seconds until the token expires. Defaults to `null`, meaning the token does not expire. */\n secondsUntilExpiration?: number | null;\n /** Custom claims to include in the M2M token payload. */\n claims?: Record<string, unknown> | null;\n /**\n * Enables server-side token reuse for opaque tokens. Only applies to opaque tokens (`token_format: 'opaque'`). JWT tokens (`token_format: 'jwt'`) are stateless and are never deduplicated. When set, if a non-revoked, non-expired M2M token already exists for this machine with identical `claims` and `scopes` and at least this many seconds of remaining lifetime, that existing token is returned and no new token is minted.\n *\n * Use this when caching tokens in application memory across requests is impractical — for example, in serverless functions, short-lived job workers, or autoscaling containers that churn faster than the token TTL. Pooling at the server collapses many redundant create calls into reuse of a single live token, which is the recommended pattern for high-volume M2M traffic.\n *\n * Must be strictly less than the effective token lifetime — that is, `seconds_until_expiration` when provided, or the machine's default TTL otherwise. A value greater than or equal to the lifetime is rejected with a `400` error, since no freshly-minted token would ever satisfy the requirement.\n */\n minRemainingTtlSeconds?: number;\n /**\n * The format of the M2M token to create. Defaults to `'opaque'`. Set to `'jwt'` to create a [JSON Web Token](/docs/guides/how-clerk-works/tokens-and-signatures#json-web-tokens-jwts) that can be verified locally without a network request. For a detailed comparison of the two formats, see [Token formats](/docs/guides/development/machine-auth/token-formats).\n */\n tokenFormat?: M2MTokenFormat;\n};\n\n/** @generateWithEmptyComment */\nexport type RevokeM2MTokenParams = {\n /** The custom machine secret key for authentication. If not provided, the SDK will use the value from the environment variables. */\n machineSecretKey?: string;\n /** The ID of the M2M token to revoke. */\n m2mTokenId: string;\n /** The reason for revoking the M2M token. Useful for your records. */\n revocationReason?: string | null;\n};\n\n/** @generateWithEmptyComment */\nexport type VerifyM2MTokenParams = {\n /** The custom machine secret key for authentication. If not provided, the SDK will use the value from the environment variables. */\n machineSecretKey?: string;\n /** The M2M token to verify. */\n token: string;\n};\n\n/** @generateWithEmptyComment */\nexport class M2MTokenApi extends AbstractAPI {\n #verifyOptions: JwtMachineVerifyOptions;\n\n /**\n * @param verifyOptions - JWT verification options (secretKey, apiUrl, etc.).\n * Passed explicitly because BuildRequestOptions are captured inside the buildRequest closure\n * and are not accessible from the RequestFunction itself.\n */\n constructor(request: RequestFunction, verifyOptions: JwtMachineVerifyOptions = {}) {\n super(request);\n this.#verifyOptions = verifyOptions;\n }\n\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 /**\n * Gets a list of M2M tokens for the given machine. By default, the list is returned in descending order by creation date (newest first). This endpoint can be authenticated by either a Machine Secret Key or by a Clerk [Secret Key](!secret-key).\n * - When fetching M2M tokens with a Machine Secret Key, only tokens associated with the authenticated machine can be retrieved.\n * - When fetching M2M tokens with a Clerk Secret Key, tokens for any machine in the instance can be retrieved.\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`M2MToken`](https://clerk.com/docs/reference/backend/types/backend-m2m-token) objects and a `totalCount` property containing the total number of M2M tokens for the machine.\n */\n async list(queryParams: GetM2MTokenListParams) {\n const { machineSecretKey, ...params } = queryParams;\n\n const requestOptions = this.#createRequestOptions(\n {\n method: 'GET',\n path: basePath,\n queryParams: params,\n },\n machineSecretKey,\n );\n\n return this.request<PaginatedResourceResponse<M2MToken[]>>(requestOptions);\n }\n\n /**\n * Creates a new [M2M token](https://clerk.com/docs/guides/development/machine-auth/m2m-tokens) for the given machine. Must be authenticated by a Machine Secret Key.\n * @returns The created [`M2MToken`](https://clerk.com/docs/reference/backend/types/backend-m2m-token) object.\n */\n async createToken(params?: CreateM2MTokenParams) {\n const {\n claims = null,\n machineSecretKey,\n minRemainingTtlSeconds,\n secondsUntilExpiration = null,\n tokenFormat = 'opaque',\n } = params || {};\n\n const requestOptions = this.#createRequestOptions(\n {\n method: 'POST',\n path: basePath,\n bodyParams: {\n secondsUntilExpiration,\n claims,\n minRemainingTtlSeconds,\n tokenFormat,\n },\n },\n machineSecretKey,\n );\n\n return this.request<M2MToken>(requestOptions);\n }\n\n /**\n * Revokes an [M2M token](https://clerk.com/docs/guides/development/machine-auth/m2m-tokens). This endpoint can be authenticated by either a Machine Secret Key or by a Clerk [Secret Key](!secret-key).\n * - When revoking M2M tokens with a Machine Secret Key, the token will be revoked using the machine secret key.\n * - When revoking M2M tokens with a Clerk Secret Key, the token will be revoked using the instance secret key.\n * @returns The revoked [`M2MToken`](https://clerk.com/docs/reference/backend/types/backend-m2m-token) object.\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 #verifyJwtFormat(token: string): Promise<M2MToken> {\n let decoded;\n try {\n const { data, errors } = decodeJwt(token);\n if (errors) {\n throw errors[0];\n }\n decoded = data;\n } catch (e) {\n throw new MachineTokenVerificationError({\n code: MachineTokenVerificationErrorCode.TokenInvalid,\n message: (e as Error).message,\n });\n }\n\n const result = await verifyM2MJwt(token, decoded, this.#verifyOptions);\n if (result.errors) {\n throw result.errors[0];\n }\n return result.data;\n }\n\n /**\n * Verifies a [M2M token](https://clerk.com/docs/guides/development/machine-auth/m2m-tokens). Must be authenticated by a Machine Secret Key.\n * @returns The verified [`M2MToken`](https://clerk.com/docs/reference/backend/types/backend-m2m-token) object.\n */\n async verify(params: VerifyM2MTokenParams) {\n const { token, machineSecretKey } = params;\n\n if (isM2MJwt(token)) {\n return this.#verifyJwtFormat(token);\n }\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","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';\n\nimport { joinPaths } from '../../util/path';\nimport type { DeletedObject, JwtTemplate } from '../resources';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\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<PaginatedResourceResponse<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 { deprecated } from '../../util/shared';\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\n/** @inline */\nexport type MetadataParams<TPublic = OrganizationPublicMetadata, TPrivate = OrganizationPrivateMetadata> = {\n /** Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}, but can be set only from the Backend API. */\n publicMetadata?: TPublic;\n /** Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}. */\n privateMetadata?: TPrivate;\n};\n\n/** @generateWithEmptyComment */\nexport type GetOrganizationListParams = ClerkPaginationRequest<{\n /** Whether to include the number of members in the Organization. */\n includeMembersCount?: boolean;\n /** Filters Organizations by ID, name, or slug. Uses exact match for ID and partial match for name and slug. */\n query?: string;\n /** Filters Organizations in a particular order. Prefix a value with `+` to sort in ascending order, or `-` to sort in descending order. Defaults to `-created_at`. */\n orderBy?: WithSign<'name' | 'created_at' | 'members_count'>;\n /** Filters Organizations by ID. Accepts up to 100 Organization IDs. */\n organizationId?: string[];\n}>;\n\n/** @generateWithEmptyComment */\nexport type CreateParams = {\n /** The name of the Organization. */\n name: string;\n /** The slug of the Organization. */\n slug?: string;\n /** The ID of the user creating the Organization. The user will become an [admin](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions#default-roles) for the Organization. */\n createdBy?: string;\n /** The maximum number of memberships allowed in the Organization. `0` means unlimited. */\n maxAllowedMemberships?: number;\n} & MetadataParams;\n\n/** @generateWithEmptyComment */\nexport type GetOrganizationParams = (\n | {\n /** The ID of the Organization to get. */\n organizationId: string;\n }\n | {\n /** The slug of the Organization to get. */\n slug: string;\n }\n) & {\n /** Whether to include the number of members in the Organization. */\n includeMembersCount?: boolean;\n};\n\n/** @inline */\nexport type UpdateParams = {\n /** The name to update the Organization with. */\n name?: string;\n /** The slug to update the Organization with. */\n slug?: string;\n /** Whether the Organization allows admins to delete users. */\n adminDeleteEnabled?: boolean;\n /** The maximum number of memberships allowed in the Organization. `0` means unlimited. */\n maxAllowedMemberships?: number;\n /**\n * @deprecated Updating metadata via [`updateOrganization()`](https://clerk.com/docs/reference/backend/organization/update-organization) is deprecated. Use [`updateOrganizationMetadata()`](https://clerk.com/docs/reference/backend/organization/update-organization-metadata) for partial updates (deep merge) or [`replaceOrganizationMetadata()`](https://clerk.com/docs/reference/backend/organization/replace-organization-metadata) for full replacement.\n */\n publicMetadata?: OrganizationPublicMetadata;\n /**\n * @deprecated Updating metadata via [`updateOrganization()`](https://clerk.com/docs/reference/backend/organization/update-organization) is deprecated. Use [`updateOrganizationMetadata()`](https://clerk.com/docs/reference/backend/organization/update-organization-metadata) for partial updates (deep merge) or [`replaceOrganizationMetadata()`](https://clerk.com/docs/reference/backend/organization/replace-organization-metadata) for full replacement.\n */\n privateMetadata?: OrganizationPrivateMetadata;\n};\n\n/** @inline */\nexport type UpdateLogoParams = {\n /** The file to upload as the logo. */\n file: Blob | File;\n /** The ID of the user uploading the logo. */\n uploaderUserId?: string;\n};\n\n/** @inline */\nexport type UpdateMetadataParams = MetadataParams;\n\n/** @generateWithEmptyComment */\nexport type GetOrganizationMembershipListParams = ClerkPaginationRequest<{\n /** The ID of the Organization to get the list of memberships for. */\n organizationId: string;\n /**\n * Filters Organization memberships in a particular order. Prefix a value with `+` to sort in ascending order, or `-` to sort in descending order. Defaults to `-created_at`.\n */\n orderBy?: WithSign<'phone_number' | 'email_address' | 'created_at' | 'first_name' | 'last_name' | 'username'>;\n /**\n * Filters Organization memberships by user ID. Accepts up to 100 user IDs.\n */\n userId?: string[];\n /** Filters Organization memberships by email address. Accepts up to 100 email addresses. */\n emailAddress?: string[];\n /** Filters Organization memberships by phone number. Accepts up to 100 phone numbers. */\n phoneNumber?: string[];\n /** Filters Organization memberships by username. Accepts up to 100 usernames. */\n username?: string[];\n /** Filters Organization memberships by web3 wallet address. Accepts up to 100 web3 wallet addresses. */\n web3Wallet?: string[];\n /** Filters Organization memberships by Role. Accepts up to 100 Roles. */\n role?: OrganizationMembershipRole[];\n /**\n * Filters Organization memberships matching the given query across email addresses, phone numbers, usernames, Web3 wallet addresses, user IDs, first names, and last names. Partial matches supported. For example, `query=hello` will match a user with the email `HELLO@example.com`.\n */\n query?: string;\n /**\n * Filters Organization memberships by email address. Accepts up to 100 email addresses. Partial matches supported. For example, `emailAddressQuery=ello` will match a user with the email `HELLO@example.com`.\n */\n emailAddressQuery?: string;\n\n /**\n * Filters Organization memberships by phone number. Accepts up to 100 phone numbers. Partial matches supported. For example, `phoneNumberQuery=555` will match a user with the phone number `+1555xxxxxxx`.\n */\n phoneNumberQuery?: string;\n /**\n * Filters Organization memberships by username. Accepts up to 100 usernames. Partial matches supported. For example, `usernameQuery=CoolUser` will match a user with the username `SomeCoolUser`.\n */\n usernameQuery?: string;\n /** Filters Organization memberships by name. Accepts up to 100 names. Partial matches supported. For example, `nameQuery=John Doe` will match a user with the name `John Doe`. */\n nameQuery?: string;\n /**\n * Filters Organization memberships by last session activity before the given date (with millisecond precision). For example, use `1700690400000` to get users whose last session activity was before 2023-11-23.\n */\n lastActiveAtBefore?: number;\n /**\n * Filters Organization memberships by last session activity after the given date (with millisecond precision). For example, use `1700690400000` to get users whose last session activity was after 2023-11-23.\n */\n lastActiveAtAfter?: number;\n /**\n * Filters Organization memberships by creation date before the given date (with millisecond precision). For example, use `1730160000000` to get users who have been created before 2024-10-29.\n */\n createdAtBefore?: number;\n /**\n * Filters Organization memberships by creation date after the given date (with millisecond precision). For example, use `1730160000000` to get users who have been created after 2024-10-29.\n */\n createdAtAfter?: number;\n}>;\n\n/** @generateWithEmptyComment */\nexport type GetInstanceOrganizationMembershipListParams = ClerkPaginationRequest<{\n /**\n * Filters Organization memberships in a particular order. Prefix a value with `+` to sort in ascending order, or `-` to sort in descending order. Defaults to `-created_at`.\n */\n orderBy?: WithSign<'phone_number' | 'email_address' | 'created_at' | 'first_name' | 'last_name' | 'username'>;\n}>;\n\n/** @generateWithEmptyComment */\nexport type CreateOrganizationMembershipParams = {\n /** The ID of the Organization the user is being added to. */\n organizationId: string;\n /** The ID of the user to be added to the Organization. */\n userId: string;\n /** The [Role](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) to assign to the user. */\n role: OrganizationMembershipRole;\n};\n\n/** @generateWithEmptyComment */\nexport type UpdateOrganizationMembershipParams = CreateOrganizationMembershipParams;\n\n/** @generateWithEmptyComment */\nexport type UpdateOrganizationMembershipMetadataParams = {\n /** The ID of the Organization the membership belongs to. */\n organizationId: string;\n /** The ID of the user the membership belongs to. */\n userId: string;\n} & MetadataParams<OrganizationMembershipPublicMetadata>;\n\n/** @generateWithEmptyComment */\nexport type DeleteOrganizationMembershipParams = {\n /** The ID of the Organization to remove the user from. */\n organizationId: string;\n /** The ID of the user to remove from the Organization. */\n userId: string;\n};\n\n/** @generateWithEmptyComment */\nexport type CreateOrganizationInvitationParams = {\n /** The ID of the Organization the user is being invited to. */\n organizationId: string;\n /** The email address of the user being invited. */\n emailAddress: string;\n /** The [Role](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) to assign to the user. */\n role: OrganizationMembershipRole;\n /** The number of days until the invitation expires. Defaults to `30`. */\n expiresInDays?: number;\n /** The ID of the user creating the invitation. */\n inviterUserId?: string;\n /** Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}. */\n privateMetadata?: OrganizationInvitationPrivateMetadata;\n /** Metadata that can be read from the Frontend API and [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}, but can be set only from the Backend API. */\n publicMetadata?: OrganizationInvitationPublicMetadata;\n /** The full URL or path where the user will land after accepting the invitation. */\n redirectUrl?: string;\n};\n\n/** @inline */\nexport type CreateBulkOrganizationInvitationParams = Array<Omit<CreateOrganizationInvitationParams, 'organizationId'>>;\n\n/** @generateWithEmptyComment */\nexport type GetOrganizationInvitationListParams = ClerkPaginationRequest<{\n /** The ID of the Organization to get the list of invitations for. */\n organizationId: string;\n /** Filters Organization invitations by status. Accepts up to 100 statuses. */\n status?: OrganizationInvitationStatus[];\n}>;\n\n/** @generateWithEmptyComment */\nexport type GetOrganizationInvitationParams = {\n /** The ID of the Organization to get the invitation for. */\n organizationId: string;\n /** The ID of the Organization invitation to get. */\n invitationId: string;\n};\n\n/** @generateWithEmptyComment */\nexport type RevokeOrganizationInvitationParams = {\n /** The ID of the Organization to revoke the invitation from. */\n organizationId: string;\n /** The ID of the Organization invitation to revoke. */\n invitationId: string;\n /** The ID of the user revoking the invitation. */\n requestingUserId?: string;\n};\n\n/** @generateWithEmptyComment */\nexport type GetOrganizationDomainListParams = {\n /** The ID of the Organization to get the list of domains for. */\n organizationId: string;\n /** Maximum number of items returned per request. Must be an integer greater than zero and less than `501`. Can be used for paginating the results together with offset. Defaults to `10`. */\n limit?: number;\n /** Skip the first `offset` items when paginating. Needs to be an integer greater or equal to zero. To be used in conjunction with `limit`. Defaults to `0`. */\n offset?: number;\n};\n\n/** @generateWithEmptyComment */\nexport type CreateOrganizationDomainParams = {\n /** The ID of the Organization to create the domain for. */\n organizationId: string;\n /** The name of the domain. */\n name: string;\n /** The enrollment mode that determines how matching users are added to the Organization.\n *\n * <ul>\n * <li>`manual_invitation`: No automatic enrollment. Users with a matching email domain are not given any [invitation](https://clerk.com/docs/guides/organizations/add-members/verified-domains#automatic-invitations) or [suggestion](https://clerk.com/docs/guides/organizations/add-members/verified-domains#automatic-suggestions); an [admin](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions#default-roles) must invite them manually.</li>\n * <li>`automatic_invitation`: Users with a matching email domain automatically receive a pending [invitation](https://clerk.com/docs/reference/types/organization-invitation) (assigned the Organization's default role) which they can accept to join.</li>\n * <li>`automatic_suggestion`: Users with a matching email domain automatically receive a [suggestion](https://clerk.com/docs/guides/organizations/add-members/verified-domains#automatic-suggestions) to join, which they can request.</li>\n * </ul>\n */\n enrollmentMode: OrganizationEnrollmentMode;\n /** Whether the domain is verified. Defaults to `true`. */\n verified?: boolean;\n};\n\n/** @generateWithEmptyComment */\nexport type UpdateOrganizationDomainParams = {\n /** The ID of the Organization to update the domain for. */\n organizationId: string;\n /** The ID of the domain to update. */\n domainId: string;\n} & Partial<CreateOrganizationDomainParams>;\n\n/** @generateWithEmptyComment */\nexport type DeleteOrganizationDomainParams = {\n /** The ID of the Organization to delete the domain for. */\n organizationId: string;\n /** The ID of the domain to delete. */\n domainId: string;\n};\n\n/** @generateWithEmptyComment */\nexport class OrganizationAPI extends AbstractAPI {\n /**\n * Gets the list of Organizations for the instance. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`Organization`](https://clerk.com/docs/reference/backend/types/backend-organization) objects and a `totalCount` property containing the total number of Organizations for the instance.\n */\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 /** Creates an [`Organization`](https://clerk.com/docs/reference/backend/types/backend-organization). */\n public async createOrganization(params: CreateParams) {\n return this.request<Organization>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n /** Gets an [Organization](https://clerk.com/docs/reference/backend/types/backend-organization). */\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 /**\n * Updates an [Organization](https://clerk.com/docs/reference/backend/types/backend-organization).\n * @param organizationId - The ID of the Organization to update.\n * @param params - The parameters to update the Organization with.\n * @returns The updated [Organization](https://clerk.com/docs/reference/backend/types/backend-organization).\n */\n public async updateOrganization(organizationId: string, params: UpdateParams) {\n this.requireId(organizationId);\n\n const { publicMetadata, privateMetadata, ...rest } = params;\n const hasMetadata = publicMetadata !== undefined || privateMetadata !== undefined;\n const hasRest = Object.keys(rest).length > 0;\n\n if (hasMetadata) {\n deprecated(\n 'updateOrganization(organizationId, { publicMetadata | privateMetadata })',\n 'Use updateOrganizationMetadata for partial updates (merge) or replaceOrganizationMetadata for full replacement.',\n );\n }\n\n if (!hasMetadata) {\n return this.request<Organization>({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId),\n bodyParams: rest,\n });\n }\n\n if (hasRest) {\n await this.request<Organization>({\n method: 'PATCH',\n path: joinPaths(basePath, organizationId),\n bodyParams: rest,\n });\n }\n\n return this.request<Organization>({\n method: 'PUT',\n path: joinPaths(basePath, organizationId, 'metadata'),\n bodyParams: { publicMetadata, privateMetadata },\n });\n }\n\n /**\n * Updates the logo of the given Organization.\n * @param organizationId - The ID of the Organization to update the logo for.\n * @param params - The parameters to update the logo with.\n * @returns The updated [`Organization`](https://clerk.com/docs/reference/backend/types/backend-organization).\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 /**\n * Deletes the logo of the given Organization.\n * @param organizationId - The ID of the Organization to delete the logo for.\n * @returns The deleted [`Organization`](https://clerk.com/docs/reference/backend/types/backend-organization).\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 /**\n * Updates the metadata for the given Organization, by merging existing values with the provided parameters.\n *\n * A \"deep\" merge will be performed - \"deep\" means that any nested JSON objects will be merged as well. You can remove metadata keys at any level by setting their value to `null`.\n *\n * @param organizationId - The ID of the Organization to update the metadata for.\n * @param params - The parameters to update the metadata with.\n * @returns The updated [`Organization`](https://clerk.com/docs/reference/backend/types/backend-organization).\n *\n * > [!TIP]\n * > If you want to fully replace the existing metadata instead of merging, use [`replaceOrganizationMetadata()`](https://clerk.com/docs/reference/backend/organization/replace-organization-metadata).\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 /**\n * Replaces the metadata associated with the specified Organization. Unlike [`updateOrganizationMetadata()`](/docs/reference/backend/organization/update-organization-metadata), which deep-merges into the existing metadata, this method uses replace semantics: when a metadata field is provided, its previous value is overwritten in full with no merging at any level.\n *\n * The distinction is at two layers:\n * - **Top-level field omission preserves the existing value.** Each top-level field (`publicMetadata`, `privateMetadata`) is handled independently. If you don't include a field in the request, the stored value for that field is left untouched.\n * - **The value inside a provided field is replaced in full.** When you do include a field, its previous content is discarded — any nested keys present before but absent in the new value are dropped. There is no merge.\n *\n * For the provided field, you can also send:\n * - `{}` (empty object) to clear the field.\n * - `null` to overwrite the field with a JSON `null` value. Prefer `{}` unless you specifically need a stored `null`.\n * @param organizationId - The ID of the Organization to replace the metadata for.\n * @param params - The metadata to replace.\n * @returns The updated [`Organization`](https://clerk.com/docs/reference/backend/types/backend-organization).\n */\n public async replaceOrganizationMetadata(organizationId: string, params: MetadataParams) {\n this.requireId(organizationId);\n\n return this.request<Organization>({\n method: 'PUT',\n path: joinPaths(basePath, organizationId, 'metadata'),\n bodyParams: params,\n });\n }\n\n /**\n * Deletes the given Organization.\n * @param organizationId - The ID of the Organization to delete.\n * @returns The deleted [`Organization`](https://clerk.com/docs/reference/backend/types/backend-organization).\n */\n public async deleteOrganization(organizationId: string) {\n this.requireId(organizationId);\n\n return this.request<Organization>({\n method: 'DELETE',\n path: joinPaths(basePath, organizationId),\n });\n }\n\n /**\n * Gets the list of Organization memberships for the specified Organization. By default, the list is returned in descending order by creation date (newest first).\n *\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`OrganizationMembership`](https://clerk.com/docs/reference/backend/types/backend-organization-membership) objects and a `totalCount` property containing the total number of Organization memberships for the Organization.\n *\n * > [!TIP]\n * > To get the list of Organization memberships **for your instance**, use [`getInstanceOrganizationMembershipList()`](/docs/reference/backend/organization/get-instance-organization-membership-list).\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 /**\n * Gets the list of Organization memberships for the instance. By default, the list is returned in descending order by creation date (newest first).\n *\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`OrganizationMembership`](https://clerk.com/docs/reference/backend/types/backend-organization-membership) objects and a `totalCount` property containing the total number of Organization memberships for the instance.\n *\n * > [!TIP]\n * > To get the list of Organization memberships **for a specific Organization**, use [`getOrganizationMembershipList()`](/docs/reference/backend/organization/get-organization-membership-list).\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 /**\n * Creates a membership to an Organization for a user directly (circumventing the need for an invitation).\n * @returns The newly created [`OrganizationMembership`](https://clerk.com/docs/reference/backend/types/backend-organization-membership) object.\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 /**\n * Updates a user's [`OrganizationMembership`](https://clerk.com/docs/reference/backend/types/backend-organization-membership).\n * @returns The updated [`OrganizationMembership`](https://clerk.com/docs/reference/backend/types/backend-organization-membership) object.\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 /**\n * Updates the metadata for the given Organization membership, by merging existing values with the provided parameters.\n *\n * A \"deep\" merge will be performed - \"deep\" means that any nested JSON objects will be merged as well. You can remove metadata keys at any level by setting their value to `null`.\n *\n * @returns The updated [`OrganizationMembership`](https://clerk.com/docs/reference/backend/types/backend-organization-membership).\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 /**\n * Removes a user from the given Organization.\n * @param organizationId - The ID of the Organization to remove the user from.\n * @param userId - The ID of the user to remove from the Organization.\n * @returns The deleted [`OrganizationMembership`](https://clerk.com/docs/reference/backend/types/backend-organization-membership).\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 /**\n * Gets the list of Organization invitations for the specified Organization.\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`OrganizationInvitation`](https://clerk.com/docs/reference/backend/types/backend-organization-invitation) objects and a `totalCount` property containing the total number of Organization invitations for the Organization.\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 /**\n * Creates an invitation for a user to join an Organization.\n * @returns The newly created [`OrganizationInvitation`](https://clerk.com/docs/reference/backend/types/backend-organization-invitation) object.\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 /** Creates multiple invitations for users to join an Organization.\n * @param organizationId - The ID of the Organization to create the invitations for.\n * @param params - The parameters to create the invitations with.\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`OrganizationInvitation`](https://clerk.com/docs/reference/backend/types/backend-organization-invitation) objects and a `totalCount` property containing the total number of Organization invitations.\n */\n public async createOrganizationInvitationBulk(\n organizationId: string,\n params: CreateBulkOrganizationInvitationParams,\n ) {\n this.requireId(organizationId);\n\n return this.request<PaginatedResourceResponse<OrganizationInvitation[]>>({\n method: 'POST',\n path: joinPaths(basePath, organizationId, 'invitations', 'bulk'),\n bodyParams: params,\n });\n }\n\n /** Gets an [`OrganizationInvitation`](https://clerk.com/docs/reference/backend/types/backend-organization-invitation). */\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 /**\n * Revokes an invitation from a user for the given Organization.\n * @returns The revoked [`OrganizationInvitation`](https://clerk.com/docs/reference/backend/types/backend-organization-invitation).\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 /**\n * Gets the list of [Verified Domains](https://clerk.com/docs/guides/organizations/add-members/verified-domains) for the given Organization. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`OrganizationDomain`](https://clerk.com/docs/reference/backend/types/backend-organization-domain) objects and a `totalCount` property containing the total number of Verified Domains for the Organization.\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 /**\n * Creates a new [Verified Domain](https://clerk.com/docs/guides/organizations/add-members/verified-domains) for the given Organization. By default, the domain is verified, but can be optionally set to unverified.\n * @returns The newly created [`OrganizationDomain`](https://clerk.com/docs/reference/backend/types/backend-organization-domain) object.\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 /**\n * Updates a [Verified Domain](https://clerk.com/docs/guides/organizations/add-members/verified-domains) for the given Organization.\n * @returns The updated [`OrganizationDomain`](https://clerk.com/docs/reference/backend/types/backend-organization-domain) object.\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 /**\n * Deletes a [Verified Domain](https://clerk.com/docs/guides/organizations/add-members/verified-domains) for the given Organization.\n * @returns The deleted [`OrganizationDomain`](https://clerk.com/docs/reference/backend/types/backend-organization-domain) object.\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/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { Permission } from '../resources/Permission';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/organization_permissions';\n\ntype GetOrganizationPermissionListParams = ClerkPaginationRequest<{\n /**\n * Returns organization permissions with ID, name, or key that match the given query.\n * Uses exact match for permission ID and partial match for name and key.\n */\n query?: string;\n /**\n * Allows to return organization permissions in a particular order.\n * At the moment, you can order the returned permissions by their `created_at`, `name`, or `key`.\n */\n orderBy?: WithSign<'created_at' | 'name' | 'key'>;\n}>;\n\ntype CreateOrganizationPermissionParams = {\n /**\n * The name of the permission.\n */\n name: string;\n /**\n * The key of the permission. Must have the format `org:feature:action`, for example `org:billing:manage`.\n * Cannot begin with `org:sys_` as that prefix is reserved for system permissions.\n */\n key: string;\n /**\n * A description of the permission.\n */\n description?: string;\n};\n\ntype UpdateOrganizationPermissionParams = {\n permissionId: string;\n} & Partial<CreateOrganizationPermissionParams>;\n\nexport class OrganizationPermissionAPI extends AbstractAPI {\n public async getOrganizationPermissionList(params: GetOrganizationPermissionListParams = {}) {\n return this.request<PaginatedResourceResponse<Permission[]>>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async getOrganizationPermission(permissionId: string) {\n this.requireId(permissionId);\n return this.request<Permission>({\n method: 'GET',\n path: joinPaths(basePath, permissionId),\n });\n }\n\n public async createOrganizationPermission(params: CreateOrganizationPermissionParams) {\n return this.request<Permission>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updateOrganizationPermission(params: UpdateOrganizationPermissionParams) {\n const { permissionId, ...bodyParams } = params;\n this.requireId(permissionId);\n return this.request<Permission>({\n method: 'PATCH',\n path: joinPaths(basePath, permissionId),\n bodyParams,\n });\n }\n\n public async deleteOrganizationPermission(permissionId: string) {\n this.requireId(permissionId);\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, permissionId),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { Role } from '../resources/Role';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/organization_roles';\n\ntype GetOrganizationRoleListParams = ClerkPaginationRequest<{\n /**\n * Returns organization roles with ID, name, or key that match the given query.\n * Uses exact match for organization role ID and partial match for name and key.\n */\n query?: string;\n /**\n * Allows to return organization roles in a particular order.\n * At the moment, you can order the returned organization roles by their `created_at`, `name`, or `key`.\n */\n orderBy?: WithSign<'created_at' | 'name' | 'key'>;\n}>;\n\ntype CreateOrganizationRoleParams = {\n /**\n * The name of the new organization role.\n */\n name: string;\n /**\n * A unique key for the organization role. Must start with `org:` and contain only lowercase\n * alphanumeric characters and underscores.\n */\n key: string;\n /**\n * Optional description for the role.\n */\n description?: string | null;\n /**\n * Array of permission IDs to assign to the role.\n */\n permissions?: string[] | null;\n /**\n * Whether this role should be included in the initial role set.\n */\n includeInInitialRoleSet?: boolean | null;\n};\n\ntype UpdateOrganizationRoleParams = {\n organizationRoleId: string;\n /**\n * The new name for the organization role.\n */\n name?: string | null;\n /**\n * A unique key for the organization role. Must start with `org:` and contain only lowercase\n * alphanumeric characters and underscores.\n */\n key?: string | null;\n /**\n * Optional description for the role.\n */\n description?: string | null;\n /**\n * Array of permission IDs to assign to the role. If provided, this will replace the existing permissions.\n */\n permissions?: string[] | null;\n};\n\ntype OrganizationRolePermissionParams = {\n organizationRoleId: string;\n permissionId: string;\n};\n\nexport class OrganizationRoleAPI extends AbstractAPI {\n public async getOrganizationRoleList(params: GetOrganizationRoleListParams = {}) {\n return this.request<PaginatedResourceResponse<Role[]>>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async getOrganizationRole(organizationRoleId: string) {\n this.requireId(organizationRoleId);\n return this.request<Role>({\n method: 'GET',\n path: joinPaths(basePath, organizationRoleId),\n });\n }\n\n public async createOrganizationRole(params: CreateOrganizationRoleParams) {\n return this.request<Role>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updateOrganizationRole(params: UpdateOrganizationRoleParams) {\n const { organizationRoleId, ...bodyParams } = params;\n this.requireId(organizationRoleId);\n return this.request<Role>({\n method: 'PATCH',\n path: joinPaths(basePath, organizationRoleId),\n bodyParams,\n });\n }\n\n public async deleteOrganizationRole(organizationRoleId: string) {\n this.requireId(organizationRoleId);\n return this.request<DeletedObject>({\n method: 'DELETE',\n path: joinPaths(basePath, organizationRoleId),\n });\n }\n\n public async assignPermissionToOrganizationRole(params: OrganizationRolePermissionParams) {\n const { organizationRoleId, permissionId } = params;\n this.requireId(organizationRoleId);\n this.requireId(permissionId);\n return this.request<Role>({\n method: 'POST',\n path: joinPaths(basePath, organizationRoleId, 'permissions', permissionId),\n });\n }\n\n public async removePermissionFromOrganizationRole(params: OrganizationRolePermissionParams) {\n const { organizationRoleId, permissionId } = params;\n this.requireId(organizationRoleId);\n this.requireId(permissionId);\n return this.request<Role>({\n method: 'DELETE',\n path: joinPaths(basePath, organizationRoleId, 'permissions', permissionId),\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\n/** @generateWithEmptyComment */\nexport type CreateOAuthApplicationParams = {\n /**\n * A descriptive name for the OAuth application (e.g., \"My Web App\", \"My Mobile App\"). Maximum length: 256 characters.\n */\n name: string;\n /** An array of redirect URIs for the OAuth application. */\n redirectUris?: Array<string> | null | undefined;\n /** Scopes for the OAuth application 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 scopes?: string | null | undefined;\n /** Whether the OAuth application is public. If `true`, the Proof Key of Code Exchange (PKCE) flow can be used. */\n public?: boolean | null | undefined;\n};\n\n/** @generateWithEmptyComment */\nexport type UpdateOAuthApplicationParams = CreateOAuthApplicationParams & {\n /** The ID of the OAuth application to update. */\n oauthApplicationId: string;\n};\n\n/** @generateWithEmptyComment */\nexport type RevokeOAuthApplicationTokenParams = {\n /** The ID of the OAuth application for which to revoke the token. */\n oauthApplicationId: string;\n /** The opaque OAuth access token or refresh token to revoke. */\n token: string;\n};\n\n/** @generateWithEmptyComment */\nexport type GetOAuthApplicationListParams = ClerkPaginationRequest<{\n /**\n * Returns OAuth applications in a particular order. Prefix a value with `+` to sort in ascending order, or `-` to sort in descending order. Defaults to `-created_at`.\n */\n orderBy?: WithSign<'name' | 'created_at'>;\n}>;\n\n/** @generateWithEmptyComment */\nexport class OAuthApplicationsApi extends AbstractAPI {\n /**\n * Gets a list of OAuth applications for the instance. By default, the list is returned in descending order by creation date (newest first).\n * @param params - The parameters to get the OAuth applications with.\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`OAuthApplication`](https://clerk.com/docs/reference/backend/types/backend-oauth-application) objects and a `totalCount` property containing the total number of OAuth applications.\n */\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 /**\n * Gets the given OAuth application.\n * @param oauthApplicationId - The ID of the OAuth application to get.\n * @returns The [`OAuthApplication`](https://clerk.com/docs/reference/backend/types/backend-oauth-application) object.\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 /**\n * Creates a new OAuth application.\n * @param params - The parameters to create the OAuth application with.\n * @returns The created [`OAuthApplication`](https://clerk.com/docs/reference/backend/types/backend-oauth-application) object.\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 /**\n * Updates the given OAuth application.\n * @returns The updated [`OAuthApplication`](https://clerk.com/docs/reference/backend/types/backend-oauth-application) object.\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 /**\n * Deletes the given OAuth application.\n * @param oauthApplicationId - The ID of the OAuth application to delete.\n * @returns The [`DeletedObject`](https://clerk.com/docs/reference/backend/types/deleted-object) object.\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 /**\n * Rotates the secret of the given OAuth application. When the client secret is rotated, ensure that you update it in your authorized OAuth clients.\n * @param oauthApplicationId - The ID of the OAuth application to rotate the secret of.\n * @returns The [`OAuthApplication`](https://clerk.com/docs/reference/backend/types/backend-oauth-application) object.\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 /**\n * Revokes both the [OAuth access token](!oauth-access-token) and refresh token for the associated grant for the given [`OAuthApplication`](/docs/reference/backend/types/backend-oauth-application). The request may specify either token.\n */\n public async revokeToken(params: RevokeOAuthApplicationTokenParams) {\n const { oauthApplicationId, ...bodyParams } = params;\n\n this.requireId(oauthApplicationId);\n\n return this.request<void>({\n method: 'POST',\n path: joinPaths(basePath, oauthApplicationId, 'revoke_token'),\n bodyParams,\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\n/** @generateWithEmptyComment */\nexport type CreatePhoneNumberParams = {\n /** The ID of the user to create the phone number for. */\n userId: string;\n /** The phone number to assign to the specified user. Must be in [E.164 format](https://en.wikipedia.org/wiki/E.164). */\n phoneNumber: string;\n /** Whether the phone number should be verified. Defaults to `false`. */\n verified?: boolean;\n /** Whether the phone number should be the primary phone number. Defaults to `false`, unless it is the first phone number added to the user. */\n primary?: boolean;\n /** Whether the phone number should be reserved for [multi-factor authentication](https://clerk.com/docs/guides/configure/auth-strategies/sign-up-sign-in-options#multi-factor-authentication). The phone number must also be verified. If there are no other reserved [second factors](!second-factor-verification), the phone number will be set as the default second factor. Defaults to `false`. */\n reservedForSecondFactor?: boolean;\n};\n\n/** @inline */\nexport type UpdatePhoneNumberParams = {\n /** Whether the phone number should be verified. Defaults to `false`. */\n verified?: boolean;\n /** Whether the phone number should be the primary phone number. Defaults to `false`, unless it is the first phone number added to the user. */\n primary?: boolean;\n /** Whether the phone number should be reserved for [multi-factor authentication](https://clerk.com/docs/guides/configure/auth-strategies/sign-up-sign-in-options#multi-factor-authentication). The phone number must also be verified. If there are no other reserved [second factors](!second-factor-verification), the phone number will be set as the default second factor. Defaults to `false`. */\n reservedForSecondFactor?: boolean;\n};\n\n/** @generateWithEmptyComment */\nexport class PhoneNumberAPI extends AbstractAPI {\n /**\n * Gets the given [`PhoneNumber`](https://clerk.com/docs/reference/backend/types/backend-phone-number).\n * @param phoneNumberId - The ID of the phone number to get.\n */\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 /**\n * Creates a new phone number for the given user.\n * @returns The created [`PhoneNumber`](https://clerk.com/docs/reference/backend/types/backend-phone-number) object.\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 /**\n * Updates the given phone number.\n * @param phoneNumberId - The ID of the phone number to update.\n * @param params - The parameters to update the phone number.\n * @returns The updated [`PhoneNumber`](https://clerk.com/docs/reference/backend/types/backend-phone-number) object.\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 /**\n * Deletes the given phone number.\n * @param phoneNumberId - The ID of the phone number to delete.\n * @returns The [`DeletedObject`](https://clerk.com/docs/reference/backend/types/deleted-object) object.\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\n/** @generateWithEmptyComment */\nexport type CreateRedirectUrlParams = {\n /** The full URL value prefixed with `https://` or a custom scheme. For example, `https://my-app.com/oauth-callback` or `my-app://oauth-callback`. */\n url: string;\n};\n\n/** @generateWithEmptyComment */\nexport class RedirectUrlAPI extends AbstractAPI {\n /**\n * Gets a list of whitelisted redirect URLs for the instance. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`RedirectUrl`](https://clerk.com/docs/reference/backend/types/backend-redirect-url) objects and a `totalCount` property containing the total number of redirect URLs.\n */\n public async getRedirectUrlList() {\n return this.request<PaginatedResourceResponse<RedirectUrl[]>>({\n method: 'GET',\n path: basePath,\n queryParams: { paginated: true },\n });\n }\n\n /**\n * Gets the given [`RedirectUrl`](https://clerk.com/docs/reference/backend/types/backend-redirect-url).\n * @param redirectUrlId - The ID of the redirect URL to get.\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 /**\n * Creates a new redirect URL for the instance.\n * @returns The created [`RedirectUrl`](https://clerk.com/docs/reference/backend/types/backend-redirect-url) object.\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 /**\n * Deletes the given redirect URL.\n * @param redirectUrlId - The ID of the redirect URL to delete.\n * @returns The deleted [`RedirectUrl`](https://clerk.com/docs/reference/backend/types/backend-redirect-url) object.\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 } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\nimport type { DeletedObject } from '../resources/DeletedObject';\nimport type { PaginatedResourceResponse } from '../resources/Deserializer';\nimport type { RoleSet } from '../resources/RoleSet';\nimport { AbstractAPI } from './AbstractApi';\nimport type { WithSign } from './util-types';\n\nconst basePath = '/role_sets';\n\ntype GetRoleSetListParams = ClerkPaginationRequest<{\n /**\n * Returns role sets with ID, name, or key that match the given query.\n * Uses exact match for role set ID and partial match for name and key.\n */\n query?: string;\n /**\n * Allows to return role sets in a particular order.\n * At the moment, you can order the returned role sets by their `created_at`, `name`, or `key`.\n */\n orderBy?: WithSign<'created_at' | 'name' | 'key'>;\n}>;\n\ntype CreateRoleSetParams = {\n /**\n * The name of the new role set.\n */\n name: string;\n /**\n * A unique key for the role set. Must start with `role_set:` and contain only lowercase\n * alphanumeric characters and underscores. If not provided, a key will be generated from the name.\n */\n key?: string;\n /**\n * Optional description for the role set.\n */\n description?: string | null;\n /**\n * The key of the role to use as the default role for new organization members.\n * Must be one of the roles in the `roles` array.\n */\n defaultRoleKey: string;\n /**\n * The key of the role to assign to organization creators.\n * Must be one of the roles in the `roles` array.\n */\n creatorRoleKey: string;\n /**\n * The type of the role set. `initial` role sets are the default for new organizations.\n * Only one role set can be `initial` per instance.\n */\n type?: 'initial' | 'custom';\n /**\n * Array of role keys to include in the role set. Must contain at least one role and no more than 10 roles.\n */\n roles: string[];\n};\n\ntype UpdateRoleSetParams = {\n roleSetKeyOrId: string;\n /**\n * The new name for the role set.\n */\n name?: string | null;\n /**\n * A unique key for the role set. Must start with `role_set:` and contain only lowercase\n * alphanumeric characters and underscores.\n */\n key?: string | null;\n /**\n * Optional description for the role set.\n */\n description?: string | null;\n /**\n * Set to `initial` to make this the default role set for new organizations.\n * Only one role set can be `initial` per instance; setting this will change any existing initial role set to `custom`.\n */\n type?: 'initial' | null;\n /**\n * The key of the role to use as the default role for new organization members. Must be an existing role in the role set.\n */\n defaultRoleKey?: string | null;\n /**\n * The key of the role to assign to organization creators. Must be an existing role in the role set.\n */\n creatorRoleKey?: string | null;\n};\n\ntype AddRolesToRoleSetParams = {\n roleSetKeyOrId: string;\n /**\n * Array of role keys to add to the role set. Must contain at least one role and no more than 10 roles.\n */\n roleKeys: string[];\n /**\n * Optionally update the default role to one of the newly added roles.\n */\n defaultRoleKey?: string;\n /**\n * Optionally update the creator role to one of the newly added roles.\n */\n creatorRoleKey?: string;\n};\n\ntype ReplaceRoleInRoleSetParams = {\n roleSetKeyOrId: string;\n /**\n * The key of the role to remove from the role set.\n */\n roleKey: string;\n /**\n * The key of the role to reassign members to.\n */\n toRoleKey: string;\n};\n\ntype ReplaceRoleSetParams = {\n roleSetKeyOrId: string;\n /**\n * The key of the destination role set.\n */\n destRoleSetKey: string;\n /**\n * Mappings from source role keys to destination role keys.\n * Required if members have roles that need to be reassigned.\n */\n reassignmentMappings?: Record<string, string>;\n};\n\nexport class RoleSetAPI extends AbstractAPI {\n public async getRoleSetList(params: GetRoleSetListParams = {}) {\n return this.request<PaginatedResourceResponse<RoleSet[]>>({\n method: 'GET',\n path: basePath,\n queryParams: params,\n });\n }\n\n public async getRoleSet(roleSetKeyOrId: string) {\n this.requireId(roleSetKeyOrId);\n return this.request<RoleSet>({\n method: 'GET',\n path: joinPaths(basePath, roleSetKeyOrId),\n });\n }\n\n public async createRoleSet(params: CreateRoleSetParams) {\n return this.request<RoleSet>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n public async updateRoleSet(params: UpdateRoleSetParams) {\n const { roleSetKeyOrId, ...bodyParams } = params;\n this.requireId(roleSetKeyOrId);\n return this.request<RoleSet>({\n method: 'PATCH',\n path: joinPaths(basePath, roleSetKeyOrId),\n bodyParams,\n });\n }\n\n public async addRolesToRoleSet(params: AddRolesToRoleSetParams) {\n const { roleSetKeyOrId, ...bodyParams } = params;\n this.requireId(roleSetKeyOrId);\n return this.request<RoleSet>({\n method: 'POST',\n path: joinPaths(basePath, roleSetKeyOrId, 'roles'),\n bodyParams,\n });\n }\n\n public async replaceRoleInRoleSet(params: ReplaceRoleInRoleSetParams) {\n const { roleSetKeyOrId, ...bodyParams } = params;\n this.requireId(roleSetKeyOrId);\n return this.request<RoleSet>({\n method: 'POST',\n path: joinPaths(basePath, roleSetKeyOrId, 'roles', 'replace'),\n bodyParams,\n });\n }\n\n public async replaceRoleSet(params: ReplaceRoleSetParams) {\n const { roleSetKeyOrId, ...bodyParams } = params;\n this.requireId(roleSetKeyOrId);\n return this.request<DeletedObject>({\n method: 'POST',\n path: joinPaths(basePath, roleSetKeyOrId, 'replace'),\n bodyParams,\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\n/** @generateWithEmptyComment */\nexport type SessionListParams = ClerkPaginationRequest<{\n /** The ID of the client to get sessions for. */\n clientId?: string;\n /** The ID of the user to get sessions for. */\n userId?: string;\n /** The status of the sessions to get. */\n status?: SessionStatus;\n}>;\n\n/** @inline */\nexport type RefreshTokenParams = {\n /** The expired token to refresh. */\n expired_token: string;\n /** The refresh token to refresh. */\n refresh_token: string;\n /** The origin of the request. */\n request_origin: string;\n /** The originating IP address of the request. */\n request_originating_ip?: string;\n /** The headers of the request. */\n request_headers?: Record<string, string[]>;\n /** Whether to use suffixed cookies. */\n suffixed_cookies?: boolean;\n /** The format of the token to refresh. */\n format?: 'token' | 'cookie';\n};\n\n/** @generateWithEmptyComment */\nexport type CreateSessionParams = {\n /** The ID of the user to create a session for. */\n userId: string;\n};\n\n/** @generateWithEmptyComment */\nexport class SessionAPI extends AbstractAPI {\n /**\n * Gets a list of sessions for either the specified client or user. Requires either `clientId` or `userId` to be provided. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`Session`](https://clerk.com/docs/reference/backend/types/backend-session) objects and a `totalCount` property containing the total number of sessions.\n */\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 /**\n * Gets the given [`Session`](https://clerk.com/docs/reference/backend/types/backend-session).\n * @param sessionId - The ID of the session to get.\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 /**\n * Creates a new session for the given user.\n * @returns The created [`Session`](https://clerk.com/docs/reference/backend/types/backend-session).\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 /**\n * Revokes the given session. The user will be signed out from the client the session is associated with.\n * @param sessionId - The ID of the session to revoke.\n * @returns The revoked [`Session`](https://clerk.com/docs/reference/backend/types/backend-session).\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 * Gets a session token or generates a JWT using a specified template that is defined in the [**JWT templates**](https://dashboard.clerk.com/~/jwt-templates) page in the Clerk Dashboard.\n *\n * @param sessionId - The ID of the session to get the token for.\n * @param template - The name of the JWT template configured in the Clerk Dashboard to generate a new token from.\n * @param expiresInSeconds - The expiration time for the token in seconds. If not provided, uses the default expiration.\n *\n * @returns The generated token.\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 /**\n * Refreshes the given session.\n * @param sessionId - The ID of the session to refresh.\n * @param params - The parameters to refresh the session.\n * @returns The refreshed token.\n */\n public async refreshSession(\n sessionId: string,\n params: RefreshTokenParams & {\n /** The format of the token to refresh. */\n format: 'token';\n },\n ): 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\n/** @generateWithEmptyComment */\nexport type CreateSignInTokensParams = {\n /** The ID of the user to create the sign-in token for. */\n userId: string;\n /** The number of seconds until the sign-in token expires. By default, the duration is `2592000` (30 days). */\n expiresInSeconds: number;\n};\n\nconst basePath = '/sign_in_tokens';\n\n/** @generateWithEmptyComment */\nexport class SignInTokenAPI extends AbstractAPI {\n /**\n * Creates a new sign-in token for the given user. By default, sign-in tokens expire in 30 days. You can optionally specify a custom expiration time in seconds using the `expiresInSeconds` parameter.\n * @returns The created [`SignInToken`](https://clerk.com/docs/reference/backend/types/backend-sign-in-token) object.\n */\n public async createSignInToken(params: CreateSignInTokensParams) {\n return this.request<SignInToken>({\n method: 'POST',\n path: basePath,\n bodyParams: params,\n });\n }\n\n /**\n * Revokes the given sign-in token.\n * @param signInTokenId - The ID of the sign-in token to revoke.\n * @returns The revoked [`SignInToken`](https://clerk.com/docs/reference/backend/types/backend-sign-in-token) object.\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\n/** @generateWithEmptyComment */\nexport class TestingTokenAPI extends AbstractAPI {\n /**\n * Creates a [Testing Token](https://clerk.com/docs/guides/development/testing/overview#testing-tokens) for the instance.\n * @returns The created [`TestingToken`](https://clerk.com/docs/reference/backend/types/backend-testing-token) object.\n */\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 EmailAddress,\n OauthAccessToken,\n OrganizationInvitation,\n OrganizationMembership,\n PhoneNumber,\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\n/** @generateWithEmptyComment */\nexport type UserCountParams = {\n /** Counts users with emails that match the given query, via case-insensitive partial match. For example, `emailAddress=hello` will match a user with the email `HELLO@example.com`. Accepts up to 100 email addresses. */\n emailAddress?: string[];\n /** Counts users with phone numbers that match the given query, via case-insensitive partial match. For example, `phoneNumber=555` will match a user with the phone number `+1555xxxxxxx`. Accepts up to 100 phone numbers. */\n phoneNumber?: string[];\n /** Counts users with usernames that match the given query, via case-insensitive partial match. For example, `username=CoolUser` will match a user with the username `SomeCoolUser`. Accepts up to 100 usernames. */\n username?: string[];\n /** Counts users with Web3 wallet addresses that match the given query, via case-insensitive partial match. For example, `web3Wallet=0x1234567890` will match a user with the Web3 wallet address `0x1234567890`. Accepts up to 100 Web3 wallet addresses. */\n web3Wallet?: string[];\n /** Counts users matching the given query across email addresses, phone numbers, usernames, Web3 wallet addresses, user IDs, first names, and last names. Partial matches supported. For example, `query=hello` will match a user with the email `HELLO@example.com`. */\n query?: string;\n /** Counts users with the specified user IDs. Accepts up to 100 user IDs. */\n userId?: string[];\n /** Counts users with the specified external IDs. Accepts up to 100 external IDs. */\n externalId?: string[];\n};\n\n/** @generateWithEmptyComment */\nexport type UserListParams = ClerkPaginationRequest<{\n /** Filters users with the specified email addresses. Accepts up to 100 email addresses. */\n emailAddress?: string[];\n /** Filters users with the specified phone numbers. Accepts up to 100 phone numbers. */\n phoneNumber?: string[];\n /** Filters users with the specified usernames. Accepts up to 100 usernames. */\n username?: string[];\n /** Filters users with the specified Web3 wallet addresses. Accepts up to 100 Web3 wallet addresses. */\n web3Wallet?: string[];\n /** Filters users matching the given query across email addresses, phone numbers, usernames, Web3 wallet addresses, user IDs, first names, and last names. Partial matches supported. */\n query?: string;\n /** Filters users with the specified user IDs. Accepts up to 100 user IDs. */\n userId?: string[];\n /** Filters users with the specified external IDs. Accepts up to 100 external IDs. */\n externalId?: string[];\n /** Filters users in a particular order. Prefix a value with `+` to sort in ascending order, or `-` to sort in descending order. Defaults to `-created_at`.*/\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 /**\n * @deprecated Use `lastActiveAtAfter` instead. This parameter will be removed in a future version.\n */\n last_active_at_since?: number;\n /** Filters users who were last active before the given date (with millisecond precision). */\n lastActiveAtBefore?: number;\n /** Filters users who were last active after the given date (with millisecond precision). */\n lastActiveAtAfter?: number;\n /** Filters users who were created before the given date (with millisecond precision). */\n createdAtBefore?: number;\n /** Filters users who were created after the given date (with millisecond precision). */\n createdAtAfter?: number;\n /** Filters users who were last signed in after the given date (with millisecond precision). */\n lastSignInAtAfter?: number;\n /** Filters users who were last signed in before the given date (with millisecond precision). */\n lastSignInAtBefore?: number;\n /** Filters users who are members of the specified Organizations. Accepts up to 100 Organization IDs. */\n organizationId?: string[];\n}>;\n\n/** @inline */\nexport type UserMetadataParams = {\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 publicMetadata?: UserPublicMetadata;\n /** Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}. */\n privateMetadata?: UserPrivateMetadata;\n /** Metadata that can be read and set from the Frontend API. It's considered unsafe because it can be modified from the Frontend API. */\n unsafeMetadata?: UserUnsafeMetadata;\n};\n\n/** @inline */\nexport type 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\n/** @inline */\nexport type UserPasswordHashingParams = {\n /** In case you already have the password digests and not the passwords, you can use them for the newly created user via this property. The digests should be generated with one of the supported algorithms. The hashing algorithm can be specified using the `password_hasher` property. */\n passwordDigest: string;\n /**\n * The hashing algorithm that was used to generate the password digest. Must be one of the supported algorithms. For password hashers considered insecure (currently, `md5`, `md5_salted`, `sha256`, `sha256_salted`, `sha512_symfony`), the corresponding user password hashes will be transparently migrated to `bcrypt` (a secure hasher) upon the user's first successful password sign in. Insecure schemes are marked with `(insecure)` in the list below.\n *\n * <ul>\n * <li>`awscognito`</li>\n * <ul>\n * <li>When set, `password_digest` must be in the format of `awscognito#<userpoolid>#<clientid>#<identifier>`.</li>\n * <li> Upon a successful migration, `password_hasher` will be updated to `bcrypt`, and `password_digest` will be updated to a `bcrypt` hash. </li>\n * <li> See the [migration guide](/docs/guides/development/migrating/cognito) for usage details. </li>\n * </ul>\n * <li> [`bcrypt`](https://en.wikipedia.org/wiki/Bcrypt) </li>\n * <ul>\n * <li> When set, `password_digest` must be in the format of `$<algorithm version>$<cost>$<salt & hash>`. </li>\n * </ul>\n * <li> [`bcrypt_sha256_django`](https://docs.djangoproject.com/en/4.0/topics/auth/passwords/) </li>\n * <ul>\n * <li> This is the Django-specific variant of Bcrypt, using SHA256 hashing function. When set, `password_digest` must be in the format of (as exported from Django): `bcrypt_sha256$$<algorithm version>$<cost>$<salt & hash>`. </li>\n * </ul>\n * <li> [`bcrypt_peppered`](https://github.com/heartcombo/devise) </li>\n * <ul>\n * <li> Used in implementations such as Devise for Ruby on Rails applications. Identical to `bcrypt` except that a `pepper` string is appended to the input before hashing. When set, `password_digest` must be in the format of `$<algorithm version>$<cost>$<salt & hash>$<pepper>`. </li>\n * </ul>\n * <li> [`md5` (insecure)](https://en.wikipedia.org/wiki/MD5) </li>\n * <ul>\n * <li> When set, `password_digest` must be in the format of `5f4dcc3b5aa765d61d8327deb882cf99`. </li>\n * </ul>\n * <li> [`md5_salted` (insecure)](https://en.wikipedia.org/wiki/MD5) </li>\n * <ul>\n * <li> When set, `password_digest` must be in the format of `salt$hash`. </li>\n * <li> _salt:_ The salt used to generate the above hash. </li>\n * <li> _hash:_ A 32-length hex string. </li>\n * </ul>\n * <li> [`pbkdf2_sha1`](https://en.wikipedia.org/wiki/PBKDF2) </li>\n * <ul>\n * <li> When set, `password_digest` must be in the format of `pbkdf2_sha1$<iterations>$<salt>$<hash-as-hex-string>` or `pbkdf2_sha1$<iterations>$<salt-as-hex-string>$<hash-as-hex-string>$<key-length>`. </li>\n * <li> Accepts the salt as a hex-encoded string. If the salt is not a valid hex string, the raw bytes will be used instead. Accepts the hash as a hex-encoded string. Optionally accepts the key length as the last parameter (defaults to 32). </li>\n * </ul>\n * <li> [`pbkdf2_sha256`](https://en.wikipedia.org/wiki/PBKDF2) </li>\n * <ul>\n * <li> This is the PBKDF2 algorithm using the SHA256 hashing function. When set, `password_digest` must be in the format of `pbkdf2_sha256$<iterations>$<salt>$<hash>`. </li>\n * <li> Both the salt and the hash are expected to be base64-encoded. </li>\n * </ul>\n * <li> [`pbkdf2_sha512`](https://en.wikipedia.org/wiki/PBKDF2) </li>\n * <ul>\n * <li> This is the PBKDF2 algorithm using the SHA512 hashing function. When set, `password_digest` must be in the format of `pbkdf2_sha512$<iterations>$<salt>$<hash>`. </li>\n * <li> The salt is expected to be an unencoded string literal, and the hash should be hex-encoded. </li>\n * </ul>\n * <li> [`pbkdf2_sha512_hex`](https://en.wikipedia.org/wiki/PBKDF2) </li>\n * <ul>\n * <li> This is the PBKDF2 algorithm using the SHA512 hashing function. When set, `password_digest` must be in the format of `pbkdf2_sha512_hex$<iterations>$<salt>$<hash>`. </li>\n * <li> Both the salt and the hash are expected to be hex-encoded. </li>\n * </ul>\n * <li> [`pbkdf2_sha256_django`](https://docs.djangoproject.com/en/4.0/topics/auth/passwords/) </li>\n * <ul>\n * <li> This is the Django-specific variant of PBKDF2. When set, `password_digest` must be in the format of (as exported from Django): `pbkdf2_sha256$<iterations>$<salt>$<hash>`. </li>\n * <li> The salt is expected to be un-encoded, the hash is expected base64-encoded. </li>\n * </ul>\n * <li> [`phpass`](https://www.openwall.com/phpass/) </li>\n * <ul>\n * <li> Portable public domain password hashing framework for use in PHP applications. When set, `password_digest` must be in the format of `$P$<rounds><salt><encoded-checksum>`. </li>\n * <li> `$P$` is the prefix used to identify `phpass` hashes. </li>\n * <li> _rounds:_ A single character encoding a 6-bit integer representing the number of rounds used. </li>\n * <li> _salt:_ Eight characters drawn from `[./0-9A-Za-z]`, providing a 48-bit salt. </li>\n * <li> _encoded-checksum:_ 22 characters drawn from the same set, encoding the 128-bit checksum with MD5. </li>\n * </ul>\n * <li> [`scrypt_firebase`](https://firebaseopensource.com/projects/firebase/scrypt/) </li>\n * <ul>\n * <li> The Firebase-specific variant of scrypt. When set, `password_digest` must be in the format of `<hash>$<salt>$<signer key>$<salt separator>$<rounds>$<memory cost>`. </li>\n * <li> _hash:_ The actual Base64 hash. This can be retrieved when exporting the user from Firebase. </li>\n * <li> _salt:_ The salt used to generate the above hash. Again, this is given when exporting the user from Firebase. </li>\n * <li> _signer key:_ The base64 encoded signer key. </li>\n * <li> _salt separator:_ The base64 encoded salt separator. </li>\n * <li> _rounds:_ The number of rounds the algorithm needs to run. </li>\n * <li> _memory cost:_ The cost of the algorithm run. </li>\n * </ul>\n * <li> [`scrypt_werkzeug`](https://werkzeug.palletsprojects.com/en/3.0.x/utils/#werkzeug.security.generate_password_hash) </li>\n * <ul>\n * <li> The Werkzeug-specific variant of scrypt. When set, `password_digest` must be in the format of `$<algorithm args>$<salt>$<hash>`. </li>\n * <li> _algorithm args:_ The algorithm used to generate the hash. </li>\n * <li> _salt:_ The salt used to generate the above hash. </li>\n * <li> _hash:_ The actual Base64 hash. </li>\n * </ul>\n * <li> [`sha256` (insecure)](https://en.wikipedia.org/wiki/SHA-2) </li>\n * <ul>\n * <li> When set, `password_digest` must be a 64-length hex string. For example: `9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08`. </li>\n * </ul>\n * <li> [`sha256_salted` (insecure)](https://en.wikipedia.org/wiki/SHA-2) </li>\n * <ul>\n * <li> When set, `password_digest` must be in the format of `salt$hash`. </li>\n * <li> _salt:_ The salt used to generate the above hash. </li>\n * <li> _hash:_ A 64-length hex string. </li>\n * </ul>\n * <li> [`argon2`](https://argon2.online/) variants: `argon2i` and `argon2id`. </li>\n * <ul>\n * <li> Parts are demarcated by the `$` character, with the first part identifying the algorithm variant The middle part is a comma-separated list of the encoding options (memory, iterations, parallelism). The final part is the actual digest. </li>\n * <li> When set, `password_digest` must be in the format of `$argon2i$v=19$m=4096,t=3,p=1$4t6CL3P7YiHBtwESXawI8Hm20zJj4cs7/4/G3c187e0$m7RQFczcKr5bIR0IIxbpO2P0tyrLjf3eUW3M3QSwnLc`. </li>\n * <li> For the argon2id case, the value of the algorithm in the first part of the digest is `argon2id`: `$argon2id$v=19$m=64,t=4,p=8$Z2liZXJyaXNo$iGXEpMBTDYQ8G/71tF0qGjxRHEmR3gpGULcE93zUJVU`. </li>\n * </ul>\n * <li> [`sha512_symfony` (insecure)](https://symfony.com/doc/current/security/passwords.html) </li>\n * <ul>\n * <li> The legacy Symfony `MessageDigestPasswordEncoder` algorithm. We currently only support the SHA512 variant. When set, `password_digest` must be in the format of `sha512_symfony$iterations$salt$hash`. </li>\n * <li> _iterations:_ A number greater than 0. </li>\n * <li> _salt:_ The salt used to generate the above hash. </li>\n * <li> _hash:_ The actual Base64 hash. </li>\n * </ul>\n * </ul>\n *\n * If you need support for any particular hashing algorithm, [contact support](https://clerk.com/contact/support).\n */\n passwordHasher: PasswordHasher;\n};\n\n/** @generateWithEmptyComment */\nexport type CreateUserParams = {\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 /** The email address(es) to assign to the user. Must be unique across your instance. The first email address will be set as the users primary email address. */\n emailAddress?: string[];\n /** The phone number(s) to assign to the user. Must be unique across your instance. The first phone number will be set as the users primary phone number. */\n phoneNumber?: string[];\n /** The username to assign to the user. Must be unique across your instance. */\n username?: string;\n /** The plaintext password to give the user. Must be at least 8 characters long, and can't be in any list of hacked passwords. */\n password?: string;\n /** The first name to assign to the user. */\n firstName?: string;\n /** The last name to assign to the user. */\n lastName?: string;\n /** The locale of the user in BCP-47 format (e.g. `'en-US'`, `'fr-FR'`). */\n locale?: string;\n /** When set to `true`, all password checks are skipped. It is recommended to use this method only when migrating plaintext passwords to Clerk. Upon migration the user base should be prompted to pick stronger password. */\n skipPasswordChecks?: boolean;\n /** When set to `true`, password is not required anymore when creating the user and can be omitted. This is useful when you are trying to create a user that doesn't have a password, in an instance that is using passwords. **You cannot use this flag if password is the only way for a user to sign into your instance.** */\n skipPasswordRequirement?: boolean;\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 /** 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 * If TOTP is enabled on the instance, you can provide the secret to enable it on the newly created user without the need to reset it. Currently, the supported options are:\n * <ul>\n * <li>Period: 30 seconds</li>\n * <li>Code length: 6 digits</li>\n * <li>Algorithm: SHA1</li>\n * </ul>\n */\n totpSecret?: string;\n /** If backup codes are enabled on the instance, you can provide them to enable it on the newly created 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 /** 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 /** When set to `true`, the user is created already banned and cannot sign in. */\n banned?: boolean;\n /** When set to `true`, the user is created already locked. Requires the [user lockout feature](https://clerk.com/docs/guides/secure/user-lockout#lock-a-user-programmatically) to be enabled on the instance. */\n locked?: boolean;\n} & UserMetadataParams &\n (UserPasswordHashingParams | object);\n\n/** @inline */\nexport type UpdateUserParams = {\n /** The first name to assign to the user. */\n firstName?: string;\n /** The last name to assign to the user. */\n lastName?: string;\n /** The username to assign to the user. Must be unique across your instance. */\n username?: string;\n /** The plaintext password to assign to the user. Must be at least 8 characters long, and can not be in any list of hacked passwords. */\n password?: string;\n /** When set to `true`, all password checks are skipped. It is recommended to use this method only when migrating plaintext passwords to Clerk. Upon migration the user base should be prompted to pick stronger password. */\n skipPasswordChecks?: boolean;\n /** When set to `true`, the user is signed out from all their active sessions once their password is updated. */\n signOutOfOtherSessions?: boolean;\n /** The ID of the email address to set as primary. Must be verified and present on the given user. */\n primaryEmailAddressID?: string;\n /** When set to `true`, the user is notified that their primary email address has changed. */\n notifyPrimaryEmailAddressChanged?: boolean;\n /** The ID of the phone number to set as primary. Must be verified and present on the given user. */\n primaryPhoneNumberID?: string;\n /** The ID of the web3 wallets to set as primary. Must be verified and present on the given user. */\n primaryWeb3WalletID?: string;\n /** The ID of the image to set as the user's profile image. */\n profileImageID?: string;\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. Currently, the supported options are:\n * <ul>\n * <li> Period: 30 seconds </li>\n * <li> Code length: 6 digits </li>\n * <li> Algorithm: SHA1 </li>\n * </ul>\n */\n totpSecret?: string;\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 /** The ID of the user as used in your external systems or your previous authentication solution. Must be unique across your entire instance. */\n externalId?: string;\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 /** 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 /** 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 /** The locale of the user in BCP-47 format (e.g. `'en-US'`). */\n locale?: string;\n /** If `true`, the user can delete themselves with the Frontend API. */\n deleteSelfEnabled?: boolean;\n /** If `true`, the user can create Organizations with the Frontend API. */\n createOrganizationEnabled?: boolean;\n /** The maximum number of Organizations the user can create. `0` means unlimited. */\n createOrganizationsLimit?: number;\n /**\n * @deprecated Updating metadata via `updateUser()` is deprecated. Use [`updateUserMetadata()`](https://clerk.com/docs/reference/backend/user/update-user-metadata) for partial updates (deep merge) or [`replaceUserMetadata()`](https://clerk.com/docs/reference/backend/user/replace-user-metadata) for full replacement.\n */\n publicMetadata?: UserPublicMetadata;\n /**\n * @deprecated Updating metadata via `updateUser()` is deprecated. Use [`updateUserMetadata()`](https://clerk.com/docs/reference/backend/user/update-user-metadata) for partial updates (deep merge) or [`replaceUserMetadata()`](https://clerk.com/docs/reference/backend/user/replace-user-metadata) for full replacement.\n */\n privateMetadata?: UserPrivateMetadata;\n /**\n * @deprecated Updating metadata via `updateUser()` is deprecated. Use [`updateUserMetadata()`](https://clerk.com/docs/reference/backend/user/update-user-metadata) for partial updates (deep merge) or [`replaceUserMetadata()`](https://clerk.com/docs/reference/backend/user/replace-user-metadata) for full replacement.\n */\n unsafeMetadata?: UserUnsafeMetadata;\n} & (UserPasswordHashingParams | object);\n\n/** @generateWithEmptyComment */\nexport type GetOrganizationMembershipListParams = ClerkPaginationRequest<{\n /** The ID of the user to get the list of Organization memberships for. */\n userId: string;\n}>;\n\n/** @generateWithEmptyComment */\nexport type GetOrganizationInvitationListParams = ClerkPaginationRequest<{\n /** The ID of the user to get the list of Organization invitations for. */\n userId: string;\n /** Filters the invitations by the provided status. */\n status?: OrganizationInvitationStatus;\n}>;\n\n/** @generateWithEmptyComment */\nexport type VerifyPasswordParams = {\n /** The ID of the user to verify the password for. */\n userId: string;\n /** The password to verify. */\n password: string;\n};\n\n/** @generateWithEmptyComment */\nexport type VerifyTOTPParams = {\n /** The ID of the user to verify the TOTP for. */\n userId: string;\n /** The TOTP or backup code to verify. */\n code: string;\n};\n\n/** @generateWithEmptyComment */\nexport type DeleteUserPasskeyParams = {\n /** The ID of the user to delete the passkey for. */\n userId: string;\n /** The ID of the passkey identification to delete. */\n passkeyIdentificationId: string;\n};\n\n/** @generateWithEmptyComment */\nexport type DeleteWeb3WalletParams = {\n /** The ID of the user to delete the Web3 wallet for. */\n userId: string;\n /** The ID of the Web3 wallet identification to delete. */\n web3WalletIdentificationId: string;\n};\n\n/** @generateWithEmptyComment */\nexport type DeleteUserExternalAccountParams = {\n /** The ID of the user to delete the external account for. */\n userId: string;\n /** The ID of the external account to delete. */\n externalAccountId: string;\n};\n\n/** @inline */\nexport type SetPasswordCompromisedParams = {\n /** Whether to revoke all sessions of the user. Defaults to `false`. */\n revokeAllSessions?: boolean;\n};\n\ntype ReplaceUserEmailAddressParams = {\n /** The new email address. Must adhere to the RFC 5322 specification for email address format. */\n emailAddress: string;\n};\n\ntype ReplaceUserPhoneNumberParams = {\n /** The new phone number. Must adhere to the E.164 standard for phone number format. */\n phoneNumber: string;\n};\n\ntype UserID = {\n userId: string;\n};\n\n/** @generateWithEmptyComment */\nexport class UserAPI extends AbstractAPI {\n /**\n * Retrieves the list of users in your instance. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property that contains an array of [`User`](https://clerk.com/docs/reference/backend/types/backend-user) objects, and a `totalCount` property that indicates the total number of users in your instance.\n */\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 /**\n * Gets a [`User`](https://clerk.com/docs/reference/backend/types/backend-user) for the specified user ID.\n * @param userId - The ID of the user to retrieve.\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 /**\n * Creates a [`User`](https://clerk.com/docs/reference/backend/types/backend-user) in your instance.\n *\n * Your settings in the [Clerk Dashboard](https://dashboard.clerk.com) determine how you should setup your user model. Anything **Required** will need to be provided when creating a user. Trying to add a field that isn't enabled will result in an error.\n *\n * Any email address and phone number created using this method will be automatically verified.\n *\n * > [!CAUTION]\n * >\n * > This endpoint is [rate limited](/docs/guides/how-clerk-works/system-limits). For development instances, a rate limit rule of **100 requests per 10 seconds** is applied.\n * > For production instances, that limit goes up to **1000 requests per 10 seconds**.\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 /** Updates the given [`User`](https://clerk.com/docs/reference/backend/types/backend-user).\n * @param userId - The ID of the user to update.\n * @param params - The user attributes to update.\n */\n public async updateUser(userId: string, params: UpdateUserParams = {}) {\n this.requireId(userId);\n\n const { publicMetadata, privateMetadata, unsafeMetadata, ...rest } = params as UpdateUserParams &\n UserMetadataParams;\n const hasMetadata = publicMetadata !== undefined || privateMetadata !== undefined || unsafeMetadata !== undefined;\n const hasRest = Object.keys(rest).length > 0;\n\n if (hasMetadata) {\n deprecated(\n 'updateUser(userId, { publicMetadata | privateMetadata | unsafeMetadata })',\n 'Use updateUserMetadata for partial updates (merge) or replaceUserMetadata for full replacement.',\n );\n }\n\n if (!hasMetadata) {\n return this.request<User>({\n method: 'PATCH',\n path: joinPaths(basePath, userId),\n bodyParams: rest,\n });\n }\n\n if (hasRest) {\n await this.request<User>({\n method: 'PATCH',\n path: joinPaths(basePath, userId),\n bodyParams: rest,\n });\n }\n\n return this.request<User>({\n method: 'PUT',\n path: joinPaths(basePath, userId, 'metadata'),\n bodyParams: { publicMetadata, privateMetadata, unsafeMetadata },\n });\n }\n\n public async replaceUserEmailAddress(userId: string, params: ReplaceUserEmailAddressParams) {\n this.requireId(userId);\n\n return this.request<EmailAddress>({\n method: 'PUT',\n path: joinPaths(basePath, userId, 'email_address'),\n bodyParams: params,\n });\n }\n\n public async replaceUserPhoneNumber(userId: string, params: ReplaceUserPhoneNumberParams) {\n this.requireId(userId);\n\n return this.request<PhoneNumber>({\n method: 'PUT',\n path: joinPaths(basePath, userId, 'phone_number'),\n bodyParams: params,\n });\n }\n\n /**\n * Updates the profile image for the given user. To remove the profile image, see [`deleteUserProfileImage()`](https://clerk.com/docs/reference/backend/user/delete-user-profile-image).\n * @param userId - The ID of the user to update the profile image for.\n * @param params - The file to set as the user's profile image.\n * @returns The updated [`User`](https://clerk.com/docs/reference/backend/types/backend-user).\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 /**\n * Updates the metadata for the given user, by merging existing values with the provided parameters.\n *\n * A \"deep\" merge will be performed - \"deep\" means that any nested JSON objects will be merged as well. You can remove metadata keys at any level by setting their value to `null`.\n *\n * > [!TIP]\n * > If you want to fully replace the existing metadata instead of merging, use [`replaceUserMetadata()`](/docs/reference/backend/user/replace-user-metadata).\n * @param userId - The ID of the user to update.\n * @param params - The metadata to update.\n * @returns The updated [`User`](https://clerk.com/docs/reference/backend/types/backend-user).\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 /**\n * Replaces the metadata associated with the specified user. Unlike [`updateUserMetadata()`](/docs/reference/backend/user/update-user-metadata), which deep-merges into the existing metadata, this method uses replace semantics: when a metadata field is provided, its previous value is overwritten in full with no merging at any level.\n *\n * The distinction is at two layers:\n * - **Top-level field omission preserves the existing value.** Each top-level field (`publicMetadata`, `privateMetadata`, `unsafeMetadata`) is handled independently. If you don't include a field in the request, the stored value for that field is left untouched.\n * - **The value inside a provided field is replaced in full.** When you do include a field, its previous content is discarded — any nested keys present before but absent in the new value are dropped. There is no merge.\n *\n * For the provided field, you can also send:\n * - `{}` (empty object) to clear the field.\n * - `null` to overwrite the field with a JSON `null` value. Prefer `{}` unless you specifically need a stored `null`.\n * @param userId - The ID of the user to replace the metadata for.\n * @param params - The metadata to replace.\n * @returns The updated [`User`](https://clerk.com/docs/reference/backend/types/backend-user).\n */\n public async replaceUserMetadata(userId: string, params: UserMetadataParams) {\n this.requireId(userId);\n\n return this.request<User>({\n method: 'PUT',\n path: joinPaths(basePath, userId, 'metadata'),\n bodyParams: params,\n });\n }\n\n /**\n * Deletes the given [`User`](https://clerk.com/docs/reference/backend/types/backend-user).\n * @param userId - The ID of the user to delete.\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 /**\n * Gets the total number of users in your instance.\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 /**\n * Gets the corresponding [OAuth access token](!oauth-access-token) for a user that has previously authenticated with the given OAuth provider.\n * @param userId - The ID of the user to get the OAuth access tokens for.\n * @param provider - The OAuth provider to get the access tokens for. If using a custom OAuth provider, prefix the provider name with `custom_` (e.g. `oauth_custom_google`).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property that contains an array of [`OauthAccessToken`](https://clerk.com/docs/reference/backend/types/backend-oauth-access-token) objects, and a `totalCount` property that indicates the total number of OAuth access tokens for the specified user and provider.\n */\n public async getUserOauthAccessToken(\n userId: string,\n provider: OAuthProvider,\n ): Promise<PaginatedResourceResponse<OauthAccessToken[]>>;\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(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 /**\n * Disable all of a user's MFA methods (e.g. [OTP](!otp) sent via SMS, TOTP on their authenticator app) at once.\n * @param userId - The ID of the user to disable MFA for.\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 /**\n * Gets a list of the given user's Organization memberships. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property that contains an array of [`OrganizationMembership`](https://clerk.com/docs/reference/backend/types/backend-organization-membership) objects, and a `totalCount` property that indicates the total number of Organization memberships for the user.\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 /**\n * Gets a list of the given user's Organization invitations. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property that contains an array of [`OrganizationInvitation`](https://clerk.com/docs/reference/backend/types/backend-organization-invitation) objects, and a `totalCount` property that indicates the total number of Organization invitations for the user.\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 /** Check that the user's password matches the supplied input. Useful for custom auth flows and re-verification. */\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 /** Verify that the provided TOTP or backup code is valid for the user. Verifying a backup code will result it in being consumed (i.e. it will become invalid). Useful for custom auth flows and re-verification. */\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 /**\n * Marks the given [`User`](https://clerk.com/docs/reference/backend/types/backend-user) as banned, which means that all their sessions are revoked and they are not allowed to sign in again.\n * @param userId - The ID of the user to ban.\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 /**\n * Removes the ban mark from the given [`User`](https://clerk.com/docs/reference/backend/types/backend-user), allowing them to sign in again.\n * @param userId - The ID of the user to unban.\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 /**\n * Locks the given [`User`](https://clerk.com/docs/reference/backend/types/backend-user), which means that they are not allowed to sign in again until the lock expires or is manually unlocked. By default, lockout duration is 1 hour, but it can be configured in the application's [**Attack protection**](https://dashboard.clerk.com/~/protect/attack-protection) settings. See the [guide on user locks](https://clerk.com/docs/guides/secure/user-lockout).\n * @param userId - The ID of the user to lock.\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 /** Removes a sign-in lock from the given [`User`](https://clerk.com/docs/reference/backend/types/backend-user), allowing them to sign in again. See the [guide on user locks](https://clerk.com/docs/guides/secure/user-lockout).\n * @param userId - The ID of the user to unlock.\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 /**\n * Deletes a user's profile image.\n * @param userId - The ID of the user to delete the profile image for.\n * @returns The updated [`User`](https://clerk.com/docs/reference/backend/types/backend-user).\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 /**\n * Deletes the passkey identification for a given user and notifies them through email.\n * @returns The [`DeletedObject`](https://clerk.com/docs/reference/backend/types/deleted-object) object.\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 /**\n * Deletes a Web3 wallet identification for the given user.\n * @returns The [`DeletedObject`](https://clerk.com/docs/reference/backend/types/deleted-object) object.\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 /**\n * Deletes an external account for the given user.\n * @returns The [`DeletedObject`](https://clerk.com/docs/reference/backend/types/deleted-object) object.\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 /**\n * Deletes all backup codes for the given user.\n * @param userId - The ID of the user to delete backup codes for.\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 /**\n * Deletes all of the TOTP secrets for the given user.\n * @param userId - The ID of the user to delete the TOTP secrets for.\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 /**\n * Sets the given user's password as compromised. The user will be prompted to reset their password on their next sign-in. See the [guide on password protection and rules](/docs/guides/secure/password-protection-and-rules#reject-compromised-passwords) for more information.\n * @param userId - The ID of the user to set the password as compromised for.\n * @param params - Other parameters for the request.\n * @returns The updated [`User`](https://clerk.com/docs/reference/backend/types/backend-user).\n */\n public async setPasswordCompromised(\n userId: string,\n params: SetPasswordCompromisedParams = {\n revokeAllSessions: false,\n },\n ) {\n this.requireId(userId);\n return this.request<User>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'password', 'set_compromised'),\n bodyParams: params,\n });\n }\n\n /**\n * Unsets the given user's password as compromised. The user will no longer be prompted to reset their password on their next sign-in. See the [guide on password protection and rules](/docs/guides/secure/password-protection-and-rules#reject-compromised-passwords) for more information.\n * @param userId - The ID of the user to unset the password as compromised for.\n * @returns The updated [`User`](https://clerk.com/docs/reference/backend/types/backend-user).\n */\n public async unsetPasswordCompromised(userId: string) {\n this.requireId(userId);\n return this.request<User>({\n method: 'POST',\n path: joinPaths(basePath, userId, 'password', 'unset_compromised'),\n });\n }\n}\n","import type { ClerkPaginationRequest } from '@clerk/shared/types';\n\nimport { joinPaths } from '../../util/path';\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\n/** @generateWithEmptyComment */\nexport type WaitlistEntryListParams = ClerkPaginationRequest<{\n /** Filters waitlist entries by `email_address` or `id`. */\n query?: string;\n /** Filters waitlist entries by status. */\n status?: WaitlistEntryStatus;\n /** Filters waitlist entries in a particular order. Prefix a value with `+` to sort in ascending order, or `-` to sort in descending order. Defaults to `-created_at`. */\n orderBy?: WithSign<'created_at' | 'invited_at' | 'email_address'>;\n}>;\n\n/** @generateWithEmptyComment */\nexport type WaitlistEntryCreateParams = {\n /** The email address to add to the waitlist. */\n emailAddress: string;\n /** Whether to notify the user that their email address has been added to the waitlist. Notifies the user if the `emailAddress` is an email address. Defaults to `true`. */\n notify?: boolean;\n};\n\n/** @generateWithEmptyComment */\nexport type WaitlistEntryBulkCreateParams = Array<WaitlistEntryCreateParams>;\n\n/** @inline */\nexport type WaitlistEntryInviteParams = {\n /** Whether to ignore an existing invitation. Defaults to `false`. */\n ignoreExisting?: boolean;\n};\n\n/** @generateWithEmptyComment */\nexport class WaitlistEntryAPI extends AbstractAPI {\n /**\n * Gets a list of waitlist entries for the instance. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`WaitlistEntry`](https://clerk.com/docs/reference/backend/types/backend-waitlist-entry) objects and a `totalCount` property containing the total number of waitlist entries for the instance.\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 for the given email address. If the email address is already on the waitlist, no new entry will be created and the existing waitlist entry will be returned.\n * @returns The created or existing [`WaitlistEntry`](https://clerk.com/docs/reference/backend/types/backend-waitlist-entry) object.\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 * Creates multiple waitlist entries for the given email addresses. If an email address is already on the waitlist, no new entry will be created and the existing waitlist entry will be returned.\n * @returns An array of created or existing [`WaitlistEntry`](https://clerk.com/docs/reference/backend/types/backend-waitlist-entry) objects.\n */\n public async createBulk(params: WaitlistEntryBulkCreateParams) {\n return this.request<WaitlistEntry[]>({\n method: 'POST',\n path: joinPaths(basePath, 'bulk'),\n bodyParams: params,\n });\n }\n\n /**\n * Invites the given waitlist entry.\n * @param id - The waitlist entry ID.\n * @param params - Optional parameters for inviting the waitlist entry.\n * @returns The invited [`WaitlistEntry`](https://clerk.com/docs/reference/backend/types/backend-waitlist-entry) object.\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 * Rejects the given waitlist entry.\n * @param id - The ID of the waitlist entry to reject.\n * @returns The rejected [`WaitlistEntry`](https://clerk.com/docs/reference/backend/types/backend-waitlist-entry) object.\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 * Deletes the given pending waitlist entry.\n * @param id - The ID of the waitlist entry to delete.\n * @returns The [`DeletedObject`](https://clerk.com/docs/reference/backend/types/deleted-object) object.\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\n/** @generateWithEmptyComment */\nexport type GetPlanListParams = ClerkPaginationRequest<{\n /**\n * Filters plans by the type of payer.\n */\n payerType: 'org' | 'user';\n}>;\n\n/** @inline */\nexport type CancelSubscriptionItemParams = {\n /**\n * Whether the Subscription Item should be canceled immediately. If `false`, the Subscription Item will be canceled at the end of the current billing period.\n */\n endNow?: boolean;\n};\n\n/** @inline */\nexport type ExtendSubscriptionItemFreeTrialParams = {\n /**\n * The date to extend the free trial to. Must be in the future and not more than 365 days from the current trial end date.\n */\n extendTo: Date;\n};\n\n/** @generateWithEmptyComment */\nexport class BillingAPI extends AbstractAPI {\n /**\n * Gets the list of Billing Plans for the instance. By default, the list is returned in descending order by creation date (newest first).\n * @returns A [`PaginatedResourceResponse`](https://clerk.com/docs/reference/backend/types/paginated-resource-response) object with a `data` property containing an array of [`BillingPlan`](https://clerk.com/docs/reference/backend/types/billing-plan) objects and a `totalCount` property containing the total number of Billing Plans for the instance.\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?: GetPlanListParams) {\n return this.request<PaginatedResourceResponse<BillingPlan[]>>({\n method: 'GET',\n path: joinPaths(basePath, 'plans'),\n queryParams: params,\n });\n }\n\n /**\n * Cancels the given Subscription Item.\n * @param subscriptionItemId - The ID of the Subscription Item to cancel.\n * @param params - The parameters for the request.\n * @returns The cancelled [`BillingSubscriptionItem`](https://clerk.com/docs/reference/backend/types/billing-subscription-item) object.\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 * Extends the free trial for the given Subscription Item.\n * @param subscriptionItemId - The ID of the Subscription Item to extend the free trial for.\n * @param params - The parameters for the request.\n * @returns The updated [`BillingSubscriptionItem`](https://clerk.com/docs/reference/backend/types/billing-subscription-item) object.\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 * Gets the [`BillingSubscription`](https://clerk.com/docs/reference/backend/types/billing-subscription) for the given Organization.\n * @param organizationId - The ID of the Organization to get the Billing Subscription for.\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 * Gets the [`BillingSubscription`](https://clerk.com/docs/reference/backend/types/billing-subscription) for the given User.\n * @param userId - The ID of the User to get the Billing Subscription for.\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 if (res.status === 204) {\n return {\n data: undefined as T,\n errors: null,\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 { AgentTaskJSON } from './JSON';\n\n/**\n * The Backend `AgentTask` object represents an Agent Task resource. Agent Tasks are used for testing purposes and allow creating sessions for users without requiring full authentication flows.\n */\nexport class AgentTask {\n constructor(\n /** The identifier for the agent, unique per `agent_name` within an instance. */\n readonly agentId: string,\n /** @deprecated Use `agentTaskId` instead. */\n readonly taskId: string,\n /** The unique identifier for this Agent Task. */\n readonly agentTaskId: string,\n /** The Frontend API URL that, when visited, creates a session for the user. Only returned by [`create()`](https://clerk.com/docs/reference/backend/agent-tasks/create); omitted from [`revoke()`](https://clerk.com/docs/reference/backend/agent-tasks/revoke). */\n readonly url: string,\n ) {}\n\n /**\n * Creates an AgentTask instance from a JSON object.\n *\n * @param data - The JSON object containing Agent Task data\n * @returns A new AgentTask instance\n */\n static fromJSON(data: AgentTaskJSON): AgentTask {\n const agentTaskId = data.agent_task_id ?? data.task_id ?? '';\n return new AgentTask(data.agent_id, agentTaskId, agentTaskId, data.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/model/AllowlistIdentifier){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class AllowlistIdentifier {\n constructor(\n /**\n * The unique identifier for the allowlist identifier.\n */\n readonly id: string,\n /** The identifier that was added to the allowlist. */\n readonly identifier: string,\n /** The type of the allowlist identifier. */\n readonly identifierType: AllowlistIdentifierType,\n /** The Unix timestamp when the allowlist identifier was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the allowlist identifier was last updated. */\n readonly updatedAt: number,\n /** The ID of the instance that this allowlist identifier belongs to. */\n readonly instanceId?: string,\n /** The ID of the invitation sent to the identifier. */\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\n/**\n * The Backend `APIKey` object holds information about an API key.\n */\nexport class APIKey {\n constructor(\n /** The unique identifier for the API key. */\n readonly id: string,\n /** The type of the API key. Currently always `'api_key'`. */\n readonly type: string,\n /** The API key's name. */\n readonly name: string,\n /** The user or organization ID that the API key is associated with. */\n readonly subject: string,\n /** An array of scopes that define what the API key can access. */\n readonly scopes: string[],\n /** Custom claims associated with the API key. */\n readonly claims: Record<string, any> | null,\n /** Whether the API key has been revoked. */\n readonly revoked: boolean,\n /** The reason for revoking the API key, if it has been revoked. */\n readonly revocationReason: string | null,\n /** Whether the API key has expired. */\n readonly expired: boolean,\n /** The Unix timestamp (in milliseconds) when the API key expires. `null` if the API key never expires. */\n readonly expiration: number | null,\n /** The user ID for the user creating the API key. */\n readonly createdBy: string | null,\n /** A description for the API key. */\n readonly description: string | null,\n /** The Unix timestamp (in milliseconds) when the API key was last used to authenticate a request. */\n readonly lastUsedAt: number | null,\n /** The Unix timestamp (in milliseconds) when the API key was created. */\n readonly createdAt: number,\n /** The Unix timestamp (in milliseconds) when the API key was last updated. */\n readonly updatedAt: number,\n /** The API key secret. */\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 /** The unique identifier for the session activity record. */\n readonly id: string,\n /** Whether the session activity came from a mobile device. */\n readonly isMobile: boolean,\n /** The IP address from which this session activity originated. */\n readonly ipAddress?: string,\n /** The city from which this session activity occurred. Resolved by IP address geo-location. */\n readonly city?: string,\n /** The country from which this session activity occurred. Resolved by IP address geo-location. */\n readonly country?: string,\n /** The version of the browser from which this session activity occurred. */\n readonly browserVersion?: string,\n /** The name of the browser from which this session activity occurred. */\n readonly browserName?: string,\n /** The type of the device which was used in this session activity. */\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/objects/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/model/Session){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class Session {\n constructor(\n /** The unique identifier for the `Session`. */\n readonly id: string,\n /** The ID of the client associated with the `Session`. */\n readonly clientId: string,\n /** The ID of the user associated with the `Session`. */\n readonly userId: string,\n /** The current state of the `Session`. */\n readonly status: string,\n /** The time the session was last active on the [`Client`](https://clerk.com/docs/reference/backend/types/backend-client). */\n readonly lastActiveAt: number,\n /** The Unix timestamp when the `Session` will expire. */\n readonly expireAt: number,\n /** The Unix timestamp when the `Session` will be abandoned. */\n readonly abandonAt: number,\n /** The Unix timestamp when the `Session` was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the `Session` was last updated. */\n readonly updatedAt: number,\n /** The ID of the last [Active Organization](!active-organization). */\n readonly lastActiveOrganizationId?: string,\n /** An object that provides additional information about this session, focused around user activity data. */\n readonly latestActivity?: SessionActivity,\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 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/objects/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/model/Client){{ target: '_blank' }} and is not directly accessible from the Frontend API.\n */\nexport class Client {\n constructor(\n /** The unique identifier for the `Client`. */\n readonly id: string,\n /** An array of [Session](https://clerk.com/docs/reference/backend/types/backend-session) IDs associated with the `Client`. */\n readonly sessionIds: string[],\n /** An array of [`Session`](https://clerk.com/docs/reference/backend/types/backend-session) objects associated with the `Client`. */\n readonly sessions: Session[],\n /** The ID of the associated [`SignIn`](https://clerk.com/docs/reference/objects/sign-in). */\n readonly signInId: string | null,\n /** The ID of the associated [`SignUp`](https://clerk.com/docs/reference/objects/sign-up). */\n readonly signUpId: string | null,\n /** The ID of the last active [`Session`](https://clerk.com/docs/reference/backend/types/backend-session). */\n readonly lastActiveSessionId: string | null,\n /** The last authentication strategy used by the `Client`. */\n readonly lastAuthenticationStrategy: LastAuthenticationStrategy | null,\n /** The Unix timestamp when the `Client` was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the `Client` was last updated. */\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\n/**\n * The `DeletedObject` object represents an item that has been deleted from the database. It is used to represent the result of a delete operation.\n */\nexport class DeletedObject {\n constructor(\n /** The type of object that has been deleted. */\n readonly object: string,\n /** The unique identifier for the deleted object. */\n readonly id: string | null,\n /** The URL-friendly identifier for the deleted object. */\n readonly slug: string | null,\n /** Whether the object has been deleted. */\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\n/** The `Domain` object represents a domain that is managed by the instance. */\nexport class Domain {\n constructor(\n /** The unique identifier of the domain. */\n readonly id: string,\n /** The name of the domain. */\n readonly name: string,\n /** Whether the domain is a satellite domain. */\n readonly isSatellite: boolean,\n /** The Frontend API URL for the domain. */\n readonly frontendApiUrl: string,\n /** The development origin for the domain. */\n readonly developmentOrigin: string,\n /** The CNAME targets for the domain. */\n readonly cnameTargets: CnameTarget[],\n /** The [Account Portal](https://clerk.com/docs/guides/account-portal/overview) URL for the domain. */\n readonly accountsPortalUrl?: string | null,\n /** The [proxy URL](https://clerk.com/docs/guides/dashboard/dns-domains/proxy-fapi) for the domain. */\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 readonly userId?: string | null,\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 data.user_id,\n );\n }\n}\n","import type { IdentificationLinkJSON } from './JSON';\n\n/**\n * The `IdentificationLink` object contains information about any identifications that might be linked to the identifier (email address, phone number, etc.).\n */\nexport class IdentificationLink {\n constructor(\n /** The unique identifier for the identification link. */\n readonly id: string,\n /** The type of the identification link, e.g., `\"email_address\"`, `\"phone_number\"`, etc. */\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 /** The strategy pertaining to the parent sign-up or sign-in attempt. */\n readonly strategy: string,\n /** The redirect URL for an external verification. */\n readonly externalVerificationRedirectURL: URL | null = null,\n /** The number of attempts related to the verification. */\n readonly attempts: number | null = null,\n /** The Unix timestamp when the verification will expire. */\n readonly expireAt: number | null = null,\n /** The [nonce](https://en.wikipedia.org/wiki/Cryptographic_nonce) pertaining to the verification. */\n readonly nonce: string | null = null,\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 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\n/** @inline */\nexport class OrganizationDomainVerification {\n constructor(\n /** The current status of the verification. */\n readonly status: string,\n /** The strategy used to verify the domain. */\n readonly strategy: string,\n /** The number of verification attempts that have been made. */\n readonly attempts: number | null = null,\n /** The Unix timestamp when the current verification attempt expires. */\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 /** The unique identifier for the email address. */\n readonly id: string,\n /** The value of the email address. */\n readonly emailAddress: string,\n /** An object holding information on the verification of the email address. */\n readonly verification: Verification | null,\n /** An array of objects containing information about any identifications that might be linked to the email address. */\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 /** The unique identifier for the Feature. */\n readonly id: string,\n /** The name of the Feature. */\n readonly name: string,\n /** The description of the Feature. */\n readonly description: string | null,\n /** The URL-friendly identifier of the Feature. */\n readonly slug: string,\n /** The URL of the Feature's avatar image. */\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`](https://clerk.com/docs/reference/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/billing/GET/billing/plans){{ target: '_blank' }} 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 /** The unique identifier for the Plan. */\n readonly id: string,\n /** The name of the Plan. */\n readonly name: string,\n /** The URL-friendly identifier of the Plan. */\n readonly slug: string,\n /** The description of the Plan. */\n readonly description: string | null,\n /** Whether the Plan is the default Plan. */\n readonly isDefault: boolean,\n /** Whether the Plan is recurring. */\n readonly isRecurring: boolean,\n /** Whether the Plan has a base fee. */\n readonly hasBaseFee: boolean,\n /** Whether the Plan is displayed in the [`<PricingTable />`](https://clerk.com/docs/nextjs/reference/components/billing/pricing-table) component. */\n readonly publiclyVisible: boolean,\n /** The monthly fee of the Plan. */\n readonly fee: BillingMoneyAmount | null,\n /** The annual fee of the Plan. */\n readonly annualFee: BillingMoneyAmount | null,\n /** The annual fee of the Plan on a monthly basis. */\n readonly annualMonthlyFee: BillingMoneyAmount | null,\n /** The type of payer for the Plan. */\n readonly forPayerType: 'org' | 'user',\n /** The [Features](https://clerk.com/docs/reference/backend/types/feature) the Plan offers. */\n readonly features: Feature[],\n /** The URL of the Plan's avatar image. */\n readonly avatarUrl: string | null,\n /** The number of free trial days for this plan. */\n readonly freeTrialDays: number | null,\n /** Whether free trial is enabled for this plan. */\n readonly freeTrialEnabled: boolean,\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\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 data.avatar_url,\n data.free_trial_days,\n data.free_trial_enabled,\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`](https://clerk.com/docs/reference/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/billing/GET/billing/subscription_items){{ target: '_blank' }} 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 /** The unique identifier for the Subscription Item. */\n readonly id: string,\n /** The status of the Subscription Item. */\n readonly status: BillingSubscriptionItemJSON['status'],\n /** The period of the Plan associated with this Subscription Item. */\n readonly planPeriod: 'month' | 'annual',\n /** The Unix timestamp (milliseconds) of when the current period starts. */\n readonly periodStart: number,\n /** Information about the next scheduled payment for this Subscription Item. */\n readonly nextPayment:\n | {\n /** The amount of the next payment. */\n amount: number;\n /** The Unix timestamp (milliseconds) of when the next payment is scheduled. */\n date: number;\n }\n | null\n | undefined,\n /** The current amount for the Subscription Item. */\n readonly amount: BillingMoneyAmount | undefined,\n /** The Plan associated with this Subscription Item. */\n readonly plan: BillingPlan | null,\n /** The ID of the Plan associated with this Subscription Item. */\n readonly planId: string | null,\n /** The Unix timestamp (milliseconds) of when the Subscription Item was created. */\n readonly createdAt: number,\n /** The Unix timestamp (milliseconds) of when the Subscription Item was last updated. */\n readonly updatedAt: number,\n /** The Unix timestamp (milliseconds) of when the current period ends. */\n readonly periodEnd: number | null,\n /** The Unix timestamp (milliseconds) of when the Subscription Item was canceled. */\n readonly canceledAt: number | null,\n /** The Unix timestamp (milliseconds) of when the Subscription Item became past due. */\n readonly pastDueAt: number | null,\n /** The Unix timestamp (milliseconds) of when the Subscription Item ended. */\n readonly endedAt: number | null,\n /** The ID of the payer for this Subscription Item. */\n readonly payerId: string | undefined,\n /** Whether this Subscription Item is currently in a free trial period. */\n readonly isFreeTrial?: boolean,\n /** The lifetime amount paid for this Subscription Item. */\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`](https://clerk.com/docs/reference/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){{ target: '_blank' }} 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 /** The unique identifier for the Subscription. */\n readonly id: string,\n /** The current status of the Subscription. */\n readonly status: BillingSubscriptionJSON['status'],\n /** The ID of the payer for this Subscription. */\n readonly payerId: string,\n /** The Unix timestamp (milliseconds) of when the Subscription was created. */\n readonly createdAt: number,\n /** The Unix timestamp (milliseconds) of when the Subscription was last updated. */\n readonly updatedAt: number,\n /** The Unix timestamp (milliseconds) of when the Subscription became active. */\n readonly activeAt: number | null,\n /** The Unix timestamp (milliseconds) of when the Subscription became past due. */\n readonly pastDueAt: number | null,\n /** All of the Subscription Items in this Subscription. */\n readonly subscriptionItems: BillingSubscriptionItem[],\n /** Information about the next scheduled payment for this Subscription. */\n readonly nextPayment: {\n /** The Unix timestamp (milliseconds) of when the next payment is scheduled. */\n date: number;\n /** The amount of the next payment. */\n amount: BillingMoneyAmount;\n } | null,\n /** Whether the payer is eligible for a free trial. */\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 { EnterpriseAccountConnectionJSON, EnterpriseAccountJSON } from './JSON';\nimport { Verification } from './Verification';\n\n/**\n * The Backend `EnterpriseAccountConnection` object represents an enterprise SSO connection associated with an enterprise account.\n */\nexport class EnterpriseAccountConnection {\n constructor(\n /** The unique identifier for this enterprise connection. */\n readonly id: string,\n /** Whether the connection is currently active. */\n readonly active: boolean,\n /** Whether IdP-initiated SSO is allowed. */\n readonly allowIdpInitiated: boolean,\n /** Whether subdomains are allowed for this connection. */\n readonly allowSubdomains: boolean,\n /** Whether additional identifications are disabled for users authenticating via this connection. */\n readonly disableAdditionalIdentifications: boolean,\n /** The domain associated with this connection. */\n readonly domain: string,\n /** The public URL of the connection's logo, if available. */\n readonly logoPublicUrl: string | null,\n /** The name of the enterprise connection. */\n readonly name: string,\n /** The SSO protocol used (e.g., `saml` or `oauth`). */\n readonly protocol: string,\n /** The SSO provider (e.g., `saml_custom`, `saml_okta`). */\n readonly provider: string,\n /** Whether user attributes are synced from the IdP. */\n readonly syncUserAttributes: boolean,\n /** The Unix timestamp when this connection was created. */\n readonly createdAt: number,\n /** The Unix timestamp when this connection was last updated. */\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: EnterpriseAccountConnectionJSON): EnterpriseAccountConnection {\n return new EnterpriseAccountConnection(\n data.id,\n data.active,\n data.allow_idp_initiated,\n data.allow_subdomains,\n data.disable_additional_identifications,\n data.domain,\n data.logo_public_url,\n data.name,\n data.protocol,\n data.provider,\n data.sync_user_attributes,\n data.created_at,\n data.updated_at,\n );\n }\n}\n\n/**\n * The Backend `EnterpriseAccount` object represents an identification obtained via enterprise SSO (SAML or OIDC).\n */\nexport class EnterpriseAccount {\n constructor(\n /**\n * The unique identifier for this enterprise account.\n */\n readonly id: string,\n /**\n * Whether this enterprise account is currently active.\n */\n readonly active: boolean,\n /**\n * The email address associated with this enterprise account.\n */\n readonly emailAddress: string,\n /**\n * The enterprise connection through which this account was authenticated.\n */\n readonly enterpriseConnection: EnterpriseAccountConnection | null,\n /**\n * The user's first name as provided by the IdP.\n */\n readonly firstName: string | null,\n /**\n * The user's last name as provided by the IdP.\n */\n readonly lastName: string | null,\n /**\n * The SSO protocol used (e.g., `saml` or `oauth`).\n */\n readonly protocol: string,\n /**\n * The SSO provider (e.g., `saml_custom`, `saml_okta`).\n */\n readonly provider: string,\n /**\n * The unique ID of the user in the provider.\n */\n readonly providerUserId: 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>,\n /**\n * An object holding information on the verification of this enterprise account.\n */\n readonly verification: Verification | null,\n /**\n * The date when the user last authenticated via this enterprise account.\n */\n readonly lastAuthenticatedAt: number | null,\n /**\n * The ID of the enterprise connection associated with this account.\n */\n readonly enterpriseConnectionId: string | null,\n ) {}\n\n static fromJSON(data: EnterpriseAccountJSON): EnterpriseAccount {\n return new EnterpriseAccount(\n data.id,\n data.active,\n data.email_address,\n data.enterprise_connection && EnterpriseAccountConnection.fromJSON(data.enterprise_connection),\n data.first_name,\n data.last_name,\n data.protocol,\n data.provider,\n data.provider_user_id,\n data.public_metadata,\n data.verification && Verification.fromJSON(data.verification),\n data.last_authenticated_at,\n data.enterprise_connection_id,\n );\n }\n}\n","import type {\n EnterpriseConnectionJSON,\n EnterpriseConnectionOauthConfigJSON,\n EnterpriseConnectionSamlConnectionJSON,\n} from './JSON';\n\n/**\n * The Backend `EnterpriseConnectionSamlConnection` object holds information about a SAML enterprise connection for an instance or organization.\n */\nexport class EnterpriseConnectionSamlConnection {\n constructor(\n /** The unique identifier for the SAML connection. */\n readonly id: string,\n /** The name to use as a label for the connection. */\n readonly name: string,\n /** The Entity ID as provided by the Identity Provider (IdP). */\n readonly idpEntityId: string,\n /** The Single-Sign On URL as provided by the Identity Provider (IdP). */\n readonly idpSsoUrl: string,\n /** The X.509 certificate as provided by the Identity Provider (IdP). */\n readonly idpCertificate: string,\n /** The Unix timestamp when the Identity Provider (IdP) certificate was issued. */\n readonly idpCertificateIssuedAt: number,\n /** The Unix timestamp when the Identity Provider (IdP) certificate expires. */\n readonly idpCertificateExpiresAt: number,\n /** The URL which serves the Identity Provider (IdP) metadata. */\n readonly idpMetadataUrl: string,\n /** The XML content of the Identity Provider (IdP) metadata file. */\n readonly idpMetadata: string,\n /** The Assertion Consumer Service (ACS) URL of the connection. */\n readonly acsUrl: string,\n /** The Entity ID as provided by the Service Provider (Clerk). */\n readonly spEntityId: string,\n /** The metadata URL as provided by the Service Provider (Clerk). */\n readonly spMetadataUrl: string,\n /** Whether the connection syncs user attributes between the IdP and Clerk. */\n readonly syncUserAttributes: boolean,\n /** Whether users with an email address subdomain are allowed to use this connection. */\n readonly allowSubdomains: boolean,\n /** Whether IdP-initiated SSO is allowed. */\n readonly allowIdpInitiated: boolean,\n ) {}\n\n static fromJSON(data: EnterpriseConnectionSamlConnectionJSON): EnterpriseConnectionSamlConnection {\n return new EnterpriseConnectionSamlConnection(\n data.id,\n data.name,\n data.idp_entity_id,\n data.idp_sso_url,\n data.idp_certificate,\n data.idp_certificate_issued_at,\n data.idp_certificate_expires_at,\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.sync_user_attributes,\n data.allow_subdomains,\n data.allow_idp_initiated,\n );\n }\n}\n\n/**\n * OAuth configuration included on a Backend API {@link EnterpriseConnection} response.\n */\nexport class EnterpriseConnectionOauthConfig {\n constructor(\n /**\n * The unique identifier for the OAuth configuration.\n */\n readonly id: string,\n /**\n * The name to use as a label for the configuration.\n */\n readonly name: string,\n /**\n * The OAuth client ID.\n */\n readonly clientId: string,\n /**\n * The OpenID Connect discovery URL.\n */\n readonly discoveryUrl: string,\n /**\n * The public URL of the OAuth provider logo, if available.\n */\n readonly logoPublicUrl: string,\n /**\n * The date when the configuration was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the configuration was last updated.\n */\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: EnterpriseConnectionOauthConfigJSON): EnterpriseConnectionOauthConfig {\n return new EnterpriseConnectionOauthConfig(\n data.id,\n data.name,\n data.client_id,\n data.discovery_url,\n data.logo_public_url,\n data.created_at,\n data.updated_at,\n );\n }\n}\n\n/**\n * The Backend `EnterpriseConnection` object holds information about an enterprise connection (SAML or OAuth) for an instance or organization.\n */\nexport class EnterpriseConnection {\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 the enterprise. Sign-in flows using an email with this domain may use the connection.\n */\n readonly domains: Array<string>,\n /**\n * The Organization ID if the connection is scoped to an organization.\n */\n readonly organizationId: string | null,\n /**\n * Whether the connection is active or not.\n */\n readonly active: boolean,\n /**\n * Whether the connection syncs user attributes between the IdP and Clerk or not.\n */\n readonly syncUserAttributes: boolean,\n /**\n * Whether users with an email address subdomain are allowed to use this connection or not.\n */\n readonly allowSubdomains: boolean,\n /**\n * Whether additional identifications are disabled for this connection.\n */\n readonly disableAdditionalIdentifications: boolean,\n /**\n * The date when the connection was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the connection was last updated.\n */\n readonly updatedAt: number,\n /**\n * SAML connection details when the enterprise connection uses SAML.\n */\n readonly samlConnection: EnterpriseConnectionSamlConnection | null,\n /**\n * OAuth (OIDC) configuration when the enterprise connection uses OAuth.\n */\n readonly oauthConfig: EnterpriseConnectionOauthConfig | null,\n ) {}\n\n static fromJSON(data: EnterpriseConnectionJSON): EnterpriseConnection {\n return new EnterpriseConnection(\n data.id,\n data.name,\n data.domains,\n data.organization_id,\n data.active,\n data.sync_user_attributes,\n data.allow_subdomains,\n data.disable_additional_identifications,\n data.created_at,\n data.updated_at,\n data.saml_connection != null ? EnterpriseConnectionSamlConnection.fromJSON(data.saml_connection) : null,\n data.oauth_config != null ? EnterpriseConnectionOauthConfig.fromJSON(data.oauth_config) : null,\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 /** The unique identifier for this external account. */\n readonly id: string,\n /** The provider name (e.g., `google`). */\n readonly provider: string,\n /** The unique ID of the user in the provider. */\n readonly providerUserId: string,\n /** The identification with which this external account is associated. */\n readonly identificationId: string,\n /** @deprecated Use `identificationId` instead. */\n readonly externalId: string,\n /** The scopes that the user has granted access to. */\n readonly approvedScopes: string,\n /** The user's email address. */\n readonly emailAddress: string,\n /** The user's first name. */\n readonly firstName: string,\n /** The user's last name. */\n readonly lastName: string,\n /** The user's image URL. */\n readonly imageUrl: string,\n /** The user's username. */\n readonly username: string | null,\n /** The phone number related to this specific external account. */\n readonly phoneNumber: string | null,\n /** Metadata that can be read from the Frontend API and Backend API and can be set only from the [Backend API](https://clerk.com/docs/reference/backend-api). */\n readonly publicMetadata: Record<string, unknown> | null = {},\n /** A descriptive label to differentiate multiple external accounts of the same user for the same provider. */\n readonly label: string | null,\n /** An object holding information on the verification of this external account. */\n readonly verification: Verification | null,\n /**\n * The `eac_`-prefixed id of the external account resource, which is the id\n * `users.deleteUserExternalAccount()` expects. Only returned for Google and\n * Facebook accounts; for other providers it is `undefined` and `id` already\n * holds the `eac_` value. Use `externalAccountId ?? id` to get a deletable id.\n */\n readonly externalAccountId?: string,\n ) {}\n\n static fromJSON(data: ExternalAccountJSON): ExternalAccount {\n return new ExternalAccount(\n data.id,\n data.provider,\n data.provider_user_id,\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 data.external_account_id,\n );\n }\n}\n","import type { InstanceJSON } from './JSON';\n\n/** @generateWithEmptyComment */\nexport class Instance {\n constructor(\n /** The unique identifier for the instance. */\n readonly id: string,\n /** The type of instance environment, either `'production'` or `'development'`. */\n readonly environmentType: string,\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. 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.js, the origin is `capacitor://localhost`. */\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\n/** The `InstanceRestrictions` object represents the [restrictions](https://clerk.com/docs/guides/secure/restricting-access) settings for the current instance. */\nexport class InstanceRestrictions {\n constructor(\n /** Whether the instance has [**Allowlist**](https://clerk.com/docs/guides/secure/restricting-access#allowlist) enabled. */\n readonly allowlist: boolean,\n /** Whether the instance has [**Blocklist**](https://clerk.com/docs/guides/secure/restricting-access#blocklist) enabled. */\n readonly blocklist: boolean,\n /** Whether the instance has [**Block email subaddresses**](https://clerk.com/docs/guides/secure/restricting-access#block-email-subaddresses) enabled. */\n readonly blockEmailSubaddresses: boolean,\n /** Whether the instance has [**Block sign-ups that use disposable email domains**](https://clerk.com/docs/guides/secure/restricting-access#block-sign-ups-that-use-disposable-email-addresses) enabled. */\n readonly blockDisposableEmailDomains: boolean,\n /** Whether the instance has [**Ignore dots for Gmail addresses**](https://clerk.com/docs/guides/secure/restricting-access#block-email-subaddresses) enabled. */\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 /** The unique identifier for the `Invitation`. */\n readonly id: string,\n /** The email address that the invitation was sent to. */\n readonly emailAddress: string,\n /** [Metadata](https://clerk.com/docs/reference/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 readonly publicMetadata: Record<string, unknown> | null,\n /** The Unix timestamp when the `Invitation` was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the `Invitation` was last updated. */\n readonly updatedAt: number,\n /** The status of the `Invitation`. */\n readonly status: InvitationStatus,\n /** The URL that the user can use to accept the invitation. */\n readonly url?: string,\n /** Whether the `Invitation` has been revoked. */\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 AgentTask: 'agent_task',\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 EnterpriseAccount: 'enterprise_account',\n EnterpriseConnection: 'enterprise_connection',\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 RoleSet: 'role_set',\n RoleSetItem: 'role_set_item',\n RoleSetMigration: 'role_set_migration',\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 EnterpriseAccountConnectionJSON extends ClerkResourceJSON {\n active: boolean;\n allow_idp_initiated: boolean;\n allow_subdomains: boolean;\n disable_additional_identifications: boolean;\n domain: string;\n logo_public_url: string | null;\n name: string;\n protocol: string;\n provider: string;\n sync_user_attributes: boolean;\n created_at: number;\n updated_at: number;\n}\n\nexport interface EnterpriseAccountJSON extends ClerkResourceJSON {\n object: typeof ObjectType.EnterpriseAccount;\n active: boolean;\n email_address: string;\n enterprise_connection: EnterpriseAccountConnectionJSON | null;\n first_name: string | null;\n last_name: string | null;\n protocol: string;\n provider: string;\n provider_user_id: string | null;\n public_metadata: Record<string, unknown>;\n verification: VerificationJSON | null;\n last_authenticated_at: number | null;\n enterprise_connection_id: string | null;\n}\n\nexport interface ExternalAccountJSON extends ClerkResourceJSON {\n object: typeof ObjectType.ExternalAccount;\n /**\n * The `eac_`-prefixed external account id. Only present for Google and Facebook accounts.\n */\n external_account_id?: string;\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 // Only present for OIDC-compliant OAuth 2.0 providers when available\n id_token?: string;\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 last_active_at?: number;\n missing_member_with_elevated_permissions?: boolean;\n role_set_key?: string | null;\n}\n\nexport interface RoleSetItemJSON {\n object: typeof ObjectType.RoleSetItem;\n id: string;\n name: string;\n key: string;\n description: string | null;\n members_count?: number | null;\n has_members?: boolean | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface RoleSetMigrationJSON {\n object: typeof ObjectType.RoleSetMigration;\n id: string;\n organization_id: string | null;\n instance_id: string;\n source_role_set_id: string;\n dest_role_set_id: string | null;\n trigger_type: string;\n status: string;\n migrated_members: number;\n mappings: Record<string, string> | null;\n started_at?: number;\n completed_at?: number;\n created_at: number;\n updated_at: number;\n}\n\nexport interface RoleSetJSON {\n object: typeof ObjectType.RoleSet;\n id: string;\n name: string;\n key: string;\n description: string | null;\n roles: RoleSetItemJSON[];\n default_role: RoleSetItemJSON | null;\n creator_role: RoleSetItemJSON | null;\n type: 'initial' | 'custom';\n role_set_migration: RoleSetMigrationJSON | null;\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/** @inline */\nexport interface PublicOrganizationDataJSON extends ClerkResourceJSON {\n /** The name of the Organization. */\n name: string;\n /** The slug of the Organization. */\n slug: string;\n /** Holds the default Organization profile image. Compatible with Clerk's [Image Optimization](https://clerk.com/docs/guides/development/image-optimization). */\n image_url?: string;\n /** Whether the Organization has a profile image. */\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 AgentTaskJSON extends ClerkResourceJSON {\n object: typeof ObjectType.AgentTask;\n agent_id: string;\n agent_task_id: string;\n /**\n * @deprecated Use `agent_task_id` instead.\n */\n task_id: string;\n url: string;\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 enterprise_accounts: EnterpriseAccountJSON[];\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 EnterpriseConnectionSamlConnectionJSON {\n id: string;\n name: string;\n idp_entity_id: string;\n idp_sso_url: string;\n idp_certificate: string;\n idp_certificate_issued_at: number;\n idp_certificate_expires_at: number;\n idp_metadata_url: string;\n idp_metadata: string;\n acs_url: string;\n sp_entity_id: string;\n sp_metadata_url: string;\n sync_user_attributes: boolean;\n allow_subdomains: boolean;\n allow_idp_initiated: boolean;\n}\n\nexport interface EnterpriseConnectionOauthConfigJSON {\n id: string;\n name: string;\n client_id: string;\n discovery_url: string;\n logo_public_url: string;\n created_at: number;\n updated_at: number;\n}\n\nexport interface EnterpriseConnectionJSON extends ClerkResourceJSON {\n object: typeof ObjectType.EnterpriseConnection;\n name: string;\n domains: string[];\n organization_id: string | null;\n active: boolean;\n sync_user_attributes: boolean;\n allow_subdomains: boolean;\n disable_additional_identifications: boolean;\n created_at: number;\n updated_at: number;\n saml_connection?: EnterpriseConnectionSamlConnectionJSON | null;\n oauth_config?: EnterpriseConnectionOauthConfigJSON | null;\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_certificate_issued_at: number;\n idp_certificate_expires_at: number;\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 | null;\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 | null;\n annual_fee: BillingMoneyAmountJSON | null;\n annual_monthly_fee: BillingMoneyAmountJSON | null;\n for_payer_type: 'org' | 'user';\n features?: FeatureJSON[];\n free_trial_days: number | null;\n free_trial_enabled: boolean;\n avatar_url: string | null;\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 | null;\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 { MachineJSON } from './JSON';\n\n/**\n * The Backend `Machine` object holds information about a machine.\n */\nexport class Machine {\n constructor(\n /** The unique identifier for the machine. */\n readonly id: string,\n /** The name of the machine. */\n readonly name: string,\n /** The ID of the instance the machine belongs to. */\n readonly instanceId: string,\n /** The Unix timestamp when the machine was created. */\n readonly createdAt: number,\n /** The Unix timestamp when the machine was last updated. */\n readonly updatedAt: number,\n /** The machines that the current machine has access to. */\n readonly scopedMachines: Machine[],\n /** The default time-to-live (TTL) in seconds for tokens created by this machine. */\n readonly defaultTokenTtl: number,\n /** The secret key for the machine. */\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 /** The ID of the machine that has access to the target machine. */\n readonly fromMachineId: string,\n /** The ID of the machine that is being accessed. */\n readonly toMachineId: string,\n /** The Unix timestamp when the machine scope was created. */\n readonly createdAt?: number,\n /** Whether the machine scope has been deleted. */\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\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\n/**\n * The Backend `OauthAccessToken` object holds information about an OAuth access token associated with a user that has previously authenticated with a particular OAuth provider.\n */\nexport class OauthAccessToken {\n constructor(\n /** The ID of the external account associated with this token. */\n readonly externalAccountId: string,\n /** The OAuth provider (e.g., `google`, `github`). */\n readonly provider: string,\n /** The OAuth access token. */\n readonly token: string,\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 readonly publicMetadata: Record<string, unknown> = {},\n /** A descriptive label to differentiate multiple access tokens of the same user for the same provider. */\n readonly label: string,\n /** The scopes granted for this access token. */\n readonly scopes?: string[],\n /** The token secret, if applicable (e.g., for OAuth 1.0 providers). */\n readonly tokenSecret?: string,\n /** The Unix timestamp when the access token expires. */\n readonly expiresAt?: number,\n /** The user's OIDC ID Token, if available. This token contains user identity information as a JWT and is returned when the provider supports [OpenID Connect (OIDC)](/docs/guides/configure/auth-strategies/oauth/overview). Not all OAuth providers implement OIDC, so this field may be `undefined` for some providers. */\n readonly idToken?: string,\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 data.id_token,\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 /** The unique identifier for the OAuth application. */\n readonly id: string,\n /** The ID of the instance that this OAuth application belongs to. */\n readonly instanceId: string,\n /** The name of the new OAuth application. */\n readonly name: string,\n /** The ID of the client associated with the OAuth application. */\n readonly clientId: string,\n /** The public-facing URL of the OAuth application, often shown on consent screens. */\n readonly clientUri: string | null,\n /** The URL of the image or logo representing the OAuth application. */\n readonly clientImageUrl: string | null,\n /** Whether the OAuth application is dynamically registered. */\n readonly dynamicallyRegistered: boolean,\n /** Whether the consent screen should be displayed in the authentication flow. Cannot be disabled for dynamically registered OAuth applications. */\n readonly consentScreenEnabled: boolean,\n /** Whether the Proof Key of Code Exchange (PKCE) flow should be required in the authentication flow. */\n readonly pkceRequired: boolean,\n /** Whether the client is public. If true, the Proof Key of Code Exchange (PKCE) flow can be used. */\n readonly isPublic: boolean, // NOTE: `public` is reserved\n /** Scopes for the new OAuth application. */\n readonly scopes: string,\n /** An array of redirect URIs of the new OAuth application. */\n readonly redirectUris: Array<string>,\n /** The URL used to authorize the user and obtain an authorization code. */\n readonly authorizeUrl: string,\n /** The URL used by the client to exchange an authorization code for an access token. */\n readonly tokenFetchUrl: string,\n /** The URL where the client can retrieve user information using an access token. */\n readonly userInfoUrl: string,\n /** The OpenID Connect discovery endpoint URL for this OAuth application. */\n readonly discoveryUrl: string,\n /** The URL used to introspect and validate issued access tokens. */\n readonly tokenIntrospectionUrl: string,\n /** The Unix timestamp when the OAuth application was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the OAuth application was last updated. */\n readonly updatedAt: number,\n /** The client secret associated with the OAuth application. Empty if public client. */\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/objects/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/model/Organization){{ 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 /** The unique identifier for the Organization. */\n readonly id: string,\n /** The name of the Organization. */\n readonly name: string,\n /** The URL-friendly identifier of the user's active Organization. If supplied, it must be unique for the instance. */\n readonly slug: string,\n /** Holds the Organization's logo. Compatible with Clerk's [Image Optimization](https://clerk.com/docs/guides/development/image-optimization). */\n readonly imageUrl: string,\n /** Whether the Organization has an image. */\n readonly hasImage: boolean,\n /** The Unix timestamp when the Organization was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the Organization was last updated. */\n readonly updatedAt: number,\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 readonly publicMetadata: OrganizationPublicMetadata | null = {},\n /** Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}. */\n readonly privateMetadata: OrganizationPrivateMetadata = {},\n /** The maximum number of memberships allowed in the Organization. */\n readonly maxAllowedMemberships: number,\n /** Whether the Organization allows admins to delete users. */\n readonly adminDeleteEnabled: boolean,\n /** The number of members in the Organization. */\n readonly membersCount?: number,\n /** The ID of the user who created the Organization. */\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/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/model/OrganizationInvitation){{ 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 /** The unique identifier for the `OrganizationInvitation`. */\n readonly id: string,\n /** The email address of the user who is invited to the [`Organization`](https://clerk.com/docs/reference/backend/types/backend-organization). */\n readonly emailAddress: string,\n /** The [Role](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) of the invited user. */\n readonly role: OrganizationMembershipRole,\n /** The name of the [Role](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) of the invited user. */\n readonly roleName: string,\n /** The ID of the [`Organization`](https://clerk.com/docs/reference/backend/types/backend-organization) that the user is invited to. */\n readonly organizationId: string,\n /** The Unix timestamp when the invitation was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the invitation was last updated. */\n readonly updatedAt: number,\n /** The Unix timestamp when the invitation expires. */\n readonly expiresAt: number,\n /** The URL that the user can use to accept the invitation. */\n readonly url: string | null,\n /** The status of the invitation. */\n readonly status?: OrganizationInvitationStatus,\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 readonly publicMetadata: OrganizationInvitationPublicMetadata = {},\n /** Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}. */\n readonly privateMetadata: OrganizationInvitationPrivateMetadata = {},\n /** Public data about the Organization that the user is invited to. */\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/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/model/OrganizationMembership){{ 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 /** The unique identifier for the membership. */\n readonly id: string,\n /** The [Role](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) of the user. */\n readonly role: OrganizationMembershipRole,\n /** The [Permissions](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) granted to the user in the Organization. */\n readonly permissions: string[],\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 readonly publicMetadata: OrganizationMembershipPublicMetadata = {},\n /** Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}. */\n readonly privateMetadata: OrganizationMembershipPrivateMetadata = {},\n /** The Unix timestamp when the membership was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the membership was last updated. */\n readonly updatedAt: number,\n /** The Organization that the user is a member of. */\n readonly organization: Organization,\n /** Public information about the user that this membership belongs to. */\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\n/** The `OrganizationSettings` object represents the [Organization-related settings](https://clerk.com/docs/guides/organizations/configure) for the current instance. */\nexport class OrganizationSettings {\n constructor(\n /** Whether the instance has [Organizations](https://clerk.com/docs/guides/organizations/overview) enabled. */\n readonly enabled: boolean,\n /** The maximum number of [memberships allowed](https://clerk.com/docs/guides/organizations/configure#membership-limits) per Organization. */\n readonly maxAllowedMemberships: number,\n /** The maximum number of Roles allowed per Organization. */\n readonly maxAllowedRoles: number,\n /** The maximum number of Permissions allowed per Organization. */\n readonly maxAllowedPermissions: number,\n /** The default [Role](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) for an Organization creator. */\n readonly creatorRole: string,\n /** Whether [admins](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions#default-roles) are allowed to delete Organizations. */\n readonly adminDeleteEnabled: boolean,\n /** Whether the instance has [Verified Domains](https://clerk.com/docs/guides/organizations/add-members/verified-domains) enabled. */\n readonly domainsEnabled: boolean,\n /** Whether the instance has [Organization slugs](https://clerk.com/docs/guides/organizations/configure#organization-slugs) disabled. */\n readonly slugDisabled: boolean,\n /**\n * The [enrollment modes](https://clerk.com/docs/guides/organizations/add-members/verified-domains#enable-verified-domains) available for Verified Domains.\n *\n * <ul>\n * <li>`manual_invitation`: No automatic enrollment. Users with a matching email domain are not given any [invitation](https://clerk.com/docs/guides/organizations/add-members/verified-domains#automatic-invitations) or [suggestion](https://clerk.com/docs/guides/organizations/add-members/verified-domains#automatic-suggestions); an [admin](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions#default-roles) must invite them manually.</li>\n * <li>`automatic_invitation`: Users with a matching email domain automatically receive a pending [invitation](https://clerk.com/docs/reference/types/organization-invitation) (assigned the Organization's default Role) which they can accept to join.</li>\n * <li>`automatic_suggestion`: Users with a matching email domain automatically receive a [suggestion](https://clerk.com/docs/guides/organizations/add-members/verified-domains#automatic-suggestions) to join, which they can request.</li>\n * </ul>\n */\n readonly domainsEnrollmentModes: Array<DomainsEnrollmentModes>,\n /** The default [Role](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) for the Organization's [Verified Domains](https://clerk.com/docs/guides/organizations/add-members/verified-domains). */\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 type { PermissionJSON } from './JSON';\n\n/**\n * The Backend `Permission` object represents an organization permission that can be assigned to organization roles.\n */\nexport class Permission {\n constructor(\n /** The unique identifier for the permission. */\n readonly id: string,\n /** The name of the permission. */\n readonly name: string,\n /** The unique key of the permission, in the format `org:feature:action`. */\n readonly key: string,\n /** A description of the permission. */\n readonly description: string,\n /** The Unix timestamp when the permission was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the permission was last updated. */\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: PermissionJSON): Permission {\n return new Permission(data.id, data.name, data.key, data.description, data.created_at, data.updated_at);\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 /** The unique identifier for this phone number. */\n readonly id: string,\n /** The value of this phone number, in [E.164 format](https://en.wikipedia.org/wiki/E.164). */\n readonly phoneNumber: string,\n /** Whether the phone number is reserved for multi-factor authentication (2FA). */\n readonly reservedForSecondFactor: boolean,\n /** Whether the phone number is the default second factor. A user must have exactly one default second factor, if multi-factor authentication (2FA) is enabled. */\n readonly defaultSecondFactor: boolean,\n /** An object holding information on the verification of this phone number. */\n readonly verification: Verification | null,\n /** An object containing information about any other identification that might be linked to this phone number. */\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 /** The unique identifier for the redirect URL. */\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 /** The Unix timestamp when the redirect URL was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the redirect URL was last updated. */\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 { RoleJSON } from './JSON';\nimport { Permission } from './Permission';\n\n/**\n * The Backend `Role` object represents an Organization [Role](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) that can be assigned to Organization members.\n */\nexport class Role {\n constructor(\n /** The unique identifier for the Role. */\n readonly id: string,\n /** The name of the Role. */\n readonly name: string,\n /** The unique key of the Role, in the format `org:role`. */\n readonly key: string,\n /** A description of the Role. */\n readonly description: string | null,\n /** The [Permissions](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) assigned to the Role. */\n readonly permissions: Permission[],\n /** Whether this Role is eligible to be an Organization creator Role. */\n readonly isCreatorEligible: boolean,\n /** The Unix timestamp when the Role was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the Role was last updated. */\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: RoleJSON): Role {\n return new Role(\n data.id,\n data.name,\n data.key,\n data.description,\n (data.permissions ?? []).map(permission => Permission.fromJSON(permission)),\n data.is_creator_eligible,\n data.created_at,\n data.updated_at,\n );\n }\n}\n","import type { RoleSetItemJSON, RoleSetJSON, RoleSetMigrationJSON } from './JSON';\n\n/**\n * The Backend `RoleSetItem` object represents a [Role](https://clerk.com/docs/guides/organizations/control-access/roles-and-permissions) that belongs to a {@link RoleSet}.\n */\nexport class RoleSetItem {\n constructor(\n /** The unique identifier for the Role. */\n readonly id: string,\n /** The name of the Role. */\n readonly name: string,\n /** The unique key of the Role. */\n readonly key: string,\n /** A description of the Role. */\n readonly description: string | null,\n /** The Unix timestamp when the Role was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the Role was last updated. */\n readonly updatedAt: number,\n /** The number of Organization members that have this Role. */\n readonly membersCount?: number | null,\n /** Whether any Organization members have this Role. */\n readonly hasMembers?: boolean | null,\n ) {}\n\n static fromJSON(data: RoleSetItemJSON): RoleSetItem {\n return new RoleSetItem(\n data.id,\n data.name,\n data.key,\n data.description,\n data.created_at,\n data.updated_at,\n data.members_count,\n data.has_members,\n );\n }\n}\n\n/**\n * The Backend `RoleSetMigration` object holds information about an in-progress migration between role sets.\n */\nexport class RoleSetMigration {\n constructor(\n readonly id: string,\n readonly organizationId: string | null,\n readonly instanceId: string,\n readonly sourceRoleSetId: string,\n readonly destRoleSetId: string | null,\n readonly triggerType: string,\n readonly status: string,\n readonly migratedMembers: number,\n readonly mappings: Record<string, string> | null,\n readonly createdAt: number,\n readonly updatedAt: number,\n readonly startedAt?: number,\n readonly completedAt?: number,\n ) {}\n\n static fromJSON(data: RoleSetMigrationJSON): RoleSetMigration {\n return new RoleSetMigration(\n data.id,\n data.organization_id,\n data.instance_id,\n data.source_role_set_id,\n data.dest_role_set_id,\n data.trigger_type,\n data.status,\n data.migrated_members,\n data.mappings,\n data.created_at,\n data.updated_at,\n data.started_at,\n data.completed_at,\n );\n }\n}\n\n/**\n * The Backend `RoleSet` object represents a collection of roles that can be assigned to organization members.\n */\nexport class RoleSet {\n constructor(\n /**\n * The unique identifier for the role set.\n */\n readonly id: string,\n /**\n * The name of the role set.\n */\n readonly name: string,\n /**\n * The unique key of the role set.\n */\n readonly key: string,\n /**\n * A description of the role set.\n */\n readonly description: string | null,\n /**\n * The roles that belong to the role set.\n */\n readonly roles: RoleSetItem[],\n /**\n * The default role assigned to new organization members.\n */\n readonly defaultRole: RoleSetItem | null,\n /**\n * The role assigned to the creator of an organization.\n */\n readonly creatorRole: RoleSetItem | null,\n /**\n * The type of the role set. `initial` role sets are the default for new organizations.\n */\n readonly type: 'initial' | 'custom',\n /**\n * Active migration information, only present when a migration is in progress.\n */\n readonly roleSetMigration: RoleSetMigration | null,\n /**\n * The date when the role set was first created.\n */\n readonly createdAt: number,\n /**\n * The date when the role set was last updated.\n */\n readonly updatedAt: number,\n ) {}\n\n static fromJSON(data: RoleSetJSON): RoleSet {\n return new RoleSet(\n data.id,\n data.name,\n data.key,\n data.description,\n (data.roles ?? []).map(role => RoleSetItem.fromJSON(role)),\n data.default_role ? RoleSetItem.fromJSON(data.default_role) : null,\n data.creator_role ? RoleSetItem.fromJSON(data.creator_role) : null,\n data.type,\n data.role_set_migration ? RoleSetMigration.fromJSON(data.role_set_migration) : null,\n data.created_at,\n data.updated_at,\n );\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 * @deprecated Use [`EnterpriseConnection`](https://clerk.com/docs/reference/backend/types/backend-enterprise-connection) instead.\n */\nexport class SamlConnection {\n constructor(\n /** The unique identifier for the connection. */\n readonly id: string,\n /** The name to use as a label for the connection. */\n readonly name: string,\n /** The domain of your Organization. Sign in flows using an email with this domain will use the connection. */\n readonly domain: string,\n /** The Organization ID of the Organization. */\n readonly organizationId: string | null,\n /** The Entity ID as provided by the Identity Provider (IdP). */\n readonly idpEntityId: string | null,\n /** The Single-Sign On URL as provided by the Identity Provider (IdP). */\n readonly idpSsoUrl: string | null,\n /** The X.509 certificate as provided by the Identity Provider (IdP). */\n readonly idpCertificate: string | null,\n /** The Unix timestamp when the Identity Provider (IdP) certificate was issued. */\n readonly idpCertificateIssuedAt: number,\n /** The Unix timestamp when the Identity Provider (IdP) certificate expires. */\n readonly idpCertificateExpiresAt: number,\n /** The URL which serves the Identity Provider (IdP) metadata. If present, it takes priority over the corresponding individual properties. */\n readonly idpMetadataUrl: string | null,\n /** The XML content of the Identity Provider (IdP) metadata file. If present, it takes priority over the corresponding individual properties. */\n readonly idpMetadata: string | null,\n /** The Assertion Consumer Service (ACS) URL of the connection. */\n readonly acsUrl: string,\n /** The Entity ID as provided by the Service Provider (Clerk). */\n readonly spEntityId: string,\n /** The metadata URL as provided by the Service Provider (Clerk). */\n readonly spMetadataUrl: string,\n /** Whether the connection is active or not. */\n readonly active: boolean,\n /** The Identity Provider (IdP) of the connection. */\n readonly provider: string,\n /** The number of users associated with the connection. */\n readonly userCount: number,\n /** Whether the connection syncs user attributes between the Service Provider (SP) and Identity Provider (IdP) or not. */\n readonly syncUserAttributes: boolean,\n /** Whether users with an email address subdomain are allowed to use this connection in order to authenticate or not. */\n readonly allowSubdomains: boolean,\n /** Whether the connection allows Identity Provider (IdP) initiated flows or not. */\n readonly allowIdpInitiated: boolean,\n /** The Unix timestamp when the connection was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the connection was last updated. */\n readonly updatedAt: number,\n /** Defines the attribute name mapping between the Identity Provider (IdP) and Clerk's [`User`](https://clerk.com/docs/reference/objects/user) properties. */\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_certificate_issued_at,\n data.idp_certificate_expires_at,\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\n/**\n * The Backend `SignInToken` object holds information about a sign-in token.\n */\nexport class SignInToken {\n constructor(\n /** The unique identifier for the token. */\n readonly id: string,\n /** The ID of the user the token is for. */\n readonly userId: string,\n /** The token itself. */\n readonly token: string,\n /** The status of the token. */\n readonly status: string,\n /** The URL the token is for. */\n readonly url: string,\n /** The Unix timestamp when the token was created. */\n readonly createdAt: number,\n /** The Unix timestamp when the token was last updated. */\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 /** The unique ID for the Web3 wallet. */\n readonly id: string,\n /** The Web3 wallet address, made up of 0x + 40 hexadecimal characters. */\n readonly web3Wallet: string,\n /** An object holding information on the verification of this Web3 wallet. */\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 { EnterpriseAccount } from './EnterpriseAccount';\nimport { ExternalAccount } from './ExternalAccount';\nimport type { EnterpriseAccountJSON, 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/model/User){{ 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 /** The unique identifier for the user. */\n readonly id: string,\n /** Whether the user has a password on their account. */\n readonly passwordEnabled: boolean,\n /** Whether the user has enabled TOTP by generating a TOTP secret and verifying it via an authenticator app. */\n readonly totpEnabled: boolean,\n /** Whether the user has enabled Backup codes. */\n readonly backupCodeEnabled: boolean,\n /** Whether the user has enabled two-factor authentication. */\n readonly twoFactorEnabled: boolean,\n /** Whether the user is banned or not. */\n readonly banned: boolean,\n /** Whether the user is [locked](https://clerk.com/docs/guides/secure/user-lockout) or not. */\n readonly locked: boolean,\n /** The Unix timestamp when the user was first created. */\n readonly createdAt: number,\n /** The Unix timestamp when the user was last updated. */\n readonly updatedAt: number,\n /** The URL of the user's profile image. */\n readonly imageUrl: string,\n /** Whether the user has uploaded an image or one was copied from OAuth. Returns `false` if Clerk is displaying an avatar for the user. */\n readonly hasImage: boolean,\n /** The ID for the `EmailAddress` that the user has set as primary. */\n readonly primaryEmailAddressId: string | null,\n /** The ID for the `PhoneNumber` that the user has set as primary. */\n readonly primaryPhoneNumberId: string | null,\n /** The ID for the [`Web3Wallet`](https://clerk.com/docs/reference/backend/types/backend-web3-wallet) that the user signed up with. */\n readonly primaryWeb3WalletId: string | null,\n /** The Unix timestamp when the user last signed in. May be empty if the user has never signed in. */\n readonly lastSignInAt: number | null,\n /** The ID of the user as used in your external systems. Must be unique across your instance. */\n readonly externalId: string | null,\n /** The user's username. */\n readonly username: string | null,\n /** The user's first name. */\n readonly firstName: string | null,\n /** The user's last name. */\n readonly lastName: string | null,\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 readonly publicMetadata: UserPublicMetadata = {},\n /** Metadata that can be read and set only from the [Backend API](https://clerk.com/docs/reference/backend-api){{ target: '_blank' }}. */\n readonly privateMetadata: UserPrivateMetadata = {},\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 readonly unsafeMetadata: UserUnsafeMetadata = {},\n /** An array of all the `EmailAddress` objects associated with the user. Includes the primary. */\n readonly emailAddresses: EmailAddress[] = [],\n /** An array of all the `PhoneNumber` objects associated with the user. Includes the primary. */\n readonly phoneNumbers: PhoneNumber[] = [],\n /** An array of all the `Web3Wallet` objects associated with the user. Includes the primary. */\n readonly web3Wallets: Web3Wallet[] = [],\n /** An array of all the `ExternalAccount` objects associated with the user via OAuth. **Note**: This includes both verified & unverified external accounts. */\n readonly externalAccounts: ExternalAccount[] = [],\n /** An array of all the `EnterpriseAccount` objects associated with the user via enterprise SSO. */\n readonly enterpriseAccounts: EnterpriseAccount[] = [],\n /** The Unix timestamp when the user was last active. */\n readonly lastActiveAt: number | null,\n /** Whether the Organization creation is enabled for the user or not. */\n readonly createOrganizationEnabled: boolean,\n /** 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 readonly createOrganizationsLimit: number | null = null,\n /** Whether the user can delete their own account. */\n readonly deleteSelfEnabled: boolean,\n /** The Unix timestamp 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 readonly legalAcceptedAt: number | null,\n\n /** The locale of the user in BCP-47 format. */\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.enterprise_accounts || []).map((x: EnterpriseAccountJSON) => EnterpriseAccount.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\n/**\n * The Backend `WaitlistEntry` object holds information about a [waitlist entry](https://clerk.com/docs/guides/secure/restricting-access#waitlist).\n */\nexport class WaitlistEntry {\n constructor(\n /** The unique identifier for the waitlist entry. */\n readonly id: string,\n /** The email address to add to the waitlist. */\n readonly emailAddress: string,\n /** The status of the waitlist entry. */\n readonly status: WaitlistEntryStatus,\n /** The invitation associated with the waitlist entry. */\n readonly invitation: Invitation | null,\n /** The Unix timestamp when the waitlist entry was created. */\n readonly createdAt: number,\n /** The Unix timestamp when the waitlist entry was last updated. */\n readonly updatedAt: number,\n /** Whether the waitlist entry is locked. */\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 AgentTask,\n AllowlistIdentifier,\n APIKey,\n BlocklistIdentifier,\n Client,\n Cookies,\n DeletedObject,\n Domain,\n Email,\n EmailAddress,\n EnterpriseAccount,\n EnterpriseConnection,\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 Permission,\n PhoneNumber,\n ProxyCheck,\n RedirectUrl,\n Role,\n RoleSet,\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 (isM2MTokenResponse(payload)) {\n // Handle M2M token list responses with m2m_tokens property\n data = payload.m2m_tokens.map(item => jsonToObject(item)) as U;\n totalCount = payload.total_count;\n\n return { data, totalCount };\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\n/**\n * Detects M2M token list responses from the Backend API.\n *\n * The Clerk Backend API returns M2M token lists with `m2m_tokens` and `total_count` properties.\n * This function identifies those responses and normalizes them to the standard `data` and\n * `totalCount` format for consistency with other paginated API methods across the SDK.\n *\n * This approach avoids making breaking changes to BAPI Proxy or supporting both response\n * formats. Once BAPI Proxy is updated to return the standard `data` property format,\n * this function can be safely removed.\n *\n * @see https://clerk.com/docs/reference/backend-api/tag/m2m-tokens/GET/m2m_tokens\n */\nfunction isM2MTokenResponse(payload: unknown): payload is { m2m_tokens: unknown[]; total_count: number } {\n if (!payload || typeof payload !== 'object' || !('m2m_tokens' in payload)) {\n return false;\n }\n\n return Array.isArray(payload.m2m_tokens);\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.EnterpriseAccount:\n return EnterpriseAccount.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.Permission:\n return Permission.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.Role:\n return Role.fromJSON(item);\n case ObjectType.RoleSet:\n return RoleSet.fromJSON(item);\n case ObjectType.EnterpriseConnection:\n return EnterpriseConnection.fromJSON(item);\n case ObjectType.SamlConnection:\n return SamlConnection.fromJSON(item);\n case ObjectType.SignInToken:\n return SignInToken.fromJSON(item);\n case ObjectType.AgentTask:\n return AgentTask.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 AgentTaskAPI,\n AllowlistIdentifierAPI,\n APIKeysAPI,\n BetaFeaturesAPI,\n BlocklistIdentifierAPI,\n ClientAPI,\n DomainAPI,\n EmailAddressAPI,\n EmailApi,\n EnterpriseConnectionAPI,\n IdPOAuthAccessTokenApi,\n InstanceAPI,\n InvitationAPI,\n JwksAPI,\n JwtTemplatesApi,\n M2MTokenApi,\n MachineApi,\n OAuthApplicationsApi,\n OrganizationAPI,\n OrganizationPermissionAPI,\n OrganizationRoleAPI,\n PhoneNumberAPI,\n ProxyCheckAPI,\n RedirectUrlAPI,\n RoleSetAPI,\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 jwtKey?: string;\n};\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 /**\n * @experimental This is an experimental API for the Agent Tasks feature that is available under a private 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 agentTasks: new AgentTaskAPI(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 /**\n * @experimental This calls an internal, not-yet-public endpoint for sending\n * transactional emails and is subject to change. It is advised to\n * [pin](https://clerk.com/docs/pinning) the SDK version to avoid breaking changes.\n */\n emails: new EmailApi(request),\n enterpriseConnections: new EnterpriseConnectionAPI(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 secretKey: options.secretKey,\n apiUrl: options.apiUrl,\n jwtKey: options.jwtKey,\n },\n ),\n oauthApplications: new OAuthApplicationsApi(request),\n organizations: new OrganizationAPI(request),\n organizationPermissions: new OrganizationPermissionAPI(request),\n organizationRoles: new OrganizationRoleAPI(request),\n phoneNumbers: new PhoneNumberAPI(request),\n proxyChecks: new ProxyCheckAPI(request),\n redirectUrls: new RedirectUrlAPI(request),\n roleSets: new RoleSetAPI(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 * @deprecated Use `enterpriseConnections` instead.\n */\n samlConnections: new SamlConnectionAPI(request),\n };\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\ntype BootstrapSignedOutParams = {\n signInUrl?: string;\n signUpUrl?: string;\n isSatellite?: boolean;\n domain?: string;\n proxyUrl?: string;\n reason?: AuthReason;\n message?: string;\n headers?: Headers;\n};\n\n/**\n * Returns a synthetic `UnauthenticatedState` without requiring a publishable key or an\n * `AuthenticateContext`. Intended for framework integrations that need to run\n * authorization logic for a request that arrived before real Clerk keys are available\n * (e.g. the Next.js keyless bootstrap window). The returned state has\n * `status: 'signed-out'` and `toAuth()` returns a standard signed-out session auth object.\n *\n * `signInUrl` / `signUpUrl` are carried through so that `redirectToSignIn` /\n * `redirectToSignUp` can resolve to the application's own routes during bootstrap.\n * `isSatellite` / `domain` / `proxyUrl` are carried through so that cross-origin\n * satellite redirects produced by `createRedirect` include the `__clerk_status=needs-sync`\n * marker required for the return-trip handshake.\n */\nexport function createBootstrapSignedOutState({\n signInUrl = '',\n signUpUrl = '',\n isSatellite = false,\n domain = '',\n proxyUrl = '',\n reason = AuthErrorReason.SessionTokenAndUATMissing,\n message = '',\n headers = new Headers(),\n}: BootstrapSignedOutParams = {}): UnauthenticatedState<SessionTokenType> {\n return withDebugHeaders({\n status: AuthStatus.SignedOut,\n reason,\n message,\n proxyUrl,\n publishableKey: '',\n isSatellite,\n domain,\n signInUrl,\n signUpUrl,\n afterSignInUrl: '',\n afterSignUpUrl: '',\n isSignedIn: false,\n isAuthenticated: false,\n tokenType: TokenType.SessionToken,\n toAuth: () => signedOutAuthObject({ status: AuthStatus.SignedOut, reason, message }),\n 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 // When cloning a Request by passing it as init, hide its `signal` and `body`.\n // Undici's Request constructor in Node 24 performs a strict instanceof check on\n // the signal and rejects ones from a different realm (e.g. NextRequest). The\n // `body` is hidden because forwarding it makes the clone share the original's\n // single-use ReadableStream; once either side is read the other throws\n // \"Body is unusable\" downstream (issue #8305). Auth only reads the method,\n // headers, cookies, and URL, so the clone never needs a body. Using a Proxy\n // keeps property access lazy so environments that don't implement optional\n // getters (e.g. Cloudflare Workers' Request lacks `cache`) still work.\n let cloneInit: RequestInit | undefined;\n if (init) {\n cloneInit = init;\n } else if (typeof input !== 'string') {\n cloneInit = new Proxy(input as Request, {\n get(target, prop) {\n if (prop === 'signal' || prop === 'body') {\n return undefined;\n }\n return Reflect.get(target, prop, target);\n },\n }) as unknown as RequestInit;\n }\n super(url, cloneInit);\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\n try {\n return createClerkUrl(initialUrl.pathname + initialUrl.search, origin);\n } catch {\n return createClerkUrl(initialUrl);\n }\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 // Use duck typing instead of instanceof to avoid issues with polyfilled Request classes\n // (e.g., in TanStack Start or other environments with multiple Request class instances)\n // ClerkRequest has unique properties 'clerkUrl' and 'cookies' that distinguish it from Request\n const isClerkRequest = args[0] && typeof args[0] === 'object' && 'clerkUrl' in args[0] && 'cookies' in args[0];\n\n return isClerkRequest ? (args[0] as ClerkRequest) : 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 { isClerkAPIResponseError } from '@clerk/shared/error';\nimport type { Jwt, 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 { verifyM2MJwt, verifyOAuthJwt } from '../jwt/verifyMachineJwt';\nimport type { LoadClerkJWKFromRemoteOptions } from './keys';\nimport { loadClerkJwkFromPem, loadClerkJWKFromRemote } from './keys';\nimport {\n API_KEY_PREFIX,\n isJwtFormat,\n JWT_CATEGORY_M2M_TOKEN,\n M2M_SUBJECT_PREFIX,\n M2M_TOKEN_PREFIX,\n OAUTH_ACCESS_TOKEN_TYPES,\n OAUTH_TOKEN_PREFIX,\n} 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/GET/jwks){{ 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 // Reject machine JWTs (e.g. M2M) tagged with a non-session category but signed by the same\n // instance key, regardless of transport. Reciprocal of the machine verifier's `cat` check.\n if (header.cat === JWT_CATEGORY_M2M_TOKEN) {\n return {\n errors: [\n new TokenVerificationError({\n action: TokenVerificationErrorAction.EnsureClerkJWT,\n reason: TokenVerificationErrorReason.TokenInvalid,\n message: 'Invalid session token category.',\n }),\n ],\n };\n }\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 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\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,\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 or JWT claims.\n * For JWTs, decodes once and routes based on claims to avoid redundant decoding.\n *\n * @param token - The token to verify (e.g. starts with \"mt_\", \"oat_\", \"ak_\", or a JWT)\n * @param options - Options including secretKey for BAPI authorization\n */\nexport async function verifyMachineAuthToken(token: string, options: VerifyTokenOptions) {\n if (isJwtFormat(token)) {\n let decodedResult: Jwt;\n try {\n const { data, errors: decodeErrors } = decodeJwt(token);\n if (decodeErrors) {\n throw decodeErrors[0];\n }\n decodedResult = data;\n } catch (e) {\n return {\n data: undefined,\n tokenType: TokenType.M2MToken,\n errors: [\n new MachineTokenVerificationError({\n code: MachineTokenVerificationErrorCode.TokenInvalid,\n message: (e as Error).message,\n }),\n ],\n } as MachineTokenReturnType<never, MachineTokenVerificationError>;\n }\n\n if (typeof decodedResult.payload.sub === 'string' && decodedResult.payload.sub.startsWith(M2M_SUBJECT_PREFIX)) {\n return verifyM2MJwt(token, decodedResult, options);\n }\n\n // OAuth JWT: typ is at+jwt or application/at+jwt\n if (OAUTH_ACCESS_TOKEN_TYPES.includes(decodedResult.header.typ as string)) {\n return verifyOAuthJwt(token, decodedResult, options);\n }\n\n return {\n data: undefined,\n tokenType: TokenType.OAuthToken,\n errors: [\n new MachineTokenVerificationError({\n code: MachineTokenVerificationErrorCode.TokenVerificationFailed,\n message: `Invalid JWT type: ${decodedResult.header.typ ?? 'missing'}. Expected one of: ${OAUTH_ACCESS_TOKEN_TYPES.join(', ')} for OAuth, or sub starting with 'mch_' for M2M`,\n }),\n ],\n } as MachineTokenReturnType<never, MachineTokenVerificationError>;\n }\n\n // Opaque token routing by prefix\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, method, secFetchDest } = this.authenticateContext;\n\n // Handshake involves a redirect to FAPI which only accepts GET requests.\n // Non-GET requests (e.g. POST form submissions) also set sec-fetch-dest: document,\n // but redirecting them would result in a 405 Method Not Allowed from FAPI.\n if (method !== 'GET') {\n return false;\n }\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.sessionToken) {\n url.searchParams.append(constants.QueryParameters.Session, this.authenticateContext.sessionToken);\n }\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 { 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; _raw?: 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 // Backend resources (`User`, `Organization`) retain the full Backend API\n // payload on the enumerable `_raw` property, which still contains\n // `private_metadata`. The payload is also nested (e.g. a `User`'s\n // `organization_memberships[*]` each carry their own `private_metadata`\n // and a nested `organization.private_metadata`), so redact recursively on\n // a deep clone — leaving the original resource (and its `raw` getter)\n // untouched.\n if ('_raw' in resource && resource['_raw']) {\n resource['_raw'] = redactPrivateMetadataDeep(resource['_raw']);\n }\n }\n\n return resource;\n}\n\n/**\n * Returns a deep clone of `value` with every `private_metadata` / `privateMetadata`\n * property removed at any depth.\n */\nfunction redactPrivateMetadataDeep(value: any): any {\n if (Array.isArray(value)) {\n return value.map(redactPrivateMetadataDeep);\n }\n if (value && typeof value === 'object') {\n const clone: Record<string, any> = {};\n for (const key of Object.keys(value)) {\n if (key === 'private_metadata' || key === 'privateMetadata') {\n continue;\n }\n clone[key] = redactPrivateMetadataDeep(value[key]);\n }\n return clone;\n }\n return value;\n}\n","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, createBootstrapSignedOutState } 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, isTokenTypeAccepted, isMachineToken } from './tokens/machine';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2GA,YAAA,cAAA;AAmbyD,YAAA,QAAA;AAnYzD,YAAA,kBAAA;AAoIA,YAAA,qBAAA;AA+P+B,YAAA,YAAA;AAzI/B,YAAA,iBAAA;AA/HA,YAAA,qBAAA;AAwQ+B,YAAA,YAAA;AAhhB/B,QAAM,mBAAmB;AAczB,QAAM,oBAAoB;AAyB1B,QAAM,oBACJ;AASF,QAAM,kBAAkB;AAKxB,QAAM,eAAe;AAErB,QAAM,aAAa,OAAO,UAAU;AAEpC,QAAM,aAA8B,uBAAK;AACvC,YAAM,IAAI,WAAA;MAAa;AACvB,QAAE,YAAY,uBAAO,OAAO,IAAI;AAChC,aAAO;IACT,GAAE;AA+BF,aAAgB,YAAY,KAAa,SAAsB;AAC7D,YAAM,MAAe,IAAI,WAAU;AACnC,YAAM,MAAM,IAAI;AAEhB,UAAI,MAAM;AAAG,eAAO;AAEpB,YAAM,MAAM,SAAS,UAAU;AAC/B,UAAI,QAAQ;AAEZ,SAAG;AACD,cAAM,QAAQ,QAAQ,KAAK,OAAO,GAAG;AACrC,YAAI,UAAU;AAAI;AAElB,cAAM,SAAS,SAAS,KAAK,OAAO,GAAG;AAEvC,YAAI,QAAQ,QAAQ;AAElB,kBAAQ,IAAI,YAAY,KAAK,QAAQ,CAAC,IAAI;AAC1C;QACF;AAEA,cAAM,MAAM,WAAW,KAAK,OAAO,KAAK;AAGxC,YAAI,IAAI,GAAG,MAAM,QAAW;AAC1B,cAAI,GAAG,IAAI,IAAI,WAAW,KA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AAQ,sBAAsB,QAAQ,mBAAmB;AAC3D;AAAA,MACF;AACA,YAAM,GAAG,IAAI,0BAA0B,MAAM,GAAG,CAAC;AAAA,IACnD;AACA,WAAO;AAAA,EACT;AACA,SAAO;AACT;;;AC3CA,SAAS,qBAAqB,mCAAmC;","names":["endIdx","eqIdx","Headers","buildAccountsBaseUrl","buildAccountsBaseUrl","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","jwk","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","basePath","match","convertCase","Cookies","data","Cookies","sessionId","authenticateContext","refreshToken","data","errors","authenticateRequest"]}