@iebh/tera-fy 2.3.8 → 2.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -61,7 +61,7 @@ Request ID: ${c}`),l){let O=`
61
61
  Resources:`;for(let D of l){if(!D||typeof D!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${D}`);O+=`
62
62
  - ${D}`}k+=O}return`${I}
63
63
  ${k}`}var le=class extends Error{constructor({message:e,code:t,cause:n,name:s}){var i;super(e,{cause:n}),this.__isWebAuthnError=!0,this.name=(i=s!=null?s:n instanceof Error?n.name:void 0)!==null&&i!==void 0?i:"Unknown Error",this.code=t}},sn=class extends le{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}};function cw({error:r,options:e}){var t,n,s;let{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new le({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else if(r.name==="ConstraintError"){if(((t=i.authenticatorSelection)===null||t===void 0?void 0:t.requireResidentKey)===!0)return new le({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:r});if(e.mediation==="conditional"&&((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new le({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:r});if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new le({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:r})}else{if(r.name==="InvalidStateError")return new le({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:r});if(r.name==="NotAllowedError")return new le({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="NotSupportedError")return i.pubKeyCredParams.filter(u=>u.type==="public-key").length===0?new le({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:r}):new le({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:r});if(r.name==="SecurityError"){let o=window.location.hostname;if(Ch(o)){if(i.rp.id!==o)return new le({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new le({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new le({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:r})}else if(r.name==="UnknownError")return new le({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return new le({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r})}function lw({error:r,options:e}){let{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new le({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else{if(r.name==="NotAllowedError")return new le({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="SecurityError"){let n=window.location.hostname;if(Ch(n)){if(t.rpId!==n)return new le({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new le({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="UnknownError")return new le({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return new le({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r})}var kh=class{createNewAbortSignal(){if(this.controller){let t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},eC=new kh;function dw(r){if(!r)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential!="undefined"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(r);let{challenge:e,user:t,excludeCredentials:n}=r,s=Kr(r,["challenge","user","excludeCredentials"]),i=yr(e).buffer,o=Object.assign(Object.assign({},t),{id:yr(t.id).buffer}),u=Object.assign(Object.assign({},s),{challenge:i,user:o});if(n&&n.length>0){u.excludeCredentials=new Array(n.length);for(let c=0;c<n.length;c++){let l=n[c];u.excludeCredentials[c]=Object.assign(Object.assign({},l),{id:yr(l.id).buffer,type:l.type||"public-key",transports:l.transports})}}return u}function fw(r){if(!r)throw new Error("Credential request options are required");if(typeof PublicKeyCredential!="undefined"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(r);let{challenge:e,allowCredentials:t}=r,n=Kr(r,["challenge","allowCredentials"]),s=yr(e).buffer,i=Object.assign(Object.assign({},n),{challenge:s});if(t&&t.length>0){i.allowCredentials=new Array(t.length);for(let o=0;o<t.length;o++){let u=t[o];i.allowCredentials[o]=Object.assign(Object.assign({},u),{id:yr(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return i}function pw(r){var e;if("toJSON"in r&&typeof r.toJSON=="function")return r.toJSON();let t=r;return{id:r.id,rawId:r.id,response:{attestationObject:Bt(new Uint8Array(r.response.attestationObject)),clientDataJSON:Bt(new Uint8Array(r.response.clientDataJSON))},type:"public-key",clientExtensionResults:r.getClientExtensionResults(),authenticatorAttachment:(e=t.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function mw(r){var e;if("toJSON"in r&&typeof r.toJSON=="function")return r.toJSON();let t=r,n=r.getClientExtensionResults(),s=r.response;return{id:r.id,rawId:r.id,response:{authenticatorData:Bt(new Uint8Array(s.authenticatorData)),clientDataJSON:Bt(new Uint8Array(s.clientDataJSON)),signature:Bt(new Uint8Array(s.signature)),userHandle:s.userHandle?Bt(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:n,authenticatorAttachment:(e=t.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Ch(r){return r==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(r)}function hw(){var r,e;return!!(Ae()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((r=navigator==null?void 0:navigator.credentials)===null||r===void 0?void 0:r.create)=="function"&&typeof((e=navigator==null?void 0:navigator.credentials)===null||e===void 0?void 0:e.get)=="function")}async function tC(r){try{let e=await navigator.credentials.create(r);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new sn("Browser returned unexpected credential type",e)}:{data:null,error:new sn("Empty credential response",e)}}catch(e){return{data:null,error:cw({error:e,options:r})}}}async function rC(r){try{let e=await navigator.credentials.get(r);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new sn("Browser returned unexpected credential type",e)}:{data:null,error:new sn("Empty credential response",e)}}catch(e){return{data:null,error:lw({error:e,options:r})}}}var nC={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},sC={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Ya(...r){let e=s=>s!==null&&typeof s=="object"&&!Array.isArray(s),t=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),n={};for(let s of r)if(s)for(let i in s){let o=s[i];if(o!==void 0)if(Array.isArray(o))n[i]=o;else if(t(o))n[i]=o;else if(e(o)){let u=n[i];e(u)?n[i]=Ya(u,o):n[i]=Ya(o)}else n[i]=o}return n}function iC(r,e){return Ya(nC,r,e||{})}function oC(r,e){return Ya(sC,r,e||{})}var Xa=class{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:s},i){var o;try{let{data:u,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!u)return{data:null,error:c};let l=s!=null?s:eC.createNewAbortSignal();if(u.webauthn.type==="create"){let{user:f}=u.webauthn.credential_options.publicKey;if(!f.name){let p=n;if(p)f.name=`${f.id}:${p}`;else{let y=(await this.client.getUser()).data.user,T=((o=y==null?void 0:y.user_metadata)===null||o===void 0?void 0:o.name)||(y==null?void 0:y.email)||(y==null?void 0:y.id)||"User";f.name=`${f.id}:${T}`}}f.displayName||(f.displayName=f.name)}switch(u.webauthn.type){case"create":{let f=iC(u.webauthn.credential_options.publicKey,i==null?void 0:i.create),{data:p,error:m}=await tC({publicKey:f,signal:l});return p?{data:{factorId:e,challengeId:u.id,webauthn:{type:u.webauthn.type,credential_response:p}},error:null}:{data:null,error:m}}case"request":{let f=oC(u.webauthn.credential_options.publicKey,i==null?void 0:i.request),{data:p,error:m}=await rC(Object.assign(Object.assign({},u.webauthn.credential_options),{publicKey:f,signal:l}));return p?{data:{factorId:e,challengeId:u.id,webauthn:{type:u.webauthn.type,credential_response:p}},error:null}:{data:null,error:m}}}}catch(u){return U(u)?{data:null,error:u}:{data:null,error:new Qe("Unexpected error in challenge",u)}}}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=typeof window!="undefined"?window.location.hostname:void 0,rpOrigins:n=typeof window!="undefined"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new gr("rpId is required for WebAuthn authentication")};try{if(!hw())return{data:null,error:new Qe("Browser does not support WebAuthn",null)};let{data:o,error:u}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:n},signal:s},{request:i});if(!o)return{data:null,error:u};let{webauthn:c}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:c.type,rpId:t,rpOrigins:n,credential_response:c.credential_response}})}catch(o){return U(o)?{data:null,error:o}:{data:null,error:new Qe("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:t=typeof window!="undefined"?window.location.hostname:void 0,rpOrigins:n=typeof window!="undefined"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new gr("rpId is required for WebAuthn registration")};try{if(!hw())return{data:null,error:new Qe("Browser does not support WebAuthn",null)};let{data:o,error:u}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(f=>{var p;return(p=f.data)===null||p===void 0?void 0:p.all.find(m=>m.factor_type==="webauthn"&&m.friendly_name===e&&m.status!=="unverified")}).then(f=>f?this.client.mfa.unenroll({factorId:f==null?void 0:f.id}):void 0),{data:null,error:u};let{data:c,error:l}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:t,rpOrigins:n},signal:s},{create:i});return c?this._verify({factorId:o.id,challengeId:c.challengeId,webauthn:{rpId:t,rpOrigins:n,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:l}}catch(o){return U(o)?{data:null,error:o}:{data:null,error:new Qe("Unexpected error in register",o)}}}};iw();var aC={url:V_,storageKey:L_,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:F_,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function gw(r,e,t){return await t()}var gs={},Za=class r{get jwks(){var e,t;return(t=(e=gs[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){gs[this.storageKey]=Object.assign(Object.assign({},gs[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=gs[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){gs[this.storageKey]=Object.assign(Object.assign({},gs[this.storageKey]),{cachedAt:e})}constructor(e){var t,n,s;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;let i=Object.assign(Object.assign({},aC),e);if(this.storageKey=i.storageKey,this.instanceID=(t=r.nextInstanceID[this.storageKey])!==null&&t!==void 0?t:0,r.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&Ae()){let o=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.admin=new nn({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=Wa(i.fetch),this.lock=i.lock||gw,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock?this.lock=i.lock:this.persistSession&&Ae()&&(!((n=globalThis==null?void 0:globalThis.navigator)===null||n===void 0)&&n.locks)?this.lock=Rh:this.lock=gw,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 Xa(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?(i.storage?this.storage=i.storage:Ga()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=xh(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=xh(this.memoryStorage)),Ae()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(u){this._debug("#broadcastChannel","error",u)}})}i.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Ma}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await 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(Ae()&&(t=H_(window.location.href),this._isImplicitGrantCallback(t)?n="implicit":await this._isPKCECallback(t)&&(n="pkce")),Ae()&&this.detectSessionInUrl&&n!=="none"){let{data:s,error:i}=await this._getSessionFromURL(t,n);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),B_(i)){let c=(e=i.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return{error:i}}let{session:o,redirectType:u}=s;return this._debug("#_initialize()","detected session in URL",o,"redirect type",u),await this._saveSession(o),setTimeout(async()=>{u==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return U(t)?this._returnResult({error:t}):this._returnResult({error:new Qe("Unexpected error during initialization",t)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,n,s;try{let i=await q(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(t=e==null?void 0:e.options)===null||t===void 0?void 0:t.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(s=e==null?void 0:e.options)===null||s===void 0?void 0:s.captchaToken}},xform:Ye}),{data:o,error:u}=i;if(u||!o)return this._returnResult({data:{user:null,session:null},error:u});let c=o.session,l=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:l,session:c},error:null})}catch(i){if(U(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var t,n,s;try{let i;if("email"in e){let{email:f,password:p,options:m}=e,y=null,T=null;this.flowType==="pkce"&&([y,T]=await en(this.storage,this.storageKey)),i=await q(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:m==null?void 0:m.emailRedirectTo,body:{email:f,password:p,data:(t=m==null?void 0:m.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:m==null?void 0:m.captchaToken},code_challenge:y,code_challenge_method:T},xform:Ye})}else if("phone"in e){let{phone:f,password:p,options:m}=e;i=await q(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:f,password:p,data:(n=m==null?void 0:m.data)!==null&&n!==void 0?n:{},channel:(s=m==null?void 0:m.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:m==null?void 0:m.captchaToken}},xform:Ye})}else throw new Jr("You must provide either an email or phone number and a password");let{data:o,error:u}=i;if(u||!o)return await Ce(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:u});let c=o.session,l=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:l,session:c},error:null})}catch(i){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),U(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(e){try{let t;if("email"in e){let{email:i,password:o,options:u}=e;t=await q(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken}},xform:Ah})}else if("phone"in e){let{phone:i,password:o,options:u}=e;t=await q(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken}},xform:Ah})}else throw new Jr("You must provide either an email or phone number and a password");let{data:n,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!n||!n.session||!n.user){let i=new Ut;return this._returnResult({data:{user:null,session:null},error:i})}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:s})}catch(t){if(U(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOAuth(e){var t,n,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{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,s,i,o,u,c,l,f,p,m;let y,T;if("message"in e)y=e.message,T=e.signature;else{let{chain:x,wallet:I,statement:k,options:O}=e,D;if(Ae())if(typeof I=="object")D=I;else{let b=window;if("ethereum"in b&&typeof b.ethereum=="object"&&"request"in b.ethereum&&typeof b.ethereum.request=="function")D=b.ethereum;else 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.")}else{if(typeof I!="object"||!(O!=null&&O.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");D=I}let M=new URL((t=O==null?void 0:O.url)!==null&&t!==void 0?t:window.location.href),B=await D.request({method:"eth_requestAccounts"}).then(b=>b).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!B||B.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let F=Ph(B[0]),w=(n=O==null?void 0:O.signInWithEthereum)===null||n===void 0?void 0:n.chainId;if(!w){let b=await D.request({method:"eth_chainId"});w=ow(b)}let _={domain:M.host,address:F,statement:k,uri:M.href,version:"1",chainId:w,nonce:(s=O==null?void 0:O.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(o=(i=O==null?void 0:O.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(u=O==null?void 0:O.signInWithEthereum)===null||u===void 0?void 0:u.expirationTime,notBefore:(c=O==null?void 0:O.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(l=O==null?void 0:O.signInWithEthereum)===null||l===void 0?void 0:l.requestId,resources:(f=O==null?void 0:O.signInWithEthereum)===null||f===void 0?void 0:f.resources};y=uw(_),T=await D.request({method:"personal_sign",params:[aw(y),F]})}try{let{data:x,error:I}=await q(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:y,signature:T},!((p=e.options)===null||p===void 0)&&p.captchaToken?{gotrue_meta_security:{captcha_token:(m=e.options)===null||m===void 0?void 0:m.captchaToken}}:null),xform:Ye});if(I)throw I;if(!x||!x.session||!x.user){let k=new Ut;return this._returnResult({data:{user:null,session:null},error:k})}return x.session&&(await this._saveSession(x.session),await this._notifyAllSubscribers("SIGNED_IN",x.session)),this._returnResult({data:Object.assign({},x),error:I})}catch(x){if(U(x))return this._returnResult({data:{user:null,session:null},error:x});throw x}}async signInWithSolana(e){var t,n,s,i,o,u,c,l,f,p,m,y;let T,x;if("message"in e)T=e.message,x=e.signature;else{let{chain:I,wallet:k,statement:O,options:D}=e,M;if(Ae())if(typeof k=="object")M=k;else{let F=window;if("solana"in F&&typeof F.solana=="object"&&("signIn"in F.solana&&typeof F.solana.signIn=="function"||"signMessage"in F.solana&&typeof F.solana.signMessage=="function"))M=F.solana;else 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.")}else{if(typeof k!="object"||!(D!=null&&D.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");M=k}let B=new URL((t=D==null?void 0:D.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in M&&M.signIn){let F=await M.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},D==null?void 0:D.signInWithSolana),{version:"1",domain:B.host,uri:B.href}),O?{statement:O}:null)),w;if(Array.isArray(F)&&F[0]&&typeof F[0]=="object")w=F[0];else if(F&&typeof F=="object"&&"signedMessage"in F&&"signature"in F)w=F;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in w&&"signature"in w&&(typeof w.signedMessage=="string"||w.signedMessage instanceof Uint8Array)&&w.signature instanceof Uint8Array)T=typeof w.signedMessage=="string"?w.signedMessage:new TextDecoder().decode(w.signedMessage),x=w.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in M)||typeof M.signMessage!="function"||!("publicKey"in M)||typeof M!="object"||!M.publicKey||!("toBase58"in M.publicKey)||typeof M.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");T=[`${B.host} wants you to sign in with your Solana account:`,M.publicKey.toBase58(),...O?["",O,""]:[""],"Version: 1",`URI: ${B.href}`,`Issued At: ${(s=(n=D==null?void 0:D.signInWithSolana)===null||n===void 0?void 0:n.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=D==null?void 0:D.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${D.signInWithSolana.notBefore}`]:[],...!((o=D==null?void 0:D.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${D.signInWithSolana.expirationTime}`]:[],...!((u=D==null?void 0:D.signInWithSolana)===null||u===void 0)&&u.chainId?[`Chain ID: ${D.signInWithSolana.chainId}`]:[],...!((c=D==null?void 0:D.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${D.signInWithSolana.nonce}`]:[],...!((l=D==null?void 0:D.signInWithSolana)===null||l===void 0)&&l.requestId?[`Request ID: ${D.signInWithSolana.requestId}`]:[],...!((p=(f=D==null?void 0:D.signInWithSolana)===null||f===void 0?void 0:f.resources)===null||p===void 0)&&p.length?["Resources",...D.signInWithSolana.resources.map(w=>`- ${w}`)]:[]].join(`
64
- `);let F=await M.signMessage(new TextEncoder().encode(T),"utf8");if(!F||!(F instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");x=F}}try{let{data:I,error:k}=await q(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:T,signature:Bt(x)},!((m=e.options)===null||m===void 0)&&m.captchaToken?{gotrue_meta_security:{captcha_token:(y=e.options)===null||y===void 0?void 0:y.captchaToken}}:null),xform:Ye});if(k)throw k;if(!I||!I.session||!I.user){let O=new Ut;return this._returnResult({data:{user:null,session:null},error:O})}return I.session&&(await this._saveSession(I.session),await this._notifyAllSubscribers("SIGNED_IN",I.session)),this._returnResult({data:Object.assign({},I),error:k})}catch(I){if(U(I))return this._returnResult({data:{user:null,session:null},error:I});throw I}}async _exchangeCodeForSession(e){let t=await _r(this.storage,`${this.storageKey}-code-verifier`),[n,s]=(t!=null?t:"").split("/");try{if(!n&&this.flowType==="pkce")throw new $a;let{data:i,error:o}=await q(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:Ye});if(await Ce(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!i||!i.session||!i.user){let u=new Ut;return this._returnResult({data:{user:null,session:null,redirectType:null},error:u})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:s!=null?s:null}),error:o})}catch(i){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),U(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{let{options:t,provider:n,token:s,access_token:i,nonce:o}=e,u=await q(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:s,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:t==null?void 0:t.captchaToken}},xform:Ye}),{data:c,error:l}=u;if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!c||!c.session||!c.user){let f=new Ut;return this._returnResult({data:{user:null,session:null},error:f})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:l})}catch(t){if(U(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOtp(e){var t,n,s,i,o;try{if("email"in e){let{email:u,options:c}=e,l=null,f=null;this.flowType==="pkce"&&([l,f]=await en(this.storage,this.storageKey));let{error:p}=await q(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:u,data:(t=c==null?void 0:c.data)!==null&&t!==void 0?t:{},create_user:(n=c==null?void 0:c.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},code_challenge:l,code_challenge_method:f},redirectTo:c==null?void 0:c.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:p})}if("phone"in e){let{phone:u,options:c}=e,{data:l,error:f}=await q(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:u,data:(s=c==null?void 0:c.data)!==null&&s!==void 0?s:{},create_user:(i=c==null?void 0:c.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},channel:(o=c==null?void 0:c.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:l==null?void 0:l.message_id},error:f})}throw new Jr("You must provide either an email or phone number.")}catch(u){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),U(u))return this._returnResult({data:{user:null,session:null},error:u});throw u}}async verifyOtp(e){var t,n;try{let s,i;"options"in e&&(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(n=e.options)===null||n===void 0?void 0:n.captchaToken);let{data:o,error:u}=await q(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:Ye});if(u)throw u;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,l=o.user;return c!=null&&c.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:l,session:c},error:null})}catch(s){if(U(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(e){var t,n,s,i,o;try{let u=null,c=null;this.flowType==="pkce"&&([u,c]=await en(this.storage,this.storageKey));let l=await q(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:(n=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&n!==void 0?n:void 0}),!((s=e==null?void 0:e.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:u,code_challenge_method:c}),headers:this.headers,xform:nw});return!((i=l.data)===null||i===void 0)&&i.url&&Ae()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(l.data.url),this._returnResult(l)}catch(u){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),U(u))return this._returnResult({data:null,error:u});throw u}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:n}=e;if(n)throw n;if(!t)throw new Oe;let{error:s}=await q(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:n,type:s,options:i}=e,{error:o}=await q(this.fetch,"POST",t,{headers:this.headers,body:{email:n,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in e){let{phone:n,type:s,options:i}=e,{data:o,error:u}=await q(this.fetch,"POST",t,{headers:this.headers,body:{phone:n,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:u})}throw new Jr("You must provide either an email or phone number and a type")}catch(t){if(U(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await n,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let n=t();for(this.pendingInLock.push((async()=>{try{await n}catch{}})()),await n;this.pendingInLock.length;){let s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await n}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{let 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,t=await _r(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let n=e.expires_at?e.expires_at*1e3-Date.now()<Ua:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){let o=await _r(this.userStorage,this.storageKey+"-user");o!=null&&o.user?e.user=o.user:e.user=Ha()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let o={value:this.suppressGetSessionWarning};e.user=tw(e.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let 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 q(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:bt}):await this._useSession(async t=>{var n,s,i;let{data:o,error:u}=t;if(u)throw u;return!(!((n=o.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Oe}:await q(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:bt})})}catch(t){if(U(t))return qa(t)&&(await this._removeSession(),await Ce(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=>{let{data:s,error:i}=n;if(i)throw i;if(!s.session)throw new Oe;let o=s.session,u=null,c=null;this.flowType==="pkce"&&e.email!=null&&([u,c]=await en(this.storage,this.storageKey));let{data:l,error:f}=await q(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t==null?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:u,code_challenge_method:c}),jwt:o.access_token,xform:bt});if(f)throw f;return o.user=l.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(n){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),U(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 Oe;let t=Date.now()/1e3,n=t,s=!0,i=null,{payload:o}=Ci(e.access_token);if(o.exp&&(n=o.exp,s=n<=t),s){let{data:u,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!u)return{data:{user:null,session:null},error:null};i=u}else{let{data:u,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});i={access_token:e.access_token,refresh_token:e.refresh_token,user:u.user,token_type:"bearer",expires_in:n-t,expires_at:n},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(t){if(U(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){let{data:o,error:u}=t;if(u)throw u;e=(n=o.session)!==null&&n!==void 0?n:void 0}if(!(e!=null&&e.refresh_token))throw new Oe;let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(t){if(U(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async _getSessionFromURL(e,t){try{if(!Ae())throw new Qr("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Qr(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(this.flowType==="pkce")throw new xi("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Qr("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new xi("No code detected.");let{data:O,error:D}=await this._exchangeCodeForSession(e.code);if(D)throw D;let M=new URL(window.location.href);return M.searchParams.delete("code"),window.history.replaceState(window.history.state,"",M.toString()),{data:{session:O.session,redirectType:null},error:null}}let{provider_token:n,provider_refresh_token:s,access_token:i,refresh_token:o,expires_in:u,expires_at:c,token_type:l}=e;if(!i||!u||!o||!l)throw new Qr("No session defined in URL");let f=Math.round(Date.now()/1e3),p=parseInt(u),m=f+p;c&&(m=parseInt(c));let y=m-f;y*1e3<=Hr&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${y}s, should have been closer to ${p}s`);let T=m-p;f-T>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",T,m,f):f-T<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",T,m,f);let{data:x,error:I}=await this._getUser(i);if(I)throw I;let k={provider_token:n,provider_refresh_token:s,access_token:i,expires_in:p,expires_at:m,refresh_token:o,token_type:l,user:x.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:k,redirectType:e.type},error:null})}catch(n){if(U(n))return this._returnResult({data:{session:null,redirectType:null},error:n});throw n}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){let t=await _r(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;let{data:s,error:i}=t;if(i&&!qa(i))return this._returnResult({error:i});let o=(n=s.session)===null||n===void 0?void 0:n.access_token;if(o){let{error:u}=await this.admin.signOut(o,e);if(u&&!(U_(u)&&(u.status===404||u.status===401||u.status===403)||qa(u)))return this._returnResult({error:u})}return e!=="others"&&(await this._removeSession(),await Ce(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let t=W_(),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,s;try{let{data:{session:i},error:o}=t;if(o)throw o;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i)}})}async resetPasswordForEmail(e,t={}){let n=null,s=null;this.flowType==="pkce"&&([n,s]=await en(this.storage,this.storageKey,!0));try{return await q(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(i){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),U(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{let{data:t,error:n}=await this.getUser();if(n)throw n;return this._returnResult({data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(t){if(U(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{let{data:n,error:s}=await this._useSession(async i=>{var o,u,c,l,f;let{data:p,error:m}=i;if(m)throw m;let y=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(u=e.options)===null||u===void 0?void 0:u.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await q(this.fetch,"GET",y,{headers:this.headers,jwt:(f=(l=p.session)===null||l===void 0?void 0:l.access_token)!==null&&f!==void 0?f:void 0})});if(s)throw s;return Ae()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(n==null?void 0:n.url),this._returnResult({data:{provider:e.provider,url:n==null?void 0:n.url},error:null})}catch(n){if(U(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{let{error:s,data:{session:i}}=t;if(s)throw s;let{options:o,provider:u,token:c,access_token:l,nonce:f}=e,p=await q(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(n=i==null?void 0:i.access_token)!==null&&n!==void 0?n:void 0,body:{provider:u,id_token:c,access_token:l,nonce:f,link_identity:!0,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:Ye}),{data:m,error:y}=p;return y?this._returnResult({data:{user:null,session:null},error:y}):!m||!m.session||!m.user?this._returnResult({data:{user:null,session:null},error:new Ut}):(m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("USER_UPDATED",m.session)),this._returnResult({data:m,error:y}))}catch(s){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),U(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var n,s;let{data:i,error:o}=t;if(o)throw o;return await q(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&s!==void 0?s:void 0})})}catch(t){if(U(t))return this._returnResult({data:null,error:t});throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let n=Date.now();return await Y_(async s=>(s>0&&await Q_(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await q(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Ye})),(s,i)=>{let o=200*Math.pow(2,s);return i&&za(i)&&Date.now()+o-n<Hr})}catch(n){if(this._debug(t,"error",n),U(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let 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),Ae()&&!t.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e,t;let n="#_recoverAndRefresh()";this._debug(n,"begin");try{let s=await _r(this.storage,this.storageKey);if(s&&this.userStorage){let o=await _r(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:s.user},await Zr(this.userStorage,this.storageKey+"-user",o)),s.user=(e=o==null?void 0:o.user)!==null&&e!==void 0?e:Ha()}else if(s&&!s.user&&!s.user){let o=await _r(this.storage,this.storageKey+"-user");o&&(o!=null&&o.user)?(s.user=o.user,await Ce(this.storage,this.storageKey+"-user"),await Zr(this.storage,this.storageKey,s)):s.user=Ha()}if(this._debug(n,"session from storage",s),!this._isValidSession(s)){this._debug(n,"session is not valid"),s!==null&&await this._removeSession();return}let i=((t=s.expires_at)!==null&&t!==void 0?t:1/0)*1e3-Date.now()<Ua;if(this._debug(n,`session has${i?"":" not"} expired with margin of ${Ua}s`),i){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),za(o)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(s.user&&s.user.__isUserNotAvailableProxy===!0)try{let{data:o,error:u}=await this._getUser(s.access_token);!u&&(o!=null&&o.user)?(s.user=o.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):this._debug(n,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(n,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(n,"error",s),console.error(s);return}finally{this._debug(n,"end")}}async _callRefreshToken(e){var t,n;if(!e)throw new Oe;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new Pi;let{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new Oe;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);let u={data:i.session,error:null};return this.refreshingDeferred.resolve(u),u}catch(i){if(this._debug(s,"error",i),U(i)){let o={data:null,error:i};return za(i)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(n=this.refreshingDeferred)===null||n===void 0||n.reject(i),i}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,n=!0){let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:t});let i=[],o=Array.from(this.stateChangeEmitters.values()).map(async u=>{try{await u.callback(e,t)}catch(c){i.push(c)}});if(await Promise.all(o),i.length>0){for(let u=0;u<i.length;u+=1)console.error(i[u]);throw i[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Ce(this.storage,`${this.storageKey}-code-verifier`);let t=Object.assign({},e),n=t.user&&t.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!n&&t.user&&await Zr(this.userStorage,this.storageKey+"-user",{user:t.user});let s=Object.assign({},t);delete s.user;let i=Ih(s);await Zr(this.storage,this.storageKey,i)}else{let s=Ih(t);await Zr(this.storage,this.storageKey,s)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Ce(this.storage,this.storageKey),await Ce(this.storage,this.storageKey+"-code-verifier"),await Ce(this.storage,this.storageKey+"-user"),this.userStorage&&await Ce(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Ae()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),Hr);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno!="undefined"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno!="undefined"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let 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{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:n}}=t;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((n.expires_at*1e3-e)/Hr);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${Hr}ms, refresh threshold is ${ja} ticks`),s<=ja&&await this._callRefreshToken(n.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof ki)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Ae()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,n){let s=[`provider=${encodeURIComponent(t)}`];if(n!=null&&n.redirectTo&&s.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n!=null&&n.scopes&&s.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){let[i,o]=await en(this.storage,this.storageKey),u=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});s.push(u.toString())}if(n!=null&&n.queryParams){let i=new URLSearchParams(n.queryParams);s.push(i.toString())}return n!=null&&n.skipBrowserRedirect&&s.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var n;let{data:s,error:i}=t;return i?this._returnResult({data:null,error:i}):await q(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(n=s==null?void 0:s.session)===null||n===void 0?void 0:n.access_token})})}catch(t){if(U(t))return this._returnResult({data:null,error:t});throw t}}async _enroll(e){try{return await this._useSession(async t=>{var n,s;let{data:i,error:o}=t;if(o)return this._returnResult({data:null,error:o});let u=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:l}=await q(this.fetch,"POST",`${this.url}/factors`,{body:u,headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token});return l?this._returnResult({data:null,error:l}):(e.factorType==="totp"&&c.type==="totp"&&(!((s=c==null?void 0:c.totp)===null||s===void 0)&&s.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(t){if(U(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;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?pw(e.webauthn.credential_response):mw(e.webauthn.credential_response)})}:{code:e.code}),{data:u,error:c}=await q(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(n=s==null?void 0:s.session)===null||n===void 0?void 0:n.access_token});return c?this._returnResult({data:null,error:c}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+u.expires_in},u)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",u),this._returnResult({data:u,error:c}))})}catch(t){if(U(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;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let o=await q(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=s==null?void 0:s.session)===null||n===void 0?void 0:n.access_token});if(o.error)return o;let{data:u}=o;if(u.type!=="webauthn")return{data:u,error:null};switch(u.webauthn.type){case"create":return{data:Object.assign(Object.assign({},u),{webauthn:Object.assign(Object.assign({},u.webauthn),{credential_options:Object.assign(Object.assign({},u.webauthn.credential_options),{publicKey:dw(u.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},u),{webauthn:Object.assign(Object.assign({},u.webauthn),{credential_options:Object.assign(Object.assign({},u.webauthn.credential_options),{publicKey:fw(u.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(t){if(U(t))return this._returnResult({data:null,error:t});throw t}})}async _challengeAndVerify(e){let{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;let{data:{user:t},error:n}=await this.getUser();if(n)return{data:null,error:n};let s={all:[],phone:[],totp:[],webauthn:[]};for(let i of(e=t==null?void 0:t.factors)!==null&&e!==void 0?e:[])s.all.push(i),i.status==="verified"&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,n,s,i;if(e)try{let{payload:y}=Ci(e),T=null;y.aal&&(T=y.aal);let x=T,{data:{user:I},error:k}=await this.getUser(e);if(k)return this._returnResult({data:null,error:k});((n=(t=I==null?void 0:I.factors)===null||t===void 0?void 0:t.filter(M=>M.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(x="aal2");let D=y.amr||[];return{data:{currentLevel:T,nextLevel:x,currentAuthenticationMethods:D},error:null}}catch(y){if(U(y))return this._returnResult({data:null,error:y});throw y}let{data:{session:o},error:u}=await this.getSession();if(u)return this._returnResult({data:null,error:u});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:c}=Ci(o.access_token),l=null;c.aal&&(l=c.aal);let f=l;((i=(s=o.user.factors)===null||s===void 0?void 0:s.filter(y=>y.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(f="aal2");let m=c.amr||[];return{data:{currentLevel:l,nextLevel:f,currentAuthenticationMethods:m},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:n},error:s}=t;return s?this._returnResult({data:null,error:s}):n?await q(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new Oe})})}catch(t){if(U(t))return this._returnResult({data:null,error:t});throw t}}async _approveAuthorization(e,t){try{return await this._useSession(async n=>{let{data:{session:s},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new Oe});let o=await q(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:u=>({data:u,error:null})});return o.data&&o.data.redirect_url&&Ae()&&!(t!=null&&t.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(n){if(U(n))return this._returnResult({data:null,error:n});throw n}}async _denyAuthorization(e,t){try{return await this._useSession(async n=>{let{data:{session:s},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new Oe});let o=await q(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:u=>({data:u,error:null})});return o.data&&o.data.redirect_url&&Ae()&&!(t!=null&&t.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(n){if(U(n))return this._returnResult({data:null,error:n});throw n}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:n}=e;return n?this._returnResult({data:null,error:n}):t?await q(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new Oe})})}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:n},error:s}=t;return s?this._returnResult({data:null,error:s}):n?(await q(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 Oe})})}catch(t){if(U(t))return this._returnResult({data:null,error:t});throw t}}async fetchJwk(e,t={keys:[]}){let n=t.keys.find(u=>u.kid===e);if(n)return n;let s=Date.now();if(n=this.jwks.keys.find(u=>u.kid===e),n&&this.jwks_cached_at+j_>s)return n;let{data:i,error:o}=await q(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,n=i.keys.find(u=>u.kid===e),!n)?null:n}async getClaims(e,t={}){try{let n=e;if(!n){let{data:y,error:T}=await this.getSession();if(T||!y.session)return this._returnResult({data:null,error:T});n=y.session.access_token}let{header:s,payload:i,signature:o,raw:{header:u,payload:c}}=Ci(n);t!=null&&t.allowExpired||Z_(i.exp);let l=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,t!=null&&t.keys?{keys:t.keys}:t==null?void 0:t.jwks);if(!l){let{error:y}=await this.getUser(n);if(y)throw y;return{data:{claims:i,header:s,signature:o},error:null}}let f=ew(s.alg),p=await crypto.subtle.importKey("jwk",l,f,!0,["verify"]);if(!await crypto.subtle.verify(f,p,o,K_(`${u}.${c}`)))throw new Yr("Invalid JWT signature");return{data:{claims:i,header:s,signature:o},error:null}}catch(n){if(U(n))return this._returnResult({data:null,error:n});throw n}}};Za.nextInstanceID={};var Oh=Za;var uC=Oh,Dh=uC;var cC="2.99.1",Oi="";typeof Deno!="undefined"?Oi="deno":typeof document!="undefined"?Oi="web":typeof navigator!="undefined"&&navigator.product==="ReactNative"?Oi="react-native":Oi="node";var lC={"X-Client-Info":`supabase-js-${Oi}/${cC}`},hC={headers:lC},dC={schema:"public"},fC={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},pC={};function Di(r){"@babel/helpers - typeof";return Di=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Di(r)}function mC(r,e){if(Di(r)!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var n=t.call(r,e||"default");if(Di(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function gC(r){var e=mC(r,"string");return Di(e)=="symbol"?e:e+""}function yC(r,e,t){return(e=gC(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function yw(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(r,s).enumerable})),t.push.apply(t,n)}return t}function me(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?yw(Object(t),!0).forEach(function(n){yC(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):yw(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var _C=r=>r?(...e)=>r(...e):(...e)=>fetch(...e),wC=()=>Headers,vC=(r,e,t)=>{let n=_C(t),s=wC();return async(i,o)=>{var u;let c=(u=await e())!==null&&u!==void 0?u:r,l=new s(o==null?void 0:o.headers);return l.has("apikey")||l.set("apikey",r),l.has("Authorization")||l.set("Authorization",`Bearer ${c}`),n(i,me(me({},o),{},{headers:l}))}};function bC(r){return r.endsWith("/")?r:r+"/"}function EC(r,e){var t,n;let{db:s,auth:i,realtime:o,global:u}=r,{db:c,auth:l,realtime:f,global:p}=e,m={db:me(me({},c),s),auth:me(me({},l),i),realtime:me(me({},f),o),storage:{},global:me(me(me({},p),u),{},{headers:me(me({},(t=p==null?void 0:p.headers)!==null&&t!==void 0?t:{}),(n=u==null?void 0:u.headers)!==null&&n!==void 0?n:{})}),accessToken:async()=>""};return r.accessToken?m.accessToken=r.accessToken:delete m.accessToken,m}function TC(r){let e=r==null?void 0:r.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(bC(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var IC=class extends Dh{constructor(r){super(r)}},AC=class{constructor(r,e,t){var n,s;this.supabaseUrl=r,this.supabaseKey=e;let i=TC(r);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);let o=`sb-${i.hostname.split(".")[0]}-auth-token`,u={db:dC,realtime:pC,auth:me(me({},fC),{},{storageKey:o}),global:hC},c=EC(t!=null?t:{},u);if(this.storageKey=(n=c.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(s=c.global.headers)!==null&&s!==void 0?s:{},c.accessToken)this.accessToken=c.accessToken,this.auth=new Proxy({},{get:(f,p)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(p)} is not possible`)}});else{var l;this.auth=this._initSupabaseAuthClient((l=c.auth)!==null&&l!==void 0?l:{},this.headers,c.global.fetch)}this.fetch=vC(e,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(me({headers:this.headers,accessToken:this._getAccessToken.bind(this)},c.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(f=>this.realtime.setAuth(f)).catch(f=>console.warn("Failed to set initial Realtime auth token:",f)),this.rest=new w_(new URL("rest/v1",i).href,{headers:this.headers,schema:c.db.schema,fetch:this.fetch,timeout:c.db.timeout,urlLengthLimit:c.db.urlLengthLimit}),this.storage=new N_(this.storageUrl.href,this.headers,this.fetch,t==null?void 0:t.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new gi(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(r){return this.rest.from(r)}schema(r){return this.rest.schema(r)}rpc(r,e={},t={head:!1,get:!1,count:void 0}){return this.rest.rpc(r,e,t)}channel(r,e={config:{}}){return this.realtime.channel(r,e)}getChannels(){return this.realtime.getChannels()}removeChannel(r){return this.realtime.removeChannel(r)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var r=this,e,t;if(r.accessToken)return await r.accessToken();let{data:n}=await r.auth.getSession();return(e=(t=n.session)===null||t===void 0?void 0:t.access_token)!==null&&e!==void 0?e:r.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:r,persistSession:e,detectSessionInUrl:t,storage:n,userStorage:s,storageKey:i,flowType:o,lock:u,debug:c,throwOnError:l},f,p){let m={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new IC({url:this.authUrl.href,headers:me(me({},m),f),storageKey:i,autoRefreshToken:r,persistSession:e,detectSessionInUrl:t,storage:n,userStorage:s,flowType:o,lock:u,debug:c,throwOnError:l,fetch:p,hasCustomAuthorizationHeader:Object.keys(this.headers).some(y=>y.toLowerCase()==="authorization")})}_initRealtimeClient(r){return new ds(this.realtimeUrl.href,me(me({},r),{},{params:me(me({},{apikey:this.supabaseKey}),r==null?void 0:r.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((r,e)=>{this._handleTokenChanged(r,"CLIENT",e==null?void 0:e.access_token)})}_handleTokenChanged(r,e,t){(r==="TOKEN_REFRESHED"||r==="SIGNED_IN")&&this.changedAccessToken!==t?(this.changedAccessToken=t,this.realtime.setAuth(t)):r==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}},_w=(r,e,t)=>new AC(r,e,t);function SC(){if(typeof window!="undefined")return!1;let r=globalThis.process;if(!r)return!1;let e=r.version;if(e==null)return!1;let t=e.match(/^v(\d+)\./);return t?parseInt(t[1],10)<=18:!1}SC()&&console.warn("\u26A0\uFE0F Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");var xC=Object.prototype.toString,RC=r=>xC.call(r)==="[object Error]",PC=new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function Nh(r){if(!(r&&RC(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"?n===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")||t==="Failed to fetch"||t.startsWith("Failed to fetch (")&&t.endsWith(")")?!0:PC.has(t)}function CC(r){if(typeof r=="number"){if(r<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function eu(r,e,{min:t=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${r}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${r}\` to be a finite number.`);if(e<t)throw new TypeError(`Expected \`${r}\` to be \u2265 ${t}.`)}}var Vh=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function kC(r,e){let t=Math.max(1,r+1),n=e.randomize?Math.random()+1:1,s=Math.round(n*e.minTimeout*e.factor**(t-1));return s=Math.min(s,e.maxTimeout),s}function ww(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function OC({error:r,attemptNumber:e,retriesConsumed:t,startTime:n,options:s}){var y,T,x,I,k;let i=r instanceof Error?r:new TypeError(`Non-error was thrown: "${r}". You should only throw errors.`);if(i instanceof Vh)throw i.originalError;let o=Number.isFinite(s.retries)?Math.max(0,s.retries-t):s.retries,u=(y=s.maxRetryTime)!=null?y:Number.POSITIVE_INFINITY,c=Object.freeze({error:i,attemptNumber:e,retriesLeft:o,retriesConsumed:t});if(await s.onFailedAttempt(c),ww(n,u)<=0)throw i;let l=await s.shouldConsumeRetry(c),f=ww(n,u);if(f<=0||o<=0)throw i;if(i instanceof TypeError&&!Nh(i)){if(l)throw i;return(T=s.signal)==null||T.throwIfAborted(),!1}if(!await s.shouldRetry(c))throw i;if(!l)return(x=s.signal)==null||x.throwIfAborted(),!1;let p=kC(t,s),m=Math.min(p,f);return(I=s.signal)==null||I.throwIfAborted(),m>0&&await new Promise((O,D)=>{var F,w;let M=()=>{var _;clearTimeout(B),(_=s.signal)==null||_.removeEventListener("abort",M),D(s.signal.reason)},B=setTimeout(()=>{var _;(_=s.signal)==null||_.removeEventListener("abort",M),O()},m);s.unref&&((F=B.unref)==null||F.call(B)),(w=s.signal)==null||w.addEventListener("abort",M,{once:!0})}),(k=s.signal)==null||k.throwIfAborted(),!0}async function Ni(r,e={}){var i,o,u,c,l,f,p,m,y,T,x,I;if(e={...e},CC(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");(i=e.retries)!=null||(e.retries=10),(o=e.factor)!=null||(e.factor=2),(u=e.minTimeout)!=null||(e.minTimeout=1e3),(c=e.maxTimeout)!=null||(e.maxTimeout=Number.POSITIVE_INFINITY),(l=e.maxRetryTime)!=null||(e.maxRetryTime=Number.POSITIVE_INFINITY),(f=e.randomize)!=null||(e.randomize=!1),(p=e.onFailedAttempt)!=null||(e.onFailedAttempt=()=>{}),(m=e.shouldRetry)!=null||(e.shouldRetry=()=>!0),(y=e.shouldConsumeRetry)!=null||(e.shouldConsumeRetry=()=>!0),eu("factor",e.factor,{min:0,allowInfinity:!1}),eu("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),eu("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),eu("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),(T=e.signal)==null||T.throwIfAborted();let t=0,n=0,s=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){t++;try{(x=e.signal)==null||x.throwIfAborted();let k=await r(t);return(I=e.signal)==null||I.throwIfAborted(),k}catch(k){await OC({error:k,attemptNumber:t,retriesConsumed:n,startTime:s,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var DC=function(e,t){if(typeof e!="function")throw new Error("First argument to supabasey() must be a callback function");let n={session:null,retries:3,retry:{minTimeout:100,factor:2,randomize:!0,onFailedAttempt:i=>console.info(`[Attempt ${i.attemptNumber}/${i.attemptNumber+i.retriesLeft-1}] failed to run Supabase query`),shouldRetry:i=>(console.log("QUERY SHOULD-RETRY",i),!0)},...t},s=n.session?typeof n.session=="string"?Se.sessions[n.session]:typeof n.session=="object"?n.session:(()=>{throw new Error(`Unknown session type for supabasey(cb, {session}) - expected Object|String got ${typeof n.session}`)})():(()=>{throw new Error("supabasey(cb, {session}) cannot be empty - specify a session or use bindSession() first")})();return Promise.resolve().then(()=>Ni(()=>e.call(s,s),{...n.retries&&{retries:n.retries},...t.retry})).then(i=>{if(i!=null&&i.error)Se.throw(i.error);else if(i.data)return i.data}).catch(i=>{throw console.log("Supabasey error:",i),i})},Se=DC;Se.bindSession=function(e){if(typeof e=="string"&&!Se.sessions[e])throw new Error(`Unable to bind to non-existant session "${e}"`);let t=(n,s)=>Se(n,{session:e,...s});return t.rpc=(n,s,i)=>Se.rpc(n,s,{session:e,...i}),t};Se.init=function(e){let t={env:{},init:!0,login:!1,session:"auto",...e},n=t.env,s=t.session=="auto"&&n.SUPABASE_URL?n.SUPABASE_URL:t.session?t.session:(()=>{throw new Error("Sesison should be truthy if using @iebh/supabasey.middleware({session:String})")})(),i=Se.sessions[s];return Promise.resolve().then(()=>{if(!i)if(t.init){if(!n.SUPABASE_URL||!n.SUPABASE_KEY)throw new Error("Both env.SUPABASE_URL + env.SUPABASE_KEY should be specified to use @iebh/supabasey.middleware(), otherwise disable with {init:false}");i=Se.sessions[s]=_w(n.SUPABASE_URL,n.SUPABASE_KEY)}else throw new Error("No Supabase session for middleware to work with!")}).then(()=>{if(t.login){if(i.supabaseyIsLoggedIn)return;if(!n.SUPABASE_USER||!n.SUPABASE_PASS)throw new Error("User credentials missing when using @iebh/supabasey.middleware(), provide in env.SUPABASE_USER + ..._PASS");return Se(o=>o.auth.signInWithPassword({email:n.SUPABASE_USER,password:n.SUPABASE_PASS}),{session:i}).then(()=>i.supabaseyIsLoggedIn=!0)}else return}).then(()=>Se.bindSession(i))};Se.middleware=function(e){let t={env:{},injectEnv:!0,...e};return async(n,s,i,o)=>Se.init({...e,env:i}).then(u=>{t.injectEnv&&(i.supabasey=u)}).catch(u=>Se.throw(u))};Se.throw=function(r){throw typeof r=="string"?new Error(r):r instanceof Error?r:/JSON object requested, multiple \(or no\) rows returned$/.test(r.message)?(console.warn("Supabase query resulted in NOT-FOUND:",r.message),console.warn("Supabase raw error",r),new Error("NOT-FOUND")):(console.warn("Supabase query threw",r.message||r||"Unknown error"),new Error(`${(r==null?void 0:r.code)||"UnknownError"}: ${(r==null?void 0:r.message)||"Unknown Supabase error"}`))};Se.rpc=function(r,e,t){return Se(async n=>await n.rpc(r,e),t)};Se.sessions={};var vw=Se;function NC(r,e){return Object.fromEntries(Object.entries(r).sort(e||void 0).map(([t,n])=>[t,n]))}function tu(r,e){return Array.isArray(r)?r.map(t=>tu(t,e)):typeof r=="object"?r==null?null:Object.fromEntries(Object.entries(NC(r,e)).map(([t,n])=>[t,tu(n,e)])):r}var bw={id:"~date",test:r=>r instanceof Date,serialize:r=>({_:"~date",v:r.toISOString()}),deserialize:r=>new Date(r.v)};var Ew={id:"~function",test:r=>typeof r=="function",serialize:r=>({_:"~function",v:r.toString()}),deserialize:v=>eval(v.v.toString())};var Tw={id:"~infinity",test:r=>r===1/0||r===-1/0,serialize:r=>({_:"~infinity",v:r===1/0?1:0}),deserialize:r=>r.v==1?1/0:-1/0};var Iw={id:"~nan",test:r=>Number.isNaN(r),serialize:r=>({_:"~nan"}),deserialize:r=>NaN};var Aw={id:"~regexp",test:r=>r instanceof RegExp,serialize:r=>({_:"~regexp",v:r.source,f:r.flags}),deserialize:r=>new RegExp(r.v,r.f)};var Sw={id:"~set",test:r=>r instanceof Set,serialize:r=>({_:"~set",v:Array.from(r)}),deserialize:r=>new Set(r.v)};var xw={id:"~undefined",test:r=>r===void 0,serialize:r=>({_:"~undefined"}),deserialize:r=>{}};var ys={settings:{stringify:!0,destringify:!0,clone:!1,depth:0,modules:[bw,Ew,Tw,Iw,Aw,Sw,xw],circular:!0,symetric:!1},loadedModules:{},loadModules(r){return r.map(e=>{if(ee(e)){if(!e.id)throw new Error("Provided custom module does not expose an `id` property");return ys.loadedModules[e.id]=e}else throw new Error("Unknown module type")})},serialize(r,e){let t=Io(e,ys.settings),n=ys.loadModules(t.modules),s=t.symetric?tu(r):t.clone?ar(r):r,i=new Map,o=(u,c)=>{let l=ee(u);if(l&&t.circular){let m=i.get(u);if(m)return ur(s,c,{_:"~circular",p:m.join(".")});i.set(u,c)}let f=n.find(m=>m.test(u,c)),p=(!t.depth||c.length<t.depth)&&l;if(f){let m=f.serialize(u,c);if(f.recursive&&p){let y=Ne(u);t.symetric&&y.sort(),ur(s,c,m),y.forEach(T=>o(u[T],c.concat(T)))}else c.length?ur(s,c,m):s=m}else if(p){let m=Ne(u);t.symetric&&m.sort(),m.forEach(y=>o(u[y],c.concat(y)))}};return o(s,[]),t.stringify?JSON.stringify(s):s},deserialize(r,e){let t=Io(e,ys.settings),n=ys.loadModules(t.modules),s=Du(n,"id"),i=t.destringify?JSON.parse(r):t.clone?ar(r):r,o=(u,c)=>{if(ee(u)&&u._&&typeof u._=="string"&&u._.startsWith("~")&&s[u._]){let l=s[u._].deserialize(u,c);c.length?s[u._].recursive&&ee(l)?(ur(i,c,l),Ne(l).forEach(f=>o(u[f],[...c,f]))):ur(i,c,l):i=l}else t.circular&&ee(u)&&u._&&u._=="~circular"?ur(i,c,Ls(i,u.p)):(!t.depth||c.length<t.depth)&&ee(u)&&Ne(u).forEach(l=>o(u[l],c.concat(l)))};return o(i,[]),i}},ru=ys;var Rw="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Pw=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=Rw[t[r]&63];return e};var Cw=new WeakMap,Vi=new WeakMap,VC=new FinalizationRegistry(({signalWeakRef:r,weakReference:e})=>{let t=r.deref();if(!t)return;let n=Vi.get(t);n&&(n.throttleds.delete(e),n.throttleds.size===0&&(t.removeEventListener("abort",n.listener),Vi.delete(t)))});function Lh({limit:r,interval:e,strict:t,signal:n,onDelay:s,weight:i}){if(!Number.isFinite(r))throw new TypeError("Expected `limit` to be a finite number");if(!Number.isFinite(e))throw new TypeError("Expected `interval` to be a finite number");if(r<0)throw new TypeError("Expected `limit` to be >= 0");if(e<0)throw new TypeError("Expected `interval` to be >= 0");if(i!==void 0&&typeof i!="function")throw new TypeError("Expected `weight` to be a function");if(i&&e===0)throw new TypeError("The `weight` option cannot be used with `interval` of 0");let o={queue:new Map,strictTicks:[],currentTick:0,activeWeight:0},u=Math.max(r,1),c=m=>{if(o.strictTicks.length===0||m.time>=o.strictTicks.at(-1).time)o.strictTicks.push(m);else{let y=o.strictTicks.findIndex(T=>T.time>m.time);o.strictTicks.splice(y,0,m)}};function l(m){let y=Date.now();return y-o.currentTick>e?(o.activeWeight=m,o.currentTick=y,0):(o.activeWeight+m<=r?o.activeWeight+=m:(o.currentTick+=e,o.activeWeight=m),o.currentTick-y)}function f(m){let y=Date.now();if(o.strictTicks.length>0&&y-o.strictTicks.at(-1).time>e&&(o.strictTicks.length=0),i){for(;o.strictTicks.length>0&&y-o.strictTicks[0].time>=e;)o.strictTicks.shift();let M=w=>{let _=0;for(let b of o.strictTicks)b.time<=w&&w-b.time<e&&(_+=b.weight);return _};if(M(y)+m<=r)return c({time:y,weight:m}),{delay:0};let B=y;for(;M(B)+m>r;){let w=o.strictTicks.find(_=>_.time<=B&&B-_.time<e);if(!w)break;B=w.time+e}let F={time:B,weight:m};return c(F),{delay:Math.max(0,B-y),tickRecord:F}}if(o.strictTicks.length<u)return o.strictTicks.push({time:y,weight:m}),{delay:0};let T=o.strictTicks[0].time,x=o.strictTicks.at(-1).time,I=T+e,k=e>0?Math.ceil(e/u):0,O=I<=x?x+k:I;o.strictTicks.shift();let D={time:O,weight:m};return o.strictTicks.push(D),{delay:Math.max(0,O-y),tickRecord:D}}let p=t?f:l;return m=>{let y=function(...T){if(!y.isEnabled)return(async()=>m.apply(this,T))();let x;return new Promise((I,k)=>{let O=1;if(i){try{O=i(...T)}catch(w){k(w);return}if(!Number.isFinite(O)||O<0){k(new TypeError("Expected `weight` to be a finite non-negative number"));return}if(O>r){k(new TypeError(`Expected \`weight\` (${O}) to be <= \`limit\` (${r})`));return}}let D=p(O),M=t?D.delay:D,B=t?D.tickRecord:void 0,F=()=>{if(B){let w=Date.now();if(i&&B.time!==w){B.time=w;let _=o.strictTicks.indexOf(B);o.strictTicks.splice(_,1),c(B)}else B.time=w}try{I(m.apply(this,T))}catch(w){k(w)}o.queue.delete(x)};if(M>0){x=setTimeout(F,M),o.queue.set(x,k);try{s==null||s(...T)}catch{}}else F()})};if(n==null||n.throwIfAborted(),n){let T=Vi.get(n);T||(T={throttleds:new Set,listener:null},T.listener=()=>{for(let I of T.throttleds){let k=I.deref();if(!k)continue;let O=Cw.get(k);if(O){for(let D of O.queue.keys())clearTimeout(D),O.queue.get(D)(n.reason);O.queue.clear(),O.strictTicks.length=0,O.currentTick=0,O.activeWeight=0}}Vi.delete(n)},Vi.set(n,T),n.addEventListener("abort",T.listener,{once:!0}));let x=new WeakRef(y);T.throttleds.add(x),VC.register(y,{signalWeakRef:new WeakRef(n),weakReference:x})}return y.isEnabled=!0,Object.defineProperty(y,"queueSize",{get(){return o.queue.size}}),Cw.set(y,o),y}}var re=class re{constructor(e,t){se(this,"path");se(this,"docRef");se(this,"value");se(this,"throttle",250);se(this,"config",{heartbeatInterval:12e4,syncroRegistryUrl:"https://tera-tools.com/api/sync",context:{}});se(this,"isDirty",!1);se(this,"_destroyActions",[]);se(this,"_heartbeatTimer");this.path=e,Object.assign(this,{...t,config:{...this.config,...t==null?void 0:t.config}}),re.session||(re.session=`syncro_${Pw()}`)}debug(...e){}debugError(...e){console.warn(`[Syncro ${this.path}]`,...e)}destroy(){return this.debug("Destroy!"),Promise.resolve().then(()=>Promise.all(this._destroyActions.map(e=>e()))).then(()=>this._destroyActions=[])}getReactive(e){console.warn("Syncro.getReactive has not been subclassed, assuming a POJO response");let t={...e};return{doc:t,setState(n){Object.entries(n||{}).forEach(([s,i])=>t[s]=i)},getState(){return ar(t)},watch(n){}}}static pathSplit(e,t){var o;let n={allowAsterisk:!1,...t},i={...(o=new RegExp("^(?<entity>\\w+?)::(?<id>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:::(?<relation>[\\w\\-"+(n.allowAsterisk?"\\*":"")+"]+?))?$").exec(e))==null?void 0:o.groups};if(!i||!i.entity||!i.id)throw new Error(`Invalid session path syntax "${e}"`);if(re.SyncroEntities&&!(i.entity in re.SyncroEntities))throw new Error(`Unsupported entity "${e}" -> Entity="${i.entity}"`);return{entity:i.entity,id:i.id,relation:i.relation,fsCollection:i.entity,fsId:i.relation?`${i.id}::${i.relation}`:i.id}}static toFirestore(e={}){return ru.serialize(e,{...kw,stringify:!1})}static fromFirestore(e={}){return ru.deserialize(e,{...kw,destringify:!1})}static toFirestoreFields(e){let t={};for(let[n,s]of Object.entries(e)){let i=typeof s;i==="string"?t[n]={stringValue:s}:i==="number"?t[n]={doubleValue:s}:i==="boolean"?t[n]={booleanValue:s}:s===null?t[n]={nullValue:null}:Array.isArray(s)?t[n]={arrayValue:{values:s.map(o=>re.toFirestoreFields({item:o}).item)}}:i==="object"&&(t[n]={mapValue:{fields:re.toFirestoreFields(s)}})}return t}static fromFirestoreFields(e={}){let t={};for(let n in e){let s=e[n],i=["stringValue","booleanValue","doubleValue","integerValue","timestampValue","mapValue","arrayValue","nullValue"].find(o=>o===Object.keys(s)[0]);if(i)switch(i){case"mapValue":t[n]=re.fromFirestoreFields(s.mapValue.fields||{});break;case"arrayValue":{let o=s.arrayValue.values;t[n]=o?o.map(u=>re.fromFirestoreFields(u)):[];break}case"nullValue":t[n]=null;break;default:t[n]=s[i]}else t[n]=re.fromFirestoreFields(s)}return t}static getSnapshot(e){let{fsCollection:t,fsId:n}=re.pathSplit(e);return Promise.resolve().then(async()=>ah(rs(re.firestore,t,n))).then(s=>s.exists()?re.fromFirestore(s.data()):null)}static setSnapshot(e,t,n){let s={method:"merge",...n},{fsCollection:i,fsId:o}=re.pathSplit(e),u=rs(re.firestore,i,o),c=re.toFirestore(t);return Promise.resolve().then(()=>s.method==="merge"?ch(u,c):uh(u,c)).then(()=>t)}mount(e){let t={initialState:null,retries:5,retryMinTime:250,...e},{fsCollection:n,fsId:s,entity:i}=re.pathSplit(this.path),o,u;return Ni(async()=>{await this.setHeartbeat(!1),this.docRef=rs(re.firestore,n,s);let c=await this.getFirestoreState();if(this.path.startsWith("projects::")&&c&&!Ao(c)&&c.users&&!c.type&&!c.name&&!c.created){this.debugError("Zombie state detected (Partial document). Forcing repair...");let f=await fetch(`${this.config.syncroRegistryUrl}/${this.path}?drop=1&force=1`);f.ok?(this.debug("Repair signal sent successfully. Reloading local state..."),c=await this.getFirestoreState()):console.error("[Syncro] Self-healing failed",f.statusText)}if(o=this.getReactive(c),!o.doc||!o.setState||!o.getState||!o.watch)throw new Error("Syncro.getReactive() requires a returned `doc`, `setState()`, `getState()` + `watch()`");if(o.throttle){let f={limit:2,interval:100,strict:!1,...typeof o.throttle=="object"&&o.throttle},p=o.setState;o.setState=Lh({limit:f.limit,interval:f.interval,onDelay:()=>this.debug("Throttling excessive Syncro.setState() writes")})(p)}this.value=u=o.doc,this.debug("Initial state",{doc:u});let l=h_(this.docRef,f=>{let p=re.fromFirestore(f.data());this.debug("Incoming snapshot",{snapshotData:p}),o.setState(p)});if(this._destroyActions.push(l),Ao(u))if(t.initialState)this.debug("Populate initial Syncro state (from provided initialState)"),await this.setFirestoreState(t.initialState,{method:"set"});else{this.debug(`Populate initial Syncro state (from "${i}" Syncro worker)`);let f=await fetch(`${this.config.syncroRegistryUrl}/${this.path}`);if(!f.ok)throw new Error(`Failed to check Syncro "${n}::${s}" status - ${f.statusText}`)}return o.watch(Nu(f=>{this.debug("Local change",{newState:f}),this.markDirty(),this.setFirestoreState(f,{method:"merge"})},this.throttle)),await this.setHeartbeat(!0,{immediate:!0}),this},{retries:t.retries,minTimeout:t.retryMinTime,randomize:!0,factor:3,onFailedAttempt:async c=>{this.debugError(`[Attempt ${c.attemptNumber}/${c.attemptNumber+c.retriesLeft-1}] to mount syncro`,c),await this.destroy()}})}async set(e,t,n){let s;if(typeof e=="string")s[e]=t;else if(typeof e=="object")[s,n]=[e,t];else throw new Error("Unknown call signature for set() - call with string+value or object");let i={delta:!0,flush:!0,forceFlush:!1,flushDestroy:!1,...n},o=!1;return i.delta?Object.entries(s).filter(([u,c])=>!Ms(this.value[u],c)).forEach(([u,c])=>{o=!0,this.value[u]=c}):(o=!0,Object.assign(this.value,s)),(i.forceFlush||o)&&i.flush&&await this.flush({destroy:i.flushDestroy}),this}setHeartbeat(e=!0,t){let n={immediate:!0,...t};if(clearTimeout(this._heartbeatTimer),e){let s=async()=>{await this.heartbeat(),e&&this.setHeartbeat(!0)};if(this._heartbeatTimer=setTimeout(s,this.config.heartbeatInterval),n.immediate)return this.heartbeat()}}async heartbeat(){this.debug("heartbeat!");try{let e=await fetch(`${this.config.syncroRegistryUrl}/${this.path}/heartbeat`,{method:"post",headers:{"Content-Type":"application/json"},body:JSON.stringify({session:re.session,...this.isDirty&&{dirty:!0}})});e.ok||console.warn(this.path,`Heartbeat failed - ${e.statusText}`,{response:e}),this.isDirty=!1}catch(e){console.warn(this.path,"Heartbeat fetch error",e)}}async setFirestoreState(e,t,n=0){let s={method:"merge",...t};if(!this.docRef)throw new Error("mount() must be called before setting Firestore state");let i=re.toFirestore(e);try{return s.method==="merge"?await ch(this.docRef,i):await uh(this.docRef,i)}catch(o){if(o instanceof et&&o.code==="not-found"){if(n<3)return console.warn("Firebase syncro document does not exist during document update, reinitializing..."),(await fetch(`${this.config.syncroRegistryUrl}/${this.path}?force=1`)).ok||console.error("Failed to reinitialize Syncro"),await this.setFirestoreState(e,t,n+1);console.warn("Max retries exceeded while trying to recover firestore syncro document, throwing error")}throw console.error(`Error during Firestore operation (${s.method}) on doc: ${this.docRef.path}`,o),o}}getFirestoreState(){if(!this.docRef)throw new Error("mount() must be called before getting Firestore state");return ah(this.docRef).then(e=>{var t;return re.fromFirestore((t=e.data())!=null?t:{})})}markDirty(){return this.isDirty=!0,this}flush(e){let t={destroy:!1,...e};return fetch(`${this.config.syncroRegistryUrl}/${this.path}/flush`+(t.destroy?"?destroy=1":"")).then(n=>n.ok?null:Promise.reject(n.statusText||"An error occurred"))}};se(re,"firebase"),se(re,"firestore"),se(re,"supabasey"),se(re,"session"),se(re,"SyncroEntities");var $t=re;var kw={circular:!1,clone:!0,modules:[{id:"~array",recursive:!0,test:r=>Array.isArray(r),serialize:r=>({_:"~array",...r}),deserialize:r=>{let e=Array.from({length:Object.keys(r).length-1});return Object.entries(r).filter(([t])=>t!=="_").forEach(([t,n])=>e[+t]=n),e}},{id:"~function",test:r=>typeof r=="function",serialize:(r,e)=>{throw console.warn("Marshal Warning: Stripping function from path",e.join(".")),new Error("Function serializing is forbidden")},deserialize:(r,e)=>{console.warn("Marshal Warning: Stripping function from path",e.join("."))}},...ru.settings.modules.filter(r=>r.id!="~function")]};var Li=class{init(){}constructor(e,t){}};var Fi=class extends Li{constructor(){super(...arguments);se(this,"syncros",{});se(this,"namespaces",{});se(this,"getCredentials");se(this,"requireProject");se(this,"debug");se(this,"getReactive")}async init(t){let n={firebaseApiKey:null,firebaseAuthDomain:null,firebaseProjectId:null,firebaseAppId:null,supabaseUrl:null,supabaseKey:null,...await this.getCredentials(),...t},s=Object.keys(n).filter(i=>i===null);if(s.length>0)throw new Error("Firebase plugin requires mandatory options: "+s.join(", "));$t.firebase=ec({apiKey:n.firebaseApiKey,authDomain:n.firebaseAuthDomain,projectId:n.firebaseProjectId,appId:n.firebaseAppId}),$t.firestore=rh($t.firebase),$t.supabasey=await vw.init({env:{SUPABASE_URL:n.supabaseUrl,SUPABASE_KEY:n.supabaseKey}})}_mountNamespace(t){let n;return Promise.resolve().then(()=>this.requireProject()).then(s=>{let i=t=="_PROJECT"?`projects::${s.id}`:`project_namespaces::${s.id}::${t}`;return n=this.syncros[t]=new $t(i,{debug:(...o)=>this.debug(`SYNCRO://${i}`,...o),getReactive:this.getReactive}),n.mount()}).then(()=>{this.namespaces[t]=n.value})}_unmountNamespace(t){let n=this.syncros[t];return delete this.namespaces[t],delete this.syncros[t],n?n.destroy():Promise.resolve()}};var Fh=class extends Fi{constructor(){super(...arguments);se(this,"Vue");se(this,"app");se(this,"project",null);se(this,"reactiveId",1001)}async init(t){let n={app:null,Vue:null,globalName:"$tera",...t};if(!n.Vue)throw new Error("Vue instance to use must be specified in init options as `Vue`");if(this.Vue=n.Vue,!n.app)throw new Error("Vue Root / App instance to use must be specified in init options as `app`");this.app=n.app,n.globalName&&(this.Vue.prototype[n.globalName]=this),await super.init(n),this.project=await this.mountNamespace("_PROJECT")}getReactive(t){let n=this.Vue.observable(t),s=`_teraFy_${this.reactiveId++}`;return this.app[s]=n,{doc:n,setState:i=>{Object.entries(i||{}).filter(([o])=>!Ms(n[o],i[o])).forEach(([o,u])=>n[o]=u)},getState:()=>ar(n),watch:i=>{this.app.$watch(s,i,{deep:!0})}}}};export{Fh as default};
64
+ `);let F=await M.signMessage(new TextEncoder().encode(T),"utf8");if(!F||!(F instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");x=F}}try{let{data:I,error:k}=await q(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:T,signature:Bt(x)},!((m=e.options)===null||m===void 0)&&m.captchaToken?{gotrue_meta_security:{captcha_token:(y=e.options)===null||y===void 0?void 0:y.captchaToken}}:null),xform:Ye});if(k)throw k;if(!I||!I.session||!I.user){let O=new Ut;return this._returnResult({data:{user:null,session:null},error:O})}return I.session&&(await this._saveSession(I.session),await this._notifyAllSubscribers("SIGNED_IN",I.session)),this._returnResult({data:Object.assign({},I),error:k})}catch(I){if(U(I))return this._returnResult({data:{user:null,session:null},error:I});throw I}}async _exchangeCodeForSession(e){let t=await _r(this.storage,`${this.storageKey}-code-verifier`),[n,s]=(t!=null?t:"").split("/");try{if(!n&&this.flowType==="pkce")throw new $a;let{data:i,error:o}=await q(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:Ye});if(await Ce(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!i||!i.session||!i.user){let u=new Ut;return this._returnResult({data:{user:null,session:null,redirectType:null},error:u})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:s!=null?s:null}),error:o})}catch(i){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),U(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{let{options:t,provider:n,token:s,access_token:i,nonce:o}=e,u=await q(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:s,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:t==null?void 0:t.captchaToken}},xform:Ye}),{data:c,error:l}=u;if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!c||!c.session||!c.user){let f=new Ut;return this._returnResult({data:{user:null,session:null},error:f})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:l})}catch(t){if(U(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOtp(e){var t,n,s,i,o;try{if("email"in e){let{email:u,options:c}=e,l=null,f=null;this.flowType==="pkce"&&([l,f]=await en(this.storage,this.storageKey));let{error:p}=await q(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:u,data:(t=c==null?void 0:c.data)!==null&&t!==void 0?t:{},create_user:(n=c==null?void 0:c.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},code_challenge:l,code_challenge_method:f},redirectTo:c==null?void 0:c.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:p})}if("phone"in e){let{phone:u,options:c}=e,{data:l,error:f}=await q(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:u,data:(s=c==null?void 0:c.data)!==null&&s!==void 0?s:{},create_user:(i=c==null?void 0:c.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},channel:(o=c==null?void 0:c.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:l==null?void 0:l.message_id},error:f})}throw new Jr("You must provide either an email or phone number.")}catch(u){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),U(u))return this._returnResult({data:{user:null,session:null},error:u});throw u}}async verifyOtp(e){var t,n;try{let s,i;"options"in e&&(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(n=e.options)===null||n===void 0?void 0:n.captchaToken);let{data:o,error:u}=await q(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:Ye});if(u)throw u;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,l=o.user;return c!=null&&c.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:l,session:c},error:null})}catch(s){if(U(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(e){var t,n,s,i,o;try{let u=null,c=null;this.flowType==="pkce"&&([u,c]=await en(this.storage,this.storageKey));let l=await q(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:(n=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&n!==void 0?n:void 0}),!((s=e==null?void 0:e.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:u,code_challenge_method:c}),headers:this.headers,xform:nw});return!((i=l.data)===null||i===void 0)&&i.url&&Ae()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(l.data.url),this._returnResult(l)}catch(u){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),U(u))return this._returnResult({data:null,error:u});throw u}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:n}=e;if(n)throw n;if(!t)throw new Oe;let{error:s}=await q(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:n,type:s,options:i}=e,{error:o}=await q(this.fetch,"POST",t,{headers:this.headers,body:{email:n,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in e){let{phone:n,type:s,options:i}=e,{data:o,error:u}=await q(this.fetch,"POST",t,{headers:this.headers,body:{phone:n,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:u})}throw new Jr("You must provide either an email or phone number and a type")}catch(t){if(U(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await n,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let n=t();for(this.pendingInLock.push((async()=>{try{await n}catch{}})()),await n;this.pendingInLock.length;){let s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await n}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{let 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,t=await _r(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let n=e.expires_at?e.expires_at*1e3-Date.now()<Ua:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){let o=await _r(this.userStorage,this.storageKey+"-user");o!=null&&o.user?e.user=o.user:e.user=Ha()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let o={value:this.suppressGetSessionWarning};e.user=tw(e.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let 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 q(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:bt}):await this._useSession(async t=>{var n,s,i;let{data:o,error:u}=t;if(u)throw u;return!(!((n=o.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Oe}:await q(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:bt})})}catch(t){if(U(t))return qa(t)&&(await this._removeSession(),await Ce(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=>{let{data:s,error:i}=n;if(i)throw i;if(!s.session)throw new Oe;let o=s.session,u=null,c=null;this.flowType==="pkce"&&e.email!=null&&([u,c]=await en(this.storage,this.storageKey));let{data:l,error:f}=await q(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t==null?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:u,code_challenge_method:c}),jwt:o.access_token,xform:bt});if(f)throw f;return o.user=l.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(n){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),U(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 Oe;let t=Date.now()/1e3,n=t,s=!0,i=null,{payload:o}=Ci(e.access_token);if(o.exp&&(n=o.exp,s=n<=t),s){let{data:u,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!u)return{data:{user:null,session:null},error:null};i=u}else{let{data:u,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});i={access_token:e.access_token,refresh_token:e.refresh_token,user:u.user,token_type:"bearer",expires_in:n-t,expires_at:n},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(t){if(U(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){let{data:o,error:u}=t;if(u)throw u;e=(n=o.session)!==null&&n!==void 0?n:void 0}if(!(e!=null&&e.refresh_token))throw new Oe;let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(t){if(U(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async _getSessionFromURL(e,t){try{if(!Ae())throw new Qr("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Qr(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(this.flowType==="pkce")throw new xi("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Qr("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new xi("No code detected.");let{data:O,error:D}=await this._exchangeCodeForSession(e.code);if(D)throw D;let M=new URL(window.location.href);return M.searchParams.delete("code"),window.history.replaceState(window.history.state,"",M.toString()),{data:{session:O.session,redirectType:null},error:null}}let{provider_token:n,provider_refresh_token:s,access_token:i,refresh_token:o,expires_in:u,expires_at:c,token_type:l}=e;if(!i||!u||!o||!l)throw new Qr("No session defined in URL");let f=Math.round(Date.now()/1e3),p=parseInt(u),m=f+p;c&&(m=parseInt(c));let y=m-f;y*1e3<=Hr&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${y}s, should have been closer to ${p}s`);let T=m-p;f-T>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",T,m,f):f-T<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",T,m,f);let{data:x,error:I}=await this._getUser(i);if(I)throw I;let k={provider_token:n,provider_refresh_token:s,access_token:i,expires_in:p,expires_at:m,refresh_token:o,token_type:l,user:x.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:k,redirectType:e.type},error:null})}catch(n){if(U(n))return this._returnResult({data:{session:null,redirectType:null},error:n});throw n}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){let t=await _r(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;let{data:s,error:i}=t;if(i&&!qa(i))return this._returnResult({error:i});let o=(n=s.session)===null||n===void 0?void 0:n.access_token;if(o){let{error:u}=await this.admin.signOut(o,e);if(u&&!(U_(u)&&(u.status===404||u.status===401||u.status===403)||qa(u)))return this._returnResult({error:u})}return e!=="others"&&(await this._removeSession(),await Ce(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let t=W_(),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,s;try{let{data:{session:i},error:o}=t;if(o)throw o;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i)}})}async resetPasswordForEmail(e,t={}){let n=null,s=null;this.flowType==="pkce"&&([n,s]=await en(this.storage,this.storageKey,!0));try{return await q(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(i){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),U(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{let{data:t,error:n}=await this.getUser();if(n)throw n;return this._returnResult({data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(t){if(U(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{let{data:n,error:s}=await this._useSession(async i=>{var o,u,c,l,f;let{data:p,error:m}=i;if(m)throw m;let y=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(u=e.options)===null||u===void 0?void 0:u.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await q(this.fetch,"GET",y,{headers:this.headers,jwt:(f=(l=p.session)===null||l===void 0?void 0:l.access_token)!==null&&f!==void 0?f:void 0})});if(s)throw s;return Ae()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(n==null?void 0:n.url),this._returnResult({data:{provider:e.provider,url:n==null?void 0:n.url},error:null})}catch(n){if(U(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{let{error:s,data:{session:i}}=t;if(s)throw s;let{options:o,provider:u,token:c,access_token:l,nonce:f}=e,p=await q(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(n=i==null?void 0:i.access_token)!==null&&n!==void 0?n:void 0,body:{provider:u,id_token:c,access_token:l,nonce:f,link_identity:!0,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:Ye}),{data:m,error:y}=p;return y?this._returnResult({data:{user:null,session:null},error:y}):!m||!m.session||!m.user?this._returnResult({data:{user:null,session:null},error:new Ut}):(m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("USER_UPDATED",m.session)),this._returnResult({data:m,error:y}))}catch(s){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),U(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var n,s;let{data:i,error:o}=t;if(o)throw o;return await q(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&s!==void 0?s:void 0})})}catch(t){if(U(t))return this._returnResult({data:null,error:t});throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let n=Date.now();return await Y_(async s=>(s>0&&await Q_(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await q(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Ye})),(s,i)=>{let o=200*Math.pow(2,s);return i&&za(i)&&Date.now()+o-n<Hr})}catch(n){if(this._debug(t,"error",n),U(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let 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),Ae()&&!t.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e,t;let n="#_recoverAndRefresh()";this._debug(n,"begin");try{let s=await _r(this.storage,this.storageKey);if(s&&this.userStorage){let o=await _r(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:s.user},await Zr(this.userStorage,this.storageKey+"-user",o)),s.user=(e=o==null?void 0:o.user)!==null&&e!==void 0?e:Ha()}else if(s&&!s.user&&!s.user){let o=await _r(this.storage,this.storageKey+"-user");o&&(o!=null&&o.user)?(s.user=o.user,await Ce(this.storage,this.storageKey+"-user"),await Zr(this.storage,this.storageKey,s)):s.user=Ha()}if(this._debug(n,"session from storage",s),!this._isValidSession(s)){this._debug(n,"session is not valid"),s!==null&&await this._removeSession();return}let i=((t=s.expires_at)!==null&&t!==void 0?t:1/0)*1e3-Date.now()<Ua;if(this._debug(n,`session has${i?"":" not"} expired with margin of ${Ua}s`),i){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),za(o)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(s.user&&s.user.__isUserNotAvailableProxy===!0)try{let{data:o,error:u}=await this._getUser(s.access_token);!u&&(o!=null&&o.user)?(s.user=o.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):this._debug(n,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(n,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(n,"error",s),console.error(s);return}finally{this._debug(n,"end")}}async _callRefreshToken(e){var t,n;if(!e)throw new Oe;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new Pi;let{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new Oe;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);let u={data:i.session,error:null};return this.refreshingDeferred.resolve(u),u}catch(i){if(this._debug(s,"error",i),U(i)){let o={data:null,error:i};return za(i)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(n=this.refreshingDeferred)===null||n===void 0||n.reject(i),i}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,n=!0){let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:t});let i=[],o=Array.from(this.stateChangeEmitters.values()).map(async u=>{try{await u.callback(e,t)}catch(c){i.push(c)}});if(await Promise.all(o),i.length>0){for(let u=0;u<i.length;u+=1)console.error(i[u]);throw i[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Ce(this.storage,`${this.storageKey}-code-verifier`);let t=Object.assign({},e),n=t.user&&t.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!n&&t.user&&await Zr(this.userStorage,this.storageKey+"-user",{user:t.user});let s=Object.assign({},t);delete s.user;let i=Ih(s);await Zr(this.storage,this.storageKey,i)}else{let s=Ih(t);await Zr(this.storage,this.storageKey,s)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Ce(this.storage,this.storageKey),await Ce(this.storage,this.storageKey+"-code-verifier"),await Ce(this.storage,this.storageKey+"-user"),this.userStorage&&await Ce(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Ae()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),Hr);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno!="undefined"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno!="undefined"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let 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{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:n}}=t;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((n.expires_at*1e3-e)/Hr);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${Hr}ms, refresh threshold is ${ja} ticks`),s<=ja&&await this._callRefreshToken(n.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof ki)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Ae()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,n){let s=[`provider=${encodeURIComponent(t)}`];if(n!=null&&n.redirectTo&&s.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n!=null&&n.scopes&&s.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){let[i,o]=await en(this.storage,this.storageKey),u=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});s.push(u.toString())}if(n!=null&&n.queryParams){let i=new URLSearchParams(n.queryParams);s.push(i.toString())}return n!=null&&n.skipBrowserRedirect&&s.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var n;let{data:s,error:i}=t;return i?this._returnResult({data:null,error:i}):await q(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(n=s==null?void 0:s.session)===null||n===void 0?void 0:n.access_token})})}catch(t){if(U(t))return this._returnResult({data:null,error:t});throw t}}async _enroll(e){try{return await this._useSession(async t=>{var n,s;let{data:i,error:o}=t;if(o)return this._returnResult({data:null,error:o});let u=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:l}=await q(this.fetch,"POST",`${this.url}/factors`,{body:u,headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token});return l?this._returnResult({data:null,error:l}):(e.factorType==="totp"&&c.type==="totp"&&(!((s=c==null?void 0:c.totp)===null||s===void 0)&&s.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(t){if(U(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;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?pw(e.webauthn.credential_response):mw(e.webauthn.credential_response)})}:{code:e.code}),{data:u,error:c}=await q(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(n=s==null?void 0:s.session)===null||n===void 0?void 0:n.access_token});return c?this._returnResult({data:null,error:c}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+u.expires_in},u)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",u),this._returnResult({data:u,error:c}))})}catch(t){if(U(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;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let o=await q(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=s==null?void 0:s.session)===null||n===void 0?void 0:n.access_token});if(o.error)return o;let{data:u}=o;if(u.type!=="webauthn")return{data:u,error:null};switch(u.webauthn.type){case"create":return{data:Object.assign(Object.assign({},u),{webauthn:Object.assign(Object.assign({},u.webauthn),{credential_options:Object.assign(Object.assign({},u.webauthn.credential_options),{publicKey:dw(u.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},u),{webauthn:Object.assign(Object.assign({},u.webauthn),{credential_options:Object.assign(Object.assign({},u.webauthn.credential_options),{publicKey:fw(u.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(t){if(U(t))return this._returnResult({data:null,error:t});throw t}})}async _challengeAndVerify(e){let{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;let{data:{user:t},error:n}=await this.getUser();if(n)return{data:null,error:n};let s={all:[],phone:[],totp:[],webauthn:[]};for(let i of(e=t==null?void 0:t.factors)!==null&&e!==void 0?e:[])s.all.push(i),i.status==="verified"&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,n,s,i;if(e)try{let{payload:y}=Ci(e),T=null;y.aal&&(T=y.aal);let x=T,{data:{user:I},error:k}=await this.getUser(e);if(k)return this._returnResult({data:null,error:k});((n=(t=I==null?void 0:I.factors)===null||t===void 0?void 0:t.filter(M=>M.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(x="aal2");let D=y.amr||[];return{data:{currentLevel:T,nextLevel:x,currentAuthenticationMethods:D},error:null}}catch(y){if(U(y))return this._returnResult({data:null,error:y});throw y}let{data:{session:o},error:u}=await this.getSession();if(u)return this._returnResult({data:null,error:u});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:c}=Ci(o.access_token),l=null;c.aal&&(l=c.aal);let f=l;((i=(s=o.user.factors)===null||s===void 0?void 0:s.filter(y=>y.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(f="aal2");let m=c.amr||[];return{data:{currentLevel:l,nextLevel:f,currentAuthenticationMethods:m},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:n},error:s}=t;return s?this._returnResult({data:null,error:s}):n?await q(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new Oe})})}catch(t){if(U(t))return this._returnResult({data:null,error:t});throw t}}async _approveAuthorization(e,t){try{return await this._useSession(async n=>{let{data:{session:s},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new Oe});let o=await q(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:u=>({data:u,error:null})});return o.data&&o.data.redirect_url&&Ae()&&!(t!=null&&t.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(n){if(U(n))return this._returnResult({data:null,error:n});throw n}}async _denyAuthorization(e,t){try{return await this._useSession(async n=>{let{data:{session:s},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new Oe});let o=await q(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:u=>({data:u,error:null})});return o.data&&o.data.redirect_url&&Ae()&&!(t!=null&&t.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(n){if(U(n))return this._returnResult({data:null,error:n});throw n}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:n}=e;return n?this._returnResult({data:null,error:n}):t?await q(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new Oe})})}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:n},error:s}=t;return s?this._returnResult({data:null,error:s}):n?(await q(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 Oe})})}catch(t){if(U(t))return this._returnResult({data:null,error:t});throw t}}async fetchJwk(e,t={keys:[]}){let n=t.keys.find(u=>u.kid===e);if(n)return n;let s=Date.now();if(n=this.jwks.keys.find(u=>u.kid===e),n&&this.jwks_cached_at+j_>s)return n;let{data:i,error:o}=await q(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,n=i.keys.find(u=>u.kid===e),!n)?null:n}async getClaims(e,t={}){try{let n=e;if(!n){let{data:y,error:T}=await this.getSession();if(T||!y.session)return this._returnResult({data:null,error:T});n=y.session.access_token}let{header:s,payload:i,signature:o,raw:{header:u,payload:c}}=Ci(n);t!=null&&t.allowExpired||Z_(i.exp);let l=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,t!=null&&t.keys?{keys:t.keys}:t==null?void 0:t.jwks);if(!l){let{error:y}=await this.getUser(n);if(y)throw y;return{data:{claims:i,header:s,signature:o},error:null}}let f=ew(s.alg),p=await crypto.subtle.importKey("jwk",l,f,!0,["verify"]);if(!await crypto.subtle.verify(f,p,o,K_(`${u}.${c}`)))throw new Yr("Invalid JWT signature");return{data:{claims:i,header:s,signature:o},error:null}}catch(n){if(U(n))return this._returnResult({data:null,error:n});throw n}}};Za.nextInstanceID={};var Oh=Za;var uC=Oh,Dh=uC;var cC="2.99.1",Oi="";typeof Deno!="undefined"?Oi="deno":typeof document!="undefined"?Oi="web":typeof navigator!="undefined"&&navigator.product==="ReactNative"?Oi="react-native":Oi="node";var lC={"X-Client-Info":`supabase-js-${Oi}/${cC}`},hC={headers:lC},dC={schema:"public"},fC={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},pC={};function Di(r){"@babel/helpers - typeof";return Di=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Di(r)}function mC(r,e){if(Di(r)!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var n=t.call(r,e||"default");if(Di(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function gC(r){var e=mC(r,"string");return Di(e)=="symbol"?e:e+""}function yC(r,e,t){return(e=gC(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function yw(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(r,s).enumerable})),t.push.apply(t,n)}return t}function me(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?yw(Object(t),!0).forEach(function(n){yC(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):yw(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var _C=r=>r?(...e)=>r(...e):(...e)=>fetch(...e),wC=()=>Headers,vC=(r,e,t)=>{let n=_C(t),s=wC();return async(i,o)=>{var u;let c=(u=await e())!==null&&u!==void 0?u:r,l=new s(o==null?void 0:o.headers);return l.has("apikey")||l.set("apikey",r),l.has("Authorization")||l.set("Authorization",`Bearer ${c}`),n(i,me(me({},o),{},{headers:l}))}};function bC(r){return r.endsWith("/")?r:r+"/"}function EC(r,e){var t,n;let{db:s,auth:i,realtime:o,global:u}=r,{db:c,auth:l,realtime:f,global:p}=e,m={db:me(me({},c),s),auth:me(me({},l),i),realtime:me(me({},f),o),storage:{},global:me(me(me({},p),u),{},{headers:me(me({},(t=p==null?void 0:p.headers)!==null&&t!==void 0?t:{}),(n=u==null?void 0:u.headers)!==null&&n!==void 0?n:{})}),accessToken:async()=>""};return r.accessToken?m.accessToken=r.accessToken:delete m.accessToken,m}function TC(r){let e=r==null?void 0:r.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(bC(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var IC=class extends Dh{constructor(r){super(r)}},AC=class{constructor(r,e,t){var n,s;this.supabaseUrl=r,this.supabaseKey=e;let i=TC(r);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);let o=`sb-${i.hostname.split(".")[0]}-auth-token`,u={db:dC,realtime:pC,auth:me(me({},fC),{},{storageKey:o}),global:hC},c=EC(t!=null?t:{},u);if(this.storageKey=(n=c.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(s=c.global.headers)!==null&&s!==void 0?s:{},c.accessToken)this.accessToken=c.accessToken,this.auth=new Proxy({},{get:(f,p)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(p)} is not possible`)}});else{var l;this.auth=this._initSupabaseAuthClient((l=c.auth)!==null&&l!==void 0?l:{},this.headers,c.global.fetch)}this.fetch=vC(e,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(me({headers:this.headers,accessToken:this._getAccessToken.bind(this)},c.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(f=>this.realtime.setAuth(f)).catch(f=>console.warn("Failed to set initial Realtime auth token:",f)),this.rest=new w_(new URL("rest/v1",i).href,{headers:this.headers,schema:c.db.schema,fetch:this.fetch,timeout:c.db.timeout,urlLengthLimit:c.db.urlLengthLimit}),this.storage=new N_(this.storageUrl.href,this.headers,this.fetch,t==null?void 0:t.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new gi(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(r){return this.rest.from(r)}schema(r){return this.rest.schema(r)}rpc(r,e={},t={head:!1,get:!1,count:void 0}){return this.rest.rpc(r,e,t)}channel(r,e={config:{}}){return this.realtime.channel(r,e)}getChannels(){return this.realtime.getChannels()}removeChannel(r){return this.realtime.removeChannel(r)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var r=this,e,t;if(r.accessToken)return await r.accessToken();let{data:n}=await r.auth.getSession();return(e=(t=n.session)===null||t===void 0?void 0:t.access_token)!==null&&e!==void 0?e:r.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:r,persistSession:e,detectSessionInUrl:t,storage:n,userStorage:s,storageKey:i,flowType:o,lock:u,debug:c,throwOnError:l},f,p){let m={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new IC({url:this.authUrl.href,headers:me(me({},m),f),storageKey:i,autoRefreshToken:r,persistSession:e,detectSessionInUrl:t,storage:n,userStorage:s,flowType:o,lock:u,debug:c,throwOnError:l,fetch:p,hasCustomAuthorizationHeader:Object.keys(this.headers).some(y=>y.toLowerCase()==="authorization")})}_initRealtimeClient(r){return new ds(this.realtimeUrl.href,me(me({},r),{},{params:me(me({},{apikey:this.supabaseKey}),r==null?void 0:r.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((r,e)=>{this._handleTokenChanged(r,"CLIENT",e==null?void 0:e.access_token)})}_handleTokenChanged(r,e,t){(r==="TOKEN_REFRESHED"||r==="SIGNED_IN")&&this.changedAccessToken!==t?(this.changedAccessToken=t,this.realtime.setAuth(t)):r==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}},_w=(r,e,t)=>new AC(r,e,t);function SC(){if(typeof window!="undefined")return!1;let r=globalThis.process;if(!r)return!1;let e=r.version;if(e==null)return!1;let t=e.match(/^v(\d+)\./);return t?parseInt(t[1],10)<=18:!1}SC()&&console.warn("\u26A0\uFE0F Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");var xC=Object.prototype.toString,RC=r=>xC.call(r)==="[object Error]",PC=new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function Nh(r){if(!(r&&RC(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"?n===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")||t==="Failed to fetch"||t.startsWith("Failed to fetch (")&&t.endsWith(")")?!0:PC.has(t)}function CC(r){if(typeof r=="number"){if(r<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function eu(r,e,{min:t=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${r}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${r}\` to be a finite number.`);if(e<t)throw new TypeError(`Expected \`${r}\` to be \u2265 ${t}.`)}}var Vh=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function kC(r,e){let t=Math.max(1,r+1),n=e.randomize?Math.random()+1:1,s=Math.round(n*e.minTimeout*e.factor**(t-1));return s=Math.min(s,e.maxTimeout),s}function ww(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function OC({error:r,attemptNumber:e,retriesConsumed:t,startTime:n,options:s}){var y,T,x,I,k;let i=r instanceof Error?r:new TypeError(`Non-error was thrown: "${r}". You should only throw errors.`);if(i instanceof Vh)throw i.originalError;let o=Number.isFinite(s.retries)?Math.max(0,s.retries-t):s.retries,u=(y=s.maxRetryTime)!=null?y:Number.POSITIVE_INFINITY,c=Object.freeze({error:i,attemptNumber:e,retriesLeft:o,retriesConsumed:t});if(await s.onFailedAttempt(c),ww(n,u)<=0)throw i;let l=await s.shouldConsumeRetry(c),f=ww(n,u);if(f<=0||o<=0)throw i;if(i instanceof TypeError&&!Nh(i)){if(l)throw i;return(T=s.signal)==null||T.throwIfAborted(),!1}if(!await s.shouldRetry(c))throw i;if(!l)return(x=s.signal)==null||x.throwIfAborted(),!1;let p=kC(t,s),m=Math.min(p,f);return(I=s.signal)==null||I.throwIfAborted(),m>0&&await new Promise((O,D)=>{var F,w;let M=()=>{var _;clearTimeout(B),(_=s.signal)==null||_.removeEventListener("abort",M),D(s.signal.reason)},B=setTimeout(()=>{var _;(_=s.signal)==null||_.removeEventListener("abort",M),O()},m);s.unref&&((F=B.unref)==null||F.call(B)),(w=s.signal)==null||w.addEventListener("abort",M,{once:!0})}),(k=s.signal)==null||k.throwIfAborted(),!0}async function Ni(r,e={}){var i,o,u,c,l,f,p,m,y,T,x,I;if(e={...e},CC(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");(i=e.retries)!=null||(e.retries=10),(o=e.factor)!=null||(e.factor=2),(u=e.minTimeout)!=null||(e.minTimeout=1e3),(c=e.maxTimeout)!=null||(e.maxTimeout=Number.POSITIVE_INFINITY),(l=e.maxRetryTime)!=null||(e.maxRetryTime=Number.POSITIVE_INFINITY),(f=e.randomize)!=null||(e.randomize=!1),(p=e.onFailedAttempt)!=null||(e.onFailedAttempt=()=>{}),(m=e.shouldRetry)!=null||(e.shouldRetry=()=>!0),(y=e.shouldConsumeRetry)!=null||(e.shouldConsumeRetry=()=>!0),eu("factor",e.factor,{min:0,allowInfinity:!1}),eu("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),eu("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),eu("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),(T=e.signal)==null||T.throwIfAborted();let t=0,n=0,s=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){t++;try{(x=e.signal)==null||x.throwIfAborted();let k=await r(t);return(I=e.signal)==null||I.throwIfAborted(),k}catch(k){await OC({error:k,attemptNumber:t,retriesConsumed:n,startTime:s,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var DC=function(e,t){if(typeof e!="function")throw new Error("First argument to supabasey() must be a callback function");let n={session:null,retries:3,retry:{minTimeout:100,factor:2,randomize:!0,onFailedAttempt:i=>console.info(`[Attempt ${i.attemptNumber}/${i.attemptNumber+i.retriesLeft-1}] failed to run Supabase query`),shouldRetry:i=>(console.log("QUERY SHOULD-RETRY",i),!0)},...t},s=n.session?typeof n.session=="string"?Se.sessions[n.session]:typeof n.session=="object"?n.session:(()=>{throw new Error(`Unknown session type for supabasey(cb, {session}) - expected Object|String got ${typeof n.session}`)})():(()=>{throw new Error("supabasey(cb, {session}) cannot be empty - specify a session or use bindSession() first")})();return Promise.resolve().then(()=>Ni(()=>e.call(s,s),{...n.retries&&{retries:n.retries},...t.retry})).then(i=>{if(i!=null&&i.error)Se.throw(i.error);else if(i.data)return i.data}).catch(i=>{throw console.log("Supabasey error:",i),i})},Se=DC;Se.bindSession=function(e){if(typeof e=="string"&&!Se.sessions[e])throw new Error(`Unable to bind to non-existant session "${e}"`);let t=(n,s)=>Se(n,{session:e,...s});return t.rpc=(n,s,i)=>Se.rpc(n,s,{session:e,...i}),t};Se.init=function(e){let t={env:{},init:!0,login:!1,session:"auto",...e},n=t.env,s=t.session=="auto"&&n.SUPABASE_URL?n.SUPABASE_URL:t.session?t.session:(()=>{throw new Error("Sesison should be truthy if using @iebh/supabasey.middleware({session:String})")})(),i=Se.sessions[s];return Promise.resolve().then(()=>{if(!i)if(t.init){if(!n.SUPABASE_URL||!n.SUPABASE_KEY)throw new Error("Both env.SUPABASE_URL + env.SUPABASE_KEY should be specified to use @iebh/supabasey.middleware(), otherwise disable with {init:false}");i=Se.sessions[s]=_w(n.SUPABASE_URL,n.SUPABASE_KEY)}else throw new Error("No Supabase session for middleware to work with!")}).then(()=>{if(t.login){if(i.supabaseyIsLoggedIn)return;if(!n.SUPABASE_USER||!n.SUPABASE_PASS)throw new Error("User credentials missing when using @iebh/supabasey.middleware(), provide in env.SUPABASE_USER + ..._PASS");return Se(o=>o.auth.signInWithPassword({email:n.SUPABASE_USER,password:n.SUPABASE_PASS}),{session:i}).then(()=>i.supabaseyIsLoggedIn=!0)}else return}).then(()=>Se.bindSession(i))};Se.middleware=function(e){let t={env:{},injectEnv:!0,...e};return async(n,s,i,o)=>Se.init({...e,env:i}).then(u=>{t.injectEnv&&(i.supabasey=u)}).catch(u=>Se.throw(u))};Se.throw=function(r){throw typeof r=="string"?new Error(r):r instanceof Error?r:/JSON object requested, multiple \(or no\) rows returned$/.test(r.message)?(console.warn("Supabase query resulted in NOT-FOUND:",r.message),console.warn("Supabase raw error",r),new Error("NOT-FOUND")):(console.warn("Supabase query threw",r.message||r||"Unknown error"),new Error(`${(r==null?void 0:r.code)||"UnknownError"}: ${(r==null?void 0:r.message)||"Unknown Supabase error"}`))};Se.rpc=function(r,e,t){return Se(async n=>await n.rpc(r,e),t)};Se.sessions={};var vw=Se;function NC(r,e){return Object.fromEntries(Object.entries(r).sort(e||void 0).map(([t,n])=>[t,n]))}function tu(r,e){return Array.isArray(r)?r.map(t=>tu(t,e)):typeof r=="object"?r==null?null:Object.fromEntries(Object.entries(NC(r,e)).map(([t,n])=>[t,tu(n,e)])):r}var bw={id:"~date",test:r=>r instanceof Date,serialize:r=>({_:"~date",v:r.toISOString()}),deserialize:r=>new Date(r.v)};var Ew={id:"~function",test:r=>typeof r=="function",serialize:r=>({_:"~function",v:r.toString()}),deserialize:v=>eval(v.v.toString())};var Tw={id:"~infinity",test:r=>r===1/0||r===-1/0,serialize:r=>({_:"~infinity",v:r===1/0?1:0}),deserialize:r=>r.v==1?1/0:-1/0};var Iw={id:"~nan",test:r=>Number.isNaN(r),serialize:r=>({_:"~nan"}),deserialize:r=>NaN};var Aw={id:"~regexp",test:r=>r instanceof RegExp,serialize:r=>({_:"~regexp",v:r.source,f:r.flags}),deserialize:r=>new RegExp(r.v,r.f)};var Sw={id:"~set",test:r=>r instanceof Set,serialize:r=>({_:"~set",v:Array.from(r)}),deserialize:r=>new Set(r.v)};var xw={id:"~undefined",test:r=>r===void 0,serialize:r=>({_:"~undefined"}),deserialize:r=>{}};var ys={settings:{stringify:!0,destringify:!0,clone:!1,depth:0,modules:[bw,Ew,Tw,Iw,Aw,Sw,xw],circular:!0,symetric:!1},loadedModules:{},loadModules(r){return r.map(e=>{if(ee(e)){if(!e.id)throw new Error("Provided custom module does not expose an `id` property");return ys.loadedModules[e.id]=e}else throw new Error("Unknown module type")})},serialize(r,e){let t=Io(e,ys.settings),n=ys.loadModules(t.modules),s=t.symetric?tu(r):t.clone?ar(r):r,i=new Map,o=(u,c)=>{let l=ee(u);if(l&&t.circular){let m=i.get(u);if(m)return ur(s,c,{_:"~circular",p:m.join(".")});i.set(u,c)}let f=n.find(m=>m.test(u,c)),p=(!t.depth||c.length<t.depth)&&l;if(f){let m=f.serialize(u,c);if(f.recursive&&p){let y=Ne(u);t.symetric&&y.sort(),ur(s,c,m),y.forEach(T=>o(u[T],c.concat(T)))}else c.length?ur(s,c,m):s=m}else if(p){let m=Ne(u);t.symetric&&m.sort(),m.forEach(y=>o(u[y],c.concat(y)))}};return o(s,[]),t.stringify?JSON.stringify(s):s},deserialize(r,e){let t=Io(e,ys.settings),n=ys.loadModules(t.modules),s=Du(n,"id"),i=t.destringify?JSON.parse(r):t.clone?ar(r):r,o=(u,c)=>{if(ee(u)&&u._&&typeof u._=="string"&&u._.startsWith("~")&&s[u._]){let l=s[u._].deserialize(u,c);c.length?s[u._].recursive&&ee(l)?(ur(i,c,l),Ne(l).forEach(f=>o(u[f],[...c,f]))):ur(i,c,l):i=l}else t.circular&&ee(u)&&u._&&u._=="~circular"?ur(i,c,Ls(i,u.p)):(!t.depth||c.length<t.depth)&&ee(u)&&Ne(u).forEach(l=>o(u[l],c.concat(l)))};return o(i,[]),i}},ru=ys;var Rw="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Pw=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=Rw[t[r]&63];return e};var Cw=new WeakMap,Vi=new WeakMap,VC=new FinalizationRegistry(({signalWeakRef:r,weakReference:e})=>{let t=r.deref();if(!t)return;let n=Vi.get(t);n&&(n.throttleds.delete(e),n.throttleds.size===0&&(t.removeEventListener("abort",n.listener),Vi.delete(t)))});function Lh({limit:r,interval:e,strict:t,signal:n,onDelay:s,weight:i}){if(!Number.isFinite(r))throw new TypeError("Expected `limit` to be a finite number");if(!Number.isFinite(e))throw new TypeError("Expected `interval` to be a finite number");if(r<0)throw new TypeError("Expected `limit` to be >= 0");if(e<0)throw new TypeError("Expected `interval` to be >= 0");if(i!==void 0&&typeof i!="function")throw new TypeError("Expected `weight` to be a function");if(i&&e===0)throw new TypeError("The `weight` option cannot be used with `interval` of 0");let o={queue:new Map,strictTicks:[],currentTick:0,activeWeight:0},u=Math.max(r,1),c=m=>{if(o.strictTicks.length===0||m.time>=o.strictTicks.at(-1).time)o.strictTicks.push(m);else{let y=o.strictTicks.findIndex(T=>T.time>m.time);o.strictTicks.splice(y,0,m)}};function l(m){let y=Date.now();return y-o.currentTick>e?(o.activeWeight=m,o.currentTick=y,0):(o.activeWeight+m<=r?o.activeWeight+=m:(o.currentTick+=e,o.activeWeight=m),o.currentTick-y)}function f(m){let y=Date.now();if(o.strictTicks.length>0&&y-o.strictTicks.at(-1).time>e&&(o.strictTicks.length=0),i){for(;o.strictTicks.length>0&&y-o.strictTicks[0].time>=e;)o.strictTicks.shift();let M=w=>{let _=0;for(let b of o.strictTicks)b.time<=w&&w-b.time<e&&(_+=b.weight);return _};if(M(y)+m<=r)return c({time:y,weight:m}),{delay:0};let B=y;for(;M(B)+m>r;){let w=o.strictTicks.find(_=>_.time<=B&&B-_.time<e);if(!w)break;B=w.time+e}let F={time:B,weight:m};return c(F),{delay:Math.max(0,B-y),tickRecord:F}}if(o.strictTicks.length<u)return o.strictTicks.push({time:y,weight:m}),{delay:0};let T=o.strictTicks[0].time,x=o.strictTicks.at(-1).time,I=T+e,k=e>0?Math.ceil(e/u):0,O=I<=x?x+k:I;o.strictTicks.shift();let D={time:O,weight:m};return o.strictTicks.push(D),{delay:Math.max(0,O-y),tickRecord:D}}let p=t?f:l;return m=>{let y=function(...T){if(!y.isEnabled)return(async()=>m.apply(this,T))();let x;return new Promise((I,k)=>{let O=1;if(i){try{O=i(...T)}catch(w){k(w);return}if(!Number.isFinite(O)||O<0){k(new TypeError("Expected `weight` to be a finite non-negative number"));return}if(O>r){k(new TypeError(`Expected \`weight\` (${O}) to be <= \`limit\` (${r})`));return}}let D=p(O),M=t?D.delay:D,B=t?D.tickRecord:void 0,F=()=>{if(B){let w=Date.now();if(i&&B.time!==w){B.time=w;let _=o.strictTicks.indexOf(B);o.strictTicks.splice(_,1),c(B)}else B.time=w}try{I(m.apply(this,T))}catch(w){k(w)}o.queue.delete(x)};if(M>0){x=setTimeout(F,M),o.queue.set(x,k);try{s==null||s(...T)}catch{}}else F()})};if(n==null||n.throwIfAborted(),n){let T=Vi.get(n);T||(T={throttleds:new Set,listener:null},T.listener=()=>{for(let I of T.throttleds){let k=I.deref();if(!k)continue;let O=Cw.get(k);if(O){for(let D of O.queue.keys())clearTimeout(D),O.queue.get(D)(n.reason);O.queue.clear(),O.strictTicks.length=0,O.currentTick=0,O.activeWeight=0}}Vi.delete(n)},Vi.set(n,T),n.addEventListener("abort",T.listener,{once:!0}));let x=new WeakRef(y);T.throttleds.add(x),VC.register(y,{signalWeakRef:new WeakRef(n),weakReference:x})}return y.isEnabled=!0,Object.defineProperty(y,"queueSize",{get(){return o.queue.size}}),Cw.set(y,o),y}}var re=class re{constructor(e,t){se(this,"path");se(this,"docRef");se(this,"value");se(this,"throttle",250);se(this,"config",{heartbeatInterval:12e4,syncroRegistryUrl:"https://tera-tools.com/api/sync",context:{}});se(this,"isDirty",!1);se(this,"_destroyActions",[]);se(this,"_heartbeatTimer");this.path=e,Object.assign(this,{...t,config:{...this.config,...t==null?void 0:t.config}}),re.session||(re.session=`syncro_${Pw()}`)}debug(...e){}debugError(...e){console.warn(`[Syncro ${this.path}]`,...e)}destroy(){return this.debug("Destroy!"),Promise.resolve().then(()=>Promise.all(this._destroyActions.map(e=>e()))).then(()=>this._destroyActions=[])}getReactive(e){console.warn("Syncro.getReactive has not been subclassed, assuming a POJO response");let t={...e};return{doc:t,setState(n){Object.entries(n||{}).forEach(([s,i])=>t[s]=i)},getState(){return ar(t)},watch(n){}}}static pathSplit(e,t){var o;let n={allowAsterisk:!1,...t},i={...(o=new RegExp("^(?<entity>\\w+?)::(?<id>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:::(?<relation>[\\w\\-"+(n.allowAsterisk?"\\*":"")+"]+?))?$").exec(e))==null?void 0:o.groups};if(!i||!i.entity||!i.id)throw new Error(`Invalid session path syntax "${e}"`);if(re.SyncroEntities&&!(i.entity in re.SyncroEntities))throw new Error(`Unsupported entity "${e}" -> Entity="${i.entity}"`);return{entity:i.entity,id:i.id,relation:i.relation,fsCollection:i.entity,fsId:i.relation?`${i.id}::${i.relation}`:i.id}}static toFirestore(e={}){return ru.serialize(e,{...kw,stringify:!1})}static fromFirestore(e={}){return ru.deserialize(e,{...kw,destringify:!1})}static toFirestoreFields(e){let t={};for(let[n,s]of Object.entries(e)){let i=typeof s;i==="string"?t[n]={stringValue:s}:i==="number"?t[n]={doubleValue:s}:i==="boolean"?t[n]={booleanValue:s}:s===null?t[n]={nullValue:null}:Array.isArray(s)?t[n]={arrayValue:{values:s.map(o=>re.toFirestoreFields({item:o}).item)}}:i==="object"&&(t[n]={mapValue:{fields:re.toFirestoreFields(s)}})}return t}static fromFirestoreFields(e={}){let t={};for(let n in e){let s=e[n],i=["stringValue","booleanValue","doubleValue","integerValue","timestampValue","mapValue","arrayValue","nullValue"].find(o=>o===Object.keys(s)[0]);if(i)switch(i){case"mapValue":t[n]=re.fromFirestoreFields(s.mapValue.fields||{});break;case"arrayValue":{let o=s.arrayValue.values;t[n]=o?o.map(u=>re.fromFirestoreFields(u)):[];break}case"nullValue":t[n]=null;break;default:t[n]=s[i]}else t[n]=re.fromFirestoreFields(s)}return t}static getSnapshot(e){let{fsCollection:t,fsId:n}=re.pathSplit(e);return Promise.resolve().then(async()=>ah(rs(re.firestore,t,n))).then(s=>s.exists()?re.fromFirestore(s.data()):null)}static setSnapshot(e,t,n){let s={method:"merge",...n},{fsCollection:i,fsId:o}=re.pathSplit(e),u=rs(re.firestore,i,o),c=re.toFirestore(t);return Promise.resolve().then(()=>s.method==="merge"?ch(u,c):uh(u,c)).then(()=>t)}mount(e){let t={initialState:null,retries:5,retryMinTime:250,...e},{fsCollection:n,fsId:s,entity:i}=re.pathSplit(this.path),o,u;return Ni(async()=>{await this.setHeartbeat(!1),this.docRef=rs(re.firestore,n,s);let c=await this.getFirestoreState();if(this.path.startsWith("projects::")&&c&&!Ao(c)&&c.users&&!c.type&&!c.name&&!c.created){this.debugError("Zombie state detected (Partial document). Forcing repair...");let f=await fetch(`${this.config.syncroRegistryUrl}/${this.path}?drop=1&force=1`);f.ok?(this.debug("Repair signal sent successfully. Reloading local state..."),c=await this.getFirestoreState()):console.error("[Syncro] Self-healing failed",f.statusText)}if(o=this.getReactive(c),!o.doc||!o.setState||!o.getState||!o.watch)throw new Error("Syncro.getReactive() requires a returned `doc`, `setState()`, `getState()` + `watch()`");if(o.throttle){let f={limit:2,interval:100,strict:!1,...typeof o.throttle=="object"&&o.throttle},p=o.setState;o.setState=Lh({limit:f.limit,interval:f.interval,onDelay:()=>this.debug("Throttling excessive Syncro.setState() writes")})(p)}this.value=u=o.doc,this.debug("Initial state",{doc:u});let l=h_(this.docRef,f=>{let p=re.fromFirestore(f.data());this.debug("Incoming snapshot",{snapshotData:p}),o.setState(p)});if(this._destroyActions.push(l),Ao(u))if(t.initialState)this.debug("Populate initial Syncro state (from provided initialState)"),await this.setFirestoreState(t.initialState,{method:"set"});else{this.debug(`Populate initial Syncro state (from "${i}" Syncro worker)`);let f=await fetch(`${this.config.syncroRegistryUrl}/${this.path}`);if(!f.ok)throw new Error(`Failed to check Syncro "${n}::${s}" status - ${f.statusText}`)}return o.watch(Nu(f=>{this.debug("Local change",{newState:f}),this.markDirty(),this.setFirestoreState(f,{method:"merge"})},this.throttle)),await this.setHeartbeat(!0,{immediate:!0}),this},{retries:t.retries,minTimeout:t.retryMinTime,randomize:!0,factor:3,onFailedAttempt:async c=>{this.debugError(`[Attempt ${c.attemptNumber}/${c.attemptNumber+c.retriesLeft-1}] to mount syncro`,c),await this.destroy()}})}async set(e,t,n){let s;if(typeof e=="string")s[e]=t;else if(typeof e=="object")[s,n]=[e,t];else throw new Error("Unknown call signature for set() - call with string+value or object");let i={delta:!0,flush:!0,forceFlush:!1,flushDestroy:!1,...n},o=!1;return i.delta?Object.entries(s).filter(([u,c])=>!Ms(this.value[u],c)).forEach(([u,c])=>{o=!0,this.value[u]=c}):(o=!0,Object.assign(this.value,s)),(i.forceFlush||o)&&i.flush&&await this.flush({destroy:i.flushDestroy}),this}setHeartbeat(e=!0,t){let n={immediate:!0,...t};if(clearTimeout(this._heartbeatTimer),e){let s=async()=>{await this.heartbeat(),e&&this.setHeartbeat(!0)};if(this._heartbeatTimer=setTimeout(s,this.config.heartbeatInterval),n.immediate)return this.heartbeat()}}async heartbeat(){this.debug("heartbeat!");try{let e=await fetch(`${this.config.syncroRegistryUrl}/${this.path}/heartbeat`,{method:"post",headers:{"Content-Type":"application/json"},body:JSON.stringify({session:re.session,...this.isDirty&&{dirty:!0}})});e.ok||console.warn(this.path,`Heartbeat failed - ${e.statusText}`,{response:e}),this.isDirty=!1}catch(e){console.warn(this.path,"Heartbeat fetch error",e)}}async setFirestoreState(e,t,n=0){let s={method:"merge",...t};if(!this.docRef)throw new Error("mount() must be called before setting Firestore state");let i=re.toFirestore(e);try{return s.method==="merge"?await ch(this.docRef,i):await uh(this.docRef,i)}catch(o){if(o instanceof et&&o.code==="not-found"){if(n<3)return console.warn("Firebase syncro document does not exist during document update, reinitializing..."),(await fetch(`${this.config.syncroRegistryUrl}/${this.path}?force=1`)).ok||console.error("Failed to reinitialize Syncro"),await this.setFirestoreState(e,t,n+1);console.warn("Max retries exceeded while trying to recover firestore syncro document, throwing error")}throw console.error(`Error during Firestore operation (${s.method}) on doc: ${this.docRef.path}`,o),o}}getFirestoreState(){if(!this.docRef)throw new Error("mount() must be called before getting Firestore state");return ah(this.docRef).then(e=>{var t;return re.fromFirestore((t=e.data())!=null?t:{})})}markDirty(){return this.isDirty=!0,this}flush(e){let t={destroy:!1,...e};return fetch(`${this.config.syncroRegistryUrl}/${this.path}/flush`+(t.destroy?"?destroy=1":"")).then(n=>n.ok?null:Promise.reject(n.statusText||"An error occurred"))}};se(re,"firebase"),se(re,"firestore"),se(re,"supabasey"),se(re,"db"),se(re,"session"),se(re,"SyncroEntities");var $t=re;var kw={circular:!1,clone:!0,modules:[{id:"~array",recursive:!0,test:r=>Array.isArray(r),serialize:r=>({_:"~array",...r}),deserialize:r=>{let e=Array.from({length:Object.keys(r).length-1});return Object.entries(r).filter(([t])=>t!=="_").forEach(([t,n])=>e[+t]=n),e}},{id:"~function",test:r=>typeof r=="function",serialize:(r,e)=>{throw console.warn("Marshal Warning: Stripping function from path",e.join(".")),new Error("Function serializing is forbidden")},deserialize:(r,e)=>{console.warn("Marshal Warning: Stripping function from path",e.join("."))}},...ru.settings.modules.filter(r=>r.id!="~function")]};var Li=class{init(){}constructor(e,t){}};var Fi=class extends Li{constructor(){super(...arguments);se(this,"syncros",{});se(this,"namespaces",{});se(this,"getCredentials");se(this,"requireProject");se(this,"debug");se(this,"getReactive")}async init(t){let n={firebaseApiKey:null,firebaseAuthDomain:null,firebaseProjectId:null,firebaseAppId:null,supabaseUrl:null,supabaseKey:null,...await this.getCredentials(),...t},s=Object.keys(n).filter(i=>i===null);if(s.length>0)throw new Error("Firebase plugin requires mandatory options: "+s.join(", "));$t.firebase=ec({apiKey:n.firebaseApiKey,authDomain:n.firebaseAuthDomain,projectId:n.firebaseProjectId,appId:n.firebaseAppId}),$t.firestore=rh($t.firebase),$t.supabasey=await vw.init({env:{SUPABASE_URL:n.supabaseUrl,SUPABASE_KEY:n.supabaseKey}})}_mountNamespace(t){let n;return Promise.resolve().then(()=>this.requireProject()).then(s=>{let i=t=="_PROJECT"?`projects::${s.id}`:`project_namespaces::${s.id}::${t}`;return n=this.syncros[t]=new $t(i,{debug:(...o)=>this.debug(`SYNCRO://${i}`,...o),getReactive:this.getReactive}),n.mount()}).then(()=>{this.namespaces[t]=n.value})}_unmountNamespace(t){let n=this.syncros[t];return delete this.namespaces[t],delete this.syncros[t],n?n.destroy():Promise.resolve()}};var Fh=class extends Fi{constructor(){super(...arguments);se(this,"Vue");se(this,"app");se(this,"project",null);se(this,"reactiveId",1001)}async init(t){let n={app:null,Vue:null,globalName:"$tera",...t};if(!n.Vue)throw new Error("Vue instance to use must be specified in init options as `Vue`");if(this.Vue=n.Vue,!n.app)throw new Error("Vue Root / App instance to use must be specified in init options as `app`");this.app=n.app,n.globalName&&(this.Vue.prototype[n.globalName]=this),await super.init(n),this.project=await this.mountNamespace("_PROJECT")}getReactive(t){let n=this.Vue.observable(t),s=`_teraFy_${this.reactiveId++}`;return this.app[s]=n,{doc:n,setState:i=>{Object.entries(i||{}).filter(([o])=>!Ms(n[o],i[o])).forEach(([o,u])=>n[o]=u)},getState:()=>ar(n),watch:i=>{this.app.$watch(s,i,{deep:!0})}}}};export{Fh as default};
65
65
  /*! Bundled license information:
66
66
 
67
67
  lodash-es/lodash.js: