import{_ as e,a as t}from"./ui-vendor-D7Fh8Ky-.js";class r extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}toJSON(){return{name:this.name,message:this.message,context:this.context}}}class s extends r{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class n extends r{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class i extends r{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var a,o;(o=a||(a={})).Any="any",o.ApNortheast1="ap-northeast-1",o.ApNortheast2="ap-northeast-2",o.ApSouth1="ap-south-1",o.ApSoutheast1="ap-southeast-1",o.ApSoutheast2="ap-southeast-2",o.CaCentral1="ca-central-1",o.EuCentral1="eu-central-1",o.EuWest1="eu-west-1",o.EuWest2="eu-west-2",o.EuWest3="eu-west-3",o.SaEast1="sa-east-1",o.UsEast1="us-east-1",o.UsWest1="us-west-1",o.UsWest2="us-west-2";class l{constructor(e,{headers:t={},customFetch:r,region:s=a.Any}={}){this.url=e,this.headers=t,this.region=s,this.fetch=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(t){return e(this,arguments,void 0,function*(e,t={}){var r;let a,o;try{const{headers:l,method:c,body:h,signal:u,timeout:d}=t;let p={},{region:f}=t;f||(f=this.region);const g=new URL(`${this.url}/${e}`);let y;f&&"any"!==f&&(p["x-region"]=f,g.searchParams.set("forceFunctionRegion",f));const m=!!l&&Object.keys(l).some(e=>"content-type"===e.toLowerCase());h&&!m?"undefined"!=typeof Blob&&h instanceof Blob||h instanceof ArrayBuffer?(p["Content-Type"]="application/octet-stream",y=h):"string"==typeof h?(p["Content-Type"]="text/plain",y=h):"undefined"!=typeof FormData&&h instanceof FormData?y=h:(p["Content-Type"]="application/json",y=JSON.stringify(h)):y=!h||"string"==typeof h||"undefined"!=typeof Blob&&h instanceof Blob||h instanceof ArrayBuffer||"undefined"!=typeof FormData&&h instanceof FormData?h:JSON.stringify(h);let w=u;d&&(o=new AbortController,a=setTimeout(()=>o.abort(),d),u?(w=o.signal,u.addEventListener("abort",()=>o.abort())):w=o.signal);const b=yield this.fetch(g.toString(),{method:c||"POST",headers:Object.assign(Object.assign(Object.assign({},p),this.headers),l),body:y,signal:w}).catch(e=>{throw new s(e)}),v=b.headers.get("x-relay-error");if(v&&"true"===v)throw new n(b);if(!b.ok)throw new i(b);let _,k=(null!==(r=b.headers.get("Content-Type"))&&void 0!==r?r:"text/plain").split(";")[0].trim();return _="application/json"===k?yield b.json():"application/octet-stream"===k||"application/pdf"===k?yield b.blob():"text/event-stream"===k?b:"multipart/form-data"===k?yield b.formData():yield b.text(),{data:_,error:null,response:b}}catch(l){return{data:null,error:l,response:l instanceof i||l instanceof n?l.context:void 0}}finally{a&&clearTimeout(a)}})}}const c=e=>Math.min(1e3*2**e,3e4),h=[520,503],u=["GET","HEAD","OPTIONS"];var d=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};function p(e,t){return new Promise(r=>{if(null==t?void 0:t.aborted)return void r();const s=setTimeout(()=>{null==t||t.removeEventListener("abort",n),r()},e);function n(){clearTimeout(s),r()}null==t||t.addEventListener("abort",n)})}function f(e,t,r,s){return!(!s||r>=3)&&(!!u.includes(e)&&!!h.includes(t))}var g=class{constructor(e){var t,r,s,n,i;this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=null!==(t=e.shouldThrowOnError)&&void 0!==t&&t,this.signal=e.signal,this.isMaybeSingle=null!==(r=e.isMaybeSingle)&&void 0!==r&&r,this.shouldStripNulls=null!==(s=e.shouldStripNulls)&&void 0!==s&&s,this.urlLengthLimit=null!==(n=e.urlLengthLimit)&&void 0!==n?n:8e3,this.retryEnabled=null===(i=e.retry)||void 0===i||i,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if("text/csv"===this.headers.get("Accept"))throw new Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}retry(e){return this.retryEnabled=e,this}then(e,t){var r=this;if(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"),this.shouldStripNulls){const e=this.headers.get("Accept");"application/vnd.pgrst.object+json"===e?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):e&&"application/json"!==e||this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}const s=this.fetch;let n=(async()=>{let e=0;for(;;){const a={};let o;r.headers.forEach((e,t)=>{a[t]=e}),e>0&&(a["X-Retry-Count"]=String(e));try{o=await s(r.url.toString(),{method:r.method,headers:a,body:JSON.stringify(r.body,(e,t)=>"bigint"==typeof t?t.toString():t),signal:r.signal})}catch(i){if("AbortError"===(null==i?void 0:i.name)||"ABORT_ERR"===(null==i?void 0:i.code))throw i;if(!u.includes(r.method))throw i;if(r.retryEnabled&&e<3){const t=c(e);e++,await p(t,r.signal);continue}throw i}if(f(r.method,o.status,e,r.retryEnabled)){var t,n;const s=null!==(t=null===(n=o.headers)||void 0===n?void 0:n.get("Retry-After"))&&void 0!==t?t:null,i=null!==s?1e3*Math.max(0,parseInt(s,10)||0):c(e);await o.text(),e++,await p(i,r.signal);continue}return await r.processResponse(o)}})();return this.shouldThrowOnError||(n=n.catch(e=>{var t;let r="",s="",n="";const i=null==e?void 0:e.cause;if(i){var a,o,l,c;const t=null!==(a=null==i?void 0:i.message)&&void 0!==a?a:"",s=null!==(o=null==i?void 0:i.code)&&void 0!==o?o:"";r=`${null!==(l=null==e?void 0:e.name)&&void 0!==l?l:"FetchError"}: ${null==e?void 0:e.message}`,r+=`\n\nCaused by: ${null!==(c=null==i?void 0:i.name)&&void 0!==c?c:"Error"}: ${t}`,s&&(r+=` (${s})`),(null==i?void 0:i.stack)&&(r+=`\n${i.stack}`)}else{var h;r=null!==(h=null==e?void 0:e.stack)&&void 0!==h?h:""}const u=this.url.toString().length;return"AbortError"===(null==e?void 0:e.name)||"ABORT_ERR"===(null==e?void 0:e.code)?(n="",s="Request was aborted (timeout or manual cancellation)",u>this.urlLengthLimit&&(s+=`. Note: Your request URL is ${u} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):"HeadersOverflowError"!==(null==i?void 0:i.name)&&"UND_ERR_HEADERS_OVERFLOW"!==(null==i?void 0:i.code)||(n="",s="HTTP headers exceeded server limits (typically 16KB)",u>this.urlLengthLimit&&(s+=`. Your request URL is ${u} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${null!==(t=null==e?void 0:e.name)&&void 0!==t?t:"FetchError"}: ${null==e?void 0:e.message}`,details:r,hint:s,code:n},data:null,count:null,status:0,statusText:""}})),n.then(e,t)}async processResponse(e){var t=this;let r=null,s=null,n=null,i=e.status,a=e.statusText;if(e.ok){var o,l;if("HEAD"!==t.method){var c;const n=await e.text();if(""===n);else if("text/csv"===t.headers.get("Accept"))s=n;else if(t.headers.get("Accept")&&(null===(c=t.headers.get("Accept"))||void 0===c?void 0:c.includes("application/vnd.pgrst.plan+text")))s=n;else try{s=JSON.parse(n)}catch(h){if(r={message:n},s=null,t.shouldThrowOnError)throw new d({message:n,details:"",hint:"",code:""})}}const u=null===(o=t.headers.get("Prefer"))||void 0===o?void 0:o.match(/count=(exact|planned|estimated)/),p=null===(l=e.headers.get("content-range"))||void 0===l?void 0:l.split("/");u&&p&&p.length>1&&(n=parseInt(p[1])),t.isMaybeSingle&&Array.isArray(s)&&(s.length>1?(r={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,n=null,i=406,a="Not Acceptable"):s=1===s.length?s[0]:null)}else{const n=await e.text();try{r=JSON.parse(n),Array.isArray(r)&&404===e.status&&(s=[],r=null,i=200,a="OK")}catch(u){404===e.status&&""===n?(i=204,a="No Content"):r={message:n}}if(r&&t.shouldThrowOnError)throw new d(r)}return{success:null===r,error:r,data:s,count:n,status:i,statusText:a}}returns(){return this}overrideTypes(){return this}},y=class extends g{throwOnError(){return super.throwOnError()}select(e){let t=!1;const r=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:s,referencedTable:n=s}={}){const i=n?`${n}.order`:"order",a=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${void 0===r?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){const s=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:s=r}={}){const n=void 0===s?"offset":`${s}.offset`,i=void 0===s?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${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 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:n=!1,format:i="text"}={}){var a;const o=[e?"analyze":null,t?"verbose":null,r?"settings":null,s?"buffers":null,n?"wal":null].filter(Boolean).join("|"),l=null!==(a=this.headers.get("Accept"))&&void 0!==a?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${l}"; options=${o};`),this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};const m=new RegExp("[,()]");var w=class extends y{throwOnError(){return super.throwOnError()}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){const r=Array.from(new Set(t)).map(e=>"string"==typeof e&&m.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}notIn(e,t){const r=Array.from(new Set(t)).map(e=>"string"==typeof e&&m.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 n="";"plain"===s?n="pl":"phrase"===s?n="ph":"websearch"===s&&(n="w");const i=void 0===r?"":`(${r})`;return this.url.searchParams.append(e,`${n}fts${i}.${t}`),this}match(e){return Object.entries(e).filter(([e,t])=>void 0!==t).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){const s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}},b=class{constructor(e,{headers:t={},schema:r,fetch:s,urlLengthLimit:n=8e3,retry:i}){this.url=e,this.headers=new Headers(t),this.schema=r,this.fetch=s,this.urlLengthLimit=n,this.retry=i}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){const{head:r=!1,count:s}=null!=t?t:{},n=r?"HEAD":"GET";let i=!1;const a=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!i?"":('"'===e&&(i=!i),e)).join(""),{url:o,headers:l}=this.cloneRequestState();return o.searchParams.set("select",a),s&&l.append("Prefer",`count=${s}`),new w({method:n,url:o,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(e,{count:t,defaultToNull:r=!0}={}){var s;const{url:n,headers:i}=this.cloneRequestState();if(t&&i.append("Prefer",`count=${t}`),r||i.append("Prefer","missing=default"),Array.isArray(e)){const t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){const e=[...new Set(t)].map(e=>`"${e}"`);n.searchParams.set("columns",e.join(","))}}return new w({method:"POST",url:n,headers:i,schema:this.schema,body:e,fetch:null!==(s=this.fetch)&&void 0!==s?s:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:s,defaultToNull:n=!0}={}){var i;const{url:a,headers:o}=this.cloneRequestState();if(o.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),void 0!==t&&a.searchParams.set("on_conflict",t),s&&o.append("Prefer",`count=${s}`),n||o.append("Prefer","missing=default"),Array.isArray(e)){const t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){const e=[...new Set(t)].map(e=>`"${e}"`);a.searchParams.set("columns",e.join(","))}}return new w({method:"POST",url:a,headers:o,schema:this.schema,body:e,fetch:null!==(i=this.fetch)&&void 0!==i?i:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(e,{count:t}={}){var r;const{url:s,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new w({method:"PATCH",url:s,headers:n,schema:this.schema,body:e,fetch:null!==(r=this.fetch)&&void 0!==r?r:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:e}={}){var t;const{url:r,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new w({method:"DELETE",url:r,headers:s,schema:this.schema,fetch:null!==(t=this.fetch)&&void 0!==t?t:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function v(e){return(v="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})(e)}function _(e){var t=function(e,t){if("object"!=v(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t);if("object"!=v(s))return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==v(t)?t:t+""}function k(e,t,r){return(t=_(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function S(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 T(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?S(Object(r),!0).forEach(function(t){k(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):S(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var E=class e{constructor(e,{headers:t={},schema:r,fetch:s,timeout:n,urlLengthLimit:i=8e3,retry:a}={}){this.url=e,this.headers=new Headers(t),this.schemaName=r,this.urlLengthLimit=i;const o=null!=s?s:globalThis.fetch;this.fetch=void 0!==n&&n>0?(e,t)=>{const r=new AbortController,s=setTimeout(()=>r.abort(),n),i=null==t?void 0:t.signal;if(i){if(i.aborted)return clearTimeout(s),o(e,t);const n=()=>{clearTimeout(s),r.abort()};return i.addEventListener("abort",n,{once:!0}),o(e,T(T({},t),{},{signal:r.signal})).finally(()=>{clearTimeout(s),i.removeEventListener("abort",n)})}return o(e,T(T({},t),{},{signal:r.signal})).finally(()=>clearTimeout(s))}:o,this.retry=a}from(e){if(!e||"string"!=typeof e||""===e.trim())throw new Error("Invalid relation name: relation must be a non-empty string.");return new b(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(t){return new e(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(e,t={},{head:r=!1,get:s=!1,count:n}={}){var i;let a;const o=new URL(`${this.url}/rpc/${e}`);let l;const c=e=>null!==e&&"object"==typeof e&&(!Array.isArray(e)||e.some(c)),h=r&&Object.values(t).some(c);h?(a="POST",l=t):r||s?(a=r?"HEAD":"GET",Object.entries(t).filter(([e,t])=>void 0!==t).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}`]).forEach(([e,t])=>{o.searchParams.append(e,t)})):(a="POST",l=t);const u=new Headers(this.headers);return h?u.set("Prefer",n?`count=${n},return=minimal`:"return=minimal"):n&&u.set("Prefer",`count=${n}`),new w({method:a,url:o,headers:u,schema:this.schemaName,body:l,fetch:null!==(i=this.fetch)&&void 0!==i?i:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};class R{constructor(){}static detectEnvironment(){var e;if("undefined"!=typeof WebSocket)return{type:"native",wsConstructor:WebSocket};const t=globalThis;if("undefined"!=typeof globalThis&&void 0!==t.WebSocket)return{type:"native",wsConstructor:t.WebSocket};const r="undefined"!=typeof global?global:void 0;if(r&&void 0!==r.WebSocket)return{type:"native",wsConstructor:r.WebSocket};if("undefined"!=typeof globalThis&&void 0!==t.WebSocketPair&&void 0===globalThis.WebSocket)return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if("undefined"!=typeof globalThis&&t.EdgeRuntime||"undefined"!=typeof navigator&&(null===(e=navigator.userAgent)||void 0===e?void 0:e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const s=globalThis.process;if(s){const e=s.versions;if(e&&e.node)return{type:"unsupported",error:"Node.js detected but native WebSocket not found.",workaround:"Ensure you are running Node.js 22+ or provide a WebSocket implementation via the transport option."}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.wsConstructor)return e.wsConstructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=`\n\nSuggested solution: ${e.workaround}`),new Error(t)}static isWebSocketSupported(){try{return"native"===this.detectEnvironment().type}catch(e){return!1}}}const A="2.0.0",O=A,P="closed",j="errored",C="joined",$="joining",I="leaving",x={close:"phx_close",error:"phx_error",join:"phx_join",leave:"phx_leave",access_token:"access_token"},N="connecting",U="closing",L="closed";class D{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=null!=e?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){var t;return this._isArrayBuffer(null===(t=e.payload)||void 0===t?void 0:t.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,r;const s=null!==(r=null===(t=e.payload)||void 0===t?void 0:t.payload)&&void 0!==r?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,s)}_encodeJsonUserBroadcastPush(e){var t,r;const s=null!==(r=null===(t=e.payload)||void 0===t?void 0:t.payload)&&void 0!==r?r:{},n=(new TextEncoder).encode(JSON.stringify(s)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,n)}_encodeUserBroadcastPush(e,t,r){var s,n;const i=e.topic,a=null!==(s=e.ref)&&void 0!==s?s:"",o=null!==(n=e.join_ref)&&void 0!==n?n:"",l=e.payload.event,c=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},h=0===Object.keys(c).length?"":JSON.stringify(c);if(o.length>255)throw new Error(`joinRef length ${o.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(i.length>255)throw new Error(`topic length ${i.length} exceeds maximum of 255`);if(l.length>255)throw new Error(`userEvent length ${l.length} exceeds maximum of 255`);if(h.length>255)throw new Error(`metadata length ${h.length} exceeds maximum of 255`);const u=this.USER_BROADCAST_PUSH_META_LENGTH+o.length+a.length+i.length+l.length+h.length,d=new ArrayBuffer(this.HEADER_LENGTH+u);let p=new DataView(d),f=0;p.setUint8(f++,this.KINDS.userBroadcastPush),p.setUint8(f++,o.length),p.setUint8(f++,a.length),p.setUint8(f++,i.length),p.setUint8(f++,l.length),p.setUint8(f++,h.length),p.setUint8(f++,t),Array.from(o,e=>p.setUint8(f++,e.charCodeAt(0))),Array.from(a,e=>p.setUint8(f++,e.charCodeAt(0))),Array.from(i,e=>p.setUint8(f++,e.charCodeAt(0))),Array.from(l,e=>p.setUint8(f++,e.charCodeAt(0))),Array.from(h,e=>p.setUint8(f++,e.charCodeAt(0)));var g=new Uint8Array(d.byteLength+r.byteLength);return g.set(new Uint8Array(d),0),g.set(new Uint8Array(r),d.byteLength),g.buffer}decode(e,t){if(this._isArrayBuffer(e)){return t(this._binaryDecode(e))}if("string"==typeof e){const r=JSON.parse(e),[s,n,i,a,o]=r;return t({join_ref:s,ref:n,topic:i,event:a,payload:o})}return t({})}_binaryDecode(e){const 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){const s=t.getUint8(1),n=t.getUint8(2),i=t.getUint8(3),a=t.getUint8(4);let o=this.HEADER_LENGTH+4;const l=r.decode(e.slice(o,o+s));o+=s;const c=r.decode(e.slice(o,o+n));o+=n;const h=r.decode(e.slice(o,o+i));o+=i;const u=e.slice(o,e.byteLength),d=a===this.JSON_ENCODING?JSON.parse(r.decode(u)):u,p={type:this.BROADCAST_EVENT,event:c,payload:d};return i>0&&(p.meta=JSON.parse(h)),{join_ref:null,ref:null,topic:l,event:this.BROADCAST_EVENT,payload:p}}_isArrayBuffer(e){var t;return e instanceof ArrayBuffer||"ArrayBuffer"===(null===(t=null==e?void 0:e.constructor)||void 0===t?void 0:t.name)}_pick(e,t){return e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e))):{}}}var B,q;(q=B||(B={})).abstime="abstime",q.bool="bool",q.date="date",q.daterange="daterange",q.float4="float4",q.float8="float8",q.int2="int2",q.int4="int4",q.int4range="int4range",q.int8="int8",q.int8range="int8range",q.json="json",q.jsonb="jsonb",q.money="money",q.numeric="numeric",q.oid="oid",q.reltime="reltime",q.text="text",q.time="time",q.timestamp="timestamp",q.timestamptz="timestamptz",q.timetz="timetz",q.tsrange="tsrange",q.tstzrange="tstzrange";const H=(e,t,r={})=>{var s;const n=null!==(s=r.skipTypes)&&void 0!==s?s:[];return t?Object.keys(t).reduce((r,s)=>(r[s]=K(s,e,t,n),r),{}):{}},K=(e,t,r,s)=>{const n=t.find(t=>t.name===e),i=null==n?void 0:n.type,a=r[e];return i&&!s.includes(i)?M(i,a):W(a)},M=(e,t)=>{if("_"===e.charAt(0)){const r=e.slice(1,e.length);return z(t,r)}switch(e){case B.bool:return F(t);case B.float4:case B.float8:case B.int2:case B.int4:case B.int8:case B.numeric:case B.oid:return J(t);case B.json:case B.jsonb:return G(t);case B.timestamp:return V(t);case B.abstime:case B.date:case B.daterange:case B.int4range:case B.int8range:case B.money:case B.reltime:case B.text:case B.time:case B.timestamptz:case B.timetz:case B.tsrange:case B.tstzrange:default:return W(t)}},W=e=>e,F=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},J=e=>{if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},G=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(t){return e}return e},z=(e,t)=>{if("string"!=typeof e)return e;const r=e.length-1,s=e[r];if("{"===e[0]&&"}"===s){let s;const i=e.slice(1,r);try{s=JSON.parse("["+i+"]")}catch(n){s=i?i.split(","):[]}return s.map(e=>M(t,e))}return e},V=e=>"string"==typeof e?e.replace(" ","T"):e,Y=e=>{const t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),""===t.pathname||"/"===t.pathname?t.pathname="/api/broadcast":t.pathname=t.pathname+"/api/broadcast",t.href};var X,Q,Z=e=>{if("function"==typeof e)return e;return function(){return e}},ee="undefined"!=typeof self?self:null,te="undefined"!=typeof window?window:null,re=ee||te||globalThis,se=0,ne=1,ie=2,ae=3,oe="closed",le="errored",ce="joined",he="joining",ue="leaving",de="phx_close",pe="phx_error",fe="phx_join",ge="phx_reply",ye="phx_leave",me="longpoll",we="websocket",be=4,ve="base64url.bearer.phx.",_e=class{constructor(e,t,r,s){this.channel=e,this.event=t,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=s,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(e){this.timeout=e,this.reset(),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()}))}receive(e,t){return this.hasReceived(e)&&t(this.receivedResp.response),this.recHooks.push({status:e,callback:t}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:e,response:t,_ref:r}){this.recHooks.filter(t=>t.status===e).forEach(e=>e.callback(t))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,e=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=e,this.matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}trigger(e,t){this.channel.trigger(this.refEvent,{status:e,response:t})}},ke=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},Se=class{constructor(e,t,r){this.state=oe,this.topic=e,this.params=Z(t||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new _e(this,fe,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new ke(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=ce,this.rejoinTimer.reset(),this.pushBuffer.forEach(e=>e.send()),this.pushBuffer=[]}),this.joinPush.receive("error",e=>{this.state=le,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,e),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=oe,this.socket.remove(this)}),this.onError(e=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,e),this.isJoining()&&this.joinPush.reset(),this.state=le,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new _e(this,ye,Z({}),this.timeout).send(),this.state=le,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(ge,(e,t)=>{this.trigger(this.replyEventName(t),e)})}join(e=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=e,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=oe,this.bindings=[]}onClose(e){this.on(de,e)}onError(e){return this.on(pe,t=>e(t))}on(e,t){let r=this.bindingRef++;return this.bindings.push({event:e,ref:r,callback:t}),r}off(e,t){this.bindings=this.bindings.filter(r=>!(r.event===e&&(void 0===t||t===r.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(e,t,r=this.timeout){if(t=t||{},!this.joinedOnce)throw new Error(`tried to push '${e}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let s=new _e(this,e,function(){return t},r);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}leave(e=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=ue;let t=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(de,"leave")},r=new _e(this,ye,Z({}),e);return r.receive("ok",()=>t()).receive("timeout",()=>t()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(e,t,r){return t}filterBindings(e,t,r){return!0}isMember(e,t,r,s){return this.topic===e&&(!s||s===this.joinRef()||(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:e,event:t,payload:r,joinRef:s}),!1))}joinRef(){return this.joinPush.ref}rejoin(e=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=he,this.joinPush.resend(e))}trigger(e,t,r,s){let n=this.onMessage(e,t,r,s);if(t&&!n)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let i=this.bindings.filter(s=>s.event===e&&this.filterBindings(s,t,r));for(let a=0;a<i.length;a++){i[a].callback(n,r,s||this.joinRef())}}replyEventName(e){return`chan_reply_${e}`}isClosed(){return this.state===oe}isErrored(){return this.state===le}isJoined(){return this.state===ce}isJoining(){return this.state===he}isLeaving(){return this.state===ue}},Te=class{static request(e,t,r,s,n,i,a){if(re.XDomainRequest){let r=new re.XDomainRequest;return this.xdomainRequest(r,e,t,s,n,i,a)}if(re.XMLHttpRequest){let o=new re.XMLHttpRequest;return this.xhrRequest(o,e,t,r,s,n,i,a)}if(re.fetch&&re.AbortController)return this.fetchRequest(e,t,r,s,n,i,a);throw new Error("No suitable XMLHttpRequest implementation found")}static fetchRequest(e,t,r,s,n,i,a){let o={method:e,headers:r,body:s},l=null;return n&&(l=new AbortController,setTimeout(()=>l.abort(),n),o.signal=l.signal),re.fetch(t,o).then(e=>e.text()).then(e=>this.parseJSON(e)).then(e=>a&&a(e)).catch(e=>{"AbortError"===e.name&&i?i():a&&a(null)}),l}static xdomainRequest(e,t,r,s,n,i,a){return e.timeout=n,e.open(t,r),e.onload=()=>{let t=this.parseJSON(e.responseText);a&&a(t)},i&&(e.ontimeout=i),e.onprogress=()=>{},e.send(s),e}static xhrRequest(e,t,r,s,n,i,a,o){e.open(t,r,!0),e.timeout=i;for(let[l,c]of Object.entries(s))e.setRequestHeader(l,c);return e.onerror=()=>o&&o(null),e.onreadystatechange=()=>{if(e.readyState===be&&o){let t=this.parseJSON(e.responseText);o(t)}},a&&(e.ontimeout=a),e.send(n),e}static parseJSON(e){if(!e||""===e)return null;try{return JSON.parse(e)}catch{return console,null}}static serialize(e,t){let r=[];for(var s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let n=t?`${t}[${s}]`:s,i=e[s];"object"==typeof i?r.push(this.serialize(i,n)):r.push(encodeURIComponent(n)+"="+encodeURIComponent(i))}return r.join("&")}static appendParams(e,t){if(0===Object.keys(t).length)return e;let r=e.match(/\?/)?"&":"?";return`${e}${r}${this.serialize(t)}`}},Ee=class{constructor(e,t){t&&2===t.length&&t[1].startsWith(ve)&&(this.authToken=atob(t[1].slice(21))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(e),this.readyState=se,setTimeout(()=>this.poll(),0)}normalizeEndpoint(e){return e.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+we),"$1/"+me)}endpointURL(){return Te.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,r){this.close(e,t,r),this.readyState=se}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===ne||this.readyState===se}poll(){const e={Accept:"application/json"};this.authToken&&(e["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",e,null,()=>this.ontimeout(),e=>{if(e){var{status:t,token:r,messages:s}=e;if(410===t&&null!==this.token)return this.onerror(410),void this.closeAndRetry(3410,"session_gone",!1);this.token=r}else t=0;switch(t){case 200:s.forEach(e=>{setTimeout(()=>this.onmessage({data:e}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=ne,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${t}`)}})}send(e){"string"!=typeof e&&(e=(e=>{let t="",r=new Uint8Array(e),s=r.byteLength;for(let n=0;n<s;n++)t+=String.fromCharCode(r[n]);return btoa(t)})(e)),this.currentBatch?this.currentBatch.push(e):this.awaitingBatchAck?this.batchBuffer.push(e):(this.currentBatch=[e],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(e){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},e.join("\n"),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,e&&200===e.status?this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[]):(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1))})}close(e,t,r){for(let n of this.reqs)n.abort();this.readyState=ae;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:e,reason:t,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,"undefined"!=typeof CloseEvent?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(e,t,r,s,n){let i;i=Te.request(e,this.endpointURL(),t,r,this.timeout,()=>{this.reqs.delete(i),s()},e=>{this.reqs.delete(i),this.isActive()&&n(e)}),this.reqs.add(i)}},Re=class e{constructor(t,r={}){let s=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=t,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(s.state,t=>{let{onJoin:r,onLeave:s,onSync:n}=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=[],n()}),this.channel.on(s.diff,t=>{let{onJoin:r,onLeave:s,onSync:n}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(t):(this.state=e.syncDiff(this.state,t,r,s),n())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(t){return e.list(this.state,t)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,t,r,s){let n=this.clone(e),i={},a={};return this.map(n,(e,r)=>{t[e]||(a[e]=r)}),this.map(t,(e,t)=>{let r=n[e];if(r){let s=t.metas.map(e=>e.phx_ref),n=r.metas.map(e=>e.phx_ref),o=t.metas.filter(e=>n.indexOf(e.phx_ref)<0),l=r.metas.filter(e=>s.indexOf(e.phx_ref)<0);o.length>0&&(i[e]=t,i[e].metas=o),l.length>0&&(a[e]=this.clone(r),a[e].metas=l)}else i[e]=t}),this.syncDiff(n,{joins:i,leaves:a},r,s)}static syncDiff(e,t,r,s){let{joins:n,leaves:i}=this.clone(t);return r||(r=function(){}),s||(s=function(){}),this.map(n,(t,s)=>{let n=e[t];if(e[t]=this.clone(s),n){let r=e[t].metas.map(e=>e.phx_ref),s=n.metas.filter(e=>r.indexOf(e.phx_ref)<0);e[t].metas.unshift(...s)}r(t,n,s)}),this.map(i,(t,r)=>{let n=e[t];if(!n)return;let i=r.metas.map(e=>e.phx_ref);n.metas=n.metas.filter(e=>i.indexOf(e.phx_ref)<0),s(t,n,r),0===n.metas.length&&delete e[t]}),e}static list(e,t){return t||(t=function(e,t){return t}),this.map(e,(e,r)=>t(e,r))}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static clone(e){return JSON.parse(JSON.stringify(e))}},Ae={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(e,t){if(e.payload.constructor===ArrayBuffer)return t(this.binaryEncode(e));{let r=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(r))}},decode(e,t){if(e.constructor===ArrayBuffer)return t(this.binaryDecode(e));{let[r,s,n,i,a]=JSON.parse(e);return t({join_ref:r,ref:s,topic:n,event:i,payload:a})}},binaryEncode(e){let{join_ref:t,ref:r,event:s,topic:n,payload:i}=e,a=this.META_LENGTH+t.length+r.length+n.length+s.length,o=new ArrayBuffer(this.HEADER_LENGTH+a),l=new DataView(o),c=0;l.setUint8(c++,this.KINDS.push),l.setUint8(c++,t.length),l.setUint8(c++,r.length),l.setUint8(c++,n.length),l.setUint8(c++,s.length),Array.from(t,e=>l.setUint8(c++,e.charCodeAt(0))),Array.from(r,e=>l.setUint8(c++,e.charCodeAt(0))),Array.from(n,e=>l.setUint8(c++,e.charCodeAt(0))),Array.from(s,e=>l.setUint8(c++,e.charCodeAt(0)));var h=new Uint8Array(o.byteLength+i.byteLength);return h.set(new Uint8Array(o),0),h.set(new Uint8Array(i),o.byteLength),h.buffer},binaryDecode(e){let t=new DataView(e),r=t.getUint8(0),s=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(e,t,s);case this.KINDS.reply:return this.decodeReply(e,t,s);case this.KINDS.broadcast:return this.decodeBroadcast(e,t,s)}},decodePush(e,t,r){let s=t.getUint8(1),n=t.getUint8(2),i=t.getUint8(3),a=this.HEADER_LENGTH+this.META_LENGTH-1,o=r.decode(e.slice(a,a+s));a+=s;let l=r.decode(e.slice(a,a+n));a+=n;let c=r.decode(e.slice(a,a+i));return a+=i,{join_ref:o,ref:null,topic:l,event:c,payload:e.slice(a,e.byteLength)}},decodeReply(e,t,r){let s=t.getUint8(1),n=t.getUint8(2),i=t.getUint8(3),a=t.getUint8(4),o=this.HEADER_LENGTH+this.META_LENGTH,l=r.decode(e.slice(o,o+s));o+=s;let c=r.decode(e.slice(o,o+n));o+=n;let h=r.decode(e.slice(o,o+i));o+=i;let u=r.decode(e.slice(o,o+a));o+=a;let d=e.slice(o,e.byteLength);return{join_ref:l,ref:c,topic:h,event:ge,payload:{status:u,response:d}}},decodeBroadcast(e,t,r){let s=t.getUint8(1),n=t.getUint8(2),i=this.HEADER_LENGTH+2,a=r.decode(e.slice(i,i+s));i+=s;let o=r.decode(e.slice(i,i+n));return i+=n,{join_ref:null,ref:null,topic:a,event:o,payload:e.slice(i,e.byteLength)}}},Oe=class{constructor(e,t={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=t.timeout||1e4,this.transport=t.transport||re.WebSocket||Ee,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null;let r=null;try{r=re&&re.sessionStorage}catch{}this.sessionStore=t.sessionStorage||r,this.establishedConnections=0,this.defaultEncoder=Ae.encode.bind(Ae),this.defaultDecoder=Ae.decode.bind(Ae),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=t.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==Ee?(this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let s=null;te&&te.addEventListener&&(te.addEventListener("pagehide",e=>{this.conn&&(this.disconnect(),s=this.connectClock)}),te.addEventListener("pageshow",e=>{s===this.connectClock&&(s=null,this.connect())}),te.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState?this.pageHidden=!0:(this.pageHidden=!1,this.isConnected()||this.closeWasClean||this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=t.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=t.autoSendHeartbeat??!0,this.heartbeatCallback=t.heartbeatCallback??(()=>{}),this.rejoinAfterMs=e=>t.rejoinAfterMs?t.rejoinAfterMs(e):[1e3,2e3,5e3][e-1]||1e4,this.reconnectAfterMs=e=>t.reconnectAfterMs?t.reconnectAfterMs(e):[10,50,100,150,200,250,500,1e3,2e3][e-1]||5e3,this.logger=t.logger||null,!this.logger&&t.debug&&(this.logger=(e,t,r)=>{}),this.longpollerTimeout=t.longpollerTimeout||2e4,this.params=Z(t.params||{}),this.endPoint=`${e}/${we}`,this.vsn=t.vsn||"2.0.0",this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new ke(()=>{if(this.pageHidden)return this.log("Not reconnecting as page is hidden!"),void this.teardown();this.teardown(async()=>{t.beforeReconnect&&await t.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=t.authToken}getLongPollTransport(){return Ee}replaceTransport(e){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=e}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let e=Te.appendParams(Te.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return"/"!==e.charAt(0)?e:"/"===e.charAt(1)?`${this.protocol()}:${e}`:`${this.protocol()}://${location.host}${e}`}disconnect(e,t,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,e&&e()},t,r)}connect(e){e&&(console,this.params=Z(e)),this.conn&&!this.disconnecting||(this.longPollFallbackMs&&this.transport!==Ee?this.connectWithFallback(Ee,this.longPollFallbackMs):this.transportConnect())}log(e,t,r){this.logger&&this.logger(e,t,r)}hasLogger(){return null!==this.logger}onOpen(e){let t=this.makeRef();return this.stateChangeCallbacks.open.push([t,e]),t}onClose(e){let t=this.makeRef();return this.stateChangeCallbacks.close.push([t,e]),t}onError(e){let t=this.makeRef();return this.stateChangeCallbacks.error.push([t,e]),t}onMessage(e){let t=this.makeRef();return this.stateChangeCallbacks.message.push([t,e]),t}onHeartbeat(e){this.heartbeatCallback=e}ping(e){if(!this.isConnected())return!1;let t=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:t});let s=this.onMessage(n=>{n.ref===t&&(this.off([s]),e(Date.now()-r))});return!0}transportName(e){return e===Ee?"LongPoll":e.name}transportConnect(){let e;this.connectClock++,this.closeWasClean=!1,this.authToken&&(e=["phoenix",`${ve}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),e),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,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)}getSession(e){return this.sessionStore&&this.sessionStore.getItem(e)}storeSession(e,t){this.sessionStore&&this.sessionStore.setItem(e,t)}connectWithFallback(e,t=2500){clearTimeout(this.fallbackTimer);let r,s=!1,n=!0,i=this.transportName(e),a=t=>{this.log("transport",`falling back to ${i}...`,t),this.off([undefined,r]),n=!1,this.replaceTransport(e),this.transportConnect()};if(this.getSession(`phx:fallback:${i}`))return a("memorized");this.fallbackTimer=setTimeout(a,t),r=this.onError(e=>{this.log("transport","error",e),n&&!s&&(clearTimeout(this.fallbackTimer),a(e))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(s=!0,!n){let t=this.transportName(e);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${t}`,"true"),this.log("transport",`established ${t} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(a,t),this.ping(e=>{this.log("transport","connected to primary after",e),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(e){this.log("error","error in heartbeat callback",e)}this.triggerChanError(new Error("heartbeat timeout")),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),1e3,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(e,t,r){if(!this.conn)return e&&e();const s=this.conn;this.waitForBufferDone(s,()=>{t?s.close(t,r||""):s.close(),this.waitForSocketClosed(s,()=>{this.conn===s&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),e&&e()})})}waitForBufferDone(e,t,r=1){5!==r&&e.bufferedAmount?setTimeout(()=>{this.waitForBufferDone(e,t,r+1)},150*r):t()}waitForSocketClosed(e,t,r=1){5!==r&&e.readyState!==ae?setTimeout(()=>{this.waitForSocketClosed(e,t,r+1)},150*r):t()}onConnClose(e){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",e),this.triggerChanError(e),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",e)}onConnError(e){this.hasLogger()&&this.log("transport","error",e);let t=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",e,t,r),(t===this.transport||r>0)&&this.triggerChanError(e)}triggerChanError(e){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(pe,e)})}connectionState(){switch(this.conn&&this.conn.readyState){case se:return"connecting";case ne:return"open";case ie:return"closing";default:return"closed"}}isConnected(){return"open"===this.connectionState()}remove(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter(t=>t!==e)}off(e){for(let t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter(([t])=>-1===e.indexOf(t))}channel(e,t={}){let r=new Se(e,t,this);return this.channels.push(r),r}push(e){if(this.hasLogger()){let{topic:t,event:r,payload:s,ref:n,join_ref:i}=e;this.log("push",`${t} ${r} (${i}, ${n})`,s)}this.isConnected()?this.encode(e,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(e,e=>this.conn.send(e)))}makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}sendHeartbeat(){if(this.isConnected())if(this.pendingHeartbeatRef)this.heartbeatTimeout();else{this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),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.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}else try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}onConnMessage(e){this.decode(e.data,e=>{let{topic:t,event:r,payload:s,ref:n,join_ref:i}=e;if(n&&n===this.pendingHeartbeatRef){const e=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback("ok"===s.status?"ok":"error",e)}catch(a){this.log("error","error in heartbeat callback",a)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${s.status||""} ${t} ${r} ${n&&"("+n+")"||""}`.trim(),s);for(let o=0;o<this.channels.length;o++){const e=this.channels[o];e.isMember(t,r,s,i)&&e.trigger(r,s,n,i)}this.triggerStateCallbacks("message",e)})}triggerStateCallbacks(e,...t){try{this.stateChangeCallbacks[e].forEach(([r,s])=>{try{s(...t)}catch(n){this.log("error",`error in ${e} callback`,n)}})}catch(r){this.log("error",`error triggering ${e} callbacks`,r)}}leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t.isJoined()||t.isJoining()));t&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${e}"`),t.leave())}};class Pe{constructor(e,t){const r=function(e){return(null==e?void 0:e.events)&&{events:e.events}}(t);this.presence=new Re(e.getChannel(),r),this.presence.onJoin((t,r,s)=>{const n=Pe.onJoinPayload(t,r,s);e.getChannel().trigger("presence",n)}),this.presence.onLeave((t,r,s)=>{const n=Pe.onLeavePayload(t,r,s);e.getChannel().trigger("presence",n)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return Pe.transformState(this.presence.state)}static transformState(e){return e=function(e){return JSON.parse(JSON.stringify(e))}(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{const s=e[r];return t[r]=je(s),t},{})}static onJoinPayload(e,t,r){return{event:"join",key:e,currentPresences:Ce(t),newPresences:je(r)}}static onLeavePayload(e,t,r){return{event:"leave",key:e,currentPresences:Ce(t),leftPresences:je(r)}}}function je(e){return e.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function Ce(e){return(null==e?void 0:e.metas)?je(e):[]}(Q=X||(X={})).SYNC="sync",Q.JOIN="join",Q.LEAVE="leave";class $e{get state(){return this.presenceAdapter.state}constructor(e,t){this.channel=e,this.presenceAdapter=new Pe(this.channel.channelAdapter,t)}}class Ie{constructor(e,t,r){const s=(n=r,{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},n.config)});var n;this.channel=e.getSocket().channel(t,s),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,t){return this.channel.on(e,t)}off(e,t){this.channel.off(e,t)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,t,r){let s;try{s=this.channel.push(e,t,r)}catch(n){throw new Error(`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>100){const e=this.channel.pushBuffer.shift();e.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${e.event}`,e.payload())}return s}updateJoinPayload(e){const t=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},t),e)}canPush(){return this.socket.isConnected()&&this.state===C}isJoined(){return this.state===C}isJoining(){return this.state===$}isClosed(){return this.state===P}isLeaving(){return this.state===I}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}}const xe=/[,()"\\]/,Ne=e=>{const t=null===e?"null":String(e);return(e=>xe.test(e)||e!==e.trim())(t)?(e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)(t):t},Ue=(e,t)=>{if("in"===e){const e=Array.isArray(t)?t:[t];if(0===e.length)throw new Error("Realtime `in` filter requires at least one value.");return`in.(${Array.from(new Set(e)).map(e=>Ne(e)).join(",")})`}return"is"===e?`is.${(e=>null===e?"null":String(e))(t)}`:`${e}.${Ne(t)}`};class Le{constructor(){this.filters=[]}add(e,t,r,s=!1){const n=s?"not.":"";return this.filters.push(`${e}=${n}${Ue(t,r)}`),this}eq(e,t){return this.add(e,"eq",t)}neq(e,t){return this.add(e,"neq",t)}gt(e,t){return this.add(e,"gt",t)}gte(e,t){return this.add(e,"gte",t)}lt(e,t){return this.add(e,"lt",t)}lte(e,t){return this.add(e,"lte",t)}in(e,t){return this.add(e,"in",t)}like(e,t){return this.add(e,"like",t)}ilike(e,t){return this.add(e,"ilike",t)}match(e,t){return this.add(e,"match",t)}imatch(e,t){return this.add(e,"imatch",t)}is(e,t){return this.add(e,"is",t)}isDistinct(e,t){return this.add(e,"isdistinct",t)}not(e,t,r){return this.add(e,t,r,!0)}build(){return this.filters.join(",")}toString(){return this.build()}}var De,Be,qe,He,Ke,Me;(Be=De||(De={})).ALL="*",Be.INSERT="INSERT",Be.UPDATE="UPDATE",Be.DELETE="DELETE",(He=qe||(qe={})).BROADCAST="broadcast",He.PRESENCE="presence",He.POSTGRES_CHANGES="postgres_changes",He.SYSTEM="system",(Me=Ke||(Ke={})).SUBSCRIBED="SUBSCRIBED",Me.TIMED_OUT="TIMED_OUT",Me.CLOSED="CLOSED",Me.CHANNEL_ERROR="CHANNEL_ERROR";class We{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,t={config:{}},r){var s,n;if(this.topic=e,this.params=t,this.socket=r,this.bindings={},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.channelAdapter=new Ie(this.socket.socketAdapter,e,this.params),this.presence=new $e(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=Y(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(null===(n=null===(s=this.params.config)||void 0===s?void 0:s.broadcast)||void 0===n?void 0:n.replay))throw new Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(e,t=this.timeout){var r,s,n;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){const{config:{broadcast:i,presence:a,private:o}}=this.params,l=null!==(s=null===(r=this.bindings.postgres_changes)||void 0===r?void 0:r.map(e=>e.filter))&&void 0!==s?s:[],c=!!this.bindings[qe.PRESENCE]&&this.bindings[qe.PRESENCE].length>0||!0===(null===(n=this.params.config.presence)||void 0===n?void 0:n.enabled),h={},u={broadcast:i,presence:Object.assign(Object.assign({},a),{enabled:c}),postgres_changes:l,private:o};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(t=>{null==e||e(Ke.CHANNEL_ERROR,function(e){if(e instanceof Error)return e;if("string"==typeof e)return new Error(e);if(e&&"object"==typeof e){const t=e;if("number"==typeof t.code){const r="string"==typeof t.reason&&t.reason?` (${t.reason})`:"";return new Error(`socket closed: ${t.code}${r}`,{cause:e})}return new Error("channel error: transport failure",{cause:e})}return new Error("channel error: connection lost")}(t))}),this._onClose(()=>null==e?void 0:e(Ke.CLOSED)),this.updateJoinPayload(Object.assign({config:u},h)),this._updateFilterMessage(),this.channelAdapter.subscribe(t).receive("ok",async({postgres_changes:t})=>{this.socket._isManualToken()||this.socket.setAuth(),void 0!==t?this._updatePostgresBindings(t,e):null==e||e(Ke.SUBSCRIBED)}).receive("error",t=>{this.state=j;const r=Object.values(t).join(", ")||"error";null==e||e(Ke.CHANNEL_ERROR,new Error(r,{cause:t}))}).receive("timeout",()=>{null==e||e(Ke.TIMED_OUT)})}return this}_updatePostgresBindings(e,t){var r;const s=this.bindings.postgres_changes,n=null!==(r=null==s?void 0:s.length)&&void 0!==r?r:0,i=[];for(let a=0;a<n;a++){const r=s[a],{filter:{event:n,schema:o,table:l,filter:c}}=r,h=e&&e[a];if(!(h&&h.event===n&&We.isFilterValueEqual(h.schema,o)&&We.isFilterValueEqual(h.table,l)&&We.isFilterValueEqual(h.filter,c)))return this.unsubscribe(),this.state=j,void(null==t||t(Ke.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes")));i.push(Object.assign(Object.assign({},r),{id:h.id}))}this.bindings.postgres_changes=i,this.state!=j&&t&&t(Ke.SUBSCRIBED)}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){const s=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),n=e===qe.PRESENCE||e===qe.POSTGRES_CHANGES;if(s&&n)throw this.socket.log("channel",`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`),new Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(e,t,r)}async httpSend(e,t,r={}){var s;if(null==t)return Promise.reject(new Error("Payload is required for httpSend()"));const n=t instanceof ArrayBuffer||ArrayBuffer.isView(t),i={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":n?"application/octet-stream":"application/json"};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);const a=new URL(this.broadcastEndpointURL);a.pathname+=`/${encodeURIComponent(this.subTopic)}/events/${encodeURIComponent(e)}`,this.private&&a.searchParams.set("private","true");const o={method:"POST",headers:i,body:n?t:JSON.stringify(t)},l=await this._fetchWithTimeout(a.toString(),o,null!==(s=r.timeout)&&void 0!==s?s:this.timeout);if(202===l.status)return{success:!0};if(404===l.status)return Promise.reject(new Error("httpSend() requires Realtime server v2.97.0 or newer; the endpoint returned 404. Update your Supabase CLI to a recent version, or upgrade the Realtime server in your self-hosted setup. See https://github.com/supabase/supabase-js/blob/master/packages/core/realtime-js/migrations/httpsend-server-version.md"));let c=l.statusText;try{const e=await l.json();c=e.error||e.message||c}catch(h){}return Promise.reject(new Error(c))}async send(e,t={}){var r,s;if(this.channelAdapter.canPush()||"broadcast"!==e.type)return new Promise(r=>{var s,n,i;const a=this.channelAdapter.push(e.type,e,t.timeout||this.timeout);"broadcast"!==e.type||(null===(i=null===(n=null===(s=this.params)||void 0===s?void 0:s.config)||void 0===n?void 0:n.broadcast)||void 0===i?void 0:i.ack)||r("ok"),a.receive("ok",()=>r("ok")),a.receive("error",()=>r("error")),a.receive("timeout",()=>r("timed out"))});{const{event:i,payload:a}=e,o={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(o.Authorization=`Bearer ${this.socket.accessTokenValue}`);const l={method:"POST",headers:o,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:a,private:this.private}]})};try{const e=await this._fetchWithTimeout(this.broadcastEndpointURL,l,null!==(r=t.timeout)&&void 0!==r?r:this.timeout);return await(null===(s=e.body)||void 0===s?void 0:s.cancel()),e.ok?"ok":"error"}catch(n){return n instanceof Error&&"AbortError"===n.name?"timed out":"error"}}}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(t=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>t("ok")).receive("timeout",()=>t("timed out")).receive("error",()=>t("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,t,r){const s=new AbortController,n=setTimeout(()=>s.abort(),r),i=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:s.signal}));return clearTimeout(n),i}_on(e,t,r){const s=e.toLocaleLowerCase(),n=null==t?void 0:t.filter;(n instanceof Le||"object"==typeof n&&null!==n&&"function"==typeof n.build)&&(t=Object.assign(Object.assign({},t),{filter:n.build()}));const i={type:s,filter:t,callback:r,ref:this.channelAdapter.on(e,r)};return this.bindings[s]?this.bindings[s].push(i):this.bindings[s]=[i],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,t,r)=>{var s,n,i,a,o,l,c;const h=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(h,r))return!1;const u=null===(s=this.bindings[h])||void 0===s?void 0:s.find(t=>t.ref===e.ref);if(!u)return!0;if(["broadcast","presence","postgres_changes"].includes(h)){if("id"in u){const e=u.id,r=null===(n=u.filter)||void 0===n?void 0:n.event;return e&&(null===(i=t.ids)||void 0===i?void 0:i.includes(e))&&("*"===r||(null==r?void 0:r.toLocaleLowerCase())===(null===(a=t.data)||void 0===a?void 0:a.type.toLocaleLowerCase()))}{const e=null===(l=null===(o=null==u?void 0:u.filter)||void 0===o?void 0:o.event)||void 0===l?void 0:l.toLocaleLowerCase();return"*"===e||e===(null===(c=null==t?void 0:t.event)||void 0===c?void 0:c.toLocaleLowerCase())}}return u.type.toLocaleLowerCase()===h})}_notThisChannelEvent(e,t){const{close:r,error:s,leave:n,join:i}=x;return t&&[r,s,n,i].includes(e)&&t!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,t,r)=>{if("object"==typeof t&&"ids"in t){const e=t.data,{schema:r,table:s,commit_timestamp:n,type:i,errors:a}=e,o={schema:r,table:s,commit_timestamp:n,eventType:i,new:{},old:{},errors:a};return Object.assign(Object.assign({},o),this._getPayloadRecords(e))}return t})}copyBindings(e){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(const t in e.bindings)for(const r of e.bindings[t])this._on(r.type,r.filter,r.callback)}static isFilterValueEqual(e,t){return(null!=e?e:void 0)===(null!=t?t:void 0)}_getPayloadRecords(e){const t={new:{},old:{}};return"INSERT"!==e.type&&"UPDATE"!==e.type||(t.new=H(e.columns,e.record)),"UPDATE"!==e.type&&"DELETE"!==e.type||(t.old=H(e.columns,e.old_record)),t}}class Fe{constructor(e,t){this.socket=new Oe(e,t)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,t,r,s=1e4){return new Promise(n=>{setTimeout(()=>n("timeout"),s),this.socket.disconnect(()=>{e(),n("ok")},t,r)})}push(e){this.socket.push(e)}log(e,t,r){this.socket.log(e,t,r)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==N}isDisconnecting(){return this.socket.connectionState()==U}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}const Je=25e3,Ge=[1e3,2e3,5e3,1e4];function ze(){try{if("undefined"!=typeof globalThis&&globalThis.sessionStorage)return globalThis.sessionStorage}catch(e){}return function(){const e=new Map;return{get length(){return e.size},clear(){e.clear()},getItem:t=>e.has(t)?e.get(t):null,key(t){var r;return null!==(r=Array.from(e.keys())[t])&&void 0!==r?r:null},removeItem(t){e.delete(t)},setItem(t,r){e.set(t,String(r))}}}()}class Ve{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,t){var r;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new D,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),!(null===(r=null==t?void 0:t.params)||void 0===r?void 0:r.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey;const s=this._initializeOptions(t);this.socketAdapter=new Fe(e,s),this.httpEndpoint=Y(e),this.fetch=this._resolveFetch(null==t?void 0:t.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){const t=e.message;throw new Error(`WebSocket not available: ${t}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,t){return this._cancelPendingDisconnect(),this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,t)}getChannels(){return this.channels}async removeChannel(e){const t=await e.unsubscribe();return"ok"===t&&e.teardown(),t}async removeAllChannels(){const e=this.channels.map(async e=>{const t=await e.unsubscribe();return e.teardown(),t}),t=await Promise.all(e);return await this.disconnect(),t}log(e,t,r){this.socketAdapter.log(e,t,r)}connectionState(){return this.socketAdapter.connectionState()||L}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,t={config:{}}){const r=`realtime:${e}`,s=this.getChannels().find(e=>e.topic===r);if(s)return s;{const r=new We(`realtime:${e}`,t,this);return this._cancelPendingDisconnect(),this.channels.push(r),r}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic),0===this.channels.length&&(this.log("transport","no channels remaining, scheduling disconnect"),this._schedulePendingDisconnect())}_schedulePendingDisconnect(){if(this._cancelPendingDisconnect(),0===this._disconnectOnEmptyChannelsAfterMs)return this.log("transport","disconnecting immediately - no channels"),void this.disconnect();this._pendingDisconnectTimer=setTimeout(()=>{this._pendingDisconnectTimer=null,0===this.channels.length&&(this.log("transport","deferred disconnect fired - no channels, disconnecting"),this.disconnect())},this._disconnectOnEmptyChannelsAfterMs),this.log("transport",`deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`)}_cancelPendingDisconnect(){null!==this._pendingDisconnectTimer&&(this.log("transport","pending disconnect cancelled - channel activity detected"),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null)}async _performAuth(e=null){let t,r=!1;if(e)t=e,r=!0;else if(this.accessToken)try{t=await this.accessToken()}catch(s){this.log("error","Error fetching access token from callback",s),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=>{const r={access_token:t,version:"realtime-js/2.110.2"};t&&e.updateJoinPayload(r),e.joinedOnce&&e.channelAdapter.isJoined()&&e.channelAdapter.push(x.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)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(e=>{this.log("error","error waiting for auth on connect",e)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(t,r)=>{"disconnected"!==t&&("sent"==t&&this._setAuthSafely(),e&&e(t,r))}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log("worker","worker error",e.message),this._terminateWorker(),this.disconnect()},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"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(e){let t;if(e)t=e;else{const e=new Blob(['\n addEventListener("message", (e) => {\n if (e.data.event === "start") {\n setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);\n }\n });'],{type:"application/javascript"});t=URL.createObjectURL(e)}return t}_initializeOptions(e){var t,r,s,n,i,a,o,l,c,h,u,d;this.worker=null!==(t=null==e?void 0:e.worker)&&void 0!==t&&t,this.accessToken=null!==(r=null==e?void 0:e.accessToken)&&void 0!==r?r:null;const p={};let f,g;p.timeout=null!==(s=null==e?void 0:e.timeout)&&void 0!==s?s:1e4,p.heartbeatIntervalMs=null!==(n=null==e?void 0:e.heartbeatIntervalMs)&&void 0!==n?n:Je,this._disconnectOnEmptyChannelsAfterMs=null!==(i=null==e?void 0:e.disconnectOnEmptyChannelsAfterMs)&&void 0!==i?i:2*(null!==(a=null==e?void 0:e.heartbeatIntervalMs)&&void 0!==a?a:Je),p.transport=null!==(o=null==e?void 0:e.transport)&&void 0!==o?o:R.getWebSocketConstructor(),p.params=null==e?void 0:e.params,p.logger=null==e?void 0:e.logger,p.heartbeatCallback=this._wrapHeartbeatCallback(null==e?void 0:e.heartbeatCallback),p.sessionStorage=null!==(l=null==e?void 0:e.sessionStorage)&&void 0!==l?l:ze(),p.reconnectAfterMs=null!==(c=null==e?void 0:e.reconnectAfterMs)&&void 0!==c?c:e=>Ge[e-1]||1e4;const y=null!==(h=null==e?void 0:e.vsn)&&void 0!==h?h:O;switch(y){case"1.0.0":f=(e,t)=>t(JSON.stringify(e)),g=(e,t)=>t(JSON.parse(e));break;case A:f=this.serializer.encode.bind(this.serializer),g=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${p.vsn}`)}if(p.vsn=y,p.encode=null!==(u=null==e?void 0:e.encode)&&void 0!==u?u:f,p.decode=null!==(d=null==e?void 0:e.decode)&&void 0!==d?d:g,p.beforeReconnect=this._reconnectAuth.bind(this),((null==e?void 0:e.logLevel)||(null==e?void 0:e.log_level))&&(this.logLevel=e.logLevel||e.log_level,p.params=Object.assign(Object.assign({},p.params),{log_level:this.logLevel})),this.worker){if("undefined"!=typeof window&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=null==e?void 0:e.workerUrl,p.autoSendHeartbeat=!this.worker}return p}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}var Ye=class extends Error{constructor(e,t){var r;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===(null==(r=t.icebergType)?void 0:r.includes("CommitState"))}isNotFound(){return 404===this.status}isConflict(){return 409===this.status}isAuthenticationTimeout(){return 419===this.status}};function Xe(e){const t=e.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:n,body:i,headers:a}){const o=function(e,t,r){const s=new URL(t,e);if(r)for(const[n,i]of Object.entries(r))void 0!==i&&s.searchParams.set(n,i);return s.toString()}(e.baseUrl,s,n),l=await async function(e){return e&&"none"!==e.type?"bearer"===e.type?{Authorization:`Bearer ${e.token}`}:"header"===e.type?{[e.name]:e.value}:"custom"===e.type?await e.getHeaders():{}:{}}(e.auth),c=await t(o,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...l,...a},body:i?JSON.stringify(i):void 0}),h=await c.text(),u=(c.headers.get("content-type")||"").includes("application/json"),d=u&&h?JSON.parse(h):h;if(!c.ok){const e=u?d:void 0,t=null==e?void 0:e.error;throw new Ye((null==t?void 0:t.message)??`Request failed with status ${c.status}`,{status:c.status,icebergType:null==t?void 0:t.type,icebergCode:null==t?void 0:t.code,details:e})}return{status:c.status,headers:c.headers,data:d}}}}function Qe(e){return e.join("")}var Ze=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){const t=e?{parent:Qe(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){const r={namespace:e.namespace,properties:null==t?void 0: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/${Qe(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Qe(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Qe(e.namespace)}`}),!0}catch(t){if(t instanceof Ye&&404===t.status)return!1;throw t}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(r){if(r instanceof Ye&&409===r.status)return;throw r}}};function et(e){return e.join("")}var tt=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/${et(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){const r={};this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation);return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${et(e.namespace)}/tables`,body:t,headers:r})).data.metadata}async updateTable(e,t){const r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${et(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/${et(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String((null==t?void 0:t.purge)??!1)}})}async loadTable(e){const t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${et(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){const t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${et(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(r){if(r instanceof Ye&&404===r.status)return!1;throw r}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(r){if(r instanceof Ye&&409===r.status)return await this.loadTable({namespace:e.namespace,name:t.name});throw r}}},rt=class{constructor(e){var t;let r="v1";e.catalogName&&(r+=`/${e.catalogName}`);const s=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=Xe({baseUrl:s,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=null==(t=e.accessDelegation)?void 0:t.join(","),this.namespaceOps=new Ze(this.client,r),this.tableOps=new tt(this.client,r,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)}};function st(e){return(st="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})(e)}function nt(e){var t=function(e,t){if("object"!=st(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t);if("object"!=st(s))return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==st(t)?t:t+""}function it(e,t,r){return(t=nt(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function at(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 ot(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?at(Object(r),!0).forEach(function(t){it(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):at(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var lt=class extends Error{constructor(e,t="storage",r,s){super(e),this.__isStorageError=!0,this.namespace=t,this.name="vectors"===t?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=s}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}};function ct(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}var ht=class extends lt{constructor(e,t,r,s="storage"){super(e,s,t,r),this.name="vectors"===s?"StorageVectorsApiError":"StorageApiError",this.status=t,this.statusCode=r}toJSON(){return ot({},super.toJSON())}},ut=class extends lt{constructor(e,t,r="storage"){super(e,r),this.name="vectors"===r?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=t}};function dt(e,t,r){const s=ot({},e),n=t.toLowerCase();for(const i of Object.keys(s))i.toLowerCase()===n&&delete s[i];return s[n]=r,s}const pt=e=>{if(Array.isArray(e))return e.map(e=>pt(e));if("function"==typeof e||e!==Object(e))return e;const t={};return Object.entries(e).forEach(([e,r])=>{const s=e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(/[-_]/g,""));t[s]=pt(r)}),t},ft=e=>{if("object"==typeof e&&null!==e){const t=e;if("string"==typeof t.msg)return t.msg;if("string"==typeof t.message)return t.message;if("string"==typeof t.error_description)return t.error_description;if("string"==typeof t.error)return t.error;if("object"==typeof t.error&&null!==t.error){const e=t.error;if("string"==typeof e.message)return e.message}}return JSON.stringify(e)},gt=(e,t,r,s)=>{const n={method:e,headers:(null==t?void 0:t.headers)||{}};if("GET"===e||"HEAD"===e||!s)return ot(ot({},n),r);if((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(s)){var i;const e=(null==t?void 0:t.headers)||{};let r;for(const[t,s]of Object.entries(e))"content-type"===t.toLowerCase()&&(r=s);n.headers=dt(e,"Content-Type",null!==(i=r)&&void 0!==i?i:"application/json"),n.body=JSON.stringify(s)}else n.body=s;return(null==t?void 0:t.duplex)&&(n.duplex=t.duplex),ot(ot({},n),r)};async function yt(e,t,r,s,n,i,a){return new Promise((o,l)=>{e(r,gt(t,s,n,i)).then(e=>{if(!e.ok)throw e;if(null==s?void 0:s.noResolveJson)return e;if("vectors"===a){const t=e.headers.get("content-type");if("0"===e.headers.get("content-length")||204===e.status)return{};if(!t||!t.includes("application/json"))return{}}return e.json()}).then(e=>o(e)).catch(e=>(async(e,t,r,s)=>{if(null!==e&&"object"==typeof e&&"json"in e&&"function"==typeof e.json){const r=e;let n=parseInt(String(r.status),10);Number.isFinite(n)||(n=500),r.json().then(e=>{const r=(null==e?void 0:e.statusCode)||(null==e?void 0:e.code)||n+"";t(new ht(ft(e),n,r,s))}).catch(()=>{const e=n+"";t(new ht(r.statusText||`HTTP ${n} error`,n,e,s))})}else t(new ut(ft(e),e,s))})(e,l,0,a))})}function mt(e="storage"){return{get:async(t,r,s,n)=>yt(t,"GET",r,s,n,void 0,e),post:async(t,r,s,n,i)=>yt(t,"POST",r,n,i,s,e),put:async(t,r,s,n,i)=>yt(t,"PUT",r,n,i,s,e),head:async(t,r,s,n)=>yt(t,"HEAD",r,ot(ot({},s),{},{noResolveJson:!0}),n,void 0,e),remove:async(t,r,s,n,i)=>yt(t,"DELETE",r,n,i,s,e)}}const wt=mt("storage"),{get:bt,post:vt,put:_t,head:kt,remove:St}=wt,Tt=mt("vectors");var Et=class{constructor(e,t={},r,s="storage"){var n;this.shouldThrowOnError=!1,this.url=e,this.headers=function(e){const t={};for(const[r,s]of Object.entries(e))t[r.toLowerCase()]=s;return t}(t),this.fetch=(n=r)?(...e)=>n(...e):(...e)=>fetch(...e),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=dt(this.headers,e,t),this}async handleOperation(e){try{return{data:await e(),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(ct(t))return{data:null,error:t};throw t}}};let Rt;Rt=Symbol.toStringTag;var At=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[Rt]="StreamDownloadBuilder",this.promise=null}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){try{return{data:(await this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(ct(e))return{data:null,error:e};throw e}}};let Ot;Ot=Symbol.toStringTag;var Pt=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[Ot]="BlobDownloadBuilder",this.promise=null}asStream(){return new At(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){try{return{data:await(await this.downloadFn()).blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(ct(e))return{data:null,error:e};throw e}}};const jt={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Ct={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var $t=class extends Et{constructor(e,t={},r,s){super(e,t,s,"storage"),this.bucketId=r}async uploadOrUpdate(e,t,r,s){var n=this;return n.handleOperation(async()=>{let i;const a=ot(ot({},Ct),s);let o=ot(ot({},n.headers),"POST"===e&&{"x-upsert":String(a.upsert)});const l=a.metadata;if("undefined"!=typeof Blob&&r instanceof Blob?(i=new FormData,i.append("cacheControl",a.cacheControl),l&&i.append("metadata",n.encodeMetadata(l)),i.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",a.cacheControl),l&&!i.has("metadata")&&i.append("metadata",n.encodeMetadata(l))):(i=r,o["cache-control"]=`max-age=${a.cacheControl}`,o["content-type"]=a.contentType,l&&(o["x-metadata"]=n.toBase64(n.encodeMetadata(l))),("undefined"!=typeof ReadableStream&&i instanceof ReadableStream||i&&"object"==typeof i&&"pipe"in i&&"function"==typeof i.pipe)&&!a.duplex&&(a.duplex="half")),null==s?void 0:s.headers)for(const[e,t]of Object.entries(s.headers))o=dt(o,e,t);const c=n._removeEmptyFolders(t),h=n._getFinalPath(c),u=await("PUT"==e?_t:vt)(n.fetch,`${n.url}/object/${h}`,i,ot({headers:o},(null==a?void 0:a.duplex)?{duplex:a.duplex}:{}));return{path:c,id:u.Id,fullPath:u.Key}})}async upload(e,t,r){return this.uploadOrUpdate("POST",e,t,r)}async uploadToSignedUrl(e,t,r,s){var n=this;const i=n._removeEmptyFolders(e),a=n._getFinalPath(i),o=new URL(n.url+`/object/upload/sign/${a}`);return o.searchParams.set("token",t),n.handleOperation(async()=>{let e;const t=ot(ot({},Ct),s);let a=ot(ot({},n.headers),{"x-upsert":String(t.upsert)});const l=t.metadata;if("undefined"!=typeof Blob&&r instanceof Blob?(e=new FormData,e.append("cacheControl",t.cacheControl),l&&e.append("metadata",n.encodeMetadata(l)),e.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?(e=r,e.has("cacheControl")||e.append("cacheControl",t.cacheControl),l&&!e.has("metadata")&&e.append("metadata",n.encodeMetadata(l))):(e=r,a["cache-control"]=`max-age=${t.cacheControl}`,a["content-type"]=t.contentType,l&&(a["x-metadata"]=n.toBase64(n.encodeMetadata(l))),("undefined"!=typeof ReadableStream&&e instanceof ReadableStream||e&&"object"==typeof e&&"pipe"in e&&"function"==typeof e.pipe)&&!t.duplex&&(t.duplex="half")),null==s?void 0:s.headers)for(const[r,n]of Object.entries(s.headers))a=dt(a,r,n);return{path:i,fullPath:(await _t(n.fetch,o.toString(),e,ot({headers:a},(null==t?void 0:t.duplex)?{duplex:t.duplex}:{}))).Key}})}async createSignedUploadUrl(e,t){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(e);const n=ot({},r.headers);(null==t?void 0:t.upsert)&&(n["x-upsert"]="true");const i=await vt(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:n}),a=new URL(r.url+i.url),o=a.searchParams.get("token");if(!o)throw new lt("No token returned by API");return{signedUrl:a.toString(),path:e,token:o}})}async update(e,t,r){return this.uploadOrUpdate("PUT",e,t,r)}async move(e,t,r){var s=this;return s.handleOperation(async()=>await vt(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==r?void 0:r.destinationBucket},{headers:s.headers}))}async copy(e,t,r){var s=this;return s.handleOperation(async()=>({path:(await vt(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==r?void 0:r.destinationBucket},{headers:s.headers})).Key}))}async createSignedUrl(e,t,r){var s=this;return s.handleOperation(async()=>{let n=s._getFinalPath(e);const i="object"==typeof(null==r?void 0:r.transform)&&null!==r.transform&&Object.keys(r.transform).length>0;let a=await vt(s.fetch,`${s.url}/object/sign/${n}`,ot({expiresIn:t},i?{transform:r.transform}:{}),{headers:s.headers});const o=new URLSearchParams;(null==r?void 0:r.download)&&o.set("download",!0===r.download?"":r.download),null!=(null==r?void 0:r.cacheNonce)&&o.set("cacheNonce",String(r.cacheNonce));const l=o.toString();return{signedUrl:encodeURI(`${s.url}${a.signedURL}${l?`&${l}`:""}`)}})}async createSignedUrls(e,t,r){var s=this;return s.handleOperation(async()=>{const n=await vt(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:t,paths:e},{headers:s.headers}),i=new URLSearchParams;(null==r?void 0:r.download)&&i.set("download",!0===r.download?"":r.download),null!=(null==r?void 0:r.cacheNonce)&&i.set("cacheNonce",String(r.cacheNonce));const a=i.toString();return n.map(e=>ot(ot({},e),{},{signedUrl:e.signedURL?encodeURI(`${s.url}${e.signedURL}${a?`&${a}`:""}`):null}))})}download(e,t,r){const s="object"==typeof(null==t?void 0:t.transform)&&null!==t.transform&&Object.keys(t.transform).length>0?"render/image/authenticated":"object",n=new URLSearchParams;(null==t?void 0:t.transform)&&this.applyTransformOptsToQuery(n,t.transform),null!=(null==t?void 0:t.cacheNonce)&&n.set("cacheNonce",String(t.cacheNonce));const i=n.toString(),a=this._getFinalPath(e);return new Pt(()=>bt(this.fetch,`${this.url}/${s}/${a}${i?`?${i}`:""}`,{headers:this.headers,noResolveJson:!0},r),this.shouldThrowOnError)}async info(e){var t=this;const r=t._getFinalPath(e);return t.handleOperation(async()=>pt(await bt(t.fetch,`${t.url}/object/info/${r}`,{headers:t.headers})))}async exists(e){var t=this;const r=t._getFinalPath(e);try{return await kt(t.fetch,`${t.url}/object/${r}`,{headers:t.headers}),{data:!0,error:null}}catch(n){if(t.shouldThrowOnError)throw n;if(ct(n)){var s;const e=n instanceof ht?n.status:n instanceof ut?null===(s=n.originalError)||void 0===s?void 0:s.status:void 0;if(void 0!==e&&[400,404].includes(e))return{data:!1,error:n}}throw n}}getPublicUrl(e,t){const r=this._getFinalPath(e),s=new URLSearchParams;(null==t?void 0:t.download)&&s.set("download",!0===t.download?"":t.download),(null==t?void 0:t.transform)&&this.applyTransformOptsToQuery(s,t.transform),null!=(null==t?void 0:t.cacheNonce)&&s.set("cacheNonce",String(t.cacheNonce));const n=s.toString(),i="object"==typeof(null==t?void 0:t.transform)&&null!==t.transform&&Object.keys(t.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}`)+(n?`?${n}`:"")}}}async remove(e){var t=this;return t.handleOperation(async()=>await St(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers}))}async purgeCache(e,t,r){var s=this;return s.handleOperation(async()=>{const n=s._getFinalPath(e),i=new URLSearchParams;(null==t?void 0:t.transformations)&&i.set("transformations","true");const a=i.toString();return await St(s.fetch,`${s.url}/cdn/${n}${a?`?${a}`:""}`,{},{headers:s.headers},r)})}async list(e,t,r){var s=this;return s.handleOperation(async()=>{const n=(null==t?void 0:t.sortBy)?ot(ot({},jt.sortBy),t.sortBy):jt.sortBy,i=ot(ot(ot({},jt),t),{},{sortBy:n,prefix:e||""});return await vt(s.fetch,`${s.url}/object/list/${s.bucketId}`,i,{headers:s.headers},r)})}async listV2(e,t){var r=this;return r.handleOperation(async()=>{const s=ot({},e);return await vt(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,s,{headers:r.headers},t)})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return"undefined"!=typeof Buffer?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(e,t){return t.width&&e.set("width",t.width.toString()),t.height&&e.set("height",t.height.toString()),t.resize&&e.set("resize",t.resize),t.format&&e.set("format",t.format),t.quality&&e.set("quality",t.quality.toString()),e}};const It={"X-Client-Info":"storage-js/2.110.2"};var xt=class extends Et{constructor(e,t={},r,s){const n=new URL(e);(null==s?void 0:s.useNewHostname)&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase."));super(n.href.replace(/\/$/,""),ot(ot({},It),t),r,"storage")}async listBuckets(e){var t=this;return t.handleOperation(async()=>{const r=t.listBucketOptionsToQueryString(e);return await bt(t.fetch,`${t.url}/bucket${r}`,{headers:t.headers})})}async getBucket(e){var t=this;return t.handleOperation(async()=>await bt(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}))}async createBucket(e,t={public:!1}){var r=this;return r.handleOperation(async()=>await vt(r.fetch,`${r.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}))}async updateBucket(e,t){var r=this;return r.handleOperation(async()=>await _t(r.fetch,`${r.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(e){var t=this;return t.handleOperation(async()=>await vt(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await St(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}async purgeBucketCache(e,t,r){var s=this;return s.handleOperation(async()=>{const n=new URLSearchParams;(null==t?void 0:t.transformations)&&n.set("transformations","true");const i=n.toString();return await St(s.fetch,`${s.url}/cdn/${e}${i?`?${i}`:""}`,{},{headers:s.headers},r)})}listBucketOptionsToQueryString(e){const t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}},Nt=class extends Et{constructor(e,t={},r){super(e.replace(/\/$/,""),ot(ot({},It),t),r,"storage")}async createBucket(e){var t=this;return t.handleOperation(async()=>await vt(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers}))}async listBuckets(e){var t=this;return t.handleOperation(async()=>{const r=new URLSearchParams;void 0!==(null==e?void 0:e.limit)&&r.set("limit",e.limit.toString()),void 0!==(null==e?void 0:e.offset)&&r.set("offset",e.offset.toString()),(null==e?void 0:e.sortColumn)&&r.set("sortColumn",e.sortColumn),(null==e?void 0:e.sortOrder)&&r.set("sortOrder",e.sortOrder),(null==e?void 0:e.search)&&r.set("search",e.search);const s=r.toString(),n=s?`${t.url}/bucket?${s}`:`${t.url}/bucket`;return await bt(t.fetch,n,{headers:t.headers})})}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await St(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}from(e){var t=this;if(!(e=>!(!e||"string"!=typeof e)&&!(0===e.length||e.length>100)&&e.trim()===e&&!e.includes("/")&&!e.includes("\\")&&/^[\w!.\*'() &$@=;:+,?-]+$/.test(e))(e))throw new lt("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const r=new rt({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){const r=e[t];return"function"!=typeof r?r:async(...t)=>{try{return{data:await r.apply(e,t),error:null}}catch(n){if(s)throw n;return{data:null,error:n}}}}})}},Ut=class extends Et{constructor(e,t={},r){super(e.replace(/\/$/,""),ot(ot({},It),{},{"Content-Type":"application/json"},t),r,"vectors")}async createIndex(e){var t=this;return t.handleOperation(async()=>await Tt.post(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{})}async getIndex(e,t){var r=this;return r.handleOperation(async()=>await Tt.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers}))}async listIndexes(e){var t=this;return t.handleOperation(async()=>await Tt.post(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}))}async deleteIndex(e,t){var r=this;return r.handleOperation(async()=>await Tt.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers})||{})}},Lt=class extends Et{constructor(e,t={},r){super(e.replace(/\/$/,""),ot(ot({},It),{},{"Content-Type":"application/json"},t),r,"vectors")}async putVectors(e){var t=this;if(e.vectors.length<1||e.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return t.handleOperation(async()=>await Tt.post(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{})}async getVectors(e){var t=this;return t.handleOperation(async()=>await Tt.post(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers}))}async listVectors(e){var t=this;if(void 0!==e.segmentCount){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(void 0!==e.segmentIndex&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error("segmentIndex must be between 0 and "+(e.segmentCount-1))}return t.handleOperation(async()=>await Tt.post(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}))}async queryVectors(e){var t=this;return t.handleOperation(async()=>await Tt.post(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers}))}async deleteVectors(e){var t=this;if(e.keys.length<1||e.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return t.handleOperation(async()=>await Tt.post(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{})}},Dt=class extends Et{constructor(e,t={},r){super(e.replace(/\/$/,""),ot(ot({},It),{},{"Content-Type":"application/json"},t),r,"vectors")}async createBucket(e){var t=this;return t.handleOperation(async()=>await Tt.post(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}async getBucket(e){var t=this;return t.handleOperation(async()=>await Tt.post(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}))}async listBuckets(e={}){var t=this;return t.handleOperation(async()=>await Tt.post(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await Tt.post(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}},Bt=class extends Dt{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new qt(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)}},qt=class extends Ut{constructor(e,t,r,s){super(e,t,s),this.vectorBucketName=r}async createIndex(e){return(()=>super.createIndex)().call(this,ot(ot({},e),{},{vectorBucketName:this.vectorBucketName}))}async listIndexes(e={}){return(()=>super.listIndexes)().call(this,ot(ot({},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 Ht(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},Ht=class extends Lt{constructor(e,t,r,s,n){super(e,t,n),this.vectorBucketName=r,this.indexName=s}async putVectors(e){var t=this;return(()=>super.putVectors)().call(t,ot(ot({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async getVectors(e){var t=this;return(()=>super.getVectors)().call(t,ot(ot({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async listVectors(e={}){var t=this;return(()=>super.listVectors)().call(t,ot(ot({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async queryVectors(e){var t=this;return(()=>super.queryVectors)().call(t,ot(ot({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async deleteVectors(e){var t=this;return(()=>super.deleteVectors)().call(t,ot(ot({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}},Kt=class extends xt{constructor(e,t={},r,s){super(e,t,r,s)}from(e){return new $t(this.url,this.headers,e,this.fetch)}get vectors(){return new Bt(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Nt(this.url+"/iceberg",this.headers,this.fetch)}};const Mt="2.110.2",Wt=3e4,Ft=9e4,Jt={"X-Client-Info":`gotrue-js/${Mt}`},Gt="X-Supabase-Api-Version",zt={timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"},Vt=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;class Yt extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}}function Xt(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class Qt extends Yt{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}}class Zt extends Yt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class er extends Yt{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}}class tr extends er{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function rr(e){return Xt(e)&&"AuthSessionMissingError"===e.name}class sr extends er{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class nr extends er{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class ir extends er{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}class ar extends er{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}class or extends er{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")}}class lr extends er{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function cr(e){return Xt(e)&&"AuthRetryableFetchError"===e.name}class hr extends er{constructor(e="Refresh result discarded: session state changed mid-flight (e.g., concurrent signOut)"){super(e,"AuthRefreshDiscardedError",409,void 0)}}class ur extends er{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}}class dr extends er{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const pr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),fr=" \t\n\r=".split(""),gr=(()=>{const e=new Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<fr.length;t+=1)e[fr[t].charCodeAt(0)]=-2;for(let t=0;t<pr.length;t+=1)e[pr[t].charCodeAt(0)]=t;return e})();function yr(e,t,r){if(null!==e)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;r(pr[e]),t.queuedBits-=6}else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;r(pr[e]),t.queuedBits-=6}}function mr(e,t,r){const s=gr[e];if(!(s>-1)){if(-2===s)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}for(t.queue=t.queue<<6|s,t.queuedBits+=6;t.queuedBits>=8;)r(t.queue>>t.queuedBits-8&255),t.queuedBits-=8}function wr(e){const t=[],r=e=>{t.push(String.fromCodePoint(e))},s={utf8seq:0,codepoint:0},n={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 new Error("Invalid UTF-8 sequence");t.codepoint=7&e}t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&r(t.codepoint)}}(e,s,r)};for(let a=0;a<e.length;a+=1)mr(e.charCodeAt(a),n,i);return t.join("")}function br(e,t){if(!(e<=127)){if(e<=2047)return t(192|e>>6),void t(128|63&e);if(e<=65535)return t(224|e>>12),t(128|e>>6&63),void t(128|63&e);if(e<=1114111)return t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),void t(128|63&e);throw new Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}t(e)}function vr(e){const t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};for(let n=0;n<e.length;n+=1)mr(e.charCodeAt(n),r,s);return new Uint8Array(t)}function _r(e){const t=[];return function(e,t){for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);if(s>55295&&s<=56319){const t=1024*(s-55296)&65535;s=65536+(e.charCodeAt(r+1)-56320&65535|t),r+=1}br(s,t)}}(e,e=>t.push(e)),new Uint8Array(t)}function kr(e){const t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};return e.forEach(e=>yr(e,r,s)),yr(null,r,s),t.join("")}const Sr=()=>"undefined"!=typeof window&&"undefined"!=typeof document,Tr={tested:!1,writable:!1},Er=()=>{if(!Sr())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(t){return!1}if(Tr.tested)return Tr.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),Tr.tested=!0,Tr.writable=!0}catch(t){Tr.tested=!0,Tr.writable=!1}return Tr.writable};const Rr=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),Ar=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},Or=async(e,t)=>{const r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch(s){return null}},Pr=async(e,t)=>{await e.removeItem(t)};class jr{constructor(){this.promise=new jr.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function Cr(e){const t=e.split(".");if(3!==t.length)throw new dr("Invalid JWT structure");for(let r=0;r<t.length;r++)if(!Vt.test(t[r]))throw new dr("JWT not in base64url format");return{header:JSON.parse(wr(t[0])),payload:JSON.parse(wr(t[1])),signature:vr(t[2]),raw:{header:t[0],payload:t[1]}}}function $r(e){return("0"+e.toString(16)).substr(-2)}async function Ir(e){if(!("undefined"!=typeof crypto&&void 0!==crypto.subtle&&"undefined"!=typeof TextEncoder))return e;const t=await async function(e){const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(r);return Array.from(s).map(e=>String.fromCharCode(e)).join("")}(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function xr(e,t,r=!1){const s=function(){const e=new Uint32Array(56);if("undefined"==typeof crypto){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length;let r="";for(let s=0;s<56;s++)r+=e.charAt(Math.floor(Math.random()*t));return r}return crypto.getRandomValues(e),Array.from(e,$r).join("")}();let n=s;r&&(n+="/recovery"),await Ar(e,`${t}-code-verifier`,n);const i=await Ir(s);return[i,s===i?"plain":"s256"]}jr.promiseConstructor=Promise;const Nr=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;const Ur=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Lr(e){if(!Ur.test(e))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Dr(e){if(!e.passkey)throw new Error("@supabase/auth-js: the passkey API is experimental and disabled by default. Enable it by passing `auth: { experimental: { passkey: true } }` to createClient (or to the GoTrueClient constructor).")}function Br(){return new Proxy({},{get:(e,t)=>{if("__isUserNotAvailableProxy"===t)return!0;if("symbol"==typeof t){const e=t.toString();if("Symbol(Symbol.toPrimitive)"===e||"Symbol(Symbol.toStringTag)"===e||"Symbol(util.inspect.custom)"===e)return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function qr(e){return JSON.parse(JSON.stringify(e))}const Hr=e=>{if("object"==typeof e&&null!==e){const t=e;if("string"==typeof t.msg)return t.msg;if("string"==typeof t.message)return t.message;if("string"==typeof t.error_description)return t.error_description;if("string"==typeof t.error)return t.error}return JSON.stringify(e)},Kr=[500,501,502,503,504,520,521,522,523,524,525,526,527,528,529,530];async function Mr(e){var t,r;if(!("object"==typeof(r=e)&&null!==r&&"status"in r&&"ok"in r&&"json"in r&&"function"==typeof r.json))throw new lr(Hr(e),0);if(Kr.includes(e.status))throw new lr(Hr(e),e.status);let s,n;try{s=await e.json()}catch(a){throw new Zt(Hr(a),a)}const i=function(e){const t=e.headers.get(Gt);if(!t)return null;if(!t.match(Nr))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch(r){return null}}(e);if(i&&i.getTime()>=zt.timestamp&&"object"==typeof s&&s&&"string"==typeof s.code?n=s.code:"object"==typeof s&&s&&"string"==typeof s.error_code&&(n=s.error_code),n){if("weak_password"===n)throw new ur(Hr(s),e.status,(null===(t=s.weak_password)||void 0===t?void 0:t.reasons)||[]);if("session_not_found"===n)throw new tr}else if("object"==typeof s&&s&&"object"==typeof s.weak_password&&s.weak_password&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0))throw new ur(Hr(s),e.status,s.weak_password.reasons);throw new Qt(Hr(s),e.status||500,n)}async function Wr(e,t,r,s){var n;const i=Object.assign({},null==s?void 0:s.headers);i[Gt]||(i[Gt]=zt.name),(null==s?void 0:s.jwt)&&(i.Authorization=`Bearer ${s.jwt}`);const a=null!==(n=null==s?void 0:s.query)&&void 0!==n?n:{};(null==s?void 0:s.redirectTo)&&(a.redirect_to=s.redirectTo);const o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",l=await async function(e,t,r,s,n,i){const a=((e,t,r,s)=>{const n={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==t?void 0:t.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),r))})(t,s,n,i);let o;try{o=await e(r,Object.assign({},a))}catch(l){throw new lr(Hr(l),0)}o.ok||await Mr(o);if(null==s?void 0:s.noResolveJson)return o;try{return await o.json()}catch(l){await Mr(l)}}(e,t,r+o,{headers:i,noResolveJson:null==s?void 0:s.noResolveJson},{},null==s?void 0:s.body);return(null==s?void 0:s.xform)?null==s?void 0:s.xform(l):{data:Object.assign({},l),error:null}}function Fr(e){var t;let r=null;var s;(function(e){return!!e.access_token&&!!e.refresh_token&&!!e.expires_in})(e)&&(r=Object.assign({},e),e.expires_at||(r.expires_at=(s=e.expires_in,Math.round(Date.now()/1e3)+s)));return{data:{session:r,user:null!==(t=e.user)&&void 0!==t?t:"string"==typeof(null==e?void 0:e.id)?e:null},error:null}}function Jr(e){const t=Fr(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 Gr(e){var t;return{data:{user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function zr(e){return{data:e,error:null}}function Vr(e){const{action_link:r,email_otp:s,hashed_token:n,redirect_to:i,verification_type:a}=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:n,redirect_to:i,verification_type:a},user:Object.assign({},o)},error:null}}function Yr(e){return e}const Xr=["global","local","others"];class Qr{constructor({url:e="",headers:t={},fetch:r,experimental:s}){this.url=e,this.headers=t,this.fetch=Rr(r),this.experimental=null!=s?s:{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(e,t=Xr[0]){if(Xr.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Xr.join(", ")}`);try{return await Wr(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(Xt(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await Wr(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:Gr})}catch(r){if(Xt(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{const{options:r}=e,s=t(e,["options"]),n=Object.assign(Object.assign({},s),r);return"newEmail"in s&&(n.new_email=null==s?void 0:s.newEmail,delete n.newEmail),await Wr(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:Vr,redirectTo:null==r?void 0:r.redirectTo})}catch(r){if(Xt(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await Wr(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Gr})}catch(t){if(Xt(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,s,n,i,a,o;try{const l={nextPage:null,lastPage:0,total:0},c=await Wr(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(r=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==r?r:"",per_page:null!==(n=null===(s=null==e?void 0:e.perPage)||void 0===s?void 0:s.toString())&&void 0!==n?n:""},xform:Yr});if(c.error)throw c.error;const h=await c.json(),u=null!==(i=c.headers.get("x-total-count"))&&void 0!==i?i:0,d=null!==(o=null===(a=c.headers.get("link"))||void 0===a?void 0:a.split(","))&&void 0!==o?o:[];return d.length>0&&(d.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l[`${r}Page`]=t}),l.total=parseInt(u)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(l){if(Xt(l))return{data:{users:[]},error:l};throw l}}async getUserById(e){Lr(e);try{return await Wr(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Gr})}catch(t){if(Xt(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){Lr(e);try{return await Wr(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:Gr})}catch(r){if(Xt(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){Lr(e);try{return await Wr(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:Gr})}catch(r){if(Xt(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){Lr(e.userId);try{const{data:t,error:r}=await Wr(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:r}}catch(t){if(Xt(t))return{data:null,error:t};throw t}}async _deleteFactor(e){Lr(e.userId),Lr(e.id);try{return{data:await Wr(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(Xt(t))return{data:null,error:t};throw t}}async _listOAuthClients(e){var t,r,s,n,i,a,o;try{const l={nextPage:null,lastPage:0,total:0},c=await Wr(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(r=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==r?r:"",per_page:null!==(n=null===(s=null==e?void 0:e.perPage)||void 0===s?void 0:s.toString())&&void 0!==n?n:""},xform:Yr});if(c.error)throw c.error;const h=await c.json(),u=null!==(i=c.headers.get("x-total-count"))&&void 0!==i?i:0,d=null!==(o=null===(a=c.headers.get("link"))||void 0===a?void 0:a.split(","))&&void 0!==o?o:[];return d.length>0&&(d.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l[`${r}Page`]=t}),l.total=parseInt(u)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(l){if(Xt(l))return{data:{clients:[]},error:l};throw l}}async _createOAuthClient(e){try{return await Wr(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(t){if(Xt(t))return{data:null,error:t};throw t}}async _getOAuthClient(e){try{return await Wr(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(t){if(Xt(t))return{data:null,error:t};throw t}}async _updateOAuthClient(e,t){try{return await Wr(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(r){if(Xt(r))return{data:null,error:r};throw r}}async _deleteOAuthClient(e){try{return await Wr(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(Xt(t))return{data:null,error:t};throw t}}async _regenerateOAuthClientSecret(e){try{return await Wr(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(t){if(Xt(t))return{data:null,error:t};throw t}}async _listCustomProviders(e){try{const t={};return(null==e?void 0:e.type)&&(t.type=e.type),await Wr(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:t,xform:e=>{var t;return{data:{providers:null!==(t=null==e?void 0:e.providers)&&void 0!==t?t:[]},error:null}}})}catch(t){if(Xt(t))return{data:{providers:[]},error:t};throw t}}async _createCustomProvider(e){try{return await Wr(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(t){if(Xt(t))return{data:null,error:t};throw t}}async _getCustomProvider(e){try{return await Wr(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(t){if(Xt(t))return{data:null,error:t};throw t}}async _updateCustomProvider(e,t){try{return await Wr(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(r){if(Xt(r))return{data:null,error:r};throw r}}async _deleteCustomProvider(e){try{return await Wr(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(Xt(t))return{data:null,error:t};throw t}}async _adminListPasskeys(e){Dr(this.experimental),Lr(e.userId);try{return await Wr(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(t){if(Xt(t))return{data:null,error:t};throw t}}async _adminDeletePasskey(e){Dr(this.experimental),Lr(e.userId),Lr(e.passkeyId);try{return await Wr(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(Xt(t))return{data:null,error:t};throw t}}}function Zr(e={}){return{getItem:t=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:t=>{delete e[t]}}}globalThis&&Er()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug");class es extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}function ts(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw new Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function rs(e){const t=(new TextEncoder).encode(e);return"0x"+Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}class ss extends Error{constructor({message:e,code:t,cause:r,name:s}){var n;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=null!==(n=null!=s?s:r instanceof Error?r.name:void 0)&&void 0!==n?n:"Unknown Error",this.code=t}toJSON(){return{name:this.name,message:this.message,code:this.code}}}class ns extends ss{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}function is({error:e,options:t}){var r,s,n;const{publicKey:i}=t;if(!i)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new ss({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if(!0===(null===(r=i.authenticatorSelection)||void 0===r?void 0:r.requireResidentKey))return new ss({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if("conditional"===t.mediation&&"required"===(null===(s=i.authenticatorSelection)||void 0===s?void 0:s.userVerification))return new ss({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if("required"===(null===(n=i.authenticatorSelection)||void 0===n?void 0:n.userVerification))return new ss({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 ss({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new ss({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("NotSupportedError"===e.name){return 0===i.pubKeyCredParams.filter(e=>"public-key"===e.type).length?new ss({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new ss({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e})}if("SecurityError"===e.name){const t=window.location.hostname;if(!ds(t))return new ss({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(i.rp.id!==t)return new ss({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new ss({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 ss({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 ss({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function as({error:e,options:t}){const{publicKey:r}=t;if(!r)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new ss({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new ss({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("SecurityError"===e.name){const t=window.location.hostname;if(!ds(t))return new ss({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(r.rpId!==t)return new ss({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 ss({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 ss({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}const os=new class{createNewAbortSignal(){if(this.controller){const e=new Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}};function ls(e){if(!e)throw new Error("Credential creation options are required");if("undefined"!=typeof PublicKeyCredential&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(e);const{challenge:r,user:s,excludeCredentials:n}=e,i=t(e,["challenge","user","excludeCredentials"]),a=vr(r).buffer,o=Object.assign(Object.assign({},s),{id:vr(s.id).buffer}),l=Object.assign(Object.assign({},i),{challenge:a,user:o});if(n&&n.length>0){l.excludeCredentials=new Array(n.length);for(let e=0;e<n.length;e++){const t=n[e];l.excludeCredentials[e]=Object.assign(Object.assign({},t),{id:vr(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return l}function cs(e){if(!e)throw new Error("Credential request options are required");if("undefined"!=typeof PublicKeyCredential&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseRequestOptionsFromJSON)return PublicKeyCredential.parseRequestOptionsFromJSON(e);const{challenge:r,allowCredentials:s}=e,n=t(e,["challenge","allowCredentials"]),i=vr(r).buffer,a=Object.assign(Object.assign({},n),{challenge:i});if(s&&s.length>0){a.allowCredentials=new Array(s.length);for(let e=0;e<s.length;e++){const t=s[e];a.allowCredentials[e]=Object.assign(Object.assign({},t),{id:vr(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return a}function hs(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();const r=e;return{id:e.id,rawId:e.id,response:{attestationObject:kr(new Uint8Array(e.response.attestationObject)),clientDataJSON:kr(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:null!==(t=r.authenticatorAttachment)&&void 0!==t?t:void 0}}function us(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();const r=e,s=e.getClientExtensionResults(),n=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:kr(new Uint8Array(n.authenticatorData)),clientDataJSON:kr(new Uint8Array(n.clientDataJSON)),signature:kr(new Uint8Array(n.signature)),userHandle:n.userHandle?kr(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:null!==(t=r.authenticatorAttachment)&&void 0!==t?t:void 0}}function ds(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function ps(){var e,t;return!!(Sr()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&"function"==typeof(null===(e=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===e?void 0:e.create)&&"function"==typeof(null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.get))}async function fs(e){try{const t=await navigator.credentials.create(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new ns("Browser returned unexpected credential type",t)}:{data:null,error:new ns("Empty credential response",t)}}catch(t){return{data:null,error:is({error:t,options:e})}}}async function gs(e){try{const t=await navigator.credentials.get(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new ns("Browser returned unexpected credential type",t)}:{data:null,error:new ns("Empty credential response",t)}}catch(t){return{data:null,error:as({error:t,options:e})}}}const ys={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},ms={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function ws(...e){const t=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),r=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),s={};for(const n of e)if(n)for(const e in n){const i=n[e];if(void 0!==i)if(Array.isArray(i))s[e]=i;else if(r(i))s[e]=i;else if(t(i)){const r=s[e];t(r)?s[e]=ws(r,i):s[e]=ws(i)}else s[e]=i}return s}class bs{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},n){var i;try{const{data:a,error:o}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!a)return{data:null,error:o};const l=null!=s?s:os.createNewAbortSignal();if("create"===a.webauthn.type){const{user:e}=a.webauthn.credential_options.publicKey;if(!e.name){const t=r;if(t)e.name=`${e.id}:${t}`;else{const t=(await this.client.getUser()).data.user,r=(null===(i=null==t?void 0:t.user_metadata)||void 0===i?void 0:i.name)||(null==t?void 0:t.email)||(null==t?void 0:t.id)||"User";e.name=`${e.id}:${r}`}}e.displayName||(e.displayName=e.name)}switch(a.webauthn.type){case"create":{const t=function(e,t){return ws(ys,e,t||{})}(a.webauthn.credential_options.publicKey,null==n?void 0:n.create),{data:r,error:s}=await fs({publicKey:t,signal:l});return r?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:r}},error:null}:{data:null,error:s}}case"request":{const t=function(e,t){return ws(ms,e,t||{})}(a.webauthn.credential_options.publicKey,null==n?void 0:n.request),{data:r,error:s}=await gs(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:t,signal:l}));return r?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:r}},error:null}:{data:null,error:s}}}}catch(a){return Xt(a)?{data:null,error:a}:{data:null,error:new Zt("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:r=("undefined"!=typeof window?[window.location.origin]:void 0),signal:s}={}},n){if(!t)return{data:null,error:new Yt("rpId is required for WebAuthn authentication")};try{if(!ps())return{data:null,error:new Zt("Browser does not support WebAuthn",null)};const{data:i,error:a}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:n});if(!i)return{data:null,error:a};const{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(i){return Xt(i)?{data:null,error:i}:{data:null,error:new Zt("Unexpected error in authenticate",i)}}}async _register({friendlyName:e,webauthn:{rpId:t=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:r=("undefined"!=typeof window?[window.location.origin]:void 0),signal:s}={}},n){if(!t)return{data:null,error:new Yt("rpId is required for WebAuthn registration")};try{if(!ps())return{data:null,error:new Zt("Browser does not support WebAuthn",null)};const{data:i,error:a}=await this._enroll({friendlyName:e});if(!i)return await this.client.mfa.listFactors().then(t=>{var r;return null===(r=t.data)||void 0===r?void 0:r.all.find(t=>"webauthn"===t.factor_type&&t.friendly_name===e&&"unverified"!==t.status)}).then(e=>e?this.client.mfa.unenroll({factorId:null==e?void 0:e.id}):void 0),{data:null,error:a};const{data:o,error:l}=await this._challenge({factorId:i.id,friendlyName:i.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:n});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:l}}catch(i){return Xt(i)?{data:null,error:i}:{data:null,error:new Zt("Unexpected error in register",i)}}}}!function(){if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){"undefined"!=typeof self&&(self.globalThis=self)}}();const vs={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Jt,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}},_s={};class ks{get jwks(){var e,t;return null!==(t=null===(e=_s[this.storageKey])||void 0===e?void 0:e.jwks)&&void 0!==t?t:{keys:[]}}set jwks(e){_s[this.storageKey]=Object.assign(Object.assign({},_s[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return null!==(t=null===(e=_s[this.storageKey])||void 0===e?void 0:e.cachedAt)&&void 0!==t?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){_s[this.storageKey]=Object.assign(Object.assign({},_s[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this._pendingInitNotifications=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const n=Object.assign(Object.assign({},vs),e);if(this.storageKey=n.storageKey,this.instanceID=null!==(t=ks.nextInstanceID[this.storageKey])&&void 0!==t?t:0,ks.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!n.debug,"function"==typeof n.debug&&(this.logger=n.debug),this.instanceID>0&&Sr()){this._logPrefix();this.logDebugMessages}if(this.persistSession=n.persistSession,this.autoRefreshToken=n.autoRefreshToken,this.experimental=null!==(r=n.experimental)&&void 0!==r?r:{},this.admin=new Qr({url:n.url,headers:n.headers,fetch:n.fetch,experimental:this.experimental}),this.url=n.url,this.headers=n.headers,this.fetch=Rr(n.fetch),this.detectSessionInUrl=n.detectSessionInUrl,this.flowType=n.flowType,this.hasCustomAuthorizationHeader=n.hasCustomAuthorizationHeader,this.throwOnError=n.throwOnError,this.lockAcquireTimeout=n.lockAcquireTimeout,null!=n.lock&&(this.lock=n.lock),this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new bs(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.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(n.storage?this.storage=n.storage:Er()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Zr(this.memoryStorage)),n.userStorage&&(this.userStorage=n.userStorage)):(this.memoryStorage={},this.storage=Zr(this.memoryStorage)),Sr()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){}null===(s=this.broadcastChannel)||void 0===s||s.addEventListener("message",async e=>{this._debug("received broadcast notification from other tab or client",e),"TOKEN_REFRESHED"!==e.data.event&&"SIGNED_IN"!==e.data.event||(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(e.data.event,e.data.session,!1)}catch(t){this._debug("#broadcastChannel","error",t)}})}n.skipAutoInitialize||this.initialize().catch(e=>{this._debug("#initialize()","error",e)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Mt}) ${(new Date).toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){var e;if(this.initializePromise)return await this.initializePromise;this._pendingInitNotifications=[],this.initializePromise=(async()=>null!=this.lock?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())();const t=await this.initializePromise,r=null!==(e=this._pendingInitNotifications)&&void 0!==e?e:[];this._pendingInitNotifications=null;for(const s of r)await this._notifyAllSubscribers(s.event,s.session,s.broadcast);return t}async _initialize(){var e;try{let t={},r="none";if(Sr()&&(t=function(e){const t={},r=new URL(e);if(r.hash&&"#"===r.hash[0])try{new URLSearchParams(r.hash.substring(1)).forEach((e,r)=>{t[r]=e})}catch(s){}return r.searchParams.forEach((e,r)=>{t[r]=e}),t}(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),Sr()&&this.detectSessionInUrl&&"none"!==r){const{data:s,error:n}=await this._getSessionFromURL(t,r);if(n){if(this._debug("#_initialize()","error detecting session from URL",n),function(e){return Xt(e)&&"AuthImplicitGrantRedirectError"===e.name}(n)){const t=null===(e=n.details)||void 0===e?void 0:e.code;if("identity_already_exists"===t||"identity_not_found"===t||"single_identity_not_deletable"===t)return{error:n}}return{error:n}}const{session:i,redirectType:a}=s;return this._debug("#_initialize()","detected session in URL",i,"redirect type",a),await this._saveSession(i),setTimeout(async()=>{"recovery"===a?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return Xt(t)?this._returnResult({error:t}):this._returnResult({error:new Zt("Unexpected error during initialization",t)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{const n=await Wr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:null!==(r=null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.data)&&void 0!==r?r:{},gotrue_meta_security:{captcha_token:null===(s=null==e?void 0:e.options)||void 0===s?void 0:s.captchaToken}},xform:Fr}),{data:i,error:a}=n;if(a||!i)return this._returnResult({data:{user:null,session:null},error:a});const o=i.session,l=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",o)),this._returnResult({data:{user:l,session:o},error:null})}catch(n){if(Xt(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signUp(e){var t,r,s;try{let n;if("email"in e){const{email:r,password:s,options:i}=e;let a=null,o=null;"pkce"===this.flowType&&([a,o]=await xr(this.storage,this.storageKey)),n=await Wr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:null==i?void 0:i.emailRedirectTo,body:{email:r,password:s,data:null!==(t=null==i?void 0:i.data)&&void 0!==t?t:{},gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:a,code_challenge_method:o},xform:Fr})}else{if(!("phone"in e))throw new nr("You must provide either an email or phone number and a password");{const{phone:t,password:i,options:a}=e;n=await Wr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:i,data:null!==(r=null==a?void 0:a.data)&&void 0!==r?r:{},channel:null!==(s=null==a?void 0:a.channel)&&void 0!==s?s:"sms",gotrue_meta_security:{captcha_token:null==a?void 0:a.captchaToken}},xform:Fr})}}const{data:i,error:a}=n;if(a||!i)return await Pr(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});const o=i.session,l=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",o)),this._returnResult({data:{user:l,session:o},error:null})}catch(n){if(await Pr(this.storage,`${this.storageKey}-code-verifier`),Xt(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithPassword(e){try{let t;if("email"in e){const{email:r,password:s,options:n}=e;t=await Wr(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:r,password:s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},xform:Jr})}else{if(!("phone"in e))throw new nr("You must provide either an email or phone number and a password");{const{phone:r,password:s,options:n}=e;t=await Wr(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:r,password:s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},xform:Jr})}}const{data:r,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){const e=new sr;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(t){if(Xt(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOAuth(e){var t,r,s,n;return await this._handleProviderSignIn(e.provider,{redirectTo:null===(t=e.options)||void 0===t?void 0:t.redirectTo,scopes:null===(r=e.options)||void 0===r?void 0:r.scopes,queryParams:null===(s=e.options)||void 0===s?void 0:s.queryParams,skipBrowserRedirect:null===(n=e.options)||void 0===n?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,null!=this.lock?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e)):this._exchangeCodeForSession(e)}async signInWithWeb3(e){const{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,s,n,i,a,o,l,c,h,u;let d,p;if("message"in e)d=e.message,p=e.signature;else{const{chain:h,wallet:u,statement:f,options:g}=e;let y;if(Sr())if("object"==typeof u)y=u;else{const e=window;if(!("ethereum"in e)||"object"!=typeof e.ethereum||!("request"in e.ethereum)||"function"!=typeof e.ethereum.request)throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.");y=e.ethereum}else{if("object"!=typeof u||!(null==g?void 0:g.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");y=u}const m=new URL(null!==(t=null==g?void 0:g.url)&&void 0!==t?t:window.location.href),w=await y.request({method:"eth_requestAccounts"}).then(e=>e).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!w||0===w.length)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const b=ts(w[0]);let v=null===(r=null==g?void 0:g.signInWithEthereum)||void 0===r?void 0:r.chainId;if(!v){const e=await y.request({method:"eth_chainId"});v=parseInt(e,16)}d=function(e){var t;const{chainId:r,domain:s,expirationTime:n,issuedAt:i=new Date,nonce:a,notBefore:o,requestId:l,resources:c,scheme:h,uri:u,version:d}=e;if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!s)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!u)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if("1"!==d)throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${d}`);if(null===(t=e.statement)||void 0===t?void 0:t.includes("\n"))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);const p=`${h?`${h}://${s}`:s} wants you to sign in with your Ethereum account:\n${ts(e.address)}\n\n${e.statement?`${e.statement}\n`:""}`;let f=`URI: ${u}\nVersion: ${d}\nChain ID: ${r}${a?`\nNonce: ${a}`:""}\nIssued At: ${i.toISOString()}`;if(n&&(f+=`\nExpiration Time: ${n.toISOString()}`),o&&(f+=`\nNot Before: ${o.toISOString()}`),l&&(f+=`\nRequest ID: ${l}`),c){let e="\nResources:";for(const t of c){if(!t||"string"!=typeof t)throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${t}`);e+=`\n- ${t}`}f+=e}return`${p}\n${f}`}({domain:m.host,address:b,statement:f,uri:m.href,version:"1",chainId:v,nonce:null===(s=null==g?void 0:g.signInWithEthereum)||void 0===s?void 0:s.nonce,issuedAt:null!==(i=null===(n=null==g?void 0:g.signInWithEthereum)||void 0===n?void 0:n.issuedAt)&&void 0!==i?i:new Date,expirationTime:null===(a=null==g?void 0:g.signInWithEthereum)||void 0===a?void 0:a.expirationTime,notBefore:null===(o=null==g?void 0:g.signInWithEthereum)||void 0===o?void 0:o.notBefore,requestId:null===(l=null==g?void 0:g.signInWithEthereum)||void 0===l?void 0:l.requestId,resources:null===(c=null==g?void 0:g.signInWithEthereum)||void 0===c?void 0:c.resources}),p=await y.request({method:"personal_sign",params:[rs(d),b]})}try{const{data:t,error:r}=await Wr(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:d,signature:p},(null===(h=e.options)||void 0===h?void 0:h.captchaToken)?{gotrue_meta_security:{captcha_token:null===(u=e.options)||void 0===u?void 0:u.captchaToken}}:null),xform:Fr});if(r)throw r;if(!t||!t.session||!t.user){const e=new sr;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(f){if(Xt(f))return this._returnResult({data:{user:null,session:null},error:f});throw f}}async signInWithSolana(e){var t,r,s,n,i,a,o,l,c,h,u,d;let p,f;if("message"in e)p=e.message,f=e.signature;else{const{chain:u,wallet:d,statement:g,options:y}=e;let m;if(Sr())if("object"==typeof d)m=d;else{const e=window;if(!("solana"in e)||"object"!=typeof e.solana||!("signIn"in e.solana&&"function"==typeof e.solana.signIn||"signMessage"in e.solana&&"function"==typeof e.solana.signMessage))throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.");m=e.solana}else{if("object"!=typeof d||!(null==y?void 0:y.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");m=d}const w=new URL(null!==(t=null==y?void 0:y.url)&&void 0!==t?t:window.location.href);if("signIn"in m&&m.signIn){const e=await m.signIn(Object.assign(Object.assign(Object.assign({issuedAt:(new Date).toISOString()},null==y?void 0:y.signInWithSolana),{version:"1",domain:w.host,uri:w.href}),g?{statement:g}:null));let t;if(Array.isArray(e)&&e[0]&&"object"==typeof e[0])t=e[0];else{if(!(e&&"object"==typeof e&&"signedMessage"in e&&"signature"in e))throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");t=e}if(!("signedMessage"in t&&"signature"in t&&("string"==typeof t.signedMessage||t.signedMessage instanceof Uint8Array)&&t.signature instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields");p="string"==typeof t.signedMessage?t.signedMessage:(new TextDecoder).decode(t.signedMessage),f=t.signature}else{if(!("signMessage"in m&&"function"==typeof m.signMessage&&"publicKey"in m&&"object"==typeof m&&m.publicKey&&"toBase58"in m.publicKey&&"function"==typeof m.publicKey.toBase58))throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=[`${w.host} wants you to sign in with your Solana account:`,m.publicKey.toBase58(),...g?["",g,""]:[""],"Version: 1",`URI: ${w.href}`,`Issued At: ${null!==(s=null===(r=null==y?void 0:y.signInWithSolana)||void 0===r?void 0:r.issuedAt)&&void 0!==s?s:(new Date).toISOString()}`,...(null===(n=null==y?void 0:y.signInWithSolana)||void 0===n?void 0:n.notBefore)?[`Not Before: ${y.signInWithSolana.notBefore}`]:[],...(null===(i=null==y?void 0:y.signInWithSolana)||void 0===i?void 0:i.expirationTime)?[`Expiration Time: ${y.signInWithSolana.expirationTime}`]:[],...(null===(a=null==y?void 0:y.signInWithSolana)||void 0===a?void 0:a.chainId)?[`Chain ID: ${y.signInWithSolana.chainId}`]:[],...(null===(o=null==y?void 0:y.signInWithSolana)||void 0===o?void 0:o.nonce)?[`Nonce: ${y.signInWithSolana.nonce}`]:[],...(null===(l=null==y?void 0:y.signInWithSolana)||void 0===l?void 0:l.requestId)?[`Request ID: ${y.signInWithSolana.requestId}`]:[],...(null===(h=null===(c=null==y?void 0:y.signInWithSolana)||void 0===c?void 0:c.resources)||void 0===h?void 0:h.length)?["Resources",...y.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join("\n");const e=await m.signMessage((new TextEncoder).encode(p),"utf8");if(!(e&&e instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");f=e}}try{const{data:t,error:r}=await Wr(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:kr(f)},(null===(u=e.options)||void 0===u?void 0:u.captchaToken)?{gotrue_meta_security:{captcha_token:null===(d=e.options)||void 0===d?void 0:d.captchaToken}}:null),xform:Fr});if(r)throw r;if(!t||!t.session||!t.user){const e=new sr;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(g){if(Xt(g))return this._returnResult({data:{user:null,session:null},error:g});throw g}}async _exchangeCodeForSession(e){const t=await Or(this.storage,`${this.storageKey}-code-verifier`),[r,s]=(null!=t?t:"").split("/");try{if(!r&&"pkce"===this.flowType)throw new or;const{data:t,error:n}=await Wr(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:Fr});if(await Pr(this.storage,`${this.storageKey}-code-verifier`),n)throw n;if(!t||!t.session||!t.user){const e=new sr;return this._returnResult({data:{user:null,session:null,redirectType:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("recovery"===s?"PASSWORD_RECOVERY":"SIGNED_IN",t.session)),this._returnResult({data:Object.assign(Object.assign({},t),{redirectType:null!=s?s:null}),error:n})}catch(n){if(await Pr(this.storage,`${this.storageKey}-code-verifier`),Xt(n))return this._returnResult({data:{user:null,session:null,redirectType:null},error:n});throw n}}async signInWithIdToken(e){try{const{options:t,provider:r,token:s,access_token:n,nonce:i}=e,a=await Wr(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:n,nonce:i,gotrue_meta_security:{captcha_token:null==t?void 0:t.captchaToken}},xform:Fr}),{data:o,error:l}=a;if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!o||!o.session||!o.user){const e=new sr;return this._returnResult({data:{user:null,session:null},error:e})}return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",o.session)),this._returnResult({data:o,error:l})}catch(t){if(Xt(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOtp(e){var t,r,s,n,i;try{if("email"in e){const{email:s,options:n}=e;let i=null,a=null;"pkce"===this.flowType&&([i,a]=await xr(this.storage,this.storageKey));const{error:o}=await Wr(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:s,data:null!==(t=null==n?void 0:n.data)&&void 0!==t?t:{},create_user:null===(r=null==n?void 0:n.shouldCreateUser)||void 0===r||r,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken},code_challenge:i,code_challenge_method:a},redirectTo:null==n?void 0:n.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}if("phone"in e){const{phone:t,options:r}=e,{data:a,error:o}=await Wr(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:null!==(s=null==r?void 0:r.data)&&void 0!==s?s:{},create_user:null===(n=null==r?void 0:r.shouldCreateUser)||void 0===n||n,gotrue_meta_security:{captcha_token:null==r?void 0:r.captchaToken},channel:null!==(i=null==r?void 0:r.channel)&&void 0!==i?i:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:null==a?void 0:a.message_id},error:o})}throw new nr("You must provide either an email or phone number.")}catch(a){if(await Pr(this.storage,`${this.storageKey}-code-verifier`),Xt(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var t,r;try{let s,n;"options"in e&&(s=null===(t=e.options)||void 0===t?void 0:t.redirectTo,n=null===(r=e.options)||void 0===r?void 0:r.captchaToken);const{data:i,error:a}=await Wr(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:s,xform:Fr});if(a)throw a;if(!i){throw new Error("An error occurred on token verification.")}const o=i.session,l=i.user;return(null==o?void 0:o.access_token)&&(await this._saveSession(o),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",o)),this._returnResult({data:{user:l,session:o},error:null})}catch(s){if(Xt(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(e){var t,r,s,n,i;try{let a=null,o=null;"pkce"===this.flowType&&([a,o]=await xr(this.storage,this.storageKey));const l=await Wr(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:null!==(r=null===(t=e.options)||void 0===t?void 0:t.redirectTo)&&void 0!==r?r:void 0}),(null===(s=null==e?void 0:e.options)||void 0===s?void 0:s.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:o}),headers:this.headers,xform:zr});return(null===(n=l.data)||void 0===n?void 0:n.url)&&Sr()&&!(null===(i=e.options)||void 0===i?void 0:i.skipBrowserRedirect)&&window.location.assign(l.data.url),this._returnResult(l)}catch(a){if(await Pr(this.storage,`${this.storageKey}-code-verifier`),Xt(a))return this._returnResult({data:null,error:a});throw a}}async reauthenticate(){return await this.initializePromise,null!=this.lock?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new tr;const{error:s}=await Wr(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(Xt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const t=`${this.url}/resend`;if("email"in e){const{email:r,type:s,options:n}=e;let i=null,a=null;"pkce"===this.flowType&&([i,a]=await xr(this.storage,this.storageKey));const{error:o}=await Wr(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken},code_challenge:i,code_challenge_method:a},redirectTo:null==n?void 0:n.emailRedirectTo});return o&&await Pr(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:o})}if("phone"in e){const{phone:r,type:s,options:n}=e,{data:i,error:a}=await Wr(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:null==i?void 0:i.message_id},error:a})}throw new nr("You must provide either an email or phone number and a type")}catch(t){if(await Pr(this.storage,`${this.storageKey}-code-verifier`),Xt(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async getSession(){return await this.initializePromise,null!=this.lock?await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e)):await this._useSession(async e=>e)}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch(e){}})()),r}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(t){}})()),await e;this.pendingInLock.length;){const e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),null==this.lock||this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",(new Error).stack);try{let e=null;const t=await Or(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),null!==t&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const r=!!e.expires_at&&1e3*e.expires_at-Date.now()<Ft;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.userStorage){const t=await Or(this.userStorage,this.storageKey+"-user");(null==t?void 0:t.user)?e.user=t.user:e.user=Br()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const t={value:this.suppressGetSessionWarning};e.user=function(e,t){return new Proxy(e,{get:(e,r,s)=>{if("__isInsecureUserWarningProxy"===r)return!0;if("symbol"==typeof r){const 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||(t.value=!0),Reflect.get(e,r,s)}})}(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:s,error:n}=await this._callRefreshToken(e.refresh_token);if(n){if(!!(e.expires_at&&1e3*e.expires_at>Date.now())){const t=await Or(this.storage,this.storageKey);if(t&&t.refresh_token===e.refresh_token)return this._returnResult({data:{session:e},error:null})}return this._returnResult({data:{session:null},error:n})}return this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);let t;return await this.initializePromise,t=null!=this.lock?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):await this._getUser(),t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await Wr(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Gr}):await this._useSession(async e=>{var t,r,s;const{data:n,error:i}=e;if(i)throw i;return(null===(t=n.session)||void 0===t?void 0:t.access_token)||this.hasCustomAuthorizationHeader?await Wr(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!==(s=null===(r=n.session)||void 0===r?void 0:r.access_token)&&void 0!==s?s:void 0,xform:Gr}):{data:{user:null},error:new tr}})}catch(t){if(Xt(t))return rr(t)&&(await this._removeSession(),await Pr(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:t});throw t}}async updateUser(e,t={}){return await this.initializePromise,null!=this.lock?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t)):await this._updateUser(e,t)}async _updateUser(e,t={}){try{return await this._useSession(async r=>{const{data:s,error:n}=r;if(n)throw n;if(!s.session)throw new tr;const i=s.session;let a=null,o=null;"pkce"===this.flowType&&null!=e.email&&([a,o]=await xr(this.storage,this.storageKey));const{data:l,error:c}=await Wr(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:o}),jwt:i.access_token,xform:Gr});if(c)throw c;return i.user=l.user,await this._saveSession(i),await this._notifyAllSubscribers("USER_UPDATED",i),this._returnResult({data:{user:i.user},error:null})})}catch(r){if(await Pr(this.storage,`${this.storageKey}-code-verifier`),Xt(r))return this._returnResult({data:{user:null},error:r});throw r}}async setSession(e){return await this.initializePromise,null!=this.lock?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e)):await this._setSession(e)}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new tr;const t=Date.now()/1e3;let r=t,s=!0,n=null;const{payload:i}=Cr(e.access_token);if(i.exp&&(r=i.exp,s=r<=t),s){const{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};n=t}else{const{data:s,error:i}=await this._getUser(e.access_token);if(i)return this._returnResult({data:{user:null,session:null},error:i});n={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(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return this._returnResult({data:{user:n.user,session:n},error:null})}catch(t){if(Xt(t))return this._returnResult({data:{session:null,user:null},error:t});throw t}}async refreshSession(e){return await this.initializePromise,null!=this.lock?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e)):await this._refreshSession(e)}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){const{data:s,error:n}=t;if(n)throw n;e=null!==(r=s.session)&&void 0!==r?r:void 0}if(!(null==e?void 0:e.refresh_token))throw new tr;const{data:s,error:n}=await this._callRefreshToken(e.refresh_token);return n?this._returnResult({data:{user:null,session:null},error:n}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(t){if(Xt(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async _getSessionFromURL(e,t){var r;try{if(!Sr())throw new ir("No browser detected.");if(e.error||e.error_description||e.error_code)throw new ir(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 ar("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new ir("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new ar("No code detected.");const{data:t,error:s}=await this._exchangeCodeForSession(e.code);if(s)throw s;const n=new URL(window.location.href);return n.searchParams.delete("code"),window.history.replaceState(window.history.state,"",n.toString()),{data:{session:t.session,redirectType:null!==(r=t.redirectType)&&void 0!==r?r:null},error:null}}const{provider_token:s,provider_refresh_token:n,access_token:i,refresh_token:a,expires_in:o,expires_at:l,token_type:c}=e;if(!(i&&o&&a&&c))throw new ir("No session defined in URL");const h=Math.round(Date.now()/1e3),u=parseInt(o);let d=h+u;l&&(d=parseInt(l));const{data:p,error:f}=await this._getUser(i);if(f)throw f;const g={provider_token:s,provider_refresh_token:n,access_token:i,expires_in:u,expires_at:d,refresh_token:a,token_type:c,user:p.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:g,redirectType:e.type},error:null})}catch(s){if(Xt(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_isImplicitGrantCallback(e){return"function"==typeof this.detectSessionInUrl?this.detectSessionInUrl(new URL(window.location.href),e):Boolean(e.access_token||e.error||e.error_description||e.error_code)}async _isPKCECallback(e){const t=await Or(this.storage,`${this.storageKey}-code-verifier`);return!(!e.code||!t)}async signOut(e={scope:"global"}){return await this.initializePromise,null!=this.lock?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e)):await this._signOut(e)}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;const s=async()=>{await this._removeSession(),await Pr(this.storage,`${this.storageKey}-code-verifier`)},{data:n,error:i}=t;if(i&&!rr(i))return this._returnResult({error:i});const a=null===(r=n.session)||void 0===r?void 0:r.access_token;if(a){const{error:t}=await this.admin.signOut(a,e);if(t&&(!function(e){return Xt(e)&&"AuthApiError"===e.name}(t)||404!==t.status&&401!==t.status&&403!==t.status)&&!rr(t))return"others"!==e&&await s(),this._returnResult({error:t})}return"others"!==e&&await s(),this._returnResult({error:null})})}onAuthStateChange(e){const 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,null!=this.lock?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)}):await this._emitInitialSession(t)})(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{const{data:{session:s},error:n}=t;if(n)throw n;await(null===(r=this.stateChangeEmitters.get(e))||void 0===r?void 0:r.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(n){await(null===(s=this.stateChangeEmitters.get(e))||void 0===s?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),rr(n)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null;"pkce"===this.flowType&&([r,s]=await xr(this.storage,this.storageKey,!0));try{return await Wr(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(n){if(await Pr(this.storage,`${this.storageKey}-code-verifier`),Xt(n))return this._returnResult({data:null,error:n});throw n}}async getUserIdentities(){var e;try{const{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:null!==(e=t.user.identities)&&void 0!==e?e:[]},error:null})}catch(t){if(Xt(t))return this._returnResult({data:null,error:t});throw t}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{const{data:r,error:s}=await this._useSession(async t=>{var r,s,n,i,a;const{data:o,error:l}=t;if(l)throw l;const c=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:null===(r=e.options)||void 0===r?void 0:r.redirectTo,scopes:null===(s=e.options)||void 0===s?void 0:s.scopes,queryParams:null===(n=e.options)||void 0===n?void 0:n.queryParams,skipBrowserRedirect:!0});return await Wr(this.fetch,"GET",c,{headers:this.headers,jwt:null!==(a=null===(i=o.session)||void 0===i?void 0:i.access_token)&&void 0!==a?a:void 0})});if(s)throw s;return Sr()&&!(null===(t=e.options)||void 0===t?void 0:t.skipBrowserRedirect)&&window.location.assign(null==r?void 0:r.url),this._returnResult({data:{provider:e.provider,url:null==r?void 0:r.url},error:null})}catch(r){if(Xt(r))return this._returnResult({data:{provider:e.provider,url:null},error:r});throw r}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{const{error:s,data:{session:n}}=t;if(s)throw s;const{options:i,provider:a,token:o,access_token:l,nonce:c}=e,h=await Wr(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:null!==(r=null==n?void 0:n.access_token)&&void 0!==r?r:void 0,body:{provider:a,id_token:o,access_token:l,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:Fr}),{data:u,error:d}=h;return d?this._returnResult({data:{user:null,session:null},error:d}):u&&u.session&&u.user?(u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers("USER_UPDATED",u.session)),this._returnResult({data:u,error:d})):this._returnResult({data:{user:null,session:null},error:new sr})}catch(s){if(await Pr(this.storage,`${this.storageKey}-code-verifier`),Xt(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;const{data:n,error:i}=t;if(i)throw i;return await Wr(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:null!==(s=null===(r=n.session)||void 0===r?void 0:r.access_token)&&void 0!==s?s:void 0})})}catch(t){if(Xt(t))return this._returnResult({data:null,error:t});throw t}}async _refreshAccessToken(e){const t="#_refreshAccessToken()";this._debug(t,"begin");try{const n=Date.now();return await(r=async r=>(r>0&&await async function(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await Wr(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Fr})),s=(e,t)=>{const r=200*Math.pow(2,e);return t&&cr(t)&&Date.now()+r-n<Wt},new Promise((e,t)=>{(async()=>{for(let i=0;i<1/0;i++)try{const t=await r(i);if(!s(i,null,t))return void e(t)}catch(n){if(!s(i,n))return void t(n)}})()}))}catch(n){if(this._debug(t,"error",n),Xt(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}finally{this._debug(t,"end")}var r,s}_isValidSession(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),Sr()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e,t;const r="#_recoverAndRefresh()";this._debug(r,"begin");try{const n=await Or(this.storage,this.storageKey);if(n&&this.userStorage){let t=await Or(this.userStorage,this.storageKey+"-user");this.storage.isServer||!Object.is(this.storage,this.userStorage)||t||(t={user:n.user},await Ar(this.userStorage,this.storageKey+"-user",t)),n.user=null!==(e=null==t?void 0:t.user)&&void 0!==e?e:Br()}else if(n&&!n.user&&!n.user){const e=await Or(this.storage,this.storageKey+"-user");e&&(null==e?void 0:e.user)?(n.user=e.user,await Pr(this.storage,this.storageKey+"-user"),await Ar(this.storage,this.storageKey,n)):n.user=Br()}if(this._debug(r,"session from storage",n),!this._isValidSession(n))return this._debug(r,"session is not valid"),void(null!==n&&await this._removeSession());const i=1e3*(null!==(t=n.expires_at)&&void 0!==t?t:1/0)-Date.now()<Ft;if(this._debug(r,`session has${i?"":" not"} expired with margin of 90000s`),i){if(this.autoRefreshToken&&n.refresh_token){const{error:e}=await this._callRefreshToken(n.refresh_token);e&&(!function(e){return Xt(e)&&"AuthRefreshDiscardedError"===e.name}(e)?this._debug(r,"refresh failed",e):this._debug(r,"refresh discarded by commit guard",e))}}else if(n.user&&!0===n.user.__isUserNotAvailableProxy)try{const{data:e,error:t}=await this._getUser(n.access_token);!t&&(null==e?void 0:e.user)?(n.user=e.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(s){this._debug(r,"error getting user data, skipping SIGNED_IN notification",s)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){return void this._debug(r,"error",n)}finally{this._debug(r,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new tr;if(this.refreshingDeferred)return this.refreshingDeferred.promise;if(this.lastRefreshFailure&&this.lastRefreshFailure.refreshToken===e&&Date.now()<this.lastRefreshFailure.expiresAt)return this._debug("#_callRefreshToken()","returning cached failure (cooldown active)"),this.lastRefreshFailure.result;const s="#_callRefreshToken()";this._debug(s,"begin");try{this.refreshingDeferred=new jr;const t=await Or(this.storage,this.storageKey),{data:r,error:n}=await this._refreshAccessToken(e);if(n)throw n;if(!r.session)throw new tr;const i=await Or(this.storage,this.storageKey);if(null!==t&&(null===i||i.refresh_token!==t.refresh_token)){this._debug(s,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:i?"replaced":"cleared"});const e={data:null,error:new hr};return this.refreshingDeferred.resolve(e),e}const a=this._sessionRemovalEpoch;if(await this._saveSession(r.session),this._sessionRemovalEpoch!==a){this._debug(s,"commit guard (post-save): _removeSession ran during _saveSession, undoing write"),await Pr(this.storage,this.storageKey),this.userStorage&&await Pr(this.userStorage,this.storageKey+"-user");const e={data:null,error:new hr};return this.refreshingDeferred.resolve(e),e}await this._notifyAllSubscribers("TOKEN_REFRESHED",r.session);const o={data:r.session,error:null};return this.lastRefreshFailure=null,this.refreshingDeferred.resolve(o),o}catch(n){if(this._debug(s,"error",n),Xt(n)){const r={data:null,error:n};if(!cr(n)){const e=await Or(this.storage,this.storageKey);!!((null==e?void 0:e.expires_at)&&1e3*e.expires_at>Date.now())?this._debug(s,"proactive refresh failed, access token still valid — preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:r,expiresAt:Date.now()+6e4},null===(t=this.refreshingDeferred)||void 0===t||t.resolve(r),r}throw null===(r=this.refreshingDeferred)||void 0===r||r.reject(n),n}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){if(null!==this._pendingInitNotifications&&r)return void this._pendingInitNotifications.push({event:e,session:t,broadcast:r});const s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});const s=[],n=Array.from(this.stateChangeEmitters.values()).map(async r=>{try{await r.callback(e,t)}catch(n){s.push(n)}});if(await Promise.all(n),s.length>0){for(let e=0;e<s.length;e+=1);throw s[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Pr(this.storage,`${this.storageKey}-code-verifier`);const t=Object.assign({},e),r=t.user&&!0===t.user.__isUserNotAvailableProxy;if(this.userStorage){!r&&t.user&&await Ar(this.userStorage,this.storageKey+"-user",{user:t.user});const e=Object.assign({},t);delete e.user;const s=qr(e);await Ar(this.storage,this.storageKey,s)}else{const e=qr(t);await Ar(this.storage,this.storageKey,e)}}async _removeSession(){this._sessionRemovalEpoch+=1,this._debug("#_removeSession()"),this.lastRefreshFailure=null,this.suppressGetSessionWarning=!1,await Pr(this.storage,this.storageKey),await Pr(this.storage,this.storageKey+"-code-verifier"),await Pr(this.storage,this.storageKey+"-user"),this.userStorage&&await Pr(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Sr()&&(null===window||void 0===window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(t){}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),Wt);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e);const t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&"object"==typeof t&&"function"==typeof t.unref?t.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),null===(e=this.broadcastChannel)||void 0===e||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),null==this.lock)if(null===this.refreshingDeferred)try{const t=Date.now();try{await this._useSession(async e=>{const{data:{session:r}}=e;if(!r||!r.refresh_token||!r.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");const s=Math.floor((1e3*r.expires_at-t)/Wt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),s<=3&&await this._callRefreshToken(r.refresh_token)})}catch(e){}}finally{this._debug("#_autoRefreshTokenTick()","end")}else this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");else try{await this._acquireLock(0,async()=>{try{const t=Date.now();try{return await this._useSession(async e=>{const{data:{session:r}}=e;if(!r||!r.refresh_token||!r.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");const s=Math.floor((1e3*r.expires_at-t)/Wt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),s<=3&&await this._callRefreshToken(r.refresh_token)})}catch(e){}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(!(e instanceof es))throw e;this._debug("auto refresh token tick lock not available")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Sr()||!(null===window||void 0===window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},null===window||void 0===window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;if(this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState){if(this.autoRefreshToken&&this._startAutoRefresh(),!e)if(await this.initializePromise,null!=this.lock)await this._acquireLock(this.lockAcquireTimeout,async()=>{"visible"===document.visibilityState?await this._recoverAndRefresh():this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting")});else{if("visible"!==document.visibilityState)return void this._debug(t,"visibilityState is no longer visible, skipping recovery");await this._recoverAndRefresh()}}else"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){const s=[`provider=${encodeURIComponent(t)}`];if((null==r?void 0:r.redirectTo)&&s.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),(null==r?void 0:r.scopes)&&s.push(`scopes=${encodeURIComponent(r.scopes)}`),"pkce"===this.flowType){const[e,t]=await xr(this.storage,this.storageKey),r=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});s.push(r.toString())}if(null==r?void 0:r.queryParams){const e=new URLSearchParams(r.queryParams);s.push(e.toString())}return(null==r?void 0:r.skipBrowserRedirect)&&s.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;const{data:s,error:n}=t;return n?this._returnResult({data:null,error:n}):await Wr(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token})})}catch(t){if(Xt(t))return this._returnResult({data:null,error:t});throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;const{data:n,error:i}=t;if(i)return this._returnResult({data:null,error:i});const a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:"totp"===e.factorType?{issuer:e.issuer}:{}),{data:o,error:l}=await Wr(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:null===(r=null==n?void 0:n.session)||void 0===r?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):("totp"===e.factorType&&"totp"===o.type&&(null===(s=null==o?void 0:o.totp)||void 0===s?void 0:s.qr_code)&&(o.totp.qr_code=`data:image/svg+xml;utf-8,${o.totp.qr_code}`),this._returnResult({data:o,error:null}))})}catch(t){if(Xt(t))return this._returnResult({data:null,error:t});throw t}}async _verify(e){const t=async()=>{try{return await this._useSession(async t=>{var r;const{data:s,error:n}=t;if(n)return this._returnResult({data:null,error:n});const i=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:"create"===e.webauthn.type?hs(e.webauthn.credential_response):us(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:o}=await Wr(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token});return o?this._returnResult({data:null,error:o}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),this._returnResult({data:a,error:o}))})}catch(t){if(Xt(t))return this._returnResult({data:null,error:t});throw t}};return null!=this.lock?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challenge(e){const t=async()=>{try{return await this._useSession(async t=>{var r;const{data:s,error:n}=t;if(n)return this._returnResult({data:null,error:n});const i=await Wr(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token});if(i.error)return i;const{data:a}=i;if("webauthn"!==a.type)return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:ls(a.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:cs(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(t){if(Xt(t))return this._returnResult({data:null,error:t});throw t}};return null!=this.lock?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challengeAndVerify(e){const{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;const{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};const s={all:[],phone:[],totp:[],webauthn:[]};for(const n of null!==(e=null==t?void 0:t.factors)&&void 0!==e?e:[])s.all.push(n),"verified"===n.status&&s[n.factor_type].push(n);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,r,s,n;if(e)try{const{payload:s}=Cr(e);let n=null;s.aal&&(n=s.aal);let i=n;const{data:{user:a},error:o}=await this.getUser(e);if(o)return this._returnResult({data:null,error:o});(null!==(r=null===(t=null==a?void 0:a.factors)||void 0===t?void 0:t.filter(e=>"verified"===e.status))&&void 0!==r?r:[]).length>0&&(i="aal2");return{data:{currentLevel:n,nextLevel:i,currentAuthenticationMethods:s.amr||[]},error:null}}catch(h){if(Xt(h))return this._returnResult({data:null,error:h});throw h}const{data:{session:i},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:o}=Cr(i.access_token);let l=null;o.aal&&(l=o.aal);let c=l;(null!==(n=null===(s=i.user.factors)||void 0===s?void 0:s.filter(e=>"verified"===e.status))&&void 0!==n?n:[]).length>0&&(c="aal2");return{data:{currentLevel:l,nextLevel:c,currentAuthenticationMethods:o.amr||[]},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{const{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await Wr(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 tr})})}catch(t){if(Xt(t))return this._returnResult({data:null,error:t});throw t}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new tr});const i=await Wr(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&&Sr()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(i.data.redirect_url),i})}catch(r){if(Xt(r))return this._returnResult({data:null,error:r});throw r}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new tr});const i=await Wr(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&&Sr()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(i.data.redirect_url),i})}catch(r){if(Xt(r))return this._returnResult({data:null,error:r});throw r}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await Wr(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 tr})})}catch(e){if(Xt(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{const{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?(await Wr(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 tr})})}catch(t){if(Xt(t))return this._returnResult({data:null,error:t});throw t}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(t=>t.kid===e);if(r)return r;const s=Date.now();if(r=this.jwks.keys.find(t=>t.kid===e),r&&this.jwks_cached_at+6e5>s)return r;const{data:n,error:i}=await Wr(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;return n.keys&&0!==n.keys.length?(this.jwks=n,this.jwks_cached_at=s,r=n.keys.find(t=>t.kid===e),r||null):null}async getClaims(e,t={}){try{let s=e;if(!s){const{data:e,error:t}=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});s=e.session.access_token}const{header:n,payload:i,signature:a,raw:{header:o,payload:l}}=Cr(s);if(!(null==t?void 0:t.allowExpired))try{!function(e){if(!e)throw new Error("Missing exp claim");if(e<=Math.floor(Date.now()/1e3))throw new Error("JWT has expired")}(i.exp)}catch(r){throw new dr(r instanceof Error?r.message:"JWT validation failed")}const c=n.alg&&!n.alg.startsWith("HS")&&n.kid&&"crypto"in globalThis&&"subtle"in globalThis.crypto?await this.fetchJwk(n.kid,(null==t?void 0:t.keys)?{keys:t.keys}:null==t?void 0:t.jwks):null;if(!c){const{error:e}=await this.getUser(s);if(e)throw e;return{data:{claims:i,header:n,signature:a},error:null}}const h=function(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}(n.alg),u=await crypto.subtle.importKey("jwk",c,h,!0,["verify"]);if(!(await crypto.subtle.verify(h,u,a,_r(`${o}.${l}`))))throw new dr("Invalid JWT signature");return{data:{claims:i,header:n,signature:a},error:null}}catch(s){if(Xt(s))return this._returnResult({data:null,error:s});throw s}}async signInWithPasskey(e){var t,r,s;Dr(this.experimental);try{if(!ps())return this._returnResult({data:null,error:new Zt("Browser does not support WebAuthn",null)});const{data:n,error:i}=await this._startPasskeyAuthentication({options:{captchaToken:null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.captchaToken}});if(i||!n)return this._returnResult({data:null,error:i});const a=cs(n.options),o=null!==(s=null===(r=null==e?void 0:e.options)||void 0===r?void 0:r.signal)&&void 0!==s?s:os.createNewAbortSignal(),{data:l,error:c}=await gs({publicKey:a,signal:o});if(c||!l)return this._returnResult({data:null,error:null!=c?c:new Zt("WebAuthn ceremony failed",null)});const h=us(l);return this._verifyPasskeyAuthentication({challengeId:n.challenge_id,credential:h})}catch(n){if(Xt(n))return this._returnResult({data:null,error:n});throw n}}async registerPasskey(e){var t,r;Dr(this.experimental);try{if(!ps())return this._returnResult({data:null,error:new Zt("Browser does not support WebAuthn",null)});const{data:s,error:n}=await this._startPasskeyRegistration();if(n||!s)return this._returnResult({data:null,error:n});const i=ls(s.options),a=null!==(r=null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.signal)&&void 0!==r?r:os.createNewAbortSignal(),{data:o,error:l}=await fs({publicKey:i,signal:a});if(l||!o)return this._returnResult({data:null,error:null!=l?l:new Zt("WebAuthn ceremony failed",null)});const c=hs(o);return this._verifyPasskeyRegistration({challengeId:s.challenge_id,credential:c})}catch(s){if(Xt(s))return this._returnResult({data:null,error:s});throw s}}async _startPasskeyRegistration(){Dr(this.experimental);try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new tr});const{data:s,error:n}=await Wr(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:t.access_token,body:{}});return n?this._returnResult({data:null,error:n}):this._returnResult({data:s,error:null})})}catch(e){if(Xt(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){Dr(this.experimental);try{return await this._useSession(async t=>{const{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new tr});const{data:n,error:i}=await Wr(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:r.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(t){if(Xt(t))return this._returnResult({data:null,error:t});throw t}}async _startPasskeyAuthentication(e){var t;Dr(this.experimental);try{const{data:r,error:s}=await Wr(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.captchaToken}}});return s?this._returnResult({data:null,error:s}):this._returnResult({data:r,error:null})}catch(r){if(Xt(r))return this._returnResult({data:null,error:r});throw r}}async _verifyPasskeyAuthentication(e){Dr(this.experimental);try{const{data:t,error:r}=await Wr(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:Fr});return r?this._returnResult({data:null,error:r}):(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:t,error:null}))}catch(t){if(Xt(t))return this._returnResult({data:null,error:t});throw t}}async _listPasskeys(){Dr(this.experimental);try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new tr});const{data:s,error:n}=await Wr(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})});return n?this._returnResult({data:null,error:n}):this._returnResult({data:s,error:null})})}catch(e){if(Xt(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){Dr(this.experimental);try{return await this._useSession(async t=>{const{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new tr});const{data:n,error:i}=await Wr(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,body:{friendly_name:e.friendlyName}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(t){if(Xt(t))return this._returnResult({data:null,error:t});throw t}}async _deletePasskey(e){Dr(this.experimental);try{return await this._useSession(async t=>{const{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new tr});const{error:n}=await Wr(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,noResolveJson:!0});return n?this._returnResult({data:null,error:n}):this._returnResult({data:null,error:null})})}catch(t){if(Xt(t))return this._returnResult({data:null,error:t});throw t}}}ks.nextInstanceID={};const Ss=ks;let Ts,Es="";var Rs;if("undefined"!=typeof Deno)Es="deno",Ts=null===(Rs=Deno.version)||void 0===Rs?void 0:Rs.deno;else if("undefined"!=typeof document)Es="web";else if("undefined"!=typeof navigator&&"ReactNative"===navigator.product)Es="react-native";else{var As;Es="node",Ts="undefined"!=typeof process?null===(As=process.version)||void 0===As?void 0:As.replace(/^v/,""):void 0}const Os=[`runtime=${Es}`];Ts&&Os.push(`runtime-version=${Ts}`);const Ps={headers:{"X-Client-Info":`supabase-js/2.110.2; ${Os.join("; ")}`}},js={schema:"public"},Cs={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},$s={},Is={enabled:!1,respectSamplingDecision:!0};function xs(e,t,r,s){return new(r||(r=Promise))(function(t,n){function i(e){try{o(s.next(e))}catch(t){n(t)}}function a(e){try{o(s.throw(e))}catch(t){n(t)}}function o(e){var s;e.done?t(e.value):(s=e.value,s instanceof r?s:new r(function(e){e(s)})).then(i,a)}o((s=s.apply(e,[])).next())})}let Ns=null;function Us(){return xs(this,0,void 0,function*(){try{const e=yield(null===Ns&&(Ns=import("@opentelemetry/api").catch(()=>null)),Ns);if(!e||!e.propagation||!e.context)return null;const t={};e.propagation.inject(e.context.active(),t);const r=t.traceparent;return r?{traceparent:r,tracestate:t.tracestate,baggage:t.baggage}:null}catch(e){return null}})}function Ls(e,t){if(t===e)return!0;if(t.startsWith("*.")){const r=t.slice(2);if(e.endsWith(r)&&(e===r||e.endsWith("."+r)))return!0}return!1}function Ds(e){return(Ds="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})(e)}function Bs(e){var t=function(e,t){if("object"!=Ds(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t);if("object"!=Ds(s))return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==Ds(t)?t:t+""}function qs(e,t,r){return(t=Bs(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Hs(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 Ks(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Hs(Object(r),!0).forEach(function(t){qs(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Hs(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}const Ms=(e,t,r,s,n)=>{const i=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(s),a=Headers,o=!0===(null==n?void 0:n.enabled),l=!1!==(null==n?void 0:n.respectSamplingDecision),c=o?function(e){const t=[];try{const r=new URL(e);t.push(r.hostname)}catch(r){}return t.push("*.supabase.co","*.supabase.in"),t.push("localhost","127.0.0.1","[::1]"),t}(t):null;return async(t,s)=>{var n;const o=null!==(n=await r())&&void 0!==n?n:e;let h=new a(null==s?void 0:s.headers);if(h.has("apikey")||h.set("apikey",e),h.has("Authorization")||h.set("Authorization",`Bearer ${o}`),c){const e=await async function(e,t,r){if(!function(e,t){if(!e||!t||0===t.length)return!1;let r;if(e instanceof URL)r=e;else try{r=new URL(e)}catch(s){return!1}for(const n of t)try{if("string"==typeof n){if(Ls(r.hostname,n))return!0}else if(n instanceof RegExp){if(n.test(r.hostname))return!0}else if("function"==typeof n&&n(r))return!0}catch(s){continue}return!1}("string"==typeof e||e instanceof URL?e:e.url,t))return null;const s=await Us();if(!s||!s.traceparent)return null;if(r){const e=function(e){if(!e||"string"!=typeof e)return null;const t=e.split("-");if(4!==t.length)return null;const[r,s,n,i]=t;if(2!==r.length||32!==s.length||16!==n.length||2!==i.length)return null;const a=/^[0-9a-f]+$/i;return a.test(r)&&a.test(s)&&a.test(n)&&a.test(i)?"00000000000000000000000000000000"===s||"0000000000000000"===n?null:{version:r,traceId:s,parentId:n,traceFlags:i,isSampled:!(1&~parseInt(i,16))}:null}(s.traceparent);if(e&&!e.isSampled)return null}return s}(t,c,l);e&&(e.traceparent&&!h.has("traceparent")&&h.set("traceparent",e.traceparent),e.tracestate&&!h.has("tracestate")&&h.set("tracestate",e.tracestate),e.baggage&&!h.has("baggage")&&h.set("baggage",e.baggage))}return i(t,Ks(Ks({},s),{},{headers:h}))}};function Ws(e){return"boolean"==typeof e?{enabled:e}:e}var Fs=class extends Ss{constructor(e){super(e)}},Js=class{constructor(e,t,r){var s,n;this.supabaseUrl=e,this.supabaseKey=t;const i=function(e){const t=null==e?void 0:e.trim();if(!t)throw new Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL((r=t).endsWith("/")?r:r+"/")}catch(s){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}var r}(e);if(!t)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);const a=`sb-${i.hostname.split(".")[0]}-auth-token`,o=function(e,t){var r,s,n,i,a,o;const{db:l,auth:c,realtime:h,global:u}=e,{db:d,auth:p,realtime:f,global:g}=t,y=Ws(e.tracePropagation),m=Ws(t.tracePropagation),w={db:Ks(Ks({},d),l),auth:Ks(Ks({},p),c),realtime:Ks(Ks({},f),h),storage:{},global:Ks(Ks(Ks({},g),u),{},{headers:Ks(Ks({},null!==(r=null==g?void 0:g.headers)&&void 0!==r?r:{}),null!==(s=null==u?void 0:u.headers)&&void 0!==s?s:{})}),tracePropagation:{enabled:null!==(n=null!==(i=null==y?void 0:y.enabled)&&void 0!==i?i:null==m?void 0:m.enabled)&&void 0!==n&&n,respectSamplingDecision:null===(a=null!==(o=null==y?void 0:y.respectSamplingDecision)&&void 0!==o?o:null==m?void 0:m.respectSamplingDecision)||void 0===a||a},accessToken:async()=>""};return e.accessToken?w.accessToken=e.accessToken:delete w.accessToken,w}(null!=r?r:{},{db:js,realtime:$s,auth:Ks(Ks({},Cs),{},{storageKey:a}),global:Ps,tracePropagation:Is});var l;(this.settings=o,this.storageKey=null!==(s=o.auth.storageKey)&&void 0!==s?s:"",this.headers=null!==(n=o.global.headers)&&void 0!==n?n:{},o.accessToken)?(this.accessToken=o.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(t)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(null!==(l=o.auth)&&void 0!==l?l:{},this.headers,o.global.fetch);this.fetch=Ms(t,e,this._getAccessToken.bind(this),o.global.fetch,o.tracePropagation),this.realtime=this._initRealtimeClient(Ks({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},o.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(e=>this.realtime.setAuth(e)).catch(e=>{}),this.rest=new E(new URL("rest/v1",i).href,{headers:this.headers,schema:o.db.schema,fetch:this.fetch,timeout:o.db.timeout,urlLengthLimit:o.db.urlLengthLimit}),this.storage=new Kt(this.storageUrl.href,this.headers,this.fetch,null==r?void 0:r.storage),o.accessToken||this._listenForAuthEvents()}get functions(){return new l(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e,t,r=this;if(r.accessToken)return await r.accessToken();const{data:s}=await r.auth.getSession();return null!==(e=null===(t=s.session)||void 0===t?void 0:t.access_token)&&void 0!==e?e:r.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:n,storageKey:i,flowType:a,lock:o,debug:l,throwOnError:c,experimental:h,lockAcquireTimeout:u,skipAutoInitialize:d},p,f){const g={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Fs({url:this.authUrl.href,headers:Ks(Ks({},g),p),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:n,flowType:a,lock:o,debug:l,throwOnError:c,experimental:h,fetch:f,lockAcquireTimeout:u,skipAutoInitialize:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(e=>"authorization"===e.toLowerCase())})}_initRealtimeClient(e){return new Ve(this.realtimeUrl.href,Ks(Ks({},e),{},{params:Ks(Ks({},{apikey:this.supabaseKey}),null==e?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",null==t?void 0:t.access_token)})}_handleTokenChanged(e,t,r){"TOKEN_REFRESHED"!==e&&"SIGNED_IN"!==e||this.changedAccessToken===r?"SIGNED_OUT"===e&&(this.realtime.setAuth(),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0):(this.changedAccessToken=r,this.realtime.setAuth(r))}};const Gs=(e,t,r)=>new Js(e,t,r);!function(){if("undefined"!=typeof window)return!1;const e=globalThis.process;if(!e)return!1;const t=e.version;if(null==t)return!1;const r=t.match(/^v(\d+)\./);!!r&&parseInt(r[1],10)}();export{Gs as c};