@clerk/backend
Advanced tools
Comparing version 0.4.0-staging.7 to 0.4.0-staging.8
@@ -1,2 +0,2 @@ | ||
var f=class{constructor(e){this.request=e}requireId(e){if(!e)throw new Error("A valid resource ID is required.")}};var Je="/",wt=new RegExp(Je+"{1,}","g");function a(...t){return t.filter(e=>e).join(Je).replace(wt,Je)}var xe="/allowlist_identifiers",se=class extends f{async getAllowlistIdentifierList(){return this.request({method:"GET",path:xe})}async createAllowlistIdentifier(e){return this.request({method:"POST",path:xe,bodyParams:e})}async deleteAllowlistIdentifier(e){return this.requireId(e),this.request({method:"DELETE",path:a(xe,e)})}};var Re="/clients",oe=class extends f{async getClientList(){return this.request({method:"GET",path:Re})}async getClient(e){return this.requireId(e),this.request({method:"GET",path:a(Re,e)})}verifyClient(e){return this.request({method:"POST",path:a(Re,"verify"),bodyParams:{token:e}})}};var ae="/email_addresses",le=class extends f{async getEmailAddress(e){return this.requireId(e),this.request({method:"GET",path:a(ae,e)})}async createEmailAddress(e){return this.request({method:"POST",path:ae,bodyParams:e})}async updateEmailAddress(e,r={}){return this.requireId(e),this.request({method:"PATCH",path:a(ae,e),bodyParams:r})}async deleteEmailAddress(e){return this.requireId(e),this.request({method:"DELETE",path:a(ae,e)})}};var Pt="/emails",ue=class extends f{async createEmail(e){return this.request({method:"POST",path:Pt,bodyParams:e})}};var de=class extends f{async getInterstitial(){return this.request({path:"internal/interstitial",method:"GET",headerParams:{"Content-Type":"text/html"}})}};var Te="/invitations",ce=class extends f{async getInvitationList(){return this.request({method:"GET",path:Te})}async createInvitation(e){return this.request({method:"POST",path:Te,bodyParams:e})}async revokeInvitation(e){return this.requireId(e),this.request({method:"POST",path:a(Te,e,"revoke")})}};var J="/organizations",pe=class extends f{async getOrganizationList(e){return this.request({method:"GET",path:J,queryParams:e})}async createOrganization(e){return this.request({method:"POST",path:J,bodyParams:e})}async getOrganization(e){let r="organizationId"in e?e.organizationId:e.slug;return this.requireId(r),this.request({method:"GET",path:a(J,r)})}async updateOrganization(e,r){return this.requireId(e),this.request({method:"PATCH",path:a(J,e),bodyParams:r})}async updateOrganizationMetadata(e,r){return this.requireId(e),this.request({method:"PATCH",path:a(J,e,"metadata"),bodyParams:r})}async deleteOrganization(e){return this.request({method:"DELETE",path:a(J,e)})}async getOrganizationMembershipList(e){let{organizationId:r,limit:n,offset:i}=e;return this.requireId(r),this.request({method:"GET",path:a(J,r,"memberships"),queryParams:{limit:n,offset:i}})}async createOrganizationMembership(e){let{organizationId:r,userId:n,role:i}=e;return this.requireId(r),this.request({method:"POST",path:a(J,r,"memberships"),bodyParams:{userId:n,role:i}})}async updateOrganizationMembership(e){let{organizationId:r,userId:n,role:i}=e;return this.requireId(r),this.request({method:"PATCH",path:a(J,r,"memberships",n),bodyParams:{role:i}})}async updateOrganizationMembershipMetadata(e){let{organizationId:r,userId:n,publicMetadata:i,privateMetadata:o}=e;return this.request({method:"PATCH",path:a(J,r,"memberships",n,"metadata"),bodyParams:{publicMetadata:i,privateMetadata:o}})}async deleteOrganizationMembership(e){let{organizationId:r,userId:n}=e;return this.requireId(r),this.request({method:"DELETE",path:a(J,r,"memberships",n)})}async getPendingOrganizationInvitationList(e){let{organizationId:r,limit:n,offset:i}=e;return this.requireId(r),this.request({method:"GET",path:a(J,r,"invitations","pending"),queryParams:{limit:n,offset:i}})}async createOrganizationInvitation(e){let{organizationId:r,...n}=e;return this.requireId(r),this.request({method:"POST",path:a(J,r,"invitations"),bodyParams:{...n}})}async revokeOrganizationInvitation(e){let{organizationId:r,invitationId:n,requestingUserId:i}=e;return this.requireId(r),this.request({method:"POST",path:a(J,r,"invitations",n,"revoke"),bodyParams:{requestingUserId:i}})}};var me="/phone_numbers",ge=class extends f{async getPhoneNumber(e){return this.requireId(e),this.request({method:"GET",path:a(me,e)})}async createPhoneNumber(e){return this.request({method:"POST",path:me,bodyParams:e})}async updatePhoneNumber(e,r={}){return this.requireId(e),this.request({method:"PATCH",path:a(me,e),bodyParams:r})}async deletePhoneNumber(e){return this.requireId(e),this.request({method:"DELETE",path:a(me,e)})}};var fe="/redirect_urls",he=class extends f{async getRedirectUrlList(){return this.request({method:"GET",path:fe})}async getRedirectUrl(e){return this.requireId(e),this.request({method:"GET",path:a(fe,e)})}async createRedirectUrl(e){return this.request({method:"POST",path:fe,bodyParams:e})}async deleteRedirectUrl(e){return this.requireId(e),this.request({method:"DELETE",path:a(fe,e)})}};var te="/sessions",ye=class extends f{constructor(){super(...arguments);this.getSessionList=async r=>this.request({method:"GET",path:te,queryParams:r});this.getSession=async r=>(this.requireId(r),this.request({method:"GET",path:a(te,r)}));this.revokeSession=async r=>(this.requireId(r),this.request({method:"POST",path:a(te,r,"revoke")}));this.verifySession=async(r,n)=>(this.requireId(r),this.request({method:"POST",path:a(te,r,"verify"),bodyParams:{token:n}}));this.getToken=async(r,n)=>(this.requireId(r),(await this.request({method:"POST",path:a(te,r,"tokens",n||"")})).jwt)}};var Le="/sign_in_tokens",be=class extends f{async createSignInToken(e){return this.request({method:"POST",path:Le,bodyParams:e})}async revokeSignInToken(e){return this.requireId(e),this.request({method:"POST",path:a(Le,e,"revoke")})}};var Jt="/sms_messages",Se=class extends f{async createSMSMessage(e){return this.request({method:"POST",path:Jt,bodyParams:e})}};var R="/users",Oe=class extends f{async getUserList(e={}){return this.request({method:"GET",path:R,queryParams:e})}async getUser(e){return this.requireId(e),this.request({method:"GET",path:a(R,e)})}async createUser(e){return this.request({method:"POST",path:R,bodyParams:e})}async updateUser(e,r={}){return this.requireId(e),this.request({method:"PATCH",path:a(R,e),bodyParams:r})}async updateUserMetadata(e,r){return this.requireId(e),this.request({method:"PATCH",path:a(R,e,"metadata"),bodyParams:r})}async deleteUser(e){return this.requireId(e),this.request({method:"DELETE",path:a(R,e)})}async getCount(e={}){return this.request({method:"GET",path:a(R,"count"),queryParams:e})}async getUserOauthAccessToken(e,r){return this.requireId(e),this.request({method:"GET",path:a(R,e,"oauth_access_tokens",r)})}async disableUserMFA(e){return this.requireId(e),this.request({method:"DELETE",path:a(R,e,"mfa")})}async getOrganizationMembershipList(e){let{userId:r,limit:n,offset:i}=e;return this.requireId(r),this.request({method:"GET",path:a(R,r,"organization_memberships"),queryParams:{limit:n,offset:i}})}};import zt from"deepmerge";import $e from"snakecase-keys";var C="https://api.clerk.dev",T="v1",Fe="@clerk/backend",xt={AuthStatus:"__clerkAuthStatus"},Rt={Session:"__session",ClientUat:"__client_uat"},Ve={AuthStatus:"x-clerk-auth-status",AuthReason:"x-clerk-auth-reason",AuthMessage:"x-clerk-auth-message",Authorization:"authorization",ForwardedPort:"x-forwarded-port",ForwardedHost:"x-forwarded-host",Referrer:"referer",UserAgent:"user-agent",Origin:"origin",Host:"host"},Tt={AuthStatus:Ve.AuthStatus},Nt={Attributes:xt,Cookies:Rt,Headers:Ve,SearchParams:Tt};import Ct from"#crypto";import vt from"#fetch";var Et={crypto:Ct,fetch:vt},N=Et;var K=class{constructor(e,r,n,i,o){this.id=e;this.identifier=r;this.createdAt=n;this.updatedAt=i;this.invitationId=o}static fromJSON(e){return new K(e.id,e.identifier,e.created_at,e.updated_at,e.invitation_id)}};var v=class{constructor(e,r,n,i,o,u,m,g,O){this.id=e;this.clientId=r;this.userId=n;this.status=i;this.lastActiveAt=o;this.expireAt=u;this.abandonAt=m;this.createdAt=g;this.updatedAt=O}static fromJSON(e){return new v(e.id,e.client_id,e.user_id,e.status,e.last_active_at,e.expire_at,e.abandon_at,e.created_at,e.updated_at)}};var j=class{constructor(e,r,n,i,o,u,m,g){this.id=e;this.sessionIds=r;this.sessions=n;this.signInId=i;this.signUpId=o;this.lastActiveSessionId=u;this.createdAt=m;this.updatedAt=g}static fromJSON(e){return new j(e.id,e.session_ids,e.sessions.map(r=>v.fromJSON(r)),e.sign_in_id,e.sign_up_id,e.last_active_session_id,e.created_at,e.updated_at)}};var W=class{constructor(e,r,n,i){this.object=e;this.id=r;this.slug=n;this.deleted=i}static fromJSON(e){return new W(e.object,e.id||null,e.slug||null,e.deleted)}};var L=class{constructor(e,r,n,i,o,u,m){this.id=e;this.fromEmailName=r;this.emailAddressId=n;this.toEmailAddress=i;this.subject=o;this.body=u;this.status=m}static fromJSON(e){return new L(e.id,e.from_email_name,e.email_address_id,e.to_email_address,e.subject,e.body,e.status)}};var E=class{constructor(e,r){this.id=e;this.type=r}static fromJSON(e){return new E(e.id,e.type)}};var x=class{constructor(e,r,n=null,i=null,o=null,u=null){this.status=e;this.strategy=r;this.externalVerificationRedirectURL=n;this.attempts=i;this.expireAt=o;this.nonce=u}static fromJSON(e){return new x(e.status,e.strategy,e.external_verification_redirect_url?new URL(e.external_verification_redirect_url):null,e.attempts,e.expire_at,e.nonce)}};var q=class{constructor(e,r,n,i){this.id=e;this.emailAddress=r;this.verification=n;this.linkedTo=i}static fromJSON(e){return new q(e.id,e.email_address,e.verification&&x.fromJSON(e.verification),e.linked_to.map(r=>E.fromJSON(r)))}};var F=class{constructor(e,r,n,i,o,u,m,g,O,_,k={},P,b){this.id=e;this.provider=r;this.identificationId=n;this.externalId=i;this.approvedScopes=o;this.emailAddress=u;this.firstName=m;this.lastName=g;this.picture=O;this.username=_;this.publicMetadata=k;this.label=P;this.verification=b}static fromJSON(e){return new F(e.id,e.provider,e.identification_id,e.provider_user_id,e.approved_scopes,e.email_address,e.first_name,e.last_name,e.avatar_url,e.username,e.public_metadata,e.label,e.verification&&x.fromJSON(e.verification))}};var V=class{constructor(e,r,n,i,o,u){this.id=e;this.emailAddress=r;this.publicMetadata=n;this.createdAt=i;this.updatedAt=o;this.revoked=u}static fromJSON(e){return new V(e.id,e.email_address,e.public_metadata,e.created_at,e.updated_at,e.revoked)}};var De=(c=>(c.AllowlistIdentifier="allowlist_identifier",c.Client="client",c.Email="email",c.EmailAddress="email_address",c.ExternalAccount="external_account",c.FacebookAccount="facebook_account",c.GoogleAccount="google_account",c.Invitation="invitation",c.OauthAccessToken="oauth_access_token",c.Organization="organization",c.OrganizationInvitation="organization_invitation",c.OrganizationMembership="organization_membership",c.PhoneNumber="phone_number",c.RedirectUrl="redirect_url",c.Session="session",c.SignInAttempt="sign_in_attempt",c.SignInToken="sign_in_token",c.SignUpAttempt="sign_up_attempt",c.SmsMessage="sms_message",c.User="user",c.Web3Wallet="web3_wallet",c.Token="token",c.TotalCount="total_count",c))(De||{});var D=class{constructor(e,r,n={},i,o,u){this.provider=e;this.token=r;this.publicMetadata=n;this.label=i;this.scopes=o;this.tokenSecret=u}static fromJSON(e){return new D(e.provider,e.token,e.public_metadata,e.label,e.scopes,e.token_secret)}};var U=class{constructor(e,r,n,i,o,u,m={},g={}){this.id=e;this.name=r;this.slug=n;this.logoUrl=i;this.createdAt=o;this.updatedAt=u;this.publicMetadata=m;this.privateMetadata=g}static fromJSON(e){return new U(e.id,e.name,e.slug,e.logo_url,e.created_at,e.updated_at,e.public_metadata,e.private_metadata)}};var G=class{constructor(e,r,n,i,o,u,m){this.id=e;this.emailAddress=r;this.role=n;this.organizationId=i;this.createdAt=o;this.updatedAt=u;this.status=m}static fromJSON(e){return new G(e.id,e.email_address,e.role,e.organization_id,e.created_at,e.updated_at,e.status)}};var $=class{constructor(e,r,n={},i={},o,u,m,g){this.id=e;this.role=r;this.publicMetadata=n;this.privateMetadata=i;this.createdAt=o;this.updatedAt=u;this.organization=m;this.publicUserData=g}static fromJSON(e){return new $(e.id,e.role,e.public_metadata,e.private_metadata,e.created_at,e.updated_at,U.fromJSON(e.organization),re.fromJSON(e.public_user_data))}},re=class{constructor(e,r,n,i,o){this.identifier=e;this.firstName=r;this.lastName=n;this.profileImageUrl=i;this.userId=o}static fromJSON(e){return new re(e.identifier,e.first_name,e.last_name,e.profile_image_url,e.user_id)}};var z=class{constructor(e,r,n,i,o,u){this.id=e;this.phoneNumber=r;this.reservedForSecondFactor=n;this.defaultSecondFactor=i;this.verification=o;this.linkedTo=u}static fromJSON(e){return new z(e.id,e.phone_number,e.reserved_for_second_factor,e.default_second_factor,e.verification&&x.fromJSON(e.verification),e.linked_to.map(r=>E.fromJSON(r)))}};var B=class{constructor(e,r,n,i){this.id=e;this.url=r;this.createdAt=n;this.updatedAt=i}static fromJSON(e){return new B(e.id,e.url,e.created_at,e.updated_at)}};var H=class{constructor(e,r,n,i,o,u){this.id=e;this.userId=r;this.token=n;this.status=i;this.createdAt=o;this.updatedAt=u}static fromJSON(e){return new H(e.id,e.user_id,e.token,e.status,e.created_at,e.updated_at)}};var Y=class{constructor(e,r,n,i,o,u){this.id=e;this.fromPhoneNumber=r;this.toPhoneNumber=n;this.message=i;this.status=o;this.phoneNumberId=u}static fromJSON(e){return new Y(e.id,e.from_phone_number,e.to_phone_number,e.message,e.status,e.phone_number_id)}};var Q=class{constructor(e){this.jwt=e}static fromJSON(e){return new Q(e.jwt)}};var X=class{constructor(e,r,n){this.id=e;this.web3Wallet=r;this.verification=n}static fromJSON(e){return new X(e.id,e.web3_wallet,e.verification&&x.fromJSON(e.verification))}};var Z=class{constructor(e,r,n,i,o,u,m,g,O,_,k,P,b,I,A,w,s,l,p,h={},S={},y={},c=[],M=[],Pe=[],We=[]){this.id=e;this.passwordEnabled=r;this.totpEnabled=n;this.backupCodeEnabled=i;this.twoFactorEnabled=o;this.banned=u;this.createdAt=m;this.updatedAt=g;this.profileImageUrl=O;this.gender=_;this.birthday=k;this.primaryEmailAddressId=P;this.primaryPhoneNumberId=b;this.primaryWeb3WalletId=I;this.lastSignInAt=A;this.externalId=w;this.username=s;this.firstName=l;this.lastName=p;this.publicMetadata=h;this.privateMetadata=S;this.unsafeMetadata=y;this.emailAddresses=c;this.phoneNumbers=M;this.web3Wallets=Pe;this.externalAccounts=We}static fromJSON(e){return new Z(e.id,e.password_enabled,e.totp_enabled,e.backup_code_enabled,e.two_factor_enabled,e.banned,e.created_at,e.updated_at,e.profile_image_url,e.gender,e.birthday,e.primary_email_address_id,e.primary_phone_number_id,e.primary_web3_wallet_id,e.last_sign_in_at,e.external_id,e.username,e.first_name,e.last_name,e.public_metadata,e.private_metadata,e.unsafe_metadata,(e.email_addresses||[]).map(r=>q.fromJSON(r)),(e.phone_numbers||[]).map(r=>z.fromJSON(r)),(e.web3_wallets||[]).map(r=>X.fromJSON(r)),(e.external_accounts||[]).map(r=>F.fromJSON(r)))}};function Ge(t){return Array.isArray(t)?t.map(e=>Ne(e)):qt(t)?t.data.map(e=>Ne(e)):Ne(t)}function qt(t){return t.data!==void 0}function Ut(t){return t.total_count}function Ne(t){if(typeof t!="string"&&"object"in t&&"deleted"in t)return W.fromJSON(t);switch(t.object){case"allowlist_identifier":return K.fromJSON(t);case"client":return j.fromJSON(t);case"email_address":return q.fromJSON(t);case"email":return L.fromJSON(t);case"invitation":return V.fromJSON(t);case"oauth_access_token":return D.fromJSON(t);case"organization":return U.fromJSON(t);case"organization_invitation":return G.fromJSON(t);case"organization_membership":return $.fromJSON(t);case"phone_number":return z.fromJSON(t);case"redirect_url":return B.fromJSON(t);case"sign_in_token":return H.fromJSON(t);case"session":return v.fromJSON(t);case"sms_message":return Y.fromJSON(t);case"token":return Q.fromJSON(t);case"total_count":return Ut(t);case"user":return Z.fromJSON(t);default:return t}}var Mt=t=>async(...e)=>{let{data:r,errors:n,status:i,statusText:o}=await t(...e);if(n===null)return r;throw new ne(o||"",{data:n,status:i||""})};function Be(t){return Mt(async r=>{let{apiKey:n,secretKey:i,apiUrl:o=C,apiVersion:u=T,userAgent:m=Fe,httpOptions:g={}}=t,{path:O,method:_,queryParams:k,headerParams:P,bodyParams:b}=r,I=i||n;if(!I)throw Error("Missing Clerk Secret Key or API Key. Go to https://dashboard.clerk.dev and get your key for your instance.");let A=a(o,u,O),w=new URL(A);if(k){let S=$e({...k});for(let[y,c]of Object.entries(S))c&&[c].flat().forEach(M=>w.searchParams.append(y,M))}let s={Authorization:`Bearer ${I}`,"Content-Type":"application/json","Clerk-Backend-SDK":m,...P},p=_!=="GET"&&b&&Object.keys(b).length>0?{body:JSON.stringify($e(b,{deep:!1}))}:null,h;try{h=await N.fetch(w.href,zt(g,{method:_,headers:s,...p}));let y=await(s&&s["Content-Type"]==="application/json"?h.json():h.text());if(!h.ok)throw y;return{data:Ge(y),errors:null}}catch(S){return S instanceof Error?{data:null,errors:[{code:"unexpected_error",message:S.message||"Unexpected error"}]}:{data:null,errors:Kt(S),status:h?.status,statusText:h?.statusText}}})}function Kt(t){if(!!t&&typeof t=="object"&&"errors"in t){let e=t.errors;return e.length>0?e.map(jt):[]}return[]}function jt(t){return{code:t.code,message:t.message,longMessage:t.long_message,meta:{paramName:t?.meta?.param_name,sessionId:t?.meta?.session_id}}}var ne=class extends Error{constructor(r,{data:n,status:i}){super(r);Object.setPrototypeOf(this,ne.prototype),this.clerkError=!0,this.message=r,this.status=i,this.errors=n}};function ee(t){let e=Be(t);return{allowlistIdentifiers:new se(e),clients:new oe(e),emailAddresses:new le(e),emails:new ue(e),interstitial:new de(e),invitations:new ce(e),organizations:new pe(e),phoneNumbers:new ge(e),redirectUrls:new he(e),sessions:new ye(e),signInTokens:new be(e),smsMessages:new Se(e),users:new Oe(e)}}var Ye=t=>()=>{let e={...t};return e.apiKey=(e.apiKey||"").substring(0,7),e.jwtKey=(e.jwtKey||"").substring(0,7),{...e}};function Qe(t,e,r){let{act:n,sid:i,org_id:o,org_role:u,org_slug:m,sub:g}=t,{apiKey:O,secretKey:_,apiUrl:k,apiVersion:P,token:b,session:I,user:A,organization:w}=e,{sessions:s}=ee({apiKey:O,secretKey:_,apiUrl:k,apiVersion:P}),l=Wt({sessionId:i,sessionToken:b,fetcher:(...p)=>s.getToken(...p)});return{actor:n,sessionClaims:t,sessionId:i,session:I,userId:g,user:A,orgId:o,orgRole:u,orgSlug:m,organization:w,getToken:l,debug:Ye(r)}}function Xe(t){return{sessionClaims:null,sessionId:null,session:null,userId:null,user:null,actor:null,orgId:null,orgRole:null,orgSlug:null,organization:null,getToken:()=>Promise.resolve(null),debug:Ye(t)}}function He(t){return t&&(delete t.privateMetadata,delete t.private_metadata),t}function Ni(t){let e=t.user?{...t.user}:t.user,r=t.organization?{...t.organization}:t.organization;return He(e),He(r),{...t,user:e,organization:r}}var Wt=t=>{let{fetcher:e,sessionToken:r,sessionId:n}=t||{};return async(i={})=>n?i.template?e(n,i.template):r:null};import{parsePublishableKey as tt}from"@clerk/shared";function Lt(t){return new Promise(e=>setTimeout(e,t))}var Ft=5;async function ie(t,e=1,r=Ft){try{return await t()}catch(n){if(e>=r)throw n;return await Lt(2**e*100),ie(t,e+1)}}function ke(t){return t.startsWith("test_")||t.startsWith("sk_test_")}function Ze(t){return t.startsWith("live_")||t.startsWith("sk_live_")}function et(t){return t.endsWith(".lclstage.dev")||t.endsWith(".stgstage.dev")||t.endsWith(".clerkstage.dev")||t.endsWith(".accountsstage.dev")}var d=class extends Error{constructor({action:r,message:n,reason:i}){super(n);Object.setPrototypeOf(this,d.prototype),this.reason=i,this.message=n,this.action=r}getFullMessage(){return`${[this.message,this.action].filter(r=>r).join(" ")} (reason=${this.reason}, token-carrier=${this.tokenCarrier})`}};function ve(t){let{debugData:e,frontendApi:r,pkgVersion:n,publishableKey:i}=t;return` | ||
var h=class{constructor(e){this.request=e}requireId(e){if(!e)throw new Error("A valid resource ID is required.")}};var xe="/",Pt=new RegExp(xe+"{1,}","g");function a(...t){return t.filter(e=>e).join(xe).replace(Pt,xe)}var Re="/allowlist_identifiers",oe=class extends h{async getAllowlistIdentifierList(){return this.request({method:"GET",path:Re})}async createAllowlistIdentifier(e){return this.request({method:"POST",path:Re,bodyParams:e})}async deleteAllowlistIdentifier(e){return this.requireId(e),this.request({method:"DELETE",path:a(Re,e)})}};var Te="/clients",ae=class extends h{async getClientList(){return this.request({method:"GET",path:Te})}async getClient(e){return this.requireId(e),this.request({method:"GET",path:a(Te,e)})}verifyClient(e){return this.request({method:"POST",path:a(Te,"verify"),bodyParams:{token:e}})}};var le="/email_addresses",ue=class extends h{async getEmailAddress(e){return this.requireId(e),this.request({method:"GET",path:a(le,e)})}async createEmailAddress(e){return this.request({method:"POST",path:le,bodyParams:e})}async updateEmailAddress(e,r={}){return this.requireId(e),this.request({method:"PATCH",path:a(le,e),bodyParams:r})}async deleteEmailAddress(e){return this.requireId(e),this.request({method:"DELETE",path:a(le,e)})}};var Jt="/emails",de=class extends h{async createEmail(e){return this.request({method:"POST",path:Jt,bodyParams:e})}};var ce=class extends h{async getInterstitial(){return this.request({path:"internal/interstitial",method:"GET",headerParams:{"Content-Type":"text/html"}})}};var Ne="/invitations",pe=class extends h{async getInvitationList(){return this.request({method:"GET",path:Ne})}async createInvitation(e){return this.request({method:"POST",path:Ne,bodyParams:e})}async revokeInvitation(e){return this.requireId(e),this.request({method:"POST",path:a(Ne,e,"revoke")})}};var J="/organizations",me=class extends h{async getOrganizationList(e){return this.request({method:"GET",path:J,queryParams:e})}async createOrganization(e){return this.request({method:"POST",path:J,bodyParams:e})}async getOrganization(e){let r="organizationId"in e?e.organizationId:e.slug;return this.requireId(r),this.request({method:"GET",path:a(J,r)})}async updateOrganization(e,r){return this.requireId(e),this.request({method:"PATCH",path:a(J,e),bodyParams:r})}async updateOrganizationMetadata(e,r){return this.requireId(e),this.request({method:"PATCH",path:a(J,e,"metadata"),bodyParams:r})}async deleteOrganization(e){return this.request({method:"DELETE",path:a(J,e)})}async getOrganizationMembershipList(e){let{organizationId:r,limit:n,offset:i}=e;return this.requireId(r),this.request({method:"GET",path:a(J,r,"memberships"),queryParams:{limit:n,offset:i}})}async createOrganizationMembership(e){let{organizationId:r,userId:n,role:i}=e;return this.requireId(r),this.request({method:"POST",path:a(J,r,"memberships"),bodyParams:{userId:n,role:i}})}async updateOrganizationMembership(e){let{organizationId:r,userId:n,role:i}=e;return this.requireId(r),this.request({method:"PATCH",path:a(J,r,"memberships",n),bodyParams:{role:i}})}async updateOrganizationMembershipMetadata(e){let{organizationId:r,userId:n,publicMetadata:i,privateMetadata:o}=e;return this.request({method:"PATCH",path:a(J,r,"memberships",n,"metadata"),bodyParams:{publicMetadata:i,privateMetadata:o}})}async deleteOrganizationMembership(e){let{organizationId:r,userId:n}=e;return this.requireId(r),this.request({method:"DELETE",path:a(J,r,"memberships",n)})}async getPendingOrganizationInvitationList(e){let{organizationId:r,limit:n,offset:i}=e;return this.requireId(r),this.request({method:"GET",path:a(J,r,"invitations","pending"),queryParams:{limit:n,offset:i}})}async createOrganizationInvitation(e){let{organizationId:r,...n}=e;return this.requireId(r),this.request({method:"POST",path:a(J,r,"invitations"),bodyParams:{...n}})}async revokeOrganizationInvitation(e){let{organizationId:r,invitationId:n,requestingUserId:i}=e;return this.requireId(r),this.request({method:"POST",path:a(J,r,"invitations",n,"revoke"),bodyParams:{requestingUserId:i}})}};var ge="/phone_numbers",fe=class extends h{async getPhoneNumber(e){return this.requireId(e),this.request({method:"GET",path:a(ge,e)})}async createPhoneNumber(e){return this.request({method:"POST",path:ge,bodyParams:e})}async updatePhoneNumber(e,r={}){return this.requireId(e),this.request({method:"PATCH",path:a(ge,e),bodyParams:r})}async deletePhoneNumber(e){return this.requireId(e),this.request({method:"DELETE",path:a(ge,e)})}};var he="/redirect_urls",ye=class extends h{async getRedirectUrlList(){return this.request({method:"GET",path:he})}async getRedirectUrl(e){return this.requireId(e),this.request({method:"GET",path:a(he,e)})}async createRedirectUrl(e){return this.request({method:"POST",path:he,bodyParams:e})}async deleteRedirectUrl(e){return this.requireId(e),this.request({method:"DELETE",path:a(he,e)})}};var re="/sessions",be=class extends h{constructor(){super(...arguments);this.getSessionList=async r=>this.request({method:"GET",path:re,queryParams:r});this.getSession=async r=>(this.requireId(r),this.request({method:"GET",path:a(re,r)}));this.revokeSession=async r=>(this.requireId(r),this.request({method:"POST",path:a(re,r,"revoke")}));this.verifySession=async(r,n)=>(this.requireId(r),this.request({method:"POST",path:a(re,r,"verify"),bodyParams:{token:n}}));this.getToken=async(r,n)=>(this.requireId(r),(await this.request({method:"POST",path:a(re,r,"tokens",n||"")})).jwt)}};var Le="/sign_in_tokens",Se=class extends h{async createSignInToken(e){return this.request({method:"POST",path:Le,bodyParams:e})}async revokeSignInToken(e){return this.requireId(e),this.request({method:"POST",path:a(Le,e,"revoke")})}};var xt="/sms_messages",Oe=class extends h{async createSMSMessage(e){return this.request({method:"POST",path:xt,bodyParams:e})}};var R="/users",ke=class extends h{async getUserList(e={}){return this.request({method:"GET",path:R,queryParams:e})}async getUser(e){return this.requireId(e),this.request({method:"GET",path:a(R,e)})}async createUser(e){return this.request({method:"POST",path:R,bodyParams:e})}async updateUser(e,r={}){return this.requireId(e),this.request({method:"PATCH",path:a(R,e),bodyParams:r})}async updateUserMetadata(e,r){return this.requireId(e),this.request({method:"PATCH",path:a(R,e,"metadata"),bodyParams:r})}async deleteUser(e){return this.requireId(e),this.request({method:"DELETE",path:a(R,e)})}async getCount(e={}){return this.request({method:"GET",path:a(R,"count"),queryParams:e})}async getUserOauthAccessToken(e,r){return this.requireId(e),this.request({method:"GET",path:a(R,e,"oauth_access_tokens",r)})}async disableUserMFA(e){return this.requireId(e),this.request({method:"DELETE",path:a(R,e,"mfa")})}async getOrganizationMembershipList(e){let{userId:r,limit:n,offset:i}=e;return this.requireId(r),this.request({method:"GET",path:a(R,r,"organization_memberships"),queryParams:{limit:n,offset:i}})}};import Mt from"deepmerge";import $e from"snakecase-keys";var C="https://api.clerk.dev",T="v1",Fe="@clerk/backend",Rt={AuthStatus:"__clerkAuthStatus"},Tt={Session:"__session",ClientUat:"__client_uat"},Ve={AuthStatus:"x-clerk-auth-status",AuthReason:"x-clerk-auth-reason",AuthMessage:"x-clerk-auth-message",Authorization:"authorization",ForwardedPort:"x-forwarded-port",ForwardedHost:"x-forwarded-host",Referrer:"referer",UserAgent:"user-agent",Origin:"origin",Host:"host"},Nt={AuthStatus:Ve.AuthStatus},Ct={Attributes:Rt,Cookies:Tt,Headers:Ve,SearchParams:Nt};import vt from"#crypto";import Et from"#fetch";var qt={crypto:vt,fetch:Et},N=qt;var K=class{constructor(e,r,n,i,o){this.id=e;this.identifier=r;this.createdAt=n;this.updatedAt=i;this.invitationId=o}static fromJSON(e){return new K(e.id,e.identifier,e.created_at,e.updated_at,e.invitation_id)}};var v=class{constructor(e,r,n,i,o,u,m,f,S){this.id=e;this.clientId=r;this.userId=n;this.status=i;this.lastActiveAt=o;this.expireAt=u;this.abandonAt=m;this.createdAt=f;this.updatedAt=S}static fromJSON(e){return new v(e.id,e.client_id,e.user_id,e.status,e.last_active_at,e.expire_at,e.abandon_at,e.created_at,e.updated_at)}};var j=class{constructor(e,r,n,i,o,u,m,f){this.id=e;this.sessionIds=r;this.sessions=n;this.signInId=i;this.signUpId=o;this.lastActiveSessionId=u;this.createdAt=m;this.updatedAt=f}static fromJSON(e){return new j(e.id,e.session_ids,e.sessions.map(r=>v.fromJSON(r)),e.sign_in_id,e.sign_up_id,e.last_active_session_id,e.created_at,e.updated_at)}};var W=class{constructor(e,r,n,i){this.object=e;this.id=r;this.slug=n;this.deleted=i}static fromJSON(e){return new W(e.object,e.id||null,e.slug||null,e.deleted)}};var L=class{constructor(e,r,n,i,o,u,m){this.id=e;this.fromEmailName=r;this.emailAddressId=n;this.toEmailAddress=i;this.subject=o;this.body=u;this.status=m}static fromJSON(e){return new L(e.id,e.from_email_name,e.email_address_id,e.to_email_address,e.subject,e.body,e.status)}};var E=class{constructor(e,r){this.id=e;this.type=r}static fromJSON(e){return new E(e.id,e.type)}};var x=class{constructor(e,r,n=null,i=null,o=null,u=null){this.status=e;this.strategy=r;this.externalVerificationRedirectURL=n;this.attempts=i;this.expireAt=o;this.nonce=u}static fromJSON(e){return new x(e.status,e.strategy,e.external_verification_redirect_url?new URL(e.external_verification_redirect_url):null,e.attempts,e.expire_at,e.nonce)}};var q=class{constructor(e,r,n,i){this.id=e;this.emailAddress=r;this.verification=n;this.linkedTo=i}static fromJSON(e){return new q(e.id,e.email_address,e.verification&&x.fromJSON(e.verification),e.linked_to.map(r=>E.fromJSON(r)))}};var F=class{constructor(e,r,n,i,o,u,m,f,S,I,O={},P,b){this.id=e;this.provider=r;this.identificationId=n;this.externalId=i;this.approvedScopes=o;this.emailAddress=u;this.firstName=m;this.lastName=f;this.picture=S;this.username=I;this.publicMetadata=O;this.label=P;this.verification=b}static fromJSON(e){return new F(e.id,e.provider,e.identification_id,e.provider_user_id,e.approved_scopes,e.email_address,e.first_name,e.last_name,e.avatar_url,e.username,e.public_metadata,e.label,e.verification&&x.fromJSON(e.verification))}};var V=class{constructor(e,r,n,i,o,u){this.id=e;this.emailAddress=r;this.publicMetadata=n;this.createdAt=i;this.updatedAt=o;this.revoked=u}static fromJSON(e){return new V(e.id,e.email_address,e.public_metadata,e.created_at,e.updated_at,e.revoked)}};var De=(p=>(p.AllowlistIdentifier="allowlist_identifier",p.Client="client",p.Email="email",p.EmailAddress="email_address",p.ExternalAccount="external_account",p.FacebookAccount="facebook_account",p.GoogleAccount="google_account",p.Invitation="invitation",p.OauthAccessToken="oauth_access_token",p.Organization="organization",p.OrganizationInvitation="organization_invitation",p.OrganizationMembership="organization_membership",p.PhoneNumber="phone_number",p.RedirectUrl="redirect_url",p.Session="session",p.SignInAttempt="sign_in_attempt",p.SignInToken="sign_in_token",p.SignUpAttempt="sign_up_attempt",p.SmsMessage="sms_message",p.User="user",p.Web3Wallet="web3_wallet",p.Token="token",p.TotalCount="total_count",p))(De||{});var D=class{constructor(e,r,n={},i,o,u){this.provider=e;this.token=r;this.publicMetadata=n;this.label=i;this.scopes=o;this.tokenSecret=u}static fromJSON(e){return new D(e.provider,e.token,e.public_metadata,e.label,e.scopes,e.token_secret)}};var U=class{constructor(e,r,n,i,o,u,m={},f={}){this.id=e;this.name=r;this.slug=n;this.logoUrl=i;this.createdAt=o;this.updatedAt=u;this.publicMetadata=m;this.privateMetadata=f}static fromJSON(e){return new U(e.id,e.name,e.slug,e.logo_url,e.created_at,e.updated_at,e.public_metadata,e.private_metadata)}};var G=class{constructor(e,r,n,i,o,u,m){this.id=e;this.emailAddress=r;this.role=n;this.organizationId=i;this.createdAt=o;this.updatedAt=u;this.status=m}static fromJSON(e){return new G(e.id,e.email_address,e.role,e.organization_id,e.created_at,e.updated_at,e.status)}};var $=class{constructor(e,r,n={},i={},o,u,m,f){this.id=e;this.role=r;this.publicMetadata=n;this.privateMetadata=i;this.createdAt=o;this.updatedAt=u;this.organization=m;this.publicUserData=f}static fromJSON(e){return new $(e.id,e.role,e.public_metadata,e.private_metadata,e.created_at,e.updated_at,U.fromJSON(e.organization),ne.fromJSON(e.public_user_data))}},ne=class{constructor(e,r,n,i,o){this.identifier=e;this.firstName=r;this.lastName=n;this.profileImageUrl=i;this.userId=o}static fromJSON(e){return new ne(e.identifier,e.first_name,e.last_name,e.profile_image_url,e.user_id)}};var z=class{constructor(e,r,n,i,o,u){this.id=e;this.phoneNumber=r;this.reservedForSecondFactor=n;this.defaultSecondFactor=i;this.verification=o;this.linkedTo=u}static fromJSON(e){return new z(e.id,e.phone_number,e.reserved_for_second_factor,e.default_second_factor,e.verification&&x.fromJSON(e.verification),e.linked_to.map(r=>E.fromJSON(r)))}};var B=class{constructor(e,r,n,i){this.id=e;this.url=r;this.createdAt=n;this.updatedAt=i}static fromJSON(e){return new B(e.id,e.url,e.created_at,e.updated_at)}};var H=class{constructor(e,r,n,i,o,u){this.id=e;this.userId=r;this.token=n;this.status=i;this.createdAt=o;this.updatedAt=u}static fromJSON(e){return new H(e.id,e.user_id,e.token,e.status,e.created_at,e.updated_at)}};var Y=class{constructor(e,r,n,i,o,u){this.id=e;this.fromPhoneNumber=r;this.toPhoneNumber=n;this.message=i;this.status=o;this.phoneNumberId=u}static fromJSON(e){return new Y(e.id,e.from_phone_number,e.to_phone_number,e.message,e.status,e.phone_number_id)}};var Q=class{constructor(e){this.jwt=e}static fromJSON(e){return new Q(e.jwt)}};var X=class{constructor(e,r,n){this.id=e;this.web3Wallet=r;this.verification=n}static fromJSON(e){return new X(e.id,e.web3_wallet,e.verification&&x.fromJSON(e.verification))}};var Z=class{constructor(e,r,n,i,o,u,m,f,S,I,O,P,b,k,_,A,w,s,l,d={},y={},g={},p=[],M=[],te=[],Je=[]){this.id=e;this.passwordEnabled=r;this.totpEnabled=n;this.backupCodeEnabled=i;this.twoFactorEnabled=o;this.banned=u;this.createdAt=m;this.updatedAt=f;this.profileImageUrl=S;this.gender=I;this.birthday=O;this.primaryEmailAddressId=P;this.primaryPhoneNumberId=b;this.primaryWeb3WalletId=k;this.lastSignInAt=_;this.externalId=A;this.username=w;this.firstName=s;this.lastName=l;this.publicMetadata=d;this.privateMetadata=y;this.unsafeMetadata=g;this.emailAddresses=p;this.phoneNumbers=M;this.web3Wallets=te;this.externalAccounts=Je}static fromJSON(e){return new Z(e.id,e.password_enabled,e.totp_enabled,e.backup_code_enabled,e.two_factor_enabled,e.banned,e.created_at,e.updated_at,e.profile_image_url,e.gender,e.birthday,e.primary_email_address_id,e.primary_phone_number_id,e.primary_web3_wallet_id,e.last_sign_in_at,e.external_id,e.username,e.first_name,e.last_name,e.public_metadata,e.private_metadata,e.unsafe_metadata,(e.email_addresses||[]).map(r=>q.fromJSON(r)),(e.phone_numbers||[]).map(r=>z.fromJSON(r)),(e.web3_wallets||[]).map(r=>X.fromJSON(r)),(e.external_accounts||[]).map(r=>F.fromJSON(r)))}};function Ge(t){return Array.isArray(t)?t.map(e=>Ce(e)):Ut(t)?t.data.map(e=>Ce(e)):Ce(t)}function Ut(t){return t.data!==void 0}function zt(t){return t.total_count}function Ce(t){if(typeof t!="string"&&"object"in t&&"deleted"in t)return W.fromJSON(t);switch(t.object){case"allowlist_identifier":return K.fromJSON(t);case"client":return j.fromJSON(t);case"email_address":return q.fromJSON(t);case"email":return L.fromJSON(t);case"invitation":return V.fromJSON(t);case"oauth_access_token":return D.fromJSON(t);case"organization":return U.fromJSON(t);case"organization_invitation":return G.fromJSON(t);case"organization_membership":return $.fromJSON(t);case"phone_number":return z.fromJSON(t);case"redirect_url":return B.fromJSON(t);case"sign_in_token":return H.fromJSON(t);case"session":return v.fromJSON(t);case"sms_message":return Y.fromJSON(t);case"token":return Q.fromJSON(t);case"total_count":return zt(t);case"user":return Z.fromJSON(t);default:return t}}var Kt=t=>async(...e)=>{let{data:r,errors:n,status:i,statusText:o}=await t(...e);if(n===null)return r;throw new ie(o||"",{data:n,status:i||""})};function Be(t){return Kt(async r=>{let{apiKey:n,secretKey:i,apiUrl:o=C,apiVersion:u=T,userAgent:m=Fe,httpOptions:f={}}=t,{path:S,method:I,queryParams:O,headerParams:P,bodyParams:b}=r,k=i||n;if(!k)throw Error("Missing Clerk Secret Key or API Key. Go to https://dashboard.clerk.dev and get your key for your instance.");let _=a(o,u,S),A=new URL(_);if(O){let y=$e({...O});for(let[g,p]of Object.entries(y))p&&[p].flat().forEach(M=>A.searchParams.append(g,M))}let w={Authorization:`Bearer ${k}`,"Content-Type":"application/json","Clerk-Backend-SDK":m,...P},l=I!=="GET"&&b&&Object.keys(b).length>0?{body:JSON.stringify($e(b,{deep:!1}))}:null,d;try{d=await N.fetch(A.href,Mt(f,{method:I,headers:w,...l}));let g=await(w&&w["Content-Type"]==="application/json"?d.json():d.text());if(!d.ok)throw g;return{data:Ge(g),errors:null}}catch(y){return y instanceof Error?{data:null,errors:[{code:"unexpected_error",message:y.message||"Unexpected error"}]}:{data:null,errors:jt(y),status:d==null?void 0:d.status,statusText:d==null?void 0:d.statusText}}})}function jt(t){if(!!t&&typeof t=="object"&&"errors"in t){let e=t.errors;return e.length>0?e.map(Wt):[]}return[]}function Wt(t){var e,r;return{code:t.code,message:t.message,longMessage:t.long_message,meta:{paramName:(e=t==null?void 0:t.meta)==null?void 0:e.param_name,sessionId:(r=t==null?void 0:t.meta)==null?void 0:r.session_id}}}var ie=class extends Error{constructor(r,{data:n,status:i}){super(r);Object.setPrototypeOf(this,ie.prototype),this.clerkError=!0,this.message=r,this.status=i,this.errors=n}};function ee(t){let e=Be(t);return{allowlistIdentifiers:new oe(e),clients:new ae(e),emailAddresses:new ue(e),emails:new de(e),interstitial:new ce(e),invitations:new pe(e),organizations:new me(e),phoneNumbers:new fe(e),redirectUrls:new ye(e),sessions:new be(e),signInTokens:new Se(e),smsMessages:new Oe(e),users:new ke(e)}}var Ye=t=>()=>{let e={...t};return e.apiKey=(e.apiKey||"").substring(0,7),e.jwtKey=(e.jwtKey||"").substring(0,7),{...e}};function Qe(t,e,r){let{act:n,sid:i,org_id:o,org_role:u,org_slug:m,sub:f}=t,{apiKey:S,secretKey:I,apiUrl:O,apiVersion:P,token:b,session:k,user:_,organization:A}=e,{sessions:w}=ee({apiKey:S,secretKey:I,apiUrl:O,apiVersion:P}),s=Lt({sessionId:i,sessionToken:b,fetcher:(...l)=>w.getToken(...l)});return{actor:n,sessionClaims:t,sessionId:i,session:k,userId:f,user:_,orgId:o,orgRole:u,orgSlug:m,organization:A,getToken:s,debug:Ye(r)}}function Xe(t){return{sessionClaims:null,sessionId:null,session:null,userId:null,user:null,actor:null,orgId:null,orgRole:null,orgSlug:null,organization:null,getToken:()=>Promise.resolve(null),debug:Ye(t)}}function He(t){return t&&(delete t.privateMetadata,delete t.private_metadata),t}function Ci(t){let e=t.user?{...t.user}:t.user,r=t.organization?{...t.organization}:t.organization;return He(e),He(r),{...t,user:e,organization:r}}var Lt=t=>{let{fetcher:e,sessionToken:r,sessionId:n}=t||{};return async(i={})=>n?i.template?e(n,i.template):r:null};import{parsePublishableKey as tt}from"@clerk/shared";function Ft(t){return new Promise(e=>setTimeout(e,t))}var Vt=5;async function se(t,e=1,r=Vt){try{return await t()}catch(n){if(e>=r)throw n;return await Ft(2**e*100),se(t,e+1)}}function Ie(t){return t.startsWith("test_")||t.startsWith("sk_test_")}function Ze(t){return t.startsWith("live_")||t.startsWith("sk_live_")}function et(t){return t.endsWith(".lclstage.dev")||t.endsWith(".stgstage.dev")||t.endsWith(".clerkstage.dev")||t.endsWith(".accountsstage.dev")}var c=class extends Error{constructor({action:r,message:n,reason:i}){super(n);Object.setPrototypeOf(this,c.prototype),this.reason=i,this.message=n,this.action=r}getFullMessage(){return`${[this.message,this.action].filter(r=>r).join(" ")} (reason=${this.reason}, token-carrier=${this.tokenCarrier})`}};function Ee(t){let{debugData:e,frontendApi:r,pkgVersion:n,publishableKey:i}=t;return` | ||
<head> | ||
@@ -47,3 +47,3 @@ <meta charset="UTF-8" /> | ||
script.async = true; | ||
script.src = '${Vt(r,n)}'; | ||
script.src = '${Dt(r,n)}'; | ||
script.crossOrigin = 'anonymous'; | ||
@@ -55,3 +55,3 @@ script.addEventListener('load', startClerk); | ||
</body> | ||
`}async function rt(t){t.frontendApi=t.frontendApi||tt(t.publishableKey)?.frontendApi||"";let e=Ie(t),r=await ie(()=>N.fetch(Ie(t)));if(!r.ok)throw new d({action:"Contact support@clerk.dev",message:`Error loading Clerk Interstitial from ${e} with code=${r.status}`,reason:"interstitial-remote-failed-to-load"});return r.text()}function Ie(t){t.frontendApi=t.frontendApi||tt(t.publishableKey)?.frontendApi||"";let{apiUrl:e,frontendApi:r,pkgVersion:n,publishableKey:i}=t,o=new URL(e);return o.pathname=a(o.pathname,T,"/public/interstitial"),o.searchParams.append("clerk_js_version",nt(r,n)),i?o.searchParams.append("publishable_key",i):o.searchParams.append("frontend_api",r),o.href}var nt=(t,e)=>!e&&et(t)?"staging":e?e.includes("next")?"next":e.split(".")[0]||"latest":"latest",Vt=(t,e)=>{let r=nt(t,e);return`https://${t}/npm/@clerk/clerk-js@${r}/dist/clerk.browser.js`};import{parsePublishableKey as rr}from"@clerk/shared";function Ee({originURL:t,host:e,forwardedHost:r,forwardedPort:n,forwardedProto:i}){if(i&&i!==t.protocol)return!0;let o=Dt(r||e);return o.port=n||o.port,o.port!==t.port||o.hostname!==t.hostname}function Dt(t){return new URL(`https://${t}`)}import{base64url as qe}from"rfc4648";var Gt=2*1e3,Me={RS256:"SHA-256",RS384:"SHA-384",RS512:"SHA-512",ES256:"SHA-256",ES384:"SHA-384",ES512:"SHA-512"},Ue="RSASSA-PKCS1-v1_5",ze="ECDSA",$t={RS256:Ue,RS384:Ue,RS512:Ue,ES256:ze,ES384:ze,ES512:ze},Bt=Object.keys(Me);async function Ht(t,e){let{header:r,signature:n,raw:i}=t,u=new TextEncoder().encode([i.header,i.payload].join(".")),m=await N.crypto.subtle.importKey("jwk",e,{name:$t[r.alg],hash:Me[r.alg]},!1,["verify"]);return N.crypto.subtle.verify("RSASSA-PKCS1-v1_5",m,n,u)}function Ke(t){let e=(t||"").toString().split(".");if(e.length!==3)throw new d({reason:"token-invalid",message:"Invalid JWT form. A JWT consists of three parts separated by dots."});let[r,n,i]=e,o=new TextDecoder,u=JSON.parse(o.decode(qe.parse(r,{loose:!0}))),m=JSON.parse(o.decode(qe.parse(n,{loose:!0}))),g=qe.parse(i,{loose:!0});return{header:u,payload:m,signature:g,raw:{header:r,payload:n,signature:i,text:t}}}async function it(t,{audience:e,authorizedParties:r,clockSkewInSeconds:n=Gt,issuer:i,key:o}){let u=Ke(t),{header:m,payload:g}=u,{typ:O,alg:_}=m;if(typeof O<"u"&&O!=="JWT")throw new d({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-invalid",message:`Invalid JWT type ${JSON.stringify(O)}. Expected "JWT".`});if(!Me[_])throw new d({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-invalid-algorithm",message:`Invalid JWT algorithm ${JSON.stringify(_)}. Supported: ${Bt}.`});let{azp:k,sub:P,aud:b,iss:I,iat:A,exp:w,nbf:s}=g;if(typeof P!="string")throw new d({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Subject claim (sub) is required and must be a string. Received ${JSON.stringify(P)}.`});if(typeof b=="string"){if(b!==e)throw new d({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Invalid JWT audience claim (aud) ${JSON.stringify(b)}. Expected "${e}".`})}else if(Array.isArray(b)&&b.length>0&&b.every(y=>typeof y=="string")&&!b.includes(e))throw new d({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Invalid JWT audience claim array (aud) ${JSON.stringify(b)}. Does not include "${e}".`});if(k&&r&&r.length>0&&!r.includes(k))throw new d({reason:"token-invalid-authorized-parties",message:`Invalid JWT Authorized party claim (azp) ${JSON.stringify(k)}. Expected "${r}".`});if(typeof i=="function"&&!i(I))throw new d({reason:"token-invalid-issuer",message:"Failed JWT issuer resolver. Make sure that the resolver returns a truthy value."});if(typeof i=="string"&&I&&I!==i)throw new d({reason:"token-invalid-issuer",message:`Invalid JWT issuer claim (iss) ${JSON.stringify(u.payload.iss)}. Expected "${i}".`});if(typeof w!="number")throw new d({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Invalid JWT expiry date claim (exp) ${JSON.stringify(w)}. Expected number.`});let l=new Date(Date.now()),p=new Date(0);if(p.setUTCSeconds(w),p.getTime()<=l.getTime()-n)throw new d({reason:"token-expired",message:`JWT is expired. Expiry date: ${p}, Current date: ${l}.`});if(s!==void 0){if(typeof s!="number")throw new d({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Invalid JWT not before date claim (nbf) ${JSON.stringify(s)}. Expected number.`});let y=new Date(0);if(y.setUTCSeconds(s),y.getTime()>l.getTime()+n)throw new d({reason:"token-not-active-yet",message:`JWT cannot be used prior to not before date claim (nbf). Not before date: ${y}; Current date: ${l};`})}if(A!==void 0){if(typeof A!="number")throw new d({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Invalid JWT issued at date claim (iat) ${JSON.stringify(A)}. Expected number.`});let y=new Date(0);if(y.setUTCSeconds(A),y.getTime()>l.getTime()+n)throw new d({reason:"token-not-active-yet",message:`JWT issued at date claim (iat) is in the future. Issued at date: ${y}; Current date: ${l};`})}let S;try{S=await Ht(u,o)}catch(y){throw new d({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Error verifying JWT signature. ${y}`})}if(!S)throw new d({reason:"token-invalid-signature",message:"JWT signature is invalid."});return g}var Ae={};function we(t){return Ae[t]}function ot(t,e=1e3*60*60){Ae[t.kid]=t,e>=0&&setTimeout(()=>{t?delete Ae[t.kid]:Ae={}},e)}var st="local",Yt="-----BEGIN PUBLIC KEY-----",Qt="-----END PUBLIC KEY-----",Xt="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA",Zt="IDAQAB";function at(t){if(!we(st)){if(!t)throw new d({action:"Set the CLERK_JWT_KEY environment variable.",message:"Missing local JWK.",reason:"jwk-local-missing"});let e=t.replace(/(\r\n|\n|\r)/gm,"").replace(Yt,"").replace(Qt,"").replace(Xt,"").replace(Zt,"").replace(/\+/g,"-").replace(/\//g,"_");ot({kid:"local",kty:"RSA",alg:"RS256",n:e,e:"AQAB"},-1)}return we(st)}async function lt({apiKey:t,secretKey:e,apiUrl:r,apiVersion:n,issuer:i,kid:o,jwksCacheTtlInMs:u=1e3*60*60,skipJwksCache:m}){if(m||!we(o)){let O,_=e||t||"";if(r)O=()=>tr(r,_,n);else if(i)O=()=>er(i);else throw new d({action:"Contact support@clerk.dev",message:"Failed to load JWKS from Clerk Backend or Frontend API.",reason:"jwk-remote-failed-to-load"});let{keys:k}=await ie(O);if(!k||!k.length)throw new d({action:"Contact support@clerk.dev",message:"The JWKS endpoint did not contain any signing keys. Contact support@clerk.dev.",reason:"jwk-remote-failed-to-load"});k.forEach(P=>ot(P,u))}let g=we(o);if(!g)throw new d({action:"Contact support@clerk.dev",message:`Unable to find a signing key in JWKS that matches kid='${o}'.`,reason:"jwk-remote-missing"});return g}async function er(t){let e=new URL(t);e.pathname=a(e.pathname,".well-known/jwks.json");let r=await N.fetch(e.href);if(!r.ok)throw new d({action:"Contact support@clerk.dev",message:`Error loading Clerk JWKS from ${e.href} with code=${r.status}`,reason:"jwk-remote-failed-to-load"});return r.json()}async function tr(t=C,e,r=T){if(!e)throw new d({action:"Set the CLERK_SECRET_KEY or CLERK_API_KEY environment variable.",message:"Missing Clerk Secret Key or API Key. Go to https://dashboard.clerk.dev and get your key for your instance.",reason:"jwk-remote-failed-to-load"});let n=new URL(t);n.pathname=a(n.pathname,r,"/jwks");let i=await N.fetch(n.href,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(!i.ok)throw new d({action:"Contact support@clerk.dev",message:`Error loading Clerk JWKS from ${n.href} with code=${i.status}`,reason:"jwk-remote-failed-to-load"});return i.json()}async function ut(t,e){let{apiKey:r,secretKey:n,apiUrl:i,apiVersion:o,authorizedParties:u,clockSkewInSeconds:m,issuer:g,jwksCacheTtlInMs:O,jwtKey:_,skipJwksCache:k}=e,{header:P}=Ke(t),{kid:b}=P,I;if(_)I=at(_);else if(r||n)I=await lt(r?{apiUrl:i,apiKey:r,apiVersion:o,kid:b,jwksCacheTtlInMs:O,skipJwksCache:k}:{apiUrl:i,secretKey:n,apiVersion:o,kid:b,jwksCacheTtlInMs:O,skipJwksCache:k});else throw new d({action:"Set the CLERK_JWT_KEY environment variable.",message:"Failed to resolve JWK during verification.",reason:"jwk-failed-to-resolve"});return await it(t,{authorizedParties:u,clockSkewInSeconds:m,key:I,issuer:g})}var dt=(n=>(n.SignedIn="signed-in",n.SignedOut="signed-out",n.Interstitial="interstitial",n))(dt||{});async function ct(t){t.frontendApi=t.frontendApi||rr(t.publishableKey)?.frontendApi||"",t.apiUrl=t.apiUrl||C,t.apiVersion=t.apiVersion||T;async function e(){let{headerToken:s}=t;try{let l=await n(s);return await u(l)}catch(l){return i(l,"header")}}async function r(){try{let s=O(t,[_,k,P,b,I,A,w]);if(s)return s;let{cookieToken:l,clientUat:p}=t,h=await n(l),S=await u(h);return!p||o(S.toAuth().sessionClaims,p)?g("cookie-outdated"):S}catch(s){return i(s,"cookie")}}function n(s){return ut(s,{...t,issuer:p=>p.startsWith("https://clerk.")||p.includes(".clerk.accounts")})}function i(s,l){return s instanceof d?(s.tokenCarrier=l,["token-expired","token-not-active-yet"].includes(s.reason)?g(s.reason,s.getFullMessage()):m(s.reason,s.getFullMessage())):m("unexpected-error",s.message)}function o(s,l){return s.iat<Number.parseInt(l)}async function u(s){let{sid:l,org_id:p,sub:h}=s,{apiKey:S,secretKey:y,apiUrl:c,apiVersion:M,cookieToken:Pe,frontendApi:We,publishableKey:mt,headerToken:gt,loadSession:ft,loadUser:ht,loadOrganization:yt}=t,{sessions:bt,users:St,organizations:Ot}=ee({apiKey:S,secretKey:y,apiUrl:c,apiVersion:M}),[kt,It,_t]=await Promise.all([ft?bt.getSession(l):Promise.resolve(void 0),ht?St.getUser(h):Promise.resolve(void 0),yt&&p?Ot.getOrganization({organizationId:p}):Promise.resolve(void 0)]),At=Qe(s,{apiKey:S,secretKey:y,apiUrl:c,apiVersion:M,token:Pe||gt||"",session:kt,user:It,organization:_t},{...t,status:"signed-in"});return{status:"signed-in",reason:null,message:null,frontendApi:We,publishableKey:mt,isSignedIn:!0,isInterstitial:!1,toAuth:()=>At}}function m(s,l=""){return{status:"signed-out",reason:s,message:l,frontendApi:t.frontendApi,publishableKey:t.publishableKey,isSignedIn:!1,isInterstitial:!1,toAuth:()=>Xe({...t,status:"signed-out",reason:s,message:l})}}function g(s,l=""){return{status:"interstitial",reason:s,message:l,frontendApi:t.frontendApi,publishableKey:t.publishableKey,isSignedIn:!1,isInterstitial:!0,toAuth:()=>null}}let O=(s,l)=>{for(let p of l){let h=p(s);if(h)return h}},_=({apiKey:s,secretKey:l,userAgent:p})=>{if(ke(l||s)&&!p?.startsWith("Mozilla/"))return m("header-missing-non-browser")},k=({origin:s,host:l,forwardedHost:p,forwardedPort:h,forwardedProto:S})=>{if(s&&Ee({originURL:new URL(s),host:l,forwardedHost:p,forwardedPort:h,forwardedProto:S}))return m("header-missing-cors")},P=({apiKey:s,secretKey:l,clientUat:p})=>{if(ke(l||s)&&!p)return g("uat-missing")},b=({apiKey:s,secretKey:l,referrer:p,host:h,forwardedHost:S,forwardedPort:y,forwardedProto:c})=>{let M=p&&Ee({originURL:new URL(p),host:h,forwardedHost:S,forwardedPort:y,forwardedProto:c});if(ke(l||s)&&M)return g("cross-origin-referrer")},I=({apiKey:s,secretKey:l,clientUat:p,cookieToken:h})=>{if(Ze(l||s)&&!p&&!h)return m("cookie-and-uat-missing")},A=({clientUat:s})=>{if(s==="0")return m("standard-signed-out")},w=({clientUat:s,cookieToken:l})=>{if(s&&!l)return g("cookie-missing")};return t.headerToken?e():r()}var je=t=>{let{frontendApi:e,isSignedIn:r,isInterstitial:n,reason:i,message:o,publishableKey:u}=t;return{frontendApi:e,isSignedIn:r,isInterstitial:n,reason:i,message:o,publishableKey:u}};function pt(t){let{apiClient:e}=t,{apiKey:r="",secretKey:n="",jwtKey:i="",apiUrl:o=C,apiVersion:u=T,frontendApi:m="",publishableKey:g=""}=t.options;return{authenticateRequest:({apiKey:I,secretKey:A,frontendApi:w,publishableKey:s,jwtKey:l,...p})=>ct({...p,apiKey:I||r,secretKey:A||n,apiUrl:o,apiVersion:u,frontendApi:w||m,publishableKey:s||g,jwtKey:l||i}),localInterstitial:ve,remotePublicInterstitial:({frontendApi:I,publishableKey:A,...w})=>rt({...w,apiUrl:o,frontendApi:I||m,publishableKey:A||g}),remotePrivateInterstitial:()=>e.interstitial.getInterstitial(),remotePublicInterstitialUrl:Ie,debugRequestState:je}}function Ps(t){let e={...t},r=ee(e),n=pt({options:e,apiClient:r});return{...r,...n,__unstable_options:e}}export{K as AllowlistIdentifier,dt as AuthStatus,Ps as Clerk,j as Client,W as DeletedObject,L as Email,q as EmailAddress,F as ExternalAccount,E as IdentificationLink,V as Invitation,D as OauthAccessToken,De as ObjectType,U as Organization,G as OrganizationInvitation,$ as OrganizationMembership,re as OrganizationMembershipPublicUserData,z as PhoneNumber,B as RedirectUrl,Y as SMSMessage,v as Session,H as SignInToken,Q as Token,Z as User,x as Verification,Nt as constants,pt as createAuthenticateRequest,je as debugRequestState,Ke as decodeJwt,Ge as deserialize,Ht as hasValidSignature,ve as loadInterstitialFromLocal,He as prunePrivateMetadata,Ni as sanitizeAuthObject,Qe as signedInAuthObject,Xe as signedOutAuthObject,it as verifyJwt,ut as verifyToken}; | ||
`}async function rt(t){var n;t.frontendApi=t.frontendApi||((n=tt(t.publishableKey))==null?void 0:n.frontendApi)||"";let e=_e(t),r=await se(()=>N.fetch(_e(t)));if(!r.ok)throw new c({action:"Contact support@clerk.dev",message:`Error loading Clerk Interstitial from ${e} with code=${r.status}`,reason:"interstitial-remote-failed-to-load"});return r.text()}function _e(t){var u;t.frontendApi=t.frontendApi||((u=tt(t.publishableKey))==null?void 0:u.frontendApi)||"";let{apiUrl:e,frontendApi:r,pkgVersion:n,publishableKey:i}=t,o=new URL(e);return o.pathname=a(o.pathname,T,"/public/interstitial"),o.searchParams.append("clerk_js_version",nt(r,n)),i?o.searchParams.append("publishable_key",i):o.searchParams.append("frontend_api",r),o.href}var nt=(t,e)=>!e&&et(t)?"staging":e?e.includes("next")?"next":e.split(".")[0]||"latest":"latest",Dt=(t,e)=>{let r=nt(t,e);return`https://${t}/npm/@clerk/clerk-js@${r}/dist/clerk.browser.js`};import{parsePublishableKey as nr}from"@clerk/shared";function qe({originURL:t,host:e,forwardedHost:r,forwardedPort:n,forwardedProto:i}){if(i&&i!==t.protocol)return!0;let o=Gt(r||e);return o.port=n||o.port,o.port!==t.port||o.hostname!==t.hostname}function Gt(t){return new URL(`https://${t}`)}import{base64url as Ue}from"rfc4648";var $t=2*1e3,Ke={RS256:"SHA-256",RS384:"SHA-384",RS512:"SHA-512",ES256:"SHA-256",ES384:"SHA-384",ES512:"SHA-512"},ze="RSASSA-PKCS1-v1_5",Me="ECDSA",Bt={RS256:ze,RS384:ze,RS512:ze,ES256:Me,ES384:Me,ES512:Me},Ht=Object.keys(Ke);async function Yt(t,e){let{header:r,signature:n,raw:i}=t,u=new TextEncoder().encode([i.header,i.payload].join(".")),m=await N.crypto.subtle.importKey("jwk",e,{name:Bt[r.alg],hash:Ke[r.alg]},!1,["verify"]);return N.crypto.subtle.verify("RSASSA-PKCS1-v1_5",m,n,u)}function je(t){let e=(t||"").toString().split(".");if(e.length!==3)throw new c({reason:"token-invalid",message:"Invalid JWT form. A JWT consists of three parts separated by dots."});let[r,n,i]=e,o=new TextDecoder,u=JSON.parse(o.decode(Ue.parse(r,{loose:!0}))),m=JSON.parse(o.decode(Ue.parse(n,{loose:!0}))),f=Ue.parse(i,{loose:!0});return{header:u,payload:m,signature:f,raw:{header:r,payload:n,signature:i,text:t}}}async function it(t,{audience:e,authorizedParties:r,clockSkewInSeconds:n=$t,issuer:i,key:o}){let u=je(t),{header:m,payload:f}=u,{typ:S,alg:I}=m;if(typeof S!="undefined"&&S!=="JWT")throw new c({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-invalid",message:`Invalid JWT type ${JSON.stringify(S)}. Expected "JWT".`});if(!Ke[I])throw new c({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-invalid-algorithm",message:`Invalid JWT algorithm ${JSON.stringify(I)}. Supported: ${Ht}.`});let{azp:O,sub:P,aud:b,iss:k,iat:_,exp:A,nbf:w}=f;if(typeof P!="string")throw new c({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Subject claim (sub) is required and must be a string. Received ${JSON.stringify(P)}.`});if(typeof b=="string"){if(b!==e)throw new c({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Invalid JWT audience claim (aud) ${JSON.stringify(b)}. Expected "${e}".`})}else if(Array.isArray(b)&&b.length>0&&b.every(g=>typeof g=="string")&&!b.includes(e))throw new c({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Invalid JWT audience claim array (aud) ${JSON.stringify(b)}. Does not include "${e}".`});if(O&&r&&r.length>0&&!r.includes(O))throw new c({reason:"token-invalid-authorized-parties",message:`Invalid JWT Authorized party claim (azp) ${JSON.stringify(O)}. Expected "${r}".`});if(typeof i=="function"&&!i(k))throw new c({reason:"token-invalid-issuer",message:"Failed JWT issuer resolver. Make sure that the resolver returns a truthy value."});if(typeof i=="string"&&k&&k!==i)throw new c({reason:"token-invalid-issuer",message:`Invalid JWT issuer claim (iss) ${JSON.stringify(u.payload.iss)}. Expected "${i}".`});if(typeof A!="number")throw new c({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Invalid JWT expiry date claim (exp) ${JSON.stringify(A)}. Expected number.`});let s=new Date(Date.now()),l=new Date(0);if(l.setUTCSeconds(A),l.getTime()<=s.getTime()-n)throw new c({reason:"token-expired",message:`JWT is expired. Expiry date: ${l}, Current date: ${s}.`});if(w!==void 0){if(typeof w!="number")throw new c({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Invalid JWT not before date claim (nbf) ${JSON.stringify(w)}. Expected number.`});let g=new Date(0);if(g.setUTCSeconds(w),g.getTime()>s.getTime()+n)throw new c({reason:"token-not-active-yet",message:`JWT cannot be used prior to not before date claim (nbf). Not before date: ${g}; Current date: ${s};`})}if(_!==void 0){if(typeof _!="number")throw new c({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Invalid JWT issued at date claim (iat) ${JSON.stringify(_)}. Expected number.`});let g=new Date(0);if(g.setUTCSeconds(_),g.getTime()>s.getTime()+n)throw new c({reason:"token-not-active-yet",message:`JWT issued at date claim (iat) is in the future. Issued at date: ${g}; Current date: ${s};`})}let y;try{y=await Yt(u,o)}catch(g){throw new c({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Error verifying JWT signature. ${g}`})}if(!y)throw new c({reason:"token-invalid-signature",message:"JWT signature is invalid."});return f}var we={};function Pe(t){return we[t]}function ot(t,e=1e3*60*60){we[t.kid]=t,e>=0&&setTimeout(()=>{t?delete we[t.kid]:we={}},e)}var st="local",Qt="-----BEGIN PUBLIC KEY-----",Xt="-----END PUBLIC KEY-----",Zt="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA",er="IDAQAB";function at(t){if(!Pe(st)){if(!t)throw new c({action:"Set the CLERK_JWT_KEY environment variable.",message:"Missing local JWK.",reason:"jwk-local-missing"});let e=t.replace(/(\r\n|\n|\r)/gm,"").replace(Qt,"").replace(Xt,"").replace(Zt,"").replace(er,"").replace(/\+/g,"-").replace(/\//g,"_");ot({kid:"local",kty:"RSA",alg:"RS256",n:e,e:"AQAB"},-1)}return Pe(st)}async function lt({apiKey:t,secretKey:e,apiUrl:r,apiVersion:n,issuer:i,kid:o,jwksCacheTtlInMs:u=1e3*60*60,skipJwksCache:m}){if(m||!Pe(o)){let S,I=e||t||"";if(r)S=()=>rr(r,I,n);else if(i)S=()=>tr(i);else throw new c({action:"Contact support@clerk.dev",message:"Failed to load JWKS from Clerk Backend or Frontend API.",reason:"jwk-remote-failed-to-load"});let{keys:O}=await se(S);if(!O||!O.length)throw new c({action:"Contact support@clerk.dev",message:"The JWKS endpoint did not contain any signing keys. Contact support@clerk.dev.",reason:"jwk-remote-failed-to-load"});O.forEach(P=>ot(P,u))}let f=Pe(o);if(!f)throw new c({action:"Contact support@clerk.dev",message:`Unable to find a signing key in JWKS that matches kid='${o}'.`,reason:"jwk-remote-missing"});return f}async function tr(t){let e=new URL(t);e.pathname=a(e.pathname,".well-known/jwks.json");let r=await N.fetch(e.href);if(!r.ok)throw new c({action:"Contact support@clerk.dev",message:`Error loading Clerk JWKS from ${e.href} with code=${r.status}`,reason:"jwk-remote-failed-to-load"});return r.json()}async function rr(t=C,e,r=T){if(!e)throw new c({action:"Set the CLERK_SECRET_KEY or CLERK_API_KEY environment variable.",message:"Missing Clerk Secret Key or API Key. Go to https://dashboard.clerk.dev and get your key for your instance.",reason:"jwk-remote-failed-to-load"});let n=new URL(t);n.pathname=a(n.pathname,r,"/jwks");let i=await N.fetch(n.href,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(!i.ok)throw new c({action:"Contact support@clerk.dev",message:`Error loading Clerk JWKS from ${n.href} with code=${i.status}`,reason:"jwk-remote-failed-to-load"});return i.json()}async function ut(t,e){let{apiKey:r,secretKey:n,apiUrl:i,apiVersion:o,authorizedParties:u,clockSkewInSeconds:m,issuer:f,jwksCacheTtlInMs:S,jwtKey:I,skipJwksCache:O}=e,{header:P}=je(t),{kid:b}=P,k;if(I)k=at(I);else if(r||n)k=await lt(r?{apiUrl:i,apiKey:r,apiVersion:o,kid:b,jwksCacheTtlInMs:S,skipJwksCache:O}:{apiUrl:i,secretKey:n,apiVersion:o,kid:b,jwksCacheTtlInMs:S,skipJwksCache:O});else throw new c({action:"Set the CLERK_JWT_KEY environment variable.",message:"Failed to resolve JWK during verification.",reason:"jwk-failed-to-resolve"});return await it(t,{authorizedParties:u,clockSkewInSeconds:m,key:k,issuer:f})}var dt=(n=>(n.SignedIn="signed-in",n.SignedOut="signed-out",n.Interstitial="interstitial",n))(dt||{});async function ct(t){var w;t.frontendApi=t.frontendApi||((w=nr(t.publishableKey))==null?void 0:w.frontendApi)||"",t.apiUrl=t.apiUrl||C,t.apiVersion=t.apiVersion||T;async function e(){let{headerToken:s}=t;try{let l=await n(s);return await u(l)}catch(l){return i(l,"header")}}async function r(){try{let s=S(t,[I,O,P,b,k,_,A]);if(s)return s;let{cookieToken:l,clientUat:d}=t,y=await n(l),g=await u(y);return!d||o(g.toAuth().sessionClaims,d)?f("cookie-outdated"):g}catch(s){return i(s,"cookie")}}function n(s){return ut(s,{...t,issuer:d=>d.startsWith("https://clerk.")||d.includes(".clerk.accounts")})}function i(s,l){return s instanceof c?(s.tokenCarrier=l,["token-expired","token-not-active-yet"].includes(s.reason)?f(s.reason,s.getFullMessage()):m(s.reason,s.getFullMessage())):m("unexpected-error",s.message)}function o(s,l){return s.iat<Number.parseInt(l)}async function u(s){let{sid:l,org_id:d,sub:y}=s,{apiKey:g,secretKey:p,apiUrl:M,apiVersion:te,cookieToken:Je,frontendApi:mt,publishableKey:gt,headerToken:ft,loadSession:ht,loadUser:yt,loadOrganization:bt}=t,{sessions:St,users:Ot,organizations:kt}=ee({apiKey:g,secretKey:p,apiUrl:M,apiVersion:te}),[It,_t,At]=await Promise.all([ht?St.getSession(l):Promise.resolve(void 0),yt?Ot.getUser(y):Promise.resolve(void 0),bt&&d?kt.getOrganization({organizationId:d}):Promise.resolve(void 0)]),wt=Qe(s,{apiKey:g,secretKey:p,apiUrl:M,apiVersion:te,token:Je||ft||"",session:It,user:_t,organization:At},{...t,status:"signed-in"});return{status:"signed-in",reason:null,message:null,frontendApi:mt,publishableKey:gt,isSignedIn:!0,isInterstitial:!1,toAuth:()=>wt}}function m(s,l=""){return{status:"signed-out",reason:s,message:l,frontendApi:t.frontendApi,publishableKey:t.publishableKey,isSignedIn:!1,isInterstitial:!1,toAuth:()=>Xe({...t,status:"signed-out",reason:s,message:l})}}function f(s,l=""){return{status:"interstitial",reason:s,message:l,frontendApi:t.frontendApi,publishableKey:t.publishableKey,isSignedIn:!1,isInterstitial:!0,toAuth:()=>null}}let S=(s,l)=>{for(let d of l){let y=d(s);if(y)return y}},I=({apiKey:s,secretKey:l,userAgent:d})=>{if(Ie(l||s)&&!(d!=null&&d.startsWith("Mozilla/")))return m("header-missing-non-browser")},O=({origin:s,host:l,forwardedHost:d,forwardedPort:y,forwardedProto:g})=>{if(s&&qe({originURL:new URL(s),host:l,forwardedHost:d,forwardedPort:y,forwardedProto:g}))return m("header-missing-cors")},P=({apiKey:s,secretKey:l,clientUat:d})=>{if(Ie(l||s)&&!d)return f("uat-missing")},b=({apiKey:s,secretKey:l,referrer:d,host:y,forwardedHost:g,forwardedPort:p,forwardedProto:M})=>{let te=d&&qe({originURL:new URL(d),host:y,forwardedHost:g,forwardedPort:p,forwardedProto:M});if(Ie(l||s)&&te)return f("cross-origin-referrer")},k=({apiKey:s,secretKey:l,clientUat:d,cookieToken:y})=>{if(Ze(l||s)&&!d&&!y)return m("cookie-and-uat-missing")},_=({clientUat:s})=>{if(s==="0")return m("standard-signed-out")},A=({clientUat:s,cookieToken:l})=>{if(s&&!l)return f("cookie-missing")};return t.headerToken?e():r()}var We=t=>{let{frontendApi:e,isSignedIn:r,isInterstitial:n,reason:i,message:o,publishableKey:u}=t;return{frontendApi:e,isSignedIn:r,isInterstitial:n,reason:i,message:o,publishableKey:u}};function pt(t){let{apiClient:e}=t,{apiKey:r="",secretKey:n="",jwtKey:i="",apiUrl:o=C,apiVersion:u=T,frontendApi:m="",publishableKey:f=""}=t.options;return{authenticateRequest:({apiKey:k,secretKey:_,frontendApi:A,publishableKey:w,jwtKey:s,...l})=>ct({...l,apiKey:k||r,secretKey:_||n,apiUrl:o,apiVersion:u,frontendApi:A||m,publishableKey:w||f,jwtKey:s||i}),localInterstitial:Ee,remotePublicInterstitial:({frontendApi:k,publishableKey:_,...A})=>rt({...A,apiUrl:o,frontendApi:k||m,publishableKey:_||f}),remotePrivateInterstitial:()=>e.interstitial.getInterstitial(),remotePublicInterstitialUrl:_e,debugRequestState:We}}function Js(t){let e={...t},r=ee(e),n=pt({options:e,apiClient:r});return{...r,...n,__unstable_options:e}}export{K as AllowlistIdentifier,dt as AuthStatus,Js as Clerk,j as Client,W as DeletedObject,L as Email,q as EmailAddress,F as ExternalAccount,E as IdentificationLink,V as Invitation,D as OauthAccessToken,De as ObjectType,U as Organization,G as OrganizationInvitation,$ as OrganizationMembership,ne as OrganizationMembershipPublicUserData,z as PhoneNumber,B as RedirectUrl,Y as SMSMessage,v as Session,H as SignInToken,Q as Token,Z as User,x as Verification,Ct as constants,pt as createAuthenticateRequest,We as debugRequestState,je as decodeJwt,Ge as deserialize,Yt as hasValidSignature,Ee as loadInterstitialFromLocal,He as prunePrivateMetadata,Ci as sanitizeAuthObject,Qe as signedInAuthObject,Xe as signedOutAuthObject,it as verifyJwt,ut as verifyToken}; | ||
//# sourceMappingURL=index.js.map |
@@ -1,2 +0,2 @@ | ||
"use strict";var Et=Object.create;var se=Object.defineProperty;var qt=Object.getOwnPropertyDescriptor;var Ut=Object.getOwnPropertyNames;var zt=Object.getPrototypeOf,Mt=Object.prototype.hasOwnProperty;var Kt=(t,e)=>{for(var r in e)se(t,r,{get:e[r],enumerable:!0})},tt=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ut(e))!Mt.call(t,i)&&i!==r&&se(t,i,{get:()=>e[i],enumerable:!(n=qt(e,i))||n.enumerable});return t};var oe=(t,e,r)=>(r=t!=null?Et(zt(t)):{},tt(e||!t||!t.__esModule?se(r,"default",{value:t,enumerable:!0}):r,t)),jt=t=>tt(se({},"__esModule",{value:!0}),t);var fr={};Kt(fr,{AllowlistIdentifier:()=>K,AuthStatus:()=>Xe,Clerk:()=>gr,Client:()=>j,DeletedObject:()=>W,Email:()=>L,EmailAddress:()=>E,ExternalAccount:()=>F,IdentificationLink:()=>v,Invitation:()=>V,OauthAccessToken:()=>D,ObjectType:()=>ze,Organization:()=>q,OrganizationInvitation:()=>G,OrganizationMembership:()=>$,OrganizationMembershipPublicUserData:()=>Z,PhoneNumber:()=>U,RedirectUrl:()=>B,SMSMessage:()=>Y,Session:()=>C,SignInToken:()=>H,Token:()=>Q,User:()=>X,Verification:()=>x,constants:()=>st,createAuthenticateRequest:()=>Ze,debugRequestState:()=>Ne,decodeJwt:()=>xe,deserialize:()=>Ke,hasValidSignature:()=>ft,loadInterstitialFromLocal:()=>Pe,prunePrivateMetadata:()=>We,sanitizeAuthObject:()=>Zt,signedInAuthObject:()=>Le,signedOutAuthObject:()=>Fe,verifyJwt:()=>Ye,verifyToken:()=>Qe});module.exports=jt(fr);var f=class{constructor(e){this.request=e}requireId(e){if(!e)throw new Error("A valid resource ID is required.")}};var ve="/",Wt=new RegExp(ve+"{1,}","g");function a(...t){return t.filter(e=>e).join(ve).replace(Wt,ve)}var Ee="/allowlist_identifiers",ae=class extends f{async getAllowlistIdentifierList(){return this.request({method:"GET",path:Ee})}async createAllowlistIdentifier(e){return this.request({method:"POST",path:Ee,bodyParams:e})}async deleteAllowlistIdentifier(e){return this.requireId(e),this.request({method:"DELETE",path:a(Ee,e)})}};var qe="/clients",le=class extends f{async getClientList(){return this.request({method:"GET",path:qe})}async getClient(e){return this.requireId(e),this.request({method:"GET",path:a(qe,e)})}verifyClient(e){return this.request({method:"POST",path:a(qe,"verify"),bodyParams:{token:e}})}};var ue="/email_addresses",de=class extends f{async getEmailAddress(e){return this.requireId(e),this.request({method:"GET",path:a(ue,e)})}async createEmailAddress(e){return this.request({method:"POST",path:ue,bodyParams:e})}async updateEmailAddress(e,r={}){return this.requireId(e),this.request({method:"PATCH",path:a(ue,e),bodyParams:r})}async deleteEmailAddress(e){return this.requireId(e),this.request({method:"DELETE",path:a(ue,e)})}};var Lt="/emails",ce=class extends f{async createEmail(e){return this.request({method:"POST",path:Lt,bodyParams:e})}};var pe=class extends f{async getInterstitial(){return this.request({path:"internal/interstitial",method:"GET",headerParams:{"Content-Type":"text/html"}})}};var Ue="/invitations",me=class extends f{async getInvitationList(){return this.request({method:"GET",path:Ue})}async createInvitation(e){return this.request({method:"POST",path:Ue,bodyParams:e})}async revokeInvitation(e){return this.requireId(e),this.request({method:"POST",path:a(Ue,e,"revoke")})}};var J="/organizations",ge=class extends f{async getOrganizationList(e){return this.request({method:"GET",path:J,queryParams:e})}async createOrganization(e){return this.request({method:"POST",path:J,bodyParams:e})}async getOrganization(e){let r="organizationId"in e?e.organizationId:e.slug;return this.requireId(r),this.request({method:"GET",path:a(J,r)})}async updateOrganization(e,r){return this.requireId(e),this.request({method:"PATCH",path:a(J,e),bodyParams:r})}async updateOrganizationMetadata(e,r){return this.requireId(e),this.request({method:"PATCH",path:a(J,e,"metadata"),bodyParams:r})}async deleteOrganization(e){return this.request({method:"DELETE",path:a(J,e)})}async getOrganizationMembershipList(e){let{organizationId:r,limit:n,offset:i}=e;return this.requireId(r),this.request({method:"GET",path:a(J,r,"memberships"),queryParams:{limit:n,offset:i}})}async createOrganizationMembership(e){let{organizationId:r,userId:n,role:i}=e;return this.requireId(r),this.request({method:"POST",path:a(J,r,"memberships"),bodyParams:{userId:n,role:i}})}async updateOrganizationMembership(e){let{organizationId:r,userId:n,role:i}=e;return this.requireId(r),this.request({method:"PATCH",path:a(J,r,"memberships",n),bodyParams:{role:i}})}async updateOrganizationMembershipMetadata(e){let{organizationId:r,userId:n,publicMetadata:i,privateMetadata:o}=e;return this.request({method:"PATCH",path:a(J,r,"memberships",n,"metadata"),bodyParams:{publicMetadata:i,privateMetadata:o}})}async deleteOrganizationMembership(e){let{organizationId:r,userId:n}=e;return this.requireId(r),this.request({method:"DELETE",path:a(J,r,"memberships",n)})}async getPendingOrganizationInvitationList(e){let{organizationId:r,limit:n,offset:i}=e;return this.requireId(r),this.request({method:"GET",path:a(J,r,"invitations","pending"),queryParams:{limit:n,offset:i}})}async createOrganizationInvitation(e){let{organizationId:r,...n}=e;return this.requireId(r),this.request({method:"POST",path:a(J,r,"invitations"),bodyParams:{...n}})}async revokeOrganizationInvitation(e){let{organizationId:r,invitationId:n,requestingUserId:i}=e;return this.requireId(r),this.request({method:"POST",path:a(J,r,"invitations",n,"revoke"),bodyParams:{requestingUserId:i}})}};var fe="/phone_numbers",he=class extends f{async getPhoneNumber(e){return this.requireId(e),this.request({method:"GET",path:a(fe,e)})}async createPhoneNumber(e){return this.request({method:"POST",path:fe,bodyParams:e})}async updatePhoneNumber(e,r={}){return this.requireId(e),this.request({method:"PATCH",path:a(fe,e),bodyParams:r})}async deletePhoneNumber(e){return this.requireId(e),this.request({method:"DELETE",path:a(fe,e)})}};var ye="/redirect_urls",be=class extends f{async getRedirectUrlList(){return this.request({method:"GET",path:ye})}async getRedirectUrl(e){return this.requireId(e),this.request({method:"GET",path:a(ye,e)})}async createRedirectUrl(e){return this.request({method:"POST",path:ye,bodyParams:e})}async deleteRedirectUrl(e){return this.requireId(e),this.request({method:"DELETE",path:a(ye,e)})}};var re="/sessions",Se=class extends f{constructor(){super(...arguments);this.getSessionList=async r=>this.request({method:"GET",path:re,queryParams:r});this.getSession=async r=>(this.requireId(r),this.request({method:"GET",path:a(re,r)}));this.revokeSession=async r=>(this.requireId(r),this.request({method:"POST",path:a(re,r,"revoke")}));this.verifySession=async(r,n)=>(this.requireId(r),this.request({method:"POST",path:a(re,r,"verify"),bodyParams:{token:n}}));this.getToken=async(r,n)=>(this.requireId(r),(await this.request({method:"POST",path:a(re,r,"tokens",n||"")})).jwt)}};var rt="/sign_in_tokens",Oe=class extends f{async createSignInToken(e){return this.request({method:"POST",path:rt,bodyParams:e})}async revokeSignInToken(e){return this.requireId(e),this.request({method:"POST",path:a(rt,e,"revoke")})}};var Ft="/sms_messages",ke=class extends f{async createSMSMessage(e){return this.request({method:"POST",path:Ft,bodyParams:e})}};var R="/users",Ie=class extends f{async getUserList(e={}){return this.request({method:"GET",path:R,queryParams:e})}async getUser(e){return this.requireId(e),this.request({method:"GET",path:a(R,e)})}async createUser(e){return this.request({method:"POST",path:R,bodyParams:e})}async updateUser(e,r={}){return this.requireId(e),this.request({method:"PATCH",path:a(R,e),bodyParams:r})}async updateUserMetadata(e,r){return this.requireId(e),this.request({method:"PATCH",path:a(R,e,"metadata"),bodyParams:r})}async deleteUser(e){return this.requireId(e),this.request({method:"DELETE",path:a(R,e)})}async getCount(e={}){return this.request({method:"GET",path:a(R,"count"),queryParams:e})}async getUserOauthAccessToken(e,r){return this.requireId(e),this.request({method:"GET",path:a(R,e,"oauth_access_tokens",r)})}async disableUserMFA(e){return this.requireId(e),this.request({method:"DELETE",path:a(R,e,"mfa")})}async getOrganizationMembershipList(e){let{userId:r,limit:n,offset:i}=e;return this.requireId(r),this.request({method:"GET",path:a(R,r,"organization_memberships"),queryParams:{limit:n,offset:i}})}};var lt=oe(require("deepmerge")),je=oe(require("snakecase-keys"));var z="https://api.clerk.dev",T="v1",nt="@clerk/backend",Vt={AuthStatus:"__clerkAuthStatus"},Dt={Session:"__session",ClientUat:"__client_uat"},it={AuthStatus:"x-clerk-auth-status",AuthReason:"x-clerk-auth-reason",AuthMessage:"x-clerk-auth-message",Authorization:"authorization",ForwardedPort:"x-forwarded-port",ForwardedHost:"x-forwarded-host",Referrer:"referer",UserAgent:"user-agent",Origin:"origin",Host:"host"},Gt={AuthStatus:it.AuthStatus},st={Attributes:Vt,Cookies:Dt,Headers:it,SearchParams:Gt};var ot=oe(require("#crypto")),at=oe(require("#fetch")),$t={crypto:ot.default,fetch:at.default},N=$t;var K=class{constructor(e,r,n,i,o){this.id=e;this.identifier=r;this.createdAt=n;this.updatedAt=i;this.invitationId=o}static fromJSON(e){return new K(e.id,e.identifier,e.created_at,e.updated_at,e.invitation_id)}};var C=class{constructor(e,r,n,i,o,u,m,g,O){this.id=e;this.clientId=r;this.userId=n;this.status=i;this.lastActiveAt=o;this.expireAt=u;this.abandonAt=m;this.createdAt=g;this.updatedAt=O}static fromJSON(e){return new C(e.id,e.client_id,e.user_id,e.status,e.last_active_at,e.expire_at,e.abandon_at,e.created_at,e.updated_at)}};var j=class{constructor(e,r,n,i,o,u,m,g){this.id=e;this.sessionIds=r;this.sessions=n;this.signInId=i;this.signUpId=o;this.lastActiveSessionId=u;this.createdAt=m;this.updatedAt=g}static fromJSON(e){return new j(e.id,e.session_ids,e.sessions.map(r=>C.fromJSON(r)),e.sign_in_id,e.sign_up_id,e.last_active_session_id,e.created_at,e.updated_at)}};var W=class{constructor(e,r,n,i){this.object=e;this.id=r;this.slug=n;this.deleted=i}static fromJSON(e){return new W(e.object,e.id||null,e.slug||null,e.deleted)}};var L=class{constructor(e,r,n,i,o,u,m){this.id=e;this.fromEmailName=r;this.emailAddressId=n;this.toEmailAddress=i;this.subject=o;this.body=u;this.status=m}static fromJSON(e){return new L(e.id,e.from_email_name,e.email_address_id,e.to_email_address,e.subject,e.body,e.status)}};var v=class{constructor(e,r){this.id=e;this.type=r}static fromJSON(e){return new v(e.id,e.type)}};var x=class{constructor(e,r,n=null,i=null,o=null,u=null){this.status=e;this.strategy=r;this.externalVerificationRedirectURL=n;this.attempts=i;this.expireAt=o;this.nonce=u}static fromJSON(e){return new x(e.status,e.strategy,e.external_verification_redirect_url?new URL(e.external_verification_redirect_url):null,e.attempts,e.expire_at,e.nonce)}};var E=class{constructor(e,r,n,i){this.id=e;this.emailAddress=r;this.verification=n;this.linkedTo=i}static fromJSON(e){return new E(e.id,e.email_address,e.verification&&x.fromJSON(e.verification),e.linked_to.map(r=>v.fromJSON(r)))}};var F=class{constructor(e,r,n,i,o,u,m,g,O,_,k={},P,b){this.id=e;this.provider=r;this.identificationId=n;this.externalId=i;this.approvedScopes=o;this.emailAddress=u;this.firstName=m;this.lastName=g;this.picture=O;this.username=_;this.publicMetadata=k;this.label=P;this.verification=b}static fromJSON(e){return new F(e.id,e.provider,e.identification_id,e.provider_user_id,e.approved_scopes,e.email_address,e.first_name,e.last_name,e.avatar_url,e.username,e.public_metadata,e.label,e.verification&&x.fromJSON(e.verification))}};var V=class{constructor(e,r,n,i,o,u){this.id=e;this.emailAddress=r;this.publicMetadata=n;this.createdAt=i;this.updatedAt=o;this.revoked=u}static fromJSON(e){return new V(e.id,e.email_address,e.public_metadata,e.created_at,e.updated_at,e.revoked)}};var ze=(c=>(c.AllowlistIdentifier="allowlist_identifier",c.Client="client",c.Email="email",c.EmailAddress="email_address",c.ExternalAccount="external_account",c.FacebookAccount="facebook_account",c.GoogleAccount="google_account",c.Invitation="invitation",c.OauthAccessToken="oauth_access_token",c.Organization="organization",c.OrganizationInvitation="organization_invitation",c.OrganizationMembership="organization_membership",c.PhoneNumber="phone_number",c.RedirectUrl="redirect_url",c.Session="session",c.SignInAttempt="sign_in_attempt",c.SignInToken="sign_in_token",c.SignUpAttempt="sign_up_attempt",c.SmsMessage="sms_message",c.User="user",c.Web3Wallet="web3_wallet",c.Token="token",c.TotalCount="total_count",c))(ze||{});var D=class{constructor(e,r,n={},i,o,u){this.provider=e;this.token=r;this.publicMetadata=n;this.label=i;this.scopes=o;this.tokenSecret=u}static fromJSON(e){return new D(e.provider,e.token,e.public_metadata,e.label,e.scopes,e.token_secret)}};var q=class{constructor(e,r,n,i,o,u,m={},g={}){this.id=e;this.name=r;this.slug=n;this.logoUrl=i;this.createdAt=o;this.updatedAt=u;this.publicMetadata=m;this.privateMetadata=g}static fromJSON(e){return new q(e.id,e.name,e.slug,e.logo_url,e.created_at,e.updated_at,e.public_metadata,e.private_metadata)}};var G=class{constructor(e,r,n,i,o,u,m){this.id=e;this.emailAddress=r;this.role=n;this.organizationId=i;this.createdAt=o;this.updatedAt=u;this.status=m}static fromJSON(e){return new G(e.id,e.email_address,e.role,e.organization_id,e.created_at,e.updated_at,e.status)}};var $=class{constructor(e,r,n={},i={},o,u,m,g){this.id=e;this.role=r;this.publicMetadata=n;this.privateMetadata=i;this.createdAt=o;this.updatedAt=u;this.organization=m;this.publicUserData=g}static fromJSON(e){return new $(e.id,e.role,e.public_metadata,e.private_metadata,e.created_at,e.updated_at,q.fromJSON(e.organization),Z.fromJSON(e.public_user_data))}},Z=class{constructor(e,r,n,i,o){this.identifier=e;this.firstName=r;this.lastName=n;this.profileImageUrl=i;this.userId=o}static fromJSON(e){return new Z(e.identifier,e.first_name,e.last_name,e.profile_image_url,e.user_id)}};var U=class{constructor(e,r,n,i,o,u){this.id=e;this.phoneNumber=r;this.reservedForSecondFactor=n;this.defaultSecondFactor=i;this.verification=o;this.linkedTo=u}static fromJSON(e){return new U(e.id,e.phone_number,e.reserved_for_second_factor,e.default_second_factor,e.verification&&x.fromJSON(e.verification),e.linked_to.map(r=>v.fromJSON(r)))}};var B=class{constructor(e,r,n,i){this.id=e;this.url=r;this.createdAt=n;this.updatedAt=i}static fromJSON(e){return new B(e.id,e.url,e.created_at,e.updated_at)}};var H=class{constructor(e,r,n,i,o,u){this.id=e;this.userId=r;this.token=n;this.status=i;this.createdAt=o;this.updatedAt=u}static fromJSON(e){return new H(e.id,e.user_id,e.token,e.status,e.created_at,e.updated_at)}};var Y=class{constructor(e,r,n,i,o,u){this.id=e;this.fromPhoneNumber=r;this.toPhoneNumber=n;this.message=i;this.status=o;this.phoneNumberId=u}static fromJSON(e){return new Y(e.id,e.from_phone_number,e.to_phone_number,e.message,e.status,e.phone_number_id)}};var Q=class{constructor(e){this.jwt=e}static fromJSON(e){return new Q(e.jwt)}};var ee=class{constructor(e,r,n){this.id=e;this.web3Wallet=r;this.verification=n}static fromJSON(e){return new ee(e.id,e.web3_wallet,e.verification&&x.fromJSON(e.verification))}};var X=class{constructor(e,r,n,i,o,u,m,g,O,_,k,P,b,I,A,w,s,l,p,h={},S={},y={},c=[],M=[],Ce=[],et=[]){this.id=e;this.passwordEnabled=r;this.totpEnabled=n;this.backupCodeEnabled=i;this.twoFactorEnabled=o;this.banned=u;this.createdAt=m;this.updatedAt=g;this.profileImageUrl=O;this.gender=_;this.birthday=k;this.primaryEmailAddressId=P;this.primaryPhoneNumberId=b;this.primaryWeb3WalletId=I;this.lastSignInAt=A;this.externalId=w;this.username=s;this.firstName=l;this.lastName=p;this.publicMetadata=h;this.privateMetadata=S;this.unsafeMetadata=y;this.emailAddresses=c;this.phoneNumbers=M;this.web3Wallets=Ce;this.externalAccounts=et}static fromJSON(e){return new X(e.id,e.password_enabled,e.totp_enabled,e.backup_code_enabled,e.two_factor_enabled,e.banned,e.created_at,e.updated_at,e.profile_image_url,e.gender,e.birthday,e.primary_email_address_id,e.primary_phone_number_id,e.primary_web3_wallet_id,e.last_sign_in_at,e.external_id,e.username,e.first_name,e.last_name,e.public_metadata,e.private_metadata,e.unsafe_metadata,(e.email_addresses||[]).map(r=>E.fromJSON(r)),(e.phone_numbers||[]).map(r=>U.fromJSON(r)),(e.web3_wallets||[]).map(r=>ee.fromJSON(r)),(e.external_accounts||[]).map(r=>F.fromJSON(r)))}};function Ke(t){return Array.isArray(t)?t.map(e=>Me(e)):Bt(t)?t.data.map(e=>Me(e)):Me(t)}function Bt(t){return t.data!==void 0}function Ht(t){return t.total_count}function Me(t){if(typeof t!="string"&&"object"in t&&"deleted"in t)return W.fromJSON(t);switch(t.object){case"allowlist_identifier":return K.fromJSON(t);case"client":return j.fromJSON(t);case"email_address":return E.fromJSON(t);case"email":return L.fromJSON(t);case"invitation":return V.fromJSON(t);case"oauth_access_token":return D.fromJSON(t);case"organization":return q.fromJSON(t);case"organization_invitation":return G.fromJSON(t);case"organization_membership":return $.fromJSON(t);case"phone_number":return U.fromJSON(t);case"redirect_url":return B.fromJSON(t);case"sign_in_token":return H.fromJSON(t);case"session":return C.fromJSON(t);case"sms_message":return Y.fromJSON(t);case"token":return Q.fromJSON(t);case"total_count":return Ht(t);case"user":return X.fromJSON(t);default:return t}}var Yt=t=>async(...e)=>{let{data:r,errors:n,status:i,statusText:o}=await t(...e);if(n===null)return r;throw new ne(o||"",{data:n,status:i||""})};function ut(t){return Yt(async r=>{let{apiKey:n,secretKey:i,apiUrl:o=z,apiVersion:u=T,userAgent:m=nt,httpOptions:g={}}=t,{path:O,method:_,queryParams:k,headerParams:P,bodyParams:b}=r,I=i||n;if(!I)throw Error("Missing Clerk Secret Key or API Key. Go to https://dashboard.clerk.dev and get your key for your instance.");let A=a(o,u,O),w=new URL(A);if(k){let S=(0,je.default)({...k});for(let[y,c]of Object.entries(S))c&&[c].flat().forEach(M=>w.searchParams.append(y,M))}let s={Authorization:`Bearer ${I}`,"Content-Type":"application/json","Clerk-Backend-SDK":m,...P},p=_!=="GET"&&b&&Object.keys(b).length>0?{body:JSON.stringify((0,je.default)(b,{deep:!1}))}:null,h;try{h=await N.fetch(w.href,(0,lt.default)(g,{method:_,headers:s,...p}));let y=await(s&&s["Content-Type"]==="application/json"?h.json():h.text());if(!h.ok)throw y;return{data:Ke(y),errors:null}}catch(S){return S instanceof Error?{data:null,errors:[{code:"unexpected_error",message:S.message||"Unexpected error"}]}:{data:null,errors:Qt(S),status:h?.status,statusText:h?.statusText}}})}function Qt(t){if(!!t&&typeof t=="object"&&"errors"in t){let e=t.errors;return e.length>0?e.map(Xt):[]}return[]}function Xt(t){return{code:t.code,message:t.message,longMessage:t.long_message,meta:{paramName:t?.meta?.param_name,sessionId:t?.meta?.session_id}}}var ne=class extends Error{constructor(r,{data:n,status:i}){super(r);Object.setPrototypeOf(this,ne.prototype),this.clerkError=!0,this.message=r,this.status=i,this.errors=n}};function te(t){let e=ut(t);return{allowlistIdentifiers:new ae(e),clients:new le(e),emailAddresses:new de(e),emails:new ce(e),interstitial:new pe(e),invitations:new me(e),organizations:new ge(e),phoneNumbers:new he(e),redirectUrls:new be(e),sessions:new Se(e),signInTokens:new Oe(e),smsMessages:new ke(e),users:new Ie(e)}}var dt=t=>()=>{let e={...t};return e.apiKey=(e.apiKey||"").substring(0,7),e.jwtKey=(e.jwtKey||"").substring(0,7),{...e}};function Le(t,e,r){let{act:n,sid:i,org_id:o,org_role:u,org_slug:m,sub:g}=t,{apiKey:O,secretKey:_,apiUrl:k,apiVersion:P,token:b,session:I,user:A,organization:w}=e,{sessions:s}=te({apiKey:O,secretKey:_,apiUrl:k,apiVersion:P}),l=er({sessionId:i,sessionToken:b,fetcher:(...p)=>s.getToken(...p)});return{actor:n,sessionClaims:t,sessionId:i,session:I,userId:g,user:A,orgId:o,orgRole:u,orgSlug:m,organization:w,getToken:l,debug:dt(r)}}function Fe(t){return{sessionClaims:null,sessionId:null,session:null,userId:null,user:null,actor:null,orgId:null,orgRole:null,orgSlug:null,organization:null,getToken:()=>Promise.resolve(null),debug:dt(t)}}function We(t){return t&&(delete t.privateMetadata,delete t.private_metadata),t}function Zt(t){let e=t.user?{...t.user}:t.user,r=t.organization?{...t.organization}:t.organization;return We(e),We(r),{...t,user:e,organization:r}}var er=t=>{let{fetcher:e,sessionToken:r,sessionId:n}=t||{};return async(i={})=>n?i.template?e(n,i.template):r:null};var De=require("@clerk/shared");function tr(t){return new Promise(e=>setTimeout(e,t))}var rr=5;async function ie(t,e=1,r=rr){try{return await t()}catch(n){if(e>=r)throw n;return await tr(2**e*100),ie(t,e+1)}}function _e(t){return t.startsWith("test_")||t.startsWith("sk_test_")}function ct(t){return t.startsWith("live_")||t.startsWith("sk_live_")}function pt(t){return t.endsWith(".lclstage.dev")||t.endsWith(".stgstage.dev")||t.endsWith(".clerkstage.dev")||t.endsWith(".accountsstage.dev")}var d=class extends Error{constructor({action:r,message:n,reason:i}){super(n);Object.setPrototypeOf(this,d.prototype),this.reason=i,this.message=n,this.action=r}getFullMessage(){return`${[this.message,this.action].filter(r=>r).join(" ")} (reason=${this.reason}, token-carrier=${this.tokenCarrier})`}};function Pe(t){let{debugData:e,frontendApi:r,pkgVersion:n,publishableKey:i}=t;return` | ||
"use strict";var qt=Object.create;var oe=Object.defineProperty;var Ut=Object.getOwnPropertyDescriptor;var zt=Object.getOwnPropertyNames;var Mt=Object.getPrototypeOf,Kt=Object.prototype.hasOwnProperty;var jt=(t,e)=>{for(var r in e)oe(t,r,{get:e[r],enumerable:!0})},tt=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of zt(e))!Kt.call(t,i)&&i!==r&&oe(t,i,{get:()=>e[i],enumerable:!(n=Ut(e,i))||n.enumerable});return t};var ae=(t,e,r)=>(r=t!=null?qt(Mt(t)):{},tt(e||!t||!t.__esModule?oe(r,"default",{value:t,enumerable:!0}):r,t)),Wt=t=>tt(oe({},"__esModule",{value:!0}),t);var hr={};jt(hr,{AllowlistIdentifier:()=>K,AuthStatus:()=>Ze,Clerk:()=>fr,Client:()=>j,DeletedObject:()=>W,Email:()=>L,EmailAddress:()=>E,ExternalAccount:()=>F,IdentificationLink:()=>v,Invitation:()=>V,OauthAccessToken:()=>D,ObjectType:()=>Me,Organization:()=>q,OrganizationInvitation:()=>G,OrganizationMembership:()=>$,OrganizationMembershipPublicUserData:()=>Z,PhoneNumber:()=>U,RedirectUrl:()=>B,SMSMessage:()=>Y,Session:()=>C,SignInToken:()=>H,Token:()=>Q,User:()=>X,Verification:()=>x,constants:()=>st,createAuthenticateRequest:()=>et,debugRequestState:()=>Ce,decodeJwt:()=>Re,deserialize:()=>je,hasValidSignature:()=>ft,loadInterstitialFromLocal:()=>Je,prunePrivateMetadata:()=>Le,sanitizeAuthObject:()=>er,signedInAuthObject:()=>Fe,signedOutAuthObject:()=>Ve,verifyJwt:()=>Qe,verifyToken:()=>Xe});module.exports=Wt(hr);var h=class{constructor(e){this.request=e}requireId(e){if(!e)throw new Error("A valid resource ID is required.")}};var Ee="/",Lt=new RegExp(Ee+"{1,}","g");function a(...t){return t.filter(e=>e).join(Ee).replace(Lt,Ee)}var qe="/allowlist_identifiers",le=class extends h{async getAllowlistIdentifierList(){return this.request({method:"GET",path:qe})}async createAllowlistIdentifier(e){return this.request({method:"POST",path:qe,bodyParams:e})}async deleteAllowlistIdentifier(e){return this.requireId(e),this.request({method:"DELETE",path:a(qe,e)})}};var Ue="/clients",ue=class extends h{async getClientList(){return this.request({method:"GET",path:Ue})}async getClient(e){return this.requireId(e),this.request({method:"GET",path:a(Ue,e)})}verifyClient(e){return this.request({method:"POST",path:a(Ue,"verify"),bodyParams:{token:e}})}};var de="/email_addresses",ce=class extends h{async getEmailAddress(e){return this.requireId(e),this.request({method:"GET",path:a(de,e)})}async createEmailAddress(e){return this.request({method:"POST",path:de,bodyParams:e})}async updateEmailAddress(e,r={}){return this.requireId(e),this.request({method:"PATCH",path:a(de,e),bodyParams:r})}async deleteEmailAddress(e){return this.requireId(e),this.request({method:"DELETE",path:a(de,e)})}};var Ft="/emails",pe=class extends h{async createEmail(e){return this.request({method:"POST",path:Ft,bodyParams:e})}};var me=class extends h{async getInterstitial(){return this.request({path:"internal/interstitial",method:"GET",headerParams:{"Content-Type":"text/html"}})}};var ze="/invitations",ge=class extends h{async getInvitationList(){return this.request({method:"GET",path:ze})}async createInvitation(e){return this.request({method:"POST",path:ze,bodyParams:e})}async revokeInvitation(e){return this.requireId(e),this.request({method:"POST",path:a(ze,e,"revoke")})}};var J="/organizations",fe=class extends h{async getOrganizationList(e){return this.request({method:"GET",path:J,queryParams:e})}async createOrganization(e){return this.request({method:"POST",path:J,bodyParams:e})}async getOrganization(e){let r="organizationId"in e?e.organizationId:e.slug;return this.requireId(r),this.request({method:"GET",path:a(J,r)})}async updateOrganization(e,r){return this.requireId(e),this.request({method:"PATCH",path:a(J,e),bodyParams:r})}async updateOrganizationMetadata(e,r){return this.requireId(e),this.request({method:"PATCH",path:a(J,e,"metadata"),bodyParams:r})}async deleteOrganization(e){return this.request({method:"DELETE",path:a(J,e)})}async getOrganizationMembershipList(e){let{organizationId:r,limit:n,offset:i}=e;return this.requireId(r),this.request({method:"GET",path:a(J,r,"memberships"),queryParams:{limit:n,offset:i}})}async createOrganizationMembership(e){let{organizationId:r,userId:n,role:i}=e;return this.requireId(r),this.request({method:"POST",path:a(J,r,"memberships"),bodyParams:{userId:n,role:i}})}async updateOrganizationMembership(e){let{organizationId:r,userId:n,role:i}=e;return this.requireId(r),this.request({method:"PATCH",path:a(J,r,"memberships",n),bodyParams:{role:i}})}async updateOrganizationMembershipMetadata(e){let{organizationId:r,userId:n,publicMetadata:i,privateMetadata:o}=e;return this.request({method:"PATCH",path:a(J,r,"memberships",n,"metadata"),bodyParams:{publicMetadata:i,privateMetadata:o}})}async deleteOrganizationMembership(e){let{organizationId:r,userId:n}=e;return this.requireId(r),this.request({method:"DELETE",path:a(J,r,"memberships",n)})}async getPendingOrganizationInvitationList(e){let{organizationId:r,limit:n,offset:i}=e;return this.requireId(r),this.request({method:"GET",path:a(J,r,"invitations","pending"),queryParams:{limit:n,offset:i}})}async createOrganizationInvitation(e){let{organizationId:r,...n}=e;return this.requireId(r),this.request({method:"POST",path:a(J,r,"invitations"),bodyParams:{...n}})}async revokeOrganizationInvitation(e){let{organizationId:r,invitationId:n,requestingUserId:i}=e;return this.requireId(r),this.request({method:"POST",path:a(J,r,"invitations",n,"revoke"),bodyParams:{requestingUserId:i}})}};var he="/phone_numbers",ye=class extends h{async getPhoneNumber(e){return this.requireId(e),this.request({method:"GET",path:a(he,e)})}async createPhoneNumber(e){return this.request({method:"POST",path:he,bodyParams:e})}async updatePhoneNumber(e,r={}){return this.requireId(e),this.request({method:"PATCH",path:a(he,e),bodyParams:r})}async deletePhoneNumber(e){return this.requireId(e),this.request({method:"DELETE",path:a(he,e)})}};var be="/redirect_urls",Se=class extends h{async getRedirectUrlList(){return this.request({method:"GET",path:be})}async getRedirectUrl(e){return this.requireId(e),this.request({method:"GET",path:a(be,e)})}async createRedirectUrl(e){return this.request({method:"POST",path:be,bodyParams:e})}async deleteRedirectUrl(e){return this.requireId(e),this.request({method:"DELETE",path:a(be,e)})}};var ne="/sessions",Oe=class extends h{constructor(){super(...arguments);this.getSessionList=async r=>this.request({method:"GET",path:ne,queryParams:r});this.getSession=async r=>(this.requireId(r),this.request({method:"GET",path:a(ne,r)}));this.revokeSession=async r=>(this.requireId(r),this.request({method:"POST",path:a(ne,r,"revoke")}));this.verifySession=async(r,n)=>(this.requireId(r),this.request({method:"POST",path:a(ne,r,"verify"),bodyParams:{token:n}}));this.getToken=async(r,n)=>(this.requireId(r),(await this.request({method:"POST",path:a(ne,r,"tokens",n||"")})).jwt)}};var rt="/sign_in_tokens",ke=class extends h{async createSignInToken(e){return this.request({method:"POST",path:rt,bodyParams:e})}async revokeSignInToken(e){return this.requireId(e),this.request({method:"POST",path:a(rt,e,"revoke")})}};var Vt="/sms_messages",Ie=class extends h{async createSMSMessage(e){return this.request({method:"POST",path:Vt,bodyParams:e})}};var R="/users",_e=class extends h{async getUserList(e={}){return this.request({method:"GET",path:R,queryParams:e})}async getUser(e){return this.requireId(e),this.request({method:"GET",path:a(R,e)})}async createUser(e){return this.request({method:"POST",path:R,bodyParams:e})}async updateUser(e,r={}){return this.requireId(e),this.request({method:"PATCH",path:a(R,e),bodyParams:r})}async updateUserMetadata(e,r){return this.requireId(e),this.request({method:"PATCH",path:a(R,e,"metadata"),bodyParams:r})}async deleteUser(e){return this.requireId(e),this.request({method:"DELETE",path:a(R,e)})}async getCount(e={}){return this.request({method:"GET",path:a(R,"count"),queryParams:e})}async getUserOauthAccessToken(e,r){return this.requireId(e),this.request({method:"GET",path:a(R,e,"oauth_access_tokens",r)})}async disableUserMFA(e){return this.requireId(e),this.request({method:"DELETE",path:a(R,e,"mfa")})}async getOrganizationMembershipList(e){let{userId:r,limit:n,offset:i}=e;return this.requireId(r),this.request({method:"GET",path:a(R,r,"organization_memberships"),queryParams:{limit:n,offset:i}})}};var lt=ae(require("deepmerge")),We=ae(require("snakecase-keys"));var z="https://api.clerk.dev",T="v1",nt="@clerk/backend",Dt={AuthStatus:"__clerkAuthStatus"},Gt={Session:"__session",ClientUat:"__client_uat"},it={AuthStatus:"x-clerk-auth-status",AuthReason:"x-clerk-auth-reason",AuthMessage:"x-clerk-auth-message",Authorization:"authorization",ForwardedPort:"x-forwarded-port",ForwardedHost:"x-forwarded-host",Referrer:"referer",UserAgent:"user-agent",Origin:"origin",Host:"host"},$t={AuthStatus:it.AuthStatus},st={Attributes:Dt,Cookies:Gt,Headers:it,SearchParams:$t};var ot=ae(require("#crypto")),at=ae(require("#fetch")),Bt={crypto:ot.default,fetch:at.default},N=Bt;var K=class{constructor(e,r,n,i,o){this.id=e;this.identifier=r;this.createdAt=n;this.updatedAt=i;this.invitationId=o}static fromJSON(e){return new K(e.id,e.identifier,e.created_at,e.updated_at,e.invitation_id)}};var C=class{constructor(e,r,n,i,o,u,m,f,S){this.id=e;this.clientId=r;this.userId=n;this.status=i;this.lastActiveAt=o;this.expireAt=u;this.abandonAt=m;this.createdAt=f;this.updatedAt=S}static fromJSON(e){return new C(e.id,e.client_id,e.user_id,e.status,e.last_active_at,e.expire_at,e.abandon_at,e.created_at,e.updated_at)}};var j=class{constructor(e,r,n,i,o,u,m,f){this.id=e;this.sessionIds=r;this.sessions=n;this.signInId=i;this.signUpId=o;this.lastActiveSessionId=u;this.createdAt=m;this.updatedAt=f}static fromJSON(e){return new j(e.id,e.session_ids,e.sessions.map(r=>C.fromJSON(r)),e.sign_in_id,e.sign_up_id,e.last_active_session_id,e.created_at,e.updated_at)}};var W=class{constructor(e,r,n,i){this.object=e;this.id=r;this.slug=n;this.deleted=i}static fromJSON(e){return new W(e.object,e.id||null,e.slug||null,e.deleted)}};var L=class{constructor(e,r,n,i,o,u,m){this.id=e;this.fromEmailName=r;this.emailAddressId=n;this.toEmailAddress=i;this.subject=o;this.body=u;this.status=m}static fromJSON(e){return new L(e.id,e.from_email_name,e.email_address_id,e.to_email_address,e.subject,e.body,e.status)}};var v=class{constructor(e,r){this.id=e;this.type=r}static fromJSON(e){return new v(e.id,e.type)}};var x=class{constructor(e,r,n=null,i=null,o=null,u=null){this.status=e;this.strategy=r;this.externalVerificationRedirectURL=n;this.attempts=i;this.expireAt=o;this.nonce=u}static fromJSON(e){return new x(e.status,e.strategy,e.external_verification_redirect_url?new URL(e.external_verification_redirect_url):null,e.attempts,e.expire_at,e.nonce)}};var E=class{constructor(e,r,n,i){this.id=e;this.emailAddress=r;this.verification=n;this.linkedTo=i}static fromJSON(e){return new E(e.id,e.email_address,e.verification&&x.fromJSON(e.verification),e.linked_to.map(r=>v.fromJSON(r)))}};var F=class{constructor(e,r,n,i,o,u,m,f,S,I,O={},P,b){this.id=e;this.provider=r;this.identificationId=n;this.externalId=i;this.approvedScopes=o;this.emailAddress=u;this.firstName=m;this.lastName=f;this.picture=S;this.username=I;this.publicMetadata=O;this.label=P;this.verification=b}static fromJSON(e){return new F(e.id,e.provider,e.identification_id,e.provider_user_id,e.approved_scopes,e.email_address,e.first_name,e.last_name,e.avatar_url,e.username,e.public_metadata,e.label,e.verification&&x.fromJSON(e.verification))}};var V=class{constructor(e,r,n,i,o,u){this.id=e;this.emailAddress=r;this.publicMetadata=n;this.createdAt=i;this.updatedAt=o;this.revoked=u}static fromJSON(e){return new V(e.id,e.email_address,e.public_metadata,e.created_at,e.updated_at,e.revoked)}};var Me=(p=>(p.AllowlistIdentifier="allowlist_identifier",p.Client="client",p.Email="email",p.EmailAddress="email_address",p.ExternalAccount="external_account",p.FacebookAccount="facebook_account",p.GoogleAccount="google_account",p.Invitation="invitation",p.OauthAccessToken="oauth_access_token",p.Organization="organization",p.OrganizationInvitation="organization_invitation",p.OrganizationMembership="organization_membership",p.PhoneNumber="phone_number",p.RedirectUrl="redirect_url",p.Session="session",p.SignInAttempt="sign_in_attempt",p.SignInToken="sign_in_token",p.SignUpAttempt="sign_up_attempt",p.SmsMessage="sms_message",p.User="user",p.Web3Wallet="web3_wallet",p.Token="token",p.TotalCount="total_count",p))(Me||{});var D=class{constructor(e,r,n={},i,o,u){this.provider=e;this.token=r;this.publicMetadata=n;this.label=i;this.scopes=o;this.tokenSecret=u}static fromJSON(e){return new D(e.provider,e.token,e.public_metadata,e.label,e.scopes,e.token_secret)}};var q=class{constructor(e,r,n,i,o,u,m={},f={}){this.id=e;this.name=r;this.slug=n;this.logoUrl=i;this.createdAt=o;this.updatedAt=u;this.publicMetadata=m;this.privateMetadata=f}static fromJSON(e){return new q(e.id,e.name,e.slug,e.logo_url,e.created_at,e.updated_at,e.public_metadata,e.private_metadata)}};var G=class{constructor(e,r,n,i,o,u,m){this.id=e;this.emailAddress=r;this.role=n;this.organizationId=i;this.createdAt=o;this.updatedAt=u;this.status=m}static fromJSON(e){return new G(e.id,e.email_address,e.role,e.organization_id,e.created_at,e.updated_at,e.status)}};var $=class{constructor(e,r,n={},i={},o,u,m,f){this.id=e;this.role=r;this.publicMetadata=n;this.privateMetadata=i;this.createdAt=o;this.updatedAt=u;this.organization=m;this.publicUserData=f}static fromJSON(e){return new $(e.id,e.role,e.public_metadata,e.private_metadata,e.created_at,e.updated_at,q.fromJSON(e.organization),Z.fromJSON(e.public_user_data))}},Z=class{constructor(e,r,n,i,o){this.identifier=e;this.firstName=r;this.lastName=n;this.profileImageUrl=i;this.userId=o}static fromJSON(e){return new Z(e.identifier,e.first_name,e.last_name,e.profile_image_url,e.user_id)}};var U=class{constructor(e,r,n,i,o,u){this.id=e;this.phoneNumber=r;this.reservedForSecondFactor=n;this.defaultSecondFactor=i;this.verification=o;this.linkedTo=u}static fromJSON(e){return new U(e.id,e.phone_number,e.reserved_for_second_factor,e.default_second_factor,e.verification&&x.fromJSON(e.verification),e.linked_to.map(r=>v.fromJSON(r)))}};var B=class{constructor(e,r,n,i){this.id=e;this.url=r;this.createdAt=n;this.updatedAt=i}static fromJSON(e){return new B(e.id,e.url,e.created_at,e.updated_at)}};var H=class{constructor(e,r,n,i,o,u){this.id=e;this.userId=r;this.token=n;this.status=i;this.createdAt=o;this.updatedAt=u}static fromJSON(e){return new H(e.id,e.user_id,e.token,e.status,e.created_at,e.updated_at)}};var Y=class{constructor(e,r,n,i,o,u){this.id=e;this.fromPhoneNumber=r;this.toPhoneNumber=n;this.message=i;this.status=o;this.phoneNumberId=u}static fromJSON(e){return new Y(e.id,e.from_phone_number,e.to_phone_number,e.message,e.status,e.phone_number_id)}};var Q=class{constructor(e){this.jwt=e}static fromJSON(e){return new Q(e.jwt)}};var ee=class{constructor(e,r,n){this.id=e;this.web3Wallet=r;this.verification=n}static fromJSON(e){return new ee(e.id,e.web3_wallet,e.verification&&x.fromJSON(e.verification))}};var X=class{constructor(e,r,n,i,o,u,m,f,S,I,O,P,b,k,_,A,w,s,l,d={},y={},g={},p=[],M=[],re=[],ve=[]){this.id=e;this.passwordEnabled=r;this.totpEnabled=n;this.backupCodeEnabled=i;this.twoFactorEnabled=o;this.banned=u;this.createdAt=m;this.updatedAt=f;this.profileImageUrl=S;this.gender=I;this.birthday=O;this.primaryEmailAddressId=P;this.primaryPhoneNumberId=b;this.primaryWeb3WalletId=k;this.lastSignInAt=_;this.externalId=A;this.username=w;this.firstName=s;this.lastName=l;this.publicMetadata=d;this.privateMetadata=y;this.unsafeMetadata=g;this.emailAddresses=p;this.phoneNumbers=M;this.web3Wallets=re;this.externalAccounts=ve}static fromJSON(e){return new X(e.id,e.password_enabled,e.totp_enabled,e.backup_code_enabled,e.two_factor_enabled,e.banned,e.created_at,e.updated_at,e.profile_image_url,e.gender,e.birthday,e.primary_email_address_id,e.primary_phone_number_id,e.primary_web3_wallet_id,e.last_sign_in_at,e.external_id,e.username,e.first_name,e.last_name,e.public_metadata,e.private_metadata,e.unsafe_metadata,(e.email_addresses||[]).map(r=>E.fromJSON(r)),(e.phone_numbers||[]).map(r=>U.fromJSON(r)),(e.web3_wallets||[]).map(r=>ee.fromJSON(r)),(e.external_accounts||[]).map(r=>F.fromJSON(r)))}};function je(t){return Array.isArray(t)?t.map(e=>Ke(e)):Ht(t)?t.data.map(e=>Ke(e)):Ke(t)}function Ht(t){return t.data!==void 0}function Yt(t){return t.total_count}function Ke(t){if(typeof t!="string"&&"object"in t&&"deleted"in t)return W.fromJSON(t);switch(t.object){case"allowlist_identifier":return K.fromJSON(t);case"client":return j.fromJSON(t);case"email_address":return E.fromJSON(t);case"email":return L.fromJSON(t);case"invitation":return V.fromJSON(t);case"oauth_access_token":return D.fromJSON(t);case"organization":return q.fromJSON(t);case"organization_invitation":return G.fromJSON(t);case"organization_membership":return $.fromJSON(t);case"phone_number":return U.fromJSON(t);case"redirect_url":return B.fromJSON(t);case"sign_in_token":return H.fromJSON(t);case"session":return C.fromJSON(t);case"sms_message":return Y.fromJSON(t);case"token":return Q.fromJSON(t);case"total_count":return Yt(t);case"user":return X.fromJSON(t);default:return t}}var Qt=t=>async(...e)=>{let{data:r,errors:n,status:i,statusText:o}=await t(...e);if(n===null)return r;throw new ie(o||"",{data:n,status:i||""})};function ut(t){return Qt(async r=>{let{apiKey:n,secretKey:i,apiUrl:o=z,apiVersion:u=T,userAgent:m=nt,httpOptions:f={}}=t,{path:S,method:I,queryParams:O,headerParams:P,bodyParams:b}=r,k=i||n;if(!k)throw Error("Missing Clerk Secret Key or API Key. Go to https://dashboard.clerk.dev and get your key for your instance.");let _=a(o,u,S),A=new URL(_);if(O){let y=(0,We.default)({...O});for(let[g,p]of Object.entries(y))p&&[p].flat().forEach(M=>A.searchParams.append(g,M))}let w={Authorization:`Bearer ${k}`,"Content-Type":"application/json","Clerk-Backend-SDK":m,...P},l=I!=="GET"&&b&&Object.keys(b).length>0?{body:JSON.stringify((0,We.default)(b,{deep:!1}))}:null,d;try{d=await N.fetch(A.href,(0,lt.default)(f,{method:I,headers:w,...l}));let g=await(w&&w["Content-Type"]==="application/json"?d.json():d.text());if(!d.ok)throw g;return{data:je(g),errors:null}}catch(y){return y instanceof Error?{data:null,errors:[{code:"unexpected_error",message:y.message||"Unexpected error"}]}:{data:null,errors:Xt(y),status:d==null?void 0:d.status,statusText:d==null?void 0:d.statusText}}})}function Xt(t){if(!!t&&typeof t=="object"&&"errors"in t){let e=t.errors;return e.length>0?e.map(Zt):[]}return[]}function Zt(t){var e,r;return{code:t.code,message:t.message,longMessage:t.long_message,meta:{paramName:(e=t==null?void 0:t.meta)==null?void 0:e.param_name,sessionId:(r=t==null?void 0:t.meta)==null?void 0:r.session_id}}}var ie=class extends Error{constructor(r,{data:n,status:i}){super(r);Object.setPrototypeOf(this,ie.prototype),this.clerkError=!0,this.message=r,this.status=i,this.errors=n}};function te(t){let e=ut(t);return{allowlistIdentifiers:new le(e),clients:new ue(e),emailAddresses:new ce(e),emails:new pe(e),interstitial:new me(e),invitations:new ge(e),organizations:new fe(e),phoneNumbers:new ye(e),redirectUrls:new Se(e),sessions:new Oe(e),signInTokens:new ke(e),smsMessages:new Ie(e),users:new _e(e)}}var dt=t=>()=>{let e={...t};return e.apiKey=(e.apiKey||"").substring(0,7),e.jwtKey=(e.jwtKey||"").substring(0,7),{...e}};function Fe(t,e,r){let{act:n,sid:i,org_id:o,org_role:u,org_slug:m,sub:f}=t,{apiKey:S,secretKey:I,apiUrl:O,apiVersion:P,token:b,session:k,user:_,organization:A}=e,{sessions:w}=te({apiKey:S,secretKey:I,apiUrl:O,apiVersion:P}),s=tr({sessionId:i,sessionToken:b,fetcher:(...l)=>w.getToken(...l)});return{actor:n,sessionClaims:t,sessionId:i,session:k,userId:f,user:_,orgId:o,orgRole:u,orgSlug:m,organization:A,getToken:s,debug:dt(r)}}function Ve(t){return{sessionClaims:null,sessionId:null,session:null,userId:null,user:null,actor:null,orgId:null,orgRole:null,orgSlug:null,organization:null,getToken:()=>Promise.resolve(null),debug:dt(t)}}function Le(t){return t&&(delete t.privateMetadata,delete t.private_metadata),t}function er(t){let e=t.user?{...t.user}:t.user,r=t.organization?{...t.organization}:t.organization;return Le(e),Le(r),{...t,user:e,organization:r}}var tr=t=>{let{fetcher:e,sessionToken:r,sessionId:n}=t||{};return async(i={})=>n?i.template?e(n,i.template):r:null};var Ge=require("@clerk/shared");function rr(t){return new Promise(e=>setTimeout(e,t))}var nr=5;async function se(t,e=1,r=nr){try{return await t()}catch(n){if(e>=r)throw n;return await rr(2**e*100),se(t,e+1)}}function Ae(t){return t.startsWith("test_")||t.startsWith("sk_test_")}function ct(t){return t.startsWith("live_")||t.startsWith("sk_live_")}function pt(t){return t.endsWith(".lclstage.dev")||t.endsWith(".stgstage.dev")||t.endsWith(".clerkstage.dev")||t.endsWith(".accountsstage.dev")}var c=class extends Error{constructor({action:r,message:n,reason:i}){super(n);Object.setPrototypeOf(this,c.prototype),this.reason=i,this.message=n,this.action=r}getFullMessage(){return`${[this.message,this.action].filter(r=>r).join(" ")} (reason=${this.reason}, token-carrier=${this.tokenCarrier})`}};function Je(t){let{debugData:e,frontendApi:r,pkgVersion:n,publishableKey:i}=t;return` | ||
<head> | ||
@@ -47,3 +47,3 @@ <meta charset="UTF-8" /> | ||
script.async = true; | ||
script.src = '${nr(r,n)}'; | ||
script.src = '${ir(r,n)}'; | ||
script.crossOrigin = 'anonymous'; | ||
@@ -55,3 +55,3 @@ script.addEventListener('load', startClerk); | ||
</body> | ||
`}async function mt(t){t.frontendApi=t.frontendApi||(0,De.parsePublishableKey)(t.publishableKey)?.frontendApi||"";let e=Ae(t),r=await ie(()=>N.fetch(Ae(t)));if(!r.ok)throw new d({action:"Contact support@clerk.dev",message:`Error loading Clerk Interstitial from ${e} with code=${r.status}`,reason:"interstitial-remote-failed-to-load"});return r.text()}function Ae(t){t.frontendApi=t.frontendApi||(0,De.parsePublishableKey)(t.publishableKey)?.frontendApi||"";let{apiUrl:e,frontendApi:r,pkgVersion:n,publishableKey:i}=t,o=new URL(e);return o.pathname=a(o.pathname,T,"/public/interstitial"),o.searchParams.append("clerk_js_version",gt(r,n)),i?o.searchParams.append("publishable_key",i):o.searchParams.append("frontend_api",r),o.href}var gt=(t,e)=>!e&&pt(t)?"staging":e?e.includes("next")?"next":e.split(".")[0]||"latest":"latest",nr=(t,e)=>{let r=gt(t,e);return`https://${t}/npm/@clerk/clerk-js@${r}/dist/clerk.browser.js`};var Ot=require("@clerk/shared");function Ge({originURL:t,host:e,forwardedHost:r,forwardedPort:n,forwardedProto:i}){if(i&&i!==t.protocol)return!0;let o=ir(r||e);return o.port=n||o.port,o.port!==t.port||o.hostname!==t.hostname}function ir(t){return new URL(`https://${t}`)}var Je=require("rfc4648");var sr=2*1e3,He={RS256:"SHA-256",RS384:"SHA-384",RS512:"SHA-512",ES256:"SHA-256",ES384:"SHA-384",ES512:"SHA-512"},$e="RSASSA-PKCS1-v1_5",Be="ECDSA",or={RS256:$e,RS384:$e,RS512:$e,ES256:Be,ES384:Be,ES512:Be},ar=Object.keys(He);async function ft(t,e){let{header:r,signature:n,raw:i}=t,u=new TextEncoder().encode([i.header,i.payload].join(".")),m=await N.crypto.subtle.importKey("jwk",e,{name:or[r.alg],hash:He[r.alg]},!1,["verify"]);return N.crypto.subtle.verify("RSASSA-PKCS1-v1_5",m,n,u)}function xe(t){let e=(t||"").toString().split(".");if(e.length!==3)throw new d({reason:"token-invalid",message:"Invalid JWT form. A JWT consists of three parts separated by dots."});let[r,n,i]=e,o=new TextDecoder,u=JSON.parse(o.decode(Je.base64url.parse(r,{loose:!0}))),m=JSON.parse(o.decode(Je.base64url.parse(n,{loose:!0}))),g=Je.base64url.parse(i,{loose:!0});return{header:u,payload:m,signature:g,raw:{header:r,payload:n,signature:i,text:t}}}async function Ye(t,{audience:e,authorizedParties:r,clockSkewInSeconds:n=sr,issuer:i,key:o}){let u=xe(t),{header:m,payload:g}=u,{typ:O,alg:_}=m;if(typeof O<"u"&&O!=="JWT")throw new d({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-invalid",message:`Invalid JWT type ${JSON.stringify(O)}. Expected "JWT".`});if(!He[_])throw new d({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-invalid-algorithm",message:`Invalid JWT algorithm ${JSON.stringify(_)}. Supported: ${ar}.`});let{azp:k,sub:P,aud:b,iss:I,iat:A,exp:w,nbf:s}=g;if(typeof P!="string")throw new d({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Subject claim (sub) is required and must be a string. Received ${JSON.stringify(P)}.`});if(typeof b=="string"){if(b!==e)throw new d({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Invalid JWT audience claim (aud) ${JSON.stringify(b)}. Expected "${e}".`})}else if(Array.isArray(b)&&b.length>0&&b.every(y=>typeof y=="string")&&!b.includes(e))throw new d({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Invalid JWT audience claim array (aud) ${JSON.stringify(b)}. Does not include "${e}".`});if(k&&r&&r.length>0&&!r.includes(k))throw new d({reason:"token-invalid-authorized-parties",message:`Invalid JWT Authorized party claim (azp) ${JSON.stringify(k)}. Expected "${r}".`});if(typeof i=="function"&&!i(I))throw new d({reason:"token-invalid-issuer",message:"Failed JWT issuer resolver. Make sure that the resolver returns a truthy value."});if(typeof i=="string"&&I&&I!==i)throw new d({reason:"token-invalid-issuer",message:`Invalid JWT issuer claim (iss) ${JSON.stringify(u.payload.iss)}. Expected "${i}".`});if(typeof w!="number")throw new d({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Invalid JWT expiry date claim (exp) ${JSON.stringify(w)}. Expected number.`});let l=new Date(Date.now()),p=new Date(0);if(p.setUTCSeconds(w),p.getTime()<=l.getTime()-n)throw new d({reason:"token-expired",message:`JWT is expired. Expiry date: ${p}, Current date: ${l}.`});if(s!==void 0){if(typeof s!="number")throw new d({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Invalid JWT not before date claim (nbf) ${JSON.stringify(s)}. Expected number.`});let y=new Date(0);if(y.setUTCSeconds(s),y.getTime()>l.getTime()+n)throw new d({reason:"token-not-active-yet",message:`JWT cannot be used prior to not before date claim (nbf). Not before date: ${y}; Current date: ${l};`})}if(A!==void 0){if(typeof A!="number")throw new d({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Invalid JWT issued at date claim (iat) ${JSON.stringify(A)}. Expected number.`});let y=new Date(0);if(y.setUTCSeconds(A),y.getTime()>l.getTime()+n)throw new d({reason:"token-not-active-yet",message:`JWT issued at date claim (iat) is in the future. Issued at date: ${y}; Current date: ${l};`})}let S;try{S=await ft(u,o)}catch(y){throw new d({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Error verifying JWT signature. ${y}`})}if(!S)throw new d({reason:"token-invalid-signature",message:"JWT signature is invalid."});return g}var Re={};function Te(t){return Re[t]}function yt(t,e=1e3*60*60){Re[t.kid]=t,e>=0&&setTimeout(()=>{t?delete Re[t.kid]:Re={}},e)}var ht="local",lr="-----BEGIN PUBLIC KEY-----",ur="-----END PUBLIC KEY-----",dr="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA",cr="IDAQAB";function bt(t){if(!Te(ht)){if(!t)throw new d({action:"Set the CLERK_JWT_KEY environment variable.",message:"Missing local JWK.",reason:"jwk-local-missing"});let e=t.replace(/(\r\n|\n|\r)/gm,"").replace(lr,"").replace(ur,"").replace(dr,"").replace(cr,"").replace(/\+/g,"-").replace(/\//g,"_");yt({kid:"local",kty:"RSA",alg:"RS256",n:e,e:"AQAB"},-1)}return Te(ht)}async function St({apiKey:t,secretKey:e,apiUrl:r,apiVersion:n,issuer:i,kid:o,jwksCacheTtlInMs:u=1e3*60*60,skipJwksCache:m}){if(m||!Te(o)){let O,_=e||t||"";if(r)O=()=>mr(r,_,n);else if(i)O=()=>pr(i);else throw new d({action:"Contact support@clerk.dev",message:"Failed to load JWKS from Clerk Backend or Frontend API.",reason:"jwk-remote-failed-to-load"});let{keys:k}=await ie(O);if(!k||!k.length)throw new d({action:"Contact support@clerk.dev",message:"The JWKS endpoint did not contain any signing keys. Contact support@clerk.dev.",reason:"jwk-remote-failed-to-load"});k.forEach(P=>yt(P,u))}let g=Te(o);if(!g)throw new d({action:"Contact support@clerk.dev",message:`Unable to find a signing key in JWKS that matches kid='${o}'.`,reason:"jwk-remote-missing"});return g}async function pr(t){let e=new URL(t);e.pathname=a(e.pathname,".well-known/jwks.json");let r=await N.fetch(e.href);if(!r.ok)throw new d({action:"Contact support@clerk.dev",message:`Error loading Clerk JWKS from ${e.href} with code=${r.status}`,reason:"jwk-remote-failed-to-load"});return r.json()}async function mr(t=z,e,r=T){if(!e)throw new d({action:"Set the CLERK_SECRET_KEY or CLERK_API_KEY environment variable.",message:"Missing Clerk Secret Key or API Key. Go to https://dashboard.clerk.dev and get your key for your instance.",reason:"jwk-remote-failed-to-load"});let n=new URL(t);n.pathname=a(n.pathname,r,"/jwks");let i=await N.fetch(n.href,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(!i.ok)throw new d({action:"Contact support@clerk.dev",message:`Error loading Clerk JWKS from ${n.href} with code=${i.status}`,reason:"jwk-remote-failed-to-load"});return i.json()}async function Qe(t,e){let{apiKey:r,secretKey:n,apiUrl:i,apiVersion:o,authorizedParties:u,clockSkewInSeconds:m,issuer:g,jwksCacheTtlInMs:O,jwtKey:_,skipJwksCache:k}=e,{header:P}=xe(t),{kid:b}=P,I;if(_)I=bt(_);else if(r||n)I=await St(r?{apiUrl:i,apiKey:r,apiVersion:o,kid:b,jwksCacheTtlInMs:O,skipJwksCache:k}:{apiUrl:i,secretKey:n,apiVersion:o,kid:b,jwksCacheTtlInMs:O,skipJwksCache:k});else throw new d({action:"Set the CLERK_JWT_KEY environment variable.",message:"Failed to resolve JWK during verification.",reason:"jwk-failed-to-resolve"});return await Ye(t,{authorizedParties:u,clockSkewInSeconds:m,key:I,issuer:g})}var Xe=(n=>(n.SignedIn="signed-in",n.SignedOut="signed-out",n.Interstitial="interstitial",n))(Xe||{});async function kt(t){t.frontendApi=t.frontendApi||(0,Ot.parsePublishableKey)(t.publishableKey)?.frontendApi||"",t.apiUrl=t.apiUrl||z,t.apiVersion=t.apiVersion||T;async function e(){let{headerToken:s}=t;try{let l=await n(s);return await u(l)}catch(l){return i(l,"header")}}async function r(){try{let s=O(t,[_,k,P,b,I,A,w]);if(s)return s;let{cookieToken:l,clientUat:p}=t,h=await n(l),S=await u(h);return!p||o(S.toAuth().sessionClaims,p)?g("cookie-outdated"):S}catch(s){return i(s,"cookie")}}function n(s){return Qe(s,{...t,issuer:p=>p.startsWith("https://clerk.")||p.includes(".clerk.accounts")})}function i(s,l){return s instanceof d?(s.tokenCarrier=l,["token-expired","token-not-active-yet"].includes(s.reason)?g(s.reason,s.getFullMessage()):m(s.reason,s.getFullMessage())):m("unexpected-error",s.message)}function o(s,l){return s.iat<Number.parseInt(l)}async function u(s){let{sid:l,org_id:p,sub:h}=s,{apiKey:S,secretKey:y,apiUrl:c,apiVersion:M,cookieToken:Ce,frontendApi:et,publishableKey:It,headerToken:_t,loadSession:At,loadUser:wt,loadOrganization:Pt}=t,{sessions:Jt,users:xt,organizations:Rt}=te({apiKey:S,secretKey:y,apiUrl:c,apiVersion:M}),[Tt,Nt,Ct]=await Promise.all([At?Jt.getSession(l):Promise.resolve(void 0),wt?xt.getUser(h):Promise.resolve(void 0),Pt&&p?Rt.getOrganization({organizationId:p}):Promise.resolve(void 0)]),vt=Le(s,{apiKey:S,secretKey:y,apiUrl:c,apiVersion:M,token:Ce||_t||"",session:Tt,user:Nt,organization:Ct},{...t,status:"signed-in"});return{status:"signed-in",reason:null,message:null,frontendApi:et,publishableKey:It,isSignedIn:!0,isInterstitial:!1,toAuth:()=>vt}}function m(s,l=""){return{status:"signed-out",reason:s,message:l,frontendApi:t.frontendApi,publishableKey:t.publishableKey,isSignedIn:!1,isInterstitial:!1,toAuth:()=>Fe({...t,status:"signed-out",reason:s,message:l})}}function g(s,l=""){return{status:"interstitial",reason:s,message:l,frontendApi:t.frontendApi,publishableKey:t.publishableKey,isSignedIn:!1,isInterstitial:!0,toAuth:()=>null}}let O=(s,l)=>{for(let p of l){let h=p(s);if(h)return h}},_=({apiKey:s,secretKey:l,userAgent:p})=>{if(_e(l||s)&&!p?.startsWith("Mozilla/"))return m("header-missing-non-browser")},k=({origin:s,host:l,forwardedHost:p,forwardedPort:h,forwardedProto:S})=>{if(s&&Ge({originURL:new URL(s),host:l,forwardedHost:p,forwardedPort:h,forwardedProto:S}))return m("header-missing-cors")},P=({apiKey:s,secretKey:l,clientUat:p})=>{if(_e(l||s)&&!p)return g("uat-missing")},b=({apiKey:s,secretKey:l,referrer:p,host:h,forwardedHost:S,forwardedPort:y,forwardedProto:c})=>{let M=p&&Ge({originURL:new URL(p),host:h,forwardedHost:S,forwardedPort:y,forwardedProto:c});if(_e(l||s)&&M)return g("cross-origin-referrer")},I=({apiKey:s,secretKey:l,clientUat:p,cookieToken:h})=>{if(ct(l||s)&&!p&&!h)return m("cookie-and-uat-missing")},A=({clientUat:s})=>{if(s==="0")return m("standard-signed-out")},w=({clientUat:s,cookieToken:l})=>{if(s&&!l)return g("cookie-missing")};return t.headerToken?e():r()}var Ne=t=>{let{frontendApi:e,isSignedIn:r,isInterstitial:n,reason:i,message:o,publishableKey:u}=t;return{frontendApi:e,isSignedIn:r,isInterstitial:n,reason:i,message:o,publishableKey:u}};function Ze(t){let{apiClient:e}=t,{apiKey:r="",secretKey:n="",jwtKey:i="",apiUrl:o=z,apiVersion:u=T,frontendApi:m="",publishableKey:g=""}=t.options;return{authenticateRequest:({apiKey:I,secretKey:A,frontendApi:w,publishableKey:s,jwtKey:l,...p})=>kt({...p,apiKey:I||r,secretKey:A||n,apiUrl:o,apiVersion:u,frontendApi:w||m,publishableKey:s||g,jwtKey:l||i}),localInterstitial:Pe,remotePublicInterstitial:({frontendApi:I,publishableKey:A,...w})=>mt({...w,apiUrl:o,frontendApi:I||m,publishableKey:A||g}),remotePrivateInterstitial:()=>e.interstitial.getInterstitial(),remotePublicInterstitialUrl:Ae,debugRequestState:Ne}}function gr(t){let e={...t},r=te(e),n=Ze({options:e,apiClient:r});return{...r,...n,__unstable_options:e}}0&&(module.exports={AllowlistIdentifier,AuthStatus,Clerk,Client,DeletedObject,Email,EmailAddress,ExternalAccount,IdentificationLink,Invitation,OauthAccessToken,ObjectType,Organization,OrganizationInvitation,OrganizationMembership,OrganizationMembershipPublicUserData,PhoneNumber,RedirectUrl,SMSMessage,Session,SignInToken,Token,User,Verification,constants,createAuthenticateRequest,debugRequestState,decodeJwt,deserialize,hasValidSignature,loadInterstitialFromLocal,prunePrivateMetadata,sanitizeAuthObject,signedInAuthObject,signedOutAuthObject,verifyJwt,verifyToken}); | ||
`}async function mt(t){var n;t.frontendApi=t.frontendApi||((n=(0,Ge.parsePublishableKey)(t.publishableKey))==null?void 0:n.frontendApi)||"";let e=we(t),r=await se(()=>N.fetch(we(t)));if(!r.ok)throw new c({action:"Contact support@clerk.dev",message:`Error loading Clerk Interstitial from ${e} with code=${r.status}`,reason:"interstitial-remote-failed-to-load"});return r.text()}function we(t){var u;t.frontendApi=t.frontendApi||((u=(0,Ge.parsePublishableKey)(t.publishableKey))==null?void 0:u.frontendApi)||"";let{apiUrl:e,frontendApi:r,pkgVersion:n,publishableKey:i}=t,o=new URL(e);return o.pathname=a(o.pathname,T,"/public/interstitial"),o.searchParams.append("clerk_js_version",gt(r,n)),i?o.searchParams.append("publishable_key",i):o.searchParams.append("frontend_api",r),o.href}var gt=(t,e)=>!e&&pt(t)?"staging":e?e.includes("next")?"next":e.split(".")[0]||"latest":"latest",ir=(t,e)=>{let r=gt(t,e);return`https://${t}/npm/@clerk/clerk-js@${r}/dist/clerk.browser.js`};var Ot=require("@clerk/shared");function $e({originURL:t,host:e,forwardedHost:r,forwardedPort:n,forwardedProto:i}){if(i&&i!==t.protocol)return!0;let o=sr(r||e);return o.port=n||o.port,o.port!==t.port||o.hostname!==t.hostname}function sr(t){return new URL(`https://${t}`)}var xe=require("rfc4648");var or=2*1e3,Ye={RS256:"SHA-256",RS384:"SHA-384",RS512:"SHA-512",ES256:"SHA-256",ES384:"SHA-384",ES512:"SHA-512"},Be="RSASSA-PKCS1-v1_5",He="ECDSA",ar={RS256:Be,RS384:Be,RS512:Be,ES256:He,ES384:He,ES512:He},lr=Object.keys(Ye);async function ft(t,e){let{header:r,signature:n,raw:i}=t,u=new TextEncoder().encode([i.header,i.payload].join(".")),m=await N.crypto.subtle.importKey("jwk",e,{name:ar[r.alg],hash:Ye[r.alg]},!1,["verify"]);return N.crypto.subtle.verify("RSASSA-PKCS1-v1_5",m,n,u)}function Re(t){let e=(t||"").toString().split(".");if(e.length!==3)throw new c({reason:"token-invalid",message:"Invalid JWT form. A JWT consists of three parts separated by dots."});let[r,n,i]=e,o=new TextDecoder,u=JSON.parse(o.decode(xe.base64url.parse(r,{loose:!0}))),m=JSON.parse(o.decode(xe.base64url.parse(n,{loose:!0}))),f=xe.base64url.parse(i,{loose:!0});return{header:u,payload:m,signature:f,raw:{header:r,payload:n,signature:i,text:t}}}async function Qe(t,{audience:e,authorizedParties:r,clockSkewInSeconds:n=or,issuer:i,key:o}){let u=Re(t),{header:m,payload:f}=u,{typ:S,alg:I}=m;if(typeof S!="undefined"&&S!=="JWT")throw new c({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-invalid",message:`Invalid JWT type ${JSON.stringify(S)}. Expected "JWT".`});if(!Ye[I])throw new c({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-invalid-algorithm",message:`Invalid JWT algorithm ${JSON.stringify(I)}. Supported: ${lr}.`});let{azp:O,sub:P,aud:b,iss:k,iat:_,exp:A,nbf:w}=f;if(typeof P!="string")throw new c({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Subject claim (sub) is required and must be a string. Received ${JSON.stringify(P)}.`});if(typeof b=="string"){if(b!==e)throw new c({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Invalid JWT audience claim (aud) ${JSON.stringify(b)}. Expected "${e}".`})}else if(Array.isArray(b)&&b.length>0&&b.every(g=>typeof g=="string")&&!b.includes(e))throw new c({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Invalid JWT audience claim array (aud) ${JSON.stringify(b)}. Does not include "${e}".`});if(O&&r&&r.length>0&&!r.includes(O))throw new c({reason:"token-invalid-authorized-parties",message:`Invalid JWT Authorized party claim (azp) ${JSON.stringify(O)}. Expected "${r}".`});if(typeof i=="function"&&!i(k))throw new c({reason:"token-invalid-issuer",message:"Failed JWT issuer resolver. Make sure that the resolver returns a truthy value."});if(typeof i=="string"&&k&&k!==i)throw new c({reason:"token-invalid-issuer",message:`Invalid JWT issuer claim (iss) ${JSON.stringify(u.payload.iss)}. Expected "${i}".`});if(typeof A!="number")throw new c({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Invalid JWT expiry date claim (exp) ${JSON.stringify(A)}. Expected number.`});let s=new Date(Date.now()),l=new Date(0);if(l.setUTCSeconds(A),l.getTime()<=s.getTime()-n)throw new c({reason:"token-expired",message:`JWT is expired. Expiry date: ${l}, Current date: ${s}.`});if(w!==void 0){if(typeof w!="number")throw new c({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Invalid JWT not before date claim (nbf) ${JSON.stringify(w)}. Expected number.`});let g=new Date(0);if(g.setUTCSeconds(w),g.getTime()>s.getTime()+n)throw new c({reason:"token-not-active-yet",message:`JWT cannot be used prior to not before date claim (nbf). Not before date: ${g}; Current date: ${s};`})}if(_!==void 0){if(typeof _!="number")throw new c({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Invalid JWT issued at date claim (iat) ${JSON.stringify(_)}. Expected number.`});let g=new Date(0);if(g.setUTCSeconds(_),g.getTime()>s.getTime()+n)throw new c({reason:"token-not-active-yet",message:`JWT issued at date claim (iat) is in the future. Issued at date: ${g}; Current date: ${s};`})}let y;try{y=await ft(u,o)}catch(g){throw new c({action:"Make sure that this is a valid Clerk generate JWT.",reason:"token-verification-failed",message:`Error verifying JWT signature. ${g}`})}if(!y)throw new c({reason:"token-invalid-signature",message:"JWT signature is invalid."});return f}var Te={};function Ne(t){return Te[t]}function yt(t,e=1e3*60*60){Te[t.kid]=t,e>=0&&setTimeout(()=>{t?delete Te[t.kid]:Te={}},e)}var ht="local",ur="-----BEGIN PUBLIC KEY-----",dr="-----END PUBLIC KEY-----",cr="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA",pr="IDAQAB";function bt(t){if(!Ne(ht)){if(!t)throw new c({action:"Set the CLERK_JWT_KEY environment variable.",message:"Missing local JWK.",reason:"jwk-local-missing"});let e=t.replace(/(\r\n|\n|\r)/gm,"").replace(ur,"").replace(dr,"").replace(cr,"").replace(pr,"").replace(/\+/g,"-").replace(/\//g,"_");yt({kid:"local",kty:"RSA",alg:"RS256",n:e,e:"AQAB"},-1)}return Ne(ht)}async function St({apiKey:t,secretKey:e,apiUrl:r,apiVersion:n,issuer:i,kid:o,jwksCacheTtlInMs:u=1e3*60*60,skipJwksCache:m}){if(m||!Ne(o)){let S,I=e||t||"";if(r)S=()=>gr(r,I,n);else if(i)S=()=>mr(i);else throw new c({action:"Contact support@clerk.dev",message:"Failed to load JWKS from Clerk Backend or Frontend API.",reason:"jwk-remote-failed-to-load"});let{keys:O}=await se(S);if(!O||!O.length)throw new c({action:"Contact support@clerk.dev",message:"The JWKS endpoint did not contain any signing keys. Contact support@clerk.dev.",reason:"jwk-remote-failed-to-load"});O.forEach(P=>yt(P,u))}let f=Ne(o);if(!f)throw new c({action:"Contact support@clerk.dev",message:`Unable to find a signing key in JWKS that matches kid='${o}'.`,reason:"jwk-remote-missing"});return f}async function mr(t){let e=new URL(t);e.pathname=a(e.pathname,".well-known/jwks.json");let r=await N.fetch(e.href);if(!r.ok)throw new c({action:"Contact support@clerk.dev",message:`Error loading Clerk JWKS from ${e.href} with code=${r.status}`,reason:"jwk-remote-failed-to-load"});return r.json()}async function gr(t=z,e,r=T){if(!e)throw new c({action:"Set the CLERK_SECRET_KEY or CLERK_API_KEY environment variable.",message:"Missing Clerk Secret Key or API Key. Go to https://dashboard.clerk.dev and get your key for your instance.",reason:"jwk-remote-failed-to-load"});let n=new URL(t);n.pathname=a(n.pathname,r,"/jwks");let i=await N.fetch(n.href,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(!i.ok)throw new c({action:"Contact support@clerk.dev",message:`Error loading Clerk JWKS from ${n.href} with code=${i.status}`,reason:"jwk-remote-failed-to-load"});return i.json()}async function Xe(t,e){let{apiKey:r,secretKey:n,apiUrl:i,apiVersion:o,authorizedParties:u,clockSkewInSeconds:m,issuer:f,jwksCacheTtlInMs:S,jwtKey:I,skipJwksCache:O}=e,{header:P}=Re(t),{kid:b}=P,k;if(I)k=bt(I);else if(r||n)k=await St(r?{apiUrl:i,apiKey:r,apiVersion:o,kid:b,jwksCacheTtlInMs:S,skipJwksCache:O}:{apiUrl:i,secretKey:n,apiVersion:o,kid:b,jwksCacheTtlInMs:S,skipJwksCache:O});else throw new c({action:"Set the CLERK_JWT_KEY environment variable.",message:"Failed to resolve JWK during verification.",reason:"jwk-failed-to-resolve"});return await Qe(t,{authorizedParties:u,clockSkewInSeconds:m,key:k,issuer:f})}var Ze=(n=>(n.SignedIn="signed-in",n.SignedOut="signed-out",n.Interstitial="interstitial",n))(Ze||{});async function kt(t){var w;t.frontendApi=t.frontendApi||((w=(0,Ot.parsePublishableKey)(t.publishableKey))==null?void 0:w.frontendApi)||"",t.apiUrl=t.apiUrl||z,t.apiVersion=t.apiVersion||T;async function e(){let{headerToken:s}=t;try{let l=await n(s);return await u(l)}catch(l){return i(l,"header")}}async function r(){try{let s=S(t,[I,O,P,b,k,_,A]);if(s)return s;let{cookieToken:l,clientUat:d}=t,y=await n(l),g=await u(y);return!d||o(g.toAuth().sessionClaims,d)?f("cookie-outdated"):g}catch(s){return i(s,"cookie")}}function n(s){return Xe(s,{...t,issuer:d=>d.startsWith("https://clerk.")||d.includes(".clerk.accounts")})}function i(s,l){return s instanceof c?(s.tokenCarrier=l,["token-expired","token-not-active-yet"].includes(s.reason)?f(s.reason,s.getFullMessage()):m(s.reason,s.getFullMessage())):m("unexpected-error",s.message)}function o(s,l){return s.iat<Number.parseInt(l)}async function u(s){let{sid:l,org_id:d,sub:y}=s,{apiKey:g,secretKey:p,apiUrl:M,apiVersion:re,cookieToken:ve,frontendApi:It,publishableKey:_t,headerToken:At,loadSession:wt,loadUser:Pt,loadOrganization:Jt}=t,{sessions:xt,users:Rt,organizations:Tt}=te({apiKey:g,secretKey:p,apiUrl:M,apiVersion:re}),[Nt,Ct,vt]=await Promise.all([wt?xt.getSession(l):Promise.resolve(void 0),Pt?Rt.getUser(y):Promise.resolve(void 0),Jt&&d?Tt.getOrganization({organizationId:d}):Promise.resolve(void 0)]),Et=Fe(s,{apiKey:g,secretKey:p,apiUrl:M,apiVersion:re,token:ve||At||"",session:Nt,user:Ct,organization:vt},{...t,status:"signed-in"});return{status:"signed-in",reason:null,message:null,frontendApi:It,publishableKey:_t,isSignedIn:!0,isInterstitial:!1,toAuth:()=>Et}}function m(s,l=""){return{status:"signed-out",reason:s,message:l,frontendApi:t.frontendApi,publishableKey:t.publishableKey,isSignedIn:!1,isInterstitial:!1,toAuth:()=>Ve({...t,status:"signed-out",reason:s,message:l})}}function f(s,l=""){return{status:"interstitial",reason:s,message:l,frontendApi:t.frontendApi,publishableKey:t.publishableKey,isSignedIn:!1,isInterstitial:!0,toAuth:()=>null}}let S=(s,l)=>{for(let d of l){let y=d(s);if(y)return y}},I=({apiKey:s,secretKey:l,userAgent:d})=>{if(Ae(l||s)&&!(d!=null&&d.startsWith("Mozilla/")))return m("header-missing-non-browser")},O=({origin:s,host:l,forwardedHost:d,forwardedPort:y,forwardedProto:g})=>{if(s&&$e({originURL:new URL(s),host:l,forwardedHost:d,forwardedPort:y,forwardedProto:g}))return m("header-missing-cors")},P=({apiKey:s,secretKey:l,clientUat:d})=>{if(Ae(l||s)&&!d)return f("uat-missing")},b=({apiKey:s,secretKey:l,referrer:d,host:y,forwardedHost:g,forwardedPort:p,forwardedProto:M})=>{let re=d&&$e({originURL:new URL(d),host:y,forwardedHost:g,forwardedPort:p,forwardedProto:M});if(Ae(l||s)&&re)return f("cross-origin-referrer")},k=({apiKey:s,secretKey:l,clientUat:d,cookieToken:y})=>{if(ct(l||s)&&!d&&!y)return m("cookie-and-uat-missing")},_=({clientUat:s})=>{if(s==="0")return m("standard-signed-out")},A=({clientUat:s,cookieToken:l})=>{if(s&&!l)return f("cookie-missing")};return t.headerToken?e():r()}var Ce=t=>{let{frontendApi:e,isSignedIn:r,isInterstitial:n,reason:i,message:o,publishableKey:u}=t;return{frontendApi:e,isSignedIn:r,isInterstitial:n,reason:i,message:o,publishableKey:u}};function et(t){let{apiClient:e}=t,{apiKey:r="",secretKey:n="",jwtKey:i="",apiUrl:o=z,apiVersion:u=T,frontendApi:m="",publishableKey:f=""}=t.options;return{authenticateRequest:({apiKey:k,secretKey:_,frontendApi:A,publishableKey:w,jwtKey:s,...l})=>kt({...l,apiKey:k||r,secretKey:_||n,apiUrl:o,apiVersion:u,frontendApi:A||m,publishableKey:w||f,jwtKey:s||i}),localInterstitial:Je,remotePublicInterstitial:({frontendApi:k,publishableKey:_,...A})=>mt({...A,apiUrl:o,frontendApi:k||m,publishableKey:_||f}),remotePrivateInterstitial:()=>e.interstitial.getInterstitial(),remotePublicInterstitialUrl:we,debugRequestState:Ce}}function fr(t){let e={...t},r=te(e),n=et({options:e,apiClient:r});return{...r,...n,__unstable_options:e}}0&&(module.exports={AllowlistIdentifier,AuthStatus,Clerk,Client,DeletedObject,Email,EmailAddress,ExternalAccount,IdentificationLink,Invitation,OauthAccessToken,ObjectType,Organization,OrganizationInvitation,OrganizationMembership,OrganizationMembershipPublicUserData,PhoneNumber,RedirectUrl,SMSMessage,Session,SignInToken,Token,User,Verification,constants,createAuthenticateRequest,debugRequestState,decodeJwt,deserialize,hasValidSignature,loadInterstitialFromLocal,prunePrivateMetadata,sanitizeAuthObject,signedInAuthObject,signedOutAuthObject,verifyJwt,verifyToken}); | ||
//# sourceMappingURL=index.js.map |
@@ -1,3 +0,11 @@ | ||
const crypto = require('node:crypto'); | ||
let webcrypto; | ||
try { | ||
webcrypto = require('node:crypto').webcrypto; | ||
if (!webcrypto) { | ||
webcrypto = new (require('@peculiar/webcrypto').Crypto)(); | ||
} | ||
} catch (e) { | ||
webcrypto = new (require('@peculiar/webcrypto').Crypto)(); | ||
} | ||
module.exports = crypto.webcrypto; | ||
module.exports = webcrypto; |
@@ -1,3 +0,14 @@ | ||
const fetch = require('node-fetch-native'); | ||
let fetch; | ||
try { | ||
// Pre-node14 runtimes do not support the node: prefix | ||
// this package uses internally, and they throw. | ||
// This package is preferred as it does not polyfill the native fetch | ||
// if it's supported by the runtime | ||
// https://github.com/node-fetch/node-fetch/issues/1367 | ||
fetch = require('node-fetch-native'); | ||
} catch (e) { | ||
// Otherwise, we will fall back to this lib | ||
fetch = require('node-fetch'); | ||
} | ||
module.exports = fetch; |
{ | ||
"name": "@clerk/backend", | ||
"version": "0.4.0-staging.7", | ||
"version": "0.4.0-staging.8", | ||
"license": "MIT", | ||
@@ -27,7 +27,9 @@ "description": "Clerk Backend SDK - REST Client for Backend API & JWT verification utilities", | ||
"dependencies": { | ||
"@clerk/shared": "^0.9.0-staging.2", | ||
"@clerk/shared": "^0.9.0-staging.3", | ||
"@clerk/types": "^3.24.0-staging.1", | ||
"@peculiar/webcrypto": "1.4.1", | ||
"@types/node": "16.18.6", | ||
"deepmerge": "^4.2.2", | ||
"node-fetch-native": "0.1.8", | ||
"deepmerge": "4.2.2", | ||
"node-fetch": "2.6.8", | ||
"node-fetch-native": "1.0.1", | ||
"rfc4648": "1.5.2", | ||
@@ -78,3 +80,3 @@ "snakecase-keys": "5.4.4", | ||
}, | ||
"gitHead": "46cf8f0dd126cc299d5cd766021557cb2886012b" | ||
"gitHead": "daf93dc67b32ec7180fe14c0ee3297b367995de9" | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
494316
1724
10
+ Added@peculiar/webcrypto@1.4.1
+ Addednode-fetch@2.6.8
+ Added@peculiar/asn1-schema@2.3.13(transitive)
+ Added@peculiar/json-schema@1.1.12(transitive)
+ Added@peculiar/webcrypto@1.4.1(transitive)
+ Addedasn1js@3.0.5(transitive)
+ Addeddeepmerge@4.2.2(transitive)
+ Addednode-fetch@2.6.8(transitive)
+ Addednode-fetch-native@1.0.1(transitive)
+ Addedpvtsutils@1.3.5(transitive)
+ Addedpvutils@1.1.3(transitive)
+ Addedtr46@0.0.3(transitive)
+ Addedtslib@2.8.1(transitive)
+ Addedwebcrypto-core@1.8.1(transitive)
+ Addedwebidl-conversions@3.0.1(transitive)
+ Addedwhatwg-url@5.0.0(transitive)
- Removeddeepmerge@4.3.1(transitive)
- Removednode-fetch-native@0.1.8(transitive)
Updateddeepmerge@4.2.2
Updatednode-fetch-native@1.0.1