import{_ as w,t as cr,s as Ae}from"./vendor-ui-Di8ht53r.js";import{j as ur}from"./vendor-react-CQmvUQ48.js";function hr(n,e){for(var t=0;t<e.length;t++){const r=e[t];if(typeof r!="string"&&!Array.isArray(r)){for(const s in r)if(s!=="default"&&!(s in n)){const i=Object.getOwnPropertyDescriptor(r,s);i&&Object.defineProperty(n,s,i.get?i:{enumerable:!0,get:()=>r[s]})}}}return Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}const dr=n=>n?(...e)=>n(...e):(...e)=>fetch(...e);class Ge extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}}class fr extends Ge{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class st extends Ge{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class it extends Ge{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var De;(function(n){n.Any="any",n.ApNortheast1="ap-northeast-1",n.ApNortheast2="ap-northeast-2",n.ApSouth1="ap-south-1",n.ApSoutheast1="ap-southeast-1",n.ApSoutheast2="ap-southeast-2",n.CaCentral1="ca-central-1",n.EuCentral1="eu-central-1",n.EuWest1="eu-west-1",n.EuWest2="eu-west-2",n.EuWest3="eu-west-3",n.SaEast1="sa-east-1",n.UsEast1="us-east-1",n.UsWest1="us-west-1",n.UsWest2="us-west-2"})(De||(De={}));class gr{constructor(e,{headers:t={},customFetch:r,region:s=De.Any}={}){this.url=e,this.headers=t,this.region=s,this.fetch=dr(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return w(this,arguments,void 0,function*(t,r={}){var s;let i,o;try{const{headers:a,method:l,body:c,signal:u,timeout:d}=r;let h={},{region:f}=r;f||(f=this.region);const g=new URL(`${this.url}/${t}`);f&&f!=="any"&&(h["x-region"]=f,g.searchParams.set("forceFunctionRegion",f));let v;c&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&c instanceof Blob||c instanceof ArrayBuffer?(h["Content-Type"]="application/octet-stream",v=c):typeof c=="string"?(h["Content-Type"]="text/plain",v=c):typeof FormData<"u"&&c instanceof FormData?v=c:(h["Content-Type"]="application/json",v=JSON.stringify(c)):v=c;let p=u;d&&(o=new AbortController,i=setTimeout(()=>o.abort(),d),u?(p=o.signal,u.addEventListener("abort",()=>o.abort())):p=o.signal);const E=yield this.fetch(g.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},h),this.headers),a),body:v,signal:p}).catch(A=>{throw new fr(A)}),b=E.headers.get("x-relay-error");if(b&&b==="true")throw new st(E);if(!E.ok)throw new it(E);let _=((s=E.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),S;return _==="application/json"?S=yield E.json():_==="application/octet-stream"||_==="application/pdf"?S=yield E.blob():_==="text/event-stream"?S=E:_==="multipart/form-data"?S=yield E.formData():S=yield E.text(),{data:S,error:null,response:E}}catch(a){return{data:null,error:a,response:a instanceof it||a instanceof st?a.context:void 0}}finally{i&&clearTimeout(i)}})}}var I={};const oe=ur(cr);var pe={},_e={},ve={},we={},ye={},be={},nt;function jt(){if(nt)return be;nt=1,Object.defineProperty(be,"__esModule",{value:!0});class n extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}}return be.default=n,be}var ot;function Ct(){if(ot)return ye;ot=1,Object.defineProperty(ye,"__esModule",{value:!0});const e=oe.__importDefault(jt());class t{constructor(s){var i,o;this.shouldThrowOnError=!1,this.method=s.method,this.url=s.url,this.headers=new Headers(s.headers),this.schema=s.schema,this.body=s.body,this.shouldThrowOnError=(i=s.shouldThrowOnError)!==null&&i!==void 0?i:!1,this.signal=s.signal,this.isMaybeSingle=(o=s.isMaybeSingle)!==null&&o!==void 0?o:!1,s.fetch?this.fetch=s.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(s,i){return this.headers=new Headers(this.headers),this.headers.set(s,i),this}then(s,i){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");const o=this.fetch;let a=o(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async l=>{var c,u,d,h;let f=null,g=null,v=null,p=l.status,E=l.statusText;if(l.ok){if(this.method!=="HEAD"){const A=await l.text();A===""||(this.headers.get("Accept")==="text/csv"||this.headers.get("Accept")&&(!((c=this.headers.get("Accept"))===null||c===void 0)&&c.includes("application/vnd.pgrst.plan+text"))?g=A:g=JSON.parse(A))}const _=(u=this.headers.get("Prefer"))===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),S=(d=l.headers.get("content-range"))===null||d===void 0?void 0:d.split("/");_&&S&&S.length>1&&(v=parseInt(S[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(g)&&(g.length>1?(f={code:"PGRST116",details:`Results contain ${g.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},g=null,v=null,p=406,E="Not Acceptable"):g.length===1?g=g[0]:g=null)}else{const _=await l.text();try{f=JSON.parse(_),Array.isArray(f)&&l.status===404&&(g=[],f=null,p=200,E="OK")}catch{l.status===404&&_===""?(p=204,E="No Content"):f={message:_}}if(f&&this.isMaybeSingle&&(!((h=f?.details)===null||h===void 0)&&h.includes("0 rows"))&&(f=null,p=200,E="OK"),f&&this.shouldThrowOnError)throw new e.default(f)}return{error:f,data:g,count:v,status:p,statusText:E}});return this.shouldThrowOnError||(a=a.catch(l=>{var c,u,d;return{error:{message:`${(c=l?.name)!==null&&c!==void 0?c:"FetchError"}: ${l?.message}`,details:`${(u=l?.stack)!==null&&u!==void 0?u:""}`,hint:"",code:`${(d=l?.code)!==null&&d!==void 0?d:""}`},data:null,count:null,status:0,statusText:""}})),a.then(s,i)}returns(){return this}overrideTypes(){return this}}return ye.default=t,ye}var at;function It(){if(at)return we;at=1,Object.defineProperty(we,"__esModule",{value:!0});const e=oe.__importDefault(Ct());class t extends e.default{select(s){let i=!1;const o=(s??"*").split("").map(a=>/\s/.test(a)&&!i?"":(a==='"'&&(i=!i),a)).join("");return this.url.searchParams.set("select",o),this.headers.append("Prefer","return=representation"),this}order(s,{ascending:i=!0,nullsFirst:o,foreignTable:a,referencedTable:l=a}={}){const c=l?`${l}.order`:"order",u=this.url.searchParams.get(c);return this.url.searchParams.set(c,`${u?`${u},`:""}${s}.${i?"asc":"desc"}${o===void 0?"":o?".nullsfirst":".nullslast"}`),this}limit(s,{foreignTable:i,referencedTable:o=i}={}){const a=typeof o>"u"?"limit":`${o}.limit`;return this.url.searchParams.set(a,`${s}`),this}range(s,i,{foreignTable:o,referencedTable:a=o}={}){const l=typeof a>"u"?"offset":`${a}.offset`,c=typeof a>"u"?"limit":`${a}.limit`;return this.url.searchParams.set(l,`${s}`),this.url.searchParams.set(c,`${i-s+1}`),this}abortSignal(s){return this.signal=s,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:s=!1,verbose:i=!1,settings:o=!1,buffers:a=!1,wal:l=!1,format:c="text"}={}){var u;const d=[s?"analyze":null,i?"verbose":null,o?"settings":null,a?"buffers":null,l?"wal":null].filter(Boolean).join("|"),h=(u=this.headers.get("Accept"))!==null&&u!==void 0?u:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${c}; for="${h}"; options=${d};`),c==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(s){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${s}`),this}}return we.default=t,we}var lt;function Ye(){if(lt)return ve;lt=1,Object.defineProperty(ve,"__esModule",{value:!0});const e=oe.__importDefault(It()),t=new RegExp("[,()]");class r extends e.default{eq(i,o){return this.url.searchParams.append(i,`eq.${o}`),this}neq(i,o){return this.url.searchParams.append(i,`neq.${o}`),this}gt(i,o){return this.url.searchParams.append(i,`gt.${o}`),this}gte(i,o){return this.url.searchParams.append(i,`gte.${o}`),this}lt(i,o){return this.url.searchParams.append(i,`lt.${o}`),this}lte(i,o){return this.url.searchParams.append(i,`lte.${o}`),this}like(i,o){return this.url.searchParams.append(i,`like.${o}`),this}likeAllOf(i,o){return this.url.searchParams.append(i,`like(all).{${o.join(",")}}`),this}likeAnyOf(i,o){return this.url.searchParams.append(i,`like(any).{${o.join(",")}}`),this}ilike(i,o){return this.url.searchParams.append(i,`ilike.${o}`),this}ilikeAllOf(i,o){return this.url.searchParams.append(i,`ilike(all).{${o.join(",")}}`),this}ilikeAnyOf(i,o){return this.url.searchParams.append(i,`ilike(any).{${o.join(",")}}`),this}is(i,o){return this.url.searchParams.append(i,`is.${o}`),this}in(i,o){const a=Array.from(new Set(o)).map(l=>typeof l=="string"&&t.test(l)?`"${l}"`:`${l}`).join(",");return this.url.searchParams.append(i,`in.(${a})`),this}contains(i,o){return typeof o=="string"?this.url.searchParams.append(i,`cs.${o}`):Array.isArray(o)?this.url.searchParams.append(i,`cs.{${o.join(",")}}`):this.url.searchParams.append(i,`cs.${JSON.stringify(o)}`),this}containedBy(i,o){return typeof o=="string"?this.url.searchParams.append(i,`cd.${o}`):Array.isArray(o)?this.url.searchParams.append(i,`cd.{${o.join(",")}}`):this.url.searchParams.append(i,`cd.${JSON.stringify(o)}`),this}rangeGt(i,o){return this.url.searchParams.append(i,`sr.${o}`),this}rangeGte(i,o){return this.url.searchParams.append(i,`nxl.${o}`),this}rangeLt(i,o){return this.url.searchParams.append(i,`sl.${o}`),this}rangeLte(i,o){return this.url.searchParams.append(i,`nxr.${o}`),this}rangeAdjacent(i,o){return this.url.searchParams.append(i,`adj.${o}`),this}overlaps(i,o){return typeof o=="string"?this.url.searchParams.append(i,`ov.${o}`):this.url.searchParams.append(i,`ov.{${o.join(",")}}`),this}textSearch(i,o,{config:a,type:l}={}){let c="";l==="plain"?c="pl":l==="phrase"?c="ph":l==="websearch"&&(c="w");const u=a===void 0?"":`(${a})`;return this.url.searchParams.append(i,`${c}fts${u}.${o}`),this}match(i){return Object.entries(i).forEach(([o,a])=>{this.url.searchParams.append(o,`eq.${a}`)}),this}not(i,o,a){return this.url.searchParams.append(i,`not.${o}.${a}`),this}or(i,{foreignTable:o,referencedTable:a=o}={}){const l=a?`${a}.or`:"or";return this.url.searchParams.append(l,`(${i})`),this}filter(i,o,a){return this.url.searchParams.append(i,`${o}.${a}`),this}}return ve.default=r,ve}var ct;function $t(){if(ct)return _e;ct=1,Object.defineProperty(_e,"__esModule",{value:!0});const e=oe.__importDefault(Ye());class t{constructor(s,{headers:i={},schema:o,fetch:a}){this.url=s,this.headers=new Headers(i),this.schema=o,this.fetch=a}select(s,i){const{head:o=!1,count:a}=i??{},l=o?"HEAD":"GET";let c=!1;const u=(s??"*").split("").map(d=>/\s/.test(d)&&!c?"":(d==='"'&&(c=!c),d)).join("");return this.url.searchParams.set("select",u),a&&this.headers.append("Prefer",`count=${a}`),new e.default({method:l,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(s,{count:i,defaultToNull:o=!0}={}){var a;const l="POST";if(i&&this.headers.append("Prefer",`count=${i}`),o||this.headers.append("Prefer","missing=default"),Array.isArray(s)){const c=s.reduce((u,d)=>u.concat(Object.keys(d)),[]);if(c.length>0){const u=[...new Set(c)].map(d=>`"${d}"`);this.url.searchParams.set("columns",u.join(","))}}return new e.default({method:l,url:this.url,headers:this.headers,schema:this.schema,body:s,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch})}upsert(s,{onConflict:i,ignoreDuplicates:o=!1,count:a,defaultToNull:l=!0}={}){var c;const u="POST";if(this.headers.append("Prefer",`resolution=${o?"ignore":"merge"}-duplicates`),i!==void 0&&this.url.searchParams.set("on_conflict",i),a&&this.headers.append("Prefer",`count=${a}`),l||this.headers.append("Prefer","missing=default"),Array.isArray(s)){const d=s.reduce((h,f)=>h.concat(Object.keys(f)),[]);if(d.length>0){const h=[...new Set(d)].map(f=>`"${f}"`);this.url.searchParams.set("columns",h.join(","))}}return new e.default({method:u,url:this.url,headers:this.headers,schema:this.schema,body:s,fetch:(c=this.fetch)!==null&&c!==void 0?c:fetch})}update(s,{count:i}={}){var o;const a="PATCH";return i&&this.headers.append("Prefer",`count=${i}`),new e.default({method:a,url:this.url,headers:this.headers,schema:this.schema,body:s,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch})}delete({count:s}={}){var i;const o="DELETE";return s&&this.headers.append("Prefer",`count=${s}`),new e.default({method:o,url:this.url,headers:this.headers,schema:this.schema,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch})}}return _e.default=t,_e}var ut;function pr(){if(ut)return pe;ut=1,Object.defineProperty(pe,"__esModule",{value:!0});const n=oe,e=n.__importDefault($t()),t=n.__importDefault(Ye());class r{constructor(i,{headers:o={},schema:a,fetch:l}={}){this.url=i,this.headers=new Headers(o),this.schemaName=a,this.fetch=l}from(i){const o=new URL(`${this.url}/${i}`);return new e.default(o,{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(i){return new r(this.url,{headers:this.headers,schema:i,fetch:this.fetch})}rpc(i,o={},{head:a=!1,get:l=!1,count:c}={}){var u;let d;const h=new URL(`${this.url}/rpc/${i}`);let f;a||l?(d=a?"HEAD":"GET",Object.entries(o).filter(([v,p])=>p!==void 0).map(([v,p])=>[v,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([v,p])=>{h.searchParams.append(v,p)})):(d="POST",f=o);const g=new Headers(this.headers);return c&&g.set("Prefer",`count=${c}`),new t.default({method:d,url:h,headers:g,schema:this.schemaName,body:f,fetch:(u=this.fetch)!==null&&u!==void 0?u:fetch})}}return pe.default=r,pe}Object.defineProperty(I,"__esModule",{value:!0});var Ut=I.PostgrestError=Vt=I.PostgrestBuilder=Wt=I.PostgrestTransformBuilder=qt=I.PostgrestFilterBuilder=Dt=I.PostgrestQueryBuilder=Nt=I.PostgrestClient=void 0;const ae=oe,xt=ae.__importDefault(pr());var Nt=I.PostgrestClient=xt.default;const Lt=ae.__importDefault($t());var Dt=I.PostgrestQueryBuilder=Lt.default;const Bt=ae.__importDefault(Ye());var qt=I.PostgrestFilterBuilder=Bt.default;const Mt=ae.__importDefault(It());var Wt=I.PostgrestTransformBuilder=Mt.default;const Ft=ae.__importDefault(Ct());var Vt=I.PostgrestBuilder=Ft.default;const Kt=ae.__importDefault(jt());Ut=I.PostgrestError=Kt.default;var Ht=I.default={PostgrestClient:xt.default,PostgrestQueryBuilder:Lt.default,PostgrestFilterBuilder:Bt.default,PostgrestTransformBuilder:Mt.default,PostgrestBuilder:Ft.default,PostgrestError:Kt.default};const _r=hr({__proto__:null,get PostgrestBuilder(){return Vt},get PostgrestClient(){return Nt},get PostgrestError(){return Ut},get PostgrestFilterBuilder(){return qt},get PostgrestQueryBuilder(){return Dt},get PostgrestTransformBuilder(){return Wt},default:Ht},[I]),{PostgrestClient:vr,PostgrestQueryBuilder:Ci,PostgrestFilterBuilder:Ii,PostgrestTransformBuilder:$i,PostgrestBuilder:Ui,PostgrestError:xi}=Ht||_r;class wr{static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};if(typeof process<"u"){const t=process.versions;if(t&&t.node){const r=t.node,s=parseInt(r.replace(/^v/,"").split(".")[0]);return s>=22?typeof globalThis.WebSocket<"u"?{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:
import ws from "ws"
new 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+=`

Suggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){const r=this.getWebSocketConstructor();return new r(e,t)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}}const yr="2.81.1",br=`realtime-js/${yr}`,Jt="1.0.0",mr="2.0.0",ht=Jt,Be=1e4,Er=1e3,Sr=100;var z;(function(n){n[n.connecting=0]="connecting",n[n.open=1]="open",n[n.closing=2]="closing",n[n.closed=3]="closed"})(z||(z={}));var j;(function(n){n.closed="closed",n.errored="errored",n.joined="joined",n.joining="joining",n.leaving="leaving"})(j||(j={}));var x;(function(n){n.close="phx_close",n.error="phx_error",n.join="phx_join",n.reply="phx_reply",n.leave="phx_leave",n.access_token="access_token"})(x||(x={}));var qe;(function(n){n.websocket="websocket"})(qe||(qe={}));var G;(function(n){n.Connecting="connecting",n.Open="open",n.Closing="closing",n.Closed="closed"})(G||(G={}));class kr{constructor(){this.HEADER_LENGTH=1,this.META_LENGTH=4,this.USER_BROADCAST_PUSH_META_LENGTH=5,this.KINDS={push:0,reply:1,broadcast:2,userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST="broadcast"}encode(e,t){if(this._isArrayBuffer(e.payload))return t(this._binaryEncodePush(e));if(e.event===this.BROADCAST&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return t(this._binaryEncodeUserBroadcastPush(e));let r=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(r))}_binaryEncodePush(e){const{join_ref:t,ref:r,event:s,topic:i,payload:o}=e,a=this.META_LENGTH+t.length+r.length+i.length+s.length,l=new ArrayBuffer(this.HEADER_LENGTH+a);let c=new DataView(l),u=0;c.setUint8(u++,this.KINDS.push),c.setUint8(u++,t.length),c.setUint8(u++,r.length),c.setUint8(u++,i.length),c.setUint8(u++,s.length),Array.from(t,h=>c.setUint8(u++,h.charCodeAt(0))),Array.from(r,h=>c.setUint8(u++,h.charCodeAt(0))),Array.from(i,h=>c.setUint8(u++,h.charCodeAt(0))),Array.from(s,h=>c.setUint8(u++,h.charCodeAt(0)));var d=new Uint8Array(l.byteLength+o.byteLength);return d.set(new Uint8Array(l),0),d.set(new Uint8Array(o),l.byteLength),d.buffer}_binaryEncodeUserBroadcastPush(e){var t;return this._isArrayBuffer((t=e.payload)===null||t===void 0?void 0:t.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,r;const{join_ref:s,ref:i,topic:o}=e,a=e.payload.event,l=(r=(t=e.payload)===null||t===void 0?void 0:t.payload)!==null&&r!==void 0?r:new ArrayBuffer(0),c=this.USER_BROADCAST_PUSH_META_LENGTH+s.length+i.length+o.length+a.length,u=new ArrayBuffer(this.HEADER_LENGTH+c);let d=new DataView(u),h=0;d.setUint8(h++,this.KINDS.userBroadcastPush),d.setUint8(h++,s.length),d.setUint8(h++,i.length),d.setUint8(h++,o.length),d.setUint8(h++,a.length),d.setUint8(h++,this.BINARY_ENCODING),Array.from(s,g=>d.setUint8(h++,g.charCodeAt(0))),Array.from(i,g=>d.setUint8(h++,g.charCodeAt(0))),Array.from(o,g=>d.setUint8(h++,g.charCodeAt(0))),Array.from(a,g=>d.setUint8(h++,g.charCodeAt(0)));var f=new Uint8Array(u.byteLength+l.byteLength);return f.set(new Uint8Array(u),0),f.set(new Uint8Array(l),u.byteLength),f.buffer}_encodeJsonUserBroadcastPush(e){var t,r;const{join_ref:s,ref:i,topic:o}=e,a=e.payload.event,l=(r=(t=e.payload)===null||t===void 0?void 0:t.payload)!==null&&r!==void 0?r:{},u=new TextEncoder().encode(JSON.stringify(l)).buffer,d=this.USER_BROADCAST_PUSH_META_LENGTH+s.length+i.length+o.length+a.length,h=new ArrayBuffer(this.HEADER_LENGTH+d);let f=new DataView(h),g=0;f.setUint8(g++,this.KINDS.userBroadcastPush),f.setUint8(g++,s.length),f.setUint8(g++,i.length),f.setUint8(g++,o.length),f.setUint8(g++,a.length),f.setUint8(g++,this.JSON_ENCODING),Array.from(s,p=>f.setUint8(g++,p.charCodeAt(0))),Array.from(i,p=>f.setUint8(g++,p.charCodeAt(0))),Array.from(o,p=>f.setUint8(g++,p.charCodeAt(0))),Array.from(a,p=>f.setUint8(g++,p.charCodeAt(0)));var v=new Uint8Array(h.byteLength+u.byteLength);return v.set(new Uint8Array(h),0),v.set(new Uint8Array(u),h.byteLength),v.buffer}decode(e,t){if(this._isArrayBuffer(e)){let r=this._binaryDecode(e);return t(r)}if(typeof e=="string"){const r=JSON.parse(e),[s,i,o,a,l]=r;return t({join_ref:s,ref:i,topic:o,event:a,payload:l})}return t({})}_binaryDecode(e){const t=new DataView(e),r=t.getUint8(0),s=new TextDecoder;switch(r){case this.KINDS.push:return this._decodePush(e,t,s);case this.KINDS.reply:return this._decodeReply(e,t,s);case this.KINDS.broadcast:return this._decodeBroadcast(e,t,s);case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,t,s)}}_decodePush(e,t,r){const s=t.getUint8(1),i=t.getUint8(2),o=t.getUint8(3);let a=this.HEADER_LENGTH+this.META_LENGTH-1;const l=r.decode(e.slice(a,a+s));a=a+s;const c=r.decode(e.slice(a,a+i));a=a+i;const u=r.decode(e.slice(a,a+o));a=a+o;const d=JSON.parse(r.decode(e.slice(a,e.byteLength)));return{join_ref:l,ref:null,topic:c,event:u,payload:d}}_decodeReply(e,t,r){const s=t.getUint8(1),i=t.getUint8(2),o=t.getUint8(3),a=t.getUint8(4);let l=this.HEADER_LENGTH+this.META_LENGTH;const c=r.decode(e.slice(l,l+s));l=l+s;const u=r.decode(e.slice(l,l+i));l=l+i;const d=r.decode(e.slice(l,l+o));l=l+o;const h=r.decode(e.slice(l,l+a));l=l+a;const f=JSON.parse(r.decode(e.slice(l,e.byteLength))),g={status:h,response:f};return{join_ref:c,ref:u,topic:d,event:x.reply,payload:g}}_decodeBroadcast(e,t,r){const s=t.getUint8(1),i=t.getUint8(2);let o=this.HEADER_LENGTH+2;const a=r.decode(e.slice(o,o+s));o=o+s;const l=r.decode(e.slice(o,o+i));o=o+i;const c=JSON.parse(r.decode(e.slice(o,e.byteLength)));return{join_ref:null,ref:null,topic:a,event:l,payload:c}}_decodeUserBroadcast(e,t,r){const s=t.getUint8(1),i=t.getUint8(2),o=t.getUint8(3),a=t.getUint8(4);let l=this.HEADER_LENGTH+4;const c=r.decode(e.slice(l,l+s));l=l+s;const u=r.decode(e.slice(l,l+i));l=l+i;const d=r.decode(e.slice(l,l+o));l=l+o;const h=e.slice(l,e.byteLength),f=a===this.JSON_ENCODING?JSON.parse(r.decode(h)):h,g={type:this.BROADCAST,event:u,payload:f};return o>0&&(g.meta=JSON.parse(d)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST,payload:g}}_isArrayBuffer(e){var t;return e instanceof ArrayBuffer||((t=e?.constructor)===null||t===void 0?void 0:t.name)==="ArrayBuffer"}}class zt{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var O;(function(n){n.abstime="abstime",n.bool="bool",n.date="date",n.daterange="daterange",n.float4="float4",n.float8="float8",n.int2="int2",n.int4="int4",n.int4range="int4range",n.int8="int8",n.int8range="int8range",n.json="json",n.jsonb="jsonb",n.money="money",n.numeric="numeric",n.oid="oid",n.reltime="reltime",n.text="text",n.time="time",n.timestamp="timestamp",n.timestamptz="timestamptz",n.timetz="timetz",n.tsrange="tsrange",n.tstzrange="tstzrange"})(O||(O={}));const dt=(n,e,t={})=>{var r;const s=(r=t.skipTypes)!==null&&r!==void 0?r:[];return e?Object.keys(e).reduce((i,o)=>(i[o]=Or(o,n,e,s),i),{}):{}},Or=(n,e,t,r)=>{const s=e.find(a=>a.name===n),i=s?.type,o=t[n];return i&&!r.includes(i)?Gt(i,o):Me(o)},Gt=(n,e)=>{if(n.charAt(0)==="_"){const t=n.slice(1,n.length);return Pr(e,t)}switch(n){case O.bool:return Tr(e);case O.float4:case O.float8:case O.int2:case O.int4:case O.int8:case O.numeric:case O.oid:return Ar(e);case O.json:case O.jsonb:return Rr(e);case O.timestamp:return jr(e);case O.abstime:case O.date:case O.daterange:case O.int4range:case O.int8range:case O.money:case O.reltime:case O.text:case O.time:case O.timestamptz:case O.timetz:case O.tsrange:case O.tstzrange:return Me(e);default:return Me(e)}},Me=n=>n,Tr=n=>{switch(n){case"t":return!0;case"f":return!1;default:return n}},Ar=n=>{if(typeof n=="string"){const e=parseFloat(n);if(!Number.isNaN(e))return e}return n},Rr=n=>{if(typeof n=="string")try{return JSON.parse(n)}catch(e){return console.log(`JSON parse error: ${e}`),n}return n},Pr=(n,e)=>{if(typeof n!="string")return n;const t=n.length-1,r=n[t];if(n[0]==="{"&&r==="}"){let i;const o=n.slice(1,t);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(a=>Gt(e,a))}return n},jr=n=>typeof n=="string"?n.replace(" ","T"):n,Yt=n=>{const e=new URL(n);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};class Pe{constructor(e,t,r={},s=Be){this.channel=e,this.event=t,this.payload=r,this.timeout=s,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 r;return this._hasReceived(e)&&t((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(r=>r.status===e).forEach(r=>r.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var ft;(function(n){n.SYNC="sync",n.JOIN="join",n.LEAVE="leave"})(ft||(ft={}));class ce{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},s=>{const{onJoin:i,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=ce.syncState(this.state,s,i,o),this.pendingDiffs.forEach(l=>{this.state=ce.syncDiff(this.state,l,i,o)}),this.pendingDiffs=[],a()}),this.channel._on(r.diff,{},s=>{const{onJoin:i,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(s):(this.state=ce.syncDiff(this.state,s,i,o),a())}),this.onJoin((s,i,o)=>{this.channel._trigger("presence",{event:"join",key:s,currentPresences:i,newPresences:o})}),this.onLeave((s,i,o)=>{this.channel._trigger("presence",{event:"leave",key:s,currentPresences:i,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,s){const i=this.cloneDeep(e),o=this.transformState(t),a={},l={};return this.map(i,(c,u)=>{o[c]||(l[c]=u)}),this.map(o,(c,u)=>{const d=i[c];if(d){const h=u.map(p=>p.presence_ref),f=d.map(p=>p.presence_ref),g=u.filter(p=>f.indexOf(p.presence_ref)<0),v=d.filter(p=>h.indexOf(p.presence_ref)<0);g.length>0&&(a[c]=g),v.length>0&&(l[c]=v)}else a[c]=u}),this.syncDiff(i,{joins:a,leaves:l},r,s)}static syncDiff(e,t,r,s){const{joins:i,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),s||(s=()=>{}),this.map(i,(a,l)=>{var c;const u=(c=e[a])!==null&&c!==void 0?c:[];if(e[a]=this.cloneDeep(l),u.length>0){const d=e[a].map(f=>f.presence_ref),h=u.filter(f=>d.indexOf(f.presence_ref)<0);e[a].unshift(...h)}r(a,u,l)}),this.map(o,(a,l)=>{let c=e[a];if(!c)return;const u=l.map(d=>d.presence_ref);c=c.filter(d=>u.indexOf(d.presence_ref)<0),e[a]=c,s(a,c,l),c.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{const s=e[r];return"metas"in s?t[r]=s.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):t[r]=s,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var gt;(function(n){n.ALL="*",n.INSERT="INSERT",n.UPDATE="UPDATE",n.DELETE="DELETE"})(gt||(gt={}));var ue;(function(n){n.BROADCAST="broadcast",n.PRESENCE="presence",n.POSTGRES_CHANGES="postgres_changes",n.SYSTEM="system"})(ue||(ue={}));var q;(function(n){n.SUBSCRIBED="SUBSCRIBED",n.TIMED_OUT="TIMED_OUT",n.CLOSED="CLOSED",n.CHANNEL_ERROR="CHANNEL_ERROR"})(q||(q={}));class Qe{constructor(e,t={config:{}},r){var s,i;if(this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=j.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 Pe(this,x.join,this.params,this.timeout),this.rejoinTimer=new zt(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=j.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(o=>o.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=j.closed,this.socket._remove(this)}),this._onError(o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=j.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=j.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=j.errored,this.rejoinTimer.scheduleTimeout())}),this._on(x.reply,{},(o,a)=>{this._trigger(this._replyEventName(a),o)}),this.presence=new ce(this),this.broadcastEndpointURL=Yt(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(!((i=(s=this.params.config)===null||s===void 0?void 0:s.broadcast)===null||i===void 0)&&i.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,t=this.timeout){var r,s,i;if(this.socket.isConnected()||this.socket.connect(),this.state==j.closed){const{config:{broadcast:o,presence:a,private:l}}=this.params,c=(s=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(f=>f.filter))!==null&&s!==void 0?s:[],u=!!this.bindings[ue.PRESENCE]&&this.bindings[ue.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,d={},h={broadcast:o,presence:Object.assign(Object.assign({},a),{enabled:u}),postgres_changes:c,private:l};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(f=>e?.(q.CHANNEL_ERROR,f)),this._onClose(()=>e?.(q.CLOSED)),this.updateJoinPayload(Object.assign({config:h},d)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:f})=>{var g;if(this.socket.setAuth(),f===void 0){e?.(q.SUBSCRIBED);return}else{const v=this.bindings.postgres_changes,p=(g=v?.length)!==null&&g!==void 0?g:0,E=[];for(let b=0;b<p;b++){const _=v[b],{filter:{event:S,schema:A,table:k,filter:P}}=_,M=f&&f[b];if(M&&M.event===S&&M.schema===A&&M.table===k&&M.filter===P)E.push(Object.assign(Object.assign({},_),{id:M.id}));else{this.unsubscribe(),this.state=j.errored,e?.(q.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=E,e&&e(q.SUBSCRIBED);return}}).receive("error",f=>{this.state=j.errored,e?.(q.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(f).join(", ")||"error")))}).receive("timeout",()=>{e?.(q.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this.state===j.joined&&e===ue.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,r)}async httpSend(e,t,r={}){var s;const i=this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"";if(t==null)return Promise.reject("Payload is required for httpSend()");const o={method:"POST",headers:{Authorization:i,apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(s=r.timeout)!==null&&s!==void 0?s:this.timeout);if(a.status===202)return{success:!0};let l=a.statusText;try{const c=await a.json();l=c.error||c.message||l}catch{}return Promise.reject(new Error(l))}async send(e,t={}){var r,s;if(!this._canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:i,payload:o}=e,l={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:i,payload:o,private:this.private}]})};try{const c=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((s=c.body)===null||s===void 0?void 0:s.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,a,l;const c=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&i("ok"),c.receive("ok",()=>i("ok")),c.receive("error",()=>i("error")),c.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=j.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(x.close,"leave",this._joinRef())};this.joinPush.destroy();let r=null;return new Promise(s=>{r=new Pe(this,x.leave,{},e),r.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),r.send(),this._canPush()||r.trigger("ok",{})}).finally(()=>{r?.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=j.closed,this.bindings={}}async _fetchWithTimeout(e,t,r){const s=new AbortController,i=setTimeout(()=>s.abort(),r),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:s.signal}));return clearTimeout(i),o}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new Pe(this,e,t,r);return this._canPush()?s.send():this._addToPushBuffer(s),s}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>Sr){const t=this.pushBuffer.shift();t&&(t.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${t.event}`,t.payload))}}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var s,i;const o=e.toLocaleLowerCase(),{close:a,error:l,leave:c,join:u}=x;if(r&&[a,l,c,u].indexOf(o)>=0&&r!==this._joinRef())return;let h=this._onMessage(o,t,r);if(t&&!h)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(s=this.bindings.postgres_changes)===null||s===void 0||s.filter(f=>{var g,v,p;return((g=f.filter)===null||g===void 0?void 0:g.event)==="*"||((p=(v=f.filter)===null||v===void 0?void 0:v.event)===null||p===void 0?void 0:p.toLocaleLowerCase())===o}).map(f=>f.callback(h,r)):(i=this.bindings[o])===null||i===void 0||i.filter(f=>{var g,v,p,E,b,_;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){const S=f.id,A=(g=f.filter)===null||g===void 0?void 0:g.event;return S&&((v=t.ids)===null||v===void 0?void 0:v.includes(S))&&(A==="*"||A?.toLocaleLowerCase()===((p=t.data)===null||p===void 0?void 0:p.type.toLocaleLowerCase()))}else{const S=(b=(E=f?.filter)===null||E===void 0?void 0:E.event)===null||b===void 0?void 0:b.toLocaleLowerCase();return S==="*"||S===((_=t?.event)===null||_===void 0?void 0:_.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof h=="object"&&"ids"in h){const g=h.data,{schema:v,table:p,commit_timestamp:E,type:b,errors:_}=g;h=Object.assign(Object.assign({},{schema:v,table:p,commit_timestamp:E,eventType:b,new:{},old:{},errors:_}),this._getPayloadRecords(g))}f.callback(h,r)})}_isClosed(){return this.state===j.closed}_isJoined(){return this.state===j.joined}_isJoining(){return this.state===j.joining}_isLeaving(){return this.state===j.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){const s=e.toLocaleLowerCase(),i={type:s,filter:t,callback:r};return this.bindings[s]?this.bindings[s].push(i):this.bindings[s]=[i],this}_off(e,t){const r=e.toLocaleLowerCase();return this.bindings[r]&&(this.bindings[r]=this.bindings[r].filter(s=>{var i;return!(((i=s.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===r&&Qe.isEqual(s.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const r in e)if(e[r]!==t[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(x.close,{},e)}_onError(e){this._on(x.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=j.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=dt(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=dt(e.columns,e.old_record)),t}}const je=()=>{},me={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Cr=[1e3,2e3,5e3,1e4],Ir=1e4,$r=`
  addEventListener("message", (e) => {
    if (e.data.event === "start") {
      setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
    }
  });`;class Ur{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=Be,this.transport=null,this.heartbeatIntervalMs=me.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=je,this.ref=0,this.reconnectTimer=null,this.vsn=ht,this.logger=je,this.conn=null,this.sendBuffer=[],this.serializer=new kr,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._resolveFetch=s=>s?(...i)=>s(...i):(...i)=>fetch(...i),!(!((r=t?.params)===null||r===void 0)&&r.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${qe.websocket}`,this.httpEndpoint=Yt(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=wr.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;throw t.includes("Node.js")?new Error(`${t}

To use Realtime in Node.js, you need to provide a WebSocket implementation:

Option 1: Use Node.js 22+ which has native WebSocket support
Option 2: Install and provide the "ws" package:

  npm install ws

  import ws from "ws"
  const client = new RealtimeClient(url, {
    ...options,
    transport: ws
  })`):new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const r=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(r),this._setConnectionState("disconnected")},typeof this.conn.close=="function"&&(e?this.conn.close(e,t??""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){const e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case z.connecting:return G.Connecting;case z.open:return G.Open;case z.closing:return G.Closing;default:return G.Closed}}isConnected(){return this.connectionState()===G.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(e,t={config:{}}){const r=`realtime:${e}`,s=this.getChannels().find(i=>i.topic===r);if(s)return s;{const i=new Qe(`realtime:${e}`,t,this);return this.channels.push(i),i}}push(e){const{topic:t,event:r,payload:s,ref:i}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${t} ${r} (${i})`,s),this.isConnected()?o():this.sendBuffer.push(o)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this._wasManualDisconnect=!1,(e=this.conn)===null||e===void 0||e.close(Er,"heartbeat timeout"),setTimeout(()=>{var t;this.isConnected()||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout()},me.HEARTBEAT_TIMEOUT_FALLBACK);return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this._setAuthSafely("heartbeat")}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(r=>r.topic===e&&(r._isJoined()||r._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,t=>{if(t.topic==="phoenix"&&t.event==="phx_reply")try{this.heartbeatCallback(t.payload.status==="ok"?"ok":"error")}catch(c){this.log("error","error in heartbeat callback",c)}t.ref&&t.ref===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null);const{topic:r,event:s,payload:i,ref:o}=t,a=o?`(${o})`:"",l=i.status||"";this.log("receive",`${l} ${r} ${s} ${a}`.trim(),i),this.channels.filter(c=>c._isMember(r)).forEach(c=>c._trigger(s,i,o)),this._triggerStateCallbacks("message",t)})}_clearTimer(e){var t;e==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e==="reconnect"&&((t=this.reconnectTimer)===null||t===void 0||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_teardownConnection(){if(this.conn){if(this.conn.readyState===z.open||this.conn.readyState===z.connecting)try{this.conn.close()}catch(e){this.log("error","Error closing connection",e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.flushSendBuffer()}).catch(t=>{this.log("error","error waiting for auth on connect",t),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=t=>{this.log("worker","worker error",t.message),this.workerRef.terminate()},this.workerRef.onmessage=t=>{t.data.event==="keepAlive"&&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||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e)}_triggerChanError(){this.channels.forEach(e=>e._trigger(x.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;const r=e.match(/\?/)?"&":"?",s=new URLSearchParams(t);return`${e}${r}${s}`}_workerObjectUrl(e){let t;if(e)t=e;else{const r=new Blob([$r],{type:"application/javascript"});t=URL.createObjectURL(r)}return t}_setConnectionState(e,t=!1){this._connectionState=e,e==="connecting"?this._wasManualDisconnect=!1:e==="disconnecting"&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t;e?t=e:this.accessToken?t=await this.accessToken():t=this.accessTokenValue,this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(r=>{const s={access_token:t,version:br};t&&r.updateJoinPayload(s),r.joinedOnce&&r._isJoined()&&r._push(x.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(r=>{try{r(t)}catch(s){this.log("error",`error in ${e} callback`,s)}})}catch(r){this.log("error",`error triggering ${e} callbacks`,r)}}_setupReconnectionTimer(){this.reconnectTimer=new zt(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},me.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var t,r,s,i,o,a,l,c,u,d,h,f;switch(this.transport=(t=e?.transport)!==null&&t!==void 0?t:null,this.timeout=(r=e?.timeout)!==null&&r!==void 0?r:Be,this.heartbeatIntervalMs=(s=e?.heartbeatIntervalMs)!==null&&s!==void 0?s:me.HEARTBEAT_INTERVAL,this.worker=(i=e?.worker)!==null&&i!==void 0?i:!1,this.accessToken=(o=e?.accessToken)!==null&&o!==void 0?o:null,this.heartbeatCallback=(a=e?.heartbeatCallback)!==null&&a!==void 0?a:je,this.vsn=(l=e?.vsn)!==null&&l!==void 0?l:ht,e?.params&&(this.params=e.params),e?.logger&&(this.logger=e.logger),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(c=e?.reconnectAfterMs)!==null&&c!==void 0?c:g=>Cr[g-1]||Ir,this.vsn){case Jt:this.encode=(u=e?.encode)!==null&&u!==void 0?u:(g,v)=>v(JSON.stringify(g)),this.decode=(d=e?.decode)!==null&&d!==void 0?d:(g,v)=>v(JSON.parse(g));break;case mr:this.encode=(h=e?.encode)!==null&&h!==void 0?h:this.serializer.encode.bind(this.serializer),this.decode=(f=e?.decode)!==null&&f!==void 0?f:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl}}}class Xe extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function T(n){return typeof n=="object"&&n!==null&&"__isStorageError"in n}class xr extends Xe{constructor(e,t,r){super(e),this.name="StorageApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class We extends Xe{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}const Ze=n=>n?(...e)=>n(...e):(...e)=>fetch(...e),Nr=()=>Response,Fe=n=>{if(Array.isArray(n))return n.map(t=>Fe(t));if(typeof n=="function"||n!==Object(n))return n;const e={};return Object.entries(n).forEach(([t,r])=>{const s=t.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[s]=Fe(r)}),e},Lr=n=>{if(typeof n!="object"||n===null)return!1;const e=Object.getPrototypeOf(n);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in n)&&!(Symbol.iterator in n)},Ce=n=>{var e;return n.msg||n.message||n.error_description||(typeof n.error=="string"?n.error:(e=n.error)===null||e===void 0?void 0:e.message)||JSON.stringify(n)},Dr=(n,e,t)=>w(void 0,void 0,void 0,function*(){const r=yield Nr();n instanceof r&&!t?.noResolveJson?n.json().then(s=>{const i=n.status||500,o=s?.statusCode||i+"";e(new xr(Ce(s),i,o))}).catch(s=>{e(new We(Ce(s),s))}):e(new We(Ce(n),n))}),Br=(n,e,t,r)=>{const s={method:n,headers:e?.headers||{}};return n==="GET"||!r?s:(Lr(r)?(s.headers=Object.assign({"Content-Type":"application/json"},e?.headers),s.body=JSON.stringify(r)):s.body=r,e?.duplex&&(s.duplex=e.duplex),Object.assign(Object.assign({},s),t))};function ge(n,e,t,r,s,i){return w(this,void 0,void 0,function*(){return new Promise((o,a)=>{n(t,Br(e,r,s,i)).then(l=>{if(!l.ok)throw l;return r?.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>Dr(l,a,r))})})}function he(n,e,t,r){return w(this,void 0,void 0,function*(){return ge(n,"GET",e,t,r)})}function D(n,e,t,r,s){return w(this,void 0,void 0,function*(){return ge(n,"POST",e,r,s,t)})}function Ve(n,e,t,r,s){return w(this,void 0,void 0,function*(){return ge(n,"PUT",e,r,s,t)})}function qr(n,e,t,r){return w(this,void 0,void 0,function*(){return ge(n,"HEAD",e,Object.assign(Object.assign({},t),{noResolveJson:!0}),r)})}function et(n,e,t,r,s){return w(this,void 0,void 0,function*(){return ge(n,"DELETE",e,r,s,t)})}class Mr{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}execute(){return w(this,void 0,void 0,function*(){try{return{data:(yield this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(T(e))return{data:null,error:e};throw e}})}}var Qt;class Wr{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[Qt]="BlobDownloadBuilder",this.promise=null}asStream(){return new Mr(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}execute(){return w(this,void 0,void 0,function*(){try{return{data:yield(yield this.downloadFn()).blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(T(e))return{data:null,error:e};throw e}})}}Qt=Symbol.toStringTag;const Fr={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},pt={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class Vr{constructor(e,t={},r,s){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.bucketId=r,this.fetch=Ze(s)}throwOnError(){return this.shouldThrowOnError=!0,this}uploadOrUpdate(e,t,r,s){return w(this,void 0,void 0,function*(){try{let i;const o=Object.assign(Object.assign({},pt),s);let a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});const l=o.metadata;typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),l&&i.append("metadata",this.encodeMetadata(l)),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",o.cacheControl),l&&!i.has("metadata")&&i.append("metadata",this.encodeMetadata(l))):(i=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=this.toBase64(this.encodeMetadata(l))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!o.duplex&&(o.duplex="half")),s?.headers&&(a=Object.assign(Object.assign({},a),s.headers));const c=this._removeEmptyFolders(t),u=this._getFinalPath(c),d=yield(e=="PUT"?Ve:D)(this.fetch,`${this.url}/object/${u}`,i,Object.assign({headers:a},o?.duplex?{duplex:o.duplex}:{}));return{data:{path:c,id:d.Id,fullPath:d.Key},error:null}}catch(i){if(this.shouldThrowOnError)throw i;if(T(i))return{data:null,error:i};throw i}})}upload(e,t,r){return w(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,s){return w(this,void 0,void 0,function*(){const i=this._removeEmptyFolders(e),o=this._getFinalPath(i),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let l;const c=Object.assign({upsert:pt.upsert},s),u=Object.assign(Object.assign({},this.headers),{"x-upsert":String(c.upsert)});typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",c.cacheControl)):(l=r,u["cache-control"]=`max-age=${c.cacheControl}`,u["content-type"]=c.contentType);const d=yield Ve(this.fetch,a.toString(),l,{headers:u});return{data:{path:i,fullPath:d.Key},error:null}}catch(l){if(this.shouldThrowOnError)throw l;if(T(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e,t){return w(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e);const s=Object.assign({},this.headers);t?.upsert&&(s["x-upsert"]="true");const i=yield D(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:s}),o=new URL(this.url+i.url),a=o.searchParams.get("token");if(!a)throw new Xe("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(T(r))return{data:null,error:r};throw r}})}update(e,t,r){return w(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return w(this,void 0,void 0,function*(){try{return{data:yield D(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers}),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(T(s))return{data:null,error:s};throw s}})}copy(e,t,r){return w(this,void 0,void 0,function*(){try{return{data:{path:(yield D(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(T(s))return{data:null,error:s};throw s}})}createSignedUrl(e,t,r){return w(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),i=yield D(this.fetch,`${this.url}/object/sign/${s}`,Object.assign({expiresIn:t},r?.transform?{transform:r.transform}:{}),{headers:this.headers});const o=r?.download?`&download=${r.download===!0?"":r.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${o}`)},{data:i,error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(T(s))return{data:null,error:s};throw s}})}createSignedUrls(e,t,r){return w(this,void 0,void 0,function*(){try{const s=yield D(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=r?.download?`&download=${r.download===!0?"":r.download}`:"";return{data:s.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${i}`):null})),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(T(s))return{data:null,error:s};throw s}})}download(e,t){const s=typeof t?.transform<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString(t?.transform||{}),o=i?`?${i}`:"",a=this._getFinalPath(e),l=()=>he(this.fetch,`${this.url}/${s}/${a}${o}`,{headers:this.headers,noResolveJson:!0});return new Wr(l,this.shouldThrowOnError)}info(e){return w(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{const r=yield he(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:Fe(r),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(T(r))return{data:null,error:r};throw r}})}exists(e){return w(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{return yield qr(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(T(r)&&r instanceof We){const s=r.originalError;if([400,404].includes(s?.status))return{data:!1,error:r}}throw r}})}getPublicUrl(e,t){const r=this._getFinalPath(e),s=[],i=t?.download?`download=${t.download===!0?"":t.download}`:"";i!==""&&s.push(i);const a=typeof t?.transform<"u"?"render/image":"object",l=this.transformOptsToQueryString(t?.transform||{});l!==""&&s.push(l);let c=s.join("&");return c!==""&&(c=`?${c}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${c}`)}}}remove(e){return w(this,void 0,void 0,function*(){try{return{data:yield et(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(T(t))return{data:null,error:t};throw t}})}list(e,t,r){return w(this,void 0,void 0,function*(){try{const s=Object.assign(Object.assign(Object.assign({},Fr),t),{prefix:e||""});return{data:yield D(this.fetch,`${this.url}/object/list/${this.bucketId}`,s,{headers:this.headers},r),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(T(s))return{data:null,error:s};throw s}})}listV2(e,t){return w(this,void 0,void 0,function*(){try{const r=Object.assign({},e);return{data:yield D(this.fetch,`${this.url}/object/list-v2/${this.bucketId}`,r,{headers:this.headers},t),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(T(r))return{data:null,error:r};throw r}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?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 Xt="2.81.1",Zt={"X-Client-Info":`storage-js/${Xt}`};class Kr{constructor(e,t={},r,s){this.shouldThrowOnError=!1;const i=new URL(e);s?.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.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},Zt),t),this.fetch=Ze(r)}throwOnError(){return this.shouldThrowOnError=!0,this}listBuckets(e){return w(this,void 0,void 0,function*(){try{const t=this.listBucketOptionsToQueryString(e);return{data:yield he(this.fetch,`${this.url}/bucket${t}`,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(T(t))return{data:null,error:t};throw t}})}getBucket(e){return w(this,void 0,void 0,function*(){try{return{data:yield he(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(T(t))return{data:null,error:t};throw t}})}createBucket(e){return w(this,arguments,void 0,function*(t,r={public:!1}){try{return{data:yield D(this.fetch,`${this.url}/bucket`,{id:t,name:t,type:r.type,public:r.public,file_size_limit:r.fileSizeLimit,allowed_mime_types:r.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(T(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return w(this,void 0,void 0,function*(){try{return{data:yield Ve(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(T(r))return{data:null,error:r};throw r}})}emptyBucket(e){return w(this,void 0,void 0,function*(){try{return{data:yield D(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(T(t))return{data:null,error:t};throw t}})}deleteBucket(e){return w(this,void 0,void 0,function*(){try{return{data:yield et(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(T(t))return{data:null,error:t};throw t}})}listBucketOptionsToQueryString(e){const t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}}class Hr{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},Zt),t),this.fetch=Ze(r)}throwOnError(){return this.shouldThrowOnError=!0,this}createBucket(e){return w(this,void 0,void 0,function*(){try{return{data:yield D(this.fetch,`${this.url}/bucket`,{name:e},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(T(t))return{data:null,error:t};throw t}})}listBuckets(e){return w(this,void 0,void 0,function*(){try{const t=new URLSearchParams;e?.limit!==void 0&&t.set("limit",e.limit.toString()),e?.offset!==void 0&&t.set("offset",e.offset.toString()),e?.sortColumn&&t.set("sortColumn",e.sortColumn),e?.sortOrder&&t.set("sortOrder",e.sortOrder),e?.search&&t.set("search",e.search);const r=t.toString(),s=r?`${this.url}/bucket?${r}`:`${this.url}/bucket`;return{data:yield he(this.fetch,s,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(T(t))return{data:null,error:t};throw t}})}deleteBucket(e){return w(this,void 0,void 0,function*(){try{return{data:yield et(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(T(t))return{data:null,error:t};throw t}})}}const tt={"X-Client-Info":`storage-js/${Xt}`,"Content-Type":"application/json"};class er extends Error{constructor(e){super(e),this.__isStorageVectorsError=!0,this.name="StorageVectorsError"}}function $(n){return typeof n=="object"&&n!==null&&"__isStorageVectorsError"in n}class Ie extends er{constructor(e,t,r){super(e),this.name="StorageVectorsApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class Jr extends er{constructor(e,t){super(e),this.name="StorageVectorsUnknownError",this.originalError=t}}var _t;(function(n){n.InternalError="InternalError",n.S3VectorConflictException="S3VectorConflictException",n.S3VectorNotFoundException="S3VectorNotFoundException",n.S3VectorBucketNotEmpty="S3VectorBucketNotEmpty",n.S3VectorMaxBucketsExceeded="S3VectorMaxBucketsExceeded",n.S3VectorMaxIndexesExceeded="S3VectorMaxIndexesExceeded"})(_t||(_t={}));const rt=n=>n?(...e)=>n(...e):(...e)=>fetch(...e),zr=n=>{if(typeof n!="object"||n===null)return!1;const e=Object.getPrototypeOf(n);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in n)&&!(Symbol.iterator in n)},vt=n=>n.msg||n.message||n.error_description||n.error||JSON.stringify(n),Gr=(n,e,t)=>w(void 0,void 0,void 0,function*(){if(n&&typeof n=="object"&&"status"in n&&"ok"in n&&typeof n.status=="number"&&!t?.noResolveJson){const s=n.status||500,i=n;if(typeof i.json=="function")i.json().then(o=>{const a=o?.statusCode||o?.code||s+"";e(new Ie(vt(o),s,a))}).catch(()=>{const o=s+"",a=i.statusText||`HTTP ${s} error`;e(new Ie(a,s,o))});else{const o=s+"",a=i.statusText||`HTTP ${s} error`;e(new Ie(a,s,o))}}else e(new Jr(vt(n),n))}),Yr=(n,e,t,r)=>{const s={method:n,headers:e?.headers||{}};return r?(zr(r)?(s.headers=Object.assign({"Content-Type":"application/json"},e?.headers),s.body=JSON.stringify(r)):s.body=r,Object.assign(Object.assign({},s),t)):s};function Qr(n,e,t,r,s,i){return w(this,void 0,void 0,function*(){return new Promise((o,a)=>{n(t,Yr(e,r,s,i)).then(l=>{if(!l.ok)throw l;if(r?.noResolveJson)return l;const c=l.headers.get("content-type");return!c||!c.includes("application/json")?{}:l.json()}).then(l=>o(l)).catch(l=>Gr(l,a,r))})})}function U(n,e,t,r,s){return w(this,void 0,void 0,function*(){return Qr(n,"POST",e,r,s,t)})}class Xr{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},tt),t),this.fetch=rt(r)}throwOnError(){return this.shouldThrowOnError=!0,this}createIndex(e){return w(this,void 0,void 0,function*(){try{return{data:(yield U(this.fetch,`${this.url}/CreateIndex`,e,{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($(t))return{data:null,error:t};throw t}})}getIndex(e,t){return w(this,void 0,void 0,function*(){try{return{data:yield U(this.fetch,`${this.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if($(r))return{data:null,error:r};throw r}})}listIndexes(e){return w(this,void 0,void 0,function*(){try{return{data:yield U(this.fetch,`${this.url}/ListIndexes`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($(t))return{data:null,error:t};throw t}})}deleteIndex(e,t){return w(this,void 0,void 0,function*(){try{return{data:(yield U(this.fetch,`${this.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:this.headers}))||{},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if($(r))return{data:null,error:r};throw r}})}}class Zr{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},tt),t),this.fetch=rt(r)}throwOnError(){return this.shouldThrowOnError=!0,this}putVectors(e){return w(this,void 0,void 0,function*(){try{if(e.vectors.length<1||e.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return{data:(yield U(this.fetch,`${this.url}/PutVectors`,e,{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($(t))return{data:null,error:t};throw t}})}getVectors(e){return w(this,void 0,void 0,function*(){try{return{data:yield U(this.fetch,`${this.url}/GetVectors`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($(t))return{data:null,error:t};throw t}})}listVectors(e){return w(this,void 0,void 0,function*(){try{if(e.segmentCount!==void 0){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(e.segmentIndex!==void 0&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error(`segmentIndex must be between 0 and ${e.segmentCount-1}`)}return{data:yield U(this.fetch,`${this.url}/ListVectors`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($(t))return{data:null,error:t};throw t}})}queryVectors(e){return w(this,void 0,void 0,function*(){try{return{data:yield U(this.fetch,`${this.url}/QueryVectors`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($(t))return{data:null,error:t};throw t}})}deleteVectors(e){return w(this,void 0,void 0,function*(){try{if(e.keys.length<1||e.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return{data:(yield U(this.fetch,`${this.url}/DeleteVectors`,e,{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($(t))return{data:null,error:t};throw t}})}}class es{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},tt),t),this.fetch=rt(r)}throwOnError(){return this.shouldThrowOnError=!0,this}createBucket(e){return w(this,void 0,void 0,function*(){try{return{data:(yield U(this.fetch,`${this.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($(t))return{data:null,error:t};throw t}})}getBucket(e){return w(this,void 0,void 0,function*(){try{return{data:yield U(this.fetch,`${this.url}/GetVectorBucket`,{vectorBucketName:e},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($(t))return{data:null,error:t};throw t}})}listBuckets(){return w(this,arguments,void 0,function*(e={}){try{return{data:yield U(this.fetch,`${this.url}/ListVectorBuckets`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($(t))return{data:null,error:t};throw t}})}deleteBucket(e){return w(this,void 0,void 0,function*(){try{return{data:(yield U(this.fetch,`${this.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($(t))return{data:null,error:t};throw t}})}}class ts extends es{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new rs(this.url,this.headers,e,this.fetch)}}class rs extends Xr{constructor(e,t,r,s){super(e,t,s),this.vectorBucketName=r}createIndex(e){const t=Object.create(null,{createIndex:{get:()=>super.createIndex}});return w(this,void 0,void 0,function*(){return t.createIndex.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName}))})}listIndexes(){const e=Object.create(null,{listIndexes:{get:()=>super.listIndexes}});return w(this,arguments,void 0,function*(t={}){return e.listIndexes.call(this,Object.assign(Object.assign({},t),{vectorBucketName:this.vectorBucketName}))})}getIndex(e){const t=Object.create(null,{getIndex:{get:()=>super.getIndex}});return w(this,void 0,void 0,function*(){return t.getIndex.call(this,this.vectorBucketName,e)})}deleteIndex(e){const t=Object.create(null,{deleteIndex:{get:()=>super.deleteIndex}});return w(this,void 0,void 0,function*(){return t.deleteIndex.call(this,this.vectorBucketName,e)})}index(e){return new ss(this.url,this.headers,this.vectorBucketName,e,this.fetch)}}class ss extends Zr{constructor(e,t,r,s,i){super(e,t,i),this.vectorBucketName=r,this.indexName=s}putVectors(e){const t=Object.create(null,{putVectors:{get:()=>super.putVectors}});return w(this,void 0,void 0,function*(){return t.putVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}getVectors(e){const t=Object.create(null,{getVectors:{get:()=>super.getVectors}});return w(this,void 0,void 0,function*(){return t.getVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}listVectors(){const e=Object.create(null,{listVectors:{get:()=>super.listVectors}});return w(this,arguments,void 0,function*(t={}){return e.listVectors.call(this,Object.assign(Object.assign({},t),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}queryVectors(e){const t=Object.create(null,{queryVectors:{get:()=>super.queryVectors}});return w(this,void 0,void 0,function*(){return t.queryVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}deleteVectors(e){const t=Object.create(null,{deleteVectors:{get:()=>super.deleteVectors}});return w(this,void 0,void 0,function*(){return t.deleteVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}}class is extends Kr{constructor(e,t={},r,s){super(e,t,r,s)}from(e){return new Vr(this.url,this.headers,e,this.fetch)}get vectors(){return new ts(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Hr(this.url+"/iceberg",this.headers,this.fetch)}}const ns="2.81.1";let le="";typeof Deno<"u"?le="deno":typeof document<"u"?le="web":typeof navigator<"u"&&navigator.product==="ReactNative"?le="react-native":le="node";const os={"X-Client-Info":`supabase-js-${le}/${ns}`},as={headers:os},ls={schema:"public"},cs={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},us={},hs=n=>n?(...e)=>n(...e):(...e)=>fetch(...e),ds=()=>Headers,fs=(n,e,t)=>{const r=hs(t),s=ds();return async(i,o)=>{var a;const l=(a=await e())!==null&&a!==void 0?a:n;let c=new s(o?.headers);return c.has("apikey")||c.set("apikey",n),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),r(i,Object.assign(Object.assign({},o),{headers:c}))}};function gs(n){return n.endsWith("/")?n:n+"/"}function ps(n,e){var t,r;const{db:s,auth:i,realtime:o,global:a}=n,{db:l,auth:c,realtime:u,global:d}=e,h={db:Object.assign(Object.assign({},l),s),auth:Object.assign(Object.assign({},c),i),realtime:Object.assign(Object.assign({},u),o),storage:{},global:Object.assign(Object.assign(Object.assign({},d),a),{headers:Object.assign(Object.assign({},(t=d?.headers)!==null&&t!==void 0?t:{}),(r=a?.headers)!==null&&r!==void 0?r:{})}),accessToken:async()=>""};return n.accessToken?h.accessToken=n.accessToken:delete h.accessToken,h}function _s(n){const e=n?.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(gs(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}const tr="2.81.1",se=30*1e3,Ke=3,$e=Ke*se,vs="http://localhost:9999",ws="supabase.auth.token",ys={"X-Client-Info":`gotrue-js/${tr}`},He="X-Supabase-Api-Version",rr={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},bs=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,ms=10*60*1e3;class de extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}}function y(n){return typeof n=="object"&&n!==null&&"__isAuthError"in n}class Es extends de{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}}function Ss(n){return y(n)&&n.name==="AuthApiError"}class Y extends de{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class V extends de{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}}class N extends V{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function ks(n){return y(n)&&n.name==="AuthSessionMissingError"}class X extends V{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class Ee extends V{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class Se extends V{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function Os(n){return y(n)&&n.name==="AuthImplicitGrantRedirectError"}class wt extends V{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 Je extends V{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function Ue(n){return y(n)&&n.name==="AuthRetryableFetchError"}class yt extends V{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}}class ze extends V{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const ke="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),bt=` 	
\r=`.split(""),Ts=(()=>{const n=new Array(128);for(let e=0;e<n.length;e+=1)n[e]=-1;for(let e=0;e<bt.length;e+=1)n[bt[e].charCodeAt(0)]=-2;for(let e=0;e<ke.length;e+=1)n[ke[e].charCodeAt(0)]=e;return n})();function mt(n,e,t){if(n!==null)for(e.queue=e.queue<<8|n,e.queuedBits+=8;e.queuedBits>=6;){const r=e.queue>>e.queuedBits-6&63;t(ke[r]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const r=e.queue>>e.queuedBits-6&63;t(ke[r]),e.queuedBits-=6}}function sr(n,e,t){const r=Ts[n];if(r>-1)for(e.queue=e.queue<<6|r,e.queuedBits+=6;e.queuedBits>=8;)t(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(r===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(n)}"`)}}function Et(n){const e=[],t=o=>{e.push(String.fromCodePoint(o))},r={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=o=>{Ps(o,r,t)};for(let o=0;o<n.length;o+=1)sr(n.charCodeAt(o),s,i);return e.join("")}function As(n,e){if(n<=127){e(n);return}else if(n<=2047){e(192|n>>6),e(128|n&63);return}else if(n<=65535){e(224|n>>12),e(128|n>>6&63),e(128|n&63);return}else if(n<=1114111){e(240|n>>18),e(128|n>>12&63),e(128|n>>6&63),e(128|n&63);return}throw new Error(`Unrecognized Unicode codepoint: ${n.toString(16)}`)}function Rs(n,e){for(let t=0;t<n.length;t+=1){let r=n.charCodeAt(t);if(r>55295&&r<=56319){const s=(r-55296)*1024&65535;r=(n.charCodeAt(t+1)-56320&65535|s)+65536,t+=1}As(r,e)}}function Ps(n,e,t){if(e.utf8seq===0){if(n<=127){t(n);return}for(let r=1;r<6;r+=1)if(!(n>>7-r&1)){e.utf8seq=r;break}if(e.utf8seq===2)e.codepoint=n&31;else if(e.utf8seq===3)e.codepoint=n&15;else if(e.utf8seq===4)e.codepoint=n&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(n<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|n&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint)}}function ne(n){const e=[],t={queue:0,queuedBits:0},r=s=>{e.push(s)};for(let s=0;s<n.length;s+=1)sr(n.charCodeAt(s),t,r);return new Uint8Array(e)}function js(n){const e=[];return Rs(n,t=>e.push(t)),new Uint8Array(e)}function Q(n){const e=[],t={queue:0,queuedBits:0},r=s=>{e.push(s)};return n.forEach(s=>mt(s,t,r)),mt(null,t,r),e.join("")}function Cs(n){return Math.round(Date.now()/1e3)+n}function Is(){return Symbol("auth-callback")}const C=()=>typeof window<"u"&&typeof document<"u",K={tested:!1,writable:!1},ir=()=>{if(!C())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(K.tested)return K.writable;const n=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(n,n),globalThis.localStorage.removeItem(n),K.tested=!0,K.writable=!0}catch{K.tested=!0,K.writable=!1}return K.writable};function $s(n){const e={},t=new URL(n);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((s,i)=>{e[i]=s})}catch{}return t.searchParams.forEach((r,s)=>{e[s]=r}),e}const nr=n=>n?(...e)=>n(...e):(...e)=>fetch(...e),Us=n=>typeof n=="object"&&n!==null&&"status"in n&&"ok"in n&&"json"in n&&typeof n.json=="function",ie=async(n,e,t)=>{await n.setItem(e,JSON.stringify(t))},H=async(n,e)=>{const t=await n.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},W=async(n,e)=>{await n.removeItem(e)};class Re{constructor(){this.promise=new Re.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}Re.promiseConstructor=Promise;function xe(n){const e=n.split(".");if(e.length!==3)throw new ze("Invalid JWT structure");for(let r=0;r<e.length;r++)if(!bs.test(e[r]))throw new ze("JWT not in base64url format");return{header:JSON.parse(Et(e[0])),payload:JSON.parse(Et(e[1])),signature:ne(e[2]),raw:{header:e[0],payload:e[1]}}}async function xs(n){return await new Promise(e=>{setTimeout(()=>e(null),n)})}function Ns(n,e){return new Promise((r,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{const o=await n(i);if(!e(i,null,o)){r(o);return}}catch(o){if(!e(i,o)){s(o);return}}})()})}function Ls(n){return("0"+n.toString(16)).substr(-2)}function Ds(){const e=new Uint32Array(56);if(typeof crypto>"u"){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length;let s="";for(let i=0;i<56;i++)s+=t.charAt(Math.floor(Math.random()*r));return s}return crypto.getRandomValues(e),Array.from(e,Ls).join("")}async function Bs(n){const t=new TextEncoder().encode(n),r=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(r);return Array.from(s).map(i=>String.fromCharCode(i)).join("")}async function qs(n){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),n;const t=await Bs(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Z(n,e,t=!1){const r=Ds();let s=r;t&&(s+="/PASSWORD_RECOVERY"),await ie(n,`${e}-code-verifier`,s);const i=await qs(r);return[i,r===i?"plain":"s256"]}const Ms=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Ws(n){const e=n.headers.get(He);if(!e||!e.match(Ms))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Fs(n){if(!n)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(n<=e)throw new Error("JWT has expired")}function Vs(n){switch(n){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const Ks=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function ee(n){if(!Ks.test(n))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Ne(){const n={};return new Proxy(n,{get:(e,t)=>{if(t==="__isUserNotAvailableProxy")return!0;if(typeof t=="symbol"){const r=t.toString();if(r==="Symbol(Symbol.toPrimitive)"||r==="Symbol(Symbol.toStringTag)"||r==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Hs(n,e){return new Proxy(n,{get:(t,r,s)=>{if(r==="__isInsecureUserWarningProxy")return!0;if(typeof r=="symbol"){const i=r.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(t,r,s)}return!e.value&&typeof r=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(t,r,s)}})}function St(n){return JSON.parse(JSON.stringify(n))}const J=n=>n.msg||n.message||n.error_description||n.error||JSON.stringify(n),Js=[502,503,504];async function kt(n){var e;if(!Us(n))throw new Je(J(n),0);if(Js.includes(n.status))throw new Je(J(n),n.status);let t;try{t=await n.json()}catch(i){throw new Y(J(i),i)}let r;const s=Ws(n);if(s&&s.getTime()>=rr["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new yt(J(t),n.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(r==="session_not_found")throw new N}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new yt(J(t),n.status,t.weak_password.reasons);throw new Es(J(t),n.status||500,r)}const zs=(n,e,t,r)=>{const s={method:n,headers:e?.headers||{}};return n==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),s.body=JSON.stringify(r),Object.assign(Object.assign({},s),t))};async function m(n,e,t,r){var s;const i=Object.assign({},r?.headers);i[He]||(i[He]=rr["2024-01-01"].name),r?.jwt&&(i.Authorization=`Bearer ${r.jwt}`);const o=(s=r?.query)!==null&&s!==void 0?s:{};r?.redirectTo&&(o.redirect_to=r.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await Gs(n,e,t+a,{headers:i,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(l):{data:Object.assign({},l),error:null}}async function Gs(n,e,t,r,s,i){const o=zs(e,r,s,i);let a;try{a=await n(t,Object.assign({},o))}catch(l){throw console.error(l),new Je(J(l),0)}if(a.ok||await kt(a),r?.noResolveJson)return a;try{return await a.json()}catch(l){await kt(l)}}function L(n){var e;let t=null;Xs(n)&&(t=Object.assign({},n),n.expires_at||(t.expires_at=Cs(n.expires_in)));const r=(e=n.user)!==null&&e!==void 0?e:n;return{data:{session:t,user:r},error:null}}function Ot(n){const e=L(n);return!e.error&&n.weak_password&&typeof n.weak_password=="object"&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.message&&typeof n.weak_password.message=="string"&&n.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=n.weak_password),e}function F(n){var e;return{data:{user:(e=n.user)!==null&&e!==void 0?e:n},error:null}}function Ys(n){return{data:n,error:null}}function Qs(n){const{action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:i}=n,o=Ae(n,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:i},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function Tt(n){return n}function Xs(n){return n.access_token&&n.refresh_token&&n.expires_in}const Le=["global","local","others"];class Zs{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=nr(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)}}async signOut(e,t=Le[0]){if(Le.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Le.join(", ")}`);try{return await m(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(y(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await m(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:F})}catch(r){if(y(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{const{options:t}=e,r=Ae(e,["options"]),s=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(s.new_email=r?.newEmail,delete s.newEmail),await m(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:Qs,redirectTo:t?.redirectTo})}catch(t){if(y(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await m(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:F})}catch(t){if(y(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,s,i,o,a,l;try{const c={nextPage:null,lastPage:0,total:0},u=await m(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(i=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:Tt});if(u.error)throw u.error;const d=await u.json(),h=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(l=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return f.length>0&&(f.forEach(g=>{const v=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),p=JSON.parse(g.split(";")[1].split("=")[1]);c[`${p}Page`]=v}),c.total=parseInt(h)),{data:Object.assign(Object.assign({},d),c),error:null}}catch(c){if(y(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){ee(e);try{return await m(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:F})}catch(t){if(y(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){ee(e);try{return await m(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:F})}catch(r){if(y(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){ee(e);try{return await m(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:F})}catch(r){if(y(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){ee(e.userId);try{const{data:t,error:r}=await m(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:t,error:r}}catch(t){if(y(t))return{data:null,error:t};throw t}}async _deleteFactor(e){ee(e.userId),ee(e.id);try{return{data:await m(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(y(t))return{data:null,error:t};throw t}}async _listOAuthClients(e){var t,r,s,i,o,a,l;try{const c={nextPage:null,lastPage:0,total:0},u=await m(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(i=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:Tt});if(u.error)throw u.error;const d=await u.json(),h=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(l=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return f.length>0&&(f.forEach(g=>{const v=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),p=JSON.parse(g.split(";")[1].split("=")[1]);c[`${p}Page`]=v}),c.total=parseInt(h)),{data:Object.assign(Object.assign({},d),c),error:null}}catch(c){if(y(c))return{data:{clients:[]},error:c};throw c}}async _createOAuthClient(e){try{return await m(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(y(t))return{data:null,error:t};throw t}}async _getOAuthClient(e){try{return await m(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(y(t))return{data:null,error:t};throw t}}async _updateOAuthClient(e,t){try{return await m(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(y(r))return{data:null,error:r};throw r}}async _deleteOAuthClient(e){try{return await m(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(y(t))return{data:null,error:t};throw t}}async _regenerateOAuthClientSecret(e){try{return await m(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(y(t))return{data:null,error:t};throw t}}}function At(n={}){return{getItem:e=>n[e]||null,setItem:(e,t)=>{n[e]=t},removeItem:e=>{delete n[e]}}}const te={debug:!!(globalThis&&ir()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class or extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class ei extends or{}async function ti(n,e,t){te.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",n,e);const r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),te.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",n)},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(n,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async s=>{if(s){te.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",n,s.name);try{return await t()}finally{te.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",n,s.name)}}else{if(e===0)throw te.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",n),new ei(`Acquiring an exclusive Navigator LockManager lock "${n}" immediately failed`);if(te.debug)try{const i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null,"  "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}}))}function ri(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function ar(n){if(!/^0x[a-fA-F0-9]{40}$/.test(n))throw new Error(`@supabase/auth-js: Address "${n}" is invalid.`);return n.toLowerCase()}function si(n){return parseInt(n,16)}function ii(n){const e=new TextEncoder().encode(n);return"0x"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}function ni(n){var e;const{chainId:t,domain:r,expirationTime:s,issuedAt:i=new Date,nonce:o,notBefore:a,requestId:l,resources:c,scheme:u,uri:d,version:h}=n;{if(!Number.isInteger(t))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${t}`);if(!r)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(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(!d)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(h!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${h}`);if(!((e=n.statement)===null||e===void 0)&&e.includes(`
`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${n.statement}`)}const f=ar(n.address),g=u?`${u}://${r}`:r,v=n.statement?`${n.statement}
`:"",p=`${g} wants you to sign in with your Ethereum account:
${f}

${v}`;let E=`URI: ${d}
Version: ${h}
Chain ID: ${t}${o?`
Nonce: ${o}`:""}
Issued At: ${i.toISOString()}`;if(s&&(E+=`
Expiration Time: ${s.toISOString()}`),a&&(E+=`
Not Before: ${a.toISOString()}`),l&&(E+=`
Request ID: ${l}`),c){let b=`
Resources:`;for(const _ of c){if(!_||typeof _!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${_}`);b+=`
- ${_}`}E+=b}return`${p}
${E}`}class R extends Error{constructor({message:e,code:t,cause:r,name:s}){var i;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=(i=s??(r instanceof Error?r.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=t}}class Oe extends R{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}function oi({error:n,options:e}){var t,r,s;const{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new R({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else if(n.name==="ConstraintError"){if(((t=i.authenticatorSelection)===null||t===void 0?void 0:t.requireResidentKey)===!0)return new R({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:n});if(e.mediation==="conditional"&&((r=i.authenticatorSelection)===null||r===void 0?void 0:r.userVerification)==="required")return new R({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:n});if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new R({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:n})}else{if(n.name==="InvalidStateError")return new R({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:n});if(n.name==="NotAllowedError")return new R({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="NotSupportedError")return i.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new R({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:n}):new R({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:n});if(n.name==="SecurityError"){const o=window.location.hostname;if(lr(o)){if(i.rp.id!==o)return new R({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new R({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new R({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:n})}else if(n.name==="UnknownError")return new R({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new R({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}function ai({error:n,options:e}){const{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new R({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else{if(n.name==="NotAllowedError")return new R({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="SecurityError"){const r=window.location.hostname;if(lr(r)){if(t.rpId!==r)return new R({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new R({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="UnknownError")return new R({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new R({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}class li{createNewAbortSignal(){if(this.controller){const t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const ci=new li;function ui(n){if(!n)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(n);const{challenge:e,user:t,excludeCredentials:r}=n,s=Ae(n,["challenge","user","excludeCredentials"]),i=ne(e).buffer,o=Object.assign(Object.assign({},t),{id:ne(t.id).buffer}),a=Object.assign(Object.assign({},s),{challenge:i,user:o});if(r&&r.length>0){a.excludeCredentials=new Array(r.length);for(let l=0;l<r.length;l++){const c=r[l];a.excludeCredentials[l]=Object.assign(Object.assign({},c),{id:ne(c.id).buffer,type:c.type||"public-key",transports:c.transports})}}return a}function hi(n){if(!n)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(n);const{challenge:e,allowCredentials:t}=n,r=Ae(n,["challenge","allowCredentials"]),s=ne(e).buffer,i=Object.assign(Object.assign({},r),{challenge:s});if(t&&t.length>0){i.allowCredentials=new Array(t.length);for(let o=0;o<t.length;o++){const a=t[o];i.allowCredentials[o]=Object.assign(Object.assign({},a),{id:ne(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return i}function di(n){var e;if("toJSON"in n&&typeof n.toJSON=="function")return n.toJSON();const t=n;return{id:n.id,rawId:n.id,response:{attestationObject:Q(new Uint8Array(n.response.attestationObject)),clientDataJSON:Q(new Uint8Array(n.response.clientDataJSON))},type:"public-key",clientExtensionResults:n.getClientExtensionResults(),authenticatorAttachment:(e=t.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function fi(n){var e;if("toJSON"in n&&typeof n.toJSON=="function")return n.toJSON();const t=n,r=n.getClientExtensionResults(),s=n.response;return{id:n.id,rawId:n.id,response:{authenticatorData:Q(new Uint8Array(s.authenticatorData)),clientDataJSON:Q(new Uint8Array(s.clientDataJSON)),signature:Q(new Uint8Array(s.signature)),userHandle:s.userHandle?Q(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:r,authenticatorAttachment:(e=t.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function lr(n){return n==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(n)}function Rt(){var n,e;return!!(C()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((n=navigator?.credentials)===null||n===void 0?void 0:n.create)=="function"&&typeof((e=navigator?.credentials)===null||e===void 0?void 0:e.get)=="function")}async function gi(n){try{const e=await navigator.credentials.create(n);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Oe("Browser returned unexpected credential type",e)}:{data:null,error:new Oe("Empty credential response",e)}}catch(e){return{data:null,error:oi({error:e,options:n})}}}async function pi(n){try{const e=await navigator.credentials.get(n);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Oe("Browser returned unexpected credential type",e)}:{data:null,error:new Oe("Empty credential response",e)}}catch(e){return{data:null,error:ai({error:e,options:n})}}}const _i={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},vi={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Te(...n){const e=s=>s!==null&&typeof s=="object"&&!Array.isArray(s),t=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),r={};for(const s of n)if(s)for(const i in s){const o=s[i];if(o!==void 0)if(Array.isArray(o))r[i]=o;else if(t(o))r[i]=o;else if(e(o)){const a=r[i];e(a)?r[i]=Te(a,o):r[i]=Te(o)}else r[i]=o}return r}function wi(n,e){return Te(_i,n,e||{})}function yi(n,e){return Te(vi,n,e||{})}class bi{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:r,signal:s},i){try{const{data:o,error:a}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!o)return{data:null,error:a};const l=s??ci.createNewAbortSignal();if(o.webauthn.type==="create"){const{user:c}=o.webauthn.credential_options.publicKey;c.name||(c.name=`${c.id}:${r}`),c.displayName||(c.displayName=c.name)}switch(o.webauthn.type){case"create":{const c=wi(o.webauthn.credential_options.publicKey,i?.create),{data:u,error:d}=await gi({publicKey:c,signal:l});return u?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:u}},error:null}:{data:null,error:d}}case"request":{const c=yi(o.webauthn.credential_options.publicKey,i?.request),{data:u,error:d}=await pi(Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:c,signal:l}));return u?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:u}},error:null}:{data:null,error:d}}}}catch(o){return y(o)?{data:null,error:o}:{data:null,error:new Y("Unexpected error in challenge",o)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new de("rpId is required for WebAuthn authentication")};try{if(!Rt())return{data:null,error:new Y("Browser does not support WebAuthn",null)};const{data:o,error:a}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:i});if(!o)return{data:null,error:a};const{webauthn:l}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:l.type,rpId:t,rpOrigins:r,credential_response:l.credential_response}})}catch(o){return y(o)?{data:null,error:o}:{data:null,error:new Y("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new de("rpId is required for WebAuthn registration")};try{if(!Rt())return{data:null,error:new Y("Browser does not support WebAuthn",null)};const{data:o,error:a}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(u=>{var d;return(d=u.data)===null||d===void 0?void 0:d.all.find(h=>h.factor_type==="webauthn"&&h.friendly_name===e&&h.status!=="unverified")}).then(u=>u?this.client.mfa.unenroll({factorId:u?.id}):void 0),{data:null,error:a};const{data:l,error:c}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:i});return l?this._verify({factorId:o.id,challengeId:l.challengeId,webauthn:{rpId:t,rpOrigins:r,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:c}}catch(o){return y(o)?{data:null,error:o}:{data:null,error:new Y("Unexpected error in register",o)}}}}ri();const mi={url:vs,storageKey:ws,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:ys,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1};async function Pt(n,e,t){return await t()}const re={};class fe{get jwks(){var e,t;return(t=(e=re[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){re[this.storageKey]=Object.assign(Object.assign({},re[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=re[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){re[this.storageKey]=Object.assign(Object.assign({},re[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,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;const i=Object.assign(Object.assign({},mi),e);if(this.storageKey=i.storageKey,this.instanceID=(t=fe.nextInstanceID[this.storageKey])!==null&&t!==void 0?t:0,fe.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&C()){const o=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.admin=new Zs({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=nr(i.fetch),this.lock=i.lock||Pt,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,i.lock?this.lock=i.lock:C()&&(!((r=globalThis?.navigator)===null||r===void 0)&&r.locks)?this.lock=ti:this.lock=Pt,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new bi(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:ir()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=At(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=At(this.memoryStorage)),C()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o),await this._notifyAllSubscribers(o.data.event,o.data.session,!1)})}this.initialize()}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${tr}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let t={},r="none";if(C()&&(t=$s(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),C()&&this.detectSessionInUrl&&r!=="none"){const{data:s,error:i}=await this._getSessionFromURL(t,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Os(i)){const l=(e=i.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:i}}return await this._removeSession(),{error:i}}const{session:o,redirectType:a}=s;return this._debug("#_initialize()","detected session in URL",o,"redirect type",a),await this._saveSession(o),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return y(t)?this._returnResult({error:t}):this._returnResult({error:new Y("Unexpected error during initialization",t)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{const i=await m(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(s=e?.options)===null||s===void 0?void 0:s.captchaToken}},xform:L}),{data:o,error:a}=i;if(a||!o)return this._returnResult({data:{user:null,session:null},error:a});const l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if(y(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var t,r,s;try{let i;if("email"in e){const{email:u,password:d,options:h}=e;let f=null,g=null;this.flowType==="pkce"&&([f,g]=await Z(this.storage,this.storageKey)),i=await m(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:h?.emailRedirectTo,body:{email:u,password:d,data:(t=h?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:h?.captchaToken},code_challenge:f,code_challenge_method:g},xform:L})}else if("phone"in e){const{phone:u,password:d,options:h}=e;i=await m(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:d,data:(r=h?.data)!==null&&r!==void 0?r:{},channel:(s=h?.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:h?.captchaToken}},xform:L})}else throw new Ee("You must provide either an email or phone number and a password");const{data:o,error:a}=i;if(a||!o)return this._returnResult({data:{user:null,session:null},error:a});const l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if(y(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(e){try{let t;if("email"in e){const{email:i,password:o,options:a}=e;t=await m(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Ot})}else if("phone"in e){const{phone:i,password:o,options:a}=e;t=await m(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Ot})}else throw new Ee("You must provide either an email or phone number and a password");const{data:r,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){const i=new X;return this._returnResult({data:{user:null,session:null},error:i})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(t){if(y(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOAuth(e){var t,r,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,s,i,o,a,l,c,u,d,h;let f,g;if("message"in e)f=e.message,g=e.signature;else{const{chain:v,wallet:p,statement:E,options:b}=e;let _;if(C())if(typeof p=="object")_=p;else{const B=window;if("ethereum"in B&&typeof B.ethereum=="object"&&"request"in B.ethereum&&typeof B.ethereum.request=="function")_=B.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof p!="object"||!b?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");_=p}const S=new URL((t=b?.url)!==null&&t!==void 0?t:window.location.href),A=await _.request({method:"eth_requestAccounts"}).then(B=>B).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!A||A.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const k=ar(A[0]);let P=(r=b?.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!P){const B=await _.request({method:"eth_chainId"});P=si(B)}const M={domain:S.host,address:k,statement:E,uri:S.href,version:"1",chainId:P,nonce:(s=b?.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(o=(i=b?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=b?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=b?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(c=b?.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(u=b?.signInWithEthereum)===null||u===void 0?void 0:u.resources};f=ni(M),g=await _.request({method:"personal_sign",params:[ii(f),k]})}try{const{data:v,error:p}=await m(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:f,signature:g},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(h=e.options)===null||h===void 0?void 0:h.captchaToken}}:null),xform:L});if(p)throw p;if(!v||!v.session||!v.user){const E=new X;return this._returnResult({data:{user:null,session:null},error:E})}return v.session&&(await this._saveSession(v.session),await this._notifyAllSubscribers("SIGNED_IN",v.session)),this._returnResult({data:Object.assign({},v),error:p})}catch(v){if(y(v))return this._returnResult({data:{user:null,session:null},error:v});throw v}}async signInWithSolana(e){var t,r,s,i,o,a,l,c,u,d,h,f;let g,v;if("message"in e)g=e.message,v=e.signature;else{const{chain:p,wallet:E,statement:b,options:_}=e;let S;if(C())if(typeof E=="object")S=E;else{const k=window;if("solana"in k&&typeof k.solana=="object"&&("signIn"in k.solana&&typeof k.solana.signIn=="function"||"signMessage"in k.solana&&typeof k.solana.signMessage=="function"))S=k.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof E!="object"||!_?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");S=E}const A=new URL((t=_?.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in S&&S.signIn){const k=await S.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},_?.signInWithSolana),{version:"1",domain:A.host,uri:A.href}),b?{statement:b}:null));let P;if(Array.isArray(k)&&k[0]&&typeof k[0]=="object")P=k[0];else if(k&&typeof k=="object"&&"signedMessage"in k&&"signature"in k)P=k;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in P&&"signature"in P&&(typeof P.signedMessage=="string"||P.signedMessage instanceof Uint8Array)&&P.signature instanceof Uint8Array)g=typeof P.signedMessage=="string"?P.signedMessage:new TextDecoder().decode(P.signedMessage),v=P.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in S)||typeof S.signMessage!="function"||!("publicKey"in S)||typeof S!="object"||!S.publicKey||!("toBase58"in S.publicKey)||typeof S.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");g=[`${A.host} wants you to sign in with your Solana account:`,S.publicKey.toBase58(),...b?["",b,""]:[""],"Version: 1",`URI: ${A.href}`,`Issued At: ${(s=(r=_?.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=_?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${_.signInWithSolana.notBefore}`]:[],...!((o=_?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${_.signInWithSolana.expirationTime}`]:[],...!((a=_?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${_.signInWithSolana.chainId}`]:[],...!((l=_?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${_.signInWithSolana.nonce}`]:[],...!((c=_?.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${_.signInWithSolana.requestId}`]:[],...!((d=(u=_?.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||d===void 0)&&d.length?["Resources",..._.signInWithSolana.resources.map(P=>`- ${P}`)]:[]].join(`
`);const k=await S.signMessage(new TextEncoder().encode(g),"utf8");if(!k||!(k instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");v=k}}try{const{data:p,error:E}=await m(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:g,signature:Q(v)},!((h=e.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:L});if(E)throw E;if(!p||!p.session||!p.user){const b=new X;return this._returnResult({data:{user:null,session:null},error:b})}return p.session&&(await this._saveSession(p.session),await this._notifyAllSubscribers("SIGNED_IN",p.session)),this._returnResult({data:Object.assign({},p),error:E})}catch(p){if(y(p))return this._returnResult({data:{user:null,session:null},error:p});throw p}}async _exchangeCodeForSession(e){const t=await H(this.storage,`${this.storageKey}-code-verifier`),[r,s]=(t??"").split("/");try{const{data:i,error:o}=await m(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:L});if(await W(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!i||!i.session||!i.user){const a=new X;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:s??null}),error:o})}catch(i){if(y(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{const{options:t,provider:r,token:s,access_token:i,nonce:o}=e,a=await m(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:L}),{data:l,error:c}=a;if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l||!l.session||!l.user){const u=new X;return this._returnResult({data:{user:null,session:null},error:u})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:c})}catch(t){if(y(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOtp(e){var t,r,s,i,o;try{if("email"in e){const{email:a,options:l}=e;let c=null,u=null;this.flowType==="pkce"&&([c,u]=await Z(this.storage,this.storageKey));const{error:d}=await m(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=l?.data)!==null&&t!==void 0?t:{},create_user:(r=l?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:c,code_challenge_method:u},redirectTo:l?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:d})}if("phone"in e){const{phone:a,options:l}=e,{data:c,error:u}=await m(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(s=l?.data)!==null&&s!==void 0?s:{},create_user:(i=l?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:c?.message_id},error:u})}throw new Ee("You must provide either an email or phone number.")}catch(a){if(y(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var t,r;try{let s,i;"options"in e&&(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(r=e.options)===null||r===void 0?void 0:r.captchaToken);const{data:o,error:a}=await m(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:L});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");const l=o.session,c=o.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(s){if(y(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(e){var t,r,s,i,o;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await Z(this.storage,this.storageKey));const c=await m(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),!((s=e?.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:l}),headers:this.headers,xform:Ys});return!((i=c.data)===null||i===void 0)&&i.url&&C()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(a){if(y(a))return this._returnResult({data:null,error:a});throw a}}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:r}=e;if(r)throw r;if(!t)throw new N;const{error:s}=await m(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(y(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const t=`${this.url}/resend`;if("email"in e){const{email:r,type:s,options:i}=e,{error:o}=await m(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:i?.captchaToken}},redirectTo:i?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in e){const{phone:r,type:s,options:i}=e,{data:o,error:a}=await m(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:i?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o?.message_id},error:a})}throw new Ee("You must provide either an email or phone number and a type")}catch(t){if(y(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),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 r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){const s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const t=await H(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const r=e.expires_at?e.expires_at*1e3-Date.now()<$e:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.userStorage){const o=await H(this.userStorage,this.storageKey+"-user");o?.user?e.user=o.user:e.user=Ne()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const o={value:this.suppressGetSessionWarning};e.user=Hs(e.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await m(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:F}):await this._useSession(async t=>{var r,s,i;const{data:o,error:a}=t;if(a)throw a;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new N}:await m(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:F})})}catch(t){if(y(t))return ks(t)&&(await this._removeSession(),await W(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:t});throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{const{data:s,error:i}=r;if(i)throw i;if(!s.session)throw new N;const o=s.session;let a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await Z(this.storage,this.storageKey));const{data:c,error:u}=await m(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:F});if(u)throw u;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(r){if(y(r))return this._returnResult({data:{user:null},error:r});throw r}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new N;const t=Date.now()/1e3;let r=t,s=!0,i=null;const{payload:o}=xe(e.access_token);if(o.exp&&(r=o.exp,s=r<=t),s){const{data:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a)return{data:{user:null,session:null},error:null};i=a}else{const{data:a,error:l}=await this._getUser(e.access_token);if(l)throw l;i={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(t){if(y(t))return this._returnResult({data:{session:null,user:null},error:t});throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){const{data:o,error:a}=t;if(a)throw a;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new N;const{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(t){if(y(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async _getSessionFromURL(e,t){try{if(!C())throw new Se("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Se(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new wt("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Se("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new wt("No code detected.");const{data:b,error:_}=await this._exchangeCodeForSession(e.code);if(_)throw _;const S=new URL(window.location.href);return S.searchParams.delete("code"),window.history.replaceState(window.history.state,"",S.toString()),{data:{session:b.session,redirectType:null},error:null}}const{provider_token:r,provider_refresh_token:s,access_token:i,refresh_token:o,expires_in:a,expires_at:l,token_type:c}=e;if(!i||!a||!o||!c)throw new Se("No session defined in URL");const u=Math.round(Date.now()/1e3),d=parseInt(a);let h=u+d;l&&(h=parseInt(l));const f=h-u;f*1e3<=se&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${d}s`);const g=h-d;u-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,h,u):u-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",g,h,u);const{data:v,error:p}=await this._getUser(i);if(p)throw p;const E={provider_token:r,provider_refresh_token:s,access_token:i,expires_in:d,expires_at:h,refresh_token:o,token_type:c,user:v.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:E,redirectType:e.type},error:null})}catch(r){if(y(r))return this._returnResult({data:{session:null,redirectType:null},error:r});throw r}}_isImplicitGrantCallback(e){return!!(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await H(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;const{data:s,error:i}=t;if(i)return this._returnResult({error:i});const o=(r=s.session)===null||r===void 0?void 0:r.access_token;if(o){const{error:a}=await this.admin.signOut(o,e);if(a&&!(Ss(a)&&(a.status===404||a.status===401||a.status===403)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await W(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const t=Is(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{const{data:{session:i},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null;this.flowType==="pkce"&&([r,s]=await Z(this.storage,this.storageKey,!0));try{return await m(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(i){if(y(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{const{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(t){if(y(t))return this._returnResult({data:null,error:t});throw t}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{const{data:r,error:s}=await this._useSession(async i=>{var o,a,l,c,u;const{data:d,error:h}=i;if(h)throw h;const f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await m(this.fetch,"GET",f,{headers:this.headers,jwt:(u=(c=d.session)===null||c===void 0?void 0:c.access_token)!==null&&u!==void 0?u:void 0})});if(s)throw s;return C()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(r?.url),this._returnResult({data:{provider:e.provider,url:r?.url},error:null})}catch(r){if(y(r))return this._returnResult({data:{provider:e.provider,url:null},error:r});throw r}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{const{error:s,data:{session:i}}=t;if(s)throw s;const{options:o,provider:a,token:l,access_token:c,nonce:u}=e,d=await m(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(r=i?.access_token)!==null&&r!==void 0?r:void 0,body:{provider:a,id_token:l,access_token:c,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:L}),{data:h,error:f}=d;return f?this._returnResult({data:{user:null,session:null},error:f}):!h||!h.session||!h.user?this._returnResult({data:{user:null,session:null},error:new X}):(h.session&&(await this._saveSession(h.session),await this._notifyAllSubscribers("USER_UPDATED",h.session)),this._returnResult({data:h,error:f}))}catch(s){if(y(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;const{data:i,error:o}=t;if(o)throw o;return await m(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(r=i.session)===null||r===void 0?void 0:r.access_token)!==null&&s!==void 0?s:void 0})})}catch(t){if(y(t))return this._returnResult({data:null,error:t});throw t}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const r=Date.now();return await Ns(async s=>(s>0&&await xs(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await m(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:L})),(s,i)=>{const o=200*Math.pow(2,s);return i&&Ue(i)&&Date.now()+o-r<se})}catch(r){if(this._debug(t,"error",r),y(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),C()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e,t;const r="#_recoverAndRefresh()";this._debug(r,"begin");try{const s=await H(this.storage,this.storageKey);if(s&&this.userStorage){let o=await H(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:s.user},await ie(this.userStorage,this.storageKey+"-user",o)),s.user=(e=o?.user)!==null&&e!==void 0?e:Ne()}else if(s&&!s.user&&!s.user){const o=await H(this.storage,this.storageKey+"-user");o&&o?.user?(s.user=o.user,await W(this.storage,this.storageKey+"-user"),await ie(this.storage,this.storageKey,s)):s.user=Ne()}if(this._debug(r,"session from storage",s),!this._isValidSession(s)){this._debug(r,"session is not valid"),s!==null&&await this._removeSession();return}const i=((t=s.expires_at)!==null&&t!==void 0?t:1/0)*1e3-Date.now()<$e;if(this._debug(r,`session has${i?"":" not"} expired with margin of ${$e}s`),i){if(this.autoRefreshToken&&s.refresh_token){const{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),Ue(o)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(s.user&&s.user.__isUserNotAvailableProxy===!0)try{const{data:o,error:a}=await this._getUser(s.access_token);!a&&o?.user?(s.user=o.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(r,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(r,"error",s),console.error(s);return}finally{this._debug(r,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new N;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new Re;const{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new N;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);const a={data:i.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(i){if(this._debug(s,"error",i),y(i)){const o={data:null,error:i};return Ue(i)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(i),i}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){const s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});const i=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(l){i.push(l)}});if(await Promise.all(o),i.length>0){for(let a=0;a<i.length;a+=1)console.error(i[a]);throw i[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0;const t=Object.assign({},e),r=t.user&&t.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!r&&t.user&&await ie(this.userStorage,this.storageKey+"-user",{user:t.user});const s=Object.assign({},t);delete s.user;const i=St(s);await ie(this.storage,this.storageKey,i)}else{const s=St(t);await ie(this.storage,this.storageKey,s)}}async _removeSession(){this._debug("#_removeSession()"),await W(this.storage,this.storageKey),await W(this.storage,this.storageKey+"-code-verifier"),await W(this.storage,this.storageKey+"-user"),this.userStorage&&await W(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&C()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),se);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async t=>{const{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const s=Math.floor((r.expires_at*1e3-e)/se);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${se}ms, refresh threshold is ${Ke} ticks`),s<=Ke&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof or)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!C()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){const s=[`provider=${encodeURIComponent(t)}`];if(r?.redirectTo&&s.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r?.scopes&&s.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){const[i,o]=await Z(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});s.push(a.toString())}if(r?.queryParams){const i=new URLSearchParams(r.queryParams);s.push(i.toString())}return r?.skipBrowserRedirect&&s.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;const{data:s,error:i}=t;return i?this._returnResult({data:null,error:i}):await m(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(y(t))return this._returnResult({data:null,error:t});throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;const{data:i,error:o}=t;if(o)return this._returnResult({data:null,error:o});const a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:c}=await m(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token});return c?this._returnResult({data:null,error:c}):(e.factorType==="totp"&&l.type==="totp"&&(!((s=l?.totp)===null||s===void 0)&&s.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(t){if(y(t))return this._returnResult({data:null,error:t});throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;const{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});const o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?di(e.webauthn.credential_response):fi(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:l}=await m(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),this._returnResult({data:a,error:l}))})}catch(t){if(y(t))return this._returnResult({data:null,error:t});throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;const{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});const o=await m(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});if(o.error)return o;const{data:a}=o;if(a.type!=="webauthn")return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:ui(a.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:hi(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(t){if(y(t))return this._returnResult({data:null,error:t});throw t}})}async _challengeAndVerify(e){const{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;const{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};const s={all:[],phone:[],totp:[],webauthn:[]};for(const i of(e=t?.factors)!==null&&e!==void 0?e:[])s.all.push(i),i.status==="verified"&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(){var e,t;const{data:{session:r},error:s}=await this.getSession();if(s)return this._returnResult({data:null,error:s});if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:i}=xe(r.access_token);let o=null;i.aal&&(o=i.aal);let a=o;((t=(e=r.user.factors)===null||e===void 0?void 0:e.filter(u=>u.status==="verified"))!==null&&t!==void 0?t:[]).length>0&&(a="aal2");const c=i.amr||[];return{data:{currentLevel:o,nextLevel:a,currentAuthenticationMethods:c},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{const{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await m(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new N})})}catch(t){if(y(t))return this._returnResult({data:null,error:t});throw t}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new N});const o=await m(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&C()&&!t?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new N});const o=await m(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&C()&&!t?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(a=>a.kid===e);if(r)return r;const s=Date.now();if(r=this.jwks.keys.find(a=>a.kid===e),r&&this.jwks_cached_at+ms>s)return r;const{data:i,error:o}=await m(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,r=i.keys.find(a=>a.kid===e),!r)?null:r}async getClaims(e,t={}){try{let r=e;if(!r){const{data:f,error:g}=await this.getSession();if(g||!f.session)return this._returnResult({data:null,error:g});r=f.session.access_token}const{header:s,payload:i,signature:o,raw:{header:a,payload:l}}=xe(r);t?.allowExpired||Fs(i.exp);const c=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,t?.keys?{keys:t.keys}:t?.jwks);if(!c){const{error:f}=await this.getUser(r);if(f)throw f;return{data:{claims:i,header:s,signature:o},error:null}}const u=Vs(s.alg),d=await crypto.subtle.importKey("jwk",c,u,!0,["verify"]);if(!await crypto.subtle.verify(u,d,o,js(`${a}.${l}`)))throw new ze("Invalid JWT signature");return{data:{claims:i,header:s,signature:o},error:null}}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}}fe.nextInstanceID={};const Ei=fe;class Si extends Ei{constructor(e){super(e)}}class ki{constructor(e,t,r){var s,i,o;this.supabaseUrl=e,this.supabaseKey=t;const a=_s(e);if(!t)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",a),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",a),this.storageUrl=new URL("storage/v1",a),this.functionsUrl=new URL("functions/v1",a);const l=`sb-${a.hostname.split(".")[0]}-auth-token`,c={db:ls,realtime:us,auth:Object.assign(Object.assign({},cs),{storageKey:l}),global:as},u=ps(r??{},c);this.storageKey=(s=u.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(i=u.global.headers)!==null&&i!==void 0?i:{},u.accessToken?(this.accessToken=u.accessToken,this.auth=new Proxy({},{get:(d,h)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(h)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((o=u.auth)!==null&&o!==void 0?o:{},this.headers,u.global.fetch),this.fetch=fs(t,this._getAccessToken.bind(this),u.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},u.realtime)),this.accessToken&&this.accessToken().then(d=>this.realtime.setAuth(d)).catch(d=>console.warn("Failed to set initial Realtime auth token:",d)),this.rest=new vr(new URL("rest/v1",a).href,{headers:this.headers,schema:u.db.schema,fetch:this.fetch}),this.storage=new is(this.storageUrl.href,this.headers,this.fetch,r?.storage),u.accessToken||this._listenForAuthEvents()}get functions(){return new gr(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e,t;if(this.accessToken)return await this.accessToken();const{data:r}=await this.auth.getSession();return(t=(e=r.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:this.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:i,storageKey:o,flowType:a,lock:l,debug:c,throwOnError:u},d,h){const f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Si({url:this.authUrl.href,headers:Object.assign(Object.assign({},f),d),storageKey:o,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:i,flowType:a,lock:l,debug:c,throwOnError:u,fetch:h,hasCustomAuthorizationHeader:Object.keys(this.headers).some(g=>g.toLowerCase()==="authorization")})}_initRealtimeClient(e){return new Ur(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,r)=>{this._handleTokenChanged(t,"CLIENT",r?.access_token)})}_handleTokenChanged(e,t,r){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const Oi=(n,e,t)=>new ki(n,e,t);function Ti(){if(typeof window<"u"||typeof process>"u")return!1;const n=process.version;if(n==null)return!1;const e=n.match(/^v(\d+)\./);return e?parseInt(e[1],10)<=18:!1}Ti()&&console.warn("⚠️  Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");const Ai="https://helubtnxspmlohllahhh.supabase.co",Ri="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImhlbHVidG54c3BtbG9obGxhaGhoIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjI5NjY4ODEsImV4cCI6MjA3ODU0Mjg4MX0.9P2XBlXFlpv6dZ7pzVffWWX3HcDTHv31hrbYfWWQ1QE",Ni=Oi(Ai,Ri,{auth:{storage:localStorage,persistSession:!0,autoRefreshToken:!0}});export{Ni as s};