const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["chunks/index.mjs-Cccyz-G1.js","chunks/chunk-CLN-lmR0.js"])))=>i.map(i=>d[i]); import{g as e,e as t}from"./chunk-CLN-lmR0.js";import{_ as s}from"./chunk-5rBBrdbz.js";class r extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}}class i extends r{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class n extends r{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class o extends r{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var a,l;(l=a||(a={})).Any="any",l.ApNortheast1="ap-northeast-1",l.ApNortheast2="ap-northeast-2",l.ApSouth1="ap-south-1",l.ApSoutheast1="ap-southeast-1",l.ApSoutheast2="ap-southeast-2",l.CaCentral1="ca-central-1",l.EuCentral1="eu-central-1",l.EuWest1="eu-west-1",l.EuWest2="eu-west-2",l.EuWest3="eu-west-3",l.SaEast1="sa-east-1",l.UsEast1="us-east-1",l.UsWest1="us-west-1",l.UsWest2="us-west-2";var h=function(e,t,s,r){return new(s||(s=Promise))(function(i,n){function o(e){try{l(r.next(e))}catch(t){n(t)}}function a(e){try{l(r.throw(e))}catch(t){n(t)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(o,a)}l((r=r.apply(e,t||[])).next())})};class c{constructor(e,{headers:t={},customFetch:r,region:i=a.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=(e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>s(async()=>{const{default:e}=await Promise.resolve().then(()=>S);return{default:e}},void 0).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)})(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return h(this,void 0,void 0,function*(){try{const{headers:r,method:a,body:l,signal:h}=t;let c={},{region:u}=t;u||(u=this.region);const d=new URL(`${this.url}/${e}`);let f;u&&"any"!==u&&(c["x-region"]=u,d.searchParams.set("forceFunctionRegion",u)),l&&(r&&!Object.prototype.hasOwnProperty.call(r,"Content-Type")||!r)&&("undefined"!=typeof Blob&&l instanceof Blob||l instanceof ArrayBuffer?(c["Content-Type"]="application/octet-stream",f=l):"string"==typeof l?(c["Content-Type"]="text/plain",f=l):"undefined"!=typeof FormData&&l instanceof FormData?f=l:(c["Content-Type"]="application/json",f=JSON.stringify(l)));const p=yield this.fetch(d.toString(),{method:a||"POST",headers:Object.assign(Object.assign(Object.assign({},c),this.headers),r),body:f,signal:h}).catch(e=>{if("AbortError"===e.name)throw e;throw new i(e)}),g=p.headers.get("x-relay-error");if(g&&"true"===g)throw new n(p);if(!p.ok)throw new o(p);let w,v=(null!==(s=p.headers.get("Content-Type"))&&void 0!==s?s:"text/plain").split(";")[0].trim();return w="application/json"===v?yield p.json():"application/octet-stream"===v?yield p.blob():"text/event-stream"===v?p:"multipart/form-data"===v?yield p.formData():yield p.text(),{data:w,error:null,response:p}}catch(r){return r instanceof Error&&"AbortError"===r.name?{data:null,error:new i(r)}:{data:null,error:r,response:r instanceof o||r instanceof n?r.context:void 0}}})}}var u={},d={},f={},p={},g={},w={},v=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("unable to locate global object")}();const y=v.fetch,m=v.fetch.bind(v),_=v.Headers,b=v.Request,k=v.Response,S=Object.freeze(Object.defineProperty({__proto__:null,Headers:_,Request:b,Response:k,default:m,fetch:y},Symbol.toStringTag,{value:"Module"})),T=e(S);var E,j,O,P,$,I,A,C={};function R(){if(E)return C;E=1,Object.defineProperty(C,"__esModule",{value:!0});class e extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}}return C.default=e,C}function x(){if(j)return w;j=1;var e=w&&w.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(w,"__esModule",{value:!0});const t=e(T),s=e(R());return w.default=class{constructor(e){var s,r;this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=null!==(s=e.shouldThrowOnError)&&void 0!==s&&s,this.signal=e.signal,this.isMaybeSingle=null!==(r=e.isMaybeSingle)&&void 0!==r&&r,e.fetch?this.fetch=e.fetch:"undefined"==typeof fetch?this.fetch=t.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}then(e,t){void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),"GET"!==this.method&&"HEAD"!==this.method&&this.headers.set("Content-Type","application/json");let r=(0,this.fetch)(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async e=>{var t,r,i,n;let o=null,a=null,l=null,h=e.status,c=e.statusText;if(e.ok){if("HEAD"!==this.method){const s=await e.text();""===s||(a="text/csv"===this.headers.get("Accept")||this.headers.get("Accept")&&(null===(t=this.headers.get("Accept"))||void 0===t?void 0:t.includes("application/vnd.pgrst.plan+text"))?s:JSON.parse(s))}const s=null===(r=this.headers.get("Prefer"))||void 0===r?void 0:r.match(/count=(exact|planned|estimated)/),n=null===(i=e.headers.get("content-range"))||void 0===i?void 0:i.split("/");s&&n&&n.length>1&&(l=parseInt(n[1])),this.isMaybeSingle&&"GET"===this.method&&Array.isArray(a)&&(a.length>1?(o={code:"PGRST116",details:`Results contain ${a.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},a=null,l=null,h=406,c="Not Acceptable"):a=1===a.length?a[0]:null)}else{const t=await e.text();try{o=JSON.parse(t),Array.isArray(o)&&404===e.status&&(a=[],o=null,h=200,c="OK")}catch(u){404===e.status&&""===t?(h=204,c="No Content"):o={message:t}}if(o&&this.isMaybeSingle&&(null===(n=null==o?void 0:o.details)||void 0===n?void 0:n.includes("0 rows"))&&(o=null,h=200,c="OK"),o&&this.shouldThrowOnError)throw new s.default(o)}return{error:o,data:a,count:l,status:h,statusText:c}});return this.shouldThrowOnError||(r=r.catch(e=>{var t,s,r;return{error:{message:`${null!==(t=null==e?void 0:e.name)&&void 0!==t?t:"FetchError"}: ${null==e?void 0:e.message}`,details:`${null!==(s=null==e?void 0:e.stack)&&void 0!==s?s:""}`,hint:"",code:`${null!==(r=null==e?void 0:e.code)&&void 0!==r?r:""}`},data:null,count:null,status:0,statusText:""}})),r.then(e,t)}returns(){return this}overrideTypes(){return this}},w}function U(){if(O)return g;O=1;var e=g&&g.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(g,"__esModule",{value:!0});const t=e(x());class s extends t.default{select(e){let t=!1;const s=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e)).join("");return this.url.searchParams.set("select",s),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable:r,referencedTable:i=r}={}){const n=i?`${i}.order`:"order",o=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${o?`${o},`:""}${e}.${t?"asc":"desc"}${void 0===s?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){const r=void 0===s?"limit":`${s}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:r=s}={}){const i=void 0===r?"offset":`${r}.offset`,n=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(n,""+(t-e+1)),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return"GET"===this.method?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:s=!1,buffers:r=!1,wal:i=!1,format:n="text"}={}){var o;const a=[e?"analyze":null,t?"verbose":null,s?"settings":null,r?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=null!==(o=this.headers.get("Accept"))&&void 0!==o?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${n}; for="${l}"; options=${a};`),this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}}return g.default=s,g}function L(){if(P)return p;P=1;var e=p&&p.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(p,"__esModule",{value:!0});const t=e(U());class s extends t.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){const s=Array.from(new Set(t)).map(e=>"string"==typeof e&&new RegExp("[,()]").test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`in.(${s})`),this}contains(e,t){return"string"==typeof t?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"string"==typeof t?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"string"==typeof t?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:s,type:r}={}){let i="";"plain"===r?i="pl":"phrase"===r?i="ph":"websearch"===r&&(i="w");const n=void 0===s?"":`(${s})`;return this.url.searchParams.append(e,`${i}fts${n}.${t}`),this}match(e){return Object.entries(e).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){const r=s?`${s}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}}return p.default=s,p}function N(){if($)return f;$=1;var e=f&&f.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(f,"__esModule",{value:!0});const t=e(L());return f.default=class{constructor(e,{headers:t={},schema:s,fetch:r}){this.url=e,this.headers=new Headers(t),this.schema=s,this.fetch=r}select(e,{head:s=!1,count:r}={}){const i=s?"HEAD":"GET";let n=!1;const o=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!n?"":('"'===e&&(n=!n),e)).join("");return this.url.searchParams.set("select",o),r&&this.headers.append("Prefer",`count=${r}`),new t.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(e,{count:s,defaultToNull:r=!0}={}){var i;if(s&&this.headers.append("Prefer",`count=${s}`),r||this.headers.append("Prefer","missing=default"),Array.isArray(e)){const t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){const e=[...new Set(t)].map(e=>`"${e}"`);this.url.searchParams.set("columns",e.join(","))}}return new t.default({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:null!==(i=this.fetch)&&void 0!==i?i:fetch})}upsert(e,{onConflict:s,ignoreDuplicates:r=!1,count:i,defaultToNull:n=!0}={}){var o;if(this.headers.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),void 0!==s&&this.url.searchParams.set("on_conflict",s),i&&this.headers.append("Prefer",`count=${i}`),n||this.headers.append("Prefer","missing=default"),Array.isArray(e)){const t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){const e=[...new Set(t)].map(e=>`"${e}"`);this.url.searchParams.set("columns",e.join(","))}}return new t.default({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:null!==(o=this.fetch)&&void 0!==o?o:fetch})}update(e,{count:s}={}){var r;return s&&this.headers.append("Prefer",`count=${s}`),new t.default({method:"PATCH",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:null!==(r=this.fetch)&&void 0!==r?r:fetch})}delete({count:e}={}){var s;return e&&this.headers.append("Prefer",`count=${e}`),new t.default({method:"DELETE",url:this.url,headers:this.headers,schema:this.schema,fetch:null!==(s=this.fetch)&&void 0!==s?s:fetch})}},f}const D=t(function(){if(A)return u;A=1;var e=u&&u.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(u,"__esModule",{value:!0}),u.PostgrestError=u.PostgrestBuilder=u.PostgrestTransformBuilder=u.PostgrestFilterBuilder=u.PostgrestQueryBuilder=u.PostgrestClient=void 0;const t=e(function(){if(I)return d;I=1;var e=d&&d.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(d,"__esModule",{value:!0});const t=e(N()),s=e(L());class r{constructor(e,{headers:t={},schema:s,fetch:r}={}){this.url=e,this.headers=new Headers(t),this.schemaName=s,this.fetch=r}from(e){const s=new URL(`${this.url}/${e}`);return new t.default(s,{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new r(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:i=!1,count:n}={}){var o;let a;const l=new URL(`${this.url}/rpc/${e}`);let h;r||i?(a=r?"HEAD":"GET",Object.entries(t).filter(([e,t])=>void 0!==t).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}`]).forEach(([e,t])=>{l.searchParams.append(e,t)})):(a="POST",h=t);const c=new Headers(this.headers);return n&&c.set("Prefer",`count=${n}`),new s.default({method:a,url:l,headers:c,schema:this.schemaName,body:h,fetch:null!==(o=this.fetch)&&void 0!==o?o:fetch})}}return d.default=r,d}());u.PostgrestClient=t.default;const s=e(N());u.PostgrestQueryBuilder=s.default;const r=e(L());u.PostgrestFilterBuilder=r.default;const i=e(U());u.PostgrestTransformBuilder=i.default;const n=e(x());u.PostgrestBuilder=n.default;const o=e(R());return u.PostgrestError=o.default,u.default={PostgrestClient:t.default,PostgrestQueryBuilder:s.default,PostgrestFilterBuilder:r.default,PostgrestTransformBuilder:i.default,PostgrestBuilder:n.default,PostgrestError:o.default},u}()),{PostgrestClient:q,PostgrestQueryBuilder:B,PostgrestFilterBuilder:W,PostgrestTransformBuilder:M,PostgrestBuilder:F,PostgrestError:K}=D;class z{static detectEnvironment(){var e;if("undefined"!=typeof WebSocket)return{type:"native",constructor:WebSocket};if("undefined"!=typeof globalThis&&void 0!==globalThis.WebSocket)return{type:"native",constructor:globalThis.WebSocket};if("undefined"!=typeof global&&void 0!==global.WebSocket)return{type:"native",constructor:global.WebSocket};if("undefined"!=typeof globalThis&&void 0!==globalThis.WebSocketPair&&void 0===globalThis.WebSocket)return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if("undefined"!=typeof globalThis&&globalThis.EdgeRuntime||"undefined"!=typeof navigator&&(null===(e=navigator.userAgent)||void 0===e?void 0:e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};if("undefined"!=typeof process){const e=process.versions;if(e&&e.node){const t=e.node,s=parseInt(t.replace(/^v/,"").split(".")[0]);return s>=22?void 0!==globalThis.WebSocket?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${s} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${s} detected without native WebSocket support.`,workaround:'For Node.js < 22, install "ws" package and provide it via the transport option:\nimport ws from "ws"\nnew RealtimeClient(url, { transport: ws })'}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=`\n\nSuggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){return new(this.getWebSocketConstructor())(e,t)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return"native"===e.type||"ws"===e.type}catch(e){return!1}}}const H=1e4;var J,G,V,Y,Q,X,Z,ee,te,se,re;(G=J||(J={}))[G.connecting=0]="connecting",G[G.open=1]="open",G[G.closing=2]="closing",G[G.closed=3]="closed",(Y=V||(V={})).closed="closed",Y.errored="errored",Y.joined="joined",Y.joining="joining",Y.leaving="leaving",(X=Q||(Q={})).close="phx_close",X.error="phx_error",X.join="phx_join",X.reply="phx_reply",X.leave="phx_leave",X.access_token="access_token",(Z||(Z={})).websocket="websocket",(te=ee||(ee={})).Connecting="connecting",te.Open="open",te.Closing="closing",te.Closed="closed";class ie{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t("string"==typeof e?JSON.parse(e):{})}_binaryDecode(e){const t=new DataView(e),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){const r=t.getUint8(1),i=t.getUint8(2);let n=this.HEADER_LENGTH+2;const o=s.decode(e.slice(n,n+r));n+=r;const a=s.decode(e.slice(n,n+i));n+=i;return{ref:null,topic:o,event:a,payload:JSON.parse(s.decode(e.slice(n,e.byteLength)))}}}class ne{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}(re=se||(se={})).abstime="abstime",re.bool="bool",re.date="date",re.daterange="daterange",re.float4="float4",re.float8="float8",re.int2="int2",re.int4="int4",re.int4range="int4range",re.int8="int8",re.int8range="int8range",re.json="json",re.jsonb="jsonb",re.money="money",re.numeric="numeric",re.oid="oid",re.reltime="reltime",re.text="text",re.time="time",re.timestamp="timestamp",re.timestamptz="timestamptz",re.timetz="timetz",re.tsrange="tsrange",re.tstzrange="tstzrange";const oe=(e,t,s={})=>{var r;const i=null!==(r=s.skipTypes)&&void 0!==r?r:[];return Object.keys(t).reduce((s,r)=>(s[r]=ae(r,e,t,i),s),{})},ae=(e,t,s,r)=>{const i=t.find(t=>t.name===e),n=null==i?void 0:i.type,o=s[e];return n&&!r.includes(n)?le(n,o):he(o)},le=(e,t)=>{if("_"===e.charAt(0)){const s=e.slice(1,e.length);return fe(t,s)}switch(e){case se.bool:return ce(t);case se.float4:case se.float8:case se.int2:case se.int4:case se.int8:case se.numeric:case se.oid:return ue(t);case se.json:case se.jsonb:return de(t);case se.timestamp:return pe(t);case se.abstime:case se.date:case se.daterange:case se.int4range:case se.int8range:case se.money:case se.reltime:case se.text:case se.time:case se.timestamptz:case se.timetz:case se.tsrange:case se.tstzrange:default:return he(t)}},he=e=>e,ce=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},ue=e=>{if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},de=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(t){return e}return e},fe=(e,t)=>{if("string"!=typeof e)return e;const s=e.length-1,r=e[s];if("{"===e[0]&&"}"===r){let r;const n=e.slice(1,s);try{r=JSON.parse("["+n+"]")}catch(i){r=n?n.split(","):[]}return r.map(e=>le(t,e))}return e},pe=e=>"string"==typeof e?e.replace(" ","T"):e,ge=e=>{let t=e;return t=t.replace(/^ws/i,"http"),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),t.replace(/\/+$/,"")+"/api/broadcast"};class we{constructor(e,t,s={},r=1e4){this.channel=e,this.event=t,this.payload=s,this.timeout=r,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var s;return this._hasReceived(e)&&t(null===(s=this.receivedResp)||void 0===s?void 0:s.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);this.channel._on(this.refEvent,{},e=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=e,this._matchReceive(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(t=>t.status===e).forEach(e=>e.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var ve,ye,me,_e,be,ke,Se,Te;(ye=ve||(ve={})).SYNC="sync",ye.JOIN="join",ye.LEAVE="leave";class Ee{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const s=(null==t?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},e=>{const{onJoin:t,onLeave:s,onSync:r}=this.caller;this.joinRef=this.channel._joinRef(),this.state=Ee.syncState(this.state,e,t,s),this.pendingDiffs.forEach(e=>{this.state=Ee.syncDiff(this.state,e,t,s)}),this.pendingDiffs=[],r()}),this.channel._on(s.diff,{},e=>{const{onJoin:t,onLeave:s,onSync:r}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(e):(this.state=Ee.syncDiff(this.state,e,t,s),r())}),this.onJoin((e,t,s)=>{this.channel._trigger("presence",{event:"join",key:e,currentPresences:t,newPresences:s})}),this.onLeave((e,t,s)=>{this.channel._trigger("presence",{event:"leave",key:e,currentPresences:t,leftPresences:s})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,r){const i=this.cloneDeep(e),n=this.transformState(t),o={},a={};return this.map(i,(e,t)=>{n[e]||(a[e]=t)}),this.map(n,(e,t)=>{const s=i[e];if(s){const r=t.map(e=>e.presence_ref),i=s.map(e=>e.presence_ref),n=t.filter(e=>i.indexOf(e.presence_ref)<0),l=s.filter(e=>r.indexOf(e.presence_ref)<0);n.length>0&&(o[e]=n),l.length>0&&(a[e]=l)}else o[e]=t}),this.syncDiff(i,{joins:o,leaves:a},s,r)}static syncDiff(e,t,s,r){const{joins:i,leaves:n}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),r||(r=()=>{}),this.map(i,(t,r)=>{var i;const n=null!==(i=e[t])&&void 0!==i?i:[];if(e[t]=this.cloneDeep(r),n.length>0){const s=e[t].map(e=>e.presence_ref),r=n.filter(e=>s.indexOf(e.presence_ref)<0);e[t].unshift(...r)}s(t,n,r)}),this.map(n,(t,s)=>{let i=e[t];if(!i)return;const n=s.map(e=>e.presence_ref);i=i.filter(e=>n.indexOf(e.presence_ref)<0),e[t]=i,r(t,i,s),0===i.length&&delete e[t]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,s)=>{const r=e[s];return t[s]="metas"in r?r.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e)):r,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()}}(_e=me||(me={})).ALL="*",_e.INSERT="INSERT",_e.UPDATE="UPDATE",_e.DELETE="DELETE",(ke=be||(be={})).BROADCAST="broadcast",ke.PRESENCE="presence",ke.POSTGRES_CHANGES="postgres_changes",ke.SYSTEM="system",(Te=Se||(Se={})).SUBSCRIBED="SUBSCRIBED",Te.TIMED_OUT="TIMED_OUT",Te.CLOSED="CLOSED",Te.CHANNEL_ERROR="CHANNEL_ERROR";class je{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=V.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new we(this,Q.join,this.params,this.timeout),this.rejoinTimer=new ne(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=V.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e=>e.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=V.closed,this.socket._remove(this)}),this._onError(e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=V.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=V.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=V.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Q.reply,{},(e,t)=>{this._trigger(this._replyEventName(t),e)}),this.presence=new Ee(this),this.broadcastEndpointURL=ge(this.socket.endPoint),this.private=this.params.config.private||!1}subscribe(e,t=this.timeout){var s,r,i;if(this.socket.isConnected()||this.socket.connect(),this.state==V.closed){const{config:{broadcast:n,presence:o,private:a}}=this.params,l=null!==(r=null===(s=this.bindings.postgres_changes)||void 0===s?void 0:s.map(e=>e.filter))&&void 0!==r?r:[],h=!!this.bindings[be.PRESENCE]&&this.bindings[be.PRESENCE].length>0||!0===(null===(i=this.params.config.presence)||void 0===i?void 0:i.enabled),c={},u={broadcast:n,presence:Object.assign(Object.assign({},o),{enabled:h}),postgres_changes:l,private:a};this.socket.accessTokenValue&&(c.access_token=this.socket.accessTokenValue),this._onError(t=>null==e?void 0:e(Se.CHANNEL_ERROR,t)),this._onClose(()=>null==e?void 0:e(Se.CLOSED)),this.updateJoinPayload(Object.assign({config:u},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:t})=>{var s;if(this.socket.setAuth(),void 0!==t){const r=this.bindings.postgres_changes,i=null!==(s=null==r?void 0:r.length)&&void 0!==s?s:0,n=[];for(let s=0;s{this.state=V.errored,null==e||e(Se.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(t).join(", ")||"error")))}).receive("timeout",()=>{null==e||e(Se.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this.state===V.joined&&e===be.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(()=>this.subscribe())),this._on(e,t,s)}async send(e,t={}){var s,r;if(this._canPush()||"broadcast"!==e.type)return new Promise(s=>{var r,i,n;const o=this._push(e.type,e,t.timeout||this.timeout);"broadcast"!==e.type||(null===(n=null===(i=null===(r=this.params)||void 0===r?void 0:r.config)||void 0===i?void 0:i.broadcast)||void 0===n?void 0:n.ack)||s("ok"),o.receive("ok",()=>s("ok")),o.receive("error",()=>s("error")),o.receive("timeout",()=>s("timed out"))});{const{event:n,payload:o}=e,a={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o,private:this.private}]})};try{const e=await this._fetchWithTimeout(this.broadcastEndpointURL,a,null!==(s=t.timeout)&&void 0!==s?s:this.timeout);return await(null===(r=e.body)||void 0===r?void 0:r.cancel()),e.ok?"ok":"error"}catch(i){return"AbortError"===i.name?"timed out":"error"}}}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=V.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Q.close,"leave",this._joinRef())};this.joinPush.destroy();let s=null;return new Promise(r=>{s=new we(this,Q.leave,{},e),s.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),s.send(),this._canPush()||s.trigger("ok",{})}).finally(()=>{null==s||s.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=V.closed,this.bindings={}}async _fetchWithTimeout(e,t,s){const r=new AbortController,i=setTimeout(()=>r.abort(),s),n=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.signal}));return clearTimeout(i),n}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let r=new we(this,e,t,s);return this._canPush()?r.send():this._addToPushBuffer(r),r}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>100){const e=this.pushBuffer.shift();e&&(e.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${e.event}`,e.payload))}}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var r,i;const n=e.toLocaleLowerCase(),{close:o,error:a,leave:l,join:h}=Q;if(s&&[o,a,l,h].indexOf(n)>=0&&s!==this._joinRef())return;let c=this._onMessage(n,t,s);if(t&&!c)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(n)?null===(r=this.bindings.postgres_changes)||void 0===r||r.filter(e=>{var t,s,r;return"*"===(null===(t=e.filter)||void 0===t?void 0:t.event)||(null===(r=null===(s=e.filter)||void 0===s?void 0:s.event)||void 0===r?void 0:r.toLocaleLowerCase())===n}).map(e=>e.callback(c,s)):null===(i=this.bindings[n])||void 0===i||i.filter(e=>{var s,r,i,o,a,l;if(["broadcast","presence","postgres_changes"].includes(n)){if("id"in e){const n=e.id,o=null===(s=e.filter)||void 0===s?void 0:s.event;return n&&(null===(r=t.ids)||void 0===r?void 0:r.includes(n))&&("*"===o||(null==o?void 0:o.toLocaleLowerCase())===(null===(i=t.data)||void 0===i?void 0:i.type.toLocaleLowerCase()))}{const s=null===(a=null===(o=null==e?void 0:e.filter)||void 0===o?void 0:o.event)||void 0===a?void 0:a.toLocaleLowerCase();return"*"===s||s===(null===(l=null==t?void 0:t.event)||void 0===l?void 0:l.toLocaleLowerCase())}}return e.type.toLocaleLowerCase()===n}).map(e=>{if("object"==typeof c&&"ids"in c){const e=c.data,{schema:t,table:s,commit_timestamp:r,type:i,errors:n}=e,o={schema:t,table:s,commit_timestamp:r,eventType:i,new:{},old:{},errors:n};c=Object.assign(Object.assign({},o),this._getPayloadRecords(e))}e.callback(c,s)})}_isClosed(){return this.state===V.closed}_isJoined(){return this.state===V.joined}_isJoining(){return this.state===V.joining}_isLeaving(){return this.state===V.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){const r=e.toLocaleLowerCase(),i={type:r,filter:t,callback:s};return this.bindings[r]?this.bindings[r].push(i):this.bindings[r]=[i],this}_off(e,t){const s=e.toLocaleLowerCase();return this.bindings[s]&&(this.bindings[s]=this.bindings[s].filter(e=>{var r;return!((null===(r=e.type)||void 0===r?void 0:r.toLocaleLowerCase())===s&&je.isEqual(e.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(Q.close,{},e)}_onError(e){this._on(Q.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=V.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return"INSERT"!==e.type&&"UPDATE"!==e.type||(t.new=oe(e.columns,e.record)),"UPDATE"!==e.type&&"DELETE"!==e.type||(t.old=oe(e.columns,e.old_record)),t}}const Oe=()=>{},Pe=25e3,$e=10,Ie=100,Ae=[1e3,2e3,5e3,1e4];class Ce{constructor(e,t){var r;if(this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=H,this.transport=null,this.heartbeatIntervalMs=Pe,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Oe,this.ref=0,this.reconnectTimer=null,this.logger=Oe,this.conn=null,this.sendBuffer=[],this.serializer=new ie,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._resolveFetch=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>s(async()=>{const{default:e}=await import("./index.mjs-Cccyz-G1.js");return{default:e}},__vite__mapDeps([0,1])).then(({default:t})=>t(...e)).catch(e=>{throw new Error(`Failed to load @supabase/node-fetch: ${e.message}. This is required for HTTP requests in Node.js environments without native fetch.`)}):fetch),(...e)=>t(...e)},!(null===(r=null==t?void 0:t.params)||void 0===r?void 0:r.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${Z.websocket}`,this.httpEndpoint=ge(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(null==t?void 0:t.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||null!==this.conn&&this.isConnected())){if(this._setConnectionState("connecting"),this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=z.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;if(t.includes("Node.js"))throw new Error(`${t}\n\nTo use Realtime in Node.js, you need to provide a WebSocket implementation:\n\nOption 1: Use Node.js 22+ which has native WebSocket support\nOption 2: Install and provide the "ws" package:\n\n npm install ws\n\n import ws from "ws"\n const client = new RealtimeClient(url, {\n ...options,\n transport: ws\n })`);throw new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:"1.0.0"}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const s=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(s),this._setConnectionState("disconnected")},e?this.conn.close(e,null!=t?t:""):this.conn.close(),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const t=await e.unsubscribe();return 0===this.channels.length&&this.disconnect(),t}async removeAllChannels(){const e=await Promise.all(this.channels.map(e=>e.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,s){this.logger(e,t,s)}connectionState(){switch(this.conn&&this.conn.readyState){case J.connecting:return ee.Connecting;case J.open:return ee.Open;case J.closing:return ee.Closing;default:return ee.Closed}}isConnected(){return this.connectionState()===ee.Open}isConnecting(){return"connecting"===this._connectionState}isDisconnecting(){return"disconnecting"===this._connectionState}channel(e,t={config:{}}){const s=`realtime:${e}`,r=this.getChannels().find(e=>e.topic===s);if(r)return r;{const s=new je(`realtime:${e}`,t,this);return this.channels.push(s),s}}push(e){const{topic:t,event:s,payload:r,ref:i}=e,n=()=>{this.encode(e,e=>{var t;null===(t=this.conn)||void 0===t||t.send(e)})};this.log("push",`${t} ${s} (${i})`,r),this.isConnected()?n():this.sendBuffer.push(n)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}async sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}return this._wasManualDisconnect=!1,null===(e=this.conn)||void 0===e||e.close(1e3,"heartbeat timeout"),void setTimeout(()=>{var e;this.isConnected()||null===(e=this.reconnectTimer)||void 0===e||e.scheduleTimeout()},Ie)}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this._setAuthSafely("heartbeat")}else try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t._isJoined()||t._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,e=>{if("phoenix"===e.topic&&"phx_reply"===e.event)try{this.heartbeatCallback("ok"===e.payload.status?"ok":"error")}catch(a){this.log("error","error in heartbeat callback",a)}e.ref&&e.ref===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null);const{topic:t,event:s,payload:r,ref:i}=e,n=i?`(${i})`:"",o=r.status||"";this.log("receive",`${o} ${t} ${s} ${n}`.trim(),r),this.channels.filter(e=>e._isMember(t)).forEach(e=>e._trigger(s,r,i)),this._triggerStateCallbacks("message",e)})}_clearTimer(e){var t;"heartbeat"===e&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):"reconnect"===e&&(null===(t=this.reconnectTimer)||void 0===t||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_teardownConnection(){this.conn&&(this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null),this._clearAllTimers(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log("worker","worker error",e.message),this.workerRef.terminate()},this.workerRef.onmessage=e=>{"keepAlive"===e.data.event&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||null===(t=this.reconnectTimer)||void 0===t||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e)}_triggerChanError(){this.channels.forEach(e=>e._trigger(Q.error))}_appendParams(e,t){if(0===Object.keys(t).length)return e;const s=e.match(/\?/)?"&":"?";return`${e}${s}${new URLSearchParams(t)}`}_workerObjectUrl(e){let t;if(e)t=e;else{const e=new Blob(['\n addEventListener("message", (e) => {\n if (e.data.event === "start") {\n setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);\n }\n });'],{type:"application/javascript"});t=URL.createObjectURL(e)}return t}_setConnectionState(e,t=!1){this._connectionState=e,"connecting"===e?this._wasManualDisconnect=!1:"disconnecting"===e&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t;t=e||(this.accessToken?await this.accessToken():this.accessTokenValue),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(e=>{const s={access_token:t,version:"realtime-js/2.15.5"};t&&e.updateJoinPayload(s),e.joinedOnce&&e._isJoined()&&e._push(Q.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this.setAuth().catch(t=>{this.log("error",`error setting auth in ${e}`,t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(s=>{try{s(t)}catch(r){this.log("error",`error in ${e} callback`,r)}})}catch(s){this.log("error",`error triggering ${e} callbacks`,s)}}_setupReconnectionTimer(){this.reconnectTimer=new ne(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},$e)},this.reconnectAfterMs)}_initializeOptions(e){var t,s,r,i,n,o,a,l,h;if(this.transport=null!==(t=null==e?void 0:e.transport)&&void 0!==t?t:null,this.timeout=null!==(s=null==e?void 0:e.timeout)&&void 0!==s?s:H,this.heartbeatIntervalMs=null!==(r=null==e?void 0:e.heartbeatIntervalMs)&&void 0!==r?r:Pe,this.worker=null!==(i=null==e?void 0:e.worker)&&void 0!==i&&i,this.accessToken=null!==(n=null==e?void 0:e.accessToken)&&void 0!==n?n:null,this.heartbeatCallback=null!==(o=null==e?void 0:e.heartbeatCallback)&&void 0!==o?o:Oe,(null==e?void 0:e.params)&&(this.params=e.params),(null==e?void 0:e.logger)&&(this.logger=e.logger),((null==e?void 0:e.logLevel)||(null==e?void 0:e.log_level))&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=null!==(a=null==e?void 0:e.reconnectAfterMs)&&void 0!==a?a:e=>Ae[e-1]||1e4,this.encode=null!==(l=null==e?void 0:e.encode)&&void 0!==l?l:(e,t)=>t(JSON.stringify(e)),this.decode=null!==(h=null==e?void 0:e.decode)&&void 0!==h?h:this.serializer.decode.bind(this.serializer),this.worker){if("undefined"!=typeof window&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=null==e?void 0:e.workerUrl}}}class Re extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function xe(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}class Ue extends Re{constructor(e,t,s){super(e),this.name="StorageApiError",this.status=t,this.statusCode=s}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class Le extends Re{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}var Ne=function(e,t,s,r){return new(s||(s=Promise))(function(i,n){function o(e){try{l(r.next(e))}catch(t){n(t)}}function a(e){try{l(r.throw(e))}catch(t){n(t)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(o,a)}l((r=r.apply(e,t||[])).next())})};const De=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>s(async()=>{const{default:e}=await Promise.resolve().then(()=>S);return{default:e}},void 0).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)},qe=e=>{if(Array.isArray(e))return e.map(e=>qe(e));if("function"==typeof e||e!==Object(e))return e;const t={};return Object.entries(e).forEach(([e,s])=>{const r=e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(/[-_]/g,""));t[r]=qe(s)}),t};var Be=function(e,t,s,r){return new(s||(s=Promise))(function(i,n){function o(e){try{l(r.next(e))}catch(t){n(t)}}function a(e){try{l(r.throw(e))}catch(t){n(t)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(o,a)}l((r=r.apply(e,t||[])).next())})};const We=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),Me=(e,t,r)=>Be(void 0,void 0,void 0,function*(){const i=yield Ne(void 0,void 0,void 0,function*(){return"undefined"==typeof Response?(yield s(()=>Promise.resolve().then(()=>S),void 0)).Response:Response});e instanceof i&&!(null==r?void 0:r.noResolveJson)?e.json().then(s=>{const r=e.status||500,i=(null==s?void 0:s.statusCode)||r+"";t(new Ue(We(s),r,i))}).catch(e=>{t(new Le(We(e),e))}):t(new Le(We(e),e))}),Fe=(e,t,s,r)=>{const i={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"!==e&&r?((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(r)?(i.headers=Object.assign({"Content-Type":"application/json"},null==t?void 0:t.headers),i.body=JSON.stringify(r)):i.body=r,(null==t?void 0:t.duplex)&&(i.duplex=t.duplex),Object.assign(Object.assign({},i),s)):i};function Ke(e,t,s,r,i,n){return Be(this,void 0,void 0,function*(){return new Promise((o,a)=>{e(s,Fe(t,r,i,n)).then(e=>{if(!e.ok)throw e;return(null==r?void 0:r.noResolveJson)?e:e.json()}).then(e=>o(e)).catch(e=>Me(e,a,r))})})}function ze(e,t,s,r){return Be(this,void 0,void 0,function*(){return Ke(e,"GET",t,s,r)})}function He(e,t,s,r,i){return Be(this,void 0,void 0,function*(){return Ke(e,"POST",t,r,i,s)})}function Je(e,t,s,r,i){return Be(this,void 0,void 0,function*(){return Ke(e,"PUT",t,r,i,s)})}function Ge(e,t,s,r,i){return Be(this,void 0,void 0,function*(){return Ke(e,"DELETE",t,r,i,s)})}var Ve=function(e,t,s,r){return new(s||(s=Promise))(function(i,n){function o(e){try{l(r.next(e))}catch(t){n(t)}}function a(e){try{l(r.throw(e))}catch(t){n(t)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(o,a)}l((r=r.apply(e,t||[])).next())})};class Ye{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}execute(){return Ve(this,void 0,void 0,function*(){try{return{data:(yield this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(xe(e))return{data:null,error:e};throw e}})}}var Qe=function(e,t,s,r){return new(s||(s=Promise))(function(i,n){function o(e){try{l(r.next(e))}catch(t){n(t)}}function a(e){try{l(r.throw(e))}catch(t){n(t)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(o,a)}l((r=r.apply(e,t||[])).next())})};class Xe{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}asStream(){return new Ye(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.execute().then(e,t)}execute(){return Qe(this,void 0,void 0,function*(){try{const e=yield this.downloadFn();return{data:yield e.blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(xe(e))return{data:null,error:e};throw e}})}}var Ze=function(e,t,s,r){return new(s||(s=Promise))(function(i,n){function o(e){try{l(r.next(e))}catch(t){n(t)}}function a(e){try{l(r.throw(e))}catch(t){n(t)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(o,a)}l((r=r.apply(e,t||[])).next())})};const et={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},tt={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class st{constructor(e,t={},s,r){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.bucketId=s,this.fetch=De(r)}throwOnError(){return this.shouldThrowOnError=!0,this}uploadOrUpdate(e,t,s,r){return Ze(this,void 0,void 0,function*(){try{let i;const n=Object.assign(Object.assign({},tt),r);let o=Object.assign(Object.assign({},this.headers),"POST"===e&&{"x-upsert":String(n.upsert)});const a=n.metadata;"undefined"!=typeof Blob&&s instanceof Blob?(i=new FormData,i.append("cacheControl",n.cacheControl),a&&i.append("metadata",this.encodeMetadata(a)),i.append("",s)):"undefined"!=typeof FormData&&s instanceof FormData?(i=s,i.append("cacheControl",n.cacheControl),a&&i.append("metadata",this.encodeMetadata(a))):(i=s,o["cache-control"]=`max-age=${n.cacheControl}`,o["content-type"]=n.contentType,a&&(o["x-metadata"]=this.toBase64(this.encodeMetadata(a)))),(null==r?void 0:r.headers)&&(o=Object.assign(Object.assign({},o),r.headers));const l=this._removeEmptyFolders(t),h=this._getFinalPath(l),c=yield("PUT"==e?Je:He)(this.fetch,`${this.url}/object/${h}`,i,Object.assign({headers:o},(null==n?void 0:n.duplex)?{duplex:n.duplex}:{}));return{data:{path:l,id:c.Id,fullPath:c.Key},error:null}}catch(i){if(this.shouldThrowOnError)throw i;if(xe(i))return{data:null,error:i};throw i}})}upload(e,t,s){return Ze(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,r){return Ze(this,void 0,void 0,function*(){const i=this._removeEmptyFolders(e),n=this._getFinalPath(i),o=new URL(this.url+`/object/upload/sign/${n}`);o.searchParams.set("token",t);try{let e;const t=Object.assign({upsert:tt.upsert},r),n=Object.assign(Object.assign({},this.headers),{"x-upsert":String(t.upsert)});"undefined"!=typeof Blob&&s instanceof Blob?(e=new FormData,e.append("cacheControl",t.cacheControl),e.append("",s)):"undefined"!=typeof FormData&&s instanceof FormData?(e=s,e.append("cacheControl",t.cacheControl)):(e=s,n["cache-control"]=`max-age=${t.cacheControl}`,n["content-type"]=t.contentType);return{data:{path:i,fullPath:(yield Je(this.fetch,o.toString(),e,{headers:n})).Key},error:null}}catch(a){if(this.shouldThrowOnError)throw a;if(xe(a))return{data:null,error:a};throw a}})}createSignedUploadUrl(e,t){return Ze(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e);const r=Object.assign({},this.headers);(null==t?void 0:t.upsert)&&(r["x-upsert"]="true");const i=yield He(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:r}),n=new URL(this.url+i.url),o=n.searchParams.get("token");if(!o)throw new Re("No token returned by API");return{data:{signedUrl:n.toString(),path:e,token:o},error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(xe(s))return{data:null,error:s};throw s}})}update(e,t,s){return Ze(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return Ze(this,void 0,void 0,function*(){try{return{data:yield He(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==s?void 0:s.destinationBucket},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(xe(r))return{data:null,error:r};throw r}})}copy(e,t,s){return Ze(this,void 0,void 0,function*(){try{return{data:{path:(yield He(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==s?void 0:s.destinationBucket},{headers:this.headers})).Key},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(xe(r))return{data:null,error:r};throw r}})}createSignedUrl(e,t,s){return Ze(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),i=yield He(this.fetch,`${this.url}/object/sign/${r}`,Object.assign({expiresIn:t},(null==s?void 0:s.transform)?{transform:s.transform}:{}),{headers:this.headers});const n=(null==s?void 0:s.download)?`&download=${!0===s.download?"":s.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${n}`)},{data:i,error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(xe(r))return{data:null,error:r};throw r}})}createSignedUrls(e,t,s){return Ze(this,void 0,void 0,function*(){try{const r=yield He(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=(null==s?void 0:s.download)?`&download=${!0===s.download?"":s.download}`:"";return{data:r.map(e=>Object.assign(Object.assign({},e),{signedUrl:e.signedURL?encodeURI(`${this.url}${e.signedURL}${i}`):null})),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(xe(r))return{data:null,error:r};throw r}})}download(e,t){const s=void 0!==(null==t?void 0:t.transform)?"render/image/authenticated":"object",r=this.transformOptsToQueryString((null==t?void 0:t.transform)||{}),i=r?`?${r}`:"",n=this._getFinalPath(e);return new Xe(()=>ze(this.fetch,`${this.url}/${s}/${n}${i}`,{headers:this.headers,noResolveJson:!0}),this.shouldThrowOnError)}info(e){return Ze(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{const e=yield ze(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:qe(e),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(xe(s))return{data:null,error:s};throw s}})}exists(e){return Ze(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{return yield function(e,t,s,r){return Be(this,void 0,void 0,function*(){return Ke(e,"HEAD",t,Object.assign(Object.assign({},s),{noResolveJson:!0}),r)})}(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(xe(s)&&s instanceof Le){const e=s.originalError;if([400,404].includes(null==e?void 0:e.status))return{data:!1,error:s}}throw s}})}getPublicUrl(e,t){const s=this._getFinalPath(e),r=[],i=(null==t?void 0:t.download)?`download=${!0===t.download?"":t.download}`:"";""!==i&&r.push(i);const n=void 0!==(null==t?void 0:t.transform)?"render/image":"object",o=this.transformOptsToQueryString((null==t?void 0:t.transform)||{});""!==o&&r.push(o);let a=r.join("&");return""!==a&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${n}/public/${s}${a}`)}}}remove(e){return Ze(this,void 0,void 0,function*(){try{return{data:yield Ge(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(xe(t))return{data:null,error:t};throw t}})}list(e,t,s){return Ze(this,void 0,void 0,function*(){try{const r=Object.assign(Object.assign(Object.assign({},et),t),{prefix:e||""});return{data:yield He(this.fetch,`${this.url}/object/list/${this.bucketId}`,r,{headers:this.headers},s),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(xe(r))return{data:null,error:r};throw r}})}listV2(e,t){return Ze(this,void 0,void 0,function*(){try{const s=Object.assign({},e);return{data:yield He(this.fetch,`${this.url}/object/list-v2/${this.bucketId}`,s,{headers:this.headers},t),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(xe(s))return{data:null,error:s};throw s}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return"undefined"!=typeof Buffer?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}}const rt={"X-Client-Info":"storage-js/2.12.2"};var it=function(e,t,s,r){return new(s||(s=Promise))(function(i,n){function o(e){try{l(r.next(e))}catch(t){n(t)}}function a(e){try{l(r.throw(e))}catch(t){n(t)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(o,a)}l((r=r.apply(e,t||[])).next())})};class nt{constructor(e,t={},s,r){this.shouldThrowOnError=!1;const i=new URL(e);if(null==r?void 0:r.useNewHostname){/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase."))}this.url=i.href,this.headers=Object.assign(Object.assign({},rt),t),this.fetch=De(s)}throwOnError(){return this.shouldThrowOnError=!0,this}listBuckets(){return it(this,void 0,void 0,function*(){try{return{data:yield ze(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(xe(e))return{data:null,error:e};throw e}})}getBucket(e){return it(this,void 0,void 0,function*(){try{return{data:yield ze(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(xe(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return it(this,void 0,void 0,function*(){try{return{data:yield He(this.fetch,`${this.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(xe(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return it(this,void 0,void 0,function*(){try{return{data:yield Je(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(xe(s))return{data:null,error:s};throw s}})}emptyBucket(e){return it(this,void 0,void 0,function*(){try{return{data:yield He(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(xe(t))return{data:null,error:t};throw t}})}deleteBucket(e){return it(this,void 0,void 0,function*(){try{return{data:yield Ge(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(xe(t))return{data:null,error:t};throw t}})}}class ot extends nt{constructor(e,t={},s,r){super(e,t,s,r)}from(e){return new st(this.url,this.headers,e,this.fetch)}}let at="";at="undefined"!=typeof Deno?"deno":"undefined"!=typeof document?"web":"undefined"!=typeof navigator&&"ReactNative"===navigator.product?"react-native":"node";const lt={headers:{"X-Client-Info":`supabase-js-${at}/2.58.0`}},ht={schema:"public"},ct={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},ut={};var dt=function(e,t,s,r){return new(s||(s=Promise))(function(i,n){function o(e){try{l(r.next(e))}catch(t){n(t)}}function a(e){try{l(r.throw(e))}catch(t){n(t)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(o,a)}l((r=r.apply(e,t||[])).next())})};const ft=(e,t,s)=>{const r=(e=>{let t;return t=e||("undefined"==typeof fetch?m:fetch),(...e)=>t(...e)})(s),i="undefined"==typeof Headers?_:Headers;return(s,n)=>dt(void 0,void 0,void 0,function*(){var o;const a=null!==(o=yield t())&&void 0!==o?o:e;let l=new i(null==n?void 0:n.headers);return l.has("apikey")||l.set("apikey",e),l.has("Authorization")||l.set("Authorization",`Bearer ${a}`),r(s,Object.assign(Object.assign({},n),{headers:l}))})};var pt=function(e,t,s,r){return new(s||(s=Promise))(function(i,n){function o(e){try{l(r.next(e))}catch(t){n(t)}}function a(e){try{l(r.throw(e))}catch(t){n(t)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(o,a)}l((r=r.apply(e,t||[])).next())})};const gt="2.72.0",wt=3e4,vt=9e4,yt={"X-Client-Info":`gotrue-js/${gt}`},mt="X-Supabase-Api-Version",_t={timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"},bt=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;class kt extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}}function St(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class Tt extends kt{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}}class Et extends kt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class jt extends kt{constructor(e,t,s,r){super(e,s,r),this.name=t,this.status=s}}class Ot extends jt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}class Pt extends jt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class $t extends jt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class It extends jt{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class At extends jt{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class Ct extends jt{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function Rt(e){return St(e)&&"AuthRetryableFetchError"===e.name}class xt extends jt{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}}class Ut extends jt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Lt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Nt=" \t\n\r=".split(""),Dt=(()=>{const e=new Array(128);for(let t=0;t=6;){const e=t.queue>>t.queuedBits-6&63;s(Lt[e]),t.queuedBits-=6}else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;s(Lt[e]),t.queuedBits-=6}}function Bt(e,t,s){const r=Dt[e];if(!(r>-1)){if(-2===r)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}for(t.queue=t.queue<<6|r,t.queuedBits+=6;t.queuedBits>=8;)s(t.queue>>t.queuedBits-8&255),t.queuedBits-=8}function Wt(e){const t=[],s=e=>{t.push(String.fromCodePoint(e))},r={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},n=e=>{!function(e,t,s){if(0===t.utf8seq){if(e<=127)return void s(e);for(let s=1;s<6;s+=1)if(!(e>>7-s&1)){t.utf8seq=s;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else{if(4!==t.utf8seq)throw new Error("Invalid UTF-8 sequence");t.codepoint=7&e}t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&s(t.codepoint)}}(e,r,s)};for(let o=0;o>6),void t(128|63&e);if(e<=65535)return t(224|e>>12),t(128|e>>6&63),void t(128|63&e);if(e<=1114111)return t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),void t(128|63&e);throw new Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}t(e)}function Ft(e){const t=[],s={queue:0,queuedBits:0},r=e=>{t.push(e)};for(let i=0;i55295&&r<=56319){const t=1024*(r-55296)&65535;r=65536+(e.charCodeAt(s+1)-56320&65535|t),s+=1}Mt(r,t)}}(e,e=>t.push(e)),new Uint8Array(t)}function zt(e){const t=[],s={queue:0,queuedBits:0},r=e=>{t.push(e)};return e.forEach(e=>qt(e,s,r)),qt(null,s,r),t.join("")}const Ht=()=>"undefined"!=typeof window&&"undefined"!=typeof document,Jt={tested:!1,writable:!1},Gt=()=>{if(!Ht())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(t){return!1}if(Jt.tested)return Jt.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),Jt.tested=!0,Jt.writable=!0}catch(t){Jt.tested=!0,Jt.writable=!1}return Jt.writable};const Vt=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>s(async()=>{const{default:e}=await Promise.resolve().then(()=>S);return{default:e}},void 0).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)},Yt=async(e,t,s)=>{await e.setItem(t,JSON.stringify(s))},Qt=async(e,t)=>{const s=await e.getItem(t);if(!s)return null;try{return JSON.parse(s)}catch(r){return s}},Xt=async(e,t)=>{await e.removeItem(t)};class Zt{constructor(){this.promise=new Zt.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function es(e){const t=e.split(".");if(3!==t.length)throw new Ut("Invalid JWT structure");for(let s=0;sString.fromCharCode(e)).join("")}(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function rs(e,t,s=!1){const r=function(){const e=new Uint32Array(56);if("undefined"==typeof crypto){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length;let s="";for(let r=0;r<56;r++)s+=e.charAt(Math.floor(Math.random()*t));return s}return crypto.getRandomValues(e),Array.from(e,ts).join("")}();let i=r;s&&(i+="/PASSWORD_RECOVERY"),await Yt(e,`${t}-code-verifier`,i);const n=await ss(r);return[n,r===n?"plain":"s256"]}Zt.promiseConstructor=Promise;const is=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;const ns=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function os(e){if(!ns.test(e))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function as(){return new Proxy({},{get:(e,t)=>{if("__isUserNotAvailableProxy"===t)return!0;if("symbol"==typeof t){const e=t.toString();if("Symbol(Symbol.toPrimitive)"===e||"Symbol(Symbol.toStringTag)"===e||"Symbol(util.inspect.custom)"===e)return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function ls(e){return JSON.parse(JSON.stringify(e))}const hs=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),cs=[502,503,504];async function us(e){var t,s;if(!("object"==typeof(s=e)&&null!==s&&"status"in s&&"ok"in s&&"json"in s&&"function"==typeof s.json))throw new Ct(hs(e),0);if(cs.includes(e.status))throw new Ct(hs(e),e.status);let r,i;try{r=await e.json()}catch(o){throw new Et(hs(o),o)}const n=function(e){const t=e.headers.get(mt);if(!t)return null;if(!t.match(is))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch(o){return null}}(e);if(n&&n.getTime()>=_t.timestamp&&"object"==typeof r&&r&&"string"==typeof r.code?i=r.code:"object"==typeof r&&r&&"string"==typeof r.error_code&&(i=r.error_code),i){if("weak_password"===i)throw new xt(hs(r),e.status,(null===(t=r.weak_password)||void 0===t?void 0:t.reasons)||[]);if("session_not_found"===i)throw new Ot}else if("object"==typeof r&&r&&"object"==typeof r.weak_password&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0))throw new xt(hs(r),e.status,r.weak_password.reasons);throw new Tt(hs(r),e.status||500,i)}async function ds(e,t,s,r){var i;const n=Object.assign({},null==r?void 0:r.headers);n[mt]||(n[mt]=_t.name),(null==r?void 0:r.jwt)&&(n.Authorization=`Bearer ${r.jwt}`);const o=null!==(i=null==r?void 0:r.query)&&void 0!==i?i:{};(null==r?void 0:r.redirectTo)&&(o.redirect_to=r.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await async function(e,t,s,r,i,n){const o=((e,t,s,r)=>{const i={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==t?void 0:t.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),s))})(t,r,i,n);let a;try{a=await e(s,Object.assign({},o))}catch(l){throw new Ct(hs(l),0)}a.ok||await us(a);if(null==r?void 0:r.noResolveJson)return a;try{return await a.json()}catch(l){await us(l)}}(e,t,s+a,{headers:n,noResolveJson:null==r?void 0:r.noResolveJson},{},null==r?void 0:r.body);return(null==r?void 0:r.xform)?null==r?void 0:r.xform(l):{data:Object.assign({},l),error:null}}function fs(e){var t;let s=null;var r;(function(e){return e.access_token&&e.refresh_token&&e.expires_in})(e)&&(s=Object.assign({},e),e.expires_at||(s.expires_at=(r=e.expires_in,Math.round(Date.now()/1e3)+r)));return{data:{session:s,user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function ps(e){const t=fs(e);return!t.error&&e.weak_password&&"object"==typeof e.weak_password&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&"string"==typeof e.weak_password.message&&e.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0)&&(t.data.weak_password=e.weak_password),t}function gs(e){var t;return{data:{user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function ws(e){return{data:e,error:null}}function vs(e){const{action_link:t,email_otp:s,hashed_token:r,redirect_to:i,verification_type:n}=e,o=function(e,t){var s={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(s[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i0&&(d.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),s=JSON.parse(e.split(";")[1].split("=")[1]);l[`${s}Page`]=t}),l.total=parseInt(u)),{data:Object.assign(Object.assign({},c),l),error:null}}catch(l){if(St(l))return{data:{users:[]},error:l};throw l}}async getUserById(e){os(e);try{return await ds(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:gs})}catch(t){if(St(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){os(e);try{return await ds(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:gs})}catch(s){if(St(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){os(e);try{return await ds(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:gs})}catch(s){if(St(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){os(e.userId);try{const{data:t,error:s}=await ds(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:s}}catch(t){if(St(t))return{data:null,error:t};throw t}}async _deleteFactor(e){os(e.userId),os(e.id);try{return{data:await ds(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(St(t))return{data:null,error:t};throw t}}}function bs(e={}){return{getItem:t=>e[t]||null,setItem:(t,s)=>{e[t]=s},removeItem:t=>{delete e[t]}}}const ks=!!(globalThis&&Gt()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"));class Ss extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class Ts extends Ss{}async function Es(e,t,s){const r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort()},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,0===t?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async r=>{if(!r){if(0===t)throw new Ts(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(ks)try{await globalThis.navigator.locks.query()}catch(i){}return await s()}try{return await s()}finally{}}))}function js(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw new Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function Os(e){const t=(new TextEncoder).encode(e);return"0x"+Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}!function(){if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){"undefined"!=typeof self&&(self.globalThis=self)}}();const Ps={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:yt,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function $s(e,t,s){return await s()}const Is={};class As{constructor(e){var t,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=As.nextInstanceID,As.nextInstanceID+=1,this.instanceID>0&&Ht();const r=Object.assign(Object.assign({},Ps),e);if(this.logDebugMessages=!!r.debug,"function"==typeof r.debug&&(this.logger=r.debug),this.persistSession=r.persistSession,this.storageKey=r.storageKey,this.autoRefreshToken=r.autoRefreshToken,this.admin=new _s({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=Vt(r.fetch),this.lock=r.lock||$s,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,this.hasCustomAuthorizationHeader=r.hasCustomAuthorizationHeader,r.lock?this.lock=r.lock:Ht()&&(null===(t=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===t?void 0:t.locks)?this.lock=Es:this.lock=$s,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?(r.storage?this.storage=r.storage:Gt()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=bs(this.memoryStorage)),r.userStorage&&(this.userStorage=r.userStorage)):(this.memoryStorage={},this.storage=bs(this.memoryStorage)),Ht()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){}null===(s=this.broadcastChannel)||void 0===s||s.addEventListener("message",async e=>{this._debug("received broadcast notification from other tab or client",e),await this._notifyAllSubscribers(e.data.event,e.data.session,!1)})}this.initialize()}get jwks(){var e,t;return null!==(t=null===(e=Is[this.storageKey])||void 0===e?void 0:e.jwks)&&void 0!==t?t:{keys:[]}}set jwks(e){Is[this.storageKey]=Object.assign(Object.assign({},Is[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return null!==(t=null===(e=Is[this.storageKey])||void 0===e?void 0:e.cachedAt)&&void 0!==t?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Is[this.storageKey]=Object.assign(Object.assign({},Is[this.storageKey]),{cachedAt:e})}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${gt}) ${(new Date).toISOString()}`,...e),this}async initialize(){return this.initializePromise||(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))()),await this.initializePromise}async _initialize(){var e;try{const t=function(e){const t={},s=new URL(e);if(s.hash&&"#"===s.hash[0])try{new URLSearchParams(s.hash.substring(1)).forEach((e,s)=>{t[s]=e})}catch(r){}return s.searchParams.forEach((e,s)=>{t[s]=e}),t}(window.location.href);let s="none";if(this._isImplicitGrantCallback(t)?s="implicit":await this._isPKCECallback(t)&&(s="pkce"),Ht()&&this.detectSessionInUrl&&"none"!==s){const{data:r,error:i}=await this._getSessionFromURL(t,s);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),function(e){return St(e)&&"AuthImplicitGrantRedirectError"===e.name}(i)){const t=null===(e=i.details)||void 0===e?void 0:e.code;if("identity_already_exists"===t||"identity_not_found"===t||"single_identity_not_deletable"===t)return{error:i}}return await this._removeSession(),{error:i}}const{session:n,redirectType:o}=r;return this._debug("#_initialize()","detected session in URL",n,"redirect type",o),await this._saveSession(n),setTimeout(async()=>{"recovery"===o?await this._notifyAllSubscribers("PASSWORD_RECOVERY",n):await this._notifyAllSubscribers("SIGNED_IN",n)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return St(t)?{error:t}:{error:new Et("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,r;try{const i=await ds(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:null!==(s=null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.data)&&void 0!==s?s:{},gotrue_meta_security:{captcha_token:null===(r=null==e?void 0:e.options)||void 0===r?void 0:r.captchaToken}},xform:fs}),{data:n,error:o}=i;if(o||!n)return{data:{user:null,session:null},error:o};const a=n.session,l=n.user;return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",a)),{data:{user:l,session:a},error:null}}catch(i){if(St(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(e){var t,s,r;try{let i;if("email"in e){const{email:s,password:r,options:n}=e;let o=null,a=null;"pkce"===this.flowType&&([o,a]=await rs(this.storage,this.storageKey)),i=await ds(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:null==n?void 0:n.emailRedirectTo,body:{email:s,password:r,data:null!==(t=null==n?void 0:n.data)&&void 0!==t?t:{},gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken},code_challenge:o,code_challenge_method:a},xform:fs})}else{if(!("phone"in e))throw new $t("You must provide either an email or phone number and a password");{const{phone:t,password:n,options:o}=e;i=await ds(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:n,data:null!==(s=null==o?void 0:o.data)&&void 0!==s?s:{},channel:null!==(r=null==o?void 0:o.channel)&&void 0!==r?r:"sms",gotrue_meta_security:{captcha_token:null==o?void 0:o.captchaToken}},xform:fs})}}const{data:n,error:o}=i;if(o||!n)return{data:{user:null,session:null},error:o};const a=n.session,l=n.user;return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",a)),{data:{user:l,session:a},error:null}}catch(i){if(St(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithPassword(e){try{let t;if("email"in e){const{email:s,password:r,options:i}=e;t=await ds(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:ps})}else{if(!("phone"in e))throw new $t("You must provide either an email or phone number and a password");{const{phone:s,password:r,options:i}=e;t=await ds(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:ps})}}const{data:s,error:r}=t;return r?{data:{user:null,session:null},error:r}:s&&s.session&&s.user?(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:r}):{data:{user:null,session:null},error:new Pt}}catch(t){if(St(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,s,r,i;return await this._handleProviderSignIn(e.provider,{redirectTo:null===(t=e.options)||void 0===t?void 0:t.redirectTo,scopes:null===(s=e.options)||void 0===s?void 0:s.scopes,queryParams:null===(r=e.options)||void 0===r?void 0:r.queryParams,skipBrowserRedirect:null===(i=e.options)||void 0===i?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,s,r,i,n,o,a,l,h,c,u;let d,f;if("message"in e)d=e.message,f=e.signature;else{const{chain:c,wallet:u,statement:p,options:g}=e;let w;if(Ht())if("object"==typeof u)w=u;else{const e=window;if(!("ethereum"in e)||"object"!=typeof e.ethereum||!("request"in e.ethereum)||"function"!=typeof e.ethereum.request)throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.");w=e.ethereum}else{if("object"!=typeof u||!(null==g?void 0:g.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");w=u}const v=new URL(null!==(t=null==g?void 0:g.url)&&void 0!==t?t:window.location.href),y=await w.request({method:"eth_requestAccounts"}).then(e=>e).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!y||0===y.length)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const m=js(y[0]);let _=null===(s=null==g?void 0:g.signInWithEthereum)||void 0===s?void 0:s.chainId;if(!_){const e=await w.request({method:"eth_chainId"});_=parseInt(e,16)}d=function(e){var t;const{chainId:s,domain:r,expirationTime:i,issuedAt:n=new Date,nonce:o,notBefore:a,requestId:l,resources:h,scheme:c,uri:u,version:d}=e;if(!Number.isInteger(s))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${s}`);if(!r)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!u)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if("1"!==d)throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${d}`);if(null===(t=e.statement)||void 0===t?void 0:t.includes("\n"))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);const f=`${c?`${c}://${r}`:r} wants you to sign in with your Ethereum account:\n${js(e.address)}\n\n${e.statement?`${e.statement}\n`:""}`;let p=`URI: ${u}\nVersion: ${d}\nChain ID: ${s}${o?`\nNonce: ${o}`:""}\nIssued At: ${n.toISOString()}`;if(i&&(p+=`\nExpiration Time: ${i.toISOString()}`),a&&(p+=`\nNot Before: ${a.toISOString()}`),l&&(p+=`\nRequest ID: ${l}`),h){let e="\nResources:";for(const t of h){if(!t||"string"!=typeof t)throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${t}`);e+=`\n- ${t}`}p+=e}return`${f}\n${p}`}({domain:v.host,address:m,statement:p,uri:v.href,version:"1",chainId:_,nonce:null===(r=null==g?void 0:g.signInWithEthereum)||void 0===r?void 0:r.nonce,issuedAt:null!==(n=null===(i=null==g?void 0:g.signInWithEthereum)||void 0===i?void 0:i.issuedAt)&&void 0!==n?n:new Date,expirationTime:null===(o=null==g?void 0:g.signInWithEthereum)||void 0===o?void 0:o.expirationTime,notBefore:null===(a=null==g?void 0:g.signInWithEthereum)||void 0===a?void 0:a.notBefore,requestId:null===(l=null==g?void 0:g.signInWithEthereum)||void 0===l?void 0:l.requestId,resources:null===(h=null==g?void 0:g.signInWithEthereum)||void 0===h?void 0:h.resources}),f=await w.request({method:"personal_sign",params:[Os(d),m]})}try{const{data:t,error:s}=await ds(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:d,signature:f},(null===(c=e.options)||void 0===c?void 0:c.captchaToken)?{gotrue_meta_security:{captcha_token:null===(u=e.options)||void 0===u?void 0:u.captchaToken}}:null),xform:fs});if(s)throw s;return t&&t.session&&t.user?(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),{data:Object.assign({},t),error:s}):{data:{user:null,session:null},error:new Pt}}catch(p){if(St(p))return{data:{user:null,session:null},error:p};throw p}}async signInWithSolana(e){var t,s,r,i,n,o,a,l,h,c,u,d;let f,p;if("message"in e)f=e.message,p=e.signature;else{const{chain:u,wallet:d,statement:g,options:w}=e;let v;if(Ht())if("object"==typeof d)v=d;else{const e=window;if(!("solana"in e)||"object"!=typeof e.solana||!("signIn"in e.solana&&"function"==typeof e.solana.signIn||"signMessage"in e.solana&&"function"==typeof e.solana.signMessage))throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.");v=e.solana}else{if("object"!=typeof d||!(null==w?void 0:w.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");v=d}const y=new URL(null!==(t=null==w?void 0:w.url)&&void 0!==t?t:window.location.href);if("signIn"in v&&v.signIn){const e=await v.signIn(Object.assign(Object.assign(Object.assign({issuedAt:(new Date).toISOString()},null==w?void 0:w.signInWithSolana),{version:"1",domain:y.host,uri:y.href}),g?{statement:g}:null));let t;if(Array.isArray(e)&&e[0]&&"object"==typeof e[0])t=e[0];else{if(!(e&&"object"==typeof e&&"signedMessage"in e&&"signature"in e))throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");t=e}if(!("signedMessage"in t&&"signature"in t&&("string"==typeof t.signedMessage||t.signedMessage instanceof Uint8Array)&&t.signature instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields");f="string"==typeof t.signedMessage?t.signedMessage:(new TextDecoder).decode(t.signedMessage),p=t.signature}else{if(!("signMessage"in v&&"function"==typeof v.signMessage&&"publicKey"in v&&"object"==typeof v&&v.publicKey&&"toBase58"in v.publicKey&&"function"==typeof v.publicKey.toBase58))throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");f=[`${y.host} wants you to sign in with your Solana account:`,v.publicKey.toBase58(),...g?["",g,""]:[""],"Version: 1",`URI: ${y.href}`,`Issued At: ${null!==(r=null===(s=null==w?void 0:w.signInWithSolana)||void 0===s?void 0:s.issuedAt)&&void 0!==r?r:(new Date).toISOString()}`,...(null===(i=null==w?void 0:w.signInWithSolana)||void 0===i?void 0:i.notBefore)?[`Not Before: ${w.signInWithSolana.notBefore}`]:[],...(null===(n=null==w?void 0:w.signInWithSolana)||void 0===n?void 0:n.expirationTime)?[`Expiration Time: ${w.signInWithSolana.expirationTime}`]:[],...(null===(o=null==w?void 0:w.signInWithSolana)||void 0===o?void 0:o.chainId)?[`Chain ID: ${w.signInWithSolana.chainId}`]:[],...(null===(a=null==w?void 0:w.signInWithSolana)||void 0===a?void 0:a.nonce)?[`Nonce: ${w.signInWithSolana.nonce}`]:[],...(null===(l=null==w?void 0:w.signInWithSolana)||void 0===l?void 0:l.requestId)?[`Request ID: ${w.signInWithSolana.requestId}`]:[],...(null===(c=null===(h=null==w?void 0:w.signInWithSolana)||void 0===h?void 0:h.resources)||void 0===c?void 0:c.length)?["Resources",...w.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join("\n");const e=await v.signMessage((new TextEncoder).encode(f),"utf8");if(!(e&&e instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");p=e}}try{const{data:t,error:s}=await ds(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:f,signature:zt(p)},(null===(u=e.options)||void 0===u?void 0:u.captchaToken)?{gotrue_meta_security:{captcha_token:null===(d=e.options)||void 0===d?void 0:d.captchaToken}}:null),xform:fs});if(s)throw s;return t&&t.session&&t.user?(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),{data:Object.assign({},t),error:s}):{data:{user:null,session:null},error:new Pt}}catch(g){if(St(g))return{data:{user:null,session:null},error:g};throw g}}async _exchangeCodeForSession(e){const t=await Qt(this.storage,`${this.storageKey}-code-verifier`),[s,r]=(null!=t?t:"").split("/");try{const{data:t,error:i}=await ds(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:fs});if(await Xt(this.storage,`${this.storageKey}-code-verifier`),i)throw i;return t&&t.session&&t.user?(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),{data:Object.assign(Object.assign({},t),{redirectType:null!=r?r:null}),error:i}):{data:{user:null,session:null,redirectType:null},error:new Pt}}catch(i){if(St(i))return{data:{user:null,session:null,redirectType:null},error:i};throw i}}async signInWithIdToken(e){try{const{options:t,provider:s,token:r,access_token:i,nonce:n}=e,o=await ds(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:r,access_token:i,nonce:n,gotrue_meta_security:{captcha_token:null==t?void 0:t.captchaToken}},xform:fs}),{data:a,error:l}=o;return l?{data:{user:null,session:null},error:l}:a&&a.session&&a.user?(a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),{data:a,error:l}):{data:{user:null,session:null},error:new Pt}}catch(t){if(St(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,r,i,n;try{if("email"in e){const{email:r,options:i}=e;let n=null,o=null;"pkce"===this.flowType&&([n,o]=await rs(this.storage,this.storageKey));const{error:a}=await ds(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:r,data:null!==(t=null==i?void 0:i.data)&&void 0!==t?t:{},create_user:null===(s=null==i?void 0:i.shouldCreateUser)||void 0===s||s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:n,code_challenge_method:o},redirectTo:null==i?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:a}}if("phone"in e){const{phone:t,options:s}=e,{data:o,error:a}=await ds(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:null!==(r=null==s?void 0:s.data)&&void 0!==r?r:{},create_user:null===(i=null==s?void 0:s.shouldCreateUser)||void 0===i||i,gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken},channel:null!==(n=null==s?void 0:s.channel)&&void 0!==n?n:"sms"}});return{data:{user:null,session:null,messageId:null==o?void 0:o.message_id},error:a}}throw new $t("You must provide either an email or phone number.")}catch(o){if(St(o))return{data:{user:null,session:null},error:o};throw o}}async verifyOtp(e){var t,s;try{let r,i;"options"in e&&(r=null===(t=e.options)||void 0===t?void 0:t.redirectTo,i=null===(s=e.options)||void 0===s?void 0:s.captchaToken);const{data:n,error:o}=await ds(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:r,xform:fs});if(o)throw o;if(!n)throw new Error("An error occurred on token verification.");const a=n.session,l=n.user;return(null==a?void 0:a.access_token)&&(await this._saveSession(a),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",a)),{data:{user:l,session:a},error:null}}catch(r){if(St(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithSSO(e){var t,s,r;try{let i=null,n=null;return"pkce"===this.flowType&&([i,n]=await rs(this.storage,this.storageKey)),await ds(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:null!==(s=null===(t=e.options)||void 0===t?void 0:t.redirectTo)&&void 0!==s?s:void 0}),(null===(r=null==e?void 0:e.options)||void 0===r?void 0:r.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:i,code_challenge_method:n}),headers:this.headers,xform:ws})}catch(i){if(St(i))return{data:null,error:i};throw i}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new Ot;const{error:r}=await ds(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:r}})}catch(e){if(St(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{const t=`${this.url}/resend`;if("email"in e){const{email:s,type:r,options:i}=e,{error:n}=await ds(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},redirectTo:null==i?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:n}}if("phone"in e){const{phone:s,type:r,options:i}=e,{data:n,error:o}=await ds(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}}});return{data:{user:null,session:null,messageId:null==n?void 0:n.message_id},error:o}}throw new $t("You must provide either an email or phone number and a type")}catch(t){if(St(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){await this.initializePromise;return await this._acquireLock(-1,async()=>this._useSession(async e=>e))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch(e){}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(t){}})()),await e;this.pendingInLock.length;){const e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",(new Error).stack);try{let e=null;const t=await Qt(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),null!==t&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const s=!!e.expires_at&&1e3*e.expires_at-Date.now()(t||"user"!==s||(t=!0,this.suppressGetSessionWarning=!0),Reflect.get(e,s,r))})}return{data:{session:e},error:null}}const{session:r,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{session:null},error:i}:{data:{session:r},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;return await this._acquireLock(-1,async()=>await this._getUser())}async _getUser(e){try{return e?await ds(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:gs}):await this._useSession(async e=>{var t,s,r;const{data:i,error:n}=e;if(n)throw n;return(null===(t=i.session)||void 0===t?void 0:t.access_token)||this.hasCustomAuthorizationHeader?await ds(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!==(r=null===(s=i.session)||void 0===s?void 0:s.access_token)&&void 0!==r?r:void 0,xform:gs}):{data:{user:null},error:new Ot}})}catch(t){if(St(t))return function(e){return St(e)&&"AuthSessionMissingError"===e.name}(t)&&(await this._removeSession(),await Xt(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{const{data:r,error:i}=s;if(i)throw i;if(!r.session)throw new Ot;const n=r.session;let o=null,a=null;"pkce"===this.flowType&&null!=e.email&&([o,a]=await rs(this.storage,this.storageKey));const{data:l,error:h}=await ds(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:a}),jwt:n.access_token,xform:gs});if(h)throw h;return n.user=l.user,await this._saveSession(n),await this._notifyAllSubscribers("USER_UPDATED",n),{data:{user:n.user},error:null}})}catch(s){if(St(s))return{data:{user:null},error:s};throw s}}async setSession(