import{j as e,P as t,ac as r,ad as s,ae as i}from"./ui-vendor-Dyu0xMC9.js";import{r as n,k as o}from"./react-vendor-BiKEbLqf.js";import{c as a,D as l,_ as c}from"./index-D2mkZfe8.js";function h(e,t){for(var r=0;r<t.length;r++){const s=t[r];if("string"!=typeof s&&!Array.isArray(s))for(const t in s)if("default"!==t&&!(t in e)){const r=Object.getOwnPropertyDescriptor(s,t);r&&Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>s[t]})}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}const u="/assets/allerin-logo-UOCkK1Ba.webp",d=n.forwardRef(({className:t,type:r,...s},i)=>e.jsx("input",{type:r,className:a("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",t),ref:i,...s}));d.displayName="Input";var f=n.forwardRef((r,s)=>e.jsx(t.label,{...r,ref:s,onMouseDown:e=>{e.target.closest("button, input, select, textarea")||(r.onMouseDown?.(e),!e.defaultPrevented&&e.detail>1&&e.preventDefault())}}));f.displayName="Label";var p=f;const g=l("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),w=n.forwardRef(({className:t,...r},s)=>e.jsx(p,{ref:s,className:a(g(),t),...r}));w.displayName=p.displayName;class v extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}}class y extends v{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class m extends v{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class b extends v{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var _,k;(k=_||(_={})).Any="any",k.ApNortheast1="ap-northeast-1",k.ApNortheast2="ap-northeast-2",k.ApSouth1="ap-south-1",k.ApSoutheast1="ap-southeast-1",k.ApSoutheast2="ap-southeast-2",k.CaCentral1="ca-central-1",k.EuCentral1="eu-central-1",k.EuWest1="eu-west-1",k.EuWest2="eu-west-2",k.EuWest3="eu-west-3",k.SaEast1="sa-east-1",k.UsEast1="us-east-1",k.UsWest1="us-west-1",k.UsWest2="us-west-2";class S{constructor(e,{headers:t={},customFetch:r,region:s=_.Any}={}){this.url=e,this.headers=t,this.region=s,this.fetch=(e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>c(async()=>{const{default:e}=await Promise.resolve().then(()=>D);return{default:e}},void 0).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)})(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return r(this,arguments,void 0,function*(e,t={}){var r;try{const{headers:s,method:i,body:n,signal:o}=t;let a={},{region:l}=t;l||(l=this.region);const c=new URL(`${this.url}/${e}`);let h;l&&"any"!==l&&(a["x-region"]=l,c.searchParams.set("forceFunctionRegion",l)),n&&(s&&!Object.prototype.hasOwnProperty.call(s,"Content-Type")||!s)?"undefined"!=typeof Blob&&n instanceof Blob||n instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",h=n):"string"==typeof n?(a["Content-Type"]="text/plain",h=n):"undefined"!=typeof FormData&&n instanceof FormData?h=n:(a["Content-Type"]="application/json",h=JSON.stringify(n)):h=n;const u=yield this.fetch(c.toString(),{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),s),body:h,signal:o}).catch(e=>{if("AbortError"===e.name)throw e;throw new y(e)}),d=u.headers.get("x-relay-error");if(d&&"true"===d)throw new m(u);if(!u.ok)throw new b(u);let f,p=(null!==(r=u.headers.get("Content-Type"))&&void 0!==r?r:"text/plain").split(";")[0].trim();return f="application/json"===p?yield u.json():"application/octet-stream"===p||"application/pdf"===p?yield u.blob():"text/event-stream"===p?u:"multipart/form-data"===p?yield u.formData():yield u.text(),{data:f,error:null,response:u}}catch(s){return s instanceof Error&&"AbortError"===s.name?{data:null,error:new y(s)}:{data:null,error:s,response:s instanceof b||s instanceof m?s.context:void 0}}})}}var E={};const T=o(s);var O={},j={},I={},P={},R={},A=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("unable to locate global object")}();const $=A.fetch,C=A.fetch.bind(A),x=A.Headers,N=A.Request,U=A.Response,D=Object.freeze(Object.defineProperty({__proto__:null,Headers:x,Request:N,Response:U,default:C,fetch:$},Symbol.toStringTag,{value:"Module"})),L=o(D);var B,q,W,K,M,V,F={};function J(){if(B)return F;B=1,Object.defineProperty(F,"__esModule",{value:!0});class e extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}}return F.default=e,F}function H(){if(q)return R;q=1,Object.defineProperty(R,"__esModule",{value:!0});const e=T,t=e.__importDefault(L),r=e.__importDefault(J());return R.default=class{constructor(e){var r,s;this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=null!==(r=e.shouldThrowOnError)&&void 0!==r&&r,this.signal=e.signal,this.isMaybeSingle=null!==(s=e.isMaybeSingle)&&void 0!==s&&s,e.fetch?this.fetch=e.fetch:"undefined"==typeof fetch?this.fetch=t.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}then(e,t){void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),"GET"!==this.method&&"HEAD"!==this.method&&this.headers.set("Content-Type","application/json");let s=(0,this.fetch)(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async e=>{var t,s,i,n;let o=null,a=null,l=null,c=e.status,h=e.statusText;if(e.ok){if("HEAD"!==this.method){const r=await e.text();""===r||(a="text/csv"===this.headers.get("Accept")||this.headers.get("Accept")&&(null===(t=this.headers.get("Accept"))||void 0===t?void 0:t.includes("application/vnd.pgrst.plan+text"))?r:JSON.parse(r))}const r=null===(s=this.headers.get("Prefer"))||void 0===s?void 0:s.match(/count=(exact|planned|estimated)/),n=null===(i=e.headers.get("content-range"))||void 0===i?void 0:i.split("/");r&&n&&n.length>1&&(l=parseInt(n[1])),this.isMaybeSingle&&"GET"===this.method&&Array.isArray(a)&&(a.length>1?(o={code:"PGRST116",details:`Results contain ${a.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},a=null,l=null,c=406,h="Not Acceptable"):a=1===a.length?a[0]:null)}else{const t=await e.text();try{o=JSON.parse(t),Array.isArray(o)&&404===e.status&&(a=[],o=null,c=200,h="OK")}catch(u){404===e.status&&""===t?(c=204,h="No Content"):o={message:t}}if(o&&this.isMaybeSingle&&(null===(n=null==o?void 0:o.details)||void 0===n?void 0:n.includes("0 rows"))&&(o=null,c=200,h="OK"),o&&this.shouldThrowOnError)throw new r.default(o)}return{error:o,data:a,count:l,status:c,statusText:h}});return this.shouldThrowOnError||(s=s.catch(e=>{var t,r,s;return{error:{message:`${null!==(t=null==e?void 0:e.name)&&void 0!==t?t:"FetchError"}: ${null==e?void 0:e.message}`,details:`${null!==(r=null==e?void 0:e.stack)&&void 0!==r?r:""}`,hint:"",code:`${null!==(s=null==e?void 0:e.code)&&void 0!==s?s:""}`},data:null,count:null,status:0,statusText:""}})),s.then(e,t)}returns(){return this}overrideTypes(){return this}},R}function z(){if(W)return P;W=1,Object.defineProperty(P,"__esModule",{value:!0});const e=T.__importDefault(H());class t extends e.default{select(e){let t=!1;const r=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:s,referencedTable:i=s}={}){const n=i?`${i}.order`:"order",o=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${o?`${o},`:""}${e}.${t?"asc":"desc"}${void 0===r?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){const s=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:s=r}={}){const i=void 0===s?"offset":`${s}.offset`,n=void 0===s?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(n,""+(t-e+1)),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return"GET"===this.method?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:s=!1,wal:i=!1,format:n="text"}={}){var o;const a=[e?"analyze":null,t?"verbose":null,r?"settings":null,s?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=null!==(o=this.headers.get("Accept"))&&void 0!==o?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${n}; for="${l}"; options=${a};`),this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}}return P.default=t,P}function G(){if(K)return I;K=1,Object.defineProperty(I,"__esModule",{value:!0});const e=T.__importDefault(z()),t=new RegExp("[,()]");class r extends e.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,r){const s=Array.from(new Set(r)).map(e=>"string"==typeof e&&t.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`in.(${s})`),this}contains(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return"string"==typeof t?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:s}={}){let i="";"plain"===s?i="pl":"phrase"===s?i="ph":"websearch"===s&&(i="w");const n=void 0===r?"":`(${r})`;return this.url.searchParams.append(e,`${i}fts${n}.${t}`),this}match(e){return Object.entries(e).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){const s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}}return I.default=r,I}function Y(){if(M)return j;M=1,Object.defineProperty(j,"__esModule",{value:!0});const e=T.__importDefault(G());return j.default=class{constructor(e,{headers:t={},schema:r,fetch:s}){this.url=e,this.headers=new Headers(t),this.schema=r,this.fetch=s}select(t,r){const{head:s=!1,count:i}=null!=r?r:{},n=s?"HEAD":"GET";let o=!1;const a=(null!=t?t:"*").split("").map(e=>/\s/.test(e)&&!o?"":('"'===e&&(o=!o),e)).join("");return this.url.searchParams.set("select",a),i&&this.headers.append("Prefer",`count=${i}`),new e.default({method:n,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(t,{count:r,defaultToNull:s=!0}={}){var i;if(r&&this.headers.append("Prefer",`count=${r}`),s||this.headers.append("Prefer","missing=default"),Array.isArray(t)){const e=t.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(e.length>0){const t=[...new Set(e)].map(e=>`"${e}"`);this.url.searchParams.set("columns",t.join(","))}}return new e.default({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:null!==(i=this.fetch)&&void 0!==i?i:fetch})}upsert(t,{onConflict:r,ignoreDuplicates:s=!1,count:i,defaultToNull:n=!0}={}){var o;if(this.headers.append("Prefer",`resolution=${s?"ignore":"merge"}-duplicates`),void 0!==r&&this.url.searchParams.set("on_conflict",r),i&&this.headers.append("Prefer",`count=${i}`),n||this.headers.append("Prefer","missing=default"),Array.isArray(t)){const e=t.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(e.length>0){const t=[...new Set(e)].map(e=>`"${e}"`);this.url.searchParams.set("columns",t.join(","))}}return new e.default({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:null!==(o=this.fetch)&&void 0!==o?o:fetch})}update(t,{count:r}={}){var s;return r&&this.headers.append("Prefer",`count=${r}`),new e.default({method:"PATCH",url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:null!==(s=this.fetch)&&void 0!==s?s:fetch})}delete({count:t}={}){var r;return t&&this.headers.append("Prefer",`count=${t}`),new e.default({method:"DELETE",url:this.url,headers:this.headers,schema:this.schema,fetch:null!==(r=this.fetch)&&void 0!==r?r:fetch})}},j}Object.defineProperty(E,"__esModule",{value:!0});var Q=E.PostgrestError=E.PostgrestBuilder=E.PostgrestTransformBuilder=E.PostgrestFilterBuilder=E.PostgrestQueryBuilder=E.PostgrestClient=void 0;const X=T,Z=X.__importDefault(function(){if(V)return O;V=1,Object.defineProperty(O,"__esModule",{value:!0});const e=T,t=e.__importDefault(Y()),r=e.__importDefault(G());class s{constructor(e,{headers:t={},schema:r,fetch:s}={}){this.url=e,this.headers=new Headers(t),this.schemaName=r,this.fetch=s}from(e){const r=new URL(`${this.url}/${e}`);return new t.default(r,{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new s(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:i=!1,count:n}={}){var o;let a;const l=new URL(`${this.url}/rpc/${e}`);let c;s||i?(a=s?"HEAD":"GET",Object.entries(t).filter(([e,t])=>void 0!==t).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}`]).forEach(([e,t])=>{l.searchParams.append(e,t)})):(a="POST",c=t);const h=new Headers(this.headers);return n&&h.set("Prefer",`count=${n}`),new r.default({method:a,url:l,headers:h,schema:this.schemaName,body:c,fetch:null!==(o=this.fetch)&&void 0!==o?o:fetch})}}return O.default=s,O}());var ee=E.PostgrestClient=Z.default;const te=X.__importDefault(Y());var re=E.PostgrestQueryBuilder=te.default;const se=X.__importDefault(G());var ie=E.PostgrestFilterBuilder=se.default;const ne=X.__importDefault(z());var oe=E.PostgrestTransformBuilder=ne.default;const ae=X.__importDefault(H());var le=E.PostgrestBuilder=ae.default;const ce=X.__importDefault(J());Q=E.PostgrestError=ce.default;var he=E.default={PostgrestClient:Z.default,PostgrestQueryBuilder:te.default,PostgrestFilterBuilder:se.default,PostgrestTransformBuilder:ne.default,PostgrestBuilder:ae.default,PostgrestError:ce.default};const ue=h({__proto__:null,get PostgrestBuilder(){return le},get PostgrestClient(){return ee},get PostgrestError(){return Q},get PostgrestFilterBuilder(){return ie},get PostgrestQueryBuilder(){return re},get PostgrestTransformBuilder(){return oe},default:he},[E]),{PostgrestClient:de,PostgrestQueryBuilder:fe,PostgrestFilterBuilder:pe,PostgrestTransformBuilder:ge,PostgrestBuilder:we,PostgrestError:ve}=he||ue;class ye{static detectEnvironment(){var e;if("undefined"!=typeof WebSocket)return{type:"native",constructor:WebSocket};if("undefined"!=typeof globalThis&&void 0!==globalThis.WebSocket)return{type:"native",constructor:globalThis.WebSocket};if("undefined"!=typeof global&&void 0!==global.WebSocket)return{type:"native",constructor:global.WebSocket};if("undefined"!=typeof globalThis&&void 0!==globalThis.WebSocketPair&&void 0===globalThis.WebSocket)return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if("undefined"!=typeof globalThis&&globalThis.EdgeRuntime||"undefined"!=typeof navigator&&(null===(e=navigator.userAgent)||void 0===e?void 0:e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};if("undefined"!=typeof process){const e=process.versions;if(e&&e.node){const t=e.node,r=parseInt(t.replace(/^v/,"").split(".")[0]);return r>=22?void 0!==globalThis.WebSocket?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${r} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${r} detected without native WebSocket support.`,workaround:'For Node.js < 22, install "ws" package and provide it via the transport option:\nimport ws from "ws"\nnew RealtimeClient(url, { transport: ws })'}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=`\n\nSuggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){return new(this.getWebSocketConstructor())(e,t)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return"native"===e.type||"ws"===e.type}catch(e){return!1}}}const me=1e4;var be,_e,ke,Se,Ee,Te,Oe,je,Ie,Pe,Re;(_e=be||(be={}))[_e.connecting=0]="connecting",_e[_e.open=1]="open",_e[_e.closing=2]="closing",_e[_e.closed=3]="closed",(Se=ke||(ke={})).closed="closed",Se.errored="errored",Se.joined="joined",Se.joining="joining",Se.leaving="leaving",(Te=Ee||(Ee={})).close="phx_close",Te.error="phx_error",Te.join="phx_join",Te.reply="phx_reply",Te.leave="phx_leave",Te.access_token="access_token",(Oe||(Oe={})).websocket="websocket",(Ie=je||(je={})).Connecting="connecting",Ie.Open="open",Ie.Closing="closing",Ie.Closed="closed";class Ae{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t("string"==typeof e?JSON.parse(e):{})}_binaryDecode(e){const t=new DataView(e),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){const s=t.getUint8(1),i=t.getUint8(2);let n=this.HEADER_LENGTH+2;const o=r.decode(e.slice(n,n+s));n+=s;const a=r.decode(e.slice(n,n+i));n+=i;return{ref:null,topic:o,event:a,payload:JSON.parse(r.decode(e.slice(n,e.byteLength)))}}}class $e{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}(Re=Pe||(Pe={})).abstime="abstime",Re.bool="bool",Re.date="date",Re.daterange="daterange",Re.float4="float4",Re.float8="float8",Re.int2="int2",Re.int4="int4",Re.int4range="int4range",Re.int8="int8",Re.int8range="int8range",Re.json="json",Re.jsonb="jsonb",Re.money="money",Re.numeric="numeric",Re.oid="oid",Re.reltime="reltime",Re.text="text",Re.time="time",Re.timestamp="timestamp",Re.timestamptz="timestamptz",Re.timetz="timetz",Re.tsrange="tsrange",Re.tstzrange="tstzrange";const Ce=(e,t,r={})=>{var s;const i=null!==(s=r.skipTypes)&&void 0!==s?s:[];return t?Object.keys(t).reduce((r,s)=>(r[s]=xe(s,e,t,i),r),{}):{}},xe=(e,t,r,s)=>{const i=t.find(t=>t.name===e),n=null==i?void 0:i.type,o=r[e];return n&&!s.includes(n)?Ne(n,o):Ue(o)},Ne=(e,t)=>{if("_"===e.charAt(0)){const r=e.slice(1,e.length);return qe(t,r)}switch(e){case Pe.bool:return De(t);case Pe.float4:case Pe.float8:case Pe.int2:case Pe.int4:case Pe.int8:case Pe.numeric:case Pe.oid:return Le(t);case Pe.json:case Pe.jsonb:return Be(t);case Pe.timestamp:return We(t);case Pe.abstime:case Pe.date:case Pe.daterange:case Pe.int4range:case Pe.int8range:case Pe.money:case Pe.reltime:case Pe.text:case Pe.time:case Pe.timestamptz:case Pe.timetz:case Pe.tsrange:case Pe.tstzrange:default:return Ue(t)}},Ue=e=>e,De=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},Le=e=>{if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},Be=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(t){return e}return e},qe=(e,t)=>{if("string"!=typeof e)return e;const r=e.length-1,s=e[r];if("{"===e[0]&&"}"===s){let s;const n=e.slice(1,r);try{s=JSON.parse("["+n+"]")}catch(i){s=n?n.split(","):[]}return s.map(e=>Ne(t,e))}return e},We=e=>"string"==typeof e?e.replace(" ","T"):e,Ke=e=>{const t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),""===t.pathname||"/"===t.pathname?t.pathname="/api/broadcast":t.pathname=t.pathname+"/api/broadcast",t.href};class Me{constructor(e,t,r={},s=1e4){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(null===(r=this.receivedResp)||void 0===r?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);this.channel._on(this.refEvent,{},e=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=e,this._matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(t=>t.status===e).forEach(e=>e.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var Ve,Fe,Je,He,ze,Ge,Ye,Qe;(Fe=Ve||(Ve={})).SYNC="sync",Fe.JOIN="join",Fe.LEAVE="leave";class Xe{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(null==t?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},e=>{const{onJoin:t,onLeave:r,onSync:s}=this.caller;this.joinRef=this.channel._joinRef(),this.state=Xe.syncState(this.state,e,t,r),this.pendingDiffs.forEach(e=>{this.state=Xe.syncDiff(this.state,e,t,r)}),this.pendingDiffs=[],s()}),this.channel._on(r.diff,{},e=>{const{onJoin:t,onLeave:r,onSync:s}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(e):(this.state=Xe.syncDiff(this.state,e,t,r),s())}),this.onJoin((e,t,r)=>{this.channel._trigger("presence",{event:"join",key:e,currentPresences:t,newPresences:r})}),this.onLeave((e,t,r)=>{this.channel._trigger("presence",{event:"leave",key:e,currentPresences:t,leftPresences:r})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,s){const i=this.cloneDeep(e),n=this.transformState(t),o={},a={};return this.map(i,(e,t)=>{n[e]||(a[e]=t)}),this.map(n,(e,t)=>{const r=i[e];if(r){const s=t.map(e=>e.presence_ref),i=r.map(e=>e.presence_ref),n=t.filter(e=>i.indexOf(e.presence_ref)<0),l=r.filter(e=>s.indexOf(e.presence_ref)<0);n.length>0&&(o[e]=n),l.length>0&&(a[e]=l)}else o[e]=t}),this.syncDiff(i,{joins:o,leaves:a},r,s)}static syncDiff(e,t,r,s){const{joins:i,leaves:n}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),s||(s=()=>{}),this.map(i,(t,s)=>{var i;const n=null!==(i=e[t])&&void 0!==i?i:[];if(e[t]=this.cloneDeep(s),n.length>0){const r=e[t].map(e=>e.presence_ref),s=n.filter(e=>r.indexOf(e.presence_ref)<0);e[t].unshift(...s)}r(t,n,s)}),this.map(n,(t,r)=>{let i=e[t];if(!i)return;const n=r.map(e=>e.presence_ref);i=i.filter(e=>n.indexOf(e.presence_ref)<0),e[t]=i,s(t,i,r),0===i.length&&delete e[t]}),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 t[r]="metas"in s?s.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e)):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()}}(He=Je||(Je={})).ALL="*",He.INSERT="INSERT",He.UPDATE="UPDATE",He.DELETE="DELETE",(Ge=ze||(ze={})).BROADCAST="broadcast",Ge.PRESENCE="presence",Ge.POSTGRES_CHANGES="postgres_changes",Ge.SYSTEM="system",(Qe=Ye||(Ye={})).SUBSCRIBED="SUBSCRIBED",Qe.TIMED_OUT="TIMED_OUT",Qe.CLOSED="CLOSED",Qe.CHANNEL_ERROR="CHANNEL_ERROR";class Ze{constructor(e,t={config:{}},r){var s,i;if(this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=ke.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 Me(this,Ee.join,this.params,this.timeout),this.rejoinTimer=new $e(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=ke.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e=>e.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=ke.closed,this.socket._remove(this)}),this._onError(e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=ke.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=ke.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=ke.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Ee.reply,{},(e,t)=>{this._trigger(this._replyEventName(t),e)}),this.presence=new Xe(this),this.broadcastEndpointURL=Ke(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(null===(i=null===(s=this.params.config)||void 0===s?void 0:s.broadcast)||void 0===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==ke.closed){const{config:{broadcast:n,presence:o,private:a}}=this.params,l=null!==(s=null===(r=this.bindings.postgres_changes)||void 0===r?void 0:r.map(e=>e.filter))&&void 0!==s?s:[],c=!!this.bindings[ze.PRESENCE]&&this.bindings[ze.PRESENCE].length>0||!0===(null===(i=this.params.config.presence)||void 0===i?void 0:i.enabled),h={},u={broadcast:n,presence:Object.assign(Object.assign({},o),{enabled:c}),postgres_changes:l,private:a};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(t=>null==e?void 0:e(Ye.CHANNEL_ERROR,t)),this._onClose(()=>null==e?void 0:e(Ye.CLOSED)),this.updateJoinPayload(Object.assign({config:u},h)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:t})=>{var r;if(this.socket.setAuth(),void 0!==t){const s=this.bindings.postgres_changes,i=null!==(r=null==s?void 0:s.length)&&void 0!==r?r:0,n=[];for(let r=0;r<i;r++){const i=s[r],{filter:{event:o,schema:a,table:l,filter:c}}=i,h=t&&t[r];if(!h||h.event!==o||h.schema!==a||h.table!==l||h.filter!==c)return this.unsubscribe(),this.state=ke.errored,void(null==e||e(Ye.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes")));n.push(Object.assign(Object.assign({},i),{id:h.id}))}return this.bindings.postgres_changes=n,void(e&&e(Ye.SUBSCRIBED))}null==e||e(Ye.SUBSCRIBED)}).receive("error",t=>{this.state=ke.errored,null==e||e(Ye.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(t).join(", ")||"error")))}).receive("timeout",()=>{null==e||e(Ye.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===ke.joined&&e===ze.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(null==t)return Promise.reject("Payload is required for httpSend()");const n={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}]})},o=await this._fetchWithTimeout(this.broadcastEndpointURL,n,null!==(s=r.timeout)&&void 0!==s?s:this.timeout);if(202===o.status)return{success:!0};let a=o.statusText;try{const e=await o.json();a=e.error||e.message||a}catch(l){}return Promise.reject(new Error(a))}async send(e,t={}){var r,s;if(this._canPush()||"broadcast"!==e.type)return new Promise(r=>{var s,i,n;const o=this._push(e.type,e,t.timeout||this.timeout);"broadcast"!==e.type||(null===(n=null===(i=null===(s=this.params)||void 0===s?void 0:s.config)||void 0===i?void 0:i.broadcast)||void 0===n?void 0:n.ack)||r("ok"),o.receive("ok",()=>r("ok")),o.receive("error",()=>r("error")),o.receive("timeout",()=>r("timed out"))});{const{event:n,payload:o}=e,a={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o,private:this.private}]})};try{const e=await this._fetchWithTimeout(this.broadcastEndpointURL,a,null!==(r=t.timeout)&&void 0!==r?r:this.timeout);return await(null===(s=e.body)||void 0===s?void 0:s.cancel()),e.ok?"ok":"error"}catch(i){return"AbortError"===i.name?"timed out":"error"}}}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=ke.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Ee.close,"leave",this._joinRef())};this.joinPush.destroy();let r=null;return new Promise(s=>{r=new Me(this,Ee.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(()=>{null==r||r.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=ke.closed,this.bindings={}}async _fetchWithTimeout(e,t,r){const s=new AbortController,i=setTimeout(()=>s.abort(),r),n=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:s.signal}));return clearTimeout(i),n}_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 Me(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>100){const e=this.pushBuffer.shift();e&&(e.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${e.event}`,e.payload))}}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var s,i;const n=e.toLocaleLowerCase(),{close:o,error:a,leave:l,join:c}=Ee;if(r&&[o,a,l,c].indexOf(n)>=0&&r!==this._joinRef())return;let h=this._onMessage(n,t,r);if(t&&!h)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(n)?null===(s=this.bindings.postgres_changes)||void 0===s||s.filter(e=>{var t,r,s;return"*"===(null===(t=e.filter)||void 0===t?void 0:t.event)||(null===(s=null===(r=e.filter)||void 0===r?void 0:r.event)||void 0===s?void 0:s.toLocaleLowerCase())===n}).map(e=>e.callback(h,r)):null===(i=this.bindings[n])||void 0===i||i.filter(e=>{var r,s,i,o,a,l;if(["broadcast","presence","postgres_changes"].includes(n)){if("id"in e){const n=e.id,o=null===(r=e.filter)||void 0===r?void 0:r.event;return n&&(null===(s=t.ids)||void 0===s?void 0:s.includes(n))&&("*"===o||(null==o?void 0:o.toLocaleLowerCase())===(null===(i=t.data)||void 0===i?void 0:i.type.toLocaleLowerCase()))}{const r=null===(a=null===(o=null==e?void 0:e.filter)||void 0===o?void 0:o.event)||void 0===a?void 0:a.toLocaleLowerCase();return"*"===r||r===(null===(l=null==t?void 0:t.event)||void 0===l?void 0:l.toLocaleLowerCase())}}return e.type.toLocaleLowerCase()===n}).map(e=>{if("object"==typeof h&&"ids"in h){const e=h.data,{schema:t,table:r,commit_timestamp:s,type:i,errors:n}=e,o={schema:t,table:r,commit_timestamp:s,eventType:i,new:{},old:{},errors:n};h=Object.assign(Object.assign({},o),this._getPayloadRecords(e))}e.callback(h,r)})}_isClosed(){return this.state===ke.closed}_isJoined(){return this.state===ke.joined}_isJoining(){return this.state===ke.joining}_isLeaving(){return this.state===ke.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(e=>{var s;return!((null===(s=e.type)||void 0===s?void 0:s.toLocaleLowerCase())===r&&Ze.isEqual(e.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(Ee.close,{},e)}_onError(e){this._on(Ee.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=ke.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return"INSERT"!==e.type&&"UPDATE"!==e.type||(t.new=Ce(e.columns,e.record)),"UPDATE"!==e.type&&"DELETE"!==e.type||(t.old=Ce(e.columns,e.old_record)),t}}const et=()=>{},tt=25e3,rt=10,st=100,it=[1e3,2e3,5e3,1e4];class nt{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=me,this.transport=null,this.heartbeatIntervalMs=tt,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=et,this.ref=0,this.reconnectTimer=null,this.logger=et,this.conn=null,this.sendBuffer=[],this.serializer=new Ae,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._resolveFetch=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>c(async()=>{const{default:e}=await Promise.resolve().then(()=>D);return{default:e}},void 0).then(({default:t})=>t(...e)).catch(e=>{throw new Error(`Failed to load @supabase/node-fetch: ${e.message}. This is required for HTTP requests in Node.js environments without native fetch.`)}):fetch),(...e)=>t(...e)},!(null===(r=null==t?void 0:t.params)||void 0===r?void 0:r.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${Oe.websocket}`,this.httpEndpoint=Ke(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(null==t?void 0:t.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||null!==this.conn&&this.isConnected())){if(this._setConnectionState("connecting"),this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=ye.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;if(t.includes("Node.js"))throw new Error(`${t}\n\nTo use Realtime in Node.js, you need to provide a WebSocket implementation:\n\nOption 1: Use Node.js 22+ which has native WebSocket support\nOption 2: Install and provide the "ws" package:\n\n npm install ws\n\n import ws from "ws"\n const client = new RealtimeClient(url, {\n ...options,\n transport: ws\n })`);throw new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:"1.0.0"}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const r=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(r),this._setConnectionState("disconnected")},e?this.conn.close(e,null!=t?t:""):this.conn.close(),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const t=await e.unsubscribe();return 0===this.channels.length&&this.disconnect(),t}async removeAllChannels(){const e=await Promise.all(this.channels.map(e=>e.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case be.connecting:return je.Connecting;case be.open:return je.Open;case be.closing:return je.Closing;default:return je.Closed}}isConnected(){return this.connectionState()===je.Open}isConnecting(){return"connecting"===this._connectionState}isDisconnecting(){return"disconnecting"===this._connectionState}channel(e,t={config:{}}){const r=`realtime:${e}`,s=this.getChannels().find(e=>e.topic===r);if(s)return s;{const r=new Ze(`realtime:${e}`,t,this);return this.channels.push(r),r}}push(e){const{topic:t,event:r,payload:s,ref:i}=e,n=()=>{this.encode(e,e=>{var t;null===(t=this.conn)||void 0===t||t.send(e)})};this.log("push",`${t} ${r} (${i})`,s),this.isConnected()?n():this.sendBuffer.push(n)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}async sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}return this._wasManualDisconnect=!1,null===(e=this.conn)||void 0===e||e.close(1e3,"heartbeat timeout"),void setTimeout(()=>{var e;this.isConnected()||null===(e=this.reconnectTimer)||void 0===e||e.scheduleTimeout()},st)}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this._setAuthSafely("heartbeat")}else try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t._isJoined()||t._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,e=>{if("phoenix"===e.topic&&"phx_reply"===e.event)try{this.heartbeatCallback("ok"===e.payload.status?"ok":"error")}catch(a){this.log("error","error in heartbeat callback",a)}e.ref&&e.ref===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null);const{topic:t,event:r,payload:s,ref:i}=e,n=i?`(${i})`:"",o=s.status||"";this.log("receive",`${o} ${t} ${r} ${n}`.trim(),s),this.channels.filter(e=>e._isMember(t)).forEach(e=>e._trigger(r,s,i)),this._triggerStateCallbacks("message",e)})}_clearTimer(e){var t;"heartbeat"===e&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):"reconnect"===e&&(null===(t=this.reconnectTimer)||void 0===t||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_teardownConnection(){this.conn&&(this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null),this._clearAllTimers(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log("worker","worker error",e.message),this.workerRef.terminate()},this.workerRef.onmessage=e=>{"keepAlive"===e.data.event&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||null===(t=this.reconnectTimer)||void 0===t||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e)}_triggerChanError(){this.channels.forEach(e=>e._trigger(Ee.error))}_appendParams(e,t){if(0===Object.keys(t).length)return e;const r=e.match(/\?/)?"&":"?";return`${e}${r}${new URLSearchParams(t)}`}_workerObjectUrl(e){let t;if(e)t=e;else{const e=new Blob(['\n addEventListener("message", (e) => {\n if (e.data.event === "start") {\n setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);\n }\n });'],{type:"application/javascript"});t=URL.createObjectURL(e)}return t}_setConnectionState(e,t=!1){this._connectionState=e,"connecting"===e?this._wasManualDisconnect=!1:"disconnecting"===e&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t;t=e||(this.accessToken?await this.accessToken():this.accessTokenValue),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(e=>{const r={access_token:t,version:"realtime-js/2.77.0"};t&&e.updateJoinPayload(r),e.joinedOnce&&e._isJoined()&&e._push(Ee.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 $e(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},rt)},this.reconnectAfterMs)}_initializeOptions(e){var t,r,s,i,n,o,a,l,c;if(this.transport=null!==(t=null==e?void 0:e.transport)&&void 0!==t?t:null,this.timeout=null!==(r=null==e?void 0:e.timeout)&&void 0!==r?r:me,this.heartbeatIntervalMs=null!==(s=null==e?void 0:e.heartbeatIntervalMs)&&void 0!==s?s:tt,this.worker=null!==(i=null==e?void 0:e.worker)&&void 0!==i&&i,this.accessToken=null!==(n=null==e?void 0:e.accessToken)&&void 0!==n?n:null,this.heartbeatCallback=null!==(o=null==e?void 0:e.heartbeatCallback)&&void 0!==o?o:et,(null==e?void 0:e.params)&&(this.params=e.params),(null==e?void 0:e.logger)&&(this.logger=e.logger),((null==e?void 0:e.logLevel)||(null==e?void 0:e.log_level))&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=null!==(a=null==e?void 0:e.reconnectAfterMs)&&void 0!==a?a:e=>it[e-1]||1e4,this.encode=null!==(l=null==e?void 0:e.encode)&&void 0!==l?l:(e,t)=>t(JSON.stringify(e)),this.decode=null!==(c=null==e?void 0:e.decode)&&void 0!==c?c:this.serializer.decode.bind(this.serializer),this.worker){if("undefined"!=typeof window&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=null==e?void 0:e.workerUrl}}}class ot extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function at(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}class lt extends ot{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 ct extends ot{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}const ht=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>c(async()=>{const{default:e}=await Promise.resolve().then(()=>D);return{default:e}},void 0).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)},ut=e=>{if(Array.isArray(e))return e.map(e=>ut(e));if("function"==typeof e||e!==Object(e))return e;const t={};return Object.entries(e).forEach(([e,r])=>{const s=e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(/[-_]/g,""));t[s]=ut(r)}),t},dt=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),ft=(e,t,s)=>r(void 0,void 0,void 0,function*(){const i=yield r(void 0,void 0,void 0,function*(){return"undefined"==typeof Response?(yield c(()=>Promise.resolve().then(()=>D),void 0)).Response:Response});e instanceof i&&!(null==s?void 0:s.noResolveJson)?e.json().then(r=>{const s=e.status||500,i=(null==r?void 0:r.statusCode)||s+"";t(new lt(dt(r),s,i))}).catch(e=>{t(new ct(dt(e),e))}):t(new ct(dt(e),e))}),pt=(e,t,r,s)=>{const i={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"!==e&&s?((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(s)?(i.headers=Object.assign({"Content-Type":"application/json"},null==t?void 0:t.headers),i.body=JSON.stringify(s)):i.body=s,(null==t?void 0:t.duplex)&&(i.duplex=t.duplex),Object.assign(Object.assign({},i),r)):i};function gt(e,t,s,i,n,o){return r(this,void 0,void 0,function*(){return new Promise((r,a)=>{e(s,pt(t,i,n,o)).then(e=>{if(!e.ok)throw e;return(null==i?void 0:i.noResolveJson)?e:e.json()}).then(e=>r(e)).catch(e=>ft(e,a,i))})})}function wt(e,t,s,i){return r(this,void 0,void 0,function*(){return gt(e,"GET",t,s,i)})}function vt(e,t,s,i,n){return r(this,void 0,void 0,function*(){return gt(e,"POST",t,i,n,s)})}function yt(e,t,s,i,n){return r(this,void 0,void 0,function*(){return gt(e,"PUT",t,i,n,s)})}function mt(e,t,s,i,n){return r(this,void 0,void 0,function*(){return gt(e,"DELETE",t,i,n,s)})}class bt{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}execute(){return r(this,void 0,void 0,function*(){try{return{data:(yield this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(at(e))return{data:null,error:e};throw e}})}}var _t;class kt{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[_t]="BlobDownloadBuilder",this.promise=null}asStream(){return new bt(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 r(this,void 0,void 0,function*(){try{const e=yield this.downloadFn();return{data:yield e.blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(at(e))return{data:null,error:e};throw e}})}}_t=Symbol.toStringTag;const St={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Et={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class Tt{constructor(e,t={},r,s){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.bucketId=r,this.fetch=ht(s)}throwOnError(){return this.shouldThrowOnError=!0,this}uploadOrUpdate(e,t,s,i){return r(this,void 0,void 0,function*(){try{let r;const n=Object.assign(Object.assign({},Et),i);let o=Object.assign(Object.assign({},this.headers),"POST"===e&&{"x-upsert":String(n.upsert)});const a=n.metadata;"undefined"!=typeof Blob&&s instanceof Blob?(r=new FormData,r.append("cacheControl",n.cacheControl),a&&r.append("metadata",this.encodeMetadata(a)),r.append("",s)):"undefined"!=typeof FormData&&s instanceof FormData?(r=s,r.append("cacheControl",n.cacheControl),a&&r.append("metadata",this.encodeMetadata(a))):(r=s,o["cache-control"]=`max-age=${n.cacheControl}`,o["content-type"]=n.contentType,a&&(o["x-metadata"]=this.toBase64(this.encodeMetadata(a)))),(null==i?void 0:i.headers)&&(o=Object.assign(Object.assign({},o),i.headers));const l=this._removeEmptyFolders(t),c=this._getFinalPath(l),h=yield("PUT"==e?yt:vt)(this.fetch,`${this.url}/object/${c}`,r,Object.assign({headers:o},(null==n?void 0:n.duplex)?{duplex:n.duplex}:{}));return{data:{path:l,id:h.Id,fullPath:h.Key},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(at(r))return{data:null,error:r};throw r}})}upload(e,t,s){return r(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,i){return r(this,void 0,void 0,function*(){const r=this._removeEmptyFolders(e),n=this._getFinalPath(r),o=new URL(this.url+`/object/upload/sign/${n}`);o.searchParams.set("token",t);try{let e;const t=Object.assign({upsert:Et.upsert},i),n=Object.assign(Object.assign({},this.headers),{"x-upsert":String(t.upsert)});"undefined"!=typeof Blob&&s instanceof Blob?(e=new FormData,e.append("cacheControl",t.cacheControl),e.append("",s)):"undefined"!=typeof FormData&&s instanceof FormData?(e=s,e.append("cacheControl",t.cacheControl)):(e=s,n["cache-control"]=`max-age=${t.cacheControl}`,n["content-type"]=t.contentType);return{data:{path:r,fullPath:(yield yt(this.fetch,o.toString(),e,{headers:n})).Key},error:null}}catch(a){if(this.shouldThrowOnError)throw a;if(at(a))return{data:null,error:a};throw a}})}createSignedUploadUrl(e,t){return r(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e);const s=Object.assign({},this.headers);(null==t?void 0:t.upsert)&&(s["x-upsert"]="true");const i=yield vt(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:s}),n=new URL(this.url+i.url),o=n.searchParams.get("token");if(!o)throw new ot("No token returned by API");return{data:{signedUrl:n.toString(),path:e,token:o},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(at(r))return{data:null,error:r};throw r}})}update(e,t,s){return r(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return r(this,void 0,void 0,function*(){try{return{data:yield vt(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==s?void 0:s.destinationBucket},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(at(r))return{data:null,error:r};throw r}})}copy(e,t,s){return r(this,void 0,void 0,function*(){try{return{data:{path:(yield vt(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==s?void 0:s.destinationBucket},{headers:this.headers})).Key},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(at(r))return{data:null,error:r};throw r}})}createSignedUrl(e,t,s){return r(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),i=yield vt(this.fetch,`${this.url}/object/sign/${r}`,Object.assign({expiresIn:t},(null==s?void 0:s.transform)?{transform:s.transform}:{}),{headers:this.headers});const n=(null==s?void 0:s.download)?`&download=${!0===s.download?"":s.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${n}`)},{data:i,error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(at(r))return{data:null,error:r};throw r}})}createSignedUrls(e,t,s){return r(this,void 0,void 0,function*(){try{const r=yield vt(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=(null==s?void 0:s.download)?`&download=${!0===s.download?"":s.download}`:"";return{data:r.map(e=>Object.assign(Object.assign({},e),{signedUrl:e.signedURL?encodeURI(`${this.url}${e.signedURL}${i}`):null})),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(at(r))return{data:null,error:r};throw r}})}download(e,t){const r=void 0!==(null==t?void 0:t.transform)?"render/image/authenticated":"object",s=this.transformOptsToQueryString((null==t?void 0:t.transform)||{}),i=s?`?${s}`:"",n=this._getFinalPath(e);return new kt(()=>wt(this.fetch,`${this.url}/${r}/${n}${i}`,{headers:this.headers,noResolveJson:!0}),this.shouldThrowOnError)}info(e){return r(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{const e=yield wt(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:ut(e),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(at(r))return{data:null,error:r};throw r}})}exists(e){return r(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{return yield function(e,t,s,i){return r(this,void 0,void 0,function*(){return gt(e,"HEAD",t,Object.assign(Object.assign({},s),{noResolveJson:!0}),i)})}(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(at(s)&&s instanceof ct){const e=s.originalError;if([400,404].includes(null==e?void 0:e.status))return{data:!1,error:s}}throw s}})}getPublicUrl(e,t){const r=this._getFinalPath(e),s=[],i=(null==t?void 0:t.download)?`download=${!0===t.download?"":t.download}`:"";""!==i&&s.push(i);const n=void 0!==(null==t?void 0:t.transform)?"render/image":"object",o=this.transformOptsToQueryString((null==t?void 0:t.transform)||{});""!==o&&s.push(o);let a=s.join("&");return""!==a&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${n}/public/${r}${a}`)}}}remove(e){return r(this,void 0,void 0,function*(){try{return{data:yield mt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(at(t))return{data:null,error:t};throw t}})}list(e,t,s){return r(this,void 0,void 0,function*(){try{const r=Object.assign(Object.assign(Object.assign({},St),t),{prefix:e||""});return{data:yield vt(this.fetch,`${this.url}/object/list/${this.bucketId}`,r,{headers:this.headers},s),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(at(r))return{data:null,error:r};throw r}})}listV2(e,t){return r(this,void 0,void 0,function*(){try{const r=Object.assign({},e);return{data:yield vt(this.fetch,`${this.url}/object/list-v2/${this.bucketId}`,r,{headers:this.headers},t),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(at(r))return{data:null,error:r};throw r}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return"undefined"!=typeof Buffer?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}}const Ot="2.77.0",jt={"X-Client-Info":`storage-js/${Ot}`};class It{constructor(e,t={},r,s){this.shouldThrowOnError=!1;const i=new URL(e);if(null==s?void 0: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({},jt),t),this.fetch=ht(r)}throwOnError(){return this.shouldThrowOnError=!0,this}listBuckets(e){return r(this,void 0,void 0,function*(){try{const t=this.listBucketOptionsToQueryString(e);return{data:yield wt(this.fetch,`${this.url}/bucket${t}`,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(at(t))return{data:null,error:t};throw t}})}getBucket(e){return r(this,void 0,void 0,function*(){try{return{data:yield wt(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(at(t))return{data:null,error:t};throw t}})}createBucket(e){return r(this,arguments,void 0,function*(e,t={public:!1}){try{return{data:yield vt(this.fetch,`${this.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(at(r))return{data:null,error:r};throw r}})}updateBucket(e,t){return r(this,void 0,void 0,function*(){try{return{data:yield yt(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(at(r))return{data:null,error:r};throw r}})}emptyBucket(e){return r(this,void 0,void 0,function*(){try{return{data:yield vt(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(at(t))return{data:null,error:t};throw t}})}deleteBucket(e){return r(this,void 0,void 0,function*(){try{return{data:yield mt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(at(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 Pt{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},jt),t),this.fetch=ht(r)}throwOnError(){return this.shouldThrowOnError=!0,this}createBucket(e){return r(this,void 0,void 0,function*(){try{return{data:yield vt(this.fetch,`${this.url}/bucket`,{name:e},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(at(t))return{data:null,error:t};throw t}})}listBuckets(e){return r(this,void 0,void 0,function*(){try{const t=new URLSearchParams;void 0!==(null==e?void 0:e.limit)&&t.set("limit",e.limit.toString()),void 0!==(null==e?void 0:e.offset)&&t.set("offset",e.offset.toString()),(null==e?void 0:e.sortColumn)&&t.set("sortColumn",e.sortColumn),(null==e?void 0:e.sortOrder)&&t.set("sortOrder",e.sortOrder),(null==e?void 0:e.search)&&t.set("search",e.search);const r=t.toString(),s=r?`${this.url}/bucket?${r}`:`${this.url}/bucket`;return{data:yield wt(this.fetch,s,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(at(t))return{data:null,error:t};throw t}})}deleteBucket(e){return r(this,void 0,void 0,function*(){try{return{data:yield mt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(at(t))return{data:null,error:t};throw t}})}}const Rt={"X-Client-Info":`storage-js/${Ot}`,"Content-Type":"application/json"};class At extends Error{constructor(e){super(e),this.__isStorageVectorsError=!0,this.name="StorageVectorsError"}}function $t(e){return"object"==typeof e&&null!==e&&"__isStorageVectorsError"in e}class Ct extends At{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 xt extends At{constructor(e,t){super(e),this.name="StorageVectorsUnknownError",this.originalError=t}}var Nt,Ut;(Ut=Nt||(Nt={})).InternalError="InternalError",Ut.S3VectorConflictException="S3VectorConflictException",Ut.S3VectorNotFoundException="S3VectorNotFoundException",Ut.S3VectorBucketNotEmpty="S3VectorBucketNotEmpty",Ut.S3VectorMaxBucketsExceeded="S3VectorMaxBucketsExceeded",Ut.S3VectorMaxIndexesExceeded="S3VectorMaxIndexesExceeded";const Dt=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>c(async()=>{const{default:e}=await Promise.resolve().then(()=>D);return{default:e}},void 0).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)},Lt=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),Bt=(e,t,r,s)=>{const i={method:e,headers:(null==t?void 0:t.headers)||{}};return s?((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(s)?(i.headers=Object.assign({"Content-Type":"application/json"},null==t?void 0:t.headers),i.body=JSON.stringify(s)):i.body=s,Object.assign(Object.assign({},i),r)):i};function qt(e,t,s,i,n,o){return r(this,void 0,void 0,function*(){return new Promise((a,l)=>{e(s,Bt(t,i,n,o)).then(e=>{if(!e.ok)throw e;if(null==i?void 0:i.noResolveJson)return e;const t=e.headers.get("content-type");return t&&t.includes("application/json")?e.json():{}}).then(e=>a(e)).catch(e=>((e,t,s)=>r(void 0,void 0,void 0,function*(){if(e&&"object"==typeof e&&"status"in e&&"ok"in e&&"number"==typeof e.status&&!(null==s?void 0:s.noResolveJson)){const r=e.status||500,s=e;if("function"==typeof s.json)s.json().then(e=>{const s=(null==e?void 0:e.statusCode)||(null==e?void 0:e.code)||r+"";t(new Ct(Lt(e),r,s))}).catch(()=>{const e=r+"",i=s.statusText||`HTTP ${r} error`;t(new Ct(i,r,e))});else{const e=r+"",i=s.statusText||`HTTP ${r} error`;t(new Ct(i,r,e))}}else t(new xt(Lt(e),e))}))(e,l,i))})})}function Wt(e,t,s,i,n){return r(this,void 0,void 0,function*(){return qt(e,"POST",t,i,n,s)})}class Kt{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},Rt),t),this.fetch=Dt(r)}throwOnError(){return this.shouldThrowOnError=!0,this}createIndex(e){return r(this,void 0,void 0,function*(){try{return{data:(yield Wt(this.fetch,`${this.url}/CreateIndex`,e,{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($t(t))return{data:null,error:t};throw t}})}getIndex(e,t){return r(this,void 0,void 0,function*(){try{return{data:yield Wt(this.fetch,`${this.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if($t(r))return{data:null,error:r};throw r}})}listIndexes(e){return r(this,void 0,void 0,function*(){try{return{data:yield Wt(this.fetch,`${this.url}/ListIndexes`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($t(t))return{data:null,error:t};throw t}})}deleteIndex(e,t){return r(this,void 0,void 0,function*(){try{return{data:(yield Wt(this.fetch,`${this.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:this.headers}))||{},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if($t(r))return{data:null,error:r};throw r}})}}class Mt{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},Rt),t),this.fetch=Dt(r)}throwOnError(){return this.shouldThrowOnError=!0,this}putVectors(e){return r(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 Wt(this.fetch,`${this.url}/PutVectors`,e,{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($t(t))return{data:null,error:t};throw t}})}getVectors(e){return r(this,void 0,void 0,function*(){try{return{data:yield Wt(this.fetch,`${this.url}/GetVectors`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($t(t))return{data:null,error:t};throw t}})}listVectors(e){return r(this,void 0,void 0,function*(){try{if(void 0!==e.segmentCount){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(void 0!==e.segmentIndex&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error("segmentIndex must be between 0 and "+(e.segmentCount-1))}return{data:yield Wt(this.fetch,`${this.url}/ListVectors`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($t(t))return{data:null,error:t};throw t}})}queryVectors(e){return r(this,void 0,void 0,function*(){try{return{data:yield Wt(this.fetch,`${this.url}/QueryVectors`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($t(t))return{data:null,error:t};throw t}})}deleteVectors(e){return r(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 Wt(this.fetch,`${this.url}/DeleteVectors`,e,{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($t(t))return{data:null,error:t};throw t}})}}class Vt{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},Rt),t),this.fetch=Dt(r)}throwOnError(){return this.shouldThrowOnError=!0,this}createBucket(e){return r(this,void 0,void 0,function*(){try{return{data:(yield Wt(this.fetch,`${this.url}/CreateVectorBucket`,{vectorBucketName:e},{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 r(this,void 0,void 0,function*(){try{return{data:yield Wt(this.fetch,`${this.url}/GetVectorBucket`,{vectorBucketName:e},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($t(t))return{data:null,error:t};throw t}})}listBuckets(){return r(this,arguments,void 0,function*(e={}){try{return{data:yield Wt(this.fetch,`${this.url}/ListVectorBuckets`,e,{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 r(this,void 0,void 0,function*(){try{return{data:(yield Wt(this.fetch,`${this.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($t(t))return{data:null,error:t};throw t}})}}class Ft extends Vt{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new Jt(this.url,this.headers,e,this.fetch)}}class Jt extends Kt{constructor(e,t,r,s){super(e,t,s),this.vectorBucketName=r}createIndex(e){const t=Object.create(null,{createIndex:{get:()=>super.createIndex}});return r(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 r(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 r(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 r(this,void 0,void 0,function*(){return t.deleteIndex.call(this,this.vectorBucketName,e)})}index(e){return new Ht(this.url,this.headers,this.vectorBucketName,e,this.fetch)}}class Ht extends Mt{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 r(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 r(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 r(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 r(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 r(this,void 0,void 0,function*(){return t.deleteVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}}class zt extends It{constructor(e,t={},r,s){super(e,t,r,s)}from(e){return new Tt(this.url,this.headers,e,this.fetch)}get vectors(){return new Ft(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Pt(this.url+"/iceberg",this.headers,this.fetch)}}let Gt="";Gt="undefined"!=typeof Deno?"deno":"undefined"!=typeof document?"web":"undefined"!=typeof navigator&&"ReactNative"===navigator.product?"react-native":"node";const Yt={headers:{"X-Client-Info":`supabase-js-${Gt}/2.77.0`}},Qt={schema:"public"},Xt={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Zt={},er=(e,t,r)=>{const s=(e=>{let t;return t=e||("undefined"==typeof fetch?C:fetch),(...e)=>t(...e)})(r),i="undefined"==typeof Headers?x:Headers;return async(r,n)=>{var o;const a=null!==(o=await t())&&void 0!==o?o:e;let l=new i(null==n?void 0:n.headers);return l.has("apikey")||l.set("apikey",e),l.has("Authorization")||l.set("Authorization",`Bearer ${a}`),s(r,Object.assign(Object.assign({},n),{headers:l}))}};const tr="2.77.0",rr=3e4,sr=9e4,ir={"X-Client-Info":`gotrue-js/${tr}`},nr="X-Supabase-Api-Version",or={timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"},ar=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;class lr extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}}function cr(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class hr extends lr{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}}class ur extends lr{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class dr extends lr{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}}class fr extends dr{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}class pr extends dr{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class gr extends dr{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class wr extends dr{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class vr extends dr{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 yr extends dr{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function mr(e){return cr(e)&&"AuthRetryableFetchError"===e.name}class br extends dr{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}}class _r extends dr{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const kr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Sr=" \t\n\r=".split(""),Er=(()=>{const e=new Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<Sr.length;t+=1)e[Sr[t].charCodeAt(0)]=-2;for(let t=0;t<kr.length;t+=1)e[kr[t].charCodeAt(0)]=t;return e})();function Tr(e,t,r){if(null!==e)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;r(kr[e]),t.queuedBits-=6}else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;r(kr[e]),t.queuedBits-=6}}function Or(e,t,r){const s=Er[e];if(!(s>-1)){if(-2===s)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}for(t.queue=t.queue<<6|s,t.queuedBits+=6;t.queuedBits>=8;)r(t.queue>>t.queuedBits-8&255),t.queuedBits-=8}function jr(e){const t=[],r=e=>{t.push(String.fromCodePoint(e))},s={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},n=e=>{!function(e,t,r){if(0===t.utf8seq){if(e<=127)return void r(e);for(let r=1;r<6;r+=1)if(!(e>>7-r&1)){t.utf8seq=r;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else{if(4!==t.utf8seq)throw new Error("Invalid UTF-8 sequence");t.codepoint=7&e}t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&r(t.codepoint)}}(e,s,r)};for(let o=0;o<e.length;o+=1)Or(e.charCodeAt(o),i,n);return t.join("")}function Ir(e,t){if(!(e<=127)){if(e<=2047)return t(192|e>>6),void t(128|63&e);if(e<=65535)return t(224|e>>12),t(128|e>>6&63),void t(128|63&e);if(e<=1114111)return t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),void t(128|63&e);throw new Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}t(e)}function Pr(e){const t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};for(let i=0;i<e.length;i+=1)Or(e.charCodeAt(i),r,s);return new Uint8Array(t)}function Rr(e){const t=[];return function(e,t){for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);if(s>55295&&s<=56319){const t=1024*(s-55296)&65535;s=65536+(e.charCodeAt(r+1)-56320&65535|t),r+=1}Ir(s,t)}}(e,e=>t.push(e)),new Uint8Array(t)}function Ar(e){const t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};return e.forEach(e=>Tr(e,r,s)),Tr(null,r,s),t.join("")}const $r=()=>"undefined"!=typeof window&&"undefined"!=typeof document,Cr={tested:!1,writable:!1},xr=()=>{if(!$r())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(t){return!1}if(Cr.tested)return Cr.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),Cr.tested=!0,Cr.writable=!0}catch(t){Cr.tested=!0,Cr.writable=!1}return Cr.writable};const Nr=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>c(async()=>{const{default:e}=await Promise.resolve().then(()=>D);return{default:e}},void 0).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)},Ur=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},Dr=async(e,t)=>{const r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch(s){return r}},Lr=async(e,t)=>{await e.removeItem(t)};class Br{constructor(){this.promise=new Br.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function qr(e){const t=e.split(".");if(3!==t.length)throw new _r("Invalid JWT structure");for(let r=0;r<t.length;r++)if(!ar.test(t[r]))throw new _r("JWT not in base64url format");return{header:JSON.parse(jr(t[0])),payload:JSON.parse(jr(t[1])),signature:Pr(t[2]),raw:{header:t[0],payload:t[1]}}}function Wr(e){return("0"+e.toString(16)).substr(-2)}async function Kr(e){if(!("undefined"!=typeof crypto&&void 0!==crypto.subtle&&"undefined"!=typeof TextEncoder))return e;const t=await async function(e){const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(r);return Array.from(s).map(e=>String.fromCharCode(e)).join("")}(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Mr(e,t,r=!1){const s=function(){const e=new Uint32Array(56);if("undefined"==typeof crypto){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length;let r="";for(let s=0;s<56;s++)r+=e.charAt(Math.floor(Math.random()*t));return r}return crypto.getRandomValues(e),Array.from(e,Wr).join("")}();let i=s;r&&(i+="/PASSWORD_RECOVERY"),await Ur(e,`${t}-code-verifier`,i);const n=await Kr(s);return[n,s===n?"plain":"s256"]}Br.promiseConstructor=Promise;const Vr=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;const Fr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Jr(e){if(!Fr.test(e))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Hr(){return new Proxy({},{get:(e,t)=>{if("__isUserNotAvailableProxy"===t)return!0;if("symbol"==typeof t){const e=t.toString();if("Symbol(Symbol.toPrimitive)"===e||"Symbol(Symbol.toStringTag)"===e||"Symbol(util.inspect.custom)"===e)return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function zr(e){return JSON.parse(JSON.stringify(e))}const Gr=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),Yr=[502,503,504];async function Qr(e){var t,r;if(!("object"==typeof(r=e)&&null!==r&&"status"in r&&"ok"in r&&"json"in r&&"function"==typeof r.json))throw new yr(Gr(e),0);if(Yr.includes(e.status))throw new yr(Gr(e),e.status);let s,i;try{s=await e.json()}catch(o){throw new ur(Gr(o),o)}const n=function(e){const t=e.headers.get(nr);if(!t)return null;if(!t.match(Vr))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch(o){return null}}(e);if(n&&n.getTime()>=or.timestamp&&"object"==typeof s&&s&&"string"==typeof s.code?i=s.code:"object"==typeof s&&s&&"string"==typeof s.error_code&&(i=s.error_code),i){if("weak_password"===i)throw new br(Gr(s),e.status,(null===(t=s.weak_password)||void 0===t?void 0:t.reasons)||[]);if("session_not_found"===i)throw new fr}else if("object"==typeof s&&s&&"object"==typeof s.weak_password&&s.weak_password&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0))throw new br(Gr(s),e.status,s.weak_password.reasons);throw new hr(Gr(s),e.status||500,i)}async function Xr(e,t,r,s){var i;const n=Object.assign({},null==s?void 0:s.headers);n[nr]||(n[nr]=or.name),(null==s?void 0:s.jwt)&&(n.Authorization=`Bearer ${s.jwt}`);const o=null!==(i=null==s?void 0:s.query)&&void 0!==i?i:{};(null==s?void 0:s.redirectTo)&&(o.redirect_to=s.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await async function(e,t,r,s,i,n){const o=((e,t,r,s)=>{const i={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==t?void 0:t.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),r))})(t,s,i,n);let a;try{a=await e(r,Object.assign({},o))}catch(l){throw new yr(Gr(l),0)}a.ok||await Qr(a);if(null==s?void 0:s.noResolveJson)return a;try{return await a.json()}catch(l){await Qr(l)}}(e,t,r+a,{headers:n,noResolveJson:null==s?void 0:s.noResolveJson},{},null==s?void 0:s.body);return(null==s?void 0:s.xform)?null==s?void 0:s.xform(l):{data:Object.assign({},l),error:null}}function Zr(e){var t;let r=null;var s;(function(e){return e.access_token&&e.refresh_token&&e.expires_in})(e)&&(r=Object.assign({},e),e.expires_at||(r.expires_at=(s=e.expires_in,Math.round(Date.now()/1e3)+s)));return{data:{session:r,user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function es(e){const t=Zr(e);return!t.error&&e.weak_password&&"object"==typeof e.weak_password&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&"string"==typeof e.weak_password.message&&e.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0)&&(t.data.weak_password=e.weak_password),t}function ts(e){var t;return{data:{user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function rs(e){return{data:e,error:null}}function ss(e){const{action_link:t,email_otp:r,hashed_token:s,redirect_to:n,verification_type:o}=e,a=i(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]);return{data:{properties:{action_link:t,email_otp:r,hashed_token:s,redirect_to:n,verification_type:o},user:Object.assign({},a)},error:null}}function is(e){return e}const ns=["global","local","others"];class os{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),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)}}async signOut(e,t=ns[0]){if(ns.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${ns.join(", ")}`);try{return await Xr(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(cr(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await Xr(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:ts})}catch(r){if(cr(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{const{options:t}=e,r=i(e,["options"]),s=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(s.new_email=null==r?void 0:r.newEmail,delete s.newEmail),await Xr(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:ss,redirectTo:null==t?void 0:t.redirectTo})}catch(t){if(cr(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await Xr(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:ts})}catch(t){if(cr(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,s,i,n,o,a;try{const l={nextPage:null,lastPage:0,total:0},c=await Xr(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(r=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==r?r:"",per_page:null!==(i=null===(s=null==e?void 0:e.perPage)||void 0===s?void 0:s.toString())&&void 0!==i?i:""},xform:is});if(c.error)throw c.error;const h=await c.json(),u=null!==(n=c.headers.get("x-total-count"))&&void 0!==n?n:0,d=null!==(a=null===(o=c.headers.get("link"))||void 0===o?void 0:o.split(","))&&void 0!==a?a:[];return d.length>0&&(d.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l[`${r}Page`]=t}),l.total=parseInt(u)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(l){if(cr(l))return{data:{users:[]},error:l};throw l}}async getUserById(e){Jr(e);try{return await Xr(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:ts})}catch(t){if(cr(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){Jr(e);try{return await Xr(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:ts})}catch(r){if(cr(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){Jr(e);try{return await Xr(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:ts})}catch(r){if(cr(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){Jr(e.userId);try{const{data:t,error:r}=await Xr(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:r}}catch(t){if(cr(t))return{data:null,error:t};throw t}}async _deleteFactor(e){Jr(e.userId),Jr(e.id);try{return{data:await Xr(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(cr(t))return{data:null,error:t};throw t}}async _listOAuthClients(e){var t,r,s,i,n,o,a;try{const l={nextPage:null,lastPage:0,total:0},c=await Xr(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(r=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==r?r:"",per_page:null!==(i=null===(s=null==e?void 0:e.perPage)||void 0===s?void 0:s.toString())&&void 0!==i?i:""},xform:is});if(c.error)throw c.error;const h=await c.json(),u=null!==(n=c.headers.get("x-total-count"))&&void 0!==n?n:0,d=null!==(a=null===(o=c.headers.get("link"))||void 0===o?void 0:o.split(","))&&void 0!==a?a:[];return d.length>0&&(d.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l[`${r}Page`]=t}),l.total=parseInt(u)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(l){if(cr(l))return{data:{clients:[]},error:l};throw l}}async _createOAuthClient(e){try{return await Xr(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(t){if(cr(t))return{data:null,error:t};throw t}}async _getOAuthClient(e){try{return await Xr(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(t){if(cr(t))return{data:null,error:t};throw t}}async _deleteOAuthClient(e){try{return await Xr(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(cr(t))return{data:null,error:t};throw t}}async _regenerateOAuthClientSecret(e){try{return await Xr(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(t){if(cr(t))return{data:null,error:t};throw t}}}function as(e={}){return{getItem:t=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:t=>{delete e[t]}}}const ls=!!(globalThis&&xr()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"));class cs extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class hs extends cs{}async function us(e,t,r){const s=new globalThis.AbortController;return t>0&&setTimeout(()=>{s.abort()},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,0===t?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async s=>{if(!s){if(0===t)throw new hs(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(ls)try{await globalThis.navigator.locks.query()}catch(i){}return await r()}try{return await r()}finally{}}))}function ds(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw new Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function fs(e){const t=(new TextEncoder).encode(e);return"0x"+Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}class ps extends Error{constructor({message:e,code:t,cause:r,name:s}){var i;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=null!==(i=null!=s?s:r instanceof Error?r.name:void 0)&&void 0!==i?i:"Unknown Error",this.code=t}}class gs extends ps{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}function ws({error:e,options:t}){var r,s,i;const{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new ps({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if(!0===(null===(r=n.authenticatorSelection)||void 0===r?void 0:r.requireResidentKey))return new ps({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if("conditional"===t.mediation&&"required"===(null===(s=n.authenticatorSelection)||void 0===s?void 0:s.userVerification))return new ps({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if("required"===(null===(i=n.authenticatorSelection)||void 0===i?void 0:i.userVerification))return new ps({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if("InvalidStateError"===e.name)return new ps({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new ps({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("NotSupportedError"===e.name){return 0===n.pubKeyCredParams.filter(e=>"public-key"===e.type).length?new ps({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new ps({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e})}if("SecurityError"===e.name){const t=window.location.hostname;if(!Ss(t))return new ps({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(n.rp.id!==t)return new ps({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new ps({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if("UnknownError"===e.name)return new ps({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new ps({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function vs({error:e,options:t}){const{publicKey:r}=t;if(!r)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new ps({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new ps({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("SecurityError"===e.name){const t=window.location.hostname;if(!Ss(t))return new ps({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(r.rpId!==t)return new ps({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("UnknownError"===e.name)return new ps({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new ps({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}const ys=new class{createNewAbortSignal(){if(this.controller){const e=new Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}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}}};function ms(e){if(!e)throw new Error("Credential creation options are required");if("undefined"!=typeof PublicKeyCredential&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(e);const{challenge:t,user:r,excludeCredentials:s}=e,n=i(e,["challenge","user","excludeCredentials"]),o=Pr(t).buffer,a=Object.assign(Object.assign({},r),{id:Pr(r.id).buffer}),l=Object.assign(Object.assign({},n),{challenge:o,user:a});if(s&&s.length>0){l.excludeCredentials=new Array(s.length);for(let e=0;e<s.length;e++){const t=s[e];l.excludeCredentials[e]=Object.assign(Object.assign({},t),{id:Pr(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return l}function bs(e){if(!e)throw new Error("Credential request options are required");if("undefined"!=typeof PublicKeyCredential&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseRequestOptionsFromJSON)return PublicKeyCredential.parseRequestOptionsFromJSON(e);const{challenge:t,allowCredentials:r}=e,s=i(e,["challenge","allowCredentials"]),n=Pr(t).buffer,o=Object.assign(Object.assign({},s),{challenge:n});if(r&&r.length>0){o.allowCredentials=new Array(r.length);for(let e=0;e<r.length;e++){const t=r[e];o.allowCredentials[e]=Object.assign(Object.assign({},t),{id:Pr(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return o}function _s(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();const r=e;return{id:e.id,rawId:e.id,response:{attestationObject:Ar(new Uint8Array(e.response.attestationObject)),clientDataJSON:Ar(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:null!==(t=r.authenticatorAttachment)&&void 0!==t?t:void 0}}function ks(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();const r=e,s=e.getClientExtensionResults(),i=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:Ar(new Uint8Array(i.authenticatorData)),clientDataJSON:Ar(new Uint8Array(i.clientDataJSON)),signature:Ar(new Uint8Array(i.signature)),userHandle:i.userHandle?Ar(new Uint8Array(i.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:null!==(t=r.authenticatorAttachment)&&void 0!==t?t:void 0}}function Ss(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function Es(){var e,t;return!!($r()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&"function"==typeof(null===(e=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===e?void 0:e.create)&&"function"==typeof(null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.get))}const Ts={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"none"},Os={userVerification:"preferred",hints:["security-key"]};function js(...e){const t=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),r=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),s={};for(const i of e)if(i)for(const e in i){const n=i[e];if(void 0!==n)if(Array.isArray(n))s[e]=n;else if(r(n))s[e]=n;else if(t(n)){const r=s[e];t(r)?s[e]=js(r,n):s[e]=js(n)}else s[e]=n}return s}class Is{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:n,error:o}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!n)return{data:null,error:o};const a=null!=s?s:ys.createNewAbortSignal();if("create"===n.webauthn.type){const{user:e}=n.webauthn.credential_options.publicKey;e.name||(e.name=`${e.id}:${r}`),e.displayName||(e.displayName=e.name)}switch(n.webauthn.type){case"create":{const t=function(e,t){return js(Ts,e,t||{})}(n.webauthn.credential_options.publicKey,null==i?void 0:i.create),{data:r,error:s}=await async function(e){try{const t=await navigator.credentials.create(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new gs("Browser returned unexpected credential type",t)}:{data:null,error:new gs("Empty credential response",t)}}catch(t){return{data:null,error:ws({error:t,options:e})}}}({publicKey:t,signal:a});return r?{data:{factorId:e,challengeId:n.id,webauthn:{type:n.webauthn.type,credential_response:r}},error:null}:{data:null,error:s}}case"request":{const t=function(e,t){return js(Os,e,t||{})}(n.webauthn.credential_options.publicKey,null==i?void 0:i.request),{data:r,error:s}=await async function(e){try{const t=await navigator.credentials.get(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new gs("Browser returned unexpected credential type",t)}:{data:null,error:new gs("Empty credential response",t)}}catch(t){return{data:null,error:vs({error:t,options:e})}}}(Object.assign(Object.assign({},n.webauthn.credential_options),{publicKey:t,signal:a}));return r?{data:{factorId:e,challengeId:n.id,webauthn:{type:n.webauthn.type,credential_response:r}},error:null}:{data:null,error:s}}}}catch(n){return cr(n)?{data:null,error:n}:{data:null,error:new ur("Unexpected error in challenge",n)}}}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=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:r=("undefined"!=typeof window?[window.location.origin]:void 0),signal:s}},i){if(!t)return{data:null,error:new lr("rpId is required for WebAuthn authentication")};try{if(!Es())return{data:null,error:new ur("Browser does not support WebAuthn",null)};const{data:n,error:o}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:i});if(!n)return{data:null,error:o};const{webauthn:a}=n;return this._verify({factorId:e,challengeId:n.challengeId,webauthn:{type:a.type,rpId:t,rpOrigins:r,credential_response:a.credential_response}})}catch(n){return cr(n)?{data:null,error:n}:{data:null,error:new ur("Unexpected error in authenticate",n)}}}async _register({friendlyName:e,rpId:t=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:r=("undefined"!=typeof window?[window.location.origin]:void 0),signal:s},i){if(!t)return{data:null,error:new lr("rpId is required for WebAuthn registration")};try{if(!Es())return{data:null,error:new ur("Browser does not support WebAuthn",null)};const{data:n,error:o}=await this._enroll({friendlyName:e});if(!n)return await this.client.mfa.listFactors().then(t=>{var r;return null===(r=t.data)||void 0===r?void 0:r.all.find(t=>"webauthn"===t.factor_type&&t.friendly_name===e&&"unverified"!==t.status)}).then(e=>e?this.client.mfa.unenroll({factorId:null==e?void 0:e.id}):void 0),{data:null,error:o};const{data:a,error:l}=await this._challenge({factorId:n.id,friendlyName:n.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:i});return a?this._verify({factorId:n.id,challengeId:a.challengeId,webauthn:{rpId:t,rpOrigins:r,type:a.webauthn.type,credential_response:a.webauthn.credential_response}}):{data:null,error:l}}catch(n){return cr(n)?{data:null,error:n}:{data:null,error:new ur("Unexpected error in register",n)}}}}!function(){if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){"undefined"!=typeof self&&(self.globalThis=self)}}();const Ps={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:ir,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function Rs(e,t,r){return await r()}const As={};class $s{get jwks(){var e,t;return null!==(t=null===(e=As[this.storageKey])||void 0===e?void 0:e.jwks)&&void 0!==t?t:{keys:[]}}set jwks(e){As[this.storageKey]=Object.assign(Object.assign({},As[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return null!==(t=null===(e=As[this.storageKey])||void 0===e?void 0:e.cachedAt)&&void 0!==t?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){As[this.storageKey]=Object.assign(Object.assign({},As[this.storageKey]),{cachedAt:e})}constructor(e){var t,r;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=$s.nextInstanceID,$s.nextInstanceID+=1,this.instanceID>0&&$r();const s=Object.assign(Object.assign({},Ps),e);if(this.logDebugMessages=!!s.debug,"function"==typeof s.debug&&(this.logger=s.debug),this.persistSession=s.persistSession,this.storageKey=s.storageKey,this.autoRefreshToken=s.autoRefreshToken,this.admin=new os({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=Nr(s.fetch),this.lock=s.lock||Rs,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,s.lock?this.lock=s.lock:$r()&&(null===(t=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===t?void 0:t.locks)?this.lock=us:this.lock=Rs,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 Is(this)},this.persistSession?(s.storage?this.storage=s.storage:xr()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=as(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=as(this.memoryStorage)),$r()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){}null===(r=this.broadcastChannel)||void 0===r||r.addEventListener("message",async e=>{this._debug("received broadcast notification from other tab or client",e),await this._notifyAllSubscribers(e.data.event,e.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${tr}) ${(new Date).toISOString()}`,...e),this}async initialize(){return this.initializePromise||(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))()),await this.initializePromise}async _initialize(){var e;try{const t=function(e){const t={},r=new URL(e);if(r.hash&&"#"===r.hash[0])try{new URLSearchParams(r.hash.substring(1)).forEach((e,r)=>{t[r]=e})}catch(s){}return r.searchParams.forEach((e,r)=>{t[r]=e}),t}(window.location.href);let r="none";if(this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce"),$r()&&this.detectSessionInUrl&&"none"!==r){const{data:s,error:i}=await this._getSessionFromURL(t,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),function(e){return cr(e)&&"AuthImplicitGrantRedirectError"===e.name}(i)){const t=null===(e=i.details)||void 0===e?void 0:e.code;if("identity_already_exists"===t||"identity_not_found"===t||"single_identity_not_deletable"===t)return{error:i}}return await this._removeSession(),{error:i}}const{session:n,redirectType:o}=s;return this._debug("#_initialize()","detected session in URL",n,"redirect type",o),await this._saveSession(n),setTimeout(async()=>{"recovery"===o?await this._notifyAllSubscribers("PASSWORD_RECOVERY",n):await this._notifyAllSubscribers("SIGNED_IN",n)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return cr(t)?{error:t}:{error:new ur("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{const i=await Xr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:null!==(r=null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.data)&&void 0!==r?r:{},gotrue_meta_security:{captcha_token:null===(s=null==e?void 0:e.options)||void 0===s?void 0:s.captchaToken}},xform:Zr}),{data:n,error:o}=i;if(o||!n)return{data:{user:null,session:null},error:o};const a=n.session,l=n.user;return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",a)),{data:{user:l,session:a},error:null}}catch(i){if(cr(i))return{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:r,password:s,options:n}=e;let o=null,a=null;"pkce"===this.flowType&&([o,a]=await Mr(this.storage,this.storageKey)),i=await Xr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:null==n?void 0:n.emailRedirectTo,body:{email:r,password:s,data:null!==(t=null==n?void 0:n.data)&&void 0!==t?t:{},gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken},code_challenge:o,code_challenge_method:a},xform:Zr})}else{if(!("phone"in e))throw new gr("You must provide either an email or phone number and a password");{const{phone:t,password:n,options:o}=e;i=await Xr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:n,data:null!==(r=null==o?void 0:o.data)&&void 0!==r?r:{},channel:null!==(s=null==o?void 0:o.channel)&&void 0!==s?s:"sms",gotrue_meta_security:{captcha_token:null==o?void 0:o.captchaToken}},xform:Zr})}}const{data:n,error:o}=i;if(o||!n)return{data:{user:null,session:null},error:o};const a=n.session,l=n.user;return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",a)),{data:{user:l,session:a},error:null}}catch(i){if(cr(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithPassword(e){try{let t;if("email"in e){const{email:r,password:s,options:i}=e;t=await Xr(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:r,password:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:es})}else{if(!("phone"in e))throw new gr("You must provide either an email or phone number and a password");{const{phone:r,password:s,options:i}=e;t=await Xr(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:r,password:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:es})}}const{data:r,error:s}=t;return s?{data:{user:null,session:null},error:s}:r&&r.session&&r.user?(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s}):{data:{user:null,session:null},error:new pr}}catch(t){if(cr(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,r,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:null===(t=e.options)||void 0===t?void 0:t.redirectTo,scopes:null===(r=e.options)||void 0===r?void 0:r.scopes,queryParams:null===(s=e.options)||void 0===s?void 0:s.queryParams,skipBrowserRedirect:null===(i=e.options)||void 0===i?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,s,i,n,o,a,l,c,h,u;let d,f;if("message"in e)d=e.message,f=e.signature;else{const{chain:h,wallet:u,statement:p,options:g}=e;let w;if($r())if("object"==typeof u)w=u;else{const e=window;if(!("ethereum"in e)||"object"!=typeof e.ethereum||!("request"in e.ethereum)||"function"!=typeof e.ethereum.request)throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.");w=e.ethereum}else{if("object"!=typeof u||!(null==g?void 0:g.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");w=u}const v=new URL(null!==(t=null==g?void 0:g.url)&&void 0!==t?t:window.location.href),y=await w.request({method:"eth_requestAccounts"}).then(e=>e).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!y||0===y.length)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const m=ds(y[0]);let b=null===(r=null==g?void 0:g.signInWithEthereum)||void 0===r?void 0:r.chainId;if(!b){const e=await w.request({method:"eth_chainId"});b=parseInt(e,16)}d=function(e){var t;const{chainId:r,domain:s,expirationTime:i,issuedAt:n=new Date,nonce:o,notBefore:a,requestId:l,resources:c,scheme:h,uri:u,version:d}=e;if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!s)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!u)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if("1"!==d)throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${d}`);if(null===(t=e.statement)||void 0===t?void 0:t.includes("\n"))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);const f=`${h?`${h}://${s}`:s} wants you to sign in with your Ethereum account:\n${ds(e.address)}\n\n${e.statement?`${e.statement}\n`:""}`;let p=`URI: ${u}\nVersion: ${d}\nChain ID: ${r}${o?`\nNonce: ${o}`:""}\nIssued At: ${n.toISOString()}`;if(i&&(p+=`\nExpiration Time: ${i.toISOString()}`),a&&(p+=`\nNot Before: ${a.toISOString()}`),l&&(p+=`\nRequest ID: ${l}`),c){let e="\nResources:";for(const t of c){if(!t||"string"!=typeof t)throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${t}`);e+=`\n- ${t}`}p+=e}return`${f}\n${p}`}({domain:v.host,address:m,statement:p,uri:v.href,version:"1",chainId:b,nonce:null===(s=null==g?void 0:g.signInWithEthereum)||void 0===s?void 0:s.nonce,issuedAt:null!==(n=null===(i=null==g?void 0:g.signInWithEthereum)||void 0===i?void 0:i.issuedAt)&&void 0!==n?n:new Date,expirationTime:null===(o=null==g?void 0:g.signInWithEthereum)||void 0===o?void 0:o.expirationTime,notBefore:null===(a=null==g?void 0:g.signInWithEthereum)||void 0===a?void 0:a.notBefore,requestId:null===(l=null==g?void 0:g.signInWithEthereum)||void 0===l?void 0:l.requestId,resources:null===(c=null==g?void 0:g.signInWithEthereum)||void 0===c?void 0:c.resources}),f=await w.request({method:"personal_sign",params:[fs(d),m]})}try{const{data:t,error:r}=await Xr(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:d,signature:f},(null===(h=e.options)||void 0===h?void 0:h.captchaToken)?{gotrue_meta_security:{captcha_token:null===(u=e.options)||void 0===u?void 0:u.captchaToken}}:null),xform:Zr});if(r)throw r;return t&&t.session&&t.user?(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),{data:Object.assign({},t),error:r}):{data:{user:null,session:null},error:new pr}}catch(p){if(cr(p))return{data:{user:null,session:null},error:p};throw p}}async signInWithSolana(e){var t,r,s,i,n,o,a,l,c,h,u,d;let f,p;if("message"in e)f=e.message,p=e.signature;else{const{chain:u,wallet:d,statement:g,options:w}=e;let v;if($r())if("object"==typeof d)v=d;else{const e=window;if(!("solana"in e)||"object"!=typeof e.solana||!("signIn"in e.solana&&"function"==typeof e.solana.signIn||"signMessage"in e.solana&&"function"==typeof e.solana.signMessage))throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.");v=e.solana}else{if("object"!=typeof d||!(null==w?void 0:w.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");v=d}const y=new URL(null!==(t=null==w?void 0:w.url)&&void 0!==t?t:window.location.href);if("signIn"in v&&v.signIn){const e=await v.signIn(Object.assign(Object.assign(Object.assign({issuedAt:(new Date).toISOString()},null==w?void 0:w.signInWithSolana),{version:"1",domain:y.host,uri:y.href}),g?{statement:g}:null));let t;if(Array.isArray(e)&&e[0]&&"object"==typeof e[0])t=e[0];else{if(!(e&&"object"==typeof e&&"signedMessage"in e&&"signature"in e))throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");t=e}if(!("signedMessage"in t&&"signature"in t&&("string"==typeof t.signedMessage||t.signedMessage instanceof Uint8Array)&&t.signature instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields");f="string"==typeof t.signedMessage?t.signedMessage:(new TextDecoder).decode(t.signedMessage),p=t.signature}else{if(!("signMessage"in v&&"function"==typeof v.signMessage&&"publicKey"in v&&"object"==typeof v&&v.publicKey&&"toBase58"in v.publicKey&&"function"==typeof v.publicKey.toBase58))throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");f=[`${y.host} wants you to sign in with your Solana account:`,v.publicKey.toBase58(),...g?["",g,""]:[""],"Version: 1",`URI: ${y.href}`,`Issued At: ${null!==(s=null===(r=null==w?void 0:w.signInWithSolana)||void 0===r?void 0:r.issuedAt)&&void 0!==s?s:(new Date).toISOString()}`,...(null===(i=null==w?void 0:w.signInWithSolana)||void 0===i?void 0:i.notBefore)?[`Not Before: ${w.signInWithSolana.notBefore}`]:[],...(null===(n=null==w?void 0:w.signInWithSolana)||void 0===n?void 0:n.expirationTime)?[`Expiration Time: ${w.signInWithSolana.expirationTime}`]:[],...(null===(o=null==w?void 0:w.signInWithSolana)||void 0===o?void 0:o.chainId)?[`Chain ID: ${w.signInWithSolana.chainId}`]:[],...(null===(a=null==w?void 0:w.signInWithSolana)||void 0===a?void 0:a.nonce)?[`Nonce: ${w.signInWithSolana.nonce}`]:[],...(null===(l=null==w?void 0:w.signInWithSolana)||void 0===l?void 0:l.requestId)?[`Request ID: ${w.signInWithSolana.requestId}`]:[],...(null===(h=null===(c=null==w?void 0:w.signInWithSolana)||void 0===c?void 0:c.resources)||void 0===h?void 0:h.length)?["Resources",...w.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join("\n");const e=await v.signMessage((new TextEncoder).encode(f),"utf8");if(!(e&&e instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");p=e}}try{const{data:t,error:r}=await Xr(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:f,signature:Ar(p)},(null===(u=e.options)||void 0===u?void 0:u.captchaToken)?{gotrue_meta_security:{captcha_token:null===(d=e.options)||void 0===d?void 0:d.captchaToken}}:null),xform:Zr});if(r)throw r;return t&&t.session&&t.user?(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),{data:Object.assign({},t),error:r}):{data:{user:null,session:null},error:new pr}}catch(g){if(cr(g))return{data:{user:null,session:null},error:g};throw g}}async _exchangeCodeForSession(e){const t=await Dr(this.storage,`${this.storageKey}-code-verifier`),[r,s]=(null!=t?t:"").split("/");try{const{data:t,error:i}=await Xr(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:Zr});if(await Lr(this.storage,`${this.storageKey}-code-verifier`),i)throw i;return t&&t.session&&t.user?(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),{data:Object.assign(Object.assign({},t),{redirectType:null!=s?s:null}),error:i}):{data:{user:null,session:null,redirectType:null},error:new pr}}catch(i){if(cr(i))return{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:n}=e,o=await Xr(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:i,nonce:n,gotrue_meta_security:{captcha_token:null==t?void 0:t.captchaToken}},xform:Zr}),{data:a,error:l}=o;return l?{data:{user:null,session:null},error:l}:a&&a.session&&a.user?(a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),{data:a,error:l}):{data:{user:null,session:null},error:new pr}}catch(t){if(cr(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,r,s,i,n;try{if("email"in e){const{email:s,options:i}=e;let n=null,o=null;"pkce"===this.flowType&&([n,o]=await Mr(this.storage,this.storageKey));const{error:a}=await Xr(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:s,data:null!==(t=null==i?void 0:i.data)&&void 0!==t?t:{},create_user:null===(r=null==i?void 0:i.shouldCreateUser)||void 0===r||r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:n,code_challenge_method:o},redirectTo:null==i?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:a}}if("phone"in e){const{phone:t,options:r}=e,{data:o,error:a}=await Xr(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:null!==(s=null==r?void 0:r.data)&&void 0!==s?s:{},create_user:null===(i=null==r?void 0:r.shouldCreateUser)||void 0===i||i,gotrue_meta_security:{captcha_token:null==r?void 0:r.captchaToken},channel:null!==(n=null==r?void 0:r.channel)&&void 0!==n?n:"sms"}});return{data:{user:null,session:null,messageId:null==o?void 0:o.message_id},error:a}}throw new gr("You must provide either an email or phone number.")}catch(o){if(cr(o))return{data:{user:null,session:null},error:o};throw o}}async verifyOtp(e){var t,r;try{let s,i;"options"in e&&(s=null===(t=e.options)||void 0===t?void 0:t.redirectTo,i=null===(r=e.options)||void 0===r?void 0:r.captchaToken);const{data:n,error:o}=await Xr(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:Zr});if(o)throw o;if(!n)throw new Error("An error occurred on token verification.");const a=n.session,l=n.user;return(null==a?void 0:a.access_token)&&(await this._saveSession(a),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",a)),{data:{user:l,session:a},error:null}}catch(s){if(cr(s))return{data:{user:null,session:null},error:s};throw s}}async signInWithSSO(e){var t,r,s;try{let i=null,n=null;return"pkce"===this.flowType&&([i,n]=await Mr(this.storage,this.storageKey)),await Xr(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:null!==(r=null===(t=e.options)||void 0===t?void 0:t.redirectTo)&&void 0!==r?r:void 0}),(null===(s=null==e?void 0:e.options)||void 0===s?void 0:s.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:i,code_challenge_method:n}),headers:this.headers,xform:rs})}catch(i){if(cr(i))return{data:null,error:i};throw i}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new fr;const{error:s}=await Xr(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:s}})}catch(e){if(cr(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{const t=`${this.url}/resend`;if("email"in e){const{email:r,type:s,options:i}=e,{error:n}=await Xr(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},redirectTo:null==i?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:n}}if("phone"in e){const{phone:r,type:s,options:i}=e,{data:n,error:o}=await Xr(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}}});return{data:{user:null,session:null,messageId:null==n?void 0:n.message_id},error:o}}throw new gr("You must provide either an email or phone number and a type")}catch(t){if(cr(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){await this.initializePromise;return await this._acquireLock(-1,async()=>this._useSession(async e=>e))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch(e){}})()),r}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(t){}})()),await e;this.pendingInLock.length;){const e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",(new Error).stack);try{let e=null;const t=await Dr(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),null!==t&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const r=!!e.expires_at&&1e3*e.expires_at-Date.now()<sr;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.userStorage){const t=await Dr(this.userStorage,this.storageKey+"-user");(null==t?void 0:t.user)?e.user=t.user:e.user=Hr()}if(this.storage.isServer&&e.user){let t=this.suppressGetSessionWarning;e=new Proxy(e,{get:(e,r,s)=>(t||"user"!==r||(t=!0,this.suppressGetSessionWarning=!0),Reflect.get(e,r,s))})}return{data:{session:e},error:null}}const{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{session:null},error:i}:{data:{session:s},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;return await this._acquireLock(-1,async()=>await this._getUser())}async _getUser(e){try{return e?await Xr(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ts}):await this._useSession(async e=>{var t,r,s;const{data:i,error:n}=e;if(n)throw n;return(null===(t=i.session)||void 0===t?void 0:t.access_token)||this.hasCustomAuthorizationHeader?await Xr(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!==(s=null===(r=i.session)||void 0===r?void 0:r.access_token)&&void 0!==s?s:void 0,xform:ts}):{data:{user:null},error:new fr}})}catch(t){if(cr(t))return function(e){return cr(e)&&"AuthSessionMissingError"===e.name}(t)&&(await this._removeSession(),await Lr(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{const{data:s,error:i}=r;if(i)throw i;if(!s.session)throw new fr;const n=s.session;let o=null,a=null;"pkce"===this.flowType&&null!=e.email&&([o,a]=await Mr(this.storage,this.storageKey));const{data:l,error:c}=await Xr(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:a}),jwt:n.access_token,xform:ts});if(c)throw c;return n.user=l.user,await this._saveSession(n),await this._notifyAllSubscribers("USER_UPDATED",n),{data:{user:n.user},error:null}})}catch(r){if(cr(r))return{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 fr;const t=Date.now()/1e3;let r=t,s=!0,i=null;const{payload:n}=qr(e.access_token);if(n.exp&&(r=n.exp,s=r<=t),s){const{data:t,error:r}=await this._callRefreshToken(e.refresh_token);if(r)return{data:{user:null,session:null},error:r};if(!t)return{data:{user:null,session:null},error:null};i=t}else{const{data:s,error:n}=await this._getUser(e.access_token);if(n)throw n;i={access_token:e.access_token,refresh_token:e.refresh_token,user:s.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(t){if(cr(t))return{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:s,error:i}=t;if(i)throw i;e=null!==(r=s.session)&&void 0!==r?r:void 0}if(!(null==e?void 0:e.refresh_token))throw new fr;const{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{user:null,session:null},error:i}:s?{data:{user:s.user,session:s},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(cr(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e,t){try{if(!$r())throw new wr("No browser detected.");if(e.error||e.error_description||e.error_code)throw new wr(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("pkce"===this.flowType)throw new vr("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new wr("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new vr("No code detected.");const{data:t,error:r}=await this._exchangeCodeForSession(e.code);if(r)throw r;const s=new URL(window.location.href);return s.searchParams.delete("code"),window.history.replaceState(window.history.state,"",s.toString()),{data:{session:t.session,redirectType:null},error:null}}const{provider_token:r,provider_refresh_token:s,access_token:i,refresh_token:n,expires_in:o,expires_at:a,token_type:l}=e;if(!(i&&o&&n&&l))throw new wr("No session defined in URL");const c=Math.round(Date.now()/1e3),h=parseInt(o);let u=c+h;a&&(u=parseInt(a));const{data:d,error:f}=await this._getUser(i);if(f)throw f;const p={provider_token:r,provider_refresh_token:s,access_token:i,expires_in:h,expires_at:u,refresh_token:n,token_type:l,user:d.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:p,redirectType:e.type},error:null}}catch(r){if(cr(r))return{data:{session:null,redirectType:null},error:r};throw r}}_isImplicitGrantCallback(e){return Boolean(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await Dr(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{error:i};const n=null===(r=s.session)||void 0===r?void 0:r.access_token;if(n){const{error:t}=await this.admin.signOut(n,e);if(t&&(!function(e){return cr(e)&&"AuthApiError"===e.name}(t)||404!==t.status&&401!==t.status&&403!==t.status))return{error:t}}return"others"!==e&&(await this._removeSession(),await Lr(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){const t="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}),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:s},error:i}=t;if(i)throw i;await(null===(r=this.stateChangeEmitters.get(e))||void 0===r?void 0:r.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(i){await(null===(s=this.stateChangeEmitters.get(e))||void 0===s?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null;"pkce"===this.flowType&&([r,s]=await Mr(this.storage,this.storageKey,!0));try{return await Xr(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(cr(i))return{data:null,error:i};throw i}}async getUserIdentities(){var e;try{const{data:t,error:r}=await this.getUser();if(r)throw r;return{data:{identities:null!==(e=t.user.identities)&&void 0!==e?e:[]},error:null}}catch(t){if(cr(t))return{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 t=>{var r,s,i,n,o;const{data:a,error:l}=t;if(l)throw l;const c=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:null===(r=e.options)||void 0===r?void 0:r.redirectTo,scopes:null===(s=e.options)||void 0===s?void 0:s.scopes,queryParams:null===(i=e.options)||void 0===i?void 0:i.queryParams,skipBrowserRedirect:!0});return await Xr(this.fetch,"GET",c,{headers:this.headers,jwt:null!==(o=null===(n=a.session)||void 0===n?void 0:n.access_token)&&void 0!==o?o:void 0})});if(s)throw s;return $r()&&!(null===(t=e.options)||void 0===t?void 0:t.skipBrowserRedirect)&&window.location.assign(null==r?void 0:r.url),{data:{provider:e.provider,url:null==r?void 0:r.url},error:null}}catch(r){if(cr(r))return{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:n,provider:o,token:a,access_token:l,nonce:c}=e,h=await Xr(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:null!==(r=null==i?void 0:i.access_token)&&void 0!==r?r:void 0,body:{provider:o,id_token:a,access_token:l,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},xform:Zr}),{data:u,error:d}=h;return d?{data:{user:null,session:null},error:d}:u&&u.session&&u.user?(u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers("USER_UPDATED",u.session)),{data:u,error:d}):{data:{user:null,session:null},error:new pr}}catch(s){if(cr(s))return{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:n}=t;if(n)throw n;return await Xr(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:null!==(s=null===(r=i.session)||void 0===r?void 0:r.access_token)&&void 0!==s?s:void 0})})}catch(t){if(cr(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const i=Date.now();return await(r=async r=>(r>0&&await async function(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await Xr(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Zr})),s=(e,t)=>{const r=200*Math.pow(2,e);return t&&mr(t)&&Date.now()+r-i<rr},new Promise((e,t)=>{(async()=>{for(let n=0;n<1/0;n++)try{const t=await r(n);if(!s(n,null,t))return void e(t)}catch(i){if(!s(n,i))return void t(i)}})()}))}catch(i){if(this._debug(t,"error",i),cr(i))return{data:{session:null,user:null},error:i};throw i}finally{this._debug(t,"end")}var r,s}_isValidSession(e){return"object"==typeof e&&null!==e&&"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),$r()&&!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 i=await Dr(this.storage,this.storageKey);if(i&&this.userStorage){let t=await Dr(this.userStorage,this.storageKey+"-user");this.storage.isServer||!Object.is(this.storage,this.userStorage)||t||(t={user:i.user},await Ur(this.userStorage,this.storageKey+"-user",t)),i.user=null!==(e=null==t?void 0:t.user)&&void 0!==e?e:Hr()}else if(i&&!i.user&&!i.user){const e=await Dr(this.storage,this.storageKey+"-user");e&&(null==e?void 0:e.user)?(i.user=e.user,await Lr(this.storage,this.storageKey+"-user"),await Ur(this.storage,this.storageKey,i)):i.user=Hr()}if(this._debug(r,"session from storage",i),!this._isValidSession(i))return this._debug(r,"session is not valid"),void(null!==i&&await this._removeSession());const n=1e3*(null!==(t=i.expires_at)&&void 0!==t?t:1/0)-Date.now()<sr;if(this._debug(r,`session has${n?"":" not"} expired with margin of 90000s`),n){if(this.autoRefreshToken&&i.refresh_token){const{error:e}=await this._callRefreshToken(i.refresh_token);e&&(mr(e)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",e),await this._removeSession()))}}else if(i.user&&!0===i.user.__isUserNotAvailableProxy)try{const{data:e,error:t}=await this._getUser(i.access_token);!t&&(null==e?void 0:e.user)?(i.user=e.user,await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(s){this._debug(r,"error getting user data, skipping SIGNED_IN notification",s)}else await this._notifyAllSubscribers("SIGNED_IN",i)}catch(i){return void this._debug(r,"error",i)}finally{this._debug(r,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new fr;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new Br;const{data:t,error:r}=await this._refreshAccessToken(e);if(r)throw r;if(!t.session)throw new fr;await this._saveSession(t.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",t.session);const s={data:t.session,error:null};return this.refreshingDeferred.resolve(s),s}catch(i){if(this._debug(s,"error",i),cr(i)){const e={data:null,error:i};return mr(i)||await this._removeSession(),null===(t=this.refreshingDeferred)||void 0===t||t.resolve(e),e}throw null===(r=this.refreshingDeferred)||void 0===r||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 s=[],i=Array.from(this.stateChangeEmitters.values()).map(async r=>{try{await r.callback(e,t)}catch(i){s.push(i)}});if(await Promise.all(i),s.length>0){for(let e=0;e<s.length;e+=1);throw s[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0;const t=Object.assign({},e),r=t.user&&!0===t.user.__isUserNotAvailableProxy;if(this.userStorage){!r&&t.user&&await Ur(this.userStorage,this.storageKey+"-user",{user:t.user});const e=Object.assign({},t);delete e.user;const s=zr(e);await Ur(this.storage,this.storageKey,s)}else{const e=zr(t);await Ur(this.storage,this.storageKey,e)}}async _removeSession(){this._debug("#_removeSession()"),await Lr(this.storage,this.storageKey),await Lr(this.storage,this.storageKey+"-code-verifier"),await Lr(this.storage,this.storageKey+"-user"),this.userStorage&&await Lr(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&$r()&&(null===window||void 0===window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(t){}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),rr);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&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 t=Date.now();try{return await this._useSession(async e=>{const{data:{session:r}}=e;if(!r||!r.refresh_token||!r.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");const s=Math.floor((1e3*r.expires_at-t)/rr);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),s<=3&&await this._callRefreshToken(r.refresh_token)})}catch(e){}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(!(e.isAcquireTimeout||e instanceof cs))throw e;this._debug("auto refresh token tick lock not available")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!$r()||!(null===window||void 0===window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),null===window||void 0===window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{"visible"===document.visibilityState?await this._recoverAndRefresh():this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting")}))):"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){const s=[`provider=${encodeURIComponent(t)}`];if((null==r?void 0:r.redirectTo)&&s.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),(null==r?void 0:r.scopes)&&s.push(`scopes=${encodeURIComponent(r.scopes)}`),"pkce"===this.flowType){const[e,t]=await Mr(this.storage,this.storageKey),r=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});s.push(r.toString())}if(null==r?void 0:r.queryParams){const e=new URLSearchParams(r.queryParams);s.push(e.toString())}return(null==r?void 0: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?{data:null,error:i}:await Xr(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token})})}catch(t){if(cr(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;const{data:i,error:n}=t;if(n)return{data:null,error:n};const o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:"totp"===e.factorType?{issuer:e.issuer}:{}),{data:a,error:l}=await Xr(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:null===(r=null==i?void 0:i.session)||void 0===r?void 0:r.access_token});return l?{data:null,error:l}:("totp"===e.factorType&&"totp"===a.type&&(null===(s=null==a?void 0:a.totp)||void 0===s?void 0:s.qr_code)&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(cr(t))return{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{data:null,error:i};const n=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:"create"===e.webauthn.type?_s(e.webauthn.credential_response):ks(e.webauthn.credential_response)})}:{code:e.code}),{data:o,error:a}=await Xr(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:n,headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(cr(t))return{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{data:null,error:i};const n=await Xr(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token});if(n.error)return n;const{data:o}=n;if("webauthn"!==o.type)return{data:o,error:null};switch(o.webauthn.type){case"create":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:ms(o.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:bs(o.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(t){if(cr(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){const{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?{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 null!==(e=null==t?void 0:t.factors)&&void 0!==e?e:[])s.all.push(i),"verified"===i.status&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,r;const{data:{session:s},error:i}=e;if(i)return{data:null,error:i};if(!s)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:n}=qr(s.access_token);let o=null;n.aal&&(o=n.aal);let a=o;(null!==(r=null===(t=s.user.factors)||void 0===t?void 0:t.filter(e=>"verified"===e.status))&&void 0!==r?r:[]).length>0&&(a="aal2");return{data:{currentLevel:o,nextLevel:a,currentAuthenticationMethods:n.amr||[]},error:null}}))}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(t=>t.kid===e);if(r)return r;const s=Date.now();if(r=this.jwks.keys.find(t=>t.kid===e),r&&this.jwks_cached_at+6e5>s)return r;const{data:i,error:n}=await Xr(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(n)throw n;return i.keys&&0!==i.keys.length?(this.jwks=i,this.jwks_cached_at=s,r=i.keys.find(t=>t.kid===e),r||null):null}async getClaims(e,t={}){try{let r=e;if(!r){const{data:e,error:t}=await this.getSession();if(t||!e.session)return{data:null,error:t};r=e.session.access_token}const{header:s,payload:i,signature:n,raw:{header:o,payload:a}}=qr(r);(null==t?void 0:t.allowExpired)||function(e){if(!e)throw new Error("Missing exp claim");if(e<=Math.floor(Date.now()/1e3))throw new Error("JWT has expired")}(i.exp);const l=s.alg&&!s.alg.startsWith("HS")&&s.kid&&"crypto"in globalThis&&"subtle"in globalThis.crypto?await this.fetchJwk(s.kid,(null==t?void 0:t.keys)?{keys:t.keys}:null==t?void 0:t.jwks):null;if(!l){const{error:e}=await this.getUser(r);if(e)throw e;return{data:{claims:i,header:s,signature:n},error:null}}const c=function(e){switch(e){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")}}(s.alg),h=await crypto.subtle.importKey("jwk",l,c,!0,["verify"]);if(!(await crypto.subtle.verify(c,h,n,Rr(`${o}.${a}`))))throw new _r("Invalid JWT signature");return{data:{claims:i,header:s,signature:n},error:null}}catch(r){if(cr(r))return{data:null,error:r};throw r}}}$s.nextInstanceID=0;const Cs=$s;class xs extends Cs{constructor(e){super(e)}}class Ns{constructor(e,t,r){var s,i,n;this.supabaseUrl=e,this.supabaseKey=t;const o=function(e){const t=null==e?void 0:e.trim();if(!t)throw new Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL((r=t).endsWith("/")?r:r+"/")}catch(s){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}var r}(e);if(!t)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",o),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",o),this.storageUrl=new URL("storage/v1",o),this.functionsUrl=new URL("functions/v1",o);const a=`sb-${o.hostname.split(".")[0]}-auth-token`,l=function(e,t){var r,s;const{db:i,auth:n,realtime:o,global:a}=e,{db:l,auth:c,realtime:h,global:u}=t,d={db:Object.assign(Object.assign({},l),i),auth:Object.assign(Object.assign({},c),n),realtime:Object.assign(Object.assign({},h),o),storage:{},global:Object.assign(Object.assign(Object.assign({},u),a),{headers:Object.assign(Object.assign({},null!==(r=null==u?void 0:u.headers)&&void 0!==r?r:{}),null!==(s=null==a?void 0:a.headers)&&void 0!==s?s:{})}),accessToken:async()=>""};return e.accessToken?d.accessToken=e.accessToken:delete d.accessToken,d}(null!=r?r:{},{db:Qt,realtime:Zt,auth:Object.assign(Object.assign({},Xt),{storageKey:a}),global:Yt});this.storageKey=null!==(s=l.auth.storageKey)&&void 0!==s?s:"",this.headers=null!==(i=l.global.headers)&&void 0!==i?i:{},l.accessToken?(this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(t)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(null!==(n=l.auth)&&void 0!==n?n:{},this.headers,l.global.fetch),this.fetch=er(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.rest=new de(new URL("rest/v1",o).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this.storage=new zt(this.storageUrl.href,this.headers,this.fetch,null==r?void 0:r.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new S(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 null!==(t=null===(e=r.session)||void 0===e?void 0:e.access_token)&&void 0!==t?t:this.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:i,storageKey:n,flowType:o,lock:a,debug:l},c,h){const u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new xs({url:this.authUrl.href,headers:Object.assign(Object.assign({},u),c),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:i,flowType:o,lock:a,debug:l,fetch:h,hasCustomAuthorizationHeader:Object.keys(this.headers).some(e=>"authorization"===e.toLowerCase())})}_initRealtimeClient(e){return new nt(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},null==e?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",null==t?void 0:t.access_token)})}_handleTokenChanged(e,t,r){"TOKEN_REFRESHED"!==e&&"SIGNED_IN"!==e||this.changedAccessToken===r?"SIGNED_OUT"===e&&(this.realtime.setAuth(),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0):(this.changedAccessToken=r,this.realtime.setAuth(r))}}!function(){if("undefined"!=typeof window)return!1;if("undefined"==typeof process)return!1;const e=process.version;if(null==e)return!1;const t=e.match(/^v(\d+)\./);!!t&&parseInt(t[1],10)}();const Us=(Ds={auth:{storage:localStorage,persistSession:!0,autoRefreshToken:!0}},new Ns("https://zivvkvoaqggapqnpxtcs.supabase.co","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InppdnZrdm9hcWdnYXBxbnB4dGNzIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE3ODE4NTIsImV4cCI6MjA3NzM1Nzg1Mn0.ZQ5S4uGnt2sJolruezkf3G5PxQL-8dfwb9tMEMAd-Js",Ds));var Ds;export{d as I,w as L,u as a,Us as s};