PageSourceSearch

https://mustwants.com/assets/vendor-data-B6iiC3HR.js

js mustwants.com collected 2026-10-08 04:40:27 UTC 211,877 bytes, 43 lines download raw bytes

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

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.