1var Bs=r=>{throw TypeError(r)};var es=(r,e,t)=>e.has(r)||Bs("Cannot "+t);var h=(r,e,t)=>(es(r,e,"read from private field"),t?t.call(r):e.get(r)),S=(r,e,t)=>e.has(r)?Bs("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),_=(r,e,t,s)=>(es(r,e,"write to private field"),s?s.call(r,t):e.set(r,t),t),T=(r,e,t)=>(es(r,e,"access private method"),t);var Lt=(r,e,t,s)=>({set _(i){_(r,e,i,t)},get _(){return h(r,e,s)}});import{r as M,g as fi,d as Z}from"./vendor-react-DT3EBgZv.js";import{j as pi}from"./vendor-ui-Cmvb7Owm.js";const gi="modulepreload",yi=function(r){return"/"+r},Ks={},$t=function(e,t,s){let i=Promise.resolve();if(t&&t.length>0){document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),o=(a==null?void 0:a.nonce)||(a==null?void 0:a.getAttribute("nonce"));i=Promise.allSettled(t.map(l=>{if(l=yi(l),l in Ks)return;Ks[l]=!0;const c=l.endsWith(".css"),u=c?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${u}`))return;const d=document.createElement("link");if(d.rel=c?"stylesheet":gi,c||(d.as="script"),d.crossOrigin="",d.href=l,o&&d.setAttribute("nonce",o),document.head.appendChild(d),c)return new Promise((f,p)=>{d.addEventListener("load",f),d.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${l}`)))})}))}function n(a){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=a,window.dispatchEvent(o),!o.defaultPrevented)throw a}return i.then(a=>{for(const o of a||[])o.status==="rejected"&&n(o.reason);return e().catch(n)})};var vt=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(r){return this.listeners.add(r),this.onSubscribe(),()=>{this.listeners.delete(r),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},He=typeof window>"u"||"Deno"in globalThis;function H(){}function vi(r,e){return typeof r=="function"?r(e):r}function cs(r){return typeof r=="number"&&r>=0&&r!==1/0}function Ar(r,e){return Math.max(r+(e||0)-Date.now(),0)}function Re(r,e){return typeof r=="function"?r(e):r}function X(r,e){return typeof r=="function"?r(e):r}function Ws(r,e){const{type:t="all",exact:s,fetchStatus:i,predicate:n,queryKey:a,stale:o}=r;if(a){if(s){if(e.queryHash!==xs(a,e.options))return!1}else if(!Tt(e.queryKey,a))return!1}if(t!=="all"){const l=e.isActive();if(t==="active"&&!l||t==="inactive"&&l)return!1}return!(typeof o=="boolean"&&e.isStale()!==o||i&&i!==e.state.fetchStatus||n&&!n(e))}function Hs(r,e){const{exact:t,status:s,predicate:i,mutationKey:n}=r;if(n){if(!e.options.mutationKey)return!1;if(t){if(Ge(e.options.mutationKey)!==Ge(n))return!1}else if(!Tt(e.options.mutationKey,n))return!1}return!(s&&e.state.status!==s||i&&!i(e))}function xs(r,e){return((e==null?void 0:e.queryKeyHashFn)||Ge)(r)}function Ge(r){return JSON.stringify(r,(e,t)=>hs(t)?Object.keys(t).sort().reduce((s,i)=>(s[i]=t[i],s),{}):t)}function Tt(r,e){return r===e?!0:typeof r!=typeof e?!1:r&&e&&typeof r=="object"&&typeof e=="object"?Object.keys(e).every(t=>Tt(r[t],e[t])):!1}function Cr(r,e){if(r===e)return r;const t=Gs(r)&&Gs(e);if(t||hs(r)&&hs(e)){const s=t?r:Object.keys(r),i=s.length,n=t?e:Object.keys(e),a=n.length,o=t?[]:{},l=new Set(s);let c=0;for(let u=0;u<a;u++){const d=t?u:n[u];(!t&&l.has(d)||t)&&r[d]===void 0&&e[d]===void 0?(o[d]=void 0,c++):(o[d]=Cr(r[d],e[d]),o[d]===r[d]&&r[d]!==void 0&&c++)}return i===a&&c===i?r:o}return e}function Kt(r,e){if(!e||Object.keys(r).length!==Object.keys(e).length)return!1;for(const t in r)if(r[t]!==e[t])return!1;return!0}function Gs(r){return Array.isArray(r)&&r.length===Object.keys(r).length}function hs(r){if(!Qs(r))return!1;const e=r.constructor;if(e===void 0)return!0;const t=e.prototype;
vendor: 33,843 bytes, line 1
1return!(!Qs(t)||!t.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(r)!==Object.prototype)}function Qs(r){return Object.prototype.toString.call(r)==="[object Object]"}function wi(r){return new Promise(e=>{setTimeout(e,r)})}function ds(r,e,t){return typeof t.structuralSharing=="function"?t.structuralSharing(r,e):t.structuralSharing!==!1?Cr(r,e):e}function _i(r,e,t=0){const s=[...r,e];return t&&s.length>t?s.slice(1):s}function bi(r,e,t=0){const s=[e,...r];return t&&s.length>t?s.slice(0,-1):s}var Us=Symbol();function Pr(r,e){return!r.queryFn&&(e!=null&&e.initialPromise)?()=>e.initialPromise:!r.queryFn||r.queryFn===Us?()=>Promise.reject(new Error(`Missing queryFn: '${r.queryHash}'`)):r.queryFn}function jr(r,e){return typeof r=="function"?r(...e):!!r}var De,ve,it,wr,mi=(wr=class extends vt{constructor(){super();S(this,De);S(this,ve);S(this,it);_(this,it,e=>{if(!He&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}})}onSubscribe(){h(this,ve)||this.setEventListener(h(this,it))}onUnsubscribe(){var e;this.hasListeners()||((e=h(this,ve))==null||e.call(this),_(this,ve,void 0))}setEventListener(e){var t;_(this,it,e),(t=h(this,ve))==null||t.call(this),_(this,ve,e(s=>{typeof s=="boolean"?this.setFocused(s):this.onFocus()}))}setFocused(e){h(this,De)!==e&&(_(this,De,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){var e;return typeof h(this,De)=="boolean"?h(this,De):((e=globalThis.document)==null?void 0:e.visibilityState)!=="hidden"}},De=new WeakMap,ve=new WeakMap,it=new WeakMap,wr),Ds=new mi,nt,we,at,_r,Si=(_r=class extends vt{constructor(){super();S(this,nt,!0);S(this,we);S(this,at);_(this,at,e=>{if(!He&&window.addEventListener){const t=()=>e(!0),s=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",s)}}})}onSubscribe(){h(this,we)||this.setEventListener(h(this,at))}onUnsubscribe(){var e;this.hasListeners()||((e=h(this,we))==null||e.call(this),_(this,we,void 0))}setEventListener(e){var t;_(this,at,e),(t=h(this,we))==null||t.call(this),_(this,we,e(this.setOnline.bind(this)))}setOnline(e){h(this,nt)!==e&&(_(this,nt,e),this.listeners.forEach(s=>{s(e)}))}isOnline(){return h(this,nt)}},nt=new WeakMap,we=new WeakMap,at=new WeakMap,_r),Wt=new Si;function fs(){let r,e;const t=new Promise((i,n)=>{r=i,e=n});t.status="pending",t.catch(()=>{});function s(i){Object.assign(t,i),delete t.resolve,delete t.reject}return t.resolve=i=>{s({status:"fulfilled",value:i}),r(i)},t.reject=i=>{s({status:"rejected",reason:i}),e(i)},t}function Ei(r){return Math.min(1e3*2**r,3e4)}function Ir(r){return(r??"online")==="online"?Wt.isOnline():!0}var $r=class extends Error{constructor(r){super("CancelledError"),this.revert=r==null?void 0:r.revert,this.silent=r==null?void 0:r.silent}};function ts(r){return r instanceof $r}function xr(r){let e=!1,t=0,s=!1,i;const n=fs(),a=y=>{var g;s||(f(new $r(y)),(g=r.abort)==null||g.call(r))},o=()=>{e=!0},l=()=>{e=!1},c=()=>Ds.isFocused()&&(r.networkMode==="always"||Wt.isOnline())&&r.canRun(),u=()=>Ir(r.networkMode)&&r.canRun(),d=y=>{var g;s||(s=!0,(g=r.onSuccess)==null||g.call(r,y),i==null||i(),n.resolve(y))},f=y=>{var g;s||(s=!0,(g=r.onError)==null||g.call(r,y),i==null||i(),n.reject(y))},p=()=>new Promise(y=>{var g;i=m=>{(s||c())&&y(m)},(g=r.onPause)==null||g.call(r)}).then(()=>{var y;i=void 0,s||(y=r.onContinue)==null||y.call(r)}),w=()=>{if(s)return;let y;const g=t===0?r.initialPromise:void 0;try{y=g??r.fn()}catch(m){y=Promise.reject(m)}Promise.resolve(y).then(d).catch(m=>{var R;if(s)return;const b=r.retry??(He?0:3),v=r.retryDelay??Ei,O=typeof v=="function"?v(t,m):v,j=b===!0||typeof b=="number"&&t<b||typeof b=="function"&&b(t,m);if(e||!j){f(m);return}t++,(R=r.onFail)==null||R.call(r,t,m),wi(O).then(()=>c()?void 0:p()).then(()=>{e?f(m):w()})})};return{promise:n,cancel:a,continue:()=>(i==null||i(),n),cancelRetry:o,continueRetry:l,canStart:u,start:()=>(u()?w():p().then(w),n)}}var Oi=r=>setTimeout(r,0);function ki(){let r=[],e=0,t=o=>{o()},s=o=>{o()},i=Oi;const n=o=>{e?r.push(o):i(()=>{t(o)})},a=()=>{const o=r;r=[],o.length&&i(()=>{s(()=>{o.forEach(l=>{t(l)})})})};return{batch:o=>{let l;e++;try{l=o()}finally{e--,e||a()}return l},batchCalls:o=>(...l)=>{n(()=>{o(...l)})},schedule:n,setNotifyFunction:o=>{t=o},setBatchNotifyFunction:o=>{s=o},setScheduler:o=>{i=o}}}var q=ki(),Le,br,Ur=(br=class{constructor(){S(this,Le)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),cs(this.gcTime)&&_(this,Le,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(r){this.gcTime=Math.max(this.gcTime||0,r??(He?1/0:5*60*1e3))}clearGcTimeout(){h(this,Le)&&(clearTimeout(h(this,Le)),_(this,Le,void 0))}},Le=new WeakMap,br),ot,Ne,Y,Fe,B,Ct,qe,te,le,mr,Ti=(mr=class extends Ur{constructor(e){super();S(this,te);S(this,ot);S(this,Ne);S(this,Y);S(this,Fe);S(this,B);S(this,Ct);S(this,qe);_(this,qe,!1),_(this,Ct,e.defaultOptions),this.setOptions(e.options),this.observers=[],_(this,Fe,e.client),_(this,Y,h(this,Fe).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,_(this,ot,Ri(this.options)),this.state=e.state??h(this,ot),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var e;return(e=h(this,B))==null?void 0:e.promise}setOptions(e){this.options={...h(this,Ct),...e},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&h(this,Y).remove(this)}setData(e,t){const s=ds(this.state.data,e,this.options);return T(this,te,le).call(this,{data:s,type:"success",dataUpdatedAt:t==null?void 0:t.updatedAt,manual:t==null?void 0:t.manual}),s}setState(e,t){T(this,te,le).call(this,{type:"setState",state:e,setStateOptions:t})}cancel(e){var s,i;const t=(s=h(this,B))==null?void 0:s.promise;return(i=h(this,B))==null||i.cancel(e),t?t.then(H).catch(H):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(h(this,ot))}isActive(){return this.observers.some(e=>X(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Us||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Re(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!Ar(this.state.dataUpdatedAt,e)}onFocus(){var t;const e=this.observers.find(s=>s.shouldFetchOnWindowFocus());e==null||e.refetch({cancelRefetch:!1}),(t=h(this,B))==null||t.continue()}onOnline(){var t;const e=this.observers.find(s=>s.shouldFetchOnReconnect());e==null||e.refetch({cancelRefetch:!1}),(t=h(this,B))==null||t.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),h(this,Y).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(h(this,B)&&(h(this,qe)?h(this,B).cancel({revert:!0}):h(this,B).cancelRetry()),this.scheduleGc()),h(this,Y).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||T(this,te,le).call(this,{type:"invalidate"})}fetch(e,t){var c,u,d;if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&(t!=null&&t.cancelRefetch))this.cancel({silent:!0});else if(h(this,B))return h(this,B).continueRetry(),h(this,B).promise}if(e&&this.setOptions(e),!this.options.queryFn){const f=this.observers.find(p=>p.options.queryFn);f&&this.setOptions(f.options)}const s=new AbortController,i=f=>{Object.defineProperty(f,"signal",{enumerable:!0,get:()=>(_(this,qe,!0),s.signal)})},n=()=>{const f=Pr(this.options,t),w=(()=>{const y={client:h(this,Fe),queryKey:this.queryKey,meta:this.meta};return i(y),y})();return _(this,qe,!1),this.options.persister?this.options.persister(f,w,this):f(w)},o=(()=>{const f={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:h(this,Fe),state:this.state,fetchFn:n};return i(f),f})();(c=this.options.behavior)==null||c.onFetch(o,this),_(this,Ne,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((u=o.fetchOptions)==null?void 0:u.meta))&&T(this,te,le).call(this,{type:"fetch",meta:(d=o.fetchOptions)==null?void 0:d.meta});const l=f=>{var p,w,y,g;ts(f)&&f.silent||T(this,te,le).call(this,{type:"error",error:f}),ts(f)||((w=(p=h(this,Y).config).onError)==null||w.call(p,f,this),(g=(y=h(this,Y).config).onSettled)==null||g.call(y,this.state.data,f,this)),this.scheduleGc()};return _(this,B,xr({initialPromise:t==null?void 0:t.initialPromise,fn:o.fetchFn,abort:s.abort.bind(s),onSuccess:f=>{var p,w,y,g;if(f===void 0){l(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(f)}catch(m){l(m);return}(w=(p=h(this,Y).config).onSuccess)==null||w.call(p,f,this),(g=(y=h(this,Y).config).onSettled)==null||g.call(y,f,this.state.error,this),this.scheduleGc()},onError:l,onFail:(f,p)=>{T(this,te,le).call(this,{type:"failed",failureCount:f,error:p})},onPause:()=>{T(this,te,le).call(this,{type:"pause"})},onContinue:()=>{T(this,te,le).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0})),h(this,B).start()}},ot=new WeakMap,Ne=new WeakMap,Y=new WeakMap,Fe=new WeakMap,B=new WeakMap,Ct=new WeakMap,qe=new WeakMap,te=new WeakSet,le=function(e){const t=s=>{switch(e.type){case"failed":return{...s,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...Dr(s.data,this.options),fetchMeta:e.meta??null};case"success":return _(this,Ne,void 0),{...s,data:e.data,dataUpdateCount:s.dataUpdateCount+1,dataUpdatedAt:e.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const i=e.error;return ts(i)&&i.revert&&h(this,Ne)?{...h(this,Ne),fetchStatus:"idle"}:{...s,error:i,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error"};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...e.state}}};this.state=t(this.state),q.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),h(this,Y).notify({query:this,type:"updated",action:e})})},mr);function Dr(r,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Ir(e.networkMode)?"fetching":"paused",...r===void 0&&{error:null,status:"pending"}}}function Ri(r){const e=typeof r.initialData=="function"?r.initialData():r.initialData,t=e!==void 0,s=t?typeof r.initialDataUpdatedAt=="function"?r.initialDataUpdatedAt():r.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:t?s??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:t?"success":"pending",fetchStatus:"idle"}}var ne,Sr,Ai=(Sr=class extends vt{constructor(e={}){super();S(this,ne);this.config=e,_(this,ne,new Map)}build(e,t,s){const i=t.queryKey,n=t.queryHash??xs(i,t);let a=this.get(n);return a||(a=new Ti({client:e,queryKey:i,queryHash:n,options:e.defaultQueryOptions(t),state:s,defaultOptions:e.getQueryDefaults(i)}),this.add(a)),a}add(e){h(this,ne).has(e.queryHash)||(h(this,ne).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=h(this,ne).get(e.queryHash);t&&(e.destroy(),t===e&&h(this,ne).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){q.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return h(this,ne).get(e)}getAll(){return[...h(this,ne).values()]}find(e){const t={exact:!0,...e};return this.getAll().find(s=>Ws(t,s))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(s=>Ws(e,s)):t}notify(e){q.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){q.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){q.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},ne=new WeakMap,Sr),ae,K,Me,oe,pe,Er,Ci=(Er=class extends Ur{constructor(e){super();S(this,oe);S(this,ae);S(this,K);S(this,Me);this.mutationId=e.mutationId,_(this,K,e.mutationCache),_(this,ae,[]),this.state=e.state||Lr(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){h(this,ae).includes(e)||(h(this,ae).push(e),this.clearGcTimeout(),h(this,K).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){_(this,ae,h(this,ae).filter(t=>t!==e)),this.scheduleGc(),h(this,K).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){h(this,ae).length||(this.state.status==="pending"?this.scheduleGc():h(this,K).remove(this))}continue(){var e;return((e=h(this,Me))==null?void 0:e.continue())??this.execute(this.state.variables)}async execute(e){var n,a,o,l,c,u,d,f,p,w,y,g,m,b,v,O,j,R,$,x;const t=()=>{T(this,oe,pe).call(this,{type:"continue"})};_(this,Me,xr({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(C,D)=>{T(this,oe,pe).call(this,{type:"failed",failureCount:C,error:D})},onPause:()=>{T(this,oe,pe).call(this,{type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>h(this,K).canRun(this)}));const s=this.state.status==="pending",i=!h(this,Me).canStart();try{if(s)t();else{T(this,oe,pe).call(this,{type:"pending",variables:e,isPaused:i}),await((a=(n=h(this,K).config).onMutate)==null?void 0:a.call(n,e,this));const D=await((l=(o=this.options).onMutate)==null?void 0:l.call(o,e));D!==this.state.context&&T(this,oe,pe).call(this,{type:"pending",context:D,variables:e,isPaused:i})}const C=await h(this,Me).start();return await((u=(c=h(this,K).config).onSuccess)==null?void 0:u.call(c,C,e,this.state.context,this)),await((f=(d=this.options).onSuccess)==null?void 0:f.call(d,C,e,this.state.context)),await((w=(p=h(this,K).config).onSettled)==null?void 0:w.call(p,C,null,this.state.variables,this.state.context,this)),await((g=(y=this.options).onSettled)==null?void 0:g.call(y,C,null,e,this.state.context)),T(this,oe,pe).call(this,{type:"success",data:C}),C}catch(C){try{throw await((b=(m=h(this,K).config).onError)==null?void 0:b.call(m,C,e,this.state.context,this)),await((O=(v=this.options).onError)==null?void 0:O.call(v,C,e,this.state.context)),await((R=(j=h(this,K).config).onSettled)==null?void 0:R.call(j,void 0,C,this.state.variables,this.state.context,this)),await((x=($=this.options).onSettled)==null?void 0:x.call($,void 0,C,e,this.state.context)),C}finally{T(this,oe,pe).call(this,{type:"error",error:C})}}finally{h(this,K).runNext(this)}}},ae=new WeakMap,K=new WeakMap,Me=new WeakMap,oe=new WeakSet,pe=function(e){const t=s=>{switch(e.type){case"failed":return{...s,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...s,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:e.error,failureCount:s.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),q.batch(()=>{h(this,ae).forEach(s=>{s.onMutationUpdate(e)}),h(this,K).notify({mutation:this,type:"updated",action:e})})},Er);function Lr(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var ce,se,Pt,Or,Pi=(Or=class extends vt{constructor(e={}){super();S(this,ce);S(this,se);S(this,Pt);this.config=e,_(this,ce,new Set),_(this,se,new Map),_(this,Pt,0)}build(e,t,s){const i=new Ci({mutationCache:this,mutationId:++Lt(this,Pt)._,options:e.defaultMutationOptions(t),state:s});return this.add(i),i}add(e){h(this,ce).add(e);const t=Nt(e);if(typeof t=="string"){const s=h(this,se).get(t);s?s.push(e):h(this,se).set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(h(this,ce).delete(e)){const t=Nt(e);if(typeof t=="string"){const s=h(this,se).get(t);if(s)if(s.length>1){const i=s.indexOf(e);i!==-1&&s.splice(i,1)}else s[0]===e&&h(this,se).delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Nt(e);if(typeof t=="string"){const s=h(this,se).get(t),i=s==null?void 0:s.find(n=>n.state.status==="pending");return!i||i===e}else return!0}runNext(e){var s;const t=Nt(e);if(typeof t=="string"){const i=(s=h(this,se).get(t))==null?void 0:s.find(n=>n!==e&&n.state.isPaused);return(i==null?void 0:i.continue())??Promise.resolve()}else return Promise.resolve()}clear(){q.batch(()=>{h(this,ce).forEach(e=>{this.notify({type:"removed",mutation:e})}),h(this,ce).clear(),h(this,se).clear()})}getAll(){return Array.from(h(this,ce))}find(e){const t={exact:!0,...e};return this.getAll().find(s=>Hs(t,s))}findAll(e={}){return this.getAll().filter(t=>Hs(e,t))}notify(e){q.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return q.batch(()=>Promise.all(e.map(t=>t.continue().catch(H))))}},ce=new WeakMap,se=new WeakMap,Pt=new WeakMap,Or);function Nt(r){var e;return(e=r.options.scope)==null?void 0:e.id}function Js(r){return{onFetch:(e,t)=>{var u,d,f,p,w;const s=e.options,i=(f=(d=(u=e.fetchOptions)==null?void 0:u.meta)==null?void 0:d.fetchMore)==null?void 0:f.direction,n=((p=e.state.data)==null?void 0:p.pages)||[],a=((w=e.state.data)==null?void 0:w.pageParams)||[];let o={pages:[],pageParams:[]},l=0;const c=async()=>{let y=!1;const g=v=>{Object.defineProperty(v,"signal",{enumerable:!0,get:()=>(e.signal.aborted?y=!0:e.signal.addEventListener("abort",()=>{y=!0}),e.signal)})},m=Pr(e.options,e.fetchOptions),b=async(v,O,j)=>{if(y)return Promise.reject();if(O==null&&v.pages.length)return Promise.resolve(v);const $=(()=>{const Ce={client:e.client,queryKey:e.queryKey,pageParam:O,direction:j?"backward":"forward",meta:e.options.meta};return g(Ce),Ce})(),x=await m($),{maxPages:C}=e.options,D=j?bi:_i;return{pages:D(v.pages,x,C),pageParams:D(v.pageParams,O,C)}};if(i&&n.length){const v=i==="backward",O=v?ji:zs,j={pages:n,pageParams:a},R=O(s,j);o=await b(j,R,v)}else{const v=r??n.length;do{const O=l===0?a[0]??s.initialPageParam:zs(s,o);if(l>0&&O==null)break;o=await b(o,O),l++}while(l<v)}return o};e.options.persister?e.fetchFn=()=>{var y,g;return(g=(y=e.options).persister)==null?void 0:g.call(y,c,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},t)}:e.fetchFn=c}}}function zs(r,{pages:e,pageParams:t}){const s=e.length-1;return e.length>0?r.getNextPageParam(e[s],e,t[s],t):void 0}function ji(r,{pages:e,pageParams:t}){var s;return e.length>0?(s=r.getPreviousPageParam)==null?void 0:s.call(r,e[0],e,t[0],t):void 0}var U,_e,be,lt,ut,me,ct,ht,kr,Ao=(kr=class{constructor(r={}){S(this,U);S(this,_e);S(this,be);S(this,lt);S(this,ut);S(this,me);S(this,ct);S(this,ht);_(this,U,r.queryCache||new Ai),_(this,_e,r.mutationCache||new Pi),_(this,be,r.defaultOptions||{}),_(this,lt,new Map),_(this,ut,new Map),_(this,me,0)}mount(){Lt(this,me)._++,h(this,me)===1&&(_(this,ct,Ds.subscribe(async r=>{r&&(await this.resumePausedMutations(),h(this,U).onFocus())})),_(this,ht,Wt.subscribe(async r=>{r&&(await this.resumePausedMutations(),h(this,U).onOnline())})))}unmount(){var r,e;Lt(this,me)._--,h(this,me)===0&&((r=h(this,ct))==null||r.call(this),_(this,ct,void 0),(e=h(this,ht))==null||e.call(this),_(this,ht,void 0))}isFetching(r){return h(this,U).findAll({...r,fetchStatus:"fetching"}).length}isMutating(r){return h(this,_e).findAll({...r,status:"pending"}).length}getQueryData(r){var t;const e=this.defaultQueryOptions({queryKey:r});return(t=h(this,U).get(e.queryHash))==null?void 0:t.state.data}ensureQueryData(r){const e=this.defaultQueryOptions(r),t=h(this,U).build(this,e),s=t.state.data;return s===void 0?this.fetchQuery(r):(r.revalidateIfStale&&t.isStaleByTime(Re(e.staleTime,t))&&this.prefetchQuery(e),Promise.resolve(s))}getQueriesData(r){return h(this,U).findAll(r).map(({queryKey:e,state:t})=>{const s=t.data;return[e,s]})}setQueryData(r,e,t){const s=this.defaultQueryOptions({queryKey:r}),i=h(this,U).get(s.queryHash),n=i==null?void 0:i.state.data,a=vi(e,n);if(a!==void 0)return h(this,U).build(this,s).setData(a,{...t,manual:!0})}setQueriesData(r,e,t){return q.batch(()=>h(this,U).findAll(r).map(({queryKey:s})=>[s,this.setQueryData(s,e,t)]))}getQueryState(r){var t;const e=this.defaultQueryOptions({queryKey:r});return(t=h(this,U).get(e.queryHash))==null?void 0:t.state}removeQueries(r){const e=h(this,U);q.batch(()=>{e.findAll(r).forEach(t=>{e.remove(t)})})}resetQueries(r,e){const t=h(this,U);return q.batch(()=>(t.findAll(r).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...r},e)))}cancelQueries(r,e={}){const t={revert:!0,...e},s=q.batch(()=>h(this,U).findAll(r).map(i=>i.cancel(t)));return Promise.all(s).then(H).catch(H)}invalidateQueries(r,e={}){return q.batch(()=>(h(this,U).findAll(r).forEach(t=>{t.invalidate()}),(r==null?void 0:r.refetchType)==="none"?Promise.resolve():this.refetchQueries({...r,type:(r==null?void 0:r.refetchType)??(r==null?void 0:r.type)??"active"},e)))}refetchQueries(r,e={}){const t={...e,cancelRefetch:e.cancelRefetch??!0},s=q.batch(()=>h(this,U).findAll(r).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let n=i.fetch(void 0,t);return t.throwOnError||(n=n.catch(H)),i.state.fetchStatus==="paused"?Promise.resolve():n}));return Promise.all(s).then(H)}fetchQuery(r){const e=this.defaultQueryOptions(r);e.retry===void 0&&(e.retry=!1);const t=h(this,U).build(this,e);return t.isStaleByTime(Re(e.staleTime,t))?t.fetch(e):Promise.resolve(t.state.data)}prefetchQuery(r){return this.fetchQuery(r).then(H).catch(H)}fetchInfiniteQuery(r){return r.behavior=Js(r.pages),this.fetchQuery(r)}prefetchInfiniteQuery(r){return this.fetchInfiniteQuery(r).then(H).catch(H)}ensureInfiniteQueryData(r){return r.behavior=Js(r.pages),this.ensureQueryData(r)}resumePausedMutations(){return Wt.isOnline()?h(this,_e).resumePausedMutations():Promise.resolve()}getQueryCache(){return h(this,U)}getMutationCache(){return h(this,_e)}getDefaultOptions(){return h(this,be)}setDefaultOptions(r){_(this,be,r)}setQueryDefaults(r,e){h(this,lt).set(Ge(r),{queryKey:r,defaultOptions:e})}getQueryDefaults(r){const e=[...h(this,lt).values()],t={};return e.forEach(s=>{Tt(r,s.queryKey)&&Object.assign(t,s.defaultOptions)}),t}setMutationDefaults(r,e){h(this,ut).set(Ge(r),{mutationKey:r,defaultOptions:e})}getMutationDefaults(r){const e=[...h(this,ut).values()],t={};return e.forEach(s=>{Tt(r,s.mutationKey)&&Object.assign(t,s.defaultOptions)}),t}defaultQueryOptions(r){if(r._defaulted)return r;const e={...h(this,be).queries,...this.getQueryDefaults(r.queryKey),...r,_defaulted:!0};return e.queryHash||(e.queryHash=xs(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===Us&&(e.enabled=!1),e}defaultMutationOptions(r){return r!=null&&r._defaulted?r:{...h(this,be).mutations,...(r==null?void 0:r.mutationKey)&&this.getMutationDefaults(r.mutationKey),...r,_defaulted:!0}}clear(){h(this,U).clear(),h(this,_e).clear()}},U=new WeakMap,_e=new WeakMap,be=new WeakMap,lt=new WeakMap,ut=new WeakMap,me=new WeakMap,ct=new WeakMap,ht=new WeakMap,kr),Q,A,jt,W,Be,dt,Se,Ee,It,ft,pt,Ke,We,Oe,gt,P,mt,ps,gs,ys,vs,ws,_s,bs,Nr,Tr,Ii=(Tr=class extends vt{constructor(e,t){super();S(this,P);S(this,Q);S(this,A);S(this,jt);S(this,W);S(this,Be);S(this,dt);S(this,Se);S(this,Ee);S(this,It);S(this,ft);S(this,pt);S(this,Ke);S(this,We);S(this,Oe);S(this,gt,new Set);this.options=t,_(this,Q,e),_(this,Ee,null),_(this,Se,fs()),this.options.experimental_prefetchInRender||h(this,Se).reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(h(this,A).addObserver(this),Vs(h(this,A),this.options)?T(this,P,mt).call(this):this.updateResult(),T(this,P,vs).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return ms(h(this,A),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return ms(h(this,A),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,T(this,P,ws).call(this),T(this,P,_s).call(this),h(this,A).removeObserver(this)}setOptions(e){const t=this.options,s=h(this,A);if(this.options=h(this,Q).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof X(this.options.enabled,h(this,A))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");T(this,P,bs).call(this),h(this,A).setOptions(this.options),t._defaulted&&!Kt(this.options,t)&&h(this,Q).getQueryCache().notify({type:"observerOptionsUpdated",query:h(this,A),observer:this});const i=this.hasListeners();i&&Ys(h(this,A),s,this.options,t)&&T(this,P,mt).call(this),this.updateResult(),i&&(h(this,A)!==s||X(this.options.enabled,h(this,A))!==X(t.enabled,h(this,A))||Re(this.options.staleTime,h(this,A))!==Re(t.staleTime,h(this,A)))&&T(this,P,ps).call(this);const n=T(this,P,gs).call(this);i&&(h(this,A)!==s||X(this.options.enabled,h(this,A))!==X(t.enabled,h(this,A))||n!==h(this,Oe))&&T(this,P,ys).call(this,n)}getOptimisticResult(e){const t=h(this,Q).getQueryCache().build(h(this,Q),e),s=this.createResult(t,e);return xi(this,s)&&(_(this,W,s),_(this,dt,this.options),_(this,Be,h(this,A).state)),s}getCurrentResult(){return h(this,W)}trackResult(e,t){return new Proxy(e,{get:(s,i)=>(this.trackProp(i),t==null||t(i),Reflect.get(s,i))})}trackProp(e){h(this,gt).add(e)}getCurrentQuery(){return h(this,A)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=h(this,Q).defaultQueryOptions(e),s=h(this,Q).getQueryCache().build(h(this,Q),t);return s.fetch().then(()=>this.createResult(s,t))}fetch(e){return T(this,P,mt).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),h(this,W)))}createResult(e,t){var C;const s=h(this,A),i=this.options,n=h(this,W),a=h(this,Be),o=h(this,dt),c=e!==s?e.state:h(this,jt),{state:u}=e;let d={...u},f=!1,p;if(t._optimisticResults){const D=this.hasListeners(),Ce=!D&&Vs(e,t),Je=D&&Ys(e,s,t,i);(Ce||Je)&&(d={...d,...Dr(u.data,e.options)}),t._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:w,errorUpdatedAt:y,status:g}=d;p=d.data;let m=!1;if(t.placeholderData!==void 0&&p===void 0&&g==="pending"){let D;n!=null&&n.isPlaceholderData&&t.placeholderData===(o==null?void 0:o.placeholderData)?(D=n.data,m=!0):D=typeof t.placeholderData=="function"?t.placeholderData((C=h(this,pt))==null?void 0:C.state.data,h(this,pt)):t.placeholderData,D!==void 0&&(g="success",p=ds(n==null?void 0:n.data,D,t),f=!0)}if(t.select&&p!==void 0&&!m)if(n&&p===(a==null?void 0:a.data)&&t.select===h(this,It))p=h(this,ft);else try{_(this,It,t.select),p=t.select(p),p=ds(n==null?void 0:n.data,p,t),_(this,ft,p),_(this,Ee,null)}catch(D){_(this,Ee,D)}h(this,Ee)&&(w=h(this,Ee),p=h(this,ft),y=Date.now(),g="error");const b=d.fetchStatus==="fetching",v=g==="pending",O=g==="error",j=v&&b,R=p!==void 0,x={status:g,fetchStatus:d.fetchStatus,isPending:v,isSuccess:g==="success",isError:O,isInitialLoading:j,isLoading:j,data:p,dataUpdatedAt:d.dataUpdatedAt,error:w,errorUpdatedAt:y,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:d.dataUpdateCount>0||d.errorUpdateCount>0,isFetchedAfterMount:d.dataUpdateCount>c.dataUpdateCount||d.errorUpdateCount>c.errorUpdateCount,isFetching:b,isRefetching:b&&!v,isLoadingError:O&&!R,isPaused:d.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:O&&R,isStale:Ls(e,t),refetch:this.refetch,promise:h(this,Se),isEnabled:X(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const D=Dt=>{x.status==="error"?Dt.reject(x.error):x.data!==void 0&&Dt.resolve(x.data)},Ce=()=>{const Dt=_(this,Se,x.promise=fs());D(Dt)},Je=h(this,Se);switch(Je.status){case"pending":e.queryHash===s.queryHash&&D(Je);break;case"fulfilled":(x.status==="error"||x.data!==Je.value)&&Ce();break;case"rejected":(x.status!=="error"||x.error!==Je.reason)&&Ce();break}}return x}updateResult(){const e=h(this,W),t=this.createResult(h(this,A),this.options);if(_(this,Be,h(this,A).state),_(this,dt,this.options),h(this,Be).data!==void 0&&_(this,pt,h(this,A)),Kt(t,e))return;_(this,W,t);const s=()=>{if(!e)return!0;const{notifyOnChangeProps:i}=this.options,n=typeof i=="function"?i():i;if(n==="all"||!n&&!h(this,gt).size)return!0;const a=new Set(n??h(this,gt));return this.options.throwOnError&&a.add("error"),Object.keys(h(this,W)).some(o=>{const l=o;return h(this,W)[l]!==e[l]&&a.has(l)})};T(this,P,Nr).call(this,{listeners:s()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&T(this,P,vs).call(this)}},Q=new WeakMap,A=new WeakMap,jt=new WeakMap,W=new WeakMap,Be=new WeakMap,dt=new WeakMap,Se=new WeakMap,Ee=new WeakMap,It=new WeakMap,ft=new WeakMap,pt=new WeakMap,Ke=new WeakMap,We=new WeakMap,Oe=new WeakMap,gt=new WeakMap,P=new WeakSet,mt=function(e){T(this,P,bs).call(this);let t=h(this,A).fetch(this.options,e);return e!=null&&e.throwOnError||(t=t.catch(H)),t},ps=function(){T(this,P,ws).call(this);const e=Re(this.options.staleTime,h(this,A));if(He||h(this,W).isStale||!cs(e))return;const s=Ar(h(this,W).dataUpdatedAt,e)+1;_(this,Ke,setTimeout(()=>{h(this,W).isStale||this.updateResult()},s))},gs=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(h(this,A)):this.options.refetchInterval)??!1},ys=function(e){T(this,P,_s).call(this),_(this,Oe,e),!(He||X(this.options.enabled,h(this,A))===!1||!cs(h(this,Oe))||h(this,Oe)===0)&&_(this,We,setInterval(()=>{(this.options.refetchIntervalInBackground||Ds.isFocused())&&T(this,P,mt).call(this)},h(this,Oe)))},vs=function(){T(this,P,ps).call(this),T(this,P,ys).call(this,T(this,P,gs).call(this))},ws=function(){h(this,Ke)&&(clearTimeout(h(this,Ke)),_(this,Ke,void 0))},_s=function(){h(this,We)&&(clearInterval(h(this,We)),_(this,We,void 0))},bs=function(){const e=h(this,Q).getQueryCache().build(h(this,Q),this.options);if(e===h(this,A))return;const t=h(this,A);_(this,A,e),_(this,jt,e.state),this.hasListeners()&&(t==null||t.removeObserver(this),e.addObserver(this))},Nr=function(e){q.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(h(this,W))}),h(this,Q).getQueryCache().notify({query:h(this,A),type:"observerResultsUpdated"})})},Tr);function $i(r,e){return X(e.enabled,r)!==!1&&r.state.data===void 0&&!(r.state.status==="error"&&e.retryOnMount===!1)}function Vs(r,e){return $i(r,e)||r.state.data!==void 0&&ms(r,e,e.refetchOnMount)}function ms(r,e,t){if(X(e.enabled,r)!==!1&&Re(e.staleTime,r)!=="static"){const s=typeof t=="function"?t(r):t;return s==="always"||s!==!1&&Ls(r,e)}return!1}function Ys(r,e,t,s){return(r!==e||X(s.enabled,r)===!1)&&(!t.suspense||r.state.status!=="error")&&Ls(r,t)}function Ls(r,e){return X(e.enabled,r)!==!1&&r.isStaleByTime(Re(e.staleTime,r))}function xi(r,e){return!Kt(r.getCurrentResult(),e)}var ke,Te,J,he,de,Bt,Ss,Rr,Ui=(Rr=class extends vt{constructor(e,t){super();S(this,de);S(this,ke);S(this,Te);S(this,J);S(this,he);_(this,ke,e),this.setOptions(t),this.bindMethods(),T(this,de,Bt).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){var s;const t=this.options;this.options=h(this,ke).defaultMutationOptions(e),Kt(this.options,t)||h(this,ke).getMutationCache().notify({type:"observerOptionsUpdated",mutation:h(this,J),observer:this}),t!=null&&t.mutationKey&&this.options.mutationKey&&Ge(t.mutationKey)!==Ge(this.options.mutationKey)?this.reset():((s=h(this,J))==null?void 0:s.state.status)==="pending"&&h(this,J).setOptions(this.options)}onUnsubscribe(){var e;this.hasListeners()||(e=h(this,J))==null||e.removeObserver(this)}onMutationUpdate(e){T(this,de,Bt).call(this),T(this,de,Ss).call(this,e)}getCurrentResult(){return h(this,Te)}reset(){var e;(e=h(this,J))==null||e.removeObserver(this),_(this,J,void 0),T(this,de,Bt).call(this),T(this,de,Ss).call(this)}mutate(e,t){var s;return _(this,he,t),(s=h(this,J))==null||s.removeObserver(this),_(this,J,h(this,ke).getMutationCache().build(h(this,ke),this.options)),h(this,J).addObserver(this),h(this,J).execute(e)}},ke=new WeakMap,Te=new WeakMap,J=new WeakMap,he=new WeakMap,de=new WeakSet,Bt=function(){var t;const e=((t=h(this,J))==null?void 0:t.state)??Lr();_(this,Te,{...e,isPending:e.status==="pending",isSuccess:e.status==="success",isError:e.status==="error",isIdle:e.status==="idle",mutate:this.mutate,reset:this.reset})},Ss=function(e){q.batch(()=>{var t,s,i,n,a,o,l,c;if(h(this,he)&&this.hasListeners()){const u=h(this,Te).variables,d=h(this,Te).context;(e==null?void 0:e.type)==="success"?((s=(t=h(this,he)).onSuccess)==null||s.call(t,e.data,u,d),(n=(i=h(this,he)).onSettled)==null||n.call(i,e.data,null,u,d)):(e==null?void 0:e.type)==="error"&&((o=(a=h(this,he)).onError)==null||o.call(a,e.error,u,d),(c=(l=h(this,he)).onSettled)==null||c.call(l,void 0,e.error,u,d))}
1this.listeners.forEach(u=>{u(h(this,Te))})})},Rr),Fr=M.createContext(void 0),qr=r=>{const e=M.useContext(Fr);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},Co=({client:r,children:e})=>(M.useEffect(()=>(r.mount(),()=>{r.unmount()}),[r]),pi.jsx(Fr.Provider,{value:r,children:e})),Mr=M.createContext(!1),Di=()=>M.useContext(Mr);Mr.Provider;function Li(){let r=!1;return{clearReset:()=>{r=!1},reset:()=>{r=!0},isReset:()=>r}}var Ni=M.createContext(Li()),Fi=()=>M.useContext(Ni),qi=(r,e)=>{(r.suspense||r.throwOnError||r.experimental_prefetchInRender)&&(e.isReset()||(r.retryOnMount=!1))},Mi=r=>{M.useEffect(()=>{r.clearReset()},[r])},Bi=({result:r,errorResetBoundary:e,throwOnError:t,query:s,suspense:i})=>r.isError&&!e.isReset()&&!r.isFetching&&s&&(i&&r.data===void 0||jr(t,[r.error,s])),Ki=r=>{if(r.suspense){const e=s=>s==="static"?s:Math.max(s??1e3,1e3),t=r.staleTime;r.staleTime=typeof t=="function"?(...s)=>e(t(...s)):e(t),typeof r.gcTime=="number"&&(r.gcTime=Math.max(r.gcTime,1e3))}},Wi=(r,e)=>r.isLoading&&r.isFetching&&!e,Hi=(r,e)=>(r==null?void 0:r.suspense)&&e.isPending,Xs=(r,e,t)=>e.fetchOptimistic(r).catch(()=>{t.clearReset()});function Gi(r,e,t){var d,f,p,w,y;const s=Di(),i=Fi(),n=qr(),a=n.defaultQueryOptions(r);(f=(d=n.getDefaultOptions().queries)==null?void 0:d._experimental_beforeQuery)==null||f.call(d,a),a._optimisticResults=s?"isRestoring":"optimistic",Ki(a),qi(a,i),Mi(i);const o=!n.getQueryCache().get(a.queryHash),[l]=M.useState(()=>new e(n,a)),c=l.getOptimisticResult(a),u=!s&&r.subscribed!==!1;if(M.useSyncExternalStore(M.useCallback(g=>{const m=u?l.subscribe(q.batchCalls(g)):H;return l.updateResult(),m},[l,u]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),M.useEffect(()=>{l.setOptions(a)},[a,l]),Hi(a,c))throw Xs(a,l,i);if(Bi({result:c,errorResetBoundary:i,throwOnError:a.throwOnError,query:n.getQueryCache().get(a.queryHash),suspense:a.suspense}))throw c.error;if((w=(p=n.getDefaultOptions().queries)==null?void 0:p._experimental_afterQuery)==null||w.call(p,a,c),a.experimental_prefetchInRender&&!He&&Wi(c,s)){const g=o?Xs(a,l,i):(y=n.getQueryCache().get(a.queryHash))==null?void 0:y.promise;g==null||g.catch(H).finally(()=>{l.updateResult()})}return a.notifyOnChangeProps?c:l.trackResult(c)}function Po(r,e){return Gi(r,Ii)}function jo(r,e){const t=qr(),[s]=M.useState(()=>new Ui(t,r));M.useEffect(()=>{s.setOptions(r)},[s,r]);const i=M.useSyncExternalStore(M.useCallback(a=>s.subscribe(q.batchCalls(a)),[s]),()=>s.getCurrentResult(),()=>s.getCurrentResult()),n=M.useCallback((a,o)=>{s.mutate(a,o).catch(H)},[s]);if(i.error&&jr(s.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:n,mutateAsync:i.mutate}}const Qi=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>$t(async()=>{const{default:s}=await Promise.resolve().then(()=>wt);return{default:s}},void 0).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};
1class Ns extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}}class Zs extends Ns{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class er extends Ns{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class tr extends Ns{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var Es;(function(r){r.Any="any",r.ApNortheast1="ap-northeast-1",r.ApNortheast2="ap-northeast-2",r.ApSouth1="ap-south-1",r.ApSoutheast1="ap-southeast-1",r.ApSoutheast2="ap-southeast-2",r.CaCentral1="ca-central-1",r.EuCentral1="eu-central-1",r.EuWest1="eu-west-1",r.EuWest2="eu-west-2",r.EuWest3="eu-west-3",r.SaEast1="sa-east-1",r.UsEast1="us-east-1",r.UsWest1="us-west-1",r.UsWest2="us-west-2"})(Es||(Es={}));var Ji=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(a){a(n)})}return new(t||(t=Promise))(function(n,a){function o(u){try{c(s.next(u))}catch(d){a(d)}}function l(u){try{c(s.throw(u))}catch(d){a(d)}}function c(u){u.done?n(u.value):i(u.value).then(o,l)}c((s=s.apply(r,e||[])).next())})};class zi{constructor(e,{headers:t={},customFetch:s,region:i=Es.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=Qi(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Ji(this,arguments,void 0,function*(t,s={}){var i;try{const{headers:n,method:a,body:o,signal:l}=s;let c={},{region:u}=s;u||(u=this.region);const d=new URL(`${this.url}/${t}`);u&&u!=="any"&&(c["x-region"]=u,d.searchParams.set("forceFunctionRegion",u));let f;o&&(n&&!Object.prototype.hasOwnProperty.call(n,"Content-Type")||!n)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(c["Content-Type"]="application/octet-stream",f=o):typeof o=="string"?(c["Content-Type"]="text/plain",f=o):typeof FormData<"u"&&o instanceof FormData?f=o:(c["Content-Type"]="application/json",f=JSON.stringify(o)));const p=yield this.fetch(d.toString(),{method:a||"POST",headers:Object.assign(Object.assign(Object.assign({},c),this.headers),n),body:f,signal:l}).catch(m=>{throw m.name==="AbortError"?m:new Zs(m)}),w=p.headers.get("x-relay-error");if(w&&w==="true")throw new er(p);if(!p.ok)throw new tr(p);let y=((i=p.headers.get("Content-Type"))!==null&&i!==void 0?i:"text/plain").split(";")[0].trim(),g;return y==="application/json"?g=yield p.json():y==="application/octet-stream"?g=yield p.blob():y==="text/event-stream"?g=p:y==="multipart/form-data"?g=yield p.formData():g=yield p.text(),{data:g,error:null,response:p}}catch(n){return n instanceof Error&&n.name==="AbortError"?{data:null,error:new Zs(n)}:{data:null,error:n,response:n instanceof tr||n instanceof er?n.context:void 0}}})}}var z={},Fs={},zt={},xt={},Vt={},Yt={},Vi=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")},yt=Vi();const Yi=yt.fetch,Br=yt.fetch.bind(yt),Kr=yt.Headers,Xi=yt.Request,Zi=yt.Response,wt=Object.freeze(Object.defineProperty({__proto__:null,Headers:Kr,Request:Xi,Response:Zi,default:Br,fetch:Yi},Symbol.toStringTag,{value:"Module"})),en=fi(wt);var Xt={};Object.defineProperty(Xt,"__esModule",{value:!0});let tn=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.co
1de=e.code}};Xt.default=tn;var Wr=Z&&Z.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Yt,"__esModule",{value:!0});const sn=Wr(en),rn=Wr(Xt);let nn=class{constructor(e){var t,s;this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=(t=e.shouldThrowOnError)!==null&&t!==void 0?t:!1,this.signal=e.signal,this.isMaybeSingle=(s=e.isMaybeSingle)!==null&&s!==void 0?s:!1,e.fetch?this.fetch=e.fetch:typeof fetch>"u"?this.fetch=sn.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");const s=this.fetch;let i=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var a,o,l,c;let u=null,d=null,f=null,p=n.status,w=n.statusText;if(n.ok){if(this.method!=="HEAD"){const b=await n.text();b===""||(this.headers.get("Accept")==="text/csv"||this.headers.get("Accept")&&(!((a=this.headers.get("Accept"))===null||a===void 0)&&a.includes("application/vnd.pgrst.plan+text"))?d=b:d=JSON.parse(b))}const g=(o=this.headers.get("Prefer"))===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),m=(l=n.headers.get("content-range"))===null||l===void 0?void 0:l.split("/");g&&m&&m.length>1&&(f=parseInt(m[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(d)&&(d.length>1?(u={code:"PGRST116",details:`Results contain ${d.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},d=null,f=null,p=406,w="Not Acceptable"):d.length===1?d=d[0]:d=null)}else{const g=await n.text();try{u=JSON.parse(g),Array.isArray(u)&&n.status===404&&(d=[],u=null,p=200,w="OK")}catch{n.status===404&&g===""?(p=204,w="No Content"):u={message:g}}if(u&&this.isMaybeSingle&&(!((c=u==null?void 0:u.details)===null||c===void 0)&&c.includes("0 rows"))&&(u=null,p=200,w="OK"),u&&this.shouldThrowOnError)throw new rn.default(u)}return{error:u,data:d,count:f,status:p,statusText:w}});return this.shouldThrowOnError||(i=i.catch(n=>{var a,o,l;return{error:{message:`${(a=n==null?void 0:n.name)!==null&&a!==void 0?a:"FetchError"}: ${n==null?void 0:n.message}`,details:`${(o=n==null?void 0:n.stack)!==null&&o!==void 0?o:""}`,hint:"",code:`${(l=n==null?void 0:n.code)!==null&&l!==void 0?l:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}returns(){return this}overrideTypes(){return this}};Yt.default=nn;var an=Z&&Z.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Vt,"__esModule",{value:!0});const on=an(Yt);let ln=class extends on.default{select(e){let t=!1;const s=(e??"*").split("").map(i=>/\s/.test(i)&&!t?"":(i==='"'&&(t=!t),i)).join("");return this.url.searchParams.set("select",s),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable:i,referencedTable:n=i}={}){const a=n?`${n}.order`:"order",o=this.url.searchParams.get(a);return this.url.searchParams.set(a,`${o?`${o},`:""}${e}.${t?"asc":"desc"}${s===void 0?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){const i=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:i=s}={}){const n=typeof i>"u"?"offset":`${i}.offset`,a=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(a,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}
1explain({analyze:e=!1,verbose:t=!1,settings:s=!1,buffers:i=!1,wal:n=!1,format:a="text"}={}){var o;const l=[e?"analyze":null,t?"verbose":null,s?"settings":null,i?"buffers":null,n?"wal":null].filter(Boolean).join("|"),c=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${a}; for="${c}"; options=${l};`),a==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};Vt.default=ln;var un=Z&&Z.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(xt,"__esModule",{value:!0});const cn=un(Vt);let hn=class extends cn.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){const s=Array.from(new Set(t)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(e,`in.(${s})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:s,type:i}={}){let n="";i==="plain"?n="pl":i==="phrase"?n="ph":i==="websearch"&&(n="w");const a=s===void 0?"":`(${s})`;return this.url.searchParams.append(e,`${n}fts${a}.${t}`),this}match(e){return Object.entries(e).forEach(([t,s])=>{this.url.searchParams.append(t,`eq.${s}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){const i=s?`${s}.or`:"or";return this.url.searchParams.append(i,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}};xt.default=hn;var dn=Z&&Z.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(zt,"__esModule",{value:!0});const bt=dn(xt);let fn=class{constructor(e,{headers:t={},schema:s,fetch:i}){this.url=e,this.headers=new Headers(t),this.schema=s,this.fetch=i}select(e,t){const{head:s=!1,count:i}=t??{},n=s?"HEAD":"GET";let a=!1;const o=(e??"*").split("").map(l=>/\s/.test(l)&&!a?"":(l==='"'&&(a=!a),l)).join("");return this.url.searchParams.set("select",o),i&&this.headers.append("Prefer",`count=${i}`),new bt.default({method:n,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(e,{count:t,defaultToNull:s=!0}={}){var i;const n="POST";if(t&&this.headers.append("Prefer",`count=${t}`),s||this.headers.append("Prefer","missing=default"),Array.isArray(e)){const a=e.reduce((o,l)=>o.concat(Object.keys(l)),[]);if(a.length>
10){const o=[...new Set(a)].map(l=>`"${l}"`);this.url.searchParams.set("columns",o.join(","))}}return new bt.default({method:n,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:i,defaultToNull:n=!0}={}){var a;const o="POST";if(this.headers.append("Prefer",`resolution=${s?"ignore":"merge"}-duplicates`),t!==void 0&&this.url.searchParams.set("on_conflict",t),i&&this.headers.append("Prefer",`count=${i}`),n||this.headers.append("Prefer","missing=default"),Array.isArray(e)){const l=e.reduce((c,u)=>c.concat(Object.keys(u)),[]);if(l.length>0){const c=[...new Set(l)].map(u=>`"${u}"`);this.url.searchParams.set("columns",c.join(","))}}return new bt.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch})}update(e,{count:t}={}){var s;const i="PATCH";return t&&this.headers.append("Prefer",`count=${t}`),new bt.default({method:i,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch})}delete({count:e}={}){var t;const s="DELETE";return e&&this.headers.append("Prefer",`count=${e}`),new bt.default({method:s,url:this.url,headers:this.headers,schema:this.schema,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch})}};zt.default=fn;var Hr=Z&&Z.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Fs,"__esModule",{value:!0});const pn=Hr(zt),gn=Hr(xt);let yn=class Gr{constructor(e,{headers:t={},schema:s,fetch:i}={}){this.url=e,this.headers=new Headers(t),this.schemaName=s,this.fetch=i}from(e){const t=new URL(`${this.url}/${e}`);return new pn.default(t,{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new Gr(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:i=!1,count:n}={}){var a;let o;const l=new URL(`${this.url}/rpc/${e}`);let c;s||i?(o=s?"HEAD":"GET",Object.entries(t).filter(([d,f])=>f!==void 0).map(([d,f])=>[d,Array.isArray(f)?`{${f.join(",")}}`:`${f}`]).forEach(([d,f])=>{l.searchParams.append(d,f)})):(o="POST",c=t);const u=new Headers(this.headers);return n&&u.set("Prefer",`count=${n}`),new gn.default({method:o,url:l,headers:u,schema:this.schemaName,body:c,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch})}};Fs.default=yn;var _t=Z&&Z.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(z,"__esModule",{value:!0});z.PostgrestError=z.PostgrestBuilder=z.PostgrestTransformBuilder=z.PostgrestFilterBuilder=z.PostgrestQueryBuilder=z.PostgrestClient=void 0;const Qr=_t(Fs);z.PostgrestClient=Qr.default;const Jr=_t(zt);z.PostgrestQueryBuilder=Jr.default;const zr=_t(xt);z.PostgrestFilterBuilder=zr.default;const Vr=_t(Vt);z.PostgrestTransformBuilder=Vr.default;const Yr=_t(Yt);z.PostgrestBuilder=Yr.default;const Xr=_t(Xt);z.PostgrestError=Xr.default;var vn=z.default={PostgrestClient:Qr.default,PostgrestQueryBuilder:Jr.default,PostgrestFilterBuilder:zr.default,PostgrestTransformBuilder:Vr.default,PostgrestBuilder:Yr.default,PostgrestError:Xr.default};const{PostgrestClient:wn,PostgrestQueryBuilder:Lo,PostgrestFilterBuilder:No,PostgrestTransformBuilder:Fo,PostgrestBuilder:qo,PostgrestError:Mo}=vn;class _n{static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};if(typeof process<"u"){const t=process.versions;if(t&&t.node){const s=t.node,i=parseInt(s.replace(/^v/,"").split(".")[0]);return i>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${i} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${i} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option: 2import ws from "ws" 3new RealtimeClient(url, { transport: ws })`}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=` 4 5Suggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){const s=this.getWebSocketConstructor();return new s(e,t)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}}const bn="2.75.0",mn=`realtime-js/${bn}`,Sn="1.0.0",Os=1e4,En=1e3,On=100;var Et;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(Et||(Et={}));var F;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(F||(F={}));var re;(function(r){r.close="phx_close",r.error="phx_error",r.join="phx_join",r.reply="phx_reply",r.leave="phx_leave",r.access_token="access_token"})(re||(re={}));var ks;(function(r){r.websocket="websocket"})(ks||(ks={}));var $e;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})($e||($e={}));class kn{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){const t=new DataView(e),s=new TextDecoder;
5return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){const i=t.getUint8(1),n=t.getUint8(2);let a=this.HEADER_LENGTH+2;const o=s.decode(e.slice(a,a+i));a=a+i;const l=s.decode(e.slice(a,a+n));a=a+n;const c=JSON.parse(s.decode(e.slice(a,e.byteLength)));return{ref:null,topic:o,event:l,payload:c}}}class Zr{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var I;(function(r){r.abstime="abstime",r.bool="bool",r.date="date",r.daterange="daterange",r.float4="float4",r.float8="float8",r.int2="int2",r.int4="int4",r.int4range="int4range",r.int8="int8",r.int8range="int8range",r.json="json",r.jsonb="jsonb",r.money="money",r.numeric="numeric",r.oid="oid",r.reltime="reltime",r.text="text",r.time="time",r.timestamp="timestamp",r.timestamptz="timestamptz",r.timetz="timetz",r.tsrange="tsrange",r.tstzrange="tstzrange"})(I||(I={}));const sr=(r,e,t={})=>{var s;const i=(s=t.skipTypes)!==null&&s!==void 0?s:[];return e?Object.keys(e).reduce((n,a)=>(n[a]=Tn(a,r,e,i),n),{}):{}},Tn=(r,e,t,s)=>{const i=e.find(o=>o.name===r),n=i==null?void 0:i.type,a=t[r];return n&&!s.includes(n)?ei(n,a):Ts(a)},ei=(r,e)=>{if(r.charAt(0)==="_"){const t=r.slice(1,r.length);return Pn(e,t)}switch(r){case I.bool:return Rn(e);case I.float4:case I.float8:case I.int2:case I.int4:case I.int8:case I.numeric:case I.oid:return An(e);case I.json:case I.jsonb:return Cn(e);case I.timestamp:return jn(e);case I.abstime:case I.date:case I.daterange:case I.int4range:case I.int8range:case I.money:case I.reltime:case I.text:case I.time:case I.timestamptz:case I.timetz:case I.tsrange:case I.tstzrange:return Ts(e);default:return Ts(e)}},Ts=r=>r,Rn=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},An=r=>{if(typeof r=="string"){const e=parseFloat(r);if(!Number.isNaN(e))return e}return r},Cn=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch(e){return console.log(`JSON parse error: ${e}`),r}return r},Pn=(r,e)=>{if(typeof r!="string")return r;const t=r.length-1,s=r[t];if(r[0]==="{"&&s==="}"){let n;const a=r.slice(1,t);try{n=JSON.parse("["+a+"]")}catch{n=a?a.split(","):[]}return n.map(o=>ei(e,o))}return r},jn=r=>typeof r=="string"?r.replace(" ","T"):r,ti=r=>{let e=r;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")+"/api/broadcast"};class ss{constructor(e,t,s={},i=Os){this.channel=e,this.event=t,this.payload=s,this.timeout=i,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var s;return this._hasReceived(e)&&t((s=this.receivedResp)===null||s===void 0?void 0:s.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var rr;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(rr||(rr={}));class Ot{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const s=(t==null?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},i=>{const{onJoin:n,onLeave:a,onSync:o}=this.caller;this.joinRef=this.channel._joinRef(),this.state=Ot.syncState(this.state,i,n,a),this.pendingDiffs.forEac
5h(l=>{this.state=Ot.syncDiff(this.state,l,n,a)}),this.pendingDiffs=[],o()}),this.channel._on(s.diff,{},i=>{const{onJoin:n,onLeave:a,onSync:o}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=Ot.syncDiff(this.state,i,n,a),o())}),this.onJoin((i,n,a)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:n,newPresences:a})}),this.onLeave((i,n,a)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:n,leftPresences:a})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,i){const n=this.cloneDeep(e),a=this.transformState(t),o={},l={};return this.map(n,(c,u)=>{a[c]||(l[c]=u)}),this.map(a,(c,u)=>{const d=n[c];if(d){const f=u.map(g=>g.presence_ref),p=d.map(g=>g.presence_ref),w=u.filter(g=>p.indexOf(g.presence_ref)<0),y=d.filter(g=>f.indexOf(g.presence_ref)<0);w.length>0&&(o[c]=w),y.length>0&&(l[c]=y)}else o[c]=u}),this.syncDiff(n,{joins:o,leaves:l},s,i)}static syncDiff(e,t,s,i){const{joins:n,leaves:a}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),i||(i=()=>{}),this.map(n,(o,l)=>{var c;const u=(c=e[o])!==null&&c!==void 0?c:[];if(e[o]=this.cloneDeep(l),u.length>0){const d=e[o].map(p=>p.presence_ref),f=u.filter(p=>d.indexOf(p.presence_ref)<0);e[o].unshift(...f)}s(o,u,l)}),this.map(a,(o,l)=>{let c=e[o];if(!c)return;const u=l.map(d=>d.presence_ref);c=c.filter(d=>u.indexOf(d.presence_ref)<0),e[o]=c,i(o,c,l),c.length===0&&delete e[o]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,s)=>{const i=e[s];return"metas"in i?t[s]=i.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[s]=i,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var ir;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(ir||(ir={}));var kt;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes",r.SYSTEM="system"})(kt||(kt={}));var ue;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(ue||(ue={}));class qs{constructor(e,t={config:{}},s){var i,n;if(this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=F.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new ss(this,re.join,this.params,this.timeout),this.rejoinTimer=new Zr(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=F.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(a=>a.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=F.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=F.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=F.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=F.errored,this.rejoinTimer.scheduleTimeout())}),this._on(re.reply,{},(a,o)=>{this._trigger(this._replyEventName(o),a)}),this.presence=new Ot(this),this.broadcastEndpointURL=ti(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(!((n=(i=this.params.config)===null||i===void 0?void 0:i.broadcast)===null||n===void 0)&&n.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,t=this.timeout){var s,i,n;if(this.socket.isConnected()||this.socket.connect(),this.state==F.closed){const{config:{broadcast:a,presence:o,private:l}}=this.params,c=(i=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(p=>p.filter))!==null&&i!==void 0?i:[],u=!!this.bindings[kt.PRESENCE]&&this.bindings[kt.PRESENCE].length>0||((n=this.params.config.presence)===null||n===void 0?void 0:n.enabled)===!0,d={},f={broadcast:a,presence:Object.assign(Object.assign({},o),{enabled:u}),postgres_changes:c,private:l};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(p=>e==null?void 0:e(ue.CHANNEL_ERROR,p)),this._onClose(()=>e==null?void 0:e(ue.CLOSED)),this.updateJoinPayload(Object.assign({config:f},d)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:p})=>{var w;if(this.socket.setAuth(),p===void 0){e==null||e(ue.SUBSCRIBED);return}else{const y=this.bindings.postgres_changes,g=(w=y==null?void 0:y.length)!==null&&w!==void 0?w:0,m=[];for(let b=0;b<g;b++){const v=y[b],{filter:{event:O,schema:j,table:R,filter:$}}=v,x=p&&p[b];if(x&&x.event===O&&x.schema===j&&x.table===R&&x.filter===$)m.push(Object.assign(Object.assign({},v),{id:x.id}));else{this.unsubscribe(),this.state=F.errored,e==null||e(ue.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=m,e&&e(ue.SUBSCRIBED);return}}).receive("error",p=>{this.state=F.errored,e==null||e(ue.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(p).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(ue.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this.state===F.joined&&e===kt.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(()=>this.subscribe())),this._on(e,t,s)}async send(e,t={}){var s,i;if(!this._canPush()&&e.type==="broadcast"){const{event:n,payload:a}=e,l={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:a,private:this.private}]})};try{const c=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(s=t.timeout)!==null&&s!==void 0?s:this.timeout);return await((i=c.body)===null||i===void 0?void 0:i.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var a,o,l;const c=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(o=(a=this.params)===null||a===void 0?void 0:a.config)===null||o===void 0?void 0:o.broadcast)===null||l===void 0)&&l.ack)&&n("ok"),c.receive("ok",()=>n("ok")),c.receive("error",()=>n("error")),c.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=F.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(re.close,"leave",this._joinRef())};this.joinPush.destroy();let s=null;return new Promise(i=>{s=new ss(this,re.leave,{},e),s.receive("ok",()=>{t(),i("ok")}).receive("timeout",()=>{t(),i("timed out")}).receive("error",()=>{i("error")}),s.send(),this._canPush()||s.trigger("ok",{})}).finally(()=>{s==null||s.destroy()})}
5teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=F.closed,this.bindings={}}async _fetchWithTimeout(e,t,s){const i=new AbortController,n=setTimeout(()=>i.abort(),s),a=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:i.signal}));return clearTimeout(n),a}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new ss(this,e,t,s);return this._canPush()?i.send():this._addToPushBuffer(i),i}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>On){const t=this.pushBuffer.shift();t&&(t.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${t.event}`,t.payload))}}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var i,n;const a=e.toLocaleLowerCase(),{close:o,error:l,leave:c,join:u}=re;if(s&&[o,l,c,u].indexOf(a)>=0&&s!==this._joinRef())return;let f=this._onMessage(a,t,s);if(t&&!f)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(a)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(p=>{var w,y,g;return((w=p.filter)===null||w===void 0?void 0:w.event)==="*"||((g=(y=p.filter)===null||y===void 0?void 0:y.event)===null||g===void 0?void 0:g.toLocaleLowerCase())===a}).map(p=>p.callback(f,s)):(n=this.bindings[a])===null||n===void 0||n.filter(p=>{var w,y,g,m,b,v;if(["broadcast","presence","postgres_changes"].includes(a))if("id"in p){const O=p.id,j=(w=p.filter)===null||w===void 0?void 0:w.event;return O&&((y=t.ids)===null||y===void 0?void 0:y.includes(O))&&(j==="*"||(j==null?void 0:j.toLocaleLowerCase())===((g=t.data)===null||g===void 0?void 0:g.type.toLocaleLowerCase()))}else{const O=(b=(m=p==null?void 0:p.filter)===null||m===void 0?void 0:m.event)===null||b===void 0?void 0:b.toLocaleLowerCase();return O==="*"||O===((v=t==null?void 0:t.event)===null||v===void 0?void 0:v.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===a}).map(p=>{if(typeof f=="object"&&"ids"in f){const w=f.data,{schema:y,table:g,commit_timestamp:m,type:b,errors:v}=w;f=Object.assign(Object.assign({},{schema:y,table:g,commit_timestamp:m,eventType:b,new:{},old:{},errors:v}),this._getPayloadRecords(w))}p.callback(f,s)})}_isClosed(){return this.state===F.closed}_isJoined(){return this.state===F.joined}_isJoining(){return this.state===F.joining}_isLeaving(){return this.state===F.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){const i=e.toLocaleLowerCase(),n={type:i,filter:t,callback:s};return this.bindings[i]?this.bindings[i].push(n):this.bindings[i]=[n],this}_off(e,t){const s=e.toLocaleLowerCase();return this.bindings[s]&&(this.bindings[s]=this.bindings[s].filter(i=>{var n;return!(((n=i.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===s&&qs.isEqual(i.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(re.close,{},e)}_onError(e){this._on(re.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=F.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=sr(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=sr(e.columns,e.old_record)),t}}const rs=()=>{},Ft={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},In=[1e3,2e3,5e3,1e4],$n=1e4,xn=` 6 addEventListener("message", (e) => { 7 if (e.data.event === "start") { 8 setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); 9 } 10 });`;class Un{constructor(e,t){var s;if(this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=Os,this.transport=null,this.heartbeatIntervalMs=Ft.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=rs,this.ref=0,this.reconnectTimer=null,this.logger=rs,this.conn=null,this.sendBuffer=[],this.serializer
10=new kn,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._resolveFetch=i=>{let n;return i?n=i:typeof fetch>"u"?n=(...a)=>$t(async()=>{const{default:o}=await Promise.resolve().then(()=>wt);return{default:o}},void 0).then(({default:o})=>o(...a)).catch(o=>{throw new Error(`Failed to load @supabase/node-fetch: ${o.message}. This is required for HTTP requests in Node.js environments without native fetch.`)}):n=fetch,(...a)=>n(...a)},!(!((s=t==null?void 0:t.params)===null||s===void 0)&&s.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${ks.websocket}`,this.httpEndpoint=ti(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(t==null?void 0:t.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=_n.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;throw t.includes("Node.js")?new Error(`${t} 11 12To use Realtime in Node.js, you need to provide a WebSocket implementation: 13 14Option 1: Use Node.js 22+ which has native WebSocket support 15Option 2: Install and provide the "ws" package: 16 17 npm install ws 18 19 import ws from "ws" 20 const client = new RealtimeClient(url, { 21 ...options, 22 transport: ws 23 })`):new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:Sn}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const s=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(s),this._setConnectionState("disconnected")},e?this.conn.close(e,t??""):this.conn.close(),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){const e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,s){this.logger(e,t,s)}connectionState(){switch(this.conn&&this.conn.readyState){case Et.connecting:return $e.Connecting;case Et.open:return $e.Open;case Et.closing:return $e.Closing;default:return $e.Closed}}isConnected(){return this.connectionState()===$e.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(e,t={config:{}}){const s=`realtime:${e}`,i=this.getChannels().find(n=>n.topic===s);if(i)return i;{const n=new qs(`realtime:${e}`,t,this);return this.channels.push(n),n}}push(e){const{topic:t,event:s,payload:i,ref:n}=e,a=()=>{this.encode(e,o=>{var l;(l=this.conn)===null||l===void 0||l.send(o)})};this.log("push",`${t} ${s} (${n})`,i),this.isConnected()?a():this.sendBuffer.push(a)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this._wasManualDisconnect=!1,(e=this.conn)===null||e===void 0||e.close(En,"heartbeat timeout"),setTimeout(()=>{var t;this.isConnected()||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout()},Ft.HEARTBEAT_TIMEOUT_FALLBACK);return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this._setAuthSafely("heartbeat")}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>
230&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(s=>s.topic===e&&(s._isJoined()||s._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,t=>{if(t.topic==="phoenix"&&t.event==="phx_reply")try{this.heartbeatCallback(t.payload.status==="ok"?"ok":"error")}catch(c){this.log("error","error in heartbeat callback",c)}t.ref&&t.ref===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null);const{topic:s,event:i,payload:n,ref:a}=t,o=a?`(${a})`:"",l=n.status||"";this.log("receive",`${l} ${s} ${i} ${o}`.trim(),n),this.channels.filter(c=>c._isMember(s)).forEach(c=>c._trigger(i,n,a)),this._triggerStateCallbacks("message",t)})}_clearTimer(e){var t;e==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e==="reconnect"&&((t=this.reconnectTimer)===null||t===void 0||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_teardownConnection(){this.conn&&(this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null),this._clearAllTimers(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=t=>{this.log("worker","worker error",t.message),this.workerRef.terminate()},this.workerRef.onmessage=t=>{t.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e)}_triggerChanError(){this.channels.forEach(e=>e._trigger(re.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;const s=e.match(/\?/)?"&":"?",i=new URLSearchParams(t);return`${e}${s}${i}`}_workerObjectUrl(e){let t;if(e)t=e;else{const s=new Blob([xn],{type:"application/javascript"});t=URL.createObjectURL(s)}return t}_setConnectionState(e,t=!1){this._connectionState=e,e==="connecting"?this._wasManualDisconnect=!1:e==="disconnecting"&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t;e?t=e:this.accessToken?t=await this.accessToken():t=this.accessTokenValue,this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(s=>{const i={access_token:t,version:mn};t&&s.updateJoinPayload(i),s.joinedOnce&&s._isJoined()&&s._push(re.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this.setAuth().catch(t=>{this.log("error",`error setting auth in ${e}`,t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(s=>{try{s(t)}catch(i){this.log("error",`error in ${e} callback`,i)}})}catch(s){this.log("error",`error triggering ${e} callbacks`,s)}}_setupReconnectionTimer(){this.reconnectTimer=new Zr(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},Ft.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var t,s,i,n,a,o,l,c,u;if(this.transport=(t=e==null?void 0:e.transport)!==null&&t!==void 0?t:null,this.timeout=(s=e
23==null?void 0:e.timeout)!==null&&s!==void 0?s:Os,this.heartbeatIntervalMs=(i=e==null?void 0:e.heartbeatIntervalMs)!==null&&i!==void 0?i:Ft.HEARTBEAT_INTERVAL,this.worker=(n=e==null?void 0:e.worker)!==null&&n!==void 0?n:!1,this.accessToken=(a=e==null?void 0:e.accessToken)!==null&&a!==void 0?a:null,this.heartbeatCallback=(o=e==null?void 0:e.heartbeatCallback)!==null&&o!==void 0?o:rs,e!=null&&e.params&&(this.params=e.params),e!=null&&e.logger&&(this.logger=e.logger),(e!=null&&e.logLevel||e!=null&&e.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(l=e==null?void 0:e.reconnectAfterMs)!==null&&l!==void 0?l:d=>In[d-1]||$n,this.encode=(c=e==null?void 0:e.encode)!==null&&c!==void 0?c:(d,f)=>f(JSON.stringify(d)),this.decode=(u=e==null?void 0:e.decode)!==null&&u!==void 0?u:this.serializer.decode.bind(this.serializer),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e==null?void 0:e.workerUrl}}}class Ms extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function N(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}class Dn extends Ms{constructor(e,t,s){super(e),this.name="StorageApiError",this.status=t,this.statusCode=s}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class Rs extends Ms{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}var Ln=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(a){a(n)})}return new(t||(t=Promise))(function(n,a){function o(u){try{c(s.next(u))}catch(d){a(d)}}function l(u){try{c(s.throw(u))}catch(d){a(d)}}function c(u){u.done?n(u.value):i(u.value).then(o,l)}c((s=s.apply(r,e||[])).next())})};const si=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>$t(async()=>{const{default:s}=await Promise.resolve().then(()=>wt);return{default:s}},void 0).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},Nn=()=>Ln(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield $t(()=>Promise.resolve().then(()=>wt),void 0)).Response:Response}),As=r=>{if(Array.isArray(r))return r.map(t=>As(t));if(typeof r=="function"||r!==Object(r))return r;const e={};return Object.entries(r).forEach(([t,s])=>{const i=t.replace(/([-_][a-z])/gi,n=>n.toUpperCase().replace(/[-_]/g,""));e[i]=As(s)}),e},Fn=r=>{if(typeof r!="object"||r===null)return!1;const e=Object.getPrototypeOf(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)};var Qe=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(a){a(n)})}return new(t||(t=Promise))(function(n,a){function o(u){try{c(s.next(u))}catch(d){a(d)}}function l(u){try{c(s.throw(u))}catch(d){a(d)}}function c(u){u.done?n(u.value):i(u.value).then(o,l)}c((s=s.apply(r,e||[])).next())})};const is=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),qn=(r,e,t)=>Qe(void 0,void 0,void 0,function*(){const s=yield Nn();r instanceof s&&!(t!=null&&t.noResolveJson)?r.json().then(i=>{const n=r.status||500,a=(i==null?void 0:i.statusCode)||n+"";e(new Dn(is(i),n,a))}).catch(i=>{e(new Rs(is(i),i))}):e(new Rs(is(r),r))}),Mn=(r,e,t,s)=>{const i={method:r,headers:(e==null?void 0:e.headers)||{}};return r==="GET"||!s?i:(Fn(s)?(i.headers=Object.assign({"Content-Type":"application/json"},e==null?void 0:e.headers),i.body=JSON.stringify(s)):i.body=s,e!=null&&e.duplex&&(i.duplex=e.duplex),Object.assign(Object.assign({},i),t))};function Ut(r,e,t,s,i,n){return Qe(this,void 0,void 0,function*(){return new Promise((a,o)=>{r(t,Mn(e,s,i,n)).then(l=>{if(!l.ok)throw l;return s!=null&&s.noResolveJson?l:l.json()}).then(l=>a(l)).catch(l=>qn(l,o,s))})})}function Ht(r,e,t,s){return Qe(this,void 0,void 0,function*(){return Ut(r,"GET",e,t,s)})}function ie(r,e,t,s,i){return Qe(this,void 0,void 0,function*(){return Ut(r,"POST",e,s,i,t)})}function Cs(r,e,t,s,i){return Qe(this,void 0,void 0,function*(){return Ut(r,"PUT",e,s,i,t)})}function Bn(r,e,t,s){return Qe(this,void 0,void 0,function*(){return Ut(r,"HEAD",e,Object.assign(Object.assign({},t),{noResolveJson:!0}),s)})}function ri(r,e,t,s,i){return Qe(this,void 0,void 0,function*(){return Ut(r,"DELETE",e,s,i,t)})}var Kn=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(a){a(n)})}return new(t||(t=Promise))(function(n,a){function o(u){try{c(s.next(u))}catch(d){a(d)}}function l(u){try{c(s.throw(u))}catch(d){a(d)}}function c(u){u.done?n(u.value):i(u.value).then(o,l)}c((s=s.apply(r,e||[])).next())})};class Wn{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}execute(){return Kn(this,void 0,void 0,function*(){try{return{data:(yield this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(N(e))return{data:null,error:e};throw e}})}}var Hn=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(a){a(n)})}return new(t||(t=Promise))(function(n,a){function o(u){try{c(s.next(u))}catch(d){a(d)}}function l(u){try{c(s.throw(u))}catch(d){a(d)}}function c(u){u.done?n(u.value):i(u.value).then(o,l)}c((s=s.apply(r,e||[])).next())})};class Gn{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}asStream(){return new Wn(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.execute().then(e,t)}execute(){return Hn(this,void 0,void 0,function*(){try{return{data:yield(yield this.downloadFn()).blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(N(e))return{data:null,error:e};throw e}})}}var G=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(a){a(n)})}return new(t||(t=Promise))(function(n,a){function o(u){try{c(s.next(u))}catch(d){a(d)}}function l(u){try{c(s.throw(u))}catch(d){a(d)}}function c(u){u.done?n(u.value):i(u.value).then(o,l)}c((s=s.apply(r,e||[])).next())})};const Qn={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},nr={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class Jn{constructor(e,t={},s,i){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.bucketId=s,this.fetch=si(i)}throwOnError(){return this.shouldThrowOnError=!0,this}uploadOrUpdate(e,t,s,i){return G(this,void 0,void 0,function*(){try{let n;const a=Object.assign(Object.assign({},nr),i);let o=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(a.upsert)});const l=a.metadata;typeof Blob<"u"&&s instanceof Blob?(n=new FormData,n.append("cacheControl",a.cacheControl),l&&n.append("metadata",this.encodeMetadata(l)),n.append("",s)):typeof FormData<"u"&&s instanceof FormData?(n=s,n.append("cacheControl",a.cacheControl),l&&n.append("metadata",this.encodeMetadata(l))):(n=s,o["cache-control"]=`max-age=${a.cacheControl}`,o["content-type"]=a.contentType,l&&(o["x-metadata"]=this.toBase64(this.encodeMetadata(l)))),i!=null&&i.headers&&(o=Object.assign(Object.assign({},o),i.headers));const c=this._removeEmptyFolders(t),u=this._getFinalPath(c),d=yield(e=="PUT"?Cs:ie)(this.fetch,`${this.url}/object/${u}`,n,Object.assign({headers:o},a!=null&&a.duplex?{duplex:a.duplex}:{}));return{data:{path:c,id:d.Id,fullPath:d.Key},error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(N(n))return{data:null,error:n};throw n}})}upload(e,t,s){return G(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,i){return G(this,void 0,void 0,function*(){const n=this._removeEmptyFolders(e),a=this._getFinalPath(n),o=new URL(this.url+`/object/upload/sign/${a}`);o.searchParams.set("token",t);try{let l;const c=Object.assign({upsert:nr.upsert},i),u=Object.assign(Object.assign({},this.headers),{"x-upsert":String(c.upsert)});typeof Blob<"u"&&s instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",s)):typeof FormData<"u"&&s instanceof FormData?(l=s,l.append("cacheControl",c.cacheControl)):(l=s,u["cache-control"]=`max-age=${c.cacheControl}`,u["content-type"]=c.contentType);const d=yield Cs(this.fetch,o.toString(),l,{headers:u});return{data:{path:n,fullPath:d.Key},error:null}}catch(l){if(this.shouldThrowOnError)throw l;if(N(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e,t){return G(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e);const i=Object.assign({},this.headers);t!=null&&t.upsert&&(i["x-upsert"]="true");const n=yield ie(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:i}),a=new URL(this.url+n.url),o=a.searchParams.get("token");if(!o)throw new Ms("No token returned by API");return{data:{signedUrl:a.toString(),path:e,token:o},error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(N(s))return{data:null,error:s};throw s}})}
23update(e,t,s){return G(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return G(this,void 0,void 0,function*(){try{return{data:yield ie(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s==null?void 0:s.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(this.shouldThrowOnError)throw i;if(N(i))return{data:null,error:i};throw i}})}copy(e,t,s){return G(this,void 0,void 0,function*(){try{return{data:{path:(yield ie(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s==null?void 0:s.destinationBucket},{headers:this.headers})).Key},error:null}}catch(i){if(this.shouldThrowOnError)throw i;if(N(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,s){return G(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield ie(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:t},s!=null&&s.transform?{transform:s.transform}:{}),{headers:this.headers});const a=s!=null&&s.download?`&download=${s.download===!0?"":s.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${a}`)},{data:n,error:null}}catch(i){if(this.shouldThrowOnError)throw i;if(N(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,s){return G(this,void 0,void 0,function*(){try{const i=yield ie(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=s!=null&&s.download?`&download=${s.download===!0?"":s.download}`:"";return{data:i.map(a=>Object.assign(Object.assign({},a),{signedUrl:a.signedURL?encodeURI(`${this.url}${a.signedURL}${n}`):null})),error:null}}catch(i){if(this.shouldThrowOnError)throw i;if(N(i))return{data:null,error:i};throw i}})}download(e,t){const i=typeof(t==null?void 0:t.transform)<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString((t==null?void 0:t.transform)||{}),a=n?`?${n}`:"",o=this._getFinalPath(e),l=()=>Ht(this.fetch,`${this.url}/${i}/${o}${a}`,{headers:this.headers,noResolveJson:!0});return new Gn(l,this.shouldThrowOnError)}info(e){return G(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{const s=yield Ht(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:As(s),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(N(s))return{data:null,error:s};throw s}})}exists(e){return G(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{return yield Bn(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(N(s)&&s instanceof Rs){const i=s.originalError;if([400,404].includes(i==null?void 0:i.status))return{data:!1,error:s}}throw s}})}getPublicUrl(e,t){const s=this._getFinalPath(e),i=[],n=t!=null&&t.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&i.push(n);const o=typeof(t==null?void 0:t.transform)<"u"?"render/image":"object",l=this.transformOptsToQueryString((t==null?void 0:t.transform)||{});l!==""&&i.push(l);let c=i.join("&");return c!==""&&(c=`?${c}`),{data:{publicUrl:encodeURI(`${this.url}/${o}/public/${s}${c}`)}}}remove(e){return G(this,void 0,void 0,function*(){try{return{data:yield ri(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(N(t))return{data:null,error:t};throw t}})}list(e,t,s){return G(this,void 0,void 0,function*(){try{const i=Object.assign(Object.assign(Object.assign({},Qn),t),{prefix:e||""});return{data:yield ie(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},s),error:null}}catch(i){if(this.shouldThrowOnError)throw i;if(N(i))return{data:null,error:i};throw i}})}listV2(e,t){return G(this,void 0,void 0,function*(){try{const s=Object.assign({},e);return{data:yield ie(this.fetch,`${this.url}/object/list-v2/${this.bucketId}`,s,{headers:this.headers},t),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(N(s))return{data:null,error:s};throw s}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}}const zn="2.75.0",Vn={"X-Client-Info":`storage-js/${zn}`};var ze=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(a){a(n)})}return new(t||(t=Promise))(function(n,a){function o(u){try{c(s.next(u))}catch(d){a(d)}}function l(u){try{c(s.throw(u))}catch(d){a(d)}}function c(u){u.done?n(u.value):i(u.value).then(o,l)}c((s=s.apply(r,e||[])).next())})};class Yn{constructor(e,t={},s,i){this.shouldThrowOnError=!1;const n=new URL(e);i!=null&&i.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase.")),this.url=n.href.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},Vn),t),this.fetch=si(s)}throwOnError(){return this.shouldThrowOnError=!0,this}listBuckets(){return ze(this,void 0,void 0,function*(){try{return{data:yield Ht(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(N(e))return{data:null,error:e};throw e}})}getBucket(e){return ze(this,void 0,void 0,function*(){try{return{data:yield Ht(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(N(t))return{data:null,error:t};throw t}})}createBucket(e){return ze(this,arguments,void 0,function*(t,s={public:!1}){try{return{data:yield ie(this.fetch,`${this.url}/bucket`,{id:t,name:t,type:s.type,public:s.public,file_size_limit:s.fileSizeLimit,allowed_mime_types:s.allowedMimeTypes},{headers:this.headers}),error:null}}catch(i){if(this.shouldThrowOnError)throw i;if(N(i))return{data:null,error:i};throw i}})}updateBucket(e,t){return ze(this,void 0,void 0,function*(){try{return{data:yield Cs(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(N(s))return{data:null,error:s};throw s}})}emptyBucket(e){return ze(this,void 0,void 0,function*(){try{return{data:yield ie(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(N(t))return{data:null,error:t};throw t}})}deleteBucket(e){return ze(this,void 0,void 0,function*(){try{return{data:yield ri(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(N(t))return{data:null,error:t};throw t}})}}class Xn extends Yn{constructor(e,t={},s,i){super(e,t,s,i)}from(e){return new Jn(this.url,this.headers,e,this.fetch)}}const Zn="2.75.0";let St="";typeof Deno<"u"?St="deno":typeof document<"u"?St="web":typeof navigator<"u"&&navigator.product==="ReactNative"?St="react-native":St="node";const ea={"X-Client-Info":`supabase-js-${St}/${Zn}`},ta={headers:ea},sa={schema:"public"},ra={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},ia={};var na=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(a){a(n)})}return new(t||(t=Promise))(function(n,a){function o(u){try{c(s.next(u))}catch(d){a(d)}}function l(u){try{c(s.throw(u))}catch(d){a(d)}}function c(u){u.done?n(u.value):i(u.value).then(o,l)}c((s=s.apply(r,e||[])).next())})};const aa=r=>{let e;return r?e=r:typeof fetch>"u"?e=Br:e=fetch,(...t)=>e(...t)},oa=()=>typeof Headers>"u"?Kr:Headers,la=(r,e,t)=>{const s=aa(t),i=oa();return(n,a)=>na(void 0,void 0,void 0,function*(){var o;const l=(o=yield e())!==null&&o!==void 0?o:r;let c=new i(a==null?void 0:a.headers);return c.has("apikey")||c.set("apikey",r),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),s(n,Object.assign(Object.assign({},a),{headers:c}))})};var ua=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(a){a(n)})}return new(t||(t=Promise))(function(n,a){function o(u){try{c(s.next(u))}catch(d){a(d)}}function l(u){try{c(s.throw(u))}catch(d){a(d)}}function c(u){u.done?n(u.value):i(u.value).then(o,l)}c((s=s.apply(r,e||[])).next())})};function ca(r){return r.endsWith("/")?r:r+"/"}function ha(r,e){var t,s;const{db:i,auth:n,realtime:a,global:o}=r,{db:l,auth:c,realtime:u,global:d}=e,f={db:Object.assign(Object.assign({},l),i),auth:Object.assign(Object.assign({},c),n),realtime:Object.assign(Object.assign({},u),a),storage:{},global:Object.assign(Object.assign(Object.assign({},d),o),{headers:Object.assign(Object.assign({},(t=d==null?void 0:d.headers)!==null&&t!==void 0?t:{}),(s=o==null?void 0:o.headers)!==null&&s!==void 0?s:{})}),accessToken:()=>ua(this,void 0,void 0,function*(){return""})};return r.accessToken?f.accessToken=r.accessToken:delete f.accessToken,f}function da(r){const e=r==null?void 0:r.trim();if(!e)throw new Error("supabaseUrl is required.");
23if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(ca(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}const ii="2.75.0",tt=30*1e3,Ps=3,ns=Ps*tt,fa="http://localhost:9999",pa="supabase.auth.token",ga={"X-Client-Info":`gotrue-js/${ii}`},js="X-Supabase-Api-Version",ni={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},ya=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,va=10*60*1e3;class Rt extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}}function E(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}class wa extends Rt{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}}function _a(r){return E(r)&&r.name==="AuthApiError"}class xe extends Rt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class Ae extends Rt{constructor(e,t,s,i){super(e,s,i),this.name=t,this.status=s}}class ge extends Ae{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function ba(r){return E(r)&&r.name==="AuthSessionMissingError"}class Ve extends Ae{constructor(){super("Auth session or user missing","AuthInvalidToken
23ResponseError",500,void 0)}}class qt extends Ae{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class Mt extends Ae{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function ma(r){return E(r)&&r.name==="AuthImplicitGrantRedirectError"}class ar extends Ae{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class Is extends Ae{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function as(r){return E(r)&&r.name==="AuthRetryableFetchError"}class or extends Ae{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}}class $s extends Ae{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Gt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),lr=` 24\r=`.split(""),Sa=(()=>{const r=new Array(128);for(let e=0;e<r.length;e+=1)r[e]=-1;for(let e=0;e<lr.length;e+=1)r[lr[e].charCodeAt(0)]=-2;for(let e=0;e<Gt.length;e+=1)r[Gt[e].charCodeAt(0)]=e;return r})();function ur(r,e,t){if(r!==null)for(e.queue=e.queue<<8|r,e.queuedBits+=8;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;t(Gt[s]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;t(Gt[s]),e.queuedBits-=6}}function ai(r,e,t){const s=Sa[r];if(s>-1)for(e.queue=e.queue<<6|s,e.queuedBits+=6;e.queuedBits>=8;)t(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(s===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(r)}"`)}}function cr(r){const e=[],t=a=>{e.push(String.fromCodePoint(a))},s={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},n=a=>{ka(a,s,t)};for(let a=0;a<r.length;a+=1)ai(r.charCodeAt(a),i,n);return e.join("")}function Ea(r,e){if(r<=127){e(r);return}else if(r<=2047){e(192|r>>6),e(128|r&63);return}else if(r<=65535){e(224|r>>12),e(128|r>>6&63),e(128|r&63);return}else if(r<=1114111){e(240|r>>18),e(128|r>>12&63),e(128|r>>6&63),e(128|r&63);return}throw new Error(`Unrecognized Unicode codepoint: ${r.toString(16)}`)}function Oa(r,e){for(let t=0;t<r.length;t+=1){let s=r.charCodeAt(t);if(s>55295&&s<=56319){const i=(s-55296)*1024&65535;s=(r.charCodeAt(t+1)-56320&65535|i)+65536,t+=1}Ea(s,e)}}function ka(r,e,t){if(e.utf8seq===0){if(r<=127){t(r);return}for(let s=1;s<6;s+=1)if(!(r>>7-s&1)){e.utf8seq=s;break}if(e.utf8seq===2)e.codepoint=r&31;else if(e.utf8seq===3)e.codepoint=r&15;else if(e.utf8seq===4)e.codepoint=r&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(r<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|r&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint)}}function rt(r){const e=[],t={queue:0,queuedBits:0},s=i=>{e.push(i)};for(let i=0;i<r.length;i+=1)ai(r.charCodeAt(i),t,s);return new Uint8Array(e)}function Ta(r){const e=[];return Oa(r,t=>e.push(t)),new Uint8Array(e)}function Ue(r){const e=[],t={queue:0,queuedBits:0},s=i=>{e.push(i)};return r.forEach(i=>ur(i,t,s)),ur(null,t,s),e.join("")}function Ra(r){return Math.round(Date.now()/1e3)+r}function Aa(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){const e=Math.random()*16|0;return(r=="x"?e:e&3|8).toString(16)})}const V=()=>typeof window<"u"&&typeof document<"u",Pe={tested:!1,writable:!1},oi=()=>{if(!V())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Pe.tested)return Pe.writable;const r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),Pe.tested=!0,Pe.writable=!0}catch{Pe.tested=!0,Pe.writable=!1}return Pe.writable};function Ca(r){const e={},t=new URL(r);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((i,n)=>{e[n]=i})}catch{}return t.searchParams.forEach((s,i)=>{e[i]=s}),e}const li=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>$t(async()=>{const{default:s}=await Promise.resolve().then(()=>wt);return{default:s}},void 0).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},Pa=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",st=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},je=async(r,e)=>{const t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},fe=async(r,e)=>{await r.removeItem(e)};class Zt{constructor(){this.promise=new Zt.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}Zt.promiseConstructor=Promise;function os(r){const e=r.split(".");if(e.length!==3)throw new $s("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!ya.test(e[s]))throw new $s("JWT not in base64url format");return{header:JSON.parse(cr(e[0])),payload:JSON.parse(cr(e[1])),signature:rt(e[2]),raw:{header:e[0],payload:e[1]}}}async function ja(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function Ia(r,e){return new Promise((s,i)=>{(async()=>{for(let n=0;n<1/0;n++)try{const a=await r(n);if(!e(n,null,a)){s(a);return}}catch(a){if(!e(n,a)){i(a);return}}})()})}function $a(r){return("0"+r.toString(16)).substr(-2)}function xa(){const e=new Uint32Array(56);if(typeof crypto>"u"){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=t.length;let i="";for(let n=0;n<56;n++)i+=t.charAt(Math.floor(Math.random()*s));return i}return crypto.getRandomValues(e),Array.from(e,$a).join("")}async function Ua(r){const t=new TextEncoder().encode(r),s=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(s);return Array.from(i).map(n=>String.fromCharCode(n)).join("")}async function Da(r){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code
24challenge method will default to use plain instead of sha256."),r;const t=await Ua(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Ye(r,e,t=!1){const s=xa();let i=s;t&&(i+="/PASSWORD_RECOVERY"),await st(r,`${e}-code-verifier`,i);const n=await Da(s);return[n,s===n?"plain":"s256"]}const La=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Na(r){const e=r.headers.get(js);if(!e||!e.match(La))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Fa(r){if(!r)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(r<=e)throw new Error("JWT has expired")}function qa(r){switch(r){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const Ma=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Xe(r){if(!Ma.test(r))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function ls(){const r={};return new Proxy(r,{get:(e,t)=>{if(t==="__isUserNotAvailableProxy")return!0;if(typeof t=="symbol"){const s=t.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function hr(r){return JSON.parse(JSON.stringify(r))}var Ba=function(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(r);i<s.length;i++)e.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(r,s[i])&&(t[s[i]]=r[s[i]]);return t};const Ie=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),Ka=[502,503,504];async function dr(r){var e;if(!Pa(r))throw new Is(Ie(r),0);if(Ka.includes(r.status))throw new Is(Ie(r),r.status);let t;try{t=await r.json()}catch(n){throw new xe(Ie(n),n)}let s;const i=Na(r);if(i&&i.getTime()>=ni["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?s=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(s=t.error_code),s){if(s==="weak_password")throw new or(Ie(t),r.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new ge}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((n,a)=>n&&typeof a=="string",!0))throw new or(Ie(t),r.status,t.weak_password.reasons);throw new wa(Ie(t),r.status||500,s)}const Wa=(r,e,t,s)=>{const i={method:r,headers:(e==null?void 0:e.headers)||{}};return r==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),t))};async function k(r,e,t,s){var i;const n=Object.assign({},s==null?void 0:s.headers);n[js]||(n[js]=ni["2024-01-01"].name),s!=null&&s.jwt&&(n.Authorization=`Bearer ${s.jwt}`);const a=(i=s==null?void 0:s.query)!==null&&i!==void 0?i:{};s!=null&&s.redirectTo&&(a.redirect_to=s.redirectTo);const o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",l=await Ha(r,e,t+o,{headers:n,noResolveJson:s==null?void 0:s.noResolveJson},{},s==null?void 0:s.body);return s!=null&&s.xform?s==null?void 0:s.xform(l):{data:Object.assign({},l),error:null}}async function Ha(r,e,t,s,i,n){const a=Wa(e,s,i,n);let o;try{o=await r(t,Object.assign({},a))}catch(l){throw console.error(l),new Is(Ie(l),0)}if(o.ok||await dr(o),s!=null&&s.noResolveJson)return o;try{return await o.json()}catch(l){await dr(l)}}function ee(r){var e;let t=null;Ja(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=Ra(r.expires_in)));const s=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:s},error:null}}function fr(r){const e=ee(r);return!e.error&&r.weak_password&&typeof r.weak_password=="object"&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.message&&typeof r.weak_password.message=="string"&&r.weak_password.reasons.reduce((t,s)=>t&&typeof s=="string",!0)&&(e.data.weak_password=r.weak_password),e}function ye(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function Ga(r){return{data:r,error:null}}function Qa(r){const{action_link:e,email_otp:t,hashed_token:s,redirect_to:i,verification_type:n}=r,a=Ba(r,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),o={action_link:e,email_otp:t,hashed_token:s,redirect_to:i,verification_type:n},l=Object.assign({},a);return{data:{properties:o,user:l},error:null}}function pr(r){return r}function Ja(r){return r.access_token&&r.refresh_token&&r.expires_in}const us=["global","local","others"];var za=function(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(r);i<s.length;i++)e.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(r,s[i])&&(t[s[i]]=r[s[i]]);return t};class Va{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=li(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)}}
vendor: 4,532 bytes, line 24
24async signOut(e,t=us[0]){if(us.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${us.join(", ")}`);try{return await k(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(E(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await k(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:ye})}catch(s){if(E(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{const{options:t}=e,s=za(e,["options"]),i=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(i.new_email=s==null?void 0:s.newEmail,delete i.newEmail),await k(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:Qa,redirectTo:t==null?void 0:t.redirectTo})}catch(t){if(E(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await k(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:ye})}catch(t){if(E(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,i,n,a,o,l;try{const c={nextPage:null,lastPage:0,total:0},u=await k(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e==null?void 0:e.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(n=(i=e==null?void 0:e.perPage)===null||i===void 0?void 0:i.toString())!==null&&n!==void 0?n:""},xform:pr});if(u.error)throw u.error;const d=await u.json(),f=(a=u.headers.get("x-total-count"))!==null&&a!==void 0?a:0,p=(l=(o=u.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&l!==void 0?l:[];return p.length>0&&(p.forEach(w=>{const y=parseInt(w.split(";")[0].split("=")[1].substring(0,1)),g=JSON.parse(w.split(";")[1].split("=")[1]);c[`${g}Page`]=y}),c.total=parseInt(f)),{data:Object.assign(Object.assign({},d),c),error:null}}catch(c){if(E(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){Xe(e);try{return await k(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:ye})}catch(t){if(E(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){Xe(e);try{return await k(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:ye})}catch(s){if(E(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){Xe(e);try{return await k(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:ye})}catch(s){if(E(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){Xe(e.userId);try{const{data:t,error:s}=await k(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:s}}catch(t){if(E(t))return{data:null,error:t};throw t}}async _deleteFactor(e){Xe(e.userId),Xe(e.id);try{return{data:await k(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(E(t))return{data:null,error:t};throw t}}async _listOAuthClients(e){var t,s,i,n,a,o,l;try{const c={nextPage:null,lastPage:0,total:0},u=await k(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e==null?void 0:e.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(n=(i=e==null?void 0:e.perPage)===null||i===void 0?void 0:i.toString())!==null&&n!==void 0?n:""},xform:pr});if(u.error)throw u.error;const d=await u.json(),f=(a=u.headers.get("x-total-count"))!==null&&a!==void 0?a:0,p=(l=(o=u.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&l!==void 0?l:[];return p.length>0&&(p.forEach(w=>{const y=parseInt(w.split(";")[0].split("=")[1].substring(0,1)),g=JSON.parse(w.split(";")[1].split("=")[1]);c[`${g}Page`]=y}),c.total=parseInt(f)),{data:Object.assign(Object.assign({},d),c),error:null}}catch(c){if(E(c))return{data:{clients:[]},error:c};throw c}}async _createOAuthClient(e){try{return await k(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(E(t))return{data:null,error:t};throw t}}async _getOAuthClient(e){try{return await k(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(E(t))return{data:null,error:t};throw t}}async _deleteOAuthClient(e){try{return await k(this.fetch,"DELET
24E",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(E(t))return{data:null,error:t};throw t}}async _regenerateOAuthClientSecret(e){try{return await k(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(E(t))return{data:null,error:t};throw t}}}function gr(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}const Ze={debug:!!(globalThis&&oi()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class ui extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class Ya extends ui{}async function Xa(r,e,t){Ze.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);const s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),Ze.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",r)},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(r,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async i=>{if(i){Ze.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,i.name);try{return await t()}finally{Ze.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,i.name)}}else{if(e===0)throw Ze.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new Ya(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(Ze.debug)try{const n=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(n,null," "))}catch(n){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",n)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}}))}function Za(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function ci(r){if(!/^0x[a-fA-F0-9]{40}$/.test(r))throw new Error(`@supabase/auth-js: Address "${r}" is invalid.`);return r.toLowerCase()}function eo(r){return parseInt(r,16)}function to(r){const e=new TextEncoder().encode(r);return"0x"+Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}function so(r){var e;const{chainId:t,domain:s,expirationTime:i,issuedAt:n=new Date,nonce:a,notBefore:o,requestId:l,resources:c,scheme:u,uri:d,version:f}=r;{if(!Number.isInteger(t))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${t}`);if(!s)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!d)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(f!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${f}`);if(!((e=r.statement)===null||e===void 0)&&e.includes(` 25`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${r.statement}`)}const p=ci(r.address),w=u?`${u}://${s}`:s,y=r.statement?`${r.statement} 26`:"",g=`${w} wants you to sign in with your Ethereum account: 27${p} 28 29${y}`;let m=`URI: ${d} 30Version: ${f} 31Chain ID: ${t}${a?` 32Nonce: ${a}`:""} 33Issued At: ${n.toISOString()}`;if(i&&(m+=` 34Expiration Time: ${i.toISOString()}`),o&&(m+=` 35Not Before: ${o.toISOString()}`),l&&(m+=` 36Request ID: ${l}`),c){let b=` 37Resources:`;for(const v of c){if(!v||typeof v!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${v}`);b+=` 38- ${v}`}m+=b}return`${g} 39${m}`}
39class L extends Error{constructor({message:e,code:t,cause:s,name:i}){var n;super(e,{cause:s}),this.__isWebAuthnError=!0,this.name=(n=i??(s instanceof Error?s.name:void 0))!==null&&n!==void 0?n:"Unknown Error",this.code=t}}class Qt extends L{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}function ro({error:r,options:e}){var t,s,i;const{publicKey:n}=e;if(!n)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new L({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else if(r.name==="ConstraintError"){if(((t=n.authenticatorSelection)===null||t===void 0?void 0:t.requireResidentKey)===!0)return new L({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:r});if(e.mediation==="conditional"&&((s=n.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new L({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:r});if(((i=n.authenticatorSelection)===null||i===void 0?void 0:i.userVerification)==="required")return new L({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:r})}else{if(r.name==="InvalidStateError")return new L({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:r});if(r.name==="NotAllowedError")return new L({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="NotSupportedError")return n.pubKeyCredParams.filter(o=>o.type==="public-key").length===0?new L({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:r}):new L({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:r});if(r.name==="SecurityError"){const a=window.location.hostname;if(di(a)){if(n.rp.id!==a)return new L({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new L({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="TypeError"){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new L({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:r})}else if(r.name==="UnknownError")return new L({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return new L({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r})}function io({error:r,options:e}){const{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new L({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else{if(r.name==="NotAllowedError")return new L({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="SecurityError"){const s=window.location.hostname;if(di(s)){if(t.rpId!==s)return new L({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new L({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="UnknownError")return new L({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return new L({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r})}var hi=function(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(r);i<s.length;i++)e.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(r,s[i])&&(t[s[i]]=r[s[i]]);return t};class no{createNewAbortSignal(){if(this.controller){const t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const ao=new no;function oo(r){if(!r)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(r);const{challenge:e,user:t,excludeCredentials:s}=r,i=hi(r,["challenge","user","excludeCredentials"]),n=rt(e).buffer,a=Object.assign(Object.assign({},t),{id:rt(t.id).buffer}),o=Object.assign(Object.assign({},i),{challenge:n,user:a});if(s&&s.length>0){o.excludeCredentials=new Array(s.length);for(let l=0;l<s.length;l++){const c=s[l];o.excludeCredentials[l]=Object.assign(Object.assign({},c),{id:rt(c.id).buffer,type:c.type||"public-key",transports:c.transports})}}return o}function lo(r){if(!r)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(r);const{challenge:e,allowCredentials:t}=r,s=hi(r,["challenge","allowCredentials"]),i=rt(e).buffer,n=Object.assign(Object.assign({}
39,s),{challenge:i});if(t&&t.length>0){n.allowCredentials=new Array(t.length);for(let a=0;a<t.length;a++){const o=t[a];n.allowCredentials[a]=Object.assign(Object.assign({},o),{id:rt(o.id).buffer,type:o.type||"public-key",transports:o.transports})}}return n}function uo(r){var e;if("toJSON"in r&&typeof r.toJSON=="function")return r.toJSON();const t=r;return{id:r.id,rawId:r.id,response:{attestationObject:Ue(new Uint8Array(r.response.attestationObject)),clientDataJSON:Ue(new Uint8Array(r.response.clientDataJSON))},type:"public-key",clientExtensionResults:r.getClientExtensionResults(),authenticatorAttachment:(e=t.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function co(r){var e;if("toJSON"in r&&typeof r.toJSON=="function")return r.toJSON();const t=r,s=r.getClientExtensionResults(),i=r.response;return{id:r.id,rawId:r.id,response:{authenticatorData:Ue(new Uint8Array(i.authenticatorData)),clientDataJSON:Ue(new Uint8Array(i.clientDataJSON)),signature:Ue(new Uint8Array(i.signature)),userHandle:i.userHandle?Ue(new Uint8Array(i.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(e=t.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function di(r){return r==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(r)}function yr(){var r,e;return!!(V()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((r=navigator==null?void 0:navigator.credentials)===null||r===void 0?void 0:r.create)=="function"&&typeof((e=navigator==null?void 0:navigator.credentials)===null||e===void 0?void 0:e.get)=="function")}async function ho(r){try{const e=await navigator.credentials.create(r);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Qt("Browser returned unexpected credential type",e)}:{data:null,error:new Qt("Empty credential response",e)}}catch(e){return{data:null,error:ro({error:e,options:r})}}}async function fo(r){try{const e=await navigator.credentials.get(r);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Qt("Browser returned unexpected credential type",e)}:{data:null,error:new Qt("Empty credential response",e)}}catch(e){return{data:null,error:io({error:e,options:r})}}}const po={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"none"},go={userVerification:"preferred",hints:["security-key"]};function Jt(...r){const e=i=>i!==null&&typeof i=="object"&&!Array.isArray(i),t=i=>i instanceof ArrayBuffer||ArrayBuffer.isView(i),s={};for(const i of r)if(i)for(const n in i){const a=i[n];if(a!==void 0)if(Array.isArray(a))s[n]=a;else if(t(a))s[n]=a;else if(e(a)){const o=s[n];e(o)?s[n]=Jt(o,a):s[n]=Jt(a)}else s[n]=a}return s}function yo(r,e){return Jt(po,r,e||{})}function vo(r,e){return Jt(go,r,e||{})}class wo{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:s,signal:i},n){try{const{data:a,error:o}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!a)return{data:null,error:o};const l=i??ao.createNewAbortSignal();if(a.webauthn.type==="create"){const{user:c}=a.webauthn.credential_options.publicKey;c.name||(c.name=`${c.id}:${s}`),c.displayName||(c.displayName=c.name)}switch(a.webauthn.type){case"create":{const c=yo(a.webauthn.credential_options.publicKey,n==null?void 0:n.create),{data:u,error:d}=await ho({publicKey:c,signal:l});return u?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:u}},error:null}:{data:null,error:d}}case"request":{const c=vo(a.webauthn.credential_options.publicKey,n==null?void 0:n.request),{data:u,error:d}=await fo(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:c,signal:l}));return u?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:u}},error:null}:{data:null,error:d}}}}catch(a){return E(a)?{data:null,error:a}:{data:null,error:new xe("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:t,webauthn:s}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:s})}async _authenticate({factorId:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:i}},n){if(!t)return{data:null,error:new Rt("rpId is required for WebAuthn authentication")};
39try{if(!yr())return{data:null,error:new xe("Browser does not support WebAuthn",null)};const{data:a,error:o}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:s},signal:i},{request:n});if(!a)return{data:null,error:o};const{webauthn:l}=a;return this._verify({factorId:e,challengeId:a.challengeId,webauthn:{type:l.type,rpId:t,rpOrigins:s,credential_response:l.credential_response}})}catch(a){return E(a)?{data:null,error:a}:{data:null,error:new xe("Unexpected error in authenticate",a)}}}async _register({friendlyName:e,rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:i},n){if(!t)return{data:null,error:new Rt("rpId is required for WebAuthn registration")};try{if(!yr())return{data:null,error:new xe("Browser does not support WebAuthn",null)};const{data:a,error:o}=await this._enroll({friendlyName:e});if(!a)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==null?void 0:u.id}):void 0),{data:null,error:o};const{data:l,error:c}=await this._challenge({factorId:a.id,friendlyName:a.friendly_name,webauthn:{rpId:t,rpOrigins:s},signal:i},{create:n});return l?this._verify({factorId:a.id,challengeId:l.challengeId,webauthn:{rpId:t,rpOrigins:s,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:c}}catch(a){return E(a)?{data:null,error:a}:{data:null,error:new xe("Unexpected error in register",a)}}}}Za();const _o={url:fa,storageKey:pa,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:ga,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function vr(r,e,t){return await t()}const et={};class At{get jwks(){var e,t;return(t=(e=et[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){et[this.storageKey]=Object.assign(Object.assign({},et[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=et[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){et[this.storageKey]=Object.assign(Object.assign({},et[this.storageKey]),{cachedAt:e})}constructor(e){var t,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=At.nextInstanceID,At.nextInstanceID+=1,this.instanceID>0&&V()&&console.warn("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.");const i=Object.assign(Object.assign({},_o),e);if(this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.persistSession=i.persistSession,this.storageKey=i.storageKey,this.autoRefreshToken=i.autoRefreshToken,this.admin=new Va({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=li(i.fetch),this.lock=i.lock||vr,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:V()&&(!((t=globalThis==null?void 0:globalThis.navigator)===null||t===void 0)&&t.locks)?this.lock=Xa:this.lock=vr,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 wo(this)},this.persistSession?(i.storage?this.storage=i.storage:oi()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=gr(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=gr(this.memoryStorage)),V()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${ii}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{const t=Ca(window.location.href);let s="none";if(this._isImplicitGrantCallback(t)?s="implicit":await this._isPKCECallback(t)&&(s="pkce"),V()&&this.detectSessionInUrl&&s!=="none"){const{data:i,error:n}=await this._getSessionFromURL(t,s);if(n){if(this._debug("#_initialize()","error detecting session from URL",n),ma(n)){const l=(e=n.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:n}}return await this._removeSession(),{error:n}}const{session:a,redirectType:o}=i;return this._debug("#_initialize()","detected session in URL",a,"redirect type",o),await this._saveSession(a),setTimeout(async()=>{o==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",a):await this._notifyAllSubscribers("SIGNED_IN",a)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return E(t)?{error:t}:{error:new xe("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,i;try{const n=await k(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e==null?void 0:e.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(i=e==null?void 0:e.options)===null||i===void 0?void 0:i.captchaToken}},xform:ee}),{data:a,error:o}=n;
39if(o||!a)return{data:{user:null,session:null},error:o};const l=a.session,c=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(n){if(E(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,s,i;try{let n;if("email"in e){const{email:u,password:d,options:f}=e;let p=null,w=null;this.flowType==="pkce"&&([p,w]=await Ye(this.storage,this.storageKey)),n=await k(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f==null?void 0:f.emailRedirectTo,body:{email:u,password:d,data:(t=f==null?void 0:f.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken},code_challenge:p,code_challenge_method:w},xform:ee})}else if("phone"in e){const{phone:u,password:d,options:f}=e;n=await k(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:d,data:(s=f==null?void 0:f.data)!==null&&s!==void 0?s:{},channel:(i=f==null?void 0:f.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken}},xform:ee})}else throw new qt("You must provide either an email or phone number and a password");const{data:a,error:o}=n;if(o||!a)return{data:{user:null,session:null},error:o};const l=a.session,c=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(n){if(E(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithPassword(e){try{let t;if("email"in e){const{email:n,password:a,options:o}=e;t=await k(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:a,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:fr})}else if("phone"in e){const{phone:n,password:a,options:o}=e;t=await k(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:a,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:fr})}else throw new qt("You must provide either an email or phone number and a password");const{data:s,error:i}=t;return i?{data:{user:null,session:null},error:i}:!s||!s.session||!s.user?{data:{user:null,session:null},error:new Ve}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:i})}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,s,i,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,s,i,n,a,o,l,c,u,d,f;let p,w;if("message"in e)p=e.message,w=e.signature;else{const{chain:y,wallet:g,statement:m,options:b}=e;let v;if(V())if(typeof g=="object")v=g;else{const C=window;if("ethereum"in C&&typeof C.ethereum=="object"&&"request"in C.ethereum&&typeof C.ethereum.request=="function")v=C.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 g!="object"||!(b!=null&&b.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");v=g}
39const O=new URL((t=b==null?void 0:b.url)!==null&&t!==void 0?t:window.location.href),j=await v.request({method:"eth_requestAccounts"}).then(C=>C).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!j||j.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const R=ci(j[0]);let $=(s=b==null?void 0:b.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!$){const C=await v.request({method:"eth_chainId"});$=eo(C)}const x={domain:O.host,address:R,statement:m,uri:O.href,version:"1",chainId:$,nonce:(i=b==null?void 0:b.signInWithEthereum)===null||i===void 0?void 0:i.nonce,issuedAt:(a=(n=b==null?void 0:b.signInWithEthereum)===null||n===void 0?void 0:n.issuedAt)!==null&&a!==void 0?a:new Date,expirationTime:(o=b==null?void 0:b.signInWithEthereum)===null||o===void 0?void 0:o.expirationTime,notBefore:(l=b==null?void 0:b.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(c=b==null?void 0:b.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(u=b==null?void 0:b.signInWithEthereum)===null||u===void 0?void 0:u.resources};p=so(x),w=await v.request({method:"personal_sign",params:[to(p),R]})}try{const{data:y,error:g}=await k(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:p,signature:w},!((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:ee});if(g)throw g;return!y||!y.session||!y.user?{data:{user:null,session:null},error:new Ve}:(y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("SIGNED_IN",y.session)),{data:Object.assign({},y),error:g})}catch(y){if(E(y))return{data:{user:null,session:null},error:y};throw y}}async signInWithSolana(e){var t,s,i,n,a,o,l,c,u,d,f,p;let w,y;if("message"in e)w=e.message,y=e.signature;else{const{chain:g,wallet:m,statement:b,options:v}=e;let O;if(V())if(typeof m=="object")O=m;else{const R=window;if("solana"in R&&typeof R.solana=="object"&&("signIn"in R.solana&&typeof R.solana.signIn=="function"||"signMessage"in R.solana&&typeof R.solana.signMessage=="function"))O=R.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 m!="object"||!(v!=null&&v.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");O=m}const j=new URL((t=v==null?void 0:v.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in O&&O.signIn){const R=await O.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},v==null?void 0:v.signInWithSolana),{version:"1",domain:j.host,uri:j.href}),b?{statement:b}:null));let $;if(Array.isArray(R)&&R[0]&&typeof R[0]=="object")$=R[0];else if(R&&typeof R=="object"&&"signedMessage"in R&&"signature"in R)$=R;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in $&&"signature"in $&&(typeof $.signedMessage=="string"||$.signedMessage instanceof Uint8Array)&&$.signature instanceof Uint8Array)w=typeof $.signedMessage=="string"?$.signedMessage:new TextDecoder().decode($.signedMessage),y=$.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in O)||typeof O.signMessage!="function"||!("publicKey"in O)||typeof O!="object"||!O.publicKey||!("toBase58"in O.publicKey)||typeof O.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");w=[`${j.host} wants you to sign in with your Solana account:`,O.publicKey.toBase58(),...b?["",b,""]:[""],"Version: 1",`URI: ${j.href}
39`,`Issued At: ${(i=(s=v==null?void 0:v.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&i!==void 0?i:new Date().toISOString()}`,...!((n=v==null?void 0:v.signInWithSolana)===null||n===void 0)&&n.notBefore?[`Not Before: ${v.signInWithSolana.notBefore}`]:[],...!((a=v==null?void 0:v.signInWithSolana)===null||a===void 0)&&a.expirationTime?[`Expiration Time: ${v.signInWithSolana.expirationTime}`]:[],...!((o=v==null?void 0:v.signInWithSolana)===null||o===void 0)&&o.chainId?[`Chain ID: ${v.signInWithSolana.chainId}`]:[],...!((l=v==null?void 0:v.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${v.signInWithSolana.nonce}`]:[],...!((c=v==null?void 0:v.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${v.signInWithSolana.requestId}`]:[],...!((d=(u=v==null?void 0:v.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||d===void 0)&&d.length?["Resources",...v.signInWithSolana.resources.map($=>`- ${$}`)]:[]].join(` 40`);const R=await O.signMessage(new TextEncoder().encode(w),"utf8");if(!R||!(R instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");y=R}}try{const{data:g,error:m}=await k(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:w,signature:Ue(y)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:ee});if(m)throw m;return!g||!g.session||!g.user?{data:{user:null,session:null},error:new Ve}:(g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("SIGNED_IN",g.session)),{data:Object.assign({},g),error:m})}catch(g){if(E(g))return{data:{user:null,session:null},error:g};throw g}}async _exchangeCodeForSession(e){const t=await je(this.storage,`${this.storageKey}-code-verifier`),[s,i]=(t??"").split("/");try{const{data:n,error:a}=await k(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:ee});if(await fe(this.storage,`${this.storageKey}-code-verifier`),a)throw a;return!n||!n.session||!n.user?{data:{user:null,session:null,redirectType:null},error:new Ve}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:i??null}),error:a})}catch(n){if(E(n))return{data:{user:null,session:null,redirectType:null},error:n};throw n}}async signInWithIdToken(e){try{const{options:t,provider:s,token:i,access_token:n,nonce:a}=e,o=await k(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:i,access_token:n,nonce:a,gotrue_meta_security:{captcha_token:t==null?void 0:t.captchaToken}},xform:ee}),{data:l,error:c}=o;return c?{data:{user:null,session:null},error:c}:!l||!l.session||!l.user?{data:{user:null,session:null},error:new Ve}:(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),{data:l,error:c})}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,i,n,a;try{if("email"in e){const{email:o,options:l}=e;let c=null,u=null;this.flowType==="pkce"&&([c,u]=await Ye(this.storage,this.storageKey));const{error:d}=await k(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:o,data:(t=l==null?void 0:l.data)!==null&&t!==void 0?t:{},create_user:(s=l==null?void 0:l.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},code_challenge:c,code_challenge_method:u},redirectTo:l==null?void 0:l.emailRedirectTo});return{data:{user:null,session:null},error:d}}if("phone"in e){const{phone:o,options:l}=e,{data:c,error:u}=await k(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:o,data:(i=l==null?void 0:l.data)!==null&&i!==void 0?i:{},create_user:(n=l==null?void 0:l.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},channel:(a=l==null?void 0:l.channel)!==null&&a!==void 0?a:"sms"}});return{data:{user:null,session:null,messageId:c==null?void 0:c.message_id},error:u}}throw new qt("You must provide either an email or phone number.")}catch(o){if(E(o))return{data:{user:null,session:null},error:o};throw o}}async verifyOtp(e){var t,s;try{let i,n;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(s=e.options)===null||s===void 0?void 0:s.captchaToken);const{data:a,error:o}=await k(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:ee});if(o)throw o;if(!a)throw new Error("An error occurred on token verification.");const l=a.session,c=a.user;return l!=null&&l.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(i){if(E(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,s,i;try{let n=null,a=null;return this.flowType==="pkce"&&([n,a]=await Ye(this.storage,this.storageKey)),await k(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:(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&s!==void 0?s:void 0}),!((i=e==null?void 0:e.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:a}),headers:this.headers,xform:Ga})}catch(n){if(E(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new ge;const{error:i}=await k(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(E(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{const t=`${this.url}/resend`;if("email"in e){const{email:s,type:i,options:n}=e,{error:a}=await k(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:i,gotrue_meta_security:{captcha_token:n==null?void 0:n.captchaToken}},redirectTo:n==null?void 0:n.emailRedirectTo});return{data:{user:null,session:null},error:a}}else if("phone"in e){const{phone:s,type:i,options:n}=e,{data:a,error:o}=await k(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:n==null?void 0:n.captchaToken}}});return{data:{user:null,session:null,messageId:a==null?void 0:a.message_id},error:o}}throw new qt("You must provide either an email or phone number and a type")}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await s,await t()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const s=t();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){const i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.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{const t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const t=await je(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not val
40id"),await this._removeSession())),!e)return{data:{session:null},error:null};const s=e.expires_at?e.expires_at*1e3-Date.now()<ns:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const a=await je(this.userStorage,this.storageKey+"-user");a!=null&&a.user?e.user=a.user:e.user=ls()}if(this.storage.isServer&&e.user){let a=this.suppressGetSessionWarning;e=new Proxy(e,{get:(l,c,u)=>(!a&&c==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),a=!0,this.suppressGetSessionWarning=!0),Reflect.get(l,c,u))})}return{data:{session:e},error:null}}const{data:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await k(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ye}):await this._useSession(async t=>{var s,i,n;const{data:a,error:o}=t;if(o)throw o;return!(!((s=a.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new ge}:await k(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(i=a.session)===null||i===void 0?void 0:i.access_token)!==null&&n!==void 0?n:void 0,xform:ye})})}catch(t){if(E(t))return ba(t)&&(await this._removeSession(),await fe(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{const{data:i,error:n}=s;if(n)throw n;if(!i.session)throw new ge;const a=i.session;let o=null,l=null;this.flowType==="pkce"&&e.email!=null&&([o,l]=await Ye(this.storage,this.storageKey));const{data:c,error:u}=await k(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t==null?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:l}),jwt:a.access_token,xform:ye});if(u)throw u;return a.user=c.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),{data:{user:a.user},error:null}})}catch(s){if(E(s))return{data:{user:null},error:s};throw s}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new ge;const t=Date.now()/1e3;let s=t,i=!0,n=null;const{payload:a}=os(e.access_token);if(a.exp&&(s=a.exp,i=s<=t),i){const{data:o,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return{data:{user:null,session:null},error:l};if(!o)return{data:{user:null,session:null},error:null};n=o}else{const{data:o,error:l}=await this._getUser(e.access_token);if(l)throw l;n={access_token:e.access_token,refresh_token:e.refresh_token,user:o.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(E(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var s;if(!e){const{data:a,error:o}=t;if(o)throw o;e=(s=a.session)!==null&&s!==void 0?s:void 0}if(!(e!=null&&e.refresh_token))throw new ge;const{data:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e,t){try{if(!V())throw new Mt("No browser detected.");
40if(e.error||e.error_description||e.error_code)throw new Mt(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new ar("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Mt("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new ar("No code detected.");const{data:b,error:v}=await this._exchangeCodeForSession(e.code);if(v)throw v;const O=new URL(window.location.href);return O.searchParams.delete("code"),window.history.replaceState(window.history.state,"",O.toString()),{data:{session:b.session,redirectType:null},error:null}}const{provider_token:s,provider_refresh_token:i,access_token:n,refresh_token:a,expires_in:o,expires_at:l,token_type:c}=e;if(!n||!o||!a||!c)throw new Mt("No session defined in URL");const u=Math.round(Date.now()/1e3),d=parseInt(o);let f=u+d;l&&(f=parseInt(l));const p=f-u;p*1e3<=tt&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${d}s`);const w=f-d;u-w>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",w,f,u):u-w<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",w,f,u);const{data:y,error:g}=await this._getUser(n);if(g)throw g;const m={provider_token:s,provider_refresh_token:i,access_token:n,expires_in:d,expires_at:f,refresh_token:a,token_type:c,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:m,redirectType:e.type},error:null}}catch(s){if(E(s))return{data:{session:null,redirectType:null},error:s};throw s}}_isImplicitGrantCallback(e){return!!(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await je(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var s;const{data:i,error:n}=t;if(n)return{error:n};const a=(s=i.session)===null||s===void 0?void 0:s.access_token;if(a){const{error:o}=await this.admin.signOut(a,e);if(o&&!(_a(o)&&(o.status===404||o.status===401||o.status===403)))return{error:o}}return e!=="others"&&(await this._removeSession(),await fe(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){const t=Aa(),s={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,s),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,i;try{const{data:{session:n},error:a}=t;if(a)throw a;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let s=null,i=null;this.flowType==="pkce"&&([s,i]=await Ye(this.storage,this.storageKey,!0));try{return await k(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(E(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{const{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(E(t))return{data:null,error:t};throw t}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{const{data:s,error:i}=await this._useSession(async n=>{var a,o,l,c,u;const{data:d,error:f}=n;if(f)throw f;const p=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(a=e.options)===null||a===void 0?void 0:a.redirectTo,scopes:(o=e.options)===null||o===void 0?void 0:o.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await k(this.fetch,"GET",p,{headers:this.headers,jwt:(u=(c=d.session)===null||c===void 0?void 0:c.access_token)!==null&&u!==void 0?u:void 0})});if(i)throw i;return V()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s==null?void 0:s.url),{data:{provider:e.provider,url:s==null?void 0:s.url},error:null}}catch(s){if(E(s))return{data:{provider:e.provider,url:null},error:s};throw s}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var s;try{const{error:i,data:{session:n}}=t;if(i)throw i;const{options:a,provider:o,token:l,access_token:c,nonce:u}=e,d=await k(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=n==null?void 0:n.access_token)!==null&&s!==void 0?s:void 0,body:{provider:o,id_token:l,access_token:c,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:ee}),{data:f,error:p}=d;return p?{data:{user:null,session:null},error:p}:!f||!f.session||!f.user?{data:{user:null,session:null},error:new Ve}:(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("USER_UPDATED",f.session)),{data:f,error:p})}catch(i){if(E(i))return{data:{user:null,session:null},error:i};throw i}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,i;const{data:n,error:a}=t;if(a)throw a;
40return await k(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(s=n.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0})})}catch(t){if(E(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const s=Date.now();return await Ia(async i=>(i>0&&await ja(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await k(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:ee})),(i,n)=>{const a=200*Math.pow(2,i);return n&&as(n)&&Date.now()+a-s<tt})}catch(s){if(this._debug(t,"error",s),E(s))return{data:{session:null,user:null},error:s};throw s}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",s),V()&&!t.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e,t;const s="#_recoverAndRefresh()";this._debug(s,"begin");try{const i=await je(this.storage,this.storageKey);if(i&&this.userStorage){let a=await je(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!a&&(a={user:i.user},await st(this.userStorage,this.storageKey+"-user",a)),i.user=(e=a==null?void 0:a.user)!==null&&e!==void 0?e:ls()}else if(i&&!i.user&&!i.user){const a=await je(this.storage,this.storageKey+"-user");a&&(a!=null&&a.user)?(i.user=a.user,await fe(this.storage,this.storageKey+"-user"),await st(this.storage,this.storageKey,i)):i.user=ls()}if(this._debug(s,"session from storage",i),!this._isValidSession(i)){this._debug(s,"session is not valid"),i!==null&&await this._removeSession();return}const n=((t=i.expires_at)!==null&&t!==void 0?t:1/0)*1e3-Date.now()<ns;if(this._debug(s,`session has${n?"":" not"} expired with margin of ${ns}s`),n){if(this.autoRefreshToken&&i.refresh_token){const{error:a}=await this._callRefreshToken(i.refresh_token);a&&(console.error(a),as(a)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",a),await this._removeSession()))}}else if(i.user&&i.user.__isUserNotAvailableProxy===!0)try{const{data:a,error:o}=await this._getUser(i.access_token);!o&&(a!=null&&a.user)?(i.user=a.user,await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(a){console.error("Error getting user data:",a),this._debug(s,"error getting user data, skipping SIGNED_IN notification",a)}else await this._notifyAllSubscribers("SIGNED_IN",i)}catch(i){this._debug(s,"error",i),console.error(i);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var t,s;if(!e)throw new ge;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new Zt;const{data:n,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!n.session)throw new ge;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);const o={data:n.session,error:null};return this.refreshingDeferred.resolve(o),o}catch(n){if(this._debug(i,"error",n),E(n)){const a={data:null,error:n};return as(n)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(a),a}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(n),n}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,t,s=!0){const i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});const n=[],a=Array.from(this.stateChangeEmitters.values()).map(async o=>{try{await o.callback(e,t)}catch(l){n.push(l)}});if(await Promise.all(a),n.length>0){for(let o=0;o<n.length;o+=1)console.error(n[o]);throw n[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0;const t=Object.assign({},e),s=t.user&&t.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&t.user&&await st(this.userStorage,this.storageKey+"-user",{user:t.user});const i=Object.assign({},t);delete i.user;const n=hr(i);await st(this.storage,this.storageKey,n)}else{const i=hr(t);await st(this.storage,this.storageKey,i)}}async _removeSession(){this._debug("#_removeSession()"),await fe(this.storage,this.storageKey),await fe(this.storage,this.storageKey+"-code-verifier"),await fe(this.storage,this.storageKey+"-user"),this.userStorage&&await fe(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&V()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}
40catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),tt);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async t=>{const{data:{session:s}}=t;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const i=Math.floor((s.expires_at*1e3-e)/tt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${tt}ms, refresh threshold is ${Ps} ticks`),i<=Ps&&await this._callRefreshToken(s.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof ui)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!V()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,s){const i=[`provider=${encodeURIComponent(t)}`];if(s!=null&&s.redirectTo&&i.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s!=null&&s.scopes&&i.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){const[n,a]=await Ye(this.storage,this.storageKey),o=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(a)}`});i.push(o.toString())}if(s!=null&&s.queryParams){const n=new URLSearchParams(s.queryParams);i.push(n.toString())}return s!=null&&s.skipBrowserRedirect&&i.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;const{data:i,error:n}=t;return n?{data:null,error:n}:await k(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(E(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,i;const{data:n,error:a}=t;if(a)return{data:null,error:a};const o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:c}=await k(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token});return c?{data:null,error:c}:(e.factorType==="totp"&&l.type==="totp"&&(!((i=l==null?void 0:l.totp)===null||i===void 0)&&i.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),{data:l,error:null})})}catch(t){if(E(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;const{data:i,error:n}=t;if(n)return{data:null,error:n};const a=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?uo(e.webauthn.credential_response):co(e.webauthn.credential_response)})}:{code:e.code}),{data:o,error:l}=await k(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:a,headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token});return l?{data:null,error:l}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:l})})}catch(t){if(E(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;const{data:i,error:n}=t;if(n)return{data:null,error:n};const a=await k(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token});if(a.error)return a;const{data:o}=a;if(o.type!=="webauthn")return{data:o,error:null};switch(o.webauthn.type){case"create":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:oo(o.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:lo(o.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(t){if(E(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){const{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;const{data:{user:t},error:s}=await this.getUser();if(s)return{data:null,error:s};const i={all:[],phone:[],totp:[],webauthn:[]};for(const n of(e=t==null?void 0:t.factors)!==null&&e!==void 0?e:[])i.all.push(n),n.status==="verified"&&i[n.factor_type].push(n);return{data:i,error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;const{data:{session:i},error:n}=e;if(n)return{data:null,error:n};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:a}=os(i.access_token);let o=null;a.aal&&(o=a.aal);let l=o;((s=(t=i.user.factors)===null||t===void 0?void 0:t.filter(d=>d.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(l="aal2");const u=a.amr||[];return{data:{currentLevel:o,nextLevel:l,currentAuthenticationMethods:u},error:null}}))}async fetchJwk(e,t={keys:[]}){let s=t.keys.find(o=>o.kid===e);if(s)return s;const i=Date.now();if(s=this.jwks.keys.find(o=>o.kid===e),s&&this.jwks_cached_at+va>i)return s;const{data:n,error:a}=await k(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return!n.keys||n.keys.length===0||(this.jwks=n,this.jwks_cached_at=i,s=n.keys.find(o=>o.kid===e),!s)?null:s}async getClaims(e,t={}){try{let s=e;if(!s){const{data:p,error:w}
40=await this.getSession();if(w||!p.session)return{data:null,error:w};s=p.session.access_token}const{header:i,payload:n,signature:a,raw:{header:o,payload:l}}=os(s);t!=null&&t.allowExpired||Fa(n.exp);const c=!i.alg||i.alg.startsWith("HS")||!i.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(i.kid,t!=null&&t.keys?{keys:t.keys}:t==null?void 0:t.jwks);if(!c){const{error:p}=await this.getUser(s);if(p)throw p;return{data:{claims:n,header:i,signature:a},error:null}}const u=qa(i.alg),d=await crypto.subtle.importKey("jwk",c,u,!0,["verify"]);if(!await crypto.subtle.verify(u,d,a,Ta(`${o}.${l}`)))throw new $s("Invalid JWT signature");return{data:{claims:n,header:i,signature:a},error:null}}catch(s){if(E(s))return{data:null,error:s};throw s}}}At.nextInstanceID=0;const bo=At;class mo extends bo{constructor(e){super(e)}}var So=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(a){a(n)})}return new(t||(t=Promise))(function(n,a){function o(u){try{c(s.next(u))}catch(d){a(d)}}function l(u){try{c(s.throw(u))}catch(d){a(d)}}function c(u){u.done?n(u.value):i(u.value).then(o,l)}c((s=s.apply(r,e||[])).next())})};class Eo{constructor(e,t,s){var i,n,a;this.supabaseUrl=e,this.supabaseKey=t;const o=da(e);if(!t)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",o),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",o),this.storageUrl=new URL("storage/v1",o),this.functionsUrl=new URL("functions/v1",o);const l=`sb-${o.hostname.split(".")[0]}-auth-token`,c={db:sa,realtime:ia,auth:Object.assign(Object.assign({},ra),{storageKey:l}),global:ta},u=ha(s??{},c);this.storageKey=(i=u.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=u.global.headers)!==null&&n!==void 0?n:{},u.accessToken?(this.accessToken=u.accessToken,this.auth=new Proxy({},{get:(d,f)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(f)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((a=u.auth)!==null&&a!==void 0?a:{},this.headers,u.global.fetch),this.fetch=la(t,this._getAccessToken.bind(this),u.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},u.realtime)),this.rest=new wn(new URL("rest/v1",o).href,{headers:this.headers,schema:u.db.schema,fetch:this.fetch}),this.storage=new Xn(this.storageUrl.href,this.headers,this.fetch,s==null?void 0:s.storage),u.accessToken||this._listenForAuthEvents()}get functions(){return new zi(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},s={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,s)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){return So(this,void 0,void 0,function*(){var e,t;if(this.accessToken)return yield this.accessToken();const{data:s}=yield this.auth.getSession();return(t=(e=s.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:this.supabaseKey})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:i,userStorage:n,storageKey:a,flowType:o,lock:l,debug:c},u,d){const f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new mo({url:this.authUrl.href,headers:Object.assign(Object.assign({},f),u),storageKey:a,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:i,userStorage:n,flowType:o,lock:l,debug:c,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(p=>p.toLowerCase()==="authorization")})}_initRealtimeClient(e){return new Un(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,s)=>{this._handleTokenChanged(t,"CLIENT",s==null?void 0:s.access_token)})}_handleTokenChanged(e,t,s){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==s?(this.changedAccessToken=s,this.realtime.setAuth(s)):e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const Bo=(r,e,t)=>new Eo(r,e,t);function Oo(){if(typeof window<"u"||typeof process>"u")return!1;const r=process.version;if(r==null)return!1;const e=r.match(/^v(\d+)\./);return e?parseInt(e[1],10)<=18:!1}Oo()&&console.warn("â ï¸ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to N
40ode.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");export{Ao as Q,$t as _,qr as a,Co as b,Bo as c,jo as d,Po as u};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.