vue-3-supabase
Version:
Simple Vue 3 wrap for Supabase.js Client (v2) build with Vitejs
2 lines • 95 kB
JavaScript
(function(B,Z){typeof exports=="object"&&typeof module!="undefined"?Z(exports,require("vue")):typeof define=="function"&&define.amd?define(["exports","vue"],Z):(B=typeof globalThis!="undefined"?globalThis:B||self,Z(B["vue-3-supabase"]={},B.vue))})(this,function(B,Z){"use strict";function tt(n,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(r){if(r!=="default"&&!(r in n)){var i=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,i.get?i:{enumerable:!0,get:function(){return t[r]}})}})}),Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}var rt=globalThis&&globalThis.__awaiter||function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(r.next(c))}catch(d){o(d)}}function h(c){try{l(r.throw(c))}catch(d){o(d)}}function l(c){c.done?s(c.value):i(c.value).then(a,h)}l((r=r.apply(n,e||[])).next())})};const it=n=>{let e;return n?e=n:typeof fetch=="undefined"?e=(...t)=>rt(void 0,void 0,void 0,function*(){return yield(yield Promise.resolve().then(function(){return ae})).fetch(...t)}):e=fetch,(...t)=>e(...t)};class pe extends Error{constructor(e,t="FunctionsError",r){super(e),super.name=t,this.context=r}}class st extends pe{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class nt extends pe{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class ot extends pe{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var at=globalThis&&globalThis.__awaiter||function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(r.next(c))}catch(d){o(d)}}function h(c){try{l(r.throw(c))}catch(d){o(d)}}function l(c){c.done?s(c.value):i(c.value).then(a,h)}l((r=r.apply(n,e||[])).next())})};class ct{constructor(e,{headers:t={},customFetch:r}={}){this.url=e,this.headers=t,this.fetch=it(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return at(this,void 0,void 0,function*(){try{const{headers:i,method:s,body:o}=t;let a={},h;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob!="undefined"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",h=o):typeof o=="string"?(a["Content-Type"]="text/plain",h=o):typeof FormData!="undefined"&&o instanceof FormData?h=o:(a["Content-Type"]="application/json",h=JSON.stringify(o)));const l=yield this.fetch(`${this.url}/${e}`,{method:s||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:h}).catch(g=>{throw new st(g)}),c=l.headers.get("x-relay-error");if(c&&c==="true")throw new nt(l);if(!l.ok)throw new ot(l);let d=((r=l.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),p;return d==="application/json"?p=yield l.json():d==="application/octet-stream"?p=yield l.blob():d==="multipart/form-data"?p=yield l.formData():p=yield l.text(),{data:p,error:null}}catch(i){return{data:null,error:i}}})}}var ht=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function lt(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var ee={exports:{}};(function(n,e){var t=typeof self!="undefined"?self:ht,r=function(){function s(){this.fetch=!1,this.DOMException=t.DOMException}return s.prototype=t,new s}();(function(s){(function(o){var a={searchParams:"URLSearchParams"in s,iterable:"Symbol"in s&&"iterator"in Symbol,blob:"FileReader"in s&&"Blob"in s&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in s,arrayBuffer:"ArrayBuffer"in s};function h(u){return u&&DataView.prototype.isPrototypeOf(u)}if(a.arrayBuffer)var l=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(u){return u&&l.indexOf(Object.prototype.toString.call(u))>-1};function d(u){if(typeof u!="string"&&(u=String(u)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(u))throw new TypeError("Invalid character in header field name");return u.toLowerCase()}function p(u){return typeof u!="string"&&(u=String(u)),u}function g(u){var f={next:function(){var m=u.shift();return{done:m===void 0,value:m}}};return a.iterable&&(f[Symbol.iterator]=function(){return f}),f}function v(u){this.map={},u instanceof v?u.forEach(function(f,m){this.append(m,f)},this):Array.isArray(u)?u.forEach(function(f){this.append(f[0],f[1])},this):u&&Object.getOwnPropertyNames(u).forEach(function(f){this.append(f,u[f])},this)}v.prototype.append=function(u,f){u=d(u),f=p(f);var m=this.map[u];this.map[u]=m?m+", "+f:f},v.prototype.delete=function(u){delete this.map[d(u)]},v.prototype.get=function(u){return u=d(u),this.has(u)?this.map[u]:null},v.prototype.has=function(u){return this.map.hasOwnProperty(d(u))},v.prototype.set=function(u,f){this.map[d(u)]=p(f)},v.prototype.forEach=function(u,f){for(var m in this.map)this.map.hasOwnProperty(m)&&u.call(f,this.map[m],m,this)},v.prototype.keys=function(){var u=[];return this.forEach(function(f,m){u.push(m)}),g(u)},v.prototype.values=function(){var u=[];return this.forEach(function(f){u.push(f)}),g(u)},v.prototype.entries=function(){var u=[];return this.forEach(function(f,m){u.push([m,f])}),g(u)},a.iterable&&(v.prototype[Symbol.iterator]=v.prototype.entries);function b(u){if(u.bodyUsed)return Promise.reject(new TypeError("Already read"));u.bodyUsed=!0}function y(u){return new Promise(function(f,m){u.onload=function(){f(u.result)},u.onerror=function(){m(u.error)}})}function S(u){var f=new FileReader,m=y(f);return f.readAsArrayBuffer(u),m}function C(u){var f=new FileReader,m=y(f);return f.readAsText(u),m}function F(u){for(var f=new Uint8Array(u),m=new Array(f.length),x=0;x<f.length;x++)m[x]=String.fromCharCode(f[x]);return m.join("")}function j(u){if(u.slice)return u.slice(0);var f=new Uint8Array(u.byteLength);return f.set(new Uint8Array(u)),f.buffer}function V(){return this.bodyUsed=!1,this._initBody=function(u){this._bodyInit=u,u?typeof u=="string"?this._bodyText=u:a.blob&&Blob.prototype.isPrototypeOf(u)?this._bodyBlob=u:a.formData&&FormData.prototype.isPrototypeOf(u)?this._bodyFormData=u:a.searchParams&&URLSearchParams.prototype.isPrototypeOf(u)?this._bodyText=u.toString():a.arrayBuffer&&a.blob&&h(u)?(this._bodyArrayBuffer=j(u.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):a.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(u)||c(u))?this._bodyArrayBuffer=j(u):this._bodyText=u=Object.prototype.toString.call(u):this._bodyText="",this.headers.get("content-type")||(typeof u=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):a.searchParams&&URLSearchParams.prototype.isPrototypeOf(u)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},a.blob&&(this.blob=function(){var u=b(this);if(u)return u;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?b(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(S)}),this.text=function(){var u=b(this);if(u)return u;if(this._bodyBlob)return C(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(F(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},a.formData&&(this.formData=function(){return this.text().then(Fr)}),this.json=function(){return this.text().then(JSON.parse)},this}var Ur=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function Lr(u){var f=u.toUpperCase();return Ur.indexOf(f)>-1?f:u}function W(u,f){f=f||{};var m=f.body;if(u instanceof W){if(u.bodyUsed)throw new TypeError("Already read");this.url=u.url,this.credentials=u.credentials,f.headers||(this.headers=new v(u.headers)),this.method=u.method,this.mode=u.mode,this.signal=u.signal,!m&&u._bodyInit!=null&&(m=u._bodyInit,u.bodyUsed=!0)}else this.url=String(u);if(this.credentials=f.credentials||this.credentials||"same-origin",(f.headers||!this.headers)&&(this.headers=new v(f.headers)),this.method=Lr(f.method||this.method||"GET"),this.mode=f.mode||this.mode||null,this.signal=f.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&m)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(m)}W.prototype.clone=function(){return new W(this,{body:this._bodyInit})};function Fr(u){var f=new FormData;return u.trim().split("&").forEach(function(m){if(m){var x=m.split("="),k=x.shift().replace(/\+/g," "),E=x.join("=").replace(/\+/g," ");f.append(decodeURIComponent(k),decodeURIComponent(E))}}),f}function Br(u){var f=new v,m=u.replace(/\r?\n[\t ]+/g," ");return m.split(/\r?\n/).forEach(function(x){var k=x.split(":"),E=k.shift().trim();if(E){var fe=k.join(":").trim();f.append(E,fe)}}),f}V.call(W.prototype);function U(u,f){f||(f={}),this.type="default",this.status=f.status===void 0?200:f.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in f?f.statusText:"OK",this.headers=new v(f.headers),this.url=f.url||"",this._initBody(u)}V.call(U.prototype),U.prototype.clone=function(){return new U(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new v(this.headers),url:this.url})},U.error=function(){var u=new U(null,{status:0,statusText:""});return u.type="error",u};var Nr=[301,302,303,307,308];U.redirect=function(u,f){if(Nr.indexOf(f)===-1)throw new RangeError("Invalid status code");return new U(null,{status:f,headers:{location:u}})},o.DOMException=s.DOMException;try{new o.DOMException}catch{o.DOMException=function(f,m){this.message=f,this.name=m;var x=Error(f);this.stack=x.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function Ce(u,f){return new Promise(function(m,x){var k=new W(u,f);if(k.signal&&k.signal.aborted)return x(new o.DOMException("Aborted","AbortError"));var E=new XMLHttpRequest;function fe(){E.abort()}E.onload=function(){var oe={status:E.status,statusText:E.statusText,headers:Br(E.getAllResponseHeaders()||"")};oe.url="responseURL"in E?E.responseURL:oe.headers.get("X-Request-URL");var Ie="response"in E?E.response:E.responseText;m(new U(Ie,oe))},E.onerror=function(){x(new TypeError("Network request failed"))},E.ontimeout=function(){x(new TypeError("Network request failed"))},E.onabort=function(){x(new o.DOMException("Aborted","AbortError"))},E.open(k.method,k.url,!0),k.credentials==="include"?E.withCredentials=!0:k.credentials==="omit"&&(E.withCredentials=!1),"responseType"in E&&a.blob&&(E.responseType="blob"),k.headers.forEach(function(oe,Ie){E.setRequestHeader(Ie,oe)}),k.signal&&(k.signal.addEventListener("abort",fe),E.onreadystatechange=function(){E.readyState===4&&k.signal.removeEventListener("abort",fe)}),E.send(typeof k._bodyInit=="undefined"?null:k._bodyInit)})}return Ce.polyfill=!0,s.fetch||(s.fetch=Ce,s.Headers=v,s.Request=W,s.Response=U),o.Headers=v,o.Request=W,o.Response=U,o.fetch=Ce,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(r),r.fetch.ponyfill=!0,delete r.fetch.polyfill;var i=r;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,n.exports=e})(ee,ee.exports);var ve=lt(ee.exports),ae=tt({__proto__:null,default:ve},[ee.exports]);class ut{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=e.headers,this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError,this.signal=e.signal,this.allowEmpty=e.allowEmpty,e.fetch?this.fetch=e.fetch:typeof fetch=="undefined"?this.fetch=ve:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){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,a,h;let l=null,c=null,d=null,p=s.status,g=s.statusText;if(s.ok){if(this.method!=="HEAD"){const S=await s.text();S===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?c=S:c=JSON.parse(S))}const b=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),y=(a=s.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");b&&y&&y.length>1&&(d=parseInt(y[1]))}else{const b=await s.text();try{l=JSON.parse(b),Array.isArray(l)&&s.status===404&&(c=[],l=null,p=200,g="OK")}catch{s.status===404&&b===""?(p=204,g="No Content"):l={message:b}}if(l&&this.allowEmpty&&((h=l==null?void 0:l.details)===null||h===void 0?void 0:h.includes("Results contain 0 rows"))&&(l=null,p=200,g="OK"),l&&this.shouldThrowOnError)throw l}return{error:l,data:c,count:d,status:p,statusText:g}});return this.shouldThrowOnError||(i=i.catch(s=>({error:{message:`FetchError: ${s.message}`,details:"",hint:"",code:s.code||""},data:null,count:null,status:0,statusText:""}))),i.then(e,t)}}class dt extends ut{select(e){let t=!1;const r=(e!=null?e:"*").split("").map(i=>/\s/.test(i)&&!t?"":(i==='"'&&(t=!t),i)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:i}={}){const s=i?`${i}.order`:"order",o=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${o?`${o},`:""}${e}.${t?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t}={}){const r=typeof t=="undefined"?"limit":`${t}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:r}={}){const i=typeof r=="undefined"?"offset":`${r}.offset`,s=typeof r=="undefined"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(s,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.headers.Accept="application/vnd.pgrst.object+json",this.allowEmpty=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:i=!1,wal:s=!1,format:o="text"}={}){const a=[e?"analyze":null,t?"verbose":null,r?"settings":null,i?"buffers":null,s?"wal":null].filter(Boolean).join("|"),h=this.headers.Accept;return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${h}"; options=${a};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}}class Q extends dt{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){const r=t.map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config: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(e,`${s}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,r])=>{this.url.searchParams.append(t,`eq.${r}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t}={}){const r=t?`${t}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}}class ft{constructor(e,{headers:t={},schema:r,fetch:i}){this.url=e,this.headers=t,this.schema=r,this.fetch=i}select(e,{head:t=!1,count:r}={}){const i=t?"HEAD":"GET";let s=!1;const o=(e!=null?e:"*").split("").map(a=>/\s/.test(a)&&!s?"":(a==='"'&&(s=!s),a)).join("");return this.url.searchParams.set("select",o),r&&(this.headers.Prefer=`count=${r}`),new Q({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t}={}){const r="POST",i=[],s=e;if(t&&i.push(`count=${t}`),this.headers.Prefer&&i.unshift(this.headers.Prefer),this.headers.Prefer=i.join(","),Array.isArray(e)){const o=e.reduce((a,h)=>a.concat(Object.keys(h)),[]);if(o.length>0){const a=[...new Set(o)].map(h=>`"${h}"`);this.url.searchParams.set("columns",a.join(","))}}return new Q({method:r,url:this.url,headers:this.headers,schema:this.schema,body:s,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:i}={}){const s="POST",o=[`resolution=${r?"ignore":"merge"}-duplicates`];t!==void 0&&this.url.searchParams.set("on_conflict",t);const a=e;return i&&o.push(`count=${i}`),this.headers.Prefer&&o.unshift(this.headers.Prefer),this.headers.Prefer=o.join(","),new Q({method:s,url:this.url,headers:this.headers,schema:this.schema,body:a,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){const r="PATCH",i=[],s=e;return t&&i.push(`count=${t}`),this.headers.Prefer&&i.unshift(this.headers.Prefer),this.headers.Prefer=i.join(","),new Q({method:r,url:this.url,headers:this.headers,schema:this.schema,body:s,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){const t="DELETE",r=[];return e&&r.push(`count=${e}`),this.headers.Prefer&&r.unshift(this.headers.Prefer),this.headers.Prefer=r.join(","),new Q({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}}const pt={"X-Client-Info":"postgrest-js/1.5.0"};class vt{constructor(e,{headers:t={},schema:r,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},pt),t),this.schema=r,this.fetch=i}from(e){const t=new URL(`${this.url}/${e}`);return new ft(t,{headers:Object.assign({},this.headers),schema:this.schema,fetch:this.fetch})}rpc(e,t={},{head:r=!1,count:i}={}){let s;const o=new URL(`${this.url}/rpc/${e}`);let a;r?(s="HEAD",Object.entries(t).forEach(([l,c])=>{o.searchParams.append(l,`${c}`)})):(s="POST",a=t);const h=Object.assign({},this.headers);return i&&(h.Prefer=`count=${i}`),new Q({method:s,url:o,headers:h,schema:this.schema,body:a,fetch:this.fetch,allowEmpty:!1})}}var yt={_args:[["websocket@1.0.34","/Users/Dido/Desktop/Test/vue-3-supabase"]],_from:"websocket@1.0.34",_id:"websocket@1.0.34",_inBundle:!1,_integrity:"sha512-PRDso2sGwF6kM75QykIesBijKSVceR6jL2G8NGYyq2XrItNC2P5/qL5XeR056GhA+Ly7JMFvJb9I312mJfmqnQ==",_location:"/websocket",_phantomChildren:{},_requested:{type:"version",registry:!0,raw:"websocket@1.0.34",name:"websocket",escapedName:"websocket",rawSpec:"1.0.34",saveSpec:null,fetchSpec:"1.0.34"},_requiredBy:["/@supabase/realtime-js"],_resolved:"https://registry.npmjs.org/websocket/-/websocket-1.0.34.tgz",_spec:"1.0.34",_where:"/Users/Dido/Desktop/Test/vue-3-supabase",author:{name:"Brian McKelvey",email:"theturtle32@gmail.com",url:"https://github.com/theturtle32"},browser:"lib/browser.js",bugs:{url:"https://github.com/theturtle32/WebSocket-Node/issues"},config:{verbose:!1},contributors:[{name:"I\xF1aki Baz Castillo",email:"ibc@aliax.net",url:"http://dev.sipdoc.net"}],dependencies:{bufferutil:"^4.0.1",debug:"^2.2.0","es5-ext":"^0.10.50","typedarray-to-buffer":"^3.1.5","utf-8-validate":"^5.0.2",yaeti:"^0.0.6"},description:"Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.",devDependencies:{"buffer-equal":"^1.0.0",gulp:"^4.0.2","gulp-jshint":"^2.0.4",jshint:"^2.0.0","jshint-stylish":"^2.2.1",tape:"^4.9.1"},directories:{lib:"./lib"},engines:{node:">=4.0.0"},homepage:"https://github.com/theturtle32/WebSocket-Node",keywords:["websocket","websockets","socket","networking","comet","push","RFC-6455","realtime","server","client"],license:"Apache-2.0",main:"index",name:"websocket",repository:{type:"git",url:"git+https://github.com/theturtle32/WebSocket-Node.git"},scripts:{gulp:"gulp",test:"tape test/unit/*.js"},version:"1.0.34"},_t=yt.version,J;if(typeof globalThis=="object")J=globalThis;else try{J=require("es5-ext/global")}catch{}finally{if(!J&&typeof window!="undefined"&&(J=window),!J)throw new Error("Could not determine global this")}var te=J.WebSocket||J.MozWebSocket,gt=_t;function De(n,e){var t;return e?t=new te(n,e):t=new te(n),t}te&&["CONNECTING","OPEN","CLOSING","CLOSED"].forEach(function(n){Object.defineProperty(De,n,{get:function(){return te[n]}})});var mt={w3cwebsocket:te?De:null,version:gt};const bt={"X-Client-Info":"realtime-js/2.7.2"},wt="1.0.0",Ue=1e4,Tt=1e3;var re;(function(n){n[n.connecting=0]="connecting",n[n.open=1]="open",n[n.closing=2]="closing",n[n.closed=3]="closed"})(re||(re={}));var P;(function(n){n.closed="closed",n.errored="errored",n.joined="joined",n.joining="joining",n.leaving="leaving"})(P||(P={}));var I;(function(n){n.close="phx_close",n.error="phx_error",n.join="phx_join",n.reply="phx_reply",n.leave="phx_leave",n.access_token="access_token"})(I||(I={}));var ye;(function(n){n.websocket="websocket"})(ye||(ye={}));var H;(function(n){n.Connecting="connecting",n.Open="open",n.Closing="closing",n.Closed="closed"})(H||(H={}));class Le{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}class Et{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){const t=new DataView(e),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){const i=t.getUint8(1),s=t.getUint8(2);let o=this.HEADER_LENGTH+2;const a=r.decode(e.slice(o,o+i));o=o+i;const h=r.decode(e.slice(o,o+s));o=o+s;const l=JSON.parse(r.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:h,payload:l}}}class _e{constructor(e,t,r={},i=Ue){this.channel=e,this.event=t,this.payload=r,this.timeout=i,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null,this.rateLimited=!1}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){if(this._hasReceived("timeout"))return;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()})==="rate limited"&&(this.rateLimited=!0)}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){!this.refEvent||this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(r=>r.status===e).forEach(r=>r.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var Fe;(function(n){n.SYNC="sync",n.JOIN="join",n.LEAVE="leave"})(Fe||(Fe={}));class ie{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(t==null?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},i=>{const{onJoin:s,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=ie.syncState(this.state,i,s,o),this.pendingDiffs.forEach(h=>{this.state=ie.syncDiff(this.state,h,s,o)}),this.pendingDiffs=[],a()}),this.channel._on(r.diff,{},i=>{const{onJoin:s,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=ie.syncDiff(this.state,i,s,o),a())}),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(e,t,r,i){const s=this.cloneDeep(e),o=this.transformState(t),a={},h={};return this.map(s,(l,c)=>{o[l]||(h[l]=c)}),this.map(o,(l,c)=>{const d=s[l];if(d){const p=c.map(y=>y.presence_ref),g=d.map(y=>y.presence_ref),v=c.filter(y=>g.indexOf(y.presence_ref)<0),b=d.filter(y=>p.indexOf(y.presence_ref)<0);v.length>0&&(a[l]=v),b.length>0&&(h[l]=b)}else a[l]=c}),this.syncDiff(s,{joins:a,leaves:h},r,i)}static syncDiff(e,t,r,i){const{joins:s,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),i||(i=()=>{}),this.map(s,(a,h)=>{var l;const c=(l=e[a])!==null&&l!==void 0?l:[];if(e[a]=this.cloneDeep(h),c.length>0){const d=e[a].map(g=>g.presence_ref),p=c.filter(g=>d.indexOf(g.presence_ref)<0);e[a].unshift(...p)}r(a,c,h)}),this.map(o,(a,h)=>{let l=e[a];if(!l)return;const c=h.map(d=>d.presence_ref);l=l.filter(d=>c.indexOf(d.presence_ref)<0),e[a]=l,i(a,l,h),l.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{const i=e[r];return"metas"in i?t[r]=i.metas.map(s=>(s.presence_ref=s.phx_ref,delete s.phx_ref,delete s.phx_ref_prev,s)):t[r]=i,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var O;(function(n){n.abstime="abstime",n.bool="bool",n.date="date",n.daterange="daterange",n.float4="float4",n.float8="float8",n.int2="int2",n.int4="int4",n.int4range="int4range",n.int8="int8",n.int8range="int8range",n.json="json",n.jsonb="jsonb",n.money="money",n.numeric="numeric",n.oid="oid",n.reltime="reltime",n.text="text",n.time="time",n.timestamp="timestamp",n.timestamptz="timestamptz",n.timetz="timetz",n.tsrange="tsrange",n.tstzrange="tstzrange"})(O||(O={}));const Be=(n,e,t={})=>{var r;const i=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((s,o)=>(s[o]=Ot(o,n,e,i),s),{})},Ot=(n,e,t,r)=>{const i=e.find(a=>a.name===n),s=i==null?void 0:i.type,o=t[n];return s&&!r.includes(s)?Ne(s,o):ge(o)},Ne=(n,e)=>{if(n.charAt(0)==="_"){const t=n.slice(1,n.length);return jt(e,t)}switch(n){case O.bool:return St(e);case O.float4:case O.float8:case O.int2:case O.int4:case O.int8:case O.numeric:case O.oid:return kt(e);case O.json:case O.jsonb:return $t(e);case O.timestamp:return xt(e);case O.abstime:case O.date:case O.daterange:case O.int4range:case O.int8range:case O.money:case O.reltime:case O.text:case O.time:case O.timestamptz:case O.timetz:case O.tsrange:case O.tstzrange:return ge(e);default:return ge(e)}},ge=n=>n,St=n=>{switch(n){case"t":return!0;case"f":return!1;default:return n}},kt=n=>{if(typeof n=="string"){const e=parseFloat(n);if(!Number.isNaN(e))return e}return n},$t=n=>{if(typeof n=="string")try{return JSON.parse(n)}catch(e){return console.log(`JSON parse error: ${e}`),n}return n},jt=(n,e)=>{if(typeof n!="string")return n;const t=n.length-1,r=n[t];if(n[0]==="{"&&r==="}"){let s;const o=n.slice(1,t);try{s=JSON.parse("["+o+"]")}catch{s=o?o.split(","):[]}return s.map(a=>Ne(e,a))}return n},xt=n=>typeof n=="string"?n.replace(" ","T"):n;var Me=globalThis&&globalThis.__awaiter||function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(r.next(c))}catch(d){o(d)}}function h(c){try{l(r.throw(c))}catch(d){o(d)}}function l(c){c.done?s(c.value):i(c.value).then(a,h)}l((r=r.apply(n,e||[])).next())})},qe;(function(n){n.ALL="*",n.INSERT="INSERT",n.UPDATE="UPDATE",n.DELETE="DELETE"})(qe||(qe={}));var Je;(function(n){n.BROADCAST="broadcast",n.PRESENCE="presence",n.POSTGRES_CHANGES="postgres_changes"})(Je||(Je={}));var He;(function(n){n.SUBSCRIBED="SUBSCRIBED",n.TIMED_OUT="TIMED_OUT",n.CLOSED="CLOSED",n.CHANNEL_ERROR="CHANNEL_ERROR"})(He||(He={}));class me{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=P.closed,this.joinedOnce=!1,this.pushBuffer=[],this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""}},t.config),this.timeout=this.socket.timeout,this.joinPush=new _e(this,I.join,this.params,this.timeout),this.rejoinTimer=new Le(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=P.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=P.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=P.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{!this._isJoining()||(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=P.errored,this.rejoinTimer.scheduleTimeout())}),this._on(I.reply,{},(i,s)=>{this._trigger(this._replyEventName(s),i)}),this.presence=new ie(this)}subscribe(e,t=this.timeout){var r,i;if(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(l=>e&&e("CHANNEL_ERROR",l)),this._onClose(()=>e&&e("CLOSED"));const a={},h={broadcast:s,presence:o,postgres_changes:(i=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(l=>l.filter))!==null&&i!==void 0?i:[]};this.socket.accessToken&&(a.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:h},a)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:l})=>{var c;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),l===void 0){e&&e("SUBSCRIBED");return}else{const d=this.bindings.postgres_changes,p=(c=d==null?void 0:d.length)!==null&&c!==void 0?c:0,g=[];for(let v=0;v<p;v++){const b=d[v],{filter:{event:y,schema:S,table:C,filter:F}}=b,j=l&&l[v];if(j&&j.event===y&&j.schema===S&&j.table===C&&j.filter===F)g.push(Object.assign(Object.assign({},b),{id:j.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=g,e&&e("SUBSCRIBED");return}}).receive("error",l=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(l).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}track(e,t={}){return Me(this,void 0,void 0,function*(){return yield this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)})}untrack(e={}){return Me(this,void 0,void 0,function*(){return yield this.send({type:"presence",event:"untrack"},e)})}on(e,t,r){return this._on(e,t,r)}send(e,t={}){return new Promise(r=>{var i,s,o;const a=this._push(e.type,e,t.timeout||this.timeout);a.rateLimited&&r("rate limited"),e.type==="broadcast"&&!(!((o=(s=(i=this.params)===null||i===void 0?void 0:i.config)===null||s===void 0?void 0:s.broadcast)===null||o===void 0)&&o.ack)&&r("ok"),a.receive("ok",()=>r("ok")),a.receive("timeout",()=>r("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=P.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(I.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{const i=new _e(this,I.leave,{},e);i.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),i.send(),this._canPush()||i.trigger("ok",{})})}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new _e(this,e,t,r);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var i,s;const o=e.toLocaleLowerCase(),{close:a,error:h,leave:l,join:c}=I;if(r&&[a,h,l,c].indexOf(o)>=0&&r!==this._joinRef())return;let p=this._onMessage(o,t,r);if(t&&!p)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(g=>{var v,b,y;return((v=g.filter)===null||v===void 0?void 0:v.event)==="*"||((y=(b=g.filter)===null||b===void 0?void 0:b.event)===null||y===void 0?void 0:y.toLocaleLowerCase())===o}).map(g=>g.callback(p,r)):(s=this.bindings[o])===null||s===void 0||s.filter(g=>{var v,b,y,S,C,F;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in g){const j=g.id,V=(v=g.filter)===null||v===void 0?void 0:v.event;return j&&((b=t.ids)===null||b===void 0?void 0:b.includes(j))&&(V==="*"||(V==null?void 0:V.toLocaleLowerCase())===((y=t.data)===null||y===void 0?void 0:y.type.toLocaleLowerCase()))}else{const j=(C=(S=g==null?void 0:g.filter)===null||S===void 0?void 0:S.event)===null||C===void 0?void 0:C.toLocaleLowerCase();return j==="*"||j===((F=t==null?void 0:t.event)===null||F===void 0?void 0:F.toLocaleLowerCase())}else return g.type.toLocaleLowerCase()===o}).map(g=>{if(typeof p=="object"&&"ids"in p){const v=p.data,{schema:b,table:y,commit_timestamp:S,type:C,errors:F}=v;p=Object.assign(Object.assign({},{schema:b,table:y,commit_timestamp:S,eventType:C,new:{},old:{},errors:F}),this._getPayloadRecords(v))}g.callback(p,r)})}_isClosed(){return this.state===P.closed}_isJoined(){return this.state===P.joined}_isJoining(){return this.state===P.joining}_isLeaving(){return this.state===P.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){const i=e.toLocaleLowerCase(),s={type:i,filter:t,callback:r};return this.bindings[i]?this.bindings[i].push(s):this.bindings[i]=[s],this}_off(e,t){const r=e.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&&me.isEqual(i.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const r in e)if(e[r]!==t[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(I.close,{},e)}_onError(e){this._on(I.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=P.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=Be(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=Be(e.columns,e.old_record)),t}}var be=globalThis&&globalThis.__awaiter||function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(r.next(c))}catch(d){o(d)}}function h(c){try{l(r.throw(c))}catch(d){o(d)}}function l(c){c.done?s(c.value):i(c.value).then(a,h)}l((r=r.apply(n,e||[])).next())})};const At=()=>{};class Pt{constructor(e,t){var r;this.accessToken=null,this.channels=[],this.endPoint="",this.headers=bt,this.params={},this.timeout=Ue,this.transport=mt.w3cwebsocket,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=At,this.conn=null,this.sendBuffer=[],this.serializer=new Et,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.eventsPerSecondLimitMs=100,this.inThrottle=!1,this.endPoint=`${e}/${ye.websocket}`,t!=null&&t.params&&(this.params=t.params),t!=null&&t.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t!=null&&t.timeout&&(this.timeout=t.timeout),t!=null&&t.logger&&(this.logger=t.logger),t!=null&&t.transport&&(this.transport=t.transport),t!=null&&t.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);const i=(r=t==null?void 0:t.params)===null||r===void 0?void 0:r.eventsPerSecond;i&&(this.eventsPerSecondLimitMs=Math.floor(1e3/i)),this.reconnectAfterMs=t!=null&&t.reconnectAfterMs?t.reconnectAfterMs:s=>[1e3,2e3,5e3,1e4][s-1]||1e4,this.encode=t!=null&&t.encode?t.encode:(s,o)=>o(JSON.stringify(s)),this.decode=t!=null&&t.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new Le(()=>be(this,void 0,void 0,function*(){this.disconnect(),this.connect()}),this.reconnectAfterMs)}connect(){this.conn||(this.conn=new this.transport(this._endPointURL(),[],null,this.headers),this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e)))}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t!=null?t:""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}removeChannel(e){return be(this,void 0,void 0,function*(){const t=yield e.unsubscribe();return this.channels.length===0&&this.disconnect(),t})}removeAllChannels(){return be(this,void 0,void 0,function*(){const e=yield Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e})}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case re.connecting:return H.Connecting;case re.open:return H.Open;case re.closing:return H.Closing;default:return H.Closed}}isConnected(){return this.connectionState()===H.Open}channel(e,t={config:{}}){this.isConnected()||this.connect();const r=new me(`realtime:${e}`,t,this);return this.channels.push(r),r}push(e){const{topic:t,event:r,payload:i,ref:s}=e;let o=()=>{this.encode(e,a=>{var h;(h=this.conn)===null||h===void 0||h.send(a)})};if(this.log("push",`${t} ${r} (${s})`,i),this.isConnected())if(["broadcast","presence","postgres_changes"].includes(r)){if(this._throttle(o)())return"rate limited"}else o();else this.sendBuffer.push(o)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(I.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(r=>r.topic===e&&(r._isJoined()||r._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:wt}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:r,event:i,payload:s,ref:o}=t;(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(a=>a._isMember(r)).forEach(a=>a._trigger(i,s,o)),this.stateChangeCallbacks.message.forEach(a=>a(t))})}_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(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(I.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;const r=e.match(/\?/)?"&":"?",i=new URLSearchParams(t);return`${e}${r}${i}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(!!this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(Tt,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}_throttle(e,t=this.eventsPerSecondLimitMs){return()=>this.inThrottle?!0:(e(),t>0&&(this.inThrottle=!0,setTimeout(()=>{this.inThrottle=!1},t)),!1)}}class we extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function $(n){return typeof n=="object"&&n!==null&&"__isStorageError"in n}class Rt extends we{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class ze extends we{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}var Ge=globalThis&&globalThis.__awaiter||function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(r.next(c))}catch(d){o(d)}}function h(c){try{l(r.throw(c))}catch(d){o(d)}}function l(c){c.done?s(c.value):i(c.value).then(a,h)}l((r=r.apply(n,e||[])).next())})};const Ke=n=>{let e;return n?e=n:typeof fetch=="undefined"?e=(...t)=>Ge(void 0,void 0,void 0,function*(){return yield(yield Promise.resolve().then(function(){return ae})).fetch(...t)}):e=fetch,(...t)=>e(...t)},Ct=()=>Ge(void 0,void 0,void 0,function*(){return typeof Response=="undefined"?(yield Promise.resolve().then(function(){return ae})).Response:Response});var X=globalThis&&globalThis.__awaiter||function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(r.next(c))}catch(d){o(d)}}function h(c){try{l(r.throw(c))}catch(d){o(d)}}function l(c){c.done?s(c.value):i(c.value).then(a,h)}l((r=r.apply(n,e||[])).next())})};const Te=n=>n.msg||n.message||n.error_description||n.error||JSON.stringify(n),It=(n,e)=>X(void 0,void 0,void 0,function*(){const t=yield Ct();n instanceof t?n.json().then(r=>{e(new Rt(Te(r),n.status||500))}).catch(r=>{e(new ze(Te(r),r))}):e(new ze(Te(n),n))}),Dt=(n,e,t,r)=>{const i={method:n,headers:(e==null?void 0:e.headers)||{}};return n==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json"},e==null?void 0:e.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};function ce(n,e,t,r,i,s){return X(this,void 0,void 0,function*(){return new Promise((o,a)=>{n(t,Dt(e,r,i,s)).then(h=>{if(!h.ok)throw h;return r!=null&&r.noResolveJson?h:h.json()}).then(h=>o(h)).catch(h=>It(h,a))})})}function Ee(n,e,t,r){return X(this,void 0,void 0,function*(){return ce(n,"GET",e,t,r)})}function N(n,e,t,r,i){return X(this,void 0,void 0,function*(){return ce(n,"POST",e,r,i,t)})}function Ut(n,e,t,r,i){return X(this,void 0,void 0,function*(){return ce(n,"PUT",e,r,i,t)})}function Ve(n,e,t,r,i){return X(this,void 0,void 0,function*(){return ce(n,"DELETE",e,r,i,t)})}var R=globalThis&&globalThis.__awaiter||function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(r.next(c))}catch(d){o(d)}}function h(c){try{l(r.throw(c))}catch(d){o(d)}}function l(c){c.done?s(c.value):i(c.value).then(a,h)}l((r=r.apply(n,e||[])).next())})};const Lt={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},We={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class Ft{constructor(e,t={},r,i){this.url=e,this.headers=t,this.bucketId=r,this.fetch=Ke(i)}uploadOrUpdate(e,t,r,i){return R(this,void 0,void 0,function*(){try{let s;const o=Object.assign(Object.assign({},We),i),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob!="undefined"&&r instanceof Blob?(s=new FormData,s.append("cacheControl",o.cacheControl),s.append("",r)):typeof FormData!="undefined"&&r instanceof FormData?(s=r,s.append("cacheControl",o.cacheControl)):(s=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);const h=this._removeEmptyFolders(t),l=this._getFinalPath(h),c=yield this.fetch(`${this.url}/object/${l}`,Object.assign({method:e,body:s,headers:a},o!=null&&o.duplex?{duplex:o.duplex}:{}));if(c.ok)return{data:{path:h},error:null};{const d=yield c.json();return{data:null,error:d}}}catch(s){if($(s))return{data:null,error:s};throw s}})}upload(e,t,r){return R(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,i){return R(this,void 0,void 0,function*(){const s=this._removeEmptyFolders(e),o=this._getFinalPath(s),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let h;const l=Object.assign({upsert:We.upsert},i),c=Object.assign(Object.assign({},this.headers),{"x-upsert":String(l.upsert)});typeof Blob!="undefined"&&r instanceof Blob?(h=new FormData,h.append("cacheControl",l.cacheControl),h.append("",r)):typeof FormData!="undefined"&&r instanceof FormData?(h=r,h.append("cacheControl",l.cacheControl)):(h=r,c["cache-control"]=`max-age=${l.cacheControl}`,c["content-type"]=l.contentType);const d=yield this.fetch(a.toString(),{method:"PUT",body:h,headers:c});if(d.ok)return{data:{path:s},error:null};{const p=yield d.json();return{data:null,error:p}}}catch(h){if($(h))return{data:null,error:h};throw h}})}createSignedUploadUrl(e){return R(this,void 0,void 0,function*(){try{let t=this._getFinalPath(e);const r=yield N(this.fetch,`${this.url}/object/upload/sign/${t}`,{},{headers:this.headers}),i=new URL(this.url+r.url),s=i.searchParams.get("token");if(!s)throw new we("No token returned by API");return{data:{signedUrl:i.toString(),path:e,token:s},error:null}}catch(t){if($(t))return{data:null,error:t};throw t}})}update(e,t,r){return R(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t){return R(this,void 0,void 0,function*(){try{return{data:yield N(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t},{headers:this.headers}),error:null}}catch(r){if($(r))return{data:null,error:r};throw r}})}copy(e,t){return R(this,void 0,void 0,function*(){try{return{data:{path:(yield N(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t},{headers:this.headers})).Key},error:null}}catch(r){if($(r))return{data:null,error:r};throw r}})}createSignedUrl(e,t,r){return R(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),s=yield N(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:t},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($(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,r){return R(this,void 0,void 0,function*(){try{const i=yield N(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{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($(i))return{data:null,error:i};throw i}})}download(e,t){return R(this,void 0,void 0,function*(){const i=typeof(t==null?void 0:t.transform)!="undefined"?"render/image/authenticated":"object",s=this.transformOptsToQueryString((t==null?void 0:t.transform)||{}),o=s?`?${s}`:"";try{const a=this._getFinalPath(e);return{data:yield(yield Ee(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if($(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){const r=this._getFinalPath(e),i=[],s=t!=null&&t.download?`download=${t.download===!0?"":t.download}`:"";s!==""&&i.push(s);const a=typeof(t==null?void 0:t.transform)!="undefined"?"render/image":"object",h=this.transformOptsToQueryString((t==null?void 0:t.transform)||{});h!==""&&i.push(h);let l=i.join("&");return l!==""&&(l=`?${l}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${l}`)}}}remove(e){return R(this,void 0,void 0,function*(){try{return{data:yield Ve(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if($(t))return{data:null,error:t};throw t}})}list(e,t,r){return R(this,void 0,void 0,function*(){try{const i=Object.assign(Object.assign(Object.assign({},Lt),t),{prefix:e||""});return{data:yield N(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},r),error:null}}catch(i){if($(i))return{data:null,error:i};throw i}})}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}}const Bt={"X-Client-Info":"storage-js/2.5.1"};var Y=globalThis&&globalThis.__awaiter||function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(r.next(c))}catch(d){o(d)}}function h(c){try{l(r.throw(c))}catch(d){o(d)}}function l(c){c.done?s(c.value):i(c.value).then(a,h)}l((r=r.apply(n,e||[])).next())})};class Nt{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},Bt),t),this.fetch=Ke(r)}listBuckets(){return Y(this,void 0,void 0,function*(){try{return{data:yield Ee(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if($(e))return{data:null,error:e};throw e}})}getBucket(e){return Y(this,void 0,void 0,function*(){try{return{data:yield Ee(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if($(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Y(this,void 0,void 0,function*(){try{return{data:yield N(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if($(r))return{data:null,error:r};throw r}})}updateBucket(e,t){return Y(this,void 0,void 0,function*(){try{return{data:yield Ut(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if($(r))return{data:null,error:r};throw r}})}emptyBucket(e){return Y(this,void 0,void 0,function*(){try{return{data:yield N(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if($(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Y(this,void 0,void 0,function*(){try{return{data:yield Ve(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if($(t))return{data:null,error:t};throw t}})}}class Mt extends Nt{constructor(e,t={},r){super(e,t,r)}from(e){return new Ft(this.url,this.headers,e,this.fetch)}}const qt={"X-Client-Info":"supabase-js/2.20.0"};var Jt=globalThis&&globalThis.__awaiter||function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(r.next(c))}catch(d){o(d)}}function h(c){try{l(r.throw(c))}catch(d){o(d)}}function l(c){c.done?s(c.value):i(c.value).then(a,h)}l((r=r.apply(n,e||[])).next())})};const Ht=n=>{let e;return n?e=n:typeof fetch=="undefined"?e=ve:e=fetch,(...t)=>e(...t)},zt=()=>typeof Headers=="undefined"?ee.exports.Headers:Headers,Gt=(n,e,t)=>{const r=Ht(t),i=zt();return(s,o)=>Jt(void 0,void 0,void 0,function*(){var a;const h=(a=yield e())!==null&&a!==void 0?a:n;let l=new i(o==null?void 0:o.headers);return l.has("apikey")||l.set("apikey",n),l.has("Authorization")||l.set("Authorization",`Bearer ${h}`),r(s,Object.assign(Object.assign({},o),{headers:l}))})};function Kt(n){return n.replace(/\/$/,"")}function Vt(n,e){const{db:t,auth:r,realtime:i,global:s}=n,{db:o,auth:a,realtime:h,global:l}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),r),realtime:Object.assign(Object.assign({},h),i),global:Object.assign(Object.assign({},l),s)}}var z=globalThis&&globalThis.__awaiter||function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(r.next(c))}catch(d){o(d)}}function h(c){try{l(r.throw(c))}catch(d){o(d)}}function l(c){c.done?s(c.value):i(c.value).then(a,h)}l((r=r.apply(n,e||[])).next())})};function Wt(n){return Math.round(Date.now()/1e3)+n}function Qt(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(n){const e=Math.random()*16|0;return(n=="x"?e:e&3|8).toString(16)})}const M=()=>typeof document!="undefined",G={tested:!1,writable:!1},Oe=()=>{if(!M())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(G.tested)return G.writable;const n=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(n,n),globalThis.localStorage.removeItem(n),G.tested=!0,G.writable=!0}catch{G.tested=!0,G.writable=!1}return G.writable};function A(n,e){var t;e||(e=((t=window==null?void 0:window.location)===null||t===void 0?void 0:t.href)||""),n=n.replace(/[\[\]]/g,"\\$&");const r=new RegExp("[?&#]"+n+"(=([^&#]*)|&|#|$)"),i=r.exec(e);return i?i[2]?decodeURIComponent(i[2].replace(/\+/g," ")):"":null}const Qe=n=>{let e;return n?e=n:typeof fetch=="undefined"?e=(...t)=>z(void 0,void 0,void 0,function*(){return yield(yield Promise.resolve().then(function(){return ae})).fetch(...t)}):e=fetch,(...t)=>e(...t)},Xt=n=>typeof n=="object"&&n!==null&&"status"in n&&"ok"in n&&"json"in n&&typeof n.json=="function",he=(n,e,t)=>z(void 0,void 0,void 0,function*(){yield n.setItem(e,JSON.stringify(t))}),le=(n,e)=>z(void 0,void 0,void 0,function*(){const t=yield n.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}}),Xe=(n,e)=>z(void 0,void 0,void 0,function*(){yield n.removeItem(e)});function Yt(n){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let t="",r,i,s,o,a,h,l,c=0;for(n=n.replace("-","+").replace("_","/");c<n.length;)o=e.indexOf(n.charAt(c++)),a=e.indexOf(n.charAt(c++)),h=e.indexOf(n.charAt(c++)),l=e.indexOf(n.charAt(c++)),r=o<<2|a>>4,i=(a&15)<<4|h>>2,s=(h&3)<<6|l,t=t+String.fromCharCode(r),h!=64&&i!=0&&(t=t+String.fromCharCode(i)),l!=64&&s!=0&&(t=t+String.fromCharCode(s));return t}class ue{constructor(){this.promise=new ue.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}ue.promiseConstructor=Promise;function Ye(n){const e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=n.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");const r=t[1];return JSON.parse(Yt(r))}function Zt(n){return new Promise(e=>{setTimeout(()=>e(null),n)})}function er(n,e){return new Promise((r,i)=>{z(this,void 0,void 0,function*(){for(let s=0;s<1/0;s++)try{const o=yield n(s);if(!e(s,null,o)){r(o);return}}catch(o){if(!e(s,o)){i(o);return}}})})}function tr(n){return("0"+n.toString(16)).substr(-2)}function Se(){const e=new Uint32Array(56);if(typeof crypto=="undefined")throw new Error("PKCE is not supported on devices without WebCrypto API support, please add polyfills");return crypto.getRandomValues(e),Array.from(e,tr).join("")}function rr(n){return z(this,void 0,void 0,function*(){const t=new TextEncoder().encode(n);if(typeof crypto=="undefined")throw new Error("PKCE is not supported on devices without WebCrypto API support, please add polyfills");const r=yield crypto.subtle.digest("SHA-256",t),i=new Uint8Array(r);return Array.from(i).map(s=>String.fromCharCode(s)).join("")})}function ir(n){return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ke(n){return z(this,void 0,void 0,function*(){const e=yield rr(n);return ir(e)})}class $e extends Error{constructor(e,t){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t}}function w(n){return typeof n=="object"&&n!==null&&"__isAuthError"in n}class sr extends $e{constructor(e,t){super(e,t),this.name="AuthApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}}function nr(n){return w(n)&&n.name==="AuthApiError"}class Ze extends $e{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class se extends $e{constructor(e,t,r){super(e),this.name=t,this.status=r}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class ne extends se{constructor(){super("Auth session missing!","AuthSessionMissingError",400)}}class je extends se{constructor(e){super(e,"AuthInvalidCredentialsError",400)}}class L extends se{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class xe extends se{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class Ae extends se{constructor(e,t){super(e,"AuthRetryableFetchError",t)}}var Pe=globalThis&&globalThis.__awaiter||function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(r.next(c))}catch(d){o(d)}}function h(c){try{l(r.throw(c))}catch(d){o(d)}}function l(c){c.done?s(c.value):i(c.value).then(a,h)}l((r=r.apply(n,e||[])).next())})},or=globalThis&&globalThis.__rest||function(n,e){var t={};for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(n);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(n,r[i])&&(t[r[i]]=n[r[i]]);return t};const de=n=>n.msg||n.message||n.error_description||n.error||JSON.stringify(n),ar=(n,e)=>Pe(void 0,void 0,void 0,function*(){const t=[502,503,504];Xt(n)?t.includes(n.status)?e(new Ae(de(n),n.status)):n.json().then(r=>{e(new sr(de(r),n.status||500))}).catch(r=>{e(new Ze(de(r),r))}):e(new Ae(de(n),0))}),cr=(n,e,t,r)=>{const i={method:n,headers:(e==null?void 0:e.headers)||{}};return n==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};function T(n,e,t,r){var i;return Pe(this,void 0,void 0,function*(){const s=Object.assign({},r==null?void 0:r.headers);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 a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",h=yield hr(n,e,t+a,{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(h):{data:Object.assign({},h),error:null}})}function hr(n,e,t,r,i,s){return Pe(this,void 0,void 0,function*(){return new Promise((o,a)=>{n(t,cr(e,r,i,s)).then(h=>{if(!h.ok)throw h;return r!=null&&r.noResolveJson?h:h.json()}).then(h=>o(h)).catch(h=>ar(h,a))})})}function q(n){var e;let t=null;fr(n)&&(t=Object.assign({},n),t.expires_at=Wt(n.expires_in));const r=(e=n.user)!==null&&e!==void 0?e:n;return{data:{session:t,user:r},error:null}}function K(n){var e;return{data:{user:(e=n.user)!==null&&e!==void 0?e:n},error:null}}function lr(n){return{data:n,error:null}}function ur(n){const{action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:s}=n,o=or(n,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:s},h=Object.assign({},o);return{data:{properties:a,user:h},error:null}}function dr(n){return n}function fr(n){return n.access_token&&n.refresh_token&&n.expires_in}var D=globalThis&&globalThis.__awaiter||function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(r.next(c))}catch(d){o(d)}}function h(c){try{l(r.throw(c))}catch(d){o(d)}}function l(c){c.done?s(c.value):i(c.value).then(a,h)}l((r=r.apply(n,e||[])).next())})},pr=globalThis&&globalThis.__rest||function(n,e){var t={};for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(n);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(n,r[i])&&(t[r[i]]=n[r[i]]);return t};class vr{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=Qe(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}signOut(e){return D(this,void 0,void 0,function*(){try{return yield T(this.fetch,"POST",`${this.url}/logout`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}})}inviteUserByEmail(e,t={}){return D(this,void 0,void 0,function*(){try{return yield T(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:K})}catch(r){if(w(r))return{data:{user:null},error:r};throw r}})}generateLink(e){return D(this,void 0,void 0,function*(){try{const{options:t}=e,r=pr(e,["options"]),i=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(i.new_email=r==null?void 0:r.newEmail,delete i.newEmail),yield T(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:ur,redirectTo:t==null?void 0:t.redirectTo})}catch(t){if(w(t))return{data:{properties:null,user:null},error:t};throw t}})}createUser(e){return D(this,void 0,void 0,function*(){try{return yield T(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:K})}catch(t){if(w(t))return{data:{user:null},error:t};throw t}})}listUsers(e){var t,r,i,s,o,a,h;return D(this,void 0,void 0,function*(){try{const l={nextPage:null,lastPage:0,total:0},c=yield T(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e==null?void 0:e.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(s=(i=e==null?void 0:e.perPage)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""},xform:dr});if(c.error)throw c.error;const d=yield c.json(),p=(o=c.headers.get("x-total-count"))!==null&&o!==void 0?o:0,g=(h=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&h!==void 0?h:[];return g.length>0&&(g.forEach(v=>{const b=parseInt(v.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(v.split(";")[1].split("=")[1]);l[`${y}Page`]=b}),l.total=parseInt(p)),{data:Object.assign(Object.assign({},d),l),error:null}}catch(l){if(w(l))return{data:{users:[]},error:l};throw l}})}getUserById(e){return D(this,void 0,void 0,function*(){try{return yield T(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:K})}catch(t){if(w(t))return{data:{user:null},error:t};throw t}})}updateUserById(e,t){return D(this,void 0,void 0,function*(){try{return yield T(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:K})}catch(r){if(w(r))return{data:{user:null},error:r};throw r}})}deleteUser(e,t=!1){return D(this,void 0,void 0,function*(){try{return yield T(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:K})}catch(r){if(w(r))return{data:{user:null},error:r};throw r}})}_listFactors(e){return D(this,void 0,void 0,function*(){try{const{data:t,error:r}=yield T(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:r}}catch(t){if(w(t))return{data:null,error:t};throw t}})}_deleteFactor(e){return D(this,void 0,void 0,function*(){try{return{data:yield T(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}})}}const yr="2.22.1",_r="http://localhost:9999",gr="supabase.auth.token",mr={"X-Client-Info":`gotrue-js/${yr}`},br=10,wr={getItem:n=>Oe()?globalThis.localStorage.getItem(n):null,setItem:(n,e)=>{!Oe()||globalThis.localStorage.setItem(n,e)},removeItem:n=>{!Oe()||globalThis.localStorage.removeItem(n)}};function Tr(){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!="undefined"&&(self.globalThis=self)}}var _=globalThis&&globalThis.__awaiter||function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(r.next(c))}catch(d){o(d)}}function h(c){try{l(r.throw(c))}catch(d){o(d)}}function l(c){c.done?s(c.value):i(c.value).then(a,h)}l((r=r.apply(n,e||[])).next())})};Tr();const Er={url:_r,storageKey:gr,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:mr,flowType:"implicit"},Re=10*1e3,Or=3;class Sr{constructor(e){var t;this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.broadcastChannel=null;const r=Object.assign(Object.assign({},Er),e);if(this.inMemorySession=null,this.storageKey=r.storageKey,this.autoRefreshToken=r.autoRefreshToken,this.persistSession=r.persistSession,this.storage=r.storage||wr,this.admin=new vr({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=Qe(r.fetch),this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,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)},M()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(t=this.broadcastChannel)===null||t===void 0||t.addEventListener("message",i=>{this._notifyAllSubscribers(i.data.event,i.data.session,!1)})}this.initialize()}initialize(){return this.initializePromise||(this.initializePromise=this._initialize()),this.initializePromise}_initialize(){return _(this,void 0,void 0,function*(){if(this.initializePromise)return this.initializePromise;try{const e=yield this._isPKCEFlow();if(this.detectSessionInUrl&&this._isImplicitGrantFlow()||e){const{data:t,error:r}=yield this._getSessionFromUrl(e);if(r)return yield this._removeSession(),{error:r};const{session:i,redirectType:s}=t;return yield this._saveSession(i),setTimeout(()=>{s==="recovery"?this._notifyAllSubscribers("PASSWORD_RECOVERY",i):this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return yield this._recoverAndRefresh(),{error:null}}catch(e){return w(e)?{error:e}:{error:new Ze("Unexpected error during initialization",e)}}finally{yield this._handleVisibilityChange()}})}signUp(e){var t,r,i;return _(this,void 0,void 0,function*(){try{yield this._removeSession();let s;if("email"in e){const{email:c,password:d,options:p}=e;s=yield T(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:p==null?void 0:p.emailRedirectTo,body:{email:c,password:d,data:(t=p==null?void 0:p.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:p==null?void 0:p.captchaToken}},xform:q})}else if("phone"in e){const{phone:c,password:d,options:p}=e;s=yield T(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:d,data:(r=p==null?void 0:p.data)!==null&&r!==void 0?r:{},channel:(i=p==null?void 0:p.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:p==null?void 0:p.captchaToken}},xform:q})}else throw new je("You must provide either an email or phone number and a password");const{data:o,error:a}=s;if(a||!o)return{data:{user:null,session:null},error:a};const h=o.session,l=o.user;return o.session&&(yield this._saveSession(o.session),this._notifyAllSubscribers("SIGNED_IN",h)),{data:{user:l,session:h},error:null}}catch(s){if(w(s))return{data:{user:null,session:null},error:s};throw s}})}signInWithPassword(e){return _(this,void 0,void 0,function*(){try{yield this._removeSession();let t;if("email"in e){const{email:s,password:o,options:a}=e;t=yield T(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:o,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:q})}else if("phone"in e){const{phone:s,password:o,options:a}=e;t=yield T(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:o,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:q})}else throw new je("You must provide either an email or phone number and a password");const{data:r,error:i}=t;return i||!r?{data:{user:null,session:null},error:i}:(r.session&&(yield this._saveSession(r.session),this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:r,error:i})}catch(t){if(w(t))return{data:{user:null,session:null},error:t};throw t}})}signInWithOAuth(e){var t,r,i,s;return _(this,void 0,void 0,function*(){return yield this._removeSession(),yield this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(s=e.options)===null||s===void 0?void 0:s.skipBrowserRedirect})})}exchangeCodeForSession(e){return _(this,void 0,void 0,function*(){const t=yield le(this.storage,`${this.storageKey}-code-verifier`),{data:r,error:i}=yield T(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:t},xform:q});return yield Xe(this.storage,`${this.storageKey}-code-verifier`),i||!r?{data:{user:null,session:null},error:i}:(r.session&&(yield this._saveSession(r.session),this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:r,error:i})})}signInWithIdToken(e){return _(this,void 0,void 0,function*(){yield this._removeSession();try{const{options:t,provider:r,token:i,nonce:s}=e,o=yield T(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:i,nonce:s,gotrue_meta_security:{captcha_token:t==null?void 0:t.captchaToken}},xform:q}),{data:a,error:h}=o;return h||!a?{data:{user:null,session:null},error:h}:(a.session&&(yield this._saveSession(a.session),this._notifyAllSubscribers("SIGNED_IN",a.session)),{data:a,error:h})}catch(t){if(w(t))return{data:{user:null,session:null},error:t};throw t}})}signInWithOtp(e){var t,r,i,s,o;return _(this,void 0,void 0,function*(){try{if(yield this._removeSession(),"email"in e){const{email:a,options:h}=e;let l=null;if(this.flowType==="pkce"){const d=Se();yield he(this.storage,`${this.storageKey}-code-verifier`,d),l=yield ke(d)}const{error:c}=yield T(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=h==null?void 0:h.data)!==null&&t!==void 0?t:{},create_user:(r=h==null?void 0:h.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:h==null?void 0:h.captchaToken},code_challenge:l,code_challenge_method:l?"s256":null},redirectTo:h==null?void 0:h.emailRedirectTo});return{data:{user:null,session:null},error:c}}if("phone"in e){const{phone:a,options:h}=e,{error:l}=yield T(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=h==null?void 0:h.data)!==null&&i!==void 0?i:{},create_user:(s=h==null?void 0:h.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:h==null?void 0:h.captchaToken},channel:(o=h==null?void 0:h.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null},error:l}}throw new je("You must provide either an email or phone number.")}catch(a){if(w(a))return{data:{user:null,session:null},error:a};throw a}})}verifyOtp(e){var t,r;return _(this,void 0,void 0,function*(){try{yield this._removeSession();const{data:i,error:s}=yield T(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:(t=e.options)===null||t===void 0?void 0:t.captchaToken}}),redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,xform:q});if(s)throw s;if(!i)throw new Error("An error occurred on token verification.");const o=i.session,a=i.user;return o!=null&&o.access_token&&(yield this._saveSession(o),this._notifyAllSubscribers("SIGNED_IN",o)),{data:{user:a,session:o},error:null}}catch(i){if(w(i))return{data:{user:null,session:null},error:i};throw i}})}signInWithSSO(e){var t,r,i;return _(this,void 0,void 0,function*(){try{return yield this._removeSession(),yield T(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),!((i=e==null?void 0:e.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0}),headers:this.headers,xform:lr})}catch(s){if(w(s))return{data:null,error:s};throw s}})}getSession(){return _(this,void 0,void 0,function*(){yield this.initializePromise;let e=null;if(this.persistSession){const s=yield le(this.storage,this.storageKey);s!==null&&(this._isValidSession(s)?e=s:yield this._removeSession())}else e=this.inMemorySession;if(!e)return{data:{session:null},error:null};if(!(e.expires_at?e.expires_at<=Date.now()/1e3:!1))return{data:{session:e},error:null};const{session:r,error:i}=yield this._callRefreshToken(e.refresh_token);return i?{data:{session:null},error:i}:{data:{session:r},error:null}})}getUser(e){var t,r;return _(this,void 0,void 0,function*(){try{if(!e){const{data:i,error:s}=yield this.getSession();if(s)throw s;e=(r=(t=i.session)===null||t===void 0?void 0:t.access_token)!==null&&r!==void 0?r:void 0}return yield T(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:K})}catch(i){if(w(i))return{data:{user:null},error:i};throw i}})}updateUser(e,t={}){return _(this,void 0,void 0,function*(){try{const{data:r,error:i}=yield this.getSession();if(i)throw i;if(!r.session)throw new ne;const s=r.session,{data:o,error:a}=yield T(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t==null?void 0:t.emailRedirectTo,body:e,jwt:s.access_token,xform:K});if(a)throw a;return s.user=o.user,yield this._saveSession(s),this._notifyAllSubscribers("USER_UPDATED",s),{data:{user:s.user},error:null}}catch(r){if(w(r))return{data:{user:null},error:r};throw r}})}_decodeJWT(e){return Ye(e)}setSession(e){return _(this,void 0,void 0,function*(){try{if(!e.access_token||!e.refresh_token)throw new ne;const t=Date.now()/1e3;let r=t,i=!0,s=null;const o=Ye(e.access_token);if(o.exp&&(r=o.exp,i=r<=t),i){const{session:a,error:h}=yield this._callRefreshToken(e.refresh_token);if(h)return{data:{user:null,session:null},error:h};if(!a)return{data:{user:null,session:null},error:null};s=a}else{const{data:a,error:h}=yield this.getUser(e.access_token);if(h)throw h;s={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:r-t,expires_at:r},yield this._saveSession(s),this._notifyAllSubscribers("SIGNED_IN",s)}return{data:{user:s.user,session:s},error:null}}catch(t){if(w(t))return{data:{session:null,user:null},error:t};throw t}})}refreshSession(e){var t;return _(this,void 0,void 0,function*(){try{if(!e){const{data:s,error:o}=yield this.getSession();if(o)throw o;e=(t=s.session)!==null&&t!==void 0?t:void 0}if(!(e!=null&&e.refresh_token))throw new ne;const{session:r,error:i}=yield this._callRefreshToken(e.refresh_token);return i?{data:{user:null,session:null},error:i}:r?{data:{user:r.user,session:r},error:null}:{data:{user:null,session:null},error:null}}catch(r){if(w(r))return{data:{user:null,session:null},error:r};throw r}})}_getSessionFromUrl(e){return _(this,void 0,void 0,function*(){try{if(!M())throw new L("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new L("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new xe("Not a valid PKCE flow url.");if(e){const y=A("code");if(!y)throw new xe("No code detected.");const{data:S,error:C}=yield this.exchangeCodeForSession(y);if(C)throw C;if(!S.session)throw new xe("No session detected.");return{data:{session:S.session,redirectType:null},error:null}}const t=A("error_description");if(t){const y=A("error_code");if(!y)throw new L("No error_code detected.");const S=A("error");throw S?new L(t,{error:S,code:y}):new L("No error detected.")}const r=A("provider_token"),i=A("provider_refresh_token"),s=A("access_token");if(!s)throw new L("No access_token detected.");const o=A("expires_in");if(!o)throw new L("No expires_in detected.");const a=A("refresh_token");if(!a)throw new L("No refresh_token detected.");const h=A("token_type");if(!h)throw new L("No token_type detected.");const c=Math.round(Date.now()/1e3)+parseInt(o),{data:d,error:p}=yield this.getUser(s);if(p)throw p;const g=d.user,v={provider_token:r,provider_refresh_token:i,access_token:s,expires_in:parseInt(o),expires_at:c,refresh_token:a,token_type:h,user:g},b=A("type");return window.location.hash="",{data:{session:v,redirectType:b},error:null}}catch(t){if(w(t))return{data:{session:null,redirectType:null},error:t};throw t}})}_isImplicitGrantFlow(){return M()&&(Boolean(A("access_token"))||Boolean(A("error_description")))}_isPKCEFlow(){return _(this,void 0,void 0,function*(){const e=yield le(this.storage,`${this.storageKey}-code-verifier`);return M()&&Boolean(A("code"))&&Boolean(e)})}signOut(){var e;return _(this,void 0,void 0,function*(){const{data:t,error:r}=yield this.getSession();if(r)return{error:r};const i=(e=t.session)===null||e===void 0?void 0:e.access_token;if(i){const{error:s}=yield this.admin.signOut(i);if(s&&!(nr(s)&&(s.status===404||s.status===401)))return{error:s}}return yield this._removeSession(),this._notifyAllSubscribers("SIGNED_OUT",null),{error:null}})}onAuthStateChange(e){const t=Qt(),r={id:t,callback:e,unsubscribe:()=>{this.stateChangeEmitters.delete(t)}};return this.stateChangeEmitters.set(t,r),this.emitInitialSession(t),{data:{subscription:r}}}emitInitialSession(e){var t,r;return _(this,void 0,void 0,function*(){try{const{data:{session:i},error:s}=yield this.getSession();if(s)throw s;(t=this.stateChangeEmitters.get(e))===null||t===void 0||t.callback("INITIAL_SESSION",i)}catch(i){(r=this.stateChangeEmitters.get(e))===null||r===void 0||r.callback("INITIAL_SESSION",null),console.error(i)}})}resetPasswordForEmail(e,t={}){return _(this,void 0,void 0,function*(){let r=null;if(this.flowType==="pkce"){const i=Se();yield he(this.storage,`${this.storageKey}-code-verifier`,i),r=yield ke(i)}try{return yield T(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:r?"s256":null,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(i){if(w(i))return{data:null,error:i};throw i}})}_refreshAccessToken(e){return _(this,void 0,void 0,function*(){try{const t=Date.now();return yield er(r=>_(this,void 0,void 0,function*(){return yield Zt(r*200),yield T(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:q})}),(r,i,s)=>s&&s.error&&s.error instanceof Ae&&Date.now()+(r+1)*200-t<Re)}catch(t){if(w(t))return{data:{session:null,user:null},error:t};throw t}})}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}_handleProviderSignIn(e,t){return _(this,void 0,void 0,function*(){const r=yield this._getUrlForProvider(e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return M()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}})}_recoverAndRefresh(){var e;return _(this,void 0,void 0,function*(){try{const t=yield le(this.storage,this.storageKey);if(!this._isValidSession(t)){t!==null&&(yield this._removeSession());return}const r=Math.round(Date.now()/1e3);if(((e=t.expires_at)!==null&&e!==void 0?e:1/0)<r+br)if(this.autoRefreshToken&&t.refresh_token){const{error:i}=yield this._callRefreshToken(t.refresh_token);i&&(console.log(i.message),yield this._removeSession())}else yield this._removeSession();else this.persistSession&&(yield this._saveSession(t)),this._notifyAllSubscribers("SIGNED_IN",t)}catch(t){console.error(t);return}})}_callRefreshToken(e){var t,r;return _(this,void 0,void 0,function*(){if(this.refreshingDeferred)return this.refreshingDeferred.promise;try{if(this.refreshingDeferred=new ue,!e)throw new ne;const{data:i,error:s}=yield this._refreshAccessToken(e);if(s)throw s;if(!i.session)throw new ne;yield this._saveSession(i.session),this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);const o={session:i.session,error:null};return this.refreshingDeferred.resolve(o),o}catch(i){if(w(i)){const s={session:null,error:i};return(t=this.refreshingDeferred)===null||t===void 0||t.resolve(s),s}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(i),i}finally{this.refreshingDeferred=null}})}_notifyAllSubscribers(e,t,r=!0){this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t}),this.stateChangeEmitters.forEach(i=>i.callback(e,t))}_saveSession(e){return _(this,void 0,void 0,function*(){this.persistSession||(this.inMemorySession=e),this.persistSession&&e.expires_at&&(yield this._persistSession(e))})}_persistSession(e){return he(this.storage,this.storageKey,e)}_removeSession(){return _(this,void 0,void 0,function*(){this.persistSession?yield Xe(this.storage,this.storageKey):this.inMemorySession=null})}_removeVisibilityChangedCallback(){const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&M()&&(window==null?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}_startAutoRefresh(){return _(this,void 0,void 0,function*(){yield this._stopAutoRefresh();const e=setInterval(()=>this._autoRefreshTokenTick(),Re);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno!="undefined"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),yield this._autoRefreshTokenTick()})}_stopAutoRefresh(){return _(this,void 0,void 0,function*(){const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)})}startAutoRefresh(){return _(this,void 0,void 0,function*(){this._removeVisibilityChangedCallback(),yield this._startAutoRefresh()})}stopAutoRefresh(){return _(this,void 0,void 0,function*(){this._removeVisibilityChangedCallback(),yield this._stopAutoRefresh()})}_autoRefreshTokenTick(){return _(this,void 0,void 0,function*(){const e=Date.now();try{const{data:{session:t}}=yield this.getSession();if(!t||!t.refresh_token||!t.expires_at)return;Math.floor((t.expires_at*1e3-e)/Re)<Or&&(yield this._callRefreshToken(t.refresh_token))}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}})}_handleVisibilityChange(){return _(this,void 0,void 0,function*(){if(!M()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=()=>_(this,void 0,void 0,function*(){return yield this._onVisibilityChanged(!1)}),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),yield this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}})}_onVisibilityChanged(e){return _(this,void 0,void 0,function*(){document.visibilityState==="visible"?(e||(yield this.initializePromise,yield this._recoverAndRefresh()),this.autoRefreshToken&&this._startAutoRefresh()):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()})}_getUrlForProvider(e,t){return _(this,void 0,void 0,function*(){const r=[`provider=${encodeURIComponent(e)}`];if(t!=null&&t.redirectTo&&r.push(`redirect_to=${encodeURIComponent(t.redirectTo)}`),t!=null&&t.scopes&&r.push(`scopes=${encodeURIComponent(t.scopes)}`),this.flowType==="pkce"){const i=Se();yield he(this.storage,`${this.storageKey}-code-verifier`,i);const s=yield ke(i),o=new URLSearchParams({code_challenge:`${encodeURIComponent(s)}`,code_challenge_method:`${encodeURIComponent("s256")}`});r.push(o.toString())}if(t!=null&&t.queryParams){const i=new URLSearchParams(t.queryParams);r.push(i.toString())}return`${this.url}/authorize?${r.join("&")}`})}_unenroll(e){var t;return _(this,void 0,void 0,function*(){try{const{data:r,error:i}=yield this.getSession();return i?{data:null,error:i}:yield T(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(t=r==null?void 0:r.session)===null||t===void 0?void 0:t.access_token})}catch(r){if(w(r))return{data:null,error:r};throw r}})}_enroll(e){var t,r;return _(this,void 0,void 0,function*(){try{const{data:i,error:s}=yield this.getSession();if(s)return{data:null,error:s};const{data:o,error:a}=yield T(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(t=i==null?void 0:i.session)===null||t===void 0?void 0:t.access_token});return a?{data:null,error:a}:(!((r=o==null?void 0:o.totp)===null||r===void 0)&&r.qr_code&&(o.totp.qr_code=`data:image/svg+xml;utf-8,${o.totp.qr_code}`),{data:o,error:null})}catch(i){if(w(i))return{data:null,error:i};throw i}})}_verify(e){var t;return _(this,void 0,void 0,function*(){try{const{data:r,error:i}=yield this.getSession();if(i)return{data:null,error:i};const{data:s,error:o}=yield T(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(t=r==null?void 0:r.session)===null||t===void 0?void 0:t.access_token});return o?{data:null,error:o}:(yield this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+s.expires_in},s)),this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",s),{data:s,error:o})}catch(r){if(w(r))return{data:null,error:r};throw r}})}_challenge(e){var t;return _(this,void 0,void 0,function*(){try{const{data:r,error:i}=yield this.getSession();return i?{data:null,error:i}:yield T(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(t=r==null?void 0:r.session)===null||t===void 0?void 0:t.access_token})}catch(r){if(w(r))return{data:null,error:r};throw r}})}_challengeAndVerify(e){return _(this,void 0,void 0,function*(){const{data:t,error:r}=yield this._challenge({factorId:e.factorId});return r?{data:null,error:r}:yield this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})})}_listFactors(){return _(this,void 0,void 0,function*(){const{data:{user:e},error:t}=yield this.getUser();if(t)return{data:null,error:t};const r=(e==null?void 0:e.factors)||[],i=r.filter(s=>s.factor_type==="totp"&&s.status==="verified");return{data:{all:r,totp:i},error:null}})}_getAuthenticatorAssuranceLevel(){var e,t;return _(this,void 0,void 0,function*(){const{data:{session:r},error:i}=yield this.getSession();if(i)return{data:null,error:i};if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const s=this._decodeJWT(r.access_token);let o=null;s.aal&&(o=s.aal);let a=o;((t=(e=r.user.factors)===null||e===void 0?void 0:e.filter(c=>c.status==="verified"))!==null&&t!==void 0?t:[]).length>0&&(a="aal2");const l=s.amr||[];return{data:{currentLevel:o,nextLevel:a,currentAuthenticationMethods:l},error:null}})}}class kr extends Sr{constructor(e){super(e)}}var $r=globalThis&&globalThis.__awaiter||function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{l(r.next(c))}catch(d){o(d)}}function h(c){try{l(r.throw(c))}catch(d){o(d)}}function l(c){c.done?s(c.value):i(c.value).then(a,h)}l((r=r.apply(n,e||[])).next())})};const jr={headers:qt},xr={schema:"public"},Ar={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Pr={};class Rr{constructor(e,t,r){var i,s,o,a,h,l,c,d;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");const p=Kt(e);if(this.realtimeUrl=`${p}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${p}/auth/v1`,this.storageUrl=`${p}/storage/v1`,p.match(/(supabase\.co)|(supabase\.in)/)){const S=p.split(".");this.functionsUrl=`${S[0]}.functions.${S[1]}.${S[2]}`}else this.functionsUrl=`${p}/functions/v1`;const v=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,b={db:xr,realtime:Pr,auth:Object.assign(Object.assign({},Ar),{storageKey:v}),global:jr},y=Vt(r!=null?r:{},b);this.storageKey=(s=(i=y.auth)===null||i===void 0?void 0:i.storageKey)!==null&&s!==void 0?s:"",this.headers=(a=(o=y.global)===null||o===void 0?void 0:o.headers)!==null&&a!==void 0?a:{},this.auth=this._initSupabaseAuthClient((h=y.auth)!==null&&h!==void 0?h:{},this.headers,(l=y.global)===null||l===void 0?void 0:l.fetch),this.fetch=Gt(t,this._getAccessToken.bind(this),(c=y.global)===null||c===void 0?void 0:c.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},y.realtime)),this.rest=new vt(`${p}/rest/v1`,{headers:this.headers,schema:(d=y.db)===null||d===void 0?void 0:d.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new ct(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Mt(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}rpc(e,t={},r){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return $r(this,void 0,void 0,function*(){const{data:r}=yield this.auth.getSession();return(t=(e=r.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,storageKey:s,flowType:o},a,h){const l={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new kr({url:this.authUrl,headers:Object.assign(Object.assign({},l),a),storageKey:s,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,flowType:o,fetch:h})}_initRealtimeClient(e){return new Pt(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,r)=>{this._handleTokenChanged(t,r==null?void 0:r.access_token,"CLIENT")})}_handleTokenChanged(e,t,r){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==t?(this.realtime.setAuth(t!=null?t:null),this.changedAccessToken=t):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),r=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const Cr=(n,e,t)=>new Rr(n,e,t),et=Symbol(),Ir=()=>Z.inject(et);var Dr={install:function(n,e){const{supabaseUrl:t,supabaseKey:r,options:i={}}=e,s=Cr(t,r,i);n.config.globalProperties.$supabase=s,n.provide(et,s)}};B.default=Dr,B.useSupabase=Ir,Object.defineProperties(B,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});