var Hs=r=>{throw TypeError(r)};var ts=(r,e,t)=>e.has(r)||Hs("Cannot "+t);var h=(r,e,t)=>(ts(r,e,"read from private field"),t?t.call(r):e.get(r)),S=(r,e,t)=>e.has(r)?Hs("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),b=(r,e,t,s)=>(ts(r,e,"write to private field"),s?s.call(r,t):e.set(r,t),t),R=(r,e,t)=>(ts(r,e,"access private method"),t);var Lt=(r,e,t,s)=>({set _(i){b(r,e,i,t)},get _(){return h(r,e,s)}});import{r as q,g as wi,d as Z}from"./vendor-react-ItNohvPm.js";import{j as _i}from"./vendor-radix-core-Nj5xHoxM.js";const bi=function(){const e=typeof document<"u"&&document.createElement("link").relList;return e&&e.supports&&e.supports("modulepreload")?"modulepreload":"preload"}(),mi=function(r){return"/"+r},Qs={},$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(u=>{if(u=mi(u),u in Qs)return;Qs[u]=!0;const c=u.endsWith(".css"),l=c?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${l}`))return;const d=document.createElement("link");if(d.rel=c?"stylesheet":bi,c||(d.as="script"),d.crossOrigin="",d.href=u,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 ${u}`)))})}))}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 B(){}function Si(r,e){return typeof r=="function"?r(e):r}function hs(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 Gs(r,e){const{type:t="all",exact:s,fetchStatus:i,predicate:n,queryKey:a,stale:o}=r;if(a){if(s){if(e.queryHash!==Ds(a,e.options))return!1}else if(!Tt(e.queryKey,a))return!1}if(t!=="all"){const u=e.isActive();if(t==="active"&&!u||t==="inactive"&&u)return!1}return!(typeof o=="boolean"&&e.isStale()!==o||i&&i!==e.state.fetchStatus||n&&!n(e))}function zs(r,e){const{exact:t,status:s,predicate:i,mutationKey:n}=r;if(n){if(!e.options.mutationKey)return!1;if(t){if(Qe(e.options.mutationKey)!==Qe(n))return!1}else if(!Tt(e.options.mutationKey,n))return!1}return!(s&&e.state.status!==s||i&&!i(e))}function Ds(r,e){return((e==null?void 0:e.queryKeyHashFn)||Qe)(r)}function Qe(r){return JSON.stringify(r,(e,t)=>ds(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=Js(r)&&Js(e);if(t||ds(r)&&ds(e)){const s=t?r:Object.keys(r),i=s.length,n=t?e:Object.keys(e),a=n.length,o=t?[]:{},u=new Set(s);let c=0;for(let l=0;l{setTimeout(e,r)})}function fs(r,e,t){return typeof t.structuralSharing=="function"?t.structuralSharing(r,e):t.structuralSharing!==!1?Cr(r,e):e}function Fo(r){return r}function Oi(r,e,t=0){const s=[...r,e];return t&&s.length>t?s.slice(1):s}function ki(r,e,t=0){const s=[e,...r];return t&&s.length>t?s.slice(0,-1):s}var Ls=Symbol();function jr(r,e){return!r.queryFn&&(e!=null&&e.initialPromise)?()=>e.initialPromise:!r.queryFn||r.queryFn===Ls?()=>Promise.reject(new Error(`Missing queryFn: '${r.queryHash}'`)):r.queryFn}function Ir(r,e){return typeof r=="function"?r(...e):!!r}var De,ve,it,_r,Ti=(_r=class extends vt{constructor(){super();S(this,De);S(this,ve);S(this,it);b(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),b(this,ve,void 0))}setEventListener(e){var t;b(this,it,e),(t=h(this,ve))==null||t.call(this),b(this,ve,e(s=>{typeof s=="boolean"?this.setFocused(s):this.onFocus()}))}setFocused(e){h(this,De)!==e&&(b(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,_r),Ns=new Ti,nt,we,at,br,Ri=(br=class extends vt{constructor(){super();S(this,nt,!0);S(this,we);S(this,at);b(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),b(this,we,void 0))}setEventListener(e){var t;b(this,at,e),(t=h(this,we))==null||t.call(this),b(this,we,e(this.setOnline.bind(this)))}setOnline(e){h(this,nt)!==e&&(b(this,nt,e),this.listeners.forEach(s=>{s(e)}))}isOnline(){return h(this,nt)}},nt=new WeakMap,we=new WeakMap,at=new WeakMap,br),Wt=new Ri;function ps(){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 Pi(r){var t;let e;if((t=r.then(s=>(e=s,s),B))==null||t.catch(B),e!==void 0)return{data:e}}function Ai(r){return Math.min(1e3*2**r,3e4)}function $r(r){return(r??"online")==="online"?Wt.isOnline():!0}var xr=class extends Error{constructor(r){super("CancelledError"),this.revert=r==null?void 0:r.revert,this.silent=r==null?void 0:r.silent}};function ss(r){return r instanceof xr}function Ur(r){let e=!1,t=0,s=!1,i;const n=ps(),a=y=>{var g;s||(f(new xr(y)),(g=r.abort)==null||g.call(r))},o=()=>{e=!0},u=()=>{e=!1},c=()=>Ns.isFocused()&&(r.networkMode==="always"||Wt.isOnline())&&r.canRun(),l=()=>$r(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 T;if(s)return;const _=r.retry??(He?0:3),v=r.retryDelay??Ai,O=typeof v=="function"?v(t,m):v,C=_===!0||typeof _=="number"&&t<_||typeof _=="function"&&_(t,m);if(e||!C){f(m);return}t++,(T=r.onFail)==null||T.call(r,t,m),Ei(O).then(()=>c()?void 0:p()).then(()=>{e?f(m):w()})})};return{promise:n,cancel:a,continue:()=>(i==null||i(),n),cancelRetry:o,continueRetry:u,canStart:l,start:()=>(l()?w():p().then(w),n)}}var Ci=r=>setTimeout(r,0);function ji(){let r=[],e=0,t=o=>{o()},s=o=>{o()},i=Ci;const n=o=>{e?r.push(o):i(()=>{t(o)})},a=()=>{const o=r;r=[],o.length&&i(()=>{s(()=>{o.forEach(u=>{t(u)})})})};return{batch:o=>{let u;e++;try{u=o()}finally{e--,e||a()}return u},batchCalls:o=>(...u)=>{n(()=>{o(...u)})},schedule:n,setNotifyFunction:o=>{t=o},setBatchNotifyFunction:o=>{s=o},setScheduler:o=>{i=o}}}var F=ji(),Le,mr,Dr=(mr=class{constructor(){S(this,Le)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),hs(this.gcTime)&&b(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)),b(this,Le,void 0))}},Le=new WeakMap,mr),ot,Ne,Y,Fe,K,At,Me,te,ue,Sr,Ii=(Sr=class extends Dr{constructor(e){super();S(this,te);S(this,ot);S(this,Ne);S(this,Y);S(this,Fe);S(this,K);S(this,At);S(this,Me);b(this,Me,!1),b(this,At,e.defaultOptions),this.setOptions(e.options),this.observers=[],b(this,Fe,e.client),b(this,Y,h(this,Fe).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,b(this,ot,$i(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,K))==null?void 0:e.promise}setOptions(e){this.options={...h(this,At),...e},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&h(this,Y).remove(this)}setData(e,t){const s=fs(this.state.data,e,this.options);return R(this,te,ue).call(this,{data:s,type:"success",dataUpdatedAt:t==null?void 0:t.updatedAt,manual:t==null?void 0:t.manual}),s}setState(e,t){R(this,te,ue).call(this,{type:"setState",state:e,setStateOptions:t})}cancel(e){var s,i;const t=(s=h(this,K))==null?void 0:s.promise;return(i=h(this,K))==null||i.cancel(e),t?t.then(B).catch(B):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===Ls||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,K))==null||t.continue()}onOnline(){var t;const e=this.observers.find(s=>s.shouldFetchOnReconnect());e==null||e.refetch({cancelRefetch:!1}),(t=h(this,K))==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,K)&&(h(this,Me)?h(this,K).cancel({revert:!0}):h(this,K).cancelRetry()),this.scheduleGc()),h(this,Y).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||R(this,te,ue).call(this,{type:"invalidate"})}fetch(e,t){var c,l,d;if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&(t!=null&&t.cancelRefetch))this.cancel({silent:!0});else if(h(this,K))return h(this,K).continueRetry(),h(this,K).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:()=>(b(this,Me,!0),s.signal)})},n=()=>{const f=jr(this.options,t),w=(()=>{const y={client:h(this,Fe),queryKey:this.queryKey,meta:this.meta};return i(y),y})();return b(this,Me,!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),b(this,Ne,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((l=o.fetchOptions)==null?void 0:l.meta))&&R(this,te,ue).call(this,{type:"fetch",meta:(d=o.fetchOptions)==null?void 0:d.meta});const u=f=>{var p,w,y,g;ss(f)&&f.silent||R(this,te,ue).call(this,{type:"error",error:f}),ss(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 b(this,K,Ur({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){u(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(f)}catch(m){u(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:u,onFail:(f,p)=>{R(this,te,ue).call(this,{type:"failed",failureCount:f,error:p})},onPause:()=>{R(this,te,ue).call(this,{type:"pause"})},onContinue:()=>{R(this,te,ue).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0})),h(this,K).start()}},ot=new WeakMap,Ne=new WeakMap,Y=new WeakMap,Fe=new WeakMap,K=new WeakMap,At=new WeakMap,Me=new WeakMap,te=new WeakSet,ue=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,...Lr(s.data,this.options),fetchMeta:e.meta??null};case"success":return b(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 ss(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),F.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),h(this,Y).notify({query:this,type:"updated",action:e})})},Sr);function Lr(r,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:$r(e.networkMode)?"fetching":"paused",...r===void 0&&{error:null,status:"pending"}}}function $i(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,Er,xi=(Er=class extends vt{constructor(e={}){super();S(this,ne);this.config=e,b(this,ne,new Map)}build(e,t,s){const i=t.queryKey,n=t.queryHash??Ds(i,t);let a=this.get(n);return a||(a=new Ii({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(){F.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=>Gs(t,s))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(s=>Gs(e,s)):t}notify(e){F.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){F.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){F.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},ne=new WeakMap,Er),ae,W,qe,oe,pe,Or,Ui=(Or=class extends Dr{constructor(e){super();S(this,oe);S(this,ae);S(this,W);S(this,qe);this.mutationId=e.mutationId,b(this,W,e.mutationCache),b(this,ae,[]),this.state=e.state||Nr(),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,W).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){b(this,ae,h(this,ae).filter(t=>t!==e)),this.scheduleGc(),h(this,W).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){h(this,ae).length||(this.state.status==="pending"?this.scheduleGc():h(this,W).remove(this))}continue(){var e;return((e=h(this,qe))==null?void 0:e.continue())??this.execute(this.state.variables)}async execute(e){var n,a,o,u,c,l,d,f,p,w,y,g,m,_,v,O,C,T,I,$;const t=()=>{R(this,oe,pe).call(this,{type:"continue"})};b(this,qe,Ur({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(A,U)=>{R(this,oe,pe).call(this,{type:"failed",failureCount:A,error:U})},onPause:()=>{R(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,W).canRun(this)}));const s=this.state.status==="pending",i=!h(this,qe).canStart();try{if(s)t();else{R(this,oe,pe).call(this,{type:"pending",variables:e,isPaused:i}),await((a=(n=h(this,W).config).onMutate)==null?void 0:a.call(n,e,this));const U=await((u=(o=this.options).onMutate)==null?void 0:u.call(o,e));U!==this.state.context&&R(this,oe,pe).call(this,{type:"pending",context:U,variables:e,isPaused:i})}const A=await h(this,qe).start();return await((l=(c=h(this,W).config).onSuccess)==null?void 0:l.call(c,A,e,this.state.context,this)),await((f=(d=this.options).onSuccess)==null?void 0:f.call(d,A,e,this.state.context)),await((w=(p=h(this,W).config).onSettled)==null?void 0:w.call(p,A,null,this.state.variables,this.state.context,this)),await((g=(y=this.options).onSettled)==null?void 0:g.call(y,A,null,e,this.state.context)),R(this,oe,pe).call(this,{type:"success",data:A}),A}catch(A){try{throw await((_=(m=h(this,W).config).onError)==null?void 0:_.call(m,A,e,this.state.context,this)),await((O=(v=this.options).onError)==null?void 0:O.call(v,A,e,this.state.context)),await((T=(C=h(this,W).config).onSettled)==null?void 0:T.call(C,void 0,A,this.state.variables,this.state.context,this)),await(($=(I=this.options).onSettled)==null?void 0:$.call(I,void 0,A,e,this.state.context)),A}finally{R(this,oe,pe).call(this,{type:"error",error:A})}}finally{h(this,W).runNext(this)}}},ae=new WeakMap,W=new WeakMap,qe=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),F.batch(()=>{h(this,ae).forEach(s=>{s.onMutationUpdate(e)}),h(this,W).notify({mutation:this,type:"updated",action:e})})},Or);function Nr(){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,Ct,kr,Di=(kr=class extends vt{constructor(e={}){super();S(this,ce);S(this,se);S(this,Ct);this.config=e,b(this,ce,new Set),b(this,se,new Map),b(this,Ct,0)}build(e,t,s){const i=new Ui({mutationCache:this,mutationId:++Lt(this,Ct)._,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(){F.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=>zs(t,s))}findAll(e={}){return this.getAll().filter(t=>zs(e,t))}notify(e){F.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return F.batch(()=>Promise.all(e.map(t=>t.continue().catch(B))))}},ce=new WeakMap,se=new WeakMap,Ct=new WeakMap,kr);function Nt(r){var e;return(e=r.options.scope)==null?void 0:e.id}function Ht(r){return{onFetch:(e,t)=>{var l,d,f,p,w;const s=e.options,i=(f=(d=(l=e.fetchOptions)==null?void 0:l.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:[]},u=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=jr(e.options,e.fetchOptions),_=async(v,O,C)=>{if(y)return Promise.reject();if(O==null&&v.pages.length)return Promise.resolve(v);const I=(()=>{const Ae={client:e.client,queryKey:e.queryKey,pageParam:O,direction:C?"backward":"forward",meta:e.options.meta};return g(Ae),Ae})(),$=await m(I),{maxPages:A}=e.options,U=C?ki:Oi;return{pages:U(v.pages,$,A),pageParams:U(v.pageParams,O,A)}};if(i&&n.length){const v=i==="backward",O=v?Fr:gs,C={pages:n,pageParams:a},T=O(s,C);o=await _(C,T,v)}else{const v=r??n.length;do{const O=u===0?a[0]??s.initialPageParam:gs(s,o);if(u>0&&O==null)break;o=await _(o,O),u++}while(u{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 gs(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 Fr(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}function Li(r,e){return e?gs(r,e)!=null:!1}function Ni(r,e){return!e||!r.getPreviousPageParam?!1:Fr(r,e)!=null}var D,_e,be,ut,lt,me,ct,ht,Tr,Mo=(Tr=class{constructor(r={}){S(this,D);S(this,_e);S(this,be);S(this,ut);S(this,lt);S(this,me);S(this,ct);S(this,ht);b(this,D,r.queryCache||new xi),b(this,_e,r.mutationCache||new Di),b(this,be,r.defaultOptions||{}),b(this,ut,new Map),b(this,lt,new Map),b(this,me,0)}mount(){Lt(this,me)._++,h(this,me)===1&&(b(this,ct,Ns.subscribe(async r=>{r&&(await this.resumePausedMutations(),h(this,D).onFocus())})),b(this,ht,Wt.subscribe(async r=>{r&&(await this.resumePausedMutations(),h(this,D).onOnline())})))}unmount(){var r,e;Lt(this,me)._--,h(this,me)===0&&((r=h(this,ct))==null||r.call(this),b(this,ct,void 0),(e=h(this,ht))==null||e.call(this),b(this,ht,void 0))}isFetching(r){return h(this,D).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,D).get(e.queryHash))==null?void 0:t.state.data}ensureQueryData(r){const e=this.defaultQueryOptions(r),t=h(this,D).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,D).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,D).get(s.queryHash),n=i==null?void 0:i.state.data,a=Si(e,n);if(a!==void 0)return h(this,D).build(this,s).setData(a,{...t,manual:!0})}setQueriesData(r,e,t){return F.batch(()=>h(this,D).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,D).get(e.queryHash))==null?void 0:t.state}removeQueries(r){const e=h(this,D);F.batch(()=>{e.findAll(r).forEach(t=>{e.remove(t)})})}resetQueries(r,e){const t=h(this,D);return F.batch(()=>(t.findAll(r).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...r},e)))}cancelQueries(r,e={}){const t={revert:!0,...e},s=F.batch(()=>h(this,D).findAll(r).map(i=>i.cancel(t)));return Promise.all(s).then(B).catch(B)}invalidateQueries(r,e={}){return F.batch(()=>(h(this,D).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=F.batch(()=>h(this,D).findAll(r).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let n=i.fetch(void 0,t);return t.throwOnError||(n=n.catch(B)),i.state.fetchStatus==="paused"?Promise.resolve():n}));return Promise.all(s).then(B)}fetchQuery(r){const e=this.defaultQueryOptions(r);e.retry===void 0&&(e.retry=!1);const t=h(this,D).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(B).catch(B)}fetchInfiniteQuery(r){return r.behavior=Ht(r.pages),this.fetchQuery(r)}prefetchInfiniteQuery(r){return this.fetchInfiniteQuery(r).then(B).catch(B)}ensureInfiniteQueryData(r){return r.behavior=Ht(r.pages),this.ensureQueryData(r)}resumePausedMutations(){return Wt.isOnline()?h(this,_e).resumePausedMutations():Promise.resolve()}getQueryCache(){return h(this,D)}getMutationCache(){return h(this,_e)}getDefaultOptions(){return h(this,be)}setDefaultOptions(r){b(this,be,r)}setQueryDefaults(r,e){h(this,ut).set(Qe(r),{queryKey:r,defaultOptions:e})}getQueryDefaults(r){const e=[...h(this,ut).values()],t={};return e.forEach(s=>{Tt(r,s.queryKey)&&Object.assign(t,s.defaultOptions)}),t}setMutationDefaults(r,e){h(this,lt).set(Qe(r),{mutationKey:r,defaultOptions:e})}getMutationDefaults(r){const e=[...h(this,lt).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=Ds(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===Ls&&(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,D).clear(),h(this,_e).clear()}},D=new WeakMap,_e=new WeakMap,be=new WeakMap,ut=new WeakMap,lt=new WeakMap,me=new WeakMap,ct=new WeakMap,ht=new WeakMap,Tr),G,P,jt,H,Be,dt,Se,Ee,It,ft,pt,Ke,We,Oe,gt,j,mt,ys,vs,ws,_s,bs,ms,Ss,qr,Rr,Mr=(Rr=class extends vt{constructor(e,t){super();S(this,j);S(this,G);S(this,P);S(this,jt);S(this,H);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,b(this,G,e),b(this,Ee,null),b(this,Se,ps()),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,P).addObserver(this),Ys(h(this,P),this.options)?R(this,j,mt).call(this):this.updateResult(),R(this,j,_s).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Es(h(this,P),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Es(h(this,P),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,R(this,j,bs).call(this),R(this,j,ms).call(this),h(this,P).removeObserver(this)}setOptions(e){const t=this.options,s=h(this,P);if(this.options=h(this,G).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof X(this.options.enabled,h(this,P))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");R(this,j,Ss).call(this),h(this,P).setOptions(this.options),t._defaulted&&!Kt(this.options,t)&&h(this,G).getQueryCache().notify({type:"observerOptionsUpdated",query:h(this,P),observer:this});const i=this.hasListeners();i&&Xs(h(this,P),s,this.options,t)&&R(this,j,mt).call(this),this.updateResult(),i&&(h(this,P)!==s||X(this.options.enabled,h(this,P))!==X(t.enabled,h(this,P))||Re(this.options.staleTime,h(this,P))!==Re(t.staleTime,h(this,P)))&&R(this,j,ys).call(this);const n=R(this,j,vs).call(this);i&&(h(this,P)!==s||X(this.options.enabled,h(this,P))!==X(t.enabled,h(this,P))||n!==h(this,Oe))&&R(this,j,ws).call(this,n)}getOptimisticResult(e){const t=h(this,G).getQueryCache().build(h(this,G),e),s=this.createResult(t,e);return Mi(this,s)&&(b(this,H,s),b(this,dt,this.options),b(this,Be,h(this,P).state)),s}getCurrentResult(){return h(this,H)}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,P)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=h(this,G).defaultQueryOptions(e),s=h(this,G).getQueryCache().build(h(this,G),t);return s.fetch().then(()=>this.createResult(s,t))}fetch(e){return R(this,j,mt).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),h(this,H)))}createResult(e,t){var A;const s=h(this,P),i=this.options,n=h(this,H),a=h(this,Be),o=h(this,dt),c=e!==s?e.state:h(this,jt),{state:l}=e;let d={...l},f=!1,p;if(t._optimisticResults){const U=this.hasListeners(),Ae=!U&&Ys(e,t),ze=U&&Xs(e,s,t,i);(Ae||ze)&&(d={...d,...Lr(l.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 U;n!=null&&n.isPlaceholderData&&t.placeholderData===(o==null?void 0:o.placeholderData)?(U=n.data,m=!0):U=typeof t.placeholderData=="function"?t.placeholderData((A=h(this,pt))==null?void 0:A.state.data,h(this,pt)):t.placeholderData,U!==void 0&&(g="success",p=fs(n==null?void 0:n.data,U,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{b(this,It,t.select),p=t.select(p),p=fs(n==null?void 0:n.data,p,t),b(this,ft,p),b(this,Ee,null)}catch(U){b(this,Ee,U)}h(this,Ee)&&(w=h(this,Ee),p=h(this,ft),y=Date.now(),g="error");const _=d.fetchStatus==="fetching",v=g==="pending",O=g==="error",C=v&&_,T=p!==void 0,$={status:g,fetchStatus:d.fetchStatus,isPending:v,isSuccess:g==="success",isError:O,isInitialLoading:C,isLoading:C,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:_,isRefetching:_&&!v,isLoadingError:O&&!T,isPaused:d.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:O&&T,isStale:Fs(e,t),refetch:this.refetch,promise:h(this,Se),isEnabled:X(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const U=Dt=>{$.status==="error"?Dt.reject($.error):$.data!==void 0&&Dt.resolve($.data)},Ae=()=>{const Dt=b(this,Se,$.promise=ps());U(Dt)},ze=h(this,Se);switch(ze.status){case"pending":e.queryHash===s.queryHash&&U(ze);break;case"fulfilled":($.status==="error"||$.data!==ze.value)&&Ae();break;case"rejected":($.status!=="error"||$.error!==ze.reason)&&Ae();break}}return $}updateResult(){const e=h(this,H),t=this.createResult(h(this,P),this.options);if(b(this,Be,h(this,P).state),b(this,dt,this.options),h(this,Be).data!==void 0&&b(this,pt,h(this,P)),Kt(t,e))return;b(this,H,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,H)).some(o=>{const u=o;return h(this,H)[u]!==e[u]&&a.has(u)})};R(this,j,qr).call(this,{listeners:s()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&R(this,j,_s).call(this)}},G=new WeakMap,P=new WeakMap,jt=new WeakMap,H=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,j=new WeakSet,mt=function(e){R(this,j,Ss).call(this);let t=h(this,P).fetch(this.options,e);return e!=null&&e.throwOnError||(t=t.catch(B)),t},ys=function(){R(this,j,bs).call(this);const e=Re(this.options.staleTime,h(this,P));if(He||h(this,H).isStale||!hs(e))return;const s=Ar(h(this,H).dataUpdatedAt,e)+1;b(this,Ke,setTimeout(()=>{h(this,H).isStale||this.updateResult()},s))},vs=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(h(this,P)):this.options.refetchInterval)??!1},ws=function(e){R(this,j,ms).call(this),b(this,Oe,e),!(He||X(this.options.enabled,h(this,P))===!1||!hs(h(this,Oe))||h(this,Oe)===0)&&b(this,We,setInterval(()=>{(this.options.refetchIntervalInBackground||Ns.isFocused())&&R(this,j,mt).call(this)},h(this,Oe)))},_s=function(){R(this,j,ys).call(this),R(this,j,ws).call(this,R(this,j,vs).call(this))},bs=function(){h(this,Ke)&&(clearTimeout(h(this,Ke)),b(this,Ke,void 0))},ms=function(){h(this,We)&&(clearInterval(h(this,We)),b(this,We,void 0))},Ss=function(){const e=h(this,G).getQueryCache().build(h(this,G),this.options);if(e===h(this,P))return;const t=h(this,P);b(this,P,e),b(this,jt,e.state),this.hasListeners()&&(t==null||t.removeObserver(this),e.addObserver(this))},qr=function(e){F.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(h(this,H))}),h(this,G).getQueryCache().notify({query:h(this,P),type:"observerResultsUpdated"})})},Rr);function Fi(r,e){return X(e.enabled,r)!==!1&&r.state.data===void 0&&!(r.state.status==="error"&&e.retryOnMount===!1)}function Ys(r,e){return Fi(r,e)||r.state.data!==void 0&&Es(r,e,e.refetchOnMount)}function Es(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&&Fs(r,e)}return!1}function Xs(r,e,t,s){return(r!==e||X(s.enabled,r)===!1)&&(!t.suspense||r.state.status!=="error")&&Fs(r,t)}function Fs(r,e){return X(e.enabled,r)!==!1&&r.isStaleByTime(Re(e.staleTime,r))}function Mi(r,e){return!Kt(r.getCurrentResult(),e)}var qi=class extends Mr{constructor(r,e){super(r,e)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(r){super.setOptions({...r,behavior:Ht()})}getOptimisticResult(r){return r.behavior=Ht(),super.getOptimisticResult(r)}fetchNextPage(r){return this.fetch({...r,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(r){return this.fetch({...r,meta:{fetchMore:{direction:"backward"}}})}createResult(r,e){var w,y;const{state:t}=r,s=super.createResult(r,e),{isFetching:i,isRefetching:n,isError:a,isRefetchError:o}=s,u=(y=(w=t.fetchMeta)==null?void 0:w.fetchMore)==null?void 0:y.direction,c=a&&u==="forward",l=i&&u==="forward",d=a&&u==="backward",f=i&&u==="backward";return{...s,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Li(e,t.data),hasPreviousPage:Ni(e,t.data),isFetchNextPageError:c,isFetchingNextPage:l,isFetchPreviousPageError:d,isFetchingPreviousPage:f,isRefetchError:o&&!c&&!d,isRefetching:n&&!l&&!f}}},ke,Te,z,he,de,Bt,Os,Pr,Bi=(Pr=class extends vt{constructor(e,t){super();S(this,de);S(this,ke);S(this,Te);S(this,z);S(this,he);b(this,ke,e),this.setOptions(t),this.bindMethods(),R(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,z),observer:this}),t!=null&&t.mutationKey&&this.options.mutationKey&&Qe(t.mutationKey)!==Qe(this.options.mutationKey)?this.reset():((s=h(this,z))==null?void 0:s.state.status)==="pending"&&h(this,z).setOptions(this.options)}onUnsubscribe(){var e;this.hasListeners()||(e=h(this,z))==null||e.removeObserver(this)}onMutationUpdate(e){R(this,de,Bt).call(this),R(this,de,Os).call(this,e)}getCurrentResult(){return h(this,Te)}reset(){var e;(e=h(this,z))==null||e.removeObserver(this),b(this,z,void 0),R(this,de,Bt).call(this),R(this,de,Os).call(this)}mutate(e,t){var s;return b(this,he,t),(s=h(this,z))==null||s.removeObserver(this),b(this,z,h(this,ke).getMutationCache().build(h(this,ke),this.options)),h(this,z).addObserver(this),h(this,z).execute(e)}},ke=new WeakMap,Te=new WeakMap,z=new WeakMap,he=new WeakMap,de=new WeakSet,Bt=function(){var t;const e=((t=h(this,z))==null?void 0:t.state)??Nr();b(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})},Os=function(e){F.batch(()=>{var t,s,i,n,a,o,u,c;if(h(this,he)&&this.hasListeners()){const l=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,l,d),(n=(i=h(this,he)).onSettled)==null||n.call(i,e.data,null,l,d)):(e==null?void 0:e.type)==="error"&&((o=(a=h(this,he)).onError)==null||o.call(a,e.error,l,d),(c=(u=h(this,he)).onSettled)==null||c.call(u,void 0,e.error,l,d))}this.listeners.forEach(l=>{l(h(this,Te))})})},Pr);function Br(r){return r}function Ki(r){return{mutationKey:r.options.mutationKey,state:r.state,...r.options.scope&&{scope:r.options.scope},...r.meta&&{meta:r.meta}}}function Wi(r,e,t){var s;return{dehydratedAt:Date.now(),state:{...r.state,...r.state.data!==void 0&&{data:e(r.state.data)}},queryKey:r.queryKey,queryHash:r.queryHash,...r.state.status==="pending"&&{promise:(s=r.promise)==null?void 0:s.then(e).catch(i=>t(i)?Promise.reject(new Error("redacted")):Promise.reject(i))},...r.meta&&{meta:r.meta}}}function Hi(r){return r.state.isPaused}function Qi(r){return r.state.status==="success"}function Gi(r){return!0}function qo(r,e={}){var u,c,l,d;const t=e.shouldDehydrateMutation??((u=r.getDefaultOptions().dehydrate)==null?void 0:u.shouldDehydrateMutation)??Hi,s=r.getMutationCache().getAll().flatMap(f=>t(f)?[Ki(f)]:[]),i=e.shouldDehydrateQuery??((c=r.getDefaultOptions().dehydrate)==null?void 0:c.shouldDehydrateQuery)??Qi,n=e.shouldRedactErrors??((l=r.getDefaultOptions().dehydrate)==null?void 0:l.shouldRedactErrors)??Gi,a=e.serializeData??((d=r.getDefaultOptions().dehydrate)==null?void 0:d.serializeData)??Br,o=r.getQueryCache().getAll().flatMap(f=>i(f)?[Wi(f,a,n)]:[]);return{mutations:s,queries:o}}function Bo(r,e,t){var u,c;if(typeof e!="object"||e===null)return;const s=r.getMutationCache(),i=r.getQueryCache(),n=((u=t==null?void 0:t.defaultOptions)==null?void 0:u.deserializeData)??((c=r.getDefaultOptions().hydrate)==null?void 0:c.deserializeData)??Br,a=e.mutations||[],o=e.queries||[];a.forEach(({state:l,...d})=>{var f,p;s.build(r,{...(f=r.getDefaultOptions().hydrate)==null?void 0:f.mutations,...(p=t==null?void 0:t.defaultOptions)==null?void 0:p.mutations,...d},l)}),o.forEach(({queryKey:l,state:d,queryHash:f,meta:p,promise:w,dehydratedAt:y})=>{var T,I;const g=w?Pi(w):void 0,m=d.data===void 0?g==null?void 0:g.data:d.data,_=m===void 0?m:n(m);let v=i.get(f);const O=(v==null?void 0:v.state.status)==="pending",C=(v==null?void 0:v.state.fetchStatus)==="fetching";if(v){const $=g&&y!==void 0&&y>v.state.dataUpdatedAt;if(d.dataUpdatedAt>v.state.dataUpdatedAt||$){const{fetchStatus:A,...U}=d;v.setState({...U,data:_})}}else v=i.build(r,{...(T=r.getDefaultOptions().hydrate)==null?void 0:T.queries,...(I=t==null?void 0:t.defaultOptions)==null?void 0:I.queries,queryKey:l,queryHash:f,meta:p},{...d,data:_,fetchStatus:"idle",status:_!==void 0?"success":d.status});w&&!O&&!C&&(y===void 0||y>v.state.dataUpdatedAt)&&v.fetch(void 0,{initialPromise:Promise.resolve(w).then(n)})})}var Kr=q.createContext(void 0),Ms=r=>{const e=q.useContext(Kr);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},Ko=({client:r,children:e})=>(q.useEffect(()=>(r.mount(),()=>{r.unmount()}),[r]),_i.jsx(Kr.Provider,{value:r,children:e})),Wr=q.createContext(!1),zi=()=>q.useContext(Wr);Wr.Provider;function Ji(){let r=!1;return{clearReset:()=>{r=!1},reset:()=>{r=!0},isReset:()=>r}}var Vi=q.createContext(Ji()),Yi=()=>q.useContext(Vi),Xi=(r,e)=>{(r.suspense||r.throwOnError||r.experimental_prefetchInRender)&&(e.isReset()||(r.retryOnMount=!1))},Zi=r=>{q.useEffect(()=>{r.clearReset()},[r])},en=({result:r,errorResetBoundary:e,throwOnError:t,query:s,suspense:i})=>r.isError&&!e.isReset()&&!r.isFetching&&s&&(i&&r.data===void 0||Ir(t,[r.error,s])),tn=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))}},sn=(r,e)=>r.isLoading&&r.isFetching&&!e,rn=(r,e)=>(r==null?void 0:r.suspense)&&e.isPending,Zs=(r,e,t)=>e.fetchOptimistic(r).catch(()=>{t.clearReset()});function Hr(r,e,t){var d,f,p,w,y;const s=zi(),i=Yi(),n=Ms(),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",tn(a),Xi(a,i),Zi(i);const o=!n.getQueryCache().get(a.queryHash),[u]=q.useState(()=>new e(n,a)),c=u.getOptimisticResult(a),l=!s&&r.subscribed!==!1;if(q.useSyncExternalStore(q.useCallback(g=>{const m=l?u.subscribe(F.batchCalls(g)):B;return u.updateResult(),m},[u,l]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),q.useEffect(()=>{u.setOptions(a)},[a,u]),rn(a,c))throw Zs(a,u,i);if(en({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&&sn(c,s)){const g=o?Zs(a,u,i):(y=n.getQueryCache().get(a.queryHash))==null?void 0:y.promise;g==null||g.catch(B).finally(()=>{u.updateResult()})}return a.notifyOnChangeProps?c:u.trackResult(c)}function Wo(r,e){return Hr(r,Mr)}function Ho(r,e){const t=Ms(),s=t.getQueryCache();return q.useSyncExternalStore(q.useCallback(i=>s.subscribe(F.batchCalls(i)),[s]),()=>t.isFetching(r),()=>t.isFetching(r))}function Qo(r,e){const t=Ms(),[s]=q.useState(()=>new Bi(t,r));q.useEffect(()=>{s.setOptions(r)},[s,r]);const i=q.useSyncExternalStore(q.useCallback(a=>s.subscribe(F.batchCalls(a)),[s]),()=>s.getCurrentResult(),()=>s.getCurrentResult()),n=q.useCallback((a,o)=>{s.mutate(a,o).catch(B)},[s]);if(i.error&&Ir(s.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:n,mutateAsync:i.mutate}}function Go(r,e){return Hr(r,qi)}const nn=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)};class qs extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}}class er extends qs{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class tr extends qs{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class sr extends qs{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var ks;(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"})(ks||(ks={}));var an=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(l){try{c(s.next(l))}catch(d){a(d)}}function u(l){try{c(s.throw(l))}catch(d){a(d)}}function c(l){l.done?n(l.value):i(l.value).then(o,u)}c((s=s.apply(r,e||[])).next())})};class on{constructor(e,{headers:t={},customFetch:s,region:i=ks.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=nn(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return an(this,arguments,void 0,function*(t,s={}){var i;try{const{headers:n,method:a,body:o,signal:u}=s;let c={},{region:l}=s;l||(l=this.region);const d=new URL(`${this.url}/${t}`);l&&l!=="any"&&(c["x-region"]=l,d.searchParams.set("forceFunctionRegion",l));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:u}).catch(m=>{throw m.name==="AbortError"?m:new er(m)}),w=p.headers.get("x-relay-error");if(w&&w==="true")throw new tr(p);if(!p.ok)throw new sr(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 er(n)}:{data:null,error:n,response:n instanceof sr||n instanceof tr?n.context:void 0}}})}}var J={},Bs={},Vt={},xt={},Yt={},Xt={},un=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=un();const ln=yt.fetch,Qr=yt.fetch.bind(yt),Gr=yt.Headers,cn=yt.Request,hn=yt.Response,wt=Object.freeze(Object.defineProperty({__proto__:null,Headers:Gr,Request:cn,Response:hn,default:Qr,fetch:ln},Symbol.toStringTag,{value:"Module"})),dn=wi(wt);var Zt={};Object.defineProperty(Zt,"__esModule",{value:!0});let fn=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};Zt.default=fn;var zr=Z&&Z.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Xt,"__esModule",{value:!0});const pn=zr(dn),gn=zr(Zt);let yn=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=pn.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,u,c;let l=null,d=null,f=null,p=n.status,w=n.statusText;if(n.ok){if(this.method!=="HEAD"){const _=await n.text();_===""||(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=_:d=JSON.parse(_))}const g=(o=this.headers.get("Prefer"))===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),m=(u=n.headers.get("content-range"))===null||u===void 0?void 0:u.split("/");g&&m&&m.length>1&&(f=parseInt(m[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(d)&&(d.length>1?(l={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{l=JSON.parse(g),Array.isArray(l)&&n.status===404&&(d=[],l=null,p=200,w="OK")}catch{n.status===404&&g===""?(p=204,w="No Content"):l={message:g}}if(l&&this.isMaybeSingle&&(!((c=l==null?void 0:l.details)===null||c===void 0)&&c.includes("0 rows"))&&(l=null,p=200,w="OK"),l&&this.shouldThrowOnError)throw new gn.default(l)}return{error:l,data:d,count:f,status:p,statusText:w}});return this.shouldThrowOnError||(i=i.catch(n=>{var a,o,u;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:`${(u=n==null?void 0:n.code)!==null&&u!==void 0?u:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}returns(){return this}overrideTypes(){return this}};Xt.default=yn;var vn=Z&&Z.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Yt,"__esModule",{value:!0});const wn=vn(Xt);let _n=class extends wn.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}explain({analyze:e=!1,verbose:t=!1,settings:s=!1,buffers:i=!1,wal:n=!1,format:a="text"}={}){var o;const u=[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=${u};`),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}};Yt.default=_n;var bn=Z&&Z.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(xt,"__esModule",{value:!0});const mn=bn(Yt);let Sn=class extends mn.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=Sn;var En=Z&&Z.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Vt,"__esModule",{value:!0});const bt=En(xt);let On=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(u=>/\s/.test(u)&&!a?"":(u==='"'&&(a=!a),u)).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,u)=>o.concat(Object.keys(u)),[]);if(a.length>0){const o=[...new Set(a)].map(u=>`"${u}"`);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 u=e.reduce((c,l)=>c.concat(Object.keys(l)),[]);if(u.length>0){const c=[...new Set(u)].map(l=>`"${l}"`);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})}};Vt.default=On;var Jr=Z&&Z.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Bs,"__esModule",{value:!0});const kn=Jr(Vt),Tn=Jr(xt);let Rn=class Vr{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 kn.default(t,{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new Vr(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 u=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])=>{u.searchParams.append(d,f)})):(o="POST",c=t);const l=new Headers(this.headers);return n&&l.set("Prefer",`count=${n}`),new Tn.default({method:o,url:u,headers:l,schema:this.schemaName,body:c,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch})}};Bs.default=Rn;var _t=Z&&Z.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(J,"__esModule",{value:!0});J.PostgrestError=J.PostgrestBuilder=J.PostgrestTransformBuilder=J.PostgrestFilterBuilder=J.PostgrestQueryBuilder=J.PostgrestClient=void 0;const Yr=_t(Bs);J.PostgrestClient=Yr.default;const Xr=_t(Vt);J.PostgrestQueryBuilder=Xr.default;const Zr=_t(xt);J.PostgrestFilterBuilder=Zr.default;const ei=_t(Yt);J.PostgrestTransformBuilder=ei.default;const ti=_t(Xt);J.PostgrestBuilder=ti.default;const si=_t(Zt);J.PostgrestError=si.default;var Pn=J.default={PostgrestClient:Yr.default,PostgrestQueryBuilder:Xr.default,PostgrestFilterBuilder:Zr.default,PostgrestTransformBuilder:ei.default,PostgrestBuilder:ti.default,PostgrestError:si.default};const{PostgrestClient:An,PostgrestQueryBuilder:Zo,PostgrestFilterBuilder:eu,PostgrestTransformBuilder:tu,PostgrestBuilder:su,PostgrestError:ru}=Pn;class Cn{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: import ws from "ws" new 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+=` Suggested 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 jn="2.75.1",In=`realtime-js/${jn}`,$n="1.0.0",Ts=1e4,xn=1e3,Un=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 M;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(M||(M={}));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 Rs;(function(r){r.websocket="websocket"})(Rs||(Rs={}));var $e;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})($e||($e={}));class Dn{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;return 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 u=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:u,payload:c}}}class ri{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 x;(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"})(x||(x={}));const rr=(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]=Ln(a,r,e,i),n),{}):{}},Ln=(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)?ii(n,a):Ps(a)},ii=(r,e)=>{if(r.charAt(0)==="_"){const t=r.slice(1,r.length);return qn(e,t)}switch(r){case x.bool:return Nn(e);case x.float4:case x.float8:case x.int2:case x.int4:case x.int8:case x.numeric:case x.oid:return Fn(e);case x.json:case x.jsonb:return Mn(e);case x.timestamp:return Bn(e);case x.abstime:case x.date:case x.daterange:case x.int4range:case x.int8range:case x.money:case x.reltime:case x.text:case x.time:case x.timestamptz:case x.timetz:case x.tsrange:case x.tstzrange:return Ps(e);default:return Ps(e)}},Ps=r=>r,Nn=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},Fn=r=>{if(typeof r=="string"){const e=parseFloat(r);if(!Number.isNaN(e))return e}return r},Mn=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch(e){return`${e}`,r}return r},qn=(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=>ii(e,o))}return r},Bn=r=>typeof r=="string"?r.replace(" ","T"):r,ni=r=>{let e=r;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")+"/api/broadcast"};class rs{constructor(e,t,s={},i=Ts){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 ir;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(ir||(ir={}));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.forEach(u=>{this.state=Ot.syncDiff(this.state,u,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={},u={};return this.map(n,(c,l)=>{a[c]||(u[c]=l)}),this.map(a,(c,l)=>{const d=n[c];if(d){const f=l.map(g=>g.presence_ref),p=d.map(g=>g.presence_ref),w=l.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&&(u[c]=y)}else o[c]=l}),this.syncDiff(n,{joins:o,leaves:u},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,u)=>{var c;const l=(c=e[o])!==null&&c!==void 0?c:[];if(e[o]=this.cloneDeep(u),l.length>0){const d=e[o].map(p=>p.presence_ref),f=l.filter(p=>d.indexOf(p.presence_ref)<0);e[o].unshift(...f)}s(o,l,u)}),this.map(a,(o,u)=>{let c=e[o];if(!c)return;const l=u.map(d=>d.presence_ref);c=c.filter(d=>l.indexOf(d.presence_ref)<0),e[o]=c,i(o,c,u),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 nr;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(nr||(nr={}));var kt;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes",r.SYSTEM="system"})(kt||(kt={}));var le;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(le||(le={}));class Ks{constructor(e,t={config:{}},s){var i,n;if(this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=M.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 rs(this,re.join,this.params,this.timeout),this.rejoinTimer=new ri(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=M.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=M.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=M.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=M.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=M.errored,this.rejoinTimer.scheduleTimeout())}),this._on(re.reply,{},(a,o)=>{this._trigger(this._replyEventName(o),a)}),this.presence=new Ot(this),this.broadcastEndpointURL=ni(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==M.closed){const{config:{broadcast:a,presence:o,private:u}}=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:[],l=!!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:l}),postgres_changes:c,private:u};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(p=>e==null?void 0:e(le.CHANNEL_ERROR,p)),this._onClose(()=>e==null?void 0:e(le.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(le.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 _=0;_{this.state=M.errored,e==null||e(le.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(p).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(le.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===M.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,u={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,u,(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,u;const c=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((u=(o=(a=this.params)===null||a===void 0?void 0:a.config)===null||o===void 0?void 0:o.broadcast)===null||u===void 0)&&u.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=M.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 rs(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()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=M.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 rs(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>Un){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:u,leave:c,join:l}=re;if(s&&[o,u,c,l].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,_,v;if(["broadcast","presence","postgres_changes"].includes(a))if("id"in p){const O=p.id,C=(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))&&(C==="*"||(C==null?void 0:C.toLocaleLowerCase())===((g=t.data)===null||g===void 0?void 0:g.type.toLocaleLowerCase()))}else{const O=(_=(m=p==null?void 0:p.filter)===null||m===void 0?void 0:m.event)===null||_===void 0?void 0:_.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:_,errors:v}=w;f=Object.assign(Object.assign({},{schema:y,table:g,commit_timestamp:m,eventType:_,new:{},old:{},errors:v}),this._getPayloadRecords(w))}p.callback(f,s)})}_isClosed(){return this.state===M.closed}_isJoined(){return this.state===M.joined}_isJoining(){return this.state===M.joining}_isLeaving(){return this.state===M.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&&Ks.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=M.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=rr(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=rr(e.columns,e.old_record)),t}}const is=()=>{},Ft={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Kn=[1e3,2e3,5e3,1e4],Wn=1e4,Hn=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class Qn{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=Ts,this.transport=null,this.heartbeatIntervalMs=Ft.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=is,this.ref=0,this.reconnectTimer=null,this.logger=is,this.conn=null,this.sendBuffer=[],this.serializer=new Dn,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}/${Rs.websocket}`,this.httpEndpoint=ni(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=Cn.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;throw t.includes("Node.js")?new Error(`${t} To use Realtime in Node.js, you need to provide a WebSocket implementation: Option 1: Use Node.js 22+ which has native WebSocket support Option 2: Install and provide the "ws" package: npm install ws import ws from "ws" const client = new RealtimeClient(url, { ...options, transport: ws })`):new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:$n}))}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 Ks(`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 u;(u=this.conn)===null||u===void 0||u.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(xn,"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>0&&(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})`:"",u=n.status||"";this.log("receive",`${u} ${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([Hn],{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:In};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 ri(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},Ft.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var t,s,i,n,a,o,u,c,l;if(this.transport=(t=e==null?void 0:e.transport)!==null&&t!==void 0?t:null,this.timeout=(s=e==null?void 0:e.timeout)!==null&&s!==void 0?s:Ts,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:is,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=(u=e==null?void 0:e.reconnectAfterMs)!==null&&u!==void 0?u:d=>Kn[d-1]||Wn,this.encode=(c=e==null?void 0:e.encode)!==null&&c!==void 0?c:(d,f)=>f(JSON.stringify(d)),this.decode=(l=e==null?void 0:e.decode)!==null&&l!==void 0?l: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 Ws 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 Gn extends Ws{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 As extends Ws{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}var zn=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(l){try{c(s.next(l))}catch(d){a(d)}}function u(l){try{c(s.throw(l))}catch(d){a(d)}}function c(l){l.done?n(l.value):i(l.value).then(o,u)}c((s=s.apply(r,e||[])).next())})};const ai=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)},Jn=()=>zn(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield $t(()=>Promise.resolve().then(()=>wt),void 0)).Response:Response}),Cs=r=>{if(Array.isArray(r))return r.map(t=>Cs(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]=Cs(s)}),e},Vn=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 Ge=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(l){try{c(s.next(l))}catch(d){a(d)}}function u(l){try{c(s.throw(l))}catch(d){a(d)}}function c(l){l.done?n(l.value):i(l.value).then(o,u)}c((s=s.apply(r,e||[])).next())})};const ns=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),Yn=(r,e,t)=>Ge(void 0,void 0,void 0,function*(){const s=yield Jn();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 Gn(ns(i),n,a))}).catch(i=>{e(new As(ns(i),i))}):e(new As(ns(r),r))}),Xn=(r,e,t,s)=>{const i={method:r,headers:(e==null?void 0:e.headers)||{}};return r==="GET"||!s?i:(Vn(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 Ge(this,void 0,void 0,function*(){return new Promise((a,o)=>{r(t,Xn(e,s,i,n)).then(u=>{if(!u.ok)throw u;return s!=null&&s.noResolveJson?u:u.json()}).then(u=>a(u)).catch(u=>Yn(u,o,s))})})}function Qt(r,e,t,s){return Ge(this,void 0,void 0,function*(){return Ut(r,"GET",e,t,s)})}function ie(r,e,t,s,i){return Ge(this,void 0,void 0,function*(){return Ut(r,"POST",e,s,i,t)})}function js(r,e,t,s,i){return Ge(this,void 0,void 0,function*(){return Ut(r,"PUT",e,s,i,t)})}function Zn(r,e,t,s){return Ge(this,void 0,void 0,function*(){return Ut(r,"HEAD",e,Object.assign(Object.assign({},t),{noResolveJson:!0}),s)})}function oi(r,e,t,s,i){return Ge(this,void 0,void 0,function*(){return Ut(r,"DELETE",e,s,i,t)})}var ea=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(l){try{c(s.next(l))}catch(d){a(d)}}function u(l){try{c(s.throw(l))}catch(d){a(d)}}function c(l){l.done?n(l.value):i(l.value).then(o,u)}c((s=s.apply(r,e||[])).next())})};class ta{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}execute(){return ea(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 sa=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(l){try{c(s.next(l))}catch(d){a(d)}}function u(l){try{c(s.throw(l))}catch(d){a(d)}}function c(l){l.done?n(l.value):i(l.value).then(o,u)}c((s=s.apply(r,e||[])).next())})},ui;class ra{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[ui]="BlobDownloadBuilder",this.promise=null}asStream(){return new ta(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}execute(){return sa(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}})}}ui=Symbol.toStringTag;var Q=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(l){try{c(s.next(l))}catch(d){a(d)}}function u(l){try{c(s.throw(l))}catch(d){a(d)}}function c(l){l.done?n(l.value):i(l.value).then(o,u)}c((s=s.apply(r,e||[])).next())})};const ia={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},ar={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class na{constructor(e,t={},s,i){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.bucketId=s,this.fetch=ai(i)}throwOnError(){return this.shouldThrowOnError=!0,this}uploadOrUpdate(e,t,s,i){return Q(this,void 0,void 0,function*(){try{let n;const a=Object.assign(Object.assign({},ar),i);let o=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(a.upsert)});const u=a.metadata;typeof Blob<"u"&&s instanceof Blob?(n=new FormData,n.append("cacheControl",a.cacheControl),u&&n.append("metadata",this.encodeMetadata(u)),n.append("",s)):typeof FormData<"u"&&s instanceof FormData?(n=s,n.append("cacheControl",a.cacheControl),u&&n.append("metadata",this.encodeMetadata(u))):(n=s,o["cache-control"]=`max-age=${a.cacheControl}`,o["content-type"]=a.contentType,u&&(o["x-metadata"]=this.toBase64(this.encodeMetadata(u)))),i!=null&&i.headers&&(o=Object.assign(Object.assign({},o),i.headers));const c=this._removeEmptyFolders(t),l=this._getFinalPath(c),d=yield(e=="PUT"?js:ie)(this.fetch,`${this.url}/object/${l}`,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 Q(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,i){return Q(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 u;const c=Object.assign({upsert:ar.upsert},i),l=Object.assign(Object.assign({},this.headers),{"x-upsert":String(c.upsert)});typeof Blob<"u"&&s instanceof Blob?(u=new FormData,u.append("cacheControl",c.cacheControl),u.append("",s)):typeof FormData<"u"&&s instanceof FormData?(u=s,u.append("cacheControl",c.cacheControl)):(u=s,l["cache-control"]=`max-age=${c.cacheControl}`,l["content-type"]=c.contentType);const d=yield js(this.fetch,o.toString(),u,{headers:l});return{data:{path:n,fullPath:d.Key},error:null}}catch(u){if(this.shouldThrowOnError)throw u;if(N(u))return{data:null,error:u};throw u}})}createSignedUploadUrl(e,t){return Q(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 Ws("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}})}update(e,t,s){return Q(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return Q(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 Q(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 Q(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 Q(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),u=()=>Qt(this.fetch,`${this.url}/${i}/${o}${a}`,{headers:this.headers,noResolveJson:!0});return new ra(u,this.shouldThrowOnError)}info(e){return Q(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{const s=yield Qt(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:Cs(s),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(N(s))return{data:null,error:s};throw s}})}exists(e){return Q(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{return yield Zn(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 As){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",u=this.transformOptsToQueryString((t==null?void 0:t.transform)||{});u!==""&&i.push(u);let c=i.join("&");return c!==""&&(c=`?${c}`),{data:{publicUrl:encodeURI(`${this.url}/${o}/public/${s}${c}`)}}}remove(e){return Q(this,void 0,void 0,function*(){try{return{data:yield oi(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 Q(this,void 0,void 0,function*(){try{const i=Object.assign(Object.assign(Object.assign({},ia),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 Q(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 aa="2.75.1",oa={"X-Client-Info":`storage-js/${aa}`};var Je=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(l){try{c(s.next(l))}catch(d){a(d)}}function u(l){try{c(s.throw(l))}catch(d){a(d)}}function c(l){l.done?n(l.value):i(l.value).then(o,u)}c((s=s.apply(r,e||[])).next())})};class ua{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({},oa),t),this.fetch=ai(s)}throwOnError(){return this.shouldThrowOnError=!0,this}listBuckets(){return Je(this,void 0,void 0,function*(){try{return{data:yield Qt(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 Je(this,void 0,void 0,function*(){try{return{data:yield Qt(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 Je(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 Je(this,void 0,void 0,function*(){try{return{data:yield js(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 Je(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 Je(this,void 0,void 0,function*(){try{return{data:yield oi(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 la extends ua{constructor(e,t={},s,i){super(e,t,s,i)}from(e){return new na(this.url,this.headers,e,this.fetch)}}const ca="2.75.1";let St="";typeof Deno<"u"?St="deno":typeof document<"u"?St="web":typeof navigator<"u"&&navigator.product==="ReactNative"?St="react-native":St="node";const ha={"X-Client-Info":`supabase-js-${St}/${ca}`},da={headers:ha},fa={schema:"public"},pa={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},ga={};var ya=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(l){try{c(s.next(l))}catch(d){a(d)}}function u(l){try{c(s.throw(l))}catch(d){a(d)}}function c(l){l.done?n(l.value):i(l.value).then(o,u)}c((s=s.apply(r,e||[])).next())})};const va=r=>{let e;return r?e=r:typeof fetch>"u"?e=Qr:e=fetch,(...t)=>e(...t)},wa=()=>typeof Headers>"u"?Gr:Headers,_a=(r,e,t)=>{const s=va(t),i=wa();return(n,a)=>ya(void 0,void 0,void 0,function*(){var o;const u=(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 ${u}`),s(n,Object.assign(Object.assign({},a),{headers:c}))})};var ba=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(l){try{c(s.next(l))}catch(d){a(d)}}function u(l){try{c(s.throw(l))}catch(d){a(d)}}function c(l){l.done?n(l.value):i(l.value).then(o,u)}c((s=s.apply(r,e||[])).next())})};function ma(r){return r.endsWith("/")?r:r+"/"}function Sa(r,e){var t,s;const{db:i,auth:n,realtime:a,global:o}=r,{db:u,auth:c,realtime:l,global:d}=e,f={db:Object.assign(Object.assign({},u),i),auth:Object.assign(Object.assign({},c),n),realtime:Object.assign(Object.assign({},l),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:()=>ba(this,void 0,void 0,function*(){return""})};return r.accessToken?f.accessToken=r.accessToken:delete f.accessToken,f}function Ea(r){const e=r==null?void 0:r.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(ma(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}const li="2.75.1",tt=30*1e3,Is=3,as=Is*tt,Oa="http://localhost:9999",ka="supabase.auth.token",Ta={"X-Client-Info":`gotrue-js/${li}`},$s="X-Supabase-Api-Version",ci={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Ra=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Pa=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 Aa extends Rt{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}}function Ca(r){return E(r)&&r.name==="AuthApiError"}class xe extends Rt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class Pe extends Rt{constructor(e,t,s,i){super(e,s,i),this.name=t,this.status=s}}class ge extends Pe{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function ja(r){return E(r)&&r.name==="AuthSessionMissingError"}class Ve extends Pe{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class Mt extends Pe{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class qt extends Pe{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 Ia(r){return E(r)&&r.name==="AuthImplicitGrantRedirectError"}class or extends Pe{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 xs extends Pe{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function os(r){return E(r)&&r.name==="AuthRetryableFetchError"}class ur extends Pe{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}}class Us extends Pe{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Gt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),lr=` \r=`.split(""),$a=(()=>{const r=new Array(128);for(let e=0;e=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 hi(r,e,t){const s=$a[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 hr(r){const e=[],t=a=>{e.push(String.fromCodePoint(a))},s={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},n=a=>{Da(a,s,t)};for(let a=0;a>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 Ua(r,e){for(let t=0;t55295&&s<=56319){const i=(s-55296)*1024&65535;s=(r.charCodeAt(t+1)-56320&65535|i)+65536,t+=1}xa(s,e)}}function Da(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;ie.push(t)),new Uint8Array(e)}function Ue(r){const e=[],t={queue:0,queuedBits:0},s=i=>{e.push(i)};return r.forEach(i=>cr(i,t,s)),cr(null,t,s),e.join("")}function Na(r){return Math.round(Date.now()/1e3)+r}function Fa(){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",Ce={tested:!1,writable:!1},di=()=>{if(!V())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Ce.tested)return Ce.writable;const r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),Ce.tested=!0,Ce.writable=!0}catch{Ce.tested=!0,Ce.writable=!1}return Ce.writable};function Ma(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 fi=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)},qa=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 es{constructor(){this.promise=new es.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}es.promiseConstructor=Promise;function us(r){const e=r.split(".");if(e.length!==3)throw new Us("Invalid JWT structure");for(let s=0;s{setTimeout(()=>e(null),r)})}function Ka(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 Wa(r){return("0"+r.toString(16)).substr(-2)}function Ha(){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,Wa).join("")}async function Qa(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 Ga(r){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),r;const t=await Qa(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Ye(r,e,t=!1){const s=Ha();let i=s;t&&(i+="/PASSWORD_RECOVERY"),await st(r,`${e}-code-verifier`,i);const n=await Ga(s);return[n,s===n?"plain":"s256"]}const za=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Ja(r){const e=r.headers.get($s);if(!e||!e.match(za))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Va(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 Ya(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 Xa=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Xe(r){if(!Xa.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 dr(r){return JSON.parse(JSON.stringify(r))}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);ir.msg||r.message||r.error_description||r.error||JSON.stringify(r),eo=[502,503,504];async function fr(r){var e;if(!qa(r))throw new xs(Ie(r),0);if(eo.includes(r.status))throw new xs(Ie(r),r.status);let t;try{t=await r.json()}catch(n){throw new xe(Ie(n),n)}let s;const i=Ja(r);if(i&&i.getTime()>=ci["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 ur(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 ur(Ie(t),r.status,t.weak_password.reasons);throw new Aa(Ie(t),r.status||500,s)}const to=(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[$s]||(n[$s]=ci["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():"",u=await so(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(u):{data:Object.assign({},u),error:null}}async function so(r,e,t,s,i,n){const a=to(e,s,i,n);let o;try{o=await r(t,Object.assign({},a))}catch(u){throw console.error(u),new xs(Ie(u),0)}if(o.ok||await fr(o),s!=null&&s.noResolveJson)return o;try{return await o.json()}catch(u){await fr(u)}}function ee(r){var e;let t=null;no(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=Na(r.expires_in)));const s=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:s},error:null}}function pr(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 ro(r){return{data:r,error:null}}function io(r){const{action_link:e,email_otp:t,hashed_token:s,redirect_to:i,verification_type:n}=r,a=Za(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},u=Object.assign({},a);return{data:{properties:o,user:u},error:null}}function gr(r){return r}function no(r){return r.access_token&&r.refresh_token&&r.expires_in}const cs=["global","local","others"];var ao=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);i0&&(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,u;try{const c={nextPage:null,lastPage:0,total:0},l=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:gr});if(l.error)throw l.error;const d=await l.json(),f=(a=l.headers.get("x-total-count"))!==null&&a!==void 0?a:0,p=(u=(o=l.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&u!==void 0?u:[];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,"DELETE",`${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 yr(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}const Ze={debug:!!(globalThis&&di()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class pi extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class uo extends pi{}async function lo(r,e,t){Ze.debug;const s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),Ze.debug},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&&i.name;try{return await t()}finally{Ze.debug&&i.name}}else{if(e===0)throw Ze.debug,new uo(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(Ze.debug)try{const n=await globalThis.navigator.locks.query();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 co(){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 gi(r){if(!/^0x[a-fA-F0-9]{40}$/.test(r))throw new Error(`@supabase/auth-js: Address "${r}" is invalid.`);return r.toLowerCase()}function ho(r){return parseInt(r,16)}function fo(r){const e=new TextEncoder().encode(r);return"0x"+Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}function po(r){var e;const{chainId:t,domain:s,expirationTime:i,issuedAt:n=new Date,nonce:a,notBefore:o,requestId:u,resources:c,scheme:l,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(` `))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${r.statement}`)}const p=gi(r.address),w=l?`${l}://${s}`:s,y=r.statement?`${r.statement} `:"",g=`${w} wants you to sign in with your Ethereum account: ${p} ${y}`;let m=`URI: ${d} Version: ${f} Chain ID: ${t}${a?` Nonce: ${a}`:""} Issued At: ${n.toISOString()}`;if(i&&(m+=` Expiration Time: ${i.toISOString()}`),o&&(m+=` Not Before: ${o.toISOString()}`),u&&(m+=` Request ID: ${u}`),c){let _=` Resources:`;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}`);_+=` - ${v}`}m+=_}return`${g} ${m}`}class 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 zt extends L{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}function go({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(vi(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 yo({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(vi(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 yi=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);i0){o.excludeCredentials=new Array(s.length);for(let u=0;u0){n.allowCredentials=new Array(t.length);for(let a=0;ai!==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 Ro(r,e){return Jt(ko,r,e||{})}function Po(r,e){return Jt(To,r,e||{})}class Ao{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 u=i??wo.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=Ro(a.webauthn.credential_options.publicKey,n==null?void 0:n.create),{data:l,error:d}=await Eo({publicKey:c,signal:u});return l?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:l}},error:null}:{data:null,error:d}}case"request":{const c=Po(a.webauthn.credential_options.publicKey,n==null?void 0:n.request),{data:l,error:d}=await Oo(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:c,signal:u}));return l?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:l}},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")};try{if(!vr())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:u}=a;return this._verify({factorId:e,challengeId:a.challengeId,webauthn:{type:u.type,rpId:t,rpOrigins:s,credential_response:u.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(!vr())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(l=>{var d;return(d=l.data)===null||d===void 0?void 0:d.all.find(f=>f.factor_type==="webauthn"&&f.friendly_name===e&&f.status!=="unverified")}).then(l=>l?this.client.mfa.unenroll({factorId:l==null?void 0:l.id}):void 0),{data:null,error:o};const{data:u,error:c}=await this._challenge({factorId:a.id,friendlyName:a.friendly_name,webauthn:{rpId:t,rpOrigins:s},signal:i},{create:n});return u?this._verify({factorId:a.id,challengeId:u.challengeId,webauthn:{rpId:t,rpOrigins:s,type:u.webauthn.type,credential_response:u.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)}}}}co();const Co={url:Oa,storageKey:ka,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ta,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function wr(r,e,t){return await t()}const et={};class Pt{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=Pt.nextInstanceID,Pt.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({},Co),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 oo({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=fi(i.fetch),this.lock=i.lock||wr,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=lo:this.lock=wr,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 Ao(this)},this.persistSession?(i.storage?this.storage=i.storage:di()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=yr(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=yr(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} (${li}) ${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=Ma(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),Ia(n)){const u=(e=n.details)===null||e===void 0?void 0:e.code;if(u==="identity_already_exists"||u==="identity_not_found"||u==="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;if(o||!a)return{data:{user:null,session:null},error:o};const u=a.session,c=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",u)),{data:{user:c,session:u},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:l,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:l,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:l,password:d,options:f}=e;n=await k(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:l,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 Mt("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 u=a.session,c=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",u)),{data:{user:c,session:u},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:pr})}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:pr})}else throw new Mt("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,u,c,l,d,f;let p,w;if("message"in e)p=e.message,w=e.signature;else{const{chain:y,wallet:g,statement:m,options:_}=e;let v;if(V())if(typeof g=="object")v=g;else{const A=window;if("ethereum"in A&&typeof A.ethereum=="object"&&"request"in A.ethereum&&typeof A.ethereum.request=="function")v=A.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"||!(_!=null&&_.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");v=g}const O=new URL((t=_==null?void 0:_.url)!==null&&t!==void 0?t:window.location.href),C=await v.request({method:"eth_requestAccounts"}).then(A=>A).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!C||C.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const T=gi(C[0]);let I=(s=_==null?void 0:_.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!I){const A=await v.request({method:"eth_chainId"});I=ho(A)}const $={domain:O.host,address:T,statement:m,uri:O.href,version:"1",chainId:I,nonce:(i=_==null?void 0:_.signInWithEthereum)===null||i===void 0?void 0:i.nonce,issuedAt:(a=(n=_==null?void 0:_.signInWithEthereum)===null||n===void 0?void 0:n.issuedAt)!==null&&a!==void 0?a:new Date,expirationTime:(o=_==null?void 0:_.signInWithEthereum)===null||o===void 0?void 0:o.expirationTime,notBefore:(u=_==null?void 0:_.signInWithEthereum)===null||u===void 0?void 0:u.notBefore,requestId:(c=_==null?void 0:_.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(l=_==null?void 0:_.signInWithEthereum)===null||l===void 0?void 0:l.resources};p=po($),w=await v.request({method:"personal_sign",params:[fo(p),T]})}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,u,c,l,d,f,p;let w,y;if("message"in e)w=e.message,y=e.signature;else{const{chain:g,wallet:m,statement:_,options:v}=e;let O;if(V())if(typeof m=="object")O=m;else{const T=window;if("solana"in T&&typeof T.solana=="object"&&("signIn"in T.solana&&typeof T.solana.signIn=="function"||"signMessage"in T.solana&&typeof T.solana.signMessage=="function"))O=T.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 C=new URL((t=v==null?void 0:v.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in O&&O.signIn){const T=await O.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},v==null?void 0:v.signInWithSolana),{version:"1",domain:C.host,uri:C.href}),_?{statement:_}:null));let I;if(Array.isArray(T)&&T[0]&&typeof T[0]=="object")I=T[0];else if(T&&typeof T=="object"&&"signedMessage"in T&&"signature"in T)I=T;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in I&&"signature"in I&&(typeof I.signedMessage=="string"||I.signedMessage instanceof Uint8Array)&&I.signature instanceof Uint8Array)w=typeof I.signedMessage=="string"?I.signedMessage:new TextDecoder().decode(I.signedMessage),y=I.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=[`${C.host} wants you to sign in with your Solana account:`,O.publicKey.toBase58(),..._?["",_,""]:[""],"Version: 1",`URI: ${C.href}`,`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}`]:[],...!((u=v==null?void 0:v.signInWithSolana)===null||u===void 0)&&u.nonce?[`Nonce: ${v.signInWithSolana.nonce}`]:[],...!((c=v==null?void 0:v.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${v.signInWithSolana.requestId}`]:[],...!((d=(l=v==null?void 0:v.signInWithSolana)===null||l===void 0?void 0:l.resources)===null||d===void 0)&&d.length?["Resources",...v.signInWithSolana.resources.map(I=>`- ${I}`)]:[]].join(` `);const T=await O.signMessage(new TextEncoder().encode(w),"utf8");if(!T||!(T instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");y=T}}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:u,error:c}=o;return c?{data:{user:null,session:null},error:c}:!u||!u.session||!u.user?{data:{user:null,session:null},error:new Ve}:(u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers("SIGNED_IN",u.session)),{data:u,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:u}=e;let c=null,l=null;this.flowType==="pkce"&&([c,l]=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=u==null?void 0:u.data)!==null&&t!==void 0?t:{},create_user:(s=u==null?void 0:u.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken},code_challenge:c,code_challenge_method:l},redirectTo:u==null?void 0:u.emailRedirectTo});return{data:{user:null,session:null},error:d}}if("phone"in e){const{phone:o,options:u}=e,{data:c,error:l}=await k(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:o,data:(i=u==null?void 0:u.data)!==null&&i!==void 0?i:{},create_user:(n=u==null?void 0:u.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken},channel:(a=u==null?void 0:u.channel)!==null&&a!==void 0?a:"sms"}});return{data:{user:null,session:null,messageId:c==null?void 0:c.message_id},error:l}}throw new Mt("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 u=a.session,c=a.user;return u!=null&&u.access_token&&(await this._saveSession(u),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",u)),{data:{user:c,session:u},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:ro})}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 Mt("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 valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const s=e.expires_at?e.expires_at*1e3-Date.now()(!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(u,c,l))})}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 ja(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,u=null;this.flowType==="pkce"&&e.email!=null&&([o,u]=await Ye(this.storage,this.storageKey));const{data:c,error:l}=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:u}),jwt:a.access_token,xform:ye});if(l)throw l;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}=us(e.access_token);if(a.exp&&(s=a.exp,i=s<=t),i){const{data:o,error:u}=await this._callRefreshToken(e.refresh_token);if(u)return{data:{user:null,session:null},error:u};if(!o)return{data:{user:null,session:null},error:null};n=o}else{const{data:o,error:u}=await this._getUser(e.access_token);if(u)throw u;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 qt("No browser detected.");if(e.error||e.error_description||e.error_code)throw new qt(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new or("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new qt("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 or("No code detected.");const{data:_,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:_.session,redirectType:null},error:null}}const{provider_token:s,provider_refresh_token:i,access_token:n,refresh_token:a,expires_in:o,expires_at:u,token_type:c}=e;if(!n||!o||!a||!c)throw new qt("No session defined in URL");const l=Math.round(Date.now()/1e3),d=parseInt(o);let f=l+d;u&&(f=parseInt(u));const p=f-l;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;l-w>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",w,f,l):l-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,l);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&&!(Ca(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=Fa(),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,u,c,l;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:(u=e.options)===null||u===void 0?void 0:u.queryParams,skipBrowserRedirect:!0});return await k(this.fetch,"GET",p,{headers:this.headers,jwt:(l=(c=d.session)===null||c===void 0?void 0:c.access_token)!==null&&l!==void 0?l: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:u,access_token:c,nonce:l}=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:u,access_token:c,nonce:l,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;return 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 Ka(async i=>(i>0&&await Ba(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&&os(n)&&Date.now()+a-s{try{await o.callback(e,t)}catch(u){n.push(u)}});if(await Promise.all(a),n.length>0){for(let o=0;othis._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 ${Is} ticks`),i<=Is&&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 pi)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:u,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"&&u.type==="totp"&&(!((i=u==null?void 0:u.totp)===null||i===void 0)&&i.qr_code)&&(u.totp.qr_code=`data:image/svg+xml;utf-8,${u.totp.qr_code}`),{data:u,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"?mo(e.webauthn.credential_response):So(e.webauthn.credential_response)})}:{code:e.code}),{data:o,error:u}=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 u?{data:null,error:u}:(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:u})})}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:_o(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:bo(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}=us(i.access_token);let o=null;a.aal&&(o=a.aal);let u=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&&(u="aal2");const l=a.amr||[];return{data:{currentLevel:o,nextLevel:u,currentAuthenticationMethods:l},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+Pa>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}=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:u}}=us(s);t!=null&&t.allowExpired||Va(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 l=Ya(i.alg),d=await crypto.subtle.importKey("jwk",c,l,!0,["verify"]);if(!await crypto.subtle.verify(l,d,a,La(`${o}.${u}`)))throw new Us("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}}}Pt.nextInstanceID=0;const jo=Pt;class Io extends jo{constructor(e){super(e)}}var $o=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(l){try{c(s.next(l))}catch(d){a(d)}}function u(l){try{c(s.throw(l))}catch(d){a(d)}}function c(l){l.done?n(l.value):i(l.value).then(o,u)}c((s=s.apply(r,e||[])).next())})};class xo{constructor(e,t,s){var i,n,a;this.supabaseUrl=e,this.supabaseKey=t;const o=Ea(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 u=`sb-${o.hostname.split(".")[0]}-auth-token`,c={db:fa,realtime:ga,auth:Object.assign(Object.assign({},pa),{storageKey:u}),global:da},l=Sa(s??{},c);this.storageKey=(i=l.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},l.accessToken?(this.accessToken=l.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=l.auth)!==null&&a!==void 0?a:{},this.headers,l.global.fetch),this.fetch=_a(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.rest=new An(new URL("rest/v1",o).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this.storage=new la(this.storageUrl.href,this.headers,this.fetch,s==null?void 0:s.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new on(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 $o(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:u,debug:c},l,d){const f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Io({url:this.authUrl.href,headers:Object.assign(Object.assign({},f),l),storageKey:a,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:i,userStorage:n,flowType:o,lock:u,debug:c,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(p=>p.toLowerCase()==="authorization")})}_initRealtimeClient(e){return new Qn(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 iu=(r,e,t)=>new xo(r,e,t);function Uo(){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}Uo()&&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 Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");export{sr as F,Mo as Q,$t as _,Wo as a,Qo as b,Go as c,Ho as d,iu as e,qo as f,Ko as g,Bo as h,Fo as k,Ms as u};