CDN Domainssupabase.co
HTML PatternscreateClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)}}async signOut(e,t=Ln[0]){if(Ln.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Ln.join(", ")}`);try{return await Cn(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if(It(n))return{data:null,error:n};throw n}}async inviteUserByEmail(e,t={}){try{return await Cn(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:Pn})}catch(n){if(It(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{const{options:t}=e,n=E(e,["options"]),r=Object.assign(Object.assign({},n),t);return"newEmail"in n&&(r.new_email=null==n?void 0:n.newEmail,delete r.newEmail),await Cn(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:r,headers:this.headers,xform:An,redirectTo:null==t?void 0:t.redirectTo})}catch(t){if(It(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await Cn(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Pn})}catch(t){if(It(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,n,r,a,s,i,o;try{const l={nextPage:null,lastPage:0,total:0},u=await Cn(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(n=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==n?n:"",per_page:null!==(a=null===(r=null==e?void 0:e.perPage)||void 0===r?void 0:r.toString())&&void 0!==a?a:""},xform:Rn});if(u.error)throw u.error;const c=await u.json(),d=null!==(s=u.headers.get("x-total-count"))&&void 0!==s?s:0,h=null!==(o=null===(i=u.headers.get("link"))||void 0===i?void 0:i.split(","))&&void 0!==o?o:[];return h.length>0&&(h.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),n=JSON.parse(e.split(";")[1].split("=")[1]);l[`${n}Page`]=t}),l.total=parseInt(d)),{data:Object.assign(Object.assign({},c),l),error:null}}catch(l){if(It(l))return{data:{users:[]},error:l};throw l}}async getUserById(e){kn(e);try{return await Cn(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Pn})}catch(t){if(It(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){kn(e);try{return await Cn(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:Pn})}catch(n){if(It(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,t=!1){kn(e);try{return await Cn(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:Pn})}catch(n){if(It(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){kn(e.userId);try{const{data:t,error:n}=await Cn(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:n}}catch(t){if(It(t))return{data:null,error:t};throw t}}async _deleteFactor(e){kn(e.userId),kn(e.id);try{return{data:await Cn(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(It(t))return{data:null,error:t};throw t}}async _listOAuthClients(e){var t,n,r,a,s,i,o;try{const l={nextPage:null,lastPage:0,total:0},u=await Cn(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(n=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==n?n:"",per_page:null!==(a=null===(r=null==e?void 0:e.perPage)||void 0===r?void 0:r.toString())&&void 0!==a?a:""},xform:Rn});if(u.error)throw u.error;const c=await u.json(),d=null!==(s=u.headers.get("x-total-count"))&&void 0!==s?s:0,h=null!==(o=null===(i=u.headers.get("link"))||void 0===i?void 0:i.split(","))&&void 0!==o?o:[];return h.length>0&&(h.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),n=JSON.parse(e.split(";")[1].split("=")[1]);l[`${n}Page`]=t}),l.total=parseInt(d)),{data:Object.assign(Object.assign({},c),l),error:null}}catch(l){if(It(l))return{data:{clients:[]},error:l};throw l}}async _createOAuthClient(e){try{return await Cn(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(t){if(It(t))return{data:null,error:t};throw t}}async _getOAuthClient(e){try{return await Cn(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(t){if(It(t))return{data:null,error:t};throw t}}async _updateOAuthClient(e,t){try{return await Cn(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(n){if(It(n))return{data:null,error:n};throw n}}async _deleteOAuthClient(e){try{return await Cn(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(It(t))return{data:null,error:t};throw t}}async _regenerateOAuthClientSecret(e){try{return await Cn(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(t){if(It(t))return{data:null,error:t};throw t}}async _listCustomProviders(e){try{const t={};return(null==e?void 0:e.type)&&(t.type=e.type),await Cn(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:t,xform:e=>{var t;return{data:{providers:null!==(t=null==e?void 0:e.providers)&&void 0!==t?t:[]},error:null}}})}catch(t){if(It(t))return{data:{providers:[]},error:t};throw t}}async _createCustomProvider(e){try{return await Cn(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(t){if(It(t))return{data:null,error:t};throw t}}async _getCustomProvider(e){try{return await Cn(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(t){if(It(t))return{data:null,error:t};throw t}}async _updateCustomProvider(e,t){try{return await Cn(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(n){if(It(n))return{data:null,error:n};throw n}}async _deleteCustomProvider(e){try{return await Cn(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(It(t))return{data:null,error:t};throw t}}}function $n(e={}){return{getItem:t=>e[t]||null,setItem:(t,n)=>{e[t]=n},removeItem:t=>{delete e[t]}}}const zn=!!(globalThis&&un()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"));class Dn extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class Un extends Dn{}async function Mn(e,t,n){const r=new globalThis.AbortController;t>0&&setTimeout(()=>{r.abort()},t),await Promise.resolve();try{return await globalThis.navigator.locks.request(e,0===t?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async r=>{if(!r){if(0===t)throw new Un(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(zn)try{await globalThis.navigator.locks.query()}catch(a){}return await n()}try{return await n()}finally{}})}catch(a){if("AbortError"===(null==a?void 0:a.name)&&t>0)return await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,{mode:"exclusive",steal:!0},async e=>{if(!e)return await n();try{return await n()}finally{}}));throw a}}function Bn(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw new Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function Fn(e){const t=(new TextEncoder).encode(e);return"0x"+Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}class qn extends Error{constructor({message:e,code:t,cause:n,name:r}){var a;super(e,{cause:n}),this.__isWebAuthnError=!0,this.name=null!==(a=null!=r?r:n instanceof Error?n.name:void 0)&&void 0!==a?a:"Unknown Error",this.code=t}}class Wn extends qn{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}function Vn({error:e,options:t}){var n,r,a;const{publicKey:s}=t;if(!s)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new qn({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if(!0===(null===(n=s.authenticatorSelection)||void 0===n?void 0:n.requireResidentKey))return new qn({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if("conditional"===t.mediation&&"required"===(null===(r=s.authenticatorSelection)||void 0===r?void 0:r.userVerification))return new qn({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if("required"===(null===(a=s.authenticatorSelection)||void 0===a?void 0:a.userVerification))return new qn({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if("InvalidStateError"===e.name)return new qn({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new qn({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("NotSupportedError"===e.name){return 0===s.pubKeyCredParams.filter(e=>"public-key"===e.type).length?new qn({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new qn({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e})}if("SecurityError"===e.name){const t=window.location.hostname;if(!Xn(t))return new qn({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(s.rp.id!==t)return new qn({message:`The RP ID "${s.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(s.user.id.byteLength<1||s.user.id.byteLength>64)return new qn({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if("UnknownError"===e.name)return new qn({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new qn({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function Hn({error:e,options:t}){const{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new qn({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new qn({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("SecurityError"===e.name){const t=window.location.hostname;if(!Xn(t))return new qn({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(n.rpId!==t)return new qn({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("UnknownError"===e.name)return new qn({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new qn({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}const Kn=new class{createNewAbortSignal(){if(this.controller){const e=new Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}};function Gn(e){if(!e)throw new Error("Credential creation options are required");if("undefined"!=typeof PublicKeyCredential&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(e);const{challenge:t,user:n,excludeCredentials:r}=e,a=E(e,["challenge","user","excludeCredentials"]),s=rn(t).buffer,i=Object.assign(Object.assign({},n),{id:rn(n.id).buffer}),o=Object.assign(Object.assign({},a),{challenge:s,user:i});if(r&&r.length>0){o.excludeCredentials=new Array(r.length);for(let e=0;e<r.length;e++){const t=r[e];o.excludeCredentials[e]=Object.assign(Object.assign({},t),{id:rn(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return o}function Jn(e){if(!e)throw new Error("Credential request options are required");if("undefined"!=typeof PublicKeyCredential&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseRequestOptionsFromJSON)return PublicKeyCredential.parseRequestOptionsFromJSON(e);const{challenge:t,allowCredentials:n}=e,r=E(e,["challenge","allowCredentials"]),a=rn(t).buffer,s=Object.assign(Object.assign({},r),{challenge:a});if(n&&n.length>0){s.allowCredentials=new Array(n.length);for(let e=0;e<n.length;e++){const t=n[e];s.allowCredentials[e]=Object.assign(Object.assign({},t),{id:rn(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return s}function Qn(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();const n=e;return{id:e.id,rawId:e.id,response:{attestationObject:sn(new Uint8Array(e.response.attestationObject)),clientDataJSON:sn(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:null!==(t=n.authenticatorAttachment)&&void 0!==t?t:void 0}}function Yn(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();const n=e,r=e.getClientExtensionResults(),a=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:sn(new Uint8Array(a.authenticatorData)),clientDataJSON:sn(new Uint8Array(a.clientDataJSON)),signature:sn(new Uint8Array(a.signature)),userHandle:a.userHandle?sn(new Uint8Array(a.userHandle)):void 0},type:"public-key",clientExtensionResults:r,authenticatorAttachment:null!==(t=n.authenticatorAttachment)&&void 0!==t?t:void 0}}function Xn(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function Zn(){var e,t;return!!(on()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&"function"==typeof(null===(e=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===e?void 0:e.create)&&"function"==typeof(null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.get))}const er={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},tr={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function nr(...e){const t=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),n=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),r={};for(const a of e)if(a)for(const e in a){const s=a[e];if(void 0!==s)if(Array.isArray(s))r[e]=s;else if(n(s))r[e]=s;else if(t(s)){const n=r[e];t(n)?r[e]=nr(n,s):r[e]=nr(s)}else r[e]=s}return r}class rr{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:n,signal:r},a){var s;try{const{data:i,error:o}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!i)return{data:null,error:o};const l=null!=r?r:Kn.createNewAbortSignal();if("create"===i.webauthn.type){const{user:e}=i.webauthn.credential_options.publicKey;if(!e.name){const t=n;if(t)e.name=`${e.id}:${t}`;else{const t=(await this.client.getUser()).data.user,n=(null===(s=null==t?void 0:t.user_metadata)||void 0===s?void 0:s.name)||(null==t?void 0:t.email)||(null==t?void 0:t.id)||"User";e.name=`${e.id}:${n}`}}e.displayName||(e.displayName=e.name)}switch(i.webauthn.type){case"create":{const t=function(e,t){return nr(er,e,t||{})}(i.webauthn.credential_options.publicKey,null==a?void 0:a.create),{data:n,error:r}=await async function(e){try{const t=await navigator.credentials.create(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new Wn("Browser returned unexpected credential type",t)}:{data:null,error:new Wn("Empty credential response",t)}}catch(t){return{data:null,error:Vn({error:t,options:e})}}}({publicKey:t,signal:l});return n?{data:{factorId:e,challengeId:i.id,webauthn:{type:i.webauthn.type,credential_response:n}},error:null}:{data:null,error:r}}case"request":{const t=function(e,t){return nr(tr,e,t||{})}(i.webauthn.credential_options.publicKey,null==a?void 0:a.request),{data:n,error:r}=await async function(e){try{const t=await navigator.credentials.get(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new Wn("Browser returned unexpected credential type",t)}:{data:null,error:new Wn("Empty credential response",t)}}catch(t){return{data:null,error:Hn({error:t,options:e})}}}(Object.assign(Object.assign({},i.webauthn.credential_options),{publicKey:t,signal:l}));return n?{data:{factorId:e,challengeId:i.id,webauthn:{type:i.webauthn.type,credential_response:n}},error:null}:{data:null,error:r}}}}catch(i){return It(i)?{data:null,error:i}:{data:null,error:new zt("Unexpected error in challenge",i)}}}async _verify({challengeId:e,factorId:t,webauthn:n}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:n})}async _authenticate({factorId:e,webauthn:{rpId:t=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:n=("undefined"!=typeof window?[window.location.origin]:void 0),signal:r}={}},a){if(!t)return{data:null,error:new Lt("rpId is required for WebAuthn authentication")};try{if(!Zn())return{data:null,error:new zt("Browser does not support WebAuthn",null)};const{data:s,error:i}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:n},signal:r},{request:a});if(!s)return{data:null,error:i};const{webauthn:o}=s;return this._verify({factorId:e,challengeId:s.challengeId,webauthn:{type:o.type,rpId:t,rpOrigins:n,credential_response:o.credential_response}})}catch(s){return It(s)?{data:null,error:s}:{data:null,error:new zt("Unexpected error in authenticate",s)}}}async _register({friendlyName:e,webauthn:{rpId:t=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:n=("undefined"!=typeof window?[window.location.origin]:void 0),signal:r}={}},a){if(!t)return{data:null,error:new Lt("rpId is required for WebAuthn registration")};try{if(!Zn())return{data:null,error:new zt("Browser does not support WebAuthn",null)};const{data:s,error:i}=await this._enroll({friendlyName:e});if(!s)return await this.client.mfa.listFactors().then(t=>{var n;return null===(n=t.data)||void 0===n?void 0:n.all.find(t=>"webauthn"===t.factor_type&&t.friendly_name===e&&"unverified"!==t.status)}).then(e=>e?this.client.mfa.unenroll({factorId:null==e?void 0:e.id}):void 0),{data:null,error:i};const{data:o,error:l}=await this._challenge({factorId:s.id,friendlyName:s.friendly_name,webauthn:{rpId:t,rpOrigins:n},signal:r},{create:a});return o?this._verify({factorId:s.id,challengeId:o.challengeId,webauthn:{rpId:t,rpOrigins:n,type:o.webauthn.type,credential_response:o.webauthn.credential_response}}):{data:null,error:l}}catch(s){return It(s)?{data:null,error:s}:{data:null,error:new zt("Unexpected error in register",s)}}}}!function(){if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){"undefined"!=typeof self&&(self.globalThis=self)}}();const ar={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Pt,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function sr(e,t,n){return await n()}const ir={};class or{get jwks(){var e,t;return null!==(t=null===(e=ir[this.storageKey])||void 0===e?void 0:e.jwks)&&void 0!==t?t:{keys:[]}}set jwks(e){ir[this.storageKey]=Object.assign(Object.assign({},ir[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return null!==(t=null===(e=ir[this.storageKey])||void 0===e?void 0:e.cachedAt)&&void 0!==t?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){ir[this.storageKey]=Object.assign(Object.assign({},ir[this.storageKey]),{cachedAt:e})}constructor(e){var t,n,r;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const a=Object.assign(Object.assign({},ar),e);if(this.storageKey=a.storageKey,this.instanceID=null!==(t=or.nextInstanceID[this.storageKey])&&void 0!==t?t:0,or.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!a.debug,"function"==typeof a.debug&&(this.logger=a.debug),this.instanceID>0&&on()){this._logPrefix();this.logDebugMessages}if(this.persistSession=a.persistSession,this.autoRefreshToken=a.autoRefreshToken,this.admin=new In({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=cn(a.fetch),this.lock=a.lock||sr,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,this.throwOnError=a.throwOnError,this.lockAcquireTimeout=a.lockAcquireTimeout,a.lock?this.lock=a.lock:this.persistSession&&on()&&(null===(n=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===n?void 0:n.locks)?this.lock=Mn:this.lock=sr,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new rr(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(a.storage?this.storage=a.storage:un()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=$n(this.memoryStorage)),a.userStorage&&(this.userStorage=a.userStorage)):(this.memoryStorage={},this.storage=$n(this.memoryStorage)),on()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(s){}null===(r=this.broadcastChannel)||void 0===r||r.addEventListener("message",async e=>{this._debug("received broadcast notification from other tab or client",e);try{await this._notifyAllSubscribers(e.data.event,e.data.session,!1)}catch(t){this._debug("#broadcastChannel","error",t)}})}a.skipAutoInitialize||this.initialize().catch(e=>{this._debug("#initialize()","error",e)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Ct}) ${(new Date).toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise||(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))()),await this.initializePromise}async _initialize(){var e;try{let t={},n="none";if(on()&&(t=function(e){const t={},n=new URL(e);if(n.hash&&"#"===n.hash[0])try{new URLSearchParams(n.hash.substring(1)).forEach((e,n)=>{t[n]=e})}catch(r){}return n.searchParams.forEach((e,n)=>{t[n]=e}),t}(window.location.href),this._isImplicitGrantCallback(t)?n="implicit":await this._isPKCECallback(t)&&(n="pkce")),on()&&this.detectSessionInUrl&&"none"!==n){const{data:r,error:a}=await this._getSessionFromURL(t,n);if(a){if(this._debug("#_initialize()","error detecting session from URL",a),function(e){return It(e)&&"AuthImplicitGrantRedirectError"===e.name}(a)){const t=null===(e=a.details)||void 0===e?void 0:e.code;if("identity_already_exists"===t||"identity_not_found"===t||"single_identity_not_deletable"===t)return{error:a}}return{error:a}}const{session:s,redirectType:i}=r;return this._debug("#_initialize()","detected session in URL",s,"redirect type",i),await this._saveSession(s),setTimeout(async()=>{"recovery"===i?await this._notifyAllSubscribers("PASSWORD_RECOVERY",s):await this._notifyAllSubscribers("SIGNED_IN",s)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return It(t)?this._returnResult({error:t}):this._returnResult({error:new zt("Unexpected error during initialization",t)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,n,r;try{const a=await Cn(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:null!==(n=null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.data)&&void 0!==n?n:{},gotrue_meta_security:{captcha_token:null===(r=null==e?void 0:e.options)||void 0===r?void 0:r.captchaToken}},xform:jn}),{data:s,error:i}=a;if(i||!s)return this._returnResult({data:{user:null,session:null},error:i});const o=s.session,l=s.user;return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",o)),this._returnResult({data:{user:l,session:o},error:null})}catch(a){if(It(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signUp(e){var t,n,r;try{let a;if("email"in e){const{email:n,password:r,options:s}=e;let i=null,o=null;"pkce"===this.flowType&&([i,o]=await vn(this.storage,this.storageKey)),a=await Cn(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:null==s?void 0:s.emailRedirectTo,body:{email:n,password:r,data:null!==(t=null==s?void 0:s.data)&&void 0!==t?t:{},gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken},code_challenge:i,code_challenge_method:o},xform:jn})}else{if(!("phone"in e))throw new Ft("You must provide either an email or phone number and a password");{const{phone:t,password:s,options:i}=e;a=await Cn(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:s,data:null!==(n=null==i?void 0:i.data)&&void 0!==n?n:{},channel:null!==(r=null==i?void 0:i.channel)&&void 0!==r?r:"sms",gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:jn})}}const{data:s,error:i}=a;if(i||!s)return await fn(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:i});const o=s.session,l=s.user;return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",o)),this._returnResult({data:{user:l,session:o},error:null})}catch(a){if(await fn(this.storage,`${this.storageKey}-code-verifier`),It(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signInWithPassword(e){try{let t;if("email"in e){const{email:n,password:r,options:a}=e;t=await Cn(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:r,gotrue_meta_security:{captcha_token:null==a?void 0:a.captchaToken}},xform:On})}else{if(!("phone"in e))throw new Ft("You must provide either an email or phone number and a password");{const{phone:n,password:r,options:a}=e;t=await Cn(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:r,gotrue_meta_security:{captcha_token:null==a?void 0:a.captchaToken}},xform:On})}}const{data:n,error:r}=t;if(r)return this._returnResult({data:{user:null,session:null},error:r});if(!n||!n.session||!n.user){const e=new Bt;return this._returnResult({data:{user:null,session:null},error:e})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:r})}catch(t){if(It(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOAuth(e){var t,n,r,a;return await this._handleProviderSignIn(e.provider,{redirectTo:null===(t=e.options)||void 0===t?void 0:t.redirectTo,scopes:null===(n=e.options)||void 0===n?void 0:n.scopes,queryParams:null===(r=e.options)||void 0===r?void 0:r.queryParams,skipBrowserRedirect:null===(a=e.options)||void 0===a?void 0:a.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,n,r,a,s,i,o,l,u,c,d;let h,f;if("message"in e)h=e.message,f=e.signature;else{const{chain:c,wallet:d,statement:p,options:m}=e;let g;if(on())if("object"==typeof d)g=d;else{const e=window;if(!("ethereum"in e)||"object"!=typeof e.ethereum||!("request"in e.ethereum)||"function"!=typeof e.ethereum.request)throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.");g=e.ethereum}else{if("object"!=typeof d||!(null==m?void 0:m.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");g=d}const y=new URL(null!==(t=null==m?void 0:m.url)&&void 0!==t?t:window.location.href),v=await g.request({method:"eth_requestAccounts"}).then(e=>e).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!v||0===v.length)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const b=Bn(v[0]);let w=null===(n=null==m?void 0:m.signInWithEthereum)||void 0===n?void 0:n.chainId;if(!w){const e=await g.request({method:"eth_chainId"});w=parseInt(e,16)}h=function(e){var t;const{chainId:n,domain:r,expirationTime:a,issuedAt:s=new Date,nonce:i,notBefore:o,requestId:l,resources:u,scheme:c,uri:d,version:h}=e;if(!Number.isInteger(n))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${n}`);if(!r)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(i&&i.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${i}`);if(!d)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if("1"!==h)throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${h}`);if(null===(t=e.statement)||void 0===t?void 0:t.includes("\n"))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);const f=`${c?`${c}://${r}`:r} wants you to sign in with your Ethereum account:\n${Bn(e.address)}\n\n${e.statement?`${e.statement}\n`:""}`;let p=`URI: ${d}\nVersion: ${h}\nChain ID: ${n}${i?`\nNonce: ${i}`:""}\nIssued At: ${s.toISOString()}`;if(a&&(p+=`\nExpiration Time: ${a.toISOString()}`),o&&(p+=`\nNot Before: ${o.toISOString()}`),l&&(p+=`\nRequest ID: ${l}`),u){let e="\nResources:";for(const t of u){if(!t||"string"!=typeof t)throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${t}`);e+=`\n- ${t}`}p+=e}return`${f}\n${p}`}({domain:y.host,address:b,statement:p,uri:y.href,version:"1",chainId:w,nonce:null===(r=null==m?void 0:m.signInWithEthereum)||void 0===r?void 0:r.nonce,issuedAt:null!==(s=null===(a=null==m?void 0:m.signInWithEthereum)||void 0===a?void 0:a.issuedAt)&&void 0!==s?s:new Date,expirationTime:null===(i=null==m?void 0:m.signInWithEthereum)||void 0===i?void 0:i.expirationTime,notBefore:null===(o=null==m?void 0:m.signInWithEthereum)||void 0===o?void 0:o.notBefore,requestId:null===(l=null==m?void 0:m.signInWithEthereum)||void 0===l?void 0:l.requestId,resources:null===(u=null==m?void 0:m.signInWithEthereum)||void 0===u?void 0:u.resources}),f=await g.request({method:"personal_sign",params:[Fn(h),b]})}try{const{data:t,error:n}=await Cn(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:h,signature:f},(null===(c=e.options)||void 0===c?void 0:c.captchaToken)?{gotrue_meta_security:{captcha_token:null===(d=e.options)||void 0===d?void 0:d.captchaToken}}:null),xform:jn});if(n)throw n;if(!t||!t.session||!t.user){const e=new Bt;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:n})}catch(p){if(It(p))return this._returnResult({data:{user:null,session:null},error:p});throw p}}async signInWithSolana(e){var t,n,r,a,s,i,o,l,u,c,d,h;let f,p;if("message"in e)f=e.message,p=e.signature;else{const{chain:d,wallet:h,statement:m,options:g}=e;let y;if(on())if("object"==typeof h)y=h;else{const e=window;if(!("solana"in e)||"object"!=typeof e.solana||!("signIn"in e.solana&&"function"==typeof e.solana.signIn||"signMessage"in e.solana&&"function"==typeof e.solana.signMessage))throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.");y=e.solana}else{if("object"!=typeof h||!(null==g?void 0:g.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");y=h}const v=new URL(null!==(t=null==g?void 0:g.url)&&void 0!==t?t:window.location.href);if("signIn"in y&&y.signIn){const e=await y.signIn(Object.assign(Object.assign(Object.assign({issuedAt:(new Date).toISOString()},null==g?void 0:g.signInWithSolana),{version:"1",domain:v.host,uri:v.href}),m?{statement:m}:null));let t;if(Array.isArray(e)&&e[0]&&"object"==typeof e[0])t=e[0];else{if(!(e&&"object"==typeof e&&"signedMessage"in e&&"signature"in e))throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");t=e}if(!("signedMessage"in t&&"signature"in t&&("string"==typeof t.signedMessage||t.signedMessage instanceof Uint8Array)&&t.signature instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields");f="string"==typeof t.signedMessage?t.signedMessage:(new TextDecoder).decode(t.signedMessage),p=t.signature}else{if(!("signMessage"in y&&"function"==typeof y.signMessage&&"publicKey"in y&&"object"==typeof y&&y.publicKey&&"toBase58"in y.publicKey&&"function"==typeof y.publicKey.toBase58))throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");f=[`${v.host} wants you to sign in with your Solana account:`,y.publicKey.toBase58(),...m?["",m,""]:[""],"Version: 1",`URI: ${v.href}`,`Issued At: ${null!==(r=null===(n=null==g?void 0:g.signInWithSolana)||void 0===n?void 0:n.issuedAt)&&void 0!==r?r:(new Date).toISOString()}`,...(null===(a=null==g?void 0:g.signInWithSolana)||void 0===a?void 0:a.notBefore)?[`Not Before: ${g.signInWithSolana.notBefore}`]:[],...(null===(s=null==g?void 0:g.signInWithSolana)||void 0===s?void 0:s.expirationTime)?[`Expiration Time: ${g.signInWithSolana.expirationTime}`]:[],...(null===(i=null==g?void 0:g.signInWithSolana)||void 0===i?void 0:i.chainId)?[`Chain ID: ${g.signInWithSolana.chainId}`]:[],...(null===(o=null==g?void 0:g.signInWithSolana)||void 0===o?void 0:o.nonce)?[`Nonce: ${g.signInWithSolana.nonce}`]:[],...(null===(l=null==g?void 0:g.signInWithSolana)||void 0===l?void 0:l.requestId)?[`Request ID: ${g.signInWithSolana.requestId}`]:[],...(null===(c=null===(u=null==g?void 0:g.signInWithSolana)||void 0===u?void 0:u.resources)||void 0===c?void 0:c.length)?["Resources",...g.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join("\n");const e=await y.signMessage((new TextEncoder).encode(f),"utf8");if(!(e&&e instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");p=e}}try{const{data:t,error:n}=await Cn(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:f,signature:sn(p)},(null===(d=e.options)||void 0===d?void 0:d.captchaToken)?{gotrue_meta_security:{captcha_token:null===(h=e.options)||void 0===h?void 0:h.captchaToken}}:null),xform:jn});if(n)throw n;if(!t||!t.session||!t.user){const e=new Bt;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:n})}catch(m){if(It(m))return this._returnResult({data:{user:null,session:null},error:m});throw m}}async _exchangeCodeForSession(e){const t=await hn(this.storage,`${this.storageKey}-code-verifier`),[n,r]=(null!=t?t:"").split("/");try{if(!n&&"pkce"===this.flowType)throw new Vt;const{data:t,error:a}=await Cn(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:jn});if(await fn(this.storage,`${this.storageKey}-code-verifier`),a)throw a;if(!t||!t.session||!t.user){const e=new Bt;return this._returnResult({data:{user:null,session:null,redirectType:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign(Object.assign({},t),{redirectType:null!=r?r:null}),error:a})}catch(a){if(await fn(this.storage,`${this.storageKey}-code-verifier`),It(a))return this._returnResult({data:{user:null,session:null,redirectType:null},error:a});throw a}}async signInWithIdToken(e){try{const{options:t,provider:n,token:r,access_token:a,nonce:s}=e,i=await Cn(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:r,access_token:a,nonce:s,gotrue_meta_security:{captcha_token:null==t?void 0:t.captchaToken}},xform:jn}),{data:o,error:l}=i;if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!o||!o.session||!o.user){const e=new Bt;return this._returnResult({data:{user:null,session:null},error:e})}return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",o.session)),this._returnResult({data:o,error:l})}catch(t){if(It(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOtp(e){var t,n,r,a,s;try{if("email"in e){const{email:r,options:a}=e;let s=null,i=null;"pkce"===this.flowType&&([s,i]=await vn(this.storage,this.storageKey));const{error:o}=await Cn(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:r,data:null!==(t=null==a?void 0:a.data)&&void 0!==t?t:{},create_user:null===(n=null==a?void 0:a.shouldCreateUser)||void 0===n||n,gotrue_meta_security:{captcha_token:null==a?void 0:a.captchaToken},code_challenge:s,code_challenge_method:i},redirectTo:null==a?void 0:a.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}if("phone"in e){const{phone:t,options:n}=e,{data:i,error:o}=await Cn(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:null!==(r=null==n?void 0:n.data)&&void 0!==r?r:{},create_user:null===(a=null==n?void 0:n.shouldCreateUser)||void 0===a||a,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken},channel:null!==(s=null==n?void 0:n.channel)&&void 0!==s?s:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:null==i?void 0:i.message_id},error:o})}throw new Ft("You must provide either an email or phone number.")}catch(i){if(await fn(this.storage,`${this.storageKey}-code-verifier`),It(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async verifyOtp(e){var t,n;try{let r,a;"options"in e&&(r=null===(t=e.options)||void 0===t?void 0:t.redirectTo,a=null===(n=e.options)||void 0===n?void 0:n.captchaToken);const{data:s,error:i}=await Cn(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:a}}),redirectTo:r,xform:jn});if(i)throw i;if(!s){throw new Error("An error occurred on token verification.")}const o=s.session,l=s.user;return(null==o?void 0:o.access_token)&&(await this._saveSession(o),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",o)),this._returnResult({data:{user:l,session:o},error:null})}catch(r){if(It(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithSSO(e){var t,n,r,a,s;try{let i=null,o=null;"pkce"===this.flowType&&([i,o]=await vn(this.storage,this.storageKey));const l=await Cn(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:null!==(n=null===(t=e.options)||void 0===t?void 0:t.redirectTo)&&void 0!==n?n:void 0}),(null===(r=null==e?void 0:e.options)||void 0===r?void 0:r.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:i,code_challenge_method:o}),headers:this.headers,xform:Nn});return(null===(a=l.data)||void 0===a?void 0:a.url)&&on()&&!(null===(s=e.options)||void 0===s?void 0:s.skipBrowserRedirect)&&window.location.assign(l.data.url),this._returnResult(l)}catch(i){if(await fn(this.storage,`${this.storageKey}-code-verifier`),It(i))return this._returnResult({data:null,error:i});throw i}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:t},error:n}=e;if(n)throw n;if(!t)throw new Ut;const{error:r}=await Cn(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:r})})}catch(e){if(It(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const t=`${this.url}/resend`;if("email"in e){const{email:n,type:r,options:a}=e,{error:s}=await Cn(this.fetch,"POST",t,{headers:this.headers,body:{email:n,type:r,gotrue_meta_security:{captcha_token:null==a?void 0:a.captchaToken}},redirectTo:null==a?void 0:a.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:s})}if("phone"in e){const{phone:n,type:r,options:a}=e,{data:s,error:i}=await Cn(this.fetch,"POST",t,{headers:this.headers,body:{phone:n,type:r,gotrue_meta_security:{captcha_token:null==a?void 0:a.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:null==s?void 0:s.message_id},error:i})}throw new Ft("You must provide either an email or phone number and a type")}catch(t){if(It(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async getSession(){await this.initializePromise;return await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await n}catch(e){}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(t){}})()),await e;this.pendingInLock.length;){const e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",(new Error).stack);try{let e=null;const t=await hn(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),null!==t&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const n=!!e.expires_at&&1e3*e.expires_at-Date.now()<Ot;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){const t=await hn(this.userStorage,this.storageKey+"-user");(null==t?void 0:t.user)?e.user=t.user:e.user=_n()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const t={value:this.suppressGetSessionWarning};e.user=function(e,t){return new Proxy(e,{get:(e,n,r)=>{if("__isInsecureUserWarningProxy"===n)return!0;if("symbol"==typeof n){const t=n.toString();if("Symbol(Symbol.toPrimitive)"===t||"Symbol(Symbol.toStringTag)"===t||"Symbol(util.inspect.custom)"===t||"Symbol(nodejs.util.inspect.custom)"===t)return Reflect.get(e,n,r)}return t.value||"string"!=typeof n||(t.value=!0),Reflect.get(e,n,r)}})}(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:r,error:a}=await this._callRefreshToken(e.refresh_token);return a?this._returnResult({data:{session:null},error:a}):this._returnResult({data:{session:r},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await Cn(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Pn}):await this._useSession(async e=>{var t,n,r;const{data:a,error:s}=e;if(s)throw s;return(null===(t=a.session)||void 0===t?void 0:t.access_token)||this.hasCustomAuthorizationHeader?await Cn(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!==(r=null===(n=a.session)||void 0===n?void 0:n.access_token)&&void 0!==r?r:void 0,xform:Pn}):{data:{user:null},error:new Ut}})}catch(t){if(It(t))return Mt(t)&&(await this._removeSession(),await fn(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:t});throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async n=>{const{data:r,error:a}=n;if(a)throw a;if(!r.session)throw new Ut;const s=r.session;let i=null,o=null;"pkce"===this.flowType&&null!=e.email&&([i,o]=await vn(this.storage,this.storageKey));const{data:l,error:u}=await Cn(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:i,code_challenge_method:o}),jwt:s.access_token,xform:Pn});if(u)throw u;return s.user=l.user,await this._saveSession(s),await this._notifyAllSubscribers("USER_UPDATED",s),this._returnResult({data:{user:s.user},error:null})})}catch(n){if(await fn(this.storage,`${this.storageKey}-code-verifier`),It(n))return this._returnResult({data:{user:null},error:n});throw n}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new Ut;const t=Date.now()/1e3;let n=t,r=!0,a=null;const{payload:s}=mn(e.access_token);if(s.exp&&(n=s.exp,r=n<=t),r){const{data:t,error:n}=await this._callRefreshToken(e.refresh_token);if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!t)return{data:{user:null,session:null},error:null};a=t}else{const{data:r,error:s}=await this._getUser(e.access_token);if(s)return this._returnResult({data:{user:null,session:null},error:s});a={access_token:e.access_token,refresh_token:e.refresh_token,user:r.user,token_type:"bearer",expires_in:n-t,expires_at:n},await this._saveSession(a),await this._notifyAllSubscribers("SIGNED_IN",a)}return this._returnResult({data:{user:a.user,session:a},error:null})}catch(t){if(It(t))return this._returnResult({data:{session:null,user:null},error:t});throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var n;if(!e){const{data:r,error:a}=t;if(a)throw a;e=null!==(n=r.session)&&void 0!==n?n:void 0}if(!(null==e?void 0:e.refresh_token))throw new Ut;const{data:r,error:a}=await this._callRefreshToken(e.refresh_token);return a?this._returnResult({data:{user:null,session:null},error:a}):r?this._returnResult({data:{user:r.user,session:r},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(t){if(It(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async _getSessionFromURL(e,t){try{if(!on())throw new qt("No browser detected.");if(e.error||e.error_description||e.error_code)throw new qt(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if("pkce"===this.flowType)throw new Wt("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new qt("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Wt("No code detected.");const{data:t,error:n}=await this._exchangeCodeForSession(e.code);if(n)throw n;const r=new URL(window.location.href);return r.searchParams.delete("code"),window.history.replaceState(window.history.state,"",r.toString()),{data:{session:t.session,redirectType:null},error:null}}const{provider_token:n,provider_refresh_token:r,access_token:a,refresh_token:s,expires_in:i,expires_at:o,token_type:l}=e;if(!(a&&i&&s&&l))throw new qt("No session defined in URL");const u=Math.round(Date.now()/1e3),c=parseInt(i);let d=u+c;o&&(d=parseInt(o));const{data:h,error:f}=await this._getUser(a);if(f)throw f;const p={provider_token:n,provider_refresh_token:r,access_token:a,expires_in:c,expires_at:d,refresh_token:s,token_type:l,user:h.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:p,redirectType:e.type},error:null})}catch(n){if(It(n))return this._returnResult({data:{session:null,redirectType:null},error:n});throw n}}_isImplicitGrantCallback(e){return"function"==typeof this.detectSessionInUrl?this.detectSessionInUrl(new URL(window.location.href),e):Boolean(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await hn(this.storage,`${this.storageKey}-code-verifier`);return!(!e.code||!t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var n;const{data:r,error:a}=t;if(a&&!Mt(a))return this._returnResult({error:a});const s=null===(n=r.session)||void 0===n?void 0:n.access_token;if(s){const{error:t}=await this.admin.signOut(s,e);if(t&&(!function(e){return It(e)&&"AuthApiError"===e.name}(t)||404!==t.status&&401!==t.status&&403!==t.status)&&!Mt(t))return this._returnResult({error:t})}return"others"!==e&&(await this._removeSession(),await fn(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const t=Symbol("auth-callback"),n={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,n),(async()=>{await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)})})(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async t=>{var n,r;try{const{data:{session:r},error:a}=t;if(a)throw a;await(null===(n=this.stateChangeEmitters.get(e))||void 0===n?void 0:n.callback("INITIAL_SESSION",r)),this._debug("INITIAL_SESSION","callback id",e,"session",r)}catch(a){await(null===(r=this.stateChangeEmitters.get(e))||void 0===r?void 0:r.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",a)}})}async resetPasswordForEmail(e,t={}){let n=null,r=null;"pkce"===this.flowType&&([n,r]=await vn(this.storage,this.storageKey,!0));try{return await Cn(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:r,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(a){if(await fn(this.storage,`${this.storageKey}-code-verifier`),It(a))return this._returnResult({data:null,error:a});throw a}}async getUserIdentities(){var e;try{const{data:t,error:n}=await this.getUser();if(n)throw n;return this._returnResult({data:{identities:null!==(e=t.user.identities)&&void 0!==e?e:[]},error:null})}catch(t){if(It(t))return this._returnResult({data:null,error:t});throw t}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{const{data:n,error:r}=await this._useSession(async t=>{var n,r,a,s,i;const{data:o,error:l}=t;if(l)throw l;const u=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:null===(n=e.options)||void 0===n?void 0:n.redirectTo,scopes:null===(r=e.options)||void 0===r?void 0:r.scopes,queryParams:null===(a=e.options)||void 0===a?void 0:a.queryParams,skipBrowserRedirect:!0});return await Cn(this.fetch,"GET",u,{headers:this.headers,jwt:null!==(i=null===(s=o.session)||void 0===s?void 0:s.access_token)&&void 0!==i?i:void 0})});if(r)throw r;return on()&&!(null===(t=e.options)||void 0===t?void 0:t.skipBrowserRedirect)&&window.location.assign(null==n?void 0:n.url),this._returnResult({data:{provider:e.provider,url:null==n?void 0:n.url},error:null})}catch(n){if(It(n))return this._returnResult({data:{provider:e.provider,url:null},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var n;try{const{error:r,data:{session:a}}=t;if(r)throw r;const{options:s,provider:i,token:o,access_token:l,nonce:u}=e,c=await Cn(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:null!==(n=null==a?void 0:a.access_token)&&void 0!==n?n:void 0,body:{provider:i,id_token:o,access_token:l,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken}},xform:jn}),{data:d,error:h}=c;return h?this._returnResult({data:{user:null,session:null},error:h}):d&&d.session&&d.user?(d.session&&(await this._saveSession(d.session),await this._notifyAllSubscribers("USER_UPDATED",d.session)),this._returnResult({data:d,error:h})):this._returnResult({data:{user:null,session:null},error:new Bt})}catch(r){if(await fn(this.storage,`${this.storageKey}-code-verifier`),It(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var n,r;const{data:a,error:s}=t;if(s)throw s;return await Cn(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:null!==(r=null===(n=a.session)||void 0===n?void 0:n.access_token)&&void 0!==r?r:void 0})})}catch(t){if(It(t))return this._returnResult({data:null,error:t});throw t}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const a=Date.now();return await(n=async n=>(n>0&&await async function(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}(200*Math.pow(2,n-1)),this._debug(t,"refreshing attempt",n),await Cn(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:jn})),r=(e,t)=>{const n=200*Math.pow(2,e);return t&&Kt(t)&&Date.now()+n-a<jt},new Promise((e,t)=>{(async()=>{for(let s=0;s<1/0;s++)try{const t=await n(s);if(!r(s,null,t))return void e(t)}catch(a){if(!r(s,a))return void t(a)}})()}))}catch(a){if(this._debug(t,"error",a),It(a))return this._returnResult({data:{session:null,user:null},error:a});throw a}finally{this._debug(t,"end")}var n,r}_isValidSession(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const n=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",n),on()&&!t.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e,t;const n="#_recoverAndRefresh()";this._debug(n,"begin");try{const a=await hn(this.storage,this.storageKey);if(a&&this.userStorage){let t=await hn(this.userStorage,this.storageKey+"-user");this.storage.isServer||!Object.is(this.storage,this.userStorage)||t||(t={user:a.user},await dn(this.userStorage,this.storageKey+"-user",t)),a.user=null!==(e=null==t?void 0:t.user)&&void 0!==e?e:_n()}else if(a&&!a.user&&!a.user){const e=await hn(this.storage,this.storageKey+"-user");e&&(null==e?void 0:e.user)?(a.user=e.user,await fn(this.storage,this.storageKey+"-user"),await dn(this.storage,this.storageKey,a)):a.user=_n()}if(this._debug(n,"session from storage",a),!this._isValidSession(a))return this._debug(n,"session is not valid"),void(null!==a&&await this._removeSession());const s=1e3*(null!==(t=a.expires_at)&&void 0!==t?t:1/0)-Date.now()<Ot;if(this._debug(n,`session has${s?"":" not"} expired with margin of 90000s`),s){if(this.autoRefreshToken&&a.refresh_token){const{error:e}=await this._callRefreshToken(a.refresh_token);e&&(Kt(e)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",e),await this._removeSession()))}}else if(a.user&&!0===a.user.__isUserNotAvailableProxy)try{const{data:e,error:t}=await this._getUser(a.access_token);!t&&(null==e?void 0:e.user)?(a.user=e.user,await this._saveSession(a),await this._notifyAllSubscribers("SIGNED_IN",a)):this._debug(n,"could not get user data, skipping SIGNED_IN notification")}catch(r){this._debug(n,"error getting user data, skipping SIGNED_IN notification",r)}else await this._notifyAllSubscribers("SIGNED_IN",a)}catch(a){return void this._debug(n,"error",a)}finally{this._debug(n,"end")}}async _callRefreshToken(e){var t,n;if(!e)throw new Ut;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const r=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{this.refreshingDeferred=new pn;const{data:t,error:n}=await this._refreshAccessToken(e);if(n)throw n;if(!t.session)throw new Ut;await this._saveSession(t.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",t.session);const r={data:t.session,error:null};return this.refreshingDeferred.resolve(r),r}catch(a){if(this._debug(r,"error",a),It(a)){const e={data:null,error:a};return Kt(a)||await this._removeSession(),null===(t=this.refreshingDeferred)||void 0===t||t.resolve(e),e}throw null===(n=this.refreshingDeferred)||void 0===n||n.reject(a),a}finally{this.refreshingDeferred=null,this._debug(r,"end")}}async _notifyAllSubscribers(e,t,n=!0){const r=`#_notifyAllSubscribers(${e})`;this._debug(r,"begin",t,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:t});const r=[],a=Array.from(this.stateChangeEmitters.values()).map(async n=>{try{await n.callback(e,t)}catch(a){r.push(a)}});if(await Promise.all(a),r.length>0){for(let e=0;e<r.length;e+=1);throw r[0]}}finally{this._debug(r,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await fn(this.storage,`${this.storageKey}-code-verifier`);const t=Object.assign({},e),n=t.user&&!0===t.user.__isUserNotAvailableProxy;if(this.userStorage){!n&&t.user&&await dn(this.userStorage,this.storageKey+"-user",{user:t.user});const e=Object.assign({},t);delete e.user;const r=Sn(e);await dn(this.storage,this.storageKey,r)}else{const e=Sn(t);await dn(this.storage,this.storageKey,e)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await fn(this.storage,this.storageKey),await fn(this.storage,this.storageKey+"-code-verifier"),await fn(this.storage,this.storageKey+"-user"),this.userStorage&&await fn(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&on()&&(null===window||void 0===window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(t){}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),jt);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e);const t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&"object"==typeof t&&"function"==typeof t.unref?t.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const t=Date.now();try{return await this._useSession(async e=>{const{data:{session:n}}=e;if(!n||!n.refresh_token||!n.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");const r=Math.floor((1e3*n.expires_at-t)/jt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${r} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),r<=3&&await this._callRefreshToken(n.refresh_token)})}catch(e){}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(!(e.isAcquireTimeout||e instanceof Dn))throw e;this._debug("auto refresh token tick lock not available")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!on()||!(null===window||void 0===window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},null===window||void 0===window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{"visible"===document.visibilityState?await this._recoverAndRefresh():this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting")}))):"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,n){const r=[`provider=${encodeURIComponent(t)}`];if((null==n?void 0:n.redirectTo)&&r.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),(null==n?void 0:n.scopes)&&r.push(`scopes=${encodeURIComponent(n.scopes)}`),"pkce"===this.flowType){const[e,t]=await vn(this.storage,this.storageKey),n=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});r.push(n.toString())}if(null==n?void 0:n.queryParams){const e=new URLSearchParams(n.queryParams);r.push(e.toString())}return(null==n?void 0:n.skipBrowserRedirect)&&r.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${r.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var n;const{data:r,error:a}=t;return a?this._returnResult({data:null,error:a}):await Cn(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:null===(n=null==r?void 0:r.session)||void 0===n?void 0:n.access_token})})}catch(t){if(It(t))return this._returnResult({data:null,error:t});throw t}}async _enroll(e){try{return await this._useSession(async t=>{var n,r;const{data:a,error:s}=t;if(s)return this._returnResult({data:null,error:s});const i=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:"totp"===e.factorType?{issuer:e.issuer}:{}),{data:o,error:l}=await Cn(this.fetch,"POST",`${this.url}/factors`,{body:i,headers:this.headers,jwt:null===(n=null==a?void 0:a.session)||void 0===n?void 0:n.access_token});return l?this._returnResult({data:null,error:l}):("totp"===e.factorType&&"totp"===o.type&&(null===(r=null==o?void 0:o.totp)||void 0===r?void 0:r.qr_code)&&(o.totp.qr_code=`data:image/svg+xml;utf-8,${o.totp.qr_code}`),this._returnResult({data:o,error:null}))})}catch(t){if(It(t))return this._returnResult({data:null,error:t});throw t}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var n;const{data:r,error:a}=t;if(a)return this._returnResult({data:null,error:a});const s=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:"create"===e.webauthn.type?Qn(e.webauthn.credential_response):Yn(e.webauthn.credential_response)})}:{code:e.code}),{data:i,error:o}=await Cn(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:s,headers:this.headers,jwt:null===(n=null==r?void 0:r.session)||void 0===n?void 0:n.access_token});return o?this._returnResult({data:null,error:o}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+i.expires_in},i)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",i),this._returnResult({data:i,error:o}))})}catch(t){if(It(t))return this._returnResult({data:null,error:t});throw t}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var n;const{data:r,error:a}=t;if(a)return this._returnResult({data:null,error:a});const s=await Cn(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:null===(n=null==r?void 0:r.session)||void 0===n?void 0:n.access_token});if(s.error)return s;const{data:i}=s;if("webauthn"!==i.type)return{data:i,error:null};switch(i.webauthn.type){case"create":return{data:Object.assign(Object.assign({},i),{webauthn:Object.assign(Object.assign({},i.webauthn),{credential_options:Object.assign(Object.assign({},i.webauthn.credential_options),{publicKey:Gn(i.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},i),{webauthn:Object.assign(Object.assign({},i.webauthn),{credential_options:Object.assign(Object.assign({},i.webauthn.credential_options),{publicKey:Jn(i.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(t){if(It(t))return this._returnResult({data:null,error:t});throw t}})}async _challengeAndVerify(e){const{data:t,error:n}=await this._challenge({factorId:e.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;const{data:{user:t},error:n}=await this.getUser();if(n)return{data:null,error:n};const r={all:[],phone:[],totp:[],webauthn:[]};for(const a of null!==(e=null==t?void 0:t.factors)&&void 0!==e?e:[])r.all.push(a),"verified"===a.status&&r[a.factor_type].push(a);return{data:r,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,n,r,a;if(e)try{const{payload:r}=mn(e);let a=null;r.aal&&(a=r.aal);let s=a;const{data:{user:i},error:o}=await this.getUser(e);if(o)return this._returnResult({data:null,error:o});(null!==(n=null===(t=null==i?void 0:i.factors)||void 0===t?void 0:t.filter(e=>"verified"===e.status))&&void 0!==n?n:[]).length>0&&(s="aal2");return{data:{currentLevel:a,nextLevel:s,currentAuthenticationMethods:r.amr||[]},error:null}}catch(c){if(It(c))return this._returnResult({data:null,error:c});throw c}const{data:{session:s},error:i}=await this.getSession();if(i)return this._returnResult({data:null,error:i});if(!s)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:o}=mn(s.access_token);let l=null;o.aal&&(l=o.aal);let u=l;(null!==(a=null===(r=s.user.factors)||void 0===r?void 0:r.filter(e=>"verified"===e.status))&&void 0!==a?a:[]).length>0&&(u="aal2");return{data:{currentLevel:l,nextLevel:u,currentAuthenticationMethods:o.amr||[]},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{const{data:{session:n},error:r}=t;return r?this._returnResult({data:null,error:r}):n?await Cn(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new Ut})})}catch(t){if(It(t))return this._returnResult({data:null,error:t});throw t}}async _approveAuthorization(e,t){try{return await this._useSession(async n=>{const{data:{session:r},error:a}=n;if(a)return this._returnResult({data:null,error:a});if(!r)return this._returnResult({data:null,error:new Ut});const s=await Cn(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:r.access_token,body:{action:"approve"},xform:e=>({data:e,error:null})});return s.data&&s.data.redirect_url&&on()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(s.data.redirect_url),s})}catch(n){if(It(n))return this._returnResult({data:null,error:n});throw n}}async _denyAuthorization(e,t){try{return await this._useSession(async n=>{const{data:{session:r},error:a}=n;if(a)return this._returnResult({data:null,error:a});if(!r)return this._returnResult({data:null,error:new Ut});const s=await Cn(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:r.access_token,body:{action:"deny"},xform:e=>({data:e,error:null})});return s.data&&s.data.redirect_url&&on()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(s.data.redirect_url),s})}catch(n){if(It(n))return this._returnResult({data:null,error:n});throw n}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:t},error:n}=e;return n?this._returnResult({data:null,error:n}):t?await Cn(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new Ut})})}catch(e){if(It(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{const{data:{session:n},error:r}=t;return r?this._returnResult({data:null,error:r}):n?(await Cn(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new Ut})})}catch(t){if(It(t))return this._returnResult({data:null,error:t});throw t}}async fetchJwk(e,t={keys:[]}){let n=t.keys.find(t=>t.kid===e);if(n)return n;const r=Date.now();if(n=this.jwks.keys.find(t=>t.kid===e),n&&this.jwks_cached_at+6e5>r)return n;const{data:a,error:s}=await Cn(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(s)throw s;return a.keys&&0!==a.keys.length?(this.jwks=a,this.jwks_cached_at=r,n=a.keys.find(t=>t.kid===e),n||null):null}async getClaims(e,t={}){try{let n=e;if(!n){const{data:e,error:t}=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});n=e.session.access_token}const{header:r,payload:a,signature:s,raw:{header:i,payload:o}}=mn(n);(null==t?void 0:t.allowExpired)||function(e){if(!e)throw new Error("Missing exp claim");if(e<=Math.floor(Date.now()/1e3))throw new Error("JWT has expired")}(a.exp);const l=r.alg&&!r.alg.startsWith("HS")&&r.kid&&"crypto"in globalThis&&"subtle"in globalThis.crypto?await this.fetchJwk(r.kid,(null==t?void 0:t.keys)?{keys:t.keys}:null==t?void 0:t.jwks):null;if(!l){const{error:e}=await this.getUser(n);if(e)throw e;return{data:{claims:a,header:r,signature:s},error:null}}const u=function(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}(r.alg),c=await crypto.subtle.importKey("jwk",l,u,!0,["verify"]);if(!(await crypto.subtle.verify(u,c,s,an(`${i}.${o}`))))throw new Jt("Invalid JWT signature");return{data:{claims:a,header:r,signature:s},error:null}}catch(n){if(It(n))return this._returnResult({data:null,error:n});throw n}}}or.nextInstanceID={};const lr=or;let ur="";ur="undefined"!=typeof Deno?"deno":"undefined"!=typeof document?"web":"undefined"!=typeof navigator&&"ReactNative"===navigator.product?"react-native":"node";const cr={headers:{"X-Client-Info":`supabase-js-${ur}/2.99.2`}},dr={schema:"public"},hr={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},fr={};function pr(e){return(pr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function mr(e){var t=function(e,t){if("object"!=pr(e)||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t);if("object"!=pr(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==pr(t)?t:t+""}function gr(e,t,n){return(t=mr(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function yr(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function vr(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?yr(Object(n),!0).forEach(function(t){gr(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):yr(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}const br=(e,t,n)=>{const r=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(n),a=Headers;return async(n,s)=>{var i;const o=null!==(i=await t())&&void 0!==i?i:e;let l=new a(null==s?void 0:s.headers);return l.has("apikey")||l.set("apikey",e),l.has("Authorization")||l.set("Authorization",`Bearer ${o}`),r(n,vr(vr({},s),{},{headers:l}))}};var wr=class extends lr{constructor(e){super(e)}},kr=class{constructor(e,t,n){var r,a;this.supabaseUrl=e,this.supabaseKey=t;const s=function(e){const t=null==e?void 0:e.trim();if(!t)throw new Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL((n=t).endsWith("/")?n:n+"/")}catch(r){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}var n}(e);if(!t)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",s),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",s),this.storageUrl=new URL("storage/v1",s),this.functionsUrl=new URL("functions/v1",s);const i=`sb-${s.hostname.split(".")[0]}-auth-token`,o=function(e,t){var n,r;const{db:a,auth:s,realtime:i,global:o}=e,{db:l,auth:u,realtime:c,global:d}=t,h={db:vr(vr({},l),a),auth:vr(vr({},u),s),realtime:vr(vr({},c),i),storage:{},global:vr(vr(vr({},d),o),{},{headers:vr(vr({},null!==(n=null==d?void 0:d.headers)&&void 0!==n?n:{}),null!==(r=null==o?void 0:o.headers)&&void 0!==r?r:{})}),accessToken:async()=>""};return e.accessToken?h.accessToken=e.accessToken:delete h.accessToken,h}(null!=n?n:{},{db:dr,realtime:fr,auth:vr(vr({},hr),{},{storageKey:i}),global:cr});var l;(this.storageKey=null!==(r=o.auth.storageKey)&&void 0!==r?r:"",this.headers=null!==(a=o.global.headers)&&void 0!==a?a:{},o.accessToken)?(this.accessToken=o.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(t)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(null!==(l=o.auth)&&void 0!==l?l:{},this.headers,o.global.fetch);this.fetch=br(t,this._getAccessToken.bind(this),o.global.fetch),this.realtime=this._initRealtimeClient(vr({headers:this.headers,accessToken:this._getAccessToken.bind(this)},o.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(e=>this.realtime.setAuth(e)).catch(e=>{}),this.rest=new V(new URL("rest/v1",s).href,{headers:this.headers,schema:o.db.schema,fetch:this.fetch,timeout:o.db.timeout,urlLengthLimit:o.db.urlLengthLimit}),this.storage=new Tt(this.storageUrl.href,this.headers,this.fetch,null==n?void 0:n.storage),o.accessToken||this._listenForAuthEvents()}get functions(){return new R(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},n={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,n)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e,t,n=this;if(n.accessToken)return await n.accessToken();const{data:r}=await n.auth.getSession();return null!==(e=null===(t=r.session)||void 0===t?void 0:t.access_token)&&void 0!==e?e:n.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:r,userStorage:a,storageKey:s,flowType:i,lock:o,debug:l,throwOnError:u},c,d){const h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new wr({url:this.authUrl.href,headers:vr(vr({},h),c),storageKey:s,autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:r,userStorage:a,flowType:i,lock:o,debug:l,throwOnError:u,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(e=>"authorization"===e.toLowerCase())})}_initRealtimeClient(e){return new Ie(this.realtimeUrl.href,vr(vr({},e),{},{params:vr(vr({},{apikey:this.supabaseKey}),null==e?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",null==t?void 0:t.access_token)})}_handleTokenChanged(e,t,n){"TOKEN_REFRESHED"!==e&&"SIGNED_IN"!==e||this.changedAccessToken===n?"SIGNED_OUT"===e&&(this.realtime.setAuth(),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0):(this.changedAccessToken=n,this.realtime.setAuth(n))}};!function(){if("undefined"!=typeof window)return!1;const e=globalThis.process;if(!e)return!1;const t=e.version;if(null==t)return!1;const n=t.match(/^v(\d+)\./);!!n&&parseInt(n[1],10)}();let _r=null;const Sr=(_r||(_r=new kr("https://vomreccjpevmdllvpclp.supabase.co","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InZvbXJlY2NqcGV2bWRsbHZwY2xwIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTI0Mzc1MzMsImV4cCI6MjA2ODAxMzUzM30.0uKtryQJpUO1LtN5WGDALe2-4IojfkT6fNGjVXP-KPA",{auth:{persistSession:!0,storageKey:"nsturs-auth"}})),_r),xr={MEMBERS:"members",EVENTS:"events",ELECTIVE_COMMITTEE:"ec",CONTACT_MESSAGES:"contact_messages",PROJECTS:"projects"},Er="NSTURS",Tr={IMAGES:"images",ADVISORS:"advisors",FOUNDERS:"founders"},Cr="https://vomreccjpevmdllvpclp.storage.supabase.co",jr=async()=>{try{const{data:e,error:t}=await Sr.from("members").select("count").limit(1);return t?{success:!1,error:"Database connection failed. Please try again."}:{success:!0,data:e}}catch(e){return{success:!1,error:"Database connection failed. Please try again."}}},Or=async()=>{try{const{data:e,error:t}=await Sr.from(xr.MEMBERS).select("name, rs_id, department, batch, research_interest, research_experience, blood_group, created_at").order("created_at",{ascending:!1});if(t){if(t.message?.includes("permission")||t.message?.includes("policy")||t.message?.includes("RLS"))throw new Error("Permission denied. RLS policies may not be set up. Run database/members_rls_public_access.sql in Supabase