1(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,462819,(e,t,r)=>{"use strict";r.parse=function(e,t){if("string"!=typeof e)throw TypeError("argument str must be a string");var r={},s=e.length;if(s<2)return r;var i=t&&t.decode||u,a=0,o=0,l=0;do{if(-1===(o=e.indexOf("=",a)))break;if(-1===(l=e.indexOf(";",a)))l=s;else if(o>l){a=e.lastIndexOf(";",o-1)+1;continue}var d=c(e,a,o),p=h(e,o,d),f=e.slice(d,p);if(!n.call(r,f)){var g=c(e,o+1,l),m=h(e,l,g);34===e.charCodeAt(g)&&34===e.charCodeAt(m-1)&&(g++,m--);var y=e.slice(g,m);r[f]=function(e,t){try{return t(e)}catch(t){return e}}(y,i)}a=l+1}while(a<s)return r},r.serialize=function(e,t,r){var n=r&&r.encode||encodeURIComponent;if("function"!=typeof n)throw TypeError("option encode is invalid");if(!i.test(e))throw TypeError("argument name is invalid");var c=n(t);if(!a.test(c))throw TypeError("argument val is invalid");var h=e+"="+c;if(!r)return h;if(null!=r.maxAge){var u=Math.floor(r.maxAge);if(!isFinite(u))throw TypeError("option maxAge is invalid");h+="; Max-Age="+u}if(r.domain){if(!o.test(r.domain))throw TypeError("option domain is invalid");h+="; Domain="+r.domain}if(r.path){if(!l.test(r.path))throw TypeError("option path is invalid");h+="; Path="+r.path}if(r.expires){var d,p=r.expires;if(d=p,"[object Date]"!==s.call(d)||isNaN(p.valueOf()))throw TypeError("option expires is invali
1d");h+="; Expires="+p.toUTCString()}if(r.httpOnly&&(h+="; HttpOnly"),r.secure&&(h+="; Secure"),r.partitioned&&(h+="; Partitioned"),r.priority)switch("string"==typeof r.priority?r.priority.toLowerCase():r.priority){case"low":h+="; Priority=Low";break;case"medium":h+="; Priority=Medium";break;case"high":h+="; Priority=High";break;default:throw TypeError("option priority is invalid")}if(r.sameSite)switch("string"==typeof r.sameSite?r.sameSite.toLowerCase():r.sameSite){case!0:case"strict":h+="; SameSite=Strict";break;case"lax":h+="; SameSite=Lax";break;case"none":h+="; SameSite=None";break;default:throw TypeError("option sameSite is invalid")}return h};var s=Object.prototype.toString,n=Object.prototype.hasOwnProperty,i=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,a=/^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/,o=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,l=/^[\u0020-\u003A\u003D-\u007E]*$/;function c(e,t,r){do{var s=e.charCodeAt(t);if(32!==s&&9!==s)return t}while(++t<r)return r}function h(e,t,r){for(;t>r;){var s=e.charCodeAt(--t);if(32!==s&&9!==s)return t+1}return r}
1function u(e){return -1!==e.indexOf("%")?decodeURIComponent(e):e}},656134,e=>{"use strict";let t,r,s,n;var i,a,o,l,c,h,u,d,p,f,g,m,y,w,b=e.i(247167),v=e.i(120786),_=e.i(92808);class k extends Error{toJSON(){return{name:this.name,message:this.message,context:this.context}}constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}}class S extends k{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class E extends k{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class T extends k{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}(i=u||(u={})).Any="any",i.ApNortheast1="ap-northeast-1",i.ApNortheast2="ap-northeast-2",i.ApSouth1="ap-south-1",i.ApSoutheast1="ap-southeast-1",i.ApSoutheast2="ap-southeast-2",i.CaCentral1="ca-central-1",i.EuCentral1="eu-central-1",i.EuWest1="eu-west-1",i.EuWest2="eu-west-2",i.EuWest3="eu-west-3",i.SaEast1="sa-east-1",i.UsEast1="us-east-1",i.UsWest1="us-west-1",i.UsWest2="us-west-2";function A(e,t){var r={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&0>t.indexOf(s)&&(r[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var n=0,s=Object.getOwnPropertySymbols(e);n<s.length;n++)0>t.indexOf(s[n])&&Object.prototype.propertyIsEnumerable.call(e,s[n])&&(r[s[n]]=e[s[n]]);return r}"function"==typeof SuppressedError&&SuppressedError;class R{setAuth(e){this.headers.Authorization="Bearer ".concat(e)}invoke(e){var t,r,s,n;return t=this,r=arguments,s=void 0,n=function*(e){var t;let r,s,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};try{let i,{headers:a,method:o,body:l,signal:c,timeout:h}=n,u={},{region:d}=n;d||(d=this.region);let p=new URL("".concat(this.url,"/").concat(e));d&&"any"!==d&&(u["x-region"]=d,p.searchParams.set("forceFunctionRegion",d)),l&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?"u">typeof Blob&&l instanceof Blob||l instanceof ArrayBuffer?(u["Content-Type"]="application/octet-stream",i=l):"string"==typeof l?(u["Content-Type"]="text/plain",i=l):"u">typeof FormData&&l instanceof FormData?i=l:(u["Content-Type"]="application/json",i=JSON.stringify(l)):i=!l||"string"==typeof l||"u">typeof Blob&&l instanceof Blob||l instanceof ArrayBuffer||"u">typeof FormData&&l instanceof FormData?l:JSON.stringify(l);let f=c;h&&(s=new AbortController,r=setTimeout(()=>s.abort(),h),c?(f=s.signal,c.addEventListener("abort",()=>s.abort())):f=s.signal);let g=yield this.fetch(p.toString(),{method:o||"POST",headers:Object.assign(Object.assign(Object.assign({},u),this.headers),a),body:i,signal:f}).catch(e=>{throw new S(e)}),m=g.headers.get("x-relay-error");if(m&&"true"===m)throw new E(g);if(!g.ok)throw new T(g);let y=(null!=(t=g.headers.get("Content-Type"))?t:"text/plain").split(";")[0].trim();return{data:"application/json"===y?yield g.json():"application/octet-stream"===y||"application/pdf"===y?yield g.blob():"text/event-stream"===y?g:"multipart/form-data"===y?yield g.formData():yield g.text(),error:null,response:g}}catch(e){return{data:null,error:e,response:e instanceof T||e instanceof E?e.context:void 0}}finally{r&&clearTimeout(r)}},new(s||(s=Promise))(function(e,i){function a(e){try{l(n.next(e))}catch(e){i(e)}}function o(e){try{l(n.throw(e))}catch(e){i(e)}}function l(t){var r;t.done?e(t.value):((r=t.value)instanceof s?r:new s(function(e){e(r)})).then(a,o)}l((n=n.apply(t,r||[])).next())})}constructor(e,{headers:t={},customFetch:r,region:s=u.Any}={}){this.url=e,this.headers=t,this.region=s,this.fetch=(e=>e?function(){for(var t=arguments.length,r=Array(t),s=0;s<t;s++)r[s]=arguments[s];return e(...r)}:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return fetch(...t)})(r)}}let O=e=>Math.min(1e3*2**e,3e4),C=[520,503],P=["GET","HEAD","OPTIONS"];var j=class extends Error{toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.co
1de=e.code}};function I(e,t){return new Promise(r=>{if(null==t?void 0:t.aborted)return void r();let s=setTimeout(()=>{null==t||t.removeEventListener("abort",n),r()},e);function n(){clearTimeout(s),r()}null==t||t.addEventListener("abort",n)})}var x=class{throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if("text/csv"===this.headers.get("Accept"))throw 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){let 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")}let s=this.fetch,n=(async()=>{let e=0;for(;;){var t,n,i,a,o;let l,c={};r.headers.forEach((e,t)=>{c[t]=e}),e>0&&(c["X-Retry-Count"]=String(e));try{l=await s(r.url.toString(),{method:r.method,headers:c,body:JSON.stringify(r.body,(e,t)=>"bigint"==typeof t?t.toString():t),signal:r.signal})}catch(t){if((null==t?void 0:t.name)==="AbortError"||(null==t?void 0:t.code)==="ABORT_ERR"||!P.includes(r.method))throw t;if(r.retryEnabled&&e<3){let t=O(e);e++,await I(t,r.signal);continue}throw t}if(t=r.method,n=l.status,i=e,r.retryEnabled&&!(i>=3)&&P.includes(t)&&C.includes(n)&&1){let t=null!=(a=null==(o=l.headers)?void 0:o.get("Retry-After"))?a:null,s=null!==t?1e3*Math.max(0,parseInt(t,10)||0):O(e);await l.text(),e++,await I(s,r.signal);continue}return await r.processResponse(l)}})();return this.shouldThrowOnError||(n=n.catch(e=>{var t,r,s,n,i,a;let o="",l="",c="",h=null==e?void 0:e.cause;if(h){let t=null!=(r=null==h?void 0:h.message)?r:"",a=null!=(s=null==h?void 0:h.code)?s:"";o="".concat(null!=(n=null==e?void 0:e.name)?n:"FetchError",": ").concat(null==e?void 0:e.message)+"\n\nCaused by: ".concat(null!=(i=null==h?void 0:h.name)?i:"Error",": ").concat(t),a&&(o+=" (".concat(a,")")),(null==h?void 0:h.stack)&&(o+="\n".concat(h.stack))}else o=null!=(a=null==e?void 0:e.stack)?a:"";let u=this.url.toString().length;return(null==e?void 0:e.name)==="AbortError"||(null==e?void 0:e.code)==="ABORT_ERR"?(c="",l="Request was aborted (timeout or manual cancellation)",u>this.urlLengthLimit&&(l+=". Note: Your request URL is ".concat(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."))):((null==h?void 0:h.name)==="HeadersOverflowError"||(null==h?void 0:h.code)==="UND_ERR_HEADERS_OVERFLOW")&&(c="",l="HTTP headers exceeded server limits (typically 16KB)",u>this.urlLengthLimit&&(l+=". Your request URL is ".concat(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:"".concat(null!=(t=null==e?void 0:e.name)?t:"FetchError",": ").concat(null==e?void 0:e.message),details:o,hint:l,code:c},data:null,count:null,status:0,statusText:""}})),n.then(e,t)}async processResponse(e){var t,r,s;let n=null,i=null,a=null,o=e.status,l=e.statusText;if(e.ok){if("HEAD"!==this.method){let t=await e.text();if(""===t);else if("text/csv"===this.headers.get("Accept"))i=t;else if(this.headers.get("Accept")&&(null==(s=this.headers.get("Accept"))?void 0:s.includes("application/vnd.pgrst.plan+text")))i=t;else try{i=JSON.parse(t)}catch(e){if(n={message:t},i=null,this.shouldThrowOnError)throw new j({message:t,details:"",hint:"",code:""})}}let c=null==(t=this.headers.get("Prefer"))?void 0:t.match(/count=(exact|planned|estimated)/),h=null==(r=e.headers.get("content-range"))?void 0:r.split("/");c&&h&&h.length>1&&(a=parseInt(h[1])),this.isMaybeSingle&&Array.isArray(i)&&(i.length>1?(n={code:"PGRST116",details:"Results contain ".concat(i.length," rows, application/vnd.pgrst.object+json requires 1 row"),hint:null,message:"JSON object requested, multiple (or no) rows returned"},i=null,a=null,o=406,l="Not Acceptable"):i=1===i.length?i[0]:null)}else{let t=await e.text();try{n=JSON.parse(t),Array.isArray(n)&&404===e.status&&(i=[],n=null,o=200,l="OK")}catch(r){404===e.status&&""===t?(o=204,l="No Content"):n={message:t}}if(n&&this.shouldThrowOnError)throw new j(n)}return{success:null===n,error:n,data:i,count:a,status:o,statusText:l}}returns(){return this}overrideTypes(){return this}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)&&t,this.signal=e.signal,this.isMaybeSingle=null!=(r=e.isMaybeSingle)&&r,this.shouldStripNulls=null!=(s=e.shouldStripNulls)&&s,this.urlLengthLimit=null!=(n=e.urlLengthLimit)?n:8e3,this.retryEnabled=null==(i=e.retry)||i,e.fetch?this.fetch=e.fetch:this.fetch=fetch}},N=class extends x{throwOnError(){return super.throwOnError()}select(e){let t=!1,r=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(e){let{ascending:t=!0,nullsFirst:r,foreignTable:s,referencedTable:n=s}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=n?"".concat(n,".order"):"order",a=this.url.searchParams.get(i);return this.url.searchParams.set(i,"".concat(a?"".concat(a,","):"").concat(e,".").concat(t?"asc":"desc").concat(void 0===r?"":r?".nullsfirst":".nullslast")),this}limit(e){let{foreignTable:t,referencedTable:r=t}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.url.searchParams.set(void 0===r?"limit":"".concat(r,".limit"),"".concat(e)),this}range(e,t){let{foreignTable:r,referencedTable:s=r}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=void 0===s?"offset":"".concat(s,".offset"),i=void 0===s?"limit":"".concat(s,".limit");return this.url.searchParams.set(n,"".concat(e)),this.url.searchParams.set(i,"".concat(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(){var e;
1let{analyze:t=!1,verbose:r=!1,settings:s=!1,buffers:n=!1,wal:i=!1,format:a="text"}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},o=[t?"analyze":null,r?"verbose":null,s?"settings":null,n?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=null!=(e=this.headers.get("Accept"))?e:"application/json";return this.headers.set("Accept","application/vnd.pgrst.plan+".concat(a,'; for="').concat(l,'"; options=').concat(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=".concat(e)),this}};let U=RegExp("[,()]");var L=class extends N{throwOnError(){return super.throwOnError()}eq(e,t){return this.url.searchParams.append(e,"eq.".concat(t)),this}neq(e,t){return this.url.searchParams.append(e,"neq.".concat(t)),this}gt(e,t){return this.url.searchParams.append(e,"gt.".concat(t)),this}gte(e,t){return this.url.searchParams.append(e,"gte.".concat(t)),this}lt(e,t){return this.url.searchParams.append(e,"lt.".concat(t)),this}lte(e,t){return this.url.searchParams.append(e,"lte.".concat(t)),this}like(e,t){return this.url.searchParams.append(e,"like.".concat(t)),this}likeAllOf(e,t){return this.url.searchParams.append(e,"like(all).{".concat(t.join(","),"}")),this}likeAnyOf(e,t){return this.url.searchParams.append(e,"like(any).{".concat(t.join(","),"}")),this}ilike(e,t){return this.url.searchParams.append(e,"ilike.".concat(t)),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,"ilike(all).{".concat(t.join(","),"}")),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,"ilike(any).{".concat(t.join(","),"}")),this}regexMatch(e,t){return this.url.searchParams.append(e,"match.".concat(t)),this}regexIMatch(e,t){return this.url.searchParams.append(e,"imatch.".concat(t)),this}is(e,t){return this.url.searchParams.append(e,"is.".concat(t)),this}isDistinct(e,t){return this.url.searchParams.append(e,"isdistinct.".concat(t)),this}in(e,t){let r=Array.from(new Set(t)).map(e=>"string"==typeof e&&U.test(e)?'"'.concat(e,'"'):"".concat(e)).join(",");return this.url.searchParams.append(e,"in.(".concat(r,")")),this}notIn(e,t){let r=Array.from(new Set(t)).map(e=>"string"==typeof e&&U.test(e)?'"'.concat(e,'"'):"".concat(e)).join(",");return this.url.searchParams.append(e,"not.in.(".concat(r,")")),this}contains(e,t){return"string"==typeof t?this.url.searchParams.append(e,"cs.".concat(t)):Array.isArray(t)?this.url.searchParams.append(e,"cs.{".concat(t.join(","),"}")):this.url.searchParams.append(e,"cs.".concat(JSON.stringify(t))),this}containedBy(e,t){return"string"==typeof t?this.url.searchParams.append(e,"cd.".concat(t)):Array.isArray(t)?this.url.searchParams.append(e,"cd.{".concat(t.join(","),"}")):this.url.searchParams.append(e,"cd.".concat(JSON.stringify(t))),this}rangeGt(e,t){return this.url.searchParams.append(e,"sr.".concat(t)),this}rangeGte(e,t){return this.url.searchParams.append(e,"nxl.".concat(t)),this}rangeLt(e,t){return this.url.searchParams.append(e,"sl.".concat(t)),this}rangeLte(e,t){return this.url.searchParams.append(e,"nxr.".concat(t)),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,"adj.".concat(t)),this}overlaps(e,t){return"string"==typeof t?this.url.searchParams.append(e,"ov.".concat(t)):this.url.searchParams.append(e,"ov.{".concat(t.join(","),"}")),this}textSearch(e,t){let{config:r,type:s}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n="";return"plain"===s?n="pl":"phrase"===s?n="ph":"websearch"===s&&(n="w"),this.url.searchParams.append(e,"".concat(n,"fts").concat(void 0===r?"":"(".concat(r,")"),".").concat(t)),this}match(e){return Object.entries(e).filter(e=>{let[t,r]=e;return void 0!==r}).forEach(e=>{let[t,r]=e;this.url.searchParams.append(t,"eq.".concat(r))}),this}not(e,t,r){return this.url.searchParams.append(e,"not.".concat(t,".").concat(r)),this}or(e){let{foreignTable:t,referencedTable:r=t}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.url.searchParams.append(r?"".concat(r,".or"):"or","(".concat(e,")")),this}filter(e,t,r){return this.url.searchParams.append(e,"".concat(t,".").concat(r)),this}}
1,D=class{cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){let{head:r=!1,count:s}=null!=t?t:{},n=!1,i=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!n?"":('"'===e&&(n=!n),e)).join(""),{url:a,headers:o}=this.cloneRequestState();return a.searchParams.set("select",i),s&&o.append("Prefer","count=".concat(s)),new L({method:r?"HEAD":"GET",url:a,headers:o,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(e){var t;let{count:r,defaultToNull:s=!0}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{url:n,headers:i}=this.cloneRequestState();if(r&&i.append("Prefer","count=".concat(r)),s||i.append("Prefer","missing=default"),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>'"'.concat(e,'"'));n.searchParams.set("columns",e.join(","))}}return new L({method:"POST",url:n,headers:i,schema:this.schema,body:e,fetch:null!=(t=this.fetch)?t:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(e){var t;let{onConflict:r,ignoreDuplicates:s=!1,count:n,defaultToNull:i=!0}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{url:a,headers:o}=this.cloneRequestState();if(o.append("Prefer","resolution=".concat(s?"ignore":"merge","-duplicates")),void 0!==r&&a.searchParams.set("on_conflict",r),n&&o.append("Prefer","count=".concat(n)),i||o.append("Prefer","missing=default"),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>'"'.concat(e,'"'));a.searchParams.set("columns",e.join(","))}}return new L({method:"POST",url:a,headers:o,schema:this.schema,body:e,fetch:null!=(t=this.fetch)?t:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(e){var t;let{count:r}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{url:s,headers:n}=this.cloneRequestState();return r&&n.append("Prefer","count=".concat(r)),new L({method:"PATCH",url:s,headers:n,schema:this.schema,body:e,fetch:null!=(t=this.fetch)?t:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete(){var e;let{count:t}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{url:r,headers:s}=this.cloneRequestState();return t&&s.append("Prefer","count=".concat(t)),new L({method:"DELETE",url:r,headers:s,schema:this.schema,fetch:null!=(e=this.fetch)?e:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}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}};function B(e){return(B="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 q(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 H(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?q(Object(r),!0).forEach(function(t){!function(e,t,r){var s;(s=function(e,t){if("object"!=B(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=B(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==B(s)?s:s+"")in e)?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r}(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):q(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var M=class e{from(e){if(!e||"string"!=typeof e||""===e.trim())throw Error("Invalid relation name: relation must be a non-empty string.");return new D(new URL("".concat(this.url,"/").concat(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){var t;let r,s,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{head:i=!1,get:a=!1,count:o}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},l=new URL("".concat(this.url,"/rpc/").concat(e)),c=e=>null!==e&&"object"==typeof e&&(!Array.isArray(e)||e.some(c)),h=i&&Object.values(n).some(c);
1h?(r="POST",s=n):i||a?(r=i?"HEAD":"GET",Object.entries(n).filter(e=>{let[t,r]=e;return void 0!==r}).map(e=>{let[t,r]=e;return[t,Array.isArray(r)?"{".concat(r.join(","),"}"):"".concat(r)]}).forEach(e=>{let[t,r]=e;l.searchParams.append(t,r)})):(r="POST",s=n);let u=new Headers(this.headers);return h?u.set("Prefer",o?"count=".concat(o,",return=minimal"):"return=minimal"):o&&u.set("Prefer","count=".concat(o)),new L({method:r,url:l,headers:u,schema:this.schemaName,body:s,fetch:null!=(t=this.fetch)?t:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}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;void 0!==n&&n>0?this.fetch=(e,t)=>{let 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);let n=()=>{clearTimeout(s),r.abort()};return i.addEventListener("abort",n,{once:!0}),o(e,H(H({},t),{},{signal:r.signal})).finally(()=>{clearTimeout(s),i.removeEventListener("abort",n)})}return o(e,H(H({},t),{},{signal:r.signal})).finally(()=>clearTimeout(s))}:this.fetch=o,this.retry=a}};let W=class{static detectEnvironment(){var t;if("u">typeof WebSocket)return{type:"native",wsConstructor:WebSocket};let r=globalThis;if("u">typeof globalThis&&void 0!==r.WebSocket)return{type:"native",wsConstructor:r.WebSocket};let s=e.g;if(s&&void 0!==s.WebSocket)return{type:"native",wsConstructor:s.WebSocket};if("u">typeof globalThis&&void 0!==r.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("u">typeof globalThis&&r.EdgeRuntime||"u">typeof navigator&&(null==(t=navigator.userAgent)?void 0:t.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};let n=globalThis.process;if(n){let e=n.versions;if(e&&e.node){let t=parseInt(e.node.replace(/^v/,"").split(".")[0]);return t>=22?void 0!==globalThis.WebSocket?{type:"native",wsConstructor:globalThis.WebSocket}:{type:"unsupported",error:"Node.js ".concat(t," detected but native WebSocket not found."),workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:"Node.js ".concat(t," detected without native WebSocket support."),workaround:'For Node.js < 22, install "ws" package and provide it via the transport option:\nimport ws from "ws"\nnew RealtimeClient(url, { transport: ws })'}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){let e=this.detectEnvironment();if(e.wsConstructor)return e.wsConstructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+="\n\nSuggested solution: ".concat(e.workaround)),Error(t)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return"native"===e.type||"ws"===e.type}catch(e){return!1}}},K="realtime-js/".concat("2.108.1"),F="2.0.0",J="errored",z="joined",G={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"};class V{encode(e,t){return e.event!==this.BROADCAST_EVENT||e.payload instanceof ArrayBuffer||"string"!=typeof e.payload.event?t(JSON.stringify([e.join_ref,e.ref,e.topic,e.event,e.payload])):t(this._binaryEncodeUserBroadcastPush(e))}_binaryEncodeUserBroadcastPush(e){var t;return this._isArrayBuffer(null==(t=e.payload)?void 0:t.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,r;let s=null!=(r=null==(t=e.payload)?void 0:t.payload)?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,s)}_encodeJsonUserBroadcastPush(e){var t,r;let s=null!=(r=null==(t=e.payload)?void 0:t.payload)?r:{},n=new TextEncoder().encode(JSON.stringify(s)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,n)}_encodeUserBroadcastPush(e,t,r){let s=e.topic,n=null!=(p=e.ref)?p:"",i=null!=(f=e.join_ref)?f:"",a=e.payload.event,o=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},l=0===Object.keys(o).length?"":JSON.stringify(o);if(i.length>255)throw Error("joinRef length ".concat(i.length," exceeds maximum of 255"));if(n.length>255)throw Error("ref length ".concat(n.length," exceeds maximum of 255"));if(s.length>255)throw Error("topic length ".concat(s.length," exceeds maximum of 255"));if(a.length>255)throw Error("userEvent length ".concat(a.length," exceeds maximum of 255"));if(l.length>255)throw Error("metadata length ".concat(l.length," exceeds maximum of 255"));let c=this.USER_BROADCAST_PUSH_META_LENGTH+i.length+n.length+s.length+a.length+l.length,h=new ArrayBuffer(this.HEADER_LENGTH+c),u=new DataView(
1h),d=0;u.setUint8(d++,this.KINDS.userBroadcastPush),u.setUint8(d++,i.length),u.setUint8(d++,n.length),u.setUint8(d++,s.length),u.setUint8(d++,a.length),u.setUint8(d++,l.length),u.setUint8(d++,t),Array.from(i,e=>u.setUint8(d++,e.charCodeAt(0))),Array.from(n,e=>u.setUint8(d++,e.charCodeAt(0))),Array.from(s,e=>u.setUint8(d++,e.charCodeAt(0))),Array.from(a,e=>u.setUint8(d++,e.charCodeAt(0))),Array.from(l,e=>u.setUint8(d++,e.charCodeAt(0)));var p,f,g=new Uint8Array(h.byteLength+r.byteLength);return g.set(new Uint8Array(h),0),g.set(new Uint8Array(r),h.byteLength),g.buffer}decode(e,t){if(this._isArrayBuffer(e))return t(this._binaryDecode(e));if("string"==typeof e){let[r,s,n,i,a]=JSON.parse(e);return t({join_ref:r,ref:s,topic:n,event:i,payload:a})}return t({})}_binaryDecode(e){let t=new DataView(e),r=t.getUint8(0),s=new TextDecoder;if(r===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,t,s)}_decodeUserBroadcast(e,t,r){let s=t.getUint8(1),n=t.getUint8(2),i=t.getUint8(3),a=t.getUint8(4),o=this.HEADER_LENGTH+4,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=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||(null==(t=null==e?void 0:e.constructor)?void 0:t.name)==="ArrayBuffer"}_pick(e,t){return e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(e=>{let[r]=e;return t.includes(r)})):{}}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:[]}}(a=d||(d={})).abstime="abstime",a.bool="bool",a.date="date",a.daterange="daterange",a.float4="float4",a.float8="float8",a.int2="int2",a.int4="int4",a.int4range="int4range",a.int8="int8",a.int8range="int8range",a.json="json",a.jsonb="jsonb",a.money="money",a.numeric="numeric",a.oid="oid",a.reltime="reltime",a.text="text",a.time="time",a.timestamp="timestamp",a.timestamptz="timestamptz",a.timetz="timetz",a.tsrange="tsrange",a.tstzrange="tstzrange";let Y=function(e,t){var r;let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=null!=(r=s.skipTypes)?r:[];return t?Object.keys(t).reduce((r,s)=>(r[s]=$(s,e,t,n),r),{}):{}},$=(e,t,r,s)=>{let n=t.find(t=>t.name===e),i=null==n?void 0:n.type,a=r[e];return i&&!s.includes(i)?X(i,a):Q(a)},X=(e,t)=>{if("_"===e.charAt(0))return er(t,e.slice(1,e.length));switch(e){case d.bool:return Z(t);case d.float4:case d.float8:case d.int2:case d.int4:case d.int8:case d.numeric:case d.oid:return ee(t);case d.json:case d.jsonb:return et(t);case d.timestamp:return es(t);case d.abstime:case d.date:case d.daterange:case d.int4range:case d.int8range:case d.money:case d.reltime:case d.text:case d.time:case d.timestamptz:case d.timetz:case d.tsrange:case d.tstzrange:default:return Q(t)}},Q=e=>e,Z=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},ee=e=>{if("string"==typeof e){let t=parseFloat(e);if(!Number.isNaN(t))return t}return e},et=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(e){}return e},er=(e,t)=>{if("string"!=typeof e)return e;let r=e.length-1,s=e[r];if("{"===e[0]&&"}"===s){let s,n=e.slice(1,r);try{s=JSON.parse("["+n+"]")}catch(e){s=n?n.split(","):[]}return s.map(e=>X(t,e))}return e},es=e=>"string"==typeof e?e.replace(" ","T"):e,en=e=>{let t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),""===t.pathname||"/"===t.pathname?t.pathname="/api/broadcast":t.pathname=t.pathname+"/api/broadcast",t.href};var ei=e=>"function"==typeof e?e:function(){return e},ea="u">typeof window?window:null,eo=("u">typeof self?self:null)||ea||globalThis,el="closed",ec="errored",eh="joined",eu="joining",ed="leaving",ep="phx_close",ef="phx_error",eg="phx_reply",em="phx_leave",ey="websocket",ew="base64url.bearer.phx.",eb=class{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,j
1oin_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(e){let{status:t,response:r,_ref:s}=e;this.recHooks.filter(e=>e.status===t).forEach(e=>e.callback(r))}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})}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}},ev=class{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))}constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0}},e_=class{join(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.timeout;if(!this.joinedOnce)return this.timeout=e,this.joinedOnce=!0,this.rejoin(),this.joinPush;throw Error("tried to join multiple times. 'join' can only be called a single time per channel instance")}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=el,this.bindings=[]}onClose(e){this.on(ep,e)}onError(e){return this.on(ef,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){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.timeout;if(t=t||{},!this.joinedOnce)throw Error("tried to push '".concat(e,"' to '").concat(this.topic,"' before joining. Use channel.join() before pushing events"));let s=new eb(this,e,function(){return t},r);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}leave(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.timeout;this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=ed;let t=()=>{this.socket.hasLogger()&&this.socket.log("channel","leave ".concat(this.topic)),this.trigger(ep,"leave")},r=new eb(this,em,ei({}),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(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.timeout;this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=eu,this.joinPush.resend(e))}trigger(e,t,r,s){let n=this.onMessage(e,t,r,s);if(t&&!n)throw 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 e=0;e<i.length;e++)i[e].callback(n,r,s||this.joinRef())}replyEventName(e){return"chan_reply_".concat(e)}isClosed(){return this.state===el}isErrored(){return this.state===ec}isJoined(){return this.state===eh}isJoining(){return this.state===eu}isLeaving(){return this.state===ed}constructor(e,t,r){this.state=el,this.topic=e,this.params=ei(t||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new eb(this,"phx_join",this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new ev(()=>{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=eh,this.rejoinTimer.reset(),this.pushBuffer.forEach(e
1=>e.send()),this.pushBuffer=[]}),this.joinPush.receive("error",e=>{this.state=ec,this.socket.hasLogger()&&this.socket.log("channel","error ".concat(this.topic),e),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel","close ".concat(this.topic)),this.state=el,this.socket.remove(this)}),this.onError(e=>{this.socket.hasLogger()&&this.socket.log("channel","error ".concat(this.topic),e),this.isJoining()&&this.joinPush.reset(),this.state=ec,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel","timeout ".concat(this.topic),this.joinPush.timeout),new eb(this,em,ei({}),this.timeout).send(),this.state=ec,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(eg,(e,t)=>{this.trigger(this.replyEventName(t),e)})}},ek=class{static request(e,t,r,s,n,i,a){if(eo.XDomainRequest){let r=new eo.XDomainRequest;return this.xdomainRequest(r,e,t,s,n,i,a)}if(eo.XMLHttpRequest){let o=new eo.XMLHttpRequest;return this.xhrRequest(o,e,t,r,s,n,i,a)}if(eo.fetch&&eo.AbortController)return this.fetchRequest(e,t,r,s,n,i,a);throw 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),eo.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){for(let[n,a]of(e.open(t,r,!0),e.timeout=i,Object.entries(s)))e.setRequestHeader(n,a);return e.onerror=()=>o&&o(null),e.onreadystatechange=()=>{4===e.readyState&&o&&o(this.parseJSON(e.responseText))},a&&(e.ontimeout=a),e.send(n),e}static parseJSON(e){if(!e||""===e)return null;try{return JSON.parse(e)}catch(t){return console&&console.log("failed to parse JSON response",e),null}}static serialize(e,t){let r=[];for(var s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let n=t?"".concat(t,"[").concat(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"".concat(e).concat(r).concat(this.serialize(t))}},eS=class{normalizeEndpoint(e){return e.replace("ws://","http://").replace("wss://","https://").replace(RegExp("(.*)/"+ey),"$1/longpoll")}endpointURL(){return ek.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,r){this.close(e,t,r),this.readyState=0}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return 1===this.readyState||0===this.readyState}poll(){let 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){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}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=1,this.onopen({}),this.poll();break;
1case 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 Error("unhandled poll status ".concat(t))}})}send(e){"string"!=typeof e&&(e=(e=>{let t="",r=new Uint8Array(e),s=r.byteLength;for(let e=0;e<s;e++)t+=String.fromCharCode(r[e]);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 e of this.reqs)e.abort();this.readyState=3;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,"u">typeof CloseEvent?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(e,t,r,s,n){let i,a=()=>{this.reqs.delete(i),s()};i=ek.request(e,this.endpointURL(),t,r,this.timeout,a,e=>{this.reqs.delete(i),this.isActive()&&n(e)}),this.reqs.add(i)}constructor(e,t){t&&2===t.length&&t[1].startsWith(ew)&&(this.authToken=atob(t[1].slice(ew.length))),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=0,setTimeout(()=>this.poll(),0)}},eE=class e{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=>0>n.indexOf(e.phx_ref)),l=r.metas.filter(e=>0>s.indexOf(e.phx_ref));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=>0>r.indexOf(e.phx_ref));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=>0>i.indexOf(e.phx_ref)),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))}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())})}},eT={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(e,t){return e.payload.constructor===ArrayBuffer?t(this.binaryEncode(e)):t(JSON.stringify([e.join_ref,e.ref,e.topic,e.event,e.payload]))},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);
1case 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));return o+=a,{join_ref:l,ref:c,topic:h,event:eg,payload:{status:u,response:e.slice(o,e.byteLength)}}},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)}}},eA=class{getLongPollTransport(){return eS}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=ek.appendParams(ek.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return"/"!==e.charAt(0)?e:"/"===e.charAt(1)?"".concat(this.protocol(),":").concat(e):"".concat(this.protocol(),"://").concat(location.host).concat(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&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=ei(e)),(!this.conn||this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==eS?this.connectWithF
1allback(eS,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===eS?"LongPoll":e.name}transportConnect(){let e;this.connectClock++,this.closeWasClean=!1,this.authToken&&(e=["phoenix","".concat(ew).concat(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){let t,r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2500;clearTimeout(this.fallbackTimer);let n=!1,i=!0,a=this.transportName(e),o=s=>{this.log("transport","falling back to ".concat(a,"..."),s),this.off([t,r]),i=!1,this.replaceTransport(e),this.transportConnect()};if(this.getSession("phx:fallback:".concat(a)))return o("memorized");this.fallbackTimer=setTimeout(o,s),r=this.onError(e=>{this.log("transport","error",e),i&&!n&&(clearTimeout(this.fallbackTimer),o(e))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(n=!0,!i){let t=this.transportName(e);return this.primaryPassedHealthCheck||this.storeSession("phx:fallback:".concat(t),"true"),this.log("transport","established ".concat(t," fallback"))}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(o,s),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 ".concat(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(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();let 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){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;5!==r&&e.bufferedAmount?setTimeout(()=>{this.waitForBufferDone(e,t,r+1)},150*r):t()}waitForSocketClosed(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;5===r||3===e.readyState?t():setTimeout(()=>{this.waitForSocketClosed(e,t,r+1)},150*r)}
1onConnClose(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(ef,e)})}connectionState(){switch(this.conn&&this.conn.readyState){case 0:return"connecting";case 1:return"open";case 2: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=>{let[r]=t;return -1===e.indexOf(r)})}channel(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=new e_(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","".concat(t," ").concat(r," (").concat(i,", ").concat(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()){try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}return}if(this.pendingHeartbeatRef)return void this.heartbeatTimeout();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)}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){let e=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback("ok"===s.status?"ok":"error",e)}catch(e){this.log("error","error in heartbeat callback",e)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive","".concat(s.status||""," ").concat(t," ").concat(r," ").concat(n&&"("+n+")"||"").trim(),s);for(let e=0;e<this.channels.length;e++){let a=this.channels[e];a.isMember(t,r,s,i)&&a.trigger(r,s,n,i)}this.triggerStateCallbacks("message",e)})}triggerStateCallbacks(e){for(var t=arguments.length,r=Array(t>1?t-1:0),s=1;s<t;s++)r[s-1]=arguments[s];try{this.stateChangeCallbacks[e].forEach(t=>{let[s,n]=t;try{n(...r)}catch(t){this.log("error","error in ".concat(e," callback"),t)}})}catch(t){this.log("error","error triggering ".concat(e," callbacks"),t)}}leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t.isJoined()||t.isJoining()));t&&(this.hasLogger()&&this.log("transport",'leaving duplicate topic "'.concat(e,'"')),t.leave())}constructor(e,t={}){var r,s;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||eo.WebSocket||eS,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null;let n=null;try{n=eo&&eo.sessionStorage}catch(e){}this.sessionStore=t.sessionStorage||n,this.establishedConnections=0,this.defaultEncoder=eT.encode.bind(eT),this.defaultDecoder=eT.decode.bind(eT),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!==eS?(this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let i=null;ea&&ea.addEventListener&&(ea.addEventListener("pagehide",e=>{this.conn&&(this.disconnect(),i=this.connectClock)}),ea.addEventListener("pageshow",e=>{i===this.connectClock&&(i=null,this.connect())}),ea.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=null==(r=t.autoSendHeartbeat)||r,this.heartbeatCallback=null!=(s=t.heartbeatCallback)?s:()=>{},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)=>{console.log("".concat(e,": ").concat(t),r)}),this.longpollerTimeout=t.longpollerTimeout||2e4,this.params=ei(t.params||{}),this.endPoint="".concat(e,"/").concat(ey),this.vsn=t.vsn||"2.0.0",this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new ev(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{t.beforeReconnect&&await t.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=t.authToken}};class eR{get state(){return eR.transformState(this.presence.state)}static transformState(e){return Object.getOwnPropertyNames(e=JSON.parse(JSON.stringify(e))).reduce((t,r)=>{let s=e[r];return t[r]=eO(s),t},{})}static onJoinPayload(e,t,r){return{event:"join",key:e,currentPresences:eC(t),newPresences:eO(r)}}static onLeavePayload(e,t,r){return{event:"leave",key:e,currentPresences:eC(t),leftPresences:eO(r)}}constructor(e,t){const r=function(e){return(null==e?void 0:e.events)&&{events:e.events}}(t);this.presence=new eE(e.getChannel(),r),this.presence.onJoin((t,r,s)=>{let n=eR.onJoinPayload(t,r,s);e.getChannel().trigger("presence",n)}),this.presence.onLeave((t,r,s)=>{let n=eR.onLeavePayload(t,r,s);e.getChannel().trigger("presence",n)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}}function eO(e){return e.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function eC(e){return(null==e?void 0:e.metas)?eO(e):[]}(o=p||(p={})).SYNC="sync",o.JOIN="join",o.LEAVE="leave";class eP{get state(){return this.presenceAdapter.state}constructor(e,t){this.channel=e,this.presenceAdapter=new eR(this.channel.channelAdapter,t)}}class ej{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(t){throw Error("tried to push '".concat(e,"' to '").concat(this.channel.topic,"' before joining. Use channel.subscribe() before pushing events"))}if(this.channel.pushBuffer.length>100){let e=this.channel.pushBuffer.shift();e.cancelTimeout(),this.socket.log("channel","discarded push due to buffer overflow: ".concat(e.event),e.payload())}return s}updateJoinPayload(e){let t=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},t),e)}canPush(){return this.socket.isConnected()&&this.state===z}isJoined(){return this.state===z}isJoining(){return"joining"===this.state}isClosed(){return"closed"===this.state}isLeaving(){return"leaving"===this.state}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}constructor(e,t,r){const s=function(e){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},e.config)}}(r);this.channel=e.getSocket().channel(t,s),this.socket=e}}(l=f||(f={})).ALL="*",l.INSERT="INSERT",l.UPDATE="UPDATE",l.DELETE="DELETE",(c=g||(g={})).BROADCAST="broadcast",c.PRESENCE="presence",c.POSTGRES_CHANGES="postgres_changes",c.SYSTEM="system",(h=m||(m={})).SUBSCRIBED="SUBSCRIBED",h.TIMED_OUT="TIMED_OUT",h.CLOSED="CLOSED",h.CHANNEL_ERROR="CHANNEL_ERROR";class eI{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}subscribe(e){var t,r,s;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.timeout;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:i,presence:a,private:o}}=this.params,l=null!=(r=null==(t=this.bindings.postgres_changes)?void 0:t.map(e=>e.filter))?r:[],c=!!this.bindings[g.PRESENCE]&&this.bindings[g.PRESENCE].length>0||(null==(s=this.params.config.presence)?void 0:s.enabled)===!0,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(m.CHANNEL_ERROR,function(e){if(e instanceof Error)return e;if("string"==typeof e)return Error(e);
1if(e&&"object"==typeof e){if("number"==typeof e.code){let t="string"==typeof e.reason&&e.reason?" (".concat(e.reason,")"):"";return Error("socket closed: ".concat(e.code).concat(t),{cause:e})}return Error("channel error: transport failure",{cause:e})}return Error("channel error: connection lost")}(t))}),this._onClose(()=>null==e?void 0:e(m.CLOSED)),this.updateJoinPayload(Object.assign({config:u},h)),this._updateFilterMessage(),this.channelAdapter.subscribe(n).receive("ok",async t=>{let{postgres_changes:r}=t;if(this.socket._isManualToken()||this.socket.setAuth(),void 0===r){null==e||e(m.SUBSCRIBED);return}this._updatePostgresBindings(r,e)}).receive("error",t=>{this.state=J;let r=Object.values(t).join(", ")||"error";null==e||e(m.CHANNEL_ERROR,Error(r,{cause:t}))}).receive("timeout",()=>{null==e||e(m.TIMED_OUT)})}return this}_updatePostgresBindings(e,t){var r;let s=this.bindings.postgres_changes,n=null!=(r=null==s?void 0:s.length)?r:0,i=[];for(let r=0;r<n;r++){let n=s[r],{filter:{event:a,schema:o,table:l,filter:c}}=n,h=e&&e[r];if(h&&h.event===a&&eI.isFilterValueEqual(h.schema,o)&&eI.isFilterValueEqual(h.table,l)&&eI.isFilterValueEqual(h.filter,c))i.push(Object.assign(Object.assign({},n),{id:h.id}));else{this.unsubscribe(),this.state=J,null==t||t(m.CHANNEL_ERROR,Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=i,this.state!=J&&t&&t(m.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){let s=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),n=e===g.PRESENCE||e===g.POSTGRES_CHANGES;if(s&&n)throw this.socket.log("channel","cannot add `".concat(e,"` callbacks for ").concat(this.topic," after `subscribe()`.")),Error("cannot add `".concat(e,"` callbacks for ").concat(this.topic," after `subscribe()`."));return this._on(e,t,r)}async httpSend(e,t){var r;let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(null==t)return Promise.reject(Error("Payload is required for httpSend()"));let 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 ".concat(this.socket.accessTokenValue));let a=new URL(this.broadcastEndpointURL);a.pathname+="/".concat(encodeURIComponent(this.subTopic),"/events/").concat(encodeURIComponent(e)),this.private&&a.searchParams.set("private","true");let o={method:"POST",headers:i,body:n?t:JSON.stringify(t)},l=await this._fetchWithTimeout(a.toString(),o,null!=(r=s.timeout)?r:this.timeout);if(202===l.status)return{success:!0};let c=l.statusText;try{let e=await l.json();c=e.error||e.message||c}catch(e){}return Promise.reject(Error(c))}async send(e){var t,r;let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.channelAdapter.canPush()||"broadcast"!==e.type)return new Promise(t=>{var r,n,i;let a=this.channelAdapter.push(e.type,e,s.timeout||this.timeout);"broadcast"!==e.type||(null==(i=null==(n=null==(r=this.params)?void 0:r.config)?void 0:n.broadcast)?void 0:i.ack)||t("ok"),a.receive("ok",()=>t("ok")),a.receive("error",()=>t("error")),a.receive("timeout",()=>t("timed out"))});{console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated
1in the future. Please use httpSend() explicitly for REST delivery.");let{event:n,payload:i}=e,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization="Bearer ".concat(this.socket.accessTokenValue));let o={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:i,private:this.private}]})};try{let e=await this._fetchWithTimeout(this.broadcastEndpointURL,o,null!=(t=s.timeout)?t:this.timeout);return await (null==(r=e.body)?void 0:r.cancel()),e.ok?"ok":"error"}catch(e){if(e instanceof Error&&"AbortError"===e.name)return"timed out";return"error"}}}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]: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){let 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){let s=e.toLocaleLowerCase(),n=this.channelAdapter.on(e,r),i={type:s,filter:t,callback:r,ref:n};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;let h=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(h,r))return!1;let u=null==(s=this.bindings[h])?void 0:s.find(t=>t.ref===e.ref);if(!u)return!0;if(!["broadcast","presence","postgres_changes"].includes(h))return u.type.toLocaleLowerCase()===h;if("id"in u){let e=u.id,r=null==(n=u.filter)?void 0:n.event;return e&&(null==(i=t.ids)?void 0:i.includes(e))&&("*"===r||(null==r?void 0:r.toLocaleLowerCase())===(null==(a=t.data)?void 0:a.type.toLocaleLowerCase()))}{let e=null==(l=null==(o=null==u?void 0:u.filter)?void 0:o.event)?void 0:l.toLocaleLowerCase();return"*"===e||e===(null==(c=null==t?void 0:t.event)?void 0:c.toLocaleLowerCase())}})}_notThisChannelEvent(e,t){let{close:r,error:s,leave:n,join:i}=G;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){let e=t.data,{schema:r,table:s,commit_timestamp:n,type:i,errors:a}=e;return Object.assign(Object.assign({},{schema:r,table:s,commit_timestamp:n,eventType:i,new:{},old:{},errors:a}),this._getPayloadRecords(e))}return t})}copyBindings(e){if(this.joinedOnce)throw Error("cannot copy bindings into joined channel");for(let t in e.bindings)for(let 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){let t={new:{},old:{}};return("INSERT"===e.type||"UPDATE"===e.type)&&(t.new=Y(e.columns,e.record)),("UPDATE"===e.type||"DELETE"===e.type)&&(t.old=Y(e.columns,e.old_record)),t}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 ej(this.socket.socketAdapter,e,this.params),this.presence=new eP(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=en(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(null==(n=null==(s=this.params.config)?void 0:s.broadcast)?void 0:n.replay))throw Error("tried to use replay on public channel '".concat(this.topic,"'. It must be a private channel."))}}class ex{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){let s=arguments.length>3&&void 0!==arguments[3]?arguments[3]: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"connecting"==this.socket.connectionState()}isDisconnecting(){return"closing"==this.socket.connectionState()}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}constructor(e,t){this.socket=new eA(e,t)}}let eN=[1e3,2e3,5e3,1e4];class eU{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}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(t){let e=t.message;if(e.includes("Node.js"))throw Error("".concat(e,"\n\n")+'To use Realtime in Node.js, you need to provide a WebSocket implementation:\n\nOption 1: Use Node.js 22+ which has native WebSocket support\nOption 2: Install and provide the "ws" package:\n\n npm install ws\n\n import ws from "ws"\n const client = new RealtimeClient(url, {\n ...options,\n transport: ws\n })');throw Error("WebSocket not available: ".concat(e))}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){let t=await e.unsubscribe();return"ok"===t&&e.teardown(),t}async removeAllChannels(){let e=this.channels.map(async e=>{let 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()||"closed"}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{config:{}},r="realtime:".concat(e),s=this.getChannels().find(e=>e.topic===r);if(s)return s;{let r=new eI("realtime:".concat(e),t,this);return this._cancelPendingDisconnect(),this.channels.push(r),r}}push(e){this.socketAdapter.push(e)}async setAuth(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]: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){this.log("transport","disconnecting immediately - no channels"),this.disconnect();return}
1this._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 ".concat(this._disconnectOnEmptyChannelsAfterMs,"ms"))}_cancelPendingDisconnect(){null!==this._pendingDisconnectTimer&&(this.log("transport","pending disconnect cancelled - channel activity detected"),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null)}async _performAuth(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,r=!1;if(t)e=t,r=!0;else if(this.accessToken)try{e=await this.accessToken()}catch(t){this.log("error","Error fetching access token from callback",t),e=this.accessTokenValue}else e=this.accessTokenValue;r?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=e&&(this.accessTokenValue=e,this.channels.forEach(t=>{let r={access_token:e,version:K};e&&t.updateJoinPayload(r),t.joinedOnce&&t.channelAdapter.isJoined()&&t.channelAdapter.push(G.access_token,{access_token:e})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"general";this._isManualToken()||this.setAuth().catch(t=>{this.log("error","Error setting auth in ".concat(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)=>{"sent"==t&&this._setAuthSafely(),e&&e(t,r)}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker","starting worker for from ".concat(this.workerUrl)):this.log("worker","starting default worker");let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log("worker","worker error",e.message),this._terminateWorker(),this.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{let e=new Blob(['\n addEventListener("message", (e) => {\n if (e.data.event === "start") {\n setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);\n }\n });'],{type:"application/javascript"});t=URL.createObjectURL(e)}return t}_initializeOptions(e){var t,r,s,n,i,a,o,l,c,h,u,d;let p,f;this.worker=null!=(t=null==e?void 0:e.worker)&&t,this.accessToken=null!=(r=null==e?void 0:e.accessToken)?r:null;let g={};g.timeout=null!=(s=null==e?void 0:e.timeout)?s:1e4,g.heartbeatIntervalMs=null!=(n=null==e?void 0:e.heartbeatIntervalMs)?n:25e3,this._disconnectOnEmptyChannelsAfterMs=null!=(i=null==e?void 0:e.disconnectOnEmptyChannelsAfterMs)?i:2*(null!=(a=null==e?void 0:e.heartbeatIntervalMs)?a:25e3),g.transport=null!=(o=null==e?void 0:e.transport)?o:W.getWebSocketConstructor(),g.params=null==e?void 0:e.params,g.logger=null==e?void 0:e.logger,g.heartbeatCallback=this._wrapHeartbeatCallback(null==e?void 0:e.heartbeatCallback),g.sessionStorage=null!=(l=null==e?void 0:e.sessionStorage)?l:function(){let e;try{if("u">typeof globalThis&&globalThis.sessionStorage)return globalThis.sessionStorage}catch(e){}return e=new Map,{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])?r:null},removeItem(t){e.delete(t)},setItem(t,r){e.set(t,String(r))}}}(),g.reconnectAfterMs=null!=(c=null==e?void 0:e.reconnectAfterMs)?c:e=>eN[e-1]||1e4;let m=null!=(h=null==e?void 0:e.vsn)?h:F;switch(m){case"1.0.0":p=(e,t)=>t(JSON.stringify(e)),f=(e,t)=>t(JSON.parse(e));break;
1case F:p=this.serializer.encode.bind(this.serializer),f=this.serializer.decode.bind(this.serializer);break;default:throw Error("Unsupported serializer version: ".concat(g.vsn))}if(g.vsn=m,g.encode=null!=(u=null==e?void 0:e.encode)?u:p,g.decode=null!=(d=null==e?void 0:e.decode)?d:f,g.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,g.params=Object.assign(Object.assign({},g.params),{log_level:this.logLevel})),this.worker){if("u">typeof window&&!window.Worker)throw Error("Web Worker is not supported");this.workerUrl=null==e?void 0:e.workerUrl,g.autoSendHeartbeat=!this.worker}return g}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}constructor(e,t){var r;if(this.channels=[],this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new V,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=e=>e?function(){for(var t=arguments.length,r=Array(t),s=0;s<t;s++)r[s]=arguments[s];return e(...r)}:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return fetch(...t)},!(null==(r=null==t?void 0:t.params)?void 0:r.apikey))throw Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey;const s=this._initializeOptions(t);this.socketAdapter=new ex(e,s),this.httpEndpoint=en(e),this.fetch=this._resolveFetch(null==t?void 0:t.fetch)}}var eL=e.i(467034),eD=class extends Error{isNotFound(){return 404===this.status}isConflict(){return 409===this.status}isAuthenticationTimeout(){return 419===this.status}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)&&(null==(r=t.icebergType)?void 0:r.includes("CommitState"))===!0}};async function eB(e){return e&&"none"!==e.type?"bearer"===e.type?{Authorization:"Bearer ".concat(e.token)}:"header"===e.type?{[e.name]:e.value}:"custom"===e.type?await e.getHeaders():{}:{}}function eq(e){return e.join("\x1f")}var eH=class{async listNamespaces(e){let t=e?{parent:eq(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:"".concat(this.prefix,"/namespaces"),query:t})).data.namespaces.map(e=>({namespace:e}))}async createNamespace(e,t){let r={namespace:e.namespace,properties:null==t?void 0:t.properties};return(await this.client.request({method:"POST",path:"".concat(this.prefix,"/namespaces"),body:r})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:"".concat(this.prefix,"/namespaces/").concat(eq(e.namespace))})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:"".concat(this.prefix,"/namespaces/").concat(eq(e.namespace))})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:"".concat(this.prefix,"/namespaces/").concat(eq(e.namespace))}),!0}catch(e){if(e instanceof eD&&404===e.status)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof eD&&409===e.status)return;throw e}}constructor(e,t=""){this.client=e,this.prefix=t}};function eM(e){return e.join("\x1f")}var eW=class{async listTables(e){return(await this.client.request({method:"GET",path:"".concat(this.prefix,"/namespaces/").concat(eM(e.namespace),"/tables")})).data.identifiers}async createTable(e,t){let r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:"".concat(this.prefix,"/namespaces/").concat(eM(e.namespace),"/tables"),body:t,headers:r})).data.metadata}async updateTable(e,t){let r=await this.client.request({method:"POST",path:"".concat(this.prefix,"/namespaces/").concat(eM(e.namespace),"/tables/").concat(e.name),body:t});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(e,t){var r;await this.client.request({method:"DELETE",path:"".concat(this.prefix,"/namespaces/").concat(eM(e.namespace),"/tables/").concat(e.name),query:{purgeRequested:String(null!=(r=null==t?void 0:t.purge)&&r)}})}async loadTable(e){let t={};return this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:"".concat(this.prefix,"/namespaces/").concat(eM(e.namespace),"/tables/").concat(e.name),headers:t})).data.metadata}async tableExists(e){let t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:"".concat(this.prefix,"/namespaces/").concat(eM(e.namespace),"/tables/").concat(e.name),headers:t}),!0}catch(e){if(e instanceof eD&&404===e.status)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(r){if(r instanceof eD&&409===r.status)return await this.loadTable({namespace:e.namespace,name:t.name});throw r}}constructor(e,t="",r){this.client=e,this.prefix=t,this.accessDelegation=r}},eK=class{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)}
1async 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)}constructor(e){var t;let r="v1";e.catalogName&&(r+="/".concat(e.catalogName));const s=e.baseUrl.endsWith("/")?e.baseUrl:"".concat(e.baseUrl,"/");this.client=function(e){var t;let r=null!=(t=e.fetchImpl)?t:globalThis.fetch;return{async request(t){let{method:s,path:n,query:i,body:a,headers:o}=t,l=function(e,t,r){let s=new URL(t,e);if(r)for(let[e,t]of Object.entries(r))void 0!==t&&s.searchParams.set(e,t);return s.toString()}(e.baseUrl,n,i),c=await eB(e.auth),h=await r(l,{method:s,headers:(0,v._)({},a?{"Content-Type":"application/json"}:{},c,o),body:a?JSON.stringify(a):void 0}),u=await h.text(),d=(h.headers.get("content-type")||"").includes("application/json"),p=d&&u?JSON.parse(u):u;if(!h.ok){var f;let e=d?p:void 0,t=null==e?void 0:e.error;throw new eD(null!=(f=null==t?void 0:t.message)?f:"Request failed with status ".concat(h.status),{status:h.status,icebergType:null==t?void 0:t.type,icebergCode:null==t?void 0:t.code,details:e})}return{status:h.status,headers:h.headers,data:p}}}}({baseUrl:s,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=null==(t=e.accessDelegation)?void 0:t.join(","),this.namespaceOps=new eH(this.client,r),this.tableOps=new eW(this.client,r,this.accessDelegation)}};function eF(e){return(eF="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 eJ(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 ez(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?eJ(Object(r),!0).forEach(function(t){!function(e,t,r){var s;(s=function(e,t){if("object"!=eF(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=eF(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==eF(s)?s:s+"")in e)?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r}(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):eJ(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var eG=class extends Error{toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}constructor(e,t="storage",r,s){super(e),this.__isStorageError=!0,this.namespace=t,this.name="vectors"===t?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=s}};function eV(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}var eY=class extends eG{toJSON(){return ez({},super.toJSON())}constructor(e,t,r,s="storage"){super(e,s,t,r),this.name="vectors"===s?"StorageVectorsApiError":"StorageApiError",this.status=t,this.statusCode=r}},e$=class extends eG{constructor(e,t,r="storage"){super(e,r),this.name="vectors"===r?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=t}};function eX(e,t,r){let s=ez({},e),n=t.toLowerCase();for(let e of Object.keys(s))e.toLowerCase()===n&&delete s[e];return s[n]=r,s}let eQ=e=>{if(Array.isArray(e))return e.map(e=>eQ(e));if("function"==typeof e||e!==Object(e))return e;let t={};return Object.entries(e).forEach(e=>{let[r,s]=e;t[r.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(/[-_]/g,""))]=eQ(s)}),t},eZ=e=>{if("object"==typeof e&&null!==e){if("string"==typeof e.msg)return e.msg;if("string"==typeof e.message)return e.message;if("string"==typeof e.error_description)return e.error_description;if("string"==typeof e.error)return e.error;if("object"==typeof e.error&&null!==e.error){let t=e.error;if("string"==typeof t.message)return t.message}}return JSON.stringify(e)},e0=async(e,t,r,s)=>{if(null!==e&&"object"==typeof e&&"json"in e&&"function"==typeof e.json){let r=parseInt(String(e.status),10);Number.isFinite(r)||(r=500),e.json().then(e=>{let n=(null==e?void 0:e.statusCode)||(null==e?void 0:e.code)||r+"";t(new eY(eZ(e),r,n,s))}).catch(()=>{let n=r+"";t(new eY(e.statusText||"HTTP ".concat(r," error"),r,n,s))})}else t(new e$(eZ(e),e,s))};async function e1(e,t,r,s,n,i,a){return new Promise((o,l)=>{e(r,((e,t,r,s)=>{let n={method:e,headers:(null==t?void 0:t.headers)||{}};if("GET"===e||"HEAD"===e||!s)return ez(ez({},n),r);
1if((e=>{if("object"!=typeof e||null===e)return!1;let t=Object.getPrototypeOf(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)})(s)){var i;let e,r=(null==t?void 0:t.headers)||{};for(let[t,s]of Object.entries(r))"content-type"===t.toLowerCase()&&(e=s);n.headers=eX(r,"Content-Type",null!=(i=e)?i:"application/json"),n.body=JSON.stringify(s)}else n.body=s;return(null==t?void 0:t.duplex)&&(n.duplex=t.duplex),ez(ez({},n),r)})(t,s,n,i)).then(e=>{if(!e.ok)throw e;if(null==s?void 0:s.noResolveJson)return e;if("vectors"===a){let t=e.headers.get("content-type");if("0"===e.headers.get("content-length")||204===e.status||!t||!t.includes("application/json"))return{}}return e.json()}).then(e=>o(e)).catch(e=>e0(e,l,s,a))})}function e2(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"storage";return{get:async(t,r,s,n)=>e1(t,"GET",r,s,n,void 0,e),post:async(t,r,s,n,i)=>e1(t,"POST",r,n,i,s,e),put:async(t,r,s,n,i)=>e1(t,"PUT",r,n,i,s,e),head:async(t,r,s,n)=>e1(t,"HEAD",r,ez(ez({},s),{},{noResolveJson:!0}),n,void 0,e),remove:async(t,r,s,n,i)=>e1(t,"DELETE",r,n,i,s,e)}}let{get:e3,post:e8,put:e5,head:e4,remove:e6}=e2("storage"),e9=e2("vectors");var e7=class{throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=eX(this.headers,e,t),this}async handleOperation(e){try{return{data:await e(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eV(e))return{data:null,error:e};throw e}}constructor(e,t={},r,s="storage"){this.shouldThrowOnError=!1,this.url=e,this.headers=function(e){let t={};for(let[r,s]of Object.entries(e))t[r.toLowerCase()]=s;return t}(t),this.fetch=(e=>e?function(){for(var t=arguments.length,r=Array(t),s=0;s<t;s++)r[s]=arguments[s];return e(...r)}:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return fetch(...t)})(r),this.namespace=s}};t=Symbol.toStringTag;var te=class{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(eV(e))return{data:null,error:e};throw e}}constructor(e,r){this.downloadFn=e,this.shouldThrowOnError=r,this[t]="StreamDownloadBuilder",this.promise=null}};r=Symbol.toStringTag;var tt=class{asStream(){return new te(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(eV(e))return{data:null,error:e};throw e}}constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[r]="BlobDownloadBuilder",this.promise=null}};let tr={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},ts={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var tn=class extends e7{async uploadOrUpdate(e,t,r,s){var n=this;return n.handleOperation(async()=>{let i,a=ez(ez({},ts),s),o=ez(ez({},n.headers),"POST"===e&&{"x-upsert":String(a.upsert)}),l=a.metadata;if("u">typeof Blob&&r instanceof Blob?((i=new FormData).append("cacheControl",a.cacheControl),l&&i.append("metadata",n.encodeMetadata(l)),i.append("",r)):"u">typeof FormData&&r instanceof FormData?((i=r).has("cacheControl")||i.append("cacheControl",a.cacheControl),l&&!i.has("metadata")&&i.append("metadata",n.encodeMetadata(l))):(i=r,o["cache-control"]="max-age=".concat(a.cacheControl),o["content-type"]=a.contentType,l&&(o["x-metadata"]=n.toBase64(n.encodeMetadata(l))),("u">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(let[e,t]of Object.entries(s.headers))o=eX(o,e,t);let c=n._removeEmptyFolders(t),h=n._getFinalPath(c),u=await ("PUT"==e?e5:e8)(n.fetch,"".concat(n.url,"/object/").concat(h),i,ez({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;let i=n._removeEmptyFolders(e),a=n._getFinalPath(i),o=new URL(n.url+"/object/upload/sign/".concat(a));return o.searchParams.set("token",t),n.handleOperation(async()=>{let e,t=ez(ez({},ts),s),a=ez(ez({},n.headers),{"x-upsert":String(t.upsert)}),l=t.metadata;if("u">typeof Blob&&r instanceof Blob?((e=new FormData).append("cacheControl",t.cacheControl),l&&e.append("metadata",n.encodeMetadata(l)),e.append("",r)):"u">typeof FormData&&r instanceof FormData?((e=r).has("cacheControl")||e.append("cacheControl",t.cacheControl),l&&!e.has("metadata")&&e.append("metadata",n.encodeMetadata(l))):(e=r,a["cache-control"]="max-age=".concat(t.cacheControl),a["content-type"]=t.contentType,l&&(a["x-metadata"]=n.toBase64(n.encodeMetadata(l))),("u">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(let[e,t]of Object.entries(s.headers))a=eX(a,e,t);return{path:i,fullPath:(await e5(n.fetch,o.toString(),e,ez({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),n=ez({},r.headers);(null==t?void 0:t.upsert)&&(n["x-upsert"]="true");let i=await e8(r.fetch,"".concat(r.url,"/object/upload/sign/").concat(s),{},{headers:n}),a=new URL(r.url+i.url),o=a.searchParams.get("token");if(!o)throw new eG("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 e8(s.fetch,"".concat(s.url,"/object/move"),{bucketId:s.bucketId,sourceKey:e,destinationKey:t,de
1stinationBucket:null==r?void 0:r.destinationBucket},{headers:s.headers}))}async copy(e,t,r){var s=this;return s.handleOperation(async()=>({path:(await e8(s.fetch,"".concat(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),i="object"==typeof(null==r?void 0:r.transform)&&null!==r.transform&&Object.keys(r.transform).length>0,a=await e8(s.fetch,"".concat(s.url,"/object/sign/").concat(n),ez({expiresIn:t},i?{transform:r.transform}:{}),{headers:s.headers}),o=new URLSearchParams;(null==r?void 0:r.download)&&o.set("download",!0===r.download?"":r.download),(null==r?void 0:r.cacheNonce)!=null&&o.set("cacheNonce",String(r.cacheNonce));let l=o.toString();return{signedUrl:encodeURI("".concat(s.url).concat(a.signedURL).concat(l?"&".concat(l):""))}})}async createSignedUrls(e,t,r){var s=this;return s.handleOperation(async()=>{let n=await e8(s.fetch,"".concat(s.url,"/object/sign/").concat(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==r?void 0:r.cacheNonce)!=null&&i.set("cacheNonce",String(r.cacheNonce));let a=i.toString();return n.map(e=>ez(ez({},e),{},{signedUrl:e.signedURL?encodeURI("".concat(s.url).concat(e.signedURL).concat(a?"&".concat(a):"")):null}))})}download(e,t,r){let 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==t?void 0:t.cacheNonce)!=null&&n.set("cacheNonce",String(t.cacheNonce));let i=n.toString(),a=this._getFinalPath(e);return new tt(()=>e3(this.fetch,"".concat(this.url,"/").concat(s,"/").concat(a).concat(i?"?".concat(i):""),{headers:this.headers,noResolveJson:!0},r),this.shouldThrowOnError)}async info(e){var t=this;let r=t._getFinalPath(e);return t.handleOperation(async()=>eQ(await e3(t.fetch,"".concat(t.url,"/object/info/").concat(r),{headers:t.headers})))}async exists(e){var t;let r=this._getFinalPath(e);try{return await e4(this.fetch,"".concat(this.url,"/object/").concat(r),{headers:this.headers}),{data:!0,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eV(e)){let r=e instanceof eY?e.status:e instanceof e$?null==(t=e.originalError)?void 0:t.status:void 0;if(void 0!==r&&[400,404].includes(r))return{data:!1,error:e}}throw e}}getPublicUrl(e,t){let 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==t?void 0:t.cacheNonce)!=null&&s.set("cacheNonce",String(t.cacheNonce));let 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("".concat(this.url,"/").concat(i,"/public/").concat(r))+(n?"?".concat(n):"")}}}async remove(e){var t=this;return t.handleOperation(async()=>await e6(t.fetch,"".concat(t.url,"/object/").concat(t.bucketId),{prefixes:e},{headers:t.headers}))}async list(e,t,r){var s=this;return s.handleOperation(async()=>{let n=ez(ez(ez({},tr),t),{},{prefix:e||""});return await e8(s.fetch,"".concat(s.url,"/object/list/").concat(s.bucketId),n,{headers:s.headers},r)})}async listV2(e,t){var r=this;return r.handleOperation(async()=>{let s=ez({},e);return await e8(r.fetch,"".concat(r.url,"/object/list-v2/").concat(r.bucketId),s,{headers:r.headers},t)})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return void 0!==eL.Buffer?eL.Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return"".concat(this.bucketId,"/").concat(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("qual
1ity",t.quality.toString()),e}constructor(e,t={},r,s){super(e,t,s,"storage"),this.bucketId=r}};let ti={"X-Client-Info":"storage-js/".concat("2.108.1")};var ta=class extends e7{async listBuckets(e){var t=this;return t.handleOperation(async()=>{let r=t.listBucketOptionsToQueryString(e);return await e3(t.fetch,"".concat(t.url,"/bucket").concat(r),{headers:t.headers})})}async getBucket(e){var t=this;return t.handleOperation(async()=>await e3(t.fetch,"".concat(t.url,"/bucket/").concat(e),{headers:t.headers}))}async createBucket(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{public:!1};var r=this;return r.handleOperation(async()=>await e8(r.fetch,"".concat(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 e5(r.fetch,"".concat(r.url,"/bucket/").concat(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 e8(t.fetch,"".concat(t.url,"/bucket/").concat(e,"/empty"),{},{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await e6(t.fetch,"".concat(t.url,"/bucket/").concat(e),{},{headers:t.headers}))}listBucketOptionsToQueryString(e){let t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}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(/\/$/,""),ez(ez({},ti),t),r,"storage")}},to=class extends e7{async createBucket(e){var t=this;return t.handleOperation(async()=>await e8(t.fetch,"".concat(t.url,"/bucket"),{name:e},{headers:t.headers}))}async listBuckets(e){var t=this;return t.handleOperation(async()=>{let r=new URLSearchParams;(null==e?void 0:e.limit)!==void 0&&r.set("limit",e.limit.toString()),(null==e?void 0:e.offset)!==void 0&&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);let s=r.toString(),n=s?"".concat(t.url,"/bucket?").concat(s):"".concat(t.url,"/bucket");return await e3(t.fetch,n,{headers:t.headers})})}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await e6(t.fetch,"".concat(t.url,"/bucket/").concat(e),{},{headers:t.headers}))}from(e){var t=this;if(!(!(!e||"string"!=typeof e||0===e.length||e.length>100||e.trim()!==e||e.includes("/")||e.includes("\\"))&&/^[\w!.\*'() &$@=;:+,?-]+$/.test(e)))throw new eG("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");let r=new eK({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:async()=>t.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(e,t){let r=e[t];return"function"!=typeof r?r:async function(){for(var t=arguments.length,n=Array(t),i=0;i<t;i++)n[i]=arguments[i];try{return{data:await r.apply(e,n),error:null}}catch(e){if(s)throw e;return{data:null,error:e}}}}})}constructor(e,t={},r){super(e.replace(/\/$/,""),ez(ez({},ti),t),r,"storage")}},tl=class extends e7{async createIndex(e){var t=this;return t.handleOperation(async()=>await e9.post(t.fetch,"".concat(t.url,"/CreateIndex"),e,{headers:t.headers})||{})}async getIndex(e,t){var r=this;return r.handleOperation(async()=>await e9.post(r.fetch,"".concat(r.url,"/GetIndex"),{vectorBucketName:e,indexName:t},{headers:r.headers}))}async listIndexes(e){var t=this;return t.handleOperation(async()=>await e9.post(t.fetch,"".concat(t.url,"/ListIndexes"),e,{headers:t.headers}))}async deleteIndex(e,t){var r=this;return r.handleOperation(async()=>await e9.post(r.fetch,"".concat(r.url,"/DeleteIndex"),{vectorBucketName:e,indexName:t},{headers:r.headers})||{})}constructor(e,t={},r){super(e.replace(/\/$/,""),ez(ez({},ti),{},{"Content-Type":"application/json"},t),r,"vectors")}},tc=class extends e7{async putVectors(e){var t=this;if(e.vectors.length<1||e.vectors.length>500)throw Error("Vector batch size must be between 1 and 500 items");return t.handleOperation(async()=>await e9.post(t.fetch,"".concat(t.url,"/PutVectors"),e,{headers:t.headers})||{})}async getVectors(e){var t=this;return t.handleOperation(async()=>await e9.post(t.fetch,"".concat(t.url,"/GetVectors"),e,{headers:t.headers}))}async listVectors(e){var t=this;if(void 0!==e.segmentCount){if(e.segmentCount<1||e.segmentCount>16)throw Error("segmentCount must be between 1 and 16");
1if(void 0!==e.segmentIndex&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw Error("segmentIndex must be between 0 and ".concat(e.segmentCount-1))}return t.handleOperation(async()=>await e9.post(t.fetch,"".concat(t.url,"/ListVectors"),e,{headers:t.headers}))}async queryVectors(e){var t=this;return t.handleOperation(async()=>await e9.post(t.fetch,"".concat(t.url,"/QueryVectors"),e,{headers:t.headers}))}async deleteVectors(e){var t=this;if(e.keys.length<1||e.keys.length>500)throw Error("Keys batch size must be between 1 and 500 items");return t.handleOperation(async()=>await e9.post(t.fetch,"".concat(t.url,"/DeleteVectors"),e,{headers:t.headers})||{})}constructor(e,t={},r){super(e.replace(/\/$/,""),ez(ez({},ti),{},{"Content-Type":"application/json"},t),r,"vectors")}},th=class extends e7{async createBucket(e){var t=this;return t.handleOperation(async()=>await e9.post(t.fetch,"".concat(t.url,"/CreateVectorBucket"),{vectorBucketName:e},{headers:t.headers})||{})}async getBucket(e){var t=this;return t.handleOperation(async()=>await e9.post(t.fetch,"".concat(t.url,"/GetVectorBucket"),{vectorBucketName:e},{headers:t.headers}))}async listBuckets(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};var t=this;return t.handleOperation(async()=>await e9.post(t.fetch,"".concat(t.url,"/ListVectorBuckets"),e,{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await e9.post(t.fetch,"".concat(t.url,"/DeleteVectorBucket"),{vectorBucketName:e},{headers:t.headers})||{})}constructor(e,t={},r){super(e.replace(/\/$/,""),ez(ez({},ti),{},{"Content-Type":"application/json"},t),r,"vectors")}},tu=class extends th{from(e){return new td(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(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return super.listBuckets.call(this,e)}async deleteBucket(e){return super.deleteBucket.call(this,e)}constructor(e,t={}){super(e,t.headers||{},t.fetch)}},td=class extends tl{async createIndex(e){return super.createIndex.call(this,ez(ez({},e),{},{vectorBucketName:this.vectorBucketName}))}async listIndexes(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return super.listIndexes.call(this,ez(ez({},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 tp(this.url,this.headers,this.vectorBucketName,e,this.fetch)}constructor(e,t,r,s){super(e,t,s),this.vectorBucketName=r}},tp=class extends tc{async putVectors(e){return super.putVectors.call(this,ez(ez({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async getVectors(e){return super.getVectors.call(this,ez(ez({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async listVectors(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return super.listVectors.call(this,ez(ez({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async queryVectors(e){return super.queryVectors.call(this,ez(ez({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async deleteVectors(e){return super.deleteVectors.call(this,ez(ez({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}constructor(e,t,r,s,n){super(e,t,n),this.vectorBucketName=r,this.indexName=s}},tf=class extends ta{from(e){return new tn(this.url,this.headers,e,this.fetch)}get vectors(){return new tu(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new to(this.url+"/iceberg",this.headers,this.fetch)}constructor(e,t={},r,s){super(e,t,r,s)}};let tg="2.108.1",tm="X-Supabase-Api-Version",ty={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},tw=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;class tb extends Error{toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.co
1de=r}}function tv(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class t_ extends tb{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}}class tk extends tb{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class tS extends tb{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}}class tE extends tS{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function tT(e){return tv(e)&&"AuthSessionMissingError"===e.name}class tA extends tS{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class tR extends tS{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class tO extends tS{toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}}class tC extends tS{toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}}class tP extends tS{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 tj extends tS{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function tI(e){return tv(e)&&"AuthRetryableFetchError"===e.name}class tx extends tS{constructor(e="Refresh result discarded: session state changed mid-flight (e.g., concurrent signOut)"){super(e,"AuthRefreshDiscardedError",409,void 0)}}class tN extends tS{toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}}class tU extends tS{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}let tL="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),tD=" \n\r=".split(""),tB=(()=>{let e=Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<tD.length;t+=1)e[tD[t].charCodeAt(0)]=-2;for(let t=0;t<tL.length;t+=1)e[tL[t].charCodeAt(0)]=t;return e})();function tq(e,t,r){if(null!==e)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;)r(tL[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6;else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;)r(tL[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6}function tH(e,t,r){let s=tB[e];if(s>-1)for(t.queue=t.queue<<6|s,t.queuedBits+=6;t.queuedBits>=8;)r(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else if(-2===s)return;else throw Error('Invalid Base64-URL character "'.concat(String.fromCharCode(e),'"'))}function tM(e){let 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 r(e);for(let r=1;r<6;r+=1)if((e>>7-r&1)==0){t.utf8seq=r;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else if(4===t.utf8seq)t.codepoint=7&e;else throw Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&r(t.codepoint)}}(e,s,r)};for(let t=0;t<e.length;t+=1)tH(e.charCodeAt(t),n,i);return t.join("")}function tW(e){let t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};for(let t=0;t<e.length;t+=1)tH(e.charCodeAt(t),r,s);return new Uint8Array(t)}function tK(e){let t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};return e.forEach(e=>tq(e,r,s)),tq(null,r,s),t.join("")}let tF=()=>"u">typeof window&&"u">typeof document,tJ={tested:!1,writable:!1},tz=()=>{if(!tF())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(tJ.tested)return tJ.writable;let e="lswt-".concat(Math.random()).concat(Math.random());try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),tJ.tested=!0,tJ.writable=!0}catch(e){tJ.tested=!0,tJ.writable=!1}return tJ.writable},tG=e=>e?function(){for(var t=arguments.length,r=Array(t),s=0;s<t;s++)r[s]=arguments[s];return e(...r)}:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return fetch(...t)},tV=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},tY=async(e,t)=>{let r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch(e){return null}},t$=async(e,t)=>{await e.removeItem(t)};class tX{constructor(){this.promise=new tX.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function tQ(e){let t=e.split(".");if(3!==t.length)throw new tU("Invalid JWT structure");for(let e=0;e<t.length;e++)if(!tw.test(t[e]))throw new tU("JWT not in base64url format");return{header:JSON.parse(tM(t[0])),payload:JSON.parse(tM(t[1])),signature:tW(t[2]),raw:{header:t[0],payload:t[1]}}}async function tZ(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}function t0(e){return("0"+e.toString(16)).substr(-2)}async function t1(e){let t=new TextEncoder().encode(e);return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",t))).map(e=>String.fromCharCode(e)).join("")}async function t2(e){return"u">typeof crypto&&void 0!==crypto.subtle&&"u">typeof TextEncoder?btoa(await t1(e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""):(console.warn("WebCrypto API is not supported. Code
1challenge method will default to use plain instead of sha256."),e)}async function t3(e,t){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],s=function(){let e=new Uint32Array(56);if("u"<typeof crypto){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length,r="";for(let s=0;s<56;s++)r+=e.charAt(Math.floor(Math.random()*t));return r}return crypto.getRandomValues(e),Array.from(e,t0).join("")}(),n=s;r&&(n+="/recovery"),await tV(e,"".concat(t,"-code-verifier"),n);let i=await t2(s),a=s===i?"plain":"s256";return[i,a]}tX.promiseConstructor=Promise;let t8=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i,t5=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function t4(e){if(!t5.test(e))throw Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function t6(e){if(!e.passkey)throw 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 t9(){return new Proxy({},{get:(e,t)=>{if("__isUserNotAvailableProxy"===t)return!0;if("symbol"==typeof t){let e=t.toString();if("Symbol(Symbol.toPrimitive)"===e||"Symbol(Symbol.toStringTag)"===e||"Symbol(util.inspect.custom)"===e)return}throw Error('@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "'.concat(t,'" property of the session object is not supported. Please use getUser() instead.'))},set:(e,t)=>{throw Error('@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "'.concat(t,'" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.'))},deleteProperty:(e,t)=>{throw Error('@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "'.concat(t,'" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.'))}})}function t7(e){return JSON.parse(JSON.stringify(e))}let re=e=>{if("object"==typeof e&&null!==e){if("string"==typeof e.msg)return e.msg;if("string"==typeof e.message)return e.message;if("string"==typeof e.error_description)return e.error_description;if("string"==typeof e.error)return e.error}return JSON.stringify(e)},rt=[502,503,504,520,521,522,523,524,530];async function rr(e){var t;let r,s;if(!("object"==typeof e&&null!==e&&"status"in e&&"ok"in e&&"json"in e&&"function"==typeof e.json))throw new tj(re(e),0);if(rt.includes(e.status))throw new tj(re(e),e.status);try{r=await e.json()}catch(e){throw new tk(re(e),e)}let n=function(e){let t=e.headers.get(tm);if(!t||!t.match(t8))return null;try{return new Date("".concat(t,"T00:00:00.0Z"))}catch(e){return null}}(e);if(n&&n.getTime()>=ty["2024-01-01"].timestamp&&"object"==typeof r&&r&&"string"==typeof r.code?s=r.code:"object"==typeof r&&r&&"string"==typeof r.error_code&&(s=r.error_code),s){if("weak_password"===s)throw new tN(re(r),e.status,(null==(t=r.weak_password)?void 0:t.reasons)||[]);else if("session_not_found"===s)throw new tE}else if("object"==typeof r&&r&&"object"==typeof r.weak_password&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0))throw new tN(re(r),e.status,r.weak_password.reasons);throw new t_(re(r),e.status||500,s)}async function rs(e,t,r,s){var n;let i=Object.assign({},null==s?void 0:s.headers);i[tm]||(i[tm]=ty["2024-01-01"].name),(null==s?void 0:s.jwt)&&(i.Authorization="Bearer ".concat(s.jwt));let a=null!=(n=null==s?void 0:s.query)?n:{};(null==s?void 0:s.redirectTo)&&(a.redirect_to=s.redirectTo);let o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",l=await rn(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}}async function rn(e,t,r,s,n,i){let a,o,l=(o={method:t,headers:(null==s?void 0:s.headers)||{}},"GET"===t?o:(o.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"}
1,null==s?void 0:s.headers),o.body=JSON.stringify(i),Object.assign(Object.assign({},o),n)));try{a=await e(r,Object.assign({},l))}catch(e){throw console.error(e),new tj(re(e),0)}if(a.ok||await rr(a),null==s?void 0:s.noResolveJson)return a;try{return await a.json()}catch(e){await rr(e)}}function ri(e){var t,r,s;let n=null;(s=e).access_token&&s.refresh_token&&s.expires_in&&(n=Object.assign({},e),e.expires_at||(n.expires_at=(r=e.expires_in,Math.round(Date.now()/1e3)+r)));return{data:{session:n,user:null!=(t=e.user)?t:"string"==typeof(null==e?void 0:e.id)?e:null},error:null}}function ra(e){let t=ri(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 ro(e){var t;return{data:{user:null!=(t=e.user)?t:e},error:null}}function rl(e){return{data:e,error:null}}function rc(e){let{action_link:t,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i}=e;return{data:{properties:{action_link:t,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i},user:Object.assign({},A(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]))},error:null}}function rh(e){return e}let ru=["global","local","others"];class rd{async signOut(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ru[0];if(0>ru.indexOf(t))throw Error("@supabase/auth-js: Parameter scope must be one of ".concat(ru.join(", ")));try{return await rs(this.fetch,"POST","".concat(this.url,"/logout?scope=").concat(t),{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(tv(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};try{return await rs(this.fetch,"POST","".concat(this.url,"/invite"),{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:ro})}catch(e){if(tv(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{let{options:t}=e,r=A(e,["options"]),s=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(s.new_email=null==r?void 0:r.newEmail,delete s.newEmail),await rs(this.fetch,"POST","".concat(this.url,"/admin/generate_link"),{body:s,headers:this.headers,xform:rc,redirectTo:null==t?void 0:t.redirectTo})}catch(e){if(tv(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await rs(this.fetch,"POST","".concat(this.url,"/admin/users"),{body:e,headers:this.headers,xform:ro})}catch(e){if(tv(e))return{data:{user:null},error:e};throw e}}async listUsers(e){var t,r,s,n,i,a,o;try{let l={nextPage:null,lastPage:0,total:0},c=await rs(this.fetch,"GET","".concat(this.url,"/admin/users"),{headers:this.headers,noResolveJson:!0,query:{page:null!=(r=null==(t=null==e?void 0:e.page)?void 0:t.toString())?r:"",per_page:null!=(n=null==(s=null==e?void 0:e.perPage)?void 0:s.toString())?n:""},xform:rh});if(c.error)throw c.error;let h=await c.json(),u=null!=(i=c.headers.get("x-total-count"))?i:0,d=null!=(o=null==(a=c.headers.get("link"))?void 0:a.split(","))?o:[];return d.length>0&&(d.forEach(e=>{let t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l["".concat(r,"Page")]=t}),l.total=parseInt(u)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(e){if(tv(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){t4(e);try{return await rs(this.fetch,"GET","".concat(this.url,"/admin/users/").concat(e),{headers:this.headers,xform:ro})}catch(e){if(tv(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){t4(e);try{return await rs(this.fetch,"PUT","".concat(this.url,"/admin/users/").concat(e),{body:t,headers:this.headers,xform:ro})}catch(e){if(tv(e))return{data:{user:null},error:e};throw e}}async deleteUser(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];t4(e);try{return await rs(this.fetch,"DELETE","".concat(this.url,"/admin/users/").concat(e),{headers:this.headers,body:{should_soft_delete:t},xform:ro})}catch(e){if(tv(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){t4(e.userId);try{let{data:t,error:r}=await rs(this.fetch,"GET","".concat(this.url,"/admin/users/").concat(e.userId,"/factors"),{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:r}}catch(e){if(tv(e))return{data:null,error:e};throw e}}async _deleteFactor(e){t4(e.userId),t4(e.id);
1try{return{data:await rs(this.fetch,"DELETE","".concat(this.url,"/admin/users/").concat(e.userId,"/factors/").concat(e.id),{headers:this.headers}),error:null}}catch(e){if(tv(e))return{data:null,error:e};throw e}}async _listOAuthClients(e){var t,r,s,n,i,a,o;try{let l={nextPage:null,lastPage:0,total:0},c=await rs(this.fetch,"GET","".concat(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.toString())?r:"",per_page:null!=(n=null==(s=null==e?void 0:e.perPage)?void 0:s.toString())?n:""},xform:rh});if(c.error)throw c.error;let h=await c.json(),u=null!=(i=c.headers.get("x-total-count"))?i:0,d=null!=(o=null==(a=c.headers.get("link"))?void 0:a.split(","))?o:[];return d.length>0&&(d.forEach(e=>{let t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l["".concat(r,"Page")]=t}),l.total=parseInt(u)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(e){if(tv(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await rs(this.fetch,"POST","".concat(this.url,"/admin/oauth/clients"),{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tv(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await rs(this.fetch,"GET","".concat(this.url,"/admin/oauth/clients/").concat(e),{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tv(e))return{data:null,error:e};throw e}}async _updateOAuthClient(e,t){try{return await rs(this.fetch,"PUT","".concat(this.url,"/admin/oauth/clients/").concat(e),{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tv(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await rs(this.fetch,"DELETE","".concat(this.url,"/admin/oauth/clients/").concat(e),{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(tv(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await rs(this.fetch,"POST","".concat(this.url,"/admin/oauth/clients/").concat(e,"/regenerate_secret"),{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tv(e))return{data:null,error:e};throw e}}async _listCustomProviders(e){try{let t={};return(null==e?void 0:e.type)&&(t.type=e.type),await rs(this.fetch,"GET","".concat(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)?t:[]},error:null}}})}catch(e){if(tv(e))return{data:{providers:[]},error:e};throw e}}async _createCustomProvider(e){try{return await rs(this.fetch,"POST","".concat(this.url,"/admin/custom-providers"),{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tv(e))return{data:null,error:e};throw e}}async _getCustomProvider(e){try{return await rs(this.fetch,"GET","".concat(this.url,"/admin/custom-providers/").concat(e),{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tv(e))return{data:null,error:e};throw e}}async _updateCustomProvider(e,t){try{return await rs(this.fetch,"PUT","".concat(this.url,"/admin/custom-providers/").concat(e),{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tv(e))return{data:null,error:e};throw e}}async _deleteCustomProvider(e){try{return await rs(this.fetch,"DELETE","".concat(this.url,"/admin/custom-providers/").concat(e),{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(tv(e))return{data:null,error:e};throw e}}async _adminListPasskeys(e){t6(this.experimental),t4(e.userId);try{return await rs(this.fetch,"GET","".concat(this.url,"/admin/users/").concat(e.userId,"/passkeys"),{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tv(e))return{data:null,error:e};throw e}}async _adminDeletePasskey(e){t6(this.experimental),t4(e.userId),t4(e.passkeyId);try{return await rs(this.fetch,"DELETE","".concat(this.url,"/admin/users/").concat(e.userId,"/passkeys/").concat(e.passkeyId),{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(tv(e))return{data:null,error:e};throw e}}constructor({url:e="",headers:t={},fetch:r,experimental:s}){this.url=e,this.headers=t,this.fetch=tG(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)}}}function rp(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{getItem:t=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:t=>{delete e[t]}}}globalThis&&tz()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug");
1class rf extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}function rg(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw Error('@supabase/auth-js: Address "'.concat(e,'" is invalid.'));return e.toLowerCase()}class rm extends Error{toJSON(){return{name:this.name,message:this.message,code:this.code}}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)?n:"Unknown Error",this.code=t}}class ry extends rm{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}let rw=new class{createNewAbortSignal(){if(this.controller){let e=Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}};function rb(e){if(!e)throw Error("Credential creation options are required");if("u">typeof PublicKeyCredential&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(e);let{challenge:t,user:r,excludeCredentials:s}=e,n=A(e,["challenge","user","excludeCredentials"]),i=tW(t).buffer,a=Object.assign(Object.assign({},r),{id:tW(r.id).buffer}),o=Object.assign(Object.assign({},n),{challenge:i,user:a});if(s&&s.length>0){o.excludeCredentials=Array(s.length);for(let e=0;e<s.length;e++){let t=s[e];o.excludeCredentials[e]=Object.assign(Object.assign({},t),{id:tW(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return o}function rv(e){if(!e)throw Error("Credential request options are required");if("u">typeof PublicKeyCredential&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseRequestOptionsFromJSON)return PublicKeyCredential.parseRequestOptionsFromJSON(e);let{challenge:t,allowCredentials:r}=e,s=A(e,["challenge","allowCredentials"]),n=tW(t).buffer,i=Object.assign(Object.assign({},s),{challenge:n});if(r&&r.length>0){i.allowCredentials=Array(r.length);for(let e=0;e<r.length;e++){let t=r[e];i.allowCredentials[e]=Object.assign(Object.assign({},t),{id:tW(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return i}function r_(e){var t;return"toJSON"in e&&"function"==typeof e.toJSON?e.toJSON():{id:e.id,rawId:e.id,response:{attestationObject:tK(new Uint8Array(e.response.attestationObject)),clientDataJSON:tK(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:null!=(t=e.authenticatorAttachment)?t:void 0}}function rk(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();let r=e.getClientExtensionResults(),s=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:tK(new Uint8Array(s.authenticatorData)),clientDataJSON:tK(new Uint8Array(s.clientDataJSON)),signature:tK(new Uint8Array(s.signature)),userHandle:s.userHandle?tK(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:r,authenticatorAttachment:null!=(t=e.authenticatorAttachment)?t:void 0}}function rS(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function rE(){var e,t;return!!(tF()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&"function"==typeof(null==(e=null==navigator?void 0:navigator.credentials)?void 0:e.create)&&"function"==typeof(null==(t=null==navigator?void 0:navigator.credentials)?void 0:t.get))}async function rT(e){try{let t=await navigator.credentials.create(e);if(!t)return{data:null,error:new ry("Empty credential response",t)};if(!(t instanceof PublicKeyCredential))return{data:null,error:new ry("Browser returned unexpected credential type",t)};return{data:t,error:null}}catch(t){return{data:null,error:function(e){var t,r,s;let{error:n,options:i}=e,{publicKey:a}=i;if(!a)throw Error("options was missing required publicKey property");if("AbortError"===n.name){if(i.signal instanceof AbortSignal)return new rm({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else if("ConstraintError"===n.name){if((null==(t=a.authenticatorSelection)?void 0:t.requireResidentKey)===!0)return new rm({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:n});else if("conditional"===i.mediation&&(null==(r=a.authenticatorSelection)?void 0:r.userVerification)==="required")return new rm({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:n});else if((null==(s=a.authenticatorSelection)?void 0:s.userVerification)==="required")return new rm({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:n})}else if("InvalidStateError"===n.name)return new rm({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:n});else if("NotAllowedError"===n.name)return new rm({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});else if("NotSupportedError"===n.name)return new rm(0===a.pubKeyCredParams.filter(e=>"public-key"===e.type).length?{message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:n}:{message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:n});else if("SecurityError"===n.name){let e=window.location.hostname;if(!rS(e))return new rm({message:"".concat(window.location.hostname," is an invali
1d domain"),code:"ERROR_INVALID_DOMAIN",cause:n});if(a.rp.id!==e)return new rm({message:'The RP ID "'.concat(a.rp.id,'" is invalid for this domain'),code:"ERROR_INVALID_RP_ID",cause:n})}else if("TypeError"===n.name){if(a.user.id.byteLength<1||a.user.id.byteLength>64)return new rm({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:n})}else if("UnknownError"===n.name)return new rm({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n});return new rm({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}({error:t,options:e})}}}async function rA(e){try{let t=await navigator.credentials.get(e);if(!t)return{data:null,error:new ry("Empty credential response",t)};if(!(t instanceof PublicKeyCredential))return{data:null,error:new ry("Browser returned unexpected credential type",t)};return{data:t,error:null}}catch(t){return{data:null,error:function(e){let{error:t,o
1ptions:r}=e,{publicKey:s}=r;if(!s)throw Error("options was missing required publicKey property");if("AbortError"===t.name){if(r.signal instanceof AbortSignal)return new rm({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if("NotAllowedError"===t.name)return new rm({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});else if("SecurityError"===t.name){let e=window.location.hostname;if(!rS(e))return new rm({message:"".concat(window.location.hostname," is an invalid domain"),code:"ERROR_INVALID_DOMAIN",cause:t});if(s.rpId!==e)return new rm({message:'The RP ID "'.concat(s.rpId,'" is invalid for this domain'),code:"ERROR_INVALID_RP_ID",cause:t})}else if("UnknownError"===t.name)return new rm({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t});return new rm({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}({error:t,options:e})}}}let rR={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},rO={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function rC(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];let s=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),n=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),i={};for(let e of t)if(e)for(let t in e){let r=e[t];if(void 0!==r)if(Array.isArray(r))i[t]=r;else if(n(r))i[t]=r;else if(s(r)){let e=i[t];s(e)?i[t]=rC(e,r):i[t]=rC(r)}else i[t]=r}return i}class rP{async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge(e,t){var r,s,n,i,a;let{factorId:o,webauthn:l,friendlyName:c,signal:h}=e;try{let{data:e,error:u}=await this.client.mfa.challenge({factorId:o,webauthn:l});if(!e)return{data:null,error:u};let d=null!=h?h:rw.createNewAbortSignal();if("create"===e.webauthn.type){let{user:t}=e.webauthn.credential_options.publicKey;if(!t.name)if(c)t.name="".concat(t.id,":").concat(c);else{let e=(await this.client.getUser()).data.user,s=(null==(r=null==e?void 0:e.user_metadata)?void 0:r.name)||(null==e?void 0:e.email)||(null==e?void 0:e.id)||"User";t.name="".concat(t.id,":").concat(s)}t.displayName||(t.displayName=t.name)}switch(e.webauthn.type){case"create":{let r=(s=e.webauthn.credential_options.publicKey,n=null==t?void 0:t.create,rC(rR,s,n||{})),{data:i,error:a}=await rT({publicKey:r,signal:d});if(i)return{data:{factorId:o,challengeId:e.id,webauthn:{type:e.webauthn.type,credential_response:i}},error:null};return{data:null,error:a}}case"request":{let r=(i=e.webauthn.credential_options.publicKey,a=null==t?void 0:t.request,rC(rO,i,a||{})),{data:s,error:n}=await rA(Object.assign(Object.assign({},e.webauthn.credential_options),{publicKey:r,signal:d}));if(s)return{data:{factorId:o,challengeId:e.id,webauthn:{type:e.webauthn.type,credential_response:s}},error:null};return{data:null,error:n}}}}catch(e){if(tv(e))return{data:null,error:e};return{data:null,error:new tk("Unexpected error in challenge",e)}}}async _verify(e){let{challengeId:t,factorId:r,webauthn:s}=e;return this.client.mfa.verify({factorId:r,challengeId:t,webauthn:s})}async _authenticate(e,t){let{factorId:r,webauthn:{rpId:s="u">typeof window?window.location.hostname:void 0,rpOrigins:n="u">typeof window?[window.location.origin]:void 0,signal:i}={}}=e;if(!s)return{data:null,error:new tb("rpId is required for WebAuthn authentication")};try{if(!rE())return{data:null,error:new tk("Browser does not support WebAuthn",null)};let{data:e,error:a}=await this.challenge({factorId:r,webauthn:{rpId:s,rpOrigins:n},signal:i},{request:t});if(!e)return{data:null,error:a};let{webauthn:o}=e;return this._verify({factorId:r,challengeId:e.challengeId,webauthn:{type:o.type,rpId:s,rpOrigins:n,credential_response:o.credential_response}})}catch(e){if(tv(e))return{data:null,error:e};return{data:null,error:new tk("Unexpected error in authenticate",e)}}}async _register(e,t){let{friendlyName:r,webauthn:{rpId:s="u">typeof window?window.location.hostname:void 0,rpOrigins:n="u">typeof window?[window.location.origin]:void 0,signal:i}={}}=e;if(!s)return{data:null,error:new tb("rpId is required for WebAuthn registration")};try{if(!rE())return{data:null,error:new tk("Browser does not support WebAuthn",null)};let{data:e,error:a}=await this._enroll({friendlyName:r});if(!e)return await this.client.mfa.listFactors().then(e=>{var t;return null==(t=e.data)?void 0:t.all.find(e=>"webauthn"===e.factor_type&&e.friendly_name===r&&"unverified"!==e.status)}).then(e=>e?this.client.mfa.unenroll({factorId:null==e?void 0:e.id}):void 0),{data:null,error:a};let{data:o,error:l}=await this._challenge({factorId:e.id,friendlyName:e.friendly_name,webauthn:{rpId:s,rpOrigins:n},signal:i},{create:t});if(!o)return{data:null,error:l};return this._verify({factorId:e.id,challengeId:o.challengeId,webauthn:{rpId:s,rpOrigins:n,type:o.webauthn.type,credential_response:o.webauthn.credential_response}})}catch(e){if(tv(e))return{data:null,error:e};return{data:null,error:new tk("Unexpected error in register",e)}}}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)}}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){"u">typeof self&&(self.globalThis=self)}let rj={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:{"X-Client-Info":"gotrue-js/".concat(tg)},flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}},rI={};class rx{get jwks(){var e,t;return null!=(t=null==(e=rI[this.storageKey])?void 0:e.jwks)?t:{keys:[]}}set jwks(e){rI[this.storageKey]=Object.assign(Object.assign({},rI[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return null!=(t=null==(e=rI[this.storageKey])?void 0:e.cachedAt)?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){rI[this.storageKey]=Object.assign(Object.assign({},rI[this.storageKey]),{cachedAt:e})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return"GoTrueClient@"+"".concat(this.storageKey,":").concat(this.instanceID," (").concat(tg,") ").concat(new Date().toISOString())}_debug(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.logDebugMessages&&this.logger(this._logPrefix(),...t),this}async initialize(){return this.initializePromise||(this.initializePromise=(async()=>null!=this.lock?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())()),await this.initializePromise}async _initialize(){var e;try{let t={},r="none";if(tF()&&(t=function(e){let t={},r=new URL(e);if(r.hash&&"#"===r.hash[0])try{new URLSearchParams(r.hash.substring(1)).forEac
1h((e,r)=>{t[r]=e})}catch(e){}return r.searchParams.forEach((e,r)=>{t[r]=e}),t}(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),tF()&&this.detectSessionInUrl&&"none"!==r){let{data:s,error:n}=await this._getSessionFromURL(t,r);if(n){(this._debug("#_initialize()","error detecting session from URL",n),tv(n)&&"AuthImplicitGrantRedirectError"===n.name)&&(null==(e=n.details)||e.code);return{error:n}}let{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(e){if(tv(e))return this._returnResult({error:e});return this._returnResult({error:new tk("Unexpected error during initialization",e)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{let{data:n,error:i}=await rs(this.fetch,"POST","".concat(this.url,"/signup"),{headers:this.headers,body:{data:null!=(r=null==(t=null==e?void 0:e.options)?void 0:t.data)?r:{},gotrue_meta_security:{captcha_token:null==(s=null==e?void 0:e.options)?void 0:s.captchaToken}},xform:ri});if(i||!n)return this._returnResult({data:{user:null,session:null},error:i});let a=n.session,o=n.user;return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",a)),this._returnResult({data:{user:o,session:a},error:null})}catch(e){if(tv(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signUp(e){var t,r,s;try{let n;if("email"in e){let{email:r,password:s,options:i}=e,a=null,o=null;"pkce"===this.flowType&&([a,o]=await t3(this.storage,this.storageKey)),n=await rs(this.fetch,"POST","".concat(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)?t:{},gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:a,code_challenge_method:o},xform:ri})}else if("phone"in e){let{phone:t,password:i,options:a}=e;n=await rs(this.fetch,"POST","".concat(this.url,"/signup"),{headers:this.headers,body:{phone:t,password:i,data:null!=(r=null==a?void 0:a.data)?r:{},channel:null!=(s=null==a?void 0:a.channel)?s:"sms",gotrue_meta_security:{captcha_token:null==a?void 0:a.captchaToken}},xform:ri})}else throw new tR("You must provide either an email or phone number and a password");let{data:i,error:a}=n;if(a||!i)return await t$(this.storage,"".concat(this.storageKey,"-code-verifier")),this._returnResult({data:{user:null,session:null},error:a});let 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(e){if(await t$(this.storage,"".concat(this.storageKey,"-code-verifier")),tv(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithPassword(e){try{let t;if("email"in e){let{email:r,password:s,options:n}=e;t=await rs(this.fetch,"POST","".concat(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:ra})}else if("phone"in e){let{phone:r,password:s,options:n}=e;t=await rs(this.fetch,"POST","".concat(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:ra})}else throw new tR("You must provide either an email or phone number and a password");let{data:r,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){let e=new tA;return this._returnResult({data:{user:null,session:null},error:e})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(e){if(tv(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOAuth(e){var t,r,s,n;return await this._handleProviderSignIn(e.provider,{redirectTo:null==(t=e.options)?void 0:t.redirectTo,scopes:null==(r=e.options)?void 0:r.scopes,queryParams:null==(s=e.options)?void 0:s.queryParams,skipBrowserRedirect:null==(n=e.options)?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){let{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw Error('@supabase/auth-js: Unsupported chain "'.concat(t,'"'))}}async signInWithEthereum(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{let h,{chain:u,wallet:g,statement:m,options:y}=e;if(tF())if("object"==typeof g)h=g;else{let e=window;if("ethereum"in e&&"object"==typeof e.ethereum&&"request"in e.ethereum&&"function"==typeof e.ethereum.request)h=e.ethereum;else throw Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if("object"!=typeof g||!(null==y?void 0:y.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");h=g}let w=new URL(null!=(t=null==y?void 0:y.url)?t:window.location.href),b=await h.request({method:"eth_requestAccounts"}).then(e=>e).catch(()=>{throw Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!b||0===b.length)throw Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let v=rg(b[0]),_=null==(r=null==y?void 0:y.signInWithEthereum)?void 0:r.chainId;_||(_=parseInt(await h.request({method:"eth_chainId"}),16)),p=function(e){var t;let{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 Error('@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: '.concat(r));if(!s)throw Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw Error('@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: '.concat(a));if(!u)throw Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if("1"!==d)throw Error("@supabase/auth-js: Invalid SIWE message field \"version\". Version must be '1'. Provided value: ".concat(d));if(null==(t=e.statement)?void 0:t.includes("\n"))throw Error("@supabase/auth-js: Invalid SIWE message field \"statement\". Statement must not include '\\n'. Provided value: ".concat(e.statement));let p=rg(e.address),f=h?"".concat(h,"://").concat(s):s,g=e.statement?"".concat(e.statement,"\n"):"",m="".concat(f," wants you to sign in with your Ethereum account:\n").concat(p,"\n\n").concat(g),y="URI: ".concat(u,"\nVersion: ").concat(d,"\nChain ID: ").concat(r).concat(a?"\nNonce: ".concat(a):"","\nIssued At: ").concat(i.toISOString());if(n&&(y+="\nExpiration Time: ".concat(n.toISOString())),o&&(y+="\nNot Before: ".concat(o.toISOString())),l&&(y+="\nRequest ID: ".concat(l)),c){let e="\nResources:";for(let t of c){if(!t||"string"!=typeof t)throw Error('@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: '.concat(t));e+="\n- ".concat(t)}y+=e}return"".concat(m,"\n").concat(y)}({domain:w.host,address:v,statement:m,uri:w.href,version:"1",chainId:_,nonce:null==(s=null==y?void 0:y.signInWithEthereum)?void 0:s.nonce,issuedAt:null!=(i=null==(n=null==y?void 0:y.signInWithEthereum)?void 0:n.issuedAt)?i:new Date,expirationTime:null==(a=null==y?void 0:y.signInWithEthereum)?void 0:a.expirationTime,notBefore:null==(o=null==y?void 0:y.signInWithEthereum)?void 0:o.notBefore,requestId:null==(l=null==y?void 0:y.signInWithEthereum)?void 0:l.requestId,resources:null==(c=null==y?void 0:y.signInWithEthereum)?void 0:c.resources}),f=await h.request({method:"personal_sign",params:[(d=p,"0x"+Array.from(new TextEncoder().encode(d),e=>e.toString(16).padStart(2,"0")).join("")),v]})}try{let{data:t,error:r}=await rs(this.fetch,"POST","".concat(this.url,"/token?grant_type=web3"),{headers:this.headers,body:Object.assign({chain:"ethereum",message:p,signature:f},(null==(h=e.options)?void 0:h.captchaToken)?{gotrue_meta_security:{captcha_token:null==(u=e.options)?void 0:u.captchaToken}}:null),xform:ri});if(r)throw r;if(!t||!t.session||!t.user){let e=new tA;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(e){if(tv(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}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{let u,{chain:d,wallet:g,statement:m,options:y}=e;if(tF())if("object"==typeof g)u=g;else{let e=window;if("solana"in e&&"object"==typeof e.solana&&("signIn"in e.solana&&"function"==typeof e.solana.signIn||"sign
1Message"in e.solana&&"function"==typeof e.solana.signMessage))u=e.solana;else throw Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if("object"!=typeof g||!(null==y?void 0:y.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");u=g}let w=new URL(null!=(t=null==y?void 0:y.url)?t:window.location.href);if("signIn"in u&&u.signIn){let e,t=await u.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}),m?{statement:m}:null));if(Array.isArray(t)&&t[0]&&"object"==typeof t[0])e=t[0];else if(t&&"object"==typeof t&&"signedMessage"in t&&"signature"in t)e=t;else throw Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in e&&"signature"in e&&("string"==typeof e.signedMessage||e.signedMessage instanceof Uint8Array)&&e.signature instanceof Uint8Array)p="string"==typeof e.signedMessage?e.signedMessage:new TextDecoder().decode(e.signedMessage),f=e.signature;else throw Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in u)||"function"!=typeof u.signMessage||!("publicKey"in u)||"object"!=typeof u||!u.publicKey||!("toBase58"in u.publicKey)||"function"!=typeof u.publicKey.toBase58)throw Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=["".concat(w.host," wants you to sign in with your Solana account:"),u.publicKey.toBase58(),...m?["",m,""]:[""],"Version: 1","URI: ".concat(w.href),"Issued At: ".concat(null!=(s=null==(r=null==y?void 0:y.signInWithSolana)?void 0:r.issuedAt)?s:new Date().toISOString()),...(null==(n=null==y?void 0:y.signInWithSolana)?void 0:n.notBefore)?["Not Before: ".concat(y.signInWithSolana.notBefore)]:[],...(null==(i=null==y?void 0:y.signInWithSolana)?void 0:i.expirationTime)?["Expiration Time: ".concat(y.signInWithSolana.expirationTime)]:[],...(null==(a=null==y?void 0:y.signInWithSolana)?void 0:a.chainId)?["Chain ID: ".concat(y.signInWithSolana.chainId)]:[],...(null==(o=null==y?void 0:y.signInWithSolana)?void 0:o.nonce)?["Nonce: ".concat(y.signInWithSolana.nonce)]:[],...(null==(l=null==y?void 0:y.signInWithSolana)?void 0:l.requestId)?["Request ID: ".concat(y.signInWithSolana.requestId)]:[],...(null==(h=null==(c=null==y?void 0:y.signInWithSolana)?void 0:c.resources)?void 0:h.length)?["Resources",...y.signInWithSolana.resources.map(e=>"- ".concat(e))]:[]].join("\n");let e=await u.signMessage(new TextEncoder().encode(p),"utf8");if(!e||!(e instanceof Uint8Array))throw Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");f=e}}try{let{data:t,error:r}=await rs(this.fetch,"POST","".concat(this.url,"/token?grant_type=web3"),{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:tK(f)},(null==(u=e.options)?void 0:u.captchaToken)?{gotrue_meta_security:{captcha_token:null==(d=e.options)?void 0:d.captchaToken}}:null),xform:ri});if(r)throw r;if(!t||!t.session||!t.user){let e=new tA;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(e){if(tv(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e){let t=await tY(this.storage,"".concat(this.storageKey,"-code-verifier")),[r,s]=(null!=t?t:"").split("/");try{if(!r&&"pkce"===this.flowType)throw new tP;let{data:t,error:n}=await rs(this.fetch,"POST","".concat(this.url,"/token?grant_type=pkce"),{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:ri});if(await t$(this.storage,"".concat(this.storageKey,"-code-verifier")),n)throw n;if(!t||!t.session||!t.user){let e=new tA;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(e){if(await t$(this.storage,"".concat(this.storageKey,"-code-verifier")),tv(e))return this._returnResult({data:{user:null,session:null,redirectType:null},error:e});throw e}}async signInWithIdToken(e){try{let{options:t,provider:r,token:s,access_token:n,nonce:i}=e,{data:a,error:o}=await rs(this.fetch,"POST","".concat(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:ri});if(o)return this._returnResult({data:{user:null,session:null},error:o});if(!a||!a.session||!a.user){let e=new tA;return this._returnResult({data:{user:null,session:null},error:e})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),this._returnResult({data:a,error:o})}catch(e){if(tv(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOtp(e){var t,r,s,n,i;try{if("email"in e){let{email:s,options:n}=e,i=null,a=null;"pkce"===this.flowType&&([i,a]=await t3(this.storage,this.storageKey));let{error:o}=await rs(this.fetch,"POST","".concat(this.url,"/otp"),{headers:this.headers,body:{email:s,data:null!=(t=null==n?void 0:n.data)?t:{},create_user:null==(r=null==n?void 0:n.shouldCreateUser)||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){let{phone:t,options:r}=e,{data:a,error:o}=await rs(this.fetch,"POST","".concat(this.url,"/otp"),{headers:this.headers,body:{phone:t,data:null!=(s=null==r?void 0:r.data)?s:{},create_user:null==(n=null==r?void 0:r.shouldCreateUser)||n,gotrue_meta_security:{captcha_token:null==r?void 0:r.captchaToken},channel:null!=(i=null==r?void 0:r.channel)?i:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:null==a?void 0:a.message_id},error:o})}throw new tR("You must provide either an email or phone number.")}catch(e){if(await t$(this.storage,"".concat(this.storageKey,"-code-verifier")),tv(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async verifyOtp(e){var t,r;try{let s,n;"options"in e&&(s=null==(t=e.options)?void 0:t.redirectTo,n=null==(r=e.options)?void 0:r.captchaToken);let{data:i,error:a}=await rs(this.fetch,"POST","".concat(this.url,"/verify"),{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:s,xform:ri});if(a)throw a;if(!i)throw Error("An error occurred on token verification.");let 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(e){if(tv(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSSO(e){var t,r,s,n,i;try{let a=null,o=null;"pkce"===this.flowType&&([a,o]=await t3(this.storage,this.storageKey));let l=await rs(this.fetch,"POST","".concat(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.redirectTo)?r:void 0}),(null==(s=null==e?void 0:e.options)?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:rl});
1return(null==(n=l.data)?void 0:n.url)&&tF()&&!(null==(i=e.options)?void 0:i.skipBrowserRedirect)&&window.location.assign(l.data.url),this._returnResult(l)}catch(e){if(await t$(this.storage,"".concat(this.storageKey,"-code-verifier")),tv(e))return this._returnResult({data:null,error:e});throw e}}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=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new tE;let{error:s}=await rs(this.fetch,"GET","".concat(this.url,"/reauthenticate"),{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(tv(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let t="".concat(this.url,"/resend");if("email"in e){let{email:r,type:s,options:n}=e,i=null,a=null;"pkce"===this.flowType&&([i,a]=await t3(this.storage,this.storageKey));let{error:o}=await rs(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 t$(this.storage,"".concat(this.storageKey,"-code-verifier")),this._returnResult({data:{user:null,session:null},error:o})}if("phone"in e){let{phone:r,type:s,options:n}=e,{data:i,error:a}=await rs(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 tR("You must provide either an email or phone number and a type")}catch(e){if(await t$(this.storage,"".concat(this.storageKey,"-code-verifier")),tv(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}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){let e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch(e){}})()),r}return await this.lock("lock:".concat(this.storageKey),e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(e){}})()),await e;this.pendingInLock.length;){let e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),null==this.lock||this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",Error().stack);try{let t=null,r=await tY(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),null!==r&&(this._isValidSession(r)?t=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!t)return{data:{session:null},error:null};let s=!!t.expires_at&&1e3*t.expires_at-Date.now()<9e4;if(this._debug("#__loadSession()","session has".concat(s?"":" not"," expired"),"expires_at",t.expires_at),!s){if(this.userStorage){let e=await tY(this.userStorage,this.storageKey+"-user");(null==e?void 0:e.user)?t.user=e.user:t.user=t9()}if(this.storage.isServer&&t.user&&!t.user.__isUserNotAvailableProxy){var e;let r={value:this.suppressGetSessionWarning};t.user=(e=t.user,new Proxy(e,{get:(e,t,s)=>{if("__isInsecureUserWarningProxy"===t)return!0;
1if("symbol"==typeof t){let r=t.toString();if("Symbol(Symbol.toPrimitive)"===r||"Symbol(Symbol.toStringTag)"===r||"Symbol(util.inspect.custom)"===r||"Symbol(nodejs.util.inspect.custom)"===r)return Reflect.get(e,t,s)}return r.value||"string"!=typeof t||(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),r.value=!0),Reflect.get(e,t,s)}})),r.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:t},error:null}}let{data:n,error:i}=await this._callRefreshToken(t.refresh_token);if(i)return this._returnResult({data:{session:null},error:i});return this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){let t;return e?await this._getUser(e):(await this.initializePromise,(t=null!=this.lock?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):await this._getUser()).data.user&&(this.suppressGetSessionWarning=!0),t)}async _getUser(e){try{if(e)return await rs(this.fetch,"GET","".concat(this.url,"/user"),{headers:this.headers,jwt:e,xform:ro});return await this._useSession(async e=>{var t,r,s;let{data:n,error:i}=e;if(i)throw i;return(null==(t=n.session)?void 0:t.access_token)||this.hasCustomAuthorizationHeader?await rs(this.fetch,"GET","".concat(this.url,"/user"),{headers:this.headers,jwt:null!=(s=null==(r=n.session)?void 0:r.access_token)?s:void 0,xform:ro}):{data:{user:null},error:new tE}})}catch(e){if(tv(e))return tT(e)&&(await this._removeSession(),await t$(this.storage,"".concat(this.storageKey,"-code-verifier"))),this._returnResult({data:{user:null},error:e});throw e}}async updateUser(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};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){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};try{return await this._useSession(async r=>{let{data:s,error:n}=r;if(n)throw n;if(!s.session)throw new tE;let i=s.session,a=null,o=null;"pkce"===this.flowType&&null!=e.email&&([a,o]=await t3(this.storage,this.storageKey));let{data:l,error:c}=await rs(this.fetch,"PUT","".concat(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:ro});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(e){if(await t$(this.storage,"".concat(this.storageKey,"-code-verifier")),tv(e))return this._returnResult({data:{user:null},error:e});throw e}}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 tE;let t=Date.now()/1e3,r=t,s=!0,n=null,{payload:i}=tQ(e.access_token);if(i.exp&&(s=(r=i.exp)<=t),s){let{data:t,error:r}=await this._callRefreshToken(e.refresh_token);if(r)return this._returnResult({data:{user:null,session:null},error:r});if(!t)return{data:{user:null,session:null},error:null};n=t}else{let{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(e){if(tv(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}}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){let{data:s,error:n}=t;if(n)throw n;e=null!=(r=s.session)?r:void 0}if(!(null==e?void 0:e.refresh_token))throw new tE;let{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(e){if(tv(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){var r;try{if(!tF())throw new tO("No browser detected.");
1if(e.error||e.error_description||e.error_code)throw new tO(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 tC("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new tO("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new tC("No code detected.");let{data:t,error:s}=await this._exchangeCodeForSession(e.code);if(s)throw s;let 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)?r:null},error:null}}let{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 tO("No session defined in URL");let h=Math.round(Date.now()/1e3),u=parseInt(o),d=h+u;l&&(d=parseInt(l));let p=d-h;1e3*p<=3e4&&console.warn("@supabase/gotrue-js: Session as retrieved from URL expires in ".concat(p,"s, should have been closer to ").concat(u,"s"));let f=d-u;h-f>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",f,d,h):h-f<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",f,d,h);let{data:g,error:m}=await this._getUser(i);if(m)throw m;let y={provider_token:s,provider_refresh_token:n,access_token:i,expires_in:u,expires_at:d,refresh_token:a,token_type:c,user:g.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:y,redirectType:e.type},error:null})}catch(e){if(tv(e))return this._returnResult({data:{session:null,redirectType:null},error:e});throw e}}_isImplicitGrantCallback(e){return"function"==typeof this.detectSessionInUrl?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error||e.error_description||e.error_code)}async _isPKCECallback(e){let t=await tY(this.storage,"".concat(this.storageKey,"-code-verifier"));return!!(e.code&&t)}async signOut(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{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(){let{scope:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{scope:"global"};return await this._useSession(async t=>{var r;let{data:s,error:n}=t;if(n&&!tT(n))return this._returnResult({error:n});let i=null==(r=s.session)?void 0:r.access_token;if(i){let{error:t}=await this.admin.signOut(i,e);if(t&&!(tv(t)&&"AuthApiError"===t.name&&(404===t.status||401===t.status||403===t.status)||tT(t)))return this._returnResult({error:t})}return"others"!==e&&(await this._removeSession(),await t$(this.storage,"".concat(this.storageKey,"-code-verifier"))),this._returnResult({error:null})})}onAuthStateChange(e){let t=Symbol("auth-callback"),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>{await this.initializePromise,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{let{data:{session:s},error:n}=t;if(n)throw n;await (null==(r=this.stateChangeEmitters.get(e))?void 0:r.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(t){await (null==(s=this.stateChangeEmitters.get(e))?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",t),tT(t)?console.warn(t):console.error(t)}})}async resetPasswordForEmail(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=null,s=null;"pkce"===this.flowType&&([r,s]=await t3(this.storage,this.storageKey,!0));try{return await rs(this.fetch,"POST","".concat(this.url,"/recover"),{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(e){if(await t$(this.storage,"".concat(this.storageKey,"-code-verifier")),tv(e))return this._returnResult({data:null,error:e});throw e}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:null!=(e=t.user.identities)?e:[]},error:null})}catch(e){if(tv(e))return this._returnResult({data:null,error:e});throw e}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{let{data:r,error:s}=await this._useSession(async t=>{var r,s,n,i,a;let{data:o,error:l}=t;if(l)throw l;let c=await this._getUrlForProvider("".concat(this.url,"/user/identities/authorize"),e.provider,{redirectTo:null==(r=e.options)?void 0:r.redirectTo,scopes:null==(s=e.options)?void 0:s.scopes,queryParams:null==(n=e.options)?void 0:n.queryParams,skipBrowserRedirect:!0});return await rs(this.fetch,"GET",c,{headers:this.headers,jwt:null!=(a=null==(i=o.session)?void 0:i.access_token)?a:void 0})});if(s)throw s;return!tF()||(null==(t=e.options)?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(t){if(tv(t))return this._returnResult({data:{provider:e.provider,url:null},error:t});throw t}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{let{error:s,data:{session:n}}=t;if(s)throw s;let{options:i,provider:a,token:o,access_token:l,nonce:c}=e,{data:h,error:u}=await rs(this.fetch,"POST","".concat(this.url,"/token?grant_type=id_token"),{headers:this.headers,jwt:null!=(r=null==n?void 0:n.access_token)?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:ri});if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!h||!h.session||!h.user)return this._returnResult({data:{user:null,session:null},error:new tA});return h.session&&(await this._saveSession(h.session),await this._notifyAllSubscribers("USER_UPDATED",h.session)),this._returnResult({data:h,error:u})}catch(e){if(await t$(this.storage,"".concat(this.storageKey,"-code-verifier")),tv(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;let{data:n,error:i}=t;if(i)throw i;
1return await rs(this.fetch,"DELETE","".concat(this.url,"/user/identities/").concat(e.identity_id),{headers:this.headers,jwt:null!=(s=null==(r=n.session)?void 0:r.access_token)?s:void 0})})}catch(e){if(tv(e))return this._returnResult({data:null,error:e});throw e}}async _refreshAccessToken(e){let t="#_refreshAccessToken()";this._debug(t,"begin");try{var r,s;let n=Date.now();return await (r=async r=>(r>0&&await tZ(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await rs(this.fetch,"POST","".concat(this.url,"/token?grant_type=refresh_token"),{body:{refresh_token:e},headers:this.headers,xform:ri})),s=(e,t)=>{let r=200*Math.pow(2,e);return t&&tI(t)&&Date.now()+r-n<3e4},new Promise((e,t)=>{(async()=>{for(let n=0;n<1/0;n++)try{let t=await r(n);if(!s(n,null,t))return void e(t)}catch(e){if(!s(n,e))return void t(e)}})()}))}catch(e){if(this._debug(t,"error",e),tv(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}finally{this._debug(t,"end")}}_isValidSession(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let r=await this._getUrlForProvider("".concat(this.url,"/authorize"),e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),tF()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e,t;let r="#_recoverAndRefresh()";this._debug(r,"begin");try{let s=await tY(this.storage,this.storageKey);if(s&&this.userStorage){let t=await tY(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!t&&(t={user:s.user},await tV(this.userStorage,this.storageKey+"-user",t)),s.user=null!=(e=null==t?void 0:t.user)?e:t9()}else if(s&&!s.user&&!s.user){let e=await tY(this.storage,this.storageKey+"-user");e&&(null==e?void 0:e.user)?(s.user=e.user,await t$(this.storage,this.storageKey+"-user"),await tV(this.storage,this.storageKey,s)):s.user=t9()}if(this._debug(r,"session from storage",s),!this._isValidSession(s)){this._debug(r,"session is not valid"),null!==s&&await this._removeSession();return}let n=(null!=(t=s.expires_at)?t:1/0)*1e3-Date.now()<9e4;if(this._debug(r,"session has".concat(n?"":" not"," expired with margin of ").concat(9e4,"s")),n){if(this.autoRefreshToken&&s.refresh_token){let{error:e}=await this._callRefreshToken(s.refresh_token);e&&(tv(e)&&"AuthRefreshDiscardedError"===e.name?this._debug(r,"refresh discarded by commit guard",e):(this._debug(r,"refresh failed",e),tI(e)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",e),await this._removeSession())))}}else if(s.user&&!0===s.user.__isUserNotAvailableProxy)try{let{data:e,error:t}=await this._getUser(s.access_token);!t&&(null==e?void 0:e.user)?(s.user=e.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(e){console.error("Error getting user data:",e),this._debug(r,"error getting user data, skipping SIGNED_IN notification",e)}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(e){this._debug(r,"error",e),console.error(e);return}finally{this._debug(r,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new tE;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s="#_callRefreshToken()";this._debug(s,"begin");try{this.refreshingDeferred=new tX;let t=await tY(this.storage,this.storageKey),{data:r,error:n}=await this._refreshAccessToken(e);if(n)throw n;if(!r.session)throw new tE;let i=await tY(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"});let e={data:null,error:new tx};return this.refreshingDeferred.resolve(e),e}let a=this._sessionRemovalEpoch;if(await this._saveSession(r.session),this._sessionRemovalEpoch!==a){this._debug(s,"commit guard (post-save): _removeSession ran during _saveSession, und
1oing write"),await t$(this.storage,this.storageKey),this.userStorage&&await t$(this.userStorage,this.storageKey+"-user");let e={data:null,error:new tx};return this.refreshingDeferred.resolve(e),e}await this._notifyAllSubscribers("TOKEN_REFRESHED",r.session);let o={data:r.session,error:null};return this.refreshingDeferred.resolve(o),o}catch(e){if(this._debug(s,"error",e),tv(e)){let r={data:null,error:e};return tI(e)||await this._removeSession(),null==(t=this.refreshingDeferred)||t.resolve(r),r}throw null==(r=this.refreshingDeferred)||r.reject(e),e}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t){let r=!(arguments.length>2)||void 0===arguments[2]||arguments[2],s="#_notifyAllSubscribers(".concat(e,")");this._debug(s,"begin",t,"broadcast = ".concat(r));try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let s=[],n=Array.from(this.stateChangeEmitters.values()).map(async r=>{try{await r.callback(e,t)}catch(e){s.push(e)}});if(await Promise.all(n),s.length>0){for(let e=0;e<s.length;e+=1)console.error(s[e]);throw s[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await t$(this.storage,"".concat(this.storageKey,"-code-verifier"));let t=Object.assign({},e),r=t.user&&!0===t.user.__isUserNotAvailableProxy;if(this.userStorage){!r&&t.user&&await tV(this.userStorage,this.storageKey+"-user",{user:t.user});let e=Object.assign({},t);delete e.user;let s=t7(e);await tV(this.storage,this.storageKey,s)}else{let e=t7(t);await tV(this.storage,this.storageKey,e)}}async _removeSession(){this._sessionRemovalEpoch+=1,this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await t$(this.storage,this.storageKey),await t$(this.storage,this.storageKey+"-code-verifier"),await t$(this.storage,this.storageKey+"-user"),this.userStorage&&await t$(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&tF()&&(null==window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(e){console.error("removing visibilitychange callback failed",e)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),3e4);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"u">typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&"object"==typeof t&&"function"==typeof t.unref?t.unref():"u">typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),null==(e=this.broadcastChannel)||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),null!=this.lock){try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");let s=Math.floor((1e3*r.expires_at-e)/3e4);this._debug("#_autoRefreshTokenTick()","access token expires in ".concat(s," ticks, a tick lasts ").concat(3e4,"ms, refresh threshold is ").concat(3," ticks")),s<=3&&await this._callRefreshToken(r.refresh_token)})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof rf)this._debug("auto refresh token tick lock not available");else throw e}return}if(null!==this.refreshingDeferred)return void this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");try{let e=Date.now();try{await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");let s=Math.floor((1e3*r.expires_at-e)/3e4);this._debug("#_autoRefreshTokenTick()","access token expires in ".concat(s," ticks, a tick lasts ").concat(3e4,"ms, refresh threshold is ").concat(3," ticks")),s<=3&&await this._callRefreshToken(r.refresh_token)})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!tF()||!(null==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||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t="#_onVisibilityChanged(".concat(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?this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting"):await this._recoverAndRefresh()});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){let s=["provider=".concat(encodeURIComponent(t))];if((null==r?void 0:r.redirectTo)&&s.push("redirect_to=".concat(encodeURIComponent(r.redirectTo))),(null==r?void 0:r.scopes)&&s.push("scopes=".concat(encodeURIComponent(r.scopes))),"pkce"===this.flowType){let[e,t]=await t3(this.storage,this.storageKey),r=new
1URLSearchParams({code_challenge:"".concat(encodeURIComponent(e)),code_challenge_method:"".concat(encodeURIComponent(t))});s.push(r.toString())}if(null==r?void 0:r.queryParams){let e=new URLSearchParams(r.queryParams);s.push(e.toString())}return(null==r?void 0:r.skipBrowserRedirect)&&s.push("skip_http_redirect=".concat(r.skipBrowserRedirect)),"".concat(e,"?").concat(s.join("&"))}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:s,error:n}=t;return n?this._returnResult({data:null,error:n}):await rs(this.fetch,"DELETE","".concat(this.url,"/factors/").concat(e.factorId),{headers:this.headers,jwt:null==(r=null==s?void 0:s.session)?void 0:r.access_token})})}catch(e){if(tv(e))return this._returnResult({data:null,error:e});throw e}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;let{data:n,error:i}=t;if(i)return this._returnResult({data:null,error:i});let a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:"totp"===e.factorType?{issuer:e.issuer}:{}),{data:o,error:l}=await rs(this.fetch,"POST","".concat(this.url,"/factors"),{body:a,headers:this.headers,jwt:null==(r=null==n?void 0:n.session)?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.qr_code)&&(o.totp.qr_code="data:image/svg+xml;utf-8,".concat(o.totp.qr_code)),this._returnResult({data:o,error:null}))})}catch(e){if(tv(e))return this._returnResult({data:null,error:e});throw e}}async _verify(e){let t=async()=>{try{return await this._useSession(async t=>{var r;let{data:s,error:n}=t;if(n)return this._returnResult({data:null,error:n});let i=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:"create"===e.webauthn.type?r_(e.webauthn.credential_response):rk(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:o}=await rs(this.fetch,"POST","".concat(this.url,"/factors/").concat(e.factorId,"/verify"),{body:i,headers:this.headers,jwt:null==(r=null==s?void 0:s.session)?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(e){if(tv(e))return this._returnResult({data:null,error:e});throw e}};return null!=this.lock?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challenge(e){let t=async()=>{try{return await this._useSession(async t=>{var r;let{data:s,error:n}=t;if(n)return this._returnResult({data:null,error:n});let i=await rs(this.fetch,"POST","".concat(this.url,"/factors/").concat(e.factorId,"/challenge"),{body:e,headers:this.headers,jwt:null==(r=null==s?void 0:s.session)?void 0:r.access_token});if(i.error)return i;let{data:a}=i;if("webauthn"!==a.type)return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:rb(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({}
1,a.webauthn.credential_options),{publicKey:rv(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(e){if(tv(e))return this._returnResult({data:null,error:e});throw e}};return null!=this.lock?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;let{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};let s={all:[],phone:[],totp:[],webauthn:[]};for(let r of null!=(e=null==t?void 0:t.factors)?e:[])s.all.push(r),"verified"===r.status&&s[r.factor_type].push(r);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,r,s,n;if(e)try{let{payload:s}=tQ(e),n=null;s.aal&&(n=s.aal);let i=n,{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.filter(e=>"verified"===e.status))?r:[]).length>0&&(i="aal2");let l=s.amr||[];return{data:{currentLevel:n,nextLevel:i,currentAuthenticationMethods:l},error:null}}catch(e){if(tv(e))return this._returnResult({data:null,error:e});throw e}let{data:{session:i},error:a}
1=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:o}=tQ(i.access_token),l=null;o.aal&&(l=o.aal);let c=l;return(null!=(n=null==(s=i.user.factors)?void 0:s.filter(e=>"verified"===e.status))?n:[]).length>0&&(c="aal2"),{data:{currentLevel:l,nextLevel:c,currentAuthenticationMethods:o.amr||[]},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await rs(this.fetch,"GET","".concat(this.url,"/oauth/authorizations/").concat(e),{headers:this.headers,jwt:r.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new tE})})}catch(e){if(tv(e))return this._returnResult({data:null,error:e});throw e}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new tE});let i=await rs(this.fetch,"POST","".concat(this.url,"/oauth/authorizations/").concat(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&&tF()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(i.data.redirect_url),i})}catch(e){if(tv(e))return this._returnResult({data:null,error:e});throw e}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new tE});let i=await rs(this.fetch,"POST","".concat(this.url,"/oauth/authorizations/").concat(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&&tF()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(i.data.redirect_url),i})}catch(e){if(tv(e))return this._returnResult({data:null,error:e});throw e}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await rs(this.fetch,"GET","".concat(this.url,"/user/oauth/grants"),{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new tE})})}catch(e){if(tv(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?(await rs(this.fetch,"DELETE","".concat(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 tE})})}catch(e){if(tv(e))return this._returnResult({data:null,error:e});throw e}}async fetchJwk(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{keys:[]},r=t.keys.find(t=>t.kid===e);if(r)return r;let s=Date.now();if((r=this.jwks.keys.find(t=>t.kid===e))&&this.jwks_cached_at+6e5>s)return r;let{data:n,error:i}=await rs(this.fetch,"GET","".concat(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}async getClaims(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};try{let n,i=e;if(!i){let{data:e,error:t}
1=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});i=e.session.access_token}let{header:a,payload:o,signature:l,raw:{header:c,payload:h}}=tQ(i);if(!(null==t?void 0:t.allowExpired))try{var r,s=o.exp;if(!s)throw Error("Missing exp claim");if(s<=Math.floor(Date.now()/1e3))throw Error("JWT has expired")}catch(e){throw new tU(e instanceof Error?e.message:"JWT validation failed")}let u=!a.alg||a.alg.startsWith("HS")||!a.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(a.kid,(null==t?void 0:t.keys)?{keys:t.keys}:null==t?void 0:t.jwks);if(!u){let{error:e}=await this.getUser(i);if(e)throw e;return{data:{claims:o,header:a,signature:l},error:null}}let d=function(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw Error("Invalid alg claim")}}(a.alg),p=await crypto.subtle.importKey("jwk",u,d,!0,["verify"]);if(!await crypto.subtle.verify(d,p,l,(r="".concat(c,".").concat(h),n=[],!function(e,t){for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);if(s>55295&&s<=56319){let t=(s-55296)*1024&65535;s=(e.charCodeAt(r+1)-56320&65535|t)+65536,r+=1}!function(e,t){if(e<=127)return t(e);if(e<=2047){t(192|e>>6),t(128|63&e);return}if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|63&e);return}if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|63&e);return}throw Error("Unrecognized Unicode codepoint: ".concat(e.toString(16)))}(s,t)}}(r,e=>n.push(e)),new Uint8Array(n))))throw new tU("Invalid JWT signature");return{data:{claims:o,header:a,signature:l},error:null}}catch(e){if(tv(e))return this._returnResult({data:null,error:e});throw e}}async signInWithPasskey(e){var t,r,s;t6(this.experimental);try{if(!rE())return this._returnResult({data:null,error:new tk("Browser does not support WebAuthn",null)});let{data:n,error:i}=await this._startPasskeyAuthentication({options:{captchaToken:null==(t=null==e?void 0:e.options)?void 0:t.captchaToken}});if(i||!n)return this._returnResult({data:null,error:i});let a=rv(n.options),o=null!=(s=null==(r=null==e?void 0:e.options)?void 0:r.signal)?s:rw.createNewAbortSignal(),{data:l,error:c}=await rA({publicKey:a,signal:o});if(c||!l)return this._returnResult({data:null,error:null!=c?c:new tk("WebAuthn ceremony failed",null)});let h=rk(l);return this._verifyPasskeyAuthentication({challengeId:n.challenge_id,credential:h})}catch(e){if(tv(e))return this._returnResult({data:null,error:e});throw e}}async registerPasskey(e){var t,r;t6(this.experimental);try{if(!rE())return this._returnResult({data:null,error:new tk("Browser does not support WebAuthn",null)});let{data:s,error:n}=await this._startPasskeyRegistration();if(n||!s)return this._returnResult({data:null,error:n});let i=rb(s.options),a=null!=(r=null==(t=null==e?void 0:e.options)?void 0:t.signal)?r:rw.createNewAbortSignal(),{data:o,error:l}=await rT({publicKey:i,signal:a});if(l||!o)return this._returnResult({data:null,error:null!=l?l:new tk("WebAuthn ceremony failed",null)});let c=r_(o);return this._verifyPasskeyRegistration({challengeId:s.challenge_id,credential:c})}catch(e){if(tv(e))return this._returnResult({data:null,error:e});throw e}}async _startPasskeyRegistration(){t6(this.experimental);try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new tE});let{data:s,error:n}=await rs(this.fetch,"POST","".concat(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(tv(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){t6(this.experimental);try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new tE});let{data:n,error:i}=await rs(this.fetch,"POST","".concat(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(e){if(tv(e))return this._returnResult({data:null,error:e});throw e}}async _startPasskeyAuthentication(e){var t;t6(this.experimental);try{let{data:r,error:s}=await rs(this.fetch,"POST","".concat(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.captchaToken}}});if(s)return this._returnResult({data:null,error:s});return this._returnResult({data:r,error:null})}catch(e){if(tv(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyAuthentication(e){t6(this.experimental);try{let{data:t,error:r}=await rs(this.fetch,"POST","".concat(this.url,"/passkeys/authentication/verify"),{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:ri});if(r)return this._returnResult({data:null,error:r});return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:t,error:null})}catch(e){if(tv(e))return this._returnResult({data:null,error:e});throw e}}async _listPasskeys(){t6(this.experimental);try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new tE});let{data:s,error:n}=await rs(this.fetch,"GET","".concat(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(tv(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){t6(this.experimental);try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new tE});let{data:n,error:i}=await rs(this.fetch,"PATCH","".concat(this.url,"/passkeys/").concat(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(e){if(tv(e))return this._returnResult({data:null,error:e});throw e}}async _deletePasskey(e){t6(this.experimental);try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new tE});let{error:n}
1=await rs(this.fetch,"DELETE","".concat(this.url,"/passkeys/").concat(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(e){if(tv(e))return this._returnResult({data:null,error:e});throw 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._sessionRemovalEpoch=0,this.initializePromise=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({},rj),e);if(this.storageKey=n.storageKey,this.instanceID=null!=(t=rx.nextInstanceID[this.storageKey])?t:0,rx.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!n.debug,"function"==typeof n.debug&&(this.logger=n.debug),this.instanceID>0&&tF()){const e="".concat(this._logPrefix()," Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");console.warn(e),this.logDebugMessages&&console.trace(e)}if(this.persistSession=n.persistSession,this.autoRefreshToken=n.autoRefreshToken,this.experimental=null!=(r=n.experimental)?r:{},this.admin=new rd({url:n.url,headers:n.headers,fetch:n.fetch,experimental:this.experimental}),this.url=n.url,this.headers=n.headers,this.fetch=tG(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 rP(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:tz()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=rp(this.memoryStorage)),n.userStorage&&(this.userStorage=n.userStorage)):(this.memoryStorage={},this.storage=rp(this.memoryStorage)),tF()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",e)}null==(s=this.broadcastChannel)||s.addEventListener("message",async e=>{this._debug("received broadcast notification from other tab or client",e);try{await this._notifyAllSubscribers(e.data.event,e.data.session,!1)}catch(e){this._debug("#broadcastChannel","error",e)}})}n.skipAutoInitialize||this.initialize().catch(e=>{this._debug("#initialize()","error",e)})}}rx.nextInstanceID={};let rN=rx,rU="";"u">typeof Deno?(rU="deno",s=null==(y=Deno.version)?void 0:y.deno):"u">typeof document?rU="web":"u">typeof navigator&&"ReactNative"===navigator.product?rU="react-native":(rU="node",s=void 0!==b.default?null==(w=b.default.version)?void 0:w.replace(/^v/,""):void 0);let rL=["runtime=".concat(rU)];s&&rL.push("runtime-version=".concat(s));let rD={headers:{"X-Client-Info":"supabase-js/".concat("2.108.1","; ").concat(rL.join("; "))}},rB={schema:"public"},rq={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},rH={},rM={enabled:!1,respectSamplingDecision:!0},rW=null;function rK(e){return(rK="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 rF(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 rJ(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};
1t%2?rF(Object(r),!0).forEach(function(t){!function(e,t,r){var s;(s=function(e,t){if("object"!=rK(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=rK(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==rK(s)?s:s+"")in e)?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r}(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):rF(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}async function rz(e,t,r){if(!function(e,t){let r;if(!e||!t||0===t.length)return!1;if(e instanceof URL)r=e;else try{r=new URL(e)}catch(e){return!1}for(let e of t)try{if("string"==typeof e){if(function(e,t){if(t===e)return!0;if(t.startsWith("*.")){let r=t.slice(2);if(e.endsWith(r)&&(e===r||e.endsWith("."+r)))return!0}return!1}(r.hostname,e))return!0}else if(e instanceof RegExp){if(e.test(r.hostname))return!0}else if("function"==typeof e&&e(r))return!0}catch(e){continue}return!1}("string"==typeof e||e instanceof URL?e:e.url,t))return null;let s=await function(){var e,t,r,s;return e=this,t=void 0,r=void 0,s=function*(){try{let e=yield(null===rW&&(rW=import("@opentelemetry/api").catch(()=>null)),rW);if(!e||!e.propagation||!e.context)return null;let t={};e.propagation.inject(e.context.active(),t);let r=t.traceparent;if(!r)return null;return{traceparent:r,tracestate:t.tracestate,baggage:t.baggage}}catch(e){return null}},new(r||(r=Promise))(function(n,i){function a(e){try{l(s.next(e))}catch(e){i(e)}}function o(e){try{l(s.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?n(e.value):((t=e.value)instanceof r?t:new r(function(e){e(t)})).then(a,o)}l((s=s.apply(e,t||[])).next())})}();if(!s||!s.traceparent)return null;if(r){let e=function(e){if(!e||"string"!=typeof e)return null;let t=e.split("-");if(4!==t.length)return null;let[r,s,n,i]=t;if(2!==r.length||32!==s.length||16!==n.length||2!==i.length)return null;let a=/^[0-9a-f]+$/i;return a.test(r)&&a.test(s)&&a.test(n)&&a.test(i)&&"00000000000000000000000000000000"!==s&&"0000000000000000"!==n?{version:r,traceId:s,parentId:n,traceFlags:i,isSampled:(1&parseInt(i,16))==1}:null}(s.traceparent);if(e&&!e.isSampled)return null}return s}function rG(e){return"boolean"==typeof e?{enabled:e}:e}var rV=class extends rN{constructor(e){super(e)}},rY=class{get functions(){return new R(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){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{head:!1,get:!1,count:void 0};return this.rest.rpc(e,t,r)}channel(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{config:{}};return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e,t;if(this.accessToken)return await this.accessToken();let{data:r}=await this.auth.getSession();return null!=(e=null==(t=r.session)?void 0:t.access_token)?e:this.supabaseKey}_initSupabaseAuthClient(e,t,r){let{autoRefreshToken:s,persistSession:n,detectSessionInUrl:i,storage:a,userStorage:o,storageKey:l,flowType:c,lock:h,debug:u,throwOnError:d,experimental:p,lockAcquireTimeout:f,skipAutoInitialize:g}=e,m={Authorization:"Bearer ".concat(this.supabaseKey),apikey:"".concat(this.supabaseKey)};return new rV({url:this.authUrl.href,headers:rJ(rJ({},m),t),storageKey:l,autoRefreshToken:s,persistSession:n,detectSessionInUrl:i,storage:a,userStorage:o,flowType:c,lock:h,debug:u,throwOnError:d,experimental:p,fetch:r,lockAcquireTimeout:f,skipAutoInitialize:g,hasCustomAuthorizationHeader:Object.keys(this.headers).some(e=>"authorization"===e.toLowerCase())})}_initRealtimeClient(e){return new eU(this.realtimeUrl.href,rJ(rJ({},e),{},{params:rJ(rJ({},{apikey:this.supabaseKey}),null==e?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",null==t?void 0:t.access_token)})}_handleTokenChanged(e,t,r){("TOKEN_REFRESHED"===e||"SIGNED_IN"===e)&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):"SIGNED_OUT"===e&&(this.realtime.setAuth(),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0)}constructor(e,t,r){var s,n,i;this.supabaseUrl=e,this.supabaseKey=t;const a=function(e){let t=null==e?void 0:e.trim();if(!t)throw Error("supabaseUrl is required.");
1if(!t.match(/^https?:\/\//i))throw Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(t.endsWith("/")?t:t+"/")}catch(e){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}(e);if(!t)throw Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",a),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",a),this.storageUrl=new URL("storage/v1",a),this.functionsUrl=new URL("functions/v1",a);const o="sb-".concat(a.hostname.split(".")[0],"-auth-token"),l=function(e,t){var r,s,n,i,a,o;let{db:l,auth:c,realtime:h,global:u}=e,{db:d,auth:p,realtime:f,global:g}=t,m=rG(e.tracePropagation),y=rG(t.tracePropagation),w={db:rJ(rJ({},d),l),auth:rJ(rJ({},p),c),realtime:rJ(rJ({},f),h),storage:{},global:rJ(rJ(rJ({},g),u),{},{headers:rJ(rJ({},null!=(r=null==g?void 0:g.headers)?r:{}),null!=(s=null==u?void 0:u.headers)?s:{})}),tracePropagation:{enabled:null!=(n=null!=(i=null==m?void 0:m.enabled)?i:null==y?void 0:y.enabled)&&n,respectSamplingDecision:null==(a=null!=(o=null==m?void 0:m.respectSamplingDecision)?o:null==y?void 0:y.respectSamplingDecision)||a},accessToken:async()=>""};return e.accessToken?w.accessToken=e.accessToken:delete w.accessToken,w}(null!=r?r:{},{db:rB,realtime:rH,auth:rJ(rJ({},rq),{},{storageKey:o}),global:rD,tracePropagation:rM});this.settings=l,this.storageKey=null!=(s=l.auth.storageKey)?s:"",this.headers=null!=(n=l.global.headers)?n:{},l.accessToken?(this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw Error("@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.".concat(String(t)," is not possible"))}})):this.auth=this._initSupabaseAuthClient(null!=(i=l.auth)?i:{},this.headers,l.global.fetch),this.fetch=((e,t,r,s,n)=>{let i=s?function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return s(...t)}:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return fetch(...t)},a=Headers,o=(null==n?void 0:n.enabled)===!0,l=(null==n?void 0:n.respectSamplingDecision)!==!1,c=o?function(e){let t=[];try{let r=new URL(e);t.push(r.hostname)}catch(e){}return t.push("*.supabase.co","*.supabase.in"),t.push("localhost","127.0.0.1","[::1]"),t}(t):null;return async(t,s)=>{var n;let o=null!=(n=await r())?n:e,h=new a(null==s?void 0:s.headers);if(h.has("apikey")||h.set("apikey",e),h.has("Authorization")||h.set("Authorization","Bearer ".concat(o)),c){let e=await rz(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,rJ(rJ({},s),{},{headers:h}))}})(t,e,this._getAccessToken.bind(this),l.global.fetch,l.tracePropagation),this.realtime=this._initRealtimeClient(rJ({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(e=>this.realtime.setAuth(e)).catch(e=>console.warn("Failed to set initial Realtime auth token:",e)),this.rest=new M(new URL("rest/v1",a).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new tf(this.storageUrl.href,this.headers,this.fetch,null==r?void 0:r.storage),l.accessToken||this._listenForAuthEvents()}};(function(){if("u">typeof window)return!1;let e=globalThis.process;if(!e)return!1;let t=e.version;if(null==t)return!1;let r=t.match(/^v(\d+)\./);return!!r&&18>=parseInt(r[1],10)})()&&console.warn("â ï¸ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");var r$=e.i(462819);function rX(){return"u">typeof window&&void 0!==window.document}r$.parse,r$.serialize;let rQ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),rZ=" \n\r=".split(""),r0=(()=>{let e=Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<rZ.length;t+=1)e[rZ[t].charCodeAt(0)]=-2;for(let t=0;t<rQ.length;t+=1)e[rQ[t].charCodeAt(0)]=t;return e})();function r1(e){let t=[],r=0,s=0;if(function(e,t){for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);if(s>55295&&s<=56319){let t=(s-55296)*1024&65535;s=(e.charCodeAt(r+1)-56320&65535|t)+65536,r+=1}!function(e,t){if(e<=127)return t(e);if(e<=2047){t(192|e>>6),t(128|63&e);return}if(e<=65535){t(224|e>>12),t(128|e>>
16&63),t(128|63&e);return}if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|63&e);return}throw Error("Unrecognized Unicode codepoint: ".concat(e.toString(16)))}(s,t)}}(e,e=>{for(r=r<<8|e,s+=8;s>=6;){let e=r>>s-6&63;t.push(rQ[e]),s-=6}}),s>0)for(r<<=6-s,s=6;s>=6;){let e=r>>s-6&63;t.push(rQ[e]),s-=6}return t.join("")}function r2(e){let t=[],r=e=>{t.push(String.fromCodePoint(e))},s={utf8seq:0,codepoint:0},n=0,i=0;for(let t=0;t<e.length;t+=1){let a=r0[e.charCodeAt(t)];if(a>-1)for(n=n<<6|a,i+=6;i>=8;)(function(e,t,r){if(0===t.utf8seq){if(e<=127)return r(e);for(let r=1;r<6;r+=1)if((e>>7-r&1)==0){t.utf8seq=r;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else if(4===t.utf8seq)t.codepoint=7&e;else throw Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&r(t.codepoint)}})(n>>i-8&255,s,r),i-=8;else if(-2===a)continue;else throw Error('Invalid Base64-URL character "'.concat(e.at(t),'" at position ').concat(t))}return t.join("")}let r3={path:"/",sameSite:"lax",httpOnly:!1,maxAge:3456e4},r8=/^(.*)[.](0|[1-9][0-9]*)$/;function r5(e,t){if(e===t)return!0;let r=e.match(r8);return!!r&&r[1]===t}function r4(e,t,r){let s=null!=r?r:3180,n=encodeURIComponent(t);if(n.length<=s)return[{name:e,value:t}];let i=[];for(;n.length>0;){let e=n.slice(0,s),t=e.lastIndexOf("%");t>s-3&&(e=e.slice(0,t));let r="";for(;e.length>0;)try{r=decodeURIComponent(e);break}catch(t){if(t instanceof URIError&&"%"===e.at(-3)&&e.length>3)e=e.slice(0,e.length-3);else throw t}i.push(r),n=n.slice(e.length)}return i.map((t,r)=>({name:"".concat(e,".").concat(r),value:t}))}async function r6(e,t){let r=await t(e);if(r)return r;let s=[];for(let r=0;;r++){let n="".concat(e,".").concat(r),i=await t(n);if(!i)break;s.push(i)}return s.length>0?s.join(""):null}let r9="base64-";async function r7(e,t){var r;let{getAll:s,setAll:n,setItems:i,removedItems:a}=e,o=t.cookieEncoding,l=null!=(r=t.cookieOptions)?r:null,c=await s([...i?Object.keys(i):[],...a?Object.keys(a):[]]),h=(null==c?void 0:c.map(e=>{let{name:t}=e;return t}))||[],u=Object.keys(a).flatMap(e=>h.filter(t=>r5(t,e))),d=Object.keys(i).flatMap(e=>{let t=new Set(h.filter(t=>r5(t,e))),r=i[e];"base64url"===o&&(r=r9+r1(r));let s=r4(e,r);return s.forEach(e=>{t.delete(e.name)}),u.push(...t),s}),p=(0,_._)((0,v._)({},r3,l),{maxAge:0}),f=(0,_._)((0,v._)({},r3,l),{maxAge:r3.maxAge});delete p.name,delete f.name,await n([...u.map(e=>({name:e,value:"",options:p})),...d.map(e=>{let{name:t,value:r}=e;return{name:t,value:r,options:f}})])}e.s(["createClient",0,function(){return function(e,t){let r=rX();if(r&&n)return n;if(!e||!t)throw Error("@supabase/ssr: Your project's URL and API key are required to create a Supabase client!\n\nCheck your Supabase project's API settings to find these values\n\nhttps://supabase.com/dashboard/project/_/settings/api");let{storage:s}=function(e,t){var r;let s,n,i=null!=(r=e.cookies)?r:null,a=e.cookieEncoding,o={},l={};if(i)if("get"in i){let e=async e=>{let t=e.flatMap(e=>[e,...Array.from({length:5}).map((t,r)=>"".concat(e,".").concat(r))]),r=[];for(let e=0;e<t.length;e+=1){let s=await i.get(t[e]);(s||"string"==typeof s)&&r.push({name:t[e],value:s})}return r};if(s=async t=>await e(t),"set"in i&&"remove"in i)n=async e=>{for(let t=0;t<e.length;t+=1){let{name:r,value:s,options:n}=e[t];s?await i.set(r,s,n):await i.remove(r,n)}};else if(t)n=async()=>{console.warn("@supabase/ssr: createServerClient was configured without set and remove cookie methods, but the client needs to set cookies. This can lead to issues such as random logouts, early session termination or increased token refresh requests. If in NextJS, check your middleware.ts file, route handlers and server actions for correctness. Consider switching to the getAll and setAll cookie methods instead of get, set and remove which are deprecated and can be difficult to use correctly.")};else throw Error("@supabase/ssr: createBrowserClient requires configuring a getAll and setAll cookie method (deprecated: alternatively both get, set and remove can be used)")}else if("getAll"in i)if(s=async()=>await i.getAll(),"setAll"in i)n=i.setAll;else if(t)n=async()=>{console.warn("@supabase/ssr: createServerClient was configured without the setAll cookie method, but the client needs to set cookies. This can lead to issues such as random logouts, early session termination or increased token refresh requests. If in NextJS, check your middleware.ts file, route handlers and server actions for c
1orrectness.")};else throw Error("@supabase/ssr: createBrowserClient requires configuring both getAll and setAll cookie methods (deprecated: alternatively both get, set and remove can be used)");else throw Error("@supabase/ssr: ".concat(t?"createServerClient":"createBrowserClient"," requires configuring getAll and setAll cookie methods (deprecated: alternatively use get, set and remove).").concat(rX()?" As this is called in a browser runtime, consider removing the cookies option object to use the document.cookie API automatically.":""));else if(!t&&rX())s=()=>{let e;return Object.keys(e=(0,r$.parse)(document.cookie)).map(t=>({name:t,value:e[t]}))},n=e=>{e.forEach(e=>{let{name:t,value:r,options:s}=e;document.cookie=(0,r$.serialize)(t,r,s)})};else if(t)throw Error("@supabase/ssr: createServerClient must be initialized with cookie options that specify getAll and setAll functions (deprecated, not recommended: alternatively use get, set and remove)");else s=()=>[],n=()=>{throw Error("@supabase/ssr: createBrowserClient in non-browser runtimes (including Next.js pre-rendering mode) was not initialized cookie options that specify getAll and setAll functions (deprecated: alternatively use get, set and remove), but they were needed")};return t?{getAll:s,setAll:n,setItems:o,removedItems:l,storage:{isServer:!0,getItem:async e=>{if("string"==typeof o[e])return o[e];if(l[e])return null;let t=await s([e]),r=await r6(e,async e=>{let r=(null==t?void 0:t.find(t=>{let{name:r}=t;return r===e}))||null;return r?r.value:null});if(!r)return null;let n=r;return"string"==typeof r&&r.startsWith(r9)&&(n=r2(r.substring(r9.length))),n},setItem:async(t,r)=>{if(t.endsWith("-code-verifier")){var i;await r7({getAll:s,setAll:n,setItems:{[t]:r},removedItems:{}},{cookieOptions:null!=(i=null==e?void 0:e.cookieOptions)?i:null,cookieEncoding:a})}o[t]=r,delete l[t]},removeItem:async e=>{delete o[e],l[e]=!0}}}:{getAll:s,setAll:n,setItems:o,removedItems:l,storage:{isServer:!1,getItem:async e=>{let t=await s([e]),r=await r6(e,async e=>{let r=(null==t?void 0:t.find(t=>{let{name:r}=t;return r===e}))||null;return r?r.value:null});if(!r)return null;let n=r;return r.startsWith(r9)&&(n=r2(r.substring(r9.length))),n},setItem:async(t,r)=>{let i=await s([t]),o=new Set(((null==i?void 0:i.map(e=>{let{name:t}=e;return t}))||[]).filter(e=>r5(e,t))),l=r;"base64url"===a&&(l=r9+r1(r));let c=r4(t,l);c.forEach(e=>{let{name:t}=e;o.delete(t)});let h=(0,_._)((0,v._)({},r3,null==e?void 0:e.cookieOptions),{maxAge:0}),u=(0,_._)((0,v._)({},r3,null==e?void 0:e.cookieOptions),{maxAge:r3.maxAge});delete h.name,delete u.name;let d=[...[...o].map(e=>({name:e,value:"",options:h})),...c.map(e=>{let{name:t,value:r}=e;return{name:t,value:r,options:u}})];d.length>0&&await n(d)},removeItem:async t=>{let r=await s([t]),i=((null==r?void 0:r.map(e=>{let{name:t}=e;return t}))||[]).filter(e=>r5(e,t)),a=(0,_._)((0,v._)({},r3,null==e?void 0:e.cookieOptions),{maxAge:0});delete a.name,i.length>0&&await n(i.map(e=>({name:e,value:"",options:a})))}}}}((0,_._)((0,v._)({},void 0),{cookieEncoding:"base64url"}),!1),i=new rY(e,t,(0,_._)((0,v._)({},void 0),{global:(0,_._)((0,v._)({},void 0),{headers:(0,_._)((0,v._)({},void 0),{"X-Client-Info":"supabase-ssr/".concat("0.5.2")})}),auth:(0,_._)((0,v._)({},void 0,null),{flowType:"pkce",autoRefreshToken:rX(),detectSessionInUrl:rX(),persistSession:!0,storage:s})}));return r&&(n=i),i}("https://kwqnrvmglcmjnznjgnvg.supabase.co","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imt3cW5ydm1nbGNtam56bmpnbnZnIiwicm9sZSI6ImFub24iLCJpYXQiOjE3Mzk0NDg3MjYsImV4cCI6MjA1NTAyNDcyNn0.BkjF1hwXr5GrNHd3uN1UmevWnkUnMUcIKrB7mo-f68U")}],656134)},881594,e=>{e.v({buttonContainer:"AuthForm-module-scss-module__m3H0Ba__buttonContainer",changePasswordFormTitle:"AuthForm-module-scss-module__m3H0Ba__changePasswordFormTitle",error:"AuthForm-module-scss-module__m3H0Ba__error",formFields:"AuthForm-module-scss-module__m3H0Ba__formFields",googleButton:"AuthForm-module-scss-module__m3H0Ba__googleButton",googleButtonIconContainer:"AuthForm-module-scss-module__m3H0Ba__googleButtonIconContainer",googleButtonInternal:"AuthForm-module-scss-module__m3H0Ba__googleButtonInternal",googleButtonText:"AuthForm-module-scss-module__m3H0Ba__googleButtonText",loginContainer:"AuthForm-module-scss-module__m3H0Ba__loginContainer",logo:"AuthForm-module-scss-module__m3H0Ba__logo",resetErrorContainer:"AuthForm-module-scss-module__m3H0Ba__resetErrorContainer",title:"AuthForm-module-scss-module__m3H0Ba__title",titleResetError:"AuthForm-module-scss-module__m3H0Ba__titleResetError"})}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.