@iebh/tera-fy 2.3.2 → 2.3.4

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.
@@ -75,7 +75,7 @@ Request ID: ${c}`),h){let O=`
75
75
  Resources:`;for(let D of h){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+=`
76
76
  - ${D}`}k+=O}return`${I}
77
77
  ${k}`}var ue=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}},Qr=class extends ue{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}};function nv({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 ue({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 ue({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 ue({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 ue({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 ue({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:r});if(r.name==="NotAllowedError")return new ue({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 ue({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:r}):new ue({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 ue({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new ue({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 ue({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 ue({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 ue({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r})}function sv({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 ue({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else{if(r.name==="NotAllowedError")return new ue({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 ue({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new ue({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="UnknownError")return new ue({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 ue({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}}},aC=new kh;function ov(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=Vr(r,["challenge","user","excludeCredentials"]),i=mr(e).buffer,o=Object.assign(Object.assign({},t),{id:mr(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 h=n[c];u.excludeCredentials[c]=Object.assign(Object.assign({},h),{id:mr(h.id).buffer,type:h.type||"public-key",transports:h.transports})}}return u}function av(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=Vr(r,["challenge","allowCredentials"]),s=mr(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:mr(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return i}function uv(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:Lt(new Uint8Array(r.response.attestationObject)),clientDataJSON:Lt(new Uint8Array(r.response.clientDataJSON))},type:"public-key",clientExtensionResults:r.getClientExtensionResults(),authenticatorAttachment:(e=t.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function cv(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:Lt(new Uint8Array(s.authenticatorData)),clientDataJSON:Lt(new Uint8Array(s.clientDataJSON)),signature:Lt(new Uint8Array(s.signature)),userHandle:s.userHandle?Lt(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 iv(){var r,e;return!!(be()&&"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 uC(r){try{let e=await navigator.credentials.create(r);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Qr("Browser returned unexpected credential type",e)}:{data:null,error:new Qr("Empty credential response",e)}}catch(e){return{data:null,error:nv({error:e,options:r})}}}async function cC(r){try{let e=await navigator.credentials.get(r);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Qr("Browser returned unexpected credential type",e)}:{data:null,error:new Qr("Empty credential response",e)}}catch(e){return{data:null,error:sv({error:e,options:r})}}}var lC={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},hC={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function qa(...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]=qa(u,o):n[i]=qa(o)}else n[i]=o}return n}function dC(r,e){return qa(lC,r,e||{})}function fC(r,e){return qa(hC,r,e||{})}var za=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 h=s!=null?s:aC.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=dC(u.webauthn.credential_options.publicKey,i==null?void 0:i.create),{data:p,error:m}=await uC({publicKey:f,signal:h});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=fC(u.webauthn.credential_options.publicKey,i==null?void 0:i.request),{data:p,error:m}=await cC(Object.assign(Object.assign({},u.webauthn.credential_options),{publicKey:f,signal:h}));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 He("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 pr("rpId is required for WebAuthn authentication")};try{if(!iv())return{data:null,error:new He("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 He("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 pr("rpId is required for WebAuthn registration")};try{if(!iv())return{data:null,error:new He("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:h}=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:h}}catch(o){return U(o)?{data:null,error:o}:{data:null,error:new He("Unexpected error in register",o)}}}};Z_();var pC={url:P_,storageKey:C_,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:k_,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4,skipAutoInitialize:!1};async function lv(r,e,t){return await t()}var as={},Ka=class r{get jwks(){var e,t;return(t=(e=as[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){as[this.storageKey]=Object.assign(Object.assign({},as[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=as[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){as[this.storageKey]=Object.assign(Object.assign({},as[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({},pC),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&&be()){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 Wr({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=Ua(i.fetch),this.lock=i.lock||lv,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&&be()&&(!((n=globalThis==null?void 0:globalThis.navigator)===null||n===void 0)&&n.locks)?this.lock=Rh:this.lock=lv,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 za(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:Ma()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=xh(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=xh(this.memoryStorage)),be()&&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} (${ka}) ${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(be()&&(t=$_(window.location.href),this._isImplicitGrantCallback(t)?n="implicit":await this._isPKCECallback(t)&&(n="pkce")),be()&&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),V_(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 He("Unexpected error during initialization",t)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,n,s;try{let i=await $(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:Qe}),{data:o,error:u}=i;if(u||!o)return this._returnResult({data:{user:null,session:null},error:u});let c=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:h,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 zr(this.storage,this.storageKey)),i=await $(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:Qe})}else if("phone"in e){let{phone:f,password:p,options:m}=e;i=await $(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:Qe})}else throw new Mr("You must provide either an email or phone number and a password");let{data:o,error:u}=i;if(u||!o)return await Se(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:u});let c=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:h,session:c},error:null})}catch(i){if(await Se(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 $(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:Sh})}else if("phone"in e){let{phone:i,password:o,options:u}=e;t=await $(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:Sh})}else throw new Mr("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 Vt;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,h,f,p,m;let y,T;if("message"in e)y=e.message,T=e.signature;else{let{chain:R,wallet:I,statement:k,options:O}=e,D;if(be())if(typeof I=="object")D=I;else{let w=window;if("ethereum"in w&&typeof w.ethereum=="object"&&"request"in w.ethereum&&typeof w.ethereum.request=="function")D=w.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 j=new URL((t=O==null?void 0:O.url)!==null&&t!==void 0?t:window.location.href),H=await D.request({method:"eth_requestAccounts"}).then(w=>w).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!H||H.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let F=Ph(H[0]),E=(n=O==null?void 0:O.signInWithEthereum)===null||n===void 0?void 0:n.chainId;if(!E){let w=await D.request({method:"eth_chainId"});E=ev(w)}let _={domain:j.host,address:F,statement:k,uri:j.href,version:"1",chainId:E,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:(h=O==null?void 0:O.signInWithEthereum)===null||h===void 0?void 0:h.requestId,resources:(f=O==null?void 0:O.signInWithEthereum)===null||f===void 0?void 0:f.resources};y=rv(_),T=await D.request({method:"personal_sign",params:[tv(y),F]})}try{let{data:R,error:I}=await $(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:Qe});if(I)throw I;if(!R||!R.session||!R.user){let k=new Vt;return this._returnResult({data:{user:null,session:null},error:k})}return R.session&&(await this._saveSession(R.session),await this._notifyAllSubscribers("SIGNED_IN",R.session)),this._returnResult({data:Object.assign({},R),error:I})}catch(R){if(U(R))return this._returnResult({data:{user:null,session:null},error:R});throw R}}async signInWithSolana(e){var t,n,s,i,o,u,c,h,f,p,m,y;let T,R;if("message"in e)T=e.message,R=e.signature;else{let{chain:I,wallet:k,statement:O,options:D}=e,j;if(be())if(typeof k=="object")j=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"))j=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.");j=k}let H=new URL((t=D==null?void 0:D.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in j&&j.signIn){let F=await j.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},D==null?void 0:D.signInWithSolana),{version:"1",domain:H.host,uri:H.href}),O?{statement:O}:null)),E;if(Array.isArray(F)&&F[0]&&typeof F[0]=="object")E=F[0];else if(F&&typeof F=="object"&&"signedMessage"in F&&"signature"in F)E=F;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in E&&"signature"in E&&(typeof E.signedMessage=="string"||E.signedMessage instanceof Uint8Array)&&E.signature instanceof Uint8Array)T=typeof E.signedMessage=="string"?E.signedMessage:new TextDecoder().decode(E.signedMessage),R=E.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in j)||typeof j.signMessage!="function"||!("publicKey"in j)||typeof j!="object"||!j.publicKey||!("toBase58"in j.publicKey)||typeof j.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");T=[`${H.host} wants you to sign in with your Solana account:`,j.publicKey.toBase58(),...O?["",O,""]:[""],"Version: 1",`URI: ${H.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}`]:[],...!((h=D==null?void 0:D.signInWithSolana)===null||h===void 0)&&h.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(E=>`- ${E}`)]:[]].join(`
78
- `);let F=await j.signMessage(new TextEncoder().encode(T),"utf8");if(!F||!(F instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");R=F}}try{let{data:I,error:k}=await $(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:T,signature:Lt(R)},!((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:Qe});if(k)throw k;if(!I||!I.session||!I.user){let O=new Vt;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 gr(this.storage,`${this.storageKey}-code-verifier`),[n,s]=(t!=null?t:"").split("/");try{if(!n&&this.flowType==="pkce")throw new Va;let{data:i,error:o}=await $(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:Qe});if(await Se(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!i||!i.session||!i.user){let u=new Vt;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 Se(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 $(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:Qe}),{data:c,error:h}=u;if(h)return this._returnResult({data:{user:null,session:null},error:h});if(!c||!c.session||!c.user){let f=new Vt;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:h})}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,h=null,f=null;this.flowType==="pkce"&&([h,f]=await zr(this.storage,this.storageKey));let{error:p}=await $(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:h,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:h,error:f}=await $(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:h==null?void 0:h.message_id},error:f})}throw new Mr("You must provide either an email or phone number.")}catch(u){if(await Se(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 $(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:Qe});if(u)throw u;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,h=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:h,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 zr(this.storage,this.storageKey));let h=await $(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:X_});return!((i=h.data)===null||i===void 0)&&i.url&&be()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(h.data.url),this._returnResult(h)}catch(u){if(await Se(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 Re;let{error:s}=await $(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 $(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 $(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 Mr("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 gr(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()<Da:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){let o=await gr(this.userStorage,this.storageKey+"-user");o!=null&&o.user?e.user=o.user:e.user=Ba()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let o={value:this.suppressGetSessionWarning};e.user=Q_(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 $(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:gt}):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 Re}:await $(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:gt})})}catch(t){if(U(t))return La(t)&&(await this._removeSession(),await Se(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 Re;let o=s.session,u=null,c=null;this.flowType==="pkce"&&e.email!=null&&([u,c]=await zr(this.storage,this.storageKey));let{data:h,error:f}=await $(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:gt});if(f)throw f;return o.user=h.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(n){if(await Se(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 Re;let t=Date.now()/1e3,n=t,s=!0,i=null,{payload:o}=bi(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 Re;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(!be())throw new Ur("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Ur(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 _i("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Ur("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 _i("No code detected.");let{data:O,error:D}=await this._exchangeCodeForSession(e.code);if(D)throw D;let j=new URL(window.location.href);return j.searchParams.delete("code"),window.history.replaceState(window.history.state,"",j.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:h}=e;if(!i||!u||!o||!h)throw new Ur("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<=jr&&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:R,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:h,user:R.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 gr(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&&!La(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&&!(N_(u)&&(u.status===404||u.status===401||u.status===403)||La(u)))return this._returnResult({error:u})}return e!=="others"&&(await this._removeSession(),await Se(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let t=B_(),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 zr(this.storage,this.storageKey,!0));try{return await $(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 Se(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,h,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 $(this.fetch,"GET",y,{headers:this.headers,jwt:(f=(h=p.session)===null||h===void 0?void 0:h.access_token)!==null&&f!==void 0?f:void 0})});if(s)throw s;return be()&&!(!((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:h,nonce:f}=e,p=await $(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:h,nonce:f,link_identity:!0,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:Qe}),{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 Vt}):(m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("USER_UPDATED",m.session)),this._returnResult({data:m,error:y}))}catch(s){if(await Se(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 $(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 K_(async s=>(s>0&&await z_(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await $(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Qe})),(s,i)=>{let o=200*Math.pow(2,s);return i&&Fa(i)&&Date.now()+o-n<jr})}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),be()&&!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 gr(this.storage,this.storageKey);if(s&&this.userStorage){let o=await gr(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:s.user},await qr(this.userStorage,this.storageKey+"-user",o)),s.user=(e=o==null?void 0:o.user)!==null&&e!==void 0?e:Ba()}else if(s&&!s.user&&!s.user){let o=await gr(this.storage,this.storageKey+"-user");o&&(o!=null&&o.user)?(s.user=o.user,await Se(this.storage,this.storageKey+"-user"),await qr(this.storage,this.storageKey,s)):s.user=Ba()}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()<Da;if(this._debug(n,`session has${i?"":" not"} expired with margin of ${Da}s`),i){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),Fa(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 Re;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new wi;let{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new Re;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 Fa(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 Se(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 qr(this.userStorage,this.storageKey+"-user",{user:t.user});let s=Object.assign({},t);delete s.user;let i=Ih(s);await qr(this.storage,this.storageKey,i)}else{let s=Ih(t);await qr(this.storage,this.storageKey,s)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Se(this.storage,this.storageKey),await Se(this.storage,this.storageKey+"-code-verifier"),await Se(this.storage,this.storageKey+"-user"),this.userStorage&&await Se(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&be()&&(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(),jr);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)/jr);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${jr}ms, refresh threshold is ${Oa} ticks`),s<=Oa&&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 Ei)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!be()||!(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 zr(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 $(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:h}=await $(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 h?this._returnResult({data:null,error:h}):(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"?uv(e.webauthn.credential_response):cv(e.webauthn.credential_response)})}:{code:e.code}),{data:u,error:c}=await $(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 $(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:ov(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:av(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}=bi(e),T=null;y.aal&&(T=y.aal);let R=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(j=>j.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(R="aal2");let D=y.amr||[];return{data:{currentLevel:T,nextLevel:R,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}=bi(o.access_token),h=null;c.aal&&(h=c.aal);let f=h;((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:h,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 $(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 Re})})}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 Re});let o=await $(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&&be()&&!(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 Re});let o=await $(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&&be()&&!(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 $(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 Re})})}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 $(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 Re})})}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+D_>s)return n;let{data:i,error:o}=await $(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}}=bi(n);t!=null&&t.allowExpired||W_(i.exp);let h=!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(!h){let{error:y}=await this.getUser(n);if(y)throw y;return{data:{claims:i,header:s,signature:o},error:null}}let f=H_(s.alg),p=await crypto.subtle.importKey("jwk",h,f,!0,["verify"]);if(!await crypto.subtle.verify(f,p,o,M_(`${u}.${c}`)))throw new Br("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}}};Ka.nextInstanceID={};var Oh=Ka;var mC=Oh,Dh=mC;var gC="2.97.0",Ii="";typeof Deno!="undefined"?Ii="deno":typeof document!="undefined"?Ii="web":typeof navigator!="undefined"&&navigator.product==="ReactNative"?Ii="react-native":Ii="node";var yC={"X-Client-Info":`supabase-js-${Ii}/${gC}`},_C={headers:yC},vC={schema:"public"},wC={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},bC={};function Si(r){"@babel/helpers - typeof";return Si=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},Si(r)}function EC(r,e){if(Si(r)!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var n=t.call(r,e||"default");if(Si(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function TC(r){var e=EC(r,"string");return Si(e)=="symbol"?e:e+""}function IC(r,e,t){return(e=TC(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function hv(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 de(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?hv(Object(t),!0).forEach(function(n){IC(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):hv(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var SC=r=>r?(...e)=>r(...e):(...e)=>fetch(...e),AC=()=>Headers,xC=(r,e,t)=>{let n=SC(t),s=AC();return async(i,o)=>{var u;let c=(u=await e())!==null&&u!==void 0?u:r,h=new s(o==null?void 0:o.headers);return h.has("apikey")||h.set("apikey",r),h.has("Authorization")||h.set("Authorization",`Bearer ${c}`),n(i,de(de({},o),{},{headers:h}))}};function RC(r){return r.endsWith("/")?r:r+"/"}function PC(r,e){var t,n;let{db:s,auth:i,realtime:o,global:u}=r,{db:c,auth:h,realtime:f,global:p}=e,m={db:de(de({},c),s),auth:de(de({},h),i),realtime:de(de({},f),o),storage:{},global:de(de(de({},p),u),{},{headers:de(de({},(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 CC(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(RC(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var kC=class extends Dh{constructor(r){super(r)}},OC=class{constructor(r,e,t){var n,s;this.supabaseUrl=r,this.supabaseKey=e;let i=CC(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:vC,realtime:bC,auth:de(de({},wC),{},{storageKey:o}),global:_C},c=PC(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 h;this.auth=this._initSupabaseAuthClient((h=c.auth)!==null&&h!==void 0?h:{},this.headers,c.global.fetch)}this.fetch=xC(e,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(de({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 f_(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 R_(this.storageUrl.href,this.headers,this.fetch,t==null?void 0:t.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new ui(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:h},f,p){let m={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new kC({url:this.authUrl.href,headers:de(de({},m),f),storageKey:i,autoRefreshToken:r,persistSession:e,detectSessionInUrl:t,storage:n,userStorage:s,flowType:o,lock:u,debug:c,throwOnError:h,fetch:p,hasCustomAuthorizationHeader:Object.keys(this.headers).some(y=>y.toLowerCase()==="authorization")})}_initRealtimeClient(r){return new ns(this.realtimeUrl.href,de(de({},r),{},{params:de(de({},{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)}},dv=(r,e,t)=>new OC(r,e,t);function DC(){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}DC()&&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 vv=yw(yv(),1);var VC=Object.prototype.toString,LC=r=>VC.call(r)==="[object Error]",FC=new Set(["network error","Failed to fetch","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&&LC(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")?!0:FC.has(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}},_v=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function Ai(r,e){return new Promise((t,n)=>{var u,c,h;e={...e},(u=e.onFailedAttempt)!=null||(e.onFailedAttempt=()=>{}),(c=e.shouldRetry)!=null||(e.shouldRetry=()=>!0),(h=e.retries)!=null||(e.retries=10);let s=vv.default.operation(e),i=()=>{var f;s.stop(),n((f=e.signal)==null?void 0:f.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",i,{once:!0});let o=()=>{var f;(f=e.signal)==null||f.removeEventListener("abort",i),s.stop()};s.attempt(async f=>{try{let p=await r(f);o(),t(p)}catch(p){try{if(!(p instanceof Error))throw new TypeError(`Non-error was thrown: "${p}". You should only throw errors.`);if(p instanceof Vh)throw p.originalError;if(p instanceof TypeError&&!Nh(p))throw p;if(_v(p,f,e),await e.shouldRetry(p)||(s.stop(),n(p)),await e.onFailedAttempt(p),!s.retry(p))throw s.mainError()}catch(m){_v(m,f,e),o(),n(m)}}})})}var jC=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"?Ee.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(()=>Ai(()=>e.call(s,s),{...n.retries&&{retries:n.retries},...t.retry})).then(i=>{if(i!=null&&i.error)Ee.throw(i.error);else if(i.data)return i.data}).catch(i=>{throw console.log("Supabasey error:",i),i})},Ee=jC;Ee.bindSession=function(e){if(typeof e=="string"&&!Ee.sessions[e])throw new Error(`Unable to bind to non-existant session "${e}"`);let t=(n,s)=>Ee(n,{session:e,...s});return t.rpc=(n,s,i)=>Ee.rpc(n,s,{session:e,...i}),t};Ee.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=Ee.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=Ee.sessions[s]=dv(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 Ee(o=>o.auth.signInWithPassword({email:n.SUPABASE_USER,password:n.SUPABASE_PASS}),{session:i}).then(()=>i.supabaseyIsLoggedIn=!0)}else return}).then(()=>Ee.bindSession(i))};Ee.middleware=function(e){let t={env:{},injectEnv:!0,...e};return async(n,s,i,o)=>Ee.init({...e,env:i}).then(u=>{t.injectEnv&&(i.supabasey=u)}).catch(u=>Ee.throw(u))};Ee.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"}`))};Ee.rpc=function(r,e,t){return Ee(async n=>await n.rpc(r,e),t)};Ee.sessions={};var wv=Ee;function MC(r,e){return Object.fromEntries(Object.entries(r).sort(e||void 0).map(([t,n])=>[t,n]))}function Ga(r,e){return Array.isArray(r)?r.map(t=>Ga(t,e)):typeof r=="object"?r==null?null:Object.fromEntries(Object.entries(MC(r,e)).map(([t,n])=>[t,Ga(n,e)])):r}var bv={id:"~date",test:r=>r instanceof Date,serialize:r=>({_:"~date",v:r.toISOString()}),deserialize:r=>new Date(r.v)};var Ev={id:"~function",test:r=>typeof r=="function",serialize:r=>({_:"~function",v:r.toString()}),deserialize:v=>eval(v.v.toString())};var Tv={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 Iv={id:"~nan",test:r=>Number.isNaN(r),serialize:r=>({_:"~nan"}),deserialize:r=>NaN};var Sv={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 Av={id:"~set",test:r=>r instanceof Set,serialize:r=>({_:"~set",v:Array.from(r)}),deserialize:r=>new Set(r.v)};var xv={id:"~undefined",test:r=>r===void 0,serialize:r=>({_:"~undefined"}),deserialize:r=>{}};var us={settings:{stringify:!0,destringify:!0,clone:!1,depth:0,modules:[bv,Ev,Tv,Iv,Sv,Av,xv],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 us.loadedModules[e.id]=e}else throw new Error("Unknown module type")})},serialize(r,e){let t=go(e,us.settings),n=us.loadModules(t.modules),s=t.symetric?Ga(r):t.clone?Zt(r):r,i=new Map,o=(u,c)=>{let h=ee(u);if(h&&t.circular){let m=i.get(u);if(m)return er(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)&&h;if(f){let m=f.serialize(u,c);if(f.recursive&&p){let y=De(u);t.symetric&&y.sort(),er(s,c,m),y.forEach(T=>o(u[T],c.concat(T)))}else c.length?er(s,c,m):s=m}else if(p){let m=De(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=go(e,us.settings),n=us.loadModules(t.modules),s=Au(n,"id"),i=t.destringify?JSON.parse(r):t.clone?Zt(r):r,o=(u,c)=>{if(ee(u)&&u._&&typeof u._=="string"&&u._.startsWith("~")&&s[u._]){let h=s[u._].deserialize(u,c);c.length?s[u._].recursive&&ee(h)?(er(i,c,h),De(h).forEach(f=>o(u[f],[...c,f]))):er(i,c,h):i=h}else t.circular&&ee(u)&&u._&&u._=="~circular"?er(i,c,Cs(i,u.p)):(!t.depth||c.length<t.depth)&&ee(u)&&De(u).forEach(h=>o(u[h],c.concat(h)))};return o(i,[]),i}},Wa=us;var Rv="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Pv=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=Rv[t[r]&63];return e};var Ft=class r{constructor(e,t){this.throttle=250;this.config={heartbeatInterval:5e4,syncroRegistryUrl:"https://tera-tools.com/api/sync",context:{}};this.isDirty=!1;this._destroyActions=[];this.path=e,Object.assign(this,{...t,config:{...this.config,...t==null?void 0:t.config}}),r.session||(r.session=`syncro_${Pv()}`)}debug(...e){}debugError(...e){console.log(`[Syncro ${this.path}]`,...e)}destroy(){return this.debug("Destroy!"),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 Zt(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(r.SyncroEntities&&!(i.entity in r.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 Wa.serialize(e,{...Cv,stringify:!1})}static fromFirestore(e={}){return Wa.deserialize(e,{...Cv,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=>r.toFirestoreFields({item:o}).item)}}:i==="object"&&(t[n]={mapValue:{fields:r.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]=r.fromFirestoreFields(s.mapValue.fields||{});break;case"arrayValue":{let o=s.arrayValue.values;t[n]=o?o.map(u=>r.fromFirestoreFields(u)):[];break}case"nullValue":t[n]=null;break;default:t[n]=s[i]}else t[n]=r.fromFirestoreFields(s)}return t}static getSnapshot(e){let{fsCollection:t,fsId:n}=r.pathSplit(e);return Promise.resolve().then(async()=>ah(ba(r.firestore,t,n))).then(s=>s.exists()?r.fromFirestore(s.data()):null)}static setSnapshot(e,t,n){let s={method:"merge",...n},{fsCollection:i,fsId:o}=r.pathSplit(e),u=ba(r.firestore,i,o),c=r.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}=r.pathSplit(this.path),o,u;return Ai(async()=>{await this.setHeartbeat(!1),this.docRef=ba(r.firestore,n,s);let c=await this.getFirestoreState();if(this.path.startsWith("projects::")&&c&&!yo(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()`");this.value=u=o.doc,this.debug("Initial state",{doc:u});let h=i_(this.docRef,f=>{let p=r.fromFirestore(f.data());this.debug("Incoming snapshot",{snapshotData:p}),o.setState(p)});if(this._destroyActions.push(h),yo(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(xu(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])=>!Os(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:r.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=r.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 r.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"))}};var Cv={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("."))}},...Wa.settings.modules.filter(r=>r.id!="~function")]};var xi=class{init(){}constructor(e,t){}};var Ri=class extends xi{constructor(){super(...arguments);this.syncros={};this.namespaces={}}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(", "));Ft.firebase=Gu({apiKey:n.firebaseApiKey,authDomain:n.firebaseAuthDomain,projectId:n.firebaseProjectId,appId:n.firebaseAppId}),Ft.firestore=Yy(Ft.firebase),Ft.supabasey=await wv.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 Ft(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 Lh=class extends Ri{constructor(){super(...arguments);this.project=null;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])=>!Os(n[o],i[o])).forEach(([o,u])=>n[o]=u)},getState:()=>Zt(n),watch:i=>{this.app.$watch(s,i,{deep:!0})}}}};export{Lh as default};
78
+ `);let F=await j.signMessage(new TextEncoder().encode(T),"utf8");if(!F||!(F instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");R=F}}try{let{data:I,error:k}=await $(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:T,signature:Lt(R)},!((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:Qe});if(k)throw k;if(!I||!I.session||!I.user){let O=new Vt;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 gr(this.storage,`${this.storageKey}-code-verifier`),[n,s]=(t!=null?t:"").split("/");try{if(!n&&this.flowType==="pkce")throw new Va;let{data:i,error:o}=await $(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:Qe});if(await Se(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!i||!i.session||!i.user){let u=new Vt;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 Se(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 $(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:Qe}),{data:c,error:h}=u;if(h)return this._returnResult({data:{user:null,session:null},error:h});if(!c||!c.session||!c.user){let f=new Vt;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:h})}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,h=null,f=null;this.flowType==="pkce"&&([h,f]=await zr(this.storage,this.storageKey));let{error:p}=await $(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:h,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:h,error:f}=await $(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:h==null?void 0:h.message_id},error:f})}throw new Mr("You must provide either an email or phone number.")}catch(u){if(await Se(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 $(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:Qe});if(u)throw u;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,h=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:h,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 zr(this.storage,this.storageKey));let h=await $(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:X_});return!((i=h.data)===null||i===void 0)&&i.url&&be()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(h.data.url),this._returnResult(h)}catch(u){if(await Se(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 Re;let{error:s}=await $(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 $(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 $(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 Mr("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 gr(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()<Da:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){let o=await gr(this.userStorage,this.storageKey+"-user");o!=null&&o.user?e.user=o.user:e.user=Ba()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let o={value:this.suppressGetSessionWarning};e.user=Q_(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 $(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:gt}):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 Re}:await $(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:gt})})}catch(t){if(U(t))return La(t)&&(await this._removeSession(),await Se(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 Re;let o=s.session,u=null,c=null;this.flowType==="pkce"&&e.email!=null&&([u,c]=await zr(this.storage,this.storageKey));let{data:h,error:f}=await $(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:gt});if(f)throw f;return o.user=h.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(n){if(await Se(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 Re;let t=Date.now()/1e3,n=t,s=!0,i=null,{payload:o}=bi(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 Re;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(!be())throw new Ur("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Ur(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 _i("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Ur("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 _i("No code detected.");let{data:O,error:D}=await this._exchangeCodeForSession(e.code);if(D)throw D;let j=new URL(window.location.href);return j.searchParams.delete("code"),window.history.replaceState(window.history.state,"",j.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:h}=e;if(!i||!u||!o||!h)throw new Ur("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<=jr&&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:R,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:h,user:R.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 gr(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&&!La(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&&!(N_(u)&&(u.status===404||u.status===401||u.status===403)||La(u)))return this._returnResult({error:u})}return e!=="others"&&(await this._removeSession(),await Se(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let t=B_(),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 zr(this.storage,this.storageKey,!0));try{return await $(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 Se(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,h,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 $(this.fetch,"GET",y,{headers:this.headers,jwt:(f=(h=p.session)===null||h===void 0?void 0:h.access_token)!==null&&f!==void 0?f:void 0})});if(s)throw s;return be()&&!(!((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:h,nonce:f}=e,p=await $(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:h,nonce:f,link_identity:!0,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:Qe}),{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 Vt}):(m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("USER_UPDATED",m.session)),this._returnResult({data:m,error:y}))}catch(s){if(await Se(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 $(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 K_(async s=>(s>0&&await z_(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await $(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Qe})),(s,i)=>{let o=200*Math.pow(2,s);return i&&Fa(i)&&Date.now()+o-n<jr})}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),be()&&!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 gr(this.storage,this.storageKey);if(s&&this.userStorage){let o=await gr(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:s.user},await qr(this.userStorage,this.storageKey+"-user",o)),s.user=(e=o==null?void 0:o.user)!==null&&e!==void 0?e:Ba()}else if(s&&!s.user&&!s.user){let o=await gr(this.storage,this.storageKey+"-user");o&&(o!=null&&o.user)?(s.user=o.user,await Se(this.storage,this.storageKey+"-user"),await qr(this.storage,this.storageKey,s)):s.user=Ba()}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()<Da;if(this._debug(n,`session has${i?"":" not"} expired with margin of ${Da}s`),i){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),Fa(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 Re;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new wi;let{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new Re;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 Fa(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 Se(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 qr(this.userStorage,this.storageKey+"-user",{user:t.user});let s=Object.assign({},t);delete s.user;let i=Ih(s);await qr(this.storage,this.storageKey,i)}else{let s=Ih(t);await qr(this.storage,this.storageKey,s)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Se(this.storage,this.storageKey),await Se(this.storage,this.storageKey+"-code-verifier"),await Se(this.storage,this.storageKey+"-user"),this.userStorage&&await Se(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&be()&&(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(),jr);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)/jr);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${jr}ms, refresh threshold is ${Oa} ticks`),s<=Oa&&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 Ei)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!be()||!(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 zr(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 $(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:h}=await $(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 h?this._returnResult({data:null,error:h}):(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"?uv(e.webauthn.credential_response):cv(e.webauthn.credential_response)})}:{code:e.code}),{data:u,error:c}=await $(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 $(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:ov(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:av(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}=bi(e),T=null;y.aal&&(T=y.aal);let R=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(j=>j.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(R="aal2");let D=y.amr||[];return{data:{currentLevel:T,nextLevel:R,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}=bi(o.access_token),h=null;c.aal&&(h=c.aal);let f=h;((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:h,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 $(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 Re})})}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 Re});let o=await $(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&&be()&&!(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 Re});let o=await $(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&&be()&&!(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 $(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 Re})})}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 $(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 Re})})}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+D_>s)return n;let{data:i,error:o}=await $(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}}=bi(n);t!=null&&t.allowExpired||W_(i.exp);let h=!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(!h){let{error:y}=await this.getUser(n);if(y)throw y;return{data:{claims:i,header:s,signature:o},error:null}}let f=H_(s.alg),p=await crypto.subtle.importKey("jwk",h,f,!0,["verify"]);if(!await crypto.subtle.verify(f,p,o,M_(`${u}.${c}`)))throw new Br("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}}};Ka.nextInstanceID={};var Oh=Ka;var mC=Oh,Dh=mC;var gC="2.97.0",Ii="";typeof Deno!="undefined"?Ii="deno":typeof document!="undefined"?Ii="web":typeof navigator!="undefined"&&navigator.product==="ReactNative"?Ii="react-native":Ii="node";var yC={"X-Client-Info":`supabase-js-${Ii}/${gC}`},_C={headers:yC},vC={schema:"public"},wC={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},bC={};function Si(r){"@babel/helpers - typeof";return Si=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},Si(r)}function EC(r,e){if(Si(r)!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var n=t.call(r,e||"default");if(Si(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function TC(r){var e=EC(r,"string");return Si(e)=="symbol"?e:e+""}function IC(r,e,t){return(e=TC(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function hv(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 de(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?hv(Object(t),!0).forEach(function(n){IC(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):hv(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var SC=r=>r?(...e)=>r(...e):(...e)=>fetch(...e),AC=()=>Headers,xC=(r,e,t)=>{let n=SC(t),s=AC();return async(i,o)=>{var u;let c=(u=await e())!==null&&u!==void 0?u:r,h=new s(o==null?void 0:o.headers);return h.has("apikey")||h.set("apikey",r),h.has("Authorization")||h.set("Authorization",`Bearer ${c}`),n(i,de(de({},o),{},{headers:h}))}};function RC(r){return r.endsWith("/")?r:r+"/"}function PC(r,e){var t,n;let{db:s,auth:i,realtime:o,global:u}=r,{db:c,auth:h,realtime:f,global:p}=e,m={db:de(de({},c),s),auth:de(de({},h),i),realtime:de(de({},f),o),storage:{},global:de(de(de({},p),u),{},{headers:de(de({},(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 CC(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(RC(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var kC=class extends Dh{constructor(r){super(r)}},OC=class{constructor(r,e,t){var n,s;this.supabaseUrl=r,this.supabaseKey=e;let i=CC(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:vC,realtime:bC,auth:de(de({},wC),{},{storageKey:o}),global:_C},c=PC(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 h;this.auth=this._initSupabaseAuthClient((h=c.auth)!==null&&h!==void 0?h:{},this.headers,c.global.fetch)}this.fetch=xC(e,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(de({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 f_(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 R_(this.storageUrl.href,this.headers,this.fetch,t==null?void 0:t.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new ui(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:h},f,p){let m={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new kC({url:this.authUrl.href,headers:de(de({},m),f),storageKey:i,autoRefreshToken:r,persistSession:e,detectSessionInUrl:t,storage:n,userStorage:s,flowType:o,lock:u,debug:c,throwOnError:h,fetch:p,hasCustomAuthorizationHeader:Object.keys(this.headers).some(y=>y.toLowerCase()==="authorization")})}_initRealtimeClient(r){return new ns(this.realtimeUrl.href,de(de({},r),{},{params:de(de({},{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)}},dv=(r,e,t)=>new OC(r,e,t);function DC(){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}DC()&&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 vv=yw(yv(),1);var VC=Object.prototype.toString,LC=r=>VC.call(r)==="[object Error]",FC=new Set(["network error","Failed to fetch","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&&LC(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")?!0:FC.has(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}},_v=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function Ai(r,e){return new Promise((t,n)=>{var u,c,h;e={...e},(u=e.onFailedAttempt)!=null||(e.onFailedAttempt=()=>{}),(c=e.shouldRetry)!=null||(e.shouldRetry=()=>!0),(h=e.retries)!=null||(e.retries=10);let s=vv.default.operation(e),i=()=>{var f;s.stop(),n((f=e.signal)==null?void 0:f.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",i,{once:!0});let o=()=>{var f;(f=e.signal)==null||f.removeEventListener("abort",i),s.stop()};s.attempt(async f=>{try{let p=await r(f);o(),t(p)}catch(p){try{if(!(p instanceof Error))throw new TypeError(`Non-error was thrown: "${p}". You should only throw errors.`);if(p instanceof Vh)throw p.originalError;if(p instanceof TypeError&&!Nh(p))throw p;if(_v(p,f,e),await e.shouldRetry(p)||(s.stop(),n(p)),await e.onFailedAttempt(p),!s.retry(p))throw s.mainError()}catch(m){_v(m,f,e),o(),n(m)}}})})}var jC=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"?Ee.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(()=>Ai(()=>e.call(s,s),{...n.retries&&{retries:n.retries},...t.retry})).then(i=>{if(i!=null&&i.error)Ee.throw(i.error);else if(i.data)return i.data}).catch(i=>{throw console.log("Supabasey error:",i),i})},Ee=jC;Ee.bindSession=function(e){if(typeof e=="string"&&!Ee.sessions[e])throw new Error(`Unable to bind to non-existant session "${e}"`);let t=(n,s)=>Ee(n,{session:e,...s});return t.rpc=(n,s,i)=>Ee.rpc(n,s,{session:e,...i}),t};Ee.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=Ee.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=Ee.sessions[s]=dv(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 Ee(o=>o.auth.signInWithPassword({email:n.SUPABASE_USER,password:n.SUPABASE_PASS}),{session:i}).then(()=>i.supabaseyIsLoggedIn=!0)}else return}).then(()=>Ee.bindSession(i))};Ee.middleware=function(e){let t={env:{},injectEnv:!0,...e};return async(n,s,i,o)=>Ee.init({...e,env:i}).then(u=>{t.injectEnv&&(i.supabasey=u)}).catch(u=>Ee.throw(u))};Ee.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"}`))};Ee.rpc=function(r,e,t){return Ee(async n=>await n.rpc(r,e),t)};Ee.sessions={};var wv=Ee;function MC(r,e){return Object.fromEntries(Object.entries(r).sort(e||void 0).map(([t,n])=>[t,n]))}function Ga(r,e){return Array.isArray(r)?r.map(t=>Ga(t,e)):typeof r=="object"?r==null?null:Object.fromEntries(Object.entries(MC(r,e)).map(([t,n])=>[t,Ga(n,e)])):r}var bv={id:"~date",test:r=>r instanceof Date,serialize:r=>({_:"~date",v:r.toISOString()}),deserialize:r=>new Date(r.v)};var Ev={id:"~function",test:r=>typeof r=="function",serialize:r=>({_:"~function",v:r.toString()}),deserialize:v=>eval(v.v.toString())};var Tv={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 Iv={id:"~nan",test:r=>Number.isNaN(r),serialize:r=>({_:"~nan"}),deserialize:r=>NaN};var Sv={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 Av={id:"~set",test:r=>r instanceof Set,serialize:r=>({_:"~set",v:Array.from(r)}),deserialize:r=>new Set(r.v)};var xv={id:"~undefined",test:r=>r===void 0,serialize:r=>({_:"~undefined"}),deserialize:r=>{}};var us={settings:{stringify:!0,destringify:!0,clone:!1,depth:0,modules:[bv,Ev,Tv,Iv,Sv,Av,xv],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 us.loadedModules[e.id]=e}else throw new Error("Unknown module type")})},serialize(r,e){let t=go(e,us.settings),n=us.loadModules(t.modules),s=t.symetric?Ga(r):t.clone?Zt(r):r,i=new Map,o=(u,c)=>{let h=ee(u);if(h&&t.circular){let m=i.get(u);if(m)return er(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)&&h;if(f){let m=f.serialize(u,c);if(f.recursive&&p){let y=De(u);t.symetric&&y.sort(),er(s,c,m),y.forEach(T=>o(u[T],c.concat(T)))}else c.length?er(s,c,m):s=m}else if(p){let m=De(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=go(e,us.settings),n=us.loadModules(t.modules),s=Au(n,"id"),i=t.destringify?JSON.parse(r):t.clone?Zt(r):r,o=(u,c)=>{if(ee(u)&&u._&&typeof u._=="string"&&u._.startsWith("~")&&s[u._]){let h=s[u._].deserialize(u,c);c.length?s[u._].recursive&&ee(h)?(er(i,c,h),De(h).forEach(f=>o(u[f],[...c,f]))):er(i,c,h):i=h}else t.circular&&ee(u)&&u._&&u._=="~circular"?er(i,c,Cs(i,u.p)):(!t.depth||c.length<t.depth)&&ee(u)&&De(u).forEach(h=>o(u[h],c.concat(h)))};return o(i,[]),i}},Wa=us;var Rv="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Pv=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=Rv[t[r]&63];return e};var Ft=class r{constructor(e,t){this.throttle=250;this.config={heartbeatInterval:12e4,syncroRegistryUrl:"https://tera-tools.com/api/sync",context:{}};this.isDirty=!1;this._destroyActions=[];this.path=e,Object.assign(this,{...t,config:{...this.config,...t==null?void 0:t.config}}),r.session||(r.session=`syncro_${Pv()}`)}debug(...e){}debugError(...e){console.log(`[Syncro ${this.path}]`,...e)}destroy(){return this.debug("Destroy!"),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 Zt(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(r.SyncroEntities&&!(i.entity in r.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 Wa.serialize(e,{...Cv,stringify:!1})}static fromFirestore(e={}){return Wa.deserialize(e,{...Cv,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=>r.toFirestoreFields({item:o}).item)}}:i==="object"&&(t[n]={mapValue:{fields:r.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]=r.fromFirestoreFields(s.mapValue.fields||{});break;case"arrayValue":{let o=s.arrayValue.values;t[n]=o?o.map(u=>r.fromFirestoreFields(u)):[];break}case"nullValue":t[n]=null;break;default:t[n]=s[i]}else t[n]=r.fromFirestoreFields(s)}return t}static getSnapshot(e){let{fsCollection:t,fsId:n}=r.pathSplit(e);return Promise.resolve().then(async()=>ah(ba(r.firestore,t,n))).then(s=>s.exists()?r.fromFirestore(s.data()):null)}static setSnapshot(e,t,n){let s={method:"merge",...n},{fsCollection:i,fsId:o}=r.pathSplit(e),u=ba(r.firestore,i,o),c=r.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}=r.pathSplit(this.path),o,u;return Ai(async()=>{await this.setHeartbeat(!1),this.docRef=ba(r.firestore,n,s);let c=await this.getFirestoreState();if(this.path.startsWith("projects::")&&c&&!yo(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()`");this.value=u=o.doc,this.debug("Initial state",{doc:u});let h=i_(this.docRef,f=>{let p=r.fromFirestore(f.data());this.debug("Incoming snapshot",{snapshotData:p}),o.setState(p)});if(this._destroyActions.push(h),yo(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(xu(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])=>!Os(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:r.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=r.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 r.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"))}};var Cv={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("."))}},...Wa.settings.modules.filter(r=>r.id!="~function")]};var xi=class{init(){}constructor(e,t){}};var Ri=class extends xi{constructor(){super(...arguments);this.syncros={};this.namespaces={}}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(", "));Ft.firebase=Gu({apiKey:n.firebaseApiKey,authDomain:n.firebaseAuthDomain,projectId:n.firebaseProjectId,appId:n.firebaseAppId}),Ft.firestore=Yy(Ft.firebase),Ft.supabasey=await wv.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 Ft(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 Lh=class extends Ri{constructor(){super(...arguments);this.project=null;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])=>!Os(n[o],i[o])).forEach(([o,u])=>n[o]=u)},getState:()=>Zt(n),watch:i=>{this.app.$watch(s,i,{deep:!0})}}}};export{Lh as default};
79
79
  /*! Bundled license information:
80
80
 
81
81
  lodash-es/lodash.js:
@@ -1,5 +1,5 @@
1
1
  var xo=typeof global=="object"&&global&&global.Object===Object&&global,ut=xo;var yo=typeof self=="object"&&self&&self.Object===Object&&self,bo=ut||yo||Function("return this")(),d=bo;var vo=d.Symbol,x=vo;var Qt=Object.prototype,wo=Qt.hasOwnProperty,To=Qt.toString,it=x?x.toStringTag:void 0;function Po(t){var e=wo.call(t,it),r=t[it];try{t[it]=void 0;var o=!0}catch{}var a=To.call(t);return o&&(e?t[it]=r:delete t[it]),a}var te=Po;var jo=Object.prototype,Oo=jo.toString;function Ao(t){return Oo.call(t)}var ee=Ao;var Io="[object Null]",So="[object Undefined]",re=x?x.toStringTag:void 0;function _o(t){return t==null?t===void 0?So:Io:re&&re in Object(t)?te(t):ee(t)}var w=_o;function Eo(t){return t!=null&&typeof t=="object"}var y=Eo;var Fo="[object Symbol]";function Co(t){return typeof t=="symbol"||y(t)&&w(t)==Fo}var k=Co;function Mo(t,e){for(var r=-1,o=t==null?0:t.length,a=Array(o);++r<o;)a[r]=e(t[r],r,t);return a}var dt=Mo;var No=Array.isArray,g=No;var Ro=1/0,oe=x?x.prototype:void 0,ae=oe?oe.toString:void 0;function ie(t){if(typeof t=="string")return t;if(g(t))return dt(t,ie)+"";if(k(t))return ae?ae.call(t):"";var e=t+"";return e=="0"&&1/t==-Ro?"-0":e}var ne=ie;function Lo(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var T=Lo;function Bo(t){return t}var se=Bo;var ko="[object AsyncFunction]",Do="[object Function]",Uo="[object GeneratorFunction]",Go="[object Proxy]";function zo(t){if(!T(t))return!1;var e=w(t);return e==Do||e==Uo||e==ko||e==Go}var ct=zo;var Ko=d["__core-js_shared__"],ht=Ko;var fe=(function(){var t=/[^.]+$/.exec(ht&&ht.keys&&ht.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""})();function Wo(t){return!!fe&&fe in t}var pe=Wo;var Yo=Function.prototype,$o=Yo.toString;function Ho(t){if(t!=null){try{return $o.call(t)}catch{}try{return t+""}catch{}}return""}var A=Ho;var Vo=/[\\^$.*+?()[\]{}|]/g,qo=/^\[object .+?Constructor\]$/,Zo=Function.prototype,Jo=Object.prototype,Xo=Zo.toString,Qo=Jo.hasOwnProperty,ta=RegExp("^"+Xo.call(Qo).replace(Vo,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ea(t){if(!T(t)||pe(t))return!1;var e=ct(t)?ta:qo;return e.test(A(t))}var le=ea;function ra(t,e){return t==null?void 0:t[e]}var me=ra;function oa(t,e){var r=me(t,e);return le(r)?r:void 0}var b=oa;var aa=b(d,"WeakMap"),gt=aa;var ue=Object.create,ia=(function(){function t(){}return function(e){if(!T(e))return{};if(ue)return ue(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}})(),de=ia;function na(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}var ce=na;function sa(t,e){var r=-1,o=t.length;for(e||(e=Array(o));++r<o;)e[r]=t[r];return e}var he=sa;var fa=800,pa=16,la=Date.now;function ma(t){var e=0,r=0;return function(){var o=la(),a=pa-(o-r);if(r=o,a>0){if(++e>=fa)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}var ge=ma;function ua(t){return function(){return t}}var xe=ua;var da=(function(){try{var t=b(Object,"defineProperty");return t({},"",{}),t}catch{}})(),D=da;var ca=D?function(t,e){return D(t,"toString",{configurable:!0,enumerable:!1,value:xe(e),writable:!0})}:se,ye=ca;var ha=ge(ye),be=ha;function ga(t,e){for(var r=-1,o=t==null?0:t.length;++r<o&&e(t[r],r,t)!==!1;);return t}var ve=ga;var xa=9007199254740991,ya=/^(?:0|[1-9]\d*)$/;function ba(t,e){var r=typeof t;return e=e==null?xa:e,!!e&&(r=="number"||r!="symbol"&&ya.test(t))&&t>-1&&t%1==0&&t<e}var U=ba;function va(t,e,r){e=="__proto__"&&D?D(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}var xt=va;function wa(t,e){return t===e||t!==t&&e!==e}var yt=wa;var Ta=Object.prototype,Pa=Ta.hasOwnProperty;function ja(t,e,r){var o=t[e];(!(Pa.call(t,e)&&yt(o,r))||r===void 0&&!(e in t))&&xt(t,e,r)}var G=ja;function Oa(t,e,r,o){var a=!r;r||(r={});for(var i=-1,n=e.length;++i<n;){var s=e[i],u=o?o(r[s],t[s],s,r,t):void 0;u===void 0&&(u=t[s]),a?xt(r,s,u):G(r,s,u)}return r}var O=Oa;var we=Math.max;function Aa(t,e,r){return e=we(e===void 0?t.length-1:e,0),function(){for(var o=arguments,a=-1,i=we(o.length-e,0),n=Array(i);++a<i;)n[a]=o[e+a];a=-1;for(var s=Array(e+1);++a<e;)s[a]=o[a];return s[e]=r(n),ce(t,this,s)}}var Te=Aa;var Ia=9007199254740991;function Sa(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=Ia}var z=Sa;function _a(t){return t!=null&&z(t.length)&&!ct(t)}var bt=_a;var Ea=Object.prototype;function Fa(t){var e=t&&t.constructor,r=typeof e=="function"&&e.prototype||Ea;return t===r}var K=Fa;function Ca(t,e){for(var r=-1,o=Array(t);++r<t;)o[r]=e(r);return o}var Pe=Ca;var Ma="[object Arguments]";function Na(t){return y(t)&&w(t)==Ma}var Lt=Na;var je=Object.prototype,Ra=je.hasOwnProperty,La=je.propertyIsEnumerable,Ba=Lt((function(){return arguments})())?Lt:function(t){return y(t)&&Ra.call(t,"callee")&&!La.call(t,"callee")},W=Ba;function ka(){return!1}var Oe=ka;var Se=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ae=Se&&typeof module=="object"&&module&&!module.nodeType&&module,Da=Ae&&Ae.exports===Se,Ie=Da?d.Buffer:void 0,Ua=Ie?Ie.isBuffer:void 0,Ga=Ua||Oe,vt=Ga;var za="[object Arguments]",Ka="[object Array]",Wa="[object Boolean]",Ya="[object Date]",$a="[object Error]",Ha="[object Function]",Va="[object Map]",qa="[object Number]",Za="[object Object]",Ja="[object RegExp]",Xa="[object Set]",Qa="[object String]",ti="[object WeakMap]",ei="[object ArrayBuffer]",ri="[object DataView]",oi="[object Float32Array]",ai="[object Float64Array]",ii="[object Int8Array]",ni="[object Int16Array]",si="[object Int32Array]",fi="[object Uint8Array]",pi="[object Uint8ClampedArray]",li="[object Uint16Array]",mi="[object Uint32Array]",m={};m[oi]=m[ai]=m[ii]=m[ni]=m[si]=m[fi]=m[pi]=m[li]=m[mi]=!0;m[za]=m[Ka]=m[ei]=m[Wa]=m[ri]=m[Ya]=m[$a]=m[Ha]=m[Va]=m[qa]=m[Za]=m[Ja]=m[Xa]=m[Qa]=m[ti]=!1;function ui(t){return y(t)&&z(t.length)&&!!m[w(t)]}var _e=ui;function di(t){return function(e){return t(e)}}var Y=di;var Ee=typeof exports=="object"&&exports&&!exports.nodeType&&exports,nt=Ee&&typeof module=="object"&&module&&!module.nodeType&&module,ci=nt&&nt.exports===Ee,Bt=ci&&ut.process,hi=(function(){try{var t=nt&&nt.require&&nt.require("util").types;return t||Bt&&Bt.binding&&Bt.binding("util")}catch{}})(),I=hi;var Fe=I&&I.isTypedArray,gi=Fe?Y(Fe):_e,Ce=gi;var xi=Object.prototype,yi=xi.hasOwnProperty;function bi(t,e){var r=g(t),o=!r&&W(t),a=!r&&!o&&vt(t),i=!r&&!o&&!a&&Ce(t),n=r||o||a||i,s=n?Pe(t.length,String):[],u=s.length;for(var c in t)(e||yi.call(t,c))&&!(n&&(c=="length"||a&&(c=="offset"||c=="parent")||i&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||U(c,u)))&&s.push(c);return s}var wt=bi;function vi(t,e){return function(r){return t(e(r))}}var Tt=vi;var wi=Tt(Object.keys,Object),Me=wi;var Ti=Object.prototype,Pi=Ti.hasOwnProperty;function ji(t){if(!K(t))return Me(t);var e=[];for(var r in Object(t))Pi.call(t,r)&&r!="constructor"&&e.push(r);return e}var Ne=ji;function Oi(t){return bt(t)?wt(t):Ne(t)}var $=Oi;function Ai(t){var e=[];if(t!=null)for(var r in Object(t))e.push(r);return e}var Re=Ai;var Ii=Object.prototype,Si=Ii.hasOwnProperty;function _i(t){if(!T(t))return Re(t);var e=K(t),r=[];for(var o in t)o=="constructor"&&(e||!Si.call(t,o))||r.push(o);return r}var Le=_i;function Ei(t){return bt(t)?wt(t,!0):Le(t)}var H=Ei;var Fi=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ci=/^\w*$/;function Mi(t,e){if(g(t))return!1;var r=typeof t;return r=="number"||r=="symbol"||r=="boolean"||t==null||k(t)?!0:Ci.test(t)||!Fi.test(t)||e!=null&&t in Object(e)}var Be=Mi;var Ni=b(Object,"create"),S=Ni;function Ri(){this.__data__=S?S(null):{},this.size=0}var ke=Ri;function Li(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var De=Li;var Bi="__lodash_hash_undefined__",ki=Object.prototype,Di=ki.hasOwnProperty;function Ui(t){var e=this.__data__;if(S){var r=e[t];return r===Bi?void 0:r}return Di.call(e,t)?e[t]:void 0}var Ue=Ui;var Gi=Object.prototype,zi=Gi.hasOwnProperty;function Ki(t){var e=this.__data__;return S?e[t]!==void 0:zi.call(e,t)}var Ge=Ki;var Wi="__lodash_hash_undefined__";function Yi(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=S&&e===void 0?Wi:e,this}var ze=Yi;function V(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var o=t[e];this.set(o[0],o[1])}}V.prototype.clear=ke;V.prototype.delete=De;V.prototype.get=Ue;V.prototype.has=Ge;V.prototype.set=ze;var kt=V;function $i(){this.__data__=[],this.size=0}var Ke=$i;function Hi(t,e){for(var r=t.length;r--;)if(yt(t[r][0],e))return r;return-1}var E=Hi;var Vi=Array.prototype,qi=Vi.splice;function Zi(t){var e=this.__data__,r=E(e,t);if(r<0)return!1;var o=e.length-1;return r==o?e.pop():qi.call(e,r,1),--this.size,!0}var We=Zi;function Ji(t){var e=this.__data__,r=E(e,t);return r<0?void 0:e[r][1]}var Ye=Ji;function Xi(t){return E(this.__data__,t)>-1}var $e=Xi;function Qi(t,e){var r=this.__data__,o=E(r,t);return o<0?(++this.size,r.push([t,e])):r[o][1]=e,this}var He=Qi;function q(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var o=t[e];this.set(o[0],o[1])}}q.prototype.clear=Ke;q.prototype.delete=We;q.prototype.get=Ye;q.prototype.has=$e;q.prototype.set=He;var F=q;var tn=b(d,"Map"),C=tn;function en(){this.size=0,this.__data__={hash:new kt,map:new(C||F),string:new kt}}var Ve=en;function rn(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}var qe=rn;function on(t,e){var r=t.__data__;return qe(e)?r[typeof e=="string"?"string":"hash"]:r.map}var M=on;function an(t){var e=M(this,t).delete(t);return this.size-=e?1:0,e}var Ze=an;function nn(t){return M(this,t).get(t)}var Je=nn;function sn(t){return M(this,t).has(t)}var Xe=sn;function fn(t,e){var r=M(this,t),o=r.size;return r.set(t,e),this.size+=r.size==o?0:1,this}var Qe=fn;function Z(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var o=t[e];this.set(o[0],o[1])}}Z.prototype.clear=Ve;Z.prototype.delete=Ze;Z.prototype.get=Je;Z.prototype.has=Xe;Z.prototype.set=Qe;var st=Z;var pn="Expected a function";function Dt(t,e){if(typeof t!="function"||e!=null&&typeof e!="function")throw new TypeError(pn);var r=function(){var o=arguments,a=e?e.apply(this,o):o[0],i=r.cache;if(i.has(a))return i.get(a);var n=t.apply(this,o);return r.cache=i.set(a,n)||i,n};return r.cache=new(Dt.Cache||st),r}Dt.Cache=st;var tr=Dt;var ln=500;function mn(t){var e=tr(t,function(o){return r.size===ln&&r.clear(),o}),r=e.cache;return e}var er=mn;var un=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,dn=/\\(\\)?/g,cn=er(function(t){var e=[];return t.charCodeAt(0)===46&&e.push(""),t.replace(un,function(r,o,a,i){e.push(a?i.replace(dn,"$1"):o||r)}),e}),rr=cn;function hn(t){return t==null?"":ne(t)}var or=hn;function gn(t,e){return g(t)?t:Be(t,e)?[t]:rr(or(t))}var P=gn;var xn=1/0;function yn(t){if(typeof t=="string"||k(t))return t;var e=t+"";return e=="0"&&1/t==-xn?"-0":e}var N=yn;function bn(t,e){e=P(e,t);for(var r=0,o=e.length;t!=null&&r<o;)t=t[N(e[r++])];return r&&r==o?t:void 0}var Pt=bn;function vn(t,e){for(var r=-1,o=e.length,a=t.length;++r<o;)t[a+r]=e[r];return t}var J=vn;var ar=x?x.isConcatSpreadable:void 0;function wn(t){return g(t)||W(t)||!!(ar&&t&&t[ar])}var ir=wn;function nr(t,e,r,o,a){var i=-1,n=t.length;for(r||(r=ir),a||(a=[]);++i<n;){var s=t[i];e>0&&r(s)?e>1?nr(s,e-1,r,o,a):J(a,s):o||(a[a.length]=s)}return a}var sr=nr;function Tn(t){var e=t==null?0:t.length;return e?sr(t,1):[]}var fr=Tn;function Pn(t){return be(Te(t,void 0,fr),t+"")}var jt=Pn;var jn=Tt(Object.getPrototypeOf,Object),X=jn;var On="[object Object]",An=Function.prototype,In=Object.prototype,pr=An.toString,Sn=In.hasOwnProperty,_n=pr.call(Object);function En(t){if(!y(t)||w(t)!=On)return!1;var e=X(t);if(e===null)return!0;var r=Sn.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&pr.call(r)==_n}var lr=En;function Fn(t,e,r){var o=-1,a=t.length;e<0&&(e=-e>a?0:a+e),r=r>a?a:r,r<0&&(r+=a),a=e>r?0:r-e>>>0,e>>>=0;for(var i=Array(a);++o<a;)i[o]=t[o+e];return i}var mr=Fn;function Cn(){this.__data__=new F,this.size=0}var ur=Cn;function Mn(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r}var dr=Mn;function Nn(t){return this.__data__.get(t)}var cr=Nn;function Rn(t){return this.__data__.has(t)}var hr=Rn;var Ln=200;function Bn(t,e){var r=this.__data__;if(r instanceof F){var o=r.__data__;if(!C||o.length<Ln-1)return o.push([t,e]),this.size=++r.size,this;r=this.__data__=new st(o)}return r.set(t,e),this.size=r.size,this}var gr=Bn;function Q(t){var e=this.__data__=new F(t);this.size=e.size}Q.prototype.clear=ur;Q.prototype.delete=dr;Q.prototype.get=cr;Q.prototype.has=hr;Q.prototype.set=gr;var xr=Q;function kn(t,e){return t&&O(e,$(e),t)}var yr=kn;function Dn(t,e){return t&&O(e,H(e),t)}var br=Dn;var Pr=typeof exports=="object"&&exports&&!exports.nodeType&&exports,vr=Pr&&typeof module=="object"&&module&&!module.nodeType&&module,Un=vr&&vr.exports===Pr,wr=Un?d.Buffer:void 0,Tr=wr?wr.allocUnsafe:void 0;function Gn(t,e){if(e)return t.slice();var r=t.length,o=Tr?Tr(r):new t.constructor(r);return t.copy(o),o}var jr=Gn;function zn(t,e){for(var r=-1,o=t==null?0:t.length,a=0,i=[];++r<o;){var n=t[r];e(n,r,t)&&(i[a++]=n)}return i}var Or=zn;function Kn(){return[]}var Ot=Kn;var Wn=Object.prototype,Yn=Wn.propertyIsEnumerable,Ar=Object.getOwnPropertySymbols,$n=Ar?function(t){return t==null?[]:(t=Object(t),Or(Ar(t),function(e){return Yn.call(t,e)}))}:Ot,tt=$n;function Hn(t,e){return O(t,tt(t),e)}var Ir=Hn;var Vn=Object.getOwnPropertySymbols,qn=Vn?function(t){for(var e=[];t;)J(e,tt(t)),t=X(t);return e}:Ot,At=qn;function Zn(t,e){return O(t,At(t),e)}var Sr=Zn;function Jn(t,e,r){var o=e(t);return g(t)?o:J(o,r(t))}var It=Jn;function Xn(t){return It(t,$,tt)}var _r=Xn;function Qn(t){return It(t,H,At)}var St=Qn;var ts=b(d,"DataView"),_t=ts;var es=b(d,"Promise"),Et=es;var rs=b(d,"Set"),Ft=rs;var Er="[object Map]",os="[object Object]",Fr="[object Promise]",Cr="[object Set]",Mr="[object WeakMap]",Nr="[object DataView]",as=A(_t),is=A(C),ns=A(Et),ss=A(Ft),fs=A(gt),L=w;(_t&&L(new _t(new ArrayBuffer(1)))!=Nr||C&&L(new C)!=Er||Et&&L(Et.resolve())!=Fr||Ft&&L(new Ft)!=Cr||gt&&L(new gt)!=Mr)&&(L=function(t){var e=w(t),r=e==os?t.constructor:void 0,o=r?A(r):"";if(o)switch(o){case as:return Nr;case is:return Er;case ns:return Fr;case ss:return Cr;case fs:return Mr}return e});var et=L;var ps=Object.prototype,ls=ps.hasOwnProperty;function ms(t){var e=t.length,r=new t.constructor(e);return e&&typeof t[0]=="string"&&ls.call(t,"index")&&(r.index=t.index,r.input=t.input),r}var Rr=ms;var us=d.Uint8Array,Ut=us;function ds(t){var e=new t.constructor(t.byteLength);return new Ut(e).set(new Ut(t)),e}var rt=ds;function cs(t,e){var r=e?rt(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.byteLength)}var Lr=cs;var hs=/\w*$/;function gs(t){var e=new t.constructor(t.source,hs.exec(t));return e.lastIndex=t.lastIndex,e}var Br=gs;var kr=x?x.prototype:void 0,Dr=kr?kr.valueOf:void 0;function xs(t){return Dr?Object(Dr.call(t)):{}}var Ur=xs;function ys(t,e){var r=e?rt(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.length)}var Gr=ys;var bs="[object Boolean]",vs="[object Date]",ws="[object Map]",Ts="[object Number]",Ps="[object RegExp]",js="[object Set]",Os="[object String]",As="[object Symbol]",Is="[object ArrayBuffer]",Ss="[object DataView]",_s="[object Float32Array]",Es="[object Float64Array]",Fs="[object Int8Array]",Cs="[object Int16Array]",Ms="[object Int32Array]",Ns="[object Uint8Array]",Rs="[object Uint8ClampedArray]",Ls="[object Uint16Array]",Bs="[object Uint32Array]";function ks(t,e,r){var o=t.constructor;switch(e){case Is:return rt(t);case bs:case vs:return new o(+t);case Ss:return Lr(t,r);case _s:case Es:case Fs:case Cs:case Ms:case Ns:case Rs:case Ls:case Bs:return Gr(t,r);case ws:return new o;case Ts:case Os:return new o(t);case Ps:return Br(t);case js:return new o;case As:return Ur(t)}}var zr=ks;function Ds(t){return typeof t.constructor=="function"&&!K(t)?de(X(t)):{}}var Kr=Ds;var Us="[object Map]";function Gs(t){return y(t)&&et(t)==Us}var Wr=Gs;var Yr=I&&I.isMap,zs=Yr?Y(Yr):Wr,$r=zs;var Ks="[object Set]";function Ws(t){return y(t)&&et(t)==Ks}var Hr=Ws;var Vr=I&&I.isSet,Ys=Vr?Y(Vr):Hr,qr=Ys;var $s=1,Hs=2,Vs=4,Zr="[object Arguments]",qs="[object Array]",Zs="[object Boolean]",Js="[object Date]",Xs="[object Error]",Jr="[object Function]",Qs="[object GeneratorFunction]",tf="[object Map]",ef="[object Number]",Xr="[object Object]",rf="[object RegExp]",of="[object Set]",af="[object String]",nf="[object Symbol]",sf="[object WeakMap]",ff="[object ArrayBuffer]",pf="[object DataView]",lf="[object Float32Array]",mf="[object Float64Array]",uf="[object Int8Array]",df="[object Int16Array]",cf="[object Int32Array]",hf="[object Uint8Array]",gf="[object Uint8ClampedArray]",xf="[object Uint16Array]",yf="[object Uint32Array]",l={};l[Zr]=l[qs]=l[ff]=l[pf]=l[Zs]=l[Js]=l[lf]=l[mf]=l[uf]=l[df]=l[cf]=l[tf]=l[ef]=l[Xr]=l[rf]=l[of]=l[af]=l[nf]=l[hf]=l[gf]=l[xf]=l[yf]=!0;l[Xs]=l[Jr]=l[sf]=!1;function Ct(t,e,r,o,a,i){var n,s=e&$s,u=e&Hs,c=e&Vs;if(r&&(n=a?r(t,o,a,i):r(t)),n!==void 0)return n;if(!T(t))return t;var h=g(t);if(h){if(n=Rr(t),!s)return he(t,n)}else{var j=et(t),ft=j==Jr||j==Qs;if(vt(t))return jr(t,s);if(j==Xr||j==Zr||ft&&!a){if(n=u||ft?{}:Kr(t),!s)return u?Sr(t,br(n,t)):Ir(t,yr(n,t))}else{if(!l[j])return a?t:{};n=zr(t,j,s)}}i||(i=new xr);var ot=i.get(t);if(ot)return ot;i.set(t,n),qr(t)?t.forEach(function(v){n.add(Ct(v,e,r,v,t,i))}):$r(t)&&t.forEach(function(v,f){n.set(f,Ct(v,e,r,f,t,i))});var pt=c?u?St:_r:u?H:$,lt=h?void 0:pt(t);return ve(lt||t,function(v,f){lt&&(f=v,v=t[f]),G(n,f,Ct(v,e,r,f,t,i))}),n}var Mt=Ct;var bf=1,vf=4;function wf(t){return Mt(t,bf|vf)}var Gt=wf;function Tf(t,e){return t!=null&&e in Object(t)}var Qr=Tf;function Pf(t,e,r){e=P(e,t);for(var o=-1,a=e.length,i=!1;++o<a;){var n=N(e[o]);if(!(i=t!=null&&r(t,n)))break;t=t[n]}return i||++o!=a?i:(a=t==null?0:t.length,!!a&&z(a)&&U(n,a)&&(g(t)||W(t)))}var to=Pf;function jf(t,e){return t!=null&&to(t,e,Qr)}var eo=jf;function Of(t){var e=t==null?0:t.length;return e?t[e-1]:void 0}var ro=Of;function Af(t,e){return e.length<2?t:Pt(t,mr(e,0,-1))}var oo=Af;var If=Object.prototype,Sf=If.hasOwnProperty;function _f(t,e){e=P(e,t);var r=-1,o=e.length;if(!o)return!0;for(var a=t==null||typeof t!="object"&&typeof t!="function";++r<o;){var i=e[r];if(typeof i=="string"){if(i==="__proto__"&&!Sf.call(t,"__proto__"))return!1;if(i==="constructor"&&r+1<o&&typeof e[r+1]=="string"&&e[r+1]==="prototype"){if(a&&r===0)continue;return!1}}}var n=oo(t,e);return n==null||delete n[N(ro(e))]}var ao=_f;function Ef(t){return lr(t)?void 0:t}var io=Ef;var Ff=1,Cf=2,Mf=4,Nf=jt(function(t,e){var r={};if(t==null)return r;var o=!1;e=dt(e,function(i){return i=P(i,t),o||(o=i.length>1),i}),O(t,St(t),r),o&&(r=Mt(r,Ff|Cf|Mf,io));for(var a=e.length;a--;)ao(r,e[a]);return r}),zt=Nf;function Rf(t,e,r,o){if(!T(t))return t;e=P(e,t);for(var a=-1,i=e.length,n=i-1,s=t;s!=null&&++a<i;){var u=N(e[a]),c=r;if(u==="__proto__"||u==="constructor"||u==="prototype")return t;if(a!=n){var h=s[u];c=o?o(h,u,s):void 0,c===void 0&&(c=T(h)?h:U(e[a+1])?[]:{})}G(s,u,c),s=s[u]}return t}var no=Rf;function Lf(t,e,r){for(var o=-1,a=e.length,i={};++o<a;){var n=e[o],s=Pt(t,n);r(s,n)&&no(i,P(n,t),s)}return i}var so=Lf;function Bf(t,e){return so(t,e,function(r,o){return eo(t,o)})}var fo=Bf;var kf=jt(function(t,e){return t==null?{}:fo(t,e)}),Nt=kf;function po(t){return{all:t=t||new Map,on:function(e,r){var o=t.get(e);o?o.push(r):t.set(e,[r])},off:function(e,r){var o=t.get(e);o&&(r?o.splice(o.indexOf(r)>>>0,1):t.set(e,[]))},emit:function(e,r){var o=t.get(e);o&&o.slice().map(function(a){a(r)}),(o=t.get("*"))&&o.slice().map(function(a){a(e,r)})}}}var lo="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Kt=(t=21)=>{let e="",r=crypto.getRandomValues(new Uint8Array(t|=0));for(;t--;)e+=lo[r[t]&63];return e};var Df="array";var mo="bits",Uf="byte",uo="bytes";var Gf="exponent",zf="function";var Kf="Invalid number",Wf="Invalid rounding method",Wt="jedec",Yf="object";var $f="round";var Hf="kbit";var Vf="string";var Yt={symbol:{iec:{bits:["bit","Kibit","Mibit","Gibit","Tibit","Pibit","Eibit","Zibit","Yibit"],bytes:["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"]},jedec:{bits:["bit","Kbit","Mbit","Gbit","Tbit","Pbit","Ebit","Zbit","Ybit"],bytes:["B","KB","MB","GB","TB","PB","EB","ZB","YB"]}},fullform:{iec:["","kibi","mebi","gibi","tebi","pebi","exbi","zebi","yobi"],jedec:["","kilo","mega","giga","tera","peta","exa","zetta","yotta"]}};function co(t,{bits:e=!1,pad:r=!1,base:o=-1,round:a=2,locale:i="",localeOptions:n={},separator:s="",spacer:u=" ",symbols:c={},standard:h="",output:j=Vf,fullform:ft=!1,fullforms:ot=[],exponent:pt=-1,roundingMethod:lt=$f,precision:v=0}={}){let f=pt,B=Number(t),p=[],R=0,Rt="";h==="si"?(o=10,h=Wt):h==="iec"||h===Wt?o=2:o===2?h="iec":(o=10,h=Wt);let mt=o===10?1e3:1024,ho=ft===!0,Ht=B<0,Vt=Math[lt];if(typeof t!="bigint"&&isNaN(t))throw new TypeError(Kf);if(typeof Vt!==zf)throw new TypeError(Wf);if(Ht&&(B=-B),(f===-1||isNaN(f))&&(f=Math.floor(Math.log(B)/Math.log(mt)),f<0&&(f=0)),f>8&&(v>0&&(v+=8-f),f=8),j===Gf)return f;if(B===0)p[0]=0,Rt=p[1]=Yt.symbol[h][e?mo:uo][f];else{R=B/(o===2?Math.pow(2,f*10):Math.pow(1e3,f)),e&&(R=R*8,R>=mt&&f<8&&(R=R/mt,f++));let at=Math.pow(10,f>0?a:0);p[0]=Vt(R*at)/at,p[0]===mt&&f<8&&pt===-1&&(p[0]=1,f++),Rt=p[1]=o===10&&f===1?e?Hf:"kB":Yt.symbol[h][e?mo:uo][f]}if(Ht&&(p[0]=-p[0]),v>0&&(p[0]=p[0].toPrecision(v)),p[1]=c[p[1]]||p[1],i===!0?p[0]=p[0].toLocaleString():i.length>0?p[0]=p[0].toLocaleString(i,n):s.length>0&&(p[0]=p[0].toString().replace(".",s)),r&&a>0){let at=p[0].toString(),qt=s||(at.match(/(\D)/g)||[]).pop()||".",Zt=at.toString().split(qt),Jt=Zt[1]||"",Xt=Jt.length,go=a-Xt;p[0]=`${Zt[0]}${qt}${Jt.padEnd(Xt+go,"0")}`}return ho&&(p[1]=ot[f]?ot[f]:Yt.fullform[h][f]+(e?"bit":Uf)+(p[0]===1?"":"s")),j===Df?p:j===Yf?{value:p[0],symbol:p[1],exponent:f,unit:Rt}:p.join(u)}var _=class t{constructor(e){this.meta={};var o;if(!e.tera)throw new Error("Basic file requires a `tera` key to access the Tera instance");Object.assign(this,zt(e,"encodeIdFunction")),e.encodeIdFunction&&typeof e.encodeIdFunction=="function"&&(this.id=e.encodeIdFunction(this.id));let r=this.tera;Object.defineProperty(this,"_tera",{enumerable:!1,configurable:!1,get(){return r}}),delete this.tera,this.created&&typeof this.created=="string"&&(this.created=new Date(this.created)),this.modified&&typeof this.modified=="string"&&(this.modified=new Date(this.modified)),this.accessed&&typeof this.accessed=="string"&&(this.accessed=new Date(this.accessed)),this.isFolder&&(this.files=(o=this.files)==null?void 0:o.map(a=>{let i=a.path.split(/\//).slice(3).join("/"),n=this.url+"/"+a.name;return a.meta.reflib&&(n=n.replace(/\/project\/download\//,"/project/library/")),new t({tera:this._tera,...a,sbId:a.id,id:a.path,encodeIdFunction:e.encodeIdFunction,path:i,url:n})})),this.teraUrl=this.url.replace(/^https?:\/\/(?:.+?)\/projects\/(?:.+?)\/project\/(.+)$/,"/project/$1"),this.sizeFormatted=co(this.size||0,{spacer:""}),this.createdFormatted=this.created?this.created.toLocaleDateString():"Unknown created date",this.modifiedFormatted=this.modified?this.modified.toLocaleDateString():"Unknown modified date",this.accessedFormatted=this.accessed?this.accessed.toLocaleDateString():"Unknown access date"}getContents(e){return this._tera.getProjectFileContents(this.id,e)}setContents(e){return this._tera.setProjectFileContents(this.id,e,{})}getRefs(){return this._tera.getProjectLibrary(this.id)}setRefs(e){return this._tera.setProjectLibrary(this.id,e)}serialize(){return Nt(this,["id","sbId","name","icon","path","url","parsedName","created","modified","accessed","size","mime","meta"])}static deserialize(e){let r=Nt(e,["tera","id","sbId","name","icon","path","url","parsedName","created","modified","accessed","size","mime","meta"]);return new t(r)}};var $t=class{constructor(e){this.settings={session:null,devMode:!1,verbosity:1,mode:"detect",modeTimeout:300,modeFallback:"child",modeOverrides:{child(e){e.siteUrl=="https://tera-tools.com/embed"&&(e.siteUrl="https://dev.tera-tools.com/embed")}},siteUrl:"https://tera-tools.com/embed",restrictOrigin:"*",frameSandbox:["allow-forms","allow-modals","allow-orientation-lock","allow-pointer-lock","allow-popups","allow-popups-to-escape-sandbox","allow-presentation","allow-same-origin","allow-scripts","allow-top-navigation"],handshakeInterval:1e3,handshakeTimeout:1e4,debugPaths:null};this.events=po();this.dom={el:null,iframe:null,popup:null,stylesheet:null};this.methods=["handshake","setServerVerbosity","getUser","requireUser","getCredentials","getKindeToken","bindProject","getProject","getProjects","setActiveProject","requireProject","selectProject","getNamespace","setNamespace","listNamespaces","getProjectState","setProjectState","setProjectStateDefaults","setProjectStateRefresh","getProjectFileContents","deleteProjectFile","setProjectFileContents","createProjectFolder","deleteProjectFolder","selectProjectLibrary","getProjectLibrary","setProjectLibrary","projectLog","setPage","uiAlert","uiConfirm","uiJson","uiPanic","uiProgress","uiPrompt","uiThrow","uiSplat","uiWindow"];this.plugins=[];this.namespaces={};this.acceptPostboxes={};this.initPromise=null;e&&this.set(e)}send(e){let r=Kt();return this.acceptPostboxes[r]={},this.acceptPostboxes[r].promise=new Promise((o,a)=>{Object.assign(this.acceptPostboxes[r],{resolve:o,reject:a}),this.sendRaw({id:r,...e})}),this.acceptPostboxes[r].promise}sendRaw(e){let r;try{if(r={TERA:1,id:e.id||Kt(),...Gt(e)},this.settings.mode=="parent")window.parent.postMessage(r,this.settings.restrictOrigin);else if(this.settings.mode=="child")this.dom.iframe.contentWindow.postMessage(r,this.settings.restrictOrigin);else if(this.settings.mode=="popup")this.dom.popup.postMessage(r,this.settings.restrictOrigin);else throw this.settings.mode=="detect"?new Error("Call init() or detectMode() before trying to send data to determine the mode"):new Error(`Unknown TERA communication mode "${this.settings.mode}"`)}catch(o){throw this.debug("ERROR",1,"Message compose client->server:",o),this.debug("ERROR",1,"Attempted to dispatch payload client->server",r),o}}rpc(e,...r){return this.send({action:"rpc",method:e,args:r})}acceptMessage(e){if(e.origin==window.location.origin)return Promise.resolve();let r=e.data;return!r.TERA||!r.id?Promise.resolve():(this.debug("INFO",3,"Received message",r),(r==null?void 0:r.action)=="response"&&this.acceptPostboxes[r.id]?(r.isError===!0?this.acceptPostboxes[r.id].reject(r.response):this.acceptPostboxes[r.id].resolve(r.response),Promise.resolve()):(r==null?void 0:r.action)=="rpc"?Promise.resolve().then(()=>this[r.method].apply(this,r.args)).then(o=>this.sendRaw({id:r.id,action:"response",response:o})).catch(o=>{console.warn(`TERA-FY client threw on RPC:${r.method}:`,o),this.sendRaw({id:r.id,action:"response",isError:!0,response:o&&o.toString()})}):(r==null?void 0:r.action)=="event"?Promise.resolve().then(()=>this.events.emit(r.event,...r.payload)).catch(o=>{throw console.warn(`TERA-FY client threw while handling emitted event "${r.event}"`,{message:r}),o}):r!=null&&r.id?(this.debug("INFO",3,`Ignoring message ID ${r.id} - was meant for someone else?`),Promise.resolve()):(this.debug("INFO",3,"Unexpected incoming TERA-FY CLIENT message",{message:r}),Promise.resolve()))}mountNamespace(e){if(!/^[\w-]+$/.test(e))throw new Error("Namespaces must be alphanumeric + hyphens + underscores");return this.namespaces[e]?Promise.resolve(this.namespaces[e]):Promise.resolve().then(()=>this._mountNamespace(e)).then(()=>this.namespaces[e]||Promise.reject(`teraFy.mountNamespace('${e}') resolved but no namespace has been mounted`))}_mountNamespace(e){throw console.warn(`teraFy._mountNamespace() for ${e} has not been overridden by a TERA-fy plugin, load one to add this functionality for your preferred framework`),new Error("teraFy._mountNamespace() is not supported")}unmountNamespace(e){return this.namespaces[e]?this._unmountNamespace(e):Promise.resolve()}_unmountNamespace(e){console.warn(`teraFy.unbindNamespace() for ${e} has not been overridden by a TERA-fy plugin, load one to add this functionality for your preferred framework`)}init(e){if(e&&this.set(e),this.initPromise)return this.initPromise;window.addEventListener("message",this.acceptMessage.bind(this));let r=this;return this.initPromise=Promise.resolve().then(()=>{var o;return(o=this.settings).session||(o.session="tfy-"+this.getEntropicString(16))}).then(()=>this.debug("INFO",4,"[0/6] Init","Session",this.settings.session,"against",this.settings.siteUrl)).then(()=>{this.settings.devMode&&(this.settings.debugPaths?this.settings.debugPaths=this.settings.debugPaths.map(o=>Array.isArray(o)?o.join("."):typeof o=="string"?o:(()=>{throw new Error("Unknown path type - should be an array or string in dotted notation")})()):this.settings.debugPaths=null,this.debug("INFO",0,"Watching state paths",this.settings.debugPaths))}).then(()=>this.detectMode()).then(o=>{if(this.debug("INFO",4,"[1/6] Setting client mode to",o),this.settings.mode=o,this.settings.modeOverrides[o])return this.debug("INFO",4,"[1/6] Applying specific config overrides for mode",o),this.settings.modeOverrides[o](this.settings)}).then(()=>this.debug("INFO",4,"[2/6] Injecting comms + styles + methods")).then(()=>Promise.all([this.injectComms(),this.injectStylesheet(),this.injectMethods()])).then(()=>{if(this.settings.verbosity<=1){this.debug("INFO",4,"[3/6] Skip - Server verbosity is already at 1");return}else return this.debug("INFO",4,`[3/6] Set server verbosity to ${this.settings.verbosity}`),this.rpc("setServerVerbosity",this.settings.verbosity)}).then(()=>this.debug("INFO",4,`[4/6] Set server mode to "${this.settings.mode}"`)).then(()=>this.rpc("setServerMode",this.settings.mode=="child"?"embedded":this.settings.mode=="parent"?"frame":this.settings.mode=="popup"?"popup":(()=>{throw new Error(`Unknown server mode "${this.settings.mode}"`)})())).then(()=>this.debug("INFO",4,"[5/6] Run client plugins")).then(()=>Promise.all(this.plugins.map(o=>o.init.call(r,this.settings)))).then(()=>(this.debug("INFO",4,"[6/6] Init complete"),r)).catch(o=>{throw this.debug("WARN",0,"Init process fault",o),o}),this.initPromise}detectMode(){return this.settings.mode!="detect"?Promise.resolve(this.settings.mode):window.self===window.parent?Promise.resolve(this.settings.modeFallback):Promise.resolve().then(()=>this.settings.mode="parent").then(()=>new Promise((e,r)=>{let o=setTimeout(()=>r("TIMEOUT"),this.settings.modeTimeout);this.rpc("handshake").then(()=>clearTimeout(o)).then(()=>e()).catch(r)})).then(()=>"parent").catch(()=>this.settings.modeFallback)}injectComms(){switch(this.settings.mode){case"child":return Promise.resolve().then(()=>new Promise(e=>{this.debug("INFO",2,"Injecting TERA site as iFrame child"),this.dom.el=document.createElement("div"),this.dom.el.id="tera-fy",this.dom.el.classList.toggle("dev-mode",this.settings.devMode),this.dom.el.classList.add("minimized"),document.body.append(this.dom.el),this.dom.el.addEventListener("click",()=>this.dom.el.classList.toggle("minimized")),this.dom.iframe=document.createElement("iframe"),this.dom.iframe.setAttribute("sandbox",this.settings.frameSandbox.join(" ")),this.dom.iframe.addEventListener("load",()=>{this.debug("INFO",3,"Embedded iframe ready"),e()}),this.dom.iframe.src=this.settings.siteUrl,this.dom.el.append(this.dom.iframe)})).then(()=>this.handshakeLoop());case"parent":return this.debug("INFO",2,"Using TERA window parent"),Promise.resolve();case"popup":return this.debug("INFO",2,"Injecting TERA site as a popup window"),this.dom.popup=window.open(this.settings.siteUrl,"_blank","popup=1, location=0, menubar=0, status=0, scrollbars=0, width=500, height=600"),this.handshakeLoop().then(()=>this.debug("INFO",3,"Popup window accepted handshake"));default:throw new Error(`Unsupported mode "${this.settings.mode}" when calling injectComms()`)}}handshakeLoop(e){let r={handshakeInterval:this.settings.handshakeInterval,handshakeTimeout:this.settings.handshakeTimeout,...e};return new Promise((o,a)=>{let i=0,n,s=setTimeout(()=>{clearTimeout(n),a("TIMEOUT")},r.handshakeTimeout),u=()=>{this.debug("INFO",4,"Trying handshake",++i),clearTimeout(n),n=setTimeout(u,r.handshakeInterval),this.rpc("handshake").then(()=>{clearTimeout(s),clearTimeout(n)}).then(()=>o()).catch(a)};u()})}injectStylesheet(){switch(this.settings.mode){case"child":this.dom.stylesheet=document.createElement("style"),this.dom.stylesheet.innerHTML=[":root {","--TERA-accent: #4d659c;","}","#tera-fy {","display: none;","position: fixed;","right: 50px;","bottom: 50px;","width: 300px;","height: 150px;","background: transparent;","body:not(.tera-fy-focus) &.minimized.dev-mode {","background: var(--TERA-accent) !important;","opacity: 0.5;","right: 0px;","bottom: 0px;","width: 30px;","height: 30px;","transition: opacity 0.2s ease-out;","cursor: pointer;","border: none;","border-top-left-radius: 30px;","border-top: 2px solid var(--TERA-accent);","border-left: 2px solid var(--TERA-accent);","display: flex;","justify-content: center;","align-items: center;","&::before {","margin: 2px 0 0 0;",'content: "\u{1F300}";',"color: #FFF;","}","&:hover {","opacity: 1;","}","& > iframe {","display: none;","}","}","body:not(.tera-fy-focus) &:not(.minimized) {","&::before {","display: flex;","align-items: center;","justify-content: center;","cursor: pointer;","background: var(--TERA-accent) !important;","opacity: 0.5;","transition: opacity 0.2s ease-out;","position: absolute;","right: 0px;","bottom: 0px;","width: 20px;","height: 20px;","margin: 2px 0 0 0;",'content: "\u2B68";',"color: #FFF;","border: none;","border-top-left-radius: 30px;","border-top: 2px solid var(--TERA-accent);","border-left: 2px solid var(--TERA-accent);","}","&:hover::before {","opacity: 1;","}","}","&.dev-mode {","display: flex;","border: 5px solid var(--TERA-accent);","background: #FFF;","}","& > iframe {","width: 100%;","height: 100%;","}","}","body.tera-fy-focus {","overflow: hidden;","& #tera-fy {","display: flex !important;","position: fixed !important;","top: 0px !important;","width: 100vw !important;","height: 100vh !important;","left: 0px !important;","z-index: 10000 !important;","}","}"].join(`
2
- `),document.head.append(this.dom.stylesheet);break;case"parent":case"popup":break;default:throw new Error(`Unsupported mode "${this.settings.mode}" when injectStylesheet()`)}return Promise.resolve()}injectMethods(){this.methods.forEach(e=>this[e]=this.rpc.bind(this,e))}debug(...e){if(!this.settings.devMode||this.settings.verbosity<1)return;let r="log",o=1;typeof e[0]=="string"&&["INFO","LOG","WARN","ERROR"].includes(e[0])&&(r=e.shift().toLowerCase()),typeof e[0]=="number"&&(o=e[0],e.shift()),!(this.settings.verbosity<o)&&console[r]("%c[TERA-FY CLIENT]","font-weight: bold; color: #ff5722;",...e)}set(e,r,o){let a={ignoreNullish:!0,...o};return typeof e=="string"?(!a.ignoreNullish||r!=null)&&(this.settings[e]=r):Object.assign(this.settings,e),this.toggleDevMode(this.settings.devMode)}setIfDev(e,r,o){return!this.settings.devMode||r===void 0?this:this.set(e,r,o)}use(e,r){let o=typeof e=="function"?new e(this,r):typeof e=="object"?e:typeof e=="string"?(()=>{throw new Error("use(String) is not yet supported")})():(()=>{throw new Error("Expected use() call to be provided with a class initializer")})();return this.mixin(this,o),this.plugins.push(o),this}mixin(e,r){let o=[],a=r;do o.unshift(a);while(a=Object.getPrototypeOf(a));o.forEach(i=>Object.getOwnPropertyNames(i).filter(n=>!["constructor","init","prototype","name"].includes(n)&&!n.startsWith("__")).forEach(n=>{typeof r[n]=="function"?Object.defineProperty(e,n,{enumerable:!1,value:r[n].bind(e)}):e[n]=r[n]}))}toggleDevMode(e="toggle"){var r;return e==="toggle"?this.settings.devMode=!this.settings.devMode:e==="proxy"?Object.assign(this.settings,{devMode:!0,siteUrl:"http://localhost:7334/embed",mode:"child"}):this.settings.devMode=!!e,this.settings.devMode&&(this.settings.restrictOrigin="*"),(r=this.dom)!=null&&r.el&&this.dom.el.classList.toggle("dev-mode",this.settings.devMode),this}toggleFocus(e="toggle"){this.debug("INFO",2,"Request focus",{isFocused:e}),globalThis.document.body.classList.toggle("tera-fy-focus",e==="toggle"?void 0:e)}getEntropicString(e=32){let r=new Uint32Array(4);return window.crypto.getRandomValues(r),btoa(String.fromCodePoint(...new Uint8Array(r.buffer))).replace(/[+/]/g,"").slice(0,e)}selectProjectFile(e){return this.rpc("selectProjectFile",e).then(r=>r&&new _({tera:this,...r}))}getProjectFiles(e){return this.rpc("getProjectFiles",e).then(r=>r.map(o=>new _({tera:this,...o})))}getProjectFile(e,r){return this.rpc("getProjectFile",e,r).then(o=>o&&new _({tera:this,...o}))}createProjectFile(e){return this.rpc("createProjectFile",e).then(r=>r&&new _({tera:this,...r}))}moveProjectFile(e,r,o){return this.rpc("moveProjectFile",e,r,o).then(a=>a?new _({tera:this,...a}):null)}};export{$t as default};
2
+ `),document.head.append(this.dom.stylesheet);break;case"parent":case"popup":break;default:throw new Error(`Unsupported mode "${this.settings.mode}" when injectStylesheet()`)}return Promise.resolve()}injectMethods(){return this.methods.forEach(e=>this[e]=this.rpc.bind(this,e)),Promise.resolve()}debug(...e){if(!this.settings.devMode||this.settings.verbosity<1)return;let r="log",o=1;typeof e[0]=="string"&&["INFO","LOG","WARN","ERROR"].includes(e[0])&&(r=e.shift().toLowerCase()),typeof e[0]=="number"&&(o=e[0],e.shift()),!(this.settings.verbosity<o)&&console[r]("%c[TERA-FY CLIENT]","font-weight: bold; color: #ff5722;",...e)}set(e,r,o){let a={ignoreNullish:!0,...o};return typeof e=="string"?(!a.ignoreNullish||r!=null)&&(this.settings[e]=r):Object.assign(this.settings,e),this.toggleDevMode(this.settings.devMode)}setIfDev(e,r,o){return!this.settings.devMode||r===void 0?this:this.set(e,r,o)}use(e,r){let o=typeof e=="function"?new e(this,r):typeof e=="object"?e:typeof e=="string"?(()=>{throw new Error("use(String) is not yet supported")})():(()=>{throw new Error("Expected use() call to be provided with a class initializer")})();return this.mixin(this,o),this.plugins.push(o),this}mixin(e,r){let o=[],a=r;do o.unshift(a);while(a=Object.getPrototypeOf(a));o.forEach(i=>Object.getOwnPropertyNames(i).filter(n=>!["constructor","init","prototype","name"].includes(n)&&!n.startsWith("__")).forEach(n=>{typeof r[n]=="function"?Object.defineProperty(e,n,{enumerable:!1,value:r[n].bind(e)}):e[n]=r[n]}))}toggleDevMode(e="toggle"){var r;return e==="toggle"?this.settings.devMode=!this.settings.devMode:e==="proxy"?Object.assign(this.settings,{devMode:!0,siteUrl:"http://localhost:7334/embed",mode:"child"}):this.settings.devMode=!!e,this.settings.devMode&&(this.settings.restrictOrigin="*"),(r=this.dom)!=null&&r.el&&this.dom.el.classList.toggle("dev-mode",this.settings.devMode),this}toggleFocus(e="toggle"){this.debug("INFO",2,"Request focus",{isFocused:e}),globalThis.document.body.classList.toggle("tera-fy-focus",e==="toggle"?void 0:e)}getEntropicString(e=32){let r=new Uint32Array(4);return window.crypto.getRandomValues(r),btoa(String.fromCodePoint(...new Uint8Array(r.buffer))).replace(/[+/]/g,"").slice(0,e)}selectProjectFile(e){return this.rpc("selectProjectFile",e).then(r=>r&&new _({tera:this,...r}))}getProjectFiles(e){return this.rpc("getProjectFiles",e).then(r=>r.map(o=>new _({tera:this,...o})))}getProjectFile(e,r){return this.rpc("getProjectFile",e,r).then(o=>o&&new _({tera:this,...o}))}createProjectFile(e){return this.rpc("createProjectFile",e).then(r=>r&&new _({tera:this,...r}))}moveProjectFile(e,r,o){return this.rpc("moveProjectFile",e,r,o).then(a=>a?new _({tera:this,...a}):null)}};export{$t as default};
3
3
  /*! Bundled license information:
4
4
 
5
5
  lodash-es/lodash.js: