summary refs log tree commit diff
diff options
context:
space:
mode:
authorBaitinq <30861839+Baitinq@users.noreply.github.com>2024-06-07 18:36:35 +0000
committerBaitinq <30861839+Baitinq@users.noreply.github.com>2024-06-07 18:36:35 +0000
commit1f0248b7b2e19d96efe4390c4a028abedf5b1a59 (patch)
tree85f3a4cbe5f37bba553bbbba578aadd9f95167f6
parentDeploying to gh-pages from @ Baitinq/fs-tracer-frontend@6b8f811e19d8c02f515ee... (diff)
downloadfs-tracer-frontend-1f0248b7b2e19d96efe4390c4a028abedf5b1a59.tar.gz
fs-tracer-frontend-1f0248b7b2e19d96efe4390c4a028abedf5b1a59.tar.bz2
fs-tracer-frontend-1f0248b7b2e19d96efe4390c4a028abedf5b1a59.zip
Deploying to gh-pages from @ Baitinq/fs-tracer-frontend@1d608e3ba2027474c0872d7614fcf02d243b9638 🚀
-rw-r--r--assets/browser-Cb7qedTs.js (renamed from assets/browser-B3mZcEix.js)2
-rw-r--r--assets/index-C1q9-kv2.css (renamed from assets/index-tmQ7CD-c.css)2
-rw-r--r--assets/index-CbF1FLl3.js (renamed from assets/index-B0RTX0s0.js)2
-rw-r--r--index.html4
4 files changed, 5 insertions, 5 deletions
diff --git a/assets/browser-B3mZcEix.js b/assets/browser-Cb7qedTs.js
index e76bb8c..8b7508f 100644
--- a/assets/browser-B3mZcEix.js
+++ b/assets/browser-Cb7qedTs.js
@@ -1 +1 @@
-import{g as a}from"./index-B0RTX0s0.js";function f(t,s){for(var o=0;o<s.length;o++){const e=s[o];if(typeof e!="string"&&!Array.isArray(e)){for(const r in e)if(r!=="default"&&!(r in t)){const n=Object.getOwnPropertyDescriptor(e,r);n&&Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var c=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")};const i=a(c),u=f({__proto__:null,default:i},[c]);export{u as b};
+import{g as a}from"./index-CbF1FLl3.js";function f(t,s){for(var o=0;o<s.length;o++){const e=s[o];if(typeof e!="string"&&!Array.isArray(e)){for(const r in e)if(r!=="default"&&!(r in t)){const n=Object.getOwnPropertyDescriptor(e,r);n&&Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var c=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")};const i=a(c),u=f({__proto__:null,default:i},[c]);export{u as b};
diff --git a/assets/index-tmQ7CD-c.css b/assets/index-C1q9-kv2.css
index 8d86128..ef750c7 100644
--- a/assets/index-tmQ7CD-c.css
+++ b/assets/index-C1q9-kv2.css
@@ -1 +1 @@
-*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]{display:none}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }.contents{display:contents}.font-bold{font-weight:700}
+*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]{display:none}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }.contents{display:contents}.font-bold{font-weight:700}.underline{text-decoration-line:underline}
diff --git a/assets/index-B0RTX0s0.js b/assets/index-CbF1FLl3.js
index e65370c..f1f2aeb 100644
--- a/assets/index-B0RTX0s0.js
+++ b/assets/index-CbF1FLl3.js
@@ -64,4 +64,4 @@ Error generating stack: `+s.message+`
  * LICENSE.md file in the root directory of this source tree.
  *
  * @license MIT
- */const $v="6";try{window.__reactRouterVersion=$v}catch{}const Nv="startTransition",cu=If[Nv];function Av(e){let{basename:t,children:n,future:r,window:i}=e,s=E.useRef();s.current==null&&(s.current=Hp({window:i,v5Compat:!0}));let o=s.current,[l,a]=E.useState({action:o.action,location:o.location}),{v7_startTransition:u}=r||{},c=E.useCallback(d=>{u&&cu?cu(()=>a(d)):a(d)},[a,u]);return E.useLayoutEffect(()=>o.listen(c),[o,c]),E.createElement(Lv,{basename:t,children:n,location:l.location,navigationType:l.action,navigator:o,future:r})}var du;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(du||(du={}));var fu;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(fu||(fu={}));const Uv="modulepreload",Dv=function(e,t){return new URL(e,t).href},hu={},Nn=function(t,n,r){let i=Promise.resolve();if(n&&n.length>0){const s=document.getElementsByTagName("link"),o=document.querySelector("meta[property=csp-nonce]"),l=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));i=Promise.all(n.map(a=>{if(a=Dv(a,r),a in hu)return;hu[a]=!0;const u=a.endsWith(".css"),c=u?'[rel="stylesheet"]':"";if(!!r)for(let m=s.length-1;m>=0;m--){const g=s[m];if(g.href===a&&(!u||g.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${a}"]${c}`))return;const h=document.createElement("link");if(h.rel=u?"stylesheet":Uv,u||(h.as="script",h.crossOrigin=""),h.href=a,l&&h.setAttribute("nonce",l),document.head.appendChild(h),u)return new Promise((m,g)=>{h.addEventListener("load",m),h.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${a}`)))})}))}return i.then(()=>t()).catch(s=>{const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=s,window.dispatchEvent(o),!o.defaultPrevented)throw s})},zv=e=>{let t;return e?t=e:typeof fetch>"u"?t=(...n)=>Nn(()=>Promise.resolve().then(()=>Fr),void 0,import.meta.url).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)};class Wl extends Error{constructor(t,n="FunctionsError",r){super(t),this.name=n,this.context=r}}class Fv extends Wl{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class Mv extends Wl{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class bv extends Wl{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var Ho;(function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"})(Ho||(Ho={}));var Bv=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};class Vv{constructor(t,{headers:n={},customFetch:r,region:i=Ho.Any}={}){this.url=t,this.headers=n,this.region=i,this.fetch=zv(r)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t,n={}){var r;return Bv(this,void 0,void 0,function*(){try{const{headers:i,method:s,body:o}=n;let l={},{region:a}=n;a||(a=this.region),a&&a!=="any"&&(l["x-region"]=a);let u;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(l["Content-Type"]="application/octet-stream",u=o):typeof o=="string"?(l["Content-Type"]="text/plain",u=o):typeof FormData<"u"&&o instanceof FormData?u=o:(l["Content-Type"]="application/json",u=JSON.stringify(o)));const c=yield this.fetch(`${this.url}/${t}`,{method:s||"POST",headers:Object.assign(Object.assign(Object.assign({},l),this.headers),i),body:u}).catch(g=>{throw new Fv(g)}),d=c.headers.get("x-relay-error");if(d&&d==="true")throw new Mv(c);if(!c.ok)throw new bv(c);let h=((r=c.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),m;return h==="application/json"?m=yield c.json():h==="application/octet-stream"?m=yield c.blob():h==="text/event-stream"?m=c:h==="multipart/form-data"?m=yield c.formData():m=yield c.text(),{data:m,error:null}}catch(i){return{data:null,error:i}}})}}var Hv=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")},An=Hv();const Wv=An.fetch,Kl=An.fetch.bind(An),tf=An.Headers,Kv=An.Request,Gv=An.Response,Fr=Object.freeze(Object.defineProperty({__proto__:null,Headers:tf,Request:Kv,Response:Gv,default:Kl,fetch:Wv},Symbol.toStringTag,{value:"Module"}));class Qv extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}}class Jv{constructor(t){this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=t.headers,this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=t.shouldThrowOnError,this.signal=t.signal,this.isMaybeSingle=t.isMaybeSingle,t.fetch?this.fetch=t.fetch:typeof fetch>"u"?this.fetch=Kl:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(t,n){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");const r=this.fetch;let i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async s=>{var o,l,a;let u=null,c=null,d=null,h=s.status,m=s.statusText;if(s.ok){if(this.method!=="HEAD"){const p=await s.text();p===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?c=p:c=JSON.parse(p))}const y=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),_=(l=s.headers.get("content-range"))===null||l===void 0?void 0:l.split("/");y&&_&&_.length>1&&(d=parseInt(_[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(c)&&(c.length>1?(u={code:"PGRST116",details:`Results contain ${c.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},c=null,d=null,h=406,m="Not Acceptable"):c.length===1?c=c[0]:c=null)}else{const y=await s.text();try{u=JSON.parse(y),Array.isArray(u)&&s.status===404&&(c=[],u=null,h=200,m="OK")}catch{s.status===404&&y===""?(h=204,m="No Content"):u={message:y}}if(u&&this.isMaybeSingle&&(!((a=u==null?void 0:u.details)===null||a===void 0)&&a.includes("0 rows"))&&(u=null,h=200,m="OK"),u&&this.shouldThrowOnError)throw new Qv(u)}return{error:u,data:c,count:d,status:h,statusText:m}});return this.shouldThrowOnError||(i=i.catch(s=>{var o,l,a;return{error:{message:`${(o=s==null?void 0:s.name)!==null&&o!==void 0?o:"FetchError"}: ${s==null?void 0:s.message}`,details:`${(l=s==null?void 0:s.stack)!==null&&l!==void 0?l:""}`,hint:"",code:`${(a=s==null?void 0:s.code)!==null&&a!==void 0?a:""}`},data:null,count:null,status:0,statusText:""}})),i.then(t,n)}}class qv extends Jv{select(t){let n=!1;const r=(t??"*").split("").map(i=>/\s/.test(i)&&!n?"":(i==='"'&&(n=!n),i)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(t,{ascending:n=!0,nullsFirst:r,foreignTable:i,referencedTable:s=i}={}){const o=s?`${s}.order`:"order",l=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${l?`${l},`:""}${t}.${n?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:n,referencedTable:r=n}={}){const i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${t}`),this}range(t,n,{foreignTable:r,referencedTable:i=r}={}){const s=typeof i>"u"?"offset":`${i}.offset`,o=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(s,`${t}`),this.url.searchParams.set(o,`${n-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:t=!1,verbose:n=!1,settings:r=!1,buffers:i=!1,wal:s=!1,format:o="text"}={}){var l;const a=[t?"analyze":null,n?"verbose":null,r?"settings":null,i?"buffers":null,s?"wal":null].filter(Boolean).join("|"),u=(l=this.headers.Accept)!==null&&l!==void 0?l:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${u}"; options=${a};`,o==="json"?this:this}rollback(){var t;return((t=this.headers.Prefer)!==null&&t!==void 0?t:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}}class ln extends qv{eq(t,n){return this.url.searchParams.append(t,`eq.${n}`),this}neq(t,n){return this.url.searchParams.append(t,`neq.${n}`),this}gt(t,n){return this.url.searchParams.append(t,`gt.${n}`),this}gte(t,n){return this.url.searchParams.append(t,`gte.${n}`),this}lt(t,n){return this.url.searchParams.append(t,`lt.${n}`),this}lte(t,n){return this.url.searchParams.append(t,`lte.${n}`),this}like(t,n){return this.url.searchParams.append(t,`like.${n}`),this}likeAllOf(t,n){return this.url.searchParams.append(t,`like(all).{${n.join(",")}}`),this}likeAnyOf(t,n){return this.url.searchParams.append(t,`like(any).{${n.join(",")}}`),this}ilike(t,n){return this.url.searchParams.append(t,`ilike.${n}`),this}ilikeAllOf(t,n){return this.url.searchParams.append(t,`ilike(all).{${n.join(",")}}`),this}ilikeAnyOf(t,n){return this.url.searchParams.append(t,`ilike(any).{${n.join(",")}}`),this}is(t,n){return this.url.searchParams.append(t,`is.${n}`),this}in(t,n){const r=Array.from(new Set(n)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}contains(t,n){return typeof n=="string"?this.url.searchParams.append(t,`cs.${n}`):Array.isArray(n)?this.url.searchParams.append(t,`cs.{${n.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(n)}`),this}containedBy(t,n){return typeof n=="string"?this.url.searchParams.append(t,`cd.${n}`):Array.isArray(n)?this.url.searchParams.append(t,`cd.{${n.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(n)}`),this}rangeGt(t,n){return this.url.searchParams.append(t,`sr.${n}`),this}rangeGte(t,n){return this.url.searchParams.append(t,`nxl.${n}`),this}rangeLt(t,n){return this.url.searchParams.append(t,`sl.${n}`),this}rangeLte(t,n){return this.url.searchParams.append(t,`nxr.${n}`),this}rangeAdjacent(t,n){return this.url.searchParams.append(t,`adj.${n}`),this}overlaps(t,n){return typeof n=="string"?this.url.searchParams.append(t,`ov.${n}`):this.url.searchParams.append(t,`ov.{${n.join(",")}}`),this}textSearch(t,n,{config:r,type:i}={}){let s="";i==="plain"?s="pl":i==="phrase"?s="ph":i==="websearch"&&(s="w");const o=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${s}fts${o}.${n}`),this}match(t){return Object.entries(t).forEach(([n,r])=>{this.url.searchParams.append(n,`eq.${r}`)}),this}not(t,n,r){return this.url.searchParams.append(t,`not.${n}.${r}`),this}or(t,{foreignTable:n,referencedTable:r=n}={}){const i=r?`${r}.or`:"or";return this.url.searchParams.append(i,`(${t})`),this}filter(t,n,r){return this.url.searchParams.append(t,`${n}.${r}`),this}}class Yv{constructor(t,{headers:n={},schema:r,fetch:i}){this.url=t,this.headers=n,this.schema=r,this.fetch=i}select(t,{head:n=!1,count:r}={}){const i=n?"HEAD":"GET";let s=!1;const o=(t??"*").split("").map(l=>/\s/.test(l)&&!s?"":(l==='"'&&(s=!s),l)).join("");return this.url.searchParams.set("select",o),r&&(this.headers.Prefer=`count=${r}`),new ln({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(t,{count:n,defaultToNull:r=!0}={}){const i="POST",s=[];if(this.headers.Prefer&&s.push(this.headers.Prefer),n&&s.push(`count=${n}`),r||s.push("missing=default"),this.headers.Prefer=s.join(","),Array.isArray(t)){const o=t.reduce((l,a)=>l.concat(Object.keys(a)),[]);if(o.length>0){const l=[...new Set(o)].map(a=>`"${a}"`);this.url.searchParams.set("columns",l.join(","))}}return new ln({method:i,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}upsert(t,{onConflict:n,ignoreDuplicates:r=!1,count:i,defaultToNull:s=!0}={}){const o="POST",l=[`resolution=${r?"ignore":"merge"}-duplicates`];if(n!==void 0&&this.url.searchParams.set("on_conflict",n),this.headers.Prefer&&l.push(this.headers.Prefer),i&&l.push(`count=${i}`),s||l.push("missing=default"),this.headers.Prefer=l.join(","),Array.isArray(t)){const a=t.reduce((u,c)=>u.concat(Object.keys(c)),[]);if(a.length>0){const u=[...new Set(a)].map(c=>`"${c}"`);this.url.searchParams.set("columns",u.join(","))}}return new ln({method:o,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}update(t,{count:n}={}){const r="PATCH",i=[];return this.headers.Prefer&&i.push(this.headers.Prefer),n&&i.push(`count=${n}`),this.headers.Prefer=i.join(","),new ln({method:r,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}delete({count:t}={}){const n="DELETE",r=[];return t&&r.push(`count=${t}`),this.headers.Prefer&&r.unshift(this.headers.Prefer),this.headers.Prefer=r.join(","),new ln({method:n,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}}const Xv="1.15.2",Zv={"X-Client-Info":`postgrest-js/${Xv}`};class Gl{constructor(t,{headers:n={},schema:r,fetch:i}={}){this.url=t,this.headers=Object.assign(Object.assign({},Zv),n),this.schemaName=r,this.fetch=i}from(t){const n=new URL(`${this.url}/${t}`);return new Yv(n,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new Gl(this.url,{headers:this.headers,schema:t,fetch:this.fetch})}rpc(t,n={},{head:r=!1,get:i=!1,count:s}={}){let o;const l=new URL(`${this.url}/rpc/${t}`);let a;r||i?(o=r?"HEAD":"GET",Object.entries(n).filter(([c,d])=>d!==void 0).map(([c,d])=>[c,Array.isArray(d)?`{${d.join(",")}}`:`${d}`]).forEach(([c,d])=>{l.searchParams.append(c,d)})):(o="POST",a=n);const u=Object.assign({},this.headers);return s&&(u.Prefer=`count=${s}`),new ln({method:o,url:l,headers:u,schema:this.schemaName,body:a,fetch:this.fetch,allowEmpty:!1})}}const em="2.9.5",tm={"X-Client-Info":`realtime-js/${em}`},nm="1.0.0",nf=1e4,rm=1e3;var Pn;(function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"})(Pn||(Pn={}));var Se;(function(e){e.closed="closed",e.errored="errored",e.joined="joined",e.joining="joining",e.leaving="leaving"})(Se||(Se={}));var Me;(function(e){e.close="phx_close",e.error="phx_error",e.join="phx_join",e.reply="phx_reply",e.leave="phx_leave",e.access_token="access_token"})(Me||(Me={}));var Wo;(function(e){e.websocket="websocket"})(Wo||(Wo={}));var bt;(function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"})(bt||(bt={}));class rf{constructor(t,n){this.callback=t,this.timerCalc=n,this.timer=void 0,this.tries=0,this.callback=t,this.timerCalc=n}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}class im{constructor(){this.HEADER_LENGTH=1}decode(t,n){return t.constructor===ArrayBuffer?n(this._binaryDecode(t)):n(typeof t=="string"?JSON.parse(t):{})}_binaryDecode(t){const n=new DataView(t),r=new TextDecoder;return this._decodeBroadcast(t,n,r)}_decodeBroadcast(t,n,r){const i=n.getUint8(1),s=n.getUint8(2);let o=this.HEADER_LENGTH+2;const l=r.decode(t.slice(o,o+i));o=o+i;const a=r.decode(t.slice(o,o+s));o=o+s;const u=JSON.parse(r.decode(t.slice(o,t.byteLength)));return{ref:null,topic:l,event:a,payload:u}}}class Bs{constructor(t,n,r={},i=nf){this.channel=t,this.event=n,this.payload=r,this.timeout=i,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(t){this.timeout=t,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(t){this.payload=Object.assign(Object.assign({},this.payload),t)}receive(t,n){var r;return this._hasReceived(t)&&n((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:t,callback:n}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const t=n=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=n,this._matchReceive(n)};this.channel._on(this.refEvent,{},t),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(t,n){this.refEvent&&this.channel._trigger(this.refEvent,{status:t,response:n})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:t,response:n}){this.recHooks.filter(r=>r.status===t).forEach(r=>r.callback(n))}_hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}}var pu;(function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"})(pu||(pu={}));class fr{constructor(t,n){this.channel=t,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(n==null?void 0:n.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},i=>{const{onJoin:s,onLeave:o,onSync:l}=this.caller;this.joinRef=this.channel._joinRef(),this.state=fr.syncState(this.state,i,s,o),this.pendingDiffs.forEach(a=>{this.state=fr.syncDiff(this.state,a,s,o)}),this.pendingDiffs=[],l()}),this.channel._on(r.diff,{},i=>{const{onJoin:s,onLeave:o,onSync:l}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=fr.syncDiff(this.state,i,s,o),l())}),this.onJoin((i,s,o)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:s,newPresences:o})}),this.onLeave((i,s,o)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:s,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(t,n,r,i){const s=this.cloneDeep(t),o=this.transformState(n),l={},a={};return this.map(s,(u,c)=>{o[u]||(a[u]=c)}),this.map(o,(u,c)=>{const d=s[u];if(d){const h=c.map(_=>_.presence_ref),m=d.map(_=>_.presence_ref),g=c.filter(_=>m.indexOf(_.presence_ref)<0),y=d.filter(_=>h.indexOf(_.presence_ref)<0);g.length>0&&(l[u]=g),y.length>0&&(a[u]=y)}else l[u]=c}),this.syncDiff(s,{joins:l,leaves:a},r,i)}static syncDiff(t,n,r,i){const{joins:s,leaves:o}={joins:this.transformState(n.joins),leaves:this.transformState(n.leaves)};return r||(r=()=>{}),i||(i=()=>{}),this.map(s,(l,a)=>{var u;const c=(u=t[l])!==null&&u!==void 0?u:[];if(t[l]=this.cloneDeep(a),c.length>0){const d=t[l].map(m=>m.presence_ref),h=c.filter(m=>d.indexOf(m.presence_ref)<0);t[l].unshift(...h)}r(l,c,a)}),this.map(o,(l,a)=>{let u=t[l];if(!u)return;const c=a.map(d=>d.presence_ref);u=u.filter(d=>c.indexOf(d.presence_ref)<0),t[l]=u,i(l,u,a),u.length===0&&delete t[l]}),t}static map(t,n){return Object.getOwnPropertyNames(t).map(r=>n(r,t[r]))}static transformState(t){return t=this.cloneDeep(t),Object.getOwnPropertyNames(t).reduce((n,r)=>{const i=t[r];return"metas"in i?n[r]=i.metas.map(s=>(s.presence_ref=s.phx_ref,delete s.phx_ref,delete s.phx_ref_prev,s)):n[r]=i,n},{})}static cloneDeep(t){return JSON.parse(JSON.stringify(t))}onJoin(t){this.caller.onJoin=t}onLeave(t){this.caller.onLeave=t}onSync(t){this.caller.onSync=t}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var D;(function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"})(D||(D={}));const vu=(e,t,n={})=>{var r;const i=(r=n.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(t).reduce((s,o)=>(s[o]=sm(o,e,t,i),s),{})},sm=(e,t,n,r)=>{const i=t.find(l=>l.name===e),s=i==null?void 0:i.type,o=n[e];return s&&!r.includes(s)?sf(s,o):Ko(o)},sf=(e,t)=>{if(e.charAt(0)==="_"){const n=e.slice(1,e.length);return um(t,n)}switch(e){case D.bool:return om(t);case D.float4:case D.float8:case D.int2:case D.int4:case D.int8:case D.numeric:case D.oid:return lm(t);case D.json:case D.jsonb:return am(t);case D.timestamp:return cm(t);case D.abstime:case D.date:case D.daterange:case D.int4range:case D.int8range:case D.money:case D.reltime:case D.text:case D.time:case D.timestamptz:case D.timetz:case D.tsrange:case D.tstzrange:return Ko(t);default:return Ko(t)}},Ko=e=>e,om=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},lm=e=>{if(typeof e=="string"){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},am=e=>{if(typeof e=="string")try{return JSON.parse(e)}catch(t){return console.log(`JSON parse error: ${t}`),e}return e},um=(e,t)=>{if(typeof e!="string")return e;const n=e.length-1,r=e[n];if(e[0]==="{"&&r==="}"){let s;const o=e.slice(1,n);try{s=JSON.parse("["+o+"]")}catch{s=o?o.split(","):[]}return s.map(l=>sf(t,l))}return e},cm=e=>typeof e=="string"?e.replace(" ","T"):e;var mu;(function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"})(mu||(mu={}));var gu;(function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes"})(gu||(gu={}));var yu;(function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"})(yu||(yu={}));class Ql{constructor(t,n={config:{}},r){this.topic=t,this.params=n,this.socket=r,this.bindings={},this.state=Se.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=t.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""}},n.config),this.timeout=this.socket.timeout,this.joinPush=new Bs(this,Me.join,this.params,this.timeout),this.rejoinTimer=new rf(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=Se.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(i=>i.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=Se.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=Se.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=Se.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Me.reply,{},(i,s)=>{this._trigger(this._replyEventName(s),i)}),this.presence=new fr(this),this.broadcastEndpointURL=this._broadcastEndpointURL()}subscribe(t,n=this.timeout){var r,i;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{const{config:{broadcast:s,presence:o}}=this.params;this._onError(u=>t&&t("CHANNEL_ERROR",u)),this._onClose(()=>t&&t("CLOSED"));const l={},a={broadcast:s,presence:o,postgres_changes:(i=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(u=>u.filter))!==null&&i!==void 0?i:[]};this.socket.accessToken&&(l.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:a},l)),this.joinedOnce=!0,this._rejoin(n),this.joinPush.receive("ok",({postgres_changes:u})=>{var c;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),u===void 0){t&&t("SUBSCRIBED");return}else{const d=this.bindings.postgres_changes,h=(c=d==null?void 0:d.length)!==null&&c!==void 0?c:0,m=[];for(let g=0;g<h;g++){const y=d[g],{filter:{event:_,schema:p,table:f,filter:v}}=y,w=u&&u[g];if(w&&w.event===_&&w.schema===p&&w.table===f&&w.filter===v)m.push(Object.assign(Object.assign({},y),{id:w.id}));else{this.unsubscribe(),t&&t("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=m,t&&t("SUBSCRIBED");return}}).receive("error",u=>{t&&t("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{t&&t("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(t,n={}){return await this.send({type:"presence",event:"track",payload:t},n.timeout||this.timeout)}async untrack(t={}){return await this.send({type:"presence",event:"untrack"},t)}on(t,n,r){return this._on(t,n,r)}async send(t,n={}){var r,i;if(!this._canPush()&&t.type==="broadcast"){const{event:s,payload:o}=t,l={method:"POST",headers:{apikey:(r=this.socket.apiKey)!==null&&r!==void 0?r:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:s,payload:o}]})};try{return(await this._fetchWithTimeout(this.broadcastEndpointURL,l,(i=n.timeout)!==null&&i!==void 0?i:this.timeout)).ok?"ok":"error"}catch(a){return a.name==="AbortError"?"timed out":"error"}}else return new Promise(s=>{var o,l,a;const u=this._push(t.type,t,n.timeout||this.timeout);t.type==="broadcast"&&!(!((a=(l=(o=this.params)===null||o===void 0?void 0:o.config)===null||l===void 0?void 0:l.broadcast)===null||a===void 0)&&a.ack)&&s("ok"),u.receive("ok",()=>s("ok")),u.receive("error",()=>s("error")),u.receive("timeout",()=>s("timed out"))})}updateJoinPayload(t){this.joinPush.updatePayload(t)}unsubscribe(t=this.timeout){this.state=Se.leaving;const n=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Me.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{const i=new Bs(this,Me.leave,{},t);i.receive("ok",()=>{n(),r("ok")}).receive("timeout",()=>{n(),r("timed out")}).receive("error",()=>{r("error")}),i.send(),this._canPush()||i.trigger("ok",{})})}_broadcastEndpointURL(){let t=this.socket.endPoint;return t=t.replace(/^ws/i,"http"),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),t.replace(/\/+$/,"")+"/api/broadcast"}async _fetchWithTimeout(t,n,r){const i=new AbortController,s=setTimeout(()=>i.abort(),r),o=await this.socket.fetch(t,Object.assign(Object.assign({},n),{signal:i.signal}));return clearTimeout(s),o}_push(t,n,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${t}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new Bs(this,t,n,r);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(t,n,r){return n}_isMember(t){return this.topic===t}_joinRef(){return this.joinPush.ref}_trigger(t,n,r){var i,s;const o=t.toLocaleLowerCase(),{close:l,error:a,leave:u,join:c}=Me;if(r&&[l,a,u,c].indexOf(o)>=0&&r!==this._joinRef())return;let h=this._onMessage(o,n,r);if(n&&!h)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(m=>{var g,y,_;return((g=m.filter)===null||g===void 0?void 0:g.event)==="*"||((_=(y=m.filter)===null||y===void 0?void 0:y.event)===null||_===void 0?void 0:_.toLocaleLowerCase())===o}).map(m=>m.callback(h,r)):(s=this.bindings[o])===null||s===void 0||s.filter(m=>{var g,y,_,p,f,v;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in m){const w=m.id,k=(g=m.filter)===null||g===void 0?void 0:g.event;return w&&((y=n.ids)===null||y===void 0?void 0:y.includes(w))&&(k==="*"||(k==null?void 0:k.toLocaleLowerCase())===((_=n.data)===null||_===void 0?void 0:_.type.toLocaleLowerCase()))}else{const w=(f=(p=m==null?void 0:m.filter)===null||p===void 0?void 0:p.event)===null||f===void 0?void 0:f.toLocaleLowerCase();return w==="*"||w===((v=n==null?void 0:n.event)===null||v===void 0?void 0:v.toLocaleLowerCase())}else return m.type.toLocaleLowerCase()===o}).map(m=>{if(typeof h=="object"&&"ids"in h){const g=h.data,{schema:y,table:_,commit_timestamp:p,type:f,errors:v}=g;h=Object.assign(Object.assign({},{schema:y,table:_,commit_timestamp:p,eventType:f,new:{},old:{},errors:v}),this._getPayloadRecords(g))}m.callback(h,r)})}_isClosed(){return this.state===Se.closed}_isJoined(){return this.state===Se.joined}_isJoining(){return this.state===Se.joining}_isLeaving(){return this.state===Se.leaving}_replyEventName(t){return`chan_reply_${t}`}_on(t,n,r){const i=t.toLocaleLowerCase(),s={type:i,filter:n,callback:r};return this.bindings[i]?this.bindings[i].push(s):this.bindings[i]=[s],this}_off(t,n){const r=t.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(i=>{var s;return!(((s=i.type)===null||s===void 0?void 0:s.toLocaleLowerCase())===r&&Ql.isEqual(i.filter,n))}),this}static isEqual(t,n){if(Object.keys(t).length!==Object.keys(n).length)return!1;for(const r in t)if(t[r]!==n[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(t){this._on(Me.close,{},t)}_onError(t){this._on(Me.error,{},n=>t(n))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=Se.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const n={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(n.new=vu(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(n.old=vu(t.columns,t.old_record)),n}}const dm=()=>{},fm=typeof WebSocket<"u";class hm{constructor(t,n){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.headers=tm,this.params={},this.timeout=nf,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=dm,this.conn=null,this.sendBuffer=[],this.serializer=new im,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=s=>{let o;return s?o=s:typeof fetch>"u"?o=(...l)=>Nn(()=>Promise.resolve().then(()=>Fr),void 0,import.meta.url).then(({default:a})=>a(...l)):o=fetch,(...l)=>o(...l)},this.endPoint=`${t}/${Wo.websocket}`,n!=null&&n.transport?this.transport=n.transport:this.transport=null,n!=null&&n.params&&(this.params=n.params),n!=null&&n.headers&&(this.headers=Object.assign(Object.assign({},this.headers),n.headers)),n!=null&&n.timeout&&(this.timeout=n.timeout),n!=null&&n.logger&&(this.logger=n.logger),n!=null&&n.heartbeatIntervalMs&&(this.heartbeatIntervalMs=n.heartbeatIntervalMs);const i=(r=n==null?void 0:n.params)===null||r===void 0?void 0:r.apikey;i&&(this.accessToken=i,this.apiKey=i),this.reconnectAfterMs=n!=null&&n.reconnectAfterMs?n.reconnectAfterMs:s=>[1e3,2e3,5e3,1e4][s-1]||1e4,this.encode=n!=null&&n.encode?n.encode:(s,o)=>o(JSON.stringify(s)),this.decode=n!=null&&n.decode?n.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new rf(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(n==null?void 0:n.fetch)}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this._endPointURL(),void 0,{headers:this.headers});return}if(fm){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new pm(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Nn(()=>import("./browser-B3mZcEix.js").then(t=>t.b),[],import.meta.url).then(({default:t})=>{this.conn=new t(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(t,n){this.conn&&(this.conn.onclose=function(){},t?this.conn.close(t,n??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(t){const n=await t.unsubscribe();return this.channels.length===0&&this.disconnect(),n}async removeAllChannels(){const t=await Promise.all(this.channels.map(n=>n.unsubscribe()));return this.disconnect(),t}log(t,n,r){this.logger(t,n,r)}connectionState(){switch(this.conn&&this.conn.readyState){case Pn.connecting:return bt.Connecting;case Pn.open:return bt.Open;case Pn.closing:return bt.Closing;default:return bt.Closed}}isConnected(){return this.connectionState()===bt.Open}channel(t,n={config:{}}){const r=new Ql(`realtime:${t}`,n,this);return this.channels.push(r),r}push(t){const{topic:n,event:r,payload:i,ref:s}=t,o=()=>{this.encode(t,l=>{var a;(a=this.conn)===null||a===void 0||a.send(l)})};this.log("push",`${n} ${r} (${s})`,i),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(t){this.accessToken=t,this.channels.forEach(n=>{t&&n.updateJoinPayload({access_token:t}),n.joinedOnce&&n._isJoined()&&n._push(Me.access_token,{access_token:t})})}_makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}_leaveOpenTopic(t){let n=this.channels.find(r=>r.topic===t&&(r._isJoined()||r._isJoining()));n&&(this.log("transport",`leaving duplicate topic "${t}"`),n.unsubscribe())}_remove(t){this.channels=this.channels.filter(n=>n._joinRef()!==t._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=t=>this._onConnError(t),this.conn.onmessage=t=>this._onConnMessage(t),this.conn.onclose=t=>this._onConnClose(t))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:nm}))}_onConnMessage(t){this.decode(t.data,n=>{let{topic:r,event:i,payload:s,ref:o}=n;(o&&o===this.pendingHeartbeatRef||i===(s==null?void 0:s.type))&&(this.pendingHeartbeatRef=null),this.log("receive",`${s.status||""} ${r} ${i} ${o&&"("+o+")"||""}`,s),this.channels.filter(l=>l._isMember(r)).forEach(l=>l._trigger(i,s,o)),this.stateChangeCallbacks.message.forEach(l=>l(n))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(t=>t())}_onConnClose(t){this.log("transport","close",t),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(n=>n(t))}_onConnError(t){this.log("transport",t.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(n=>n(t))}_triggerChanError(){this.channels.forEach(t=>t._trigger(Me.error))}_appendParams(t,n){if(Object.keys(n).length===0)return t;const r=t.match(/\?/)?"&":"?",i=new URLSearchParams(n);return`${t}${r}${i}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}_sendHeartbeat(){var t;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(t=this.conn)===null||t===void 0||t.close(rm,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}}class pm{constructor(t,n,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=Pn.connecting,this.send=()=>{},this.url=null,this.url=t,this.close=r.close}}class Jl extends Error{constructor(t){super(t),this.__isStorageError=!0,this.name="StorageError"}}function ae(e){return typeof e=="object"&&e!==null&&"__isStorageError"in e}class vm extends Jl{constructor(t,n){super(t),this.name="StorageApiError",this.status=n}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class wu extends Jl{constructor(t,n){super(t),this.name="StorageUnknownError",this.originalError=n}}var mm=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};const of=e=>{let t;return e?t=e:typeof fetch>"u"?t=(...n)=>Nn(()=>Promise.resolve().then(()=>Fr),void 0,import.meta.url).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},gm=()=>mm(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Nn(()=>Promise.resolve().then(()=>Fr),void 0,import.meta.url)).Response:Response});var bn=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};const Vs=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),ym=(e,t)=>bn(void 0,void 0,void 0,function*(){const n=yield gm();e instanceof n?e.json().then(r=>{t(new vm(Vs(r),e.status||500))}).catch(r=>{t(new wu(Vs(r),r))}):t(new wu(Vs(e),e))}),wm=(e,t,n,r)=>{const i={method:e,headers:(t==null?void 0:t.headers)||{}};return e==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json"},t==null?void 0:t.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),n))};function fs(e,t,n,r,i,s){return bn(this,void 0,void 0,function*(){return new Promise((o,l)=>{e(n,wm(t,r,i,s)).then(a=>{if(!a.ok)throw a;return r!=null&&r.noResolveJson?a:a.json()}).then(a=>o(a)).catch(a=>ym(a,l))})})}function Go(e,t,n,r){return bn(this,void 0,void 0,function*(){return fs(e,"GET",t,n,r)})}function pt(e,t,n,r,i){return bn(this,void 0,void 0,function*(){return fs(e,"POST",t,r,i,n)})}function _m(e,t,n,r,i){return bn(this,void 0,void 0,function*(){return fs(e,"PUT",t,r,i,n)})}function lf(e,t,n,r,i){return bn(this,void 0,void 0,function*(){return fs(e,"DELETE",t,r,i,n)})}var Re=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};const Sm={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},_u={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class km{constructor(t,n={},r,i){this.url=t,this.headers=n,this.bucketId=r,this.fetch=of(i)}uploadOrUpdate(t,n,r,i){return Re(this,void 0,void 0,function*(){try{let s;const o=Object.assign(Object.assign({},_u),i),l=Object.assign(Object.assign({},this.headers),t==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&r instanceof Blob?(s=new FormData,s.append("cacheControl",o.cacheControl),s.append("",r)):typeof FormData<"u"&&r instanceof FormData?(s=r,s.append("cacheControl",o.cacheControl)):(s=r,l["cache-control"]=`max-age=${o.cacheControl}`,l["content-type"]=o.contentType);const a=this._removeEmptyFolders(n),u=this._getFinalPath(a),c=yield this.fetch(`${this.url}/object/${u}`,Object.assign({method:t,body:s,headers:l},o!=null&&o.duplex?{duplex:o.duplex}:{})),d=yield c.json();return c.ok?{data:{path:a,id:d.Id,fullPath:d.Key},error:null}:{data:null,error:d}}catch(s){if(ae(s))return{data:null,error:s};throw s}})}upload(t,n,r){return Re(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",t,n,r)})}uploadToSignedUrl(t,n,r,i){return Re(this,void 0,void 0,function*(){const s=this._removeEmptyFolders(t),o=this._getFinalPath(s),l=new URL(this.url+`/object/upload/sign/${o}`);l.searchParams.set("token",n);try{let a;const u=Object.assign({upsert:_u.upsert},i),c=Object.assign(Object.assign({},this.headers),{"x-upsert":String(u.upsert)});typeof Blob<"u"&&r instanceof Blob?(a=new FormData,a.append("cacheControl",u.cacheControl),a.append("",r)):typeof FormData<"u"&&r instanceof FormData?(a=r,a.append("cacheControl",u.cacheControl)):(a=r,c["cache-control"]=`max-age=${u.cacheControl}`,c["content-type"]=u.contentType);const d=yield this.fetch(l.toString(),{method:"PUT",body:a,headers:c}),h=yield d.json();return d.ok?{data:{path:s,fullPath:h.Key},error:null}:{data:null,error:h}}catch(a){if(ae(a))return{data:null,error:a};throw a}})}createSignedUploadUrl(t){return Re(this,void 0,void 0,function*(){try{let n=this._getFinalPath(t);const r=yield pt(this.fetch,`${this.url}/object/upload/sign/${n}`,{},{headers:this.headers}),i=new URL(this.url+r.url),s=i.searchParams.get("token");if(!s)throw new Jl("No token returned by API");return{data:{signedUrl:i.toString(),path:t,token:s},error:null}}catch(n){if(ae(n))return{data:null,error:n};throw n}})}update(t,n,r){return Re(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",t,n,r)})}move(t,n){return Re(this,void 0,void 0,function*(){try{return{data:yield pt(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:t,destinationKey:n},{headers:this.headers}),error:null}}catch(r){if(ae(r))return{data:null,error:r};throw r}})}copy(t,n){return Re(this,void 0,void 0,function*(){try{return{data:{path:(yield pt(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:t,destinationKey:n},{headers:this.headers})).Key},error:null}}catch(r){if(ae(r))return{data:null,error:r};throw r}})}createSignedUrl(t,n,r){return Re(this,void 0,void 0,function*(){try{let i=this._getFinalPath(t),s=yield pt(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:n},r!=null&&r.transform?{transform:r.transform}:{}),{headers:this.headers});const o=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return s={signedUrl:encodeURI(`${this.url}${s.signedURL}${o}`)},{data:s,error:null}}catch(i){if(ae(i))return{data:null,error:i};throw i}})}createSignedUrls(t,n,r){return Re(this,void 0,void 0,function*(){try{const i=yield pt(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:n,paths:t},{headers:this.headers}),s=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return{data:i.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${s}`):null})),error:null}}catch(i){if(ae(i))return{data:null,error:i};throw i}})}download(t,n){return Re(this,void 0,void 0,function*(){const i=typeof(n==null?void 0:n.transform)<"u"?"render/image/authenticated":"object",s=this.transformOptsToQueryString((n==null?void 0:n.transform)||{}),o=s?`?${s}`:"";try{const l=this._getFinalPath(t);return{data:yield(yield Go(this.fetch,`${this.url}/${i}/${l}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(l){if(ae(l))return{data:null,error:l};throw l}})}getPublicUrl(t,n){const r=this._getFinalPath(t),i=[],s=n!=null&&n.download?`download=${n.download===!0?"":n.download}`:"";s!==""&&i.push(s);const l=typeof(n==null?void 0:n.transform)<"u"?"render/image":"object",a=this.transformOptsToQueryString((n==null?void 0:n.transform)||{});a!==""&&i.push(a);let u=i.join("&");return u!==""&&(u=`?${u}`),{data:{publicUrl:encodeURI(`${this.url}/${l}/public/${r}${u}`)}}}remove(t){return Re(this,void 0,void 0,function*(){try{return{data:yield lf(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers}),error:null}}catch(n){if(ae(n))return{data:null,error:n};throw n}})}list(t,n,r){return Re(this,void 0,void 0,function*(){try{const i=Object.assign(Object.assign(Object.assign({},Sm),n),{prefix:t||""});return{data:yield pt(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},r),error:null}}catch(i){if(ae(i))return{data:null,error:i};throw i}})}_getFinalPath(t){return`${this.bucketId}/${t}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){const n=[];return t.width&&n.push(`width=${t.width}`),t.height&&n.push(`height=${t.height}`),t.resize&&n.push(`resize=${t.resize}`),t.format&&n.push(`format=${t.format}`),t.quality&&n.push(`quality=${t.quality}`),n.join("&")}}const Em="2.5.5",Cm={"X-Client-Info":`storage-js/${Em}`};var rn=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};class xm{constructor(t,n={},r){this.url=t,this.headers=Object.assign(Object.assign({},Cm),n),this.fetch=of(r)}listBuckets(){return rn(this,void 0,void 0,function*(){try{return{data:yield Go(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(t){if(ae(t))return{data:null,error:t};throw t}})}getBucket(t){return rn(this,void 0,void 0,function*(){try{return{data:yield Go(this.fetch,`${this.url}/bucket/${t}`,{headers:this.headers}),error:null}}catch(n){if(ae(n))return{data:null,error:n};throw n}})}createBucket(t,n={public:!1}){return rn(this,void 0,void 0,function*(){try{return{data:yield pt(this.fetch,`${this.url}/bucket`,{id:t,name:t,public:n.public,file_size_limit:n.fileSizeLimit,allowed_mime_types:n.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(ae(r))return{data:null,error:r};throw r}})}updateBucket(t,n){return rn(this,void 0,void 0,function*(){try{return{data:yield _m(this.fetch,`${this.url}/bucket/${t}`,{id:t,name:t,public:n.public,file_size_limit:n.fileSizeLimit,allowed_mime_types:n.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(ae(r))return{data:null,error:r};throw r}})}emptyBucket(t){return rn(this,void 0,void 0,function*(){try{return{data:yield pt(this.fetch,`${this.url}/bucket/${t}/empty`,{},{headers:this.headers}),error:null}}catch(n){if(ae(n))return{data:null,error:n};throw n}})}deleteBucket(t){return rn(this,void 0,void 0,function*(){try{return{data:yield lf(this.fetch,`${this.url}/bucket/${t}`,{},{headers:this.headers}),error:null}}catch(n){if(ae(n))return{data:null,error:n};throw n}})}}class Pm extends xm{constructor(t,n={},r){super(t,n,r)}from(t){return new km(this.url,this.headers,t,this.fetch)}}const Tm="2.43.4";let nr="";typeof Deno<"u"?nr="deno":typeof document<"u"?nr="web":typeof navigator<"u"&&navigator.product==="ReactNative"?nr="react-native":nr="node";const Om={"X-Client-Info":`supabase-js-${nr}/${Tm}`},Rm={headers:Om},jm={schema:"public"},Lm={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Im={};var $m=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};const Nm=e=>{let t;return e?t=e:typeof fetch>"u"?t=Kl:t=fetch,(...n)=>t(...n)},Am=()=>typeof Headers>"u"?tf:Headers,Um=(e,t,n)=>{const r=Nm(n),i=Am();return(s,o)=>$m(void 0,void 0,void 0,function*(){var l;const a=(l=yield t())!==null&&l!==void 0?l:e;let u=new i(o==null?void 0:o.headers);return u.has("apikey")||u.set("apikey",e),u.has("Authorization")||u.set("Authorization",`Bearer ${a}`),r(s,Object.assign(Object.assign({},o),{headers:u}))})};function Dm(e){return e.replace(/\/$/,"")}function zm(e,t){const{db:n,auth:r,realtime:i,global:s}=e,{db:o,auth:l,realtime:a,global:u}=t;return{db:Object.assign(Object.assign({},o),n),auth:Object.assign(Object.assign({},l),r),realtime:Object.assign(Object.assign({},a),i),global:Object.assign(Object.assign({},u),s)}}const af="2.64.2",Fm="http://localhost:9999",Mm="supabase.auth.token",bm={"X-Client-Info":`gotrue-js/${af}`},Su=10,Qo="X-Supabase-Api-Version",uf={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Bm(e){return Math.round(Date.now()/1e3)+e}function Vm(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=Math.random()*16|0;return(e=="x"?t:t&3|8).toString(16)})}const De=()=>typeof document<"u",Ut={tested:!1,writable:!1},hr=()=>{if(!De())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Ut.tested)return Ut.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),Ut.tested=!0,Ut.writable=!0}catch{Ut.tested=!0,Ut.writable=!1}return Ut.writable};function Hs(e){const t={},n=new URL(e);if(n.hash&&n.hash[0]==="#")try{new URLSearchParams(n.hash.substring(1)).forEach((i,s)=>{t[s]=i})}catch{}return n.searchParams.forEach((r,i)=>{t[i]=r}),t}const cf=e=>{let t;return e?t=e:typeof fetch>"u"?t=(...n)=>Nn(()=>Promise.resolve().then(()=>Fr),void 0,import.meta.url).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},Hm=e=>typeof e=="object"&&e!==null&&"status"in e&&"ok"in e&&"json"in e&&typeof e.json=="function",df=async(e,t,n)=>{await e.setItem(t,JSON.stringify(n))},si=async(e,t)=>{const n=await e.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return n}},Ws=async(e,t)=>{await e.removeItem(t)};function Wm(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let n="",r,i,s,o,l,a,u,c=0;for(e=e.replace("-","+").replace("_","/");c<e.length;)o=t.indexOf(e.charAt(c++)),l=t.indexOf(e.charAt(c++)),a=t.indexOf(e.charAt(c++)),u=t.indexOf(e.charAt(c++)),r=o<<2|l>>4,i=(l&15)<<4|a>>2,s=(a&3)<<6|u,n=n+String.fromCharCode(r),a!=64&&i!=0&&(n=n+String.fromCharCode(i)),u!=64&&s!=0&&(n=n+String.fromCharCode(s));return n}class hs{constructor(){this.promise=new hs.promiseConstructor((t,n)=>{this.resolve=t,this.reject=n})}}hs.promiseConstructor=Promise;function ku(e){const t=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,n=e.split(".");if(n.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!t.test(n[1]))throw new Error("JWT is not valid: payload is not in base64url format");const r=n[1];return JSON.parse(Wm(r))}async function Km(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}function Gm(e,t){return new Promise((r,i)=>{(async()=>{for(let s=0;s<1/0;s++)try{const o=await e(s);if(!t(s,null,o)){r(o);return}}catch(o){if(!t(s,o)){i(o);return}}})()})}function Qm(e){return("0"+e.toString(16)).substr(-2)}function Jm(){const t=new Uint32Array(56);if(typeof crypto>"u"){const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=n.length;let i="";for(let s=0;s<56;s++)i+=n.charAt(Math.floor(Math.random()*r));return i}return crypto.getRandomValues(t),Array.from(t,Qm).join("")}async function qm(e){const n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n),i=new Uint8Array(r);return Array.from(i).map(s=>String.fromCharCode(s)).join("")}function Ym(e){return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Xm(e){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."),e;const n=await qm(e);return Ym(n)}async function sn(e,t,n=!1){const r=Jm();let i=r;n&&(i+="/PASSWORD_RECOVERY"),await df(e,`${t}-code-verifier`,i);const s=await Xm(r);return[s,r===s?"plain":"s256"]}const Zm=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function eg(e){const t=e.headers.get(Qo);if(!t||!t.match(Zm))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}class ql extends Error{constructor(t,n,r){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=n,this.code=r}}function I(e){return typeof e=="object"&&e!==null&&"__isAuthError"in e}class tg extends ql{constructor(t,n,r){super(t,n,r),this.name="AuthApiError",this.status=n,this.code=r}}function ng(e){return I(e)&&e.name==="AuthApiError"}class ff extends ql{constructor(t,n){super(t),this.name="AuthUnknownError",this.originalError=n}}class tn extends ql{constructor(t,n,r,i){super(t,r,i),this.name=n,this.status=r}}class Dt extends tn{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}class Ks extends tn{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class oi extends tn{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class li extends tn{constructor(t,n=null){super(t,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=n}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class Eu extends tn{constructor(t,n=null){super(t,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=n}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class Jo extends tn{constructor(t,n){super(t,"AuthRetryableFetchError",n,void 0)}}function Gs(e){return I(e)&&e.name==="AuthRetryableFetchError"}class Cu extends tn{constructor(t,n,r){super(t,"AuthWeakPasswordError",n,"weak_password"),this.reasons=r}}var rg=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n};const Mt=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),ig=[502,503,504];async function xu(e){var t;if(!Hm(e))throw new Jo(Mt(e),0);if(ig.includes(e.status))throw new Jo(Mt(e),e.status);let n;try{n=await e.json()}catch(s){throw new ff(Mt(s),s)}let r;const i=eg(e);if(i&&i.getTime()>=uf["2024-01-01"].timestamp&&typeof n=="object"&&n&&typeof n.code=="string"?r=n.code:typeof n=="object"&&n&&typeof n.error_code=="string"&&(r=n.error_code),r){if(r==="weak_password")throw new Cu(Mt(n),e.status,((t=n.weak_password)===null||t===void 0?void 0:t.reasons)||[])}else if(typeof n=="object"&&n&&typeof n.weak_password=="object"&&n.weak_password&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.reasons.reduce((s,o)=>s&&typeof o=="string",!0))throw new Cu(Mt(n),e.status,n.weak_password.reasons);throw new tg(Mt(n),e.status||500,r)}const sg=(e,t,n,r)=>{const i={method:e,headers:(t==null?void 0:t.headers)||{}};return e==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},t==null?void 0:t.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),n))};async function N(e,t,n,r){var i;const s=Object.assign({},r==null?void 0:r.headers);s[Qo]||(s[Qo]=uf["2024-01-01"].name),r!=null&&r.jwt&&(s.Authorization=`Bearer ${r.jwt}`);const o=(i=r==null?void 0:r.query)!==null&&i!==void 0?i:{};r!=null&&r.redirectTo&&(o.redirect_to=r.redirectTo);const l=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",a=await og(e,t,n+l,{headers:s,noResolveJson:r==null?void 0:r.noResolveJson},{},r==null?void 0:r.body);return r!=null&&r.xform?r==null?void 0:r.xform(a):{data:Object.assign({},a),error:null}}async function og(e,t,n,r,i,s){const o=sg(t,r,i,s);let l;try{l=await e(n,Object.assign({},o))}catch(a){throw console.error(a),new Jo(Mt(a),0)}if(l.ok||await xu(l),r!=null&&r.noResolveJson)return l;try{return await l.json()}catch(a){await xu(a)}}function dt(e){var t;let n=null;cg(e)&&(n=Object.assign({},e),e.expires_at||(n.expires_at=Bm(e.expires_in)));const r=(t=e.user)!==null&&t!==void 0?t:e;return{data:{session:n,user:r},error:null}}function Pu(e){const t=dt(e);return!t.error&&e.weak_password&&typeof e.weak_password=="object"&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&typeof e.weak_password.message=="string"&&e.weak_password.reasons.reduce((n,r)=>n&&typeof r=="string",!0)&&(t.data.weak_password=e.weak_password),t}function gt(e){var t;return{data:{user:(t=e.user)!==null&&t!==void 0?t:e},error:null}}function lg(e){return{data:e,error:null}}function ag(e){const{action_link:t,email_otp:n,hashed_token:r,redirect_to:i,verification_type:s}=e,o=rg(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),l={action_link:t,email_otp:n,hashed_token:r,redirect_to:i,verification_type:s},a=Object.assign({},o);return{data:{properties:l,user:a},error:null}}function ug(e){return e}function cg(e){return e.access_token&&e.refresh_token&&e.expires_in}var dg=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n};class fg{constructor({url:t="",headers:n={},fetch:r}){this.url=t,this.headers=n,this.fetch=cf(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(t,n="global"){try{return await N(this.fetch,"POST",`${this.url}/logout?scope=${n}`,{headers:this.headers,jwt:t,noResolveJson:!0}),{data:null,error:null}}catch(r){if(I(r))return{data:null,error:r};throw r}}async inviteUserByEmail(t,n={}){try{return await N(this.fetch,"POST",`${this.url}/invite`,{body:{email:t,data:n.data},headers:this.headers,redirectTo:n.redirectTo,xform:gt})}catch(r){if(I(r))return{data:{user:null},error:r};throw r}}async generateLink(t){try{const{options:n}=t,r=dg(t,["options"]),i=Object.assign(Object.assign({},r),n);return"newEmail"in r&&(i.new_email=r==null?void 0:r.newEmail,delete i.newEmail),await N(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:ag,redirectTo:n==null?void 0:n.redirectTo})}catch(n){if(I(n))return{data:{properties:null,user:null},error:n};throw n}}async createUser(t){try{return await N(this.fetch,"POST",`${this.url}/admin/users`,{body:t,headers:this.headers,xform:gt})}catch(n){if(I(n))return{data:{user:null},error:n};throw n}}async listUsers(t){var n,r,i,s,o,l,a;try{const u={nextPage:null,lastPage:0,total:0},c=await N(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(n=t==null?void 0:t.page)===null||n===void 0?void 0:n.toString())!==null&&r!==void 0?r:"",per_page:(s=(i=t==null?void 0:t.perPage)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""},xform:ug});if(c.error)throw c.error;const d=await c.json(),h=(o=c.headers.get("x-total-count"))!==null&&o!==void 0?o:0,m=(a=(l=c.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&a!==void 0?a:[];return m.length>0&&(m.forEach(g=>{const y=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(g.split(";")[1].split("=")[1]);u[`${_}Page`]=y}),u.total=parseInt(h)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(I(u))return{data:{users:[]},error:u};throw u}}async getUserById(t){try{return await N(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:gt})}catch(n){if(I(n))return{data:{user:null},error:n};throw n}}async updateUserById(t,n){try{return await N(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:n,headers:this.headers,xform:gt})}catch(r){if(I(r))return{data:{user:null},error:r};throw r}}async deleteUser(t,n=!1){try{return await N(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:n},xform:gt})}catch(r){if(I(r))return{data:{user:null},error:r};throw r}}async _listFactors(t){try{const{data:n,error:r}=await N(this.fetch,"GET",`${this.url}/admin/users/${t.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:n,error:r}}catch(n){if(I(n))return{data:null,error:n};throw n}}async _deleteFactor(t){try{return{data:await N(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(n){if(I(n))return{data:null,error:n};throw n}}}const hg={getItem:e=>hr()?globalThis.localStorage.getItem(e):null,setItem:(e,t)=>{hr()&&globalThis.localStorage.setItem(e,t)},removeItem:e=>{hr()&&globalThis.localStorage.removeItem(e)}};function Tu(e={}){return{getItem:t=>e[t]||null,setItem:(t,n)=>{e[t]=n},removeItem:t=>{delete e[t]}}}function pg(){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)}}const on={debug:!!(globalThis&&hr()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class hf extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class vg extends hf{}async function mg(e,t,n){on.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);const r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort(),on.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t),await globalThis.navigator.locks.request(e,t===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async i=>{if(i){on.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,i.name);try{return await n()}finally{on.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",e,i.name)}}else{if(t===0)throw on.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new vg(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(on.debug)try{const s=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(s,null,"  "))}catch(s){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",s)}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 n()}})}pg();const gg={url:Fm,storageKey:Mm,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:bm,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},Yn=30*1e3,Ou=3;async function Ru(e,t,n){return await n()}class $r{constructor(t){var n,r;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=$r.nextInstanceID,$r.nextInstanceID+=1,this.instanceID>0&&De()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");const i=Object.assign(Object.assign({},gg),t);if(this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.persistSession=i.persistSession,this.storageKey=i.storageKey,this.autoRefreshToken=i.autoRefreshToken,this.admin=new fg({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=cf(i.fetch),this.lock=i.lock||Ru,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:De()&&(!((n=globalThis==null?void 0:globalThis.navigator)===null||n===void 0)&&n.locks)?this.lock=mg:this.lock=Ru,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)},this.persistSession?i.storage?this.storage=i.storage:hr()?this.storage=hg:(this.memoryStorage={},this.storage=Tu(this.memoryStorage)):(this.memoryStorage={},this.storage=Tu(this.memoryStorage)),De()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(s){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",s)}(r=this.broadcastChannel)===null||r===void 0||r.addEventListener("message",async s=>{this._debug("received broadcast notification from other tab or client",s),await this._notifyAllSubscribers(s.data.event,s.data.session,!1)})}this.initialize()}_debug(...t){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${af}) ${new Date().toISOString()}`,...t),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(){try{const t=De()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",t),t||this.detectSessionInUrl&&this._isImplicitGrantFlow()){const{data:n,error:r}=await this._getSessionFromURL(t);if(r)return this._debug("#_initialize()","error detecting session from URL",r),(r==null?void 0:r.message)==="Identity is already linked"||(r==null?void 0:r.message)==="Identity is already linked to another user"?{error:r}:(await this._removeSession(),{error:r});const{session:i,redirectType:s}=n;return this._debug("#_initialize()","detected session in URL",i,"redirect type",s),await this._saveSession(i),setTimeout(async()=>{s==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return I(t)?{error:t}:{error:new ff("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var n,r,i;try{await this._removeSession();const s=await N(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(n=t==null?void 0:t.options)===null||n===void 0?void 0:n.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(i=t==null?void 0:t.options)===null||i===void 0?void 0:i.captchaToken}},xform:dt}),{data:o,error:l}=s;if(l||!o)return{data:{user:null,session:null},error:l};const a=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",a)),{data:{user:u,session:a},error:null}}catch(s){if(I(s))return{data:{user:null,session:null},error:s};throw s}}async signUp(t){var n,r,i;try{await this._removeSession();let s;if("email"in t){const{email:c,password:d,options:h}=t;let m=null,g=null;this.flowType==="pkce"&&([m,g]=await sn(this.storage,this.storageKey)),s=await N(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:h==null?void 0:h.emailRedirectTo,body:{email:c,password:d,data:(n=h==null?void 0:h.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:h==null?void 0:h.captchaToken},code_challenge:m,code_challenge_method:g},xform:dt})}else if("phone"in t){const{phone:c,password:d,options:h}=t;s=await N(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:d,data:(r=h==null?void 0:h.data)!==null&&r!==void 0?r:{},channel:(i=h==null?void 0:h.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:h==null?void 0:h.captchaToken}},xform:dt})}else throw new oi("You must provide either an email or phone number and a password");const{data:o,error:l}=s;if(l||!o)return{data:{user:null,session:null},error:l};const a=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",a)),{data:{user:u,session:a},error:null}}catch(s){if(I(s))return{data:{user:null,session:null},error:s};throw s}}async signInWithPassword(t){try{await this._removeSession();let n;if("email"in t){const{email:s,password:o,options:l}=t;n=await N(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:o,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:Pu})}else if("phone"in t){const{phone:s,password:o,options:l}=t;n=await N(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:o,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:Pu})}else throw new oi("You must provide either an email or phone number and a password");const{data:r,error:i}=n;return i?{data:{user:null,session:null},error:i}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new Ks}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:i})}catch(n){if(I(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithOAuth(t){var n,r,i,s;return await this._removeSession(),await this._handleProviderSignIn(t.provider,{redirectTo:(n=t.options)===null||n===void 0?void 0:n.redirectTo,scopes:(r=t.options)===null||r===void 0?void 0:r.scopes,queryParams:(i=t.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(s=t.options)===null||s===void 0?void 0:s.skipBrowserRedirect})}async exchangeCodeForSession(t){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(t))}async _exchangeCodeForSession(t){const n=await si(this.storage,`${this.storageKey}-code-verifier`),[r,i]=(n??"").split("/"),{data:s,error:o}=await N(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:r},xform:dt});return await Ws(this.storage,`${this.storageKey}-code-verifier`),o?{data:{user:null,session:null,redirectType:null},error:o}:!s||!s.session||!s.user?{data:{user:null,session:null,redirectType:null},error:new Ks}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign(Object.assign({},s),{redirectType:i??null}),error:o})}async signInWithIdToken(t){await this._removeSession();try{const{options:n,provider:r,token:i,access_token:s,nonce:o}=t,l=await N(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:i,access_token:s,nonce:o,gotrue_meta_security:{captcha_token:n==null?void 0:n.captchaToken}},xform:dt}),{data:a,error:u}=l;return u?{data:{user:null,session:null},error:u}:!a||!a.session||!a.user?{data:{user:null,session:null},error:new Ks}:(a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),{data:a,error:u})}catch(n){if(I(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithOtp(t){var n,r,i,s,o;try{if(await this._removeSession(),"email"in t){const{email:l,options:a}=t;let u=null,c=null;this.flowType==="pkce"&&([u,c]=await sn(this.storage,this.storageKey));const{error:d}=await N(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:l,data:(n=a==null?void 0:a.data)!==null&&n!==void 0?n:{},create_user:(r=a==null?void 0:a.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken},code_challenge:u,code_challenge_method:c},redirectTo:a==null?void 0:a.emailRedirectTo});return{data:{user:null,session:null},error:d}}if("phone"in t){const{phone:l,options:a}=t,{data:u,error:c}=await N(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:l,data:(i=a==null?void 0:a.data)!==null&&i!==void 0?i:{},create_user:(s=a==null?void 0:a.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken},channel:(o=a==null?void 0:a.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:u==null?void 0:u.message_id},error:c}}throw new oi("You must provide either an email or phone number.")}catch(l){if(I(l))return{data:{user:null,session:null},error:l};throw l}}async verifyOtp(t){var n,r;try{t.type!=="email_change"&&t.type!=="phone_change"&&await this._removeSession();let i,s;"options"in t&&(i=(n=t.options)===null||n===void 0?void 0:n.redirectTo,s=(r=t.options)===null||r===void 0?void 0:r.captchaToken);const{data:o,error:l}=await N(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:s}}),redirectTo:i,xform:dt});if(l)throw l;if(!o)throw new Error("An error occurred on token verification.");const a=o.session,u=o.user;return a!=null&&a.access_token&&(await this._saveSession(a),await this._notifyAllSubscribers(t.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",a)),{data:{user:u,session:a},error:null}}catch(i){if(I(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(t){var n,r,i;try{await this._removeSession();let s=null,o=null;return this.flowType==="pkce"&&([s,o]=await sn(this.storage,this.storageKey)),await N(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in t?{provider_id:t.providerId}:null),"domain"in t?{domain:t.domain}:null),{redirect_to:(r=(n=t.options)===null||n===void 0?void 0:n.redirectTo)!==null&&r!==void 0?r:void 0}),!((i=t==null?void 0:t.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:t.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:s,code_challenge_method:o}),headers:this.headers,xform:lg})}catch(s){if(I(s))return{data:null,error:s};throw s}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async t=>{const{data:{session:n},error:r}=t;if(r)throw r;if(!n)throw new Dt;const{error:i}=await N(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:n.access_token});return{data:{user:null,session:null},error:i}})}catch(t){if(I(t))return{data:{user:null,session:null},error:t};throw t}}async resend(t){try{t.type!="email_change"&&t.type!="phone_change"&&await this._removeSession();const n=`${this.url}/resend`;if("email"in t){const{email:r,type:i,options:s}=t,{error:o}=await N(this.fetch,"POST",n,{headers:this.headers,body:{email:r,type:i,gotrue_meta_security:{captcha_token:s==null?void 0:s.captchaToken}},redirectTo:s==null?void 0:s.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in t){const{phone:r,type:i,options:s}=t,{data:o,error:l}=await N(this.fetch,"POST",n,{headers:this.headers,body:{phone:r,type:i,gotrue_meta_security:{captcha_token:s==null?void 0:s.captchaToken}}});return{data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:l}}throw new oi("You must provide either an email or phone number and a type")}catch(n){if(I(n))return{data:{user:null,session:null},error:n};throw n}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async n=>n))}async _acquireLock(t,n){this._debug("#_acquireLock","begin",t);try{if(this.lockAcquired){const r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await r,await n()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,t,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const r=n();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){const i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(t){this._debug("#_useSession","begin");try{const n=await this.__loadSession();return await t(n)}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 t=null;const n=await si(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",n),n!==null&&(this._isValidSession(n)?t=n:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!t)return{data:{session:null},error:null};const r=t.expires_at?t.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",t.expires_at),!r){if(this.storage.isServer){const o=this.suppressGetSessionWarning;t=new Proxy(t,{get(a,u,c){return!o&&u==="user"&&console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),Reflect.get(a,u,c)}})}return{data:{session:t},error:null}}const{session:i,error:s}=await this._callRefreshToken(t.refresh_token);return s?{data:{session:null},error:s}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(t){return t?await this._getUser(t):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(t){try{return t?await N(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:gt}):await this._useSession(async n=>{var r,i,s;const{data:o,error:l}=n;if(l)throw l;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Dt}:await N(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(s=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&s!==void 0?s:void 0,xform:gt})})}catch(n){if(I(n))return{data:{user:null},error:n};throw n}}async updateUser(t,n={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(t,n))}async _updateUser(t,n={}){try{return await this._useSession(async r=>{const{data:i,error:s}=r;if(s)throw s;if(!i.session)throw new Dt;const o=i.session;let l=null,a=null;this.flowType==="pkce"&&t.email!=null&&([l,a]=await sn(this.storage,this.storageKey));const{data:u,error:c}=await N(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:n==null?void 0:n.emailRedirectTo,body:Object.assign(Object.assign({},t),{code_challenge:l,code_challenge_method:a}),jwt:o.access_token,xform:gt});if(c)throw c;return o.user=u.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(r){if(I(r))return{data:{user:null},error:r};throw r}}_decodeJWT(t){return ku(t)}async setSession(t){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(t))}async _setSession(t){try{if(!t.access_token||!t.refresh_token)throw new Dt;const n=Date.now()/1e3;let r=n,i=!0,s=null;const o=ku(t.access_token);if(o.exp&&(r=o.exp,i=r<=n),i){const{session:l,error:a}=await this._callRefreshToken(t.refresh_token);if(a)return{data:{user:null,session:null},error:a};if(!l)return{data:{user:null,session:null},error:null};s=l}else{const{data:l,error:a}=await this._getUser(t.access_token);if(a)throw a;s={access_token:t.access_token,refresh_token:t.refresh_token,user:l.user,token_type:"bearer",expires_in:r-n,expires_at:r},await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)}return{data:{user:s.user,session:s},error:null}}catch(n){if(I(n))return{data:{session:null,user:null},error:n};throw n}}async refreshSession(t){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(t))}async _refreshSession(t){try{return await this._useSession(async n=>{var r;if(!t){const{data:o,error:l}=n;if(l)throw l;t=(r=o.session)!==null&&r!==void 0?r:void 0}if(!(t!=null&&t.refresh_token))throw new Dt;const{session:i,error:s}=await this._callRefreshToken(t.refresh_token);return s?{data:{user:null,session:null},error:s}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(n){if(I(n))return{data:{user:null,session:null},error:n};throw n}}async _getSessionFromURL(t){try{if(!De())throw new li("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new li("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!t)throw new Eu("Not a valid PKCE flow url.");const n=Hs(window.location.href);if(t){if(!n.code)throw new Eu("No code detected.");const{data:f,error:v}=await this._exchangeCodeForSession(n.code);if(v)throw v;const w=new URL(window.location.href);return w.searchParams.delete("code"),window.history.replaceState(window.history.state,"",w.toString()),{data:{session:f.session,redirectType:null},error:null}}if(n.error||n.error_description||n.error_code)throw new li(n.error_description||"Error in URL with unspecified error_description",{error:n.error||"unspecified_error",code:n.error_code||"unspecified_code"});const{provider_token:r,provider_refresh_token:i,access_token:s,refresh_token:o,expires_in:l,expires_at:a,token_type:u}=n;if(!s||!l||!o||!u)throw new li("No session defined in URL");const c=Math.round(Date.now()/1e3),d=parseInt(l);let h=c+d;a&&(h=parseInt(a));const m=h-c;m*1e3<=Yn&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${d}s`);const g=h-d;c-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,h,c):c-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",g,h,c);const{data:y,error:_}=await this._getUser(s);if(_)throw _;const p={provider_token:r,provider_refresh_token:i,access_token:s,expires_in:d,expires_at:h,refresh_token:o,token_type:u,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:p,redirectType:n.type},error:null}}catch(n){if(I(n))return{data:{session:null,redirectType:null},error:n};throw n}}_isImplicitGrantFlow(){const t=Hs(window.location.href);return!!(De()&&(t.access_token||t.error_description))}async _isPKCEFlow(){const t=Hs(window.location.href),n=await si(this.storage,`${this.storageKey}-code-verifier`);return!!(t.code&&n)}async signOut(t={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(t))}async _signOut({scope:t}={scope:"global"}){return await this._useSession(async n=>{var r;const{data:i,error:s}=n;if(s)return{error:s};const o=(r=i.session)===null||r===void 0?void 0:r.access_token;if(o){const{error:l}=await this.admin.signOut(o,t);if(l&&!(ng(l)&&(l.status===404||l.status===401||l.status===403)))return{error:l}}return t!=="others"&&(await this._removeSession(),await Ws(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(t){const n=Vm(),r={id:n,callback:t,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",n),this.stateChangeEmitters.delete(n)}};return this._debug("#onAuthStateChange()","registered callback with id",n),this.stateChangeEmitters.set(n,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(n)})))(),{data:{subscription:r}}}async _emitInitialSession(t){return await this._useSession(async n=>{var r,i;try{const{data:{session:s},error:o}=n;if(o)throw o;await((r=this.stateChangeEmitters.get(t))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",t,"session",s)}catch(s){await((i=this.stateChangeEmitters.get(t))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",t,"error",s),console.error(s)}})}async resetPasswordForEmail(t,n={}){let r=null,i=null;this.flowType==="pkce"&&([r,i]=await sn(this.storage,this.storageKey,!0));try{return await N(this.fetch,"POST",`${this.url}/recover`,{body:{email:t,code_challenge:r,code_challenge_method:i,gotrue_meta_security:{captcha_token:n.captchaToken}},headers:this.headers,redirectTo:n.redirectTo})}catch(s){if(I(s))return{data:null,error:s};throw s}}async getUserIdentities(){var t;try{const{data:n,error:r}=await this.getUser();if(r)throw r;return{data:{identities:(t=n.user.identities)!==null&&t!==void 0?t:[]},error:null}}catch(n){if(I(n))return{data:null,error:n};throw n}}async linkIdentity(t){var n;try{const{data:r,error:i}=await this._useSession(async s=>{var o,l,a,u,c;const{data:d,error:h}=s;if(h)throw h;const m=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,t.provider,{redirectTo:(o=t.options)===null||o===void 0?void 0:o.redirectTo,scopes:(l=t.options)===null||l===void 0?void 0:l.scopes,queryParams:(a=t.options)===null||a===void 0?void 0:a.queryParams,skipBrowserRedirect:!0});return await N(this.fetch,"GET",m,{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(i)throw i;return De()&&!(!((n=t.options)===null||n===void 0)&&n.skipBrowserRedirect)&&window.location.assign(r==null?void 0:r.url),{data:{provider:t.provider,url:r==null?void 0:r.url},error:null}}catch(r){if(I(r))return{data:{provider:t.provider,url:null},error:r};throw r}}async unlinkIdentity(t){try{return await this._useSession(async n=>{var r,i;const{data:s,error:o}=n;if(o)throw o;return await N(this.fetch,"DELETE",`${this.url}/user/identities/${t.identity_id}`,{headers:this.headers,jwt:(i=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&i!==void 0?i:void 0})})}catch(n){if(I(n))return{data:null,error:n};throw n}}async _refreshAccessToken(t){const n=`#_refreshAccessToken(${t.substring(0,5)}...)`;this._debug(n,"begin");try{const r=Date.now();return await Gm(async i=>(i>0&&await Km(200*Math.pow(2,i-1)),this._debug(n,"refreshing attempt",i),await N(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:dt})),(i,s)=>{const o=200*Math.pow(2,i);return s&&Gs(s)&&Date.now()+o-r<Yn})}catch(r){if(this._debug(n,"error",r),I(r))return{data:{session:null,user:null},error:r};throw r}finally{this._debug(n,"end")}}_isValidSession(t){return typeof t=="object"&&t!==null&&"access_token"in t&&"refresh_token"in t&&"expires_at"in t}async _handleProviderSignIn(t,n){const r=await this._getUrlForProvider(`${this.url}/authorize`,t,{redirectTo:n.redirectTo,scopes:n.scopes,queryParams:n.queryParams});return this._debug("#_handleProviderSignIn()","provider",t,"options",n,"url",r),De()&&!n.skipBrowserRedirect&&window.location.assign(r),{data:{provider:t,url:r},error:null}}async _recoverAndRefresh(){var t;const n="#_recoverAndRefresh()";this._debug(n,"begin");try{const r=await si(this.storage,this.storageKey);if(this._debug(n,"session from storage",r),!this._isValidSession(r)){this._debug(n,"session is not valid"),r!==null&&await this._removeSession();return}const i=Math.round(Date.now()/1e3),s=((t=r.expires_at)!==null&&t!==void 0?t:1/0)<i+Su;if(this._debug(n,`session has${s?"":" not"} expired with margin of ${Su}s`),s){if(this.autoRefreshToken&&r.refresh_token){const{error:o}=await this._callRefreshToken(r.refresh_token);o&&(console.error(o),Gs(o)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",r)}catch(r){this._debug(n,"error",r),console.error(r);return}finally{this._debug(n,"end")}}async _callRefreshToken(t){var n,r;if(!t)throw new Dt;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const i=`#_callRefreshToken(${t.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new hs;const{data:s,error:o}=await this._refreshAccessToken(t);if(o)throw o;if(!s.session)throw new Dt;await this._saveSession(s.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",s.session);const l={session:s.session,error:null};return this.refreshingDeferred.resolve(l),l}catch(s){if(this._debug(i,"error",s),I(s)){const o={session:null,error:s};return Gs(s)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(n=this.refreshingDeferred)===null||n===void 0||n.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(s),s}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(t,n,r=!0){const i=`#_notifyAllSubscribers(${t})`;this._debug(i,"begin",n,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:t,session:n});const s=[],o=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(t,n)}catch(a){s.push(a)}});if(await Promise.all(o),s.length>0){for(let l=0;l<s.length;l+=1)console.error(s[l]);throw s[0]}}finally{this._debug(i,"end")}}async _saveSession(t){this._debug("#_saveSession()",t),this.suppressGetSessionWarning=!0,await df(this.storage,this.storageKey,t)}async _removeSession(){this._debug("#_removeSession()"),await Ws(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const t=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{t&&De()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",t)}catch(n){console.error("removing visibilitychange callback failed",n)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const t=setInterval(()=>this._autoRefreshTokenTick(),Yn);this.autoRefreshTicker=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const t=this.autoRefreshTicker;this.autoRefreshTicker=null,t&&clearInterval(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const t=Date.now();try{return await this._useSession(async n=>{const{data:{session:r}}=n;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const i=Math.floor((r.expires_at*1e3-t)/Yn);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Yn}ms, refresh threshold is ${Ou} ticks`),i<=Ou&&await this._callRefreshToken(r.refresh_token)})}catch(n){console.error("Auto refresh tick failed with error. This is likely a transient error.",n)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(t){if(t.isAcquireTimeout||t instanceof hf)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!De()||!(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(t){console.error("_handleVisibilityChange",t)}}async _onVisibilityChanged(t){const n=`#_onVisibilityChanged(${t})`;this._debug(n,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),t||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(n,"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(t,n,r){const i=[`provider=${encodeURIComponent(n)}`];if(r!=null&&r.redirectTo&&i.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r!=null&&r.scopes&&i.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){const[s,o]=await sn(this.storage,this.storageKey),l=new URLSearchParams({code_challenge:`${encodeURIComponent(s)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(l.toString())}if(r!=null&&r.queryParams){const s=new URLSearchParams(r.queryParams);i.push(s.toString())}return r!=null&&r.skipBrowserRedirect&&i.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${t}?${i.join("&")}`}async _unenroll(t){try{return await this._useSession(async n=>{var r;const{data:i,error:s}=n;return s?{data:null,error:s}:await N(this.fetch,"DELETE",`${this.url}/factors/${t.factorId}`,{headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token})})}catch(n){if(I(n))return{data:null,error:n};throw n}}async _enroll(t){try{return await this._useSession(async n=>{var r,i;const{data:s,error:o}=n;if(o)return{data:null,error:o};const{data:l,error:a}=await N(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:t.friendlyName,factor_type:t.factorType,issuer:t.issuer},headers:this.headers,jwt:(r=s==null?void 0:s.session)===null||r===void 0?void 0:r.access_token});return a?{data:null,error:a}:(!((i=l==null?void 0:l.totp)===null||i===void 0)&&i.qr_code&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),{data:l,error:null})})}catch(n){if(I(n))return{data:null,error:n};throw n}}async _verify(t){return this._acquireLock(-1,async()=>{try{return await this._useSession(async n=>{var r;const{data:i,error:s}=n;if(s)return{data:null,error:s};const{data:o,error:l}=await N(this.fetch,"POST",`${this.url}/factors/${t.factorId}/verify`,{body:{code:t.code,challenge_id:t.challengeId},headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token});return l?{data:null,error:l}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:l})})}catch(n){if(I(n))return{data:null,error:n};throw n}})}async _challenge(t){return this._acquireLock(-1,async()=>{try{return await this._useSession(async n=>{var r;const{data:i,error:s}=n;return s?{data:null,error:s}:await N(this.fetch,"POST",`${this.url}/factors/${t.factorId}/challenge`,{headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token})})}catch(n){if(I(n))return{data:null,error:n};throw n}})}async _challengeAndVerify(t){const{data:n,error:r}=await this._challenge({factorId:t.factorId});return r?{data:null,error:r}:await this._verify({factorId:t.factorId,challengeId:n.id,code:t.code})}async _listFactors(){const{data:{user:t},error:n}=await this.getUser();if(n)return{data:null,error:n};const r=(t==null?void 0:t.factors)||[],i=r.filter(s=>s.factor_type==="totp"&&s.status==="verified");return{data:{all:r,totp:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async t=>{var n,r;const{data:{session:i},error:s}=t;if(s)return{data:null,error:s};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const o=this._decodeJWT(i.access_token);let l=null;o.aal&&(l=o.aal);let a=l;((r=(n=i.user.factors)===null||n===void 0?void 0:n.filter(d=>d.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(a="aal2");const c=o.amr||[];return{data:{currentLevel:l,nextLevel:a,currentAuthenticationMethods:c},error:null}}))}}$r.nextInstanceID=0;const yg=$r;class wg extends yg{constructor(t){super(t)}}var _g=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};class Sg{constructor(t,n,r){var i,s,o;if(this.supabaseUrl=t,this.supabaseKey=n,!t)throw new Error("supabaseUrl is required.");if(!n)throw new Error("supabaseKey is required.");const l=Dm(t);this.realtimeUrl=`${l}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${l}/auth/v1`,this.storageUrl=`${l}/storage/v1`,this.functionsUrl=`${l}/functions/v1`;const a=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,u={db:jm,realtime:Im,auth:Object.assign(Object.assign({},Lm),{storageKey:a}),global:Rm},c=zm(r??{},u);this.storageKey=(i=c.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(s=c.global.headers)!==null&&s!==void 0?s:{},this.auth=this._initSupabaseAuthClient((o=c.auth)!==null&&o!==void 0?o:{},this.headers,c.global.fetch),this.fetch=Um(n,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},c.realtime)),this.rest=new Gl(`${l}/rest/v1`,{headers:this.headers,schema:c.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new Vv(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Pm(this.storageUrl,this.headers,this.fetch)}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,n={},r={}){return this.rest.rpc(t,n,r)}channel(t,n={config:{}}){return this.realtime.channel(t,n)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var t,n;return _g(this,void 0,void 0,function*(){const{data:r}=yield this.auth.getSession();return(n=(t=r.session)===null||t===void 0?void 0:t.access_token)!==null&&n!==void 0?n:null})}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:n,detectSessionInUrl:r,storage:i,storageKey:s,flowType:o,debug:l},a,u){var c;const d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new wg({url:this.authUrl,headers:Object.assign(Object.assign({},d),a),storageKey:s,autoRefreshToken:t,persistSession:n,detectSessionInUrl:r,storage:i,flowType:o,debug:l,fetch:u,hasCustomAuthorizationHeader:(c="Authorization"in this.headers)!==null&&c!==void 0?c:!1})}_initRealtimeClient(t){return new hm(this.realtimeUrl,Object.assign(Object.assign({},t),{params:Object.assign({apikey:this.supabaseKey},t==null?void 0:t.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((n,r)=>{this._handleTokenChanged(n,"CLIENT",r==null?void 0:r.access_token)})}_handleTokenChanged(t,n,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.realtime.setAuth(r??null),this.changedAccessToken=r):t==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),n=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const kg=(e,t,n)=>new Sg(e,t,n);function Eg(e){const t=Xd(),[n,r]=E.useState([]);E.useEffect(()=>{e.session||t("/login")},[e.session]);const i=E.useCallback(async()=>{const{data:s,error:o}=await e.supabase.from("file").select();if(o){console.error(o);return}r(s.map(l=>l))},[e.supabase]);return E.useEffect(()=>{i()},[]),z.jsx(z.Fragment,{children:z.jsxs("div",{children:[z.jsx("h1",{className:"font-bold",children:"Home"}),z.jsx("p",{children:"Logged in!"}),n.map(s=>z.jsx("div",{children:z.jsxs("p",{children:["file: ",s.absolute_path]})},s.id))]})})}function Cg(e={}){const{nonce:t,onScriptLoadSuccess:n,onScriptLoadError:r}=e,[i,s]=E.useState(!1),o=E.useRef(n);o.current=n;const l=E.useRef(r);return l.current=r,E.useEffect(()=>{const a=document.createElement("script");return a.src="https://accounts.google.com/gsi/client",a.async=!0,a.defer=!0,a.nonce=t,a.onload=()=>{var u;s(!0),(u=o.current)===null||u===void 0||u.call(o)},a.onerror=()=>{var u;s(!1),(u=l.current)===null||u===void 0||u.call(l)},document.body.appendChild(a),()=>{document.body.removeChild(a)}},[t]),i}const pf=E.createContext(null);function xg({clientId:e,nonce:t,onScriptLoadSuccess:n,onScriptLoadError:r,children:i}){const s=Cg({nonce:t,onScriptLoadSuccess:n,onScriptLoadError:r}),o=E.useMemo(()=>({clientId:e,scriptLoadedSuccessfully:s}),[e,s]);return Gi.createElement(pf.Provider,{value:o},i)}function Pg(){const e=E.useContext(pf);if(!e)throw new Error("Google OAuth components must be used within GoogleOAuthProvider");return e}function Tg(e){var t;return(t=e==null?void 0:e.clientId)!==null&&t!==void 0?t:e==null?void 0:e.client_id}const Og={large:40,medium:32,small:20};function Rg({onSuccess:e,onError:t,useOneTap:n,promptMomentNotification:r,type:i="standard",theme:s="outline",size:o="large",text:l,shape:a,logo_alignment:u,width:c,locale:d,click_listener:h,containerProps:m,...g}){const y=E.useRef(null),{clientId:_,scriptLoadedSuccessfully:p}=Pg(),f=E.useRef(e);f.current=e;const v=E.useRef(t);v.current=t;const w=E.useRef(r);return w.current=r,E.useEffect(()=>{var k,P,T,O,M,j,de,qe,Ye;if(p)return(T=(P=(k=window==null?void 0:window.google)===null||k===void 0?void 0:k.accounts)===null||P===void 0?void 0:P.id)===null||T===void 0||T.initialize({client_id:_,callback:Oe=>{var Xe;if(!(Oe!=null&&Oe.credential))return(Xe=v.current)===null||Xe===void 0?void 0:Xe.call(v);const{credential:Ze,select_by:Bn}=Oe;f.current({credential:Ze,clientId:Tg(Oe),select_by:Bn})},...g}),(j=(M=(O=window==null?void 0:window.google)===null||O===void 0?void 0:O.accounts)===null||M===void 0?void 0:M.id)===null||j===void 0||j.renderButton(y.current,{type:i,theme:s,size:o,text:l,shape:a,logo_alignment:u,width:c,locale:d,click_listener:h}),n&&((Ye=(qe=(de=window==null?void 0:window.google)===null||de===void 0?void 0:de.accounts)===null||qe===void 0?void 0:qe.id)===null||Ye===void 0||Ye.prompt(w.current)),()=>{var Oe,Xe,Ze;n&&((Ze=(Xe=(Oe=window==null?void 0:window.google)===null||Oe===void 0?void 0:Oe.accounts)===null||Xe===void 0?void 0:Xe.id)===null||Ze===void 0||Ze.cancel())}},[_,p,n,i,s,o,l,a,u,c,d]),Gi.createElement("div",{...m,ref:y,style:{height:Og[o],...m==null?void 0:m.style}})}function jg(e){const t=Xd();return E.useEffect(()=>{e.supabase.auth.getSession().then(({data:{session:r}})=>{e.setSession(r),console.log("LOGIN SESSION",r)});const{data:{subscription:n}}=e.supabase.auth.onAuthStateChange((r,i)=>{e.setSession(i),console.log("SESSION CHANGE",i)});return()=>n.unsubscribe()},[e.supabase]),E.useEffect(()=>{e.session&&t("/")},[e.session]),z.jsxs(z.Fragment,{children:[z.jsxs("div",{children:[z.jsx("h1",{children:"Login"}),z.jsxs("p",{children:["Log in to access your account! ",JSON.stringify(e.session)]})]}),z.jsx(xg,{clientId:"952965459060-nrnrsdoq22mf646vfa72hk410pvdda5q.apps.googleusercontent.com",children:z.jsx(Rg,{onSuccess:async n=>{await e.supabase.auth.signInWithIdToken({provider:"google",token:n.credential})},onError:()=>{console.log("Login Failed")}})})]})}const ju=kg("https://slpoocycjgqsuoedhkbn.supabase.co","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InNscG9vY3ljamdxc3VvZWRoa2JuIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTUyMDU0MjUsImV4cCI6MjAzMDc4MTQyNX0.xZYRTRN65rlms1Hb96IBAQvw3EGtMzUxlGPP5TVey34");function Lg(){const[e,t]=E.useState(null);return z.jsx(z.Fragment,{children:z.jsx(Av,{basename:"/fs-tracer-frontend",children:z.jsxs(Iv,{children:[z.jsx(_i,{index:!0,element:z.jsx(Eg,{supabase:ju,session:e})}),z.jsx(_i,{path:"login",element:z.jsx(jg,{supabase:ju,session:e,setSession:t})}),z.jsx(_i,{path:"*",element:z.jsx("p",{children:"notfound"})})]})})})}Qs.createRoot(document.getElementById("root")).render(z.jsx(Gi.StrictMode,{children:z.jsx(Lg,{})}));export{mf as g};
+ */const $v="6";try{window.__reactRouterVersion=$v}catch{}const Nv="startTransition",cu=If[Nv];function Av(e){let{basename:t,children:n,future:r,window:i}=e,s=E.useRef();s.current==null&&(s.current=Hp({window:i,v5Compat:!0}));let o=s.current,[l,a]=E.useState({action:o.action,location:o.location}),{v7_startTransition:u}=r||{},c=E.useCallback(d=>{u&&cu?cu(()=>a(d)):a(d)},[a,u]);return E.useLayoutEffect(()=>o.listen(c),[o,c]),E.createElement(Lv,{basename:t,children:n,location:l.location,navigationType:l.action,navigator:o,future:r})}var du;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(du||(du={}));var fu;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(fu||(fu={}));const Uv="modulepreload",Dv=function(e,t){return new URL(e,t).href},hu={},Nn=function(t,n,r){let i=Promise.resolve();if(n&&n.length>0){const s=document.getElementsByTagName("link"),o=document.querySelector("meta[property=csp-nonce]"),l=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));i=Promise.all(n.map(a=>{if(a=Dv(a,r),a in hu)return;hu[a]=!0;const u=a.endsWith(".css"),c=u?'[rel="stylesheet"]':"";if(!!r)for(let m=s.length-1;m>=0;m--){const g=s[m];if(g.href===a&&(!u||g.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${a}"]${c}`))return;const h=document.createElement("link");if(h.rel=u?"stylesheet":Uv,u||(h.as="script",h.crossOrigin=""),h.href=a,l&&h.setAttribute("nonce",l),document.head.appendChild(h),u)return new Promise((m,g)=>{h.addEventListener("load",m),h.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${a}`)))})}))}return i.then(()=>t()).catch(s=>{const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=s,window.dispatchEvent(o),!o.defaultPrevented)throw s})},zv=e=>{let t;return e?t=e:typeof fetch>"u"?t=(...n)=>Nn(()=>Promise.resolve().then(()=>Fr),void 0,import.meta.url).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)};class Wl extends Error{constructor(t,n="FunctionsError",r){super(t),this.name=n,this.context=r}}class Fv extends Wl{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class Mv extends Wl{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class bv extends Wl{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var Ho;(function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"})(Ho||(Ho={}));var Bv=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};class Vv{constructor(t,{headers:n={},customFetch:r,region:i=Ho.Any}={}){this.url=t,this.headers=n,this.region=i,this.fetch=zv(r)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t,n={}){var r;return Bv(this,void 0,void 0,function*(){try{const{headers:i,method:s,body:o}=n;let l={},{region:a}=n;a||(a=this.region),a&&a!=="any"&&(l["x-region"]=a);let u;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(l["Content-Type"]="application/octet-stream",u=o):typeof o=="string"?(l["Content-Type"]="text/plain",u=o):typeof FormData<"u"&&o instanceof FormData?u=o:(l["Content-Type"]="application/json",u=JSON.stringify(o)));const c=yield this.fetch(`${this.url}/${t}`,{method:s||"POST",headers:Object.assign(Object.assign(Object.assign({},l),this.headers),i),body:u}).catch(g=>{throw new Fv(g)}),d=c.headers.get("x-relay-error");if(d&&d==="true")throw new Mv(c);if(!c.ok)throw new bv(c);let h=((r=c.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),m;return h==="application/json"?m=yield c.json():h==="application/octet-stream"?m=yield c.blob():h==="text/event-stream"?m=c:h==="multipart/form-data"?m=yield c.formData():m=yield c.text(),{data:m,error:null}}catch(i){return{data:null,error:i}}})}}var Hv=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")},An=Hv();const Wv=An.fetch,Kl=An.fetch.bind(An),tf=An.Headers,Kv=An.Request,Gv=An.Response,Fr=Object.freeze(Object.defineProperty({__proto__:null,Headers:tf,Request:Kv,Response:Gv,default:Kl,fetch:Wv},Symbol.toStringTag,{value:"Module"}));class Qv extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}}class Jv{constructor(t){this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=t.headers,this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=t.shouldThrowOnError,this.signal=t.signal,this.isMaybeSingle=t.isMaybeSingle,t.fetch?this.fetch=t.fetch:typeof fetch>"u"?this.fetch=Kl:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(t,n){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");const r=this.fetch;let i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async s=>{var o,l,a;let u=null,c=null,d=null,h=s.status,m=s.statusText;if(s.ok){if(this.method!=="HEAD"){const p=await s.text();p===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?c=p:c=JSON.parse(p))}const y=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),_=(l=s.headers.get("content-range"))===null||l===void 0?void 0:l.split("/");y&&_&&_.length>1&&(d=parseInt(_[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(c)&&(c.length>1?(u={code:"PGRST116",details:`Results contain ${c.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},c=null,d=null,h=406,m="Not Acceptable"):c.length===1?c=c[0]:c=null)}else{const y=await s.text();try{u=JSON.parse(y),Array.isArray(u)&&s.status===404&&(c=[],u=null,h=200,m="OK")}catch{s.status===404&&y===""?(h=204,m="No Content"):u={message:y}}if(u&&this.isMaybeSingle&&(!((a=u==null?void 0:u.details)===null||a===void 0)&&a.includes("0 rows"))&&(u=null,h=200,m="OK"),u&&this.shouldThrowOnError)throw new Qv(u)}return{error:u,data:c,count:d,status:h,statusText:m}});return this.shouldThrowOnError||(i=i.catch(s=>{var o,l,a;return{error:{message:`${(o=s==null?void 0:s.name)!==null&&o!==void 0?o:"FetchError"}: ${s==null?void 0:s.message}`,details:`${(l=s==null?void 0:s.stack)!==null&&l!==void 0?l:""}`,hint:"",code:`${(a=s==null?void 0:s.code)!==null&&a!==void 0?a:""}`},data:null,count:null,status:0,statusText:""}})),i.then(t,n)}}class qv extends Jv{select(t){let n=!1;const r=(t??"*").split("").map(i=>/\s/.test(i)&&!n?"":(i==='"'&&(n=!n),i)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(t,{ascending:n=!0,nullsFirst:r,foreignTable:i,referencedTable:s=i}={}){const o=s?`${s}.order`:"order",l=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${l?`${l},`:""}${t}.${n?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:n,referencedTable:r=n}={}){const i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${t}`),this}range(t,n,{foreignTable:r,referencedTable:i=r}={}){const s=typeof i>"u"?"offset":`${i}.offset`,o=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(s,`${t}`),this.url.searchParams.set(o,`${n-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:t=!1,verbose:n=!1,settings:r=!1,buffers:i=!1,wal:s=!1,format:o="text"}={}){var l;const a=[t?"analyze":null,n?"verbose":null,r?"settings":null,i?"buffers":null,s?"wal":null].filter(Boolean).join("|"),u=(l=this.headers.Accept)!==null&&l!==void 0?l:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${u}"; options=${a};`,o==="json"?this:this}rollback(){var t;return((t=this.headers.Prefer)!==null&&t!==void 0?t:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}}class ln extends qv{eq(t,n){return this.url.searchParams.append(t,`eq.${n}`),this}neq(t,n){return this.url.searchParams.append(t,`neq.${n}`),this}gt(t,n){return this.url.searchParams.append(t,`gt.${n}`),this}gte(t,n){return this.url.searchParams.append(t,`gte.${n}`),this}lt(t,n){return this.url.searchParams.append(t,`lt.${n}`),this}lte(t,n){return this.url.searchParams.append(t,`lte.${n}`),this}like(t,n){return this.url.searchParams.append(t,`like.${n}`),this}likeAllOf(t,n){return this.url.searchParams.append(t,`like(all).{${n.join(",")}}`),this}likeAnyOf(t,n){return this.url.searchParams.append(t,`like(any).{${n.join(",")}}`),this}ilike(t,n){return this.url.searchParams.append(t,`ilike.${n}`),this}ilikeAllOf(t,n){return this.url.searchParams.append(t,`ilike(all).{${n.join(",")}}`),this}ilikeAnyOf(t,n){return this.url.searchParams.append(t,`ilike(any).{${n.join(",")}}`),this}is(t,n){return this.url.searchParams.append(t,`is.${n}`),this}in(t,n){const r=Array.from(new Set(n)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}contains(t,n){return typeof n=="string"?this.url.searchParams.append(t,`cs.${n}`):Array.isArray(n)?this.url.searchParams.append(t,`cs.{${n.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(n)}`),this}containedBy(t,n){return typeof n=="string"?this.url.searchParams.append(t,`cd.${n}`):Array.isArray(n)?this.url.searchParams.append(t,`cd.{${n.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(n)}`),this}rangeGt(t,n){return this.url.searchParams.append(t,`sr.${n}`),this}rangeGte(t,n){return this.url.searchParams.append(t,`nxl.${n}`),this}rangeLt(t,n){return this.url.searchParams.append(t,`sl.${n}`),this}rangeLte(t,n){return this.url.searchParams.append(t,`nxr.${n}`),this}rangeAdjacent(t,n){return this.url.searchParams.append(t,`adj.${n}`),this}overlaps(t,n){return typeof n=="string"?this.url.searchParams.append(t,`ov.${n}`):this.url.searchParams.append(t,`ov.{${n.join(",")}}`),this}textSearch(t,n,{config:r,type:i}={}){let s="";i==="plain"?s="pl":i==="phrase"?s="ph":i==="websearch"&&(s="w");const o=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${s}fts${o}.${n}`),this}match(t){return Object.entries(t).forEach(([n,r])=>{this.url.searchParams.append(n,`eq.${r}`)}),this}not(t,n,r){return this.url.searchParams.append(t,`not.${n}.${r}`),this}or(t,{foreignTable:n,referencedTable:r=n}={}){const i=r?`${r}.or`:"or";return this.url.searchParams.append(i,`(${t})`),this}filter(t,n,r){return this.url.searchParams.append(t,`${n}.${r}`),this}}class Yv{constructor(t,{headers:n={},schema:r,fetch:i}){this.url=t,this.headers=n,this.schema=r,this.fetch=i}select(t,{head:n=!1,count:r}={}){const i=n?"HEAD":"GET";let s=!1;const o=(t??"*").split("").map(l=>/\s/.test(l)&&!s?"":(l==='"'&&(s=!s),l)).join("");return this.url.searchParams.set("select",o),r&&(this.headers.Prefer=`count=${r}`),new ln({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(t,{count:n,defaultToNull:r=!0}={}){const i="POST",s=[];if(this.headers.Prefer&&s.push(this.headers.Prefer),n&&s.push(`count=${n}`),r||s.push("missing=default"),this.headers.Prefer=s.join(","),Array.isArray(t)){const o=t.reduce((l,a)=>l.concat(Object.keys(a)),[]);if(o.length>0){const l=[...new Set(o)].map(a=>`"${a}"`);this.url.searchParams.set("columns",l.join(","))}}return new ln({method:i,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}upsert(t,{onConflict:n,ignoreDuplicates:r=!1,count:i,defaultToNull:s=!0}={}){const o="POST",l=[`resolution=${r?"ignore":"merge"}-duplicates`];if(n!==void 0&&this.url.searchParams.set("on_conflict",n),this.headers.Prefer&&l.push(this.headers.Prefer),i&&l.push(`count=${i}`),s||l.push("missing=default"),this.headers.Prefer=l.join(","),Array.isArray(t)){const a=t.reduce((u,c)=>u.concat(Object.keys(c)),[]);if(a.length>0){const u=[...new Set(a)].map(c=>`"${c}"`);this.url.searchParams.set("columns",u.join(","))}}return new ln({method:o,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}update(t,{count:n}={}){const r="PATCH",i=[];return this.headers.Prefer&&i.push(this.headers.Prefer),n&&i.push(`count=${n}`),this.headers.Prefer=i.join(","),new ln({method:r,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}delete({count:t}={}){const n="DELETE",r=[];return t&&r.push(`count=${t}`),this.headers.Prefer&&r.unshift(this.headers.Prefer),this.headers.Prefer=r.join(","),new ln({method:n,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}}const Xv="1.15.2",Zv={"X-Client-Info":`postgrest-js/${Xv}`};class Gl{constructor(t,{headers:n={},schema:r,fetch:i}={}){this.url=t,this.headers=Object.assign(Object.assign({},Zv),n),this.schemaName=r,this.fetch=i}from(t){const n=new URL(`${this.url}/${t}`);return new Yv(n,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new Gl(this.url,{headers:this.headers,schema:t,fetch:this.fetch})}rpc(t,n={},{head:r=!1,get:i=!1,count:s}={}){let o;const l=new URL(`${this.url}/rpc/${t}`);let a;r||i?(o=r?"HEAD":"GET",Object.entries(n).filter(([c,d])=>d!==void 0).map(([c,d])=>[c,Array.isArray(d)?`{${d.join(",")}}`:`${d}`]).forEach(([c,d])=>{l.searchParams.append(c,d)})):(o="POST",a=n);const u=Object.assign({},this.headers);return s&&(u.Prefer=`count=${s}`),new ln({method:o,url:l,headers:u,schema:this.schemaName,body:a,fetch:this.fetch,allowEmpty:!1})}}const em="2.9.5",tm={"X-Client-Info":`realtime-js/${em}`},nm="1.0.0",nf=1e4,rm=1e3;var Pn;(function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"})(Pn||(Pn={}));var Se;(function(e){e.closed="closed",e.errored="errored",e.joined="joined",e.joining="joining",e.leaving="leaving"})(Se||(Se={}));var Me;(function(e){e.close="phx_close",e.error="phx_error",e.join="phx_join",e.reply="phx_reply",e.leave="phx_leave",e.access_token="access_token"})(Me||(Me={}));var Wo;(function(e){e.websocket="websocket"})(Wo||(Wo={}));var bt;(function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"})(bt||(bt={}));class rf{constructor(t,n){this.callback=t,this.timerCalc=n,this.timer=void 0,this.tries=0,this.callback=t,this.timerCalc=n}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}class im{constructor(){this.HEADER_LENGTH=1}decode(t,n){return t.constructor===ArrayBuffer?n(this._binaryDecode(t)):n(typeof t=="string"?JSON.parse(t):{})}_binaryDecode(t){const n=new DataView(t),r=new TextDecoder;return this._decodeBroadcast(t,n,r)}_decodeBroadcast(t,n,r){const i=n.getUint8(1),s=n.getUint8(2);let o=this.HEADER_LENGTH+2;const l=r.decode(t.slice(o,o+i));o=o+i;const a=r.decode(t.slice(o,o+s));o=o+s;const u=JSON.parse(r.decode(t.slice(o,t.byteLength)));return{ref:null,topic:l,event:a,payload:u}}}class Bs{constructor(t,n,r={},i=nf){this.channel=t,this.event=n,this.payload=r,this.timeout=i,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(t){this.timeout=t,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(t){this.payload=Object.assign(Object.assign({},this.payload),t)}receive(t,n){var r;return this._hasReceived(t)&&n((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:t,callback:n}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const t=n=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=n,this._matchReceive(n)};this.channel._on(this.refEvent,{},t),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(t,n){this.refEvent&&this.channel._trigger(this.refEvent,{status:t,response:n})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:t,response:n}){this.recHooks.filter(r=>r.status===t).forEach(r=>r.callback(n))}_hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}}var pu;(function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"})(pu||(pu={}));class fr{constructor(t,n){this.channel=t,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(n==null?void 0:n.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},i=>{const{onJoin:s,onLeave:o,onSync:l}=this.caller;this.joinRef=this.channel._joinRef(),this.state=fr.syncState(this.state,i,s,o),this.pendingDiffs.forEach(a=>{this.state=fr.syncDiff(this.state,a,s,o)}),this.pendingDiffs=[],l()}),this.channel._on(r.diff,{},i=>{const{onJoin:s,onLeave:o,onSync:l}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=fr.syncDiff(this.state,i,s,o),l())}),this.onJoin((i,s,o)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:s,newPresences:o})}),this.onLeave((i,s,o)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:s,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(t,n,r,i){const s=this.cloneDeep(t),o=this.transformState(n),l={},a={};return this.map(s,(u,c)=>{o[u]||(a[u]=c)}),this.map(o,(u,c)=>{const d=s[u];if(d){const h=c.map(_=>_.presence_ref),m=d.map(_=>_.presence_ref),g=c.filter(_=>m.indexOf(_.presence_ref)<0),y=d.filter(_=>h.indexOf(_.presence_ref)<0);g.length>0&&(l[u]=g),y.length>0&&(a[u]=y)}else l[u]=c}),this.syncDiff(s,{joins:l,leaves:a},r,i)}static syncDiff(t,n,r,i){const{joins:s,leaves:o}={joins:this.transformState(n.joins),leaves:this.transformState(n.leaves)};return r||(r=()=>{}),i||(i=()=>{}),this.map(s,(l,a)=>{var u;const c=(u=t[l])!==null&&u!==void 0?u:[];if(t[l]=this.cloneDeep(a),c.length>0){const d=t[l].map(m=>m.presence_ref),h=c.filter(m=>d.indexOf(m.presence_ref)<0);t[l].unshift(...h)}r(l,c,a)}),this.map(o,(l,a)=>{let u=t[l];if(!u)return;const c=a.map(d=>d.presence_ref);u=u.filter(d=>c.indexOf(d.presence_ref)<0),t[l]=u,i(l,u,a),u.length===0&&delete t[l]}),t}static map(t,n){return Object.getOwnPropertyNames(t).map(r=>n(r,t[r]))}static transformState(t){return t=this.cloneDeep(t),Object.getOwnPropertyNames(t).reduce((n,r)=>{const i=t[r];return"metas"in i?n[r]=i.metas.map(s=>(s.presence_ref=s.phx_ref,delete s.phx_ref,delete s.phx_ref_prev,s)):n[r]=i,n},{})}static cloneDeep(t){return JSON.parse(JSON.stringify(t))}onJoin(t){this.caller.onJoin=t}onLeave(t){this.caller.onLeave=t}onSync(t){this.caller.onSync=t}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var D;(function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"})(D||(D={}));const vu=(e,t,n={})=>{var r;const i=(r=n.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(t).reduce((s,o)=>(s[o]=sm(o,e,t,i),s),{})},sm=(e,t,n,r)=>{const i=t.find(l=>l.name===e),s=i==null?void 0:i.type,o=n[e];return s&&!r.includes(s)?sf(s,o):Ko(o)},sf=(e,t)=>{if(e.charAt(0)==="_"){const n=e.slice(1,e.length);return um(t,n)}switch(e){case D.bool:return om(t);case D.float4:case D.float8:case D.int2:case D.int4:case D.int8:case D.numeric:case D.oid:return lm(t);case D.json:case D.jsonb:return am(t);case D.timestamp:return cm(t);case D.abstime:case D.date:case D.daterange:case D.int4range:case D.int8range:case D.money:case D.reltime:case D.text:case D.time:case D.timestamptz:case D.timetz:case D.tsrange:case D.tstzrange:return Ko(t);default:return Ko(t)}},Ko=e=>e,om=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},lm=e=>{if(typeof e=="string"){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},am=e=>{if(typeof e=="string")try{return JSON.parse(e)}catch(t){return console.log(`JSON parse error: ${t}`),e}return e},um=(e,t)=>{if(typeof e!="string")return e;const n=e.length-1,r=e[n];if(e[0]==="{"&&r==="}"){let s;const o=e.slice(1,n);try{s=JSON.parse("["+o+"]")}catch{s=o?o.split(","):[]}return s.map(l=>sf(t,l))}return e},cm=e=>typeof e=="string"?e.replace(" ","T"):e;var mu;(function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"})(mu||(mu={}));var gu;(function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes"})(gu||(gu={}));var yu;(function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"})(yu||(yu={}));class Ql{constructor(t,n={config:{}},r){this.topic=t,this.params=n,this.socket=r,this.bindings={},this.state=Se.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=t.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""}},n.config),this.timeout=this.socket.timeout,this.joinPush=new Bs(this,Me.join,this.params,this.timeout),this.rejoinTimer=new rf(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=Se.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(i=>i.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=Se.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=Se.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=Se.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Me.reply,{},(i,s)=>{this._trigger(this._replyEventName(s),i)}),this.presence=new fr(this),this.broadcastEndpointURL=this._broadcastEndpointURL()}subscribe(t,n=this.timeout){var r,i;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{const{config:{broadcast:s,presence:o}}=this.params;this._onError(u=>t&&t("CHANNEL_ERROR",u)),this._onClose(()=>t&&t("CLOSED"));const l={},a={broadcast:s,presence:o,postgres_changes:(i=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(u=>u.filter))!==null&&i!==void 0?i:[]};this.socket.accessToken&&(l.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:a},l)),this.joinedOnce=!0,this._rejoin(n),this.joinPush.receive("ok",({postgres_changes:u})=>{var c;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),u===void 0){t&&t("SUBSCRIBED");return}else{const d=this.bindings.postgres_changes,h=(c=d==null?void 0:d.length)!==null&&c!==void 0?c:0,m=[];for(let g=0;g<h;g++){const y=d[g],{filter:{event:_,schema:p,table:f,filter:v}}=y,w=u&&u[g];if(w&&w.event===_&&w.schema===p&&w.table===f&&w.filter===v)m.push(Object.assign(Object.assign({},y),{id:w.id}));else{this.unsubscribe(),t&&t("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=m,t&&t("SUBSCRIBED");return}}).receive("error",u=>{t&&t("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{t&&t("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(t,n={}){return await this.send({type:"presence",event:"track",payload:t},n.timeout||this.timeout)}async untrack(t={}){return await this.send({type:"presence",event:"untrack"},t)}on(t,n,r){return this._on(t,n,r)}async send(t,n={}){var r,i;if(!this._canPush()&&t.type==="broadcast"){const{event:s,payload:o}=t,l={method:"POST",headers:{apikey:(r=this.socket.apiKey)!==null&&r!==void 0?r:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:s,payload:o}]})};try{return(await this._fetchWithTimeout(this.broadcastEndpointURL,l,(i=n.timeout)!==null&&i!==void 0?i:this.timeout)).ok?"ok":"error"}catch(a){return a.name==="AbortError"?"timed out":"error"}}else return new Promise(s=>{var o,l,a;const u=this._push(t.type,t,n.timeout||this.timeout);t.type==="broadcast"&&!(!((a=(l=(o=this.params)===null||o===void 0?void 0:o.config)===null||l===void 0?void 0:l.broadcast)===null||a===void 0)&&a.ack)&&s("ok"),u.receive("ok",()=>s("ok")),u.receive("error",()=>s("error")),u.receive("timeout",()=>s("timed out"))})}updateJoinPayload(t){this.joinPush.updatePayload(t)}unsubscribe(t=this.timeout){this.state=Se.leaving;const n=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Me.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{const i=new Bs(this,Me.leave,{},t);i.receive("ok",()=>{n(),r("ok")}).receive("timeout",()=>{n(),r("timed out")}).receive("error",()=>{r("error")}),i.send(),this._canPush()||i.trigger("ok",{})})}_broadcastEndpointURL(){let t=this.socket.endPoint;return t=t.replace(/^ws/i,"http"),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),t.replace(/\/+$/,"")+"/api/broadcast"}async _fetchWithTimeout(t,n,r){const i=new AbortController,s=setTimeout(()=>i.abort(),r),o=await this.socket.fetch(t,Object.assign(Object.assign({},n),{signal:i.signal}));return clearTimeout(s),o}_push(t,n,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${t}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new Bs(this,t,n,r);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(t,n,r){return n}_isMember(t){return this.topic===t}_joinRef(){return this.joinPush.ref}_trigger(t,n,r){var i,s;const o=t.toLocaleLowerCase(),{close:l,error:a,leave:u,join:c}=Me;if(r&&[l,a,u,c].indexOf(o)>=0&&r!==this._joinRef())return;let h=this._onMessage(o,n,r);if(n&&!h)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(m=>{var g,y,_;return((g=m.filter)===null||g===void 0?void 0:g.event)==="*"||((_=(y=m.filter)===null||y===void 0?void 0:y.event)===null||_===void 0?void 0:_.toLocaleLowerCase())===o}).map(m=>m.callback(h,r)):(s=this.bindings[o])===null||s===void 0||s.filter(m=>{var g,y,_,p,f,v;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in m){const w=m.id,k=(g=m.filter)===null||g===void 0?void 0:g.event;return w&&((y=n.ids)===null||y===void 0?void 0:y.includes(w))&&(k==="*"||(k==null?void 0:k.toLocaleLowerCase())===((_=n.data)===null||_===void 0?void 0:_.type.toLocaleLowerCase()))}else{const w=(f=(p=m==null?void 0:m.filter)===null||p===void 0?void 0:p.event)===null||f===void 0?void 0:f.toLocaleLowerCase();return w==="*"||w===((v=n==null?void 0:n.event)===null||v===void 0?void 0:v.toLocaleLowerCase())}else return m.type.toLocaleLowerCase()===o}).map(m=>{if(typeof h=="object"&&"ids"in h){const g=h.data,{schema:y,table:_,commit_timestamp:p,type:f,errors:v}=g;h=Object.assign(Object.assign({},{schema:y,table:_,commit_timestamp:p,eventType:f,new:{},old:{},errors:v}),this._getPayloadRecords(g))}m.callback(h,r)})}_isClosed(){return this.state===Se.closed}_isJoined(){return this.state===Se.joined}_isJoining(){return this.state===Se.joining}_isLeaving(){return this.state===Se.leaving}_replyEventName(t){return`chan_reply_${t}`}_on(t,n,r){const i=t.toLocaleLowerCase(),s={type:i,filter:n,callback:r};return this.bindings[i]?this.bindings[i].push(s):this.bindings[i]=[s],this}_off(t,n){const r=t.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(i=>{var s;return!(((s=i.type)===null||s===void 0?void 0:s.toLocaleLowerCase())===r&&Ql.isEqual(i.filter,n))}),this}static isEqual(t,n){if(Object.keys(t).length!==Object.keys(n).length)return!1;for(const r in t)if(t[r]!==n[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(t){this._on(Me.close,{},t)}_onError(t){this._on(Me.error,{},n=>t(n))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=Se.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const n={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(n.new=vu(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(n.old=vu(t.columns,t.old_record)),n}}const dm=()=>{},fm=typeof WebSocket<"u";class hm{constructor(t,n){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.headers=tm,this.params={},this.timeout=nf,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=dm,this.conn=null,this.sendBuffer=[],this.serializer=new im,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=s=>{let o;return s?o=s:typeof fetch>"u"?o=(...l)=>Nn(()=>Promise.resolve().then(()=>Fr),void 0,import.meta.url).then(({default:a})=>a(...l)):o=fetch,(...l)=>o(...l)},this.endPoint=`${t}/${Wo.websocket}`,n!=null&&n.transport?this.transport=n.transport:this.transport=null,n!=null&&n.params&&(this.params=n.params),n!=null&&n.headers&&(this.headers=Object.assign(Object.assign({},this.headers),n.headers)),n!=null&&n.timeout&&(this.timeout=n.timeout),n!=null&&n.logger&&(this.logger=n.logger),n!=null&&n.heartbeatIntervalMs&&(this.heartbeatIntervalMs=n.heartbeatIntervalMs);const i=(r=n==null?void 0:n.params)===null||r===void 0?void 0:r.apikey;i&&(this.accessToken=i,this.apiKey=i),this.reconnectAfterMs=n!=null&&n.reconnectAfterMs?n.reconnectAfterMs:s=>[1e3,2e3,5e3,1e4][s-1]||1e4,this.encode=n!=null&&n.encode?n.encode:(s,o)=>o(JSON.stringify(s)),this.decode=n!=null&&n.decode?n.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new rf(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(n==null?void 0:n.fetch)}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this._endPointURL(),void 0,{headers:this.headers});return}if(fm){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new pm(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Nn(()=>import("./browser-Cb7qedTs.js").then(t=>t.b),[],import.meta.url).then(({default:t})=>{this.conn=new t(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(t,n){this.conn&&(this.conn.onclose=function(){},t?this.conn.close(t,n??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(t){const n=await t.unsubscribe();return this.channels.length===0&&this.disconnect(),n}async removeAllChannels(){const t=await Promise.all(this.channels.map(n=>n.unsubscribe()));return this.disconnect(),t}log(t,n,r){this.logger(t,n,r)}connectionState(){switch(this.conn&&this.conn.readyState){case Pn.connecting:return bt.Connecting;case Pn.open:return bt.Open;case Pn.closing:return bt.Closing;default:return bt.Closed}}isConnected(){return this.connectionState()===bt.Open}channel(t,n={config:{}}){const r=new Ql(`realtime:${t}`,n,this);return this.channels.push(r),r}push(t){const{topic:n,event:r,payload:i,ref:s}=t,o=()=>{this.encode(t,l=>{var a;(a=this.conn)===null||a===void 0||a.send(l)})};this.log("push",`${n} ${r} (${s})`,i),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(t){this.accessToken=t,this.channels.forEach(n=>{t&&n.updateJoinPayload({access_token:t}),n.joinedOnce&&n._isJoined()&&n._push(Me.access_token,{access_token:t})})}_makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}_leaveOpenTopic(t){let n=this.channels.find(r=>r.topic===t&&(r._isJoined()||r._isJoining()));n&&(this.log("transport",`leaving duplicate topic "${t}"`),n.unsubscribe())}_remove(t){this.channels=this.channels.filter(n=>n._joinRef()!==t._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=t=>this._onConnError(t),this.conn.onmessage=t=>this._onConnMessage(t),this.conn.onclose=t=>this._onConnClose(t))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:nm}))}_onConnMessage(t){this.decode(t.data,n=>{let{topic:r,event:i,payload:s,ref:o}=n;(o&&o===this.pendingHeartbeatRef||i===(s==null?void 0:s.type))&&(this.pendingHeartbeatRef=null),this.log("receive",`${s.status||""} ${r} ${i} ${o&&"("+o+")"||""}`,s),this.channels.filter(l=>l._isMember(r)).forEach(l=>l._trigger(i,s,o)),this.stateChangeCallbacks.message.forEach(l=>l(n))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(t=>t())}_onConnClose(t){this.log("transport","close",t),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(n=>n(t))}_onConnError(t){this.log("transport",t.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(n=>n(t))}_triggerChanError(){this.channels.forEach(t=>t._trigger(Me.error))}_appendParams(t,n){if(Object.keys(n).length===0)return t;const r=t.match(/\?/)?"&":"?",i=new URLSearchParams(n);return`${t}${r}${i}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}_sendHeartbeat(){var t;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(t=this.conn)===null||t===void 0||t.close(rm,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}}class pm{constructor(t,n,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=Pn.connecting,this.send=()=>{},this.url=null,this.url=t,this.close=r.close}}class Jl extends Error{constructor(t){super(t),this.__isStorageError=!0,this.name="StorageError"}}function ae(e){return typeof e=="object"&&e!==null&&"__isStorageError"in e}class vm extends Jl{constructor(t,n){super(t),this.name="StorageApiError",this.status=n}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class wu extends Jl{constructor(t,n){super(t),this.name="StorageUnknownError",this.originalError=n}}var mm=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};const of=e=>{let t;return e?t=e:typeof fetch>"u"?t=(...n)=>Nn(()=>Promise.resolve().then(()=>Fr),void 0,import.meta.url).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},gm=()=>mm(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Nn(()=>Promise.resolve().then(()=>Fr),void 0,import.meta.url)).Response:Response});var bn=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};const Vs=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),ym=(e,t)=>bn(void 0,void 0,void 0,function*(){const n=yield gm();e instanceof n?e.json().then(r=>{t(new vm(Vs(r),e.status||500))}).catch(r=>{t(new wu(Vs(r),r))}):t(new wu(Vs(e),e))}),wm=(e,t,n,r)=>{const i={method:e,headers:(t==null?void 0:t.headers)||{}};return e==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json"},t==null?void 0:t.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),n))};function fs(e,t,n,r,i,s){return bn(this,void 0,void 0,function*(){return new Promise((o,l)=>{e(n,wm(t,r,i,s)).then(a=>{if(!a.ok)throw a;return r!=null&&r.noResolveJson?a:a.json()}).then(a=>o(a)).catch(a=>ym(a,l))})})}function Go(e,t,n,r){return bn(this,void 0,void 0,function*(){return fs(e,"GET",t,n,r)})}function pt(e,t,n,r,i){return bn(this,void 0,void 0,function*(){return fs(e,"POST",t,r,i,n)})}function _m(e,t,n,r,i){return bn(this,void 0,void 0,function*(){return fs(e,"PUT",t,r,i,n)})}function lf(e,t,n,r,i){return bn(this,void 0,void 0,function*(){return fs(e,"DELETE",t,r,i,n)})}var Re=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};const Sm={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},_u={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class km{constructor(t,n={},r,i){this.url=t,this.headers=n,this.bucketId=r,this.fetch=of(i)}uploadOrUpdate(t,n,r,i){return Re(this,void 0,void 0,function*(){try{let s;const o=Object.assign(Object.assign({},_u),i),l=Object.assign(Object.assign({},this.headers),t==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&r instanceof Blob?(s=new FormData,s.append("cacheControl",o.cacheControl),s.append("",r)):typeof FormData<"u"&&r instanceof FormData?(s=r,s.append("cacheControl",o.cacheControl)):(s=r,l["cache-control"]=`max-age=${o.cacheControl}`,l["content-type"]=o.contentType);const a=this._removeEmptyFolders(n),u=this._getFinalPath(a),c=yield this.fetch(`${this.url}/object/${u}`,Object.assign({method:t,body:s,headers:l},o!=null&&o.duplex?{duplex:o.duplex}:{})),d=yield c.json();return c.ok?{data:{path:a,id:d.Id,fullPath:d.Key},error:null}:{data:null,error:d}}catch(s){if(ae(s))return{data:null,error:s};throw s}})}upload(t,n,r){return Re(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",t,n,r)})}uploadToSignedUrl(t,n,r,i){return Re(this,void 0,void 0,function*(){const s=this._removeEmptyFolders(t),o=this._getFinalPath(s),l=new URL(this.url+`/object/upload/sign/${o}`);l.searchParams.set("token",n);try{let a;const u=Object.assign({upsert:_u.upsert},i),c=Object.assign(Object.assign({},this.headers),{"x-upsert":String(u.upsert)});typeof Blob<"u"&&r instanceof Blob?(a=new FormData,a.append("cacheControl",u.cacheControl),a.append("",r)):typeof FormData<"u"&&r instanceof FormData?(a=r,a.append("cacheControl",u.cacheControl)):(a=r,c["cache-control"]=`max-age=${u.cacheControl}`,c["content-type"]=u.contentType);const d=yield this.fetch(l.toString(),{method:"PUT",body:a,headers:c}),h=yield d.json();return d.ok?{data:{path:s,fullPath:h.Key},error:null}:{data:null,error:h}}catch(a){if(ae(a))return{data:null,error:a};throw a}})}createSignedUploadUrl(t){return Re(this,void 0,void 0,function*(){try{let n=this._getFinalPath(t);const r=yield pt(this.fetch,`${this.url}/object/upload/sign/${n}`,{},{headers:this.headers}),i=new URL(this.url+r.url),s=i.searchParams.get("token");if(!s)throw new Jl("No token returned by API");return{data:{signedUrl:i.toString(),path:t,token:s},error:null}}catch(n){if(ae(n))return{data:null,error:n};throw n}})}update(t,n,r){return Re(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",t,n,r)})}move(t,n){return Re(this,void 0,void 0,function*(){try{return{data:yield pt(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:t,destinationKey:n},{headers:this.headers}),error:null}}catch(r){if(ae(r))return{data:null,error:r};throw r}})}copy(t,n){return Re(this,void 0,void 0,function*(){try{return{data:{path:(yield pt(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:t,destinationKey:n},{headers:this.headers})).Key},error:null}}catch(r){if(ae(r))return{data:null,error:r};throw r}})}createSignedUrl(t,n,r){return Re(this,void 0,void 0,function*(){try{let i=this._getFinalPath(t),s=yield pt(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:n},r!=null&&r.transform?{transform:r.transform}:{}),{headers:this.headers});const o=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return s={signedUrl:encodeURI(`${this.url}${s.signedURL}${o}`)},{data:s,error:null}}catch(i){if(ae(i))return{data:null,error:i};throw i}})}createSignedUrls(t,n,r){return Re(this,void 0,void 0,function*(){try{const i=yield pt(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:n,paths:t},{headers:this.headers}),s=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return{data:i.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${s}`):null})),error:null}}catch(i){if(ae(i))return{data:null,error:i};throw i}})}download(t,n){return Re(this,void 0,void 0,function*(){const i=typeof(n==null?void 0:n.transform)<"u"?"render/image/authenticated":"object",s=this.transformOptsToQueryString((n==null?void 0:n.transform)||{}),o=s?`?${s}`:"";try{const l=this._getFinalPath(t);return{data:yield(yield Go(this.fetch,`${this.url}/${i}/${l}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(l){if(ae(l))return{data:null,error:l};throw l}})}getPublicUrl(t,n){const r=this._getFinalPath(t),i=[],s=n!=null&&n.download?`download=${n.download===!0?"":n.download}`:"";s!==""&&i.push(s);const l=typeof(n==null?void 0:n.transform)<"u"?"render/image":"object",a=this.transformOptsToQueryString((n==null?void 0:n.transform)||{});a!==""&&i.push(a);let u=i.join("&");return u!==""&&(u=`?${u}`),{data:{publicUrl:encodeURI(`${this.url}/${l}/public/${r}${u}`)}}}remove(t){return Re(this,void 0,void 0,function*(){try{return{data:yield lf(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers}),error:null}}catch(n){if(ae(n))return{data:null,error:n};throw n}})}list(t,n,r){return Re(this,void 0,void 0,function*(){try{const i=Object.assign(Object.assign(Object.assign({},Sm),n),{prefix:t||""});return{data:yield pt(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},r),error:null}}catch(i){if(ae(i))return{data:null,error:i};throw i}})}_getFinalPath(t){return`${this.bucketId}/${t}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){const n=[];return t.width&&n.push(`width=${t.width}`),t.height&&n.push(`height=${t.height}`),t.resize&&n.push(`resize=${t.resize}`),t.format&&n.push(`format=${t.format}`),t.quality&&n.push(`quality=${t.quality}`),n.join("&")}}const Em="2.5.5",Cm={"X-Client-Info":`storage-js/${Em}`};var rn=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};class xm{constructor(t,n={},r){this.url=t,this.headers=Object.assign(Object.assign({},Cm),n),this.fetch=of(r)}listBuckets(){return rn(this,void 0,void 0,function*(){try{return{data:yield Go(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(t){if(ae(t))return{data:null,error:t};throw t}})}getBucket(t){return rn(this,void 0,void 0,function*(){try{return{data:yield Go(this.fetch,`${this.url}/bucket/${t}`,{headers:this.headers}),error:null}}catch(n){if(ae(n))return{data:null,error:n};throw n}})}createBucket(t,n={public:!1}){return rn(this,void 0,void 0,function*(){try{return{data:yield pt(this.fetch,`${this.url}/bucket`,{id:t,name:t,public:n.public,file_size_limit:n.fileSizeLimit,allowed_mime_types:n.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(ae(r))return{data:null,error:r};throw r}})}updateBucket(t,n){return rn(this,void 0,void 0,function*(){try{return{data:yield _m(this.fetch,`${this.url}/bucket/${t}`,{id:t,name:t,public:n.public,file_size_limit:n.fileSizeLimit,allowed_mime_types:n.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(ae(r))return{data:null,error:r};throw r}})}emptyBucket(t){return rn(this,void 0,void 0,function*(){try{return{data:yield pt(this.fetch,`${this.url}/bucket/${t}/empty`,{},{headers:this.headers}),error:null}}catch(n){if(ae(n))return{data:null,error:n};throw n}})}deleteBucket(t){return rn(this,void 0,void 0,function*(){try{return{data:yield lf(this.fetch,`${this.url}/bucket/${t}`,{},{headers:this.headers}),error:null}}catch(n){if(ae(n))return{data:null,error:n};throw n}})}}class Pm extends xm{constructor(t,n={},r){super(t,n,r)}from(t){return new km(this.url,this.headers,t,this.fetch)}}const Tm="2.43.4";let nr="";typeof Deno<"u"?nr="deno":typeof document<"u"?nr="web":typeof navigator<"u"&&navigator.product==="ReactNative"?nr="react-native":nr="node";const Om={"X-Client-Info":`supabase-js-${nr}/${Tm}`},Rm={headers:Om},jm={schema:"public"},Lm={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Im={};var $m=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};const Nm=e=>{let t;return e?t=e:typeof fetch>"u"?t=Kl:t=fetch,(...n)=>t(...n)},Am=()=>typeof Headers>"u"?tf:Headers,Um=(e,t,n)=>{const r=Nm(n),i=Am();return(s,o)=>$m(void 0,void 0,void 0,function*(){var l;const a=(l=yield t())!==null&&l!==void 0?l:e;let u=new i(o==null?void 0:o.headers);return u.has("apikey")||u.set("apikey",e),u.has("Authorization")||u.set("Authorization",`Bearer ${a}`),r(s,Object.assign(Object.assign({},o),{headers:u}))})};function Dm(e){return e.replace(/\/$/,"")}function zm(e,t){const{db:n,auth:r,realtime:i,global:s}=e,{db:o,auth:l,realtime:a,global:u}=t;return{db:Object.assign(Object.assign({},o),n),auth:Object.assign(Object.assign({},l),r),realtime:Object.assign(Object.assign({},a),i),global:Object.assign(Object.assign({},u),s)}}const af="2.64.2",Fm="http://localhost:9999",Mm="supabase.auth.token",bm={"X-Client-Info":`gotrue-js/${af}`},Su=10,Qo="X-Supabase-Api-Version",uf={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Bm(e){return Math.round(Date.now()/1e3)+e}function Vm(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=Math.random()*16|0;return(e=="x"?t:t&3|8).toString(16)})}const De=()=>typeof document<"u",Ut={tested:!1,writable:!1},hr=()=>{if(!De())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Ut.tested)return Ut.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),Ut.tested=!0,Ut.writable=!0}catch{Ut.tested=!0,Ut.writable=!1}return Ut.writable};function Hs(e){const t={},n=new URL(e);if(n.hash&&n.hash[0]==="#")try{new URLSearchParams(n.hash.substring(1)).forEach((i,s)=>{t[s]=i})}catch{}return n.searchParams.forEach((r,i)=>{t[i]=r}),t}const cf=e=>{let t;return e?t=e:typeof fetch>"u"?t=(...n)=>Nn(()=>Promise.resolve().then(()=>Fr),void 0,import.meta.url).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},Hm=e=>typeof e=="object"&&e!==null&&"status"in e&&"ok"in e&&"json"in e&&typeof e.json=="function",df=async(e,t,n)=>{await e.setItem(t,JSON.stringify(n))},si=async(e,t)=>{const n=await e.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return n}},Ws=async(e,t)=>{await e.removeItem(t)};function Wm(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let n="",r,i,s,o,l,a,u,c=0;for(e=e.replace("-","+").replace("_","/");c<e.length;)o=t.indexOf(e.charAt(c++)),l=t.indexOf(e.charAt(c++)),a=t.indexOf(e.charAt(c++)),u=t.indexOf(e.charAt(c++)),r=o<<2|l>>4,i=(l&15)<<4|a>>2,s=(a&3)<<6|u,n=n+String.fromCharCode(r),a!=64&&i!=0&&(n=n+String.fromCharCode(i)),u!=64&&s!=0&&(n=n+String.fromCharCode(s));return n}class hs{constructor(){this.promise=new hs.promiseConstructor((t,n)=>{this.resolve=t,this.reject=n})}}hs.promiseConstructor=Promise;function ku(e){const t=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,n=e.split(".");if(n.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!t.test(n[1]))throw new Error("JWT is not valid: payload is not in base64url format");const r=n[1];return JSON.parse(Wm(r))}async function Km(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}function Gm(e,t){return new Promise((r,i)=>{(async()=>{for(let s=0;s<1/0;s++)try{const o=await e(s);if(!t(s,null,o)){r(o);return}}catch(o){if(!t(s,o)){i(o);return}}})()})}function Qm(e){return("0"+e.toString(16)).substr(-2)}function Jm(){const t=new Uint32Array(56);if(typeof crypto>"u"){const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=n.length;let i="";for(let s=0;s<56;s++)i+=n.charAt(Math.floor(Math.random()*r));return i}return crypto.getRandomValues(t),Array.from(t,Qm).join("")}async function qm(e){const n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n),i=new Uint8Array(r);return Array.from(i).map(s=>String.fromCharCode(s)).join("")}function Ym(e){return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Xm(e){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."),e;const n=await qm(e);return Ym(n)}async function sn(e,t,n=!1){const r=Jm();let i=r;n&&(i+="/PASSWORD_RECOVERY"),await df(e,`${t}-code-verifier`,i);const s=await Xm(r);return[s,r===s?"plain":"s256"]}const Zm=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function eg(e){const t=e.headers.get(Qo);if(!t||!t.match(Zm))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}class ql extends Error{constructor(t,n,r){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=n,this.code=r}}function I(e){return typeof e=="object"&&e!==null&&"__isAuthError"in e}class tg extends ql{constructor(t,n,r){super(t,n,r),this.name="AuthApiError",this.status=n,this.code=r}}function ng(e){return I(e)&&e.name==="AuthApiError"}class ff extends ql{constructor(t,n){super(t),this.name="AuthUnknownError",this.originalError=n}}class tn extends ql{constructor(t,n,r,i){super(t,r,i),this.name=n,this.status=r}}class Dt extends tn{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}class Ks extends tn{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class oi extends tn{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class li extends tn{constructor(t,n=null){super(t,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=n}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class Eu extends tn{constructor(t,n=null){super(t,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=n}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class Jo extends tn{constructor(t,n){super(t,"AuthRetryableFetchError",n,void 0)}}function Gs(e){return I(e)&&e.name==="AuthRetryableFetchError"}class Cu extends tn{constructor(t,n,r){super(t,"AuthWeakPasswordError",n,"weak_password"),this.reasons=r}}var rg=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n};const Mt=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),ig=[502,503,504];async function xu(e){var t;if(!Hm(e))throw new Jo(Mt(e),0);if(ig.includes(e.status))throw new Jo(Mt(e),e.status);let n;try{n=await e.json()}catch(s){throw new ff(Mt(s),s)}let r;const i=eg(e);if(i&&i.getTime()>=uf["2024-01-01"].timestamp&&typeof n=="object"&&n&&typeof n.code=="string"?r=n.code:typeof n=="object"&&n&&typeof n.error_code=="string"&&(r=n.error_code),r){if(r==="weak_password")throw new Cu(Mt(n),e.status,((t=n.weak_password)===null||t===void 0?void 0:t.reasons)||[])}else if(typeof n=="object"&&n&&typeof n.weak_password=="object"&&n.weak_password&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.reasons.reduce((s,o)=>s&&typeof o=="string",!0))throw new Cu(Mt(n),e.status,n.weak_password.reasons);throw new tg(Mt(n),e.status||500,r)}const sg=(e,t,n,r)=>{const i={method:e,headers:(t==null?void 0:t.headers)||{}};return e==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},t==null?void 0:t.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),n))};async function N(e,t,n,r){var i;const s=Object.assign({},r==null?void 0:r.headers);s[Qo]||(s[Qo]=uf["2024-01-01"].name),r!=null&&r.jwt&&(s.Authorization=`Bearer ${r.jwt}`);const o=(i=r==null?void 0:r.query)!==null&&i!==void 0?i:{};r!=null&&r.redirectTo&&(o.redirect_to=r.redirectTo);const l=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",a=await og(e,t,n+l,{headers:s,noResolveJson:r==null?void 0:r.noResolveJson},{},r==null?void 0:r.body);return r!=null&&r.xform?r==null?void 0:r.xform(a):{data:Object.assign({},a),error:null}}async function og(e,t,n,r,i,s){const o=sg(t,r,i,s);let l;try{l=await e(n,Object.assign({},o))}catch(a){throw console.error(a),new Jo(Mt(a),0)}if(l.ok||await xu(l),r!=null&&r.noResolveJson)return l;try{return await l.json()}catch(a){await xu(a)}}function dt(e){var t;let n=null;cg(e)&&(n=Object.assign({},e),e.expires_at||(n.expires_at=Bm(e.expires_in)));const r=(t=e.user)!==null&&t!==void 0?t:e;return{data:{session:n,user:r},error:null}}function Pu(e){const t=dt(e);return!t.error&&e.weak_password&&typeof e.weak_password=="object"&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&typeof e.weak_password.message=="string"&&e.weak_password.reasons.reduce((n,r)=>n&&typeof r=="string",!0)&&(t.data.weak_password=e.weak_password),t}function gt(e){var t;return{data:{user:(t=e.user)!==null&&t!==void 0?t:e},error:null}}function lg(e){return{data:e,error:null}}function ag(e){const{action_link:t,email_otp:n,hashed_token:r,redirect_to:i,verification_type:s}=e,o=rg(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),l={action_link:t,email_otp:n,hashed_token:r,redirect_to:i,verification_type:s},a=Object.assign({},o);return{data:{properties:l,user:a},error:null}}function ug(e){return e}function cg(e){return e.access_token&&e.refresh_token&&e.expires_in}var dg=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n};class fg{constructor({url:t="",headers:n={},fetch:r}){this.url=t,this.headers=n,this.fetch=cf(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(t,n="global"){try{return await N(this.fetch,"POST",`${this.url}/logout?scope=${n}`,{headers:this.headers,jwt:t,noResolveJson:!0}),{data:null,error:null}}catch(r){if(I(r))return{data:null,error:r};throw r}}async inviteUserByEmail(t,n={}){try{return await N(this.fetch,"POST",`${this.url}/invite`,{body:{email:t,data:n.data},headers:this.headers,redirectTo:n.redirectTo,xform:gt})}catch(r){if(I(r))return{data:{user:null},error:r};throw r}}async generateLink(t){try{const{options:n}=t,r=dg(t,["options"]),i=Object.assign(Object.assign({},r),n);return"newEmail"in r&&(i.new_email=r==null?void 0:r.newEmail,delete i.newEmail),await N(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:ag,redirectTo:n==null?void 0:n.redirectTo})}catch(n){if(I(n))return{data:{properties:null,user:null},error:n};throw n}}async createUser(t){try{return await N(this.fetch,"POST",`${this.url}/admin/users`,{body:t,headers:this.headers,xform:gt})}catch(n){if(I(n))return{data:{user:null},error:n};throw n}}async listUsers(t){var n,r,i,s,o,l,a;try{const u={nextPage:null,lastPage:0,total:0},c=await N(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(n=t==null?void 0:t.page)===null||n===void 0?void 0:n.toString())!==null&&r!==void 0?r:"",per_page:(s=(i=t==null?void 0:t.perPage)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""},xform:ug});if(c.error)throw c.error;const d=await c.json(),h=(o=c.headers.get("x-total-count"))!==null&&o!==void 0?o:0,m=(a=(l=c.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&a!==void 0?a:[];return m.length>0&&(m.forEach(g=>{const y=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(g.split(";")[1].split("=")[1]);u[`${_}Page`]=y}),u.total=parseInt(h)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(I(u))return{data:{users:[]},error:u};throw u}}async getUserById(t){try{return await N(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:gt})}catch(n){if(I(n))return{data:{user:null},error:n};throw n}}async updateUserById(t,n){try{return await N(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:n,headers:this.headers,xform:gt})}catch(r){if(I(r))return{data:{user:null},error:r};throw r}}async deleteUser(t,n=!1){try{return await N(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:n},xform:gt})}catch(r){if(I(r))return{data:{user:null},error:r};throw r}}async _listFactors(t){try{const{data:n,error:r}=await N(this.fetch,"GET",`${this.url}/admin/users/${t.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:n,error:r}}catch(n){if(I(n))return{data:null,error:n};throw n}}async _deleteFactor(t){try{return{data:await N(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(n){if(I(n))return{data:null,error:n};throw n}}}const hg={getItem:e=>hr()?globalThis.localStorage.getItem(e):null,setItem:(e,t)=>{hr()&&globalThis.localStorage.setItem(e,t)},removeItem:e=>{hr()&&globalThis.localStorage.removeItem(e)}};function Tu(e={}){return{getItem:t=>e[t]||null,setItem:(t,n)=>{e[t]=n},removeItem:t=>{delete e[t]}}}function pg(){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)}}const on={debug:!!(globalThis&&hr()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class hf extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class vg extends hf{}async function mg(e,t,n){on.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);const r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort(),on.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t),await globalThis.navigator.locks.request(e,t===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async i=>{if(i){on.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,i.name);try{return await n()}finally{on.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",e,i.name)}}else{if(t===0)throw on.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new vg(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(on.debug)try{const s=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(s,null,"  "))}catch(s){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",s)}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 n()}})}pg();const gg={url:Fm,storageKey:Mm,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:bm,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},Yn=30*1e3,Ou=3;async function Ru(e,t,n){return await n()}class $r{constructor(t){var n,r;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=$r.nextInstanceID,$r.nextInstanceID+=1,this.instanceID>0&&De()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");const i=Object.assign(Object.assign({},gg),t);if(this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.persistSession=i.persistSession,this.storageKey=i.storageKey,this.autoRefreshToken=i.autoRefreshToken,this.admin=new fg({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=cf(i.fetch),this.lock=i.lock||Ru,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:De()&&(!((n=globalThis==null?void 0:globalThis.navigator)===null||n===void 0)&&n.locks)?this.lock=mg:this.lock=Ru,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)},this.persistSession?i.storage?this.storage=i.storage:hr()?this.storage=hg:(this.memoryStorage={},this.storage=Tu(this.memoryStorage)):(this.memoryStorage={},this.storage=Tu(this.memoryStorage)),De()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(s){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",s)}(r=this.broadcastChannel)===null||r===void 0||r.addEventListener("message",async s=>{this._debug("received broadcast notification from other tab or client",s),await this._notifyAllSubscribers(s.data.event,s.data.session,!1)})}this.initialize()}_debug(...t){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${af}) ${new Date().toISOString()}`,...t),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(){try{const t=De()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",t),t||this.detectSessionInUrl&&this._isImplicitGrantFlow()){const{data:n,error:r}=await this._getSessionFromURL(t);if(r)return this._debug("#_initialize()","error detecting session from URL",r),(r==null?void 0:r.message)==="Identity is already linked"||(r==null?void 0:r.message)==="Identity is already linked to another user"?{error:r}:(await this._removeSession(),{error:r});const{session:i,redirectType:s}=n;return this._debug("#_initialize()","detected session in URL",i,"redirect type",s),await this._saveSession(i),setTimeout(async()=>{s==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return I(t)?{error:t}:{error:new ff("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var n,r,i;try{await this._removeSession();const s=await N(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(n=t==null?void 0:t.options)===null||n===void 0?void 0:n.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(i=t==null?void 0:t.options)===null||i===void 0?void 0:i.captchaToken}},xform:dt}),{data:o,error:l}=s;if(l||!o)return{data:{user:null,session:null},error:l};const a=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",a)),{data:{user:u,session:a},error:null}}catch(s){if(I(s))return{data:{user:null,session:null},error:s};throw s}}async signUp(t){var n,r,i;try{await this._removeSession();let s;if("email"in t){const{email:c,password:d,options:h}=t;let m=null,g=null;this.flowType==="pkce"&&([m,g]=await sn(this.storage,this.storageKey)),s=await N(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:h==null?void 0:h.emailRedirectTo,body:{email:c,password:d,data:(n=h==null?void 0:h.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:h==null?void 0:h.captchaToken},code_challenge:m,code_challenge_method:g},xform:dt})}else if("phone"in t){const{phone:c,password:d,options:h}=t;s=await N(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:d,data:(r=h==null?void 0:h.data)!==null&&r!==void 0?r:{},channel:(i=h==null?void 0:h.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:h==null?void 0:h.captchaToken}},xform:dt})}else throw new oi("You must provide either an email or phone number and a password");const{data:o,error:l}=s;if(l||!o)return{data:{user:null,session:null},error:l};const a=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",a)),{data:{user:u,session:a},error:null}}catch(s){if(I(s))return{data:{user:null,session:null},error:s};throw s}}async signInWithPassword(t){try{await this._removeSession();let n;if("email"in t){const{email:s,password:o,options:l}=t;n=await N(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:o,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:Pu})}else if("phone"in t){const{phone:s,password:o,options:l}=t;n=await N(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:o,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:Pu})}else throw new oi("You must provide either an email or phone number and a password");const{data:r,error:i}=n;return i?{data:{user:null,session:null},error:i}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new Ks}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:i})}catch(n){if(I(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithOAuth(t){var n,r,i,s;return await this._removeSession(),await this._handleProviderSignIn(t.provider,{redirectTo:(n=t.options)===null||n===void 0?void 0:n.redirectTo,scopes:(r=t.options)===null||r===void 0?void 0:r.scopes,queryParams:(i=t.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(s=t.options)===null||s===void 0?void 0:s.skipBrowserRedirect})}async exchangeCodeForSession(t){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(t))}async _exchangeCodeForSession(t){const n=await si(this.storage,`${this.storageKey}-code-verifier`),[r,i]=(n??"").split("/"),{data:s,error:o}=await N(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:r},xform:dt});return await Ws(this.storage,`${this.storageKey}-code-verifier`),o?{data:{user:null,session:null,redirectType:null},error:o}:!s||!s.session||!s.user?{data:{user:null,session:null,redirectType:null},error:new Ks}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign(Object.assign({},s),{redirectType:i??null}),error:o})}async signInWithIdToken(t){await this._removeSession();try{const{options:n,provider:r,token:i,access_token:s,nonce:o}=t,l=await N(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:i,access_token:s,nonce:o,gotrue_meta_security:{captcha_token:n==null?void 0:n.captchaToken}},xform:dt}),{data:a,error:u}=l;return u?{data:{user:null,session:null},error:u}:!a||!a.session||!a.user?{data:{user:null,session:null},error:new Ks}:(a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),{data:a,error:u})}catch(n){if(I(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithOtp(t){var n,r,i,s,o;try{if(await this._removeSession(),"email"in t){const{email:l,options:a}=t;let u=null,c=null;this.flowType==="pkce"&&([u,c]=await sn(this.storage,this.storageKey));const{error:d}=await N(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:l,data:(n=a==null?void 0:a.data)!==null&&n!==void 0?n:{},create_user:(r=a==null?void 0:a.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken},code_challenge:u,code_challenge_method:c},redirectTo:a==null?void 0:a.emailRedirectTo});return{data:{user:null,session:null},error:d}}if("phone"in t){const{phone:l,options:a}=t,{data:u,error:c}=await N(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:l,data:(i=a==null?void 0:a.data)!==null&&i!==void 0?i:{},create_user:(s=a==null?void 0:a.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken},channel:(o=a==null?void 0:a.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:u==null?void 0:u.message_id},error:c}}throw new oi("You must provide either an email or phone number.")}catch(l){if(I(l))return{data:{user:null,session:null},error:l};throw l}}async verifyOtp(t){var n,r;try{t.type!=="email_change"&&t.type!=="phone_change"&&await this._removeSession();let i,s;"options"in t&&(i=(n=t.options)===null||n===void 0?void 0:n.redirectTo,s=(r=t.options)===null||r===void 0?void 0:r.captchaToken);const{data:o,error:l}=await N(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:s}}),redirectTo:i,xform:dt});if(l)throw l;if(!o)throw new Error("An error occurred on token verification.");const a=o.session,u=o.user;return a!=null&&a.access_token&&(await this._saveSession(a),await this._notifyAllSubscribers(t.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",a)),{data:{user:u,session:a},error:null}}catch(i){if(I(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(t){var n,r,i;try{await this._removeSession();let s=null,o=null;return this.flowType==="pkce"&&([s,o]=await sn(this.storage,this.storageKey)),await N(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in t?{provider_id:t.providerId}:null),"domain"in t?{domain:t.domain}:null),{redirect_to:(r=(n=t.options)===null||n===void 0?void 0:n.redirectTo)!==null&&r!==void 0?r:void 0}),!((i=t==null?void 0:t.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:t.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:s,code_challenge_method:o}),headers:this.headers,xform:lg})}catch(s){if(I(s))return{data:null,error:s};throw s}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async t=>{const{data:{session:n},error:r}=t;if(r)throw r;if(!n)throw new Dt;const{error:i}=await N(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:n.access_token});return{data:{user:null,session:null},error:i}})}catch(t){if(I(t))return{data:{user:null,session:null},error:t};throw t}}async resend(t){try{t.type!="email_change"&&t.type!="phone_change"&&await this._removeSession();const n=`${this.url}/resend`;if("email"in t){const{email:r,type:i,options:s}=t,{error:o}=await N(this.fetch,"POST",n,{headers:this.headers,body:{email:r,type:i,gotrue_meta_security:{captcha_token:s==null?void 0:s.captchaToken}},redirectTo:s==null?void 0:s.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in t){const{phone:r,type:i,options:s}=t,{data:o,error:l}=await N(this.fetch,"POST",n,{headers:this.headers,body:{phone:r,type:i,gotrue_meta_security:{captcha_token:s==null?void 0:s.captchaToken}}});return{data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:l}}throw new oi("You must provide either an email or phone number and a type")}catch(n){if(I(n))return{data:{user:null,session:null},error:n};throw n}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async n=>n))}async _acquireLock(t,n){this._debug("#_acquireLock","begin",t);try{if(this.lockAcquired){const r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await r,await n()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,t,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const r=n();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){const i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(t){this._debug("#_useSession","begin");try{const n=await this.__loadSession();return await t(n)}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 t=null;const n=await si(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",n),n!==null&&(this._isValidSession(n)?t=n:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!t)return{data:{session:null},error:null};const r=t.expires_at?t.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",t.expires_at),!r){if(this.storage.isServer){const o=this.suppressGetSessionWarning;t=new Proxy(t,{get(a,u,c){return!o&&u==="user"&&console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),Reflect.get(a,u,c)}})}return{data:{session:t},error:null}}const{session:i,error:s}=await this._callRefreshToken(t.refresh_token);return s?{data:{session:null},error:s}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(t){return t?await this._getUser(t):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(t){try{return t?await N(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:gt}):await this._useSession(async n=>{var r,i,s;const{data:o,error:l}=n;if(l)throw l;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Dt}:await N(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(s=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&s!==void 0?s:void 0,xform:gt})})}catch(n){if(I(n))return{data:{user:null},error:n};throw n}}async updateUser(t,n={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(t,n))}async _updateUser(t,n={}){try{return await this._useSession(async r=>{const{data:i,error:s}=r;if(s)throw s;if(!i.session)throw new Dt;const o=i.session;let l=null,a=null;this.flowType==="pkce"&&t.email!=null&&([l,a]=await sn(this.storage,this.storageKey));const{data:u,error:c}=await N(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:n==null?void 0:n.emailRedirectTo,body:Object.assign(Object.assign({},t),{code_challenge:l,code_challenge_method:a}),jwt:o.access_token,xform:gt});if(c)throw c;return o.user=u.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(r){if(I(r))return{data:{user:null},error:r};throw r}}_decodeJWT(t){return ku(t)}async setSession(t){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(t))}async _setSession(t){try{if(!t.access_token||!t.refresh_token)throw new Dt;const n=Date.now()/1e3;let r=n,i=!0,s=null;const o=ku(t.access_token);if(o.exp&&(r=o.exp,i=r<=n),i){const{session:l,error:a}=await this._callRefreshToken(t.refresh_token);if(a)return{data:{user:null,session:null},error:a};if(!l)return{data:{user:null,session:null},error:null};s=l}else{const{data:l,error:a}=await this._getUser(t.access_token);if(a)throw a;s={access_token:t.access_token,refresh_token:t.refresh_token,user:l.user,token_type:"bearer",expires_in:r-n,expires_at:r},await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)}return{data:{user:s.user,session:s},error:null}}catch(n){if(I(n))return{data:{session:null,user:null},error:n};throw n}}async refreshSession(t){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(t))}async _refreshSession(t){try{return await this._useSession(async n=>{var r;if(!t){const{data:o,error:l}=n;if(l)throw l;t=(r=o.session)!==null&&r!==void 0?r:void 0}if(!(t!=null&&t.refresh_token))throw new Dt;const{session:i,error:s}=await this._callRefreshToken(t.refresh_token);return s?{data:{user:null,session:null},error:s}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(n){if(I(n))return{data:{user:null,session:null},error:n};throw n}}async _getSessionFromURL(t){try{if(!De())throw new li("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new li("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!t)throw new Eu("Not a valid PKCE flow url.");const n=Hs(window.location.href);if(t){if(!n.code)throw new Eu("No code detected.");const{data:f,error:v}=await this._exchangeCodeForSession(n.code);if(v)throw v;const w=new URL(window.location.href);return w.searchParams.delete("code"),window.history.replaceState(window.history.state,"",w.toString()),{data:{session:f.session,redirectType:null},error:null}}if(n.error||n.error_description||n.error_code)throw new li(n.error_description||"Error in URL with unspecified error_description",{error:n.error||"unspecified_error",code:n.error_code||"unspecified_code"});const{provider_token:r,provider_refresh_token:i,access_token:s,refresh_token:o,expires_in:l,expires_at:a,token_type:u}=n;if(!s||!l||!o||!u)throw new li("No session defined in URL");const c=Math.round(Date.now()/1e3),d=parseInt(l);let h=c+d;a&&(h=parseInt(a));const m=h-c;m*1e3<=Yn&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${d}s`);const g=h-d;c-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,h,c):c-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",g,h,c);const{data:y,error:_}=await this._getUser(s);if(_)throw _;const p={provider_token:r,provider_refresh_token:i,access_token:s,expires_in:d,expires_at:h,refresh_token:o,token_type:u,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:p,redirectType:n.type},error:null}}catch(n){if(I(n))return{data:{session:null,redirectType:null},error:n};throw n}}_isImplicitGrantFlow(){const t=Hs(window.location.href);return!!(De()&&(t.access_token||t.error_description))}async _isPKCEFlow(){const t=Hs(window.location.href),n=await si(this.storage,`${this.storageKey}-code-verifier`);return!!(t.code&&n)}async signOut(t={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(t))}async _signOut({scope:t}={scope:"global"}){return await this._useSession(async n=>{var r;const{data:i,error:s}=n;if(s)return{error:s};const o=(r=i.session)===null||r===void 0?void 0:r.access_token;if(o){const{error:l}=await this.admin.signOut(o,t);if(l&&!(ng(l)&&(l.status===404||l.status===401||l.status===403)))return{error:l}}return t!=="others"&&(await this._removeSession(),await Ws(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(t){const n=Vm(),r={id:n,callback:t,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",n),this.stateChangeEmitters.delete(n)}};return this._debug("#onAuthStateChange()","registered callback with id",n),this.stateChangeEmitters.set(n,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(n)})))(),{data:{subscription:r}}}async _emitInitialSession(t){return await this._useSession(async n=>{var r,i;try{const{data:{session:s},error:o}=n;if(o)throw o;await((r=this.stateChangeEmitters.get(t))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",t,"session",s)}catch(s){await((i=this.stateChangeEmitters.get(t))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",t,"error",s),console.error(s)}})}async resetPasswordForEmail(t,n={}){let r=null,i=null;this.flowType==="pkce"&&([r,i]=await sn(this.storage,this.storageKey,!0));try{return await N(this.fetch,"POST",`${this.url}/recover`,{body:{email:t,code_challenge:r,code_challenge_method:i,gotrue_meta_security:{captcha_token:n.captchaToken}},headers:this.headers,redirectTo:n.redirectTo})}catch(s){if(I(s))return{data:null,error:s};throw s}}async getUserIdentities(){var t;try{const{data:n,error:r}=await this.getUser();if(r)throw r;return{data:{identities:(t=n.user.identities)!==null&&t!==void 0?t:[]},error:null}}catch(n){if(I(n))return{data:null,error:n};throw n}}async linkIdentity(t){var n;try{const{data:r,error:i}=await this._useSession(async s=>{var o,l,a,u,c;const{data:d,error:h}=s;if(h)throw h;const m=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,t.provider,{redirectTo:(o=t.options)===null||o===void 0?void 0:o.redirectTo,scopes:(l=t.options)===null||l===void 0?void 0:l.scopes,queryParams:(a=t.options)===null||a===void 0?void 0:a.queryParams,skipBrowserRedirect:!0});return await N(this.fetch,"GET",m,{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(i)throw i;return De()&&!(!((n=t.options)===null||n===void 0)&&n.skipBrowserRedirect)&&window.location.assign(r==null?void 0:r.url),{data:{provider:t.provider,url:r==null?void 0:r.url},error:null}}catch(r){if(I(r))return{data:{provider:t.provider,url:null},error:r};throw r}}async unlinkIdentity(t){try{return await this._useSession(async n=>{var r,i;const{data:s,error:o}=n;if(o)throw o;return await N(this.fetch,"DELETE",`${this.url}/user/identities/${t.identity_id}`,{headers:this.headers,jwt:(i=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&i!==void 0?i:void 0})})}catch(n){if(I(n))return{data:null,error:n};throw n}}async _refreshAccessToken(t){const n=`#_refreshAccessToken(${t.substring(0,5)}...)`;this._debug(n,"begin");try{const r=Date.now();return await Gm(async i=>(i>0&&await Km(200*Math.pow(2,i-1)),this._debug(n,"refreshing attempt",i),await N(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:dt})),(i,s)=>{const o=200*Math.pow(2,i);return s&&Gs(s)&&Date.now()+o-r<Yn})}catch(r){if(this._debug(n,"error",r),I(r))return{data:{session:null,user:null},error:r};throw r}finally{this._debug(n,"end")}}_isValidSession(t){return typeof t=="object"&&t!==null&&"access_token"in t&&"refresh_token"in t&&"expires_at"in t}async _handleProviderSignIn(t,n){const r=await this._getUrlForProvider(`${this.url}/authorize`,t,{redirectTo:n.redirectTo,scopes:n.scopes,queryParams:n.queryParams});return this._debug("#_handleProviderSignIn()","provider",t,"options",n,"url",r),De()&&!n.skipBrowserRedirect&&window.location.assign(r),{data:{provider:t,url:r},error:null}}async _recoverAndRefresh(){var t;const n="#_recoverAndRefresh()";this._debug(n,"begin");try{const r=await si(this.storage,this.storageKey);if(this._debug(n,"session from storage",r),!this._isValidSession(r)){this._debug(n,"session is not valid"),r!==null&&await this._removeSession();return}const i=Math.round(Date.now()/1e3),s=((t=r.expires_at)!==null&&t!==void 0?t:1/0)<i+Su;if(this._debug(n,`session has${s?"":" not"} expired with margin of ${Su}s`),s){if(this.autoRefreshToken&&r.refresh_token){const{error:o}=await this._callRefreshToken(r.refresh_token);o&&(console.error(o),Gs(o)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",r)}catch(r){this._debug(n,"error",r),console.error(r);return}finally{this._debug(n,"end")}}async _callRefreshToken(t){var n,r;if(!t)throw new Dt;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const i=`#_callRefreshToken(${t.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new hs;const{data:s,error:o}=await this._refreshAccessToken(t);if(o)throw o;if(!s.session)throw new Dt;await this._saveSession(s.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",s.session);const l={session:s.session,error:null};return this.refreshingDeferred.resolve(l),l}catch(s){if(this._debug(i,"error",s),I(s)){const o={session:null,error:s};return Gs(s)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(n=this.refreshingDeferred)===null||n===void 0||n.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(s),s}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(t,n,r=!0){const i=`#_notifyAllSubscribers(${t})`;this._debug(i,"begin",n,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:t,session:n});const s=[],o=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(t,n)}catch(a){s.push(a)}});if(await Promise.all(o),s.length>0){for(let l=0;l<s.length;l+=1)console.error(s[l]);throw s[0]}}finally{this._debug(i,"end")}}async _saveSession(t){this._debug("#_saveSession()",t),this.suppressGetSessionWarning=!0,await df(this.storage,this.storageKey,t)}async _removeSession(){this._debug("#_removeSession()"),await Ws(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const t=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{t&&De()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",t)}catch(n){console.error("removing visibilitychange callback failed",n)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const t=setInterval(()=>this._autoRefreshTokenTick(),Yn);this.autoRefreshTicker=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const t=this.autoRefreshTicker;this.autoRefreshTicker=null,t&&clearInterval(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const t=Date.now();try{return await this._useSession(async n=>{const{data:{session:r}}=n;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const i=Math.floor((r.expires_at*1e3-t)/Yn);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Yn}ms, refresh threshold is ${Ou} ticks`),i<=Ou&&await this._callRefreshToken(r.refresh_token)})}catch(n){console.error("Auto refresh tick failed with error. This is likely a transient error.",n)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(t){if(t.isAcquireTimeout||t instanceof hf)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!De()||!(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(t){console.error("_handleVisibilityChange",t)}}async _onVisibilityChanged(t){const n=`#_onVisibilityChanged(${t})`;this._debug(n,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),t||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(n,"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(t,n,r){const i=[`provider=${encodeURIComponent(n)}`];if(r!=null&&r.redirectTo&&i.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r!=null&&r.scopes&&i.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){const[s,o]=await sn(this.storage,this.storageKey),l=new URLSearchParams({code_challenge:`${encodeURIComponent(s)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(l.toString())}if(r!=null&&r.queryParams){const s=new URLSearchParams(r.queryParams);i.push(s.toString())}return r!=null&&r.skipBrowserRedirect&&i.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${t}?${i.join("&")}`}async _unenroll(t){try{return await this._useSession(async n=>{var r;const{data:i,error:s}=n;return s?{data:null,error:s}:await N(this.fetch,"DELETE",`${this.url}/factors/${t.factorId}`,{headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token})})}catch(n){if(I(n))return{data:null,error:n};throw n}}async _enroll(t){try{return await this._useSession(async n=>{var r,i;const{data:s,error:o}=n;if(o)return{data:null,error:o};const{data:l,error:a}=await N(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:t.friendlyName,factor_type:t.factorType,issuer:t.issuer},headers:this.headers,jwt:(r=s==null?void 0:s.session)===null||r===void 0?void 0:r.access_token});return a?{data:null,error:a}:(!((i=l==null?void 0:l.totp)===null||i===void 0)&&i.qr_code&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),{data:l,error:null})})}catch(n){if(I(n))return{data:null,error:n};throw n}}async _verify(t){return this._acquireLock(-1,async()=>{try{return await this._useSession(async n=>{var r;const{data:i,error:s}=n;if(s)return{data:null,error:s};const{data:o,error:l}=await N(this.fetch,"POST",`${this.url}/factors/${t.factorId}/verify`,{body:{code:t.code,challenge_id:t.challengeId},headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token});return l?{data:null,error:l}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:l})})}catch(n){if(I(n))return{data:null,error:n};throw n}})}async _challenge(t){return this._acquireLock(-1,async()=>{try{return await this._useSession(async n=>{var r;const{data:i,error:s}=n;return s?{data:null,error:s}:await N(this.fetch,"POST",`${this.url}/factors/${t.factorId}/challenge`,{headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token})})}catch(n){if(I(n))return{data:null,error:n};throw n}})}async _challengeAndVerify(t){const{data:n,error:r}=await this._challenge({factorId:t.factorId});return r?{data:null,error:r}:await this._verify({factorId:t.factorId,challengeId:n.id,code:t.code})}async _listFactors(){const{data:{user:t},error:n}=await this.getUser();if(n)return{data:null,error:n};const r=(t==null?void 0:t.factors)||[],i=r.filter(s=>s.factor_type==="totp"&&s.status==="verified");return{data:{all:r,totp:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async t=>{var n,r;const{data:{session:i},error:s}=t;if(s)return{data:null,error:s};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const o=this._decodeJWT(i.access_token);let l=null;o.aal&&(l=o.aal);let a=l;((r=(n=i.user.factors)===null||n===void 0?void 0:n.filter(d=>d.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(a="aal2");const c=o.amr||[];return{data:{currentLevel:l,nextLevel:a,currentAuthenticationMethods:c},error:null}}))}}$r.nextInstanceID=0;const yg=$r;class wg extends yg{constructor(t){super(t)}}var _g=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};class Sg{constructor(t,n,r){var i,s,o;if(this.supabaseUrl=t,this.supabaseKey=n,!t)throw new Error("supabaseUrl is required.");if(!n)throw new Error("supabaseKey is required.");const l=Dm(t);this.realtimeUrl=`${l}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${l}/auth/v1`,this.storageUrl=`${l}/storage/v1`,this.functionsUrl=`${l}/functions/v1`;const a=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,u={db:jm,realtime:Im,auth:Object.assign(Object.assign({},Lm),{storageKey:a}),global:Rm},c=zm(r??{},u);this.storageKey=(i=c.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(s=c.global.headers)!==null&&s!==void 0?s:{},this.auth=this._initSupabaseAuthClient((o=c.auth)!==null&&o!==void 0?o:{},this.headers,c.global.fetch),this.fetch=Um(n,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},c.realtime)),this.rest=new Gl(`${l}/rest/v1`,{headers:this.headers,schema:c.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new Vv(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Pm(this.storageUrl,this.headers,this.fetch)}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,n={},r={}){return this.rest.rpc(t,n,r)}channel(t,n={config:{}}){return this.realtime.channel(t,n)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var t,n;return _g(this,void 0,void 0,function*(){const{data:r}=yield this.auth.getSession();return(n=(t=r.session)===null||t===void 0?void 0:t.access_token)!==null&&n!==void 0?n:null})}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:n,detectSessionInUrl:r,storage:i,storageKey:s,flowType:o,debug:l},a,u){var c;const d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new wg({url:this.authUrl,headers:Object.assign(Object.assign({},d),a),storageKey:s,autoRefreshToken:t,persistSession:n,detectSessionInUrl:r,storage:i,flowType:o,debug:l,fetch:u,hasCustomAuthorizationHeader:(c="Authorization"in this.headers)!==null&&c!==void 0?c:!1})}_initRealtimeClient(t){return new hm(this.realtimeUrl,Object.assign(Object.assign({},t),{params:Object.assign({apikey:this.supabaseKey},t==null?void 0:t.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((n,r)=>{this._handleTokenChanged(n,"CLIENT",r==null?void 0:r.access_token)})}_handleTokenChanged(t,n,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.realtime.setAuth(r??null),this.changedAccessToken=r):t==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),n=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const kg=(e,t,n)=>new Sg(e,t,n);function Eg(e){const t=Xd(),[n,r]=E.useState([]);E.useEffect(()=>{e.session||t("/login")},[e.session]);const i=E.useCallback(async()=>{const{data:s,error:o}=await e.supabase.from("file").select();if(o){console.error(o);return}r(s.map(l=>l))},[e.supabase]);return E.useEffect(()=>{i()},[]),z.jsx(z.Fragment,{children:z.jsxs("div",{children:[z.jsx("h1",{className:"font-bold",children:"Home"}),z.jsx("p",{children:"Logged in!"}),n.map(s=>z.jsx("div",{children:z.jsxs("p",{className:"underline",children:["file: ",s.absolute_path]})},s.id))]})})}function Cg(e={}){const{nonce:t,onScriptLoadSuccess:n,onScriptLoadError:r}=e,[i,s]=E.useState(!1),o=E.useRef(n);o.current=n;const l=E.useRef(r);return l.current=r,E.useEffect(()=>{const a=document.createElement("script");return a.src="https://accounts.google.com/gsi/client",a.async=!0,a.defer=!0,a.nonce=t,a.onload=()=>{var u;s(!0),(u=o.current)===null||u===void 0||u.call(o)},a.onerror=()=>{var u;s(!1),(u=l.current)===null||u===void 0||u.call(l)},document.body.appendChild(a),()=>{document.body.removeChild(a)}},[t]),i}const pf=E.createContext(null);function xg({clientId:e,nonce:t,onScriptLoadSuccess:n,onScriptLoadError:r,children:i}){const s=Cg({nonce:t,onScriptLoadSuccess:n,onScriptLoadError:r}),o=E.useMemo(()=>({clientId:e,scriptLoadedSuccessfully:s}),[e,s]);return Gi.createElement(pf.Provider,{value:o},i)}function Pg(){const e=E.useContext(pf);if(!e)throw new Error("Google OAuth components must be used within GoogleOAuthProvider");return e}function Tg(e){var t;return(t=e==null?void 0:e.clientId)!==null&&t!==void 0?t:e==null?void 0:e.client_id}const Og={large:40,medium:32,small:20};function Rg({onSuccess:e,onError:t,useOneTap:n,promptMomentNotification:r,type:i="standard",theme:s="outline",size:o="large",text:l,shape:a,logo_alignment:u,width:c,locale:d,click_listener:h,containerProps:m,...g}){const y=E.useRef(null),{clientId:_,scriptLoadedSuccessfully:p}=Pg(),f=E.useRef(e);f.current=e;const v=E.useRef(t);v.current=t;const w=E.useRef(r);return w.current=r,E.useEffect(()=>{var k,P,T,O,M,j,de,qe,Ye;if(p)return(T=(P=(k=window==null?void 0:window.google)===null||k===void 0?void 0:k.accounts)===null||P===void 0?void 0:P.id)===null||T===void 0||T.initialize({client_id:_,callback:Oe=>{var Xe;if(!(Oe!=null&&Oe.credential))return(Xe=v.current)===null||Xe===void 0?void 0:Xe.call(v);const{credential:Ze,select_by:Bn}=Oe;f.current({credential:Ze,clientId:Tg(Oe),select_by:Bn})},...g}),(j=(M=(O=window==null?void 0:window.google)===null||O===void 0?void 0:O.accounts)===null||M===void 0?void 0:M.id)===null||j===void 0||j.renderButton(y.current,{type:i,theme:s,size:o,text:l,shape:a,logo_alignment:u,width:c,locale:d,click_listener:h}),n&&((Ye=(qe=(de=window==null?void 0:window.google)===null||de===void 0?void 0:de.accounts)===null||qe===void 0?void 0:qe.id)===null||Ye===void 0||Ye.prompt(w.current)),()=>{var Oe,Xe,Ze;n&&((Ze=(Xe=(Oe=window==null?void 0:window.google)===null||Oe===void 0?void 0:Oe.accounts)===null||Xe===void 0?void 0:Xe.id)===null||Ze===void 0||Ze.cancel())}},[_,p,n,i,s,o,l,a,u,c,d]),Gi.createElement("div",{...m,ref:y,style:{height:Og[o],...m==null?void 0:m.style}})}function jg(e){const t=Xd();return E.useEffect(()=>{e.supabase.auth.getSession().then(({data:{session:r}})=>{e.setSession(r),console.log("LOGIN SESSION",r)});const{data:{subscription:n}}=e.supabase.auth.onAuthStateChange((r,i)=>{e.setSession(i),console.log("SESSION CHANGE",i)});return()=>n.unsubscribe()},[e.supabase]),E.useEffect(()=>{e.session&&t("/")},[e.session]),z.jsxs(z.Fragment,{children:[z.jsxs("div",{children:[z.jsx("h1",{children:"Login"}),z.jsxs("p",{children:["Log in to access your account! ",JSON.stringify(e.session)]})]}),z.jsx(xg,{clientId:"952965459060-nrnrsdoq22mf646vfa72hk410pvdda5q.apps.googleusercontent.com",children:z.jsx(Rg,{onSuccess:async n=>{await e.supabase.auth.signInWithIdToken({provider:"google",token:n.credential})},onError:()=>{console.log("Login Failed")}})})]})}const ju=kg("https://slpoocycjgqsuoedhkbn.supabase.co","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InNscG9vY3ljamdxc3VvZWRoa2JuIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTUyMDU0MjUsImV4cCI6MjAzMDc4MTQyNX0.xZYRTRN65rlms1Hb96IBAQvw3EGtMzUxlGPP5TVey34");function Lg(){const[e,t]=E.useState(null);return z.jsx(z.Fragment,{children:z.jsx(Av,{basename:"/fs-tracer-frontend",children:z.jsxs(Iv,{children:[z.jsx(_i,{index:!0,element:z.jsx(Eg,{supabase:ju,session:e})}),z.jsx(_i,{path:"login",element:z.jsx(jg,{supabase:ju,session:e,setSession:t})}),z.jsx(_i,{path:"*",element:z.jsx("p",{children:"notfound"})})]})})})}Qs.createRoot(document.getElementById("root")).render(z.jsx(Gi.StrictMode,{children:z.jsx(Lg,{})}));export{mf as g};
diff --git a/index.html b/index.html
index 6602721..89e5667 100644
--- a/index.html
+++ b/index.html
@@ -30,8 +30,8 @@
       }(window.location))
     </script>
     <!-- End Single Page Apps for GitHub Pages -->
-    <script type="module" crossorigin src="./assets/index-B0RTX0s0.js"></script>
-    <link rel="stylesheet" crossorigin href="./assets/index-tmQ7CD-c.css">
+    <script type="module" crossorigin src="./assets/index-CbF1FLl3.js"></script>
+    <link rel="stylesheet" crossorigin href="./assets/index-C1q9-kv2.css">
   </head>
   <body>
     <div id="root"></div>