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