PageSourceSearch

https://merchforall.com/_next/static/chunks/338-dd0a4a884e161982.js

js merchforall.com collected 2026-09-24 13:39:51 UTC 179,562 bytes, 56 lines download raw bytes

1!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},t=(new e.Error).stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5d6b3b77-ddc9-482d-89e7-9587b988cc8e",e._sentryDebugIdIdentifier="sentry-dbid-5d6b3b77-ddc9-482d-89e7-9587b988cc8e")}catch(e){}}();"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[338],{80485:function(e,t,r){r.r(t),r.d(t,{Headers:function(){return n},Request:function(){return a},Response:function(){return o},fetch:function(){return i}});var s=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==r.g)return r.g;throw Error("unable to locate global object")}();let i=s.fetch;t.default=s.fetch.bind(s);let n=s.Headers,a=s.Request,o=s.Response},35257:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});let s=r(5853),i=s.__importDefault(r(80485)),n=s.__importDefault(r(63038));class a{constructor(e){var t,r;this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=null!==(t=e.shouldThrowOnError)&&void 0!==t&&t,this.signal=e.signal,this.isMaybeSingle=null!==(r=e.isMaybeSingle)&&void 0!==r&&r,e.fetch?this.fetch=e.fetch:"undefined"==typeof fetch?this.fetch=i.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}then(e,t){void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),"GET"!==this.method&&"HEAD"!==this.method&&this.headers.set("Content-Type","application/json");let r=(0,this.fetch)(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async e=>{var t,r,s,i;let a=null,o=null,l=null,u=e.status,h=e.statusText;if(e.ok){if("HEAD"!==this.method){let r=await e.text();""===r||(o="text/csv"===this.headers.get("Accept")?r: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))}let i=null===(r=this.headers.get("Prefer"))||void 0===r?void 0:r.match(/count=(exact|planned|estimated)/),n=null===(s=e.headers.get("content-range"))||void 0===s?void 0:s.split("/");i&&n&&n.length>1&&(l=parseInt(n[1])),this.isMaybeSingle&&"GET"===this.method&&Array.isArray(o)&&(o.length>1?(a={code:"PGRST116",details:`Results contain ${o.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},o=null,l=null,u=406,h="Not Acceptable"):o=1===o.length?o[0]:null)}else{let t=await e.text();try{a=JSON.parse(t),Array.isArray(a)&&404===e.status&&(o=[],a=null,u=200,h="OK")}catch(r){404===e.status&&""===t?(u=204,h="No Content"):a={message:t}}if(a&&this.isMaybeSingle&&(null===(i=null==a?void 0:a.details)||void 0===i?void 0:i.includes("0 rows"))&&(a=null,u=200,h="OK"),a&&this.shouldThrowOnError)throw new n.default(a)}return{error:a,data:o,count:l,status:u,statusText:h}});return this.shouldThrowOnError||(r=r.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:""}})),r.then(e,t)}returns(){return this}overrideTypes(){return this}}t.default=a},79590:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});let s=r(5853),i=s.__importDefault(r(40934)),n=s.__importDefault(r(22495));class a{constructor(e,{headers:t={},schema:r,fetch:s}={}){this.url=e,this.headers=new Headers(t),this.schemaName=r,this.fetch=s}from(e){let t=new URL(`${this.url}/${e}`);return new i.default(t,{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new a(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:s=!1,count:i}={}){var a;let o,l;let u=new URL(`${this.url}/rpc/${e}`);r||s?(o=r?"HEAD":"GET",Object.entries(t).filter(([e,t])=>void 0!==t).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}
1`]).forEach(([e,t])=>{u.searchParams.append(e,t)})):(o="POST",l=t);let h=new Headers(this.headers);return i&&h.set("Prefer",`count=${i}`),new n.default({method:o,url:u,headers:h,schema:this.schemaName,body:l,fetch:null!==(a=this.fetch)&&void 0!==a?a:fetch})}}t.default=a},63038:function(e,t){Object.defineProperty(t,"__esModule",{value:!0});class r extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}}t.default=r},22495:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});let s=r(5853).__importDefault(r(3377));class i extends s.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let r=Array.from(new Set(t)).map(e=>"string"==typeof e&&RegExp("[,()]").test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),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");let 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}={}){let 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}}t.default=i},40934:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});let s=r(5853).__importDefault(r(22495));class i{constructor(e,{headers:t={},schema:r,fetch:s}){this.url=e,this.headers=new Headers(t),this.schema=r,this.fetch=s}select(e,t){let{head:r=!1,count:i}=null!=t?t:{},n=!1,a=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!n?"":('"'===e&&(n=!n),e)).join("");return this.url.searchParams.set("select",a),i&&this.headers.append("Prefer",`count=${i}`),new s.default({method:r?"HEAD":"GET",url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(e,{count:t,defaultToNull:r=!0}={}){var i;if(t&&this.headers.append("Prefer",`count=${t}`),r||this.headers.append("Prefer","missing=default"),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);this.url.searchParams.set("columns",e.join(","))}}return new s.default({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:null!==(i=this.fetch)&&void 0!==i?i:fetch})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:i,defaultToNull:n=!0}={}){var a;if(this.headers.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),void 0!==t&&this.url.searchParams.set("on_conflict",t),i&&this.headers.append("Prefer",`count=${i}`),n||this.headers.append("Prefer","missing=default"),Array.isArray(e)){let t=e.reduce((e,t)=>
1e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);this.url.searchParams.set("columns",e.join(","))}}return new s.default({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:null!==(a=this.fetch)&&void 0!==a?a:fetch})}update(e,{count:t}={}){var r;return t&&this.headers.append("Prefer",`count=${t}`),new s.default({method:"PATCH",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:null!==(r=this.fetch)&&void 0!==r?r:fetch})}delete({count:e}={}){var t;return e&&this.headers.append("Prefer",`count=${e}`),new s.default({method:"DELETE",url:this.url,headers:this.headers,schema:this.schema,fetch:null!==(t=this.fetch)&&void 0!==t?t:fetch})}}t.default=i},3377:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});let s=r(5853).__importDefault(r(35257));class i extends s.default{select(e){let t=!1,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}={}){let n=i?`${i}.order`:"order",a=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${void 0===r?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){let s=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:s=r}={}){let 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 a;let o=[e?"analyze":null,t?"verbose":null,r?"settings":null,s?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=null!==(a=this.headers.get("Accept"))&&void 0!==a?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${n}; for="${l}"; options=${o};`),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}}t.default=i},19640:function(e,t,r){t.PostgrestError=t.PostgrestBuilder=t.PostgrestTransformBuilder=t.PostgrestFilterBuilder=t.PostgrestQueryBuilder=t.PostgrestClient=void 0;let s=r(5853),i=s.__importDefault(r(79590));t.PostgrestClient=i.default;let n=s.__importDefault(r(40934));t.PostgrestQueryBuilder=n.default;let a=s.__importDefault(r(22495));t.PostgrestFilterBuilder=a.default;let o=s.__importDefault(r(3377));t.PostgrestTransformBuilder=o.default;let l=s.__importDefault(r(35257));t.PostgrestBuilder=l.default;let u=s.__importDefault(r(63038));t.PostgrestError=u.default,i.default,n.default,a.default,o.default,l.default,u.default},20338:function(e,t,r){let s;r.d(t,{createBrowserClient:function(){return rU}});var i,n,a,o,l,u,h,c,d,f,p,g,w,y,v,m,b,_,k,S,E,O,T,j,A=r(5853);let I=e=>{let t;return e?t=e:"undefined"==typeof fetch?t=(...e)=>Promise.resolve().then(r.bind(r,80485)).then(({default:t})=>t(...e)):t=fetch,(...e)=>t(...e)};class P extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}}class R extends P{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class C extends P{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class $ extends P{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}(i=g||(g={})).Any="any",i.ApNortheast1="ap-northeast-1",i.ApNortheast2="ap-northeast-2",i.ApSouth1="ap-south-1",i.ApSoutheast1="ap-southeast-1",i.ApSoutheast2="ap-southeast-2",i.CaCentral1="ca-central-1",i.EuCentral1="eu-central-1",i.EuWest1="eu-west-1",i.EuWest2="eu-west-2",i.EuWest3="eu-west-3",i.SaEast1="sa-east-1",i.UsEast1="us-east-1",i.UsWest1="us-west-1",i.UsWest2="us-west-2";class x{constructor(e,{headers:t={},customFetch:r,region:s=g.Any}={}){this.url=e,this.headers=t,this.region=s,this.fetch=I(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return(0,A.__awaiter)(this,arguments,void 0,function*(e,t={}){var r;try{let s;let{headers:i,method:n,body:a,signal:o}=t,l={},{region:u}=t;u||(u=this.region);let h=new URL(`${this.url}/${e}`);u&&"any"!==u&&(l["x-region"]=u,h.searchParams.set("forceFunctionRegion",u)),a&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)?"undefined"!=typeof Blob&&a instanceof Blob||a instanceof ArrayBuffer?(l["Content-Type"]="application/octet-stream",s=a):"string"==typeof a?(l["Content-Type"]="text/plain",s=a):"undefined"!=typeof FormData&&a instanceof FormData?s=a:(l["Content-Type"]="application/json",s=JSON.stringify(a)):s=a;let c=yield this.fetch(h.toString(),{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},l),this.headers),i),body:s,signal:o}).catch(e=>{if("AbortError"===e.name)throw e;throw new R(e)}),d=c.headers.get("x-relay-error");
1if(d&&"true"===d)throw new C(c);if(!c.ok)throw new $(c);let f=(null!==(r=c.headers.get("Content-Type"))&&void 0!==r?r:"text/plain").split(";")[0].trim();return{data:"application/json"===f?yield c.json():"application/octet-stream"===f||"application/pdf"===f?yield c.blob():"text/event-stream"===f?c:"multipart/form-data"===f?yield c.formData():yield c.text(),error:null,response:c}}catch(e){if(e instanceof Error&&"AbortError"===e.name)return{data:null,error:new R(e)};return{data:null,error:e,response:e instanceof $||e instanceof C?e.context:void 0}}})}}let{PostgrestClient:N,PostgrestQueryBuilder:U,PostgrestFilterBuilder:D,PostgrestTransformBuilder:L,PostgrestBuilder:q,PostgrestError:B}=r(19640);var W=r(40257);class M{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(void 0!==r.g&&void 0!==r.g.WebSocket)return{type:"native",constructor:r.g.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(void 0!==W){let e=W.versions;if(e&&e.node){let t=parseInt(e.node.replace(/^v/,"").split(".")[0]);return t>=22?void 0!==globalThis.WebSocket?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${t} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${t} 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(){let e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=`
2
3Suggested solution: ${e.workaround}`),Error(t)}static createWebSocket(e,t){return new(this.getWebSocketConstructor())(e,t)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return"native"===e.type||"ws"===e.type}catch(e){return!1}}}(n=w||(w={}))[n.connecting=0]="connecting",n[n.open=1]="open",n[n.closing=2]="closing",n[n.closed=3]="closed",(a=y||(y={})).closed="closed",a.errored="errored",a.joined="joined",a.joining="joining",a.leaving="leaving",(o=v||(v={})).close="phx_close",o.error="phx_error",o.join="phx_join",o.reply="phx_reply",o.leave="phx_leave",o.access_token="access_token",(m||(m={})).websocket="websocket",(l=b||(b={})).Connecting="connecting",l.Open="open",l.Closing="closing",l.Closed="closed";class K{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):"string"==typeof e?t(JSON.parse(e)):t({})}_binaryDecode(e){let t=new DataView(e),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){let s=t.getUint8(1),i=t.getUint8(2),n=this.HEADER_LENGTH+2,a=r.decode(e.slice(n,n+s));n+=s;let o=r.decode(e.slice(n,n+i));return n+=i,{ref:null,topic:a,event:o,payload:JSON.parse(r.decode(e.slice(n,e.byteLength)))}}}class V{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))}}(u=_||(_={})).abstime="abstime",u.bool="bool",u.date="date",u.daterange="daterange",u.float4="float4",u.float8="float8",u.int2="int2",u.int4="int4",u.int4range="int4range",u.int8="int8",u.int8range="int8range",u.json="json",u.jsonb="jsonb",u.money="money",u.numeric="numeric",u.oid="oid",u.reltime="reltime",u.text="text",u.time="time",u.timestamp="timestamp",u.timestamptz="timestamptz",u.timetz="timetz",u.tsrange="tsrange",u.tstzrange="tstzrange";let F=(e,t,r={})=>{var s;let i=null!==(s=r.skipTypes)&&void 0!==s?s:[];return t?Object.keys(t).reduce((r,s)=>(r[s]=H(s,e,t,i),r),{}):{}},H=(e,t,r,s)=>{let i=t.find(t=>t.name===e),n=null==i?void 0:i.type,a=r[e];return n&&!s.includes(n)?J(n,a):z(a)},J=(e,t)=>
3{if("_"===e.charAt(0))return X(t,e.slice(1,e.length));switch(e){case _.bool:return G(t);case _.float4:case _.float8:case _.int2:case _.int4:case _.int8:case _.numeric:case _.oid:return Y(t);case _.json:case _.jsonb:return Q(t);case _.timestamp:return Z(t);case _.abstime:case _.date:case _.daterange:case _.int4range:case _.int8range:case _.money:case _.reltime:case _.text:case _.time:case _.timestamptz:case _.timetz:case _.tsrange:case _.tstzrange:default:return z(t)}},z=e=>e,G=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},Y=e=>{if("string"==typeof e){let t=parseFloat(e);if(!Number.isNaN(t))return t}return e},Q=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(e){console.log(`JSON parse error: ${e}`)}return e},X=(e,t)=>{if("string"!=typeof e)return e;let r=e.length-1,s=e[r];if("{"===e[0]&&"}"===s){let s;let i=e.slice(1,r);try{s=JSON.parse("["+i+"]")}catch(e){s=i?i.split(","):[]}return s.map(e=>J(t,e))}return e},Z=e=>"string"==typeof e?e.replace(" ","T"):e,ee=e=>{let 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 et{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(){this.timeoutTimer||(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}}(h=k||(k={})).SYNC="sync",h.JOIN="join",h.LEAVE="leave";class er{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let r=(null==t?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},e=>{let{onJoin:t,onLeave:r,onSync:s}=this.caller;this.joinRef=this.channel._joinRef(),this.state=er.syncState(this.state,e,t,r),this.pendingDiffs.forEach(e=>{this.state=er.syncDiff(this.state,e,t,r)}),this.pendingDiffs=[],s()}),this.channel._on(r.diff,{},e=>{let{onJoin:t,onLeave:r,onSync:s}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(e):(this.state=er.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){let i=this.cloneDeep(e),n=this.transformState(t),a={},o={};return this.map(i,(e,t)=>{n[e]||(o[e]=t)}),this.map(n,(e,t)=>{let r=i[e];if(r){let s=t.map(e=>e.presence_ref),i=r.map(e=>e.presence_ref),n=t.filter(e=>0>i.indexOf(e.presence_ref)),l=r.filter(e=>0>s.indexOf(e.presence_ref));n.length>0&&(a[e]=n),l.length>0&&(o[e]=l)}else a[e]=t}),this.syncDiff(i,{joins:a,leaves:o},r,s)}static syncDiff(e,t,r,s){let{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;let n=null!==(i=e[t])&&void 0!==i?i:[];if(e[t]=this.cloneDeep(s),n.length>0){let r=e[t].map(e=>e.presence_ref),s=n.filter(e=>0>r.indexOf(e.presence_ref));e[t].unshift(...s)}r(t,n,s)}),this.map(n,(t,r)=>{let i=e[t];if(!i)return;let n=r.map(e=>e.presence_ref);i=i.filter(e=>0>n.indexOf(e.presence_ref)),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 Object.getOwnPropertyNames(e=this.cloneDeep(e)).reduce((t,r)=>{let s=e[r];return"metas"in s?t[r]=s.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e)):t[r]=s,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}(c=S||(S={})).ALL="*",c.INSERT="INSERT",c.UPDATE="UPDATE",c.DELETE="DELETE",(d=E||(E={})).BROADCAST="broadcast",d.PRESENCE="presence",d.POSTGRES_CHANGES="postgres_changes",d.SYSTEM="system",(f=O||(O={})).SUBSCRIBED="SUBSCRIBED",f.TIMED_OUT="TIMED_OUT",f.CLOSED="CLOSED",f.CHANNEL_ERROR="CHANNEL_ERROR";class es{constructor(e,t={config:{}},r){var s,i;if(this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=y.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 et(this,v.join,this.params,this.timeout),this.rejoinTimer=new V(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=y.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e
3=>e.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=y.closed,this.socket._remove(this)}),this._onError(e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=y.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=y.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=y.errored,this.rejoinTimer.scheduleTimeout())}),this._on(v.reply,{},(e,t)=>{this._trigger(this._replyEventName(t),e)}),this.presence=new er(this),this.broadcastEndpointURL=ee(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==y.closed){let{config:{broadcast:n,presence:a,private:o}}=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:[],u=!!this.bindings[E.PRESENCE]&&this.bindings[E.PRESENCE].length>0||(null===(i=this.params.config.presence)||void 0===i?void 0:i.enabled)===!0,h={},c={broadcast:n,presence:Object.assign(Object.assign({},a),{enabled:u}),postgres_changes:l,private:o};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(t=>null==e?void 0:e(O.CHANNEL_ERROR,t)),this._onClose(()=>null==e?void 0:e(O.CLOSED)),this.updateJoinPayload(Object.assign({config:c},h)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:t})=>{var r;if(this.socket.setAuth(),void 0===t){null==e||e(O.SUBSCRIBED);return}{let 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++){let i=s[r],{filter:{event:a,schema:o,table:l,filter:u}}=i,h=t&&t[r];if(h&&h.event===a&&h.schema===o&&h.table===l&&h.filter===u)n.push(Object.assign(Object.assign({},i),{id:h.id}));else{this.unsubscribe(),this.state=y.errored,null==e||e(O.CHANNEL_ERROR,Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=n,e&&e(O.SUBSCRIBED);return}}).receive("error",t=>{this.state=y.errored,null==e||e(O.CHANNEL_ERROR,Error(JSON.stringify(Object.values(t).join(", ")||"error")))}).receive("timeout",()=>{null==e||e(O.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===y.joined&&e===E.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;let i=this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"";if(null==t)return Promise.reject("Payload is required for httpSend()");let 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}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,n,null!==(s=r.timeout)&&void 0!==s?s:this.timeout);if(202===a.status)return{success:!0};let o=a.statusText;try{let e=await a.json();o=e.error||e.message||o}catch(e){}return Promise.reject(Error(o))}async send(e,t={}){var r,s;if(this._canPush()||"broadcast"!==e.type)return new Promise(r=>{var s,i,n;let a=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"),a.receive("ok",()=>r("ok")),a.receive("error",()=>r("error")),a.receive("timeout",()=>r("timed out"))});{console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated 
3in the future. Please use httpSend() explicitly for REST delivery.");let{event:i,payload:n}=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:i,payload:n,private:this.private}]})};try{let 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(e){if("AbortError"===e.name)return"timed out";return"error"}}}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=y.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(v.close,"leave",this._joinRef())};this.joinPush.destroy();let r=null;return new Promise(s=>{(r=new et(this,v.leave,{},e)).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=y.closed,this.bindings={}}async _fetchWithTimeout(e,t,r){let 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 et(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){let 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;let n=e.toLocaleLowerCase(),{close:a,error:o,leave:l,join:u}=v;if(r&&[a,o,l,u].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,a,o,l;if(!["broadcast","presence","postgres_changes"].includes(n))return e.type.toLocaleLowerCase()===n;if("id"in e){let n=e.id,a=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))&&("*"===a||(null==a?void 0:a.toLocaleLowerCase())===(null===(i=t.data)||void 0===i?void 0:i.type.toLocaleLowerCase()))}{let r=null===(o=null===(a=null==e?void 0:e.filter)||void 0===a?void 0:a.event)||void 0===o?void 0:o.toLocaleLowerCase();return"*"===r||r===(null===(l=null==t?void 0:t.event)||void 0===l?void 0:l.toLocaleLowerCase())}}).map(e=>{if("object"==typeof h&&"ids"in h){let e=h.data,{schema:t,table:r,commit_timestamp:s,type:i,errors:n}=e;h=Object.assign(Object.assign({},{schema:t,table:r,commit_timestamp:s,eventType:i,new:{},old:{},errors:n}),this._getPayloadRecords(e))}e.callback(h,r)})}_isClosed(){return this.state===y.closed}_isJoined(){return this.state===y.joined}_isJoining(){return this.state===y.joining}_isLeaving(){return this.state===y.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){let 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){let 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&&es.isEqual(e.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let 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(v.close,{},e)}_onError(e){this._on(v.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=y.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return("INSERT"===e.type||"UPDATE"===e.type)&&(t.new=F(e.columns,e.record)),("UPDATE"===e.type||"DELET
3E"===e.type)&&(t.old=F(e.columns,e.old_record)),t}}let ei=()=>{},en={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},ea=[1e3,2e3,5e3,1e4],eo=`
4  addEventListener("message", (e) => {
5    if (e.data.event === "start") {
6      setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
7    }
8  });`;class el{constructor(e,t){var s;if(this.accessTokenValue=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=1e4,this.transport=null,this.heartbeatIntervalMs=en.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=ei,this.ref=0,this.reconnectTimer=null,this.logger=ei,this.conn=null,this.sendBuffer=[],this.serializer=new K,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._resolveFetch=e=>{let t;return e?t=e:"undefined"==typeof fetch?t=(...e)=>Promise.resolve().then(r.bind(r,80485)).then(({default:t})=>t(...e)).catch(e=>{throw Error(`Failed to load @supabase/node-fetch: ${e.message}. This is required for HTTP requests in Node.js environments without native fetch.`)}):t=fetch,(...e)=>t(...e)},!(null===(s=null==t?void 0:t.params)||void 0===s?void 0:s.apikey))throw Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${m.websocket}`,this.httpEndpoint=ee(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=M.createWebSocket(this.endpointURL())}catch(t){this._setConnectionState("disconnected");let e=t.message;if(e.includes("Node.js"))throw Error(`${e}
9
10To use Realtime in Node.js, you need to provide a WebSocket implementation:
11
12Option 1: Use Node.js 22+ which has native WebSocket support
13Option 2: Install and provide the "ws" package:
14
15  npm install ws
16
17  import ws from "ws"
18  const client = new RealtimeClient(url, {
19    ...options,
20    transport: ws
21  })`);throw Error(`WebSocket not available: ${e}`)}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){let 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){let t=await e.unsubscribe();return 0===this.channels.length&&this.disconnect(),t}async removeAllChannels(){let 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 w.connecting:return b.Connecting;case w.open:return b.Open;case w.closing:return b.Closing;default:return b.Closed}}isConnected(){return this.connectionState()===b.Open}isConnecting(){return"connecting"===this._connectionState}isDisconnecting(){return"disconnecting"===this._connectionState}channel(e,t={config:{}}){let r=`realtime:${e}`,s=this.getChannels().find(e=>e.topic===r);if(s)return s;{let r=new es(`realtime:${e}`,t,this);return this.channels.push(r),r}}push(e){let{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()){try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(e){this.log("error","error in heartbeat callback",e)}this._wasManualDisconnect=!1,null===(e=this.conn)||void 0===e||e.close(1e3,"heartbeat timeout"),setTimeout(()=>{var e;this.isConnected()||null===(e=this.reconnectTimer)||void 0===e||e.scheduleTimeout()},en.HEARTBEAT_TIMEOUT_FALLBACK);return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(e){this.log("error","error in heartbeat callback",e)}this._setAuthSafely("heartbeat")}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>
210&&(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(e){this.log("error","error in heartbeat callback",e)}e.ref&&e.ref===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null);let{topic:t,event:r,payload:s,ref:i}=e,n=i?`(${i})`:"",a=s.status||"";this.log("receive",`${a} ${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");let 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(v.error))}_appendParams(e,t){if(0===Object.keys(t).length)return e;let r=e.match(/\?/)?"&":"?",s=new URLSearchParams(t);return`${e}${r}${s}`}_workerObjectUrl(e){let t;if(e)t=e;else{let e=new Blob([eo],{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=>{t&&e.updateJoinPayload({access_token:t,version:"realtime-js/2.76.1"}),e.joinedOnce&&e._isJoined()&&e._push(v.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(t){this.log("error",`error in ${e} callback`,t)}})}catch(t){this.log("error",`error triggering ${e} callbacks`,t)}}_setupReconnectionTimer(){this.reconnectTimer=new V(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},en.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var t,r,s,i,n,a,o,l,u;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:1e4,this.heartbeatIntervalMs=null!==(s=null==e?void 0:e.heartbeatIntervalMs)&&void 0!==s?s:en.HEARTBEAT_INTERVAL,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!==(a=null==e?void 0:e.heartbeatCallback)&&void 0!==a?a:ei,(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!==(o=null==e?void 0:e.reconnectAfterMs)&&void 0!==o?o:e=>ea[e-1]||1e4,this.encode=null!==(l=null==e?void 0:e.encode)&&void 0!==l?l:(e,t)=>
21t(JSON.stringify(e)),this.decode=null!==(u=null==e?void 0:e.decode)&&void 0!==u?u:this.serializer.decode.bind(this.serializer),this.worker){if("undefined"!=typeof window&&!window.Worker)throw Error("Web Worker is not supported");this.workerUrl=null==e?void 0:e.workerUrl}}}class eu extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function eh(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}class ec extends eu{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 ed extends eu{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}let ef=e=>{let t;return e?t=e:"undefined"==typeof fetch?t=(...e)=>Promise.resolve().then(r.bind(r,80485)).then(({default:t})=>t(...e)):t=fetch,(...e)=>t(...e)},ep=()=>(0,A.__awaiter)(void 0,void 0,void 0,function*(){return"undefined"==typeof Response?(yield Promise.resolve().then(r.bind(r,80485))).Response:Response}),eg=e=>{if(Array.isArray(e))return e.map(e=>eg(e));if("function"==typeof e||e!==Object(e))return e;let t={};return Object.entries(e).forEach(([e,r])=>{t[e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(/[-_]/g,""))]=eg(r)}),t},ew=e=>{if("object"!=typeof e||null===e)return!1;let t=Object.getPrototypeOf(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},ey=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),ev=(e,t,r)=>(0,A.__awaiter)(void 0,void 0,void 0,function*(){e instanceof(yield ep())&&!(null==r?void 0:r.noResolveJson)?e.json().then(r=>{let s=e.status||500,i=(null==r?void 0:r.statusCode)||s+"";t(new ec(ey(r),s,i))}).catch(e=>{t(new ed(ey(e),e))}):t(new ed(ey(e),e))}),em=(e,t,r,s)=>{let i={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"!==e&&s?(ew(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 eb(e,t,r,s,i,n){return(0,A.__awaiter)(this,void 0,void 0,function*(){return new Promise((a,o)=>{e(r,em(t,s,i,n)).then(e=>{if(!e.ok)throw e;return(null==s?void 0:s.noResolveJson)?e:e.json()}).then(e=>a(e)).catch(e=>ev(e,o,s))})})}function e_(e,t,r,s){return(0,A.__awaiter)(this,void 0,void 0,function*(){return eb(e,"GET",t,r,s)})}function ek(e,t,r,s,i){return(0,A.__awaiter)(this,void 0,void 0,function*(){return eb(e,"POST",t,s,i,r)})}function eS(e,t,r,s,i){return(0,A.__awaiter)(this,void 0,void 0,function*(){return eb(e,"PUT",t,s,i,r)})}function eE(e,t,r,s,i){return(0,A.__awaiter)(this,void 0,void 0,function*(){return eb(e,"DELETE",t,s,i,r)})}class eO{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}execute(){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{return{data:(yield this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eh(e))return{data:null,error:e};throw e}})}}class eT{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[T]="BlobDownloadBuilder",this.promise=null}asStream(){return new eO(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(0,A.__awaiter)(this,void 0,void 0,function*(){try{let e=yield this.downloadFn();return{data:yield e.blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eh(e))return{data:null,error:e};throw e}})}}T=Symbol.toStringTag;var ej=r(96434).Buffer;let eA={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},eI={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class eP{constructor(e,t={},r,s){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.bucketId=r,this.fetch=ef(s)}throwOnError(){return this.shouldThrowOnError=!0,this}uploadOrUpdate(e,t,r,s){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{let i;let n=Object.assign(Object.assign({},eI),s),a=Object.assign(Object.assign({},this.headers),"POST"===e&&{"x-upsert":String(n.upsert)}),o=n.metadata;"undefined"!=typeof Blob&&r instanceof Blob?((i=new FormData).append("cacheControl",n.cacheControl),o&&i.append("metadata",this.encodeMetadata(o)),i.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?((i=r).append("cacheControl",n.cacheControl),o&&i.append("metadata",this.encodeMetadata(o))):(i=r,a["cache-control"]=`max-age=${n.cacheControl}`,a["content-type"]=n.contentType,o&&(a["x-metadata"]=this.toBase64(this.encodeMetadata(o)))),(null==s?void 0:s.headers)&&(a=Object.assign(Object.assign({},a),s.headers));let l=this._removeEmptyFolders(t),u=this._getFinalPath(l),h=yield("PUT"==e?eS:ek)(this.fetch,`${this.url}/object/${u}`,i,Object.assign({headers:a},(null==n?void 0:n.duplex)?{duplex:n.duplex}:{}));return{data:{path:l,id:h.Id,fullPath:h.Key},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eh(e))return{data:null,error:e};throw e}})}upload(e,t,r){return(0,A.__awaiter)(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,s){return(0,A.__awaiter)(this,void 0,void 0,function*(){let i=this._removeEmptyFolders(e),n=this._getFinalPath(i),a=new URL(this.url+`/object/upload/sign/${n}`);a.searchParams.set("token",t);try{let e;let t=Object.assign({upsert:eI.upsert},s),n=Object.assign(Object.assign({},this.headers),{"x-upsert":String(t.upsert)});"undefined"!=typeof Blob&&r instanceof Blob?((e=new FormData).append("cacheControl",t.cacheControl),e.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?(e=r).append("cacheControl",t.cacheControl):(e=r,n["cache-control"]=`max-age=${t.cacheControl}`,n["content-type"]=t.contentType);let o=yield eS(this.fetch,a.toString(),e,{headers:n});return{data:{path:i,fullPath:o.Key},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eh(e))return{data:null,error:e};throw e}})}createSignedUploadUrl(e,t){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),s=Object.assign({},this.headers);(null==t?void 0:t.upsert)&&(s["x-upsert"]="true");let i=yield ek(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:s}),n=new URL(this.url+i.url),a=n.searchParams.get("token");if(!a)throw new eu("No token returned by API");return{data:{signedUrl:n.toString(),path:e,token:a},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eh(e))return{data:null,error:e};throw e}})}update(e,t,r){return(0,A.__awaiter)(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield ek(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,de
21stinationBucket:null==r?void 0:r.destinationBucket},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eh(e))return{data:null,error:e};throw e}})}copy(e,t,r){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{return{data:{path:(yield ek(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==r?void 0:r.destinationBucket},{headers:this.headers})).Key},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eh(e))return{data:null,error:e};throw e}})}createSignedUrl(e,t,r){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),i=yield ek(this.fetch,`${this.url}/object/sign/${s}`,Object.assign({expiresIn:t},(null==r?void 0:r.transform)?{transform:r.transform}:{}),{headers:this.headers}),n=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return{data:i={signedUrl:encodeURI(`${this.url}${i.signedURL}${n}`)},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eh(e))return{data:null,error:e};throw e}})}createSignedUrls(e,t,r){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{let s=yield ek(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return{data:s.map(e=>Object.assign(Object.assign({},e),{signedUrl:e.signedURL?encodeURI(`${this.url}${e.signedURL}${i}`):null})),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eh(e))return{data:null,error:e};throw e}})}download(e,t){let 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 eT(()=>e_(this.fetch,`${this.url}/${r}/${n}${i}`,{headers:this.headers,noResolveJson:!0}),this.shouldThrowOnError)}info(e){return(0,A.__awaiter)(this,void 0,void 0,function*(){let t=this._getFinalPath(e);try{let e=yield e_(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:eg(e),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eh(e))return{data:null,error:e};throw e}})}exists(e){return(0,A.__awaiter)(this,void 0,void 0,function*(){let t=this._getFinalPath(e);try{return yield function(e,t,r,s){return(0,A.__awaiter)(this,void 0,void 0,function*(){return eb(e,"HEAD",t,Object.assign(Object.assign({},r),{noResolveJson:!0}),void 0)})}(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eh(e)&&e instanceof ed){let t=e.originalError;if([400,404].includes(null==t?void 0:t.status))return{data:!1,error:e}}throw e}})}getPublicUrl(e,t){let r=this._getFinalPath(e),s=[],i=(null==t?void 0:t.download)?`download=${!0===t.download?"":t.download}`:"";""!==i&&s.push(i);let n=void 0!==(null==t?void 0:t.transform),a=this.transformOptsToQueryString((null==t?void 0:t.transform)||{});""!==a&&s.push(a);let o=s.join("&");return""!==o&&(o=`?${o}`),{data:{publicUrl:encodeURI(`${this.url}/${n?"render/image":"object"}/public/${r}${o}`)}}}remove(e){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield eE(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eh(e))return{data:null,error:e};throw e}})}list(e,t,r){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{let s=Object.assign(Object.assign(Object.assign({},eA),t),{prefix:e||""});return{data:yield ek(this.fetch,`${this.url}/object/list/${this.bucketId}`,s,{headers:this.headers},r),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eh(e))return{data:null,error:e};throw e}})}listV2(e,t){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{let r=Object.assign({},e);return{data:yield ek(this.fetch,`${this.url}/object/list-v2/${this.bucketId}`,r,{headers:this.headers},t),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eh(e))return{data:null,error:e};throw e}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return void 0!==ej?ej.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let 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("&")}}let eR="2.76.1",eC={"X-Client-Info":`storage-js/${eR}`};class e${constructor(e,t={},r,s){this.shouldThrowOnError=!1;let i=new URL(e);(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({},eC),t),this.fetch=ef(r)}throwOnError(){return this.shouldThrowOnError=!0,this}listBuckets(){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield e_(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eh(e))return{data:null,error:e};throw e}})}getBucket(e){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield e_(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eh(e))return{data:null,error:e};throw e}})}createBucket(e){return(0,A.__awaiter)(this,arguments,void 0,function*(e,t={public:!1}){try{return{data:yield ek(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(e){if(this.shouldThrowOnError)throw e;if(eh(e))return{data:null,error:e};throw e}})}updateBucket(e,t){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield eS(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(e){if(this.shouldThrowOnError)throw e;if(eh(e))return{data:null,error:e};throw e}})}emptyBucket(e){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield ek(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eh(e))return{data:null,error:e};throw e}})}deleteBucket(e){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield eE(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eh(e))return{data:null,error:e};throw e}})}}class ex{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},eC),t),this.fetch=ef(r)}throwOnError(){return this.shouldThrowOnError=!0,this}createBucket(e){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield ek(this.fetch,`${this.url}/bucket`,{name:e},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eh(e))return{data:null,error:e};throw e}})}listBuckets(e){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{let t=new URLSearchParams;(null==e?void 0:e.limit)!==void 0&&t.set("limit",e.limit.toString()),(null==e?void 0:e.offset)!==void 0&&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);let r=t.toString(),s=r?`${this.url}/bucket?${r}`:`${this.url}/bucket`,i=yield e_(this.fetch,s,{headers:this.headers});return{data:Array.isArray(i)?i.filter(e=>"ANALYTICS"===e.type):[],error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eh(e))return{data:null,error:e};throw e}})}deleteBucket(e){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield eE(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eh(e))return{data:null,error:e};throw e}})}}let eN={"X-Client-Info":`storage-js/${eR}`,"Content-Type":"application/json"};
21class eU extends Error{constructor(e){super(e),this.__isStorageVectorsError=!0,this.name="StorageVectorsError"}}function eD(e){return"object"==typeof e&&null!==e&&"__isStorageVectorsError"in e}class eL extends eU{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 eq extends eU{constructor(e,t){super(e),this.name="StorageVectorsUnknownError",this.originalError=t}}(p=j||(j={})).InternalError="InternalError",p.S3VectorConflictException="S3VectorConflictException",p.S3VectorNotFoundException="S3VectorNotFoundException",p.S3VectorBucketNotEmpty="S3VectorBucketNotEmpty",p.S3VectorMaxBucketsExceeded="S3VectorMaxBucketsExceeded",p.S3VectorMaxIndexesExceeded="S3VectorMaxIndexesExceeded";let eB=e=>{let t;return e?t=e:"undefined"==typeof fetch?t=(...e)=>Promise.resolve().then(r.bind(r,80485)).then(({default:t})=>t(...e)):t=fetch,(...e)=>t(...e)},eW=e=>{if("object"!=typeof e||null===e)return!1;let t=Object.getPrototypeOf(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},eM=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),eK=(e,t,r)=>(0,A.__awaiter)(void 0,void 0,void 0,function*(){if(!(e&&"object"==typeof e&&"status"in e&&"ok"in e&&"number"==typeof e.status)||(null==r?void 0:r.noResolveJson))t(new eq(eM(e),e));else{let r=e.status||500;"function"==typeof e.json?e.json().then(e=>{let s=(null==e?void 0:e.statusCode)||(null==e?void 0:e.code)||r+"";t(new eL(eM(e),r,s))}).catch(()=>{t(new eL(e.statusText||`HTTP ${r} error`,r,r+""))}):t(new eL(e.statusText||`HTTP ${r} error`,r,r+""))}}),eV=(e,t,r,s)=>{let i={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"!==e&&s?(eW(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 eF(e,t,r,s,i){return(0,A.__awaiter)(this,void 0,void 0,function*(){return function(e,t,r,s,i,n){return(0,A.__awaiter)(this,void 0,void 0,function*(){return new Promise((a,o)=>{e(r,eV(t,s,i,n)).then(e=>{if(!e.ok)throw e;if(null==s?void 0:s.noResolveJson)return e;let t=e.headers.get("content-type");return t&&t.includes("application/json")?e.json():{}}).then(e=>a(e)).catch(e=>eK(e,o,s))})})}(e,"POST",t,s,i,r)})}class eH{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},eN),t),this.fetch=eB(r)}throwOnError(){return this.shouldThrowOnError=!0,this}createIndex(e){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{return{data:(yield eF(this.fetch,`${this.url}/CreateIndex`,e,{headers:this.headers}))||{},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eD(e))return{data:null,error:e};throw e}})}getIndex(e,t){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield eF(this.fetch,`${this.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eD(e))return{data:null,error:e};throw e}})}listIndexes(e){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield eF(this.fetch,`${this.url}/ListIndexes`,e,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eD(e))return{data:null,error:e};throw e}})}deleteIndex(e,t){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{return{data:(yield eF(this.fetch,`${this.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:this.headers}))||{},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eD(e))return{data:null,error:e};throw e}})}}class eJ{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},eN),t),this.fetch=eB(r)}throwOnError(){return this.shouldThrowOnError=!0,this}putVectors(e){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{if(e.vectors.length<1||e.vectors.length>500)throw Error("Vector batch size must be between 1 and 500 items");return{data:(yield eF(this.fetch,`${this.url}/PutVectors`,e,{headers:this.headers}))||{},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eD(e))return{data:null,error:e};throw e}})}getVectors(e){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield eF(this.fetch,`${this.url}/GetVectors`,e,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eD(e))return{data:null,error:e};throw e}})}listVectors(e){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{if(void 0!==e.segmentCount){if(e.segmentCount<1||e.segmentCount>16)throw Error("segmentCount must be between 1 and 16");
21if(void 0!==e.segmentIndex&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw Error(`segmentIndex must be between 0 and ${e.segmentCount-1}`)}return{data:yield eF(this.fetch,`${this.url}/ListVectors`,e,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eD(e))return{data:null,error:e};throw e}})}queryVectors(e){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield eF(this.fetch,`${this.url}/QueryVectors`,e,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eD(e))return{data:null,error:e};throw e}})}deleteVectors(e){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{if(e.keys.length<1||e.keys.length>500)throw Error("Keys batch size must be between 1 and 500 items");return{data:(yield eF(this.fetch,`${this.url}/DeleteVectors`,e,{headers:this.headers}))||{},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eD(e))return{data:null,error:e};throw e}})}}class ez{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},eN),t),this.fetch=eB(r)}throwOnError(){return this.shouldThrowOnError=!0,this}createBucket(e){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{return{data:(yield eF(this.fetch,`${this.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:this.headers}))||{},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eD(e))return{data:null,error:e};throw e}})}getBucket(e){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{return{data:yield eF(this.fetch,`${this.url}/GetVectorBucket`,{vectorBucketName:e},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eD(e))return{data:null,error:e};throw e}})}listBuckets(){return(0,A.__awaiter)(this,arguments,void 0,function*(e={}){try{return{data:yield eF(this.fetch,`${this.url}/ListVectorBuckets`,e,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eD(e))return{data:null,error:e};throw e}})}deleteBucket(e){return(0,A.__awaiter)(this,void 0,void 0,function*(){try{return{data:(yield eF(this.fetch,`${this.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:this.headers}))||{},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eD(e))return{data:null,error:e};throw e}})}}class eG extends ez{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new eY(this.url,this.headers,e,this.fetch)}}class eY extends eH{constructor(e,t,r,s){super(e,t,s),this.vectorBucketName=r}createIndex(e){let t=Object.create(null,{createIndex:{get:()=>super.createIndex}});return(0,A.__awaiter)(this,void 0,void 0,function*(){return t.createIndex.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName}))})}listIndexes(){let e=Object.create(null,{listIndexes:{get:()=>super.listIndexes}});return(0,A.__awaiter)(this,arguments,void 0,function*(t={}){return e.listIndexes.call(this,Object.assign(Object.assign({},t),{vectorBucketName:this.vectorBucketName}))})}getIndex(e){let t=Object.create(null,{getIndex:{get:()=>super.getIndex}});return(0,A.__awaiter)(this,void 0,void 0,function*(){return t.getIndex.call(this,this.vectorBucketName,e)})}deleteIndex(e){let t=Object.create(null,{deleteIndex:{get:()=>super.deleteIndex}});return(0,A.__awaiter)(this,void 0,void 0,function*(){return t.deleteIndex.call(this,this.vectorBucketName,e)})}index(e){return new eQ(this.url,this.headers,this.vectorBucketName,e,this.fetch)}}class eQ extends eJ{constructor(e,t,r,s,i){super(e,t,i),this.vectorBucketName=r,this.indexName=s}putVectors(e){let t=Object.create(null,{putVectors:{get:()=>super.putVectors}});return(0,A.__awaiter)(this,void 0,void 0,function*(){return t.putVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}getVectors(e){let t=Object.create(null,{getVectors:{get:()=>super.getVectors}});return(0,A.__awaiter)(this,void 0,void 0,function*(){return t.getVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}listVectors(){let e=Object.create(null,{listVectors:{get:()=>super.listVectors}});return(0,A.__awaiter)(this,arguments,void 0,function*(t={}){return e.listVectors.call(this,Object.assign(Object.assign({},t),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}queryVectors(e){let t=Object.create(null,{queryVectors:{get:()=>super.queryVectors}});return(0,A.__awaiter)(this,void 0,void 0,function*(){return t.queryVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}deleteVectors(e){let t=Object.create(null,{deleteVectors:{get:()=>super.deleteVectors}});return(0,A.__awaiter)(this,void 0,void 0,function*(){return t.deleteVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}}class eX extends e${constructor(e,t={},r,s){super(e,t,r,s)}from(e){return new eP(this.url,this.headers,e,this.fetch)}get vectors(){return new eG(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new ex(this.url+"/iceberg",this.headers,this.fetch)}}let eZ="";"undefined"!=typeof Deno?eZ="deno":"undefined"!=typeof document?eZ="web":"undefined"!=typeof navigator&&"ReactNative"===navigator.product?eZ="react-native":eZ="node";let e0={headers:{"X-Client-Info":`supabase-js-${eZ}/2.76.1`}},e1={schema:"public"},e2={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},e3={};var e8=r(80485);let e5=e=>{let t;return e?t=e:"undefined"==typeof fetch?t=e8.default:t=fetch,(...e)=>t(...e)},e6=()=>"undefined"==typeof Headers?e8.Headers:Headers,e4=(e,t,r)=>{let s=e5(r),i=e6();return async(r,n)=>{var a;let o=null!==(a=await t())&&void 0!==a?a:e,l=new i(null==n?void 0:n.headers);return l.has("apikey")||l.set("apikey",e),l.has("Authorization")||l.set("Authorization",`Bearer ${o}`),s(r,Object.assign(Object.assign({},n),{headers:l}))}},e9="2.76.1",e7={"X-Client-Info":`gotrue-js/${e9}`},te="X-Supabase-Api-Version",tt={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},tr=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;
21class ts extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}}function ti(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class tn extends ts{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}}class ta extends ts{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class to extends ts{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}}class tl extends to{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}class tu extends to{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class th extends to{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class tc extends to{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 td extends to{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 tf extends to{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function tp(e){return ti(e)&&"AuthRetryableFetchError"===e.name}class tg extends to{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}}class tw extends to{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}let ty="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),tv=" 	\n\r=".split(""),tm=(()=>{let e=Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<tv.length;t+=1)e[tv[t].charCodeAt(0)]=-2;for(let t=0;t<ty.length;t+=1)e[ty[t].charCodeAt(0)]=t;return e})();function tb(e,t,r){if(null!==e)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;)r(ty[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6;else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;)r(ty[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6}function t_(e,t,r){let s=tm[e];if(s>-1)for(t.queue=t.queue<<6|s,t.queuedBits+=6;t.queuedBits>=8;)r(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else if(-2===s)return;else throw Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}function tk(e){let 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){r(e);return}for(let r=1;r<6;r+=1)if((e>>7-r&1)==0){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)t.codepoint=7&e;else throw Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw 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 t=0;t<e.length;t+=1)t_(e.charCodeAt(t),i,n);return t.join("")}function tS(e){let t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};for(let t=0;t<e.length;t+=1)t_(e.charCodeAt(t),r,s);return new Uint8Array(t)}function tE(e){let t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};return e.forEach(e=>tb(e,r,s)),tb(null,r,s),t.join("")}let tO=()=>"undefined"!=typeof window&&"undefined"!=typeof document,tT={tested:!1,writable:!1},tj=()=>{if(!tO())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(tT.tested)return tT.writable;let e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),tT.tested=!0,tT.writable=!0}catch(e){tT.tested=!0,tT.writable=!1}return tT.writable},tA=e=>{let t;return e?t=e:"undefined"==typeof fetch?t=(...e)=>Promise.resolve().then(r.bind(r,80485)).then(({default:t})=>t(...e)):t=fetch,(...e)=>t(...e)},tI=e=>"object"==typeof e&&null!==e&&"status"in e&&"ok"in e&&"json"in e&&"function"==typeof e.json,tP=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},tR=async(e,t)=>{let r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch(e){return r}},tC=async(e,t)=>{await e.removeItem(t)};class t${constructor(){this.promise=new t$.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function tx(e){let t=e.split(".");if(3!==t.length)throw new tw("Invalid JWT structure");for(let e=0;e<t.length;e++)if(!tr.test(t[e]))throw new tw("JWT not in base64url format");return{header:JSON.parse(tk(t[0])),payload:JSON.parse(tk(t[1])),signature:tS(t[2]),raw:{header:t[0],payload:t[1]}}}async function tN(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}function tU(e){return("0"+e.toString(16)).substr(-2)}async function tD(e){let t=new TextEncoder().encode(e);return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",t))).map(e=>String.fromCharCode(e)).join("")}async function tL(e){return"undefined"!=typeof crypto&&void 0!==crypto.subtle&&"undefined"!=typeof TextEncoder?btoa(await tD(e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""):(console.warn("WebCrypto API is not supported. Code 
21challenge method will default to use plain instead of sha256."),e)}async function tq(e,t,r=!1){let s=function(){let e=new Uint32Array(56);if("undefined"==typeof crypto){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length,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,tU).join("")}(),i=s;r&&(i+="/PASSWORD_RECOVERY"),await tP(e,`${t}-code-verifier`,i);let n=await tL(s),a=s===n?"plain":"s256";return[n,a]}t$.promiseConstructor=Promise;let tB=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i,tW=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function tM(e){if(!tW.test(e))throw Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function tK(){return new Proxy({},{get:(e,t)=>{if("__isUserNotAvailableProxy"===t)return!0;if("symbol"==typeof t){let e=t.toString();if("Symbol(Symbol.toPrimitive)"===e||"Symbol(Symbol.toStringTag)"===e||"Symbol(util.inspect.custom)"===e)return}throw 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 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 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 tV(e){return JSON.parse(JSON.stringify(e))}let tF=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),tH=[502,503,504];async function tJ(e){var t;let r,s;if(!tI(e))throw new tf(tF(e),0);if(tH.includes(e.status))throw new tf(tF(e),e.status);try{r=await e.json()}catch(e){throw new ta(tF(e),e)}let i=function(e){let t=e.headers.get(te);if(!t||!t.match(tB))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch(e){return null}}(e);if(i&&i.getTime()>=tt["2024-01-01"].timestamp&&"object"==typeof r&&r&&"string"==typeof r.code?s=r.code:"object"==typeof r&&r&&"string"==typeof r.error_code&&(s=r.error_code),s){if("weak_password"===s)throw new tg(tF(r),e.status,(null===(t=r.weak_password)||void 0===t?void 0:t.reasons)||[]);if("session_not_found"===s)throw new tl}else if("object"==typeof r&&r&&"object"==typeof r.weak_password&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0))throw new tg(tF(r),e.status,r.weak_password.reasons);throw new tn(tF(r),e.status||500,s)}let tz=(e,t,r,s)=>{let 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))};async function tG(e,t,r,s){var i;let n=Object.assign({},null==s?void 0:s.headers);n[te]||(n[te]=tt["2024-01-01"].name),(null==s?void 0:s.jwt)&&(n.Authorization=`Bearer ${s.jwt}`);let a=null!==(i=null==s?void 0:s.query)&&void 0!==i?i:{};(null==s?void 0:s.redirectTo)&&(a.redirect_to=s.redirectTo);let o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",l=await tY(e,t,r+o,{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}}async function tY(e,t,r,s,i,n){let a;let o=tz(t,s,i,n);try{a=await e(r,Object.assign({},o))}catch(e){throw console.error(e),new tf(tF(e),0)}if(a.ok||await tJ(a),null==s?void 0:s.noResolveJson)return a;try{return await a.json()}catch(e){await tJ(e)}}function tQ(e){var t,r;let s=null;return e.access_token&&e.refresh_token&&e.expires_in&&(s=Object.assign({},e),!e.expires_at)&&(s.expires_at=(r=e.expires_in,Math.round(Date.now()/1e3)+r)),{data:{session:s,user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function tX(e){let t=tQ(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)=>
21e&&"string"==typeof t,!0)&&(t.data.weak_password=e.weak_password),t}function tZ(e){var t;return{data:{user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function t0(e){return{data:e,error:null}}function t1(e){let{action_link:t,email_otp:r,hashed_token:s,redirect_to:i,verification_type:n}=e;return{data:{properties:{action_link:t,email_otp:r,hashed_token:s,redirect_to:i,verification_type:n},user:Object.assign({},(0,A.__rest)(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]))},error:null}}function t2(e){return e}let t3=["global","local","others"];class t8{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=tA(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=t3[0]){if(0>t3.indexOf(t))throw Error(`@supabase/auth-js: Parameter scope must be one of ${t3.join(", ")}`);try{return await tG(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(ti(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await tG(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:tZ})}catch(e){if(ti(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{let{options:t}=e,r=(0,A.__rest)(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 tG(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:t1,redirectTo:null==t?void 0:t.redirectTo})}catch(e){if(ti(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await tG(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:tZ})}catch(e){if(ti(e))return{data:{user:null},error:e};throw e}}async listUsers(e){var t,r,s,i,n,a,o;try{let l={nextPage:null,lastPage:0,total:0},u=await tG(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:t2});if(u.error)throw u.error;let h=await u.json(),c=null!==(n=u.headers.get("x-total-count"))&&void 0!==n?n:0,d=null!==(o=null===(a=u.headers.get("link"))||void 0===a?void 0:a.split(","))&&void 0!==o?o:[];return d.length>0&&(d.forEach(e=>{let 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(c)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(e){if(ti(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){tM(e);try{return await tG(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:tZ})}catch(e){if(ti(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){tM(e);try{return await tG(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:tZ})}catch(e){if(ti(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){tM(e);try{return await tG(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:tZ})}catch(e){if(ti(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){tM(e.userId);try{let{data:t,error:r}=await tG(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(e){if(ti(e))return{data:null,error:e};throw e}}async _deleteFactor(e){tM(e.userId),tM(e.id);try{return{data:await tG(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(ti(e))return{data:null,error:e};throw e}}async _listOAuthClients(e){var t,r,s,i,n,a,o;try{let l={nextPage:null,lastPage:0,total:0},u=await tG(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:t2});if(u.error)throw u.error;let h=await u.json(),c=null!==(n=u.headers.get("x-total-count"))&&void 0!==n?n:0,d=null!==(o=null===(a=u.headers.get("link"))||void 0===a?void 0:a.split(","))&&void 0!==o?o:[];return d.length>
210&&(d.forEach(e=>{let 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(c)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(e){if(ti(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await tG(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(ti(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await tG(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(ti(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await tG(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(ti(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await tG(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(ti(e))return{data:null,error:e};throw e}}}function t5(e={}){return{getItem:t=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:t=>{delete e[t]}}}let t6={debug:!!(globalThis&&tj()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"))};class t4 extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class t9 extends t4{}async function t7(e,t,r){t6.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);let s=new globalThis.AbortController;return t>0&&setTimeout(()=>{s.abort(),t6.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},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){t6.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,s.name);try{return await r()}finally{t6.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",e,s.name)}}else{if(0===t)throw t6.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new t9(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(t6.debug)try{let e=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(e,null,"  "))}catch(e){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",e)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await r()}}))}function re(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}class rt 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 rr extends rt{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}class rs{createNewAbortSignal(){if(this.controller){let e=Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}let ri=new rs;function rn(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function ra(){var e,t;return!!(tO()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&"function"==typeof(null===(e=null==navigator?void 0:navigator.credentials)||void 0===e?void 0:e.create)&&"function"==typeof(null===(t=null==navigator?void 0:navigator.credentials)||void 0===t?void 0:t.get))}async function ro(e){try{let t=await navigator.credentials.create(e);if(!t)return{data:null,error:new rr("Empty credential response",t)};if(!(t instanceof PublicKeyCredential))return{data:null,error:new rr("Browser returned unexpected credential type",t)};return{data:t,error:null}}catch(t){return{data:null,error:function({error:e,options:t}){var r,s,i;let{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new rt({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if((null===(r=n.authenticatorSelection)||void 0===r?void 0:r.requireResidentKey)===!0)return new rt({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if("conditional"===t.mediation&&(null===(s=n.authenticatorSelection)||void 0===s?void 0:s.userVerification)==="required")return new rt({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if((null===(i=n.authenticatorSelection)||void 0===i?void 0:i.userVerification)==="required")return new rt({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 rt({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});else if("NotAllowedError"===e.name)return new rt({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});else if("NotSupportedError"===e.name)return new rt(0===n.pubKeyCredParams.filter(e=>"public-key"===e.type).length?{message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}:{message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});else if("SecurityError"===e.name){let t=window.location.hostname;if(!rn(t))return new rt({message:`${window.location.hostname}
21 is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(n.rp.id!==t)return new rt({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 rt({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 rt({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 rt({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}({error:t,options:e})}}}async function rl(e){try{let t=await navigator.credentials.get(e);if(!t)return{data:null,error:new rr("Empty credential response",t)};if(!(t instanceof PublicKeyCredential))return{data:null,error:new rr("Browser returned unexpected credential type",t)};return{data:t,error:null}}catch(t){return{data:null,error:function({error:e,options:t}){let{publicKey:r}=t;if(!r)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new rt({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("NotAllowedError"===e.name)return new rt({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});else if("SecurityError"===e.name){let t=window.location.hostname;if(!rn(t))return new rt({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(r.rpId!==t)return new rt({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 rt({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 rt({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}({error:t,options:e})}}}let ru={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"none"},rh={userVerification:"preferred",hints:["security-key"]};function rc(...e){let t=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),r=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),s={};for(let i of e)if(i)for(let e in i){let 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)){let r=s[e];t(r)?s[e]=rc(r,n):s[e]=rc(n)}else s[e]=n}}return s}class rd{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{var n,a,o,l;let{data:u,error:h}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!u)return{data:null,error:h};let c=null!=s?s:ri.createNewAbortSignal();if("create"===u.webauthn.type){let{user:e}=u.webauthn.credential_options.publicKey;e.name||(e.name=`${e.id}:${r}`),e.displayName||(e.displayName=e.name)}switch(u.webauthn.type){case"create":{let t=(n=u.webauthn.credential_options.publicKey,a=null==i?void 0:i.create,rc(ru,n,a||{})),{data:r,error:s}=await ro({publicKey:t,signal:c});if(r)return{data:{factorId:e,challengeId:u.id,webauthn:{type:u.webauthn.type,credential_response:r}},error:null};return{data:null,error:s}}case"request":{let t=(o=u.webauthn.credential_options.publicKey,l=null==i?void 0:i.request,rc(rh,o,l||{})),{data:r,error:s}=await rl(Object.assign(Object.assign({},u.webauthn.credential_options),{publicKey:t,signal:c}));if(r)return{data:{factorId:e,challengeId:u.id,webauthn:{type:u.webauthn.type,credential_response:r}},error:null};return{data:null,error:s}}}}catch(e){if(ti(e))return{data:null,error:e};return{data:null,error:new ta("Unexpected error in challenge",e)}}}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 ts("rpId is required for WebAuthn authentication")};try{if(!ra())return{data:null,error:new ta("Browser does not support WebAuthn",null)};let{data:n,error:a}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:i});if(!n)return{data:null,error:a};let{webauthn:o}=n;return this._verify({factorId:e,challengeId:n.challengeId,webauthn:{type:o.type,rpId:t,rpOrigins:r,credential_response:o.credential_response}})}catch(e){if(ti(e))return{data:null,error:e};return{data:null,error:new ta("Unexpected error in authenticate",e)}}}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 ts("rpId is required for WebAuthn registration")};try{if(!ra())return{data:null,error:new ta("Browser does not support WebAuthn",null)};let{data:n,error:a}=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:a};let{data:o,error:l}=await this._challenge({factorId:n.id,friendlyName:n.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:i});if(!o)return{data:null,error:l};return this._verify({factorId:n.id,challengeId:o.challengeId,webauthn:{rpId:t,rpOrigins:r,type:o.webauthn.type,credential_response:o.webauthn.credential_response}})}catch(e){if(ti(e))return{data:null,error:e};return{data:null,error:new ta("Unexpected error in register",e)}}}}!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)}}();let rf={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:e7,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function rp(e,t,r){return await r()}let rg={};class rw{get jwks(){var e,t;return null!==(t=null===(e=rg[this.storageKey])||void 0===e?void 0:e.jwks)&&void 0!==t?t:{keys:[]}}set jwks(e){rg[this.storageKey]=Object.assign(Object.assign({},rg[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return null!==(t=null===(e=rg[this.storageKey])||void 0===e?void 0:e.cachedAt)&&void 0!==t?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){rg[this.storageKey]=Object.assign(Object.assign({},rg[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=rw.nextInstanceID,rw.nextInstanceID+=1,this.instanceID>0&&tO()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");let s=Object.assign(Object.assign({},rf),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 t8({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=tA(s.fetch),this.lock=s.lock||rp,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,s.lock?this.lock=s.lock:tO()&&(null===(t=null==globalThis?void 0:globalThis.navigator)||void 0===t?void 0:t.locks)?this.lock=t7:this.lock=rp,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 rd(this)},this.persistSession?(s.storage?this.storage=s.storage:tj()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=t5(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=t5(this.memoryStorage)),tO()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",e)}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} (${e9}) ${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{let t=function(e){let t={},r=new URL(e);if(r.hash&&"#"===r.hash[0])try{new URLSearchParams(r.hash.substring(1)).forEac
21h((e,r)=>{t[r]=e})}catch(e){}return r.searchParams.forEach((e,r)=>{t[r]=e}),t}(window.location.href),r="none";if(this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce"),tO()&&this.detectSessionInUrl&&"none"!==r){let{data:s,error:i}=await this._getSessionFromURL(t,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),ti(i)&&"AuthImplicitGrantRedirectError"===i.name){let 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}}let{session:n,redirectType:a}=s;return this._debug("#_initialize()","detected session in URL",n,"redirect type",a),await this._saveSession(n),setTimeout(async()=>{"recovery"===a?await this._notifyAllSubscribers("PASSWORD_RECOVERY",n):await this._notifyAllSubscribers("SIGNED_IN",n)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){if(ti(e))return{error:e};return{error:new ta("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{let{data:i,error:n}=await tG(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:tQ});if(n||!i)return{data:{user:null,session:null},error:n};let a=i.session,o=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",a)),{data:{user:o,session:a},error:null}}catch(e){if(ti(e))return{data:{user:null,session:null},error:e};throw e}}async signUp(e){var t,r,s;try{let i;if("email"in e){let{email:r,password:s,options:n}=e,a=null,o=null;"pkce"===this.flowType&&([a,o]=await tq(this.storage,this.storageKey)),i=await tG(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:a,code_challenge_method:o},xform:tQ})}else if("phone"in e){let{phone:t,password:n,options:a}=e;i=await tG(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:n,data:null!==(r=null==a?void 0:a.data)&&void 0!==r?r:{},channel:null!==(s=null==a?void 0:a.channel)&&void 0!==s?s:"sms",gotrue_meta_security:{captcha_token:null==a?void 0:a.captchaToken}},xform:tQ})}else throw new th("You must provide either an email or phone number and a password");let{data:n,error:a}=i;if(a||!n)return{data:{user:null,session:null},error:a};let o=n.session,l=n.user;return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",o)),{data:{user:l,session:o},error:null}}catch(e){if(ti(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithPassword(e){try{let t;if("email"in e){let{email:r,password:s,options:i}=e;t=await tG(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:tX})}else if("phone"in e){let{phone:r,password:s,options:i}=e;t=await tG(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:tX})}else throw new th("You must provide either an email or phone number and a password");let{data:r,error:s}=t;if(s)return{data:{user:null,session:null},error:s};if(!r||!r.session||!r.user)return{data:{user:null,session:null},error:new tu};return 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}}catch(e){if(ti(e))return{data:{user:null,session:null},error:e};throw e}}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){let{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,s,i,n,a,o,l,u,h,c,d;let f,p;if("message"in e)f=e.message,p=e.signature;else{let h;let{chain:c,wallet:g,statement:w,options:y}=e;if(tO()){if("object"==typeof g)h=g;else{let e=window;if("ethereum"in e&&"object"==typeof e.ethereum&&"request"in e.ethereum&&"function"==typeof e.ethereum.request)h=e.ethereum;else throw Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}}else{if("object"!=typeof g||!(null==y?void 0:y.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");h=g}let v=new URL(null!==(t=null==y?void 0:y.url)&&void 0!==t?t:window.location.href),m=await h.request({method:"eth_requestAccounts"}).then(e=>e).catch(()=>{throw Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!m||0===m.length)throw Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let b=re(m[0]),_=null===(r=null==y?void 0:y.signInWithEthereum)||void 0===r?void 0:r.chainId;_||(_=parseInt(await h.request({method:"eth_chainId"}),16)),f=function(e){var t;let{chainId:r,domain:s,expirationTime:i,issuedAt:n=new Date,nonce:a,notBefore:o,requestId:l,resources:u,scheme:h,uri:c,version:d}=e;if(!Number.isInteger(r))throw Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!s)throw Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!c)throw Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if("1"!==d)throw 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 Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);let f=re(e.address),p=h?`${h}://${s}`:s,g=e.statement?`${e.statement}
22`:"",w=`${p} wants you to sign in with your Ethereum account:
23${f}
24
25${g}`,y=`URI: ${c}
26Version: ${d}
27Chain ID: ${r}${a?`
28Nonce: ${a}`:""}
29Issued At: ${n.toISOString()}`;if(i&&(y+=`
30Expiration Time: ${i.toISOString()}`),o&&(y+=`
31Not Before: ${o.toISOString()}`),l&&(y+=`
32Request ID: ${l}`),u){let e="\nResources:";for(let t of u){if(!t||"string"!=typeof t)throw Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${t}`);e+=`
33- ${t}`}y+=e}return`${w}
34${y}`}({domain:v.host,address:b,statement:w,uri:v.href,version:"1",chainId:_,nonce:null===(s=null==y?void 0:y.signInWithEthereum)||void 0===s?void 0:s.nonce,issuedAt:null!==(n=null===(i=null==y?void 0:y.signInWithEthereum)||void 0===i?void 0:i.issuedAt)&&void 0!==n?n:new Date,expirationTime:null===(a=null==y?void 0:y.signInWithEthereum)||void 0===a?void 0:a.expirationTime,notBefore:null===(o=null==y?void 0:y.signInWithEthereum)||void 0===o?void 0:o.notBefore,requestId:null===(l=null==y?void 0:y.signInWithEthereum)||void 0===l?void 0:l.requestId,resources:null===(u=null==y?void 0:y.signInWithEthereum)||void 0===u?void 0:u.resources}),p=await h.request({method:"personal_sign",params:[(d=f,"0x"+Array.from(new TextEncoder().encode(d),e=>e.toString(16).padStart(2,"0")).join("")),b]})}try{let{data:t,error:r}=await tG(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:f,signature:p},(null===(h=e.options)||void 0===h?void 0:h.captchaToken)?{gotrue_meta_security:{captcha_token:null===(c=e.options)||void 0===c?void 0:c.captchaToken}}:null),xform:tQ});if(r)throw r;if(!t||!t.session||!t.user)return{data:{user:null,session:null},error:new tu};return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),{data:Object.assign({},t),error:r}}catch(e){if(ti(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithSolana(e){var t,r,s,i,n,a,o,l,u,h,c,d;let f,p;if("message"in e)f=e.message,p=e.signature;else{let c;let{chain:d,wallet:g,statement:w,options:y}=e;if(tO()){if("object"==typeof g)c=g;else{let 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))c=e.solana;else throw Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}}else{if("object"!=typeof g||!(null==y?void 0:y.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");c=g}let v=new URL(null!==(t=null==y?void 0:y.url)&&void 0!==t?t:window.location.href);if("signIn"in c&&c.signIn){let e;let t=await c.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},null==y?void 0:y.signInWithSolana),{version:"1",domain:v.host,uri:v.href}),w?{statement:w}:null));if(Array.isArray(t)&&t[0]&&"object"==typeof t[0])e=t[0];else if(t&&"object"==typeof t&&"signedMessage"in t&&"signature"in t)e=t;else throw Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in e&&"signature"in e&&("string"==typeof e.signedMessage||e.signedMessage instanceof Uint8Array)&&e.signature instanceof Uint8Array)f="string"==typeof e.signedMessage?e.signedMessage:new TextDecoder().decode(e.signedMessage),p=e.signature;else throw Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in c)||"function"!=typeof c.signMessage||!("publicKey"in c)||"object"!=typeof c||!c.publicKey||!("toBase58"in c.publicKey)||"function"!=typeof c.publicKey.toBase58)throw Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");f=[`${v.host} wants you to sign in with your Solana account:`,c.publicKey.toBase58(),...w?["",w,""]:[""],"Version: 1",`URI: ${v.href}`,`Issued At: ${null!==(s=null===(r=null==y?void 0:y.signInWithSolana)||void 0===r?void 0:r.issuedAt)&&void 0!==s?s:new Date().toISOString()}`,...(null===(i=null==y?void 0:y.signInWithSolana)||void 0===i?void 0:i.notBefore)?[`Not Before: ${y.signInWithSolana.notBefore}`]:[],...(null===(n=null==y?void 0:y.signInWithSolana)||void 0===n?void 0:n.expirationTime)?[`Expiration Time: ${y.signInWithSolana.expirationTime}`]:[],...(null===(a=null==y?void 0:y.signInWithSolana)||void 0===a?void 0:a.chainId)?[`Chain ID: ${y.signInWithSolana.chainId}`]:[],...(null===(o=null==y?void 0:y.signInWithSolana)||void 0===o?void 0:o.nonce)?[`Nonce: ${y.signInWithSolana.nonce}`]:[],...(null===(l=null==y?void 0:y.signInWithSolana)||void 0===l?void 0:l.requestId)?[`Request ID: ${y.signInWithSolana.requestId}`]:[],...(null===(h=null===(u=null==y?void 0:y.signInWithSolana)||void 0===u?void 0:u.resources)||void 0===h?void 0:h.length)?["Resources",...y.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join("\n");let e=await c.signMessage(new TextEncoder().encode(f),"utf8");if(!e||!(e instanceof Uint8Array))throw Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");p=e}}try{let{data:t,error:r}=await tG(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:f,signature:tE(p)},(null===(c=e.options)||void 0===c?void 0:c.captchaToken)?{gotrue_meta_security:{captcha_token:null===(d=e.options)||void 0===d?void 0:d.captchaToken}}:null),xform:tQ});if(r)throw r;if(!t||!t.session||!t.user)return{data:{user:null,session:null},error:new tu};return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),{data:Object.assign({},t),error:r}}catch(e){if(ti(e))return{data:{user:null,session:null},error:e};throw e}}async _exchangeCodeForSession(e){let t=await tR(this.storage,`${this.storageKey}-code-verifier`),[r,s]=(null!=t?t:"").split("/");try{let{data:t,error:i}=await tG(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:tQ});if(await tC(this.storage,`${this.storageKey}-code-verifier`),i)throw i;if(!t||!t.session||!t.user)return{data:{user:null,session:null,redirectType:null},error:new tu};return 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}}catch(e){if(ti(e))return{data:{user:null,session:null,redirectType:null},error:e};throw e}}async signInWithIdToken(e){try{let{options:t,provider:r,token:s,access_token:i,nonce:n}=e,{data:a,error:o}=await tG(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:tQ});if(o)return{data:{user:null,session:null},error:o};if(!a||!a.session||!a.user)return{data:{user:null,session:null},error:new tu};return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),{data:a,error:o}}catch(e){if(ti(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithOtp(e){var t,r,s,i,n;try{if("email"in e){let{email:s,options:i}=e,n=null,a=null;"pkce"===this.flowType&&([n,a]=await tq(this.storage,this.storageKey));let{error:o}=await tG(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:{}
34,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:a},redirectTo:null==i?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:o}}if("phone"in e){let{phone:t,options:r}=e,{data:a,error:o}=await tG(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==a?void 0:a.message_id},error:o}}throw new th("You must provide either an email or phone number.")}catch(e){if(ti(e))return{data:{user:null,session:null},error:e};throw e}}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);let{data:n,error:a}=await tG(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:tQ});if(a)throw a;if(!n)throw Error("An error occurred on token verification.");let o=n.session,l=n.user;return(null==o?void 0:o.access_token)&&(await this._saveSession(o),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",o)),{data:{user:l,session:o},error:null}}catch(e){if(ti(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithSSO(e){var t,r,s;try{let i=null,n=null;return"pkce"===this.flowType&&([i,n]=await tq(this.storage,this.storageKey)),await tG(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:t0})}catch(e){if(ti(e))return{data:null,error:e};throw e}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new tl;let{error:s}=await tG(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:s}})}catch(e){if(ti(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:r,type:s,options:i}=e,{error:n}=await tG(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){let{phone:r,type:s,options:i}=e,{data:n,error:a}=await tG(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:a}}throw new th("You must provide either an email or phone number and a type")}catch(e){if(ti(e))return{data:{user:null,session:null},error:e};throw e}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async e=>e))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let 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;let e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(e){}})()),await e;this.pendingInLock.length;){let 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{let 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!",Error().stack);try{let e=null,t=await tR(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 val
34id"),await this._removeSession())),!e)return{data:{session:null},error:null};let r=!!e.expires_at&&1e3*e.expires_at-Date.now()<9e4;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.userStorage){let t=await tR(this.userStorage,this.storageKey+"-user");(null==t?void 0:t.user)?e.user=t.user:e.user=tK()}if(this.storage.isServer&&e.user){let t=this.suppressGetSessionWarning;e=new Proxy(e,{get:(e,r,s)=>(t||"user"!==r||(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),t=!0,this.suppressGetSessionWarning=!0),Reflect.get(e,r,s))})}return{data:{session:e},error:null}}let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);if(i)return{data:{session:null},error:i};return{data:{session:s},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{if(e)return await tG(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:tZ});return await this._useSession(async e=>{var t,r,s;let{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 tG(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:tZ}):{data:{user:null},error:new tl}})}catch(e){if(ti(e))return ti(e)&&"AuthSessionMissingError"===e.name&&(await this._removeSession(),await tC(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:e};throw e}}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=>{let{data:s,error:i}=r;if(i)throw i;if(!s.session)throw new tl;let n=s.session,a=null,o=null;"pkce"===this.flowType&&null!=e.email&&([a,o]=await tq(this.storage,this.storageKey));let{data:l,error:u}=await tG(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:o}),jwt:n.access_token,xform:tZ});if(u)throw u;return n.user=l.user,await this._saveSession(n),await this._notifyAllSubscribers("USER_UPDATED",n),{data:{user:n.user},error:null}})}catch(e){if(ti(e))return{data:{user:null},error:e};throw e}}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 tl;let t=Date.now()/1e3,r=t,s=!0,i=null,{payload:n}=tx(e.access_token);if(n.exp&&(s=(r=n.exp)<=t),s){let{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{let{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(e){if(ti(e))return{data:{session:null,user:null},error:e};throw e}}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){let{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 tl;let{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(e){if(ti(e))return{data:{user:null,session:null},error:e};throw e}}async _getSessionFromURL(e,t){try{if(!tO())throw new tc("No browser detected.");
34if(e.error||e.error_description||e.error_code)throw new tc(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 td("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new tc("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new td("No code detected.");let{data:t,error:r}=await this._exchangeCodeForSession(e.code);if(r)throw r;let 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}}let{provider_token:r,provider_refresh_token:s,access_token:i,refresh_token:n,expires_in:a,expires_at:o,token_type:l}=e;if(!i||!a||!n||!l)throw new tc("No session defined in URL");let u=Math.round(Date.now()/1e3),h=parseInt(a),c=u+h;o&&(c=parseInt(o));let d=c-u;1e3*d<=3e4&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${d}s, should have been closer to ${h}s`);let f=c-h;u-f>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",f,c,u):u-f<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",f,c,u);let{data:p,error:g}=await this._getUser(i);if(g)throw g;let w={provider_token:r,provider_refresh_token:s,access_token:i,expires_in:h,expires_at:c,refresh_token:n,token_type:l,user:p.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:w,redirectType:e.type},error:null}}catch(e){if(ti(e))return{data:{session:null,redirectType:null},error:e};throw e}}_isImplicitGrantCallback(e){return!!(e.access_token||e.error_description)}async _isPKCECallback(e){let t=await tR(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;let{data:s,error:i}=t;if(i)return{error:i};let n=null===(r=s.session)||void 0===r?void 0:r.access_token;if(n){let{error:t}=await this.admin.signOut(n,e);if(t&&!(ti(t)&&"AuthApiError"===t.name&&(404===t.status||401===t.status||403===t.status)))return{error:t}}return"others"!==e&&(await this._removeSession(),await tC(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){let t="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){let 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{let{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(t){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",t),console.error(t)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null;"pkce"===this.flowType&&([r,s]=await tq(this.storage,this.storageKey,!0));try{return await tG(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(e){if(ti(e))return{data:null,error:e};throw e}}async getUserIdentities(){var e;try{let{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(e){if(ti(e))return{data:null,error:e};throw e}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{let{data:r,error:s}=await this._useSession(async t=>{var r,s,i,n,a;let{data:o,error:l}=t;if(l)throw l;let u=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 tG(this.fetch,"GET",u,{headers:this.headers,jwt:null!==(a=null===(n=o.session)||void 0===n?void 0:n.access_token)&&void 0!==a?a:void 0})});if(s)throw s;return!tO()||(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(t){if(ti(t))return{data:{provider:e.provider,url:null},error:t};throw t}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{let{error:s,data:{session:i}}=t;if(s)throw s;let{options:n,provider:a,token:o,access_token:l,nonce:u}=e,{data:h,error:c}=await tG(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:a,id_token:o,access_token:l,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},xform:tQ});if(c)return{data:{user:null,session:null},error:c};if(!h||!h.session||!h.user)return{data:{user:null,session:null},error:new tu};return h.session&&(await this._saveSession(h.session),await this._notifyAllSubscribers("USER_UPDATED",h.session)),{data:h,error:c}}catch(e){if(ti(e))return{data:{user:null,session:null},error:e};throw e}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:n}=t;if(n)throw n;
34return await tG(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(e){if(ti(e))return{data:null,error:e};throw e}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{var r,s;let i=Date.now();return await (r=async r=>(r>0&&await tN(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await tG(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:tQ})),s=(e,t)=>t&&tp(t)&&Date.now()+200*Math.pow(2,e)-i<3e4,new Promise((e,t)=>{(async()=>{for(let i=0;i<1/0;i++)try{let t=await r(i);if(!s(i,null,t)){e(t);return}}catch(e){if(!s(i,e)){t(e);return}}})()}))}catch(e){if(this._debug(t,"error",e),ti(e))return{data:{session:null,user:null},error:e};throw e}finally{this._debug(t,"end")}}_isValidSession(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let 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),tO()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e,t;let r="#_recoverAndRefresh()";this._debug(r,"begin");try{let s=await tR(this.storage,this.storageKey);if(s&&this.userStorage){let t=await tR(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!t&&(t={user:s.user},await tP(this.userStorage,this.storageKey+"-user",t)),s.user=null!==(e=null==t?void 0:t.user)&&void 0!==e?e:tK()}else if(s&&!s.user&&!s.user){let e=await tR(this.storage,this.storageKey+"-user");e&&(null==e?void 0:e.user)?(s.user=e.user,await tC(this.storage,this.storageKey+"-user"),await tP(this.storage,this.storageKey,s)):s.user=tK()}if(this._debug(r,"session from storage",s),!this._isValidSession(s)){this._debug(r,"session is not valid"),null!==s&&await this._removeSession();return}let i=(null!==(t=s.expires_at)&&void 0!==t?t:1/0)*1e3-Date.now()<9e4;if(this._debug(r,`session has${i?"":" not"} expired with margin of 90000s`),i){if(this.autoRefreshToken&&s.refresh_token){let{error:e}=await this._callRefreshToken(s.refresh_token);e&&(console.error(e),tp(e)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",e),await this._removeSession()))}}else if(s.user&&!0===s.user.__isUserNotAvailableProxy)try{let{data:e,error:t}=await this._getUser(s.access_token);!t&&(null==e?void 0:e.user)?(s.user=e.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(e){console.error("Error getting user data:",e),this._debug(r,"error getting user data, skipping SIGNED_IN notification",e)}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(e){this._debug(r,"error",e),console.error(e);return}finally{this._debug(r,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new tl;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new t$;let{data:t,error:r}=await this._refreshAccessToken(e);if(r)throw r;if(!t.session)throw new tl;await this._saveSession(t.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",t.session);let s={data:t.session,error:null};return this.refreshingDeferred.resolve(s),s}catch(e){if(this._debug(s,"error",e),ti(e)){let r={data:null,error:e};return tp(e)||await this._removeSession(),null===(t=this.refreshingDeferred)||void 0===t||t.resolve(r),r}throw null===(r=this.refreshingDeferred)||void 0===r||r.reject(e),e}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let s=[],i=Array.from(this.stateChangeEmitters.values()).map(async r=>{try{await r.callback(e,t)}catch(e){s.push(e)}});if(await Promise.all(i),s.length>0){for(let e=0;e<s.length;e+=1)console.error(s[e]);throw s[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0;let t=Object.assign({},e),r=t.user&&!0===t.user.__isUserNotAvailableProxy;if(this.userStorage){!r&&t.user&&await tP(this.userStorage,this.storageKey+"-user",{user:t.user});let e=Object.assign({},t);delete e.user;let s=tV(e);await tP(this.storage,this.storageKey,s)}else{let e=tV(t);await tP(this.storage,this.storageKey,e)}}async _removeSession(){this._debug("#_removeSession()"),await tC(this.storage,this.storageKey),await tC(this.storage,this.storageKey+"-code-verifier"),await tC(this.storage,this.storageKey+"-user"),this.userStorage&&await tC(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&tO()&&(null==window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}
34catch(e){console.error("removing visibilitychange callback failed",e)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),3e4);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()");let 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{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((1e3*r.expires_at-e)/3e4);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){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof t4)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!tO()||!(null==window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),null==window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let 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()=>{if("visible"!==document.visibilityState){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let 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){let[e,t]=await tq(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){let 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;let{data:s,error:i}=t;return i?{data:null,error:i}:await tG(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(e){if(ti(e))return{data:null,error:e};throw e}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:n}=t;if(n)return{data:null,error:n};let a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:"totp"===e.factorType?{issuer:e.issuer}:{}),{data:o,error:l}=await tG(this.fetch,"POST",`${this.url}/factors`,{body:a,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"===o.type&&(null===(s=null==o?void 0:o.totp)||void 0===s?void 0:s.qr_code)&&(o.totp.qr_code=`data:image/svg+xml;utf-8,${o.totp.qr_code}`),{data:o,error:null})})}catch(e){if(ti(e))return{data:null,error:e};throw e}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r,s,i;let{data:n,error:a}=t;if(a)return{data:null,error:a};let o=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,"toJSON"in s&&"function"==typeof s.toJSON?s.toJSON():{id:s.id,rawId:s.id,response:{attestationObject:tE(new Uint8Array(s.response.attestationObject)),clientDataJSON:tE(new Uint8Array(s.response.clientDataJSON))},type:"public-key",clientExtensionResults:s.getClientExtensionResults(),authenticatorAttachment:null!==(i=s.authenticatorAttachment)&&void 0!==i?i:void 0}):function(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();let r=e.getClientExtensionResults(),s=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:tE(new Uint8Array(s.authenticatorData)),clientDataJSON:tE(new Uint8Array(s.clientDataJSON)),signature:tE(new Uint8Array(s.signature)),userHandle:s.userHandle?tE(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:r,authenticatorAttachment:null!==(t=e.authenticatorAttachment)&&void 0!==t?t:void 0}}(e.webauthn.credential_response)})}:{code:e.code}),{data:l,error:u}=await tG(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:null===(r=null==n?void 0:n.session)||void 0===r?void 0:r.access_token});return u?{data:null,error:u}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+l.expires_in},l)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",l),{data:l,error:u})})}catch(e){if(ti(e))return{data:null,error:e};throw e}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;if(i)return{data:null,error:i};let n=await tG(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;let{data:a}=n;if("webauthn"!==a.type)return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:function(e){if(!e)throw Error("Credential creation options are required");if("undefined"!=typeof PublicKeyCredential&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(e);let{challenge:t,user:r,excludeCredentials:s}=e,i=(0,A.__rest)(e,["challenge","user","excludeCredentials"]),n=tS(t).buffer,a=Object.assign(Object.assign({}
34,r),{id:tS(r.id).buffer}),o=Object.assign(Object.assign({},i),{challenge:n,user:a});if(s&&s.length>0){o.excludeCredentials=Array(s.length);for(let e=0;e<s.length;e++){let t=s[e];o.excludeCredentials[e]=Object.assign(Object.assign({},t),{id:tS(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return o}(a.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:function(e){if(!e)throw Error("Credential request options are required");if("undefined"!=typeof PublicKeyCredential&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseRequestOptionsFromJSON)return PublicKeyCredential.parseRequestOptionsFromJSON(e);let{challenge:t,allowCredentials:r}=e,s=(0,A.__rest)(e,["challenge","allowCredentials"]),i=tS(t).buffer,n=Object.assign(Object.assign({},s),{challenge:i});if(r&&r.length>0){n.allowCredentials=Array(r.length);for(let e=0;e<r.length;e++){let t=r[e];n.allowCredentials[e]=Object.assign(Object.assign({},t),{id:tS(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return n}(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(e){if(ti(e))return{data:null,error:e};throw e}})}async _challengeAndVerify(e){let{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;let{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};let s={all:[],phone:[],totp:[],webauthn:[]};for(let r of null!==(e=null==t?void 0:t.factors)&&void 0!==e?e:[])s.all.push(r),"verified"===r.status&&s[r.factor_type].push(r);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,r;let{data:{session:s},error:i}=e;if(i)return{data:null,error:i};if(!s)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:n}=tx(s.access_token),a=null;n.aal&&(a=n.aal);let o=a;return(null!==(r=null===(t=s.user.factors)||void 0===t?void 0:t.filter(e=>"verified"===e.status))&&void 0!==r?r:[]).length>0&&(o="aal2"),{data:{currentLevel:a,nextLevel:o,currentAuthenticationMethods:n.amr||[]},error:null}}))}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(t=>t.kid===e);if(r)return r;let s=Date.now();if((r=this.jwks.keys.find(t=>t.kid===e))&&this.jwks_cached_at+6e5>s)return r;let{data:i,error:n}=await tG(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}async getClaims(e,t={}){try{let r=e;if(!r){let{data:e,error:t}
34=await this.getSession();if(t||!e.session)return{data:null,error:t};r=e.session.access_token}let{header:s,payload:i,signature:n,raw:{header:a,payload:o}}=tx(r);(null==t?void 0:t.allowExpired)||function(e){if(!e)throw Error("Missing exp claim");if(e<=Math.floor(Date.now()/1e3))throw Error("JWT has expired")}(i.exp);let l=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,(null==t?void 0:t.keys)?{keys:t.keys}:null==t?void 0:t.jwks);if(!l){let{error:e}=await this.getUser(r);if(e)throw e;return{data:{claims:i,header:s,signature:n},error:null}}let u=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 Error("Invalid alg claim")}}(s.alg),h=await crypto.subtle.importKey("jwk",l,u,!0,["verify"]);if(!await crypto.subtle.verify(u,h,n,function(e){let t=[];return!function(e,t){for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);if(s>55295&&s<=56319){let t=(s-55296)*1024&65535;s=(e.charCodeAt(r+1)-56320&65535|t)+65536,r+=1}!function(e,t){if(e<=127){t(e);return}if(e<=2047){t(192|e>>6),t(128|63&e);return}if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|63&e);return}if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|63&e);return}throw Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}(s,t)}}(e,e=>t.push(e)),new Uint8Array(t)}(`${a}.${o}`)))throw new tw("Invalid JWT signature");return{data:{claims:i,header:s,signature:n},error:null}}catch(e){if(ti(e))return{data:null,error:e};throw e}}}rw.nextInstanceID=0;var ry=rw;class rv extends ry{constructor(e){super(e)}}class rm{constructor(e,t,r){var s,i,n;this.supabaseUrl=e,this.supabaseKey=t;let a=function(e){let t=null==e?void 0:e.trim();if(!t)throw Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(t.endsWith("/")?t:t+"/")}catch(e){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}(e);if(!t)throw Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",a),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",a),this.storageUrl=new URL("storage/v1",a),this.functionsUrl=new URL("functions/v1",a);let o=`sb-${a.hostname.split(".")[0]}-auth-token`,l=function(e,t){var r,s;let{db:i,auth:n,realtime:a,global:o}=e,{db:l,auth:u,realtime:h,global:c}=t,d={db:Object.assign(Object.assign({},l),i),auth:Object.assign(Object.assign({},u),n),realtime:Object.assign(Object.assign({},h),a),storage:{},global:Object.assign(Object.assign(Object.assign({},c),o),{headers:Object.assign(Object.assign({},null!==(r=null==c?void 0:c.headers)&&void 0!==r?r:{}),null!==(s=null==o?void 0:o.headers)&&void 0!==s?s:{})}),accessToken:async()=>""};return e.accessToken?d.accessToken=e.accessToken:delete d.accessToken,d}(null!=r?r:{},{db:e1,realtime:e3,auth:Object.assign(Object.assign({},e2),{storageKey:o}),global:e0});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 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=e4(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 N(new URL("rest/v1",a).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this.storage=new eX(this.storageUrl.href,this.headers,this.fetch,null==r?void 0:r.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new x(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)}
34channel(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();let{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:a,lock:o,debug:l},u,h){let c={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new rv({url:this.authUrl.href,headers:Object.assign(Object.assign({},c),u),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:i,flowType:a,lock:o,debug:l,fetch:h,hasCustomAuthorizationHeader:Object.keys(this.headers).some(e=>"authorization"===e.toLowerCase())})}_initRealtimeClient(e){return new el(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?(this.changedAccessToken=r,this.realtime.setAuth(r)):"SIGNED_OUT"===e&&(this.realtime.setAuth(),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0)}}var rb=r(40257);let r_=(e,t,r)=>new rm(e,t,r);(function(){if("undefined"!=typeof window||void 0===rb)return!1;let e=rb.version;if(null==e)return!1;let t=e.match(/^v(\d+)\./);return!!t&&18>=parseInt(t[1],10)})()&&console.warn(`⚠️  Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217`);var rk=r(27696);function rS(){return"undefined"!=typeof window&&void 0!==window.document}rk.Qc,rk.qC;let rE={path:"/",sameSite:"lax",httpOnly:!1,maxAge:3456e4},rO=/^(.*)[.](0|[1-9][0-9]*)$/;function rT(e,t){if(e===t)return!0;let r=e.match(rO);return!!r&&r[1]===t}function rj(e,t,r){let s=r??3180,i=encodeURIComponent(t);if(i.length<=s)return[{name:e,value:t}];let n=[];for(;i.length>0;){let e=i.slice(0,s),t=e.lastIndexOf("%");t>s-3&&(e=e.slice(0,t));let r="";for(;e.length>0;)try{r=decodeURIComponent(e);break}catch(t){if(t instanceof URIError&&"%"===e.at(-3)&&e.length>3)e=e.slice(0,e.length-3);else throw t}n.push(r),i=i.slice(e.length)}return n.map((t,r)=>({name:`${e}.${r}`,value:t}))}async function rA(e,t){let r=await t(e);if(r)return r;let s=[];for(let r=0;;r++){let i=`${e}.${r}`,n=await t(i);if(!n)break;s.push(n)}return s.length>0?s.join(""):null}let rI="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),rP=" 	\n\r=".split(""),rR=(()=>{let e=Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<rP.length;t+=1)e[rP[t].charCodeAt(0)]=-2;for(let t=0;t<rI.length;t+=1)e[rI[t].charCodeAt(0)]=t;return e})();function rC(e){let t=[],r=0,s=0;if(function(e,t){for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);if(s>55295&&s<=56319){let t=(s-55296)*1024&65535;s=(e.charCodeAt(r+1)-56320&65535|t)+65536,r+=1}!function(e,t){if(e<=127){t(e);return}if(e<=2047){t(192|e>>6),t(128|63&e);return}if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|63&e);return}if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|63&e);return}throw Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}(s,t)}}(e,e=>{for(r=r<<8|e,s+=8;s>=6;){let e=r>>s-6&63;t.push(rI[e]),s-=6}}),s>0)for(r<<=6-s,s=6;s>=6;){let e=r>>s-6&63;t.push(rI[e]),s-=6}return t.join("")}function r$(e){let t=[],r=e=>{t.push(String.fromCodePoint(e))},s={utf8seq:0,codepoint:0},i=0,n=0;for(let t=0;t<e.length;t+=1){let a=rR[e.charCodeAt(t)];if(a>-1)for(i=i<<6|a,n+=6;n>=8;)(function(e,t,r){if(0===t.utf8seq){if(e<=127){r(e);return}for(let r=1;r<6;r+=1)if((e>>7-r&1)==0){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)t.codepoint=7&e;else throw Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&r(t.codepoint)}})(i>>n-8&255,s,r),n-=8;else if(-2===a)continue;else throw Error(`Invalid Base64-URL character "${e.at(t)}" at position ${t}`)}return t.join("")}let rx="base64-";async function rN({getAll:e,setAll:t,setItems:r,removedItems:s},i){let n=i.cookieEncoding,a=i.cookieOptions??null,o=await e([...r?Object.keys(r):[],...s?Object.keys(s):[]]),l=o?.map(({name:e})=>e)||[],u=Object.keys(s).flatMap(e=>l.filter(t=>rT(t,e))),h=Object.keys(r).flatMap(e=>{let t=new Set(l.filter(t=>rT(t,e))),s=r[e];"base64url"===n&&(s=rx+rC(s));let i=rj(e,s);
34return i.forEach(e=>{t.delete(e.name)}),u.push(...t),i}),c={...rE,...a,maxAge:0},d={...rE,...a,maxAge:rE.maxAge};delete c.name,delete d.name,await t([...u.map(e=>({name:e,value:"",options:c})),...h.map(({name:e,value:t})=>({name:e,value:t,options:d}))])}function rU(e,t,r){let i=r?.isSingleton===!0||(!r||!("isSingleton"in r))&&rS();if(i&&s)return s;if(!e||!t)throw Error(`@supabase/ssr: Your project's URL and API key are required to create a Supabase client!
35
36Check your Supabase project's API settings to find these values
37
38https://supabase.com/dashboard/project/_/settings/api`);let{storage:n}=function(e,t){let r,s;let i=e.cookies??null,n=e.cookieEncoding,a={},o={};if(i){if("get"in i){let e=async e=>{let t=e.flatMap(e=>[e,...Array.from({length:5}).map((t,r)=>`${e}.${r}`)]),r=[];for(let e=0;e<t.length;e+=1){let s=await i.get(t[e]);(s||"string"==typeof s)&&r.push({name:t[e],value:s})}return r};if(r=async t=>await e(t),"set"in i&&"remove"in i)s=async e=>{for(let t=0;t<e.length;t+=1){let{name:r,value:s,options:n}=e[t];s?await i.set(r,s,n):await i.remove(r,n)}};else if(t)s=async()=>{console.warn("@supabase/ssr: createServerClient was configured without set and remove cookie methods, but the client needs to set cookies. This can lead to issues such as random logouts, early session termination or increased token refresh requests. If in NextJS, check your middleware.ts file, route handlers and server actions for correctness. Consider switching to the getAll and setAll cookie methods instead of get, set and remove which are deprecated and can be difficult to use correctly.")};else throw Error("@supabase/ssr: createBrowserClient requires configuring a getAll and setAll cookie method (deprecated: alternatively both get, set and remove can be used)")}else if("getAll"in i){if(r=async()=>await i.getAll(),"setAll"in i)s=i.setAll;else if(t)s=async()=>{console.warn("@supabase/ssr: createServerClient was configured without the setAll cookie method, but the client needs to set cookies. This can lead to issues such as random logouts, early session termination or increased token refresh requests. If in NextJS, check your middleware.ts file, route handlers and server actions for correctness.")};else throw Error("@supabase/ssr: createBrowserClient requires configuring both getAll and setAll cookie methods (deprecated: alternatively both get, set and remove can be used)")}else throw Error(`@supabase/ssr: ${t?"createServerClient":"createBrowserClient"} requires configuring getAll and setAll cookie methods (deprecated: alternatively use get, set and remove).${rS()?" As this is called in a browser runtime, consider removing the cookies option object to use the document.cookie API automatically.":""}`)}else if(!t&&rS()){let e=()=>{let e=(0,rk.Qc)(document.cookie);return Object.keys(e).map(t=>({name:t,value:e[t]??""}))};r=()=>e(),s=e=>{e.forEach(({name:e,value:t,options:r})=>{document.cookie=(0,rk.qC)(e,t,r)})}}else if(t)throw Error("@supabase/ssr: createServerClient must be initialized with cookie options that specify getAll and setAll functions (deprecated, not recommended: alternatively use get, set and remove)");else r=()=>[],s=()=>{throw Error("@supabase/ssr: createBrowserClient in non-browser runtimes (including Next.js pre-rendering mode) was not initialized cookie options that specify getAll and setAll functions (deprecated: alternatively use get, set and remove), but they were needed")};return t?{getAll:r,setAll:s,setItems:a,removedItems:o,storage:{isServer:!0,getItem:async e=>{if("string"==typeof a[e])return a[e];if(o[e])return null;let t=await r([e]),s=await rA(e,async e=>{let r=t?.find(({name:t})=>t===e)||null;return r?r.value:null});if(!s)return null;let i=s;return"string"==typeof s&&s.startsWith(rx)&&(i=r$(s.substring(rx.length))),i},setItem:async(t,i)=>{t.endsWith("-code-verifier")&&await rN({getAll:r,setAll:s,setItems:{[t]:i},removedItems:{}},{cookieOptions:e?.cookieOptions??null,cookieEncoding:n}),a[t]=i,delete o[t]},removeItem:async e=>{delete a[e],o[e]=!0}}}:{getAll:r,setAll:s,setItems:a,removedItems:o,storage:{isServer:!1,getItem:async e=>{let t=await r([e]),s=await rA(e,async e=>{let r=t?.find(({name:t})=>t===e)||null;return r?r.value:null});if(!s)return null;let i=s;return s.startsWith(rx)&&(i=r$(s.substring(rx.length))),i},setItem:async(t,i)=>{let a=await r([t]),o=new Set((a?.map(({name:e})=>e)||[]).filter(e=>rT(e,t))),l=i;"base64url"===n&&(l=rx+rC(i));let u=rj(t,l);u.forEach(({name:e})=>{o.delete(e)});let h={...rE,...e?.cookieOptions,maxAge:0},c={...rE,...e?.cookieOptions,maxAge:rE.maxAge};delete h.name,delete c.name;let d=[...[...o].map(e=>({name:e,value:"",options:h})),...u.map(({name:e,value:t})=>({name:e,value:t,options:c}))];d.length>0&&await s(d)},removeItem:async t=>{let i=await r([t]),n=(i?.map(({name:e})=>e)||[]).filter(e=>rT(e,t)),a={...rE,...e?.cookieOptions,maxAge:0};delete a.name,n.length>0&&await s(n.map(e=>({name:e,value:"",options:a})))}}}}({...r,cookieEncoding:r?.cookieEncoding??"base64url"},!1),a=r_(e,t,{...r,global:{...r?.global,headers:{...r?.global?.headers,"X-Client-Info":"supabase-ssr/0.8.0 createBrowserClient"}},auth:{...r?.auth,...r?.cookieOptions?.name?{storageKey:r.cookieOptions.name}:null,flowType:"pkce",autoRefreshToken:rS(),detectSessionInUrl:rS(),persistSession:!0,storage:n,...r?.cookies&&"encode"in r.cookies&&"tokens-only"===r.cookies.encode?{userStorage:r?.auth?.userStorage??window.localStorage}:null}});return i&&(s=a),a}var rD=r(40257);if(void 0!==rD&&rD.env?.npm_package_name){let e=rD.env.npm_package_name;["@supabase/auth-helpers-nextjs","@supabase/auth-helpers-react","@supabase/auth-helpers-remix","@supabase/auth-helpers-sveltekit"].includes(e)&&console.warn(`
39╔════════════════════════════════════════════════════════════════════════════╗
40║ ⚠️  IMPORTANT: Package Consolidation Notice                                ║
41║                                                                            ║
42║ The ${e.padEnd(35)} package name is deprecated.  ║
43║                                                                            ║
44║ You are now using @supabase/ssr - a unified solution for all frameworks.  ║
45║                                                                            ║
46║ The auth-helpers packages have been consolidated into @supabase/ssr       ║
47║ to provide better maintenance and consistent APIs across frameworks.      ║
48║                                                                            ║
49║ Please update your package.json to use @supabase/ssr directly:            ║
50║   npm uninstall ${e.padEnd(42)} ║
51║   npm install @supabase/ssr                                               ║
52║                                                                            ║
53║ For more information, visit:                                              ║
54║ https://supabase.com/docs/guides/auth/server-side                         ║
55╚════════════════════════════════════════════════════════════════════════════╝
56    `)}},27696:function(e,t){t.Qc=function(e,t){let r=new o,s=e.length;if(s<2)return r;let i=t?.decode||h,n=0;do{let t=function(e,t,r){let s=e.indexOf("=",t);return s<r?s:-1}(e,n,s);if(-1===t)break;let a=function(e,t,r){let s=e.indexOf(";",t);return -1===s?r:s}(e,n,s);if(t>a){n=e.lastIndexOf(";",t-1)+1;continue}let o=u(e,n,t);void 0===r[o]&&(r[o]=i(u(e,t+1,a))),n=a+1}while(n<s);return r},t.qC=l,t.qC=l;let r=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,s=/^[\u0021-\u003A\u003C-\u007E]*$/,i=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,n=/^[\u0020-\u003A\u003D-\u007E]*$/,a=Object.prototype.toString,o=(()=>{let e=function(){};return e.prototype=Object.create(null),e})();function l(e,t,o){let l="object"==typeof e?e:{...o,name:e,value:String(t)},u=("object"==typeof t?t:o)?.encode||encodeURIComponent;
56if(!r.test(l.name))throw TypeError(`argument name is invalid: ${l.name}`);let h=l.value?u(l.value):"";if(!s.test(h))throw TypeError(`argument val is invalid: ${l.value}`);let c=l.name+"="+h;if(void 0!==l.maxAge){if(!Number.isInteger(l.maxAge))throw TypeError(`option maxAge is invalid: ${l.maxAge}`);c+="; Max-Age="+l.maxAge}if(l.domain){if(!i.test(l.domain))throw TypeError(`option domain is invalid: ${l.domain}`);c+="; Domain="+l.domain}if(l.path){if(!n.test(l.path))throw TypeError(`option path is invalid: ${l.path}`);c+="; Path="+l.path}if(l.expires){var d;if(d=l.expires,"[object Date]"!==a.call(d)||!Number.isFinite(l.expires.valueOf()))throw TypeError(`option expires is invalid: ${l.expires}`);c+="; Expires="+l.expires.toUTCString()}if(l.httpOnly&&(c+="; HttpOnly"),l.secure&&(c+="; Secure"),l.partitioned&&(c+="; Partitioned"),l.priority)switch("string"==typeof l.priority?l.priority.toLowerCase():void 0){case"low":c+="; Priority=Low";break;case"medium":c+="; Priority=Medium";break;case"high":c+="; Priority=High";break;
56default:throw TypeError(`option priority is invalid: ${l.priority}`)}if(l.sameSite)switch("string"==typeof l.sameSite?l.sameSite.toLowerCase():l.sameSite){case!0:case"strict":c+="; SameSite=Strict";break;case"lax":c+="; SameSite=Lax";break;case"none":c+="; SameSite=None";break;default:throw TypeError(`option sameSite is invalid: ${l.sameSite}`)}return c}function u(e,t,r){let s=t,i=r;do{let t=e.charCodeAt(s);if(32!==t&&9!==t)break}while(++s<i);for(;i>s;){let t=e.charCodeAt(i-1);if(32!==t&&9!==t)break;i--}return e.slice(s,i)}function h(e){if(-1===e.indexOf("%"))return e;try{return decodeURIComponent(e)}catch(t){return e}}},5853:function(e,t,r){r.r(t),r.d(t,{__addDisposableResource:function(){return N},__assign:function(){return n},__asyncDelegator:function(){return O},__asyncGenerator:function(){return E},__asyncValues:function(){return T},__await:function(){return S},__awaiter:function(){return p},__classPrivateFieldGet:function(){return C},__classPrivateFieldIn:function(){return x},__classPrivateFieldSet:function(){return $},__createBinding:function(){return w},__decorate:function(){return o},__disposeResources:function(){return D},__esDecorate:function(){return u},__exportStar:function(){return y},__extends:function(){return i},__generator:function(){return g},__importDefault:function(){return R},__importStar:function(){return P}
56,__makeTemplateObject:function(){return j},__metadata:function(){return f},__param:function(){return l},__propKey:function(){return c},__read:function(){return m},__rest:function(){return a},__rewriteRelativeImportExtension:function(){return L},__runInitializers:function(){return h},__setFunctionName:function(){return d},__spread:function(){return b},__spreadArray:function(){return k},__spreadArrays:function(){return _},__values:function(){return v}});var s=function(e,t){return(s=Object.setPrototypeOf||({__proto__:[]})instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])})(e,t)};function i(e,t){if("function"!=typeof t&&null!==t)throw TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}s(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var n=function(){return(n=Object.assign||function(e){for(var t,r=1,s=arguments.length;r<s;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e}).apply(this,arguments)};function a(e,t){var r={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&0>t.indexOf(s)&&(r[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,s=Object.getOwnPropertySymbols(e);i<s.length;i++)0>t.indexOf(s[i])&&Object.prototype.propertyIsEnumerable.call(e,s[i])&&(r[s[i]]=e[s[i]]);return r}function o(e,t,r,s){var i,n=arguments.length,a=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,s);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(a=(n<3?i(a):n>3?i(t,r,a):i(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a}function l(e,t){return function(r,s){t(r,s,e)}}function u(e,t,r,s,i,n){function a(e){if(void 0!==e&&"function"!=typeof e)throw TypeError("Function expected");return e}for(var o,l=s.kind,u="getter"===l?"get":"setter"===l?"set":"value",h=!t&&e?s.static?e:e.prototype:null,c=t||(h?Object.getOwnPropertyDescriptor(h,s.name):{}),d=!1,f=r.length-1;f>=0;f--){var p={};for(var g in s)p[g]="access"===g?{}:s[g];for(var g in s.access)p.access[g]=s.access[g];p.addInitializer=function(e){if(d)throw TypeError("Cannot add initializers after decoration has completed");n.push(a(e||null))};var w=(0,r[f])("accessor"===l?{get:c.get,set:c.set}:c[u],p);if("accessor"===l){if(void 0===w)continue;if(null===w||"object"!=typeof w)throw TypeError("Object expected");(o=a(w.get))&&(c.get=o),(o=a(w.set))&&(c.set=o),(o=a(w.init))&&i.unshift(o)}else(o=a(w))&&("field"===l?i.unshift(o):c[u]=o)}h&&Object.defineProperty(h,s.name,c),d=!0}function h(e,t,r){for(var s=arguments.length>2,i=0;i<t.length;i++)r=s?t[i].call(e,r):t[i].call(e);return s?r:void 0}function c(e){return"symbol"==typeof e?e:"".concat(e)}function d(e,t,r){return"symbol"==typeof t&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:r?"".concat(r," ",t):t})}function f(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function p(e,t,r,s){return new(r||(r=Promise))(function(i,n){function a(e){try{l(s.next(e))}catch(e){n(e)}}function o(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?i(e.value):((t=e.value)instanceof r?t:new r(function(e){e(t)})).then(a,o)}l((s=s.apply(e,t||[])).next())})}function g(e,t){var r,s,i,n={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=o(0),a.throw=o(1),a.return=o(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function o(o){return function(l){return function(o){if(r)throw TypeError("Generator is already executing.");for(;a&&(a=0,o[0]&&(n=0)),n;)try{if(r=1,s&&(i=2&o[0]?s.return:o[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,o[1])).done)return i;switch(s=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return n.label++,{value:o[1],done:!1};case 5:n.label++,s=o[1],o=[0];continue;case 7:o=n.ops.pop(),n.trys.pop();continue;default:if(!(i=(i=n.trys).length>0&&i[i.length-1])&&(6===o[0]||2===o[0])){n=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){n.label=o[1];break}if(6===o[0]&&n.label<i[1]){n.label=i[1],i=o;break}if(i&&n.label<i[2]){n.label=i[2],n.ops.push(o);break}i[2]&&n.ops.pop(),n.trys.pop();continue}o=t.call(e,n)}catch(e){o=[6,e],s=0}finally{r=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}}var w=Object.create?function(e,t,r,s){void 0===s&&(s=r);var i=Object.getOwnPropertyDescriptor(t,r);
56(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,s,i)}:function(e,t,r,s){void 0===s&&(s=r),e[s]=t[r]};function y(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||w(t,e,r)}function v(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],s=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&s>=e.length&&(e=void 0),{value:e&&e[s++],done:!e}}};throw TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function m(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var s,i,n=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(s=n.next()).done;)a.push(s.value)}catch(e){i={error:e}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return a}function b(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(m(arguments[t]));return e}function _(){for(var e=0,t=0,r=arguments.length;t<r;t++)e+=arguments[t].length;for(var s=Array(e),i=0,t=0;t<r;t++)for(var n=arguments[t],a=0,o=n.length;a<o;a++,i++)s[i]=n[a];return s}function k(e,t,r){if(r||2==arguments.length)for(var s,i=0,n=t.length;i<n;i++)!s&&i in t||(s||(s=Array.prototype.slice.call(t,0,i)),s[i]=t[i]);return e.concat(s||Array.prototype.slice.call(t))}function S(e){return this instanceof S?(this.v=e,this):new S(e)}function E(e,t,r){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var s,i=r.apply(e,t||[]),n=[];return s=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",function(e){return function(t){return Promise.resolve(t).then(e,u)}}),s[Symbol.asyncIterator]=function(){return this},s;function a(e,t){i[e]&&(s[e]=function(t){return new Promise(function(r,s){n.push([e,t,r,s])>1||o(e,t)})},t&&(s[e]=t(s[e])))}function o(e,t){try{var r;(r=i[e](t)).value instanceof S?Promise.resolve(r.value.v).then(l,u):h(n[0][2],r)}catch(e){h(n[0][3],e)}}function l(e){o("next",e)}function u(e){o("throw",e)}function h(e,t){e(t),n.shift(),n.length&&o(n[0][0],n[0][1])}}function O(e){var t,r;return t={},s("next"),s("throw",function(e){throw e}),s("return"),t[Symbol.iterator]=function(){return this},t;function s(s,i){t[s]=e[s]?function(t){return(r=!r)?{value:S(e[s](t)),done:!1}:i?i(t):t}:i}}function T(e){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=v(e),t={},s("next"),s("throw"),s("return"),t[Symbol.asyncIterator]=function(){return this},t);function s(r){t[r]=e[r]&&function(t){return new Promise(function(s,i){!function(e,t,r,s){Promise.resolve(s).then(function(t){e({value:t,done:r})},t)}(s,i,(t=e[r](t)).done,t.value)})}}}function j(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}var A=Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t},I=function(e){return(I=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t})(e)};function P(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=I(e),s=0;s<r.length;s++)"default"!==r[s]&&w(t,e,r[s]);return A(t,e),t}function R(e){return e&&e.__esModule?e:{default:e}}function C(e,t,r,s){if("a"===r&&!s)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?s:"a"===r?s.call(e):s?s.value:t.get(e)}function $(e,t,r,s,i){if("m"===s)throw TypeError("Private method is not writable");if("a"===s&&!i)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?i.call(e,r):i?i.value=r:t.set(e,r),r}function x(e,t){if(null===t||"object"!=typeof t&&"function"!=typeof t)throw TypeError("Cannot use 'in' operator on non-object");return"function"==typeof e?t===e:e.has(t)}function N(e,t,r){if(null!=t){var s,i;if("object"!=typeof t&&"function"!=typeof t)throw TypeError("Object expected.");
56if(r){if(!Symbol.asyncDispose)throw TypeError("Symbol.asyncDispose is not defined.");s=t[Symbol.asyncDispose]}if(void 0===s){if(!Symbol.dispose)throw TypeError("Symbol.dispose is not defined.");s=t[Symbol.dispose],r&&(i=s)}if("function"!=typeof s)throw TypeError("Object not disposable.");i&&(s=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:s,async:r})}else r&&e.stack.push({async:!0});return t}var U="function"==typeof SuppressedError?SuppressedError:function(e,t,r){var s=Error(r);return s.name="SuppressedError",s.error=e,s.suppressed=t,s};function D(e){function t(t){e.error=e.hasError?new U(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}var r,s=0;return function i(){for(;r=e.stack.pop();)try{if(!r.async&&1===s)return s=0,e.stack.push(r),Promise.resolve().then(i);if(r.dispose){var n=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(n).then(i,function(e){return t(e),i()})}else s|=1}catch(e){t(e)}if(1===s)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()}function L(e,t){return"string"==typeof e&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(e,r,s,i,n){return r?t?".jsx":".js":!s||i&&n?s+i+"."+n.toLowerCase()+"js":e}):e}t.default={__extends:i,__assign:n,__rest:a,__decorate:o,__param:l,__esDecorate:u,__runInitializers:h,__propKey:c,__setFunctionName:d,__metadata:f,__awaiter:p,__generator:g,__createBinding:w,__exportStar:y,__values:v,__read:m,__spread:b,__spreadArrays:_,__spreadArray:k,__await:S,__asyncGenerator:E,__asyncDelegator:O,__asyncValues:T,__makeTemplateOb
56ject:j,__importStar:P,__importDefault:R,__classPrivateFieldGet:C,__classPrivateFieldSet:$,__classPrivateFieldIn:x,__addDisposableResource:N,__disposeResources:D,__rewriteRelativeImportExtension:L}}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.