/** * Minified by jsDelivr using Terser v5.39.0. * Original file: /npm/@supabase/supabase-js@2.89.0/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 a=0;for(s=Object.getOwnPropertySymbols(e);ae?(...t)=>e(...t):(...e)=>fetch(...e))(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return function(e,t,r,s){function a(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||=Promise)((function(r,i){function n(e){try{h(s.next(e))}catch(e){i(e)}}function o(e){try{h(s.throw(e))}catch(e){i(e)}}function h(e){e.done?r(e.value):a(e.value).then(n,o)}h((s=s.apply(e,t||[])).next())}))}(this,arguments,void 0,(function*(e,t={}){let r,s;try{let{headers:o,method:h,body:l,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)),l&&(o&&!Object.prototype.hasOwnProperty.call(o,"Content-Type")||!o)?typeof Blob<"u"&&l instanceof Blob||l instanceof ArrayBuffer?(d["Content-Type"]="application/octet-stream",f=l):"string"==typeof l?(d["Content-Type"]="text/plain",f=l):typeof FormData<"u"&&l instanceof FormData?f=l:(d["Content-Type"]="application/json",f=JSON.stringify(l)):f=l;let w=c;u&&(s=new AbortController,r=setTimeout((()=>s.abort()),u),c?(w=s.signal,c.addEventListener("abort",(()=>s.abort()))):w=s.signal);let y=yield this.fetch(g.toString(),{method:h||"POST",headers:Object.assign(Object.assign(Object.assign({},d),this.headers),o),body:f,signal:w}).catch((e=>{throw new a(e)})),m=y.headers.get("x-relay-error");if(m&&"true"===m)throw new i(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 i?e.context:void 0}}finally{r&&clearTimeout(r)}}))}},h=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}},l=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,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,a=null,i=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)/),h=e.headers.get("content-range")?.split("/");o&&h&&h.length>1&&(a=parseInt(h[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,a=null,i=406,n="Not Acceptable"):s=1===s.length?s[0]:null)}else{var o;let a=await e.text();try{t=JSON.parse(a),Array.isArray(t)&&404===e.status&&(s=[],t=null,i=200,n="OK")}catch{404===e.status&&""===a?(i=204,n="No Content"):t={message:a}}if(t&&r.isMaybeSingle&&!(null==t||null==(o=t.details))&&o.includes("0 rows")&&(t=null,i=200,n="OK"),t&&r.shouldThrowOnError)throw new h(t)}return{error:t,data:s,count:a,status:i,statusText:n}}));return this.shouldThrowOnError||(s=s.catch((e=>{let t="",r=e?.cause;if(r){let s=r?.message??"",a=r?.code??"";t=`${e?.name??"FetchError"}: ${e?.message}`,t+=`\n\nCaused by: ${r?.name??"Error"}: ${s}`,a&&(t+=` (${a})`),r?.stack&&(t+=`\n${r.stack}`)}else t=e?.stack??"";return{error:{message:`${e?.name??"FetchError"}: ${e?.message}`,details:t,hint:"",code:""},data:null,count:null,status:0,statusText:""}}))),s.then(e,t)}returns(){return this}overrideTypes(){return this}},c=class extends l{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:a=s}={}){let i=a?`${a}.order`:"order",n=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${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 a=void 0===s?"offset":`${s}.offset`,i=void 0===s?"limit":`${s}.limit`;return this.url.searchParams.set(a,`${e}`),this.url.searchParams.set(i,""+(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:a=!1,format:i="text"}={}){let n=[e?"analyze":null,t?"verbose":null,r?"settings":null,s?"buffers":null,a?"wal":null].filter(Boolean).join("|"),o=this.headers.get("Accept")??"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; 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 a="";"plain"===s?a="pl":"phrase"===s?a="ph":"websearch"===s&&(a="w");let i=void 0===r?"":`(${r})`;return this.url.searchParams.append(e,`${a}fts${i}.${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}){this.url=e,this.headers=new Headers(t),this.schema=r,this.fetch=s}select(e,t){let{head:r=!1,count:s}=t??{},a=r?"HEAD":"GET",i=!1,n=(e??"*").split("").map((e=>/\s/.test(e)&&!i?"":('"'===e&&(i=!i),e))).join("");return this.url.searchParams.set("select",n),s&&this.headers.append("Prefer",`count=${s}`),new d({method:a,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(e,{count:t,defaultToNull:r=!0}={}){if(t&&this.headers.append("Prefer",`count=${t}`),r||this.headers.append("Prefer","missing=default"),Array.isArray(e)){let t=e.reduce(((e,t)=>e.concat(Object.keys(t))),[]);if(t.length>0){let e=[...new Set(t)].map((e=>`"${e}"`));this.url.searchParams.set("columns",e.join(","))}}return new d({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch??fetch})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:s,defaultToNull:a=!0}={}){if(this.headers.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),void 0!==t&&this.url.searchParams.set("on_conflict",t),s&&this.headers.append("Prefer",`count=${s}`),a||this.headers.append("Prefer","missing=default"),Array.isArray(e)){let t=e.reduce(((e,t)=>e.concat(Object.keys(t))),[]);if(t.length>0){let e=[...new Set(t)].map((e=>`"${e}"`));this.url.searchParams.set("columns",e.join(","))}}return new d({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch??fetch})}update(e,{count:t}={}){return t&&this.headers.append("Prefer",`count=${t}`),new d({method:"PATCH",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch??fetch})}delete({count:e}={}){return e&&this.headers.append("Prefer",`count=${e}`),new d({method:"DELETE",url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch??fetch})}},f=class e{constructor(e,{headers:t={},schema:r,fetch:s}={}){this.url=e,this.headers=new Headers(t),this.schemaName=r,this.fetch=s}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})}schema(t){return new e(this.url,{headers:this.headers,schema:t,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:s=!1,count:a}={}){let i,n,o=new URL(`${this.url}/rpc/${e}`);r||s?(i=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)}))):(i="POST",n=t);let h=new Headers(this.headers);return a&&h.set("Prefer",`count=${a}`),new d({method:i,url:o,headers:h,schema:this.schemaName,body:n,fetch:this.fetch??fetch})}},g=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."};if(typeof process<"u"){let e=process.versions;if(e&&e.node){let t=e.node,r=parseInt(t.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 w="1.0.0",y=w,m=1e4;var b,_,k,v,E;!function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"}(b||={}),function(e){e.closed="closed",e.errored="errored",e.joined="joined",e.joining="joining",e.leaving="leaving"}(_||={}),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"}(k||={}),function(e){e.websocket="websocket"}(v||={}),function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"}(E||={});var S,T=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,a=e.ref??"",i=e.join_ref??"",n=e.payload.event,o=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},h=0===Object.keys(o).length?"":JSON.stringify(o);if(i.length>255)throw Error(`joinRef length ${i.length} exceeds maximum of 255`);if(a.length>255)throw Error(`ref length ${a.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(h.length>255)throw Error(`metadata length ${h.length} exceeds maximum of 255`);let l=this.USER_BROADCAST_PUSH_META_LENGTH+i.length+a.length+s.length+n.length+h.length,c=new ArrayBuffer(this.HEADER_LENGTH+l),u=new DataView(c),d=0;u.setUint8(d++,this.KINDS.userBroadcastPush),u.setUint8(d++,i.length),u.setUint8(d++,a.length),u.setUint8(d++,s.length),u.setUint8(d++,n.length),u.setUint8(d++,h.length),u.setUint8(d++,t),Array.from(i,(e=>u.setUint8(d++,e.charCodeAt(0)))),Array.from(a,(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(h,(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,a,i,n]=JSON.parse(e);return t({join_ref:r,ref:s,topic:a,event:i,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),a=t.getUint8(2),i=t.getUint8(3),n=t.getUint8(4),o=this.HEADER_LENGTH+4,h=r.decode(e.slice(o,o+s));o+=s;let l=r.decode(e.slice(o,o+a));o+=a;let c=r.decode(e.slice(o,o+i));o+=i;let u=e.slice(o,e.byteLength),d=n===this.JSON_ENCODING?JSON.parse(r.decode(u)):u,p={type:this.BROADCAST_EVENT,event:l,payload:d};return i>0&&(p.meta=JSON.parse(c)),{join_ref:null,ref:null,topic:h,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)))):{}}},O=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"}(S||={});let R=(e,t,r={})=>{let s=r.skipTypes??[];return t?Object.keys(t).reduce(((r,a)=>(r[a]=A(a,e,t,s),r)),{}):{}},A=(e,t,r,s)=>{let a=t.find((t=>t.name===e))?.type,i=r[e];return a&&!s.includes(a)?j(a,i):$(i)},j=(e,t)=>{if("_"===e.charAt(0))return x(t,e.slice(1,e.length));switch(e){case S.bool:return I(t);case S.float4:case S.float8:case S.int2:case S.int4:case S.int8:case S.numeric:case S.oid:return P(t);case S.json:case S.jsonb:return C(t);case S.timestamp:return N(t);case S.abstime:case S.date:case S.daterange:case S.int4range:case S.int8range:case S.money:case S.reltime:case S.text:case S.time:case S.timestamptz:case S.timetz:case S.tsrange:case S.tstzrange:default:return $(t)}},$=e=>e,I=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},P=e=>{if("string"==typeof e){let t=parseFloat(e);if(!Number.isNaN(t))return t}return e},C=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch{return e}return e},x=(e,t)=>{if("string"!=typeof e)return e;let r=e.length-1,s=e[r];if("{"===e[0]&&"}"===s){let s,a=e.slice(1,r);try{s=JSON.parse("["+a+"]")}catch{s=a?a.split(","):[]}return s.map((e=>j(t,e)))}return e},N=e=>"string"==typeof e?e.replace(" ","T"):e,U=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 D,L=class{constructor(e,t,r={},s=m){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"}(D||={});var B,q,K,W=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:a}=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=[],a()})),this.channel._on(s.diff,{},(t=>{let{onJoin:r,onLeave:s,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(t):(this.state=e.syncDiff(this.state,t,r,s),a())})),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 a=this.cloneDeep(e),i=this.transformState(t),n={},o={};return this.map(a,((e,t)=>{i[e]||(o[e]=t)})),this.map(i,((e,t)=>{let r=a[e];if(r){let s=t.map((e=>e.presence_ref)),a=r.map((e=>e.presence_ref)),i=t.filter((e=>a.indexOf(e.presence_ref)<0)),h=r.filter((e=>s.indexOf(e.presence_ref)<0));i.length>0&&(n[e]=i),h.length>0&&(o[e]=h)}else n[e]=t})),this.syncDiff(a,{joins:n,leaves:o},r,s)}static syncDiff(e,t,r,s){let{joins:a,leaves:i}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||=()=>{},s||=()=>{},this.map(a,((t,s)=>{let a=e[t]??[];if(e[t]=this.cloneDeep(s),a.length>0){let r=e[t].map((e=>e.presence_ref)),s=a.filter((e=>r.indexOf(e.presence_ref)<0));e[t].unshift(...s)}r(t,a,s)})),this.map(i,((t,r)=>{let a=e[t];if(!a)return;let i=r.map((e=>e.presence_ref));a=a.filter((e=>i.indexOf(e.presence_ref)<0)),e[t]=a,s(t,a,r),0===a.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"}(B||={}),function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"}(q||={}),function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"}(K||={});let M=_;var F=class e{constructor(e,t={config:{}},r){if(this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=_.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 L(this,k.join,this.params,this.timeout),this.rejoinTimer=new O((()=>this._rejoinUntilConnected()),this.socket.reconnectAfterMs),this.joinPush.receive("ok",(()=>{this.state=_.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=_.closed,this.socket._remove(this)})),this._onError((e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=_.errored,this.rejoinTimer.scheduleTimeout())})),this.joinPush.receive("timeout",(()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=_.errored,this.rejoinTimer.scheduleTimeout())})),this.joinPush.receive("error",(e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=_.errored,this.rejoinTimer.scheduleTimeout())})),this._on(k.reply,{},((e,t)=>{this._trigger(this._replyEventName(t),e)})),this.presence=new W(this),this.broadcastEndpointURL=U(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==_.closed){let{config:{broadcast:s,presence:a,private:i}}=this.params,n=this.bindings.postgres_changes?.map((e=>e.filter))??[],o=!!this.bindings[q.PRESENCE]&&this.bindings[q.PRESENCE].length>0||!0===this.params.config.presence?.enabled,h={},l={broadcast:s,presence:Object.assign(Object.assign({},a),{enabled:o}),postgres_changes:n,private:i};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError((e=>t?.(K.CHANNEL_ERROR,e))),this._onClose((()=>t?.(K.CLOSED))),this.updateJoinPayload(Object.assign({config:l},h)),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,a=s?.length??0,i=[];for(let n=0;n{this.state=_.errored,t?.(K.CHANNEL_ERROR,Error(JSON.stringify(Object.values(e).join(", ")||"error")))})).receive("timeout",(()=>{t?.(K.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===_.joined&&e===q.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 a={method:"POST",headers:s,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},i=await this._fetchWithTimeout(this.broadcastEndpointURL,a,r.timeout??this.timeout);if(202===i.status)return{success:!0};let n=i.statusText;try{let e=await i.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,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);let i={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:r,payload:s,private:this.private}]})};try{let e=await this._fetchWithTimeout(this.broadcastEndpointURL,i,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=_.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(k.close,"leave",this._joinRef())};this.joinPush.destroy();let r=null;return new Promise((s=>{r=new L(this,k.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=_.closed,this.bindings={}}async _fetchWithTimeout(e,t,r){let s=new AbortController,a=setTimeout((()=>s.abort()),r),i=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:s.signal}));return clearTimeout(a),i}_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 L(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,a;let i=e.toLocaleLowerCase(),{close:n,error:o,leave:h,join:l}=k;if(r&&[n,o,h,l].indexOf(i)>=0&&r!==this._joinRef())return;let c=this._onMessage(i,t,r);if(t&&!c)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(i)?null==(s=this.bindings.postgres_changes)||s.filter((e=>"*"===e.filter?.event||(e.filter?.event)?.toLocaleLowerCase()===i)).map((e=>e.callback(c,r))):null==(a=this.bindings[i])||a.filter((e=>{if(["broadcast","presence","postgres_changes"].includes(i)){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()===i})).map((e=>{if("object"==typeof c&&"ids"in c){let e=c.data,{schema:t,table:r,commit_timestamp:s,type:a,errors:i}=e,n={schema:t,table:r,commit_timestamp:s,eventType:a,new:{},old:{},errors:i};c=Object.assign(Object.assign({},n),this._getPayloadRecords(e))}e.callback(c,r)}))}_isClosed(){return this.state===_.closed}_isJoined(){return this.state===_.joined}_isJoining(){return this.state===_.joining}_isLeaving(){return this.state===_.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){let s=e.toLocaleLowerCase(),a={type:s,filter:t,callback:r};return this.bindings[s]?this.bindings[s].push(a):this.bindings[s]=[a],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(k.close,{},e)}_onError(e){this._on(k.error,{},(t=>e(t)))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=_.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return("INSERT"===e.type||"UPDATE"===e.type)&&(t.new=R(e.columns,e.record)),("UPDATE"===e.type||"DELETE"===e.type)&&(t.old=R(e.columns,e.old_record)),t}};let J=()=>{},G=25e3,V=10,H=100,z=[1e3,2e3,5e3,1e4];var Y=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=m,this.transport=null,this.heartbeatIntervalMs=G,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=J,this.ref=0,this.reconnectTimer=null,this.vsn=y,this.logger=J,this.conn=null,this.sendBuffer=[],this.serializer=new T,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=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}/${v.websocket}`,this.httpEndpoint=U(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=g.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 b.connecting:return E.Connecting;case b.open:return E.Open;case b.closing:return E.Closing;default:return E.Closed}}isConnected(){return this.connectionState()===E.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 F(`realtime:${e}`,t,this);return this.channels.push(r),r}}push(e){let{topic:t,event:r,payload:s,ref:a}=e,i=()=>{this.encode(e,(e=>{var t;null==(t=this.conn)||t.send(e)}))};this.log("push",`${t} ${r} (${a})`,s),this.isConnected()?i():this.sendBuffer.push(i)}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.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()}),H)}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)try{this.heartbeatCallback("ok"===e.payload.status?"ok":"error")}catch(e){this.log("error","error in heartbeat callback",e)}e.ref&&e.ref===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null);let{topic:t,event:r,payload:s,ref:a}=e,i=a?`(${a})`:"",n=s.status||"";this.log("receive",`${n} ${t} ${r} ${i}`.trim(),s),this.channels.filter((e=>e._isMember(t))).forEach((e=>e._trigger(r,s,a))),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===b.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===b.open||this.conn.readyState===b.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.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)}_triggerChanError(){this.channels.forEach((e=>e._trigger(k.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.89.0"};t&&e.updateJoinPayload(r),e.joinedOnce&&e._isJoined()&&e._push(k.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 O((async()=>{setTimeout((async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}),V)}),this.reconnectAfterMs)}_initializeOptions(e){switch(this.transport=e?.transport??null,this.timeout=e?.timeout??m,this.heartbeatIntervalMs=e?.heartbeatIntervalMs??G,this.worker=e?.worker??!1,this.accessToken=e?.accessToken??null,this.heartbeatCallback=e?.heartbeatCallback??J,this.vsn=e?.vsn??y,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=>z[e-1]||1e4),this.vsn){case w:this.encode=e?.encode??((e,t)=>t(JSON.stringify(e))),this.decode=e?.decode??((e,t)=>t(JSON.parse(e)));break;case"2.0.0":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}}},X=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 Q(e){let t=e.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:a,body:i,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,a),h=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),l=await t(o,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...h,...n},body:i?JSON.stringify(i):void 0}),c=await l.text(),u=(l.headers.get("content-type")||"").includes("application/json"),d=u&&c?JSON.parse(c):c;if(!l.ok){let e=u?d:void 0,t=e?.error;throw new X(t?.message??`Request failed with status ${l.status}`,{status:l.status,icebergType:t?.type,icebergCode:t?.code,details:e})}return{status:l.status,headers:l.headers,data:d}}}}function Z(e){return e.join("")}var ee=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){let t=e?{parent:Z(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/${Z(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Z(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Z(e.namespace)}`}),!0}catch(e){if(e instanceof X&&404===e.status)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof X&&409===e.status)return;throw e}}};function te(e){return e.join("")}var re=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/${te(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/${te(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/${te(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/${te(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/${te(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/${te(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(e){if(e instanceof X&&404===e.status)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(r){if(r instanceof X&&409===r.status)return await this.loadTable({namespace:e.namespace,name:t.name});throw r}}},se=class{constructor(e){let t="v1";e.catalogName&&(t+=`/${e.catalogName}`),this.client=Q({baseUrl:e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(","),this.namespaceOps=new ee(this.client,t),this.tableOps=new re(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)}},ae=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function ie(e){return"object"==typeof e&&!!e&&"__isStorageError"in e}var ne=class extends ae{constructor(e,t,r){super(e),this.name="StorageApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},oe=class extends ae{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};let he=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),le=e=>{if(Array.isArray(e))return e.map((e=>le(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]=le(r)})),t};function ce(e){return ce="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},ce(e)}function ue(e){var t=function(e,t){if("object"!=ce(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=ce(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==ce(t)?t:t+""}function de(e,t,r){return(t=ue(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function pe(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 fe(e){for(var t=1;te.msg||e.message||e.error_description||("string"==typeof e.error?e.error:e.error?.message)||JSON.stringify(e),we=async(e,t,r)=>{e instanceof await Response&&!r?.noResolveJson?e.json().then((r=>{let s=e.status||500,a=r?.statusCode||s+"";t(new ne(ge(r),s,a))})).catch((e=>{t(new oe(ge(e),e))})):t(new oe(ge(e),e))},ye=(e,t,r,s)=>{let a={method:e,headers:t?.headers||{}};return"GET"!==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)?(a.headers=fe({"Content-Type":"application/json"},t?.headers),a.body=JSON.stringify(s)):a.body=s,t?.duplex&&(a.duplex=t.duplex),fe(fe({},a),r)):a};async function me(e,t,r,s,a,i){return new Promise(((n,o)=>{e(r,ye(t,s,a,i)).then((e=>{if(!e.ok)throw e;return s?.noResolveJson?e:e.json()})).then((e=>n(e))).catch((e=>we(e,o,s)))}))}async function be(e,t,r,s){return me(e,"GET",t,r,s)}async function _e(e,t,r,s,a){return me(e,"POST",t,s,a,r)}async function ke(e,t,r,s,a){return me(e,"PUT",t,s,a,r)}async function ve(e,t,r,s,a){return me(e,"DELETE",t,s,a,r)}var Ee=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(ie(e))return{data:null,error:e};throw e}}};let Se;Se=Symbol.toStringTag;var Te=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[Se]="BlobDownloadBuilder",this.promise=null}asStream(){return new Ee(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(ie(e))return{data:null,error:e};throw e}}};let Oe={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Re={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var Ae=class{constructor(e,t={},r,s){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.bucketId=r,this.fetch=he(s)}throwOnError(){return this.shouldThrowOnError=!0,this}async uploadOrUpdate(e,t,r,s){var a=this;try{let i,n=fe(fe({},Re),s),o=fe(fe({},a.headers),"POST"===e&&{"x-upsert":String(n.upsert)}),h=n.metadata;typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",n.cacheControl),h&&i.append("metadata",a.encodeMetadata(h)),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",n.cacheControl),h&&!i.has("metadata")&&i.append("metadata",a.encodeMetadata(h))):(i=r,o["cache-control"]=`max-age=${n.cacheControl}`,o["content-type"]=n.contentType,h&&(o["x-metadata"]=a.toBase64(a.encodeMetadata(h))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&"object"==typeof i&&"pipe"in i&&"function"==typeof i.pipe)&&!n.duplex&&(n.duplex="half")),s?.headers&&(o=fe(fe({},o),s.headers));let l=a._removeEmptyFolders(t),c=a._getFinalPath(l),u=await("PUT"==e?ke:_e)(a.fetch,`${a.url}/object/${c}`,i,fe({headers:o},n?.duplex?{duplex:n.duplex}:{}));return{data:{path:l,id:u.Id,fullPath:u.Key},error:null}}catch(e){if(a.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async upload(e,t,r){return this.uploadOrUpdate("POST",e,t,r)}async uploadToSignedUrl(e,t,r,s){var a=this;let i=a._removeEmptyFolders(e),n=a._getFinalPath(i),o=new URL(a.url+`/object/upload/sign/${n}`);o.searchParams.set("token",t);try{let e,t=fe({upsert:Re.upsert},s),n=fe(fe({},a.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),{data:{path:i,fullPath:(await ke(a.fetch,o.toString(),e,{headers:n})).Key},error:null}}catch(e){if(a.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async createSignedUploadUrl(e,t){var r=this;try{let s=r._getFinalPath(e),a=fe({},r.headers);t?.upsert&&(a["x-upsert"]="true");let i=await _e(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:a}),n=new URL(r.url+i.url),o=n.searchParams.get("token");if(!o)throw new ae("No token returned by API");return{data:{signedUrl:n.toString(),path:e,token:o},error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async update(e,t,r){return this.uploadOrUpdate("PUT",e,t,r)}async move(e,t,r){var s=this;try{return{data:await _e(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:s.headers}),error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async copy(e,t,r){var s=this;try{return{data:{path:(await _e(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:s.headers})).Key},error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async createSignedUrl(e,t,r){var s=this;try{let a=s._getFinalPath(e),i=await _e(s.fetch,`${s.url}/object/sign/${a}`,fe({expiresIn:t},r?.transform?{transform:r.transform}:{}),{headers:s.headers}),n=r?.download?`&download=${!0===r.download?"":r.download}`:"";return i={signedUrl:encodeURI(`${s.url}${i.signedURL}${n}`)},{data:i,error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async createSignedUrls(e,t,r){var s=this;try{let a=await _e(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:t,paths:e},{headers:s.headers}),i=r?.download?`&download=${!0===r.download?"":r.download}`:"";return{data:a.map((e=>fe(fe({},e),{},{signedUrl:e.signedURL?encodeURI(`${s.url}${e.signedURL}${i}`):null}))),error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}download(e,t){let r=void 0===t?.transform?"object":"render/image/authenticated",s=this.transformOptsToQueryString(t?.transform||{}),a=s?`?${s}`:"",i=this._getFinalPath(e);return new Te((()=>be(this.fetch,`${this.url}/${r}/${i}${a}`,{headers:this.headers,noResolveJson:!0})),this.shouldThrowOnError)}async info(e){var t=this;let r=t._getFinalPath(e);try{return{data:le(await be(t.fetch,`${t.url}/object/info/${r}`,{headers:t.headers})),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async exists(e){var t=this;let r=t._getFinalPath(e);try{return await async function(e,t,r,s){return me(e,"HEAD",t,fe(fe({},r),{},{noResolveJson:!0}),s)}(t.fetch,`${t.url}/object/${r}`,{headers:t.headers}),{data:!0,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e)&&e instanceof oe){let t=e.originalError;if([400,404].includes(t?.status))return{data:!1,error:e}}throw e}}getPublicUrl(e,t){let r=this._getFinalPath(e),s=[],a=t?.download?`download=${!0===t.download?"":t.download}`:"";""!==a&&s.push(a);let i=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}/${i}/public/${r}${o}`)}}}async remove(e){var t=this;try{return{data:await ve(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async list(e,t,r){var s=this;try{let a=fe(fe(fe({},Oe),t),{},{prefix:e||""});return{data:await _e(s.fetch,`${s.url}/object/list/${s.bucketId}`,a,{headers:s.headers},r),error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async listV2(e,t){var r=this;try{let s=fe({},e);return{data:await _e(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,s,{headers:r.headers},t),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}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 je="2.89.0",$e={"X-Client-Info":`storage-js/${je}`};var Ie=class{constructor(e,t={},r,s){this.shouldThrowOnError=!1;let a=new URL(e);s?.useNewHostname&&/supabase\.(co|in|red)$/.test(a.hostname)&&!a.hostname.includes("storage.supabase.")&&(a.hostname=a.hostname.replace("supabase.","storage.supabase.")),this.url=a.href.replace(/\/$/,""),this.headers=fe(fe({},$e),t),this.fetch=he(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async listBuckets(e){var t=this;try{let r=t.listBucketOptionsToQueryString(e);return{data:await be(t.fetch,`${t.url}/bucket${r}`,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async getBucket(e){var t=this;try{return{data:await be(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async createBucket(e,t={public:!1}){var r=this;try{return{data:await _e(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}),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async updateBucket(e,t){var r=this;try{return{data:await ke(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}),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async emptyBucket(e){var t=this;try{return{data:await _e(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async deleteBucket(e){var t=this;try{return{data:await ve(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}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():""}},Pe=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=fe(fe({},$e),t),this.fetch=he(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async createBucket(e){var t=this;try{return{data:await _e(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async listBuckets(e){var t=this;try{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(),a=s?`${t.url}/bucket?${s}`:`${t.url}/bucket`;return{data:await be(t.fetch,a,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}async deleteBucket(e){var t=this;try{return{data:await ve(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ie(e))return{data:null,error:e};throw e}}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 ae("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 se({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}})}};let Ce={"X-Client-Info":`storage-js/${je}`,"Content-Type":"application/json"};var xe=class extends Error{constructor(e){super(e),this.__isStorageVectorsError=!0,this.name="StorageVectorsError"}};function Ne(e){return"object"==typeof e&&!!e&&"__isStorageVectorsError"in e}var Ue=class extends xe{constructor(e,t,r){super(e),this.name="StorageVectorsApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},De=class extends xe{constructor(e,t){super(e),this.name="StorageVectorsUnknownError",this.originalError=t}};let Le=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),Be=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),qe=(e,t,r,s)=>{let a={method:e,headers:t?.headers||{}};return"GET"!==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)?(a.headers=fe({"Content-Type":"application/json"},t?.headers),a.body=JSON.stringify(s)):a.body=s,fe(fe({},a),r)):a};async function Ke(e,t,r,s,a,i){return new Promise(((n,o)=>{e(r,qe(t,s,a,i)).then((e=>{if(!e.ok)throw e;if(s?.noResolveJson)return e;let t=e.headers.get("content-type");return t&&t.includes("application/json")?e.json():{}})).then((e=>n(e))).catch((e=>(async(e,t,r)=>{if(e&&"object"==typeof e&&"status"in e&&"ok"in e&&"number"==typeof e.status&&!r?.noResolveJson){let r=e.status||500,s=e;if("function"==typeof s.json)s.json().then((e=>{let s=e?.statusCode||e?.code||r+"";t(new Ue(Be(e),r,s))})).catch((()=>{let e=r+"";t(new Ue(s.statusText||`HTTP ${r} error`,r,e))}));else{let e=r+"";t(new Ue(s.statusText||`HTTP ${r} error`,r,e))}}else t(new De(Be(e),e))})(e,o,s)))}))}async function We(e,t,r,s,a){return Ke(e,"POST",t,s,a,r)}var Me=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=fe(fe({},Ce),t),this.fetch=Le(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async createIndex(e){var t=this;try{return{data:await We(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Ne(e))return{data:null,error:e};throw e}}async getIndex(e,t){var r=this;try{return{data:await We(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers}),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(Ne(e))return{data:null,error:e};throw e}}async listIndexes(e){var t=this;try{return{data:await We(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Ne(e))return{data:null,error:e};throw e}}async deleteIndex(e,t){var r=this;try{return{data:await We(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers})||{},error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(Ne(e))return{data:null,error:e};throw e}}},Fe=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=fe(fe({},Ce),t),this.fetch=Le(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async putVectors(e){var t=this;try{if(e.vectors.length<1||e.vectors.length>500)throw Error("Vector batch size must be between 1 and 500 items");return{data:await We(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Ne(e))return{data:null,error:e};throw e}}async getVectors(e){var t=this;try{return{data:await We(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Ne(e))return{data:null,error:e};throw e}}async listVectors(e){var t=this;try{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{data:await We(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Ne(e))return{data:null,error:e};throw e}}async queryVectors(e){var t=this;try{return{data:await We(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Ne(e))return{data:null,error:e};throw e}}async deleteVectors(e){var t=this;try{if(e.keys.length<1||e.keys.length>500)throw Error("Keys batch size must be between 1 and 500 items");return{data:await We(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Ne(e))return{data:null,error:e};throw e}}},Je=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=fe(fe({},Ce),t),this.fetch=Le(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async createBucket(e){var t=this;try{return{data:await We(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Ne(e))return{data:null,error:e};throw e}}async getBucket(e){var t=this;try{return{data:await We(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Ne(e))return{data:null,error:e};throw e}}async listBuckets(e={}){var t=this;try{return{data:await We(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Ne(e))return{data:null,error:e};throw e}}async deleteBucket(e){var t=this;try{return{data:await We(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Ne(e))return{data:null,error:e};throw e}}},Ge=class extends Je{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new Ve(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)}},Ve=class extends Me{constructor(e,t,r,s){super(e,t,s),this.vectorBucketName=r}async createIndex(e){return(()=>super.createIndex)().call(this,fe(fe({},e),{},{vectorBucketName:this.vectorBucketName}))}async listIndexes(e={}){return(()=>super.listIndexes)().call(this,fe(fe({},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 He(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},He=class extends Fe{constructor(e,t,r,s,a){super(e,t,a),this.vectorBucketName=r,this.indexName=s}async putVectors(e){var t=this;return(()=>super.putVectors)().call(t,fe(fe({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async getVectors(e){var t=this;return(()=>super.getVectors)().call(t,fe(fe({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async listVectors(e={}){var t=this;return(()=>super.listVectors)().call(t,fe(fe({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async queryVectors(e){var t=this;return(()=>super.queryVectors)().call(t,fe(fe({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async deleteVectors(e){var t=this;return(()=>super.deleteVectors)().call(t,fe(fe({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}},ze=class extends Ie{constructor(e,t={},r,s){super(e,t,r,s)}from(e){return new Ae(this.url,this.headers,e,this.fetch)}get vectors(){return new Ge(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Pe(this.url+"/iceberg",this.headers,this.fetch)}};let Ye="";Ye=typeof Deno<"u"?"deno":typeof document<"u"?"web":typeof navigator<"u"&&"ReactNative"===navigator.product?"react-native":"node";let Xe={headers:{"X-Client-Info":`supabase-js-${Ye}/2.89.0`}},Qe={schema:"public"},Ze={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},et={},tt=(e,t,r)=>{let s=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(r),a=Headers;return async(r,i)=>{let n=await t()??e,o=new a(i?.headers);return o.has("apikey")||o.set("apikey",e),o.has("Authorization")||o.set("Authorization",`Bearer ${n}`),s(r,{...i,headers:o})}};let rt="2.89.0",st=3e4,at=3*st,it={"X-Client-Info":`gotrue-js/${rt}`},nt="X-Supabase-Api-Version",ot={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},ht=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;var lt=class extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}};function ct(e){return"object"==typeof e&&!!e&&"__isAuthError"in e}var ut=class extends lt{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function dt(e){return ct(e)&&"AuthApiError"===e.name}var pt=class extends lt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},ft=class extends lt{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}},gt=class extends ft{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function wt(e){return ct(e)&&"AuthSessionMissingError"===e.name}var yt=class extends ft{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},mt=class extends ft{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},bt=class extends ft{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 _t(e){return ct(e)&&"AuthImplicitGrantRedirectError"===e.name}var kt=class extends ft{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}}},vt=class extends ft{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 Et=class extends ft{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function St(e){return ct(e)&&"AuthRetryableFetchError"===e.name}var Tt=class extends ft{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}};var Ot=class extends ft{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};let Rt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),At=" \t\n\r=".split(""),jt=(()=>{let e=Array(128);for(let t=0;t=6;)r(Rt[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(Rt[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6}function It(e,t,r){let s=jt[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 Pt(e){let t=[],r=e=>{t.push(String.fromCodePoint(e))},s={utf8seq:0,codepoint:0},a={queue:0,queuedBits:0},i=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 xt(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}Ct(s,t)}}(e,(e=>t.push(e))),new Uint8Array(t)}function Ut(e){let t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};return e.forEach((e=>$t(e,r,s))),$t(null,r,s),t.join("")}let Dt=()=>typeof window<"u"&&typeof document<"u",Lt={tested:!1,writable:!1},Bt=()=>{if(!Dt())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch{return!1}if(Lt.tested)return Lt.writable;let e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),Lt.tested=!0,Lt.writable=!0}catch{Lt.tested=!0,Lt.writable=!1}return Lt.writable};let qt=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),Kt=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},Wt=async(e,t)=>{let r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch{return r}},Mt=async(e,t)=>{await e.removeItem(t)};var Ft=class e{constructor(){this.promise=new e.promiseConstructor(((e,t)=>{this.resolve=e,this.reject=t}))}};function Jt(e){let t=e.split(".");if(3!==t.length)throw new Ot("Invalid JWT structure");for(let e=0;eString.fromCharCode(e))).join("")}(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Ht(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,Gt).join("")}(),a=s;r&&(a+="/PASSWORD_RECOVERY"),await Kt(e,`${t}-code-verifier`,a);let i=await Vt(s);return[i,s===i?"plain":"s256"]}Ft.promiseConstructor=Promise;let zt=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;let Yt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Xt(e){if(!Yt.test(e))throw Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Qt(){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 er=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),tr=[502,503,504];async function rr(e){if(!(e=>"object"==typeof e&&!!e&&"status"in e&&"ok"in e&&"json"in e&&"function"==typeof e.json)(e))throw new Et(er(e),0);if(tr.includes(e.status))throw new Et(er(e),e.status);let t;try{t=await e.json()}catch(e){throw new pt(er(e),e)}let r,s=function(e){let t=e.headers.get(nt);if(!t||!t.match(zt))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}(e);if(s&&s.getTime()>=ot["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 Tt(er(t),e.status,t.weak_password?.reasons||[]);if("session_not_found"===r)throw new gt}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 Tt(er(t),e.status,t.weak_password.reasons);throw new ut(er(t),e.status||500,r)}async function sr(e,t,r,s){let a=Object.assign({},s?.headers);a[nt]||(a[nt]=ot["2024-01-01"].name),s?.jwt&&(a.Authorization=`Bearer ${s.jwt}`);let i=s?.query??{};s?.redirectTo&&(i.redirect_to=s.redirectTo);let n=await async function(e,t,r,s,a,i){let n,o=((e,t,r,s)=>{let a={method:e,headers:t?.headers||{}};return"GET"===e?a:(a.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},t?.headers),a.body=JSON.stringify(s),Object.assign(Object.assign({},a),r))})(t,s,a,i);try{n=await e(r,Object.assign({},o))}catch(e){throw console.error(e),new Et(er(e),0)}if(n.ok||await rr(n),s?.noResolveJson)return n;try{return await n.json()}catch(e){await rr(e)}}(e,t,r+(Object.keys(i).length?"?"+new URLSearchParams(i).toString():""),{headers:a,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(n):{data:Object.assign({},n),error:null}}function ar(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 ir(e){let t=ar(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 nr(e){return{data:{user:e.user??e},error:null}}function or(e){return{data:e,error:null}}function hr(e){let{action_link:r,email_otp:s,hashed_token:a,redirect_to:i,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:a,redirect_to:i,verification_type:n},user:Object.assign({},o)},error:null}}function lr(e){return e}let cr=["global","local","others"];var ur=class{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=qt(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)}}async signOut(e,t=cr[0]){if(cr.indexOf(t)<0)throw Error(`@supabase/auth-js: Parameter scope must be one of ${cr.join(", ")}`);try{return await sr(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(ct(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await sr(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:nr})}catch(e){if(ct(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{let{options:r}=e,s=t(e,["options"]),a=Object.assign(Object.assign({},s),r);return"newEmail"in s&&(a.new_email=s?.newEmail,delete a.newEmail),await sr(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:a,headers:this.headers,xform:hr,redirectTo:r?.redirectTo})}catch(e){if(ct(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await sr(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:nr})}catch(e){if(ct(e))return{data:{user:null},error:e};throw e}}async listUsers(e){try{let t={nextPage:null,lastPage:0,total:0},r=await sr(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(e?.page)?.toString()??"",per_page:(e?.perPage)?.toString()??""},xform:lr});if(r.error)throw r.error;let s=await r.json(),a=r.headers.get("x-total-count")??0,i=r.headers.get("link")?.split(",")??[];return i.length>0&&(i.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(a)),{data:Object.assign(Object.assign({},s),t),error:null}}catch(e){if(ct(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){Xt(e);try{return await sr(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:nr})}catch(e){if(ct(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){Xt(e);try{return await sr(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:nr})}catch(e){if(ct(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){Xt(e);try{return await sr(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:nr})}catch(e){if(ct(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){Xt(e.userId);try{let{data:t,error:r}=await sr(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(ct(e))return{data:null,error:e};throw e}}async _deleteFactor(e){Xt(e.userId),Xt(e.id);try{return{data:await sr(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(ct(e))return{data:null,error:e};throw e}}async _listOAuthClients(e){try{let t={nextPage:null,lastPage:0,total:0},r=await sr(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(e?.page)?.toString()??"",per_page:(e?.perPage)?.toString()??""},xform:lr});if(r.error)throw r.error;let s=await r.json(),a=r.headers.get("x-total-count")??0,i=r.headers.get("link")?.split(",")??[];return i.length>0&&(i.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(a)),{data:Object.assign(Object.assign({},s),t),error:null}}catch(e){if(ct(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await sr(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(ct(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await sr(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(ct(e))return{data:null,error:e};throw e}}async _updateOAuthClient(e,t){try{return await sr(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(ct(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await sr(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(ct(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await sr(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(ct(e))return{data:null,error:e};throw e}}};function dr(e={}){return{getItem:t=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:t=>{delete e[t]}}}let pr={debug:!!(globalThis&&Bt()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"))};var fr=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},gr=class extends fr{},wr=class extends fr{};async function yr(e,t,r){pr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);let s=new globalThis.AbortController;return t>0&&setTimeout((()=>{s.abort(),pr.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)}),t),await Promise.resolve().then((()=>globalThis.navigator.locks.request(e,0===t?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},(async s=>{if(!s){if(0===t)throw pr.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new gr(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(pr.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()}pr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,s.name);try{return await r()}finally{pr.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",e,s.name)}}))))}let mr={};function br(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function _r(e){let t=(new TextEncoder).encode(e);return"0x"+Array.from(t,(e=>e.toString(16).padStart(2,"0"))).join("")}var kr=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}},vr=class extends kr{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}};function Er({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 kr({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 kr({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 kr({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 kr({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 kr({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new kr({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 kr({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new kr({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(!$r(t))return new kr({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(r.rp.id!==t)return new kr({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 kr({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 kr({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 kr({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function Sr({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 kr({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new kr({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("SecurityError"===e.name){let t=window.location.hostname;if(!$r(t))return new kr({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(r.rpId!==t)return new kr({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 kr({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 kr({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}let Tr=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 Or(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:a}=e,i=t(e,["challenge","user","excludeCredentials"]),n=xt(r).buffer,o=Object.assign(Object.assign({},s),{id:xt(s.id).buffer}),h=Object.assign(Object.assign({},i),{challenge:n,user:o});if(a&&a.length>0){h.excludeCredentials=Array(a.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 a of e)if(a)for(let e in a){let i=a[e];if(void 0!==i)if(Array.isArray(i))s[e]=i;else if(r(i))s[e]=i;else if(t(i)){let r=s[e];t(r)?s[e]=xr(r,i):s[e]=xr(i)}else s[e]=i}return s}function Nr(e,t){return xr(Pr,e,t||{})}var Ur=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},a){try{let{data:i,error:n}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!i)return{data:null,error:n};let o=s??Tr.createNewAbortSignal();if("create"===i.webauthn.type){let{user:e}=i.webauthn.credential_options.publicKey;e.name||=`${e.id}:${r}`,e.displayName||=e.name}switch(i.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 vr("Browser returned unexpected credential type",t)}:{data:null,error:new vr("Empty credential response",t)}}catch(t){return{data:null,error:Er({error:t,options:e})}}}({publicKey:Nr(i.webauthn.credential_options.publicKey,a?.create),signal:o});return t?{data:{factorId:e,challengeId:i.id,webauthn:{type:i.webauthn.type,credential_response:t}},error:null}:{data:null,error:r}}case"request":{let t=function(e,t){return xr(Cr,e,t||{})}(i.webauthn.credential_options.publicKey,a?.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 vr("Browser returned unexpected credential type",t)}:{data:null,error:new vr("Empty credential response",t)}}catch(t){return{data:null,error:Sr({error:t,options:e})}}}(Object.assign(Object.assign({},i.webauthn.credential_options),{publicKey:t,signal:o}));return r?{data:{factorId:e,challengeId:i.id,webauthn:{type:i.webauthn.type,credential_response:r}},error:null}:{data:null,error:s}}}}catch(e){return ct(e)?{data:null,error:e}:{data:null,error:new pt("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}={}},a){if(!t)return{data:null,error:new lt("rpId is required for WebAuthn authentication")};try{if(!Ir())return{data:null,error:new pt("Browser does not support WebAuthn",null)};let{data:i,error:n}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:a});if(!i)return{data:null,error:n};let{webauthn:o}=i;return this._verify({factorId:e,challengeId:i.challengeId,webauthn:{type:o.type,rpId:t,rpOrigins:r,credential_response:o.credential_response}})}catch(e){return ct(e)?{data:null,error:e}:{data:null,error:new pt("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}={}},a){if(!t)return{data:null,error:new lt("rpId is required for WebAuthn registration")};try{if(!Ir())return{data:null,error:new pt("Browser does not support WebAuthn",null)};let{data:i,error:n}=await this._enroll({friendlyName:e});if(!i)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:h}=await this._challenge({factorId:i.id,friendlyName:i.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:a});return o?this._verify({factorId:i.id,challengeId:o.challengeId,webauthn:{rpId:t,rpOrigins:r,type:o.webauthn.type,credential_response:o.webauthn.credential_response}}):{data:null,error:h}}catch(e){return ct(e)?{data:null,error:e}:{data:null,error:new pt("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 Dr={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:it,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1};async function Lr(e,t,r){return await r()}let Br={};var qr=class e{get jwks(){return Br[this.storageKey]?.jwks??{keys:[]}}set jwks(e){Br[this.storageKey]=Object.assign(Object.assign({},Br[this.storageKey]),{jwks:e})}get jwks_cached_at(){return Br[this.storageKey]?.cachedAt??-(2**53-1)}set jwks_cached_at(e){Br[this.storageKey]=Object.assign(Object.assign({},Br[this.storageKey]),{cachedAt:e})}constructor(t){var r;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let s=Object.assign(Object.assign({},Dr),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&&Dt()){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 ur({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=qt(s.fetch),this.lock=s.lock||Lr,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,this.throwOnError=s.throwOnError,s.lock?this.lock=s.lock:this.persistSession&&Dt()&&(null==globalThis?void 0:globalThis.navigator)?.locks?this.lock=yr:this.lock=Lr,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 Ur(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:Bt()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=dr(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=dr(this.memoryStorage)),Dt()&&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),await this._notifyAllSubscribers(e.data.event,e.data.session,!1)}))}this.initialize()}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${rt}) ${(new Date).toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise||=(async()=>await this._acquireLock(-1,(async()=>await this._initialize())))(),await this.initializePromise}async _initialize(){try{let e={},t="none";if(Dt()&&(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")),Dt()&&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),_t(s)){let e=s.details?.code;if("identity_already_exists"===e||"identity_not_found"===e||"single_identity_not_deletable"===e)return{error:s}}return await this._removeSession(),{error:s}}let{session:a,redirectType:i}=r;return this._debug("#_initialize()","detected session in URL",a,"redirect type",i),await this._saveSession(a),setTimeout((async()=>{"recovery"===i?await this._notifyAllSubscribers("PASSWORD_RECOVERY",a):await this._notifyAllSubscribers("SIGNED_IN",a)}),0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return ct(e)?this._returnResult({error:e}):this._returnResult({error:new pt("Unexpected error during initialization",e)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){try{let{data:t,error:r}=await sr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:e?.options?.data??{},gotrue_meta_security:{captcha_token:e?.options?.captchaToken}},xform:ar});if(r||!t)return this._returnResult({data:{user:null,session:null},error:r});let s=t.session,a=t.user;return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",s)),this._returnResult({data:{user:a,session:s},error:null})}catch(e){if(ct(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:a}=e,i=null,n=null;"pkce"===this.flowType&&([i,n]=await Ht(this.storage,this.storageKey)),t=await sr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:a?.emailRedirectTo,body:{email:r,password:s,data:a?.data??{},gotrue_meta_security:{captcha_token:a?.captchaToken},code_challenge:i,code_challenge_method:n},xform:ar})}else{if(!("phone"in e))throw new mt("You must provide either an email or phone number and a password");{let{phone:r,password:s,options:a}=e;t=await sr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:r,password:s,data:a?.data??{},channel:a?.channel??"sms",gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:ar})}}let{data:r,error:s}=t;if(s||!r)return await Mt(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:s});let a=r.session,i=r.user;return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",a)),this._returnResult({data:{user:i,session:a},error:null})}catch(e){if(await Mt(this.storage,`${this.storageKey}-code-verifier`),ct(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:a}=e;t=await sr(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:r,password:s,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:ir})}else{if(!("phone"in e))throw new mt("You must provide either an email or phone number and a password");{let{phone:r,password:s,options:a}=e;t=await sr(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:r,password:s,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:ir})}}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 yt;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(ct(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(-1,(async()=>this._exchangeCodeForSession(e)))}async signInWithWeb3(e){let{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){let t,r;if("message"in e)t=e.message,r=e.signature;else{let s,{chain:a,wallet:i,statement:n,options:o}=e;if(Dt())if("object"==typeof i)s=i;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 i||!o?.url)throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");s=i}let h=new URL(o?.url??window.location.href),l=await s.request({method:"eth_requestAccounts"}).then((e=>e)).catch((()=>{throw Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")}));if(!l||0===l.length)throw Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let c=br(l[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:a=new Date,nonce:i,notBefore:n,requestId:o,resources:h,scheme:l,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(i&&i.length<8)throw Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${i}`);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=`${l?`${l}://${r}`:r} wants you to sign in with your Ethereum account:\n${br(e.address)}\n\n${e.statement?`${e.statement}\n`:""}`,p=`URI: ${c}\nVersion: ${u}\nChain ID: ${t}${i?`\nNonce: ${i}`:""}\nIssued At: ${a.toISOString()}`;if(s&&(p+=`\nExpiration Time: ${s.toISOString()}`),n&&(p+=`\nNot Before: ${n.toISOString()}`),o&&(p+=`\nRequest ID: ${o}`),h){let e="\nResources:";for(let t of h){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:h.host,address:c,statement:n,uri:h.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:[_r(t),c]})}try{let{data:s,error:a}=await sr(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:ar});if(a)throw a;if(!s||!s.session||!s.user){let e=new yt;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:a})}catch(e){if(ct(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:a,wallet:i,statement:n,options:o}=e;if(Dt())if("object"==typeof i)s=i;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 i||!o?.url)throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");s=i}let h=new URL(o?.url??window.location.href);if("signIn"in s&&s.signIn){let e,a=await s.signIn(Object.assign(Object.assign(Object.assign({issuedAt:(new Date).toISOString()},o?.signInWithSolana),{version:"1",domain:h.host,uri:h.href}),n?{statement:n}:null));if(Array.isArray(a)&&a[0]&&"object"==typeof a[0])e=a[0];else{if(!(a&&"object"==typeof a&&"signedMessage"in a&&"signature"in a))throw Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");e=a}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=[`${h.host} wants you to sign in with your Solana account:`,s.publicKey.toBase58(),...n?["",n,""]:[""],"Version: 1",`URI: ${h.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:a}=await sr(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:t,signature:Ut(r)},e.options?.captchaToken?{gotrue_meta_security:{captcha_token:e.options?.captchaToken}}:null),xform:ar});if(a)throw a;if(!s||!s.session||!s.user){let e=new yt;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:a})}catch(e){if(ct(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e){let[t,r]=(await Wt(this.storage,`${this.storageKey}-code-verifier`)??"").split("/");try{if(!t&&"pkce"===this.flowType)throw new vt;let{data:s,error:a}=await sr(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:t},xform:ar});if(await Mt(this.storage,`${this.storageKey}-code-verifier`),a)throw a;if(!s||!s.session||!s.user){let e=new yt;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:a})}catch(e){if(await Mt(this.storage,`${this.storageKey}-code-verifier`),ct(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:a,nonce:i}=e,{data:n,error:o}=await sr(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:a,nonce:i,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:ar});if(o)return this._returnResult({data:{user:null,session:null},error:o});if(!n||!n.session||!n.user){let e=new yt;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(ct(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,a=null;"pkce"===this.flowType&&([s,a]=await Ht(this.storage,this.storageKey));let{error:i}=await sr(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:a},redirectTo:r?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:i})}if("phone"in e){let{phone:t,options:r}=e,{data:s,error:a}=await sr(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:a})}throw new mt("You must provide either an email or phone number.")}catch(e){if(await Mt(this.storage,`${this.storageKey}-code-verifier`),ct(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:a}=await sr(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:r}}),redirectTo:t,xform:ar});if(a)throw a;if(!s)throw Error("An error occurred on token verification.");let i=s.session,n=s.user;return i?.access_token&&(await this._saveSession(i),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",i)),this._returnResult({data:{user:n,session:i},error:null})}catch(e){if(ct(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 Ht(this.storage,this.storageKey));let s=await sr(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:or});return s.data?.url&&Dt()&&!e.options?.skipBrowserRedirect&&window.location.assign(s.data.url),this._returnResult(s)}catch(e){if(await Mt(this.storage,`${this.storageKey}-code-verifier`),ct(e))return this._returnResult({data:null,error:e});throw e}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,(async()=>await this._reauthenticate()))}async _reauthenticate(){try{return await this._useSession((async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new gt;let{error:s}=await sr(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(ct(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:a}=e,{error:i}=await sr(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:a?.captchaToken}},redirectTo:a?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:i})}if("phone"in e){let{phone:r,type:s,options:a}=e,{data:i,error:n}=await sr(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:a?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:i?.message_id},error:n})}throw new mt("You must provide either an email or phone number and a type")}catch(e){if(ct(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,(async()=>this._useSession((async e=>e))))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch{}})()),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 Wt(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:a}=await this._callRefreshToken(e.refresh_token);return a?this._returnResult({data:{session:null},error:a}):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(-1,(async()=>await this._getUser()));return t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await sr(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:nr}):await this._useSession((async e=>{let{data:t,error:r}=e;if(r)throw r;return t.session?.access_token||this.hasCustomAuthorizationHeader?await sr(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t.session?.access_token??void 0,xform:nr}):{data:{user:null},error:new gt}}))}catch(e){if(ct(e))return wt(e)&&(await this._removeSession(),await Mt(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(-1,(async()=>await this._updateUser(e,t)))}async _updateUser(e,t={}){try{return await this._useSession((async r=>{let{data:s,error:a}=r;if(a)throw a;if(!s.session)throw new gt;let i=s.session,n=null,o=null;"pkce"===this.flowType&&null!=e.email&&([n,o]=await Ht(this.storage,this.storageKey));let{data:h,error:l}=await sr(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:i.access_token,xform:nr});if(l)throw l;return i.user=h.user,await this._saveSession(i),await this._notifyAllSubscribers("USER_UPDATED",i),this._returnResult({data:{user:i.user},error:null})}))}catch(e){if(await Mt(this.storage,`${this.storageKey}-code-verifier`),ct(e))return this._returnResult({data:{user:null},error:e});throw e}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,(async()=>await this._setSession(e)))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new gt;let t=Date.now()/1e3,r=t,s=!0,a=null,{payload:i}=Jt(e.access_token);if(i.exp&&(r=i.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};a=t}else{let{data:s,error:i}=await this._getUser(e.access_token);if(i)throw i;a={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(a),await this._notifyAllSubscribers("SIGNED_IN",a)}return this._returnResult({data:{user:a.user,session:a},error:null})}catch(e){if(ct(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,(async()=>await this._refreshSession(e)))}async _refreshSession(e){try{return await this._useSession((async t=>{if(!e){let{data:r,error:s}=t;if(s)throw s;e=r.session??void 0}if(!e?.refresh_token)throw new gt;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(ct(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){try{if(!Dt())throw new bt("No browser detected.");if(e.error||e.error_description||e.error_code)throw new bt(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 kt("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new bt("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new kt("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:a,refresh_token:i,expires_in:n,expires_at:o,token_type:h}=e;if(!(a&&n&&i&&h))throw new bt("No session defined in URL");let l=Math.round(Date.now()/1e3),c=parseInt(n),u=l+c;o&&(u=parseInt(o));let d=u-l;1e3*d<=st&&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;l-p>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,u,l):l-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,l);let{data:f,error:g}=await this._getUser(a);if(g)throw g;let w={provider_token:r,provider_refresh_token:s,access_token:a,expires_in:c,expires_at:u,refresh_token:i,token_type:h,user:f.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:w,redirectType:e.type},error:null})}catch(e){if(ct(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 Wt(this.storage,`${this.storageKey}-code-verifier`);return!(!e.code||!t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,(async()=>await this._signOut(e)))}async _signOut({scope:e}={scope:"global"}){return await this._useSession((async t=>{let{data:r,error:s}=t;if(s)return this._returnResult({error:s});let a=r.session?.access_token;if(a){let{error:t}=await this.admin.signOut(a,e);if(t&&(!dt(t)||404!==t.status&&401!==t.status&&403!==t.status))return this._returnResult({error:t})}return"others"!==e&&(await this._removeSession(),await Mt(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(-1,(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 Ht(this.storage,this.storageKey,!0));try{return await sr(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 Mt(this.storage,`${this.storageKey}-code-verifier`),ct(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(ct(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 a=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 sr(this.fetch,"GET",a,{headers:this.headers,jwt:r.session?.access_token??void 0})}));if(r)throw r;return Dt()&&!e.options?.skipBrowserRedirect&&window.location.assign(t?.url),this._returnResult({data:{provider:e.provider,url:t?.url},error:null})}catch(t){if(ct(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:a,provider:i,token:n,access_token:o,nonce:h}=e,{data:l,error:c}=await sr(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:s?.access_token??void 0,body:{provider:i,id_token:n,access_token:o,nonce:h,link_identity:!0,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:ar});return c?this._returnResult({data:{user:null,session:null},error:c}):l&&l.session&&l.user?(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("USER_UPDATED",l.session)),this._returnResult({data:l,error:c})):this._returnResult({data:{user:null,session:null},error:new yt})}catch(e){if(await Mt(this.storage,`${this.storageKey}-code-verifier`),ct(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 sr(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:r.session?.access_token??void 0})}))}catch(e){if(ct(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 a=0;a<1/0;a++)try{let s=await e(a);if(!t(a,null,s))return void r(s)}catch(e){if(!t(a,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 sr(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:ar}))),((e,t)=>{let s=200*2**e;return t&&St(t)&&Date.now()+s-r{try{await r.callback(e,t)}catch(e){s.push(e)}}));if(await Promise.all(a),s.length>0){for(let e=0;ethis._autoRefreshTokenTick()),st);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():typeof Deno<"u"&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e),setTimeout((async()=>{await this.initializePromise,await this._autoRefreshTokenTick()}),0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,(async()=>{try{let e=Date.now();try{return await this._useSession((async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");let s=Math.floor((1e3*r.expires_at-e)/st);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${st}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 fr))throw e;this._debug("auto refresh token tick lock not available")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Dt()||null==window||!window.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),null==window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,(async()=>{"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 Ht(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 sr(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:r?.session?.access_token})}))}catch(e){if(ct(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 a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:"totp"===e.factorType?{issuer:e.issuer}:{}),{data:i,error:n}=await sr(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:r?.session?.access_token});return n?this._returnResult({data:null,error:n}):("totp"===e.factorType&&"totp"===i.type&&i?.totp?.qr_code&&(i.totp.qr_code=`data:image/svg+xml;utf-8,${i.totp.qr_code}`),this._returnResult({data:i,error:null}))}))}catch(e){if(ct(e))return this._returnResult({data:null,error:e});throw e}}async _verify(e){return this._acquireLock(-1,(async()=>{try{return await this._useSession((async t=>{let{data:r,error:s}=t;if(s)return this._returnResult({data:null,error:s});let a=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:"create"===e.webauthn.type?Ar(e.webauthn.credential_response):jr(e.webauthn.credential_response)})}:{code:e.code}),{data:i,error:n}=await sr(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:a,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)+i.expires_in},i)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",i),this._returnResult({data:i,error:n}))}))}catch(e){if(ct(e))return this._returnResult({data:null,error:e});throw e}}))}async _challenge(e){return this._acquireLock(-1,(async()=>{try{return await this._useSession((async t=>{let{data:r,error:s}=t;if(s)return this._returnResult({data:null,error:s});let a=await sr(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:r?.session?.access_token});if(a.error)return a;let{data:i}=a;if("webauthn"!==i.type)return{data:i,error:null};switch(i.webauthn.type){case"create":return{data:Object.assign(Object.assign({},i),{webauthn:Object.assign(Object.assign({},i.webauthn),{credential_options:Object.assign(Object.assign({},i.webauthn.credential_options),{publicKey:Or(i.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},i),{webauthn:Object.assign(Object.assign({},i.webauthn),{credential_options:Object.assign(Object.assign({},i.webauthn.credential_options),{publicKey:Rr(i.webauthn.credential_options.publicKey)})})}),error:null}}}))}catch(e){if(ct(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(){let{data:{session:e},error:t}=await this.getSession();if(t)return this._returnResult({data:null,error:t});if(!e)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:r}=Jt(e.access_token),s=null;r.aal&&(s=r.aal);let a=s;return(e.user.factors?.filter((e=>"verified"===e.status))??[]).length>0&&(a="aal2"),{data:{currentLevel:s,nextLevel:a,currentAuthenticationMethods:r.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 sr(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 gt})}))}catch(e){if(ct(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:a}=r;if(a)return this._returnResult({data:null,error:a});if(!s)return this._returnResult({data:null,error:new gt});let i=await sr(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 i.data&&i.data.redirect_url&&Dt()&&!t?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i}))}catch(e){if(ct(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:a}=r;if(a)return this._returnResult({data:null,error:a});if(!s)return this._returnResult({data:null,error:new gt});let i=await sr(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 i.data&&i.data.redirect_url&&Dt()&&!t?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i}))}catch(e){if(ct(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 sr(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 gt})}))}catch(e){if(ct(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 sr(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 gt})}))}catch(e){if(ct(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:a,error:i}=await sr(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;return a.keys&&0!==a.keys.length&&(this.jwks=a,this.jwks_cached_at=s,r=a.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:a,signature:i,raw:{header:n,payload:o}}=Jt(r);t?.allowExpired||function(e){if(!e)throw Error("Missing exp claim");if(e<=Math.floor(Date.now()/1e3))throw Error("JWT has expired")}(a.exp);let h=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(!h){let{error:e}=await this.getUser(r);if(e)throw e;return{data:{claims:a,header:s,signature:i},error:null}}let l=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",h,l,!0,["verify"]);if(!await crypto.subtle.verify(l,c,i,Nt(`${n}.${o}`)))throw new Ot("Invalid JWT signature");return{data:{claims:a,header:s,signature:i},error:null}}catch(e){if(ct(e))return this._returnResult({data:null,error:e});throw e}}};qr.nextInstanceID={};var Kr=qr,Wr=ur,Mr=Kr,Fr=class extends Mr{constructor(e){super(e)}},Jr=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 a=`sb-${s.hostname.split(".")[0]}-auth-token`,i=function(e,t){let{db:r,auth:s,realtime:a,global:i}=e,{db:n,auth:o,realtime:h,global:l}=t,c={db:{...n,...r},auth:{...o,...s},realtime:{...h,...a},storage:{},global:{...l,...i,headers:{...l?.headers??{},...i?.headers??{}}},accessToken:async()=>""};return e.accessToken?c.accessToken=e.accessToken:delete c.accessToken,c}(r??{},{db:Qe,realtime:et,auth:{...Ze,storageKey:a},global:Xe});this.storageKey=i.auth.storageKey??"",this.headers=i.global.headers??{},i.accessToken?(this.accessToken=i.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(i.auth??{},this.headers,i.global.fetch),this.fetch=tt(t,this._getAccessToken.bind(this),i.global.fetch),this.realtime=this._initRealtimeClient({headers:this.headers,accessToken:this._getAccessToken.bind(this),...i.realtime}),this.accessToken&&this.accessToken().then((e=>this.realtime.setAuth(e))).catch((e=>console.warn("Failed to set initial Realtime auth token:",e))),this.rest=new f(new URL("rest/v1",s).href,{headers:this.headers,schema:i.db.schema,fetch:this.fetch}),this.storage=new ze(this.storageUrl.href,this.headers,this.fetch,r?.storage),i.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:a,storageKey:i,flowType:n,lock:o,debug:h,throwOnError:l},c,u){let d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Fr({url:this.authUrl.href,headers:{...d,...c},storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:a,flowType:n,lock:o,debug:h,throwOnError:l,fetch:u,hasCustomAuthorizationHeader:Object.keys(this.headers).some((e=>"authorization"===e.toLowerCase()))})}_initRealtimeClient(e){return new Y(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"||typeof process>"u")return!1;let e=process.version;if(null==e)return!1;let t=e.match(/^v(\d+)\./);return!!t&&parseInt(t[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=Wr,e.AuthApiError=ut,e.AuthClient=Mr,e.AuthError=lt,e.AuthImplicitGrantRedirectError=bt,e.AuthInvalidCredentialsError=mt,e.AuthInvalidJwtError=Ot,e.AuthInvalidTokenResponseError=yt,e.AuthPKCECodeVerifierMissingError=vt,e.AuthPKCEGrantCodeExchangeError=kt,e.AuthRetryableFetchError=Et,e.AuthSessionMissingError=gt,e.AuthUnknownError=pt,e.AuthWeakPasswordError=Tt,e.CustomAuthError=ft,Object.defineProperty(e,"FunctionRegion",{enumerable:!0,get:function(){return r}}),e.FunctionsError=s,e.FunctionsFetchError=a,e.FunctionsHttpError=n,e.FunctionsRelayError=i,e.GoTrueAdminApi=ur,e.GoTrueClient=Kr,e.NavigatorLockAcquireTimeoutError=gr,e.PostgrestError=h,e.REALTIME_CHANNEL_STATES=M,Object.defineProperty(e,"REALTIME_LISTEN_TYPES",{enumerable:!0,get:function(){return q}}),Object.defineProperty(e,"REALTIME_POSTGRES_CHANGES_LISTEN_EVENT",{enumerable:!0,get:function(){return B}}),Object.defineProperty(e,"REALTIME_PRESENCE_LISTEN_EVENTS",{enumerable:!0,get:function(){return D}}),Object.defineProperty(e,"REALTIME_SUBSCRIBE_STATES",{enumerable:!0,get:function(){return K}}),e.RealtimeChannel=F,e.RealtimeClient=Y,e.RealtimePresence=W,e.SIGN_OUT_SCOPES=cr,e.SupabaseClient=Jr,e.WebSocketFactory=g,e.createClient=(e,t,r)=>new Jr(e,t,r),e.isAuthApiError=dt,e.isAuthError=ct,e.isAuthImplicitGrantRedirectError=_t,e.isAuthPKCECodeVerifierMissingError=function(e){return ct(e)&&"AuthPKCECodeVerifierMissingError"===e.name},e.isAuthRetryableFetchError=St,e.isAuthSessionMissingError=wt,e.isAuthWeakPasswordError=function(e){return ct(e)&&"AuthWeakPasswordError"===e.name},e.lockInternals=pr,e.navigatorLock=yr,e.processLock=async function(e,t,r){let s=mr[e]??Promise.resolve(),a=Promise.race([s.catch((()=>null)),t>=0?new Promise(((r,s)=>{setTimeout((()=>{s(new wr(`Acquiring process lock with name "${e}" timed out`))}),t)})):null].filter((e=>e))).catch((e=>{if(e&&e.isAcquireTimeout)throw e;return null})).then((async()=>await r()));return mr[e]=a.catch((async e=>{if(e&&e.isAcquireTimeout)return await s,null;throw e})),await a},e}({}); //# sourceMappingURL=/sm/709e3e77371d20934b0853d79f10d1b8a8107dc56e1c6c738b98a78962a83d89.map