@clerk/backend
Version:
Clerk Backend SDK - REST Client for Backend API & JWT verification utilities
1,742 lines (1,695 loc) • 181 kB
JavaScript
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
// src/index.ts
var index_exports = {};
__export(index_exports, {
createClerkClient: () => createClerkClient,
verifyToken: () => verifyToken2
});
module.exports = __toCommonJS(index_exports);
var import_telemetry = require("@clerk/shared/telemetry");
// src/util/path.ts
var SEPARATOR = "/";
var MULTIPLE_SEPARATOR_REGEX = new RegExp("(?<!:)" + SEPARATOR + "{1,}", "g");
function joinPaths(...args) {
return args.filter((p) => p).join(SEPARATOR).replace(MULTIPLE_SEPARATOR_REGEX, SEPARATOR);
}
// src/api/endpoints/AbstractApi.ts
var AbstractAPI = class {
constructor(request) {
this.request = request;
}
requireId(id) {
if (!id) {
throw new Error("A valid resource ID is required.");
}
}
};
// src/api/endpoints/ActorTokenApi.ts
var basePath = "/actor_tokens";
var ActorTokenAPI = class extends AbstractAPI {
async create(params) {
return this.request({
method: "POST",
path: basePath,
bodyParams: params
});
}
async revoke(actorTokenId) {
this.requireId(actorTokenId);
return this.request({
method: "POST",
path: joinPaths(basePath, actorTokenId, "revoke")
});
}
};
// src/api/endpoints/AccountlessApplicationsAPI.ts
var basePath2 = "/accountless_applications";
var AccountlessApplicationAPI = class extends AbstractAPI {
async createAccountlessApplication(params) {
const headerParams = params?.requestHeaders ? Object.fromEntries(params.requestHeaders.entries()) : void 0;
return this.request({
method: "POST",
path: basePath2,
headerParams
});
}
async completeAccountlessApplicationOnboarding(params) {
const headerParams = params?.requestHeaders ? Object.fromEntries(params.requestHeaders.entries()) : void 0;
return this.request({
method: "POST",
path: joinPaths(basePath2, "complete"),
headerParams
});
}
};
// src/api/endpoints/AllowlistIdentifierApi.ts
var basePath3 = "/allowlist_identifiers";
var AllowlistIdentifierAPI = class extends AbstractAPI {
async getAllowlistIdentifierList(params = {}) {
return this.request({
method: "GET",
path: basePath3,
queryParams: { ...params, paginated: true }
});
}
async createAllowlistIdentifier(params) {
return this.request({
method: "POST",
path: basePath3,
bodyParams: params
});
}
async deleteAllowlistIdentifier(allowlistIdentifierId) {
this.requireId(allowlistIdentifierId);
return this.request({
method: "DELETE",
path: joinPaths(basePath3, allowlistIdentifierId)
});
}
};
// src/api/endpoints/APIKeysApi.ts
var basePath4 = "/api_keys";
var APIKeysAPI = class extends AbstractAPI {
async create(params) {
return this.request({
method: "POST",
path: basePath4,
bodyParams: params
});
}
async revoke(params) {
const { apiKeyId, ...bodyParams } = params;
this.requireId(apiKeyId);
return this.request({
method: "POST",
path: joinPaths(basePath4, apiKeyId, "revoke"),
bodyParams
});
}
async getSecret(apiKeyId) {
this.requireId(apiKeyId);
return this.request({
method: "GET",
path: joinPaths(basePath4, apiKeyId, "secret")
});
}
async verifySecret(secret) {
return this.request({
method: "POST",
path: joinPaths(basePath4, "verify"),
bodyParams: { secret }
});
}
};
// src/api/endpoints/BetaFeaturesApi.ts
var basePath5 = "/beta_features";
var BetaFeaturesAPI = class extends AbstractAPI {
/**
* Change the domain of a production instance.
*
* Changing the domain requires updating the DNS records accordingly, deploying new SSL certificates,
* updating your Social Connection's redirect URLs and setting the new keys in your code.
*
* @remarks
* WARNING: Changing your domain will invalidate all current user sessions (i.e. users will be logged out).
* Also, while your application is being deployed, a small downtime is expected to occur.
*/
async changeDomain(params) {
return this.request({
method: "POST",
path: joinPaths(basePath5, "change_domain"),
bodyParams: params
});
}
};
// src/api/endpoints/BlocklistIdentifierApi.ts
var basePath6 = "/blocklist_identifiers";
var BlocklistIdentifierAPI = class extends AbstractAPI {
async getBlocklistIdentifierList(params = {}) {
return this.request({
method: "GET",
path: basePath6,
queryParams: params
});
}
async createBlocklistIdentifier(params) {
return this.request({
method: "POST",
path: basePath6,
bodyParams: params
});
}
async deleteBlocklistIdentifier(blocklistIdentifierId) {
this.requireId(blocklistIdentifierId);
return this.request({
method: "DELETE",
path: joinPaths(basePath6, blocklistIdentifierId)
});
}
};
// src/api/endpoints/ClientApi.ts
var basePath7 = "/clients";
var ClientAPI = class extends AbstractAPI {
async getClientList(params = {}) {
return this.request({
method: "GET",
path: basePath7,
queryParams: { ...params, paginated: true }
});
}
async getClient(clientId) {
this.requireId(clientId);
return this.request({
method: "GET",
path: joinPaths(basePath7, clientId)
});
}
verifyClient(token) {
return this.request({
method: "POST",
path: joinPaths(basePath7, "verify"),
bodyParams: { token }
});
}
async getHandshakePayload(queryParams) {
return this.request({
method: "GET",
path: joinPaths(basePath7, "handshake_payload"),
queryParams
});
}
};
// src/api/endpoints/DomainApi.ts
var basePath8 = "/domains";
var DomainAPI = class extends AbstractAPI {
async list() {
return this.request({
method: "GET",
path: basePath8
});
}
async add(params) {
return this.request({
method: "POST",
path: basePath8,
bodyParams: params
});
}
async update(params) {
const { domainId, ...bodyParams } = params;
this.requireId(domainId);
return this.request({
method: "PATCH",
path: joinPaths(basePath8, domainId),
bodyParams
});
}
/**
* Deletes a satellite domain for the instance.
* It is currently not possible to delete the instance's primary domain.
*/
async delete(satelliteDomainId) {
return this.deleteDomain(satelliteDomainId);
}
/**
* @deprecated Use `delete` instead
*/
async deleteDomain(satelliteDomainId) {
this.requireId(satelliteDomainId);
return this.request({
method: "DELETE",
path: joinPaths(basePath8, satelliteDomainId)
});
}
};
// src/api/endpoints/EmailAddressApi.ts
var basePath9 = "/email_addresses";
var EmailAddressAPI = class extends AbstractAPI {
async getEmailAddress(emailAddressId) {
this.requireId(emailAddressId);
return this.request({
method: "GET",
path: joinPaths(basePath9, emailAddressId)
});
}
async createEmailAddress(params) {
return this.request({
method: "POST",
path: basePath9,
bodyParams: params
});
}
async updateEmailAddress(emailAddressId, params = {}) {
this.requireId(emailAddressId);
return this.request({
method: "PATCH",
path: joinPaths(basePath9, emailAddressId),
bodyParams: params
});
}
async deleteEmailAddress(emailAddressId) {
this.requireId(emailAddressId);
return this.request({
method: "DELETE",
path: joinPaths(basePath9, emailAddressId)
});
}
};
// src/api/endpoints/IdPOAuthAccessTokenApi.ts
var basePath10 = "/oauth_applications/access_tokens";
var IdPOAuthAccessTokenApi = class extends AbstractAPI {
async verifyAccessToken(accessToken) {
return this.request({
method: "POST",
path: joinPaths(basePath10, "verify"),
bodyParams: { access_token: accessToken }
});
}
};
// src/api/endpoints/InstanceApi.ts
var basePath11 = "/instance";
var InstanceAPI = class extends AbstractAPI {
async get() {
return this.request({
method: "GET",
path: basePath11
});
}
async update(params) {
return this.request({
method: "PATCH",
path: basePath11,
bodyParams: params
});
}
async updateRestrictions(params) {
return this.request({
method: "PATCH",
path: joinPaths(basePath11, "restrictions"),
bodyParams: params
});
}
async updateOrganizationSettings(params) {
return this.request({
method: "PATCH",
path: joinPaths(basePath11, "organization_settings"),
bodyParams: params
});
}
};
// src/api/endpoints/InvitationApi.ts
var basePath12 = "/invitations";
var InvitationAPI = class extends AbstractAPI {
async getInvitationList(params = {}) {
return this.request({
method: "GET",
path: basePath12,
queryParams: { ...params, paginated: true }
});
}
async createInvitation(params) {
return this.request({
method: "POST",
path: basePath12,
bodyParams: params
});
}
async revokeInvitation(invitationId) {
this.requireId(invitationId);
return this.request({
method: "POST",
path: joinPaths(basePath12, invitationId, "revoke")
});
}
};
// src/api/endpoints/MachineApi.ts
var basePath13 = "/machines";
var MachineApi = class extends AbstractAPI {
async get(machineId) {
this.requireId(machineId);
return this.request({
method: "GET",
path: joinPaths(basePath13, machineId)
});
}
async list(queryParams = {}) {
return this.request({
method: "GET",
path: basePath13,
queryParams
});
}
async create(bodyParams) {
return this.request({
method: "POST",
path: basePath13,
bodyParams
});
}
async update(params) {
const { machineId, ...bodyParams } = params;
this.requireId(machineId);
return this.request({
method: "PATCH",
path: joinPaths(basePath13, machineId),
bodyParams
});
}
async delete(machineId) {
this.requireId(machineId);
return this.request({
method: "DELETE",
path: joinPaths(basePath13, machineId)
});
}
async getSecretKey(machineId) {
this.requireId(machineId);
return this.request({
method: "GET",
path: joinPaths(basePath13, machineId, "secret_key")
});
}
/**
* Creates a new machine scope, allowing the specified machine to access another machine.
*
* @param machineId - The ID of the machine that will have access to another machine.
* @param toMachineId - The ID of the machine that will be scoped to the current machine.
*/
async createScope(machineId, toMachineId) {
this.requireId(machineId);
return this.request({
method: "POST",
path: joinPaths(basePath13, machineId, "scopes"),
bodyParams: {
toMachineId
}
});
}
/**
* Deletes a machine scope, removing access from one machine to another.
*
* @param machineId - The ID of the machine that has access to another machine.
* @param otherMachineId - The ID of the machine that is being accessed.
*/
async deleteScope(machineId, otherMachineId) {
this.requireId(machineId);
return this.request({
method: "DELETE",
path: joinPaths(basePath13, machineId, "scopes", otherMachineId)
});
}
};
// src/api/endpoints/M2MTokenApi.ts
var basePath14 = "/m2m_tokens";
var _M2MTokenApi_instances, createRequestOptions_fn;
var M2MTokenApi = class extends AbstractAPI {
constructor() {
super(...arguments);
__privateAdd(this, _M2MTokenApi_instances);
}
async createToken(params) {
const { claims = null, machineSecretKey, secondsUntilExpiration = null } = params || {};
const requestOptions = __privateMethod(this, _M2MTokenApi_instances, createRequestOptions_fn).call(this, {
method: "POST",
path: basePath14,
bodyParams: {
secondsUntilExpiration,
claims
}
}, machineSecretKey);
return this.request(requestOptions);
}
async revokeToken(params) {
const { m2mTokenId, revocationReason = null, machineSecretKey } = params;
this.requireId(m2mTokenId);
const requestOptions = __privateMethod(this, _M2MTokenApi_instances, createRequestOptions_fn).call(this, {
method: "POST",
path: joinPaths(basePath14, m2mTokenId, "revoke"),
bodyParams: {
revocationReason
}
}, machineSecretKey);
return this.request(requestOptions);
}
async verifyToken(params) {
const { token, machineSecretKey } = params;
const requestOptions = __privateMethod(this, _M2MTokenApi_instances, createRequestOptions_fn).call(this, {
method: "POST",
path: joinPaths(basePath14, "verify"),
bodyParams: { token }
}, machineSecretKey);
return this.request(requestOptions);
}
};
_M2MTokenApi_instances = new WeakSet();
createRequestOptions_fn = function(options, machineSecretKey) {
if (machineSecretKey) {
return {
...options,
headerParams: {
...options.headerParams,
Authorization: `Bearer ${machineSecretKey}`
}
};
}
return options;
};
// src/api/endpoints/JwksApi.ts
var basePath15 = "/jwks";
var JwksAPI = class extends AbstractAPI {
async getJwks() {
return this.request({
method: "GET",
path: basePath15
});
}
};
// src/api/endpoints/JwtTemplatesApi.ts
var basePath16 = "/jwt_templates";
var JwtTemplatesApi = class extends AbstractAPI {
async list(params = {}) {
return this.request({
method: "GET",
path: basePath16,
queryParams: { ...params, paginated: true }
});
}
async get(templateId) {
this.requireId(templateId);
return this.request({
method: "GET",
path: joinPaths(basePath16, templateId)
});
}
async create(params) {
return this.request({
method: "POST",
path: basePath16,
bodyParams: params
});
}
async update(params) {
const { templateId, ...bodyParams } = params;
this.requireId(templateId);
return this.request({
method: "PATCH",
path: joinPaths(basePath16, templateId),
bodyParams
});
}
async delete(templateId) {
this.requireId(templateId);
return this.request({
method: "DELETE",
path: joinPaths(basePath16, templateId)
});
}
};
// src/runtime.ts
var import_crypto = require("#crypto");
var globalFetch = fetch.bind(globalThis);
var runtime = {
crypto: import_crypto.webcrypto,
get fetch() {
return process.env.NODE_ENV === "test" ? fetch : globalFetch;
},
AbortController: globalThis.AbortController,
Blob: globalThis.Blob,
FormData: globalThis.FormData,
Headers: globalThis.Headers,
Request: globalThis.Request,
Response: globalThis.Response
};
// src/api/endpoints/OrganizationApi.ts
var basePath17 = "/organizations";
var OrganizationAPI = class extends AbstractAPI {
async getOrganizationList(params) {
return this.request({
method: "GET",
path: basePath17,
queryParams: params
});
}
async createOrganization(params) {
return this.request({
method: "POST",
path: basePath17,
bodyParams: params
});
}
async getOrganization(params) {
const { includeMembersCount } = params;
const organizationIdOrSlug = "organizationId" in params ? params.organizationId : params.slug;
this.requireId(organizationIdOrSlug);
return this.request({
method: "GET",
path: joinPaths(basePath17, organizationIdOrSlug),
queryParams: {
includeMembersCount
}
});
}
async updateOrganization(organizationId, params) {
this.requireId(organizationId);
return this.request({
method: "PATCH",
path: joinPaths(basePath17, organizationId),
bodyParams: params
});
}
async updateOrganizationLogo(organizationId, params) {
this.requireId(organizationId);
const formData = new runtime.FormData();
formData.append("file", params?.file);
if (params?.uploaderUserId) {
formData.append("uploader_user_id", params?.uploaderUserId);
}
return this.request({
method: "PUT",
path: joinPaths(basePath17, organizationId, "logo"),
formData
});
}
async deleteOrganizationLogo(organizationId) {
this.requireId(organizationId);
return this.request({
method: "DELETE",
path: joinPaths(basePath17, organizationId, "logo")
});
}
async updateOrganizationMetadata(organizationId, params) {
this.requireId(organizationId);
return this.request({
method: "PATCH",
path: joinPaths(basePath17, organizationId, "metadata"),
bodyParams: params
});
}
async deleteOrganization(organizationId) {
return this.request({
method: "DELETE",
path: joinPaths(basePath17, organizationId)
});
}
async getOrganizationMembershipList(params) {
const { organizationId, ...queryParams } = params;
this.requireId(organizationId);
return this.request({
method: "GET",
path: joinPaths(basePath17, organizationId, "memberships"),
queryParams
});
}
async getInstanceOrganizationMembershipList(params) {
return this.request({
method: "GET",
path: "/organization_memberships",
queryParams: params
});
}
async createOrganizationMembership(params) {
const { organizationId, ...bodyParams } = params;
this.requireId(organizationId);
return this.request({
method: "POST",
path: joinPaths(basePath17, organizationId, "memberships"),
bodyParams
});
}
async updateOrganizationMembership(params) {
const { organizationId, userId, ...bodyParams } = params;
this.requireId(organizationId);
return this.request({
method: "PATCH",
path: joinPaths(basePath17, organizationId, "memberships", userId),
bodyParams
});
}
async updateOrganizationMembershipMetadata(params) {
const { organizationId, userId, ...bodyParams } = params;
return this.request({
method: "PATCH",
path: joinPaths(basePath17, organizationId, "memberships", userId, "metadata"),
bodyParams
});
}
async deleteOrganizationMembership(params) {
const { organizationId, userId } = params;
this.requireId(organizationId);
return this.request({
method: "DELETE",
path: joinPaths(basePath17, organizationId, "memberships", userId)
});
}
async getOrganizationInvitationList(params) {
const { organizationId, ...queryParams } = params;
this.requireId(organizationId);
return this.request({
method: "GET",
path: joinPaths(basePath17, organizationId, "invitations"),
queryParams
});
}
async createOrganizationInvitation(params) {
const { organizationId, ...bodyParams } = params;
this.requireId(organizationId);
return this.request({
method: "POST",
path: joinPaths(basePath17, organizationId, "invitations"),
bodyParams
});
}
async createOrganizationInvitationBulk(organizationId, params) {
this.requireId(organizationId);
return this.request({
method: "POST",
path: joinPaths(basePath17, organizationId, "invitations", "bulk"),
bodyParams: params
});
}
async getOrganizationInvitation(params) {
const { organizationId, invitationId } = params;
this.requireId(organizationId);
this.requireId(invitationId);
return this.request({
method: "GET",
path: joinPaths(basePath17, organizationId, "invitations", invitationId)
});
}
async revokeOrganizationInvitation(params) {
const { organizationId, invitationId, ...bodyParams } = params;
this.requireId(organizationId);
return this.request({
method: "POST",
path: joinPaths(basePath17, organizationId, "invitations", invitationId, "revoke"),
bodyParams
});
}
async getOrganizationDomainList(params) {
const { organizationId, ...queryParams } = params;
this.requireId(organizationId);
return this.request({
method: "GET",
path: joinPaths(basePath17, organizationId, "domains"),
queryParams
});
}
async createOrganizationDomain(params) {
const { organizationId, ...bodyParams } = params;
this.requireId(organizationId);
return this.request({
method: "POST",
path: joinPaths(basePath17, organizationId, "domains"),
bodyParams: {
...bodyParams,
verified: bodyParams.verified ?? true
}
});
}
async updateOrganizationDomain(params) {
const { organizationId, domainId, ...bodyParams } = params;
this.requireId(organizationId);
this.requireId(domainId);
return this.request({
method: "PATCH",
path: joinPaths(basePath17, organizationId, "domains", domainId),
bodyParams
});
}
async deleteOrganizationDomain(params) {
const { organizationId, domainId } = params;
this.requireId(organizationId);
this.requireId(domainId);
return this.request({
method: "DELETE",
path: joinPaths(basePath17, organizationId, "domains", domainId)
});
}
};
// src/api/endpoints/OAuthApplicationsApi.ts
var basePath18 = "/oauth_applications";
var OAuthApplicationsApi = class extends AbstractAPI {
async list(params = {}) {
return this.request({
method: "GET",
path: basePath18,
queryParams: params
});
}
async get(oauthApplicationId) {
this.requireId(oauthApplicationId);
return this.request({
method: "GET",
path: joinPaths(basePath18, oauthApplicationId)
});
}
async create(params) {
return this.request({
method: "POST",
path: basePath18,
bodyParams: params
});
}
async update(params) {
const { oauthApplicationId, ...bodyParams } = params;
this.requireId(oauthApplicationId);
return this.request({
method: "PATCH",
path: joinPaths(basePath18, oauthApplicationId),
bodyParams
});
}
async delete(oauthApplicationId) {
this.requireId(oauthApplicationId);
return this.request({
method: "DELETE",
path: joinPaths(basePath18, oauthApplicationId)
});
}
async rotateSecret(oauthApplicationId) {
this.requireId(oauthApplicationId);
return this.request({
method: "POST",
path: joinPaths(basePath18, oauthApplicationId, "rotate_secret")
});
}
};
// src/api/endpoints/PhoneNumberApi.ts
var basePath19 = "/phone_numbers";
var PhoneNumberAPI = class extends AbstractAPI {
async getPhoneNumber(phoneNumberId) {
this.requireId(phoneNumberId);
return this.request({
method: "GET",
path: joinPaths(basePath19, phoneNumberId)
});
}
async createPhoneNumber(params) {
return this.request({
method: "POST",
path: basePath19,
bodyParams: params
});
}
async updatePhoneNumber(phoneNumberId, params = {}) {
this.requireId(phoneNumberId);
return this.request({
method: "PATCH",
path: joinPaths(basePath19, phoneNumberId),
bodyParams: params
});
}
async deletePhoneNumber(phoneNumberId) {
this.requireId(phoneNumberId);
return this.request({
method: "DELETE",
path: joinPaths(basePath19, phoneNumberId)
});
}
};
// src/api/endpoints/ProxyCheckApi.ts
var basePath20 = "/proxy_checks";
var ProxyCheckAPI = class extends AbstractAPI {
async verify(params) {
return this.request({
method: "POST",
path: basePath20,
bodyParams: params
});
}
};
// src/api/endpoints/RedirectUrlApi.ts
var basePath21 = "/redirect_urls";
var RedirectUrlAPI = class extends AbstractAPI {
async getRedirectUrlList() {
return this.request({
method: "GET",
path: basePath21,
queryParams: { paginated: true }
});
}
async getRedirectUrl(redirectUrlId) {
this.requireId(redirectUrlId);
return this.request({
method: "GET",
path: joinPaths(basePath21, redirectUrlId)
});
}
async createRedirectUrl(params) {
return this.request({
method: "POST",
path: basePath21,
bodyParams: params
});
}
async deleteRedirectUrl(redirectUrlId) {
this.requireId(redirectUrlId);
return this.request({
method: "DELETE",
path: joinPaths(basePath21, redirectUrlId)
});
}
};
// src/api/endpoints/SamlConnectionApi.ts
var basePath22 = "/saml_connections";
var SamlConnectionAPI = class extends AbstractAPI {
async getSamlConnectionList(params = {}) {
return this.request({
method: "GET",
path: basePath22,
queryParams: params
});
}
async createSamlConnection(params) {
return this.request({
method: "POST",
path: basePath22,
bodyParams: params,
options: {
deepSnakecaseBodyParamKeys: true
}
});
}
async getSamlConnection(samlConnectionId) {
this.requireId(samlConnectionId);
return this.request({
method: "GET",
path: joinPaths(basePath22, samlConnectionId)
});
}
async updateSamlConnection(samlConnectionId, params = {}) {
this.requireId(samlConnectionId);
return this.request({
method: "PATCH",
path: joinPaths(basePath22, samlConnectionId),
bodyParams: params,
options: {
deepSnakecaseBodyParamKeys: true
}
});
}
async deleteSamlConnection(samlConnectionId) {
this.requireId(samlConnectionId);
return this.request({
method: "DELETE",
path: joinPaths(basePath22, samlConnectionId)
});
}
};
// src/api/endpoints/SessionApi.ts
var basePath23 = "/sessions";
var SessionAPI = class extends AbstractAPI {
async getSessionList(params = {}) {
return this.request({
method: "GET",
path: basePath23,
queryParams: { ...params, paginated: true }
});
}
async getSession(sessionId) {
this.requireId(sessionId);
return this.request({
method: "GET",
path: joinPaths(basePath23, sessionId)
});
}
async createSession(params) {
return this.request({
method: "POST",
path: basePath23,
bodyParams: params
});
}
async revokeSession(sessionId) {
this.requireId(sessionId);
return this.request({
method: "POST",
path: joinPaths(basePath23, sessionId, "revoke")
});
}
async verifySession(sessionId, token) {
this.requireId(sessionId);
return this.request({
method: "POST",
path: joinPaths(basePath23, sessionId, "verify"),
bodyParams: { token }
});
}
/**
* Retrieves a session token or generates a JWT using a specified template.
*
* @param sessionId - The ID of the session for which to generate the token
* @param template - Optional name of the JWT template configured in the Clerk Dashboard.
* @param expiresInSeconds - Optional expiration time for the token in seconds.
* If not provided, uses the default expiration.
*
* @returns A promise that resolves to the generated token
*
* @throws {Error} When sessionId is invalid or empty
*/
async getToken(sessionId, template, expiresInSeconds) {
this.requireId(sessionId);
const path = template ? joinPaths(basePath23, sessionId, "tokens", template) : joinPaths(basePath23, sessionId, "tokens");
const requestOptions = {
method: "POST",
path
};
if (expiresInSeconds !== void 0) {
requestOptions.bodyParams = { expires_in_seconds: expiresInSeconds };
}
return this.request(requestOptions);
}
async refreshSession(sessionId, params) {
this.requireId(sessionId);
const { suffixed_cookies, ...restParams } = params;
return this.request({
method: "POST",
path: joinPaths(basePath23, sessionId, "refresh"),
bodyParams: restParams,
queryParams: { suffixed_cookies }
});
}
};
// src/api/endpoints/SignInTokenApi.ts
var basePath24 = "/sign_in_tokens";
var SignInTokenAPI = class extends AbstractAPI {
async createSignInToken(params) {
return this.request({
method: "POST",
path: basePath24,
bodyParams: params
});
}
async revokeSignInToken(signInTokenId) {
this.requireId(signInTokenId);
return this.request({
method: "POST",
path: joinPaths(basePath24, signInTokenId, "revoke")
});
}
};
// src/api/endpoints/SignUpApi.ts
var basePath25 = "/sign_ups";
var SignUpAPI = class extends AbstractAPI {
async get(signUpAttemptId) {
this.requireId(signUpAttemptId);
return this.request({
method: "GET",
path: joinPaths(basePath25, signUpAttemptId)
});
}
async update(params) {
const { signUpAttemptId, ...bodyParams } = params;
return this.request({
method: "PATCH",
path: joinPaths(basePath25, signUpAttemptId),
bodyParams
});
}
};
// src/api/endpoints/TestingTokenApi.ts
var basePath26 = "/testing_tokens";
var TestingTokenAPI = class extends AbstractAPI {
async createTestingToken() {
return this.request({
method: "POST",
path: basePath26
});
}
};
// src/util/shared.ts
var import_url = require("@clerk/shared/url");
var import_retry = require("@clerk/shared/retry");
var import_keys = require("@clerk/shared/keys");
var import_deprecated = require("@clerk/shared/deprecated");
var import_error = require("@clerk/shared/error");
var import_keys2 = require("@clerk/shared/keys");
var errorThrower = (0, import_error.buildErrorThrower)({ packageName: "@clerk/backend" });
var { isDevOrStagingUrl } = (0, import_keys2.createDevOrStagingUrlCache)();
// src/api/endpoints/UserApi.ts
var basePath27 = "/users";
var UserAPI = class extends AbstractAPI {
async getUserList(params = {}) {
const { limit, offset, orderBy, ...userCountParams } = params;
const [data, totalCount] = await Promise.all([
this.request({
method: "GET",
path: basePath27,
queryParams: params
}),
this.getCount(userCountParams)
]);
return { data, totalCount };
}
async getUser(userId) {
this.requireId(userId);
return this.request({
method: "GET",
path: joinPaths(basePath27, userId)
});
}
async createUser(params) {
return this.request({
method: "POST",
path: basePath27,
bodyParams: params
});
}
async updateUser(userId, params = {}) {
this.requireId(userId);
return this.request({
method: "PATCH",
path: joinPaths(basePath27, userId),
bodyParams: params
});
}
async updateUserProfileImage(userId, params) {
this.requireId(userId);
const formData = new runtime.FormData();
formData.append("file", params?.file);
return this.request({
method: "POST",
path: joinPaths(basePath27, userId, "profile_image"),
formData
});
}
async updateUserMetadata(userId, params) {
this.requireId(userId);
return this.request({
method: "PATCH",
path: joinPaths(basePath27, userId, "metadata"),
bodyParams: params
});
}
async deleteUser(userId) {
this.requireId(userId);
return this.request({
method: "DELETE",
path: joinPaths(basePath27, userId)
});
}
async getCount(params = {}) {
return this.request({
method: "GET",
path: joinPaths(basePath27, "count"),
queryParams: params
});
}
async getUserOauthAccessToken(userId, provider) {
this.requireId(userId);
const hasPrefix = provider.startsWith("oauth_");
const _provider = hasPrefix ? provider : `oauth_${provider}`;
if (hasPrefix) {
(0, import_deprecated.deprecated)(
"getUserOauthAccessToken(userId, provider)",
"Remove the `oauth_` prefix from the `provider` argument."
);
}
return this.request({
method: "GET",
path: joinPaths(basePath27, userId, "oauth_access_tokens", _provider),
queryParams: { paginated: true }
});
}
async disableUserMFA(userId) {
this.requireId(userId);
return this.request({
method: "DELETE",
path: joinPaths(basePath27, userId, "mfa")
});
}
async getOrganizationMembershipList(params) {
const { userId, limit, offset } = params;
this.requireId(userId);
return this.request({
method: "GET",
path: joinPaths(basePath27, userId, "organization_memberships"),
queryParams: { limit, offset }
});
}
async getOrganizationInvitationList(params) {
const { userId, ...queryParams } = params;
this.requireId(userId);
return this.request({
method: "GET",
path: joinPaths(basePath27, userId, "organization_invitations"),
queryParams
});
}
async verifyPassword(params) {
const { userId, password } = params;
this.requireId(userId);
return this.request({
method: "POST",
path: joinPaths(basePath27, userId, "verify_password"),
bodyParams: { password }
});
}
async verifyTOTP(params) {
const { userId, code } = params;
this.requireId(userId);
return this.request({
method: "POST",
path: joinPaths(basePath27, userId, "verify_totp"),
bodyParams: { code }
});
}
async banUser(userId) {
this.requireId(userId);
return this.request({
method: "POST",
path: joinPaths(basePath27, userId, "ban")
});
}
async unbanUser(userId) {
this.requireId(userId);
return this.request({
method: "POST",
path: joinPaths(basePath27, userId, "unban")
});
}
async lockUser(userId) {
this.requireId(userId);
return this.request({
method: "POST",
path: joinPaths(basePath27, userId, "lock")
});
}
async unlockUser(userId) {
this.requireId(userId);
return this.request({
method: "POST",
path: joinPaths(basePath27, userId, "unlock")
});
}
async deleteUserProfileImage(userId) {
this.requireId(userId);
return this.request({
method: "DELETE",
path: joinPaths(basePath27, userId, "profile_image")
});
}
async deleteUserPasskey(params) {
this.requireId(params.userId);
this.requireId(params.passkeyIdentificationId);
return this.request({
method: "DELETE",
path: joinPaths(basePath27, params.userId, "passkeys", params.passkeyIdentificationId)
});
}
async deleteUserWeb3Wallet(params) {
this.requireId(params.userId);
this.requireId(params.web3WalletIdentificationId);
return this.request({
method: "DELETE",
path: joinPaths(basePath27, params.userId, "web3_wallets", params.web3WalletIdentificationId)
});
}
async deleteUserExternalAccount(params) {
this.requireId(params.userId);
this.requireId(params.externalAccountId);
return this.request({
method: "DELETE",
path: joinPaths(basePath27, params.userId, "external_accounts", params.externalAccountId)
});
}
async deleteUserBackupCodes(userId) {
this.requireId(userId);
return this.request({
method: "DELETE",
path: joinPaths(basePath27, userId, "backup_code")
});
}
async deleteUserTOTP(userId) {
this.requireId(userId);
return this.request({
method: "DELETE",
path: joinPaths(basePath27, userId, "totp")
});
}
};
// src/api/endpoints/WaitlistEntryApi.ts
var basePath28 = "/waitlist_entries";
var WaitlistEntryAPI = class extends AbstractAPI {
async list(params = {}) {
return this.request({
method: "GET",
path: basePath28,
queryParams: params
});
}
async create(params) {
return this.request({
method: "POST",
path: basePath28,
bodyParams: params
});
}
};
// src/api/endpoints/WebhookApi.ts
var basePath29 = "/webhooks";
var WebhookAPI = class extends AbstractAPI {
async createSvixApp() {
return this.request({
method: "POST",
path: joinPaths(basePath29, "svix")
});
}
async generateSvixAuthURL() {
return this.request({
method: "POST",
path: joinPaths(basePath29, "svix_url")
});
}
async deleteSvixApp() {
return this.request({
method: "DELETE",
path: joinPaths(basePath29, "svix")
});
}
};
// src/api/endpoints/BillingApi.ts
var basePath30 = "/commerce";
var BillingAPI = class extends AbstractAPI {
/**
* @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 the SDK version to avoid breaking changes.
*/
async getPlanList(params) {
return this.request({
method: "GET",
path: joinPaths(basePath30, "plans"),
queryParams: params
});
}
};
// src/api/request.ts
var import_error2 = require("@clerk/shared/error");
// ../../node_modules/.pnpm/map-obj@5.0.2/node_modules/map-obj/index.js
var isObject = (value) => typeof value === "object" && value !== null;
var isObjectCustom = (value) => isObject(value) && !(value instanceof RegExp) && !(value instanceof Error) && !(value instanceof Date) && !(globalThis.Blob && value instanceof globalThis.Blob);
var mapObjectSkip = Symbol("mapObjectSkip");
var _mapObject = (object, mapper, options, isSeen = /* @__PURE__ */ new WeakMap()) => {
options = {
deep: false,
target: {},
...options
};
if (isSeen.has(object)) {
return isSeen.get(object);
}
isSeen.set(object, options.target);
const { target } = options;
delete options.target;
const mapArray = (array) => array.map((element) => isObjectCustom(element) ? _mapObject(element, mapper, options, isSeen) : element);
if (Array.isArray(object)) {
return mapArray(object);
}
for (const [key, value] of Object.entries(object)) {
const mapResult = mapper(key, value, object);
if (mapResult === mapObjectSkip) {
continue;
}
let [newKey, newValue, { shouldRecurse = true } = {}] = mapResult;
if (newKey === "__proto__") {
continue;
}
if (options.deep && shouldRecurse && isObjectCustom(newValue)) {
newValue = Array.isArray(newValue) ? mapArray(newValue) : _mapObject(newValue, mapper, options, isSeen);
}
target[newKey] = newValue;
}
return target;
};
function mapObject(object, mapper, options) {
if (!isObject(object)) {
throw new TypeError(`Expected an object, got \`${object}\` (${typeof object})`);
}
if (Array.isArray(object)) {
throw new TypeError("Expected an object, got an array");
}
return _mapObject(object, mapper, options);
}
// ../../node_modules/.pnpm/change-case@5.4.4/node_modules/change-case/dist/index.js
var SPLIT_LOWER_UPPER_RE = /([\p{Ll}\d])(\p{Lu})/gu;
var SPLIT_UPPER_UPPER_RE = /(\p{Lu})([\p{Lu}][\p{Ll}])/gu;
var SPLIT_SEPARATE_NUMBER_RE = /(\d)\p{Ll}|(\p{L})\d/u;
var DEFAULT_STRIP_REGEXP = /[^\p{L}\d]+/giu;
var SPLIT_REPLACE_VALUE = "$1\0$2";
var DEFAULT_PREFIX_SUFFIX_CHARACTERS = "";
function split(value) {
let result = value.trim();
result = result.replace(SPLIT_LOWER_UPPER_RE, SPLIT_REPLACE_VALUE).replace(SPLIT_UPPER_UPPER_RE, SPLIT_REPLACE_VALUE);
result = result.replace(DEFAULT_STRIP_REGEXP, "\0");
let start = 0;
let end = result.length;
while (result.charAt(start) === "\0")
start++;
if (start === end)
return [];
while (result.charAt(end - 1) === "\0")
end--;
return result.slice(start, end).split(/\0/g);
}
function splitSeparateNumbers(value) {
const words = split(value);
for (let i = 0; i < words.length; i++) {
const word = words[i];
const match2 = SPLIT_SEPARATE_NUMBER_RE.exec(word);
if (match2) {
const offset = match2.index + (match2[1] ?? match2[2]).length;
words.splice(i, 1, word.slice(0, offset), word.slice(offset));
}
}
return words;
}
function noCase(input, options) {
const [prefix, words, suffix] = splitPrefixSuffix(input, options);
return prefix + words.map(lowerFactory(options?.locale)).join(options?.delimiter ?? " ") + suffix;
}
function snakeCase(input, options) {
return noCase(input, { delimiter: "_", ...options });
}
function lowerFactory(locale) {
return locale === false ? (input) => input.toLowerCase() : (input) => input.toLocaleLowerCase(locale);
}
function splitPrefixSuffix(input, options = {}) {
const splitFn = options.split ?? (options.separateNumbers ? splitSeparateNumbers : split);
const prefixCharacters = options.prefixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS;
const suffixCharacters = options.suffixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS;
let prefixIndex = 0;
let suffixIndex = input.length;
while (prefixIndex < input.length) {
const char = input.charAt(prefixIndex);
if (!prefixCharacters.includes(char))
break;
prefixIndex++;
}
while (suffixIndex > prefixIndex) {
const index = suffixIndex - 1;
const char = input.charAt(index);
if (!suffixCharacters.includes(char))
break;
suffixIndex = index;
}
return [
input.slice(0, prefixIndex),
splitFn(input.slice(prefixIndex, suffixIndex)),
input.slice(suffixIndex)
];
}
// ../../node_modules/.pnpm/snakecase-keys@9.0.2/node_modules/snakecase-keys/index.js
var PlainObjectConstructor = {}.constructor;
function snakecaseKeys(obj, options) {
if (Array.isArray(obj)) {
if (obj.some((item) => item.constructor !== PlainObjectConstructor)) {
throw new Error("obj must be array of plain objects");
}
options = { deep: true, exclude: [], parsingOptions: {}, ...options };
const convertCase2 = options.snakeCase || ((key) => snakeCase(key, options.parsingOptions));
return obj.map((item) => {
return mapObject(item, (key, val) => {
return [
matches(options.exclude, key) ? key : convertCase2(key),
val,
mapperOptions(key, val, options)
];
}, options);
});
} else {
if (obj.constructor !== PlainObjectConstructor) {
throw new Error("obj must be an plain object");
}
}
options = { deep: true, exclude: [], parsingOptions: {}, ...options };
const convertCase = options.snakeCase || ((key) => snakeCase(key, options.parsingOptions));
return mapObject(obj, (key, val) => {
return [
matches(options.exclude, key) ? key : convertCase(key),
val,
mapperOptions(key, val, options)
];
}, options);
}
function matches(patterns, value) {
return patterns.some((pattern) => {
return typeof pattern === "string" ? pattern === value : pattern.test(value);
});
}
function mapperOptions(key, val, options) {
return options.shouldRecurse ? { shouldRecurse: options.shouldRecurse(key, val) } : void 0;
}
var snakecase_keys_default = snakecaseKeys;
// src/constants.ts
var API_URL = "https://api.clerk.com";
var API_VERSION = "v1";
var USER_AGENT = `${"@clerk/backend"}@${"2.9.4"}`;
var MAX_CACHE_LAST_UPDATED_AT_SECONDS = 5 * 60;
var SUPPORTED_BAPI_VERSION = "2025-04-10";
var Attributes = {
AuthToken: "__clerkAuthToken",
AuthSignature: "__clerkAuthSignature",
AuthStatus: "__clerkAuthStatus",
AuthReason: "__clerkAuthReason",
AuthMessage: "__clerkAuthMessage",
ClerkUrl: "__clerkUrl"
};
var Cookies = {
Session: "__session",
Refresh: "__refresh",
ClientUat: "__client_uat",
Handshake: "__clerk_handshake",
DevBrowser: "__clerk_db_jwt",
RedirectCount: "__clerk_redirect_count",
HandshakeNonce: "__clerk_handshake_nonce"
};
var QueryParameters = {
ClerkSynced: "__clerk_synced",
SuffixedCookies: "suffixed_cookies",
ClerkRedirectUrl: "__clerk_redirect_url",
// use the reference to Cookies to indicate that it's the same value
DevBrowser: Cookies.DevBrowser,
Handshake: Cookies.Handshake,
HandshakeHelp: "__clerk_help",
LegacyDevBrowser: "__dev_session",
HandshakeReason: "__clerk_hs_reason",
HandshakeNonce: Cookies.HandshakeNonce,
HandshakeFormat: "format"
};
var Headers2 = {
Accept: "accept",
AuthMessage: "x-clerk-auth-message",
Authorization: "authorization",
AuthReason: "x-clerk-auth-reason",
AuthSignature: "x-clerk-auth-signature",
AuthStatus: "x-clerk-auth-status",
AuthToken: "x-clerk-auth-token",
CacheControl: "cache-control",
ClerkRedirectTo: "x-clerk-redirect-to",
ClerkRequestData: "x-clerk-request-data",
ClerkUrl: "x-clerk-clerk-url",
CloudFrontForwardedProto: "cloudfront-forwarded-proto",
ContentType: "content-type",
ContentSecurityPolicy: "content-security-policy",
ContentSecurityPolicyReportOnly: "content-security-policy-report-only",
EnableDebug: "x-clerk-debug",
ForwardedHost: "x-forwarded-host",
ForwardedPort: "x-forwarded-port",
ForwardedProto: "x-forwarded-proto",
Host: "host",
Location: "location",
Nonce: "x-nonce",
Origin: "origin",
Referrer: "referer",
SecFetchDest: "sec-fetch-dest",
SecFetchSite: "sec-fetch-site",
UserAgent: "user-agent",
ReportingEndpoints: "reporting-endpoints"
};
var ContentTypes = {
Json: "application/json"
};
var constants = {
Attributes,
Cookies,
Headers: Headers2,
ContentTypes,
QueryParameters
};
// src/util/optionsAssertions.ts
function assertValidSecretKey(val) {
if (!val || typeof val !== "string") {
throw Error("Missing Clerk Secret Key. Go to https://dashboard.clerk.com and get your key for your instance.");
}
}
function assertValidPublishableKey(val) {
(0, import_keys.parsePublishableKey)(val, { fatal: true });
}
// src/api/resources/AccountlessApplication.ts
var AccountlessApplication = class _AccountlessApplication {
constructor(publishableKey, secretKey, claimUrl, apiKeysUrl) {
this.publishableKey = publishableKey;
this.secretKey = secretKey;
this.claimUrl = claimUrl;
this.apiKeysUrl = apiKeysUrl;
}
static fromJSON(data) {
return new _AccountlessApplication(data.publishable_key, data.secret_key, data.claim_url, data.api_keys_url);
}
};
// src/api/resources/ActorToken.ts
var ActorToken = class _ActorToken {
constructor(id, status, userId, actor, token, url, createdAt, updatedAt) {
this.id = id;
this.status = status;
this.userId = userId;
this.actor = actor;
this.token = token;
this.url = url;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
}
static fromJSON(data) {
return new _ActorToken(
data.id,
data.status,
data.user_id,
data.actor,
data.token,
data.url,
data.created_at,
data.updated_at
);
}
};
// src/api/resources/AllowlistIdentifier.ts
var AllowlistIdentifier = class _AllowlistIdentifier {
constructor(id, identifier, identifierType, createdAt, updatedAt, instanceId, invitationId) {
this.id = id;
this.identifier = identifier;
this.identifierType = identifierType;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
this.instanceId = instanceId;
this.invitationId = invitationId;
}
static fromJSON(data) {
return new _AllowlistIdentifier(
data.id,
data.identifier,
data.identifier_type,
data.created_at,
data.updated_at,
data.instance_id,
data.invitation_id
);
}
};
// src/api/resources/APIKey.ts
var APIKey = class _APIKey {
constructor(id, type, name, subject, scopes, claims, revoked, revocationReason, expired, expiration, createdBy, description, lastUsedAt, createdAt, updatedAt, secret) {
this.id = id;
this.type = type;
this.name = name;
this.subject = subject;
this.scopes = scopes;
this.claims = claims;
this.revoked = revoked;
this.revocationReason = revocationReason;
this.expired = expired;
this.expiration = expiration;
this.createdBy = createdBy;
this.description = description;
this.lastUsedAt = lastUsedAt;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
this.secret = secret;
}
static fromJSON(data) {
return new _APIKey(
data.id,
data.type,
data.name,
data.subject,
data.scopes,
data.claims,
data.revoked,
data.revocation_reason,
data.expired,
data.expiration,
data.created_by,
data.description,
data.last_used_at,
data.created_at,
data.updated_at,
data.secret
);
}
};
// src/api/resources/BlocklistIdentifier.ts
var BlocklistIdentifier = class _BlocklistIdentifier {
constructor(id, identifier, identifierType, createdAt, updatedAt, instanceId) {
this.id = id;
this.identifier = identifier;
this.identifierType = identifierType;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
this.instanceId = instanceId;
}
static fromJSON(data) {
return new _BlocklistIdentifier(
data.id,
data.identifier,
data.identifier_type,
data.created_at,
data.updated_at,
data.instance_id
);
}
};
// src/api/resources/Session.ts
var SessionActivity = class _SessionActivity {
constructor(id, isMobile, ipAddress, city, co