@convokitapp/chat-embed 1.2.0 → 1.3.0

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.
package/README.md CHANGED
@@ -125,9 +125,12 @@ the widget shows the cards your support agent sends:
125
125
  - **The welcome message**, if you set one up, is posted when a visitor opens a
126
126
  new chat: your greeting with up to three options shown as tiles, two per
127
127
  row. Tapping a tile sends that card straight away.
128
- - **"Talk to a person"** appears under the newest link or quick-reply card. It
129
- hands the conversation to your team and pauses automatic replies for 24
130
- hours.
128
+ - **AI answers**, if you turned on the AI agent and added FAQ entries, appear
129
+ as ordinary bubbles labelled "AI answer", so visitors know they are not
130
+ talking to a person.
131
+ - **"Talk to a person"** appears under the newest link, quick-reply card or AI
132
+ answer. It hands the conversation to your team and pauses automatic replies
133
+ for 24 hours.
131
134
  - **Handoff and "submitted" notices** appear as small centred lines, as does
132
135
  the reply sent when nothing matches ("Our support team will get back to
133
136
  you.", or your own wording).
package/dist/index.js CHANGED
@@ -194,6 +194,8 @@ header h2 { flex: 1; margin: 0; font-size: 15px; font-weight: 600; white-space:
194
194
  .option.chosen:disabled { opacity: 1; }
195
195
  .options.grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px; }
196
196
  .options.grid .option { border-radius: 10px; padding: 10px 8px; min-height: 44px; font-weight: 600; text-align: center; overflow-wrap: anywhere; }
197
+ .ai-label { font-size: 11px; font-weight: 600; color: var(--ck-muted); text-transform: uppercase; letter-spacing: .04em; }
198
+ .msg .bubble.ai { border: 1px solid var(--ck-border); }
197
199
  .escape { align-self: flex-start; border: 0; background: transparent; padding: 2px 0; color: var(--ck-muted); font-size: 12px; text-decoration: underline; }
198
200
  .escape:disabled { cursor: default; opacity: .6; }
199
201
  .card-error { color: var(--ck-danger); }
@@ -533,8 +535,9 @@ var ChatWidget = class {
533
535
  if (!mine && message.senderId !== previousSender) item.append(el("span", { className: "who", textContent: thread.names.get(message.senderId) ?? message.senderId }));
534
536
  if (card?.kind === "link") item.append(this.linkCard(message, card));
535
537
  else if (card?.kind === "quick_replies") item.append(this.quickReplies(thread, message, card, ordered));
538
+ else if (card?.kind === "answer") item.append(el("span", { className: "ai-label", textContent: "AI answer" }), el("div", { className: "bubble ai", textContent: message.text ?? "" }));
536
539
  else if (message.text) item.append(el("div", { className: "bubble", textContent: message.text }));
537
- if (latestCard === message && (card?.kind === "link" || card?.kind === "quick_replies")) item.append(this.escapeButton(thread, message));
540
+ if (latestCard === message && (card?.kind === "link" || card?.kind === "quick_replies" || card?.kind === "answer")) item.append(this.escapeButton(thread, message));
538
541
  const cardError = thread.cards.errors.get(message.id);
539
542
  if (cardError) item.append(el("span", { className: "meta card-error", textContent: cardError }));
540
543
  if (message.media.length) item.append(el("span", { className: "attachment", textContent: `\u{1F4CE} ${message.media.length === 1 ? "1 attachment" : `${message.media.length} attachments`}` }));
package/dist/main.js CHANGED
@@ -26,7 +26,7 @@ Request ID: ${c}`),l){let _=`
26
26
  Resources:`;for(let b of l){if(!b||typeof b!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${b}`);_+=`
27
27
  - ${b}`}w+=_}return`${m}
28
28
  ${w}`}var O=class extends Error{constructor({message:e,code:r,cause:s,name:n}){var i;super(e,{cause:s}),this.__isWebAuthnError=!0,this.name=(i=n??(s instanceof Error?s.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=r}toJSON(){return{name:this.name,message:this.message,code:this.code}}},Ie=class extends O{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}};function kn({error:t,options:e}){var r,s,n;let{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new O({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=i.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new O({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new O({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new O({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new O({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new O({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new O({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new O({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){let o=window.location.hostname;if(Ur(o)){if(i.rp.id!==o)return new O({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new O({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new O({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new O({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new O({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Tn({error:t,options:e}){let{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new O({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new O({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){let s=window.location.hostname;if(Ur(s)){if(r.rpId!==s)return new O({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new O({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new O({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new O({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}var jr=class{createNewAbortSignal(){if(this.controller){let r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}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}}},tr=new jr;function Lr(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);let{challenge:e,user:r,excludeCredentials:s}=t,n=be(t,["challenge","user","excludeCredentials"]),i=ye(e).buffer,o=Object.assign(Object.assign({},r),{id:ye(r.id).buffer}),a=Object.assign(Object.assign({},n),{challenge:i,user:o});if(s&&s.length>0){a.excludeCredentials=new Array(s.length);for(let c=0;c<s.length;c++){let l=s[c];a.excludeCredentials[c]=Object.assign(Object.assign({},l),{id:ye(l.id).buffer,type:l.type||"public-key",transports:l.transports})}}return a}function $r(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);let{challenge:e,allowCredentials:r}=t,s=be(t,["challenge","allowCredentials"]),n=ye(e).buffer,i=Object.assign(Object.assign({},s),{challenge:n});if(r&&r.length>0){i.allowCredentials=new Array(r.length);for(let o=0;o<r.length;o++){let a=r[o];i.allowCredentials[o]=Object.assign(Object.assign({},a),{id:ye(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return i}function Dr(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t;return{id:t.id,rawId:t.id,response:{attestationObject:he(new Uint8Array(t.response.attestationObject)),clientDataJSON:he(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Mr(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t,s=t.getClientExtensionResults(),n=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:he(new Uint8Array(n.authenticatorData)),clientDataJSON:he(new Uint8Array(n.clientDataJSON)),signature:he(new Uint8Array(n.signature)),userHandle:n.userHandle?he(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Ur(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function kt(){var t,e;return!!(j()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator?.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator?.credentials)===null||e===void 0?void 0:e.get)=="function")}async function qr(t){try{let e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ie("Browser returned unexpected credential type",e)}:{data:null,error:new Ie("Empty credential response",e)}}catch(e){return{data:null,error:kn({error:e,options:t})}}}async function Br(t){try{let e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ie("Browser returned unexpected credential type",e)}:{data:null,error:new Ie("Empty credential response",e)}}catch(e){return{data:null,error:Tn({error:e,options:t})}}}var zo={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},Jo={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Zt(...t){let e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),r=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),s={};for(let n of t)if(n)for(let i in n){let o=n[i];if(o!==void 0)if(Array.isArray(o))s[i]=o;else if(r(o))s[i]=o;else if(e(o)){let a=s[i];e(a)?s[i]=Zt(a,o):s[i]=Zt(o)}else s[i]=o}return s}function Xo(t,e){return Zt(zo,t,e||{})}function Yo(t,e){return Zt(Jo,t,e||{})}var er=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:r,friendlyName:s,signal:n},i){var o;try{let{data:a,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!a)return{data:null,error:c};let l=n??tr.createNewAbortSignal();if(a.webauthn.type==="create"){let{user:u}=a.webauthn.credential_options.publicKey;if(!u.name){let d=s;if(d)u.name=`${u.id}:${d}`;else{let h=(await this.client.getUser()).data.user,p=((o=h?.user_metadata)===null||o===void 0?void 0:o.name)||h?.email||h?.id||"User";u.name=`${u.id}:${p}`}}u.displayName||(u.displayName=u.name)}switch(a.webauthn.type){case"create":{let u=Xo(a.webauthn.credential_options.publicKey,i?.create),{data:d,error:f}=await qr({publicKey:u,signal:l});return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:f}}case"request":{let u=Yo(a.webauthn.credential_options.publicKey,i?.request),{data:d,error:f}=await Br(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:u,signal:l}));return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:f}}}}catch(a){return y(a)?{data:null,error:a}:{data:null,error:new q("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:s}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:s})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new ge("rpId is required for WebAuthn authentication")};try{if(!kt())return{data:null,error:new q("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:s},signal:n},{request:i});if(!o)return{data:null,error:a};let{webauthn:c}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:c.type,rpId:r,rpOrigins:s,credential_response:c.credential_response}})}catch(o){return y(o)?{data:null,error:o}:{data:null,error:new q("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new ge("rpId is required for WebAuthn registration")};try{if(!kt())return{data:null,error:new q("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(u=>{var d;return(d=u.data)===null||d===void 0?void 0:d.all.find(f=>f.factor_type==="webauthn"&&f.friendly_name===e&&f.status==="unverified")}).then(u=>u?this.client.mfa.unenroll({factorId:u?.id}):void 0),{data:null,error:a};let{data:c,error:l}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:r,rpOrigins:s},signal:n},{create:i});return c?this._verify({factorId:o.id,challengeId:c.challengeId,webauthn:{rpId:r,rpOrigins:s,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:l}}catch(o){return y(o)?{data:null,error:o}:{data:null,error:new q("Unexpected error in register",o)}}}};bn();var Qo={url:Ws,storageKey:Vs,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Gs,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};var Xe={},An=!1,rr=class t{get jwks(){var e,r;return(r=(e=Xe[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Xe[this.storageKey]=Object.assign(Object.assign({},Xe[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=Xe[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Xe[this.storageKey]=Object.assign(Object.assign({},Xe[this.storageKey]),{cachedAt:e})}constructor(e){var r,s,n;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this._pendingInitNotifications=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let i=Object.assign(Object.assign({},Qo),e);if(this.storageKey=i.storageKey,this.instanceID=(r=t.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,t.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&j()){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.experimental=(s=i.experimental)!==null&&s!==void 0?s:{},this.admin=new xe({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=Jt(i.fetch),this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock!=null&&(this.lock=i.lock,An||(An=!0,console.warn(`${this._logPrefix()} The "lock" option is deprecated and will be removed in v3. The client now coordinates session refreshes without a lock, so most apps can drop the option. See https://github.com/supabase/supabase-js/blob/master/packages/core/auth-js/migrations/lockless-coordination.md`))),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 er(this),recoveryCodes:{getStatus:this._getRecoveryCodesStatus.bind(this),generate:this._generateRecoveryCodes.bind(this),verify:this._verifyRecoveryCode.bind(this),regenerate:this._regenerateRecoveryCodes.bind(this),unenroll:this._unenrollRecoveryCodes.bind(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.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:zt()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Pr(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=Pr(this.memoryStorage)),j()&&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)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o),(o.data.event==="TOKEN_REFRESHED"||o.data.event==="SIGNED_IN")&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(a){this._debug("#broadcastChannel","error",a)}})}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} (${Ht}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){var e;if(this.initializePromise)return await this.initializePromise;this._pendingInitNotifications=[],this.initializePromise=(async()=>this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())();let r=await this.initializePromise,s=(e=this._pendingInitNotifications)!==null&&e!==void 0?e:[];this._pendingInitNotifications=null;for(let n of s)await this._notifyAllSubscribers(n.event,n.session,n.broadcast);return r}async _initialize(){var e;try{let r={},s="none";if(j()&&(r=Rr(window.location.href),this._isImplicitGrantCallback(r)?s="implicit":await this._isPKCECallback(r)&&(s="pkce")),j()&&this.detectSessionInUrl&&s!=="none"){let{data:n,error:i}=await this._getSessionFromURL(r,s);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Ys(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:a}=n;return this._debug("#_initialize()","detected session in URL",o,"redirect type",a),await this._saveSession(o),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return y(r)?this._returnResult({error:r}):this._returnResult({error:new q("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,s,n;try{let i=await v(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(n=e?.options)===null||n===void 0?void 0:n.captchaToken}},xform:V}),{data:o,error:a}=i;if(a||!o)return this._returnResult({data:{user:null,session:null},error:a});let c=o.session,l=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:l,session:c},error:null})}catch(i){if(y(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var r,s,n;let i=null;try{let o;if("email"in e){let{email:d,password:f,options:h}=e,p=null,g=null;this.flowType==="pkce"&&([p,g,i]=await this._getCodeChallengeAndMethod()),o=await v(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(h?.emailRedirectTo,i),body:{email:d,password:f,data:(r=h?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:h?.captchaToken},code_challenge:p,code_challenge_method:g},xform:V})}else if("phone"in e){let{phone:d,password:f,options:h}=e;o=await v(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:d,password:f,data:(s=h?.data)!==null&&s!==void 0?s:{},channel:(n=h?.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:h?.captchaToken}},xform:V})}else throw new Se("You must provide either an email or phone number and a password");let{data:a,error:c}=o;if(c||!a)return await z(this.storage,this.storageKey,i),this._returnResult({data:{user:null,session:null},error:c});let l=a.session,u=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(o){if(await z(this.storage,this.storageKey,i),y(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async signInWithPassword(e){try{let r;if("email"in e){let{email:i,password:o,options:a}=e;r=await v(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Ir})}else if("phone"in e){let{phone:i,password:o,options:a}=e;r=await v(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Ir})}else throw new Se("You must provide either an email or phone number and a password");let{data:s,error:n}=r;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!s||!s.session||!s.user){let i=new de;return this._returnResult({data:{user:null,session:null},error:i})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:n})}catch(r){if(y(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,s,n,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e,r){return await this.initializePromise,this.lock!=null?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e,r)):this._exchangeCodeForSession(e,r)}async signInWithWeb3(e){let{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,s,n,i,o,a,c,l,u,d,f;let h,p;if("message"in e)h=e.message,p=e.signature;else{let{chain:g,wallet:m,statement:w,options:_}=e,b;if(j())if(typeof m=="object")b=m;else{let ce=window;if("ethereum"in ce&&typeof ce.ethereum=="object"&&"request"in ce.ethereum&&typeof ce.ethereum.request=="function")b=ce.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 m!="object"||!_?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");b=m}let A=new URL((r=_?.url)!==null&&r!==void 0?r:window.location.href),B=await b.request({method:"eth_requestAccounts"}).then(ce=>ce).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!B||B.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let C=Nr(B[0]),I=(s=_?.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!I){let ce=await b.request({method:"eth_chainId"});I=_n(ce)}let Ze={domain:A.host,address:C,statement:w,uri:A.href,version:"1",chainId:I,nonce:(n=_?.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(o=(i=_?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=_?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(c=_?.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(l=_?.signInWithEthereum)===null||l===void 0?void 0:l.requestId,resources:(u=_?.signInWithEthereum)===null||u===void 0?void 0:u.resources};h=Sn(Ze),p=await b.request({method:"personal_sign",params:[En(h),C]})}try{let{data:g,error:m}=await v(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:h,signature:p},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:V});if(m)throw m;if(!g||!g.session||!g.user){let w=new de;return this._returnResult({data:{user:null,session:null},error:w})}return g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("SIGNED_IN",g.session)),this._returnResult({data:Object.assign({},g),error:m})}catch(g){if(y(g))return this._returnResult({data:{user:null,session:null},error:g});throw g}}async signInWithSolana(e){var r,s,n,i,o,a,c,l,u,d,f,h;let p,g;if("message"in e)p=e.message,g=e.signature;else{let{chain:m,wallet:w,statement:_,options:b}=e,A;if(j())if(typeof w=="object")A=w;else{let C=window;if("solana"in C&&typeof C.solana=="object"&&("signIn"in C.solana&&typeof C.solana.signIn=="function"||"signMessage"in C.solana&&typeof C.solana.signMessage=="function"))A=C.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 w!="object"||!b?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");A=w}let B=new URL((r=b?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in A&&A.signIn){let C=await A.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},b?.signInWithSolana),{version:"1",domain:B.host,uri:B.href}),_?{statement:_}:null)),I;if(Array.isArray(C)&&C[0]&&typeof C[0]=="object")I=C[0];else if(C&&typeof C=="object"&&"signedMessage"in C&&"signature"in C)I=C;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in I&&"signature"in I&&(typeof I.signedMessage=="string"||I.signedMessage instanceof Uint8Array)&&I.signature instanceof Uint8Array)p=typeof I.signedMessage=="string"?I.signedMessage:new TextDecoder().decode(I.signedMessage),g=I.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in A)||typeof A.signMessage!="function"||!("publicKey"in A)||typeof A!="object"||!A.publicKey||!("toBase58"in A.publicKey)||typeof A.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=[`${B.host} wants you to sign in with your Solana account:`,A.publicKey.toBase58(),..._?["",_,""]:[""],"Version: 1",`URI: ${B.href}`,`Issued At: ${(n=(s=b?.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((i=b?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${b.signInWithSolana.notBefore}`]:[],...!((o=b?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${b.signInWithSolana.expirationTime}`]:[],...!((a=b?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${b.signInWithSolana.chainId}`]:[],...!((c=b?.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${b.signInWithSolana.nonce}`]:[],...!((l=b?.signInWithSolana)===null||l===void 0)&&l.requestId?[`Request ID: ${b.signInWithSolana.requestId}`]:[],...!((d=(u=b?.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||d===void 0)&&d.length?["Resources",...b.signInWithSolana.resources.map(I=>`- ${I}`)]:[]].join(`
29
- `);let C=await A.signMessage(new TextEncoder().encode(p),"utf8");if(!C||!(C instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");g=C}}try{let{data:m,error:w}=await v(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:he(g)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(h=e.options)===null||h===void 0?void 0:h.captchaToken}}:null),xform:V});if(w)throw w;if(!m||!m.session||!m.user){let _=new de;return this._returnResult({data:{user:null,session:null},error:_})}return m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("SIGNED_IN",m.session)),this._returnResult({data:Object.assign({},m),error:w})}catch(m){if(y(m))return this._returnResult({data:{user:null,session:null},error:m});throw m}}async _exchangeCodeForSession(e,r){let s=r?.flowId!=null,n=s?St(r?.flowId):j()?St(Rr(window.location.href)[ue]):null;s&&!n&&this._debug("#_exchangeCodeForSession()","provided flowId is not a valid flow id",r?.flowId);let{verifier:i,flowId:o}=s&&!n?{verifier:null,flowId:null}:await cn(this.storage,this.storageKey,n),[a,c]=(i??"").split("/");try{if(!a&&this.flowType==="pkce")throw new Wt;let{data:l,error:u}=await v(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:a},xform:V});if(await z(this.storage,this.storageKey,o),u)throw u;if(!l||!l.session||!l.user){let d=new de;return this._returnResult({data:{user:null,session:null,redirectType:null},error:d})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers(c==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l.session)),this._returnResult({data:Object.assign(Object.assign({},l),{redirectType:c??null}),error:u})}catch(l){if(await z(this.storage,this.storageKey,o),y(l))return this._returnResult({data:{user:null,session:null,redirectType:null},error:l});throw l}}async signInWithIdToken(e){try{let{options:r,provider:s,token:n,access_token:i,nonce:o}=e,a=await v(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:n,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:V}),{data:c,error:l}=a;if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!c||!c.session||!c.user){let u=new de;return this._returnResult({data:{user:null,session:null},error:u})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:l})}catch(r){if(y(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,s,n,i,o;let a=null;try{if("email"in e){let{email:c,options:l}=e,u=null,d=null;this.flowType==="pkce"&&([u,d,a]=await this._getCodeChallengeAndMethod());let{error:f}=await v(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:c,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:u,code_challenge_method:d},redirectTo:this._maybeAppendFlowIdToRedirect(l?.emailRedirectTo,a)});return this._returnResult({data:{user:null,session:null},error:f})}if("phone"in e){let{phone:c,options:l}=e,{data:u,error:d}=await v(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:c,data:(n=l?.data)!==null&&n!==void 0?n:{},create_user:(i=l?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u?.message_id},error:d})}throw new Se("You must provide either an email or phone number.")}catch(c){if(await z(this.storage,this.storageKey,a),y(c))return this._returnResult({data:{user:null,session:null},error:c});throw c}}async verifyOtp(e){var r,s;try{let n,i;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,i=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:o,error:a}=await v(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:V});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,l=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:l,session:c},error:null})}catch(n){if(y(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,s,n,i;let o=null;try{let a=null,c=null;this.flowType==="pkce"&&([a,c,o]=await this._getCodeChallengeAndMethod());let l=await v(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:this._maybeAppendFlowIdToRedirect((r=e.options)===null||r===void 0?void 0:r.redirectTo,o)}),!((s=e?.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:c}),headers:this.headers,xform:vn});return!((n=l.data)===null||n===void 0)&&n.url&&j()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(l.data.url),this._returnResult(l)}catch(a){if(await z(this.storage,this.storageKey,o),y(a))return this._returnResult({data:null,error:a});throw a}}async reauthenticate(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:r},error:s}=e;if(s)throw s;if(!r)throw new P;let{error:n}=await v(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(y(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){let r=null;try{let s=`${this.url}/resend`;if("email"in e){let{email:n,type:i,options:o}=e,a=null,c=null;this.flowType==="pkce"&&([a,c,r]=await this._getCodeChallengeAndMethod());let{error:l}=await v(this.fetch,"POST",s,{headers:this.headers,body:{email:n,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken},code_challenge:a,code_challenge_method:c},redirectTo:this._maybeAppendFlowIdToRedirect(o?.emailRedirectTo,r)});return l&&await z(this.storage,this.storageKey,r),this._returnResult({data:{user:null,session:null},error:l})}else if("phone"in e){let{phone:n,type:i,options:o}=e,{data:a,error:c}=await v(this.fetch,"POST",s,{headers:this.headers,body:{phone:n,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:a?.message_id},error:c})}throw new Se("You must provide either an email or phone number and a type")}catch(s){if(await z(this.storage,this.storageKey,r),y(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async getSession(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e)):await this._useSession(async e=>e)}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await s,await r()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let s=r();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){let n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await s}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 r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lock!=null&&!this.lockAcquired&&this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,r=await D(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let s=e.expires_at?e.expires_at*1e3-Date.now()<Ft:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s)return{data:{session:await this._hydrateSessionUser(e)},error:null};let{data:n,error:i}=await this._callRefreshToken(e.refresh_token);if(i){let o=await D(this.storage,this.storageKey);return o&&this._isValidSession(o)&&o.expires_at&&o.expires_at*1e3>Date.now()?this._returnResult({data:{session:await this._hydrateSessionUser(o)},error:null}):this._returnResult({data:{session:null},error:i})}return this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async _hydrateSessionUser(e){if(this.userStorage){let r=await D(this.userStorage,this.storageKey+"-user");e.user=r?.user?r.user:Xt()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let r={value:this.suppressGetSessionWarning};e.user=gn(e.user,r),r.value&&(this.suppressGetSessionWarning=!0)}return e}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let r;return this.lock!=null?r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):r=await this._getUser(),r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await v(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ie}):await this._useSession(async r=>{var s,n,i;let{data:o,error:a}=r;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new P}:await v(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=o.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:ie})})}catch(r){if(y(r))return vt(r)&&await this._removeSession(),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r)):await this._updateUser(e,r)}async _updateUser(e,r={}){let s=null;try{return await this._useSession(async n=>{let{data:i,error:o}=n;if(o)throw o;if(!i.session)throw new P;let a=i.session,c=null,l=null;this.flowType==="pkce"&&e.email!=null&&([c,l,s]=await this._getCodeChallengeAndMethod());let{data:u,error:d}=await v(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(r?.emailRedirectTo,s),body:Object.assign(Object.assign({},e),{code_challenge:c,code_challenge_method:l}),jwt:a.access_token,xform:ie});if(d)throw d;return a.user=u.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),this._returnResult({data:{user:a.user},error:null})})}catch(n){if(await z(this.storage,this.storageKey,s),y(n))return this._returnResult({data:{user:null},error:n});throw n}}async setSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e)):await this._setSession(e)}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new P;let r=Date.now()/1e3,s=r,n=!0,i=null,{payload:o}=Et(e.access_token);if(o.exp&&(s=o.exp,n=s<=r),n){let{data:a,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!a)return{data:{user:null,session:null},error:null};i=a}else{let{data:a,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:a.user,token_type:"bearer",expires_in:s-r,expires_at:s},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(r){if(y(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e)):await this._refreshSession(e)}async _refreshSession(e){try{return await this._useSession(async r=>{var s;if(!e){let{data:o,error:a}=r;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new P;let{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(y(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){var s;try{if(!j())throw new ke("No browser detected.");if(e.error||e.error_description||e.error_code)throw new ke(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new gt("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new ke("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new gt("No code detected.");let{data:b,error:A}=await this._exchangeCodeForSession(e.code,{flowId:e[ue]});if(A)throw A;let B=new URL(window.location.href);return B.searchParams.delete("code"),B.searchParams.delete(ue),window.history.replaceState(window.history.state,"",B.toString()),{data:{session:b.session,redirectType:(s=b.redirectType)!==null&&s!==void 0?s:null},error:null}}let{provider_token:n,provider_refresh_token:i,access_token:o,refresh_token:a,expires_in:c,expires_at:l,token_type:u}=e;if(!o||!c||!a||!u)throw new ke("No session defined in URL");let d=Math.round(Date.now()/1e3),f=parseInt(c),h=d+f;l&&(h=parseInt(l));let p=h-d;p*1e3<=re&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${f}s`);let g=h-f;d-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,h,d):d-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",g,h,d);let{data:m,error:w}=await this._getUser(o);if(w)throw w;let _={provider_token:n,provider_refresh_token:i,access_token:o,expires_in:f,expires_at:h,refresh_token:a,token_type:u,user:m.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:_,redirectType:e.type},error:null})}catch(n){if(y(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||e.error_description||e.error_code)}async _isPKCECallback(e){if(!e.code)return!1;let r=St(e[ue]);return r&&await D(this.storage,Re(this.storageKey,r))?!0:!!await D(this.storage,`${this.storageKey}-code-verifier`)}async signOut(e={scope:"global"}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e)):await this._signOut(e)}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var s;let n=async()=>{await this._removeSession()},{data:i,error:o}=r;if(o&&!vt(o))return this._returnResult({error:o});let a=(s=i.session)===null||s===void 0?void 0:s.access_token;if(a){let{error:c}=await this.admin.signOut(a,e);if(c&&!(kr(c)&&(c.status===404||c.status===401||c.status===403)||vt(c)))return e!=="others"&&await n(),this._returnResult({error:c})}return e!=="others"&&await n(),this._returnResult({error:null})})}onAuthStateChange(e){let r=rn(),s={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,s),(async()=>(await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)}):await this._emitInitialSession(r)))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async r=>{var s,n;try{let{data:{session:i},error:o}=r;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){if(await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),Tr(i))return;vt(i)||wt(i)||kr(i)&&(i.code==="refresh_token_not_found"||i.code==="refresh_token_already_used"||i.code==="session_expired")?console.warn(i):console.error(i)}})}async resetPasswordForEmail(e,r={}){let s=null,n=null,i=null;this.flowType==="pkce"&&([s,n,i]=await this._getCodeChallengeAndMethod(!0));try{return await v(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(r.redirectTo,i)})}catch(o){if(await z(this.storage,this.storageKey,i),y(o))return this._returnResult({data:null,error:o});throw o}}async getUserIdentities(){var e;try{let{data:r,error:s}=await this.getUser();if(s)throw s;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;let s=null;try{let{data:n,error:i}=await this._useSession(async o=>{var a,c,l,u,d;let{data:f,error:h}=o;if(h)throw h;let{url:p,flowId:g}=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(a=e.options)===null||a===void 0?void 0:a.redirectTo,scopes:(c=e.options)===null||c===void 0?void 0:c.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return s=g,await v(this.fetch,"GET",p,{headers:this.headers,jwt:(d=(u=f.session)===null||u===void 0?void 0:u.access_token)!==null&&d!==void 0?d:void 0})});if(i)throw i;return j()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n?.url),this._returnResult({data:{provider:e.provider,url:n?.url,flowId:s},error:null})}catch(n){if(y(n))return this._returnResult({data:{provider:e.provider,url:null,flowId:s},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var s;try{let{error:n,data:{session:i}}=r;if(n)throw n;let{options:o,provider:a,token:c,access_token:l,nonce:u}=e,d=await v(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=i?.access_token)!==null&&s!==void 0?s:void 0,body:{provider:a,id_token:c,access_token:l,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:V}),{data:f,error:h}=d;return h?this._returnResult({data:{user:null,session:null},error:h}):!f||!f.session||!f.user?this._returnResult({data:{user:null,session:null},error:new de}):(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("USER_UPDATED",f.session)),this._returnResult({data:f,error:h}))}catch(n){if(await z(this.storage,this.storageKey,null),y(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var s,n;let{data:i,error:o}=r;if(o)throw o;return await v(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(s=i.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){let r="#_refreshAccessToken()";this._debug(r,"begin");try{let s=Date.now();return await on(async n=>(n>0&&await nn(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await v(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:V})),(n,i)=>{let o=200*Math.pow(2,n);return i&&wt(i)&&Date.now()+o-s<re})}catch(s){if(this._debug(r,"error",s),y(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){let{url:s,flowId:n}=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",s),j()&&!r.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s,flowId:n},error:null}}async _recoverAndRefresh(){var e,r;let s="#_recoverAndRefresh()";this._debug(s,"begin");try{let n=await D(this.storage,this.storageKey);if(n&&this.userStorage){let o=await D(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:n.user},await se(this.userStorage,this.storageKey+"-user",o)),n.user=(e=o?.user)!==null&&e!==void 0?e:Xt()}else if(n&&!n.user&&!n.user){let o=await D(this.storage,this.storageKey+"-user");o&&o?.user?(n.user=o.user,await H(this.storage,this.storageKey+"-user"),await se(this.storage,this.storageKey,n)):n.user=Xt()}if(this._debug(s,"session from storage",n),!this._isValidSession(n)){this._debug(s,"session is not valid"),n!==null&&await this._removeSession();return}let i=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<Ft;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${Ft}s`),i){if(this.autoRefreshToken&&n.refresh_token){let{error:o}=await this._callRefreshToken(n.refresh_token);o&&(Tr(o)?this._debug(s,"refresh discarded by commit guard",o):this._debug(s,"refresh failed",o))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{let{data:o,error:a}=await this._getUser(n.access_token);!a&&o?.user?(n.user=o.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(s,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(s,"error",n),wt(n)?console.warn(n):console.error(n);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var r,s;if(!e)throw new P;if(this.refreshingDeferred)return this.refreshingDeferred.promise;if(this.lastRefreshFailure&&this.lastRefreshFailure.refreshToken===e&&Date.now()<this.lastRefreshFailure.expiresAt)return this._debug("#_callRefreshToken()","returning cached failure (cooldown active)"),this.lastRefreshFailure.result;let n="#_callRefreshToken()";this._debug(n,"begin");try{this.refreshingDeferred=new bt,this.refreshingDeferred.promise.then(void 0,()=>{});let i=await D(this.storage,this.storageKey),{data:o,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!o.session)throw new P;let c=await D(this.storage,this.storageKey);if(i!==null&&(c===null||c.refresh_token!==i.refresh_token)){this._debug(n,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:c?"replaced":"cleared"});let f={data:null,error:new mt};return this.refreshingDeferred.resolve(f),f}let u=this._sessionRemovalEpoch;if(await this._saveSession(o.session),this._sessionRemovalEpoch!==u){this._debug(n,"commit guard (post-save): _removeSession ran during _saveSession, undoing write"),await H(this.storage,this.storageKey),this.userStorage&&await H(this.userStorage,this.storageKey+"-user");let f={data:null,error:new mt};return this.refreshingDeferred.resolve(f),f}await this._notifyAllSubscribers("TOKEN_REFRESHED",o.session);let d={data:o.session,error:null};return this.lastRefreshFailure=null,this.refreshingDeferred.resolve(d),d}catch(i){if(this._debug(n,"error",i),y(i)){let o={data:null,error:i};if(!wt(i)){let a=await D(this.storage,this.storageKey);!!(a?.expires_at&&a.expires_at*1e3>Date.now())?this._debug(n,"proactive refresh failed, access token still valid \u2014 preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:o,expiresAt:Date.now()+Ks},(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,s=!0){if(this._pendingInitNotifications!==null&&s){this._pendingInitNotifications.push({event:e,session:r,broadcast:s});return}let n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:r});let i=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r)}catch(c){i.push(c)}});if(await Promise.all(o),i.length>0){for(let a=0;a<i.length;a+=1)console.error(i[a]);throw i[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0;let r=Object.assign({},e),s=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&r.user&&await se(this.userStorage,this.storageKey+"-user",{user:r.user});let n=Object.assign({},r);delete n.user;let i=xr(n);await se(this.storage,this.storageKey,i)}else{let n=xr(r);await se(this.storage,this.storageKey,n)}}async _removeSession(){this._sessionRemovalEpoch+=1,this._debug("#_removeSession()"),this.lastRefreshFailure=null,this.suppressGetSessionWarning=!1,await H(this.storage,this.storageKey),await ln(this.storage,this.storageKey),await H(this.storage,this.storageKey+"-user"),this.userStorage&&await H(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&j()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),re);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(e=this.broadcastChannel)===null||e===void 0||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),this.lock!=null){try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async r=>{let{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((s.expires_at*1e3-e)/re);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${re}ms, refresh threshold is ${ze} ticks`),n<=ze&&await this._callRefreshToken(s.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof Qt)this._debug("auto refresh token tick lock not available");else throw e}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{let e=Date.now();try{await this._useSession(async r=>{let{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((s.expires_at*1e3-e)/re);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${re}ms, refresh threshold is ${ze} ticks`),n<=ze&&await this._callRefreshToken(s.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!j()||!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?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let r=`#_onVisibilityChanged(${e})`;if(this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"){if(this.autoRefreshToken&&this._startAutoRefresh(),!e)if(await this.initializePromise,this.lock!=null)await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()});else{if(document.visibilityState!=="visible"){this._debug(r,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}else document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,s){let n=s?.redirectTo,i=null,o=null,a=null;this.flowType==="pkce"&&([i,o,a]=await this._getCodeChallengeAndMethod(),n=this._maybeAppendFlowIdToRedirect(n,a));let c=[`provider=${encodeURIComponent(r)}`];if(n&&c.push(`redirect_to=${encodeURIComponent(n)}`),s?.scopes&&c.push(`scopes=${encodeURIComponent(s.scopes)}`),i!=null&&o!=null){let l=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});c.push(l.toString())}if(s?.queryParams){let l=new URLSearchParams(s.queryParams);c.push(l.toString())}return s?.skipBrowserRedirect&&c.push(`skip_http_redirect=${s.skipBrowserRedirect}`),{url:`${e}?${c.join("&")}`,flowId:a}}_maybeAppendFlowIdToRedirect(e,r){return!e||!r||!this.experimental.appendPkceFlowIdToRedirects?e??void 0:un(e,r)}async _getCodeChallengeAndMethod(e=!1){return dn(this.storage,this.storageKey,e,r=>this._debug("#_getCodeChallengeAndMethod()","evicted oldest pending PKCE verifier slot",r))}async _unenroll(e){try{return await this._useSession(async r=>{var s;let{data:n,error:i}=r;return i?this._returnResult({data:null,error:i}):await v(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var s,n;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:l}=await v(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return l?this._returnResult({data:null,error:l}):(e.factorType==="totp"&&c.type==="totp"&&(!((n=c?.totp)===null||n===void 0)&&n.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){let r=async()=>{try{return await this._useSession(async s=>{var n;let{data:i,error:o}=s;if(o)return this._returnResult({data:null,error:o});let a=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Dr(e.webauthn.credential_response):Mr(e.webauthn.credential_response)})}:{code:e.code}),{data:c,error:l}=await v(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:a,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});return l?this._returnResult({data:null,error:l}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+c.expires_in},c)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",c),this._returnResult({data:c,error:l}))})}catch(s){if(y(s))return this._returnResult({data:null,error:s});throw s}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _challenge(e){let r=async()=>{try{return await this._useSession(async s=>{var n;let{data:i,error:o}=s;if(o)return this._returnResult({data:null,error:o});let a=await v(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});if(a.error)return a;let{data:c}=a;if(c.type!=="webauthn")return{data:c,error:null};switch(c.webauthn.type){case"create":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:Lr(c.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:$r(c.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(s){if(y(s))return this._returnResult({data:null,error:s});throw s}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _challengeAndVerify(e){let{data:r,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};let n={all:[],phone:[],totp:[],webauthn:[],recovery_code:[]};for(let i of(e=r?.factors)!==null&&e!==void 0?e:[])n.all.push(i),i.status==="verified"&&i.factor_type in n&&Array.isArray(n[i.factor_type])&&n[i.factor_type].push(i);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,s,n,i;if(e)try{let{payload:h}=Et(e),p=null;h.aal&&(p=h.aal);let g=p,{data:{user:m},error:w}=await this.getUser(e);if(w)return this._returnResult({data:null,error:w});((s=(r=m?.factors)===null||r===void 0?void 0:r.filter(A=>A.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(g="aal2");let b=h.amr||[];return{data:{currentLevel:p,nextLevel:g,currentAuthenticationMethods:b},error:null}}catch(h){if(y(h))return this._returnResult({data:null,error:h});throw h}let{data:{session:o},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:c}=Et(o.access_token),l=null;c.aal&&(l=c.aal);let u=l;((i=(n=o.user.factors)===null||n===void 0?void 0:n.filter(h=>h.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(u="aal2");let f=c.amr||[];return{data:{currentLevel:l,nextLevel:u,currentAuthenticationMethods:f},error:null}}async _getRecoveryCodesStatus(){Je(this.experimental);try{return await this._useSession(async e=>{var r;let{data:s,error:n}=e;if(n)return this._returnResult({data:null,error:n});let{data:i,error:o}=await v(this.fetch,"GET",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(y(e))return this._returnResult({data:null,error:e});throw e}}async _generateRecoveryCodes(e){Je(this.experimental);try{return await this._useSession(async r=>{var s;let{data:n,error:i}=r;if(i)return this._returnResult({data:null,error:i});let{data:o,error:a}=await v(this.fetch,"POST",`${this.url}/factors/recovery-codes`,{body:e?.friendlyName?{friendly_name:e.friendlyName}:void 0,headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return a?this._returnResult({data:null,error:a}):this._returnResult({data:o,error:null})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _verifyRecoveryCode(e){Je(this.experimental);let r=async()=>{try{return await this._useSession(async s=>{var n;let{data:i,error:o}=s;if(o)return this._returnResult({data:null,error:o});let{data:a,error:c}=await v(this.fetch,"POST",`${this.url}/factors/recovery-codes/verify`,{body:{code:e.code},headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});if(c)return this._returnResult({data:null,error:c});let l=Object.assign({expires_at:Gt(a.expires_in)},a);return await this._saveSession(l),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",l),this._returnResult({data:a,error:null})})}catch(s){if(y(s))return this._returnResult({data:null,error:s});throw s}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _regenerateRecoveryCodes(){Je(this.experimental);try{return await this._useSession(async e=>{var r;let{data:s,error:n}=e;if(n)return this._returnResult({data:null,error:n});let{data:i,error:o}=await v(this.fetch,"POST",`${this.url}/factors/recovery-codes/regenerate`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(y(e))return this._returnResult({data:null,error:e});throw e}}async _unenrollRecoveryCodes(){Je(this.experimental);try{return await this._useSession(async e=>{var r;let{data:s,error:n}=e;if(n)return this._returnResult({data:null,error:n});let{data:i,error:o}=await v(this.fetch,"DELETE",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(y(e))return this._returnResult({data:null,error:e});throw e}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?await v(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:s.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new P})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async s=>{let{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new P});let o=await v(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&j()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(s){if(y(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(e,r){try{return await this._useSession(async s=>{let{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new P});let o=await v(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&j()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(s){if(y(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:s}=e;return s?this._returnResult({data:null,error:s}):r?await v(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new P})})}catch(e){if(y(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?(await v(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:s.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new P})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let s=r.keys.find(a=>a.kid===e);if(s)return s;let n=Date.now();if(s=this.jwks.keys.find(a=>a.kid===e),s&&this.jwks_cached_at+Xs>n)return s;let{data:i,error:o}=await v(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=n,s=i.keys.find(a=>a.kid===e),!s)?null:s}async getClaims(e,r={}){try{let s=e;if(!s){let{data:h,error:p}=await this.getSession();if(p||!h.session)return this._returnResult({data:null,error:p});s=h.session.access_token}let{header:n,payload:i,signature:o,raw:{header:a,payload:c}}=Et(s);if(!r?.allowExpired)try{fn(i.exp)}catch(h){throw new me(h instanceof Error?h.message:"JWT validation failed")}let l=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!l){let{error:h}=await this.getUser(s);if(h)throw h;return{data:{claims:i,header:n,signature:o},error:null}}let u=pn(n.alg),d=await crypto.subtle.importKey("jwk",l,u,!0,["verify"]);if(!await crypto.subtle.verify(u,d,o,tn(`${a}.${c}`)))throw new me("Invalid JWT signature");return{data:{claims:i,header:n,signature:o},error:null}}catch(s){if(y(s))return this._returnResult({data:null,error:s});throw s}}async signInWithPasskey(e){var r,s,n,i;try{if(!kt())return this._returnResult({data:null,error:new q("Browser does not support WebAuthn",null)});let{data:o,error:a}=await this._startPasskeyAuthentication({options:{captchaToken:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}});if(a||!o)return this._returnResult({data:null,error:a});let c=$r(o.options),l=(n=(s=e?.options)===null||s===void 0?void 0:s.signal)!==null&&n!==void 0?n:tr.createNewAbortSignal(),{data:u,error:d}=await Br({publicKey:c,signal:l,mediation:(i=e?.options)===null||i===void 0?void 0:i.mediation});if(d||!u)return this._returnResult({data:null,error:d??new q("WebAuthn ceremony failed",null)});let f=Mr(u);return this._verifyPasskeyAuthentication({challengeId:o.challenge_id,credential:f})}catch(o){if(y(o))return this._returnResult({data:null,error:o});throw o}}async registerPasskey(e){var r,s;try{if(!kt())return this._returnResult({data:null,error:new q("Browser does not support WebAuthn",null)});let{data:n,error:i}=await this._startPasskeyRegistration();if(i||!n)return this._returnResult({data:null,error:i});let o=Lr(n.options),a=(s=(r=e?.options)===null||r===void 0?void 0:r.signal)!==null&&s!==void 0?s:tr.createNewAbortSignal(),{data:c,error:l}=await qr({publicKey:o,signal:a});if(l||!c)return this._returnResult({data:null,error:l??new q("WebAuthn ceremony failed",null)});let u=Dr(c);return this._verifyPasskeyRegistration({challengeId:n.challenge_id,credential:u})}catch(n){if(y(n))return this._returnResult({data:null,error:n});throw n}}async _startPasskeyRegistration(){try{return await this._useSession(async e=>{let{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new P});let{data:n,error:i}=await v(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:r.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(e){if(y(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new P});let{data:i,error:o}=await v(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:s.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _startPasskeyAuthentication(e){var r;try{let{data:s,error:n}=await v(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}}});return n?this._returnResult({data:null,error:n}):this._returnResult({data:s,error:null})}catch(s){if(y(s))return this._returnResult({data:null,error:s});throw s}}async _verifyPasskeyAuthentication(e){try{let{data:r,error:s}=await v(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:V});return s?this._returnResult({data:null,error:s}):(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:r,error:null}))}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _listPasskeys(){try{return await this._useSession(async e=>{let{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new P});let{data:n,error:i}=await v(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:r.access_token,xform:o=>({data:o,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(e){if(y(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new P});let{data:i,error:o}=await v(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:s.access_token,body:{friendly_name:e.friendlyName}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _deletePasskey(e){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new P});let{error:i}=await v(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:s.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}};rr.nextInstanceID={};var Hr=rr;var Zo=Hr,Fr=Zo;var ea="2.118.0",Tt="",ir;if(typeof Deno<"u")Tt="deno",ir=(sr=Deno.version)===null||sr===void 0?void 0:sr.deno;else if(typeof document<"u")Tt="web";else if(typeof navigator<"u"&&navigator.product==="ReactNative")Tt="react-native";else{Tt="node";let t=globalThis.process;ir=t==null||(nr=t.version)===null||nr===void 0?void 0:nr.replace(/^v/,"")}var sr,nr,Un=[`runtime=${Tt}`];ir&&Un.push(`runtime-version=${ir}`);var ta={"X-Client-Info":`supabase-js/${ea}; ${Un.join("; ")}`},ra={headers:ta},sa={schema:"public"},na={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},ia={},oa={enabled:!1,respectSamplingDecision:!0};function aa(t){if(!t||typeof t!="string")return null;let e=t.split("-");if(e.length!==4)return null;let[r,s,n,i]=e;if(r.length!==2||s.length!==32||n.length!==16||i.length!==2)return null;let o=/^[0-9a-f]+$/i;return!o.test(r)||!o.test(s)||!o.test(n)||!o.test(i)||s==="00000000000000000000000000000000"||n==="0000000000000000"?null:{version:r,traceId:s,parentId:n,traceFlags:i,isSampled:(parseInt(i,16)&1)===1}}function ca(t,e){if(!t||!e||e.length===0)return!1;let r;if(t instanceof URL)r=t;else try{r=new URL(t)}catch{return!1}for(let s of e)try{if(typeof s=="string"){if(la(r.hostname,s))return!0}else if(s instanceof RegExp){if(s.test(r.hostname))return!0}else if(typeof s=="function"&&s(r))return!0}catch{continue}return!1}function la(t,e){if(e===t)return!0;if(e.startsWith("*.")){let r=e.slice(2);if(t.endsWith(r)&&(t===r||t.endsWith("."+r)))return!0}return!1}function ua(t){let e=[];try{let r=new URL(t);e.push(r.hostname)}catch{}return e.push("*.supabase.co","*.supabase.in"),e.push("localhost","127.0.0.1","[::1]"),e}function At(t){"@babel/helpers - typeof";return At=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},At(t)}function da(t,e){if(At(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(At(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function ha(t){var e=da(t,"string");return At(e)=="symbol"?e:e+""}function fa(t,e,r){return(e=ha(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Rn(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function N(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Rn(Object(r),!0).forEach(function(s){fa(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Rn(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var pa=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),ga=()=>Headers,jn=t=>t.startsWith("sb_publishable_")||t.startsWith("sb_secret_"),ma="sb_temp_",Cn=new Set,ya=t=>{var e,r;if(!t.startsWith("sb_")||jn(t)||t.startsWith(ma))return;let s=(e=(r=t.match(/^sb_[a-zA-Z0-9]+_/))===null||r===void 0?void 0:r[0])!==null&&e!==void 0?e:"unknown";Cn.has(s)||(Cn.add(s),console.warn("@supabase/supabase-js: Unrecognized Supabase API key format. The client will proceed and send this key as-is; if you see authentication errors you may need to upgrade @supabase/supabase-js to a version that recognizes this key type."))},xn=(t,e,r,s,n,i)=>{let o=pa(s),a=ga(),c=n?.enabled===!0,l=n?.respectSamplingDecision!==!1,u=c?ua(e):null,d=!(i?.omitApiKeyAsBearer&&jn(t));return async(f,h)=>{let p=await r(),g=new a(h?.headers);if(g.has("apikey")||g.set("apikey",t),!g.has("Authorization")){let m=p??(d?t:null);m&&g.set("Authorization",`Bearer ${m}`)}if(u){let m=va(f,u,l);m&&(m.traceparent&&!g.has("traceparent")&&g.set("traceparent",m.traceparent),m.tracestate&&!g.has("tracestate")&&g.set("tracestate",m.tracestate),m.baggage&&!g.has("baggage")&&g.set("baggage",m.baggage))}return o(f,N(N({},h),{},{headers:g}))}},In=!1,On=!1;function va(t,e,r){let s=os();if(!s)return In||(In=!0,console.warn("@supabase/supabase-js: tracePropagation is enabled but the tracing runtime is not loaded, so trace headers will not be attached. Add `import '@supabase/supabase-js/tracing'` at your application entry point (requires the OpenTelemetry API package to be installed). The CDN/UMD build does not support trace propagation.")),null;if(!ca(typeof t=="string"||t instanceof URL?t:t.url,e))return null;let n=s();if(!n||!n.traceparent){var i;if(!(n==null||(i=n.carrierKeys)===null||i===void 0)&&i.length&&!On){On=!0;let o=n.carrierKeys.includes("sentry-trace")?" Sentry detected: set `propagateTraceparent: true` in Sentry.init() to emit it.":" Configure your tracing SDK to emit W3C trace context on outgoing requests.";console.warn(`@supabase/supabase-js: tracePropagation is enabled and a tracing SDK is active, but its propagator wrote [${n.carrierKeys.join(", ")}] and no W3C traceparent header, so trace headers will not be attached.`+o)}return null}if(r){let o=aa(n.traceparent);if(o&&!o.isSampled)return{traceparent:n.traceparent}}return n}function Pn(t){return typeof t=="boolean"?{enabled:t}:t}function wa(t){return t.endsWith("/")?t:t+"/"}var Nn=!1;function ba(t){Nn||typeof t!="object"||t===null||!("schema"in t)||t.schema===void 0||(Nn=!0,console.warn(`@supabase/supabase-js: The "schema" option must be nested under "db", e.g. createClient(url, key, { db: { schema: 'myschema' } }). A top-level "schema" is ignored and queries go to the default schema.`))}function _a(t,e){var r,s,n,i,o,a;let{db:c,auth:l,realtime:u,global:d}=t,{db:f,auth:h,realtime:p,global:g}=e,m=Pn(t.tracePropagation),w=Pn(e.tracePropagation),_={db:N(N({},f),c),auth:N(N({},h),l),realtime:N(N({},p),u),storage:{},global:N(N(N({},g),d),{},{headers:N(N({},(r=g?.headers)!==null&&r!==void 0?r:{}),(s=d?.headers)!==null&&s!==void 0?s:{})}),tracePropagation:{enabled:(n=(i=m?.enabled)!==null&&i!==void 0?i:w?.enabled)!==null&&n!==void 0?n:!1,respectSamplingDecision:(o=(a=m?.respectSamplingDecision)!==null&&a!==void 0?a:w?.respectSamplingDecision)!==null&&o!==void 0?o:!0},accessToken:async()=>""};return t.accessToken?_.accessToken=t.accessToken:delete _.accessToken,_}function Ea(t){let e=t?.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(wa(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Sa=class extends Fr{constructor(t){super(t)}},ka=class{constructor(t,e,r){var s,n;this.supabaseUrl=t,this.supabaseKey=e;let i=Ea(t);if(!e)throw new Error("supabaseKey is required.");ya(e),ba(r),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`,a={db:sa,realtime:ia,auth:N(N({},na),{},{storageKey:o}),global:ra,tracePropagation:oa},c=_a(r??{},a);if(this.settings=c,this.storageKey=(s=c.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(n=c.global.headers)!==null&&n!==void 0?n:{},c.accessToken)this.accessToken=c.accessToken,this.auth=new Proxy({},{get:(u,d)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(d)} is not possible`)}});else{var l;this.auth=this._initSupabaseAuthClient((l=c.auth)!==null&&l!==void 0?l:{},this.headers,c.global.fetch)}this.fetch=xn(e,t,this._getSessionToken.bind(this),c.global.fetch,c.tracePropagation),this.functionsFetch=xn(e,t,this._getSessionToken.bind(this),c.global.fetch,c.tracePropagation,{omitApiKeyAsBearer:!0}),this.realtime=this._initRealtimeClient(N({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},c.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(u=>this.realtime.setAuth(u)).catch(u=>console.warn("Failed to set initial Realtime auth token:",u)),this.rest=new ys(new URL("rest/v1",i).href,{headers:this.headers,schema:c.db.schema,fetch:this.fetch,timeout:c.db.timeout,urlLengthLimit:c.db.urlLengthLimit,retry:c.db.retry}),this.storage=new Fs(this.storageUrl.href,this.headers,this.fetch,r?.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new rt(this.functionsUrl.href,{headers:this.headers,customFetch:this.functionsFetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}getOpenApiSpec(){return this.rest.getOpenApiSpec()}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getSessionToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();let{data:s}=await t.auth.getSession();return(e=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:null}async _getAccessToken(){var t=this,e;return(e=await t._getSessionToken())!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,storageKey:i,flowType:o,lock:a,debug:c,throwOnError:l,experimental:u,lockAcquireTimeout:d,skipAutoInitialize:f},h,p){let g={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Sa({url:this.authUrl.href,headers:N(N({},g),h),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,flowType:o,lock:a,debug:c,throwOnError:l,experimental:u,fetch:p,lockAcquireTimeout:d,skipAutoInitialize:f,hasCustomAuthorizationHeader:Object.keys(this.headers).some(m=>m.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new Fe(this.realtimeUrl.href,N(N({},t),{},{params:N(N({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e?.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN"||t==="INITIAL_SESSION")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}},Ln=(t,e,r)=>new ka(t,e,r);function Ta(){if(typeof window<"u"||globalThis.Deno!==void 0)return!1;let t=globalThis.process;if(!t)return!1;let e=t.version;if(e==null)return!1;let r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=20:!1}Ta()&&console.warn("\u26A0\uFE0F Node.js 20 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 22 or later. For more information, visit: https://github.com/orgs/supabase/discussions/45715");var M=[];for(let t=0;t<256;++t)M.push((t+256).toString(16).slice(1));function $n(t,e=0){return(M[t[e+0]]+M[t[e+1]]+M[t[e+2]]+M[t[e+3]]+"-"+M[t[e+4]]+M[t[e+5]]+"-"+M[t[e+6]]+M[t[e+7]]+"-"+M[t[e+8]]+M[t[e+9]]+"-"+M[t[e+10]]+M[t[e+11]]+M[t[e+12]]+M[t[e+13]]+M[t[e+14]]+M[t[e+15]]).toLowerCase()}var Kr,Aa=new Uint8Array(16);function Wr(){if(!Kr){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Kr=crypto.getRandomValues.bind(crypto)}return Kr(Aa)}var Ra=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Vr={randomUUID:Ra};function Ca(t,e,r){if(Vr.randomUUID&&!e&&!t)return Vr.randomUUID();t=t||{};let s=t.random??t.rng?.()??Wr();if(s.length<16)throw new Error("Random bytes length must be >= 16");if(s[6]=s[6]&15|64,s[8]=s[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let n=0;n<16;++n)e[r+n]=s[n];return e}return $n(s)}var Gr=Ca;var xa="https://api.convokit.app",k=class extends Error{constructor(e,r={}){super(e,r.cause===void 0?void 0:{cause:r.cause});R(this,"status");R(this,"responseBody");R(this,"code");this.name="ConvoKitError",this.status=r.status,this.responseBody=r.responseBody,this.code=r.code}};function Ia(t){let e=t.trim().replace(/\/+$/,"");if(!e)throw new k("backendUrl is required",{code:"INVALID_CONFIG"});return e}function Dn(t,e){if(typeof e=="object"&&e!==null){let r=e;if(typeof r.error=="string")return r.error;if(typeof r.message=="string")return r.message}return typeof e=="string"&&e.trim()?e:`ConvoKit request failed with status ${t}`}function Mn(t){if(typeof t=="object"&&t!==null){let e=t.code;if(typeof e=="string"&&e.trim())return e}return"HTTP_ERROR"}async function qn(t){if(t.status===204)return;let e=await t.text();if(!e)return;if((t.headers.get("content-type")??"").includes("application/json"))try{return JSON.parse(e)}catch{return e}return e}var Oa=class{constructor(t){R(this,"backendUrl");R(this,"clientId");R(this,"fetchImplementation");R(this,"headersProvider");if(this.backendUrl=Ia(t.backendUrl),this.clientId=t.clientId.trim(),!this.clientId)throw new k("clientId is required",{code:"INVALID_CONFIG"});let e=t.fetchImplementation??globalThis.fetch;if(typeof e!="function")throw new k("A Fetch API implementation is required",{code:"FETCH_UNAVAILABLE"});this.fetchImplementation=e.bind(globalThis),this.headersProvider=t.headersProvider}async request(t,e={}){let r=new URL(`${this.backendUrl}${t}`);for(let[a,c]of Object.entries(e.query??{}))c!=null&&r.searchParams.set(a,String(c));let s={"x-client-id":this.clientId,...e.authenticated===!1?{}:this.headersProvider(),...e.headers},n;e.body!==void 0&&(typeof e.body=="string"||e.body instanceof ArrayBuffer||ArrayBuffer.isView(e.body)||typeof Blob<"u"&&e.body instanceof Blob?n=e.body:(s["Content-Type"]??(s["Content-Type"]="application/json"),n=JSON.stringify(e.body)));let i;try{i=await this.fetchImplementation(r,{method:e.method??"GET",headers:s,...n===void 0?{}:{body:n}})}catch(a){throw new k("Could not reach the ConvoKit backend",{code:"NETWORK_ERROR",cause:a})}let o=await qn(i);if(!i.ok)throw new k(Dn(i.status,o),{status:i.status,responseBody:o,code:Mn(o)});return o}async requestRaw(t,e={}){let r=new URL(`${this.backendUrl}${t}`);for(let[n,i]of Object.entries(e.query??{}))i!=null&&r.searchParams.set(n,String(i));let s;try{s=await this.fetchImplementation(r,{method:e.method??"GET",headers:{"x-client-id":this.clientId,...e.authenticated===!1?{}:this.headersProvider(),...e.headers}})}catch(n){throw new k("Could not reach the ConvoKit backend",{code:"NETWORK_ERROR",cause:n})}if(!s.ok){let n=await qn(s);throw new k(Dn(s.status,n),{status:s.status,responseBody:n,code:Mn(n)})}return s}};function Yr(){return Gr()}var Bn=2147483647;function Pa(t,e){if(!Number.isInteger(t)||t<0||t>Bn)throw new k(`${e} must be an integer between 0 and ${Bn}`,{code:"INVALID_ARGUMENT"});return t}function Hn(t){let e=U(L(t).data);if(typeof e.messageId!="string"||typeof e.emoji!="string"||typeof e.changed!="boolean")throw new TypeError("Invalid ConvoKit reaction mutation");return{messageId:e.messageId,emoji:e.emoji,changed:e.changed}}function Na(t){let e=L(t).data;if(!Array.isArray(e))throw new TypeError("Invalid ConvoKit reaction summaries");return e.map(r=>{let s=U(r);if(typeof s.messageId!="string"||!Array.isArray(s.reactions)||typeof s.hasMore!="boolean")throw new TypeError("Invalid ConvoKit reaction summary");return{messageId:s.messageId,hasMore:s.hasMore,reactions:s.reactions.map(n=>{let i=U(n);if(typeof i.emoji!="string"||typeof i.count!="number"||!Number.isInteger(i.count)||i.count<1||typeof i.reactedByMe!="boolean")throw new TypeError("Invalid ConvoKit reaction count");return{emoji:i.emoji,count:i.count,reactedByMe:i.reactedByMe}})}})}function Ua(t){let e=U(t);if(!Array.isArray(e.data)||e.nextCursor!==null&&typeof e.nextCursor!="string")throw new TypeError("Invalid ConvoKit reaction users page");return{data:e.data.map(r=>{let s=U(r);if(typeof s.userId!="string")throw new TypeError("Invalid ConvoKit reaction user");return{userId:s.userId,name:Y(s.name),imageUrl:Y(s.imageUrl),reactedAt:we(s.reactedAt)}}),nextCursor:e.nextCursor}}function U(t){return typeof t!="object"||t===null||Array.isArray(t)?{}:t}function $(t,e=""){return typeof t=="string"?t:e}function Y(t){return typeof t=="string"?t:null}function we(t){let e=new Date($(t));if(Number.isNaN(e.getTime()))throw new TypeError(`Invalid ConvoKit date: ${String(t)}`);return e}function ae(t){return t==null?null:we(t)}function oe(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim()!==""){let e=Number(t);if(Number.isFinite(e))return e}}function Fn(t){let e=U(t);return{id:$(e.id),appId:$(e.appId??e.app_id),name:Y(e.name??e.display_name),imageUrl:Y(e.imageUrl??e.image_url),lastSeenAt:ae(e.lastSeenAt??e.last_seen_at),createdAt:ae(e.createdAt??e.created_at),updatedAt:ae(e.updatedAt??e.updated_at)}}function cr(t){if(t==null)return null;let e=U(t),r=e.messageId??e.message_id;if(typeof r!="string"||!r.trim())throw new TypeError("Invalid ConvoKit read position: missing messageId");return{messageId:r,createdAt:we(e.createdAt??e.created_at)}}function ja(t){let e=U(t),r=$(e.id);return{id:r,appUserId:$(e.appUserId??e.app_user_id,r),name:$(e.name??e.display_name),imageUrl:Y(e.imageUrl??e.image_url),role:$(e.role,"READ_WRITE"),lastReadAt:ae(e.lastReadAt??e.last_read_at),readPosition:cr(e.readPosition??e.read_position)}}function Rt(t){let e=U(t),r=Y(e.title),s=e.participants??e.members,n=Array.isArray(s)?s.map(ja):[];return{id:$(e.id),title:r,imageUrl:Y(e.imageUrl??e.image_url),appId:$(e.appId??e.app_id),displayTitle:$(e.displayTitle??e.display_title,r??"Conversation"),description:Y(e.description),participants:n,createdAt:we(e.createdAt??e.created_at),updatedAt:we(e.updatedAt??e.updated_at)}}function Qr(t){if(t==null)return 0;let e=oe(t);if(e===void 0||!Number.isInteger(e)||e<0)throw new TypeError(`Invalid ConvoKit private state version: ${String(t)}`);return e}function La(t){if(t==null)return null;let e=U(t);return{role:$(e.role,"READ_WRITE"),lastReadAt:ae(e.lastReadAt??e.last_read_at),readPosition:cr(e.readPosition??e.read_position),unreadMarkedAt:ae(e.unreadMarkedAt??e.unread_marked_at),privateStateVersion:Qr(e.privateStateVersion??e.private_state_version)}}function Qn(t){let e=U(t),r=e.conversationId??e.conversation_id;if(typeof r!="string"||!r.trim())throw new TypeError("Invalid ConvoKit private state: missing conversationId");return{conversationId:r,unreadMarkedAt:ae(e.unreadMarkedAt??e.unread_marked_at),privateStateVersion:Qr(e.privateStateVersion??e.private_state_version)}}function $a(t){return{...Qn(t),cleared:ar(U(t).cleared,"cleared")}}function Da(t){let e=U(t),r=$(e.type),s={...typeof e.id=="string"?{id:e.id}:{},...typeof e.name=="string"?{name:e.name}:{},...oe(e.sortOrder??e.sort_order)!==void 0?{sortOrder:oe(e.sortOrder??e.sort_order)}:{}};if(r==="image"||r==="file")return{...s,type:r,url:$(e.url),...oe(e.size)!==void 0?{size:oe(e.size)}:{},...typeof e.metadata=="object"&&e.metadata!==null?{metadata:e.metadata}:{}};let n=U(e.metadata);if(r==="location")return{...s,type:r,metadata:{...n,lat:oe(n.lat)??Number.NaN,lng:oe(n.lng)??Number.NaN}};if(r==="contact")return{...s,type:r,metadata:{...n,...typeof n.phone=="string"?{phone:n.phone}:{},...typeof n.email=="string"?{email:n.email}:{}}};throw new TypeError(`Unsupported ConvoKit media type: ${r||"(missing)"}`)}function Zn(t){if(t==null)return 0;let e=oe(t);if(e===void 0||!Number.isInteger(e)||e<0)throw new TypeError(`Invalid ConvoKit message revision: ${String(t)}`);return e}var Kn=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),fe=t=>typeof t=="string"&&t.length>0;function Ma(t){if(fe(t))try{return new URL(t).protocol==="https:"?t:void 0}catch{return}}function qa(t){if(t==null)return;let e={kind:"unknown",raw:t};if(!Kn(t)||t.v!==1)return e;switch(t.kind){case"link":{let r=Ma(t.url);return!fe(t.title)||!r?e:{v:1,kind:"link",title:t.title,url:r,...fe(t.description)?{description:t.description}:{},...fe(t.buttonLabel)?{buttonLabel:t.buttonLabel}:{}}}case"quick_replies":{if(!fe(t.prompt)||!Array.isArray(t.options)||t.options.length===0)return e;let r=t.options.map(s=>Kn(s)&&fe(s.id)&&fe(s.label)?{id:s.id,label:s.label}:null);return r.some(s=>s===null)?e:{v:1,kind:"quick_replies",prompt:t.prompt,options:r,...t.layout==="grid"?{layout:"grid"}:{}}}case"handoff":return{v:1,kind:"handoff"};case"form_completed":return!fe(t.cardMessageId)||!fe(t.title)?e:{v:1,kind:"form_completed",cardMessageId:t.cardMessageId,title:t.title};default:return e}}function ve(t){let e=U(t);return{id:$(e.id),...e.clientMessageId===void 0?{}:{clientMessageId:Y(e.clientMessageId)},conversationId:$(e.conversationId??e.conversation_id),senderId:$(e.appUserId??e.app_user_id??e.senderId),text:Y(e.text??e.content),media:Array.isArray(e.media)?e.media.map(Da):[],createdAt:we(e.createdAt??e.created_at),updatedAt:ae(e.updatedAt??e.updated_at),revision:Zn(e.revision),...typeof e.replyToMessageId=="string"?{replyToMessageId:e.replyToMessageId}:{},...Ba(e.card)}}function Ba(t){let e=qa(t);return e?{card:e}:{}}function Ha(t){if(t==null)return 0;let e=oe(t);if(e===void 0||!Number.isInteger(e)||e<0)throw new TypeError(`Invalid ConvoKit media count: ${String(t)}`);return e}function Fa(t){let e=U(t),r=e.id;if(typeof r!="string"||!r.trim())throw new TypeError("Invalid ConvoKit reply preview: missing id");return{id:r,conversationId:$(e.conversationId??e.conversation_id),senderId:$(e.appUserId??e.app_user_id??e.senderId),text:Y(e.text),textTruncated:ar(e.textTruncated??e.text_truncated,"textTruncated"),createdAt:we(e.createdAt??e.created_at),revision:Zn(e.revision),mediaCount:Ha(e.mediaCount??e.media_count)}}function Ka(t){let e=U(t);if(!Array.isArray(e.data))throw new TypeError("Invalid ConvoKit message context: missing data");return{messages:e.data.map(ve),olderCursor:Wn(e.olderCursor??e.older_cursor,"olderCursor"),newerCursor:Wn(e.newerCursor??e.newer_cursor,"newerCursor")}}function Wn(t,e){if(t!=null&&typeof t!="string")throw new TypeError(`Invalid ConvoKit message context: ${e} must be a string or null`);return typeof t=="string"?t:null}function Wa(t){if(t==null)return 0;let e=oe(t);if(e===void 0||!Number.isInteger(e)||e<0)throw new TypeError(`Invalid ConvoKit unread count: ${String(t)}`);return e}function ar(t,e){if(t==null)return!1;if(typeof t!="boolean")throw new TypeError(`Invalid ConvoKit ${e}: ${String(t)}`);return t}function Va(t){let e=U(t),r=e.latestMessage??e.latest_message,s=Wa(e.unreadCount??e.unread_count),n=ar(e.unreadCountCapped??e.unread_count_capped,"unreadCountCapped"),i=ae(e.unreadMarkedAt??e.unread_marked_at),o=e.isUnread??e.is_unread;return{conversation:Rt(e.conversation),latestMessage:r==null?null:ve(r),unreadCount:s,unreadCountCapped:n,readPosition:cr(e.readPosition??e.read_position),lastReadAt:ae(e.lastReadAt??e.last_read_at),isUnread:o==null?s>0||n||i!==null:ar(o,"isUnread"),unreadMarkedAt:i,privateStateVersion:Qr(e.privateStateVersion??e.private_state_version),activityAt:we(e.activityAt??e.activity_at)}}function Ga(t){let e=U(t);if(!Array.isArray(e.entries))throw new TypeError("Invalid ConvoKit inbox page: missing entries");let r=e.nextCursor??e.next_cursor;if(r!=null&&typeof r!="string")throw new TypeError("Invalid ConvoKit inbox page: nextCursor must be a string or null");return{entries:e.entries.map(Va),nextCursor:typeof r=="string"?r:null}}function za(t){let e=U(t);if(!Array.isArray(e.data))throw new TypeError("Invalid ConvoKit message page: missing data");let r=e.nextCursor!==void 0?e.nextCursor:e.next_cursor;if(r!==null&&(typeof r!="string"||r.length===0))throw new TypeError("Invalid ConvoKit message page: nextCursor must be a non-empty string or null");return{messages:e.data.map(ve),nextCursor:r}}function L(t){return U(t)}function zr(t){return typeof t=="function"?{onEvent:t}:t}function xt(t){let e=L(t);return L(e.payload??e)}function Ja(t){let e=xt(t);if(typeof e.userId!="string"||typeof e.isTyping!="boolean")throw new TypeError("typing payload is missing userId or isTyping");return{userId:e.userId,isTyping:e.isTyping}}function Xa(t){let e=xt(t);if(typeof e.userId!="string"||typeof e.readAt!="string")throw new TypeError("read payload is missing userId or readAt");let r=new Date(e.readAt);if(Number.isNaN(r.getTime()))throw new TypeError("readAt is not a date");return{userId:e.userId,readAt:r,readPosition:cr(e.readPosition??e.read_position)}}function Ya(t){let e=xt(t);if(typeof e.userId!="string"||typeof e.isOnline!="boolean"||typeof e.lastSeenAt!="string")throw new TypeError("presence payload is incomplete");let r=new Date(e.lastSeenAt);if(Number.isNaN(r.getTime()))throw new TypeError("lastSeenAt is not a date");return{userId:e.userId,isOnline:e.isOnline,lastSeenAt:r}}var Qe,Yn,Jr=(Yn=class{constructor(t){R(this,"close");rs(this,Qe,!1);this.close=t}get closed(){return ur(this,Qe)}async unsubscribe(){ur(this,Qe)||(ss(this,Qe,!0),await this.close())}},Qe=new WeakMap,Yn),Qa=class{constructor(t,e,r,s){R(this,"supabase");R(this,"appUserIdValue");R(this,"resolveTopic");R(this,"defaultErrorHandler");R(this,"subscriptions",new Set);R(this,"broadcastHubs",new Map);R(this,"connectionListeners",new Map);R(this,"sequence",0);R(this,"disposed",!1);this.supabase=t,this.appUserIdValue=e,this.resolveTopic=r,this.defaultErrorHandler=s}get appUserId(){return this.appUserIdValue}onConnectionEvent(t){this.requireOpen();let e=new Jr(async()=>{this.connectionListeners.delete(e),this.subscriptions.delete(e)});return this.connectionListeners.set(e,t),this.subscriptions.add(e),e}onMessage(t,e){this.requireOpen();let r=zr(e),s,n=`messages:${t}`,i=this.supabase.channel(this.channelName(n),{config:{private:!0}});for(let o of["INSERT","UPDATE"])i.on("postgres_changes",{event:o,schema:"public",table:"Message",filter:`conversationId=eq.${t}`},a=>{if(!(this.disposed||s?.closed))try{let c=ve(a.new);if(!c.id.trim()||c.conversationId!==t)throw new TypeError("Invalid message identity");r.onEvent({type:o==="INSERT"?"insert":"update",message:c})}catch{this.reportError(r,"Could not parse or deliver a realtime message")}});return s=this.subscribeChannel(i,r,n),s}onMessageDeleted(t,e){return this.subscribeBroadcast(`conversation:${t}`,"message_deleted",e,r=>{let s=xt(r);if(typeof s.id!="string"||!s.id.trim()||!t.trim()||s.conversationId!==t)throw new TypeError("Invalid message deletion");return{id:s.id,conversationId:t}})}onReactionChanged(t,e){return this.subscribeBroadcast(`conversation:${t}`,"reaction_changed",e,r=>{let s=xt(r);if(typeof s.id!="string"||!s.id.trim()||!t.trim()||s.conversationId!==t)throw new TypeError("Invalid reaction invalidation");return{id:s.id,conversationId:t}})}onTyping(t,e){return this.subscribeBroadcast(`conversation:${t}`,"typing",e,Ja)}onReadReceipt(t,e){return this.subscribeBroadcast(`conversation:${t}`,"read",e,Xa)}onPresence(t,e){return this.subscribeBroadcast(`app:${t}`,"presence",e,Ya)}onInboxChanged(t,e){let r=zr(e);return this.subscribeBroadcast(`app:${t}`,"inbox_changed",{...r,onStatus:s=>{if(s==="SUBSCRIBED")try{r.onEvent()}catch{this.reportError(r,"Could not deliver inbox invalidation")}r.onStatus?.(s)}},()=>{})}onInboxActivity(t,e){return this.subscribeBroadcast(`app:${t}`,"inbox_activity",e,()=>{})}async dispose(){if(this.disposed)return;this.disposed=!0;let t=[...this.subscriptions];for(let[e,r]of[...this.connectionListeners])if(!e.closed)try{r.onSessionEnded?.()}catch{this.reportError(r,"Could not notify a retired Realtime session")}await Promise.all(t.map(e=>e.unsubscribe()))}connection(t,e){if(!this.disposed){for(let[r,s]of[...this.connectionListeners])if(!r.closed)try{s.onEvent({topic:t,status:e})}catch{this.reportError(s,"Could not deliver Realtime connection state")}}}channelName(t){return this.sequence+=1,`${t}:${Date.now()}:${this.sequence}`}subscribeChannel(t,e,r){let s;return s=new Jr(async()=>{this.subscriptions.delete(s),await this.supabase.removeChannel(t)}),this.subscriptions.add(s),t.subscribe(n=>{if(this.disposed||s.closed)return;let i=n;this.connection(r,i),!(this.disposed||s.closed)&&(e.onStatus?.(i),(i==="CHANNEL_ERROR"||i==="TIMED_OUT")&&this.reportError(e,`Realtime subscription ${i.toLowerCase()}`))}),s}subscribeBroadcast(t,e,r,s){this.requireOpen();let n=zr(r),i=this.broadcastHubs.get(t),o=!1;i||(i={listeners:new Set,generation:0,failures:0},this.broadcastHubs.set(t,i),o=!0);let a={event:e,onPayload:u=>{try{n.onEvent(s(u))}catch{this.reportError(n,`Could not parse or deliver a realtime ${e} event`)}},...n.onStatus===void 0?{}:{onStatus:n.onStatus},...n.onError===void 0?{}:{onError:n.onError}};i.listeners.add(a);let c=i,l=new Jr(async()=>{this.subscriptions.delete(l),c.listeners.delete(a),c.listeners.size===0&&(this.broadcastHubs.get(t)===c&&this.broadcastHubs.delete(t),c.generation+=1,clearTimeout(c.retry),c.channel&&await this.supabase.removeChannel(c.channel))});return this.subscriptions.add(l),o?this.resolveBroadcastHub(t,c):i.status&&n.onStatus?.(i.status),l}hubIsCurrent(t,e){return!this.disposed&&e.listeners.size>0&&this.broadcastHubs.get(t)===e}broadcastStatus(t,e,r){if(this.hubIsCurrent(t,e)){e.status=r,this.connection(t,r);for(let s of[...e.listeners]){if(!this.hubIsCurrent(t,e))return;if(e.listeners.has(s)){try{s.onStatus?.(r)}catch{}if(r==="CHANNEL_ERROR"||r==="TIMED_OUT")try{s.onError?.(new k(`Realtime subscription ${r.toLowerCase()}`,{code:"REALTIME_ERROR"}))}catch{}}}(r==="CHANNEL_ERROR"||r==="TIMED_OUT")&&this.reportError({},`Realtime subscription ${r.toLowerCase()}`)}}resolveBroadcastHub(t,e,r=!1){if(!this.hubIsCurrent(t,e))return;clearTimeout(e.retry);let s=++e.generation,n=()=>this.hubIsCurrent(t,e)&&e.generation===s,i=a=>{if(!n())return;let c=e.channel;delete e.channel,c&&this.supabase.removeChannel(c).catch(()=>{}),this.broadcastStatus(t,e,"CHANNEL_ERROR"),!(a instanceof k&&[401,403,404].includes(a.status??0))&&++e.failures<=3&&n()&&(e.retry=setTimeout(()=>this.resolveBroadcastHub(t,e),1e3*e.failures),e.retry.unref?.())},o=a=>{if(!n())return;if(!a.startsWith(`${t}:`)||!a.slice(t.length+1).trim()||a.slice(t.length+1).includes(":"))throw new TypeError("Invalid private topic");if(e.channel&&e.wireTopic===a){r&&(e.failures=0,this.broadcastStatus(t,e,"SUBSCRIBED"));return}let c=e.channel;delete e.channel,delete e.status,c&&this.supabase.removeChannel(c).catch(()=>{});let l=this.createBroadcastChannel(t,a);e.channel=l,e.wireTopic=a,l.on("broadcast",{event:"scope_changed"},()=>{this.hubIsCurrent(t,e)&&e.channel===l&&(delete e.channel,delete e.status,this.supabase.removeChannel(l).catch(()=>{}),this.resolveBroadcastHub(t,e))}),l.subscribe(u=>{if(!this.hubIsCurrent(t,e)||e.channel!==l)return;let d=u;d==="SUBSCRIBED"?this.resolveBroadcastHub(t,e,!0):(this.broadcastStatus(t,e,d),(d==="CHANNEL_ERROR"||d==="TIMED_OUT"||d==="CLOSED")&&(delete e.channel,this.supabase.removeChannel(l).catch(()=>{}),++e.failures<=3&&(clearTimeout(e.retry),e.retry=setTimeout(()=>this.resolveBroadcastHub(t,e),1e3*e.failures),e.retry.unref?.())))})};try{let a=this.resolveTopic(t);typeof a=="string"?o(a):a.then(o).catch(i)}catch(a){i(a)}}createBroadcastChannel(t,e){let r=this.supabase.channel(e,{config:{private:!0}});return t.startsWith("conversation:")?r.on("broadcast",{event:"typing"},s=>{this.dispatchBroadcast(t,r,"typing",s)}).on("broadcast",{event:"read"},s=>{this.dispatchBroadcast(t,r,"read",s)}).on("broadcast",{event:"message_deleted"},s=>{this.dispatchBroadcast(t,r,"message_deleted",s)}).on("broadcast",{event:"reaction_changed"},s=>{this.dispatchBroadcast(t,r,"reaction_changed",s)}):(r.on("broadcast",{event:"presence"},s=>{this.dispatchBroadcast(t,r,"presence",s)}),r.on("broadcast",{event:"inbox_changed"},s=>{this.dispatchBroadcast(t,r,"inbox_changed",s)}),r.on("broadcast",{event:"inbox_activity"},s=>{this.dispatchBroadcast(t,r,"inbox_activity",s)})),r}dispatchBroadcast(t,e,r,s){if(this.disposed)return;let n=this.broadcastHubs.get(t);if(!(!n||n.channel!==e))for(let i of[...n.listeners])n.listeners.has(i)&&i.event===r&&i.onPayload(s)}requireOpen(){if(this.disposed)throw new k("This Realtime session has been closed; use the connected client\u2019s current session",{code:"SESSION_CHANGED"})}reportError(t,e){let r=new k(e,{code:"REALTIME_ERROR"});for(let s of[t.onError,this.defaultErrorHandler])try{s?.(r)}catch{}}},Za=2147483647;function Vn(t){try{let e=t.split(".")[1];if(!e)return 1/0;let r=e.replace(/-/g,"+").replace(/_/g,"/"),s=JSON.parse(atob(r.padEnd(Math.ceil(r.length/4)*4,"=")));return typeof s.exp=="number"&&Number.isSafeInteger(s.exp)?s.exp*1e3:1/0}catch{return 1/0}}function or(t){let e=Math.min(Vn(t.userToken),Vn(t.realtimeToken));if(e<=Date.now())throw new k("Session token has expired",{code:"TOKEN_EXPIRED"});return e}var ec=class{constructor(t){R(this,"options");R(this,"generation",0);R(this,"sessionSequence",0);R(this,"active",null);R(this,"pending",null);R(this,"refreshTimer");R(this,"expirationTimer");R(this,"listeners",new Set);R(this,"snapshot",Object.freeze({status:"disconnected",currentUserId:null,previousUserId:null,sessionId:null,reason:null,requiresReauthentication:!1,errorCode:null}));this.options=t}get connected(){return this.active!==null}get state(){return this.snapshot}get userId(){return this.requireActive().userId}get tokens(){return this.requireActive().tokens}get resource(){return this.requireActive().resource}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}capture(){let t=this.requireActive();return()=>this.assertActive(t)}async connect(t){let e=++this.generation,r=++this.sessionSequence,s=Object.freeze({status:"connecting",currentUserId:null,requestedUserId:t,sessionId:r});try{await this.clear(s),this.assertGeneration(e);let n=await this.options.tokens(t,()=>this.assertGeneration(e));this.assertGeneration(e),or(n);let i=!0,o;try{o=await this.options.create(t,n,()=>e===this.generation?this.active?.tokens.realtimeToken??(i?n.realtimeToken:null):null)}finally{i=!1}if(e!==this.generation)throw await o.close(),this.changed();try{let a={id:r,userId:t,tokens:n,resource:o,refreshAt:1/0,expiresAt:or(n),failures:0};this.active=a,this.schedule(a),this.transition(Object.freeze({status:"connected",currentUserId:t,sessionId:r}))}catch(a){throw this.active?.resource===o&&(this.active=null,this.cancelTimers()),await o.close(),a}}catch(n){if(e===this.generation&&this.active===null){let i=this.endState(t,r,this.connectionFailure(n));this.transition(i)}throw n}}async disconnect(){this.generation+=1;let t=this.snapshot,e=this.active?.userId??(t.status==="connecting"?t.requestedUserId:null),r=this.active?.id??(t.status==="connecting"?t.sessionId:null);await this.clear(this.endState(e,r,{reason:"user-disconnected",requiresReauthentication:!1,errorCode:null}))}async request(t){let e=this.requireActive();Date.now()>=e.refreshAt&&await this.renew(e),this.assertActive(e);let r=e.tokens.userToken;try{let s=await t(r);return this.assertActive(e),s}catch(s){if(this.assertActive(e),!(s instanceof k)||s.status!==401)throw s;if(r===e.tokens.userToken)try{await this.renew(e)}catch{throw this.assertActive(e),s}this.assertActive(e);let n=await t(e.tokens.userToken);return this.assertActive(e),n}}renew(t){if(this.assertActive(t),this.pending?.session===t)return this.pending.promise;let e=this.performRenewal(t).finally(()=>{this.pending?.promise===e&&(this.pending=null)});return this.pending={session:t,promise:e},e}async performRenewal(t){try{let e=await this.options.tokens(t.userId,()=>this.assertActive(t));this.assertActive(t);let r=or(e);if(Date.now()>=t.refreshAt&&r<=t.expiresAt)throw new k("The token provider did not extend the session lifetime",{code:"SESSION_TOKEN_NOT_RENEWED"});if(e.supabaseUrl!==t.tokens.supabaseUrl||e.supabaseKey!==t.tokens.supabaseKey)throw new k("Realtime configuration changed; reconnect the user",{code:"SESSION_CONFIGURATION_CHANGED"});try{await t.resource.setAuth(e.realtimeToken)}catch{throw new k("Could not authenticate the renewed Realtime session",{code:"SESSION_REALTIME_AUTH_FAILED"})}this.assertActive(t),t.tokens=e,t.failures=0,this.schedule(t)}catch(e){throw this.active===t&&(e instanceof k&&([401,403].includes(e.status??0)||["TOKEN_EXPIRED","SESSION_CONFIGURATION_CHANGED","SESSION_REALTIME_AUTH_FAILED"].includes(e.code??""))||t.expiresAt<=Date.now()?this.retire(t,this.renewalFailure(e,t.expiresAt<=Date.now())):(t.failures+=1,t.refreshAt=Math.min(t.expiresAt,Date.now()+Math.min(3e4,5e3*2**Math.min(t.failures-1,3))),this.armRefresh(t)),this.report("Session token renewal failed","SESSION_REFRESH_FAILED")),e}}schedule(t){this.cancelTimers(),t.expiresAt=or(t.tokens);let e=t.expiresAt-Date.now();t.refreshAt=Number.isFinite(e)?Date.now()+e-Math.min(3e5,e*.2):1/0,this.armRefresh(t),this.armExpiration(t)}armRefresh(t){clearTimeout(this.refreshTimer),Number.isFinite(t.refreshAt)&&(this.refreshTimer=this.timer(t.refreshAt-Date.now(),()=>{if(this.active===t){if(Date.now()<t.refreshAt){this.armRefresh(t);return}this.renew(t).catch(()=>{})}}))}armExpiration(t){clearTimeout(this.expirationTimer),Number.isFinite(t.expiresAt)&&(this.expirationTimer=this.timer(t.expiresAt-Date.now(),()=>{if(this.active===t){if(Date.now()<t.expiresAt){this.armExpiration(t);return}this.retire(t,{reason:"token-expired",requiresReauthentication:!0,errorCode:"SESSION_EXPIRED"}),this.report("Session expired; reconnect the user","SESSION_EXPIRED")}}))}timer(t,e){let r=setTimeout(e,Math.max(0,Math.min(Za,t)));return r.unref?.(),r}retire(t,e){this.active===t&&(this.generation+=1,this.clear(this.endState(t.userId,t.id,e)).catch(()=>this.report("Could not finish closing the session","SESSION_CLOSE_FAILED")))}clear(t){let e=this.active;return this.active=null,this.pending=null,this.cancelTimers(),this.transition(t),e?.resource.close()??Promise.resolve()}transition(t){if(this.snapshot!==t){this.snapshot=t;for(let e of[...this.listeners])try{e()}catch{}}}endState(t,e,r){return Object.freeze({status:"disconnected",currentUserId:null,previousUserId:t,sessionId:e,reason:r.reason,requiresReauthentication:r.requiresReauthentication,errorCode:r.errorCode})}connectionFailure(t){if(t instanceof k){if([401,403].includes(t.status??0))return{reason:"authentication-rejected",requiresReauthentication:!0,errorCode:"SESSION_AUTHENTICATION_REJECTED"};if(t.code==="TOKEN_EXPIRED")return{reason:"token-expired",requiresReauthentication:!0,errorCode:"TOKEN_EXPIRED"}}return{reason:"connection-failed",requiresReauthentication:!1,errorCode:"SESSION_CONNECT_FAILED"}}renewalFailure(t,e){if(e||t instanceof k&&t.code==="TOKEN_EXPIRED")return{reason:"token-expired",requiresReauthentication:!0,errorCode:"SESSION_EXPIRED"};if(t instanceof k){if([401,403].includes(t.status??0))return{reason:"authentication-rejected",requiresReauthentication:!0,errorCode:"SESSION_REFRESH_REJECTED"};if(t.code==="SESSION_CONFIGURATION_CHANGED")return{reason:"configuration-changed",requiresReauthentication:!1,errorCode:t.code};if(t.code==="SESSION_REALTIME_AUTH_FAILED")return{reason:"realtime-authentication-failed",requiresReauthentication:!1,errorCode:t.code}}return{reason:"token-expired",requiresReauthentication:!0,errorCode:"SESSION_EXPIRED"}}cancelTimers(){clearTimeout(this.refreshTimer),clearTimeout(this.expirationTimer),this.refreshTimer=void 0,this.expirationTimer=void 0}report(t,e){try{this.options.onError?.(new k(t,{code:e}))}catch{}}requireActive(){if(!this.active)throw new k("Call connectUser() first",{code:"NOT_CONNECTED"});return this.active}assertActive(t){if(this.active!==t)throw this.changed()}assertGeneration(t){if(t!==this.generation)throw this.changed()}changed(){return new k("The user session changed while the operation was pending",{code:"SESSION_CHANGED"})}};function T(t,e){let r=t.trim();if(!r)throw new k(`${e} is required`,{code:"INVALID_ARGUMENT"});return r}function Ye(t,e){if(!Number.isInteger(t)||t<0)throw new k(`${e} must be a non-negative integer`,{code:"INVALID_ARGUMENT"});return t}function Ct(t,e,r,s){if(!Number.isInteger(t)||t<r||t>s)throw new k(`${e} must be an integer between ${r} and ${s}`,{code:"INVALID_ARGUMENT"});return t}var tc=2147483647,Gn=64,zn=50,Jn=50;function Xr(t){if(typeof t!="string"||t.length===0)throw new k("emoji is required",{code:"INVALID_ARGUMENT"});return t}function Oe(t,e){let r=typeof t=="string"?t.trim():"";if(!r)throw new k(`${e} must be a non-empty string`,{code:"INVALID_ARGUMENT"});if(r.length>Gn)throw new k(`${e} must be at most ${Gn} characters`,{code:"INVALID_ARGUMENT"});return r}function Xn(t,e){return Ct(t,e,0,tc)}function rc(t){if(t instanceof Blob||t instanceof ArrayBuffer)return t;if(ArrayBuffer.isView(t)){let e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),e.buffer}throw new k("bytes must be a Blob, ArrayBuffer, or typed array",{code:"INVALID_ARGUMENT"})}var ei=class{constructor(t){R(this,"backendUrl");R(this,"clientId");R(this,"tokenProvider");R(this,"onRealtimeError");R(this,"fetchImplementation");R(this,"transport");R(this,"session");this.tokenProvider=t.tokenProvider,this.onRealtimeError=t.onRealtimeError,this.fetchImplementation=(t.fetch??globalThis.fetch).bind(globalThis),this.clientId=T(t.clientId,"clientId"),this.transport=new Oa({backendUrl:t.backendUrl??xa,clientId:this.clientId,...t.fetch===void 0?{}:{fetchImplementation:t.fetch},headersProvider:()=>({})}),this.backendUrl=this.transport.backendUrl,this.session=new ec({tokens:async(e,r)=>{let s=T(await this.tokenProvider(e),"tokenProvider result");r();let n=await this.transport.request("/api/v1/realtime/token",{method:"POST",authenticated:!1,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:{appUserId:e}});return r(),{userToken:s,realtimeToken:T(n.data.token,"realtime token"),supabaseUrl:T(n.data.supabaseUrl,"supabaseUrl"),supabaseKey:T(n.data.supabaseKey,"supabaseKey")}},create:async(e,r,s)=>{let n=Ln(r.supabaseUrl,r.supabaseKey,{auth:{autoRefreshToken:!1,persistSession:!1,detectSessionInUrl:!1},accessToken:async()=>s()});try{await n.realtime.setAuth(r.realtimeToken)}catch(o){throw n.realtime.disconnect(),o}let i=new Qa(n,e,async o=>{if(!s())throw new k("Realtime session ended",{code:"SESSION_CHANGED"});let a=this.session.capture(),c=await this.request("/api/v1/realtime/topic",{query:{topic:o}});if(a(),!s())throw new k("Realtime session ended",{code:"SESSION_CHANGED"});return T(c.data.topic,"private Realtime topic")},this.onRealtimeError);return{supabase:n,realtime:i,setAuth:o=>n.realtime.setAuth(o),close:async()=>{try{await i.dispose()}finally{n.realtime.disconnect()}}}},onError:this.onRealtimeError})}get connected(){return this.session.connected}get sessionState(){return this.session.state}subscribeSession(t){return this.session.subscribe(t)}get currentUserId(){return this.session.userId}get authHeaders(){return{"Content-Type":"application/json","x-client-id":this.clientId,Authorization:`Bearer ${this.requireUserToken()}`}}get lastToken(){return this.session.tokens.realtimeToken}get lastUserToken(){return this.requireUserToken()}get lastTokenClaims(){let t=this.lastToken.split(".");if(t.length!==3||t[1]===void 0)throw new k("Invalid JWT format",{code:"INVALID_TOKEN"});let e=t[1].replace(/-/g,"+").replace(/_/g,"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");try{let s=Uint8Array.from(atob(r),n=>n.charCodeAt(0));return JSON.parse(new TextDecoder().decode(s))}catch(s){throw new k("Could not decode realtime token",{code:"INVALID_TOKEN",cause:s})}}get supabase(){return this.session.resource.supabase}get realtime(){return this.session.resource.realtime}async connectUser(t){await this.session.connect(T(t,"appUserId"))}async disconnectUser(){await this.session.disconnect()}async getUsers(t={}){this.requireConnected();let e=Ye(t.limit??50,"limit"),r=Ye(t.offset??0,"offset"),s=await this.request("/api/v1/user",{query:{limit:e,offset:r}}),n=L(s),i=Array.isArray(n.data)?n.data:[];return{data:i.map(Fn),totalCount:typeof n.total_count=="number"?n.total_count:i.length}}async getUser(t){this.requireConnected();let e=await this.request(`/api/v1/user/${encodeURIComponent(T(t,"id"))}`);return Fn(L(e).data)}async getConversations(t={}){this.requireConnected();let e=Ye(t.limit??50,"limit"),r=Ye(t.offset??0,"offset"),s=await this.request("/api/v1/conversations",{query:{limit:e,offset:r,...t.archived===!0?{archived:!0}:{}}}),n=L(s).conversations;return Array.isArray(n)?n.map(Rt):[]}async listInbox(t={}){this.requireConnected();let e=Ct(t.limit??30,"limit",1,100),r=t.cursor??void 0;if(r!==void 0&&(typeof r!="string"||r.trim()===""))throw new k("cursor must be a non-empty string",{code:"INVALID_ARGUMENT"});let s=await this.request("/api/v1/inbox",{query:{limit:e,...r===void 0?{}:{cursor:r},...t.archived===!0?{archived:!0}:{}}});return Ga(s)}async getConversation(t){this.requireConnected();let e=await this.request(`/api/v1/conversations/${encodeURIComponent(T(t,"id"))}`),r=L(e),s=La(r.membership);return{...Rt(r.conversation),...s===null?{}:{membership:s}}}async createConversation(t){this.requireConnected();let e=await this.request("/api/v1/conversations",{method:"POST",body:{participants:t.participants,...t.title===void 0?{}:{title:t.title},...t.description===void 0?{}:{description:t.description},...t.imageUrl===void 0?{}:{imageUrl:t.imageUrl}}});return Rt(L(e).conversation)}async markConversationRead(t,e={}){this.requireConnected();let r=e.throughMessageId;if(r!==void 0&&typeof r!="string")throw new k("throughMessageId must be a string",{code:"INVALID_ARGUMENT"});let s=e.privateStateVersion;await this.request(`/api/v1/conversations/${encodeURIComponent(T(t,"conversationId"))}/read`,{method:"POST",body:{...r===void 0?{}:{throughMessageId:T(r,"throughMessageId")},...s===void 0?{}:{privateStateVersion:Xn(s,"privateStateVersion")}}})}async markConversationUnread(t){this.requireConnected();let e=await this.request(`/api/v1/conversations/${encodeURIComponent(T(t,"conversationId"))}/unread`,{method:"POST"});return Qn(e)}async clearConversationUnread(t,e={}){this.requireConnected();let r=e.ifVersion,s=await this.request(`/api/v1/conversations/${encodeURIComponent(T(t,"conversationId"))}/unread`,{method:"DELETE",query:r===void 0?{}:{privateStateVersion:Xn(r,"ifVersion")}});return $a(s)}async sendTyping(t){this.requireConnected(),await this.request(`/api/v1/conversations/${encodeURIComponent(T(t.conversationId,"conversationId"))}/typing`,{method:"POST",body:{isTyping:t.isTyping}})}async updatePresence(t){this.requireConnected(),await this.request("/api/v1/presence",{method:"POST",body:{isOnline:t.isOnline}})}async leaveConversation(t){return this.conversationAction(t,"leave","POST")}async archiveConversation(t){return this.conversationAction(t,"archive","POST")}async unarchiveConversation(t){return this.conversationAction(t,"archive","DELETE")}async updateConversationTitle(t){this.requireConnected();let e=await this.request(`/api/v1/conversations/${encodeURIComponent(T(t.conversationId,"conversationId"))}/title`,{method:"PATCH",body:{title:t.title}});return Rt(L(e).conversation)}async getMessages(t){this.requireConnected();let e=Ye(t.offset??0,"offset"),r=t.beforeCreatedAt!==void 0,s=t.beforeId!==void 0;if(r!==s||r&&e!==0)throw new k("Provide both cursor values without a nonzero offset",{code:"INVALID_ARGUMENT"});let n;if(r&&s){if(!(t.beforeCreatedAt instanceof Date)||!Number.isFinite(t.beforeCreatedAt.getTime()))throw new k("beforeCreatedAt must be a valid Date",{code:"INVALID_ARGUMENT"});n={beforeCreatedAt:t.beforeCreatedAt.toISOString(),beforeId:T(t.beforeId,"beforeId")}}let i=await this.request("/api/v1/messages",{query:{conversationId:T(t.conversationId,"conversationId"),limit:Ye(t.limit??20,"limit"),offset:e,...n}}),o=L(i).data;return Array.isArray(o)?o.map(ve):[]}async listMessages(t){this.requireConnected();let e=Ct(t.limit??20,"limit",1,100),r=t.cursor??void 0;if(r!==void 0&&(typeof r!="string"||r.trim()===""))throw new k("cursor must be a non-empty string",{code:"INVALID_ARGUMENT"});let s=await this.request("/api/v1/messages",{query:{conversationId:T(t.conversationId,"conversationId"),limit:e,...r===void 0?{}:{cursor:r}}});return za(s)}async getMessage(t){this.requireConnected();let e=await this.request(`/api/v1/messages/${encodeURIComponent(T(t,"id"))}`);return ve(L(e).data)}async sendMessage(t){this.requireConnected();let e=await this.request("/api/v1/messages",{method:"POST",body:{conversationId:T(t.conversationId,"conversationId"),clientMessageId:t.clientMessageId??Yr(),...t.text===void 0?{}:{text:t.text},...t.media===void 0||t.media.length===0?{}:{media:t.media},...t.replyToMessageId===void 0?{}:{replyToMessageId:T(t.replyToMessageId,"replyToMessageId")}}});return ve(L(e).data)}async editMessage(t,e){this.requireConnected();let r=T(t,"messageId"),s=e.text;if(s===void 0)throw new k("text is required",{code:"INVALID_ARGUMENT"});if(s!==null&&typeof s!="string")throw new k("text must be a string or null",{code:"INVALID_ARGUMENT"});let n=Pa(e.revision,"revision"),i=await this.request(`/api/v1/messages/${encodeURIComponent(r)}/own`,{method:"PATCH",body:{text:s,revision:n}});return ve(L(i).data)}async deleteMessage(t){this.requireConnected(),await this.request(`/api/v1/messages/${encodeURIComponent(T(t,"messageId"))}/own`,{method:"DELETE"})}async sendCardEvent(t,e,r){if(this.requireConnected(),e!=="opened"&&e!=="escape"&&e!=="quick_reply")throw new TypeError("event must be opened, escape or quick_reply");if(e==="quick_reply"?!r||typeof r!="string":r!==void 0)throw new TypeError(e==="quick_reply"?"optionId is required for quick_reply":"optionId is only allowed with quick_reply");await this.request(`/api/v1/automation/cards/${encodeURIComponent(Oe(t,"messageId"))}/events`,{method:"POST",body:e==="quick_reply"?{event:e,optionId:r}:{event:e}})}async addReaction(t,e){this.requireConnected();let r=await this.request(`/api/v1/messages/${encodeURIComponent(Oe(t,"messageId"))}/reactions`,{method:"POST",body:{emoji:Xr(e)}});return Hn(r)}async removeReaction(t,e){this.requireConnected();let r=await this.request(`/api/v1/messages/${encodeURIComponent(Oe(t,"messageId"))}/reactions`,{method:"DELETE",query:{emoji:Xr(e)}});return Hn(r)}async getReactionSummaries(t,e){this.requireConnected();let r=this.session.capture(),s=T(t,"conversationId");if(!Array.isArray(e)||e.length===0)throw new k("messageIds must be a non-empty array",{code:"INVALID_ARGUMENT"});let n=Array.from(new Set(e.map(o=>Oe(o,"messageIds")))),i=[];for(let o=0;o<n.length;o+=Jn){r();let a=await this.request(`/api/v1/conversations/${encodeURIComponent(s)}/reactions`,{query:{ids:n.slice(o,o+Jn).join(",")}});i.push(...Na(a))}return r(),i}async listReactionUsers(t,e,r={}){this.requireConnected();let s=Oe(t,"messageId"),n=Ct(r.limit??30,"limit",1,100),i=r.cursor===void 0?void 0:T(r.cursor,"cursor"),o=await this.request(`/api/v1/messages/${encodeURIComponent(s)}/reactions`,{query:{emoji:Xr(e),limit:n,...i===void 0?{}:{cursor:i}}});return Ua(o)}async getReplyPreviews(t,e){this.requireConnected();let r=this.session.capture(),s=T(t,"conversationId");if(!Array.isArray(e))throw new k("messageIds must be an array",{code:"INVALID_ARGUMENT"});if(e.length===0)throw new k("messageIds must not be empty",{code:"INVALID_ARGUMENT"});let n=[],i=new Set;for(let a of e){let c=Oe(a,"messageIds");i.has(c)||(i.add(c),n.push(c))}let o=[];for(let a=0;a<n.length;a+=zn){r();let c=await this.request(`/api/v1/conversations/${encodeURIComponent(s)}/reply-previews`,{query:{ids:n.slice(a,a+zn).join(",")}}),l=L(c).data;if(!Array.isArray(l))throw new TypeError("Invalid ConvoKit reply previews: missing data");for(let u of l)o.push(Fa(u))}return o}async getMessageContext(t,e={}){this.requireConnected();let r=T(t,"conversationId"),s=Ct(e.limit??30,"limit",1,100),i=["messageId","olderCursor","newerCursor"].filter(c=>e[c]!==void 0);if(i.length!==1)throw new k("Use a message ID or a cursor, not both",{code:"INVALID_ARGUMENT"});let o={limit:s};if(e.messageId!==void 0)o.messageId=Oe(e.messageId,"messageId");else{let c=i[0],l=e[c];if(typeof l!="string"||l.trim()==="")throw new k(`${c} must be a non-empty string`,{code:"INVALID_ARGUMENT"});o[c]=l}let a=await this.request(`/api/v1/conversations/${encodeURIComponent(r)}/context`,{query:o});return Ka(a)}async uploadUserAvatar(t){this.requireConnected();let e=this.session.capture(),r=await this.upload({folder:"user_avatar",bytes:t.bytes,fileName:t.fileName,...t.contentType===void 0?{}:{contentType:t.contentType},userId:T(t.userId,"userId")});return e(),await this.request(`/api/v1/user/${encodeURIComponent(t.userId)}/avatar`,{method:"PATCH",body:{imageUrl:r}}),r}async uploadConversationImage(t){this.requireConnected();let e=this.session.capture(),r=T(t.conversationId,"conversationId"),s=await this.upload({folder:"conversation_image",bytes:t.bytes,fileName:t.fileName,...t.contentType===void 0?{}:{contentType:t.contentType},conversationId:r});return e(),await this.request(`/api/v1/conversations/${encodeURIComponent(r)}/image`,{method:"PATCH",body:{imageUrl:s}}),s}async uploadMessageMedia(t){return this.requireConnected(),this.upload({folder:"message_media",bytes:t.bytes,fileName:t.fileName,...t.contentType===void 0?{}:{contentType:t.contentType},conversationId:T(t.conversationId,"conversationId")})}async deleteUserAvatar(t){this.requireConnected(),await this.request(`/api/v1/user/${encodeURIComponent(T(t.userId,"userId"))}/avatar`,{method:"DELETE"})}async deleteConversationImage(t){this.requireConnected(),await this.request(`/api/v1/conversations/${encodeURIComponent(T(t.conversationId,"conversationId"))}/image`,{method:"DELETE"})}async downloadMedia(t){this.requireConnected();let e=this.session.capture(),s=await(await this.requestRaw("/api/v1/media/download",{query:{url:T(t,"url")}})).blob();return e(),s}requireConnected(){this.currentUserId}requireUserToken(){return this.session.tokens.userToken}request(t,e={}){return this.session.request(r=>this.transport.request(t,{...e,authenticated:!1,headers:{...e.headers,"Content-Type":"application/json",Authorization:`Bearer ${r}`}}))}requestRaw(t,e={}){return this.session.request(r=>this.transport.requestRaw(t,{...e,authenticated:!1,headers:{...e.headers,"Content-Type":"application/json",Authorization:`Bearer ${r}`}}))}async conversationAction(t,e,r){this.requireConnected();let s=await this.request(`/api/v1/conversations/${encodeURIComponent(T(t,"id"))}/${e}`,{method:r}),n=L(s).conversationId;return T(typeof n=="string"?n:"","conversationId response")}async upload(t){let e=this.session.capture(),r=await this.request("/api/v1/media/sign-upload",{method:"POST",query:{folder:t.folder,fileName:T(t.fileName,"fileName"),contentType:t.contentType,userId:t.userId,conversationId:t.conversationId}});e();let s=L(L(r).data),n=T(String(s.uploadUrl??""),"uploadUrl response"),i=T(String(s.fileUrl??""),"fileUrl response"),o=T(String(s.objectKey??""),"objectKey response"),a=typeof s.contentType=="string"?s.contentType:"application/octet-stream",c;try{c=await this.fetchImplementation(n,{method:"PUT",headers:{"Content-Type":a},body:rc(t.bytes)})}catch(l){throw new k("Could not upload media to storage",{code:"UPLOAD_NETWORK_ERROR",cause:l})}if(!c.ok)throw new k(`Media upload failed with status ${c.status}`,{code:"UPLOAD_ERROR",status:c.status});return e(),await this.request("/api/v1/media/complete-upload",{method:"POST",body:{objectKey:o}}),i}};var ti=(t,e)=>t.createdAt.getTime()>e.createdAt.getTime()||t.createdAt.getTime()===e.createdAt.getTime()&&t.id>e.id;function ri(t,e,r){for(let s of e)if(s.senderId===r&&s.id!==t.id&&ti(s,t))return!0;return!1}function si(t){let e;for(let r of t)r.card&&(!e||ti(r,e))&&(e=r);return e}var Pe=class extends Error{constructor(r,s,n){super(r);this.status=s;this.code=n}};function ai(t){try{return t==="SESSION"?window.sessionStorage:window.localStorage}catch{return null}}var ci=t=>`convokit-widget:${t}:guest`;function sc(t){try{return ai(t.storageMode)?.getItem(ci(t.clientId))??null}catch{return null}}function nc(t,e){try{ai(t.storageMode)?.setItem(ci(t.clientId),e)}catch{}}async function ni(t,e,r){let s=await r(`${t.apiUrl}/api/v1/widget/session`,{method:"POST",headers:{"Content-Type":"application/json","x-client-id":t.clientId,"x-widget-key":t.widgetKey},body:JSON.stringify(e)}),n=await s.json().catch(()=>null);if(!s.ok||!n?.data?.token||!n.data.appUserId)throw new Pe(n?.error??"Could not start the chat session",s.status,n?.code);return n.data}function ii(t){let e={};return t.user?.name&&(e.name=t.user.name),t.user?.imageUrl&&(e.imageUrl=t.user.imageUrl),e}function oi(t,e){let r=t.token;return{appUserId:t.appUserId,showBranding:t.showBranding===!0,tokenProvider:async s=>{if(r){let i=r;return r=null,i}let n=await e();if(n.appUserId!==s)throw new Pe("The chat session belongs to a different user",401);return n.token}}}async function li(t,e=fetch){if(t.mode==="guest"){let s=()=>ni(t,{mode:"guest",resumeToken:sc(t),...ii(t)},e).then(n=>(n.resumeToken&&nc(t,n.resumeToken),n));return oi(await s(),s)}if(t.mode==="uid"){let s=()=>ni(t,{mode:"uid",uid:t.uid,...ii(t)},e);return oi(await s(),s)}let r=t.tokenProvider??(async s=>{let n=await e(t.tokenUrl,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({appUserId:s})}),i=await n.json().catch(()=>null),o=i?.token??i?.data?.token;if(!n.ok||!o)throw new Pe("Your token endpoint did not return a token",n.status);return o});return{appUserId:t.userId,tokenProvider:r,showBranding:!1}}var ui=(t,e,r,s)=>`
29
+ `);let C=await A.signMessage(new TextEncoder().encode(p),"utf8");if(!C||!(C instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");g=C}}try{let{data:m,error:w}=await v(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:he(g)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(h=e.options)===null||h===void 0?void 0:h.captchaToken}}:null),xform:V});if(w)throw w;if(!m||!m.session||!m.user){let _=new de;return this._returnResult({data:{user:null,session:null},error:_})}return m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("SIGNED_IN",m.session)),this._returnResult({data:Object.assign({},m),error:w})}catch(m){if(y(m))return this._returnResult({data:{user:null,session:null},error:m});throw m}}async _exchangeCodeForSession(e,r){let s=r?.flowId!=null,n=s?St(r?.flowId):j()?St(Rr(window.location.href)[ue]):null;s&&!n&&this._debug("#_exchangeCodeForSession()","provided flowId is not a valid flow id",r?.flowId);let{verifier:i,flowId:o}=s&&!n?{verifier:null,flowId:null}:await cn(this.storage,this.storageKey,n),[a,c]=(i??"").split("/");try{if(!a&&this.flowType==="pkce")throw new Wt;let{data:l,error:u}=await v(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:a},xform:V});if(await z(this.storage,this.storageKey,o),u)throw u;if(!l||!l.session||!l.user){let d=new de;return this._returnResult({data:{user:null,session:null,redirectType:null},error:d})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers(c==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l.session)),this._returnResult({data:Object.assign(Object.assign({},l),{redirectType:c??null}),error:u})}catch(l){if(await z(this.storage,this.storageKey,o),y(l))return this._returnResult({data:{user:null,session:null,redirectType:null},error:l});throw l}}async signInWithIdToken(e){try{let{options:r,provider:s,token:n,access_token:i,nonce:o}=e,a=await v(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:n,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:V}),{data:c,error:l}=a;if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!c||!c.session||!c.user){let u=new de;return this._returnResult({data:{user:null,session:null},error:u})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:l})}catch(r){if(y(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,s,n,i,o;let a=null;try{if("email"in e){let{email:c,options:l}=e,u=null,d=null;this.flowType==="pkce"&&([u,d,a]=await this._getCodeChallengeAndMethod());let{error:f}=await v(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:c,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:u,code_challenge_method:d},redirectTo:this._maybeAppendFlowIdToRedirect(l?.emailRedirectTo,a)});return this._returnResult({data:{user:null,session:null},error:f})}if("phone"in e){let{phone:c,options:l}=e,{data:u,error:d}=await v(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:c,data:(n=l?.data)!==null&&n!==void 0?n:{},create_user:(i=l?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u?.message_id},error:d})}throw new Se("You must provide either an email or phone number.")}catch(c){if(await z(this.storage,this.storageKey,a),y(c))return this._returnResult({data:{user:null,session:null},error:c});throw c}}async verifyOtp(e){var r,s;try{let n,i;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,i=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:o,error:a}=await v(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:V});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,l=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:l,session:c},error:null})}catch(n){if(y(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,s,n,i;let o=null;try{let a=null,c=null;this.flowType==="pkce"&&([a,c,o]=await this._getCodeChallengeAndMethod());let l=await v(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:this._maybeAppendFlowIdToRedirect((r=e.options)===null||r===void 0?void 0:r.redirectTo,o)}),!((s=e?.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:c}),headers:this.headers,xform:vn});return!((n=l.data)===null||n===void 0)&&n.url&&j()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(l.data.url),this._returnResult(l)}catch(a){if(await z(this.storage,this.storageKey,o),y(a))return this._returnResult({data:null,error:a});throw a}}async reauthenticate(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:r},error:s}=e;if(s)throw s;if(!r)throw new P;let{error:n}=await v(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(y(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){let r=null;try{let s=`${this.url}/resend`;if("email"in e){let{email:n,type:i,options:o}=e,a=null,c=null;this.flowType==="pkce"&&([a,c,r]=await this._getCodeChallengeAndMethod());let{error:l}=await v(this.fetch,"POST",s,{headers:this.headers,body:{email:n,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken},code_challenge:a,code_challenge_method:c},redirectTo:this._maybeAppendFlowIdToRedirect(o?.emailRedirectTo,r)});return l&&await z(this.storage,this.storageKey,r),this._returnResult({data:{user:null,session:null},error:l})}else if("phone"in e){let{phone:n,type:i,options:o}=e,{data:a,error:c}=await v(this.fetch,"POST",s,{headers:this.headers,body:{phone:n,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:a?.message_id},error:c})}throw new Se("You must provide either an email or phone number and a type")}catch(s){if(await z(this.storage,this.storageKey,r),y(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async getSession(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e)):await this._useSession(async e=>e)}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await s,await r()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let s=r();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){let n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await s}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 r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lock!=null&&!this.lockAcquired&&this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,r=await D(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let s=e.expires_at?e.expires_at*1e3-Date.now()<Ft:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s)return{data:{session:await this._hydrateSessionUser(e)},error:null};let{data:n,error:i}=await this._callRefreshToken(e.refresh_token);if(i){let o=await D(this.storage,this.storageKey);return o&&this._isValidSession(o)&&o.expires_at&&o.expires_at*1e3>Date.now()?this._returnResult({data:{session:await this._hydrateSessionUser(o)},error:null}):this._returnResult({data:{session:null},error:i})}return this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async _hydrateSessionUser(e){if(this.userStorage){let r=await D(this.userStorage,this.storageKey+"-user");e.user=r?.user?r.user:Xt()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let r={value:this.suppressGetSessionWarning};e.user=gn(e.user,r),r.value&&(this.suppressGetSessionWarning=!0)}return e}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let r;return this.lock!=null?r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):r=await this._getUser(),r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await v(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ie}):await this._useSession(async r=>{var s,n,i;let{data:o,error:a}=r;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new P}:await v(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=o.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:ie})})}catch(r){if(y(r))return vt(r)&&await this._removeSession(),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r)):await this._updateUser(e,r)}async _updateUser(e,r={}){let s=null;try{return await this._useSession(async n=>{let{data:i,error:o}=n;if(o)throw o;if(!i.session)throw new P;let a=i.session,c=null,l=null;this.flowType==="pkce"&&e.email!=null&&([c,l,s]=await this._getCodeChallengeAndMethod());let{data:u,error:d}=await v(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(r?.emailRedirectTo,s),body:Object.assign(Object.assign({},e),{code_challenge:c,code_challenge_method:l}),jwt:a.access_token,xform:ie});if(d)throw d;return a.user=u.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),this._returnResult({data:{user:a.user},error:null})})}catch(n){if(await z(this.storage,this.storageKey,s),y(n))return this._returnResult({data:{user:null},error:n});throw n}}async setSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e)):await this._setSession(e)}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new P;let r=Date.now()/1e3,s=r,n=!0,i=null,{payload:o}=Et(e.access_token);if(o.exp&&(s=o.exp,n=s<=r),n){let{data:a,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!a)return{data:{user:null,session:null},error:null};i=a}else{let{data:a,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:a.user,token_type:"bearer",expires_in:s-r,expires_at:s},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(r){if(y(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e)):await this._refreshSession(e)}async _refreshSession(e){try{return await this._useSession(async r=>{var s;if(!e){let{data:o,error:a}=r;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new P;let{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(y(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){var s;try{if(!j())throw new ke("No browser detected.");if(e.error||e.error_description||e.error_code)throw new ke(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new gt("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new ke("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new gt("No code detected.");let{data:b,error:A}=await this._exchangeCodeForSession(e.code,{flowId:e[ue]});if(A)throw A;let B=new URL(window.location.href);return B.searchParams.delete("code"),B.searchParams.delete(ue),window.history.replaceState(window.history.state,"",B.toString()),{data:{session:b.session,redirectType:(s=b.redirectType)!==null&&s!==void 0?s:null},error:null}}let{provider_token:n,provider_refresh_token:i,access_token:o,refresh_token:a,expires_in:c,expires_at:l,token_type:u}=e;if(!o||!c||!a||!u)throw new ke("No session defined in URL");let d=Math.round(Date.now()/1e3),f=parseInt(c),h=d+f;l&&(h=parseInt(l));let p=h-d;p*1e3<=re&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${f}s`);let g=h-f;d-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,h,d):d-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",g,h,d);let{data:m,error:w}=await this._getUser(o);if(w)throw w;let _={provider_token:n,provider_refresh_token:i,access_token:o,expires_in:f,expires_at:h,refresh_token:a,token_type:u,user:m.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:_,redirectType:e.type},error:null})}catch(n){if(y(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||e.error_description||e.error_code)}async _isPKCECallback(e){if(!e.code)return!1;let r=St(e[ue]);return r&&await D(this.storage,Re(this.storageKey,r))?!0:!!await D(this.storage,`${this.storageKey}-code-verifier`)}async signOut(e={scope:"global"}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e)):await this._signOut(e)}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var s;let n=async()=>{await this._removeSession()},{data:i,error:o}=r;if(o&&!vt(o))return this._returnResult({error:o});let a=(s=i.session)===null||s===void 0?void 0:s.access_token;if(a){let{error:c}=await this.admin.signOut(a,e);if(c&&!(kr(c)&&(c.status===404||c.status===401||c.status===403)||vt(c)))return e!=="others"&&await n(),this._returnResult({error:c})}return e!=="others"&&await n(),this._returnResult({error:null})})}onAuthStateChange(e){let r=rn(),s={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,s),(async()=>(await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)}):await this._emitInitialSession(r)))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async r=>{var s,n;try{let{data:{session:i},error:o}=r;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){if(await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),Tr(i))return;vt(i)||wt(i)||kr(i)&&(i.code==="refresh_token_not_found"||i.code==="refresh_token_already_used"||i.code==="session_expired")?console.warn(i):console.error(i)}})}async resetPasswordForEmail(e,r={}){let s=null,n=null,i=null;this.flowType==="pkce"&&([s,n,i]=await this._getCodeChallengeAndMethod(!0));try{return await v(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(r.redirectTo,i)})}catch(o){if(await z(this.storage,this.storageKey,i),y(o))return this._returnResult({data:null,error:o});throw o}}async getUserIdentities(){var e;try{let{data:r,error:s}=await this.getUser();if(s)throw s;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;let s=null;try{let{data:n,error:i}=await this._useSession(async o=>{var a,c,l,u,d;let{data:f,error:h}=o;if(h)throw h;let{url:p,flowId:g}=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(a=e.options)===null||a===void 0?void 0:a.redirectTo,scopes:(c=e.options)===null||c===void 0?void 0:c.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return s=g,await v(this.fetch,"GET",p,{headers:this.headers,jwt:(d=(u=f.session)===null||u===void 0?void 0:u.access_token)!==null&&d!==void 0?d:void 0})});if(i)throw i;return j()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n?.url),this._returnResult({data:{provider:e.provider,url:n?.url,flowId:s},error:null})}catch(n){if(y(n))return this._returnResult({data:{provider:e.provider,url:null,flowId:s},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var s;try{let{error:n,data:{session:i}}=r;if(n)throw n;let{options:o,provider:a,token:c,access_token:l,nonce:u}=e,d=await v(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=i?.access_token)!==null&&s!==void 0?s:void 0,body:{provider:a,id_token:c,access_token:l,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:V}),{data:f,error:h}=d;return h?this._returnResult({data:{user:null,session:null},error:h}):!f||!f.session||!f.user?this._returnResult({data:{user:null,session:null},error:new de}):(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("USER_UPDATED",f.session)),this._returnResult({data:f,error:h}))}catch(n){if(await z(this.storage,this.storageKey,null),y(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var s,n;let{data:i,error:o}=r;if(o)throw o;return await v(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(s=i.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){let r="#_refreshAccessToken()";this._debug(r,"begin");try{let s=Date.now();return await on(async n=>(n>0&&await nn(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await v(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:V})),(n,i)=>{let o=200*Math.pow(2,n);return i&&wt(i)&&Date.now()+o-s<re})}catch(s){if(this._debug(r,"error",s),y(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){let{url:s,flowId:n}=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",s),j()&&!r.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s,flowId:n},error:null}}async _recoverAndRefresh(){var e,r;let s="#_recoverAndRefresh()";this._debug(s,"begin");try{let n=await D(this.storage,this.storageKey);if(n&&this.userStorage){let o=await D(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:n.user},await se(this.userStorage,this.storageKey+"-user",o)),n.user=(e=o?.user)!==null&&e!==void 0?e:Xt()}else if(n&&!n.user&&!n.user){let o=await D(this.storage,this.storageKey+"-user");o&&o?.user?(n.user=o.user,await H(this.storage,this.storageKey+"-user"),await se(this.storage,this.storageKey,n)):n.user=Xt()}if(this._debug(s,"session from storage",n),!this._isValidSession(n)){this._debug(s,"session is not valid"),n!==null&&await this._removeSession();return}let i=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<Ft;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${Ft}s`),i){if(this.autoRefreshToken&&n.refresh_token){let{error:o}=await this._callRefreshToken(n.refresh_token);o&&(Tr(o)?this._debug(s,"refresh discarded by commit guard",o):this._debug(s,"refresh failed",o))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{let{data:o,error:a}=await this._getUser(n.access_token);!a&&o?.user?(n.user=o.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(s,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(s,"error",n),wt(n)?console.warn(n):console.error(n);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var r,s;if(!e)throw new P;if(this.refreshingDeferred)return this.refreshingDeferred.promise;if(this.lastRefreshFailure&&this.lastRefreshFailure.refreshToken===e&&Date.now()<this.lastRefreshFailure.expiresAt)return this._debug("#_callRefreshToken()","returning cached failure (cooldown active)"),this.lastRefreshFailure.result;let n="#_callRefreshToken()";this._debug(n,"begin");try{this.refreshingDeferred=new bt,this.refreshingDeferred.promise.then(void 0,()=>{});let i=await D(this.storage,this.storageKey),{data:o,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!o.session)throw new P;let c=await D(this.storage,this.storageKey);if(i!==null&&(c===null||c.refresh_token!==i.refresh_token)){this._debug(n,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:c?"replaced":"cleared"});let f={data:null,error:new mt};return this.refreshingDeferred.resolve(f),f}let u=this._sessionRemovalEpoch;if(await this._saveSession(o.session),this._sessionRemovalEpoch!==u){this._debug(n,"commit guard (post-save): _removeSession ran during _saveSession, undoing write"),await H(this.storage,this.storageKey),this.userStorage&&await H(this.userStorage,this.storageKey+"-user");let f={data:null,error:new mt};return this.refreshingDeferred.resolve(f),f}await this._notifyAllSubscribers("TOKEN_REFRESHED",o.session);let d={data:o.session,error:null};return this.lastRefreshFailure=null,this.refreshingDeferred.resolve(d),d}catch(i){if(this._debug(n,"error",i),y(i)){let o={data:null,error:i};if(!wt(i)){let a=await D(this.storage,this.storageKey);!!(a?.expires_at&&a.expires_at*1e3>Date.now())?this._debug(n,"proactive refresh failed, access token still valid \u2014 preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:o,expiresAt:Date.now()+Ks},(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,s=!0){if(this._pendingInitNotifications!==null&&s){this._pendingInitNotifications.push({event:e,session:r,broadcast:s});return}let n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:r});let i=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r)}catch(c){i.push(c)}});if(await Promise.all(o),i.length>0){for(let a=0;a<i.length;a+=1)console.error(i[a]);throw i[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0;let r=Object.assign({},e),s=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&r.user&&await se(this.userStorage,this.storageKey+"-user",{user:r.user});let n=Object.assign({},r);delete n.user;let i=xr(n);await se(this.storage,this.storageKey,i)}else{let n=xr(r);await se(this.storage,this.storageKey,n)}}async _removeSession(){this._sessionRemovalEpoch+=1,this._debug("#_removeSession()"),this.lastRefreshFailure=null,this.suppressGetSessionWarning=!1,await H(this.storage,this.storageKey),await ln(this.storage,this.storageKey),await H(this.storage,this.storageKey+"-user"),this.userStorage&&await H(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&j()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),re);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(e=this.broadcastChannel)===null||e===void 0||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),this.lock!=null){try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async r=>{let{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((s.expires_at*1e3-e)/re);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${re}ms, refresh threshold is ${ze} ticks`),n<=ze&&await this._callRefreshToken(s.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof Qt)this._debug("auto refresh token tick lock not available");else throw e}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{let e=Date.now();try{await this._useSession(async r=>{let{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((s.expires_at*1e3-e)/re);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${re}ms, refresh threshold is ${ze} ticks`),n<=ze&&await this._callRefreshToken(s.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!j()||!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?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let r=`#_onVisibilityChanged(${e})`;if(this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"){if(this.autoRefreshToken&&this._startAutoRefresh(),!e)if(await this.initializePromise,this.lock!=null)await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()});else{if(document.visibilityState!=="visible"){this._debug(r,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}else document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,s){let n=s?.redirectTo,i=null,o=null,a=null;this.flowType==="pkce"&&([i,o,a]=await this._getCodeChallengeAndMethod(),n=this._maybeAppendFlowIdToRedirect(n,a));let c=[`provider=${encodeURIComponent(r)}`];if(n&&c.push(`redirect_to=${encodeURIComponent(n)}`),s?.scopes&&c.push(`scopes=${encodeURIComponent(s.scopes)}`),i!=null&&o!=null){let l=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});c.push(l.toString())}if(s?.queryParams){let l=new URLSearchParams(s.queryParams);c.push(l.toString())}return s?.skipBrowserRedirect&&c.push(`skip_http_redirect=${s.skipBrowserRedirect}`),{url:`${e}?${c.join("&")}`,flowId:a}}_maybeAppendFlowIdToRedirect(e,r){return!e||!r||!this.experimental.appendPkceFlowIdToRedirects?e??void 0:un(e,r)}async _getCodeChallengeAndMethod(e=!1){return dn(this.storage,this.storageKey,e,r=>this._debug("#_getCodeChallengeAndMethod()","evicted oldest pending PKCE verifier slot",r))}async _unenroll(e){try{return await this._useSession(async r=>{var s;let{data:n,error:i}=r;return i?this._returnResult({data:null,error:i}):await v(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var s,n;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:l}=await v(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return l?this._returnResult({data:null,error:l}):(e.factorType==="totp"&&c.type==="totp"&&(!((n=c?.totp)===null||n===void 0)&&n.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){let r=async()=>{try{return await this._useSession(async s=>{var n;let{data:i,error:o}=s;if(o)return this._returnResult({data:null,error:o});let a=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Dr(e.webauthn.credential_response):Mr(e.webauthn.credential_response)})}:{code:e.code}),{data:c,error:l}=await v(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:a,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});return l?this._returnResult({data:null,error:l}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+c.expires_in},c)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",c),this._returnResult({data:c,error:l}))})}catch(s){if(y(s))return this._returnResult({data:null,error:s});throw s}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _challenge(e){let r=async()=>{try{return await this._useSession(async s=>{var n;let{data:i,error:o}=s;if(o)return this._returnResult({data:null,error:o});let a=await v(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});if(a.error)return a;let{data:c}=a;if(c.type!=="webauthn")return{data:c,error:null};switch(c.webauthn.type){case"create":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:Lr(c.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:$r(c.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(s){if(y(s))return this._returnResult({data:null,error:s});throw s}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _challengeAndVerify(e){let{data:r,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};let n={all:[],phone:[],totp:[],webauthn:[],recovery_code:[]};for(let i of(e=r?.factors)!==null&&e!==void 0?e:[])n.all.push(i),i.status==="verified"&&i.factor_type in n&&Array.isArray(n[i.factor_type])&&n[i.factor_type].push(i);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,s,n,i;if(e)try{let{payload:h}=Et(e),p=null;h.aal&&(p=h.aal);let g=p,{data:{user:m},error:w}=await this.getUser(e);if(w)return this._returnResult({data:null,error:w});((s=(r=m?.factors)===null||r===void 0?void 0:r.filter(A=>A.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(g="aal2");let b=h.amr||[];return{data:{currentLevel:p,nextLevel:g,currentAuthenticationMethods:b},error:null}}catch(h){if(y(h))return this._returnResult({data:null,error:h});throw h}let{data:{session:o},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:c}=Et(o.access_token),l=null;c.aal&&(l=c.aal);let u=l;((i=(n=o.user.factors)===null||n===void 0?void 0:n.filter(h=>h.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(u="aal2");let f=c.amr||[];return{data:{currentLevel:l,nextLevel:u,currentAuthenticationMethods:f},error:null}}async _getRecoveryCodesStatus(){Je(this.experimental);try{return await this._useSession(async e=>{var r;let{data:s,error:n}=e;if(n)return this._returnResult({data:null,error:n});let{data:i,error:o}=await v(this.fetch,"GET",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(y(e))return this._returnResult({data:null,error:e});throw e}}async _generateRecoveryCodes(e){Je(this.experimental);try{return await this._useSession(async r=>{var s;let{data:n,error:i}=r;if(i)return this._returnResult({data:null,error:i});let{data:o,error:a}=await v(this.fetch,"POST",`${this.url}/factors/recovery-codes`,{body:e?.friendlyName?{friendly_name:e.friendlyName}:void 0,headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return a?this._returnResult({data:null,error:a}):this._returnResult({data:o,error:null})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _verifyRecoveryCode(e){Je(this.experimental);let r=async()=>{try{return await this._useSession(async s=>{var n;let{data:i,error:o}=s;if(o)return this._returnResult({data:null,error:o});let{data:a,error:c}=await v(this.fetch,"POST",`${this.url}/factors/recovery-codes/verify`,{body:{code:e.code},headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});if(c)return this._returnResult({data:null,error:c});let l=Object.assign({expires_at:Gt(a.expires_in)},a);return await this._saveSession(l),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",l),this._returnResult({data:a,error:null})})}catch(s){if(y(s))return this._returnResult({data:null,error:s});throw s}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _regenerateRecoveryCodes(){Je(this.experimental);try{return await this._useSession(async e=>{var r;let{data:s,error:n}=e;if(n)return this._returnResult({data:null,error:n});let{data:i,error:o}=await v(this.fetch,"POST",`${this.url}/factors/recovery-codes/regenerate`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(y(e))return this._returnResult({data:null,error:e});throw e}}async _unenrollRecoveryCodes(){Je(this.experimental);try{return await this._useSession(async e=>{var r;let{data:s,error:n}=e;if(n)return this._returnResult({data:null,error:n});let{data:i,error:o}=await v(this.fetch,"DELETE",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(y(e))return this._returnResult({data:null,error:e});throw e}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?await v(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:s.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new P})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async s=>{let{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new P});let o=await v(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&j()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(s){if(y(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(e,r){try{return await this._useSession(async s=>{let{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new P});let o=await v(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&j()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(s){if(y(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:s}=e;return s?this._returnResult({data:null,error:s}):r?await v(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new P})})}catch(e){if(y(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?(await v(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:s.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new P})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let s=r.keys.find(a=>a.kid===e);if(s)return s;let n=Date.now();if(s=this.jwks.keys.find(a=>a.kid===e),s&&this.jwks_cached_at+Xs>n)return s;let{data:i,error:o}=await v(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=n,s=i.keys.find(a=>a.kid===e),!s)?null:s}async getClaims(e,r={}){try{let s=e;if(!s){let{data:h,error:p}=await this.getSession();if(p||!h.session)return this._returnResult({data:null,error:p});s=h.session.access_token}let{header:n,payload:i,signature:o,raw:{header:a,payload:c}}=Et(s);if(!r?.allowExpired)try{fn(i.exp)}catch(h){throw new me(h instanceof Error?h.message:"JWT validation failed")}let l=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!l){let{error:h}=await this.getUser(s);if(h)throw h;return{data:{claims:i,header:n,signature:o},error:null}}let u=pn(n.alg),d=await crypto.subtle.importKey("jwk",l,u,!0,["verify"]);if(!await crypto.subtle.verify(u,d,o,tn(`${a}.${c}`)))throw new me("Invalid JWT signature");return{data:{claims:i,header:n,signature:o},error:null}}catch(s){if(y(s))return this._returnResult({data:null,error:s});throw s}}async signInWithPasskey(e){var r,s,n,i;try{if(!kt())return this._returnResult({data:null,error:new q("Browser does not support WebAuthn",null)});let{data:o,error:a}=await this._startPasskeyAuthentication({options:{captchaToken:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}});if(a||!o)return this._returnResult({data:null,error:a});let c=$r(o.options),l=(n=(s=e?.options)===null||s===void 0?void 0:s.signal)!==null&&n!==void 0?n:tr.createNewAbortSignal(),{data:u,error:d}=await Br({publicKey:c,signal:l,mediation:(i=e?.options)===null||i===void 0?void 0:i.mediation});if(d||!u)return this._returnResult({data:null,error:d??new q("WebAuthn ceremony failed",null)});let f=Mr(u);return this._verifyPasskeyAuthentication({challengeId:o.challenge_id,credential:f})}catch(o){if(y(o))return this._returnResult({data:null,error:o});throw o}}async registerPasskey(e){var r,s;try{if(!kt())return this._returnResult({data:null,error:new q("Browser does not support WebAuthn",null)});let{data:n,error:i}=await this._startPasskeyRegistration();if(i||!n)return this._returnResult({data:null,error:i});let o=Lr(n.options),a=(s=(r=e?.options)===null||r===void 0?void 0:r.signal)!==null&&s!==void 0?s:tr.createNewAbortSignal(),{data:c,error:l}=await qr({publicKey:o,signal:a});if(l||!c)return this._returnResult({data:null,error:l??new q("WebAuthn ceremony failed",null)});let u=Dr(c);return this._verifyPasskeyRegistration({challengeId:n.challenge_id,credential:u})}catch(n){if(y(n))return this._returnResult({data:null,error:n});throw n}}async _startPasskeyRegistration(){try{return await this._useSession(async e=>{let{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new P});let{data:n,error:i}=await v(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:r.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(e){if(y(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new P});let{data:i,error:o}=await v(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:s.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _startPasskeyAuthentication(e){var r;try{let{data:s,error:n}=await v(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}}});return n?this._returnResult({data:null,error:n}):this._returnResult({data:s,error:null})}catch(s){if(y(s))return this._returnResult({data:null,error:s});throw s}}async _verifyPasskeyAuthentication(e){try{let{data:r,error:s}=await v(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:V});return s?this._returnResult({data:null,error:s}):(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:r,error:null}))}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _listPasskeys(){try{return await this._useSession(async e=>{let{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new P});let{data:n,error:i}=await v(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:r.access_token,xform:o=>({data:o,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(e){if(y(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new P});let{data:i,error:o}=await v(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:s.access_token,body:{friendly_name:e.friendlyName}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _deletePasskey(e){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new P});let{error:i}=await v(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:s.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}};rr.nextInstanceID={};var Hr=rr;var Zo=Hr,Fr=Zo;var ea="2.118.0",Tt="",ir;if(typeof Deno<"u")Tt="deno",ir=(sr=Deno.version)===null||sr===void 0?void 0:sr.deno;else if(typeof document<"u")Tt="web";else if(typeof navigator<"u"&&navigator.product==="ReactNative")Tt="react-native";else{Tt="node";let t=globalThis.process;ir=t==null||(nr=t.version)===null||nr===void 0?void 0:nr.replace(/^v/,"")}var sr,nr,Un=[`runtime=${Tt}`];ir&&Un.push(`runtime-version=${ir}`);var ta={"X-Client-Info":`supabase-js/${ea}; ${Un.join("; ")}`},ra={headers:ta},sa={schema:"public"},na={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},ia={},oa={enabled:!1,respectSamplingDecision:!0};function aa(t){if(!t||typeof t!="string")return null;let e=t.split("-");if(e.length!==4)return null;let[r,s,n,i]=e;if(r.length!==2||s.length!==32||n.length!==16||i.length!==2)return null;let o=/^[0-9a-f]+$/i;return!o.test(r)||!o.test(s)||!o.test(n)||!o.test(i)||s==="00000000000000000000000000000000"||n==="0000000000000000"?null:{version:r,traceId:s,parentId:n,traceFlags:i,isSampled:(parseInt(i,16)&1)===1}}function ca(t,e){if(!t||!e||e.length===0)return!1;let r;if(t instanceof URL)r=t;else try{r=new URL(t)}catch{return!1}for(let s of e)try{if(typeof s=="string"){if(la(r.hostname,s))return!0}else if(s instanceof RegExp){if(s.test(r.hostname))return!0}else if(typeof s=="function"&&s(r))return!0}catch{continue}return!1}function la(t,e){if(e===t)return!0;if(e.startsWith("*.")){let r=e.slice(2);if(t.endsWith(r)&&(t===r||t.endsWith("."+r)))return!0}return!1}function ua(t){let e=[];try{let r=new URL(t);e.push(r.hostname)}catch{}return e.push("*.supabase.co","*.supabase.in"),e.push("localhost","127.0.0.1","[::1]"),e}function At(t){"@babel/helpers - typeof";return At=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},At(t)}function da(t,e){if(At(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(At(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function ha(t){var e=da(t,"string");return At(e)=="symbol"?e:e+""}function fa(t,e,r){return(e=ha(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Rn(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function N(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Rn(Object(r),!0).forEach(function(s){fa(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Rn(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var pa=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),ga=()=>Headers,jn=t=>t.startsWith("sb_publishable_")||t.startsWith("sb_secret_"),ma="sb_temp_",Cn=new Set,ya=t=>{var e,r;if(!t.startsWith("sb_")||jn(t)||t.startsWith(ma))return;let s=(e=(r=t.match(/^sb_[a-zA-Z0-9]+_/))===null||r===void 0?void 0:r[0])!==null&&e!==void 0?e:"unknown";Cn.has(s)||(Cn.add(s),console.warn("@supabase/supabase-js: Unrecognized Supabase API key format. The client will proceed and send this key as-is; if you see authentication errors you may need to upgrade @supabase/supabase-js to a version that recognizes this key type."))},xn=(t,e,r,s,n,i)=>{let o=pa(s),a=ga(),c=n?.enabled===!0,l=n?.respectSamplingDecision!==!1,u=c?ua(e):null,d=!(i?.omitApiKeyAsBearer&&jn(t));return async(f,h)=>{let p=await r(),g=new a(h?.headers);if(g.has("apikey")||g.set("apikey",t),!g.has("Authorization")){let m=p??(d?t:null);m&&g.set("Authorization",`Bearer ${m}`)}if(u){let m=va(f,u,l);m&&(m.traceparent&&!g.has("traceparent")&&g.set("traceparent",m.traceparent),m.tracestate&&!g.has("tracestate")&&g.set("tracestate",m.tracestate),m.baggage&&!g.has("baggage")&&g.set("baggage",m.baggage))}return o(f,N(N({},h),{},{headers:g}))}},In=!1,On=!1;function va(t,e,r){let s=os();if(!s)return In||(In=!0,console.warn("@supabase/supabase-js: tracePropagation is enabled but the tracing runtime is not loaded, so trace headers will not be attached. Add `import '@supabase/supabase-js/tracing'` at your application entry point (requires the OpenTelemetry API package to be installed). The CDN/UMD build does not support trace propagation.")),null;if(!ca(typeof t=="string"||t instanceof URL?t:t.url,e))return null;let n=s();if(!n||!n.traceparent){var i;if(!(n==null||(i=n.carrierKeys)===null||i===void 0)&&i.length&&!On){On=!0;let o=n.carrierKeys.includes("sentry-trace")?" Sentry detected: set `propagateTraceparent: true` in Sentry.init() to emit it.":" Configure your tracing SDK to emit W3C trace context on outgoing requests.";console.warn(`@supabase/supabase-js: tracePropagation is enabled and a tracing SDK is active, but its propagator wrote [${n.carrierKeys.join(", ")}] and no W3C traceparent header, so trace headers will not be attached.`+o)}return null}if(r){let o=aa(n.traceparent);if(o&&!o.isSampled)return{traceparent:n.traceparent}}return n}function Pn(t){return typeof t=="boolean"?{enabled:t}:t}function wa(t){return t.endsWith("/")?t:t+"/"}var Nn=!1;function ba(t){Nn||typeof t!="object"||t===null||!("schema"in t)||t.schema===void 0||(Nn=!0,console.warn(`@supabase/supabase-js: The "schema" option must be nested under "db", e.g. createClient(url, key, { db: { schema: 'myschema' } }). A top-level "schema" is ignored and queries go to the default schema.`))}function _a(t,e){var r,s,n,i,o,a;let{db:c,auth:l,realtime:u,global:d}=t,{db:f,auth:h,realtime:p,global:g}=e,m=Pn(t.tracePropagation),w=Pn(e.tracePropagation),_={db:N(N({},f),c),auth:N(N({},h),l),realtime:N(N({},p),u),storage:{},global:N(N(N({},g),d),{},{headers:N(N({},(r=g?.headers)!==null&&r!==void 0?r:{}),(s=d?.headers)!==null&&s!==void 0?s:{})}),tracePropagation:{enabled:(n=(i=m?.enabled)!==null&&i!==void 0?i:w?.enabled)!==null&&n!==void 0?n:!1,respectSamplingDecision:(o=(a=m?.respectSamplingDecision)!==null&&a!==void 0?a:w?.respectSamplingDecision)!==null&&o!==void 0?o:!0},accessToken:async()=>""};return t.accessToken?_.accessToken=t.accessToken:delete _.accessToken,_}function Ea(t){let e=t?.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(wa(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Sa=class extends Fr{constructor(t){super(t)}},ka=class{constructor(t,e,r){var s,n;this.supabaseUrl=t,this.supabaseKey=e;let i=Ea(t);if(!e)throw new Error("supabaseKey is required.");ya(e),ba(r),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`,a={db:sa,realtime:ia,auth:N(N({},na),{},{storageKey:o}),global:ra,tracePropagation:oa},c=_a(r??{},a);if(this.settings=c,this.storageKey=(s=c.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(n=c.global.headers)!==null&&n!==void 0?n:{},c.accessToken)this.accessToken=c.accessToken,this.auth=new Proxy({},{get:(u,d)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(d)} is not possible`)}});else{var l;this.auth=this._initSupabaseAuthClient((l=c.auth)!==null&&l!==void 0?l:{},this.headers,c.global.fetch)}this.fetch=xn(e,t,this._getSessionToken.bind(this),c.global.fetch,c.tracePropagation),this.functionsFetch=xn(e,t,this._getSessionToken.bind(this),c.global.fetch,c.tracePropagation,{omitApiKeyAsBearer:!0}),this.realtime=this._initRealtimeClient(N({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},c.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(u=>this.realtime.setAuth(u)).catch(u=>console.warn("Failed to set initial Realtime auth token:",u)),this.rest=new ys(new URL("rest/v1",i).href,{headers:this.headers,schema:c.db.schema,fetch:this.fetch,timeout:c.db.timeout,urlLengthLimit:c.db.urlLengthLimit,retry:c.db.retry}),this.storage=new Fs(this.storageUrl.href,this.headers,this.fetch,r?.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new rt(this.functionsUrl.href,{headers:this.headers,customFetch:this.functionsFetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}getOpenApiSpec(){return this.rest.getOpenApiSpec()}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getSessionToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();let{data:s}=await t.auth.getSession();return(e=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:null}async _getAccessToken(){var t=this,e;return(e=await t._getSessionToken())!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,storageKey:i,flowType:o,lock:a,debug:c,throwOnError:l,experimental:u,lockAcquireTimeout:d,skipAutoInitialize:f},h,p){let g={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Sa({url:this.authUrl.href,headers:N(N({},g),h),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,flowType:o,lock:a,debug:c,throwOnError:l,experimental:u,fetch:p,lockAcquireTimeout:d,skipAutoInitialize:f,hasCustomAuthorizationHeader:Object.keys(this.headers).some(m=>m.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new Fe(this.realtimeUrl.href,N(N({},t),{},{params:N(N({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e?.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN"||t==="INITIAL_SESSION")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}},Ln=(t,e,r)=>new ka(t,e,r);function Ta(){if(typeof window<"u"||globalThis.Deno!==void 0)return!1;let t=globalThis.process;if(!t)return!1;let e=t.version;if(e==null)return!1;let r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=20:!1}Ta()&&console.warn("\u26A0\uFE0F Node.js 20 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 22 or later. For more information, visit: https://github.com/orgs/supabase/discussions/45715");var M=[];for(let t=0;t<256;++t)M.push((t+256).toString(16).slice(1));function $n(t,e=0){return(M[t[e+0]]+M[t[e+1]]+M[t[e+2]]+M[t[e+3]]+"-"+M[t[e+4]]+M[t[e+5]]+"-"+M[t[e+6]]+M[t[e+7]]+"-"+M[t[e+8]]+M[t[e+9]]+"-"+M[t[e+10]]+M[t[e+11]]+M[t[e+12]]+M[t[e+13]]+M[t[e+14]]+M[t[e+15]]).toLowerCase()}var Kr,Aa=new Uint8Array(16);function Wr(){if(!Kr){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Kr=crypto.getRandomValues.bind(crypto)}return Kr(Aa)}var Ra=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Vr={randomUUID:Ra};function Ca(t,e,r){if(Vr.randomUUID&&!e&&!t)return Vr.randomUUID();t=t||{};let s=t.random??t.rng?.()??Wr();if(s.length<16)throw new Error("Random bytes length must be >= 16");if(s[6]=s[6]&15|64,s[8]=s[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let n=0;n<16;++n)e[r+n]=s[n];return e}return $n(s)}var Gr=Ca;var xa="https://api.convokit.app",k=class extends Error{constructor(e,r={}){super(e,r.cause===void 0?void 0:{cause:r.cause});R(this,"status");R(this,"responseBody");R(this,"code");this.name="ConvoKitError",this.status=r.status,this.responseBody=r.responseBody,this.code=r.code}};function Ia(t){let e=t.trim().replace(/\/+$/,"");if(!e)throw new k("backendUrl is required",{code:"INVALID_CONFIG"});return e}function Dn(t,e){if(typeof e=="object"&&e!==null){let r=e;if(typeof r.error=="string")return r.error;if(typeof r.message=="string")return r.message}return typeof e=="string"&&e.trim()?e:`ConvoKit request failed with status ${t}`}function Mn(t){if(typeof t=="object"&&t!==null){let e=t.code;if(typeof e=="string"&&e.trim())return e}return"HTTP_ERROR"}async function qn(t){if(t.status===204)return;let e=await t.text();if(!e)return;if((t.headers.get("content-type")??"").includes("application/json"))try{return JSON.parse(e)}catch{return e}return e}var Oa=class{constructor(t){R(this,"backendUrl");R(this,"clientId");R(this,"fetchImplementation");R(this,"headersProvider");if(this.backendUrl=Ia(t.backendUrl),this.clientId=t.clientId.trim(),!this.clientId)throw new k("clientId is required",{code:"INVALID_CONFIG"});let e=t.fetchImplementation??globalThis.fetch;if(typeof e!="function")throw new k("A Fetch API implementation is required",{code:"FETCH_UNAVAILABLE"});this.fetchImplementation=e.bind(globalThis),this.headersProvider=t.headersProvider}async request(t,e={}){let r=new URL(`${this.backendUrl}${t}`);for(let[a,c]of Object.entries(e.query??{}))c!=null&&r.searchParams.set(a,String(c));let s={"x-client-id":this.clientId,...e.authenticated===!1?{}:this.headersProvider(),...e.headers},n;e.body!==void 0&&(typeof e.body=="string"||e.body instanceof ArrayBuffer||ArrayBuffer.isView(e.body)||typeof Blob<"u"&&e.body instanceof Blob?n=e.body:(s["Content-Type"]??(s["Content-Type"]="application/json"),n=JSON.stringify(e.body)));let i;try{i=await this.fetchImplementation(r,{method:e.method??"GET",headers:s,...n===void 0?{}:{body:n}})}catch(a){throw new k("Could not reach the ConvoKit backend",{code:"NETWORK_ERROR",cause:a})}let o=await qn(i);if(!i.ok)throw new k(Dn(i.status,o),{status:i.status,responseBody:o,code:Mn(o)});return o}async requestRaw(t,e={}){let r=new URL(`${this.backendUrl}${t}`);for(let[n,i]of Object.entries(e.query??{}))i!=null&&r.searchParams.set(n,String(i));let s;try{s=await this.fetchImplementation(r,{method:e.method??"GET",headers:{"x-client-id":this.clientId,...e.authenticated===!1?{}:this.headersProvider(),...e.headers}})}catch(n){throw new k("Could not reach the ConvoKit backend",{code:"NETWORK_ERROR",cause:n})}if(!s.ok){let n=await qn(s);throw new k(Dn(s.status,n),{status:s.status,responseBody:n,code:Mn(n)})}return s}};function Yr(){return Gr()}var Bn=2147483647;function Pa(t,e){if(!Number.isInteger(t)||t<0||t>Bn)throw new k(`${e} must be an integer between 0 and ${Bn}`,{code:"INVALID_ARGUMENT"});return t}function Hn(t){let e=U(L(t).data);if(typeof e.messageId!="string"||typeof e.emoji!="string"||typeof e.changed!="boolean")throw new TypeError("Invalid ConvoKit reaction mutation");return{messageId:e.messageId,emoji:e.emoji,changed:e.changed}}function Na(t){let e=L(t).data;if(!Array.isArray(e))throw new TypeError("Invalid ConvoKit reaction summaries");return e.map(r=>{let s=U(r);if(typeof s.messageId!="string"||!Array.isArray(s.reactions)||typeof s.hasMore!="boolean")throw new TypeError("Invalid ConvoKit reaction summary");return{messageId:s.messageId,hasMore:s.hasMore,reactions:s.reactions.map(n=>{let i=U(n);if(typeof i.emoji!="string"||typeof i.count!="number"||!Number.isInteger(i.count)||i.count<1||typeof i.reactedByMe!="boolean")throw new TypeError("Invalid ConvoKit reaction count");return{emoji:i.emoji,count:i.count,reactedByMe:i.reactedByMe}})}})}function Ua(t){let e=U(t);if(!Array.isArray(e.data)||e.nextCursor!==null&&typeof e.nextCursor!="string")throw new TypeError("Invalid ConvoKit reaction users page");return{data:e.data.map(r=>{let s=U(r);if(typeof s.userId!="string")throw new TypeError("Invalid ConvoKit reaction user");return{userId:s.userId,name:Y(s.name),imageUrl:Y(s.imageUrl),reactedAt:we(s.reactedAt)}}),nextCursor:e.nextCursor}}function U(t){return typeof t!="object"||t===null||Array.isArray(t)?{}:t}function $(t,e=""){return typeof t=="string"?t:e}function Y(t){return typeof t=="string"?t:null}function we(t){let e=new Date($(t));if(Number.isNaN(e.getTime()))throw new TypeError(`Invalid ConvoKit date: ${String(t)}`);return e}function ae(t){return t==null?null:we(t)}function oe(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim()!==""){let e=Number(t);if(Number.isFinite(e))return e}}function Fn(t){let e=U(t);return{id:$(e.id),appId:$(e.appId??e.app_id),name:Y(e.name??e.display_name),imageUrl:Y(e.imageUrl??e.image_url),lastSeenAt:ae(e.lastSeenAt??e.last_seen_at),createdAt:ae(e.createdAt??e.created_at),updatedAt:ae(e.updatedAt??e.updated_at)}}function cr(t){if(t==null)return null;let e=U(t),r=e.messageId??e.message_id;if(typeof r!="string"||!r.trim())throw new TypeError("Invalid ConvoKit read position: missing messageId");return{messageId:r,createdAt:we(e.createdAt??e.created_at)}}function ja(t){let e=U(t),r=$(e.id);return{id:r,appUserId:$(e.appUserId??e.app_user_id,r),name:$(e.name??e.display_name),imageUrl:Y(e.imageUrl??e.image_url),role:$(e.role,"READ_WRITE"),lastReadAt:ae(e.lastReadAt??e.last_read_at),readPosition:cr(e.readPosition??e.read_position)}}function Rt(t){let e=U(t),r=Y(e.title),s=e.participants??e.members,n=Array.isArray(s)?s.map(ja):[];return{id:$(e.id),title:r,imageUrl:Y(e.imageUrl??e.image_url),appId:$(e.appId??e.app_id),displayTitle:$(e.displayTitle??e.display_title,r??"Conversation"),description:Y(e.description),participants:n,createdAt:we(e.createdAt??e.created_at),updatedAt:we(e.updatedAt??e.updated_at)}}function Qr(t){if(t==null)return 0;let e=oe(t);if(e===void 0||!Number.isInteger(e)||e<0)throw new TypeError(`Invalid ConvoKit private state version: ${String(t)}`);return e}function La(t){if(t==null)return null;let e=U(t);return{role:$(e.role,"READ_WRITE"),lastReadAt:ae(e.lastReadAt??e.last_read_at),readPosition:cr(e.readPosition??e.read_position),unreadMarkedAt:ae(e.unreadMarkedAt??e.unread_marked_at),privateStateVersion:Qr(e.privateStateVersion??e.private_state_version)}}function Qn(t){let e=U(t),r=e.conversationId??e.conversation_id;if(typeof r!="string"||!r.trim())throw new TypeError("Invalid ConvoKit private state: missing conversationId");return{conversationId:r,unreadMarkedAt:ae(e.unreadMarkedAt??e.unread_marked_at),privateStateVersion:Qr(e.privateStateVersion??e.private_state_version)}}function $a(t){return{...Qn(t),cleared:ar(U(t).cleared,"cleared")}}function Da(t){let e=U(t),r=$(e.type),s={...typeof e.id=="string"?{id:e.id}:{},...typeof e.name=="string"?{name:e.name}:{},...oe(e.sortOrder??e.sort_order)!==void 0?{sortOrder:oe(e.sortOrder??e.sort_order)}:{}};if(r==="image"||r==="file")return{...s,type:r,url:$(e.url),...oe(e.size)!==void 0?{size:oe(e.size)}:{},...typeof e.metadata=="object"&&e.metadata!==null?{metadata:e.metadata}:{}};let n=U(e.metadata);if(r==="location")return{...s,type:r,metadata:{...n,lat:oe(n.lat)??Number.NaN,lng:oe(n.lng)??Number.NaN}};if(r==="contact")return{...s,type:r,metadata:{...n,...typeof n.phone=="string"?{phone:n.phone}:{},...typeof n.email=="string"?{email:n.email}:{}}};throw new TypeError(`Unsupported ConvoKit media type: ${r||"(missing)"}`)}function Zn(t){if(t==null)return 0;let e=oe(t);if(e===void 0||!Number.isInteger(e)||e<0)throw new TypeError(`Invalid ConvoKit message revision: ${String(t)}`);return e}var Kn=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),fe=t=>typeof t=="string"&&t.length>0;function Ma(t){if(fe(t))try{return new URL(t).protocol==="https:"?t:void 0}catch{return}}function qa(t){if(t==null)return;let e={kind:"unknown",raw:t};if(!Kn(t)||t.v!==1)return e;switch(t.kind){case"link":{let r=Ma(t.url);return!fe(t.title)||!r?e:{v:1,kind:"link",title:t.title,url:r,...fe(t.description)?{description:t.description}:{},...fe(t.buttonLabel)?{buttonLabel:t.buttonLabel}:{}}}case"quick_replies":{if(!fe(t.prompt)||!Array.isArray(t.options)||t.options.length===0)return e;let r=t.options.map(s=>Kn(s)&&fe(s.id)&&fe(s.label)?{id:s.id,label:s.label}:null);return r.some(s=>s===null)?e:{v:1,kind:"quick_replies",prompt:t.prompt,options:r,...t.layout==="grid"?{layout:"grid"}:{}}}case"handoff":return{v:1,kind:"handoff"};case"form_completed":return!fe(t.cardMessageId)||!fe(t.title)?e:{v:1,kind:"form_completed",cardMessageId:t.cardMessageId,title:t.title};case"answer":return{v:1,kind:"answer"};default:return e}}function ve(t){let e=U(t);return{id:$(e.id),...e.clientMessageId===void 0?{}:{clientMessageId:Y(e.clientMessageId)},conversationId:$(e.conversationId??e.conversation_id),senderId:$(e.appUserId??e.app_user_id??e.senderId),text:Y(e.text??e.content),media:Array.isArray(e.media)?e.media.map(Da):[],createdAt:we(e.createdAt??e.created_at),updatedAt:ae(e.updatedAt??e.updated_at),revision:Zn(e.revision),...typeof e.replyToMessageId=="string"?{replyToMessageId:e.replyToMessageId}:{},...Ba(e.card)}}function Ba(t){let e=qa(t);return e?{card:e}:{}}function Ha(t){if(t==null)return 0;let e=oe(t);if(e===void 0||!Number.isInteger(e)||e<0)throw new TypeError(`Invalid ConvoKit media count: ${String(t)}`);return e}function Fa(t){let e=U(t),r=e.id;if(typeof r!="string"||!r.trim())throw new TypeError("Invalid ConvoKit reply preview: missing id");return{id:r,conversationId:$(e.conversationId??e.conversation_id),senderId:$(e.appUserId??e.app_user_id??e.senderId),text:Y(e.text),textTruncated:ar(e.textTruncated??e.text_truncated,"textTruncated"),createdAt:we(e.createdAt??e.created_at),revision:Zn(e.revision),mediaCount:Ha(e.mediaCount??e.media_count)}}function Ka(t){let e=U(t);if(!Array.isArray(e.data))throw new TypeError("Invalid ConvoKit message context: missing data");return{messages:e.data.map(ve),olderCursor:Wn(e.olderCursor??e.older_cursor,"olderCursor"),newerCursor:Wn(e.newerCursor??e.newer_cursor,"newerCursor")}}function Wn(t,e){if(t!=null&&typeof t!="string")throw new TypeError(`Invalid ConvoKit message context: ${e} must be a string or null`);return typeof t=="string"?t:null}function Wa(t){if(t==null)return 0;let e=oe(t);if(e===void 0||!Number.isInteger(e)||e<0)throw new TypeError(`Invalid ConvoKit unread count: ${String(t)}`);return e}function ar(t,e){if(t==null)return!1;if(typeof t!="boolean")throw new TypeError(`Invalid ConvoKit ${e}: ${String(t)}`);return t}function Va(t){let e=U(t),r=e.latestMessage??e.latest_message,s=Wa(e.unreadCount??e.unread_count),n=ar(e.unreadCountCapped??e.unread_count_capped,"unreadCountCapped"),i=ae(e.unreadMarkedAt??e.unread_marked_at),o=e.isUnread??e.is_unread;return{conversation:Rt(e.conversation),latestMessage:r==null?null:ve(r),unreadCount:s,unreadCountCapped:n,readPosition:cr(e.readPosition??e.read_position),lastReadAt:ae(e.lastReadAt??e.last_read_at),isUnread:o==null?s>0||n||i!==null:ar(o,"isUnread"),unreadMarkedAt:i,privateStateVersion:Qr(e.privateStateVersion??e.private_state_version),activityAt:we(e.activityAt??e.activity_at)}}function Ga(t){let e=U(t);if(!Array.isArray(e.entries))throw new TypeError("Invalid ConvoKit inbox page: missing entries");let r=e.nextCursor??e.next_cursor;if(r!=null&&typeof r!="string")throw new TypeError("Invalid ConvoKit inbox page: nextCursor must be a string or null");return{entries:e.entries.map(Va),nextCursor:typeof r=="string"?r:null}}function za(t){let e=U(t);if(!Array.isArray(e.data))throw new TypeError("Invalid ConvoKit message page: missing data");let r=e.nextCursor!==void 0?e.nextCursor:e.next_cursor;if(r!==null&&(typeof r!="string"||r.length===0))throw new TypeError("Invalid ConvoKit message page: nextCursor must be a non-empty string or null");return{messages:e.data.map(ve),nextCursor:r}}function L(t){return U(t)}function zr(t){return typeof t=="function"?{onEvent:t}:t}function xt(t){let e=L(t);return L(e.payload??e)}function Ja(t){let e=xt(t);if(typeof e.userId!="string"||typeof e.isTyping!="boolean")throw new TypeError("typing payload is missing userId or isTyping");return{userId:e.userId,isTyping:e.isTyping}}function Xa(t){let e=xt(t);if(typeof e.userId!="string"||typeof e.readAt!="string")throw new TypeError("read payload is missing userId or readAt");let r=new Date(e.readAt);if(Number.isNaN(r.getTime()))throw new TypeError("readAt is not a date");return{userId:e.userId,readAt:r,readPosition:cr(e.readPosition??e.read_position)}}function Ya(t){let e=xt(t);if(typeof e.userId!="string"||typeof e.isOnline!="boolean"||typeof e.lastSeenAt!="string")throw new TypeError("presence payload is incomplete");let r=new Date(e.lastSeenAt);if(Number.isNaN(r.getTime()))throw new TypeError("lastSeenAt is not a date");return{userId:e.userId,isOnline:e.isOnline,lastSeenAt:r}}var Qe,Yn,Jr=(Yn=class{constructor(t){R(this,"close");rs(this,Qe,!1);this.close=t}get closed(){return ur(this,Qe)}async unsubscribe(){ur(this,Qe)||(ss(this,Qe,!0),await this.close())}},Qe=new WeakMap,Yn),Qa=class{constructor(t,e,r,s){R(this,"supabase");R(this,"appUserIdValue");R(this,"resolveTopic");R(this,"defaultErrorHandler");R(this,"subscriptions",new Set);R(this,"broadcastHubs",new Map);R(this,"connectionListeners",new Map);R(this,"sequence",0);R(this,"disposed",!1);this.supabase=t,this.appUserIdValue=e,this.resolveTopic=r,this.defaultErrorHandler=s}get appUserId(){return this.appUserIdValue}onConnectionEvent(t){this.requireOpen();let e=new Jr(async()=>{this.connectionListeners.delete(e),this.subscriptions.delete(e)});return this.connectionListeners.set(e,t),this.subscriptions.add(e),e}onMessage(t,e){this.requireOpen();let r=zr(e),s,n=`messages:${t}`,i=this.supabase.channel(this.channelName(n),{config:{private:!0}});for(let o of["INSERT","UPDATE"])i.on("postgres_changes",{event:o,schema:"public",table:"Message",filter:`conversationId=eq.${t}`},a=>{if(!(this.disposed||s?.closed))try{let c=ve(a.new);if(!c.id.trim()||c.conversationId!==t)throw new TypeError("Invalid message identity");r.onEvent({type:o==="INSERT"?"insert":"update",message:c})}catch{this.reportError(r,"Could not parse or deliver a realtime message")}});return s=this.subscribeChannel(i,r,n),s}onMessageDeleted(t,e){return this.subscribeBroadcast(`conversation:${t}`,"message_deleted",e,r=>{let s=xt(r);if(typeof s.id!="string"||!s.id.trim()||!t.trim()||s.conversationId!==t)throw new TypeError("Invalid message deletion");return{id:s.id,conversationId:t}})}onReactionChanged(t,e){return this.subscribeBroadcast(`conversation:${t}`,"reaction_changed",e,r=>{let s=xt(r);if(typeof s.id!="string"||!s.id.trim()||!t.trim()||s.conversationId!==t)throw new TypeError("Invalid reaction invalidation");return{id:s.id,conversationId:t}})}onTyping(t,e){return this.subscribeBroadcast(`conversation:${t}`,"typing",e,Ja)}onReadReceipt(t,e){return this.subscribeBroadcast(`conversation:${t}`,"read",e,Xa)}onPresence(t,e){return this.subscribeBroadcast(`app:${t}`,"presence",e,Ya)}onInboxChanged(t,e){let r=zr(e);return this.subscribeBroadcast(`app:${t}`,"inbox_changed",{...r,onStatus:s=>{if(s==="SUBSCRIBED")try{r.onEvent()}catch{this.reportError(r,"Could not deliver inbox invalidation")}r.onStatus?.(s)}},()=>{})}onInboxActivity(t,e){return this.subscribeBroadcast(`app:${t}`,"inbox_activity",e,()=>{})}async dispose(){if(this.disposed)return;this.disposed=!0;let t=[...this.subscriptions];for(let[e,r]of[...this.connectionListeners])if(!e.closed)try{r.onSessionEnded?.()}catch{this.reportError(r,"Could not notify a retired Realtime session")}await Promise.all(t.map(e=>e.unsubscribe()))}connection(t,e){if(!this.disposed){for(let[r,s]of[...this.connectionListeners])if(!r.closed)try{s.onEvent({topic:t,status:e})}catch{this.reportError(s,"Could not deliver Realtime connection state")}}}channelName(t){return this.sequence+=1,`${t}:${Date.now()}:${this.sequence}`}subscribeChannel(t,e,r){let s;return s=new Jr(async()=>{this.subscriptions.delete(s),await this.supabase.removeChannel(t)}),this.subscriptions.add(s),t.subscribe(n=>{if(this.disposed||s.closed)return;let i=n;this.connection(r,i),!(this.disposed||s.closed)&&(e.onStatus?.(i),(i==="CHANNEL_ERROR"||i==="TIMED_OUT")&&this.reportError(e,`Realtime subscription ${i.toLowerCase()}`))}),s}subscribeBroadcast(t,e,r,s){this.requireOpen();let n=zr(r),i=this.broadcastHubs.get(t),o=!1;i||(i={listeners:new Set,generation:0,failures:0},this.broadcastHubs.set(t,i),o=!0);let a={event:e,onPayload:u=>{try{n.onEvent(s(u))}catch{this.reportError(n,`Could not parse or deliver a realtime ${e} event`)}},...n.onStatus===void 0?{}:{onStatus:n.onStatus},...n.onError===void 0?{}:{onError:n.onError}};i.listeners.add(a);let c=i,l=new Jr(async()=>{this.subscriptions.delete(l),c.listeners.delete(a),c.listeners.size===0&&(this.broadcastHubs.get(t)===c&&this.broadcastHubs.delete(t),c.generation+=1,clearTimeout(c.retry),c.channel&&await this.supabase.removeChannel(c.channel))});return this.subscriptions.add(l),o?this.resolveBroadcastHub(t,c):i.status&&n.onStatus?.(i.status),l}hubIsCurrent(t,e){return!this.disposed&&e.listeners.size>0&&this.broadcastHubs.get(t)===e}broadcastStatus(t,e,r){if(this.hubIsCurrent(t,e)){e.status=r,this.connection(t,r);for(let s of[...e.listeners]){if(!this.hubIsCurrent(t,e))return;if(e.listeners.has(s)){try{s.onStatus?.(r)}catch{}if(r==="CHANNEL_ERROR"||r==="TIMED_OUT")try{s.onError?.(new k(`Realtime subscription ${r.toLowerCase()}`,{code:"REALTIME_ERROR"}))}catch{}}}(r==="CHANNEL_ERROR"||r==="TIMED_OUT")&&this.reportError({},`Realtime subscription ${r.toLowerCase()}`)}}resolveBroadcastHub(t,e,r=!1){if(!this.hubIsCurrent(t,e))return;clearTimeout(e.retry);let s=++e.generation,n=()=>this.hubIsCurrent(t,e)&&e.generation===s,i=a=>{if(!n())return;let c=e.channel;delete e.channel,c&&this.supabase.removeChannel(c).catch(()=>{}),this.broadcastStatus(t,e,"CHANNEL_ERROR"),!(a instanceof k&&[401,403,404].includes(a.status??0))&&++e.failures<=3&&n()&&(e.retry=setTimeout(()=>this.resolveBroadcastHub(t,e),1e3*e.failures),e.retry.unref?.())},o=a=>{if(!n())return;if(!a.startsWith(`${t}:`)||!a.slice(t.length+1).trim()||a.slice(t.length+1).includes(":"))throw new TypeError("Invalid private topic");if(e.channel&&e.wireTopic===a){r&&(e.failures=0,this.broadcastStatus(t,e,"SUBSCRIBED"));return}let c=e.channel;delete e.channel,delete e.status,c&&this.supabase.removeChannel(c).catch(()=>{});let l=this.createBroadcastChannel(t,a);e.channel=l,e.wireTopic=a,l.on("broadcast",{event:"scope_changed"},()=>{this.hubIsCurrent(t,e)&&e.channel===l&&(delete e.channel,delete e.status,this.supabase.removeChannel(l).catch(()=>{}),this.resolveBroadcastHub(t,e))}),l.subscribe(u=>{if(!this.hubIsCurrent(t,e)||e.channel!==l)return;let d=u;d==="SUBSCRIBED"?this.resolveBroadcastHub(t,e,!0):(this.broadcastStatus(t,e,d),(d==="CHANNEL_ERROR"||d==="TIMED_OUT"||d==="CLOSED")&&(delete e.channel,this.supabase.removeChannel(l).catch(()=>{}),++e.failures<=3&&(clearTimeout(e.retry),e.retry=setTimeout(()=>this.resolveBroadcastHub(t,e),1e3*e.failures),e.retry.unref?.())))})};try{let a=this.resolveTopic(t);typeof a=="string"?o(a):a.then(o).catch(i)}catch(a){i(a)}}createBroadcastChannel(t,e){let r=this.supabase.channel(e,{config:{private:!0}});return t.startsWith("conversation:")?r.on("broadcast",{event:"typing"},s=>{this.dispatchBroadcast(t,r,"typing",s)}).on("broadcast",{event:"read"},s=>{this.dispatchBroadcast(t,r,"read",s)}).on("broadcast",{event:"message_deleted"},s=>{this.dispatchBroadcast(t,r,"message_deleted",s)}).on("broadcast",{event:"reaction_changed"},s=>{this.dispatchBroadcast(t,r,"reaction_changed",s)}):(r.on("broadcast",{event:"presence"},s=>{this.dispatchBroadcast(t,r,"presence",s)}),r.on("broadcast",{event:"inbox_changed"},s=>{this.dispatchBroadcast(t,r,"inbox_changed",s)}),r.on("broadcast",{event:"inbox_activity"},s=>{this.dispatchBroadcast(t,r,"inbox_activity",s)})),r}dispatchBroadcast(t,e,r,s){if(this.disposed)return;let n=this.broadcastHubs.get(t);if(!(!n||n.channel!==e))for(let i of[...n.listeners])n.listeners.has(i)&&i.event===r&&i.onPayload(s)}requireOpen(){if(this.disposed)throw new k("This Realtime session has been closed; use the connected client\u2019s current session",{code:"SESSION_CHANGED"})}reportError(t,e){let r=new k(e,{code:"REALTIME_ERROR"});for(let s of[t.onError,this.defaultErrorHandler])try{s?.(r)}catch{}}},Za=2147483647;function Vn(t){try{let e=t.split(".")[1];if(!e)return 1/0;let r=e.replace(/-/g,"+").replace(/_/g,"/"),s=JSON.parse(atob(r.padEnd(Math.ceil(r.length/4)*4,"=")));return typeof s.exp=="number"&&Number.isSafeInteger(s.exp)?s.exp*1e3:1/0}catch{return 1/0}}function or(t){let e=Math.min(Vn(t.userToken),Vn(t.realtimeToken));if(e<=Date.now())throw new k("Session token has expired",{code:"TOKEN_EXPIRED"});return e}var ec=class{constructor(t){R(this,"options");R(this,"generation",0);R(this,"sessionSequence",0);R(this,"active",null);R(this,"pending",null);R(this,"refreshTimer");R(this,"expirationTimer");R(this,"listeners",new Set);R(this,"snapshot",Object.freeze({status:"disconnected",currentUserId:null,previousUserId:null,sessionId:null,reason:null,requiresReauthentication:!1,errorCode:null}));this.options=t}get connected(){return this.active!==null}get state(){return this.snapshot}get userId(){return this.requireActive().userId}get tokens(){return this.requireActive().tokens}get resource(){return this.requireActive().resource}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}capture(){let t=this.requireActive();return()=>this.assertActive(t)}async connect(t){let e=++this.generation,r=++this.sessionSequence,s=Object.freeze({status:"connecting",currentUserId:null,requestedUserId:t,sessionId:r});try{await this.clear(s),this.assertGeneration(e);let n=await this.options.tokens(t,()=>this.assertGeneration(e));this.assertGeneration(e),or(n);let i=!0,o;try{o=await this.options.create(t,n,()=>e===this.generation?this.active?.tokens.realtimeToken??(i?n.realtimeToken:null):null)}finally{i=!1}if(e!==this.generation)throw await o.close(),this.changed();try{let a={id:r,userId:t,tokens:n,resource:o,refreshAt:1/0,expiresAt:or(n),failures:0};this.active=a,this.schedule(a),this.transition(Object.freeze({status:"connected",currentUserId:t,sessionId:r}))}catch(a){throw this.active?.resource===o&&(this.active=null,this.cancelTimers()),await o.close(),a}}catch(n){if(e===this.generation&&this.active===null){let i=this.endState(t,r,this.connectionFailure(n));this.transition(i)}throw n}}async disconnect(){this.generation+=1;let t=this.snapshot,e=this.active?.userId??(t.status==="connecting"?t.requestedUserId:null),r=this.active?.id??(t.status==="connecting"?t.sessionId:null);await this.clear(this.endState(e,r,{reason:"user-disconnected",requiresReauthentication:!1,errorCode:null}))}async request(t){let e=this.requireActive();Date.now()>=e.refreshAt&&await this.renew(e),this.assertActive(e);let r=e.tokens.userToken;try{let s=await t(r);return this.assertActive(e),s}catch(s){if(this.assertActive(e),!(s instanceof k)||s.status!==401)throw s;if(r===e.tokens.userToken)try{await this.renew(e)}catch{throw this.assertActive(e),s}this.assertActive(e);let n=await t(e.tokens.userToken);return this.assertActive(e),n}}renew(t){if(this.assertActive(t),this.pending?.session===t)return this.pending.promise;let e=this.performRenewal(t).finally(()=>{this.pending?.promise===e&&(this.pending=null)});return this.pending={session:t,promise:e},e}async performRenewal(t){try{let e=await this.options.tokens(t.userId,()=>this.assertActive(t));this.assertActive(t);let r=or(e);if(Date.now()>=t.refreshAt&&r<=t.expiresAt)throw new k("The token provider did not extend the session lifetime",{code:"SESSION_TOKEN_NOT_RENEWED"});if(e.supabaseUrl!==t.tokens.supabaseUrl||e.supabaseKey!==t.tokens.supabaseKey)throw new k("Realtime configuration changed; reconnect the user",{code:"SESSION_CONFIGURATION_CHANGED"});try{await t.resource.setAuth(e.realtimeToken)}catch{throw new k("Could not authenticate the renewed Realtime session",{code:"SESSION_REALTIME_AUTH_FAILED"})}this.assertActive(t),t.tokens=e,t.failures=0,this.schedule(t)}catch(e){throw this.active===t&&(e instanceof k&&([401,403].includes(e.status??0)||["TOKEN_EXPIRED","SESSION_CONFIGURATION_CHANGED","SESSION_REALTIME_AUTH_FAILED"].includes(e.code??""))||t.expiresAt<=Date.now()?this.retire(t,this.renewalFailure(e,t.expiresAt<=Date.now())):(t.failures+=1,t.refreshAt=Math.min(t.expiresAt,Date.now()+Math.min(3e4,5e3*2**Math.min(t.failures-1,3))),this.armRefresh(t)),this.report("Session token renewal failed","SESSION_REFRESH_FAILED")),e}}schedule(t){this.cancelTimers(),t.expiresAt=or(t.tokens);let e=t.expiresAt-Date.now();t.refreshAt=Number.isFinite(e)?Date.now()+e-Math.min(3e5,e*.2):1/0,this.armRefresh(t),this.armExpiration(t)}armRefresh(t){clearTimeout(this.refreshTimer),Number.isFinite(t.refreshAt)&&(this.refreshTimer=this.timer(t.refreshAt-Date.now(),()=>{if(this.active===t){if(Date.now()<t.refreshAt){this.armRefresh(t);return}this.renew(t).catch(()=>{})}}))}armExpiration(t){clearTimeout(this.expirationTimer),Number.isFinite(t.expiresAt)&&(this.expirationTimer=this.timer(t.expiresAt-Date.now(),()=>{if(this.active===t){if(Date.now()<t.expiresAt){this.armExpiration(t);return}this.retire(t,{reason:"token-expired",requiresReauthentication:!0,errorCode:"SESSION_EXPIRED"}),this.report("Session expired; reconnect the user","SESSION_EXPIRED")}}))}timer(t,e){let r=setTimeout(e,Math.max(0,Math.min(Za,t)));return r.unref?.(),r}retire(t,e){this.active===t&&(this.generation+=1,this.clear(this.endState(t.userId,t.id,e)).catch(()=>this.report("Could not finish closing the session","SESSION_CLOSE_FAILED")))}clear(t){let e=this.active;return this.active=null,this.pending=null,this.cancelTimers(),this.transition(t),e?.resource.close()??Promise.resolve()}transition(t){if(this.snapshot!==t){this.snapshot=t;for(let e of[...this.listeners])try{e()}catch{}}}endState(t,e,r){return Object.freeze({status:"disconnected",currentUserId:null,previousUserId:t,sessionId:e,reason:r.reason,requiresReauthentication:r.requiresReauthentication,errorCode:r.errorCode})}connectionFailure(t){if(t instanceof k){if([401,403].includes(t.status??0))return{reason:"authentication-rejected",requiresReauthentication:!0,errorCode:"SESSION_AUTHENTICATION_REJECTED"};if(t.code==="TOKEN_EXPIRED")return{reason:"token-expired",requiresReauthentication:!0,errorCode:"TOKEN_EXPIRED"}}return{reason:"connection-failed",requiresReauthentication:!1,errorCode:"SESSION_CONNECT_FAILED"}}renewalFailure(t,e){if(e||t instanceof k&&t.code==="TOKEN_EXPIRED")return{reason:"token-expired",requiresReauthentication:!0,errorCode:"SESSION_EXPIRED"};if(t instanceof k){if([401,403].includes(t.status??0))return{reason:"authentication-rejected",requiresReauthentication:!0,errorCode:"SESSION_REFRESH_REJECTED"};if(t.code==="SESSION_CONFIGURATION_CHANGED")return{reason:"configuration-changed",requiresReauthentication:!1,errorCode:t.code};if(t.code==="SESSION_REALTIME_AUTH_FAILED")return{reason:"realtime-authentication-failed",requiresReauthentication:!1,errorCode:t.code}}return{reason:"token-expired",requiresReauthentication:!0,errorCode:"SESSION_EXPIRED"}}cancelTimers(){clearTimeout(this.refreshTimer),clearTimeout(this.expirationTimer),this.refreshTimer=void 0,this.expirationTimer=void 0}report(t,e){try{this.options.onError?.(new k(t,{code:e}))}catch{}}requireActive(){if(!this.active)throw new k("Call connectUser() first",{code:"NOT_CONNECTED"});return this.active}assertActive(t){if(this.active!==t)throw this.changed()}assertGeneration(t){if(t!==this.generation)throw this.changed()}changed(){return new k("The user session changed while the operation was pending",{code:"SESSION_CHANGED"})}};function T(t,e){let r=t.trim();if(!r)throw new k(`${e} is required`,{code:"INVALID_ARGUMENT"});return r}function Ye(t,e){if(!Number.isInteger(t)||t<0)throw new k(`${e} must be a non-negative integer`,{code:"INVALID_ARGUMENT"});return t}function Ct(t,e,r,s){if(!Number.isInteger(t)||t<r||t>s)throw new k(`${e} must be an integer between ${r} and ${s}`,{code:"INVALID_ARGUMENT"});return t}var tc=2147483647,Gn=64,zn=50,Jn=50;function Xr(t){if(typeof t!="string"||t.length===0)throw new k("emoji is required",{code:"INVALID_ARGUMENT"});return t}function Oe(t,e){let r=typeof t=="string"?t.trim():"";if(!r)throw new k(`${e} must be a non-empty string`,{code:"INVALID_ARGUMENT"});if(r.length>Gn)throw new k(`${e} must be at most ${Gn} characters`,{code:"INVALID_ARGUMENT"});return r}function Xn(t,e){return Ct(t,e,0,tc)}function rc(t){if(t instanceof Blob||t instanceof ArrayBuffer)return t;if(ArrayBuffer.isView(t)){let e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),e.buffer}throw new k("bytes must be a Blob, ArrayBuffer, or typed array",{code:"INVALID_ARGUMENT"})}var ei=class{constructor(t){R(this,"backendUrl");R(this,"clientId");R(this,"tokenProvider");R(this,"onRealtimeError");R(this,"fetchImplementation");R(this,"transport");R(this,"session");this.tokenProvider=t.tokenProvider,this.onRealtimeError=t.onRealtimeError,this.fetchImplementation=(t.fetch??globalThis.fetch).bind(globalThis),this.clientId=T(t.clientId,"clientId"),this.transport=new Oa({backendUrl:t.backendUrl??xa,clientId:this.clientId,...t.fetch===void 0?{}:{fetchImplementation:t.fetch},headersProvider:()=>({})}),this.backendUrl=this.transport.backendUrl,this.session=new ec({tokens:async(e,r)=>{let s=T(await this.tokenProvider(e),"tokenProvider result");r();let n=await this.transport.request("/api/v1/realtime/token",{method:"POST",authenticated:!1,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:{appUserId:e}});return r(),{userToken:s,realtimeToken:T(n.data.token,"realtime token"),supabaseUrl:T(n.data.supabaseUrl,"supabaseUrl"),supabaseKey:T(n.data.supabaseKey,"supabaseKey")}},create:async(e,r,s)=>{let n=Ln(r.supabaseUrl,r.supabaseKey,{auth:{autoRefreshToken:!1,persistSession:!1,detectSessionInUrl:!1},accessToken:async()=>s()});try{await n.realtime.setAuth(r.realtimeToken)}catch(o){throw n.realtime.disconnect(),o}let i=new Qa(n,e,async o=>{if(!s())throw new k("Realtime session ended",{code:"SESSION_CHANGED"});let a=this.session.capture(),c=await this.request("/api/v1/realtime/topic",{query:{topic:o}});if(a(),!s())throw new k("Realtime session ended",{code:"SESSION_CHANGED"});return T(c.data.topic,"private Realtime topic")},this.onRealtimeError);return{supabase:n,realtime:i,setAuth:o=>n.realtime.setAuth(o),close:async()=>{try{await i.dispose()}finally{n.realtime.disconnect()}}}},onError:this.onRealtimeError})}get connected(){return this.session.connected}get sessionState(){return this.session.state}subscribeSession(t){return this.session.subscribe(t)}get currentUserId(){return this.session.userId}get authHeaders(){return{"Content-Type":"application/json","x-client-id":this.clientId,Authorization:`Bearer ${this.requireUserToken()}`}}get lastToken(){return this.session.tokens.realtimeToken}get lastUserToken(){return this.requireUserToken()}get lastTokenClaims(){let t=this.lastToken.split(".");if(t.length!==3||t[1]===void 0)throw new k("Invalid JWT format",{code:"INVALID_TOKEN"});let e=t[1].replace(/-/g,"+").replace(/_/g,"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");try{let s=Uint8Array.from(atob(r),n=>n.charCodeAt(0));return JSON.parse(new TextDecoder().decode(s))}catch(s){throw new k("Could not decode realtime token",{code:"INVALID_TOKEN",cause:s})}}get supabase(){return this.session.resource.supabase}get realtime(){return this.session.resource.realtime}async connectUser(t){await this.session.connect(T(t,"appUserId"))}async disconnectUser(){await this.session.disconnect()}async getUsers(t={}){this.requireConnected();let e=Ye(t.limit??50,"limit"),r=Ye(t.offset??0,"offset"),s=await this.request("/api/v1/user",{query:{limit:e,offset:r}}),n=L(s),i=Array.isArray(n.data)?n.data:[];return{data:i.map(Fn),totalCount:typeof n.total_count=="number"?n.total_count:i.length}}async getUser(t){this.requireConnected();let e=await this.request(`/api/v1/user/${encodeURIComponent(T(t,"id"))}`);return Fn(L(e).data)}async getConversations(t={}){this.requireConnected();let e=Ye(t.limit??50,"limit"),r=Ye(t.offset??0,"offset"),s=await this.request("/api/v1/conversations",{query:{limit:e,offset:r,...t.archived===!0?{archived:!0}:{}}}),n=L(s).conversations;return Array.isArray(n)?n.map(Rt):[]}async listInbox(t={}){this.requireConnected();let e=Ct(t.limit??30,"limit",1,100),r=t.cursor??void 0;if(r!==void 0&&(typeof r!="string"||r.trim()===""))throw new k("cursor must be a non-empty string",{code:"INVALID_ARGUMENT"});let s=await this.request("/api/v1/inbox",{query:{limit:e,...r===void 0?{}:{cursor:r},...t.archived===!0?{archived:!0}:{}}});return Ga(s)}async getConversation(t){this.requireConnected();let e=await this.request(`/api/v1/conversations/${encodeURIComponent(T(t,"id"))}`),r=L(e),s=La(r.membership);return{...Rt(r.conversation),...s===null?{}:{membership:s}}}async createConversation(t){this.requireConnected();let e=await this.request("/api/v1/conversations",{method:"POST",body:{participants:t.participants,...t.title===void 0?{}:{title:t.title},...t.description===void 0?{}:{description:t.description},...t.imageUrl===void 0?{}:{imageUrl:t.imageUrl}}});return Rt(L(e).conversation)}async markConversationRead(t,e={}){this.requireConnected();let r=e.throughMessageId;if(r!==void 0&&typeof r!="string")throw new k("throughMessageId must be a string",{code:"INVALID_ARGUMENT"});let s=e.privateStateVersion;await this.request(`/api/v1/conversations/${encodeURIComponent(T(t,"conversationId"))}/read`,{method:"POST",body:{...r===void 0?{}:{throughMessageId:T(r,"throughMessageId")},...s===void 0?{}:{privateStateVersion:Xn(s,"privateStateVersion")}}})}async markConversationUnread(t){this.requireConnected();let e=await this.request(`/api/v1/conversations/${encodeURIComponent(T(t,"conversationId"))}/unread`,{method:"POST"});return Qn(e)}async clearConversationUnread(t,e={}){this.requireConnected();let r=e.ifVersion,s=await this.request(`/api/v1/conversations/${encodeURIComponent(T(t,"conversationId"))}/unread`,{method:"DELETE",query:r===void 0?{}:{privateStateVersion:Xn(r,"ifVersion")}});return $a(s)}async sendTyping(t){this.requireConnected(),await this.request(`/api/v1/conversations/${encodeURIComponent(T(t.conversationId,"conversationId"))}/typing`,{method:"POST",body:{isTyping:t.isTyping}})}async updatePresence(t){this.requireConnected(),await this.request("/api/v1/presence",{method:"POST",body:{isOnline:t.isOnline}})}async leaveConversation(t){return this.conversationAction(t,"leave","POST")}async archiveConversation(t){return this.conversationAction(t,"archive","POST")}async unarchiveConversation(t){return this.conversationAction(t,"archive","DELETE")}async updateConversationTitle(t){this.requireConnected();let e=await this.request(`/api/v1/conversations/${encodeURIComponent(T(t.conversationId,"conversationId"))}/title`,{method:"PATCH",body:{title:t.title}});return Rt(L(e).conversation)}async getMessages(t){this.requireConnected();let e=Ye(t.offset??0,"offset"),r=t.beforeCreatedAt!==void 0,s=t.beforeId!==void 0;if(r!==s||r&&e!==0)throw new k("Provide both cursor values without a nonzero offset",{code:"INVALID_ARGUMENT"});let n;if(r&&s){if(!(t.beforeCreatedAt instanceof Date)||!Number.isFinite(t.beforeCreatedAt.getTime()))throw new k("beforeCreatedAt must be a valid Date",{code:"INVALID_ARGUMENT"});n={beforeCreatedAt:t.beforeCreatedAt.toISOString(),beforeId:T(t.beforeId,"beforeId")}}let i=await this.request("/api/v1/messages",{query:{conversationId:T(t.conversationId,"conversationId"),limit:Ye(t.limit??20,"limit"),offset:e,...n}}),o=L(i).data;return Array.isArray(o)?o.map(ve):[]}async listMessages(t){this.requireConnected();let e=Ct(t.limit??20,"limit",1,100),r=t.cursor??void 0;if(r!==void 0&&(typeof r!="string"||r.trim()===""))throw new k("cursor must be a non-empty string",{code:"INVALID_ARGUMENT"});let s=await this.request("/api/v1/messages",{query:{conversationId:T(t.conversationId,"conversationId"),limit:e,...r===void 0?{}:{cursor:r}}});return za(s)}async getMessage(t){this.requireConnected();let e=await this.request(`/api/v1/messages/${encodeURIComponent(T(t,"id"))}`);return ve(L(e).data)}async sendMessage(t){this.requireConnected();let e=await this.request("/api/v1/messages",{method:"POST",body:{conversationId:T(t.conversationId,"conversationId"),clientMessageId:t.clientMessageId??Yr(),...t.text===void 0?{}:{text:t.text},...t.media===void 0||t.media.length===0?{}:{media:t.media},...t.replyToMessageId===void 0?{}:{replyToMessageId:T(t.replyToMessageId,"replyToMessageId")}}});return ve(L(e).data)}async editMessage(t,e){this.requireConnected();let r=T(t,"messageId"),s=e.text;if(s===void 0)throw new k("text is required",{code:"INVALID_ARGUMENT"});if(s!==null&&typeof s!="string")throw new k("text must be a string or null",{code:"INVALID_ARGUMENT"});let n=Pa(e.revision,"revision"),i=await this.request(`/api/v1/messages/${encodeURIComponent(r)}/own`,{method:"PATCH",body:{text:s,revision:n}});return ve(L(i).data)}async deleteMessage(t){this.requireConnected(),await this.request(`/api/v1/messages/${encodeURIComponent(T(t,"messageId"))}/own`,{method:"DELETE"})}async sendCardEvent(t,e,r){if(this.requireConnected(),e!=="opened"&&e!=="escape"&&e!=="quick_reply")throw new TypeError("event must be opened, escape or quick_reply");if(e==="quick_reply"?!r||typeof r!="string":r!==void 0)throw new TypeError(e==="quick_reply"?"optionId is required for quick_reply":"optionId is only allowed with quick_reply");await this.request(`/api/v1/automation/cards/${encodeURIComponent(Oe(t,"messageId"))}/events`,{method:"POST",body:e==="quick_reply"?{event:e,optionId:r}:{event:e}})}async addReaction(t,e){this.requireConnected();let r=await this.request(`/api/v1/messages/${encodeURIComponent(Oe(t,"messageId"))}/reactions`,{method:"POST",body:{emoji:Xr(e)}});return Hn(r)}async removeReaction(t,e){this.requireConnected();let r=await this.request(`/api/v1/messages/${encodeURIComponent(Oe(t,"messageId"))}/reactions`,{method:"DELETE",query:{emoji:Xr(e)}});return Hn(r)}async getReactionSummaries(t,e){this.requireConnected();let r=this.session.capture(),s=T(t,"conversationId");if(!Array.isArray(e)||e.length===0)throw new k("messageIds must be a non-empty array",{code:"INVALID_ARGUMENT"});let n=Array.from(new Set(e.map(o=>Oe(o,"messageIds")))),i=[];for(let o=0;o<n.length;o+=Jn){r();let a=await this.request(`/api/v1/conversations/${encodeURIComponent(s)}/reactions`,{query:{ids:n.slice(o,o+Jn).join(",")}});i.push(...Na(a))}return r(),i}async listReactionUsers(t,e,r={}){this.requireConnected();let s=Oe(t,"messageId"),n=Ct(r.limit??30,"limit",1,100),i=r.cursor===void 0?void 0:T(r.cursor,"cursor"),o=await this.request(`/api/v1/messages/${encodeURIComponent(s)}/reactions`,{query:{emoji:Xr(e),limit:n,...i===void 0?{}:{cursor:i}}});return Ua(o)}async getReplyPreviews(t,e){this.requireConnected();let r=this.session.capture(),s=T(t,"conversationId");if(!Array.isArray(e))throw new k("messageIds must be an array",{code:"INVALID_ARGUMENT"});if(e.length===0)throw new k("messageIds must not be empty",{code:"INVALID_ARGUMENT"});let n=[],i=new Set;for(let a of e){let c=Oe(a,"messageIds");i.has(c)||(i.add(c),n.push(c))}let o=[];for(let a=0;a<n.length;a+=zn){r();let c=await this.request(`/api/v1/conversations/${encodeURIComponent(s)}/reply-previews`,{query:{ids:n.slice(a,a+zn).join(",")}}),l=L(c).data;if(!Array.isArray(l))throw new TypeError("Invalid ConvoKit reply previews: missing data");for(let u of l)o.push(Fa(u))}return o}async getMessageContext(t,e={}){this.requireConnected();let r=T(t,"conversationId"),s=Ct(e.limit??30,"limit",1,100),i=["messageId","olderCursor","newerCursor"].filter(c=>e[c]!==void 0);if(i.length!==1)throw new k("Use a message ID or a cursor, not both",{code:"INVALID_ARGUMENT"});let o={limit:s};if(e.messageId!==void 0)o.messageId=Oe(e.messageId,"messageId");else{let c=i[0],l=e[c];if(typeof l!="string"||l.trim()==="")throw new k(`${c} must be a non-empty string`,{code:"INVALID_ARGUMENT"});o[c]=l}let a=await this.request(`/api/v1/conversations/${encodeURIComponent(r)}/context`,{query:o});return Ka(a)}async uploadUserAvatar(t){this.requireConnected();let e=this.session.capture(),r=await this.upload({folder:"user_avatar",bytes:t.bytes,fileName:t.fileName,...t.contentType===void 0?{}:{contentType:t.contentType},userId:T(t.userId,"userId")});return e(),await this.request(`/api/v1/user/${encodeURIComponent(t.userId)}/avatar`,{method:"PATCH",body:{imageUrl:r}}),r}async uploadConversationImage(t){this.requireConnected();let e=this.session.capture(),r=T(t.conversationId,"conversationId"),s=await this.upload({folder:"conversation_image",bytes:t.bytes,fileName:t.fileName,...t.contentType===void 0?{}:{contentType:t.contentType},conversationId:r});return e(),await this.request(`/api/v1/conversations/${encodeURIComponent(r)}/image`,{method:"PATCH",body:{imageUrl:s}}),s}async uploadMessageMedia(t){return this.requireConnected(),this.upload({folder:"message_media",bytes:t.bytes,fileName:t.fileName,...t.contentType===void 0?{}:{contentType:t.contentType},conversationId:T(t.conversationId,"conversationId")})}async deleteUserAvatar(t){this.requireConnected(),await this.request(`/api/v1/user/${encodeURIComponent(T(t.userId,"userId"))}/avatar`,{method:"DELETE"})}async deleteConversationImage(t){this.requireConnected(),await this.request(`/api/v1/conversations/${encodeURIComponent(T(t.conversationId,"conversationId"))}/image`,{method:"DELETE"})}async downloadMedia(t){this.requireConnected();let e=this.session.capture(),s=await(await this.requestRaw("/api/v1/media/download",{query:{url:T(t,"url")}})).blob();return e(),s}requireConnected(){this.currentUserId}requireUserToken(){return this.session.tokens.userToken}request(t,e={}){return this.session.request(r=>this.transport.request(t,{...e,authenticated:!1,headers:{...e.headers,"Content-Type":"application/json",Authorization:`Bearer ${r}`}}))}requestRaw(t,e={}){return this.session.request(r=>this.transport.requestRaw(t,{...e,authenticated:!1,headers:{...e.headers,"Content-Type":"application/json",Authorization:`Bearer ${r}`}}))}async conversationAction(t,e,r){this.requireConnected();let s=await this.request(`/api/v1/conversations/${encodeURIComponent(T(t,"id"))}/${e}`,{method:r}),n=L(s).conversationId;return T(typeof n=="string"?n:"","conversationId response")}async upload(t){let e=this.session.capture(),r=await this.request("/api/v1/media/sign-upload",{method:"POST",query:{folder:t.folder,fileName:T(t.fileName,"fileName"),contentType:t.contentType,userId:t.userId,conversationId:t.conversationId}});e();let s=L(L(r).data),n=T(String(s.uploadUrl??""),"uploadUrl response"),i=T(String(s.fileUrl??""),"fileUrl response"),o=T(String(s.objectKey??""),"objectKey response"),a=typeof s.contentType=="string"?s.contentType:"application/octet-stream",c;try{c=await this.fetchImplementation(n,{method:"PUT",headers:{"Content-Type":a},body:rc(t.bytes)})}catch(l){throw new k("Could not upload media to storage",{code:"UPLOAD_NETWORK_ERROR",cause:l})}if(!c.ok)throw new k(`Media upload failed with status ${c.status}`,{code:"UPLOAD_ERROR",status:c.status});return e(),await this.request("/api/v1/media/complete-upload",{method:"POST",body:{objectKey:o}}),i}};var ti=(t,e)=>t.createdAt.getTime()>e.createdAt.getTime()||t.createdAt.getTime()===e.createdAt.getTime()&&t.id>e.id;function ri(t,e,r){for(let s of e)if(s.senderId===r&&s.id!==t.id&&ti(s,t))return!0;return!1}function si(t){let e;for(let r of t)r.card&&(!e||ti(r,e))&&(e=r);return e}var Pe=class extends Error{constructor(r,s,n){super(r);this.status=s;this.code=n}};function ai(t){try{return t==="SESSION"?window.sessionStorage:window.localStorage}catch{return null}}var ci=t=>`convokit-widget:${t}:guest`;function sc(t){try{return ai(t.storageMode)?.getItem(ci(t.clientId))??null}catch{return null}}function nc(t,e){try{ai(t.storageMode)?.setItem(ci(t.clientId),e)}catch{}}async function ni(t,e,r){let s=await r(`${t.apiUrl}/api/v1/widget/session`,{method:"POST",headers:{"Content-Type":"application/json","x-client-id":t.clientId,"x-widget-key":t.widgetKey},body:JSON.stringify(e)}),n=await s.json().catch(()=>null);if(!s.ok||!n?.data?.token||!n.data.appUserId)throw new Pe(n?.error??"Could not start the chat session",s.status,n?.code);return n.data}function ii(t){let e={};return t.user?.name&&(e.name=t.user.name),t.user?.imageUrl&&(e.imageUrl=t.user.imageUrl),e}function oi(t,e){let r=t.token;return{appUserId:t.appUserId,showBranding:t.showBranding===!0,tokenProvider:async s=>{if(r){let i=r;return r=null,i}let n=await e();if(n.appUserId!==s)throw new Pe("The chat session belongs to a different user",401);return n.token}}}async function li(t,e=fetch){if(t.mode==="guest"){let s=()=>ni(t,{mode:"guest",resumeToken:sc(t),...ii(t)},e).then(n=>(n.resumeToken&&nc(t,n.resumeToken),n));return oi(await s(),s)}if(t.mode==="uid"){let s=()=>ni(t,{mode:"uid",uid:t.uid,...ii(t)},e);return oi(await s(),s)}let r=t.tokenProvider??(async s=>{let n=await e(t.tokenUrl,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({appUserId:s})}),i=await n.json().catch(()=>null),o=i?.token??i?.data?.token;if(!n.ok||!o)throw new Pe("Your token endpoint did not return a token",n.status);return o});return{appUserId:t.userId,tokenProvider:r,showBranding:!1}}var ui=(t,e,r,s)=>`
30
30
  :host { all: initial; --ck-primary: ${t}; --ck-bg: #ffffff; --ck-fg: #111827; --ck-muted: #6b7280; --ck-border: #e5e7eb; --ck-bubble: #f3f4f6; --ck-danger: #b91c1c;
31
31
  font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; font-size: 14px; line-height: 1.4; color: var(--ck-fg); }
32
32
  @media (prefers-color-scheme: dark) {
@@ -79,6 +79,8 @@ header h2 { flex: 1; margin: 0; font-size: 15px; font-weight: 600; white-space:
79
79
  .option.chosen:disabled { opacity: 1; }
80
80
  .options.grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px; }
81
81
  .options.grid .option { border-radius: 10px; padding: 10px 8px; min-height: 44px; font-weight: 600; text-align: center; overflow-wrap: anywhere; }
82
+ .ai-label { font-size: 11px; font-weight: 600; color: var(--ck-muted); text-transform: uppercase; letter-spacing: .04em; }
83
+ .msg .bubble.ai { border: 1px solid var(--ck-border); }
82
84
  .escape { align-self: flex-start; border: 0; background: transparent; padding: 2px 0; color: var(--ck-muted); font-size: 12px; text-decoration: underline; }
83
85
  .escape:disabled { cursor: default; opacity: .6; }
84
86
  .card-error { color: var(--ck-danger); }
@@ -94,4 +96,4 @@ form .primary:disabled { opacity: .5; cursor: default; }
94
96
  @media (max-width: 480px) {
95
97
  .docked .panel { position: fixed; inset: 0; width: 100vw; height: 100dvh; max-width: none; max-height: none; border-radius: 0; }
96
98
  }
97
- `;var fi={chat:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>',close:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12"/></svg>',back:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="m15 18-6-6 6-6"/></svg>'},di={WIDGET_USER_LIMIT_REACHED:"Chat is busy right now. Please try again later.",PLAN_USER_LIMIT_REACHED:"Chat is busy right now. Please try again later.",PLAN_UPGRADE_REQUIRED:"Chat is currently unavailable.",RATE_LIMITED:"Too many attempts. Please wait a few minutes and try again.",ORIGIN_NOT_ALLOWED:"Chat is not enabled for this website.",WIDGET_DISABLED:"Chat is currently unavailable.",WIDGET_MODE_DISABLED:"Chat is currently unavailable.",SUBSCRIPTION_REQUIRED:"Chat is currently unavailable."},ic={PLAN_UPGRADE_REQUIRED:'This ConvoKit plan only supports guest mode. Use mode: "guest", or upgrade to Starter for "uid" and "authToken".',SUBSCRIPTION_REQUIRED:'The free ConvoKit plan only supports guest mode. Use mode: "guest", or subscribe in the ConvoKit dashboard for "uid" and "authToken".',PLAN_USER_LIMIT_REACHED:"This ConvoKit plan has reached its monthly active user limit. Upgrade the plan in the ConvoKit dashboard.",WIDGET_USER_LIMIT_REACHED:"The monthly limit of new widget users is reached. Raise it in the ConvoKit dashboard or upgrade the plan."},Zr=t=>t instanceof Pe||t instanceof k?t.code:void 0;function oc(t){let e=Zr(t);return e&&di[e]?di[e]:"Could not connect to chat. Check your connection and try again."}function S(t,e={},...r){let s=Object.assign(document.createElement(t),e);return s.append(...r),s}function hi(t,e,r){let s=S("button",{type:"button",className:"icon",onclick:r});return s.setAttribute("aria-label",e),s.innerHTML=fi[t],s}var lr=class{constructor(e,r={}){this.config=e;this.deps=r;this.launcher=null;this.badge=null;this.client=null;this.session=null;this.connecting=null;this.inbox=[];this.inboxSubscriptions=[];this.threadSubscriptions=[];this.thread=null;this.inboxRefresh=null;this.unsubscribeSession=null;this.destroyed=!1;let s=e.mount?document.querySelector(e.mount):null;s||(s=document.createElement("div"),e.mount?.startsWith("#")&&(s.id=e.mount.slice(1)),document.body.append(s)),this.host=s,this.root=s.shadowRoot??s.attachShadow({mode:"open"}),this.root.replaceChildren(S("style",{textContent:ui(e.primaryColor,e.width,e.height,e.dockedAlignment)})),this.heading=S("h2",{textContent:e.title}),this.backSlot=S("span"),this.headerActions=S("span"),this.body=S("div",{className:"body"}),this.branding=S("footer",{className:"branding",hidden:!0},"Powered by ",S("a",{href:"https://convokit.app/?utm_source=chat-widget&utm_medium=referral",target:"_blank",rel:"noopener",textContent:"ConvoKit"})),this.panel=S("section",{className:"panel"},S("header",{},this.backSlot,this.heading,this.headerActions),this.body,this.branding),this.panel.setAttribute("aria-label",e.title),this.isOpen=!e.isDocked,e.isDocked?(this.badge=S("span",{className:"badge",hidden:!0}),this.launcher=S("button",{type:"button",className:"launcher",onclick:()=>this.toggle()}),this.launcher.innerHTML=fi.chat,this.launcher.append(this.badge),this.headerActions.append(hi("close","Close chat",()=>this.close())),this.panel.hidden=!0,this.root.append(S("div",{className:"docked"},this.panel,this.launcher)),this.updateLauncher()):(this.root.append(S("div",{className:"inline"},this.panel)),this.connect())}open(){this.destroyed||(this.isOpen=!0,this.panel.hidden=!1,this.updateLauncher(),this.connect().then(()=>this.markThreadRead()))}close(){this.config.isDocked&&(this.isOpen=!1,this.panel.hidden=!0,this.updateLauncher(),this.launcher?.focus())}toggle(){this.isOpen?this.close():this.open()}async destroy(){this.destroyed=!0,this.inboxRefresh&&clearTimeout(this.inboxRefresh),this.unsubscribeSession?.(),await this.leaveThread(),await Promise.allSettled(this.inboxSubscriptions.map(e=>e.unsubscribe())),await this.client?.disconnectUser().catch(()=>{}),this.root.replaceChildren()}get chatClient(){return this.client}connect(){return this.client&&this.session?Promise.resolve():(this.connecting??(this.connecting=this.doConnect().finally(()=>{this.connecting=null})),this.connecting)}async doConnect(){this.showCenter("Connecting\u2026");try{let e=await li(this.config,this.deps.fetch),r={clientId:this.config.clientId,tokenProvider:e.tokenProvider,backendUrl:this.config.apiUrl},s=this.deps.createClient?this.deps.createClient(r):new ei(r);if(await s.connectUser(e.appUserId),this.destroyed){await s.disconnectUser();return}this.client=s,this.session=e,this.branding.hidden=!e.showBranding,this.unsubscribeSession=s.subscribeSession(()=>{let n=s.sessionState;n.status==="disconnected"&&n.requiresReauthentication&&this.reset("Your chat session ended.")}),this.watchInbox(),this.config.startConversationWith.length?await this.openConversation(await this.findOrCreateConversation()):await this.showInbox()}catch(e){let r=ic[Zr(e)??""];r&&console.warn(`[ConvoKitWidget] ${r}`),console.error("[ConvoKitWidget] could not start chat:",e),this.client=null,this.session=null,this.showCenter(oc(e),!0)}}async reset(e){await this.leaveThread(),await Promise.allSettled(this.inboxSubscriptions.map(r=>r.unsubscribe())),this.inboxSubscriptions=[],this.unsubscribeSession?.(),this.unsubscribeSession=null,this.client=null,this.session=null,this.showCenter(e,!0)}get me(){return this.session.appUserId}watchInbox(){let e=this.client.realtime,r=()=>{this.inboxRefresh&&clearTimeout(this.inboxRefresh),this.inboxRefresh=setTimeout(()=>{this.loadInbox()},300)};this.inboxSubscriptions=[e.onInboxActivity(this.client.clientId,r),e.onInboxChanged(this.client.clientId,r)]}async loadInbox(){if(this.client)try{this.inbox=(await this.client.listInbox({limit:50})).entries,this.updateLauncher(),this.thread||this.renderInbox()}catch{}}async findOrCreateConversation(){let e=new Set([this.me,...this.config.startConversationWith]),r=await this.client.listInbox({limit:100});this.inbox=r.entries;let s=r.entries.find(n=>{let i=new Set(n.conversation.participants.map(o=>o.appUserId));return i.size===e.size&&[...e].every(o=>i.has(o))});return s?s.conversation:this.client.createConversation({participants:this.config.startConversationWith,...this.config.conversationTitle?{title:this.config.conversationTitle}:{}})}async showInbox(){await this.leaveThread(),this.heading.textContent=this.config.title,this.backSlot.replaceChildren(),this.showCenter("Loading\u2026"),await this.loadInbox(),this.renderInbox()}renderInbox(){if(!this.client||this.thread)return;if(this.inbox.length===0){let r=[S("p",{textContent:"No conversations yet."})];this.config.startConversationWith.length&&r.push(S("button",{type:"button",className:"primary",textContent:"Start a conversation",onclick:()=>{this.findOrCreateConversation().then(s=>this.openConversation(s))}})),this.body.replaceChildren(S("div",{className:"center"},...r));return}let e=S("ul",{className:"list"});for(let r of this.inbox){let s=r.latestMessage?r.latestMessage.text??"Attachment":"No messages yet",n=S("button",{type:"button",onclick:()=>{this.openConversation(r.conversation)}},S("span",{className:"name",textContent:r.conversation.displayTitle}),S("span",{className:"preview",textContent:s}));r.isUnread&&n.append(S("span",{className:"dot",textContent:r.unreadCount?String(r.unreadCount):""})),e.append(S("li",{},n))}this.body.replaceChildren(e)}updateLauncher(){if(!this.launcher||!this.badge)return;let e=this.inbox.reduce((r,s)=>r+(s.isUnread?Math.max(1,s.unreadCount):0),0);this.badge.textContent=e>99?"99+":String(e),this.badge.hidden=e===0||this.isOpen,this.launcher.setAttribute("aria-label",this.isOpen?"Close chat":e?`Open chat, ${e} unread`:"Open chat"),this.launcher.setAttribute("aria-expanded",String(this.isOpen))}async leaveThread(){let e=this.threadSubscriptions;this.threadSubscriptions=[],this.thread=null,await Promise.allSettled(e.map(r=>r.unsubscribe()))}async openConversation(e){await this.leaveThread();let r=this.client,s=S("div",{className:"messages"});s.setAttribute("role","log"),s.setAttribute("aria-live","polite");let n=new Map(e.participants.map(a=>[a.appUserId,a.name])),i={conversation:e,messages:new Map,pending:[],nextCursor:null,list:s,names:n,cards:{busy:new Set,errors:new Map,expired:new Set}};this.thread=i,this.heading.textContent=e.displayTitle||this.config.title,this.backSlot.replaceChildren(hi("back","All conversations",()=>{this.showInbox()})),this.body.replaceChildren(s,this.composer());let o=r.realtime;this.threadSubscriptions=[o.onMessage(e.id,a=>{this.thread===i&&(i.pending=i.pending.filter(c=>c.clientMessageId!==a.message.clientMessageId),i.messages.set(a.message.id,a.message),this.renderMessages(!0),this.markThreadRead())}),o.onMessageDeleted(e.id,a=>{this.thread===i&&(i.messages.delete(a.id),this.renderMessages(!1))})],await this.loadOlder(i),this.markThreadRead()}async loadOlder(e){let r=await this.client.listMessages({conversationId:e.conversation.id,limit:30,cursor:e.nextCursor});if(this.thread!==e)return;for(let i of r.messages)e.messages.has(i.id)||e.messages.set(i.id,i);e.nextCursor=r.nextCursor;let s=e.list.childElementCount===0,n=e.list.scrollHeight;this.renderMessages(s),s||(e.list.scrollTop=e.list.scrollHeight-n)}renderMessages(e){let r=this.thread;if(!r)return;let{list:s}=r,n=s.scrollHeight-s.scrollTop-s.clientHeight<80,i=[...r.messages.values()].sort((l,u)=>l.createdAt.getTime()-u.createdAt.getTime()||l.id.localeCompare(u.id)),o=[];r.nextCursor&&o.push(S("button",{type:"button",className:"older",textContent:"Load earlier messages",onclick:()=>{this.loadOlder(r)}})),i.length===0&&r.pending.length===0&&o.push(S("p",{className:"empty",textContent:"Say hello \u{1F44B}"}));let a=null,c=si(i);for(let l of i){let u=l.card;if(u?.kind==="handoff"||u?.kind==="form_completed"){let g=S("div",{className:u.kind==="handoff"?"notice":"notice receipt",textContent:u.kind==="handoff"?l.text??"":`\u2713 ${u.title}`});g.setAttribute("role","status"),o.push(g),a=null;continue}let d=l.senderId===this.me,f=S("div",{className:d?"msg mine":"msg"});!d&&l.senderId!==a&&f.append(S("span",{className:"who",textContent:r.names.get(l.senderId)??l.senderId})),u?.kind==="link"?f.append(this.linkCard(l,u)):u?.kind==="quick_replies"?f.append(this.quickReplies(r,l,u,i)):l.text&&f.append(S("div",{className:"bubble",textContent:l.text})),c===l&&(u?.kind==="link"||u?.kind==="quick_replies")&&f.append(this.escapeButton(r,l));let h=r.cards.errors.get(l.id);h&&f.append(S("span",{className:"meta card-error",textContent:h})),l.media.length&&f.append(S("span",{className:"attachment",textContent:`\u{1F4CE} ${l.media.length===1?"1 attachment":`${l.media.length} attachments`}`}));let p=l.createdAt.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});f.append(S("span",{className:"meta",textContent:l.revision>0?`${p} \xB7 edited`:p})),o.push(f),a=l.senderId}for(let l of r.pending){let u=S("div",{className:l.failed?"msg mine failed":"msg mine"},S("div",{className:"bubble",textContent:l.text}));u.append(l.failed?S("button",{type:"button",className:"older",textContent:"Not sent. Tap to retry",onclick:()=>{this.send(l)}}):S("span",{className:"meta",textContent:"Sending\u2026"})),o.push(u)}s.replaceChildren(...o),(e||n)&&(s.scrollTop=s.scrollHeight)}linkCard(e,r){let s=S("a",{className:"card-action",href:r.url,target:"_blank",rel:"noopener noreferrer",textContent:r.buttonLabel??"Open"});s.onclick=()=>{this.client?.sendCardEvent(e.id,"opened").catch(()=>{})};let n=S("div",{className:"card"},S("strong",{className:"card-title",textContent:r.title}));return r.description&&n.append(S("p",{className:"card-text",textContent:r.description})),n.append(s),n}quickReplies(e,r,s,n){let i=e.cards.expired.has(r.id)||e.pending.length>0||ri(r,n,this.me),o=e.cards.busy.has(r.id),a=i?n.slice(n.indexOf(r)+1).find(l=>l.senderId===this.me):void 0,c=S("div",{className:s.layout==="grid"?"options grid":"options"});c.setAttribute("role","group"),c.setAttribute("aria-label",s.prompt);for(let l of s.options){let u=a?.text===l.label,d=S("button",{type:"button",className:u?"option chosen":"option",textContent:l.label,disabled:i||o});d.setAttribute("aria-pressed",String(u)),d.onclick=()=>{this.cardAction(e,r,()=>this.client.sendCardEvent(r.id,"quick_reply",l.id))},c.append(d)}return S("div",{className:"card"},S("p",{className:"card-text",textContent:s.prompt}),c)}escapeButton(e,r){let s=S("button",{type:"button",className:"escape",textContent:"Talk to a person",disabled:e.cards.busy.has(r.id)});return s.onclick=()=>{this.cardAction(e,r,()=>this.client.sendCardEvent(r.id,"escape"))},s}async cardAction(e,r,s){if(!(!this.client||e.cards.busy.has(r.id))){e.cards.busy.add(r.id),e.cards.errors.delete(r.id),this.renderMessages(!1);try{await s()}catch(n){Zr(n)==="CARD_EXPIRED"?e.cards.expired.add(r.id):e.cards.errors.set(r.id,"Could not send. Try again.")}finally{e.cards.busy.delete(r.id)}this.thread===e&&this.renderMessages(!1)}}composer(){let e=S("textarea",{rows:1,placeholder:"Write a message\u2026",maxLength:4e3});e.setAttribute("aria-label","Message");let r=S("button",{type:"submit",className:"primary",textContent:"Send",disabled:!0});e.oninput=()=>{r.disabled=!e.value.trim(),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,120)}px`};let s=S("form",{},e,r),n=()=>{let i=e.value.trim();!i||!this.thread||(e.value="",e.oninput?.(new Event("input")),this.send({clientMessageId:Yr(),text:i,failed:!1}))};return s.onsubmit=i=>{i.preventDefault(),n()},e.onkeydown=i=>{i.key==="Enter"&&!i.shiftKey&&!i.isComposing&&(i.preventDefault(),n())},s}async send(e){let r=this.thread;if(!(!r||!this.client)){e.failed=!1,r.pending.includes(e)||r.pending.push(e),this.renderMessages(!0);try{let s=await this.client.sendMessage({conversationId:r.conversation.id,text:e.text,clientMessageId:e.clientMessageId});if(this.thread!==r)return;r.pending=r.pending.filter(n=>n!==e),r.messages.set(s.id,s)}catch{e.failed=!0}this.renderMessages(!0)}}markThreadRead(){let e=this.thread;if(!e||!this.client||!this.isOpen)return;this.client.markConversationRead(e.conversation.id).catch(()=>{});let r=this.inbox.find(s=>s.conversation.id===e.conversation.id);r&&(r.isUnread=!1,r.unreadCount=0,this.updateLauncher())}showCenter(e,r=!1){let s=[S("p",{className:r?"error":"",textContent:e})];r&&s.push(S("button",{type:"button",className:"primary",textContent:"Try again",onclick:()=>{this.connect()}}));let n=S("div",{className:"center"},...s);n.setAttribute("role",r?"alert":"status"),this.body.replaceChildren(n)}};function pi(t,e){if(typeof document>"u")throw new TypeError("ConvoKitWidget: start() must run in a browser");let r=is(t),s=()=>new lr(r,e);return document.body?s():new Promise(n=>document.addEventListener("DOMContentLoaded",()=>n(s()),{once:!0}))}window.ConvoKitWidget={start:pi};})();
99
+ `;var fi={chat:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>',close:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12"/></svg>',back:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="m15 18-6-6 6-6"/></svg>'},di={WIDGET_USER_LIMIT_REACHED:"Chat is busy right now. Please try again later.",PLAN_USER_LIMIT_REACHED:"Chat is busy right now. Please try again later.",PLAN_UPGRADE_REQUIRED:"Chat is currently unavailable.",RATE_LIMITED:"Too many attempts. Please wait a few minutes and try again.",ORIGIN_NOT_ALLOWED:"Chat is not enabled for this website.",WIDGET_DISABLED:"Chat is currently unavailable.",WIDGET_MODE_DISABLED:"Chat is currently unavailable.",SUBSCRIPTION_REQUIRED:"Chat is currently unavailable."},ic={PLAN_UPGRADE_REQUIRED:'This ConvoKit plan only supports guest mode. Use mode: "guest", or upgrade to Starter for "uid" and "authToken".',SUBSCRIPTION_REQUIRED:'The free ConvoKit plan only supports guest mode. Use mode: "guest", or subscribe in the ConvoKit dashboard for "uid" and "authToken".',PLAN_USER_LIMIT_REACHED:"This ConvoKit plan has reached its monthly active user limit. Upgrade the plan in the ConvoKit dashboard.",WIDGET_USER_LIMIT_REACHED:"The monthly limit of new widget users is reached. Raise it in the ConvoKit dashboard or upgrade the plan."},Zr=t=>t instanceof Pe||t instanceof k?t.code:void 0;function oc(t){let e=Zr(t);return e&&di[e]?di[e]:"Could not connect to chat. Check your connection and try again."}function S(t,e={},...r){let s=Object.assign(document.createElement(t),e);return s.append(...r),s}function hi(t,e,r){let s=S("button",{type:"button",className:"icon",onclick:r});return s.setAttribute("aria-label",e),s.innerHTML=fi[t],s}var lr=class{constructor(e,r={}){this.config=e;this.deps=r;this.launcher=null;this.badge=null;this.client=null;this.session=null;this.connecting=null;this.inbox=[];this.inboxSubscriptions=[];this.threadSubscriptions=[];this.thread=null;this.inboxRefresh=null;this.unsubscribeSession=null;this.destroyed=!1;let s=e.mount?document.querySelector(e.mount):null;s||(s=document.createElement("div"),e.mount?.startsWith("#")&&(s.id=e.mount.slice(1)),document.body.append(s)),this.host=s,this.root=s.shadowRoot??s.attachShadow({mode:"open"}),this.root.replaceChildren(S("style",{textContent:ui(e.primaryColor,e.width,e.height,e.dockedAlignment)})),this.heading=S("h2",{textContent:e.title}),this.backSlot=S("span"),this.headerActions=S("span"),this.body=S("div",{className:"body"}),this.branding=S("footer",{className:"branding",hidden:!0},"Powered by ",S("a",{href:"https://convokit.app/?utm_source=chat-widget&utm_medium=referral",target:"_blank",rel:"noopener",textContent:"ConvoKit"})),this.panel=S("section",{className:"panel"},S("header",{},this.backSlot,this.heading,this.headerActions),this.body,this.branding),this.panel.setAttribute("aria-label",e.title),this.isOpen=!e.isDocked,e.isDocked?(this.badge=S("span",{className:"badge",hidden:!0}),this.launcher=S("button",{type:"button",className:"launcher",onclick:()=>this.toggle()}),this.launcher.innerHTML=fi.chat,this.launcher.append(this.badge),this.headerActions.append(hi("close","Close chat",()=>this.close())),this.panel.hidden=!0,this.root.append(S("div",{className:"docked"},this.panel,this.launcher)),this.updateLauncher()):(this.root.append(S("div",{className:"inline"},this.panel)),this.connect())}open(){this.destroyed||(this.isOpen=!0,this.panel.hidden=!1,this.updateLauncher(),this.connect().then(()=>this.markThreadRead()))}close(){this.config.isDocked&&(this.isOpen=!1,this.panel.hidden=!0,this.updateLauncher(),this.launcher?.focus())}toggle(){this.isOpen?this.close():this.open()}async destroy(){this.destroyed=!0,this.inboxRefresh&&clearTimeout(this.inboxRefresh),this.unsubscribeSession?.(),await this.leaveThread(),await Promise.allSettled(this.inboxSubscriptions.map(e=>e.unsubscribe())),await this.client?.disconnectUser().catch(()=>{}),this.root.replaceChildren()}get chatClient(){return this.client}connect(){return this.client&&this.session?Promise.resolve():(this.connecting??(this.connecting=this.doConnect().finally(()=>{this.connecting=null})),this.connecting)}async doConnect(){this.showCenter("Connecting\u2026");try{let e=await li(this.config,this.deps.fetch),r={clientId:this.config.clientId,tokenProvider:e.tokenProvider,backendUrl:this.config.apiUrl},s=this.deps.createClient?this.deps.createClient(r):new ei(r);if(await s.connectUser(e.appUserId),this.destroyed){await s.disconnectUser();return}this.client=s,this.session=e,this.branding.hidden=!e.showBranding,this.unsubscribeSession=s.subscribeSession(()=>{let n=s.sessionState;n.status==="disconnected"&&n.requiresReauthentication&&this.reset("Your chat session ended.")}),this.watchInbox(),this.config.startConversationWith.length?await this.openConversation(await this.findOrCreateConversation()):await this.showInbox()}catch(e){let r=ic[Zr(e)??""];r&&console.warn(`[ConvoKitWidget] ${r}`),console.error("[ConvoKitWidget] could not start chat:",e),this.client=null,this.session=null,this.showCenter(oc(e),!0)}}async reset(e){await this.leaveThread(),await Promise.allSettled(this.inboxSubscriptions.map(r=>r.unsubscribe())),this.inboxSubscriptions=[],this.unsubscribeSession?.(),this.unsubscribeSession=null,this.client=null,this.session=null,this.showCenter(e,!0)}get me(){return this.session.appUserId}watchInbox(){let e=this.client.realtime,r=()=>{this.inboxRefresh&&clearTimeout(this.inboxRefresh),this.inboxRefresh=setTimeout(()=>{this.loadInbox()},300)};this.inboxSubscriptions=[e.onInboxActivity(this.client.clientId,r),e.onInboxChanged(this.client.clientId,r)]}async loadInbox(){if(this.client)try{this.inbox=(await this.client.listInbox({limit:50})).entries,this.updateLauncher(),this.thread||this.renderInbox()}catch{}}async findOrCreateConversation(){let e=new Set([this.me,...this.config.startConversationWith]),r=await this.client.listInbox({limit:100});this.inbox=r.entries;let s=r.entries.find(n=>{let i=new Set(n.conversation.participants.map(o=>o.appUserId));return i.size===e.size&&[...e].every(o=>i.has(o))});return s?s.conversation:this.client.createConversation({participants:this.config.startConversationWith,...this.config.conversationTitle?{title:this.config.conversationTitle}:{}})}async showInbox(){await this.leaveThread(),this.heading.textContent=this.config.title,this.backSlot.replaceChildren(),this.showCenter("Loading\u2026"),await this.loadInbox(),this.renderInbox()}renderInbox(){if(!this.client||this.thread)return;if(this.inbox.length===0){let r=[S("p",{textContent:"No conversations yet."})];this.config.startConversationWith.length&&r.push(S("button",{type:"button",className:"primary",textContent:"Start a conversation",onclick:()=>{this.findOrCreateConversation().then(s=>this.openConversation(s))}})),this.body.replaceChildren(S("div",{className:"center"},...r));return}let e=S("ul",{className:"list"});for(let r of this.inbox){let s=r.latestMessage?r.latestMessage.text??"Attachment":"No messages yet",n=S("button",{type:"button",onclick:()=>{this.openConversation(r.conversation)}},S("span",{className:"name",textContent:r.conversation.displayTitle}),S("span",{className:"preview",textContent:s}));r.isUnread&&n.append(S("span",{className:"dot",textContent:r.unreadCount?String(r.unreadCount):""})),e.append(S("li",{},n))}this.body.replaceChildren(e)}updateLauncher(){if(!this.launcher||!this.badge)return;let e=this.inbox.reduce((r,s)=>r+(s.isUnread?Math.max(1,s.unreadCount):0),0);this.badge.textContent=e>99?"99+":String(e),this.badge.hidden=e===0||this.isOpen,this.launcher.setAttribute("aria-label",this.isOpen?"Close chat":e?`Open chat, ${e} unread`:"Open chat"),this.launcher.setAttribute("aria-expanded",String(this.isOpen))}async leaveThread(){let e=this.threadSubscriptions;this.threadSubscriptions=[],this.thread=null,await Promise.allSettled(e.map(r=>r.unsubscribe()))}async openConversation(e){await this.leaveThread();let r=this.client,s=S("div",{className:"messages"});s.setAttribute("role","log"),s.setAttribute("aria-live","polite");let n=new Map(e.participants.map(a=>[a.appUserId,a.name])),i={conversation:e,messages:new Map,pending:[],nextCursor:null,list:s,names:n,cards:{busy:new Set,errors:new Map,expired:new Set}};this.thread=i,this.heading.textContent=e.displayTitle||this.config.title,this.backSlot.replaceChildren(hi("back","All conversations",()=>{this.showInbox()})),this.body.replaceChildren(s,this.composer());let o=r.realtime;this.threadSubscriptions=[o.onMessage(e.id,a=>{this.thread===i&&(i.pending=i.pending.filter(c=>c.clientMessageId!==a.message.clientMessageId),i.messages.set(a.message.id,a.message),this.renderMessages(!0),this.markThreadRead())}),o.onMessageDeleted(e.id,a=>{this.thread===i&&(i.messages.delete(a.id),this.renderMessages(!1))})],await this.loadOlder(i),this.markThreadRead()}async loadOlder(e){let r=await this.client.listMessages({conversationId:e.conversation.id,limit:30,cursor:e.nextCursor});if(this.thread!==e)return;for(let i of r.messages)e.messages.has(i.id)||e.messages.set(i.id,i);e.nextCursor=r.nextCursor;let s=e.list.childElementCount===0,n=e.list.scrollHeight;this.renderMessages(s),s||(e.list.scrollTop=e.list.scrollHeight-n)}renderMessages(e){let r=this.thread;if(!r)return;let{list:s}=r,n=s.scrollHeight-s.scrollTop-s.clientHeight<80,i=[...r.messages.values()].sort((l,u)=>l.createdAt.getTime()-u.createdAt.getTime()||l.id.localeCompare(u.id)),o=[];r.nextCursor&&o.push(S("button",{type:"button",className:"older",textContent:"Load earlier messages",onclick:()=>{this.loadOlder(r)}})),i.length===0&&r.pending.length===0&&o.push(S("p",{className:"empty",textContent:"Say hello \u{1F44B}"}));let a=null,c=si(i);for(let l of i){let u=l.card;if(u?.kind==="handoff"||u?.kind==="form_completed"){let g=S("div",{className:u.kind==="handoff"?"notice":"notice receipt",textContent:u.kind==="handoff"?l.text??"":`\u2713 ${u.title}`});g.setAttribute("role","status"),o.push(g),a=null;continue}let d=l.senderId===this.me,f=S("div",{className:d?"msg mine":"msg"});!d&&l.senderId!==a&&f.append(S("span",{className:"who",textContent:r.names.get(l.senderId)??l.senderId})),u?.kind==="link"?f.append(this.linkCard(l,u)):u?.kind==="quick_replies"?f.append(this.quickReplies(r,l,u,i)):u?.kind==="answer"?f.append(S("span",{className:"ai-label",textContent:"AI answer"}),S("div",{className:"bubble ai",textContent:l.text??""})):l.text&&f.append(S("div",{className:"bubble",textContent:l.text})),c===l&&(u?.kind==="link"||u?.kind==="quick_replies"||u?.kind==="answer")&&f.append(this.escapeButton(r,l));let h=r.cards.errors.get(l.id);h&&f.append(S("span",{className:"meta card-error",textContent:h})),l.media.length&&f.append(S("span",{className:"attachment",textContent:`\u{1F4CE} ${l.media.length===1?"1 attachment":`${l.media.length} attachments`}`}));let p=l.createdAt.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});f.append(S("span",{className:"meta",textContent:l.revision>0?`${p} \xB7 edited`:p})),o.push(f),a=l.senderId}for(let l of r.pending){let u=S("div",{className:l.failed?"msg mine failed":"msg mine"},S("div",{className:"bubble",textContent:l.text}));u.append(l.failed?S("button",{type:"button",className:"older",textContent:"Not sent. Tap to retry",onclick:()=>{this.send(l)}}):S("span",{className:"meta",textContent:"Sending\u2026"})),o.push(u)}s.replaceChildren(...o),(e||n)&&(s.scrollTop=s.scrollHeight)}linkCard(e,r){let s=S("a",{className:"card-action",href:r.url,target:"_blank",rel:"noopener noreferrer",textContent:r.buttonLabel??"Open"});s.onclick=()=>{this.client?.sendCardEvent(e.id,"opened").catch(()=>{})};let n=S("div",{className:"card"},S("strong",{className:"card-title",textContent:r.title}));return r.description&&n.append(S("p",{className:"card-text",textContent:r.description})),n.append(s),n}quickReplies(e,r,s,n){let i=e.cards.expired.has(r.id)||e.pending.length>0||ri(r,n,this.me),o=e.cards.busy.has(r.id),a=i?n.slice(n.indexOf(r)+1).find(l=>l.senderId===this.me):void 0,c=S("div",{className:s.layout==="grid"?"options grid":"options"});c.setAttribute("role","group"),c.setAttribute("aria-label",s.prompt);for(let l of s.options){let u=a?.text===l.label,d=S("button",{type:"button",className:u?"option chosen":"option",textContent:l.label,disabled:i||o});d.setAttribute("aria-pressed",String(u)),d.onclick=()=>{this.cardAction(e,r,()=>this.client.sendCardEvent(r.id,"quick_reply",l.id))},c.append(d)}return S("div",{className:"card"},S("p",{className:"card-text",textContent:s.prompt}),c)}escapeButton(e,r){let s=S("button",{type:"button",className:"escape",textContent:"Talk to a person",disabled:e.cards.busy.has(r.id)});return s.onclick=()=>{this.cardAction(e,r,()=>this.client.sendCardEvent(r.id,"escape"))},s}async cardAction(e,r,s){if(!(!this.client||e.cards.busy.has(r.id))){e.cards.busy.add(r.id),e.cards.errors.delete(r.id),this.renderMessages(!1);try{await s()}catch(n){Zr(n)==="CARD_EXPIRED"?e.cards.expired.add(r.id):e.cards.errors.set(r.id,"Could not send. Try again.")}finally{e.cards.busy.delete(r.id)}this.thread===e&&this.renderMessages(!1)}}composer(){let e=S("textarea",{rows:1,placeholder:"Write a message\u2026",maxLength:4e3});e.setAttribute("aria-label","Message");let r=S("button",{type:"submit",className:"primary",textContent:"Send",disabled:!0});e.oninput=()=>{r.disabled=!e.value.trim(),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,120)}px`};let s=S("form",{},e,r),n=()=>{let i=e.value.trim();!i||!this.thread||(e.value="",e.oninput?.(new Event("input")),this.send({clientMessageId:Yr(),text:i,failed:!1}))};return s.onsubmit=i=>{i.preventDefault(),n()},e.onkeydown=i=>{i.key==="Enter"&&!i.shiftKey&&!i.isComposing&&(i.preventDefault(),n())},s}async send(e){let r=this.thread;if(!(!r||!this.client)){e.failed=!1,r.pending.includes(e)||r.pending.push(e),this.renderMessages(!0);try{let s=await this.client.sendMessage({conversationId:r.conversation.id,text:e.text,clientMessageId:e.clientMessageId});if(this.thread!==r)return;r.pending=r.pending.filter(n=>n!==e),r.messages.set(s.id,s)}catch{e.failed=!0}this.renderMessages(!0)}}markThreadRead(){let e=this.thread;if(!e||!this.client||!this.isOpen)return;this.client.markConversationRead(e.conversation.id).catch(()=>{});let r=this.inbox.find(s=>s.conversation.id===e.conversation.id);r&&(r.isUnread=!1,r.unreadCount=0,this.updateLauncher())}showCenter(e,r=!1){let s=[S("p",{className:r?"error":"",textContent:e})];r&&s.push(S("button",{type:"button",className:"primary",textContent:"Try again",onclick:()=>{this.connect()}}));let n=S("div",{className:"center"},...s);n.setAttribute("role",r?"alert":"status"),this.body.replaceChildren(n)}};function pi(t,e){if(typeof document>"u")throw new TypeError("ConvoKitWidget: start() must run in a browser");let r=is(t),s=()=>new lr(r,e);return document.body?s():new Promise(n=>document.addEventListener("DOMContentLoaded",()=>n(s()),{once:!0}))}window.ConvoKitWidget={start:pi};})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@convokitapp/chat-embed",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "Paste-a-snippet ConvoKit chat widget for any website, including Wix and Shopify.",
5
5
  "keywords": [
6
6
  "convokit",
@@ -38,7 +38,7 @@
38
38
  "validate": "npm run lint && npm run test && npm run build"
39
39
  },
40
40
  "dependencies": {
41
- "@convokitapp/sdk": "^1.3.0"
41
+ "@convokitapp/sdk": "^1.4.0"
42
42
  },
43
43
  "devDependencies": {
44
44
  "jsdom": "^25.0.1",
@@ -46,4 +46,4 @@
46
46
  "typescript": "^5.9.3",
47
47
  "vitest": "^2.1.9"
48
48
  }
49
- }
49
+ }