/** * Minified by jsDelivr using Terser v5.39.0. * Original file: /npm/@supabase/supabase-js@2.99.1/dist/umd/supabase.js * * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files */ var supabase=function(e){function t(e,t){var r={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(r[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(s=Object.getOwnPropertySymbols(e);ie?(...t)=>e(...t):(...e)=>fetch(...e))(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return function(e,t,r,s){function i(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||=Promise)((function(r,a){function n(e){try{l(s.next(e))}catch(e){a(e)}}function o(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){e.done?r(e.value):i(e.value).then(n,o)}l((s=s.apply(e,t||[])).next())}))}(this,arguments,void 0,(function*(e,t={}){let r,s;try{let{headers:o,method:l,body:h,signal:c,timeout:u}=t,d={},{region:p}=t;p||=this.region;let f,g=new URL(`${this.url}/${e}`);p&&"any"!==p&&(d["x-region"]=p,g.searchParams.set("forceFunctionRegion",p)),h&&(o&&!Object.prototype.hasOwnProperty.call(o,"Content-Type")||!o)?typeof Blob<"u"&&h instanceof Blob||h instanceof ArrayBuffer?(d["Content-Type"]="application/octet-stream",f=h):"string"==typeof h?(d["Content-Type"]="text/plain",f=h):typeof FormData<"u"&&h instanceof FormData?f=h:(d["Content-Type"]="application/json",f=JSON.stringify(h)):f=!h||"string"==typeof h||typeof Blob<"u"&&h instanceof Blob||h instanceof ArrayBuffer||typeof FormData<"u"&&h instanceof FormData?h:JSON.stringify(h);let m=c;u&&(s=new AbortController,r=setTimeout((()=>s.abort()),u),c?(m=s.signal,c.addEventListener("abort",(()=>s.abort()))):m=s.signal);let y=yield this.fetch(g.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},d),this.headers),o),body:f,signal:m}).catch((e=>{throw new i(e)})),w=y.headers.get("x-relay-error");if(w&&"true"===w)throw new a(y);if(!y.ok)throw new n(y);let b,_=(y.headers.get("Content-Type")??"text/plain").split(";")[0].trim();return b="application/json"===_?yield y.json():"application/octet-stream"===_||"application/pdf"===_?yield y.blob():"text/event-stream"===_?y:"multipart/form-data"===_?yield y.formData():yield y.text(),{data:b,error:null,response:y}}catch(e){return{data:null,error:e,response:e instanceof n||e instanceof a?e.context:void 0}}finally{r&&clearTimeout(r)}}))}},l=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}},h=class{constructor(e){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=e.shouldThrowOnError??!1,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle??!1,this.urlLengthLimit=e.urlLengthLimit??8e3,e.fetch?this.fetch=e.fetch: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){var r=this;void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),"GET"!==this.method&&"HEAD"!==this.method&&this.headers.set("Content-Type","application/json");let s=(0,this.fetch)(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then((async e=>{let t=null,s=null,i=null,a=e.status,n=e.statusText;if(e.ok){if("HEAD"!==r.method){let t=await e.text();""===t||(s="text/csv"===r.headers.get("Accept")||r.headers.get("Accept")&&r.headers.get("Accept")?.includes("application/vnd.pgrst.plan+text")?t:JSON.parse(t))}let o=r.headers.get("Prefer")?.match(/count=(exact|planned|estimated)/),l=e.headers.get("content-range")?.split("/");o&&l&&l.length>1&&(i=parseInt(l[1])),r.isMaybeSingle&&"GET"===r.method&&Array.isArray(s)&&(s.length>1?(t={code:"PGRST116",details:`Results contain ${s.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},s=null,i=null,a=406,n="Not Acceptable"):s=1===s.length?s[0]:null)}else{var o;let i=await e.text();try{t=JSON.parse(i),Array.isArray(t)&&404===e.status&&(s=[],t=null,a=200,n="OK")}catch{404===e.status&&""===i?(a=204,n="No Content"):t={message:i}}if(t&&r.isMaybeSingle&&!(null==t||null==(o=t.details))&&o.includes("0 rows")&&(t=null,a=200,n="OK"),t&&r.shouldThrowOnError)throw new l(t)}return{error:t,data:s,count:i,status:a,statusText:n}}));return this.shouldThrowOnError||(s=s.catch((e=>{let t="",r="",s="",i=e?.cause;if(i){let r=i?.message??"",s=i?.code??"";t=`${e?.name??"FetchError"}: ${e?.message}`,t+=`\n\nCaused by: ${i?.name??"Error"}: ${r}`,s&&(t+=` (${s})`),i?.stack&&(t+=`\n${i.stack}`)}else t=e?.stack??"";let a=this.url.toString().length;return"AbortError"===e?.name||"ABORT_ERR"===e?.code?(s="",r="Request was aborted (timeout or manual cancellation)",a>this.urlLengthLimit&&(r+=`. Note: Your request URL is ${a} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):("HeadersOverflowError"===i?.name||"UND_ERR_HEADERS_OVERFLOW"===i?.code)&&(s="",r="HTTP headers exceeded server limits (typically 16KB)",a>this.urlLengthLimit&&(r+=`. Your request URL is ${a} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${e?.name??"FetchError"}: ${e?.message}`,details:t,hint:r,code:s},data:null,count:null,status:0,statusText:""}}))),s.then(e,t)}returns(){return this}overrideTypes(){return this}},c=class extends h{select(e){let t=!1,r=(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 a=i?`${i}.order`:"order",n=this.url.searchParams.get(a);return this.url.searchParams.set(a,`${n?`${n},`:""}${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`,a=void 0===s?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(a,""+(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:a="text"}={}){let n=[e?"analyze":null,t?"verbose":null,r?"settings":null,s?"buffers":null,i?"wal":null].filter(Boolean).join("|"),o=this.headers.get("Accept")??"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${a}; for="${o}"; options=${n};`),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}};let u=RegExp("[,()]");var d=class extends c{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}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){let r=Array.from(new Set(t)).map((e=>"string"==typeof e&&u.test(e)?`"${e}"`:`${e}`)).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}notIn(e,t){let r=Array.from(new Set(t)).map((e=>"string"==typeof e&&u.test(e)?`"${e}"`:`${e}`)).join(",");return this.url.searchParams.append(e,`not.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 a=void 0===r?"":`(${r})`;return this.url.searchParams.append(e,`${i}fts${a}.${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}},p=class{constructor(e,{headers:t={},schema:r,fetch:s,urlLengthLimit:i=8e3}){this.url=e,this.headers=new Headers(t),this.schema=r,this.fetch=s,this.urlLengthLimit=i}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){let{head:r=!1,count:s}=t??{},i=r?"HEAD":"GET",a=!1,n=(e??"*").split("").map((e=>/\s/.test(e)&&!a?"":('"'===e&&(a=!a),e))).join(""),{url:o,headers:l}=this.cloneRequestState();return o.searchParams.set("select",n),s&&l.append("Prefer",`count=${s}`),new d({method:i,url:o,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(e,{count:t,defaultToNull:r=!0}={}){let{url:s,headers:i}=this.cloneRequestState();if(t&&i.append("Prefer",`count=${t}`),r||i.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}"`));s.searchParams.set("columns",e.join(","))}}return new d({method:"POST",url:s,headers:i,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:s,defaultToNull:i=!0}={}){let{url:a,headers:n}=this.cloneRequestState();if(n.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),void 0!==t&&a.searchParams.set("on_conflict",t),s&&n.append("Prefer",`count=${s}`),i||n.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}"`));a.searchParams.set("columns",e.join(","))}}return new d({method:"POST",url:a,headers:n,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit})}update(e,{count:t}={}){let{url:r,headers:s}=this.cloneRequestState();return t&&s.append("Prefer",`count=${t}`),new d({method:"PATCH",url:r,headers:s,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:e}={}){let{url:t,headers:r}=this.cloneRequestState();return e&&r.append("Prefer",`count=${e}`),new d({method:"DELETE",url:t,headers:r,schema:this.schema,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit})}};function f(e){return f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},f(e)}function g(e){var t=function(e,t){if("object"!=f(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=f(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==f(t)?t:t+""}function m(e,t,r){return(t=g(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function y(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,s)}return r}function w(e){for(var t=1;t0?(e,t)=>{let r=new AbortController,s=setTimeout((()=>r.abort()),i),a=t?.signal;if(a){if(a.aborted)return clearTimeout(s),n(e,t);let i=()=>{clearTimeout(s),r.abort()};return a.addEventListener("abort",i,{once:!0}),n(e,w(w({},t),{},{signal:r.signal})).finally((()=>{clearTimeout(s),a.removeEventListener("abort",i)}))}return n(e,w(w({},t),{},{signal:r.signal})).finally((()=>clearTimeout(s)))}:n}from(e){if(!e||"string"!=typeof e||""===e.trim())throw Error("Invalid relation name: relation must be a non-empty string.");return new p(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(t){return new e(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,t={},{head:r=!1,get:s=!1,count:i}={}){let a,n,o=new URL(`${this.url}/rpc/${e}`),l=e=>"object"==typeof e&&!!e&&(!Array.isArray(e)||e.some(l)),h=r&&Object.values(t).some(l);h?(a="POST",n=t):r||s?(a=r?"HEAD":"GET",Object.entries(t).filter((([e,t])=>void 0!==t)).map((([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}`])).forEach((([e,t])=>{o.searchParams.append(e,t)}))):(a="POST",n=t);let c=new Headers(this.headers);return h?c.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&c.set("Prefer",`count=${i}`),new d({method:a,url:o,headers:c,schema:this.schemaName,body:n,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit})}},_=class{constructor(){}static detectEnvironment(){if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&void 0!==globalThis.WebSocket)return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&void 0!==global.WebSocket)return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&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(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&navigator.userAgent?.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."};let e=globalThis.process;if(e){let t=e.versions;if(t&&t.node){let e=t.node,r=parseInt(e.replace(/^v/,"").split(".")[0]);return r>=22?void 0===globalThis.WebSocket?{type:"unsupported",error:`Node.js ${r} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${r} detected without native WebSocket support.`,workaround:'For Node.js < 22, install "ws" package and provide it via the transport option:\nimport ws from "ws"\nnew RealtimeClient(url, { transport: ws })'}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){let e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=`\n\nSuggested solution: ${e.workaround}`),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{return!1}}};let v="2.0.0",k=v,S=1e4;var E,T,O,R,A;!function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"}(E||={}),function(e){e.closed="closed",e.errored="errored",e.joined="joined",e.joining="joining",e.leaving="leaving"}(T||={}),function(e){e.close="phx_close",e.error="phx_error",e.join="phx_join",e.reply="phx_reply",e.leave="phx_leave",e.access_token="access_token"}(O||={}),function(e){e.websocket="websocket"}(R||={}),function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"}(A||={});var j,P=class{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,t){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&"string"==typeof e.payload.event)return t(this._binaryEncodeUserBroadcastPush(e));let r=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(r))}_binaryEncodeUserBroadcastPush(e){return this._isArrayBuffer(e.payload?.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){let t=e.payload?.payload??new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,t)}_encodeJsonUserBroadcastPush(e){let t=e.payload?.payload??{},r=(new TextEncoder).encode(JSON.stringify(t)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,r)}_encodeUserBroadcastPush(e,t,r){let s=e.topic,i=e.ref??"",a=e.join_ref??"",n=e.payload.event,o=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},l=0===Object.keys(o).length?"":JSON.stringify(o);if(a.length>255)throw Error(`joinRef length ${a.length} exceeds maximum of 255`);if(i.length>255)throw Error(`ref length ${i.length} exceeds maximum of 255`);if(s.length>255)throw Error(`topic length ${s.length} exceeds maximum of 255`);if(n.length>255)throw Error(`userEvent length ${n.length} exceeds maximum of 255`);if(l.length>255)throw Error(`metadata length ${l.length} exceeds maximum of 255`);let h=this.USER_BROADCAST_PUSH_META_LENGTH+a.length+i.length+s.length+n.length+l.length,c=new ArrayBuffer(this.HEADER_LENGTH+h),u=new DataView(c),d=0;u.setUint8(d++,this.KINDS.userBroadcastPush),u.setUint8(d++,a.length),u.setUint8(d++,i.length),u.setUint8(d++,s.length),u.setUint8(d++,n.length),u.setUint8(d++,l.length),u.setUint8(d++,t),Array.from(a,(e=>u.setUint8(d++,e.charCodeAt(0)))),Array.from(i,(e=>u.setUint8(d++,e.charCodeAt(0)))),Array.from(s,(e=>u.setUint8(d++,e.charCodeAt(0)))),Array.from(n,(e=>u.setUint8(d++,e.charCodeAt(0)))),Array.from(l,(e=>u.setUint8(d++,e.charCodeAt(0))));var p=new Uint8Array(c.byteLength+r.byteLength);return p.set(new Uint8Array(c),0),p.set(new Uint8Array(r),c.byteLength),p.buffer}decode(e,t){if(this._isArrayBuffer(e))return t(this._binaryDecode(e));if("string"==typeof e){let[r,s,i,a,n]=JSON.parse(e);return t({join_ref:r,ref:s,topic:i,event:a,payload:n})}return t({})}_binaryDecode(e){let t=new DataView(e),r=t.getUint8(0),s=new TextDecoder;if(r===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,t,s)}_decodeUserBroadcast(e,t,r){let s=t.getUint8(1),i=t.getUint8(2),a=t.getUint8(3),n=t.getUint8(4),o=this.HEADER_LENGTH+4,l=r.decode(e.slice(o,o+s));o+=s;let h=r.decode(e.slice(o,o+i));o+=i;let c=r.decode(e.slice(o,o+a));o+=a;let u=e.slice(o,e.byteLength),d=n===this.JSON_ENCODING?JSON.parse(r.decode(u)):u,p={type:this.BROADCAST_EVENT,event:h,payload:d};return a>0&&(p.meta=JSON.parse(c)),{join_ref:null,ref:null,topic:l,event:this.BROADCAST_EVENT,payload:p}}_isArrayBuffer(e){return e instanceof ArrayBuffer||"ArrayBuffer"===e?.constructor?.name}_pick(e,t){return e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter((([e])=>t.includes(e)))):{}}},$=class{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+=1,this.callback()}),this.timerCalc(this.tries+1))}};!function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"}(j||={});let I=(e,t,r={})=>{let s=r.skipTypes??[];return t?Object.keys(t).reduce(((r,i)=>(r[i]=C(i,e,t,s),r)),{}):{}},C=(e,t,r,s)=>{let i=t.find((t=>t.name===e))?.type,a=r[e];return i&&!s.includes(i)?x(i,a):N(a)},x=(e,t)=>{if("_"===e.charAt(0))return B(t,e.slice(1,e.length));switch(e){case j.bool:return U(t);case j.float4:case j.float8:case j.int2:case j.int4:case j.int8:case j.numeric:case j.oid:return L(t);case j.json:case j.jsonb:return D(t);case j.timestamp:return q(t);case j.abstime:case j.date:case j.daterange:case j.int4range:case j.int8range:case j.money:case j.reltime:case j.text:case j.time:case j.timestamptz:case j.timetz:case j.tsrange:case j.tstzrange:default:return N(t)}},N=e=>e,U=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},L=e=>{if("string"==typeof e){let t=parseFloat(e);if(!Number.isNaN(t))return t}return e},D=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch{return e}return e},B=(e,t)=>{if("string"!=typeof e)return e;let r=e.length-1,s=e[r];if("{"===e[0]&&"}"===s){let s,i=e.slice(1,r);try{s=JSON.parse("["+i+"]")}catch{s=i?i.split(","):[]}return s.map((e=>x(t,e)))}return e},q=e=>"string"==typeof e?e.replace(" ","T"):e,K=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+="/api/broadcast",t.href};var W,M=class{constructor(e,t,r={},s=S){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){return this._hasReceived(e)&&t(this.receivedResp?.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)})),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}};!function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"}(W||={});var F,G,H,V=class e{constructor(t,r){this.channel=t,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let s=r?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},(t=>{let{onJoin:r,onLeave:s,onSync:i}=this.caller;this.joinRef=this.channel._joinRef(),this.state=e.syncState(this.state,t,r,s),this.pendingDiffs.forEach((t=>{this.state=e.syncDiff(this.state,t,r,s)})),this.pendingDiffs=[],i()})),this.channel._on(s.diff,{},(t=>{let{onJoin:r,onLeave:s,onSync:i}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(t):(this.state=e.syncDiff(this.state,t,r,s),i())})),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),a=this.transformState(t),n={},o={};return this.map(i,((e,t)=>{a[e]||(o[e]=t)})),this.map(a,((e,t)=>{let r=i[e];if(r){let s=t.map((e=>e.presence_ref)),i=r.map((e=>e.presence_ref)),a=t.filter((e=>i.indexOf(e.presence_ref)<0)),l=r.filter((e=>s.indexOf(e.presence_ref)<0));a.length>0&&(n[e]=a),l.length>0&&(o[e]=l)}else n[e]=t})),this.syncDiff(i,{joins:n,leaves:o},r,s)}static syncDiff(e,t,r,s){let{joins:i,leaves:a}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||=()=>{},s||=()=>{},this.map(i,((t,s)=>{let i=e[t]??[];if(e[t]=this.cloneDeep(s),i.length>0){let r=e[t].map((e=>e.presence_ref)),s=i.filter((e=>r.indexOf(e.presence_ref)<0));e[t].unshift(...s)}r(t,i,s)})),this.map(a,((t,r)=>{let i=e[t];if(!i)return;let a=r.map((e=>e.presence_ref));i=i.filter((e=>a.indexOf(e.presence_ref)<0)),e[t]=i,s(t,i,r),0===i.length&&delete e[t]})),e}static map(e,t){return Object.getOwnPropertyNames(e).map((r=>t(r,e[r])))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce(((t,r)=>{let s=e[r];return t[r]="metas"in s?s.metas.map((e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))):s,t}),{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};!function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"}(F||={}),function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"}(G||={}),function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"}(H||={});let J=T;var z=class e{constructor(e,t={config:{}},r){if(this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=T.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 M(this,O.join,this.params,this.timeout),this.rejoinTimer=new $((()=>this._rejoinUntilConnected()),this.socket.reconnectAfterMs),this.joinPush.receive("ok",(()=>{this.state=T.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach((e=>e.send())),this.pushBuffer=[]})),this._onClose((()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=T.closed,this.socket._remove(this)})),this._onError((e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=T.errored,this.rejoinTimer.scheduleTimeout())})),this.joinPush.receive("timeout",(()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=T.errored,this.rejoinTimer.scheduleTimeout())})),this.joinPush.receive("error",(e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=T.errored,this.rejoinTimer.scheduleTimeout())})),this._on(O.reply,{},((e,t)=>{this._trigger(this._replyEventName(t),e)})),this.presence=new V(this),this.broadcastEndpointURL=K(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&this.params.config?.broadcast?.replay)throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(t,r=this.timeout){if(this.socket.isConnected()||this.socket.connect(),this.state==T.closed){let{config:{broadcast:s,presence:i,private:a}}=this.params,n=this.bindings.postgres_changes?.map((e=>e.filter))??[],o=!!this.bindings[G.PRESENCE]&&this.bindings[G.PRESENCE].length>0||!0===this.params.config.presence?.enabled,l={},h={broadcast:s,presence:Object.assign(Object.assign({},i),{enabled:o}),postgres_changes:n,private:a};this.socket.accessTokenValue&&(l.access_token=this.socket.accessTokenValue),this._onError((e=>t?.(H.CHANNEL_ERROR,e))),this._onClose((()=>t?.(H.CLOSED))),this.updateJoinPayload(Object.assign({config:h},l)),this.joinedOnce=!0,this._rejoin(r),this.joinPush.receive("ok",(async({postgres_changes:r})=>{if(this.socket._isManualToken()||this.socket.setAuth(),void 0!==r){let s=this.bindings.postgres_changes,i=s?.length??0,a=[];for(let n=0;n{this.state=T.errored,t?.(H.CHANNEL_ERROR,Error(JSON.stringify(Object.values(e).join(", ")||"error")))})).receive("timeout",(()=>{t?.(H.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===T.joined&&e===G.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then((async()=>await this.subscribe()))),this._on(e,t,r)}async httpSend(e,t,r={}){if(null==t)return Promise.reject("Payload is required for httpSend()");let s={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(s.Authorization=`Bearer ${this.socket.accessTokenValue}`);let i={method:"POST",headers:s,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,i,r.timeout??this.timeout);if(202===a.status)return{success:!0};let n=a.statusText;try{let e=await a.json();n=e.error||e.message||n}catch{}return Promise.reject(Error(n))}async send(e,t={}){if(this._canPush()||"broadcast"!==e.type)return new Promise((r=>{let s=this._push(e.type,e,t.timeout||this.timeout);"broadcast"===e.type&&!this.params?.config?.broadcast?.ack&&r("ok"),s.receive("ok",(()=>r("ok"))),s.receive("error",(()=>r("error"))),s.receive("timeout",(()=>r("timed out")))}));{console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");let{event:r,payload:s}=e,i={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);let a={method:"POST",headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:r,payload:s,private:this.private}]})};try{let e=await this._fetchWithTimeout(this.broadcastEndpointURL,a,t.timeout??this.timeout);return await(e.body?.cancel()),e.ok?"ok":"error"}catch(e){return"AbortError"===e.name?"timed out":"error"}}}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=T.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(O.close,"leave",this._joinRef())};this.joinPush.destroy();let r=null;return new Promise((s=>{r=new M(this,O.leave,{},e),r.receive("ok",(()=>{t(),s("ok")})).receive("timeout",(()=>{t(),s("timed out")})).receive("error",(()=>{s("error")})),r.send(),this._canPush()||r.trigger("ok",{})})).finally((()=>{r?.destroy()}))}teardown(){this.pushBuffer.forEach((e=>e.destroy())),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=T.closed,this.bindings={}}async _fetchWithTimeout(e,t,r){let s=new AbortController,i=setTimeout((()=>s.abort()),r),a=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:s.signal}));return clearTimeout(i),a}_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 M(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 a=e.toLocaleLowerCase(),{close:n,error:o,leave:l,join:h}=O;if(r&&[n,o,l,h].indexOf(a)>=0&&r!==this._joinRef())return;let c=this._onMessage(a,t,r);if(t&&!c)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(a)?null==(s=this.bindings.postgres_changes)||s.filter((e=>"*"===e.filter?.event||(e.filter?.event)?.toLocaleLowerCase()===a)).map((e=>e.callback(c,r))):null==(i=this.bindings[a])||i.filter((e=>{if(["broadcast","presence","postgres_changes"].includes(a)){if("id"in e){let r=e.id,s=e.filter?.event;return r&&t.ids?.includes(r)&&("*"===s||s?.toLocaleLowerCase()===t.data?.type.toLocaleLowerCase())}{let r=(e?.filter?.event)?.toLocaleLowerCase();return"*"===r||r===(t?.event)?.toLocaleLowerCase()}}return e.type.toLocaleLowerCase()===a})).map((e=>{if("object"==typeof c&&"ids"in c){let e=c.data,{schema:t,table:r,commit_timestamp:s,type:i,errors:a}=e,n={schema:t,table:r,commit_timestamp:s,eventType:i,new:{},old:{},errors:a};c=Object.assign(Object.assign({},n),this._getPayloadRecords(e))}e.callback(c,r)}))}_isClosed(){return this.state===T.closed}_isJoined(){return this.state===T.joined}_isJoining(){return this.state===T.joining}_isLeaving(){return this.state===T.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(t,r){let s=t.toLocaleLowerCase();return this.bindings[s]&&(this.bindings[s]=this.bindings[s].filter((t=>!(t.type?.toLocaleLowerCase()===s&&e.isEqual(t.filter,r))))),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}static isFilterValueEqual(e,t){return(e??void 0)===(t??void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(O.close,{},e)}_onError(e){this._on(O.error,{},(t=>e(t)))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=T.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return("INSERT"===e.type||"UPDATE"===e.type)&&(t.new=I(e.columns,e.record)),("UPDATE"===e.type||"DELETE"===e.type)&&(t.old=I(e.columns,e.old_record)),t}};let Y=()=>{},X=25e3,Q=10,Z=100,ee=[1e3,2e3,5e3,1e4];var te=class{constructor(e,t){if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=S,this.transport=null,this.heartbeatIntervalMs=X,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Y,this.ref=0,this.reconnectTimer=null,this.vsn=k,this.logger=Y,this.conn=null,this.sendBuffer=[],this.serializer=new P,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),!t?.params?.apikey)throw Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${R.websocket}`,this.httpEndpoint=K(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||null!==this.conn&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=_.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");let t=e.message;throw t.includes("Node.js")?Error(`${t}\n\nTo use Realtime in Node.js, you need to provide a WebSocket implementation:\n\nOption 1: Use Node.js 22+ which has native WebSocket support\nOption 2: Install and provide the "ws" package:\n\n npm install ws\n\n import ws from "ws"\n const client = new RealtimeClient(url, {\n ...options,\n transport: ws\n })`):Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){let r=setTimeout((()=>{this._setConnectionState("disconnected")}),100);this.conn.onclose=()=>{clearTimeout(r),this._setConnectionState("disconnected")},"function"==typeof this.conn.close&&(e?this.conn.close(e,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 E.connecting:return A.Connecting;case E.open:return A.Open;case E.closing:return A.Closing;default:return A.Closed}}isConnected(){return this.connectionState()===A.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 z(`realtime:${e}`,t,this);return this.channels.push(r),r}}push(e){let{topic:t,event:r,payload:s,ref:i}=e,a=()=>{this.encode(e,(e=>{var t;null==(t=this.conn)||t.send(e)}))};this.log("push",`${t} ${r} (${i})`,s),this.isConnected()?a():this.sendBuffer.push(a)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=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)}return this._wasManualDisconnect=!1,null==(e=this.conn)||e.close(1e3,"heartbeat timeout"),void setTimeout((()=>{var e;this.isConnected()||null==(e=this.reconnectTimer)||e.scheduleTimeout()}),Z)}this._heartbeatSentAt=Date.now(),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")}else try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach((e=>e())),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find((t=>t.topic===e&&(t._isJoined()||t._isJoining())));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter((t=>t.topic!==e.topic))}_onConnMessage(e){this.decode(e.data,(e=>{if("phoenix"===e.topic&&"phx_reply"===e.event&&e.ref&&e.ref===this.pendingHeartbeatRef){let t=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback("ok"===e.payload.status?"ok":"error",t)}catch(e){this.log("error","error in heartbeat callback",e)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}let{topic:t,event:r,payload:s,ref:i}=e,a=i?`(${i})`:"",n=s.status||"";this.log("receive",`${n} ${t} ${r} ${a}`.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)||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),this.conn.readyState===E.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===E.open||this.conn.readyState===E.connecting)try{this.conn.close()}catch(e){this.log("error","Error closing connection",e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach((e=>e.teardown()))}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then((()=>{this.accessTokenValue&&(this.channels.forEach((e=>{e.updateJoinPayload({access_token:this.accessTokenValue})})),this.sendBuffer=[],this.channels.forEach((e=>{e._isJoining()&&(e.joinPush.sent=!1,e.joinPush.send())}))),this.flushSendBuffer()})).catch((e=>{this.log("error","error waiting for auth on connect",e),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._terminateWorker()},this.workerRef.onmessage=e=>{"keepAlive"===e.data.event&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&=(this.log("worker","terminating worker"),void this.workerRef.terminate())}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||null==(t=this.reconnectTimer)||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e);try{this.heartbeatCallback("error")}catch(e){this.log("error","error in heartbeat callback",e)}}_triggerChanError(){this.channels.forEach((e=>e._trigger(O.error)))}_appendParams(e,t){return 0===Object.keys(t).length?e:`${e}${e.match(/\?/)?"&":"?"}${new URLSearchParams(t)}`}_workerObjectUrl(e){let t;if(e)t=e;else{let e=new Blob(['\n addEventListener("message", (e) => {\n if (e.data.event === "start") {\n setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);\n }\n });'],{type:"application/javascript"});t=URL.createObjectURL(e)}return t}_setConnectionState(e,t=!1){this._connectionState=e,"connecting"===e?this._wasManualDisconnect=!1:"disconnecting"===e&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t,r=!1;if(e)t=e,r=!0;else if(this.accessToken)try{t=await this.accessToken()}catch(e){this.log("error","Error fetching access token from callback",e),t=this.accessTokenValue}else t=this.accessTokenValue;r?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach((e=>{let r={access_token:t,version:"realtime-js/2.99.1"};t&&e.updateJoinPayload(r),e.joinedOnce&&e._isJoined()&&e._push(O.access_token,{access_token:t})})))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||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 $((async()=>{setTimeout((async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}),Q)}),this.reconnectAfterMs)}_initializeOptions(e){switch(this.transport=e?.transport??null,this.timeout=e?.timeout??S,this.heartbeatIntervalMs=e?.heartbeatIntervalMs??X,this.worker=e?.worker??!1,this.accessToken=e?.accessToken??null,this.heartbeatCallback=e?.heartbeatCallback??Y,this.vsn=e?.vsn??k,e?.params&&(this.params=e.params),e?.logger&&(this.logger=e.logger),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=e?.reconnectAfterMs??(e=>ee[e-1]||1e4),this.vsn){case"1.0.0":this.encode=e?.encode??((e,t)=>t(JSON.stringify(e))),this.decode=e?.decode??((e,t)=>t(JSON.parse(e)));break;case v:this.encode=e?.encode??this.serializer.encode.bind(this.serializer),this.decode=e?.decode??this.serializer.decode.bind(this.serializer);break;default:throw Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if(typeof window<"u"&&!window.Worker)throw Error("Web Worker is not supported");this.workerUrl=e?.workerUrl}}},re=class extends Error{constructor(e,t){super(e),this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown="CommitStateUnknownException"===t.icebergType||[500,502,504].includes(t.status)&&!0===t.icebergType?.includes("CommitState")}isNotFound(){return 404===this.status}isConflict(){return 409===this.status}isAuthenticationTimeout(){return 419===this.status}};function se(e){let t=e.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:i,body:a,headers:n}){let o=function(e,t,r){let s=new URL(t,e);if(r)for(let[e,t]of Object.entries(r))void 0!==t&&s.searchParams.set(e,t);return s.toString()}(e.baseUrl,s,i),l=await async function(e){return e&&"none"!==e.type?"bearer"===e.type?{Authorization:`Bearer ${e.token}`}:"header"===e.type?{[e.name]:e.value}:"custom"===e.type?await e.getHeaders():{}:{}}(e.auth),h=await t(o,{method:r,headers:{...a?{"Content-Type":"application/json"}:{},...l,...n},body:a?JSON.stringify(a):void 0}),c=await h.text(),u=(h.headers.get("content-type")||"").includes("application/json"),d=u&&c?JSON.parse(c):c;if(!h.ok){let e=u?d:void 0,t=e?.error;throw new re(t?.message??`Request failed with status ${h.status}`,{status:h.status,icebergType:t?.type,icebergCode:t?.code,details:e})}return{status:h.status,headers:h.headers,data:d}}}}function ie(e){return e.join("")}var ae=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){let t=e?{parent:ie(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map((e=>({namespace:e})))}async createNamespace(e,t){let r={namespace:e.namespace,properties:t?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${ie(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${ie(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${ie(e.namespace)}`}),!0}catch(e){if(e instanceof re&&404===e.status)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof re&&409===e.status)return;throw e}}};function ne(e){return e.join("")}var oe=class{constructor(e,t="",r){this.client=e,this.prefix=t,this.accessDelegation=r}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${ne(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){let r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${ne(e.namespace)}/tables`,body:t,headers:r})).data.metadata}async updateTable(e,t){let r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${ne(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(e,t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${ne(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String(t?.purge??!1)}})}async loadTable(e){let t={};return this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${ne(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){let t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${ne(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(e){if(e instanceof re&&404===e.status)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(r){if(r instanceof re&&409===r.status)return await this.loadTable({namespace:e.namespace,name:t.name});throw r}}},le=class{constructor(e){let t="v1";e.catalogName&&(t+=`/${e.catalogName}`),this.client=se({baseUrl:e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(","),this.namespaceOps=new ae(this.client,t),this.tableOps=new oe(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}},he=class extends Error{constructor(e,t="storage",r,s){super(e),this.__isStorageError=!0,this.namespace=t,this.name="vectors"===t?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=s}};function ce(e){return"object"==typeof e&&!!e&&"__isStorageError"in e}var ue=class extends he{constructor(e,t,r,s="storage"){super(e,s,t,r),this.name="vectors"===s?"StorageVectorsApiError":"StorageApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},de=class extends he{constructor(e,t,r="storage"){super(e,r),this.name="vectors"===r?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=t}};let pe=e=>{if(Array.isArray(e))return e.map((e=>pe(e)));if("function"==typeof e||e!==Object(e))return e;let t={};return Object.entries(e).forEach((([e,r])=>{let s=e.replace(/([-_][a-z])/gi,(e=>e.toUpperCase().replace(/[-_]/g,"")));t[s]=pe(r)})),t};function fe(e){return fe="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},fe(e)}function ge(e){var t=function(e,t){if("object"!=fe(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=fe(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==fe(t)?t:t+""}function me(e,t,r){return(t=ge(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function ye(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,s)}return r}function we(e){for(var t=1;te.msg||e.message||e.error_description||("string"==typeof e.error?e.error:e.error?.message)||JSON.stringify(e),_e=(e,t,r,s)=>{let i={method:e,headers:t?.headers||{}};return"GET"!==e&&"HEAD"!==e&&s?((e=>{if("object"!=typeof e||!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)})(s)?(i.headers=we({"Content-Type":"application/json"},t?.headers),i.body=JSON.stringify(s)):i.body=s,t?.duplex&&(i.duplex=t.duplex),we(we({},i),r)):we(we({},i),r)};async function ve(e,t,r,s,i,a,n){return new Promise(((o,l)=>{e(r,_e(t,s,i,a)).then((e=>{if(!e.ok)throw e;if(s?.noResolveJson)return e;if("vectors"===n){let t=e.headers.get("content-type");if("0"===e.headers.get("content-length")||204===e.status||!t||!t.includes("application/json"))return{}}return e.json()})).then((e=>o(e))).catch((e=>(async(e,t,r,s)=>{if(e&&"object"==typeof e&&"status"in e&&"ok"in e&&"number"==typeof e.status){let r=e,i=r.status||500;if("function"==typeof r.json)r.json().then((e=>{let r=e?.statusCode||e?.code||i+"";t(new ue(be(e),i,r,s))})).catch((()=>{if("vectors"===s){let e=i+"";t(new ue(r.statusText||`HTTP ${i} error`,i,e,s))}else{let e=i+"";t(new ue(r.statusText||`HTTP ${i} error`,i,e,s))}}));else{let e=i+"";t(new ue(r.statusText||`HTTP ${i} error`,i,e,s))}}else t(new de(be(e),e,s))})(e,l,0,n)))}))}function ke(e="storage"){return{get:async(t,r,s,i)=>ve(t,"GET",r,s,i,void 0,e),post:async(t,r,s,i,a)=>ve(t,"POST",r,i,a,s,e),put:async(t,r,s,i,a)=>ve(t,"PUT",r,i,a,s,e),head:async(t,r,s,i)=>ve(t,"HEAD",r,we(we({},s),{},{noResolveJson:!0}),i,void 0,e),remove:async(t,r,s,i,a)=>ve(t,"DELETE",r,i,a,s,e)}}let{get:Se,post:Ee,put:Te,head:Oe,remove:Re}=ke("storage"),Ae=ke("vectors");var je=class{constructor(e,t={},r,s="storage"){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.fetch=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(r),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=we(we({},this.headers),{},{[e]:t}),this}async handleOperation(e){try{return{data:await e(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(ce(e))return{data:null,error:e};throw e}}},Pe=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}async execute(){try{return{data:(await this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(ce(e))return{data:null,error:e};throw e}}};let $e;$e=Symbol.toStringTag;var Ie=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[$e]="BlobDownloadBuilder",this.promise=null}asStream(){return new Pe(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.execute(),this.promise}async execute(){try{return{data:await(await this.downloadFn()).blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(ce(e))return{data:null,error:e};throw e}}};let Ce={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},xe={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var Ne=class extends je{constructor(e,t={},r,s){super(e,t,s,"storage"),this.bucketId=r}async uploadOrUpdate(e,t,r,s){var i=this;return i.handleOperation((async()=>{let a,n=we(we({},xe),s),o=we(we({},i.headers),"POST"===e&&{"x-upsert":String(n.upsert)}),l=n.metadata;typeof Blob<"u"&&r instanceof Blob?(a=new FormData,a.append("cacheControl",n.cacheControl),l&&a.append("metadata",i.encodeMetadata(l)),a.append("",r)):typeof FormData<"u"&&r instanceof FormData?(a=r,a.has("cacheControl")||a.append("cacheControl",n.cacheControl),l&&!a.has("metadata")&&a.append("metadata",i.encodeMetadata(l))):(a=r,o["cache-control"]=`max-age=${n.cacheControl}`,o["content-type"]=n.contentType,l&&(o["x-metadata"]=i.toBase64(i.encodeMetadata(l))),(typeof ReadableStream<"u"&&a instanceof ReadableStream||a&&"object"==typeof a&&"pipe"in a&&"function"==typeof a.pipe)&&!n.duplex&&(n.duplex="half")),s?.headers&&(o=we(we({},o),s.headers));let h=i._removeEmptyFolders(t),c=i._getFinalPath(h),u=await("PUT"==e?Te:Ee)(i.fetch,`${i.url}/object/${c}`,a,we({headers:o},n?.duplex?{duplex:n.duplex}:{}));return{path:h,id:u.Id,fullPath:u.Key}}))}async upload(e,t,r){return this.uploadOrUpdate("POST",e,t,r)}async uploadToSignedUrl(e,t,r,s){var i=this;let a=i._removeEmptyFolders(e),n=i._getFinalPath(a),o=new URL(i.url+`/object/upload/sign/${n}`);return o.searchParams.set("token",t),i.handleOperation((async()=>{let e,t=we({upsert:xe.upsert},s),n=we(we({},i.headers),{"x-upsert":String(t.upsert)});return typeof Blob<"u"&&r instanceof Blob?(e=new FormData,e.append("cacheControl",t.cacheControl),e.append("",r)):typeof FormData<"u"&&r instanceof FormData?(e=r,e.append("cacheControl",t.cacheControl)):(e=r,n["cache-control"]=`max-age=${t.cacheControl}`,n["content-type"]=t.contentType),{path:a,fullPath:(await Te(i.fetch,o.toString(),e,{headers:n})).Key}}))}async createSignedUploadUrl(e,t){var r=this;return r.handleOperation((async()=>{let s=r._getFinalPath(e),i=we({},r.headers);t?.upsert&&(i["x-upsert"]="true");let a=await Ee(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:i}),n=new URL(r.url+a.url),o=n.searchParams.get("token");if(!o)throw new he("No token returned by API");return{signedUrl:n.toString(),path:e,token:o}}))}async update(e,t,r){return this.uploadOrUpdate("PUT",e,t,r)}async move(e,t,r){var s=this;return s.handleOperation((async()=>await Ee(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:s.headers})))}async copy(e,t,r){var s=this;return s.handleOperation((async()=>({path:(await Ee(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:s.headers})).Key})))}async createSignedUrl(e,t,r){var s=this;return s.handleOperation((async()=>{let i=s._getFinalPath(e),a=await Ee(s.fetch,`${s.url}/object/sign/${i}`,we({expiresIn:t},r?.transform?{transform:r.transform}:{}),{headers:s.headers}),n=r?.download?`&download=${!0===r.download?"":r.download}`:"",o=r?.transform&&a.signedURL.includes("/object/sign/")?a.signedURL.replace("/object/sign/","/render/image/sign/"):a.signedURL;return{signedUrl:encodeURI(`${s.url}${o}${n}`)}}))}async createSignedUrls(e,t,r){var s=this;return s.handleOperation((async()=>{let i=await Ee(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:t,paths:e},{headers:s.headers}),a=r?.download?`&download=${!0===r.download?"":r.download}`:"";return i.map((e=>we(we({},e),{},{signedUrl:e.signedURL?encodeURI(`${s.url}${e.signedURL}${a}`):null})))}))}download(e,t,r){let s=void 0===t?.transform?"object":"render/image/authenticated",i=this.transformOptsToQueryString(t?.transform||{}),a=i?`?${i}`:"",n=this._getFinalPath(e);return new Ie((()=>Se(this.fetch,`${this.url}/${s}/${n}${a}`,{headers:this.headers,noResolveJson:!0},r)),this.shouldThrowOnError)}async info(e){var t=this;let r=t._getFinalPath(e);return t.handleOperation((async()=>pe(await Se(t.fetch,`${t.url}/object/info/${r}`,{headers:t.headers}))))}async exists(e){var t=this;let r=t._getFinalPath(e);try{return await Oe(t.fetch,`${t.url}/object/${r}`,{headers:t.headers}),{data:!0,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ce(e)){let t=e instanceof ue?e.status:e instanceof de?e.originalError?.status:void 0;if(void 0!==t&&[400,404].includes(t))return{data:!1,error:e}}throw e}}getPublicUrl(e,t){let r=this._getFinalPath(e),s=[],i=t?.download?`download=${!0===t.download?"":t.download}`:"";""!==i&&s.push(i);let a=void 0===t?.transform?"object":"render/image",n=this.transformOptsToQueryString(t?.transform||{});""!==n&&s.push(n);let o=s.join("&");return""!==o&&(o=`?${o}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${o}`)}}}async remove(e){var t=this;return t.handleOperation((async()=>await Re(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers})))}async list(e,t,r){var s=this;return s.handleOperation((async()=>{let i=we(we(we({},Ce),t),{},{prefix:e||""});return await Ee(s.fetch,`${s.url}/object/list/${s.bucketId}`,i,{headers:s.headers},r)}))}async listV2(e,t){var r=this;return r.handleOperation((async()=>{let s=we({},e);return await Ee(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,s,{headers:r.headers},t)}))}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){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 Ue={"X-Client-Info":"storage-js/2.99.1"};var Le=class extends je{constructor(e,t={},r,s){let i=new URL(e);s?.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase.")),super(i.href.replace(/\/$/,""),we(we({},Ue),t),r,"storage")}async listBuckets(e){var t=this;return t.handleOperation((async()=>{let r=t.listBucketOptionsToQueryString(e);return await Se(t.fetch,`${t.url}/bucket${r}`,{headers:t.headers})}))}async getBucket(e){var t=this;return t.handleOperation((async()=>await Se(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers})))}async createBucket(e,t={public:!1}){var r=this;return r.handleOperation((async()=>await Ee(r.fetch,`${r.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers})))}async updateBucket(e,t){var r=this;return r.handleOperation((async()=>await Te(r.fetch,`${r.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers})))}async emptyBucket(e){var t=this;return t.handleOperation((async()=>await Ee(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers})))}async deleteBucket(e){var t=this;return t.handleOperation((async()=>await Re(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers})))}listBucketOptionsToQueryString(e){let t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}},De=class extends je{constructor(e,t={},r){super(e.replace(/\/$/,""),we(we({},Ue),t),r,"storage")}async createBucket(e){var t=this;return t.handleOperation((async()=>await Ee(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers})))}async listBuckets(e){var t=this;return t.handleOperation((async()=>{let r=new URLSearchParams;void 0!==e?.limit&&r.set("limit",e.limit.toString()),void 0!==e?.offset&&r.set("offset",e.offset.toString()),e?.sortColumn&&r.set("sortColumn",e.sortColumn),e?.sortOrder&&r.set("sortOrder",e.sortOrder),e?.search&&r.set("search",e.search);let s=r.toString(),i=s?`${t.url}/bucket?${s}`:`${t.url}/bucket`;return await Se(t.fetch,i,{headers:t.headers})}))}async deleteBucket(e){var t=this;return t.handleOperation((async()=>await Re(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers})))}from(e){var t=this;if(!(e=>!(!e||"string"!=typeof e||0===e.length||e.length>100||e.trim()!==e||e.includes("/")||e.includes("\\"))&&/^[\w!.\*'() &$@=;:+,?-]+$/.test(e))(e))throw new he("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");let r=new le({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:async()=>t.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(e,t){let r=e[t];return"function"==typeof r?async(...t)=>{try{return{data:await r.apply(e,t),error:null}}catch(e){if(s)throw e;return{data:null,error:e}}}:r}})}},Be=class extends je{constructor(e,t={},r){super(e.replace(/\/$/,""),we(we({},Ue),{},{"Content-Type":"application/json"},t),r,"vectors")}async createIndex(e){var t=this;return t.handleOperation((async()=>await Ae.post(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{}))}async getIndex(e,t){var r=this;return r.handleOperation((async()=>await Ae.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers})))}async listIndexes(e){var t=this;return t.handleOperation((async()=>await Ae.post(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers})))}async deleteIndex(e,t){var r=this;return r.handleOperation((async()=>await Ae.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers})||{}))}},qe=class extends je{constructor(e,t={},r){super(e.replace(/\/$/,""),we(we({},Ue),{},{"Content-Type":"application/json"},t),r,"vectors")}async putVectors(e){var t=this;if(e.vectors.length<1||e.vectors.length>500)throw Error("Vector batch size must be between 1 and 500 items");return t.handleOperation((async()=>await Ae.post(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{}))}async getVectors(e){var t=this;return t.handleOperation((async()=>await Ae.post(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers})))}async listVectors(e){var t=this;if(void 0!==e.segmentCount){if(e.segmentCount<1||e.segmentCount>16)throw Error("segmentCount must be between 1 and 16");if(void 0!==e.segmentIndex&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw Error("segmentIndex must be between 0 and "+(e.segmentCount-1))}return t.handleOperation((async()=>await Ae.post(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers})))}async queryVectors(e){var t=this;return t.handleOperation((async()=>await Ae.post(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers})))}async deleteVectors(e){var t=this;if(e.keys.length<1||e.keys.length>500)throw Error("Keys batch size must be between 1 and 500 items");return t.handleOperation((async()=>await Ae.post(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{}))}},Ke=class extends je{constructor(e,t={},r){super(e.replace(/\/$/,""),we(we({},Ue),{},{"Content-Type":"application/json"},t),r,"vectors")}async createBucket(e){var t=this;return t.handleOperation((async()=>await Ae.post(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{}))}async getBucket(e){var t=this;return t.handleOperation((async()=>await Ae.post(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers})))}async listBuckets(e={}){var t=this;return t.handleOperation((async()=>await Ae.post(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers})))}async deleteBucket(e){var t=this;return t.handleOperation((async()=>await Ae.post(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{}))}},We=class extends Ke{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new Me(this.url,this.headers,e,this.fetch)}async createBucket(e){return(()=>super.createBucket)().call(this,e)}async getBucket(e){return(()=>super.getBucket)().call(this,e)}async listBuckets(e={}){return(()=>super.listBuckets)().call(this,e)}async deleteBucket(e){return(()=>super.deleteBucket)().call(this,e)}},Me=class extends Be{constructor(e,t,r,s){super(e,t,s),this.vectorBucketName=r}async createIndex(e){return(()=>super.createIndex)().call(this,we(we({},e),{},{vectorBucketName:this.vectorBucketName}))}async listIndexes(e={}){return(()=>super.listIndexes)().call(this,we(we({},e),{},{vectorBucketName:this.vectorBucketName}))}async getIndex(e){return(()=>super.getIndex)().call(this,this.vectorBucketName,e)}async deleteIndex(e){return(()=>super.deleteIndex)().call(this,this.vectorBucketName,e)}index(e){return new Fe(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},Fe=class extends qe{constructor(e,t,r,s,i){super(e,t,i),this.vectorBucketName=r,this.indexName=s}async putVectors(e){var t=this;return(()=>super.putVectors)().call(t,we(we({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async getVectors(e){var t=this;return(()=>super.getVectors)().call(t,we(we({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async listVectors(e={}){var t=this;return(()=>super.listVectors)().call(t,we(we({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async queryVectors(e){var t=this;return(()=>super.queryVectors)().call(t,we(we({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async deleteVectors(e){var t=this;return(()=>super.deleteVectors)().call(t,we(we({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}},Ge=class extends Le{constructor(e,t={},r,s){super(e,t,r,s)}from(e){return new Ne(this.url,this.headers,e,this.fetch)}get vectors(){return new We(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new De(this.url+"/iceberg",this.headers,this.fetch)}};let He="";He=typeof Deno<"u"?"deno":typeof document<"u"?"web":typeof navigator<"u"&&"ReactNative"===navigator.product?"react-native":"node";let Ve={headers:{"X-Client-Info":`supabase-js-${He}/2.99.1`}},Je={schema:"public"},ze={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Ye={},Xe=(e,t,r)=>{let s=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(r),i=Headers;return async(r,a)=>{let n=await t()??e,o=new i(a?.headers);return o.has("apikey")||o.set("apikey",e),o.has("Authorization")||o.set("Authorization",`Bearer ${n}`),s(r,{...a,headers:o})}};let Qe="2.99.1",Ze=3e4,et=3*Ze,tt={"X-Client-Info":`gotrue-js/${Qe}`},rt="X-Supabase-Api-Version",st={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},it=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;var at=class extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}};function nt(e){return"object"==typeof e&&!!e&&"__isAuthError"in e}var ot=class extends at{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function lt(e){return nt(e)&&"AuthApiError"===e.name}var ht=class extends at{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},ct=class extends at{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}},ut=class extends ct{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function dt(e){return nt(e)&&"AuthSessionMissingError"===e.name}var pt=class extends ct{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},ft=class extends ct{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},gt=class extends ct{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}};function mt(e){return nt(e)&&"AuthImplicitGrantRedirectError"===e.name}var yt=class extends ct{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}}},wt=class extends ct{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}};var bt=class extends ct{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function _t(e){return nt(e)&&"AuthRetryableFetchError"===e.name}var vt=class extends ct{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}};var kt=class extends ct{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};let St="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Et=" \t\n\r=".split(""),Tt=(()=>{let e=Array(128);for(let t=0;t=6;)r(St[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6;else if(t.queuedBits>0)for(t.queue<<=6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;)r(St[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6}function Rt(e,t,r){let s=Tt[e];if(!(s>-1)){if(-2===s)return;throw Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}for(t.queue=t.queue<<6|s,t.queuedBits+=6;t.queuedBits>=8;)r(t.queue>>t.queuedBits-8&255),t.queuedBits-=8}function At(e){let t=[],r=e=>{t.push(String.fromCodePoint(e))},s={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},a=e=>{!function(e,t,r){if(0===t.utf8seq){if(e<=127)return void r(e);for(let r=1;r<6;r+=1)if(!(e>>7-r&1)){t.utf8seq=r;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else{if(4!==t.utf8seq)throw Error("Invalid UTF-8 sequence");t.codepoint=7&e}--t.utf8seq}else if(t.utf8seq>0){if(e<=127)throw Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,--t.utf8seq,0===t.utf8seq&&r(t.codepoint)}}(e,s,r)};for(let t=0;t>6),void t(128|63&e);if(e<=65535)return t(224|e>>12),t(128|e>>6&63),void t(128|63&e);if(e<=1114111)return t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),void t(128|63&e);throw Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}t(e)}function Pt(e){let t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};for(let t=0;t55295&&s<=56319){let t=1024*(s-55296)&65535;s=65536+(e.charCodeAt(r+1)-56320&65535|t),r+=1}jt(s,t)}}(e,(e=>t.push(e))),new Uint8Array(t)}function It(e){let t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};return e.forEach((e=>Ot(e,r,s))),Ot(null,r,s),t.join("")}let Ct=()=>typeof window<"u"&&typeof document<"u",xt={tested:!1,writable:!1},Nt=()=>{if(!Ct())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch{return!1}if(xt.tested)return xt.writable;let e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),xt.tested=!0,xt.writable=!0}catch{xt.tested=!0,xt.writable=!1}return xt.writable};let Ut=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),Lt=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},Dt=async(e,t)=>{let r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch{return r}},Bt=async(e,t)=>{await e.removeItem(t)};var qt=class e{constructor(){this.promise=new e.promiseConstructor(((e,t)=>{this.resolve=e,this.reject=t}))}};function Kt(e){let t=e.split(".");if(3!==t.length)throw new kt("Invalid JWT structure");for(let e=0;eString.fromCharCode(e))).join("")}(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Ft(e,t,r=!1){let s=function(){let e=new Uint32Array(56);if(typeof crypto>"u"){let e="";for(let t=0;t<56;t++)e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~".charAt(Math.floor(66*Math.random()));return e}return crypto.getRandomValues(e),Array.from(e,Wt).join("")}(),i=s;r&&(i+="/PASSWORD_RECOVERY"),await Lt(e,`${t}-code-verifier`,i);let a=await Mt(s);return[a,s===a?"plain":"s256"]}qt.promiseConstructor=Promise;let Gt=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;let Ht=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Vt(e){if(!Ht.test(e))throw Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Jt(){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 zt(e){return JSON.parse(JSON.stringify(e))}let Yt=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),Xt=[502,503,504];async function Qt(e){if(!(e=>"object"==typeof e&&!!e&&"status"in e&&"ok"in e&&"json"in e&&"function"==typeof e.json)(e))throw new bt(Yt(e),0);if(Xt.includes(e.status))throw new bt(Yt(e),e.status);let t;try{t=await e.json()}catch(e){throw new ht(Yt(e),e)}let r,s=function(e){let t=e.headers.get(rt);if(!t||!t.match(Gt))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}(e);if(s&&s.getTime()>=st["2024-01-01"].timestamp&&"object"==typeof t&&t&&"string"==typeof t.code?r=t.code:"object"==typeof t&&t&&"string"==typeof t.error_code&&(r=t.error_code),r){if("weak_password"===r)throw new vt(Yt(t),e.status,t.weak_password?.reasons||[]);if("session_not_found"===r)throw new ut}else if("object"==typeof t&&t&&"object"==typeof t.weak_password&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce(((e,t)=>e&&"string"==typeof t),!0))throw new vt(Yt(t),e.status,t.weak_password.reasons);throw new ot(Yt(t),e.status||500,r)}async function Zt(e,t,r,s){let i=Object.assign({},s?.headers);i[rt]||(i[rt]=st["2024-01-01"].name),s?.jwt&&(i.Authorization=`Bearer ${s.jwt}`);let a=s?.query??{};s?.redirectTo&&(a.redirect_to=s.redirectTo);let n=await async function(e,t,r,s,i,a){let n,o=((e,t,r,s)=>{let i={method:e,headers:t?.headers||{}};return"GET"===e?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},t?.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),r))})(t,s,i,a);try{n=await e(r,Object.assign({},o))}catch(e){throw console.error(e),new bt(Yt(e),0)}if(n.ok||await Qt(n),s?.noResolveJson)return n;try{return await n.json()}catch(e){await Qt(e)}}(e,t,r+(Object.keys(a).length?"?"+new URLSearchParams(a).toString():""),{headers:i,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(n):{data:Object.assign({},n),error:null}}function er(e){let t=null;return function(e){return e.access_token&&e.refresh_token&&e.expires_in}(e)&&(t=Object.assign({},e),e.expires_at||(t.expires_at=function(e){return Math.round(Date.now()/1e3)+e}(e.expires_in))),{data:{session:t,user:e.user??e},error:null}}function tr(e){let t=er(e);return!t.error&&e.weak_password&&"object"==typeof e.weak_password&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&"string"==typeof e.weak_password.message&&e.weak_password.reasons.reduce(((e,t)=>e&&"string"==typeof t),!0)&&(t.data.weak_password=e.weak_password),t}function rr(e){return{data:{user:e.user??e},error:null}}function sr(e){return{data:e,error:null}}function ir(e){let{action_link:r,email_otp:s,hashed_token:i,redirect_to:a,verification_type:n}=e,o=t(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]);return{data:{properties:{action_link:r,email_otp:s,hashed_token:i,redirect_to:a,verification_type:n},user:Object.assign({},o)},error:null}}function ar(e){return e}let nr=["global","local","others"];var or=class{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=Ut(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)}}async signOut(e,t=nr[0]){if(nr.indexOf(t)<0)throw Error(`@supabase/auth-js: Parameter scope must be one of ${nr.join(", ")}`);try{return await Zt(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(nt(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await Zt(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:rr})}catch(e){if(nt(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{let{options:r}=e,s=t(e,["options"]),i=Object.assign(Object.assign({},s),r);return"newEmail"in s&&(i.new_email=s?.newEmail,delete i.newEmail),await Zt(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:ir,redirectTo:r?.redirectTo})}catch(e){if(nt(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await Zt(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:rr})}catch(e){if(nt(e))return{data:{user:null},error:e};throw e}}async listUsers(e){try{let t={nextPage:null,lastPage:0,total:0},r=await Zt(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(e?.page)?.toString()??"",per_page:(e?.perPage)?.toString()??""},xform:ar});if(r.error)throw r.error;let s=await r.json(),i=r.headers.get("x-total-count")??0,a=r.headers.get("link")?.split(",")??[];return a.length>0&&(a.forEach((e=>{let r=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),s=JSON.parse(e.split(";")[1].split("=")[1]);t[`${s}Page`]=r})),t.total=parseInt(i)),{data:Object.assign(Object.assign({},s),t),error:null}}catch(e){if(nt(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){Vt(e);try{return await Zt(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:rr})}catch(e){if(nt(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){Vt(e);try{return await Zt(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:rr})}catch(e){if(nt(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){Vt(e);try{return await Zt(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:rr})}catch(e){if(nt(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){Vt(e.userId);try{let{data:t,error:r}=await Zt(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(nt(e))return{data:null,error:e};throw e}}async _deleteFactor(e){Vt(e.userId),Vt(e.id);try{return{data:await Zt(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(nt(e))return{data:null,error:e};throw e}}async _listOAuthClients(e){try{let t={nextPage:null,lastPage:0,total:0},r=await Zt(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(e?.page)?.toString()??"",per_page:(e?.perPage)?.toString()??""},xform:ar});if(r.error)throw r.error;let s=await r.json(),i=r.headers.get("x-total-count")??0,a=r.headers.get("link")?.split(",")??[];return a.length>0&&(a.forEach((e=>{let r=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),s=JSON.parse(e.split(";")[1].split("=")[1]);t[`${s}Page`]=r})),t.total=parseInt(i)),{data:Object.assign(Object.assign({},s),t),error:null}}catch(e){if(nt(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await Zt(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(nt(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await Zt(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(nt(e))return{data:null,error:e};throw e}}async _updateOAuthClient(e,t){try{return await Zt(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(nt(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await Zt(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(nt(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await Zt(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(nt(e))return{data:null,error:e};throw e}}async _listCustomProviders(e){try{let t={};return e?.type&&(t.type=e.type),await Zt(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:t,xform:e=>({data:{providers:e?.providers??[]},error:null})})}catch(e){if(nt(e))return{data:{providers:[]},error:e};throw e}}async _createCustomProvider(e){try{return await Zt(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(nt(e))return{data:null,error:e};throw e}}async _getCustomProvider(e){try{return await Zt(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(nt(e))return{data:null,error:e};throw e}}async _updateCustomProvider(e,t){try{return await Zt(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(nt(e))return{data:null,error:e};throw e}}async _deleteCustomProvider(e){try{return await Zt(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(nt(e))return{data:null,error:e};throw e}}};function lr(e={}){return{getItem:t=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:t=>{delete e[t]}}}let hr={debug:!!(globalThis&&Nt()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"))};var cr=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},ur=class extends cr{},dr=class extends cr{};async function pr(e,t,r){hr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);let s=new globalThis.AbortController;t>0&&setTimeout((()=>{s.abort(),hr.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)}),t),await Promise.resolve();try{return await globalThis.navigator.locks.request(e,0===t?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},(async s=>{if(!s){if(0===t)throw hr.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new ur(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(hr.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()}hr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,s.name);try{return await r()}finally{hr.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",e,s.name)}}))}catch(s){if("AbortError"===s?.name&&t>0)return hr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",e),console.warn(`@supabase/gotrue-js: Lock "${e}" was not released within ${t}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then((()=>globalThis.navigator.locks.request(e,{mode:"exclusive",steal:!0},(async t=>{if(!t)return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r();hr.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",e,t.name);try{return await r()}finally{hr.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",e,t.name)}}))));throw s}}let fr={};function gr(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function mr(e){let t=(new TextEncoder).encode(e);return"0x"+Array.from(t,(e=>e.toString(16).padStart(2,"0"))).join("")}var yr=class extends Error{constructor({message:e,code:t,cause:r,name:s}){super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=s??(r instanceof Error?r.name:void 0)??"Unknown Error",this.code=t}},wr=class extends yr{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}};function br({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 yr({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if(!0===r.authenticatorSelection?.requireResidentKey)return new yr({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if("conditional"===t.mediation&&"required"===r.authenticatorSelection?.userVerification)return new yr({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if("required"===r.authenticatorSelection?.userVerification)return new yr({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 yr({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new yr({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("NotSupportedError"===e.name)return 0===r.pubKeyCredParams.filter((e=>"public-key"===e.type)).length?new yr({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new yr({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});if("SecurityError"===e.name){let t=window.location.hostname;if(!Or(t))return new yr({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(r.rp.id!==t)return new yr({message:`The RP ID "${r.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(r.user.id.byteLength<1||r.user.id.byteLength>64)return new yr({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 yr({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 yr({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function _r({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 yr({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new yr({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("SecurityError"===e.name){let t=window.location.hostname;if(!Or(t))return new yr({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(r.rpId!==t)return new yr({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 yr({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 yr({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}let vr=new class{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}}};function kr(e){if(!e)throw Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(e);let{challenge:r,user:s,excludeCredentials:i}=e,a=t(e,["challenge","user","excludeCredentials"]),n=Pt(r).buffer,o=Object.assign(Object.assign({},s),{id:Pt(s.id).buffer}),l=Object.assign(Object.assign({},a),{challenge:n,user:o});if(i&&i.length>0){l.excludeCredentials=Array(i.length);for(let e=0;e0){n.allowCredentials=Array(s.length);for(let e=0;e"object"==typeof e&&!!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 a=i[e];if(void 0!==a)if(Array.isArray(a))s[e]=a;else if(r(a))s[e]=a;else if(t(a)){let r=s[e];t(r)?s[e]=Pr(r,a):s[e]=Pr(a)}else s[e]=a}return s}function $r(e,t){return Pr(Ar,e,t||{})}var Ir=class{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{let{data:a,error:n}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!a)return{data:null,error:n};let o=s??vr.createNewAbortSignal();if("create"===a.webauthn.type){let{user:e}=a.webauthn.credential_options.publicKey;if(!e.name){let t=r;if(t)e.name=`${e.id}:${t}`;else{let t=(await this.client.getUser()).data.user,r=t?.user_metadata?.name||t?.email||t?.id||"User";e.name=`${e.id}:${r}`}}e.displayName||=e.name}switch(a.webauthn.type){case"create":{let{data:t,error:r}=await async function(e){try{let t=await navigator.credentials.create(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new wr("Browser returned unexpected credential type",t)}:{data:null,error:new wr("Empty credential response",t)}}catch(t){return{data:null,error:br({error:t,options:e})}}}({publicKey:$r(a.webauthn.credential_options.publicKey,i?.create),signal:o});return t?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:t}},error:null}:{data:null,error:r}}case"request":{let t=function(e,t){return Pr(jr,e,t||{})}(a.webauthn.credential_options.publicKey,i?.request),{data:r,error:s}=await async function(e){try{let t=await navigator.credentials.get(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new wr("Browser returned unexpected credential type",t)}:{data:null,error:new wr("Empty credential response",t)}}catch(t){return{data:null,error:_r({error:t,options:e})}}}(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:t,signal:o}));return r?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:r}},error:null}:{data:null,error:s}}}}catch(e){return nt(e)?{data:null,error:e}:{data:null,error:new ht("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=(typeof window<"u"?window.location.hostname:void 0),rpOrigins:r=(typeof window<"u"?[window.location.origin]:void 0),signal:s}={}},i){if(!t)return{data:null,error:new at("rpId is required for WebAuthn authentication")};try{if(!Rr())return{data:null,error:new ht("Browser does not support WebAuthn",null)};let{data:a,error:n}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:i});if(!a)return{data:null,error:n};let{webauthn:o}=a;return this._verify({factorId:e,challengeId:a.challengeId,webauthn:{type:o.type,rpId:t,rpOrigins:r,credential_response:o.credential_response}})}catch(e){return nt(e)?{data:null,error:e}:{data:null,error:new ht("Unexpected error in authenticate",e)}}}async _register({friendlyName:e,webauthn:{rpId:t=(typeof window<"u"?window.location.hostname:void 0),rpOrigins:r=(typeof window<"u"?[window.location.origin]:void 0),signal:s}={}},i){if(!t)return{data:null,error:new at("rpId is required for WebAuthn registration")};try{if(!Rr())return{data:null,error:new ht("Browser does not support WebAuthn",null)};let{data:a,error:n}=await this._enroll({friendlyName:e});if(!a)return await this.client.mfa.listFactors().then((t=>t.data?.all.find((t=>"webauthn"===t.factor_type&&t.friendly_name===e&&"unverified"!==t.status)))).then((e=>e?this.client.mfa.unenroll({factorId:e?.id}):void 0)),{data:null,error:n};let{data:o,error:l}=await this._challenge({factorId:a.id,friendlyName:a.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:i});return o?this._verify({factorId:a.id,challengeId:o.challengeId,webauthn:{rpId:t,rpOrigins:r,type:o.webauthn.type,credential_response:o.webauthn.credential_response}}):{data:null,error:l}}catch(e){return nt(e)?{data:null,error:e}:{data:null,error:new ht("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{typeof self<"u"&&(self.globalThis=self)}}();let Cr={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:tt,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function xr(e,t,r){return await r()}let Nr={};var Ur=class e{get jwks(){return Nr[this.storageKey]?.jwks??{keys:[]}}set jwks(e){Nr[this.storageKey]=Object.assign(Object.assign({},Nr[this.storageKey]),{jwks:e})}get jwks_cached_at(){return Nr[this.storageKey]?.cachedAt??-(2**53-1)}set jwks_cached_at(e){Nr[this.storageKey]=Object.assign(Object.assign({},Nr[this.storageKey]),{cachedAt:e})}constructor(t){var r;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=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;let s=Object.assign(Object.assign({},Cr),t);if(this.storageKey=s.storageKey,this.instanceID=e.nextInstanceID[this.storageKey]??0,e.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!s.debug,"function"==typeof s.debug&&(this.logger=s.debug),this.instanceID>0&&Ct()){let e=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(e),this.logDebugMessages&&console.trace(e)}if(this.persistSession=s.persistSession,this.autoRefreshToken=s.autoRefreshToken,this.admin=new or({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=Ut(s.fetch),this.lock=s.lock||xr,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,this.throwOnError=s.throwOnError,this.lockAcquireTimeout=s.lockAcquireTimeout,s.lock?this.lock=s.lock:this.persistSession&&Ct()&&(null==globalThis?void 0:globalThis.navigator)?.locks?this.lock=pr:this.lock=xr,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=-(2**53-1)),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 Ir(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(s.storage?this.storage=s.storage:Nt()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=lr(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=lr(this.memoryStorage)),Ct()&&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)||r.addEventListener("message",(async e=>{this._debug("received broadcast notification from other tab or client",e);try{await this._notifyAllSubscribers(e.data.event,e.data.session,!1)}catch(e){this._debug("#broadcastChannel","error",e)}}))}s.skipAutoInitialize||this.initialize().catch((e=>{this._debug("#initialize()","error",e)}))}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Qe}) ${(new Date).toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise||=(async()=>await this._acquireLock(this.lockAcquireTimeout,(async()=>await this._initialize())))(),await this.initializePromise}async _initialize(){try{let e={},t="none";if(Ct()&&(e=function(e){let t={},r=new URL(e);if(r.hash&&"#"===r.hash[0])try{new URLSearchParams(r.hash.substring(1)).forEach(((e,r)=>{t[r]=e}))}catch{}return r.searchParams.forEach(((e,r)=>{t[r]=e})),t}(window.location.href),this._isImplicitGrantCallback(e)?t="implicit":await this._isPKCECallback(e)&&(t="pkce")),Ct()&&this.detectSessionInUrl&&"none"!==t){let{data:r,error:s}=await this._getSessionFromURL(e,t);if(s){if(this._debug("#_initialize()","error detecting session from URL",s),mt(s)){let e=s.details?.code;if("identity_already_exists"===e||"identity_not_found"===e||"single_identity_not_deletable"===e)return{error:s}}return{error:s}}let{session:i,redirectType:a}=r;return this._debug("#_initialize()","detected session in URL",i,"redirect type",a),await this._saveSession(i),setTimeout((async()=>{"recovery"===a?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)}),0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return nt(e)?this._returnResult({error:e}):this._returnResult({error:new ht("Unexpected error during initialization",e)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){try{let{data:t,error:r}=await Zt(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:e?.options?.data??{},gotrue_meta_security:{captcha_token:e?.options?.captchaToken}},xform:er});if(r||!t)return this._returnResult({data:{user:null,session:null},error:r});let s=t.session,i=t.user;return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",s)),this._returnResult({data:{user:i,session:s},error:null})}catch(e){if(nt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signUp(e){try{let t;if("email"in e){let{email:r,password:s,options:i}=e,a=null,n=null;"pkce"===this.flowType&&([a,n]=await Ft(this.storage,this.storageKey)),t=await Zt(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:i?.emailRedirectTo,body:{email:r,password:s,data:i?.data??{},gotrue_meta_security:{captcha_token:i?.captchaToken},code_challenge:a,code_challenge_method:n},xform:er})}else{if(!("phone"in e))throw new ft("You must provide either an email or phone number and a password");{let{phone:r,password:s,options:i}=e;t=await Zt(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:r,password:s,data:i?.data??{},channel:i?.channel??"sms",gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:er})}}let{data:r,error:s}=t;if(s||!r)return await Bt(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:s});let i=r.session,a=r.user;return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",i)),this._returnResult({data:{user:a,session:i},error:null})}catch(e){if(await Bt(this.storage,`${this.storageKey}-code-verifier`),nt(e))return this._returnResult({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 Zt(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:r,password:s,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:tr})}else{if(!("phone"in e))throw new ft("You must provide either an email or phone number and a password");{let{phone:r,password:s,options:i}=e;t=await Zt(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:r,password:s,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:tr})}}let{data:r,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){let e=new pt;return this._returnResult({data:{user:null,session:null},error:e})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(e){if(nt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOAuth(e){return await this._handleProviderSignIn(e.provider,{redirectTo:e.options?.redirectTo,scopes:e.options?.scopes,queryParams:e.options?.queryParams,skipBrowserRedirect:e.options?.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,(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){let t,r;if("message"in e)t=e.message,r=e.signature;else{let s,{chain:i,wallet:a,statement:n,options:o}=e;if(Ct())if("object"==typeof a)s=a;else{let e=window;if(!("ethereum"in e)||"object"!=typeof e.ethereum||!("request"in e.ethereum)||"function"!=typeof e.ethereum.request)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.");s=e.ethereum}else{if("object"!=typeof a||!o?.url)throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");s=a}let l=new URL(o?.url??window.location.href),h=await s.request({method:"eth_requestAccounts"}).then((e=>e)).catch((()=>{throw Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")}));if(!h||0===h.length)throw Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let c=gr(h[0]),u=o?.signInWithEthereum?.chainId;u||=function(e){return parseInt(e,16)}(await s.request({method:"eth_chainId"})),t=function(e){let{chainId:t,domain:r,expirationTime:s,issuedAt:i=new Date,nonce:a,notBefore:n,requestId:o,resources:l,scheme:h,uri:c,version:u}=e;if(!Number.isInteger(t))throw Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${t}`);if(!r)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"!==u)throw Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${u}`);if(e.statement?.includes("\n"))throw Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);let d=`${h?`${h}://${r}`:r} wants you to sign in with your Ethereum account:\n${gr(e.address)}\n\n${e.statement?`${e.statement}\n`:""}`,p=`URI: ${c}\nVersion: ${u}\nChain ID: ${t}${a?`\nNonce: ${a}`:""}\nIssued At: ${i.toISOString()}`;if(s&&(p+=`\nExpiration Time: ${s.toISOString()}`),n&&(p+=`\nNot Before: ${n.toISOString()}`),o&&(p+=`\nRequest ID: ${o}`),l){let e="\nResources:";for(let t of l){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+=`\n- ${t}`}p+=e}return`${d}\n${p}`}({domain:l.host,address:c,statement:n,uri:l.href,version:"1",chainId:u,nonce:o?.signInWithEthereum?.nonce,issuedAt:o?.signInWithEthereum?.issuedAt??new Date,expirationTime:o?.signInWithEthereum?.expirationTime,notBefore:o?.signInWithEthereum?.notBefore,requestId:o?.signInWithEthereum?.requestId,resources:o?.signInWithEthereum?.resources}),r=await s.request({method:"personal_sign",params:[mr(t),c]})}try{let{data:s,error:i}=await Zt(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:t,signature:r},e.options?.captchaToken?{gotrue_meta_security:{captcha_token:e.options?.captchaToken}}:null),xform:er});if(i)throw i;if(!s||!s.session||!s.user){let e=new pt;return this._returnResult({data:{user:null,session:null},error:e})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign({},s),error:i})}catch(e){if(nt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSolana(e){let t,r;if("message"in e)t=e.message,r=e.signature;else{let s,{chain:i,wallet:a,statement:n,options:o}=e;if(Ct())if("object"==typeof a)s=a;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))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.");s=e.solana}else{if("object"!=typeof a||!o?.url)throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");s=a}let l=new URL(o?.url??window.location.href);if("signIn"in s&&s.signIn){let e,i=await s.signIn(Object.assign(Object.assign(Object.assign({issuedAt:(new Date).toISOString()},o?.signInWithSolana),{version:"1",domain:l.host,uri:l.href}),n?{statement:n}:null));if(Array.isArray(i)&&i[0]&&"object"==typeof i[0])e=i[0];else{if(!(i&&"object"==typeof i&&"signedMessage"in i&&"signature"in i))throw Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");e=i}if(!("signedMessage"in e&&"signature"in e&&("string"==typeof e.signedMessage||e.signedMessage instanceof Uint8Array)&&e.signature instanceof Uint8Array))throw Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields");t="string"==typeof e.signedMessage?e.signedMessage:(new TextDecoder).decode(e.signedMessage),r=e.signature}else{if(!("signMessage"in s&&"function"==typeof s.signMessage&&"publicKey"in s&&"object"==typeof s&&s.publicKey&&"toBase58"in s.publicKey&&"function"==typeof s.publicKey.toBase58))throw Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");t=[`${l.host} wants you to sign in with your Solana account:`,s.publicKey.toBase58(),...n?["",n,""]:[""],"Version: 1",`URI: ${l.href}`,`Issued At: ${o?.signInWithSolana?.issuedAt??(new Date).toISOString()}`,...o?.signInWithSolana?.notBefore?[`Not Before: ${o.signInWithSolana.notBefore}`]:[],...o?.signInWithSolana?.expirationTime?[`Expiration Time: ${o.signInWithSolana.expirationTime}`]:[],...o?.signInWithSolana?.chainId?[`Chain ID: ${o.signInWithSolana.chainId}`]:[],...o?.signInWithSolana?.nonce?[`Nonce: ${o.signInWithSolana.nonce}`]:[],...o?.signInWithSolana?.requestId?[`Request ID: ${o.signInWithSolana.requestId}`]:[],...o?.signInWithSolana?.resources?.length?["Resources",...o.signInWithSolana.resources.map((e=>`- ${e}`))]:[]].join("\n");let e=await s.signMessage((new TextEncoder).encode(t),"utf8");if(!(e&&e instanceof Uint8Array))throw Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");r=e}}try{let{data:s,error:i}=await Zt(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:t,signature:It(r)},e.options?.captchaToken?{gotrue_meta_security:{captcha_token:e.options?.captchaToken}}:null),xform:er});if(i)throw i;if(!s||!s.session||!s.user){let e=new pt;return this._returnResult({data:{user:null,session:null},error:e})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign({},s),error:i})}catch(e){if(nt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e){let[t,r]=(await Dt(this.storage,`${this.storageKey}-code-verifier`)??"").split("/");try{if(!t&&"pkce"===this.flowType)throw new wt;let{data:s,error:i}=await Zt(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:t},xform:er});if(await Bt(this.storage,`${this.storageKey}-code-verifier`),i)throw i;if(!s||!s.session||!s.user){let e=new pt;return this._returnResult({data:{user:null,session:null,redirectType:null},error:e})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign(Object.assign({},s),{redirectType:r??null}),error:i})}catch(e){if(await Bt(this.storage,`${this.storageKey}-code-verifier`),nt(e))return this._returnResult({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:a}=e,{data:n,error:o}=await Zt(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:i,nonce:a,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:er});if(o)return this._returnResult({data:{user:null,session:null},error:o});if(!n||!n.session||!n.user){let e=new pt;return this._returnResult({data:{user:null,session:null},error:e})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:n,error:o})}catch(e){if(nt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOtp(e){try{if("email"in e){let{email:t,options:r}=e,s=null,i=null;"pkce"===this.flowType&&([s,i]=await Ft(this.storage,this.storageKey));let{error:a}=await Zt(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:t,data:r?.data??{},create_user:r?.shouldCreateUser??!0,gotrue_meta_security:{captcha_token:r?.captchaToken},code_challenge:s,code_challenge_method:i},redirectTo:r?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}if("phone"in e){let{phone:t,options:r}=e,{data:s,error:i}=await Zt(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:r?.data??{},create_user:r?.shouldCreateUser??!0,gotrue_meta_security:{captcha_token:r?.captchaToken},channel:r?.channel??"sms"}});return this._returnResult({data:{user:null,session:null,messageId:s?.message_id},error:i})}throw new ft("You must provide either an email or phone number.")}catch(e){if(await Bt(this.storage,`${this.storageKey}-code-verifier`),nt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async verifyOtp(e){try{let t,r;"options"in e&&(t=e.options?.redirectTo,r=e.options?.captchaToken);let{data:s,error:i}=await Zt(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:r}}),redirectTo:t,xform:er});if(i)throw i;if(!s)throw Error("An error occurred on token verification.");let a=s.session,n=s.user;return a?.access_token&&(await this._saveSession(a),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",a)),this._returnResult({data:{user:n,session:a},error:null})}catch(e){if(nt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSSO(e){try{let t=null,r=null;"pkce"===this.flowType&&([t,r]=await Ft(this.storage,this.storageKey));let s=await Zt(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:e.options?.redirectTo??void 0}),e?.options?.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:t,code_challenge_method:r}),headers:this.headers,xform:sr});return s.data?.url&&Ct()&&!e.options?.skipBrowserRedirect&&window.location.assign(s.data.url),this._returnResult(s)}catch(e){if(await Bt(this.storage,`${this.storageKey}-code-verifier`),nt(e))return this._returnResult({data:null,error:e});throw e}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,(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 ut;let{error:s}=await Zt(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})}))}catch(e){if(nt(e))return this._returnResult({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:a}=await Zt(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:i?.captchaToken}},redirectTo:i?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}if("phone"in e){let{phone:r,type:s,options:i}=e,{data:a,error:n}=await Zt(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:i?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:a?.message_id},error:n})}throw new ft("You must provide either an email or phone number and a type")}catch(e){if(nt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,(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{}})()),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{}})()),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{return await e(await this.__loadSession())}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 Dt(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),null!==t&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let r=!!e.expires_at&&1e3*e.expires_at-Date.now(){if("__isInsecureUserWarningProxy"===r)return!0;if("symbol"==typeof r){let t=r.toString();if("Symbol(Symbol.toPrimitive)"===t||"Symbol(Symbol.toStringTag)"===t||"Symbol(util.inspect.custom)"===t||"Symbol(nodejs.util.inspect.custom)"===t)return Reflect.get(e,r,s)}return!t.value&&"string"==typeof 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.value=!0),Reflect.get(e,r,s)}})}(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let t=await this._acquireLock(this.lockAcquireTimeout,(async()=>await this._getUser()));return t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await Zt(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:rr}):await this._useSession((async e=>{let{data:t,error:r}=e;if(r)throw r;return t.session?.access_token||this.hasCustomAuthorizationHeader?await Zt(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t.session?.access_token??void 0,xform:rr}):{data:{user:null},error:new ut}}))}catch(e){if(nt(e))return dt(e)&&(await this._removeSession(),await Bt(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:e});throw e}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,(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 ut;let a=s.session,n=null,o=null;"pkce"===this.flowType&&null!=e.email&&([n,o]=await Ft(this.storage,this.storageKey));let{data:l,error:h}=await Zt(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:n,code_challenge_method:o}),jwt:a.access_token,xform:rr});if(h)throw h;return a.user=l.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),this._returnResult({data:{user:a.user},error:null})}))}catch(e){if(await Bt(this.storage,`${this.storageKey}-code-verifier`),nt(e))return this._returnResult({data:{user:null},error:e});throw e}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,(async()=>await this._setSession(e)))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new ut;let t=Date.now()/1e3,r=t,s=!0,i=null,{payload:a}=Kt(e.access_token);if(a.exp&&(r=a.exp,s=r<=t),s){let{data:t,error:r}=await this._callRefreshToken(e.refresh_token);if(r)return this._returnResult({data:{user:null,session:null},error:r});if(!t)return{data:{user:null,session:null},error:null};i=t}else{let{data:s,error:a}=await this._getUser(e.access_token);if(a)return this._returnResult({data:{user:null,session:null},error:a});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 this._returnResult({data:{user:i.user,session:i},error:null})}catch(e){if(nt(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,(async()=>await this._refreshSession(e)))}async _refreshSession(e){try{return await this._useSession((async t=>{if(!e){let{data:r,error:s}=t;if(s)throw s;e=r.session??void 0}if(!e?.refresh_token)throw new ut;let{data:r,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{user:null,session:null},error:s}):r?this._returnResult({data:{user:r.user,session:r},error:null}):this._returnResult({data:{user:null,session:null},error:null})}))}catch(e){if(nt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){try{if(!Ct())throw new gt("No browser detected.");if(e.error||e.error_description||e.error_code)throw new gt(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 yt("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new gt("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new yt("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:a,expires_in:n,expires_at:o,token_type:l}=e;if(!(i&&n&&a&&l))throw new gt("No session defined in URL");let h=Math.round(Date.now()/1e3),c=parseInt(n),u=h+c;o&&(u=parseInt(o));let d=u-h;1e3*d<=Ze&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${d}s, should have been closer to ${c}s`);let p=u-c;h-p>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,u,h):h-p<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",p,u,h);let{data:f,error:g}=await this._getUser(i);if(g)throw g;let m={provider_token:r,provider_refresh_token:s,access_token:i,expires_in:c,expires_at:u,refresh_token:a,token_type:l,user:f.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:m,redirectType:e.type},error:null})}catch(e){if(nt(e))return this._returnResult({data:{session:null,redirectType:null},error:e});throw e}}_isImplicitGrantCallback(e){return"function"==typeof this.detectSessionInUrl?this.detectSessionInUrl(new URL(window.location.href),e):!(!e.access_token&&!e.error_description)}async _isPKCECallback(e){let t=await Dt(this.storage,`${this.storageKey}-code-verifier`);return!(!e.code||!t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,(async()=>await this._signOut(e)))}async _signOut({scope:e}={scope:"global"}){return await this._useSession((async t=>{let{data:r,error:s}=t;if(s&&!dt(s))return this._returnResult({error:s});let i=r.session?.access_token;if(i){let{error:t}=await this.admin.signOut(i,e);if(t&&(!lt(t)||404!==t.status&&401!==t.status&&403!==t.status)&&!dt(t))return this._returnResult({error:t})}return"others"!==e&&(await this._removeSession(),await Bt(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})}))}onAuthStateChange(e){let t=Symbol("auth-callback"),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(this.lockAcquireTimeout,(async()=>{this._emitInitialSession(t)}))})(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession((async t=>{try{let{data:{session:r},error:s}=t;if(s)throw s;await(this.stateChangeEmitters.get(e)?.callback("INITIAL_SESSION",r)),this._debug("INITIAL_SESSION","callback id",e,"session",r)}catch(t){await(this.stateChangeEmitters.get(e)?.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 Ft(this.storage,this.storageKey,!0));try{return await Zt(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(await Bt(this.storage,`${this.storageKey}-code-verifier`),nt(e))return this._returnResult({data:null,error:e});throw e}}async getUserIdentities(){try{let{data:e,error:t}=await this.getUser();if(t)throw t;return this._returnResult({data:{identities:e.user.identities??[]},error:null})}catch(e){if(nt(e))return this._returnResult({data:null,error:e});throw e}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){try{let{data:t,error:r}=await this._useSession((async t=>{let{data:r,error:s}=t;if(s)throw s;let i=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:e.options?.redirectTo,scopes:e.options?.scopes,queryParams:e.options?.queryParams,skipBrowserRedirect:!0});return await Zt(this.fetch,"GET",i,{headers:this.headers,jwt:r.session?.access_token??void 0})}));if(r)throw r;return Ct()&&!e.options?.skipBrowserRedirect&&window.location.assign(t?.url),this._returnResult({data:{provider:e.provider,url:t?.url},error:null})}catch(t){if(nt(t))return this._returnResult({data:{provider:e.provider,url:null},error:t});throw t}}async linkIdentityIdToken(e){return await this._useSession((async t=>{try{let{error:r,data:{session:s}}=t;if(r)throw r;let{options:i,provider:a,token:n,access_token:o,nonce:l}=e,{data:h,error:c}=await Zt(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:s?.access_token??void 0,body:{provider:a,id_token:n,access_token:o,nonce:l,link_identity:!0,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:er});return c?this._returnResult({data:{user:null,session:null},error:c}):h&&h.session&&h.user?(h.session&&(await this._saveSession(h.session),await this._notifyAllSubscribers("USER_UPDATED",h.session)),this._returnResult({data:h,error:c})):this._returnResult({data:{user:null,session:null},error:new pt})}catch(e){if(await Bt(this.storage,`${this.storageKey}-code-verifier`),nt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}))}async unlinkIdentity(e){try{return await this._useSession((async t=>{let{data:r,error:s}=t;if(s)throw s;return await Zt(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:r.session?.access_token??void 0})}))}catch(e){if(nt(e))return this._returnResult({data:null,error:e});throw e}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let r=Date.now();return await function(e,t){return new Promise(((r,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{let s=await e(i);if(!t(i,null,s))return void r(s)}catch(e){if(!t(i,e))return void s(e)}})()}))}((async r=>(r>0&&await async function(e){return await new Promise((t=>{setTimeout((()=>t(null)),e)}))}(200*2**(r-1)),this._debug(t,"refreshing attempt",r),await Zt(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:er}))),((e,t)=>{let s=200*2**e;return t&&_t(t)&&Date.now()+s-r{try{await r.callback(e,t)}catch(e){s.push(e)}}));if(await Promise.all(i),s.length>0){for(let e=0;ethis._autoRefreshTokenTick()),Ze);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():typeof Deno<"u"&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e);let t=setTimeout((async()=>{await this.initializePromise,await this._autoRefreshTokenTick()}),0);this.autoRefreshTickTimeout=t,t&&"object"==typeof t&&"function"==typeof t.unref?t.unref():typeof Deno<"u"&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}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)return void this._debug("#_autoRefreshTokenTick()","no session");let s=Math.floor((1e3*r.expires_at-e)/Ze);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${Ze}ms, 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 cr))throw e;this._debug("auto refresh token tick lock not available")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Ct()||null==window||!window.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},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(this.lockAcquireTimeout,(async()=>{"visible"===document.visibilityState?await this._recoverAndRefresh():this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting")})))):"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let s=[`provider=${encodeURIComponent(t)}`];if(r?.redirectTo&&s.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r?.scopes&&s.push(`scopes=${encodeURIComponent(r.scopes)}`),"pkce"===this.flowType){let[e,t]=await Ft(this.storage,this.storageKey),r=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});s.push(r.toString())}if(r?.queryParams){let e=new URLSearchParams(r.queryParams);s.push(e.toString())}return r?.skipBrowserRedirect&&s.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession((async t=>{let{data:r,error:s}=t;return s?this._returnResult({data:null,error:s}):await Zt(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:r?.session?.access_token})}))}catch(e){if(nt(e))return this._returnResult({data:null,error:e});throw e}}async _enroll(e){try{return await this._useSession((async t=>{let{data:r,error:s}=t;if(s)return this._returnResult({data:null,error:s});let i=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:"totp"===e.factorType?{issuer:e.issuer}:{}),{data:a,error:n}=await Zt(this.fetch,"POST",`${this.url}/factors`,{body:i,headers:this.headers,jwt:r?.session?.access_token});return n?this._returnResult({data:null,error:n}):("totp"===e.factorType&&"totp"===a.type&&a?.totp?.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),this._returnResult({data:a,error:null}))}))}catch(e){if(nt(e))return this._returnResult({data:null,error:e});throw e}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,(async()=>{try{return await this._useSession((async t=>{let{data:r,error:s}=t;if(s)return this._returnResult({data:null,error:s});let i=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:"create"===e.webauthn.type?Er(e.webauthn.credential_response):Tr(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:n}=await Zt(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:r?.session?.access_token});return n?this._returnResult({data:null,error:n}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),this._returnResult({data:a,error:n}))}))}catch(e){if(nt(e))return this._returnResult({data:null,error:e});throw e}}))}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,(async()=>{try{return await this._useSession((async t=>{let{data:r,error:s}=t;if(s)return this._returnResult({data:null,error:s});let i=await Zt(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:r?.session?.access_token});if(i.error)return i;let{data:a}=i;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:kr(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:Sr(a.webauthn.credential_options.publicKey)})})}),error:null}}}))}catch(e){if(nt(e))return this._returnResult({data:null,error:e});throw e}}))}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let r={all:[],phone:[],totp:[],webauthn:[]};for(let t of e?.factors??[])r.all.push(t),"verified"===t.status&&r[t.factor_type].push(t);return{data:r,error:null}}async _getAuthenticatorAssuranceLevel(e){if(e)try{let{payload:t}=Kt(e),r=null;t.aal&&(r=t.aal);let s=r,{data:{user:i},error:a}=await this.getUser(e);return a?this._returnResult({data:null,error:a}):(((i?.factors)?.filter((e=>"verified"===e.status))??[]).length>0&&(s="aal2"),{data:{currentLevel:r,nextLevel:s,currentAuthenticationMethods:t.amr||[]},error:null})}catch(e){if(nt(e))return this._returnResult({data:null,error:e});throw e}let{data:{session:t},error:r}=await this.getSession();if(r)return this._returnResult({data:null,error:r});if(!t)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:s}=Kt(t.access_token),i=null;s.aal&&(i=s.aal);let a=i;return(t.user.factors?.filter((e=>"verified"===e.status))??[]).length>0&&(a="aal2"),{data:{currentLevel:i,nextLevel:a,currentAuthenticationMethods:s.amr||[]},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession((async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await Zt(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new ut})}))}catch(e){if(nt(e))return this._returnResult({data:null,error:e});throw e}}async _approveAuthorization(e,t){try{return await this._useSession((async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new ut});let a=await Zt(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:e=>({data:e,error:null})});return a.data&&a.data.redirect_url&&Ct()&&!t?.skipBrowserRedirect&&window.location.assign(a.data.redirect_url),a}))}catch(e){if(nt(e))return this._returnResult({data:null,error:e});throw e}}async _denyAuthorization(e,t){try{return await this._useSession((async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new ut});let a=await Zt(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:e=>({data:e,error:null})});return a.data&&a.data.redirect_url&&Ct()&&!t?.skipBrowserRedirect&&window.location.assign(a.data.redirect_url),a}))}catch(e){if(nt(e))return this._returnResult({data:null,error:e});throw e}}async _listOAuthGrants(){try{return await this._useSession((async e=>{let{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await Zt(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new ut})}))}catch(e){if(nt(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession((async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?(await Zt(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new ut})}))}catch(e){if(nt(e))return this._returnResult({data:null,error:e});throw e}}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)),r&&this.jwks_cached_at+6e5>s)return r;let{data:i,error:a}=await Zt(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return i.keys&&0!==i.keys.length&&(this.jwks=i,this.jwks_cached_at=s,r=i.keys.find((t=>t.kid===e)),r)?r:null}async getClaims(e,t={}){try{let r=e;if(!r){let{data:e,error:t}=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});r=e.session.access_token}let{header:s,payload:i,signature:a,raw:{header:n,payload:o}}=Kt(r);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?await this.fetchJwk(s.kid,t?.keys?{keys:t.keys}:t?.jwks):null;if(!l){let{error:e}=await this.getUser(r);if(e)throw e;return{data:{claims:i,header:s,signature:a},error:null}}let h=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),c=await crypto.subtle.importKey("jwk",l,h,!0,["verify"]);if(!await crypto.subtle.verify(h,c,a,$t(`${n}.${o}`)))throw new kt("Invalid JWT signature");return{data:{claims:i,header:s,signature:a},error:null}}catch(e){if(nt(e))return this._returnResult({data:null,error:e});throw e}}};Ur.nextInstanceID={};var Lr=Ur,Dr=or,Br=Lr,qr=class extends Br{constructor(e){super(e)}},Kr=class{constructor(e,t,r){this.supabaseUrl=e,this.supabaseKey=t;let s=function(e){let t=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(function(e){return e.endsWith("/")?e:e+"/"}(t))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}(e);if(!t)throw Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",s),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",s),this.storageUrl=new URL("storage/v1",s),this.functionsUrl=new URL("functions/v1",s);let i=`sb-${s.hostname.split(".")[0]}-auth-token`,a=function(e,t){let{db:r,auth:s,realtime:i,global:a}=e,{db:n,auth:o,realtime:l,global:h}=t,c={db:{...n,...r},auth:{...o,...s},realtime:{...l,...i},storage:{},global:{...h,...a,headers:{...h?.headers??{},...a?.headers??{}}},accessToken:async()=>""};return e.accessToken?c.accessToken=e.accessToken:delete c.accessToken,c}(r??{},{db:Je,realtime:Ye,auth:{...ze,storageKey:i},global:Ve});this.storageKey=a.auth.storageKey??"",this.headers=a.global.headers??{},a.accessToken?(this.accessToken=a.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(a.auth??{},this.headers,a.global.fetch),this.fetch=Xe(t,this._getAccessToken.bind(this),a.global.fetch),this.realtime=this._initRealtimeClient({headers:this.headers,accessToken:this._getAccessToken.bind(this),...a.realtime}),this.accessToken&&Promise.resolve(this.accessToken()).then((e=>this.realtime.setAuth(e))).catch((e=>console.warn("Failed to set initial Realtime auth token:",e))),this.rest=new b(new URL("rest/v1",s).href,{headers:this.headers,schema:a.db.schema,fetch:this.fetch,timeout:a.db.timeout,urlLengthLimit:a.db.urlLengthLimit}),this.storage=new Ge(this.storageUrl.href,this.headers,this.fetch,r?.storage),a.accessToken||this._listenForAuthEvents()}get functions(){return new o(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){if(this.accessToken)return await this.accessToken();let{data:e}=await this.auth.getSession();return e.session?.access_token??this.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:i,storageKey:a,flowType:n,lock:o,debug:l,throwOnError:h},c,u){let d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new qr({url:this.authUrl.href,headers:{...d,...c},storageKey:a,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:i,flowType:n,lock:o,debug:l,throwOnError:h,fetch:u,hasCustomAuthorizationHeader:Object.keys(this.headers).some((e=>"authorization"===e.toLowerCase()))})}_initRealtimeClient(e){return new te(this.realtimeUrl.href,{...e,params:{apikey:this.supabaseKey,...e?.params}})}_listenForAuthEvents(){return this.auth.onAuthStateChange(((e,t)=>{this._handleTokenChanged(e,"CLIENT",t?.access_token)}))}_handleTokenChanged(e,t,r){"TOKEN_REFRESHED"!==e&&"SIGNED_IN"!==e||this.changedAccessToken===r?"SIGNED_OUT"===e&&(this.realtime.setAuth(),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0):(this.changedAccessToken=r,this.realtime.setAuth(r))}};return function(){if(typeof window<"u")return!1;let e=globalThis.process;if(!e)return!1;let t=e.version;if(null==t)return!1;let r=t.match(/^v(\d+)\./);return!!r&&parseInt(r[1],10)<=18}()&&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"),e.AuthAdminApi=Dr,e.AuthApiError=ot,e.AuthClient=Br,e.AuthError=at,e.AuthImplicitGrantRedirectError=gt,e.AuthInvalidCredentialsError=ft,e.AuthInvalidJwtError=kt,e.AuthInvalidTokenResponseError=pt,e.AuthPKCECodeVerifierMissingError=wt,e.AuthPKCEGrantCodeExchangeError=yt,e.AuthRetryableFetchError=bt,e.AuthSessionMissingError=ut,e.AuthUnknownError=ht,e.AuthWeakPasswordError=vt,e.CustomAuthError=ct,Object.defineProperty(e,"FunctionRegion",{enumerable:!0,get:function(){return r}}),e.FunctionsError=s,e.FunctionsFetchError=i,e.FunctionsHttpError=n,e.FunctionsRelayError=a,e.GoTrueAdminApi=or,e.GoTrueClient=Lr,e.NavigatorLockAcquireTimeoutError=ur,e.PostgrestError=l,e.REALTIME_CHANNEL_STATES=J,Object.defineProperty(e,"REALTIME_LISTEN_TYPES",{enumerable:!0,get:function(){return G}}),Object.defineProperty(e,"REALTIME_POSTGRES_CHANGES_LISTEN_EVENT",{enumerable:!0,get:function(){return F}}),Object.defineProperty(e,"REALTIME_PRESENCE_LISTEN_EVENTS",{enumerable:!0,get:function(){return W}}),Object.defineProperty(e,"REALTIME_SUBSCRIBE_STATES",{enumerable:!0,get:function(){return H}}),e.RealtimeChannel=z,e.RealtimeClient=te,e.RealtimePresence=V,e.SIGN_OUT_SCOPES=nr,e.SupabaseClient=Kr,e.WebSocketFactory=_,e.createClient=(e,t,r)=>new Kr(e,t,r),e.isAuthApiError=lt,e.isAuthError=nt,e.isAuthImplicitGrantRedirectError=mt,e.isAuthPKCECodeVerifierMissingError=function(e){return nt(e)&&"AuthPKCECodeVerifierMissingError"===e.name},e.isAuthRetryableFetchError=_t,e.isAuthSessionMissingError=dt,e.isAuthWeakPasswordError=function(e){return nt(e)&&"AuthWeakPasswordError"===e.name},e.lockInternals=hr,e.navigatorLock=pr,e.processLock=async function(e,t,r){let s=fr[e]??Promise.resolve(),i=(async()=>{try{return await s,null}catch{return null}})(),a=(async()=>{let s=null;try{let r=t>=0?new Promise(((r,i)=>{s=setTimeout((()=>{console.warn(`@supabase/gotrue-js: Lock "${e}" acquisition timed out after ${t}ms. This may be caused by another operation holding the lock. Consider increasing lockAcquireTimeout or checking for stuck operations.`),i(new dr(`Acquiring process lock with name "${e}" timed out`))}),t)})):null;await Promise.race([i,r].filter((e=>e))),null!==s&&clearTimeout(s)}catch(e){if(null!==s&&clearTimeout(s),e&&e.isAcquireTimeout)throw e}return await r()})();return fr[e]=(async()=>{try{return await a}catch(e){if(e&&e.isAcquireTimeout){try{await s}catch{}return null}throw e}})(),await a},e}({}); //# sourceMappingURL=/sm/c507643d1b8eb4bf1d8147558dec7b6670ba29361827d22022a0855e78072818.map